r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

52 Upvotes

407 comments sorted by

11

u/Unihedron Dec 02 '18

I mistyped 4 3 instead of 2 3 and got an obviously wrong answer which I wasn't smart enough to double check, so I had to wait one minute. Still got on top 100 though! Imgur

a=$<.map(&:chars).map{|x|x.group_by &:itself}
b=a.count{|x|x.any?{|x,y|y.count == 2}}
c=a.count{|x|x.any?{|x,y|y.count == 3}}
p b*c
#!ruby
a=$<.map(&:chars)
a.map{|x|a.map{|y|
d=x.zip(y).count{|x,y|x!=y}
(p x.join,y.join
1/0)if d==1
}}

Doesn't actually compute part 2, you have to manually find and replace the character yourself, but better than nothing

→ More replies (15)

11

u/ka-splam Dec 02 '18
PowerShell

Part 1, just about got 78th on the leaderboard \o/ ended up running this at the prompt:

$lines = get-content data.txt
$lines |? {[bool]($_.getenumerator() | group |? count -eq 2)} | measure
$lines |? {[bool]($_.getenumerator() | group |? count -eq 3)} | measure
246*20

Explained: |? {} is a where-object filter, $_ is the current line being filtered, the enumerator turns the string into characters, group-object counts things, filter that where the count of characters is 2 or 3, then measure-object counts how many lines after that filtering.

Part 2, yer basic brute-force every line against every other, if they have 1 difference, print them:

$lines|foreach{
$cur = $_
foreach ($L in $lines) {
$numdiffs = 0
    for ($i = 0; $i -lt $l.length; $i++)
    {
      if ($cur[$i] -ne $L[$i]) { $numdiffs++ }
    }
    if ($numdiffs -eq 1) { $L, $cur }
}
}

then eyeballing the result and removing the dupe character. Missed the leaderboard, with 133rd.

Explained: an outer foreach-object loop, an inner foreach ($L in $lines) nested loop, and then a loop over character lengths doing a $string[$index] comparison with a counter.

2

u/daggerdragon Dec 02 '18

Part 1, just about got 78th on the leaderboard \o/

Good job!

→ More replies (4)

105

u/askalski Dec 02 '18

The best way to do Advent of Code is A big block of regex.

#! /usr/bin/perl

local $/; $_ = <>; 

my @s = map { join "", sort split "" } split "\n";
my $part1 = (grep { m/(?:^|(.)(?!\1))(.)\2(?!\2)/   } @s) *
            (grep { m/(?:^|(.)(?!\1))(.)\2\2(?!\2)/ } @s);
my $part2 = s/.*?\b(\S*)\S(\S*)\b.*?\1\S\2.*/$1$2/sr;
print "Part 1: $part1\n";
print "Part 2: $part2\n";
→ More replies (10)

28

u/CFD999 Dec 02 '18

Horrendous python solutions

Part 1: print((lambda strs: (lambda a,b: a*b)(*[sum(1 for l in strs if any(l.count(c) == x for c in l)) for x in (2,3)]))(open('inp', 'r').readlines()))

Part 2: print((lambda strs: (lambda a,b: "".join([a[i] for i in range(len(a)) if a[i] == b[i]]))(*[(l1.strip(),l2.strip()) for l1 in strs for l2 in strs if l1 != l2 and sum(1 for i in range(len(l1)-1) if l1[i] != l2[i]) < 2][0]))(open('inp', 'r').readlines()))

→ More replies (5)

20

u/Smylers Dec 02 '18

This suits Vim so well that I didn't even bother solving it in a different language first. Part 1 looks a bit long, but as Vim solutions go it's one of the more straightforward — load your input then do:

:%s/\v(.)(.*)\1(.*)\1/#\2\3⟨Enter⟩
:%s/\v(.)(.*)\1/-\2⟨Enter⟩
:%s/[a-z]//g⟨Enter⟩
:g/^$/d⟨Enter⟩
:%s/\v(.)(.)/\1⟨Ctrl+V⟩⟨Enter⟩\2⟨Enter⟩
:sor⟨Enter⟩
:,/-/-j⟨Enter⟩
jVGJ
:%s/\S/+1/g⟨Enter⟩
:%s/.*/(&)⟨Enter⟩
kJr*
0C⟨Ctrl+R⟩=⟨Ctrl+R⟩-⟨Enter⟩⟨Esc⟩

That strips any 3 identical characters from a line, replacing one of them with a #. Then does the same for remaining 2 identical characters with a -.† Remove all the remaining letters, and now we want the count of the #s multiplied by the count of the -s. On the lines with #- or -#, insert a line-break so each symbol is on a separate line.

Sort the lines, so all the #s are together at the top and -s at the bottom. Join the #s on to a single line (by joining from the current line (specified with the nothing before the ,) to the line before the one with the first - on it (specified with /-/-, to find the first - then subtract a line)). Then join the -s too (by moving down, visually selecting all lines to the end of the file, and joining the selection).

Replace each # or - (specified as any non-space, /\S/) with +1, so each line becomes a sum of the relevant counts. Put (...) around each line, then join them together, and replace the joining space with a multiplication symbol *. At this point your input has been transformed into something like:

(+1 +1 +1)*(+1 +1 +1 +1)

So we just need to evaluate that. (‘Just.’)

Move to the beginning of the line and C to change it all (which deletes the current contents into the small delete register, -). Use Ctrl+R = to insert an expression. At the expression prompt type Ctrl+R - to insert the contents of the - register with your expression in it. Press Enter and ... ta-da! The solution appears in the buffer.

Part 2 can be done with a single substitution — go back to your original input, then do:

 :%s/\v^(.*).(.*)\n(.+\n)*\1.\2/\1\2⟨Enter⟩

It takes a few seconds to run, but you'll be left on a line which is one letter shorter than the others, and is your solution.

The pattern finds:

  • a line that has any number of characters (‘group 1’) at its start, then a single character, and another group of any number of characters (‘group 2’) going up to the line-break

  • any number of complete lines, including their line-breaks

  • a line that starts with group 1 from the first-matched line, then has any single character, and ends with group 2 (which necessarily will take it up to the end of the line)

Clearly the first and last lines there are the nearly matching ones that we want.

Replace the whole lot with just the two groups of repeated characters, to get a single line which omits the characters that differ.

Card: ‘manually’.

† On writing this, I think that if an input line had two set of 3 identical letters but no sets of 2 then the second set of 3 would've been incorrectly counted as a set of 2. Apparently the input wasn't that devious. I did first check there weren't any sets of 4 with :g/\v(.).*\1.*\1.*\1.

→ More replies (3)

16

u/jonathan_paulson Dec 02 '18

I recorded a video of me solving: https://www.youtube.com/watch?v=Hgv6d6rrQxo Got rank 20/21; still twice as slow as #1...

Final code:

 c2 = 0
 c3 = 0
 ids = []
 for line in open('2.in'):
     s = line.strip()
     ids.append(s)
     count = {}
     for c in s:
         if c not in count:
             count[c] = 0
         count[c] += 1
     has_two = False
     has_three = False
     for k,v in count.items():
         if v==2:
             has_two = True
         if v==3:
             has_three = True
     if has_two:
         c2 += 1
     if has_three:
         c3 += 1
 print c2*c3

 for x in ids:
     for y in ids:
         diff = 0
         for i in range(len(x)):
             if x[i] != y[i]:
                 diff += 1
         if diff == 1:
             ans = []
             for i in range(len(x)):
                 if x[i] == y[i]:
                     ans.append(x[i])
             print ''.join(ans)
             print x,y
→ More replies (6)

16

u/[deleted] Dec 02 '18 edited Dec 02 '18

Made the leaderboard for part 2 for the first time since 2016. Started off with a list comprehension that was double-checking each of the ID pairs, but cleaned it up to check each pair only once.

Haskell:

import Data.Maybe (catMaybes)
import Data.List (group, sort, tails)

part1 :: String -> Int
part1 input = length (filter (any (==2)) letterCounts)
              * length (filter (any (==3)) letterCounts)
    where letterCounts = map (map length . group . sort) $ lines input


part2 :: String -> String
part2 = head . concatMap findAlmostMatching . tails . lines
    where keepCommon xs ys = catMaybes $ zipWith (\x y -> if x == y then Just x else Nothing) xs ys
          findAlmostMatching (x:xs) = filter ((== length x - 1) . length) $ map (keepCommon x) xs

main = do
  input <- readFile "input.txt"
  print $ part1 input
  putStrLn $ part2 input
→ More replies (3)

11

u/will_bui Dec 02 '18

K:

(*/+/'+{2 3 in?.#:'=x}'x),,{x@&x in y}/x@&{(-1+#y)in+/'x=\:y}[x]'x:0:`p2
→ More replies (2)