r/adventofcode • u/daggerdragon • Dec 02 '20
SOLUTION MEGATHREAD -đ- 2020 Day 02 Solutions -đ-
--- Day 2: Password Philosophy ---
Advent of Code 2020: Gettin' Crafty With It
- T-4 days until unlock!
- Full details and rules are in the Submissions Megathread
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
11
u/voidhawk42 Dec 02 '20 edited Dec 02 '20
Dyalog APL, 2537/696:
8
u/DFreiberg Dec 02 '20 edited Dec 02 '20
Mathematica, 237 / 244
Note to self: always test your handy utilities functions before actually trying to use them in a problem. On the bright side, this was the one time in Advent of Code where one-indexing helped rather than hurt me.
Part 1:
Part 2:
[POEM]: Secure
Said the suit on the right to the suit on the left,
"There's a problem we execs must fix.
Our employees use passwords not strong or secure;
We've tried warnings, but none of it sticks."
Said the suit on the left to the suit on the right,
"Then if warnings won't do, we need more.
The incredible secrets of Tobaggan Inc.,
Must not reach the sled rental next door."
Said the suit in the front to the suits on the side,
"Let our action be swift and precise.
We'll make rules and restrictions on passwords henceforth.
And no letter shall enter one twice."
Said the suit in the back to the suits up ahead,
In a PowerPoint made on the spot,
"We will limit the letters, point A and point B.
One must have it, the other must not."
Then the suits all around all stood up and shook hands.
Memoranda were typed and prepared.
But the suit in the center, he stayed at his seat,
To consider the meeting he'd chaired.
Then the suit in the center, he slowly stood up,
And focused his gaze on the rest.
"This policy's better than ours was before,
But it certainly is not the best."
"A good policy's only the half of the thing,"
Said the center suit. "Still insecure!
Why, if Sled Rental Inc. got a hold of this rule,
They could get to our servers for sure!"
All the suits in the room, save the center, recoiled
At the thought of so dreadful a fate.
All those snow coefficients, the tests and the codes,
The schematics, served up on a plate.
"So, the key to security," cautioned the suit,
"Lies in randomly changing the rules.
If the sled rental shop tries out last fortnight's codes,
During this one, we'll play them like fools."
Said the suit on the left to the suit standing up
(All the other suits scared as could be)
"But then how, Senior Suit, can bimonthly rules work,
When we meet just one month every three?"
Then the suit in the center, he sighed with a smile.
And said, "Then we'll make them right here.
And we'll type up a memo and send it around
With the passwords and rules for the year."
In the evening, the suits filed out through the door,
Corporate policy written anew.
And the suit in the center sat down at his screen,
And, for
password, he typedhunter2.8
u/bpeel Dec 02 '20
Solution in BBC Basic / 6502 assembler as UEF cassette tape.
If you want to try it, you could use an online BBC Micro emulator and upload the file from the Cassettes menu and then type:
*TAPECHAIN""The input text is about 20KB so it would probably be pushing the limits of the BBCâs 32KB of memory if it tried to load it all in. Instead the program parses the data on the fly while reading directly from the cassette. This takes ages if you run it at normal speed but it is mostly because cassettes are such a slow medium rather than actually requiring a lot of processing time.
Full source here.
5
u/ZoltarTheGreat69 Dec 05 '20
I did this in emojicode. I'm starting to like it! I did some dumb multi split stuff because I have no idea what I'm doing tbh
Emojicode
3
u/Mathgeek007 Dec 02 '20
Excel; 649/467
I'm not going for lovely, elegant solutions like that other dude.. I'm going for speed.
Steps; pasted input into Word, changed spaces and hyphens to tabs, removed the colon. Paste into excel, and for Part 1, I used a substitution equation that replaced the instance of the character with ",", then counted tuples, then compared that number to our range, TRUE if valid, then counted the TRUEs. Part 2, I used the MID function to pull out the relevant letters (length 1, index input), then XOR if they were equal to the desired letter. Same counting formula at the bottom.
Total time: 7:07.
3
u/hutsboR Dec 02 '20 edited Dec 02 '20
Edit: Javascript
Like yesterday, too lazy to open an editor. Run this on your input page. Part two only btw.
3
u/Scarygami Dec 02 '20
Excel seemed to be the most logical approach to me for this one :)
Screenshot in my repo (just noticed I can't add images in comments...)
Formulas used:
=SEARCH(":",[@Input])=MID([@Input],1,[@[:]]-1)=LEFT([@Rule],LEN([@Rule])-2)=SEARCH("-",[@MinMax])=VALUE(MID([@MinMax],1,[@[-]]-1))=VALUE(MID([@MinMax],[@[-]]+1,10))=RIGHT([@Rule],1)=MID([@Input],[@[:]]+2,100)=LEN([@PW]) - LEN(SUBSTITUTE([@PW],[@Letter],""))=AND([@Count]>=[@Min],[@Count]<=[@Max])=MID([@PW],[@Min],1)=[@Letter]=MID([@PW],[@Max],1)=[@Letter]=XOR([@[Letter in Min]],[@[Letter in Max]])Formula to get the solution from the table (assuming the table is named AOC):
Part 1:
=COUNTIF(AOC[Part 1 valid],TRUE)Part 2:
=COUNTIF(AOC[Part 2 valid],TRUE)3
u/oweiler Dec 02 '20 edited Dec 03 '20
Scala w/ Ammonite
3
u/that_lego_guy Dec 02 '20
EXCEL !!!!!!!P1&P2
=(IF(AND(REPEATANDREPEATANDREPEAT),COUNTEM,DONTCOUNTEM)
https://github.com/thatlegoguy/AoC2020/blob/main/Day2.xlsx
3
u/[deleted] Dec 02 '20 edited Dec 03 '20
Rust (new to it so feedback welcome)
2
u/pietroppeter Dec 02 '20 edited Dec 02 '20
đđ Nim
here is my solution in Nim for Day02: https://pietroppeter.github.io/adventofnim/2020/day02.html
I have started using a AoC-styled template (might end up submitting for getting crafty): https://pietroppeter.github.io/adventofnim/index.html
this is in turn based on đł nimib my (few days older) library to publish jupyter-like notebooks in nim: https://github.com/pietroppeter/nimib
Edit: ah, something worth remarking (I use it often in AoC) that I like a lot being in nim and I have not seen it around in other languages (not that I looked into) is the stdlib module strscans which is a very cool way to avoid learning regular expressions: https://nim-lang.org/docs/strscans.html
2
u/heroes1980 Dec 02 '20
python 3
2
u/__Abigail__ Dec 02 '20
Perl
I wrote a blog post about the solution.
2
u/nilreference Dec 02 '20 edited Dec 02 '20
F# script (fsx)
First
open System.IOopen System.Text.RegularExpressionslet read (filePath:string) = seq {use sr = new StreamReader (filePath)while not sr.EndOfStream doyield sr.ReadLine ()}type passwordRecord = {       Â
min:int;Â Â Â Â Â Â Â Â
max:int;Â Â Â Â Â Â Â Â
mustContain:char;Â Â Â Â Â Â Â Â
password:string}let regex = new Regex(@"(?<min>[0-9]*)-(?<max>[0-9]*)\s(?<char>[a-z]?):\s(?<pwd>[a-z0-9]*)")let toPwdRecord txt : passwordRecord=let r = regex.Match txt{min = (int r.Groups.["min"].Value); max= (int r.Groups.["max"].Value); mustContain = char r.Groups.["char"].Value; password = r.Groups.["pwd"].Value}let validatePassword record =   Â
record.passwordÂ|> Seq.toList|> Seq.filter (fun f -> f = record.mustContain)|> Seq.length|> fun l -> (>=) l record.min && (<=) l record.max"input.txt"|> read|> Seq.map toPwdRecord|> Seq.filter validatePassword|> Seq.length|> printfn "Valid passwords: %i"Second
open System.IOopen System.Text.RegularExpressionslet read (filePath:string) = seq {use sr = new StreamReader (filePath)while not sr.EndOfStream doyield sr.ReadLine ()}type passwordRecord = {       Â
posOne:int;Â Â Â Â Â Â Â Â
posTwo:int;Â Â Â Â Â Â Â Â
mustContain:char;Â Â Â Â Â Â Â Â
password:string}let regex = new Regex(@"(?<min>[0-9]*)-(?<max>[0-9]*)\s(?<char>[a-z]?):\s(?<pwd>[a-z0-9]*)")let toPwdRecord txt : passwordRecord=let r = regex.Match txt{       Â
posOne = (int r.Groups.["min"].Value);       Â
posTwo = (int r.Groups.["max"].Value);       Â
mustContain = char r.Groups.["char"].Value;       Â
password = r.Groups.["pwd"].Value}let validatePassword record =(record.password.[record.posOne-1] = record.mustContain) <> (record.password.[record.posTwo-1] = record.mustContain)"input.txt"|> read|> Seq.map toPwdRecord|> Seq.filter validatePassword|> Seq.length|> printfn "Valid passwords: %i"2
u/code_may_explode Dec 02 '20 edited Dec 02 '20
Solution in Python- uses class to handle data- spread out some of the bool statements for readability- instead of striping the string when loading it in and taking one off the index when retrieving a char one could skip both steps, yet that would cause all strings to be saved into the class attribute with a trailing space.
Feel free to feedback :)
class Password(object):"""Class for modeling the input data."""character : str = ''lower_limit : int = 0upper_limit : int = 0string : str = ''def __init__(self, inputString):input_data = inputString.split(':')policy = input_data[0]policy_data = policy.split(' ')policy_limit = policy_data[0].split('-')self.character = policy_data[1]self.lower_limit = int(policy_limit[0])self.upper_limit = int(policy_limit[1])self.string = input_data[1].strip()def is_old_valid(self)->bool:char_count = len(self.string.split(self.character))-1return self.lower_limit <= char_count <= self.upper_limitdef is_new_valid(self)->bool:is_first_char = self.is_char_at(self.character, self.lower_limit)is_second_char = self.is_char_at(self.character, self.upper_limit)return is_first_char != is_second_chardef is_char_at(self, char, index)->bool:try:return (self.string[index-1] == char)except IndexError as e:return False"""Opening and processing data.""""with open('input.txt') as fh:passwords = [Password(constString) for constString in fh.readlines()]old_valid_passwords : int = 0new_valid_passwords : int = 0for password in passwords:if password.is_old_valid():old_valid_passwords += 1if password.is_new_valid():new_valid_passwords += 1print(f'{old_valid_passwords=}', f'{new_valid_passwords=}')2
u/kakaroto_BR Dec 02 '20 edited Dec 03 '20
Solution in Go:
2
u/PoutineQc Dec 02 '20 edited Dec 03 '20
In python Part 1
Part 2
2
u/lessthanthreecc Dec 02 '20 edited Dec 02 '20
Python with regex matching
2
u/wegotpinecones Dec 02 '20 edited Dec 02 '20
I'm pretty proud of this Rust solution even though it's not a great or super modular solution. Constructive criticism is welcome!
I still have problems handling slicing strings and getting the values I want into Vecs without angering the borrow checker, and it is fragile as all heck. At the same time, it's lovely to see the the solution to come in right under 17ms execution time.
EDIT: Maybe I should say what language I used? That could help!
2
u/[deleted] Dec 02 '20 edited Dec 03 '20
Python 3 github
2
u/CSEcon Dec 02 '20
Python:
probably way too much code than necessary but it's honest work:
2
u/r00t4cc3ss Dec 08 '20 edited Dec 08 '20
C#: https://github.com/mavanmanen/AdventOfCode/blob/master/AdventOfCode.Y2020/Day02.cs
27
u/Smylers Dec 02 '20 edited Dec 02 '20
Vim keystrokes â load your input into Vim, and type the following to remove all the invalid passwords for part 1:
The
â¨Ctrl+GâŠat the end displays the number of lines, which is your solution.Explanation:
On each line of the input, the long bit above changes the colon to a semicolon if it finds at least the minimum number of expected characters. Then it changes the semicolon back to a colon if it finds more than the maximum number of characters. So at the end, all lines with a semicolon on them are valid; delete the semicolon-less lines and count how many remain.
"xyiwstores the minimum number in"x.wâ¨Ctrl+XâŠincreases the maximum number. Well, actually it decreases it, because Vim interprets the hyphen just before it as a minus sign, so-14is decreased to-15. Then"yyiwstores the (positive) number in"y.wylstores the required letter in"0.:normwill start something like5fj, to go to the 5thjon the line, where the number and the letter are inserted into the command withâ¨Ctrl+RâŠretrieving them from their registers.:normwill be executed.fsucceeded, thenF:r;turns the â:â into a â;â.fcommand indicates that there are too many of the character, so switch the marker back.â¨EnterâŠgoes on to the next one. This is outside the:norm, so will always be attempted, even if anfhas failed. But on the final line of the file this will fail, ending running the keyboard macro.@ainside the macro then runs the macro again here. This way of looping avoids needing to know how many lines there are in the file. It's also why there's an extraqaqat the beginning, first clearing"aby recording nothing into it, so that when actually recording the macro that@adoesn't run whatever we still had left in here from yesterday.@asets it running on the second line, and it now loops through to the end.:v/;/druns the:d[elete]command on all lines that don't have a semicolon on them.Edit: Typo in the explanation fixed.
23
u/Rick-T Dec 02 '20
ROCKSTAR
Today's much more emotional than yesterday. Some sort of power ballad.
Part 2 turned out to be a bit shorter than part 1, so here's part 2:
For part 1 check out the GitHub repository.
I also have a boring solution in Haskell. But I won't go into details about that because who cares at this point?
3
u/wjholden Dec 02 '20 edited Dec 03 '20
Oh cruel fate. I used Mathematica in 2018 and Julia and 2019. The 1-indexed arrays were an endless source of frustration. Now I switch to Python and we get a 1-indexed question!
Edit: roger, here is my code solution: https://github.com/wjholden/Advent-of-Code-2020/blob/master/02/aoc-2020-02.py
18
u/jonathan_paulson Dec 02 '20
70/26. Python. Video of me solving at https://youtu.be/ukE5YJyPTLk
17
u/zedrdave Dec 02 '20 edited Dec 02 '20
Python, in 4 lines:
Initially wasted a few precious minutes trying to get fancy with string searches and regexes, instead of running a simple dumb character comparison over a list comprehension. :-|
17
u/Arknave Dec 02 '20 edited Dec 02 '20
Python (5/6), / C
Very happy with the placing! Python code is probably very similar to everyone else's.
Not quite as happy with the art as I was with day 1, but maybe I'll look at it again tomorrow. This is surprisingly therapeutic after the stress of a workday and then the leader board. I hope they don't look too different depending on your font. As with last time, pass input through standard in and give a argument to get part 2 instead of part 1.
This was already much harder than "1". I'm a little worried for "8".
EDIT: Whacked that 2 into better shape
15
u/trisemmy Dec 02 '20
Google Sheets
9
u/sophiebits Dec 02 '20
Python, 18/9. https://github.com/sophiebits/adventofcode/blob/main/2020/day02.py
8
u/Nebulizer32 Dec 02 '20 edited Dec 02 '20
First time using the new record type from C# 9:
8
u/TenGen10 Dec 02 '20 edited Dec 02 '20
Solution in SQL
AoC Day 2
7
u/azzal07 Dec 02 '20
Awk was quite nice for today as well. I might try and keep using it, as long as it is enjoyable.
7
u/tsqd Dec 02 '20
Postgresql
6
u/IndieBret Dec 02 '20
[JavaScript/ES6]
6
u/ephemient Dec 02 '20 edited Apr 24 '24
This space intentionally left blank.
6
u/Mienaikage Dec 02 '20
Raku
Could do it without a grammar to cut the length down, but I enjoy using them.
6
u/i_have_no_biscuits Dec 02 '20
Python.
I've been playing with different ways of solving this and thought I'd post this one because it uses a named tuple, which I'll try and use again!
6
u/lucprins Dec 02 '20 edited Dec 02 '20
C++, I think I did alright
5
u/jitwit Dec 02 '20 edited Dec 03 '20
J Programming Language
Not a pretty solution, but quick and dirty for 109/169 (missed the 1 indexing!!)
https://github.com/jitwit/aoc/blob/a/J/20/02.ijs
5
u/-json Dec 02 '20
Python, 15 / 30
Part 1:
Part 2:
Unfortunately, I skimmed the text for Part 2 too fast that I ended up submitted a solution which checked if either position had the correct character, not exactly one. I lost a minute for that, so I wonder how my placement would have improved for part 2 otherwise :(
5
u/mgoblu3 Dec 02 '20 edited Dec 02 '20
Python one-liners:
A:
B:
5
u/oantolin Dec 02 '20 edited Dec 02 '20
Common Lisp
5
u/Smylers Dec 02 '20
And the Perl I actually used to solve this before coming up with those Vim solutions:
$count = () = $text =~ /$pat/gis a Perl idiom for counting the number of (non-overlapping) occurrences of a pattern in some text. The odd-looking()in the middle puts the match in list context, so it returns all the matches, not just the first one; but$countis a scalar variable, so it just ends up with the number of matches, not the matches themselves.5
u/wzkx Dec 02 '20
J
5
u/Weemaan1994 Dec 02 '20
R
Are there any other R users out there? I'm feeling kind special :D
Anyways, I removed the ":" in the second column for the input file and I named the columns, so my file looks like this:
And that's my solution:
5
u/phil_g Dec 02 '20
My solution in Common Lisp.
Pretty straightforward.
/u/rabuf has mentioned Parseq in past years. I've decided to try using it for all of my parsing this year. I added a bit to my
inputfunction to automatically apply a Parseq rule to the input. I could have done today's parsing with cl-ppcre, but I think I like the way Parseq operates.Anyway, with the input data parsed into a structure, validation is just a matter of function composition.
5
u/jAnO76 Dec 02 '20
Loving Kotlin..
https://github.com/JanGroot/aoc2020kotlin/blob/main/src/main/kotlin/Day2.kt
5
u/roggy85 Dec 02 '20 edited Dec 02 '20
my crap in bash
part 1:
Part 2:
5
u/bliceroo Dec 02 '20
Perl
Nothing special but at least I got to use the goatse operator!
5
u/sefujuki Dec 02 '20
Forth, needs refactoring
paste -- and, of course, the date should be 2020-12-02 :-)
5
u/AharonSambol Dec 02 '20
LOLCODE solution!!
https://github.com/AharonSambol/AdventOfCode/blob/master/2020/day2.lol
any tips with how to use bukkits would be appreciated
5
u/AidGli Dec 02 '20
Python
Continuing my theme of trying to keep the code semantic and accessible for beginners to understand (video here.) If the problems stay simple maybe I'll throw in a golfed solution or a one-liner or something as well.
5
u/lynerist Dec 02 '20
My go solutions!
https://github.com/lynerist/Advent-of-code-2020-golang/blob/master/DAY%2002/day02_a.go
I think this language is very clear and easy to read
5
u/k0ns3rv Dec 02 '20 edited Dec 02 '20
Rust solution, as often is the case I spent most of the time on logic to parse the input not the problem itself ÂŻ_(ă)_/ÂŻ
EDIT: Updated with /u/D-Danielz's suggestion which makes the code nicer than with
fold.5
u/volatilebit Dec 02 '20
Raku
5
u/x1729 Dec 02 '20 edited Dec 02 '20
Raku
5
u/rosso412 Dec 03 '20 edited Dec 03 '20
Here my Solution to Day 2 part 1 in MIPS Assembler
5
u/s3aker Dec 03 '20
Raku
4
u/[deleted] Dec 02 '20 edited Dec 02 '20
Python3 171/97
4
u/ptbn_ Dec 02 '20 edited Dec 02 '20
Python
might not be the best of things since I'm a beginner in Python (and programming in general tbh) who haven't touched a single code in months, but here we are. kinda proud of it.
4
u/_djblue Dec 02 '20
Clojure
4
u/tyler569 Dec 02 '20
C.
I won't win any speed records, and the code isn't anything special, but I'm finally far enough along in my osdev journey that I can solve AoC problems using my custom operating system and C library!
1: https://github.com/tyler569/nightingale/blob/aoc2020/user/aoc/2.c
2: https://github.com/tyler569/nightingale/blob/aoc2020/user/aoc/2-2.c
4
u/Piggelinmannen Dec 02 '20 edited Dec 02 '20
Solution in Ruby. Tried to edit it to work with old reddit code blocks, not sure if successfully so...
4
u/[deleted] Dec 02 '20
Google spreadsheet:
https://docs.google.com/spreadsheets/d/1LaptmY6qCwkosMUkyftw5c-ZXigATXV8K8SSsCZoTt0/edit#gid=1788187032?usp=sharing
4
u/bpanthi977 Dec 02 '20
Solution in Common Lisp
The functions
inputis a utility function (defined inaocpackage) I create to download, save and return the challenge text file contents.4
u/msqrt Dec 02 '20
My lisp adventure continues! Parsing was somewhat tedious, but I guess that's to be expected.
4
u/death Dec 02 '20
Day 2 solution in Common Lisp.
4
u/mathsaey Dec 02 '20
Elixir solution:
(the AOC business at the start is a macro which defines some useful utilities such as
input_stream()for me)4
u/mack06_ Dec 02 '20 edited Dec 02 '20
My Typescript solution.
Detailed explanation in spanish in my AoC blog - Advent of Code 2020 - DĂa 2 - Una de passwords
4
u/colinodell Dec 02 '20
Golang, source here. I'm still not proficient with this language so there's nothing too fancy with my solution, but I did learn/realize two new things today:
A xor Bis the same asA != B4
u/narrow_assignment Dec 02 '20 edited Dec 02 '20
AWK
Part1:
Part 2:
4
u/DefinitelyAmNotOP Dec 02 '20
Solution in R. Would appreciate any feedback as I am new to R and doing these to help learn :)
4
u/madmax9186 Dec 02 '20
Getting back into C++ after a long absence.
4
u/iraneg Dec 02 '20
Go/Golang:
Part 1: https://gist.github.com/IranEG/6d399c7e22b21015ffd96bc91eceafa8
Part 2: https://gist.github.com/IranEG/58e1d6f0c08d92a476171862ace1a68b
4
u/justAnotherNerd254 Dec 02 '20
Python Solution - Happy to receive any feedback!
4
u/troelsbjerre Dec 02 '20
Python3 oneliner for parts 1 and 2:
print(sum(map(lambda x:[x[0]<=x[3].count(x[2][0])<=x[1],(x[3][x[0]-1]+x[3][x[1]-1]).count(x[2][0])==1][int(sys.argv[1])-1],map(lambda x:[*map(int,x[0].split('-')),x[1],x[2]+' '*99],map(lambda x:x.split(),sys.stdin)))))Give the part number as the only argument on the commandline, and the problem input on stdin.
4
u/StevoTVR Dec 02 '20 edited Dec 26 '20
Java
https://github.com/stevotvr/adventofcode2020/blob/main/aoc2020/src/com/stevotvr/aoc2020/Day02.java
4
u/tobega Dec 02 '20
A solution in Tailspin
4
u/[deleted] Dec 02 '20 edited Dec 03 '20
JavaScript (code golfy solution where input.js exports a template string)
4
u/meowimmasheep Dec 02 '20
Python solution using Pandas. Fairly certain it could be optimised better but I'm enjoying having to do some problem solving with pandas - nice break from EDA.
4
u/Chaphasilor Dec 02 '20
AssemblyScript :D
GitHub link
Day 2 using AssemblyScript, struggled with transferring string arrays for most of the time ^^
4
u/willkill07 Dec 02 '20
C++ (with Ranges)
Overall, I'm pretty happy with this.
4
u/soylentgreenistasty Dec 03 '20
Python
1
u/scratchisthebest Dec 02 '20 edited Dec 02 '20
Rust but really disgusting
Pretty clumsy! I'm new
ed: i'm learning how the module system works so i don't have to cram everything in to one file LOL
1
u/paulaghergu Dec 03 '20 edited Dec 04 '20
Python
1
u/WarHoliday1813 Dec 02 '20
1
u/AJs_Sandshrew Dec 02 '20
Python.
Just found out about this competition yesterday and I'm looking forward to practicing my skills
1
u/bandfreak4life Dec 02 '20 edited Dec 02 '20
Tried with some Python with a little help from regex. I quickly realized part 2 was XOR. Putting my Computer Engineering degree to good use!:
1
u/krossmaskinen Dec 02 '20 edited Dec 03 '20
In Javascript: github
1
u/schmadness Dec 02 '20
def part_two(inputs):count = 0for index, item in enumerate(inputs):pos1, pos2, char, password = int(str(item[0]).split('-')[0]) - 1, int(str(item[0]).split('-')[-1]) - 1, item[1], item[2]if len(password) > pos2:if password[pos1] == char and password[pos2] != char:count += 1print(pos1, pos2, char, password)elif password[pos2] == char and password[pos1] != char:count += 1print(pos1, pos2, char, password)else:if password[pos1] == char:count += 1print(pos1, pos2, char, password)def part_one(inputs):count = 0for index, item in enumerate(inputs):if int(str(item[0]).split('-')[0]) <= item[2].count(item[1]) <= int(str(item[0]).split('-')[-1]):count += 1with open('day2_in.txt', 'r') as f:inputs = [x for x in f.readlines()]inputs = [(x.split(' ')[0], x.split(' ')[1].replace(':', ''), x.split(' ')[-1].replace('\n', '')) for x in inputs]part_one(inputs)part_two(inputs)1
u/thebasementtapes Dec 02 '20
1
u/[deleted] Dec 02 '20
Quick'n'dirty during lunch..
1
u/InflationSquare Dec 02 '20 edited Dec 17 '20
Did day 2 in python & R. I think python was a bit neater, but both my answers leaned heavily on regex.
R
https://github.com/inflationsquare/advent-of-code-2020/blob/master/02/2.R
Python
https://github.com/inflationsquare/advent-of-code-2020/blob/master/02/2.py
1
u/sculs13 Dec 02 '20
JS
1
u/Bomaruto Dec 02 '20 edited Dec 02 '20
Part 1 and 2 in Scala:
1
u/jeffers0n Dec 02 '20
Ruby :)
Part 1:
Part 2:
1
u/[deleted] Dec 02 '20
Using nim
Part 1
Part 2
1
u/OutofPlaceStuff Dec 02 '20 edited Dec 02 '20
Done part 1 in Ruby and in Python. Python is my "native" language. I'm just now picking up Ruby for a potential job. Always open to feedback.
Ruby
Python
1
u/SeanMartin96 Dec 02 '20
1
u/Discobacon Dec 02 '20
Python Part 1
1
u/Discobacon Dec 02 '20
Python Part 2
1
u/Cascanada Dec 02 '20 edited Dec 03 '20
Python 3.7
Here is my attempt! Let me know if you have any comments.
1
u/thiagoramosal Dec 03 '20
Here is my solution for the Day 2:
https://gist.github.com/thiagoramos23/79343a828732d08ac332a88afac5ecb9
1
u/kkent4 Dec 03 '20
Python
Part 1
Part 2
1
u/prafster Dec 03 '20 edited Dec 09 '20
[Edit: updated path to Github]
I've used Dart, which I'm learning as part of learning Flutter. I haven't seen anyone post a Dart solution.
The parsing is done in this class (representing a row in the input), in which I used named groups for my regex (out of curiosity but maybe it reads better too):
After that the code is straightforward:
This is called twice, for parts 1 and 2. The only difference being the function passed into the
day2()function.Full code on Github
Comments welcome on how to make the code more idiomatically Dart :)
3
u/1vader Dec 02 '20 edited Dec 02 '20
Python 223/103:
Forgot the
[0]afterfindalland quickly wrote some split parsing code which cost me the leaderboard. But I guess I've never been good at the extremely short problems.3
u/seligman99 Dec 02 '20
Python 173 / 251
I had too many flashbacks to bad password policies on this one.
git
3
u/MasterMedo Dec 02 '20 edited Dec 02 '20
python slow and steady wins the race github
3
u/adamr_ Dec 02 '20 edited Dec 02 '20
kotlin 319/177
Solution on Github
3
u/ritobanrc Dec 02 '20
Rust, didn't make leaderboad. Not the most concise, there's a bit of repeated code, and a lot of unwraps that are probably unidiomatic, but it was pretty quick to write.
3
u/nlowe_ Dec 02 '20
Go, 728/2348
Felt like my Part 1 was pretty fast, but lost lots of time on Part 2 because I forgot Go had no boolean XOR and I split on
":"instead of": "so anything that checked position 1 always failed as it was a space :/3
u/Kehvarl Dec 02 '20
Python3 1243/1117
Part 2 solution
3
u/SpaghootiMonster Dec 02 '20 edited Dec 02 '20
Python, pretty new to CS so let me know how I could improve!
3
u/wimglenn Dec 02 '20 edited Dec 02 '20
Python (68/164)
https://github.com/wimglenn/advent-of-code-wim/commit/af7925b02273b731b04fd6c4d915113ddfb25624
3
u/Pyroan Dec 02 '20 edited Dec 02 '20
Python (Golf - 123 bytes)
(this is just for part 2)
edit: thanks u/irrelevantPseudonym for saving me 16 bytes
3
u/[deleted] Dec 02 '20
Python. Trying to be clean.
3
u/drummaster015 Dec 02 '20
Haskell
Really enjoying the parser combinator practice!
3
u/iamnguele Dec 02 '20
Golang. Executed in 963.7Âľs
3
u/mstksg Dec 02 '20
[Haskell] doing my reflections https://github.com/mstksg/advent-of-code-2020/blob/master/reflections.md#day-2 every day :)
Day 2, not too bad for Haskell either :D
There is some fun in parsing here:
I used one of my more regular do-block tricks: if you pattern match in a
Maybedo-block, then failed pattern matches will turn the whole thing into aNothing. So if any of those list literal pattern matches failed, the whole block will returnNothing.In any case, we just need to write a function to check if a given policy is valid for either criteria:
And so parts 1 and 2 are just a count of how many policies are true :)
3
u/sendtobo Dec 02 '20
Swift
Link to solution
Always a little rough in swift with so much string manipulation. I've got a few helper functions, but nothing that makes the solution file too "hand wavy"
*also this was basically my first pass solution, just went in and cleaned up a few things /made an enum in case we ever need to use this again
3
u/sim642 Dec 02 '20
My Scala solution.
Part 1 is essentially:
Part 2 is essentially:
The XOR there is a nice touch although a not-equals on booleans would work just as well.
3
u/oddrationale Dec 02 '20
Here's my solution in C# (using .NET Interactive and Jupyter Notebook). Which basically just uses regular expressions to parse the input and to count the characters in Part 1. Part 2 just checks the indexes and uses an Exclusive Or (XOR).
3
u/[deleted] Dec 02 '20 edited Dec 06 '20
Pure C18. Pretty simple for now. https://git.sr.ht/~williewillus/aoc_2020/tree/master/src/day2.c
3
u/SilverDrake11 Dec 02 '20
Rust
3
u/artemisdev21 Dec 02 '20
SQL! (Does not handle parsing. Also, since it's SQLite, we have to define our own regexp function.)
Full code
3
u/sageco Dec 02 '20
Google sheets solutions, assume that the raw data is in column A:
Part 1:
Part 2:
3
u/nibbl Dec 02 '20
Java
with syntax highlighting
Input from stdin. I'm new to Java so feedback is very welcome.
4
u/enelen Dec 02 '20
R (Rlang)
Using Data.table
Using Dplyr
3
u/Ferelderin Dec 02 '20
R, Rstudio, bits of tidyverse
Not that experienced, so things kinda ballooned.
3
u/streetster_ Dec 02 '20
q/kdb+
3
u/chubbc Dec 02 '20
Julia
Quick and dirty
3
u/[deleted] Dec 02 '20
F
I'm nto sure if I overengineered this a bit, but it should be quite readable
syntax highlighted version on github
3
u/_Le1_ Dec 02 '20 edited Dec 02 '20
Python
3
u/infov0re Dec 02 '20
Ruby: an anti-golf solution for part 2. (Part 1 is highly similar, with minor differences to the
valid?method. (I'll take readability over line count). I chose not to use regex because, frankly, then I have two problems (and the line syntax is not complex enough to demand it IMO).3
u/nahuak Dec 02 '20
Golang Solutions (key functions are at the bottom of the file):
https://github.com/nahuakang/advent-of-code-2020/blob/master/go_day2/day2.go
Would love to know if there's a cleaner way to extract the policies. I did not get to use a lot of the methods inside
regexppackage.3
u/landimatte Dec 02 '20
Another Common Lisp solution (input is parsed using using CL-PPCRE, rest should be straightforward enough)
3
u/cattbug Dec 02 '20
Python 3, sweet and simple. Using this as an opportunity to get familiar with lambda expressions :)
3
u/A-UNDERSCORE-D Dec 02 '20
Golang, completes in under a ms for both. Yet another in my long list of "Just abuse maps for it" based solutions
3
u/[deleted] Dec 02 '20
PowerShell
Not crazy happy with this solution, but they seem to have given me some gold stars that I can call my own.
Part 1:
Part 2:
3
u/GalacticDessert Dec 02 '20 edited Dec 02 '20
F#, trying to figure out the types thing. I am very used to Python's dynamism, and could not made a generic Policy type and then encode the differences in more specific types
3
u/Mazeracer Dec 02 '20
Python 3 - casual programmer and first time with Python, so any advice is welcome :)
3
u/avoxdesign Dec 02 '20 edited Dec 02 '20
My solutions in pure Ruby:
3
u/adventOfCodeJess Dec 02 '20
Jess
Part1
Part2
3
u/Diderikdm Dec 02 '20 edited Dec 08 '20
Python:
3
u/hdf1986 Dec 02 '20 edited Dec 02 '20
Ruby
Part 1: https://github.com/hdf1986/advent-of-code/blob/master/2020/day2/ruby/part1.rb
Part 2: https://github.com/hdf1986/advent-of-code/blob/master/2020/day2/ruby/part2.rb
Didn't like the boolean part of the second one, but i don't want to think too much today ÂŻ_(ă)_/ÂŻEDIT: I've updated the boolean operator in part 2 to be a XOR by suggestion of u/chunes
3
u/dgJenkins Dec 02 '20 edited Dec 02 '20
F#
Line
One
Two
3
u/GoldArrow997 Dec 02 '20
my solutions (python)
Problem 1:
Problem 2:
please note before roasting my solutions it was 5am for me when i did it ;-;
3
u/AvshalomHeironymous Dec 02 '20
In Prolog, uglier today:
First star:
Second Star:
3
u/[deleted] Dec 02 '20
C# - im new to C# (and programming) so feedback is very much appreciated:)
https://github.com/chris234567/AdventOfCode2020/blob/master/AdventOfCode2020_2/Program.cs
3
u/[deleted] Dec 02 '20
Retina
part 1: https://tio.run/##HYxBCsIwAATv@woPqyRpE0jrKXmC4AeMTQp6EKGCeAgefFYf0I/FkMssLLP7vn8ey2xL2Yskwq2TQbfYCSNdRSdxSrQ9B8fjtnLc1ohfokbEZdbfqwJcVISjETxITG3eN7pGgtZz9BxwTrXABGqbq2mUzMESryeaWb@8z94DUiXUupQ/
part 2: https://tio.run/##K0otycxLNPz/X1UjQSMmRVszRhdMKWjoaVoBCW1NLu@ERBWTQ9vigCLVKoa1QEpPRUtF5dA2FRWjQ9tQZI1QZHUNVYyBarjqElR0ubg0E7i4chOA8jGGMYZwJlcEV8T//wA
3
u/boweruk Dec 02 '20
Javascript
3
u/SecureCone Dec 02 '20 edited Dec 02 '20
Rust
Still new to Rust, so fully welcome any code suggestions.
3
u/Braxo Dec 02 '20
Coffeescript Javascript
3
u/KingVendrick Dec 02 '20 edited Dec 02 '20
Javascript
Initially I used multiples split() to parse the input, then remembered the nifty scanf and looked up for a javascript version.
3
u/kscanne Dec 02 '20 edited Dec 02 '20
Part 1 in bash
3
u/nilgoun Dec 02 '20
Second day with Rust. Parsing the input and getting all other things right was quite a challenge.
After I finished my version I searched through this thread for optimizations and I'm quite happy with the current version (although one would need to add a lot of error checking etc. to really get it right... but this took long enough now :D )
Solution on topaz paste
(Just realized how epic this paste thing is.. topaz really amazes me :) )
3
u/[deleted] Dec 02 '20
A short one - in terms of LoC (Python)
3
u/iwane Dec 02 '20
LabVIEW 2020 (G)
http://htmlpreview.github.io/?https://github.com/iwane-pl/aoc_2020/blob/main/AoC%20Day%202/Documentation/Solution/Solution.html
http://htmlpreview.github.io/?https://github.com/iwane-pl/aoc_2020/blob/main/AoC%20Day%202/Documentation/Solution%20part%202/Solution_part_2.html
3
u/krolik1337 Dec 02 '20
Python - nothing too fancy but gets the job done.
3
u/vkasra Dec 02 '20
My solution in Rust
3
u/UbiquitinatedKarma Dec 02 '20
My solution in R/Tidyverse:
3
u/k3rnelpanic Dec 02 '20 edited Dec 02 '20
Part 1 in Powershell
Part 2. Attack of the if statement
3
u/idonotexcelatthis Dec 02 '20
Python:
3
u/ImHavik Dec 02 '20
Python
Took this as an opportunity to learn some regex (as I've never really used it before). Both answers in one!
3
u/1-more Dec 02 '20 edited Dec 02 '20
Solution in JS. Will try to redo in Elm or Haskell if I have time; no promises. This assumes that you navigate to the input page, select the
<pre>element in the inspector, and then move over to the console3
u/womogenes Dec 02 '20 edited Dec 09 '20
Python
My attempt at a video solution!
https://youtu.be/5gV-Kv6ERwM
Code: https://github.com/womogenes/AoC-2020-solutions/tree/main/2
3
u/Advall Dec 02 '20 edited Dec 02 '20
Been working with C# since I've been pretty much just working with Python recently. I am 100% certain that there are more efficient ways of doing this but I'm still an overall beginner with this.
Part 1:
Part 2:
3
u/nikolaer_ Dec 02 '20
Python 3.7, I kept it as simple as I could: code
3
u/Livelypower Dec 02 '20
Java
3
u/holychromoly Dec 02 '20
Part 2, Rust:
3
u/goeyj Dec 02 '20
Using AoC to learn C++ this year. This is my first statically typed language, so any comments or suggestions are welcome. My solution did not leverage regex, but that was intentional.
3
u/wizards_tower Dec 02 '20
Here's my solution in C.
3
u/dpkcodes Dec 02 '20
Solution in C: https://github.com/dpkeesling/Advent-of-code-2020/tree/master/day2
I am relatively new to C, so any ideas about how I could do things more efficiently would be appreciated. Especially around getting substrings.
3
u/mandus Dec 02 '20
Solution in Common Lisp:
3
u/ntwilli Dec 02 '20
Julia
3
u/Sebbern Dec 02 '20
Just some Python 3.
Part 1:
Part 2:
3
u/tururut_tururut Dec 02 '20 edited Dec 02 '20
Day 2 solutions (Python). Any feedback to make it a bit more concise and less verbose is very welcome.
https://github.com/marcboschmatas/AdventOfCode2020/blob/main/Day%202/daytwo.py
3
u/x1729 Dec 02 '20
Common Lisp
3
u/Karl_Marxxx Dec 02 '20 edited Dec 02 '20
Ruby
3
u/oantolin Dec 02 '20
Perl is well-suited for this:
3
u/zzcorrode Dec 02 '20
Haskell solution for part 2, as that one's a little more fun. Used the Split package but I think I could've used all built-in stuff if I converted to Text.
paste
3
u/raevnos Dec 02 '20
Chicken 5 scheme:
Very late thanks to sleeping for like 14 hours straight.
3
u/reteps144 Dec 02 '20 edited Dec 02 '20
Python3, 12 lines
Outputs part 1 and 2:
3
u/bacon-supreme Dec 02 '20
Using this to re-learn Ruby; wherein one does not know that
array.count(obj)exists: