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/[deleted] Dec 02 '20

Using nim

Part 1

import strutils
import sequtils

func occurances(s: string, c:char): int =
    for cc in s:
        if cc == c:
            result += 1

func getRange(s: string): (int, int) =
    let minMax = s.split(" ")[0].split("-").map(parseInt)
    (minMax[0], minMax[1])

func getChar(s: string): char =
    s.split(" ")[1][0]

func getPwd(s: string): string =
    s.split(" ")[2]

func checkPwd(min: int, max: int, c: char, pwd: string): bool =
    let o = occurances(pwd, c)
    o >= min and o <= max

func countValid(lines: openArray[string]): int =
    for line in lines:
        let
            (min, max) = getRange(line)
            c = getChar(line)
            pwd = getPwd(line)
        if checkPwd(min, max, c, pwd):
            result += 1


let input = readAll(stdin).splitLines

echo countValid(input)

Part 2

import strutils
import sequtils

func getRange(s: string): (int, int) =
    let minMax = s.split(" ")[0].split("-").map(parseInt)
    (minMax[0], minMax[1])

func getChar(s: string): char =
    s.split(" ")[1][0]

func getPwd(s: string): string =
    s.split(" ")[2]

func checkPwd(min: int, max: int, c: char, pwd: string): bool =
    pwd[min - 1] == c xor pwd[max - 1] == c

func countValid(lines: openArray[string]): int =
    for line in lines:
        let
            (min, max) = getRange(line)
            c = getChar(line)
            pwd = getPwd(line)
        if checkPwd(min, max, c, pwd):
            result += 1

let input = readAll(stdin).splitLines

echo countValid(input)

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.