RSSAmplifier

Chewing the Cud · Dec 9, 2020

Advent of Code 2020 - Day 2

0
Sign in to vote or save

James Aimonetti · Chewing the Cud

main(_) ->
    PasswordDB = read_input("p2.txt"),
    Valid = lists:foldl(fun count_valid_pw/2, 0, PasswordDB),
    io:format('user', "valid: ~p~n", [Valid]).
count_valid_pw({Min, Max, Char, PW}, ValidCount) ->
    case is_valid_pw(Min, Max, Char, PW) of
	'true' -> ValidCount + 1;
	'false' -> ValidCount
    end.
is_valid_pw(Min, Max, Char, PW) ->
    Count = length(binary:split(PW, Char, ['global']))-1,
    Count >= Min andalso Count =< Max.

After loading the passwords and rules into PasswordDB, we fold over the list and count only those passwords that are valid.

To validate the password, I chose to split the password on the Char value, get the length of the list and decrement by one. For instance:

binary:split(<<"aaa">>, <<"a">>, ['global']).
[<<>>,<<>>,<<>>,<<>>]
Count = 3
binary:split(<<"cdefg">>, <<"b">>, ['global']).
[<<"cdefg">>]
Count = 0
binary:split(<<"ccccccccc">>, <<"c">>, ['global']).
[<<>>,<<>>,<<>>,<<>>,<<>>,<<>>,<<>>,<<>>,<<>>,<<>>]
Count = 9

Then it is a simple check on Min <= Count <= Max.

Read the original on jamesaimonetti.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.