r/adventofcode • • Dec 02 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 02 Solutions -🎄-

--- Day 2: Password Philosophy ---


Advent of Code 2020: Gettin' Crafty With It


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:02:31, megathread unlocked!

99 Upvotes

1.2k comments sorted by

View all comments

1

u/jeffers0n Dec 02 '20

Ruby :)

Part 1:

#!/bin/env ruby

def parse_line (line)
    ret = Hash.new
    ret[:pass] = line.split(':')[1].strip
    ret[:char] = line.split(' ')[1][0]
    ret[:min] = line.split(' ')[0].split('-')[0].to_i
    ret[:max] = line.split(' ')[0].split('-')[1].to_i
    return ret
end
results = {
    :pass => 0,
    :fail => 0
}

File.readlines('./input').each do |line|
    password = parse_line(line)
    count = password[:pass].count(password[:char])
    if count <= password[:max] && count >= password[:min]
        results[:pass] += 1
    else
        results[:fail] += 1
    end
end

pp results

Part 2:

#!/bin/env ruby

def parse_line (line)
    ret = Hash.new
    ret[:pass] = line.split(':')[1].strip
    ret[:char] = line.split(' ')[1][0]
    ret[:min] = line.split(' ')[0].split('-')[0].to_i
    ret[:max] = line.split(' ')[0].split('-')[1].to_i
    return ret
end
results = {
    :pass => 0,
    :fail => 0
}

File.readlines('./input').each do |line|
    password = parse_line(line)
    c1 = password[:pass][password[:min] - 1]
    c2 = password[:pass][password[:max] - 1]
    if (c1 == password[:char]) ^ (c2 == password[:char])
        results[:pass] += 1
    else
        results[:fail] += 1
    end
end

pp results

1

u/daggerdragon Dec 02 '20

This code is really hard to read on old.reddit. Could you please edit it using old.reddit's four-spaces formatting instead of new.reddit's triple backticks? Note that if you're using the visual editor, you may have to "Switch to Markdown" to get Reddit to understand the formatting properly.

1

u/backtickbot Dec 02 '20

Hello, jeffers0n: code blocks using backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead. It's a bit annoying, but then your code blocks are properly formatted for everyone.

An easy way to do this is to use the code-block button in the editor. If it's not working, try switching to the fancy-pants editor and back again.

Comment with formatting fixed for old.reddit.com users

FAQ

You can opt out by replying with backtickopt6 to this comment.