r/adventofcode • • Dec 16 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 16 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It

  • 6 days remaining until the submission deadline on December 22 at 23:59 EST

  • Full details and rules are in the Submissions Megathread


--- Day 16: Ticket Translation ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code 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:21:03, megathread unlocked!

37 Upvotes

498 comments sorted by

10

u/pred Dec 16 '20 edited Dec 16 '20

Python; one fun little hack today is that for two sets, s1 and s2, s1 < s2 iff s1 is a subset of s2. Given the nature of the constraint satisfaction problem in part two, this allowed you to get the result by simply sorting the domains; i.e. do what amounts to

domain = {
    i: {j for j in range(20) if
        all((t1 <= l[j] <= t2) or (t3 <= l[j] <= t4) for l in valids)}
    for i, (t1, t2, t3, t4) in enumerate(ranges)
}

model = {}
for k, values in sorted(domain.items(), key=lambda x: x[1]):
    model[k], = values - set(model.values())

But then again, why bother when you have scipy.sparse.csgraph.maximum_bipartite_matching for doing all the work in the more general case.

GitHub

→ More replies (2)

3

u/keramitas Dec 16 '20 edited Dec 16 '20

Welp today was fun, got 949 then 338, but difficulty this year is somewhat puzzling ~,~ Not at home, so here's a gist with my cleaned up Python code, I'll add it to the repo later

2

u/daggerdragon Dec 16 '20

Please follow the posting guidelines and edit your post to add what language(s) you used. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.

2

u/vanderZwan Dec 16 '20 edited Dec 16 '20

javascript (ObservableHQ)

One of these days I'll learn how to regex the input, but for now I'll just get by with repeated applications of split() and .map()

Also I see everyone else have elegant solution here but I'm too dumb for that at 6:00 after a night of insomnia. Behold, my disgusting nested for-loops:

https://observablehq.com/@jobleonard/day-16-ticket-translation

→ More replies (2)

2

u/Symbroson Dec 18 '20 edited Dec 18 '20

Perl. One beautiful 17 line mess

Part 2

→ More replies (1)

16

u/Mathgeek007 Dec 16 '20 edited Dec 16 '20

Nice, sub-hour.

EXCEL

I did this by pure, analytic force. For part 1, I made ranges and for every value in the ticket, checked if they were between the values permitted. Return 0 if legit, the value otherwise. Then it's just a matter of counting.

Part 2 I made a lookup chart - the column was the value from 1-1000, the row was the rule. Pretty easy to write those rules, the rest was checking each value, summing. Then I had a logic table I needed to simplify, which I did by recursion.

EDIT: Expect an update to my online Sheets soon, once I get the logic table recursion to work.

EDIT 2: It officially is now all automatic in Excel. Lastly is to upload it to Sheets. Lots of INDIRECTs, so it hopefully won't be too bad once I wake up

11

u/xelf Dec 16 '20 edited Dec 16 '20

python: comprehensions gone wild.

Another surprisingly quick one. part 1&2 in 12 lines:

First parse all the data, I parse the rules into a pair of ranges per rule, and the tickets into a list of ints, and then find all the valid tickets. Form there I find all the possible positions that all the rules match. I sort that list by the number of possibilities and then just iterate over it adding each position to a used set as I determine the rule it matches.

rules    = re.findall('(.+): (.+)-(.+) or (.+)-(.+)\n', open(day_16_path1).read())
rules    = { name:[range(int(a),int(b)+1), range(int(c),int(d)+1)] for name,a,b,c,d in rules}
tickets  = [ list(map(int,line.split(','))) for line in open(day_16_path2).readlines() ]
part1    = sum(n for t in tickets for n in t if not any(n in rule[0] or n in rule[1] for rule in rules.values()))
yourtix  = list(map(int,open(day_16_path3).read().split(',')))
valid    = [ t for t in tickets if all( any(n in rule[0] or n in rule[1] for rule in rules.values()) for n in t) ]
possible = { name: { j for j in range(20) if all((v[j] in rule[0] or v[j] in rule[1]) for v in valid) } for name,rule in rules.items() }

part2,used = 1,set()
for p in sorted(possible, key=lambda l: len(possible[l])):
    if p.startswith('departure'): part2 *= yourtix[(possible[p]-used).pop()]
    used.update(possible[p])
print('part 1:', part1, 'part 2:', part2)
→ More replies (6)

13

u/DFreiberg Dec 16 '20

Mathematica, 1118 / 859

Not too bad, today; I ended up forgetting about, remembering, importing, deleting and rewriting my code from 2018's Day 16 part 2 (in roughly that order).

[POEM]: Self-Reflection

There are times I stop and ponder,
As I'm waiting to depart,
Whether I'm in fact, the bad guy,
Though I'm innocent at heart.

Hacking into airport cameras
Doesn't fit your average geek,
But I've hacked through those (and networks)
Thrice or more, just this past week.

I've scanned through people's tickets
Both for land trains and for flights.
I've forgotten last week's passwords,
'Cause I'm busy with tonight's.

Is there coal bound for my stocking,
When I hang it up at last,
Even though I've aided Santa
Several times in Christmas Past?

I suppose there is an option,
When the Big Guy makes his list.
Since he checks it two times only,
Maybe I can still be missed.

If the list is based on hashes,
I think I'll know what to do.
When the Naughty List comes calling...

...I think I'll just hack that too.

→ More replies (2)

12

u/jayfoad Dec 16 '20 edited Dec 16 '20

Dyalog APL 313/85

⎕IO←0 ⋄ ⎕PP←17 ⋄ to←{⍺+⍳1+⍵-⍺}
r y n←1 2 2↓¨{⍵⊂⍨0=≢¨⍵}(⊂''),⊃⎕NGET'p16.txt'1
r←↑{a b c d←⍎¨⍵ ⋄ 1000↑⍸⍣¯1⊢(a to b),c to d}¨'\d+'⎕S'&'¨r ⍝ rules
y←⍎⊃y ⍝ your ticket
n←↑⍎¨n ⍝ nearby tickets
+/(,n)/⍨~,t←(⊂n)⌷∨⌿r ⍝ part 1
v←n⌿⍨∧/t ⍝ valid nearby tickets
×/y/⍨{∨⌿(6>g)⌿2<⌿0⍪⍵⌷⍨⊂g←⍋+/⍵}(↓r)∘.{∧/⍺[⍵]}↓⍉v ⍝ part 2

This relies on all the values in nearby tickets being < 1000, and the six "departure" rules being the first six rules.

7

u/pxOMR Dec 16 '20

How do you even write this? Is this compiled from some language that is more readable?

→ More replies (2)
→ More replies (5)

6

u/mserrano Dec 16 '20

35/15, Python2 with some Z3: https://gist.github.com/mserrano/70bb9ba725217849600bfe7637c22480

The greedy algorithm would also have worked on my input, but I knew Z3 would produce the solution, and it would have taken me more time to think of (and potentially debug) real code than to just write down the constraints and have Z3 solve them.

This was one of the better problems so far this year, IMO!

→ More replies (4)

6

u/0rac1e Dec 16 '20 edited Dec 17 '20

Raku

Logic-wise, I don't think I'm doing anything too interesting (besides maybe doing a few things inefficiently), but it's the way Raku allows me to express it that's interesting.

The rules are described as ranges (eg. seat: 13-40 or 45-50). I convert the ranges to Raku Range objects inside an "any" Junction, then I can simply smartmatch against it. For example: -

my $rule = any(13..40, 45..50);
put 38 ~~ $rule;  # True
put 42 ~~ $rule;  # False
put 46 ~~ $rule;  # True

Another nice little Raku gem is when checking valid tickets, I created a state variable inside my loop, which I incremented, and then used a LAST phaser to print the value before it exits the loop.

my @valid = @tickets.skip.map: -> @ticket {
    state $err = 0;
    LAST { put $err }
    if @ticket.grep(* ~~ none %rules.values) -> @errs {
        $err += @errs.sum and next
    }
    @ticket
}

Raku variables are lexically scoped to the block, so $err only exists inside the loop. I could have just declared it before the loop, and printed it after the loop at the same LOC cost, but I like state vars in Raku (and Perl) as I like to keep the scope of my variables as small as possible.

All tickets (including mine) are in @tickets. It says to ignore your ticket during this check - which is why I skip the first one (mine) - but since my ticket must be valid, there's no real need to skip it (apart from saving a few clock-cycles).

2

u/MasterMedo Dec 16 '20 edited Dec 16 '20

Really cool puzzle today, definitely made up for yesterday's :)

I thought I was going to have to do a recursive search, but what I noticed after removing false rules from columns was that a particular column could only have a single rule. So I tried removing that rule from other columns. Then I had another column with only one possible rule. Rinse and repeat until you're done. Not sure if this would work on all inputs. python

2

u/daggerdragon Dec 16 '20

Please follow the posting guidelines and edit your post to add what language(s) you used. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.

→ More replies (2)

5

u/2lines1bug Dec 16 '20

Kotlin, 196/233

First time ever in the top 1000. Absolutely mindblowingly ugly code, but apparently this is what you need to achieve good times (unless you are, you know, actually talented).

5

u/sggts04 Dec 16 '20

Python Part-1 Rank 679

Created a dictionary with each valid number from any field marked as true, then for each ticket field check if that number is in the dictionary.

Python Part-2 Rank 906

For each field, iterated through every field index for every ticket and formed a list with all the possible indexes for that field. After this, checked which field has only 1 possible index, assigned that index to that field, removed that index from possible indexes list of other fields, and then repeated this, slowly possible index list for every field got reduced to 1 index and the exact field-index relation was formed.

PS: There's probably a wayyyy more efficient and clean way to solve part 2, but I definitely enjoyed my logic.

→ More replies (2)

5

u/Archek Dec 16 '20

Prolog

First day I skip Golang and immediately started writing Prolog. Feels like it fit the problem very very well. I'm especially proud of part1:

join_domains(Domains, AllowedDomain) :-
    foldl([X,Y,Z]>>(
        Z = Y\/X
    ), Domains, -1, AllowedDomain).

part1(Fields, Tickets, Ans) :-
    maplist([[_,D],X]>>(X=D), Fields, Domains),
    join_domains(Domains, AllowedDomain),
    maplist({AllowedDomain}/[List, Sum]>>(
        exclude([X]>>(X in AllowedDomain), List, Inv),
        sum(Inv, #=, Sum)
    ), Tickets, Invalid),
    sum(Invalid, #=, Ans).
→ More replies (1)

5

u/blazemas Dec 16 '20

C#

One of the few I felt good with how I handled part 1 in prep for part 2. OOP, verbose but relatively clean. I avoided regex up until today just for fun to see how long I could go. Also the 2nd day in a row I could finish one before the kids woke up. I failed to do that for days 10-14.

https://github.com/jbush7401/AdventOfCode/blob/master/AdventOfCode/2020/Day16.cs

→ More replies (3)

5

u/ai_prof Dec 16 '20 edited Dec 16 '20

Python 3

I saw one rule with only one possibility, and another with two, so I hoped that I could just keep removing singletons, and it worked (even though really hard in general):

valid_tickets = [t for t in tickets if isvalidticket(t)]
possrules = [getvalidruleids(list(i)) for i in zip(*valid_tickets)] # possible rules for the data for each of the 20 fields

ruleids = [-1] * 20 # ruleids[i] is the chosen rule for data in field i, or -1 if not yet chosen
while -1 in ruleids:
    for i in range(20):
        r = possrules[i]
        if len(r) == 1:
            ruleids[i] = r[0] # fix this rulecode
            possrules = [[x for x in possrules[i] if x != r[0]] for i in range(20)] # remove ruleids[i] from elsewhere

depvals = [myticket[i] for i in range(20) if ruleids[i] < 6]
from math import prod
print("Product of departure values:", prod(depvals))

5

u/nutki2 Dec 16 '20 edited Dec 16 '20

Perl golf for both parts. About 240 characters. The code assumes the "departure" fields are the first six and that the two validity ranges are not overlapping.

#!perl -lp0
@V=/\d+-.*/g;@T=/\d+,.*/g;@M=$T[0]=~/\d+/g;$m=0 x s!!$t=$&;($z=join'',map{1&grep
$t<$_+$|--,//g}@V)=~1or$c+=$t;$z!ge,/$m/||(@R=($r=$r&$_||$_)=~//g)for@T;$_=$R[
++$i%@R]&~$m,s/\01/$&/g-1||($.*="@-">5||$M[$i%@R],$m|=$_)while$m=~0;$_="$c $."

https://github.com/nutki/adventofcode

→ More replies (1)

5

u/voidhawk42 Dec 16 '20 edited Dec 16 '20

Dyalog APL, finally got my solution to something I kind of like!

p←(⊢⊆⍨0≠≢¨)⊃⎕nget'in\16.txt'1 ⋄ ds←{⍎¨⍵(∊⊆⊣)⎕D}
rs←{1+@2 4⊢ds⍵}¨⊃p ⋄ yt ot←{↑ds¨1↓⍵⊃p}¨2 3
ir←2|⍸⍨ ⋄ +/,ot×~e←∨/ot∘.ir rs ⍝ part 1
m←∧⌿rs∘.ir⍨yt⍪ot⌿⍨∧/e
×/6↑(,yt)⌷⍨⊂⍋(⊂⍋n)⌷∊~⍨\⍸¨↓m[n←⍋+/m;] ⍝ part 2

9

u/jonathan_paulson Dec 16 '20 edited Dec 16 '20

Placed 16/5 (best day yet!). Python. Code: https://github.com/jonathanpaulson/AdventOfCode/blob/master/2020/16.py. Video of me solving: https://youtu.be/OhqvfoaBljY.

I liked part2. No advanced algorithms or math, but still requires some problem-solving to extract the ticket_index::field_name mapping from the given information.

I think there was a problem last year with a similar extraction step at the end. Anyone remember what it was?

→ More replies (8)

4

u/silxikys Dec 16 '20

C++, 236/275, part1 part2

For C++ I find it's sometimes faster to clean the input in Vim and then reading in data goes a lot smoother.

I didn't know that at each step, there would be one position with exactly one possibility. I wrote the code up to this point, and then manually inspected the possibilities to determine that this was the case. So that was lucky!

→ More replies (1)

4

u/CodeIsTheEnd Dec 16 '20

Ruby: 9:13/23:45, 300/153

Here's a recording of me solving it, and the code is here. (I'm streaming myself solving the problems right when they come out on Twitch!)

This one was great! Super fun. My favorite yet. Thankfully Eric made Part 2 "easy", but it still would have been fun even if we had to "search" for a solution. I don't mind getting to bed a little earlier though!

4

u/Loonis Dec 16 '20

Perl

This one was fun! The code could probably be shorter, but I'm happy enough with how it turned out. I really wasn't sure how to handle the rule validations, but went with the "just start typing" strategy.

Solution after some significant cleanup:

I also found an excuse to use the chained comparisons added in 5.32, even if this line probably has too many arrows:

next COLUMN unless $rule->[0]{min} <= $t->[$col] <= $rule->[0]{max} || $rule->[1]{min} <= $t->[$col] <= $rule->[1]{max};

FAQ: The ->@* is a postfix dereference - available in 5.24+

→ More replies (3)

4

u/[deleted] Dec 16 '20 edited Dec 16 '20

Scala Solution

Gnarly recursive solution. It runs Fast Enough (<100ms).

→ More replies (3)

4

u/MannerShark Dec 16 '20

Python

I considered using ranges and sets today. They both have quick 'in' checks. Ended up with sets though, as range objects don't support set operations as far as I know.

As you may already know, part 2 is the interesting one. I immediately thought of bipartite matching, as it's something I've used in real applications plenty of times.
I used NetworkX for the bipartite matching, as implementing the algorithm would take quite a bit of time (I did that a month or so ago when I needed a custom version that would also indicate edges that will never get used).

matches = []
for name, values in fields:
    for i, column in enumerate(column_values):
        if column.issubset(values):
            matches.append((name, i))

g = nx.DiGraph()
top_nodes = [name for name, _ in fields]
for name, i in matches:
  g.add_edge(name, i)

matching = maximum_matching(g, top_nodes)

4

u/sebastiannielsen Dec 16 '20

Perl: https://pastebin.com/zQsezuxr

Part2 is like sudoku, multiple fieldnames are valid for the same field, but in such a way that you need to "spend" the fields to get only one "solution" in the end.

→ More replies (2)

4

u/Smylers Dec 16 '20

Perl, which is nice and short for part 1, with pairmap being today's new List::AllUtils function. Note that for parsing both the field spec and the nearby tickets, line-breaks are irrelevant: just grab all the integers found anywhere in the ‘paragraph’ and iterate over them:

use v5.14; use warnings; use List::AllUtils qw<pairmap sum none>;
local $/ = '';
my ($spec, undef, $nearby) = <>;
my @range = pairmap { {min => $a, max => $b} } $spec =~ /\d+/g;
say sum grep { my $n = $_; none { $_->{min} <= $n && $n <= $_->{max} } @range } $nearby =~ /\d+/g;

Here's a sample of my part 2 solution:

            }
          }
        }
      }
    }
  }
}

Do you think it's possible I've over-nested things here? Though the full code still seems shorter than many other Perl solutions on here, with just 1 line at most of those nesting levels. I'll take a look at others' algorithms and see if I've over-complicated things.

Those nesting levels in full:

  1. Looping over each nearby ticket.

  2. Looping over each value in a ticket.

  3. Looping over each field definition (from the top section).

  4. If none of the field's ranges include the value then:

  5. If that was previously a possible position for this field, and having removed it there's only one possible position left, then:

  6. Add it to the ‘done’ list and loop until there's nothing left in that list.

  7. Loop over all of the other fields (except for the ‘done’ one), and remove the ‘done’ position as a possible position for that field. If that in turn leaves a field with only one possible position, add it to the ‘done’ list.

Obviously that's a lot of looping, but it finds the answer in about ¼ s, so it doesn't seem like Too Much Looping.

4

u/hrunt Dec 16 '20

Python 3

Nothing special here, just a very procedural, iterative approach to the problem. You know how when it's crunch time and you're pushing out a project and you say, "Well, it works." That's me today, coding before heading off to work.

code

4

u/[deleted] Dec 16 '20

C#: https://gist.github.com/grnde/fcdc5b9221c1156274846a11147a08c4

Was getting always the wrong value for part 2. It took a while until I noticed the overflow and changed the data type from int to long. But i'm pretty proud of my solution. Maybe it's not the shortest or fastet, but i'd like to share it.

→ More replies (1)

4

u/rabuf Dec 16 '20

Common Lisp

It works, not proud of it. I made a stupid mistake last night, butchered my code, went to bed. Figured it out this morning, didn't unbutcher it but it does get the correct answer.

4

u/sky_badger Dec 16 '20

Python3. Happy to complete today's. Naturally I assumed that each set of ticket values would only fit one 'rule' so the elimination code was a late addition! [paste]

→ More replies (2)

4

u/IlliterateJedi Dec 16 '20 edited Dec 16 '20

Python 3.9 solution -> 650ms for both, 647ms for part B - both parts read in the file separately

Advent of Code day 1: I'm going to try to make clean code and smart algorithms so I can learn to be a better coder

Advent of Code day 16:With enough hacking at my script, I can get the answer, and when in doubt, throw in some more loops and if-statements just to be safe

4

u/prutsw3rk Dec 16 '20 edited Dec 16 '20

My Python3 solution

For part1 put all valid numbers in a set:

for rule in [list(map(int, r)) for r in rules]:
    fldcond.append(rule)
    for j in [0, 2]:
        for i in range(rule[j], rule[j+1]+1):
            ok.add(i)

Then sum up the wrong numbers:

for tl in alltickets[1:]:
    ticket = [int(x) for x in tl.split(',')]
    wrongsum = sum([i for i in ticket if i not in ok])
    if wrongsum > 0:
        cnt += wrongsum

For part2, first create an 2d array with all possibilities, then remove columns that are out of bounds:

possible = [set(i for i in range(N) for _ in range(N))]
for col, fld in enumerate(ticket):
   for r, poss in zip(fldcond, possible):
       if fld < r[0] or (fld > r[1] and fld < r[2]) or fld > r[3]:
           poss.discard(col)

Finally go through possibilities sets in order of set size and create field mapping:

prev = set()
for field_set in sorted(possible, key=lambda i: len(i)):
    field_row = possible.index(field_set)
    field_map[field_row] = list(field_set - prev)[0]
    prev = field_set

4

u/ric2b Dec 16 '20 edited Dec 16 '20

Haskell

For some reason I assumed only one rule would be valid for each column (it worked for the example) and had to rewrite my algorithm when I noticed that wasn't the case. Took me a while to re-organize my head :/

But it was still an interesting problem!

paste

4

u/jitwit Dec 16 '20 edited Dec 17 '20

J Programming Language

n =: 1 + +/ ','={:];._2 in =: aoc 2020 16
'R T S' =: (<;._2~ (2#LF)&E.) in,LF
vals =: {{ ". ' ' (I. -. y e. a09)} y }}
T =: {: vals;._2 T,LF
R =: _2 (_1 0&+)\ vals R NB. omg this is why!
S =: _2 +./\ R ([:+./1=I.)"1 0/ V =: (-n) ]\ vals S

+/ (,V) #~ -. , +./ S NB. part A

NB. find rows with only 1 option, and clear that option from the
NB. others, simpleton's vertex cover
G =: *./"2 (+./ *./"1 S) #"2 S NB. constraints
A =: {{1(<"1 r,"0 c)}0(<a:;c=.I.(r=.I.1=+/"1 y){y)}y}}

*/ (6{. ,I. A^:_ G) { T NB. part B

Late to the party as I ended up giving up last night after I kept getting an invalid constraint graph from an off by one error... The problem was 1 = I. for checking intervals was cutting off lower number... Anyhow

Idea is R are rules, T our ticket, V the values of the other tickets, and S is a 3d table (or brick or report in J vernacular) where columns are fields, rows are tickets, and matrices/tables are rules. We find the constraint graph G by and-reducing over the tickets, after throwing out tickets with invalid fields (found by and-reducing over the rules then or-reducing for each ticket).

A then is used to pick a constraint with only 1 option for possible rules and eliminate that option from the others. This happens to work for this problem, with no need for branching/guessing.

→ More replies (2)

4

u/HAEC_EST_SPARTA Dec 16 '20

Common Lisp

Solution on GitHub

Started this afternoon instead of last night again after looking at the input and thinking that parsing would be painful. That part turned out not to be too onerous, but I was fooled by the same issue as most people here (0 can be a field value!) that cost me a good deal of time. After figuring that out, some optimisations were able to get my Part 2 runtime down to 5 ms, which I'm going to consider good enough.

→ More replies (1)

4

u/symbolicprocessor Dec 17 '20

Common Lisp solution.

Parsing: pretty straightforward.

Part 1: neat, tidy, and direct.

Part 2: a hideous tangle of pasted-together REPL code.

→ More replies (1)

4

u/gfvirga Dec 17 '20

Python

I think this one was one of my favorites!

Coming up with (without searching) the following line made me feel good about myself LOL

if all(any(num[idx] in sublist for sublist in ranges) for num in valid_tickets):

I am learning so much! Feel like even more than my CS classes \o/

GitHub

4

u/oantolin Dec 17 '20

Perl solution. For part 2 I wrote a backtracking search to match field indices with field names. I used the standard heuristic of assigning the field with fewest possibilities first. It turns out that with my input, at each step there is always a field that has only one option left! So no backtracking was really necessary, but I couldn't have known that beforehand.

1

u/fmynarski Dec 16 '20 edited Dec 17 '20

Python - 612/10546. Not my best performance ngl :D But i feel my solution is quite clean paste

1

u/daggerdragon Dec 16 '20

Please follow the posting guidelines and edit your post to add what language(s) you used. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.

1

u/warbaque Dec 16 '20

Python

(40 lines of mostly readable code)

def day16(input):
    ticket_data = input.strip().split('\n\n')

    r = re.compile(r'(\d+)-(\d+)')
    def parse_rule(rule):
        field, ranges = rule.split(': ')
        return field, [tuple(map(int, m)) for m in r.findall(ranges)]

    rules = dict(parse_rule(rule) for rule in ticket_data[0].split('\n'))
    our_ticket = list(map(int, ticket_data[1].split('your ticket:\n')[1].split(',')))
    other_tickets = [list(map(int, t.split(','))) for t in ticket_data[2].split('nearby tickets:\n')[1].split()]

    @lru_cache
    def valid_fields(value):
        return {
            field for field, ranges in rules.items()
            if any(mi <= value <= ma for mi, ma in ranges)
        }

    def part1():
        return sum([v for values in other_tickets for v in values if not valid_fields(v)])

    def part2():
        options = [[valid_fields(v) for v in values] for values in other_tickets]

        possible = {
            i: set.intersection(*(fields[i] for fields in options if all(fields)))
            for i in range(len(rules))
        }

        solved_fields = {}
        for i in sorted(possible, key=lambda i: len(possible[i])):
            solved_fields[i] = min(possible[i] - set(solved_fields.values()))

        departure_values = [our_ticket[k] for k, v in solved_fields.items() if v.startswith('departure')]
        return numpy.prod(departure_values)

    print(part1())
    print(part2())

1

u/daggerdragon Dec 16 '20

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.

3

u/hugh_tc Dec 16 '20 edited Dec 16 '20

Python 3, 501/53.

Quite the climb! I'm pretty proud of that pseudo-state-based-parser thing... .split("\n\n") probably would have been more pythonic but it's what you get when you gotta go fast! paste

edit: the cleaned-up version. Much nicer than my original solution, with the exception of the awful, awful input parsing lambda.

→ More replies (1)

3

u/sophiebits Dec 16 '20

13/421, Python. https://github.com/sophiebits/adventofcode/blob/main/2020/day16.py

Not sure what got into me today. I first tried a recursive backtracking solution but that seemed too slow (possible I did it wrong). Then I thought maybe there would be individual tickets evidencing a particular assignment (eg: this ticket says 17 in the first spot; there's only one label that applies to) and coded that up, but that was also wrong.

Turns out this greedy-esque approach is all that was needed for the inputs we got. Was kinda tempted to use Z3 but didn't – I probably should have.

→ More replies (10)

3

u/seligman99 Dec 16 '20

Python, 124 / 226

One of these days I'll get used to implementing weird rules quickly. Today is not that day.

github

3

u/UItraDonut Dec 16 '20

Java 1777/948
First time top 1000!
Code
Probably most awful Java code you will see for this day x)

3

u/_O-o-f Dec 16 '20

Python 3

link Today's instructions were a bit jank, but it could just be attributed to me not reading clearly enough.

For part 1, you just make sure to check ALL constraints, and not just the one at the current index.

For Part 2, I was (slightly) lucky as I've done a problem very similar to this: a Sudoku solver(hush, it's a bit basic but meh). I just eliminated the fields which were not available, and if an elimination was made I could loop over again. If there were none, I'd check for all of the ones with 1 solution and eliminate that from the rest.

3

u/EAJakobsen Dec 16 '20

Python 3.

Nothing too fancy. For part 2 I made a dictionary with each index in a ticket as keys, and the fields this index could possibly represent as values. I initialized every key to map to every field, and then went through each ticket and removed a field from index i every time I found a value that didn't fit the rules of that field at index i.

Finally, go through the indices by how many fields they can possibly represent, starting with the index that only fits one field, and remove this field from all other indices. This yields a one-to-one mapping between indices and ticket fields.

3

u/pxOMR Dec 16 '20

JavaScript 452/1504

It took me too long to realize that I had to use the filtered tickets while looking for the correct indexes...

→ More replies (1)

3

u/Dioxy Dec 16 '20

TypeScript

https://kufii.github.io/advent-of-code-2020/#/16 (click Show Code)

1531/776. a lot of my code is just parsing the input file. I think it's a pretty clean solution overall

3

u/A-UNDERSCORE-D Dec 16 '20

Go / Golang

This was really fun, I liked this one. It challenged me on an area Im not super good at, and Im really happy with the solution I came up with and speed thereof: https://github.com/A-UNDERSCORE-D/aoc2020/blob/main/2020/16/solution.go

completes in under a ms for each part: Rules parsed. Took: 16.581µs, Part 1: 32835 Took: 284.094µs, Part 2: 514662805187 Took: 299.163µs

3

u/spookywooky_FE Dec 16 '20

Todays puzzle asks for implementation skills, so much indexes, so much indirections...

In the end it is hard to implement this kind of problems in simple to read code, I tried in c++

→ More replies (1)

3

u/omginbd Dec 16 '20

Elixir


I was ashamed of my code and wasn't going to post until I saw that it looks like everyone is ashamed of their code so I figured what the hell.

code

→ More replies (2)

3

u/mebeim Dec 16 '20 edited Dec 16 '20

EDIT: clean solution - walkthrough

1308/482 - Python 3 solution (hacked together with punches and glue)

No walkthrough nor clean solution for now, will probably add it later in the day. Sorry, but I've got to get some sleep today. Not a difficult problem anyway, just really boring if you ask me.

Quick part 2 explanation of my solution: build a set of valid "possible" indexes starting with all indexes for all fields, then proceed to check every field of every ticket: if that field was wrong, remove the index of the field from the set of valid indexes associated with that field. In the end you're left with a dictionary of sets, of which at least one must have only 1 index. From there, start looking for the only set which has one index only, then take that index as valid for that field and remove it from all the other sets. Do this until all sets have length 1 and you found the indexes.

3

u/SuperSmurfen Dec 16 '20 edited Dec 16 '20

Rust

Link to solution (566/1977)

Very happy with part 1 but had a frustrating error on part two! Definitely one of the most "implementation heavy" so far. Took me an hour and still got top 2k.

A single misplaced i instead of a j meant the simple solution for part two did not work.. Started trying to implement a recursive backtrack approach to find a valid assignment of rules. When that did not work either I realized something else must be wrong. Those types of errors are always annoying and it cost me so much time.

For part two, I first collect which rules are possible for which indexes. I then try to find an index with only one possible rule assignment. We then know that has to be the correct assignment! By then removing that rule as a possibility for all others, we eventually get a unique solution. This just happens to be the case with our input, that it has a unique solution.

Somewhat fast solution, about 260μs on my machine.

3

u/mendelmunkis Dec 16 '20 edited Dec 16 '20

C

https://github.com/mendelmunkis/AoC/blob/master/2020/ticket.c

Uses a set of nested loops to collapse the possibility space

EDIT: Switched to a column based collapsing method to save some time.

3

u/ChrisVittal Dec 16 '20

Python

Somewhat cleaned up. Pretty neat problem. Didn't think of z3 nor am I familiar enough with the api to use it quickly. But interestingly, sorting by the size of our candidate sets and then updating and sorting again meant that the top of the queue was always only one element, so it worked!

3

u/[deleted] Dec 16 '20

Pure C18. For each position, keep a bitset of the possible keys that could be at that spot. For each sample, turn off the bits that are impossible.

After that, run a "fixpoint" algorithm: For all bitsets that only have 1 bit remaining, go through all the other bitsets and turn off that specific position. Keep doing this until nothing changes anymore. At this point, every bitset has exactly 1 bit identifying which key belongs at that position.

I went with bitsets since doing a hashtable was annoying and unidiomatic C, but I felt like I would have been at least 33% faster if I had just stored a string in a hashtable or something instead of bit fiddling. I was bitten by __builtin_ffs returning 1-indexed results >.>.

https://git.sr.ht/~williewillus/aoc_2020/tree/master/src/day16.c

3

u/Colts_Fan10 Dec 16 '20

Python 3

For each position on the ticket, we maintain a set of valid fields, which we cut down as we read tickets.

Then, we use the process of elimination: if any position has only one item in its set, that position has to be that field and we remove that field from all other sets—repeat this process until we get to a final ordering.

→ More replies (7)

3

u/nospamas Dec 16 '20

F# Not as short as it could be I expect. But also not too bad. Note that if you're hitting errors in part 2 and you think you've done it all right then watch out for the answer being greater than int32 max.

Solution

3

u/DemiKoss Dec 16 '20

Rust

7.96ms, it's a real ugly solution that I'll probably groom tomorrow :P

Decided to stay up tonight and try my luck! P1 was just a matter of iterating over the tickets and checking against each rule set's range bounds. P2 transposed this to look at indicies across tickets against the rule sets; sorting by the number of rule sets each index can meet & eliminating them one-by-one.

3

u/Wunkolo Dec 16 '20

C++

Didn't have much fun with this one tbh. It was faster to do the gaussian elimination by hand than to implement the algorithm for it.

Maybe later I'll come back to this to optimize it with bit-mask set-arithmetic and such like some of the other more fun ones.

3

u/GamerWoona Dec 16 '20

C++

Truncated my ranges for part 1, ended up with just 2.

Part two involved me a vector of all possible indexes, slowly reducing it until only one spot is left, then reducing the others.

Runtime is not the best:

Part one calculated36892 microseconds , so 37 ms
Part two calculated in:199435 microseconds , so 200 ms

source: https://github.com/neiomi1/AdventofCode2020/tree/master/Day_16

3

u/Diderikdm Dec 16 '20 edited Dec 16 '20

Python:

with open("C:\Advent\day16.txt", "r") as file:
    data = file.read()
    my_ticket = [int(x) for x in data.split('your ticket:')[1].split('nearby tickets:')[0].strip('\n').split(',')]
    nearby_tickets = [[int(x) for x in y.split(',')] for y in data.split('nearby tickets:')[1].strip('\n').split('\n')]
    raw_rules = {x.split(':')[0] : x for x in data.split('your ticket:')[0].strip('\n').split('\n')}
    rules = {y.split(':')[0] : (lambda x, val : int(x.split(': ')[1].split(' or ')[0].split('-')[0]) <= val <= int(x.split(': ')[1].split(' or ')[0].split('-')[1])   \
                                             or int(x.split(': ')[1].split(' or ')[1].split('-')[0]) <= val <= int(x.split(': ')[1].split(' or ')[1].split('-')[1]))  \
             for y in data.split('your ticket:')[0].strip('\n').split('\n')}  
    invalids = [[x for x in row if not any([rules[rule](raw_rules[rule],x) for rule in rules.keys()])] for row in nearby_tickets]
    print('Part 1: {}'.format(sum([sum([x for x in y]) for y in invalids])))
    valids = [nearby_tickets[i] for i in range(len(nearby_tickets)) if not invalids[i]]
    combinations = {rule:[i for i in range(len(valids[0])) if all([rules[rule](raw_rules[rule],row[i]) for row in valids])] for rule in rules.keys()}
    indexes, final_combinations = [], {}
    for x,y in sorted(combinations.items(), key=lambda item: len(item[1])):
        for z in y:
            if z in indexes:
                continue
            else:
                indexes.append(z)
                final_combinations[x] = z
                break
    print('Part 2: {}'.format(reduce(lambda x,y: x*y, [my_ticket[final_combinations[z]] for z in final_combinations.keys() if z.startswith('departure')])))
→ More replies (1)

3

u/woutervdb Dec 16 '20

PHP.

I think I took the wrong approach parsing the input. I discovered halfway through part 2 that I was also parsing the "your ticket" and "nearby ticket" lines as tickets...

My solution for part 2 is a mess and I have no idea why it works, but seeing as the input is small enough this quadratic solution is good enough.

3

u/azzal07 Dec 16 '20

Awk; my solution for today felt so dirty with all those loops, might revisit it later... (paste)

/yo/,/,/{FS=",";for(t=split($0,T);o++<N;)for(k in K)O[k,o]=1}/b/,0{for(i=e=0;
$++i;)e+=$i*!($i in R);E+=e}!t{K[$1];for(j=0;j++<4;)for(i=$++j;i<=$(1+j);i++)
F[$1,i]=1R[i];N++}!e{for(;$++e;)for(k in K)F[k,$e]||O[k,e]=0}END{for(D=p=1;p;
){p=0;for(k in K){for(n=i=0;i++<N;)n+=O[k,i]&&p=i;if(n==1){P[k]=p;for(k in K)
O[k,p]=0}}}for(k in P)k~/part?/&&D*=T[P[k]];print E"\n"D}BEGIN{FS=":| or |-"}

3

u/SymmetryManagement Dec 16 '20 edited Dec 17 '20

Java

https://github.com/linl33/adventofcode/blob/year2020/year2020/src/main/java/dev/linl33/adventofcode/year2020/Day16.java

The Predicate interface is perfect for today's puzzle. Simple brute force and return when all 6 departures are found.

Part 1 550us. Part 2 800us.

Edit

Improved the parsing a bit. Part 1 now takes 340us, part 2 now takes 630us. Parsing the input and removing the invalid tickets still take up about 50% of the runtime for part 2.

3

u/emu_fake Dec 16 '20

C#

Part 1: 2ms

Part 2: 25ms

Guess I've could make it a bit faster by reducing the linq expressions. But the algorithm itself should be pretty efficient.

3

u/compdog Dec 16 '20

JavaScript (Node.JS)


Reasonably efficient solution to parts 1 and 2. This was the first time where I couldn't parse the input without using intermediate variables, which was interesting. My final parsing code could be cleaner, but it works and is simple enough that my IDE is able to infer the type of the parsed input object.

Part 1 was simple, but I had already guessed what part 2 would be so I took a bit longer to make sure that the same logic could be used to both filter the tickets and count the values. But after I had that working, I still ended up throwing out that original code in favor of a cleaner solution.

I don't know how efficient my part 2 solution is compared to an ideal one, but its clean and very easy to read. The basic algorithm is to keep a list of fields and indexes that have not been mapped, and then repeatedly search for indexes that match exactly one field. Mapped fields and indexes are excluded from later iterations, so each round reduces the remaining search space for the rest.

3

u/Beardanha Dec 16 '20

My Python3 solution.

Nice one again!

3

u/VileVerminVanquisher Dec 16 '20

Python

Nothing fancy. It felt like this required a bit less thinking than the previous days, demanding implementation precision instead and that suited me nicely

3

u/[deleted] Dec 16 '20

Python3 1831/342

Sad that my code is really messy for today

3

u/Krillegeddon Dec 16 '20

C#

I solved it just like I have solved sodukus before. I made rows out of tickets and columns out of fields. Than ran some elimination and find algorithms. Without any optimization, it completed in about 200 ms.

public class SudokuSquare
{
   public int Value { get; set; }
   public int FieldID { get; set; }
   public List<int> PossibleFieldIds { get; set; }
}

There were only four algorithms needed in order to solve it. When I wrote it, I thought I'd need to loop them many times, but one go was actually enough!

EliminateByValueRanges(): Eliminate field Ids that are outside of bounds based on Value (duh).

EliminateColumn(): If a field is not valid for one ticket's particular column, no other ticket can have this field on that column either.

FindSingle(): On a row (ticket), if one column has only one possible field ID, then mark the FieldID with that single possible value.

FindOnlyColumnInRow(): If one column is the only one in a row that has one particular fieldID as possible - then this column must have this field ID.

My code is not very interesting and worth sharing, it's just a bunch of for-loops and if-statments. :-)

Really nice puzzle today! Had my brain going on high for some time!

Will be interesting to see how others approached this problem...

3

u/zid Dec 16 '20

C

After a heavy rewrite it is somewhat readable.

The 'solve a sudoku logic' wasn't hard to code in theory, but in practice not getting my rows and columns and rules and tickets etc all confused was a strain at 5am.

3

u/[deleted] Dec 16 '20

Learning C

Three different parsing regimes means some ugly code, but otherwise happy that I found a way to implement intersecting bitmask sets to get the whole thing running in 1ms with only a single pass though the data, not having to store tickets in memory.

Code here

→ More replies (2)

3

u/WayOfTheGeophysicist Dec 16 '20

Python

I usually say "if you iterate of numpy you're probably doing it wrong", yet here we are. Full solution and here's the sieve for the part 2 search:

max_counter = counter == np.max(counter, axis=1)
# Create a prototype all true mask to copy
mask_prototype = np.ones_like(max_counter).astype(bool)
while any(np.sum(max_counter, axis=1) != 1):
    row = max_counter[i, :]
    # All true mask
    mask = mask_prototype.copy()
    # If this row has a single Maximum value
    if sum(row) == 1:
        # Set the mask column of the single maximum value to false
        mask = mask * ~row
        # Except for that one value of our row
        mask[i, :] += row
        # mask the max_counter
        max_counter *= mask
    # Wrap around the counter
    i = (i + 1) % max_counter.shape[0]
→ More replies (1)

3

u/codertee Dec 16 '20

Python 3: github

Bit more difficult to write readable solution today

→ More replies (2)

3

u/SomeCynicalBastard Dec 16 '20

Python

This should have been a matter of parsing the input and not much more difficult than that. But I got myself stuck with this:

for ticket in nearbytickets:
    for num in ticket:
        if num not in all_fields:
            nearbytickets.remove(ticket)

Turns out that python won't complain about you changing the list you're iterating over, but it will skip the next item. Some invalid tickets were consecutive…

Full script.

→ More replies (1)

3

u/wzkx Dec 16 '20

Python 🐍 Like a real program, like we're really doing something :) ≈73/84 LOC

source code @ paste

3

u/ywgdana Dec 16 '20

C# repo!

I enjoyed this one -- a good, blue-collar coding task, as it were! I was a little surprised that process of elimination got us to a single unique arrangement of the columns. I was anticipating having to eliminate a bunch of possibilities and then have to test the remaining combinations.

Right now on github is the first draft of my code that spat out the correct answer. I think it's way more verbose than it needs to be so I'll likely go and tidy it up at some point.

3

u/i_have_no_biscuits Dec 16 '20 edited Dec 16 '20

GWBASIC - Part 1

10 OPEN "I",1,"data16.txt": DIM OK(1000)
20 LINE INPUT#1,S$: E=INSTR(S$,": "): IF E<1 THEN 60
30 X=VAL(MID$(S$,E+2,2)): Y=VAL(MID$(S$,E+5,3)): GOSUB 50
40 X=VAL(MID$(S$,E+12,3)): Y=VAL(MID$(S$,E+16,3)): GOSUB 50: GOTO 20
50 FOR I=X TO Y: OK(I)=-1: NEXT I: RETURN
60 FOR I=1 TO 4: LINE INPUT#1,S$: NEXT I
70 WHILE NOT EOF(1): E=0: LINE INPUT#1,S$: S$=S$+","
80 F=INSTR(E+1,S$,","): IF F THEN GOSUB 100: E=F: GOTO 80
90 WEND: PRINT "Part 1:",T: END
100 N=VAL(MID$(S$,E+1,F-E)): IF OK(N) THEN RETURN ELSE T=T+N: RETURN

Only part 1 for the moment. Part 2 should be doable but will require some tokenisation and will not be particularly fast! This works by creating an array OK which is 0 (false) when it's not in a valid range and -1 (true) when it is in a valid range. Most of the program is taken up with parsing the input.

(Edit: removed a couple of small errors that crept their way in)

3

u/Judheg Dec 16 '20 edited Dec 16 '20

Scala

AoC problems appear at 6 a.m my time zone, I usually tried to solve in the morning by hooks or by crooks with lots of debugs and then refactor later after work :D

Evening cleaned up version:
https://paste2.org/JNxC8H74

Morning write only sleepy version:
https://paste2.org/pbU1p2kf

I did a lot of debugging in the morning and noticed that candidate field names are kind of neat and can be sorted per column.

3

u/aurele Dec 16 '20

Around 500µs in Rust.

3

u/Henkatoni Dec 16 '20 edited Dec 18 '20

Csharp

It might not be the prettiest, but it's rather compact and quite fast (A ~30ms and B ~70ms, both including the parsing). Oh, and I'm sorry about the parser. Just couldn't be arsed...

Code here

→ More replies (4)

3

u/PhysicsAndAlcohol Dec 16 '20

Haskell, runs in 20 ms.

I used Text.ParserCombinators.ReadP for parsing and I tried optimizing certain parts by sorting ranges and numbers.

Part 2 is one big recursive clusterf*ck, I seriously think I just forgot how to program.

→ More replies (1)

3

u/vrtxt Dec 16 '20 edited Dec 26 '20

c# solution. Part2 was bit tricky with some implicit assumptions to uncover and no test cases provided but happy how it turned out.

3

u/AndrewHutcheson Dec 16 '20

Python 3 https://github.com/AndrewHutcheson/AdventOfCode2020-Python/blob/main/Day16/processor.py

Once again I misinterpreted the instructions but eventually I got it. First time posting a solution, it's not short but I like how it has steps that reflect my thought process.

3

u/LinAGKar Dec 16 '20 edited Dec 16 '20

Mine in Rust:

Part 2 ended up being a bit of a mess, and I can't be bothered to clean it up, but at least it performs decently. It only compares each field against each rule once, and save which rules matches each field, and it doesn't bother matching everything, it stops once it's matched the "departure" rules.

Anyway, part 2 was basically about writing a sat solver, which I don't see anyone mention by name here.

→ More replies (1)

3

u/clumsveed Dec 16 '20 edited Dec 17 '20

Java Solution

​ all solutions so far: repl.it

This is a solution. Is it pretty? No. Does it work? Yes.

As always, this is straightforward and limited to APCSA curriculum. It is currently a little messy and I don't have a ton of comments. I'll probably clean some stuff up and comment more when I have some time later or tomorrow, but I wanted to get what I have up here.

** updated **

I refactored some stuff to cut out repeating similar things between part1 and part2 and added a metric ton of comments in case my jibberish doesn't make sense.

→ More replies (5)

3

u/rf314 Dec 16 '20 edited Dec 16 '20

Python 3 - Comprehension Hell Edition

2020 - day 16

Looks like Lisp, if I'm being perfectly honest.

→ More replies (1)

3

u/mandus Dec 16 '20

Another Common Lisp of Day 16

Kind of like part-2 starting out assuming any field match any position, and then elimination of those that doesn't fit when going through data (it's a second pass though since bad tickets are removed first). At the end, another recursive pass successively gets the list of fields uniquely assigned to position.

For the most part I'm sticking to recursion. But for some parts of todays problem it's better to keep things in same order, and when recursing it's so easy to `cons` things together and order is reversed. So, I used some loops as well, where we can collect the right way.

3

u/__Abigail__ Dec 16 '20

Perl

I used the same technique almost everyone else used. Takes about 80ms to run on my box.

Blog post and full program.

3

u/Chris_Hemsworth Dec 16 '20

A little late to the party.

My Python 3 Solution

For Part 2, I used a while loop to check for positions that could only be a single field, and removed those fields from all other candidate fields. This looped until all positional fields were uniquely defined. It worked on this set because we know the solution is non-ambiguous, however an ambiguous set would get caught in the loop forever.

3

u/exploding_cat_wizard Dec 16 '20

C++

As others have said, messy. But I'm too tired to change it now. Code has horrible names and some unnecessary includes, and I didn't remove my timer code.

Used regex to match both input and get the part2 entries. rules for the fields are a hashmap of function objects returning true if the given int is withing the range. tickets are vector<int>. part2 is a horrible jumble of containers, I basically just threw whatever in there, including, terrifyingly, a vector<bool> per field noting which column was allowed for this field. These are then shoved into another hashmap with the respective field names...

Another loop, going through all the fields multiple times, in order to slowly find the sole candidate for each column by checking where there's only one "true" entry in the entire vector<bool>. This most definitely has a worse complexity than O(n), but since /u/LinAGKar mentioned sat solvers, that's to be expected.

part2 runs in 850 microseconds on my laptop, which surprises me given that I didn't optimize at all. Reading the input takes 5ms, but if I wanted fast parsing, I wouldn't use streams and regex, now, would I?

Something more to do with getting a feeling for numbers than with programming: I used Fermi's approximation to see that the int I saved the part2 result in was overflowing before I tried to send in the answer: I got 6 numbers to be multiplied, each between 50 and 200. In a Fermi approximation, these are all equal to the (logarithmically) nearest power of 10 - so 100, or 102 . 6*102 = 1012, but my answer only was an 8-digit int, far too small for the required answer - I obvously needed a long instead.

3

u/mathsaey Dec 16 '20

Elixir

https://github.com/mathsaey/adventofcode/blob/master/lib/2020/16.ex

Not super pretty, but fairly concise: 42 LOC without parsing, 72 with. Lots of nested uses of the Enum module in this one :).

3

u/friedrich_aurelius Dec 16 '20

Elixir

Github link

Part 1: I used MapSets of all possible values for each field, and MapSet.member? to test validity. Maybe not the most efficient way, but it still runs very fast.

Part 2: With ticket indexes 0 to 19, I used a Reduce to check each index and save the results, then another Reduce on my ticket to get the product of the appropriate indexes.

0..(length(my_ticket) - 1)
|> Enum.reduce(%{}, fn x, acc ->
     vals = Enum.reduce(valid_tickets, [], &(&2 ++ [Enum.at(&1, x)]))
     Map.put(acc, x, match_field(rules, vals)) end)

...

get_departure_indexes
|> Enum.reduce(1, fn x, acc -> acc * Enum.at(my_ticket, x) end)

3

u/phil_g Dec 16 '20

My solution in Common Lisp.

Normally, I get up in the morning and work on Advent of Code problems until I have to go to work. Today is the first day this year that I didn't finish both parts before I had to start work.

And it was an annoying mistake. For part two I reused part one's function to get a ticket's error rate. Unfortunately, one ticket had a value of zero, which was not valid, but which looked valid because of my test. Once I fixed that issue, I got my answer.

→ More replies (1)

3

u/lboshuizen Dec 17 '20 edited Dec 17 '20

Haskell

Late to the party, got my 2nd star early but was not happy with solution.

Transpose the nearby, reduce possible fields then find a fit on col-order by subtracting fields that can only be in 1 place till all stable.

runs under 50ms 20ms, good enough.

code

→ More replies (2)

3

u/F0sh Dec 17 '20

My solution in nim is quite compact by doing something I haven't seen in the other solutions I clicked on: in part 2, the matrix of possible field assignments can be inverted, and then the ith named field is assigned to the jth column where j is the index of the unique entry of value 1 in row i of the inverse.

I used a third-party nim library for the first time to do this (manu)

3

u/ponyta_hk Dec 17 '20

Python3

Tricky implementation for part 2.

My Solution
All My Solutions

→ More replies (1)

3

u/bcgroom Dec 17 '20

Elixir

This can probably be cleaner, but I spent most of the day on part 2 operating on a false assumption that gave me an answer but an incorrect one and I'm too tired to refactor. Lesson to be learned: make sure to put assertions into your code, even if it seems like a pain in the ass.

https://github.com/ericgroom/advent2020/blob/master/lib/days/day_16.ex

5

u/mzprx42 Dec 16 '20

Purely functional JavaScript (no variables at all, just function calls)
https://pastebin.com/v85YzsP9

→ More replies (2)

1

u/HesletQuillan Dec 16 '20

Fortran

1ms!

 program AOC16A
    implicit none

    type rule_t
        integer:: low_1, low_2, high_1, high_2
        integer :: position_mask
        integer :: position
        character(24) :: field
    end type rule_t
    type(rule_t) :: rules(20)
    integer :: n_rules, i, j,valid_mask,remaining
    character(100) :: line
    integer, allocatable :: ticket(:), my_ticket(:)
    integer :: valid(0:1000)
    integer(8) :: answer
    
    open (unit=1,file='input.txt', form='formatted', status='old', action='read')
    n_rules = 0
    valid = 0
    valid_mask = 0
    read_rules: do
        read (1,'(A)') line
        if (line == "") exit read_rules
        n_rules = n_rules + 1
        rules(n_rules)%position_mask = 0
        rules(n_rules)%position = 0
        i = index(line,":")
        rules(n_rules)%field = line(1:i-1)
        line = line(i+2:)
        i = index(line,'-')
        read (line(1:i-1),*) rules(n_rules)%low_1
        j = index(line,' ')
        read (line(i+1:j-1),*) rules(n_rules)%high_1
        line = line(j+4:)
        i = index(line,'-')
        read (line(1:i-1),*) rules(n_rules)%low_2
        read (line(i+1:),*) rules(n_rules)%high_2
        do i=rules(n_rules)%low_1,rules(n_rules)%high_1
            valid(i) = ibset(valid(i),n_rules)
        end do
        do i=rules(n_rules)%low_2,rules(n_rules)%high_2
            valid(i) = ibset(valid(i),n_rules)
        end do
        valid_mask = ibset(valid_mask,n_rules)
    end do read_rules
    
    do i=1,n_rules
        rules(i)%position_mask = valid_mask
        end do
    
    allocate (ticket(n_rules))
    allocate (my_ticket(n_rules))   
    read (1,*)
    read (1,*) my_ticket
    read (1,*)
    read (1,*)
        
    read_tickets: do
        read (1,'(A)',end=900) line
        if (line == "") cycle
        read (line,*) ticket
        do i=1,n_rules
            if (valid(ticket(i)) == 0) cycle read_tickets
        end do
        do i=1,n_rules
            do j=1,n_rules
                if (.not. btest(valid(ticket(i)),j)) then
                    rules(j)%position_mask = ibclr(rules(j)%position_mask,i)
                end if
            end do
        end do    
    end do read_tickets
    
900 remaining = n_rules
    do while (remaining > 0)
        do i=1,n_rules
            if ((rules(i)%position == 0) .and. &
                popcnt(rules(i)%position_mask) == 1) then
                rules(i)%position = trailz(rules(i)%position_mask)
                do j=1,n_rules
                    if (rules(j)%position == 0) rules(j)%position_mask = &
                      ibclr(rules(j)%position_mask,rules(i)%position)
                end do
                remaining = remaining - 1
            end if
        end do
    end do
    
    answer = 1
    do i=1,6
        answer = answer * my_ticket(rules(i)%position)
    end do
    
    end program AOC16A

1

u/daggerdragon Dec 16 '20

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.

4

u/sciyoshi Dec 16 '20

Python 3, 52/9 - code here. Luckily the rules didn't have any dependencies between them so a simple greedy algorithm worked for determining which fields were which.

→ More replies (1)

2

u/imbadatreading Dec 16 '20

My hideous python solution

I should learn how to parse inputs properly

4

u/kippertie Dec 16 '20

If you f.read().split(‘\n\n’) first then each section of the input will be in its own string. Makes parsing them nicer.

→ More replies (1)

2

u/nomisjp Dec 16 '20

F# (another one, for science)

Pleased with today's answer, flowed nicely once you try to apply the sort of logic problem approach you see in the old puzzle books on the test data to eliminate the options available at each step.

As usual parsing took too long as despite the regex practise so far, still useless.

→ More replies (1)

2

u/Nerdlinger Dec 16 '20

Swift

Needs some cleaning up, and I'm sure could be sped up. I'm happy though, because I got to play with the new RangeSet struct in the standard library preview, even if it wasn't really needed for this problem.

Note that this also heavily depends on the input being valid, which thank goodness it is for AoC.

2

u/thulyadalas Dec 16 '20

My rust solution link.

P1 was uneventful but on P2, I thought we needed to implement a backtrack search to find the possible field-rule match and I got really lazy to do that. But after a second look, the propagation always gives one clear choice and no backtrack is necessary so the algorithm got simpler than the initial expectation. Code is a bit messy with lots of vec index key usage. Might clean it later.

2

u/cattgravelyn Dec 16 '20

Python3

https://pastebin.com/R0LuSjdi

I usually don't share my solutions (they suck) but this time was quite funny. I decided to do the final bit of part 2 on paper and found it oddly satisfying.

https://imgur.com/ij2nI1d - Paper working out

2

u/heyitsmattwade Dec 16 '20 edited Dec 16 '20

JavaScript

Pretty happy with how this one turned out. I worked on this in the morning so I had time to think and write better code.

I'm particularly happy with Part Two, and how I was able to determine what the fields were. The key helper function is lodash's intersection (technically I used intersectionBy because I parsed my rules to Objects). That is, I loop over a specific field across all the tickets, see what rules could apply to that field, then find the intersection between them. As I determine what fields are what, I continue looping over the fields, using the previously determined answers to further filter things.

function determineOrderingOfTicketFields(rules, valid_tickets) {
    // At first, say that each field could match any of the rules
    let field_possibilities = valid_tickets[0].map((_) => rules);
    let known_rules = {};

    while (field_possibilities.some((possibility) => possibility.length > 1)) {
        field_possibilities = field_possibilities.map((possible_rules, field_index) => {
            // Don't bother filtering if we've already determined what this field is
            if (possible_rules.length === 1) return possible_rules;

            let rules_that_may_apply_to_field = valid_tickets.map((ticket) => {
                let field = ticket[field_index];
                let narrowed_down_rules_for_field = possible_rules.filter(
                    (rule) => !known_rules[rule.name] && fieldFallsWithinRanges(field, rule.ranges)
                );

                return narrowed_down_rules_for_field;
            });

            let itersected_rules = intersectionBy(...rules_that_may_apply_to_field, 'name');
            if (itersected_rules.length === 1) known_rules[itersected_rules[0].name] = true;

            return itersected_rules;
        });
    }

    return field_possibilities.flat();
}

Full code available here

2

u/gbronner2 Dec 16 '20 edited Dec 16 '20

Python3

Uses a lot of vectorized numpy functions. (ugh I hate markdown!)

https://np.reddit.com/r/adventofcode/comments/ke2qp6/2020_day_16_solutions/gg1ow2y/

paste

→ More replies (1)

2

u/Chrinkus Dec 16 '20

C++

I got messed up by rules being able to match multiple fields and needing to be eliminated from comparisons when a single match was found. I DID find a way to use a std::deque though so that will help in my STL::Bingo side project!

paste

GitHub

2

u/chkas Dec 16 '20

easylang.online

Solution

2

u/astory11 Dec 16 '20

F#

My F# solution. Code is a little longer than I'd like, but overall happy with it

2

u/mstksg Dec 16 '20

[Haskell] Today was a nice little self-contained constraint satisfaction problem! Well, it didn't have to be (apparently), but it was fun as one :)

This post taken from my daily Haskell reflections for all the puzzles.

First, our data type:

type Passport = [Int]

data Info = Info
      { iFields :: IntervalMap Int (Set Text)
      , iYours  :: Passport
      , iTheirs :: [Passport]
      }

Here we're using IntervalMap from the data-interval package, which makes it easy to store data at different intervals with easy lookups. For example, if we have ["class"] at interval (1,5), and we had ["row"] at interval (3,7), IntervalMap will merge them together (with <>, if we choose) to get ["class"] at (1,3), ["class","row"] at (3,5), and ["row"] at (5,7).

If we have this IntervalMap, part 1 becomes straightforward enough with the efficient IM.notMember:

import qualified Data.IntervalMap.Lazy as IM

part1 :: Info -> Int
part1 info = sum
    [ n
    | ns <- iTheirs info
    , n  <- ns
    , n `IM.notMember` iFields info
    ]

So now let's move on to the search for part 2!

Our goal is to get a list [(Int, Set Text)] of a column number (in the passport) with the set of all valid field names for that position. And because we are going to be doing a search, we want this list in order of smallest to largest valid-name sets.

First, we can replace the Ints in each passport instead with the set of fields they are valid for

validate :: IntervalMap Int (Set Text) -> [Int] -> Maybe [Set Text]
validate flds = traverse (`IM.lookup` flds)

validateAll :: IntervalMap Int (Set Text) -> [Passport] -> [[Set Text]]
validateAll flds = mapMaybe (validate flds)

Here (\IM.lookup` flds)isInt -> Set Text: it'll look up theSet Textcorresponding to the interval that theIntfalls under in theIntervalMap. It'll returnNothingif *any* of theInts are invalid, andJustif *all* of theInt`s are valid.

Next we want to build our [(Int, Set Text)]. The Set Text is a set of what is valid for that column number, so to get the Set Text for 0, for instance, we need to S.intersection all of the first Set Texts in our list,; to get the Set Text for 1, we need to S.intersection all of the second Set Texts in our lists, etc. This can be done succinctly with a transpose (transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]]). Then we can use sortOn to sort by the size of the valids set.

columnSets :: [[Set Text]] -> [(Int, Set Text)]
columnSets = sortOn (S.size . snd)
           . zip [0..]
           . map (foldl1' S.intersection)
           . transpose

Now we're ready for our search! We'll be using StateT over list, to get a backtracking search with backtracking state (I described this technique in a constraint solving blog post). Our state will be the Set Text of all the "committed" fields so far.

search :: [(Int, Set Text)] -> Maybe [(Int, Text)]
search candidateMap = listToMaybe . flip evalStateT S.empty $ do
    for candidates $ \(i, cands) -> do              -- for each (Int, Set Text):
      soFar <- get                                  -- get the seen candidates
      pick  <- lift . toList $ cands S.\\ soFar     -- pick from the Set Text not including seens
      (i, pick) <$ modify (S.insert pick)           -- propose this index/pick, inserting into seens

And that should be it for our search! In the end this gets the first [(Int, Text)] that is valid, matching a column ID to the field at that column. Our search supports backtracking through the list monad, but it should be noted that we actually don't end up needing it for the way the puzzle input is structured. But, because we sort our lists first from smallest to largest valid-sets, our solution ends up being equivalent to the non-backtracking method and backtracking is never actually triggered.

And we can wrap it all up:

part2 :: Info -> Int
part2 = product
    [ iYours info !! i
    | (i, fld) <- res
    , "departure" `isPrefixOf` fld
    ]
  where
    cSets    = columnSets $ validateAll (iFields info) (iTheirs info)
    Just res = search cSets

2

u/foolnotion Dec 16 '20

C++

The idea for part 2:

  1. build an n x n matrix where n is the number of ranges

  2. fill the matrix such that m(i, j) == 1 if all values in position j from the nearby tickets are contained in range i

  3. count the number of ones in each row

  4. iterate over that count in ascending order, get the index of the 1 (and set the respective column values to zero), rinse and repeat

I used Eigen because I am lazy.

code on github

2

u/RudeGuy2000 Dec 16 '20

Bash, part 1: https://hastebin.com/tiduzehebo.bash

Doing this one in bash was definitely a mistake. It takes a while to output the solution, even without writing output.

2

u/prophetjohn Dec 16 '20

RUBY

https://github.com/j-clark/adventofcode/commit/29225aa85fe56909fa2cdd19fb30c68537f79d46

I just hacked it as naively as I could think of and it worked and was definitely not my slowest solution 🤷‍♀️

2

u/thecro99 Dec 16 '20

C++ - Very Clear Object-Oriented Solution

https://github.com/mateom99/Advent-of-Code/tree/main/2020/Day%2016

I upload every day and try to comment everything to make it really intuitive and easy to understand. I also "blog" about my experience in the README!

2

u/[deleted] Dec 16 '20

C99 with glib2.0

Benchmarked on a MacBook Pro (15-inch, 2017) - 100 runs per part.

PartWorstAverageBest
I687us77us63us
II10326us5017us718us

2

u/rrcjab Dec 16 '20

Python not awesome, especially the winnowing down of the possibilities at the end, but it works https://pastebin.com/XPKZNrvm

2

u/chicagocode Dec 16 '20

Kotlin -> [Blog/Commentary] - [Solution for Today] - [GitHub Repo for 2020 Solutions]

I really enjoyed today's puzzle. I used some nice functions from the Kotlin standard library - any, none, and all. I also really like the fact that Kotlin has great support for ranges!

2

u/tristanbeedellAOC Dec 16 '20

Node JS / Javascript

part 1 this was pretty quick. I kinda had a feeling for what was coming in part 2 but decided to do something lazy instead.

part 2 this solution isn't particularly beautiful but it worked.

2

u/e_blake Dec 16 '20 edited Dec 16 '20

m4 day16.m4

Depends on my common.m4 and math64.m4, with the latter needed because 6 values multiplied together overflowed m4's 32-bit math. I'm pretty happy with how it turned out; I got 150ms execution time with 'm4' (where parsing is O(n) with patsubst), and 170ms with 'm4 -G' (my approach for O(n log n) parsing is hands-down better than a O(n^2) foreach over every comma). My general approach:

  1. for every valid value in the first third of the input file, define 'vN' to a bitmask representing which slots N may appear in (so, for the first sample, 'v0' is undefined, 'v1' is 1, 'v7' is 7, 'v14' is 4, all the way to `v50'); also, define 'sX' to the field name (where X is a power of 2) [the first call to do()]

  2. for every line in the last third of the input file, if any of the arguments in position P have no corresponding 'vN', increment 'part1'; otherwise, compute 'nP &= vN' (for the first sample, this results in 'n0' of 3, 'n1' of 1, 'n2' of 4) [the second call to do()]

  3. with an O(x^3) loop (but with x=number of lines in part 1, and where x=20 for the actual puzzle input was not too bad), find an entry in 'nP' that is a power of 2, map it back to the appropriate field name 'sX' via 'lN', and remove that bit from all 'nP' [nested call to forloop()]

  4. a loop through the resulting via 'lN' vs. the middle third of my input tells me which values to multiply for 'part2' [call to tally()]

2

u/dinkelhopper Dec 16 '20

C++

Source

I really think a few steps can be eliminated from my solution, but it runs pretty darn fast.

Benchmarks from my 2017 Macbook Pro

Run on (8 X 2900 MHz CPU s)
CPU Caches:
  L1 Data 32 KiB (x4)
  L1 Instruction 32 KiB (x4)
  L2 Unified 256 KiB (x4)
  L3 Unified 8192 KiB (x1)
Load Average: 4.66, 3.04, 2.83
-----------------------------------------------------
Benchmark           Time             CPU   Iterations
-----------------------------------------------------
Day16/1         0.921 ms        0.902 ms          911
Day16/2          1.08 ms         1.08 ms          662

2

u/ropecrawler Dec 16 '20

Rust

https://github.com/ropewalker/advent_of_code_2020/blob/master/src/day16.rs

A bit clunky, but I guess it will do. 8.9130 μs / 296.71 μs on my machine.

2

u/TheElTea Dec 16 '20

C# Solution for 2020 Day 16 Parts 1 and 2

Commented code on Pastebin

This was a fun one! I really broke this one down, making a class for Ticket Rules that could check for values being in range. Part 2 was solved by:

  • Finding the possible field matches for every rule by checking each field from all tickets, one at a time, for each rule. If no values were rejected, they were a possible match.

    • Remember to include your own ticket in this set! (Easy to forget as you had been told to ignore it for part one).

  • Match each rule to one field.

    • Note that I took a debug step here to see that 1 rule has 1 match, but another has 2 matches, another has 3 etc.

    • So, the puzzle was built such that you can match the rule with 1 matching field and remove it from all other rules' potential matches.

    • That creates a new rule that has only one match. Repeat these steps until all rules have just one matching field.

  • Find the six rules with "departure" and multiply their values together.

→ More replies (1)

2

u/RileyJohnGibbs Dec 16 '20

I used numpy and I think loading numpy was the slowest part of the solve. Part 1 and Part 2 each ran in under a tenth of a second.

numpy solution in Github

It took a lot longer to code up because I needed to refresh myself on how to manipulate arrays in numpy, but I guess that's kinda the point of these challenges for me. 🙂

2

u/BASED_CCP_SHILL Dec 16 '20

Ty

paste

Part 2, slightly messy and not very optimized. Takes 700ms on my laptop.

2

u/pwhyz Dec 16 '20

Python

part2 in 34 lines

2

u/[deleted] Dec 16 '20

Python solution.

Ungainly but it's quick enough. 8 ms or so.

2

u/levital Dec 16 '20

Rust

This day looked a lot worse than it ended up being, though particularly the last bit of my part 2 solution is pretty hacky.

2

u/kippertie Dec 16 '20

Python 2

19 LOC if you remove all the blank lines and collapse lines 17-25 down to a single line.

https://github.com/soundidea/aoc2020/blob/main/16_solution.py

2

u/taomage Dec 16 '20

Python 3.7 Solution.

Interesting problem today.

2

u/AuntieRob Dec 16 '20

I'm kinda dumb and this took me longer then it should have. Anyways here is my c++ solution

https://github.com/ffamilyfriendly/Advent-Of-Code/blob/master/day_16/challange_2/main.cpp

(code was rage-written towards the end so dont judge too harshly lol)

2

u/jjameson18 Dec 16 '20

This took me way too long. I kept kicking myself thinking that Part 2 had to be easier than I was making it; ended up using a while loop on Part 2. Anyways, solution in Julia. Part 1 performance: 1.445 ms (3376 allocations: 685.48 KiB). Part 2 performance: 184.747 ms (89228 allocations: 84.24 MiB).

2

u/Resident_Astronaut76 Dec 16 '20

Python

What I did was create a dict of all potential indices for a field and when only one index was possible for a certain field, I removed it from all the others. The loop runs until every field is left with one potential index.

2

u/misanthropicdrunkard Dec 16 '20

A not very pretty Scala solution but it runs a quickly-ish. It also gave the right answer once I switched from Int to Long at the end

2

u/ViliamPucik Dec 16 '20

Python 3 - (Almost) minimal readable solution for both parts [GitHub]

The code optimizes processing time by combining related part 1 and part 2 calculations into a single loop.

It tries to be also memory efficient by not expanding rule number ranges or doing any data duplication.

And no 3rd party libraries, just set() magic ;)

A short snippet:

...
    for number in map(int, ticket.split(",")):
        # all possible matching rules (indexes)
        matching_rules = set(
            i
            for i, (_, lo1, hi1, lo2, hi2) in enumerate(rules)
            if lo1 <= number <= hi1 or lo2 <= number <= hi2
        )
        if len(matching_rules) == 0:
            error_rate += number  # part 1
            valid_ticket = False
        elif valid_ticket:
            ticket_rules.append(matching_rules)

    if valid_ticket:
        for col, matching_rules in zip(cols, ticket_rules):
            # store just overlapping rules for each column, part 2
            col &= matching_rules  # col is a reference, not a copy
...

2

u/Crafty-Visual198 Dec 16 '20 edited Dec 16 '20

python day 16 - sweep line + SAT solver. 70ms for pt2

2

u/skawid Dec 16 '20

Ruby!

Keep finding ticket columns with only a single valid rule, until you have all the columns. My original solution (breadth first search) is still running.

2

u/MischaDy Dec 16 '20 edited Dec 17 '20

Python 3 - Readable enough.™

EDIT: Added part 1.

2

u/nikcorg Dec 16 '20 edited Dec 17 '20

Day 16 using Golang

Finally, I thought, there was a good use case for bitwise masks. Initially I believed it would just be a matter of calculating the bitmask for each column, xor'ing all of them together and the solution would just magically appear. Alas, it was not to be quite that easy. In the end I'm not sure the bitwise operations were that useful, but at least I got to practise using them, which is why I'm doing this I guess.

Using the test data as example, here's how I solved Part 2.

1) Get a bitmask for each column (cid), a high bit denotes a rule matched by
   every value in a column. The bitwise ANDing made this part really easy,
   so maybe it wasn't *all* in vain.

cid= 0, mask=010 (from 110 & 011 & 111)
cid= 1, mask=011 (from 111 & 111 & 011)
cid= 2, mask=111 (from 111 & 111 & 111)

2) Find a column/mask with only 1 high bit, and zero that bit from all other
   bitmasks. This process of elimination requires several passes, and could
   possibly be optimised, but it was quick enough for this dataset.

cid= 0, mask=010 <-- identified
cid= 1, mask=001 <-- filtered
cid= 2, mask=101 <-- filtered

cid= 1, mask=001 <-- identified
cid= 2, mask=100 <-- filtered

cid= 2, mask=100 <-- identified

3) Use the high bit position to match the column (cid) on your ticket
   to a field (fid) in your rules

cid= 0, mask=010, fid= 1, name=  row, value=11
cid= 1, mask=001, fid= 0, name=class, value=12
cid= 2, mask=100, fid= 2, name= seat, value=13

2

u/Lakret Dec 16 '20 edited Dec 16 '20

Rust

Part 1 Solution code, Live Stream.

Part 2 Solution with backtracking, tabu search, and multi-threading: 1, 2. Live Stream.

Part 1 was trivial, parsing was the hardest part, as usual :) Part 2 - a typical constraint satisfaction problem. I went with backtracking algorithm to solve it, which worked in the end, but initially was too slow. I optimized it with Tabu search (remembering the excluded values to not re-start the same searches with them), and multi-threading to search with multiple initial assignments in parallel, and terminate once at least one solution is found. Before I could finish my multi-threading thing, one of the multiple terminals in which I ran the single-threaded version has found the solution. I finished the multi-threading thing after the stream, and figured that Tabu search did help after all. A bit of brag screenshots :)

So far, the best task!

2

u/chennuz Dec 16 '20 edited Dec 16 '20

C solution, part two took me a while, the algo was correct but I struggled with the res

part 1

part 2

2

u/melefabrizio Dec 16 '20

PHP 8 --> Gist p1+p2

This is me trying to make sense of 2h of coding with and extra 30 minutes of commenting. Should be pretty readable. Runs in 0.03s! (with php8 and jit).

Somewhere in the middle of part 2 (which approximates to the middle of the day) I realized that probably the problem could be solved by fancy matrix operations but I was too lazy and opted for an iterative search. I do not dare to calculate the O-cost of the algorithm.

Is it good that I spent my evening doing this instead of raging on Cyberpunk2077 ps4 crashes?

2

u/gamepopper Dec 16 '20

C++

This part 2 challenge had to be the hardest one I've faced so far. Thanks to the other redditors who gave me hints on how to figure out the order, although it still took multiple attempts to calculate the correct answer (partially due to how large it is and partially because I messed up the field and ticket output order).

https://pastebin.com/8uKh3hdC

2

u/wishiwascooler Dec 16 '20

Tried to do stuff with sets/intersect/symmetric difference etc but when i couldnt get that to work i used backtracking. Anyways, here's my 3 minute runtime Javascript code lol

https://github.com/matthewgehring/adventofcode/blob/main/2020/day16/script.js

2

u/okawei Dec 16 '20

My golang solution, it's gross. I did a map of all the possible numbers available for rules so I didn't have to think about comparisons for part one.

https://github.com/maxheckel/advent2020/blob/main/16/main.go

2

u/tobidope Dec 16 '20

Java

https://github.com/tobidope/aoc2020/blob/master/src/main/java/de/tobiasbell/aoc_2020/Day16.java

Quite good for part 1, but part 2 seems way to big. And I have bad feeling on using the Predicate functional interface.

2

u/prafster Dec 16 '20

Dart

My version although fast enough (<0.5s) seems verbose. I'm going to look at how others solved this because although not difficult it was a bit messy for me.

2

u/AlaskanShade Dec 17 '20

C# 534/475

Paste

First pass on the process of elimination step was done by hand in notepad++. This "final" solution was after spending a bit more relaxed time to work out the reduction and then to make it work for the odd test case with part 2. I try to keep as many test cases handled as possible in the code. It could still use just a bit of tweaking, but runs both parts in just a few milliseconds.

2

u/mattaman101 Dec 17 '20 edited Dec 17 '20

RUBY Part 2

Using hashes with a key of the rule (route, price etc) and a value of sets containing indexes in the ticket that it cannot be. A pattern emerged and these sets were of length 19 - 18 - 17- 16- 15 etc etc. You look at the length 19 set and see what index is missing, and assign that as the correct index of that sets key in a new hash, and then add that missing number to all of the sets, since now none of them can be at that index. Keep checking the length 19 set (since the length 18 one is now 19, and the former 19 one is now 20) and eventually, you get all of the correct indexes.

2

u/thedjotaku Dec 17 '20

Python

I'm not entirely sure, but I think I must have chosen the most ridiculously roundabout way to solve part 2. But, given the fact that first I had to figure out how in the world I was going to solve it WITHOUT programming and then trying to figure out how to solve it WITH programming, I'm INCREDIBLY happy that it worked! I mean, shoot, 24 hours later my solution attempt at day 15 part 2 is still running.

https://github.com/djotaku/adventofcode/tree/main/2020/Day_16

2

u/ragnario Dec 17 '20

Rust solution on my Github

For part 2 I keep list of valid field indices for each column in the ticket, initialize with "your ticket". Go through each nearby ticket, one by one, update indices by the intersection. Finally, go through several loops to eliminate the final model (with sorting and keep the indices with single item).

Took around 1.2s.

2

u/pdr77 Dec 17 '20

Haskell

Video Walkthrough: https://youtu.be/w9ZONXFQkyE

Code Repository: https://github.com/haskelling/aoc2020

Part 1:

main = interactg f

attribp :: String -> Int -> Bool
attribp s = or . mapM inRange rules
  where
    [_, rs] = splitOn ": " s
    rules = map (map read . splitOn "-") $ splitOn " or " rs
    inRange [low, high] x = low <= x && x <= high

ticketp :: String -> [Int]
ticketp = map read . splitOn ","

f [as, [_, t], _:ts] = sum $ filter matchesNoRules $ concat tickets
  where
    (attribs, tickets) = (map attribp as, map ticketp ts)
    matchesNoRules = not . or . sequence attribs

Part 2:

main = interactg f

attribp :: String -> (String, Int -> Bool)
attribp s = (name, or . mapM inRange rules)
  where
    [name, rs] = splitOn ": " s
    rules = map (map read . splitOn "-") $ splitOn " or " rs
    inRange [low, high] x = low <= x && x <= high

ticketp :: String -> [Int]
ticketp = map read . splitOn ","

f [as, [_, t], _:ts] = product $ map fst $ filter (isPrefixOf "departure" . snd) $ zip ticket fieldNames
  where
    (attribs, ticket, tickets) = (map attribp as, ticketp t, map ticketp ts)
    matchesAnyRule = or . mapM snd attribs
    tickets' = filter (all matchesAnyRule) tickets

    attributes = map filterAttribs $ transpose tickets'
    filterAttribs xs = map fst $ filter (\(_, r) -> all r xs) attribs

    fieldNames = map head $ converge removeKnowns attributes
    removeKnowns names = let knowns = concat $ filter ((==1) . length) names
                             doRemove ns = if length ns /= 1
                                             then filter (`notElem` knowns) ns
                                             else ns
                         in  map doRemove names

2

u/mykepredko Dec 17 '20

C - Probably not the right language for this challenge

I was able to get Part 1 together with a minimum of fuss. But, as others have pointed out, there is some work at getting the parsing together and you need to plan your data structure.

Part 2 is quite a bit more involved with multiple steps that aren't typically there for the challenges as well as needing to have a strategy for identifying the different fields. I would have done really well, except that I have a reducing ticket field table (each iteration, one or two of the fields are identified) that my loop didn't handle well and I ended up in an infinite loop that was difficult to identify and correct.

I suspect that there are better solutions available if you're not coding this challenge in C - as I'm writing this, I see a nim program which inverts the ticket field table to solve the challenge.

→ More replies (3)

2

u/aoc-fan Dec 17 '20

JavaSCript/TypeScript Repo. Probably first day of 2020, which required intensive coding.

The part 2 was rare today, probably first time there was no clear instructions on what to expect.

2

u/saahilclaypool Dec 17 '20

(C# / dotnet 5) aoc_2020/Day16.cs at main · SaahilClaypool/aoc_2020 (github.com)

This was a fun one - I wrote a brute force solution before realizing that permutations grow quite rapidly..

2

u/GiftOfDeath Dec 17 '20

It's me, the GML(GameMaker Language) guy again! It got kinda lengthy so have a link to the repo. To be frank I'm fairly happy with how this turned out. :D

For part 1: what I ended up doing - just purely for practice as I anticipated that which range is which might be relevant in the second part - joining all the ranges together to reduce the number of comparisons. Turns out all the ranges in my input fit into a single number pair!

Then ran all the ticket values through the range check adding the erroneous numbers, and flagged and deleted the invalid tickets from the list, which was passed down to part two. You know, why not? The method also avoided the fairly common problem with 0 values. :P

For part 2: generate an array filled with possible lists, run the tickets against it, find the key lists that had only a single valid range for any ticket, remove from other fields, repeat. Pretty plain and simple.

2

u/aexl Dec 17 '20 edited Mar 01 '21

Julia.

Not proud of my today's solution.. but hey, I guess it works...

Github: https://github.com/goggle/AdventOfCode2020.jl/blob/master/src/day16.jl

2

u/_ZoqFotPik Dec 17 '20

Rather messy Rust solution which took me ages to get right. Runs in 1.3ms (without measuring parsing).

There is likely tons of stuff one could do better but you don't wanna know how late it is around here. I go sleep now :)

2

u/ratherforky Dec 17 '20

Haskell

This was a tough one but I'm relatively happy with my solution here (though I'm sure it could be refactored a little). Runs in ~23ms (~3ms for part 1 + ~4ms for part 2 + ~16ms of file reading/parsing)

Solution

2

u/jkpr23 Dec 17 '20

Python, numpy solution

Data initialization: 20 lines of code

Part 1: 5 lines of code

Part 2: 16 lines of code

Code on github, blog-ish post on the repo README.

Main idea is to create a 3-D array of booleans. Dimension 0 for the different fields / rules, Dimension 1 for the various lines of the nearby tickets, and Dimension 2 for the columns of the nearby tickets. A given entry (i, j, k) is True if nearby ticket j, column k, fits in the range for field / rule i. Then do numpy manipulations on that cube to get the answers.

2

u/dangermaximum Dec 17 '20

R / Tidyverse

I really overthought part 1 and should've just run with my initial instinct. Very simple solution in the end.

Part 2 worked out OK, mainly because it didn't need any recursion.

code

2

u/Dullstar Dec 17 '20

C++

The performance is good; takes between 10 and 24 ms including parsing on my computer.

While it could be much, much worse, I like to make my code tidy and easy to follow, and I'm not sure that's what I've created for this one. I might go back later and fix it.

2

u/Marco21Burgos Dec 17 '20

Python 3

Part 1:

def ticket_translation_1():
    input = read_and_load_input("DAY16")
    valid_seq = set()
    rules = True
    nearby = False
    solution = 0

    for line in input:
        if rules:
            seq = re.findall('\d+', line)
            round = 0
            while round < 3 and len(seq) > 0:
                for _ in range(int(seq[round]),int(seq[round +1]) + 1):
                    valid_seq.add(_)
                round += 2
            sorted(valid_seq)

        elif nearby:
            numbers = line.split(",")
            for number in numbers:
                if int(number) not in valid_seq:
                    solution += int(number)

        if len(line) == 0:
            rules = False

        if line.startswith("nearby"):
            nearby = True
    return solution

I created a big sequence and then compare each ticket to validate it.

2

u/Attitude-Certain Dec 17 '20

Python

Not my favorite puzzle, very straightforward without a way to do it especially cleanly (that I can think of or have seen here at least). Still fun though! Runs in ~30 ms in total.

paste

→ More replies (1)

2

u/mc_ Dec 17 '20

Erlang

Part 1

Part 2

These are non-optimized, likely duplication of effort, multiple passes when one would suffice, etc. But each part runs under 300ms to the answer so calling it good. Craftsmanship when the code needs to be maintained lol!

2

u/sporksmith Dec 19 '20

Rust. After part1 was kind enough to not have to do reasoning like "Field 0 only works for rule 0; field 1 also only works for rule 0; they can't both be rule 0; -> the ticket is invalid", I initially took a stab at part 2 assuming that each ticket-offset would only have one field rule that worked for all tickets. No such luck, but still wasn't too bad.

part1: 247 us
part2: 579 us

2

u/mschaap Dec 20 '20

Raku

Pretty straightforward. Used a `grammar` for the ticket notes, and put all the functionality in a `TicketParser` class. I commented it for a change, and it should be pretty easy to read.

https://github.com/mscha/aoc/blob/master/aoc2020/aoc16

2

u/kaklarakol Dec 21 '20

Python 3

I could have done the input file parsing with a RegEx, but anyway ...

Topaz Link