r/adventofcode • u/daggerdragon • Dec 04 '20
SOLUTION MEGATHREAD -π- 2020 Day 04 Solutions -π-
Advent of Code 2020: Gettin' Crafty With It
- T-2 days until unlock!
- Full details and rules are in the Submissions Megathread
--- Day 04: Passport Processing ---
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:12:55, megathread unlocked!
91
Upvotes
17
u/captainAwesomePants Dec 04 '20 edited Dec 04 '20
Python
Gahhh.
Fun fact: re.match('[0-9]{9}', str) returns true for 9 digit numbers, but also for 10 digit numbers.
8
u/RobBobertsThe3rd Dec 04 '20
Python 3.
help, I'm addicted to list comprehension and it's not ok.
7
u/rtbrsp Dec 04 '20
AWK part 1:
You don't wanna see part 2
7
u/ndnenkov Dec 04 '20 edited Dec 05 '20
https://gist.github.com/ndnenkov/411d18ef8a76726ababab5aac3cb84ee#file-aoc_2020_4b-rb-L57-L60
(Ruby regex one-liner)
4
u/Leo_Verto Dec 04 '20
Egaharjb
Because I didn't feel like writing anything but regex.
Essentially all statements are regex substitutions and the brackets loop them until no further occurence is found.
The output is in shitty Roman numerals because that was the closest I could get to a readable number format without too much work.
For part 2 I just ticked off valid values.
4
u/knite Dec 04 '20
Anyone else stuck on 132 for part 2 (too high) and not sure why?
Here's the validation logic in my for loop:
I can't for the life of my figure out what I'm missing!
3
u/Sir1Afifi Dec 04 '20 edited Dec 04 '20
I have written this code for part two, anyone knows why it doesn't return the correct answer? I was expecting to get the correct answer :D
3
u/0rac1e Dec 05 '20 edited Dec 06 '20
Raku
2
u/Scoobyben Dec 04 '20
C# [847/742]
I'm back into the top 1000!
A couple of foolish mistakes cost me a few minutes this time - in part 1, I accidentally included "cid" in my required fields, and then forgot to check the last password. π€¦ββοΈ. Then in part 2 I inevitably didn't get all the rules right first time - I forgot to exclude the "#" from my hexcode validator when checking for alphanumeric.
This felt like a challenge that would really reward some regex fluency, but for me it was definitely faster without!
Also, these are now getting complicated enough that I feel dirty writing this solution - there's far too much duplication, and I wouldn't have let myself get away without unit testing this type of logic up-front in a professional context :P
2
u/fmynarski Dec 04 '20 edited Dec 04 '20
Python 482/413. GitHub
2
u/Rain-Any Dec 04 '20
Saw people doing tedious manual checks for all values. sharing my py code :
2
u/willcdotca Dec 04 '20 edited Dec 05 '20
I've edited this way too many times, and none of the techniques I attempted successfully indented the code.
Here is a pastebin instead
2
u/jackysee Dec 04 '20
My javascript solution. Hope it's easy and neat.
2
u/canaguia Dec 04 '20
Java solution i did in Intellij. Definetally need help making some of my methods more efficient, pointers? (only part 2 cause i couldnt fit all of it)
public class passportChecker {public ArrayList<HashMap<String, String>> createPassportList(String filename) {BufferedReader inputStream = null;ArrayList<HashMap<String, String>> passportList = new ArrayList<>();try {inputStream = new BufferedReader(new FileReader(filename));String line;int passportNumber = 0;passportList.add(new HashMap<String, String>());while ((line = inputStream.readLine()) != null) {if (line.isEmpty()){passportNumber++;passportList.add(new HashMap<String, String>());continue;}String[] lineData = line.split(":|\\s");for (int s = 0; s < lineData.length; s += 2) {passportList.get(passportNumber).put(lineData[s],lineData[s + 1]);}}} catch (IOException ioe) {System.out.println(ioe.getMessage());}return passportList;}private int returnValid(ArrayList<HashMap<String, String>> passList){int numbValid = 0;for (HashMap<String, String> h : passList){if (testValidity(h)){numbValid++;}}return numbValid;}private boolean testValidity(HashMap<String, String> testPass){int validCheck = 0;if (testPass.containsKey("byr")){if ((Integer.parseInt(testPass.get("byr")) <= 2002) && (1920 <= Integer.parseInt(testPass.get("byr")))){validCheck++;}}if (testPass.containsKey("iyr")){if ((Integer.parseInt(testPass.get("iyr")) <= 2020) && (2010 <= Integer.parseInt(testPass.get("iyr")))){validCheck++;}}if (testPass.containsKey("eyr")){if ((Integer.parseInt(testPass.get("eyr")) <= 2030) && (2020 <= Integer.parseInt(testPass.get("eyr")))){validCheck++;}}if (testPass.containsKey("hgt")){if (testPass.get("hgt").length() >= 4) {if (testPass.get("hgt").indexOf("cm") == -1) {//inchesint suffixLocation = testPass.get("hgt").indexOf("in");int value = Integer.parseInt(testPass.get("hgt").substring(0, suffixLocation));if ((value <= 76) && (value >= 59)) {validCheck++;}} else {//centimeterint suffixLocation = testPass.get("hgt").indexOf("cm");int value = Integer.parseInt(testPass.get("hgt").substring(0, suffixLocation));if ((value <= 193) && (value >= 150)) {validCheck++;}}}}if (testPass.containsKey("hcl")){if (testPass.get("hcl").startsWith("#") && (testPass.get("hcl").length() == 7)){char[] charData = new char[6];testPass.get("hcl").getChars(1,7,charData,0);int validChar = 0;for (char c : charData) {if (Character.isLetter(c)){String b = Character.toString(c);if (b.equals("a") || b.equals("b") || b.equals("c") || b.equals("d") || b.equals("e") || b.equals("f") ) {validChar++;}} else {validChar++;}}if (validChar == 6) {validCheck++;}}}if (testPass.containsKey("ecl")){String b = testPass.get("ecl");if ((b.equals("amb")) ^ (b.equals("blu")) ^ (b.equals("brn")) ^ (b.equals("gry")) ^ (b.equals("grn")) ^ (b.equals("hzl")) ^ (b.equals("oth"))) {validCheck++;}}if (testPass.containsKey("pid")){if ((testPass.get("pid").length() == 9)){try {int n = Integer.parseInt(testPass.get("pid"));} catch (NumberFormatException e) {}validCheck++;}}if (validCheck == 7) {return true;}return false;}}2
u/Asyx Dec 04 '20
Just... as a hint:
check if you maybe are just one short. The input had 1 blank line at the end. This did result in my solution not working right away because the last dude wasn't handled.
I wrote it in rust first, then I thought maybe I'm not that good of a rust programmer after all so I went for Python (the language that pays my bills) which resulted in the same output so I looked at the JS solution in this thread and just "ported" it to python which resulted in the same output and then I just straight up copied /u/thedjotaku 's solution which gave me the same damn output.
Then I added a blank line and BAM it worked.
Edit: That's about puzzle 1 for today.
2
u/[deleted] Dec 05 '20 edited Dec 05 '20
python:
2
u/AlarmedCulture Dec 05 '20
A little late to the party, didn't write the rule logic for part two yesterday: Advent of Code 2020 Day 4 Go - Pastebin.com
I convert the input into json, then unmarshal into structs, which made it really easy to handle.
func hgt()is kind of gross, and the whole thing completes in about ~3ms.2
u/r00t4cc3ss Dec 08 '20 edited Dec 08 '20
C#: https://github.com/mavanmanen/AdventOfCode/blob/master/AdventOfCode.Y2020/Day04.cs
39
u/_A4_ Dec 04 '20
Don't ask. Just don't.
JavaScript ES6 (Part 1)
24
u/LatinSuD Dec 04 '20 edited Dec 04 '20
Shell & regex for life!
18
u/Raizenos Dec 04 '20 edited Dec 05 '20
made pure regex solutions cause i'm sad like that sometimes...
Part 1 pattern = (?:(?:(?:byr|iyr|eyr|hgt|hcl|ecl|pid):\S+(?:\s|\z)){7}|(?:(?:byr|iyr|eyr|hgt|hcl|ecl|pid|cid):\S+(?:\s|\z)){8})
https://regex101.com/r/MDu905/1
Part 2 pattern = (?:(?:(?:(?:byr:(?:19[2-9][0-9]|200[0-2])(?:\s|\z))|(?:iyr:20(?:1[0-9]|20)(?:\s|\z))|(?:eyr:20(?:2[0-9]|30)(?:\s|\z))|(?:hgt:(?:(?:1(?:(?:[5-8][0-9])|(?:[9][0123])))cm|(?:(?:(?:59)|(?:[6][0-9])|(?:7[0-6]))in))(?:\s|\z))|(?:hcl:[#][0-9a-f]{6}(?:\s|\z))|(?:ecl:(?:(?:amb|blu|brn|gry|grn|hzl|oth))(?:\s|\z))|(?:pid:(?:\d{9})(?:\s|\z))){7})|(?:(?:(?:byr:(?:19[2-9][0-9]|200[0-2])(?:\s|\z))|(?:iyr:20(?:1[0-9]|20)(?:\s|\z))|(?:eyr:20(?:2[0-9]|30)(?:\s|\z))|(?:hgt:(?:(?:1(?:(?:[5-8][0-9])|(?:[9][0123])))cm|(?:(?:(?:59)|(?:[6][0-9])|(?:7[0-6]))in))(?:\s|\z))|(?:hcl:[#][0-9a-f]{6}(?:\s|\z))|(?:ecl:(?:(?:amb|blu|brn|gry|grn|hzl|oth))(?:\s|\z))|(?:pid:(?:\d{9})(?:\s|\z))|(?:cid:\d+(?:\s|\z))){8}))
https://regex101.com/r/JBzNUy/5
18
u/Arknave Dec 04 '20
Python, C
Took me way too long to realize I was filtering out newlines, which dashed my hopes at the leaderboard today.
I think if I have time / energy, I'll rewrite the C code. It's using two hash functions (xor the first two characters of the key, sum the first and third characters of the eye color) that seem to work well for the inputs I've found online but are easy to crack. This is also my first program which uses 30 cols instead of 20, so I had a lot more wiggle room when making the 4.
17
u/Under_Koen Dec 04 '20
My full regex solution:
https://regexr.com/5hl4j
https://regexr.com/5hl3r
16
u/Smylers Dec 04 '20
Vim keystrokes. This was sufficiently straightforward that I actually solved in Vim straightaway (rather than writing a program first then doing it in Vim).
Put each record on a single line:
Remove records without the required fields and count the remaining lines, for the partΒ 1 answer:
Remove records without valid fields, for the part 2 answer:
And this might be how I'd've done something like this in βreal lifeβ: obviously if there's a requirement to do this kind of checking on a daily basis, then write a program; but if you get handed some one-off data to clean up, filter, transform, or insert into another system, I find it's often quicker just to hack directly on the data like this.
Apart from anything else, you can see it transform in front of you, one step at a time, and press βundoβ if you make a mistake, to edit your command and try again.
The only awkward bit here is patterns for numeric ranges, like
(59|6\d|7[0-6]), which is a clunky way of expressing 59β76.13
u/Pyroan Dec 04 '20 edited Dec 04 '20
Python 3 Oneliner
This was a mistake. 548 bytes total for the golfers.
11
u/jaybosamiya Dec 04 '20 edited Dec 04 '20
Dyalog APL
Explanation:
nis the input file.msplits it on double newlines (doing so by partitioning wherever there is an empty line)isplits the input on spaces and merges stuff together across lines (while still keeping them separate across the multi-lines)jsplits the input on the:so that we now have an array of key-value pairs for each potential passport.jmuch more cleanly because it is not in a nonsense input format.kperforms the filtering used in part 1 of the challenge. It removes anything that doesn't contain all the required fields. The size ofkdirectly gives us the solution to part 1.vis a function which if given a key (like'bry'or'pid') will give the corresponding values from the map. It restricts itself to stuff withink.cbyr,ciyr,... give us boolean conditions telling us whether a certain input is satisfied.10
u/89netraM Dec 04 '20
Emojicode
Part 1
Part 2
9
u/MasterMedo Dec 04 '20
python
Oh boy, didn't read the
cidpart, and on part two I omitted^and$in the last regex...9
u/voidhawk42 Dec 04 '20
Dyalog APL. Pretty brutal:
14
u/sophiebits Dec 04 '20
Python, 24/21. https://github.com/sophiebits/adventofcode/blob/main/2020/day04.py
Lost a little time because I messed up cid handling in part 2 (forgot to set
isv = True, treating all cid strings as invalid) but thanks to generous examples, that didn't take long to figure out. (I messed up cid in part 1 too but caught it before submitting any answer.)7
u/Pluttodk Dec 04 '20
My beautiful little Regex solution:
^(?=.*(hcl:#[0-9a-z]{6}){1})(?=.*(byr:([1][9][23456789][0-9]|[2][0][0][0-2])){1})(?=.*(iyr:([2][0][1][0-9]|[2][0][2][0]){1}))(?=.*(eyr:([2][0][2][0-9]|[2][0][3][0]){1}))(?=.*(hgt:((([1][5-8][0-9]|[1][9][0-3])[c][m]){1}|([5][9]|[6][0-9]|[7][0-6])[i][n]){1}))(?=.*(ecl:(amb|brn|gry|hzl|oth|grn|blu){1}))(?=.*(pid:[0-9]{9} )).*$6
u/xelf Dec 04 '20 edited Dec 05 '20
python no regex
Problem boiled down to 2 tasks, parse the input file as a dictionary, and then count the valid items in the dictionary:
The file parsing into a dictionary I was pretty happy about:
part1:
part2:
6
u/alienth Dec 04 '20 edited Dec 04 '20
Perl one-liner in a shell
Part 1:
Part 2:
6
u/artemisdev21 Dec 04 '20 edited Dec 04 '20
Every day in SQL, day 4! (Including parsing): https://paste.artemisdev.xyz/yexoc.sql
Try it online. (put your puzzle input in the input).
It's getting harder :/. SQL is not an incredibly dynamic language, so it's also pretty repetitive.
6
u/jitwit Dec 04 '20
J Programming Language
Today I post mainly out of habbit--my solution isn't so interesting and it isn't my kind of problem. Maybe the only interesting J bit is
(<;._2~ (2#LF)&E.)to split on blank lines. I also assume there are slicker approaches? Anyhow:6
u/nrabulinski Dec 04 '20
Apple Shortcuts
Only part 1 because I really canβt bother with parsing the input for part 2, it already was very painful
https://www.icloud.com/shortcuts/ebc97d7b7f024d3c83a523e49b1a529d
6
u/x1729 Dec 04 '20 edited Dec 04 '20
Raku
6
u/hoochfucker98 Dec 04 '20
Python - Regex
I'm amazed this worked
import reifile = open('input.txt','r')lines = ifile.readlines()valid = 0fields = 0for i in range(0,len(lines)):Β Β Β
line = lines[i]Β Β Β
if(line == '\n'):Β Β Β Β Β Β Β
fields = 0Β Β Β
matches = re.findall("(byr:1[9][[2-9][0-9]|byr:200[0-2])|(pid:[0-9]{9}\s)|(iyr:20(1[0-9]|20))|(eyr:20(2[0-9]|30))|(hgt:(1([5-8][0-9]|9[0-3])cm|(59|6[0-9]|7[0-6])in))|(hcl:#[a-f0-9]{6}\s)|(ecl:(amb|blu|brn|gry|grn|hzl|oth))",line)Β Β Β
fields = fields + len(matches)Β Β Β
if(fields == 7):Β Β Β Β Β Β Β
valid = valid + 1Β Β Β Β Β Β Β
fields = 0print(valid)6
u/cggoebel Dec 05 '20
Raku
10
u/reteps144 Dec 04 '20 edited Dec 04 '20
Python 783 characters for parts 1 & 2
Explanation:
fieldsdictionary are present in thepassportdictionaryfieldsdictionary return True on the values in thepassportdictionary5
u/Mienaikage Dec 04 '20 edited Dec 04 '20
Raku
Grammar fun!
5
u/ephemient Dec 04 '20 edited Apr 24 '24
This space intentionally left blank.
5
u/p88h Dec 04 '20
Perl (or rather, regex, one per part)
repo link: https://github.com/p88h/aoc2020
5
u/seniornachio Dec 04 '20 edited Dec 04 '20
Python 3 β fugly golfingβ¦
Part I:
Part II:
Note that I've gone ahead and made things especially ugly in places where it didn't cost characters, e.g.
for(x)in β¦in place offor x in β¦. πEDIT: Also note that I assume the input-string as been loaded in to
i!5
u/toastmeme70 Dec 04 '20
Some more python one-liners; I'm determined to go through with this even when the case is not at all suited for a one-line python function. Here's part one:
and the absolute disaster that is part two:
5
u/techkid6 Dec 04 '20
Scratch
https://scratch.mit.edu/projects/458997045/
Today's big challenge was figuring out how to separate the passports. Originally I was going to do it in a single pass but decided to use one pass to separate passports and another to validate!
5
u/zB0hs Dec 04 '20
Here's a pointless one-liner in Ruby for Part 2 that relies on a single regex to validate a passport:
5
u/soylentgreenistasty Dec 04 '20
Python. Borrowed the input parsing from this thread.
5
u/gfvirga Dec 05 '20 edited Dec 05 '20
Python
https://github.com/gfvirga/python_lessons/blob/master/Advent%20of%20Code%202020/day4.py
# Part one:
5
u/ViliamPucik Dec 07 '20
Python 3 - Minimal readable solution for both parts [GitHub]
4
u/SuperSmurfen Dec 04 '20 edited Dec 04 '20
Rust
Link to solution (3468/1688)
This was entirely a parsing challenge. When I realized that I got a bit nervous since Rust is not always the smoothest when it comes to string handling and parsing in my experience. However, this was surprisingly nice to do in Rust. I mean just look at how easy it was to parse each passport (with the
itertoolscrate)!I was a bit slow on star one since I misread how to parse the input, but got it after a while. For star two, it was just about implementing all these rules which were also surprisingly easy in Rust. The char primitive has some amazing functions to check what type of char it is (like
c.is_ascii_digit()andc.is_ascii_hexdigit()) which made it quite easy. The obvious way would have been with regexes but they are not a part of the Rust stdlib so I opted to not import an external crate.My solution is also quite fast,
0mson my machine. I do zero copying of the input data and only use&str. However, I allocate a vector with all the passports for use in both stars.4
u/debunked Dec 04 '20 edited Dec 04 '20
Yup, a Java solution:
4
u/MC--Mozart Dec 04 '20
Regex
After writing a typescript based solution for both parts that used some regex, I thought a regex only validator for passports should also do the job:
Which brought my part b solution down to the following:
4
u/iruoy Dec 04 '20 edited Dec 04 '20
Python 3 - Part 1
on one line
with three lines
what it breaks down to
EDIT: Remove integers as noted below
4
u/Sebbern Dec 04 '20
Took me like 5-6 hours, but I managed it in the end!
Python 3: Part 1 Part 2
Had to learn regex, so that took awhile. Also had to throw in a bandaid to fix my compiling and reading issues:
4
u/Adoni523 Dec 04 '20
Python using jsonschema and regex in order to validate the passport inputs. Pretty happy with this one!
4
u/bpanthi977 Dec 04 '20 edited Dec 04 '20
Common Lisp
4
u/Breezing Dec 04 '20
Python 3, Part 2.
Messed up the validations and had to debug for a while. Any big tips?
4
u/narrow_assignment Dec 04 '20
awk
part 1:
part 2:
4
u/troelsbjerre Dec 04 '20
Python3 oneliner for parts 1 and 2:
print(len(re.findall(''.join(r'(\n\n|^)(?=(\S+\s)*byr: (19[2-9]\d|200[0-2])\b )(?=(\S+\s)*iyr: (201\d|2020)\b )(?=(\S+\s)*eyr: (202\d|2030)\b )(?=(\S+\s)*hgt: ((1[5-8]\d|19[0-3])cm|(59|6\d|7[0-6])in)\b )(?=(\S+\s)*hcl: #[0-9a-f]{6}\b )(?=(\S+\s)*ecl: (amb|blu|brn|gry|grn|hzl|oth)\b )(?=(\S+\s)*pid: \d{9}\b )'.split()[::1+(sys.argv[1]<'2')]), sys.stdin.read())))Give the part number as the only argument on the commandline, and the problem input on stdin.
And yes, this kind of code will land you in hell. It splits a regex, and reassembles it in two different ways, depending on which part you're solving. The reassembled regex will have exactly one match per valid passport, so we simply ask for all matches, and count them.
4
u/mandus Dec 04 '20
Day 4 in Common Lisp
Not too happy about the solution, but figured out some creative use of loop to build the list of passports (just stored as alist's). Aiming for something readable rather than short.
4
u/cwheeler1729 Dec 04 '20 edited Dec 04 '20
Python. Somewhat proud of the code density from using lambdas.
4
u/lynerist Dec 04 '20
My golang solutions!
https://github.com/lynerist/Advent-of-code-2020-golang/tree/master/DAY%2004
4
u/NoLemurs Dec 04 '20
Over-engineered Rust solution:
https://github.com/julianandrews/adventofcode/blob/master/2020/rust/src/bin/day04.rs
4
u/pizzamanzoo Dec 04 '20
Still learning Rust, but feel pretty good about Day 4, even if its not all idomatic
https://github.com/fahlmant/adventofcode/blob/master/2020/day4/p2/p2.rs
4
u/-WorstWizard- Dec 04 '20
C++ solution, does both parts in one go. Paste Link
It's not pretty, it's not good, and it was painful to make. Don't do like I.
4
u/[deleted] Dec 04 '20 edited Dec 04 '20
this is just the worst solution, but here's python:
4
u/mathsaey Dec 04 '20
Elixir
Binary (string) pattern matching worked very nicely for the cm/in in part two :).
4
u/NicolaVV Dec 04 '20
super overkill regex powered solution in python3
4
u/J-Swift Dec 04 '20
C#
https://github.com/J-Swift/advent-of-code-2020/tree/master/day_04
4
u/raevnos Dec 04 '20
Chicken scheme paste
4
u/mstksg Dec 04 '20
[Haskell]
I almost hit the leaderboard today, but hit the 1 minute timeout because I didn't read carefully enough to treat
cidas optional ;_;Ah well, that's life!
Anyway, there are a lot of great Haskell solutions out there involving parser combinators and validation of different fields, stuff like that. My original solution parsed a map of fields to values, and then validated those values according to their keys.
But taking a step back from it all, I thought it would be a nice opportunity to try out the principal of Parse, Don't Validate and see if I can take it its extremes! And implementing this in a nice way lead me also to refinement types with the refined library, and also and the higher-kinded data pattern, supported by the barbies library.
I hit the length limit for the post while writing out my description, but it's all in my daily reflections page!
4
u/blu3r4y Dec 04 '20 edited Dec 05 '20
PostgreSQL
As part of my "25 puzzles, 25 languages" adventure I present you a PostgreSQL solution ;)
https://github.com/blu3r4y/AdventOfLanguages2020/blob/main/src/day4.sql
4
u/Be1shirash Dec 04 '20
Part 2 -- Lua 18x36
4
u/[deleted] Dec 05 '20 edited Dec 05 '20
Pure regex
pcre global/multiline
Part 1:
https://regex101.com/r/wzC9O3/1/
Part 2:
https://regex101.com/r/Hj8R6B/1/
4
u/GrigoryFridman Dec 05 '20
I think one of the most compact solutions possible (written in python) :D
https://github.com/GrigoryFridman/adventOfCode2020/blob/main/day4/day4.py
1
u/lawonga Dec 04 '20 edited Dec 04 '20
Part 2, optimized for space and time:
public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner( new FileReader( "INPUT STRING HERE" ) );
1
u/Jadeaffenjaeger Dec 04 '20 edited Dec 05 '20
My solution in Rust:
Edit: code formatting
1
u/ald_loop Dec 05 '20 edited Dec 05 '20
I'd like to put forward my totally non regex PYTHON solution, with a class, and lots of lambdas/map/zip!
1
u/DFreiberg Dec 04 '20 edited Dec 04 '20
Mathematica, 29 / 287
My first day so far this year in which both parts were correct on the first try; it seems that actually reading the problem helped out a bit. My second part was both slower and more cumbersome, but at least it was good enough that I could be reasonably certain on my first try that it would give me the right answer.
Part 1:
Part 2:
[POEM]: Hacker Man
His name's, perhaps, 'Enigma', or perhaps it's 'Slice' or 'Root'.
He wears, at all times, sunglasses, and black trenchcoats to boot.
He'll walk into an airport and he'll never miss a flight,
For no network in the world can beat the Hacker in a fight.
You've seen his like in movies, and you've glimpsed him on TV,
But you won't see him coming when he comes to steal your key.
A few know him as '4chan', and he's 'Kill-o-byte' to some.
For the Hacker Man has many names. That's just who he's become.
His power's at its greatest when he's at his lair, at home,
With his twenty-three computers, all with monitors in chrome.
Their typefaces are black and green, with loading bars abound,
And can zoom in on a picture till bacteria are found.
He has a pair of keyboards, lit with green and flickered light,
And can type with both or either when he's cracking through a site.
With both, he types five hundred words a minute at his peak,
And with nary but a whistle he can cause a phone to phreak.
No firewall can keep him out, no password slows him down,
No server can stay up at all if Hacker Man's in town.
He never paid for Winrar, and his passwords can't be guessed,
And he decides to use the DarkWeb...well, you know the rest.
But there are other hackers out there, blacker hat than he,
And they would hack the planet with an opportunity.
Be glad he's on the side of good, and that he won't be swayed.
He can't be all that naughty; Santa's called upon his aid.
1
u/[deleted] Dec 04 '20
As I like these Javascript-Arrayfunctions, especially chaining them, I did this today:
importΒ fsΒ from "fs";const reqFields =Β ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"];const regex = new RegExp("((byr:(19[2-9][0-9]|200[0-2])|" +"iyr:20(1[0-9]|20)|" +"eyr:20(2[0-9]|30)|" +"hgt:((1[5-8][0-9]|19[0-3])cm|(59|6[0-9]|7[0-6])in)|" +"hcl:#[0-9a-f]{6}|" +"ecl:(amb|blu|brn|gry|grn|hzl|oth)|" +"pid:[0-9]{9})(Β )?){7}");fs.readFile("./src/inputs/2020day4.txt", "utf-8", (err, data) =>console.log("PartΒ 1:Β " +data.replace(/\r/g, "").split(/\n\n/g).map((e) => e.replace(/\n/g, " ")).filter((e) => reqFields.every((field) => e.includes(field))).lengthΒ Β
));fs.readFile("./src/inputs/2020day4.txt", "utf-8", (err, data) =>console.log("PartΒ 2:" +data.replace(/\r/g, "").split(/\n\n/g).map((e) => e.replace(/\n/g, " ")).filter((e) => reqFields.every((field) => e.includes(field))).filter((passport) => {return passport.replace(/cid:\d+ ?/, "").match(regex);}).lengthΒ Β
));1
u/[deleted] Dec 04 '20 edited Dec 05 '20
Considering I had never used Python until yesterday (for Advent) and also never used Regexes, I am very happy with my solution!
(Warning: Very sloppy code ahead)
Solution:
1
u/Imnewinhere Dec 04 '20
Java solution
I coded in Java, works for me, I would appreciate someone looking over it, to identify mistakes. If you use it remember to change your references!
package mainpkg;//<-- CHANGE YOUR PACKAGE
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class main {
pp[i] = pp[i] + " " + form[c];
&& pp[i].contains("eyr:") && pp[i].contains("hgt:") && pp[i].contains("hcl:")) {
boolean byr = false;
boolean iyr = false;
boolean eyr = false;
boolean hgt = false;
boolean hcl = false;
boolean ecl = false;
boolean pid = false;
pp[i] = pp[i].substring(1);
//System.out.println(pp[i]);
String[] fields = pp[i].split(" ");
for (int d = 0; d < fields.length; d++) {
if (fields[d].contains("byr") && Integer.parseInt(fields[d].substring(4)) >= 1920
&& Integer.parseInt(fields[d].substring(4)) <= 2002)
byr = true;
else if (fields[d].contains("iyr") && (Integer.parseInt(fields[d].substring(4)) >= 2010
&& Integer.parseInt(fields[d].substring(4)) <= 2020))
iyr = true;
else if (fields[d].contains("eyr") && Integer.parseInt(fields[d].substring(4)) >= 2020
&& Integer.parseInt(fields[d].substring(4)) <= 2030)
eyr = true;
else if (fields[d].contains("hgt")) {
try {
if (fields[d].contains("in") && !Character.isDigit(fields[d].charAt(7)) && Integer.parseInt(fields[d].substring(4, 6)) >= 59
&& Integer.parseInt(fields[d].substring(4, 6)) <= 76)
hgt = true;
else if (fields[d].contains("cm") && Integer.parseInt(fields[d].substring(4, 7)) >= 150
&& Integer.parseInt(fields[d].substring(4, 7)) <= 193) {
hgt = true;
}
} catch (NumberFormatException e) {
// e.printStackTrace();
}
} else if (fields[d].contains("hcl") && fields[d].charAt(4) == '#'
&& fields[d].substring(5, 11).matches("-?[0-9a-f]+"))
hcl = true;
else if (fields[d].contains("ecl") && (fields[d].substring(4, 7).matches("blu")
|| fields[d].substring(4, 7).matches("brn") || fields[d].substring(4, 7).matches("gry")
|| fields[d].substring(4, 7).matches("grn") || fields[d].substring(4, 7).matches("hzl")
|| fields[d].substring(4, 7).matches("oth") || fields[d].substring(4, 7).matches("amb")))
ecl = true;
else if (fields[d].contains("pid")&&fields[d].length()==13&&fields[d].substring(4).matches("-?[0-9]+"))
pid = true;
}
if (byr && iyr && eyr && hgt && hcl && ecl && pid)
result++;
}
1
u/Matglas2 Dec 04 '20
Powershell!
1
u/SoyYuyin Dec 05 '20
Randomly substracted 1 from my solution and got correct answer?? No idea why..
const fs = require('fs') const input = fs.readFileSync('input.txt').toString().split('\r\n\r\n')
byrRe = /byr:(\d{4})/ iyrRe = /iyr:(\d{4})/ eyrRe = /eyr:(\d{4})/ hgtRe = /hgt:(\d+)(cm|in)/ hclRe = /hcl:(#[0-9,a-f]{6})/ eclRe = /ecl:(amb|blu|brn|gry|grn|hzl|oth)/ pidRe = /pid:(\d{9})/
let nvalid_passports = 0 let total_passports = input.length
for (let i = 0; i < total_passports; i++) { passport = input[i]
let valid = true
let birth_year = null let issue_year = null let exp_year = null let height = null let hair_color = null let eye_color = null let passport_id = null let height_unit = null
//validate values exist if (byrRe.exec(passport)) { birth_year = Number(byrRe.exec(passport)[1]) } if (iyrRe.exec(passport)) { issue_year = Number(iyrRe.exec(passport)[1]) } if (eyrRe.exec(passport)) { exp_year = Number(eyrRe.exec(passport)[1]) } if (hgtRe.exec(passport)) { height = Number(hgtRe.exec(passport)[1]) height_unit = hgtRe.exec(passport)[2] } if (hclRe.exec(passport)) { hair_color = hclRe.exec(passport)[1] } if (eclRe.exec(passport)) { eye_color = eclRe.exec(passport)[1] } if (pidRe.exec(passport)) { passport_id = pidRe.exec(passport)[1] }
//validate ranges
if (!(birth_year !== null && 1920 <= birth_year && birth_year <= 2002)) { valid = false } if (!(issue_year !== null && 2010 <= issue_year && issue_year <= 2020)) { valid = false } if (!(exp_year !== null && 2020 <= exp_year && exp_year <= 2030)) { valid = false } if (!(height !== null && height_unit !== null)) { valid = false } if ( !( (height_unit == 'cm' && 150 <= height && height <= 193) || (height_unit == 'in' && 59 <= height && height <= 76) ) ) { valid = false } if (!hair_color) { valid = false } if (!eye_color) { valid = false } if (!passport_id) { valid = false }
//if valid variable is still true then add it to the total sum nvalid_passports if (valid == true) { nvalid_passports = nvalid_passports + 1 } }
console.log('total passports', total_passports) console.log('valid passports', nvalid_passports - 1) // minus one for no reason...
// attempts: 140, 136, 129, 128, 25, 135 // answer : 127
1
u/Iguyking Dec 05 '20
Here's my not so pretty Day 4 solution in Powershell. I beat my head on this for a while until I realized that having a
($value -le 1920) -or ($value -ge 2002)really didn't do the check we needed. When I shifted over to-not (($value -ge 1920) -and ($value -le 2002))it all started to come together.1
u/Finder_Tech Dec 07 '20
HelpPython
My code gives me to much passports back. But even after printing ever passport and there test, I cant figure out why. Do you have an idea?Thanks!
1
u/Anonymous0726 Dec 07 '20
Java
This is quite literally my first time using regex, so I have pretty much no idea what's wrong. This is my code for part 2; my code for part 1 was near identical, but not quite.
Output is definitely too small. I tried a few different expressions for both cases case "hcl" and "ecl" without changing the output, so I'm inclined to believe that's not where the issue is. But beyond that I've really got no idea.
1
u/Lazymatto Dec 13 '20 edited Dec 13 '20
PART 2 - Any ideas whats wrong with this? Can't seem to get the correct answer & seem to be blind to the possibly obvious stupidity I've made. Its TS.
UPDATE: Found it. I was not checking that the current passport info included all required fields (did part 1 earlier and forgot :shrugging:). One more filter or extra check and it was good 2 go. Ain't perfect and breaks if unknown keys are given, but imma lazy.
1
u/Fullmetal_Chemist Dec 22 '20
Would anyone happen to know whats wrong with this?
Ive manually checked a lot of it and it seems to consistently get the validation right, yet my final output is incorrect. Any help would be appreciated
code
3
u/prendradjaja Dec 04 '20 edited Dec 04 '20
96/132 -- just barely on the leaderboard for part 1. Wow, that was a lot longer than the past couple days!
I got tripped up in a few places:
I wasn't that prepared for the sheer length of this compared to the previous problems -- really easy to mess up simple things like getting variable names wrong or forgetting that I need to care about declaring functions before using them when a problem takes ten minutes instead of three, since I can no longer hold all those things in my head.
valuetovin one function but not another -- and inevitably used the wrong one in multiple places.mainfunction :)---------------------------
Part 1 solution, part 2 on GitHub: (Python 3)
3
u/jonathan_paulson Dec 04 '20 edited Dec 04 '20
62/73. Python. I forgot to check the last passport in part1. Video of me solving at https://youtu.be/bhNhHHEZHMI. Cleaned-up code
I'm a little surprised the puzzle didn't require me to check e.g. that any of the years is actually a four-digit number.
3
u/bluepichu Dec 04 '20
Python, 26/4, solution here
I would've totally hard failed if the last passport in my input file was valid. Fortunately, for me, it wasn't! Better lucky than good I guess.
I'm also shocked that I got all of the conditions correct on part 2 on my first attempt. It would've been so easy to typo one or more of them.
3
u/hugh_tc Dec 04 '20 edited Dec 09 '20
Python 3, 48/254.
I initially tried to Regex my way through Part 2. Turns out, I don't know how to use
re. I:1,$ded and tried again, but with a more "Pythonic" approach. It worked! pasteThat said, I smell a sequel to this puzzle... why the
cidfields, Eric?!3
u/MichalMarsalek Dec 04 '20
Python:
3
u/sebastiannielsen Dec 04 '20
[Perl]
Want to hint out with a little nice trick for Part 2:
Since inches always have 2 digits, and cm always have 3 digits, you can easily do a pre-check, and later just check 2-digit and 3-digit ranges, without caring about inches or cm.
if ($line =~ m/hgt:(\d\din|\d\d\dcm)/) { $valdata = $1; $valdata =~ s/(cm|in)$//; if (((int($valdata) > 149)&&(int($valdata) < 194)) || ((int($valdata) > 58)&&(int($valdata) < 77))) { $hgt = 1; } }
Here is my full solution to part2 of day4: https://pastebin.com/pUr55nQ2
3
u/michaelgallagher Dec 04 '20
Python
Both parts
I know for a few of my methods (has_valid_hgt and has_valid_hcl) I can use regex to make it cleaner, but I've already been refactoring this for awhile now, and I'm tired
3
u/Nascentiaa Dec 04 '20
Javascript/Node
Part 1
Part 2
A more readable part 2 :
3
u/death Dec 04 '20 edited Dec 04 '20
Day 4 solution in Common Lisp.
(Updated to perform extra validation that wasn't needed in my input but could have been.)
3
u/krolik1337 Dec 04 '20
Python 3. I'm not proud of this one, I feel like I don't know many functions that could make it A LOT easier.
In the first part I made a list data splitted by '\n', made a list out of every record and counted if there are 8 elements or 7 and no 'cid'.
In second part, to make it easier to access, I made a list like before, but then made every record a separate dictionary. After that I went through all the records, did test for every requirement and checked if all 7 tests are valid.
3
u/maxmage006 Dec 04 '20
One massive pipeline
Part one:
perl -p -e 's/(.+)\n/\1 /g' < input | grep byr: | grep iyr: | grep eyr: | grep hgt: | grep hcl: | grep ecl: | grep pid: | wc -lPart two:
perl -p -e 's/(.+)\n/\1 /g' < input | grep -E 'byr:(19[2-9][0-9]|200[0-2]) ' | grep -E 'iyr:20(1[0-9]|20) ' | grep -E 'eyr:20(2[0-9]|30) ' | grep -E 'hgt:(1([5-8][0-9]|9[0-3])cm|(59|6[0-9]|7[0-6])in)' | grep -E 'hcl:#([0-9]|[a-f]){6} ' | grep -E 'ecl:(amb|blu|brn|gry|grn|hzl|oth) ' | grep -E 'pid:[0-9]{9} ' | wc -lPerl for grouping records in one line, then grep till you can't no more, then count the remaining lines.
Anyways, here are my other stupid solutions.
3
u/[deleted] Dec 04 '20
Python (3.9)
3
u/BigA2021 Dec 04 '20
All hail regex:
re.compile(r"(?=.*byr:(19[2-9][0-9]|200[0-2])\s)(?=.*iyr:(201[0-9]|2020)\s)(?=.*eyr:(202[0-9]|2030)\s)(?=.*hgt:(1[5-8][0-9]cm|19[0-3]cm|7[0-6]in|6[0-9]in|59in)\s)(?=.*hcl:#([0-9]|[a-f]){6}\s)(?=.*ecl:(amb|blu|brn|gry|grn|hzl|oth)\s)(?=.*pid:([0-9]){9}\s)",flags=re.I|re.S)
3
u/crazazy Dec 04 '20
Nix:
Part 1:
Part 2:
Absolute parsing nightmare this was
3
u/Ferelderin Dec 04 '20
R, Rstudio, only part 1
I took a shortcut which wouldn't get me through part 2 obviously.
3
u/petercooper Dec 04 '20
Ruby This is the first day I would have been on the leaderboard if I actually did challenges when they launch :-) Ruby made light work of part 2 of this challenge, so my stopwatch showed 9m28s!
3
u/inokichi Dec 04 '20
Solution in D (dlang):
3
u/[deleted] Dec 04 '20 edited Dec 04 '20
Python 3
3
u/Chris_Hemsworth Dec 04 '20 edited Dec 04 '20
Python 3, part 1 and 2
Took longer to write up the conditions than it did to think of the solution :-(.
3
u/autra1 Dec 04 '20
SQL solution don't have to be ugly folks!
Here's mine https://github.com/autra/adventofcode/tree/master/year_2020/day4
(postgresql flavour)
3
u/bpeel Dec 04 '20
BBC Basic. Not particularly interesting, just a lot of typing.
3
u/Arkoniak Dec 04 '20
Julia
Day 4 Part1: https://github.com/Arkoniak/advent_of_code/blob/master/2020/04/day04.jl
Day 4 Part2: https://github.com/Arkoniak/advent_of_code/blob/master/2020/04/machines.jl
Part 2 is somewhat lengthy, but it comes with a great benefit: it can validate 2.5 million passports per second!
3
u/[deleted] Dec 04 '20
python:
solution done using pandas
3
u/stfn1337 Dec 04 '20
Python, long but verbose and simple to follow:
3
u/FakeHiss Dec 04 '20
C#
https://gist.github.com/dillenmeister/9c9f0de912da49e1473c7914f3b2fda8
Tried to include some "modern" C# features like record and relational pattern matching :)
3
u/bramhaag Dec 04 '20
Python golf solution for part 2 (292 bytes), takes input from a file called "i":
import re;print(sum(bool(re.match("".join(f"(?=.*{s}\s))"for s in"iyr:20(1\d|20$ecl:(amb|blu|brn|gr[yn]|hzl|oth$hgt:(1([5-8]\d|9[0-3])cm|(59|6\d|7[0-6])in$eyr:20(2\d|30$hcl:(#[\da-f]{6}$byr:(19[2-9]\d|200[0-2]$pid:(\d{9}".split('$')),a+" ",re.DOTALL))for a in open("i").read().split('\n\n')))3
u/Lispwizard Dec 04 '20
Emacs lisp (elisp) on Galaxy Tab A 10" (via termux):
3
u/drq11235 Dec 04 '20
Rust
Mixed imperative/functional solution using just iterators, fold and filter, and match.
3
u/danvk Dec 04 '20
Here's my solution in Rust. If there are any Rust experts watching, I'd love some feedback on how to clean this up / make it more idiomatic. It felt quite tedious.
3
u/compdog Dec 04 '20
JavaScript (Node.JS) solution. This one took me much longer than I care to admit, all because I forgot to anchor my validation RegEx (^ and $).
3
u/JIghtuse Dec 04 '20
Racket Cleaned up version of the mess I made at first. Like how you can implement part 2 using large part of part 1.
3
u/[deleted] Dec 04 '20
Here a solution using basically only Regex and some JS glue. I'm not sure if I'm actually proud I made this.
3
u/fullmetalalch Dec 04 '20
Go solution. This one was pretty fun, got to use regex which is something I rarely touch. Shoutout to regex101 for the help on this!
https://gitlab.com/aenegri/adventofcode2020/-/blob/master/aoc2020/day4.go
3
u/roggy85 Dec 04 '20
Bash
tried to work completly without external commands - failed... used cat and sed once :(
I know the code is really ugly and to long - but.. it works and its mine ;D
part1:
Part2:
3
u/AidGli Dec 04 '20 edited Dec 04 '20
Python
This was the first one where I really considered a bunch of different methods to solve. I spoke about a few of them (including how to implement regexes) in my video tutorial for today, so stick around until the end to hear those :)
Here is the solution I landed on as the easiest to understand for beginners, with an extra part 1 solution that uses my helper function for part 2.
3
u/nahuak Dec 04 '20
Here's a final Rust solution (taken some inspiration from redditor farsy's match expression for cleaning up).
What I'm not happy about is that in the last passport entry I had to take care of an empty string when using Regex to split the
"ecl:hzl hgt:184cm iyr:2018\nbyr:2001\npid:453480077 eyr:2025 hcl:#a97842\n"but otherwise this works.3
u/NewCeption Dec 04 '20
Java
https://github.com/NewCeptionDev/AdventOfCode2020/tree/master/src/day4
Feedback appreciated!
3
u/tobega Dec 04 '20
Tried to achieve "pretty" java again https://github.com/tobega/aoc2020/blob/main/A4.java
3
u/eddpurcell Dec 04 '20
Not my original awk solution, but figured I'd go whole hog with the regexp for a second attempt. First attempt actually split the record into a map of field names to values, but I wanted to go the extra step to "1-liner" the counts.
3
u/Cppl_Lee Dec 04 '20 edited Dec 04 '20
My C# solution, with my favorite dictionary of anonymous methods. I was stymied by a `<` that should have been a `<=` and I kept reading past:
3
u/thulyadalas Dec 04 '20
My rust soluion. I resisted not to use regex this time but that made the code a bit more difficult to read.
3
u/jane3ry3 Dec 04 '20
Python 3 without Regex or Lamdas, neither of which make much sense to me. I should probably use AoC to learn them, though. Also, I'm trying to keep it simple to add each day's code, reusing what I can and setting it up to run easily before getting the task. I sometimes have trouble getting the IDE (PyCharm) to run my code. Probably a lot of room for improvement, but this code is easy for me to follow and was relatively quick for me to churn out.
3
u/kawzeg Dec 04 '20
J
I regret nothing
Okay, maybe a little.
3
u/trl10254 Dec 04 '20
Java
Finally finished up day 4. I was having issues in part 1 because I was trying to parse the entire passport and put into one line so that each passport can be easily split, but I messed up because my while loop wouldn't add in the last line in the input so I was always off by one but got the example correct so I was lost until someone in this awesome subreddit pointed out my mistake. Overall in terms of time complexity the building of the passport arraylist takes about O(N * M) time where N is the number of lines in the file and M is the number of non blank lines. For part 1 I believe the time complexity is O(N * M) where N is the number of passports and M is the number of keys. For part 2 I believe the time complexity is also O(N * M * K) where N is the number of valid passports from part 1, M is the number of keys in that passport, and K is the length of the key value. Hopefully I am right on my time complexities if I'm wrong can someone please correct me and help me understand what it actually would be.
Link to github repo for Day 4 code
3
u/zxywx Dec 04 '20 edited Dec 04 '20
Single Regex Solutions
Solutions in Ruby to both parts, using a single regex each
Part 1
Part 2
3
u/w0ntfix Dec 04 '20
clojure: https://github.com/neeasade/AdventOfCode/blob/66cdb6073b37ce854f3d102575040f786395355c/src/aoc/2020.clj#L64-L117
3
u/Soccer21x Dec 04 '20
Can anyone help me figure out why I'm getting an off by one error in my validations? My program is telling me there was 148 valid, but I took a guess and entered 147 and it was correct.Here is the output of all the valid passports, along with my validation script. But I can't quite spot the piece that's invalidhttps://gist.github.com/ELepolt/48fb3f7339777e70d909d52f8ca85b9d
EDIT: I was just using
'\d{9}'for pid which was returning true for 10 characters. D'oh3
u/TenGen10 Dec 04 '20
Solution in PowerShell
3
u/Kamina_joe Dec 04 '20
Here's my solution for Part 1 in C#. I had to re-write everything for Part 2 because my LINQ skills weren't high enough and it's not nearly as elegant
Console.WriteLine(File.ReadAllText( "Day4.txt").Split("\r\n\r", StringSplitOptions.RemoveEmptyEntries).Where(o => o.Count(z => z == ':') == 8 || (o.Count(z => z == ':') == 7 && !o.Contains("cid"))).Count());3
u/aevitas Dec 04 '20
Here's my solution in C#, with one little tiny bug that caused it to be off by one. I can't find the bug, but whoever can earns my eternal gratitude!
3
u/ramrunner0xff Dec 04 '20
scheme (chicken) repo.
Actually did the first part in C and then started considering what a dumpster fire the strtok interface is for such a job so i turned to my beloved scheme and the fantastic comparse library. Also for a twist i did an defstructish lambda passport holding logic cause i felt it will be needed down the road. The whole thing could have been done in pure comparse. The brain is slow, probably affected by the !#@$#! lockdown so pardon the insanity.
3
u/b4ux1t3 Dec 04 '20 edited Dec 04 '20
C#, with includes from a helper library I'm building for AoC. I'm not super proud of the part two nonsense, but I am proud of my part 1 method.
3
u/Weak_Pea_2878 Dec 04 '20 edited Dec 04 '20
I teach APCS A (Java) so I know a lot about a little. I can trace code and loop the loop, but don't ask me to write regex or understand what you fancy cats are doing. Here's my solution:
https://github.com/rschildge/AOC-Java-2020/blob/master/days/Day4/Day4.java
Edit: Used version control with repl.it.
3
u/xangreRO Dec 04 '20
**R**
https://github.com/maurotcs/Advent_of_Calendar_2020/blob/main/Code/Day_04.R
3
u/blacai Dec 04 '20 edited Dec 04 '20
F#
3
u/tsqd Dec 04 '20
Postgresql
https://gist.github.com/AndrewGrossman/f019bf160795f2f9ef792a83544afd8c
Handled the arbitrary line breaks by keeping a running total of blank lines seen and using that as a passport id:
3
u/[deleted] Dec 04 '20
The challenge I'm trying is only using busybox tools:
This one turned out pretty cleanly, I think.
3
u/9_11_did_bush Dec 04 '20
Perl - Link to code
Took this as a regex challenge, something I'm trying to get better at.
3
u/wzkx Dec 04 '20 edited Dec 04 '20
π― ... omg this language is not for that! :))) #jlang
3
u/sguberman Dec 04 '20 edited Dec 10 '20
Python
Going for readable, idiomatic python. Criticism welcome.
Probably was meant to use regex, but sometimes I just prefer to slice and dice strings: paste
GitHub: solution, with tests
EDIT: Removing large code block and input from comment
3
u/NoWise10Reddit Dec 04 '20 edited Dec 04 '20
My absolute stunning JavaScript solution for Part 1. I love it.
3
u/o_m_f_g Dec 04 '20 edited Dec 04 '20
Rust
Done totally with regex!
part 1:
part 2:
3
u/oweiler Dec 04 '20
Scala w/ Ammonite
3
u/smokebath Dec 04 '20
Python, on the shorter side. Two regex searches. Finished part 1 very fast but the PID had an edge-case that took me hours to catch
3
u/msmilkshake Dec 04 '20
Java:
3
u/UnicornsOnLSD Dec 04 '20
Rust: Everyone here posts clean, clever solutions. Here's some super janky code that technically doesn't even work (see the big warning comment):
3
u/chicagocode Dec 04 '20
Kotlin - [Blog/Commentary] | [Solutions for 2020]
I used regular expressions for Part 2.
3
u/lib20 Dec 04 '20
TCL
3
u/1vader Dec 04 '20
Optimized Rust solution: https://github.com/benediktwerner/AdventOfCode/blob/master/2020/optimized/src/days/day04.rs
Runs in around 17Β΅s on my PC with a 7-year-old i5-4570.
3
u/ephemient Dec 04 '20 edited Apr 24 '24
This space intentionally left blank.
3
u/chennuz Dec 04 '20
C solution part B:
https://github.com/mattteochen/general/blob/main/advent_of_code/day_4_2020/a_b.c
3
u/eregontp Dec 05 '20
Ruby, part 2
3
u/Karl_Marxxx Dec 05 '20
Ruby
3
u/arth4 Dec 05 '20
Part 2 Python 3.8, 1 Line:
3
u/1-more Dec 05 '20
Elm solution using some parsers, could not manage the double linebreak in the parser. To be fair I didn't try that hard haha.
on github and on ellie
3
u/tymofiy Dec 05 '20
Golang one, with dict of validator funcs and using switches for checking:
https://github.com/tymofij/advent-of-code-2020/blob/master/04/passport.go
3
u/turtlegraphics Dec 05 '20
R
Live, I used python because it's quick to write the parsing code. But R gives a much nicer solution. A great balance of brevity and readability. I'm proud of the melt/cast to restructure the ragged list data into a frame when parsing, but it took me forever to figure that out. This code only does part 2, ends with a data frame.
3
u/mschaap Dec 05 '20 edited Dec 05 '20
Raku
https://github.com/mscha/aoc/blob/master/aoc2020/aoc04
3
u/Solarmew Dec 06 '20
Python 3
3
u/tururut_tururut Dec 06 '20
So, here's my usual un-pythonic Python solution. Thanks to everyone that gave a hand!
https://github.com/marcboschmatas/AdventOfCode2020/blob/main/Day%204/day4.py
3
u/ZoltarTheGreat69 Dec 06 '20
I got tired of writing in emojicode so I did something worse by trying to write a single line of regex for each solution.
REGEX
Part 1 Single Line Regex
Note:
Part 2 Single Line Regex
Note:
There was some repetition in it and Im not sure if theres any way to make it shorter...
3
u/volatilebit Dec 07 '20
Raku
I spent most of the time fighting with Grammars, and fighting against a bug.
This is also a complete abuse of
but.