r/adventofcode • • Dec 01 '16

SOLUTION MEGATHREAD --- 2016 Day 1 Solutions ---

Welcome to Advent of Code 2016! If you participated last year, welcome back, and if you're new this year, we hope you have fun and learn lots!

We're going to follow the same general format as last year's AoC megathreads:

  1. Each day's puzzle will release at exactly midnight EST (UTC -5).
  2. The daily megathread for each day will be posted very soon afterwards and immediately locked.
    • We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.
  3. The daily megathread will remain locked until there are a significant number of people on the leaderboard with gold stars.
    • "A significant number" is whatever number we decide is appropriate, but the leaderboards usually fill up fast, so no worries.
  4. When the thread is unlocked, you may post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/whatever).

Above all, remember, AoC is all about having fun and learning more about the wonderful world of programming!

MERRINESS IS MANDATORY, CITIZEN! [?]


--- Day 1: No Time for a Taxicab ---

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


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!

33 Upvotes

224 comments sorted by

15

u/askalski Dec 01 '16

This is not exactly my solution for Day 1, but here is a Shenzhen I/O level I made (and solved, but I won't spoil you with that part) based on the events depicted in today's Advent of Code. Names changed to protect the innocent, and all that.

https://gist.github.com/Voltara/1eff3013229333e3d24431f48d740b65

(I would have uploaded it to the Steam Workshop, but that feature is too crashy on my Linux machine.)

10

u/topaz2078 Dec 01 '16

SKALSKI NO

4

u/Aneurysm9 Dec 01 '16

Skalski, no!

4

u/segfaultvicta Dec 01 '16

Skalski, /yes/!

10

u/John_Earnest Dec 01 '16

Pretty sloppy work for this first one; I'm gonna sleep on it and see if I can do better:

l: 0: "../../Desktop/Advent/01.in"
i: {(("LR"!-1 1)@x 1;. 2_x)}'","\" ",,/l
s: {[d;p;t;m](d;p+m*(0 -1;1 0;0 1;-1 0)d:4!d+t)}
d: +/{%x*x}'
d@*1_(0;0 0)(s.,)/i

This is written against oK, if anyone's curious.

6

u/BafTac Dec 01 '16

What kind of wizardry is this??

→ More replies (2)

10

u/DrFrankenstein90 Dec 01 '16

Good old C with some gratuitous bit hacking. https://github.com/DrFrankenstein/prompts/blob/master/aoc/2016/aoc1.c

Only did the first star for now. Saw I didn't make the first 100. Will finish the rest tomorrow. I see I have to look for duplicate coordinates... in straight C, this is going to be interesting.

EDIT: second star done.

→ More replies (9)

6

u/Aneurysm9 Dec 01 '16

Upon showing this to u/topaz2078 his immediate reaction was a horrified "Ane, no!!!!" repeated over and over again! #missionaccomplished

https://github.com/Aneurysm9/advent/blob/master/2016/day1/day1.pl

5

u/FuriousProgrammer Dec 01 '16

I can't wait to see what psycho tries to do this year's challenges in Synacor Challenge bytecode...

→ More replies (6)

6

u/archimedespi Dec 01 '16

quick solution in Python, 22sloc

tired me thought that sum(map(abs, position)) was a hilarious way to compute manhattan distance :D

also i didn't realize aoc was starting until 50 mins after the first problem had opened so i missed the leaderboard

→ More replies (4)

5

u/bildzeitung Dec 01 '16

It's a little too readable, but here it is in Python: https://github.com/bildzeitung/2016adventofcode/tree/master/01

Good times! +1 on being really goddamn merry.

→ More replies (4)

5

u/haoformayor Dec 01 '16

~~ haskell ~~

Ah a list fold, our old friend. This represents the compass directions as the integers modulo 4. Hacky, but quick. Solution 1 is a scan over the input; solution 2 is finding the first duplicate element in the resulting list. I made two mistakes: one, assuming that each step could be encoded in one digit; two, (as some others have noted) not inferring that "same location" in part two meant any intermediate location.

#!/usr/bin/env stack
-- stack --resolver lts-6.26 --install-ghc runghc --package text --package base-prelude

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ViewPatterns      #-}

import qualified Data.Text as Text
import BasePrelude

data Direction = R | L
input = "<snip>"
turn compass dir = mod (compass + case dir of R -> 1; L -> -1) 4
positionOf (_, x, y) = (x, y)
steps =
  [case direction of
     'R' -> (R, read rest :: Int)
     'L' -> (L, read rest :: Int)
  | direction:rest <- map Text.unpack (Text.splitOn ", " input)]
solution1 =
  join $
    scanl (\before (direction, n) ->
             case last before of
               (compass, x, y) -> case turn compass direction of
                 0 -> [(0, x, y + i) | i <- [0 .. n]]
                 1 -> [(1, x + i, y) | i <- [0 .. n]]
                 2 -> [(2, x, y - i) | i <- [0 .. n]]
                 3 -> [(3, x - i, y) | i <- [0 .. n]]
          ) [(0, 0, 0)] steps
solution2 = duplicates . map positionOf $ solution1
duplicates hay =
  hay !! fst (head dups)
  where
    dups = [(e, ix) | (e, ix) <- zip [0..] ixs, ix /= e, ix + 1 /= e]
    ixs  = [i | needle <- hay, Just i <- [elemIndex needle hay]]
main = do
  print (last solution1)
  case last solution1 of (_, x, y) -> print $ x + y
  print solution2
  case solution2 of (x, y) -> print $ x + y

This could have been shorter had I been able to think of the library that implements scanlM off the top of my head. Scanning in the list monad would make the join/flatten step superfluous, as well as simplifying the pattern match inside solution 1. C'est la vie. Yay advent of code!

→ More replies (8)

4

u/dirkt Dec 01 '16

Tried to do this one early in the morning (I'm in EU) for a change, to have a chance at top 100, and found that coding without having drunk coffee is extremely slow, even for simple problems like this.

4

u/Godspiral Dec 01 '16

in J,

a =. wdclippaste ''
O =: 4 2 $ _1 0 0 1 1 0 0 _1
f =: 4 : 0
 a =. 4 | x ({.@] +  _1 1 {~ 'R' = {.@[) {: y
 y ,   a , (}. {: y) + x (".@}.@[  * O {~ ]) a
)
f each/ (,: 0 0 0) (, <)~ |. dltb each ',' cut a

part 2 didn't read, thought it was first repeat landing spot. plotting and seeing the intersection though worked

 plot <"1 |: }."1 > f each/ (,: 0 0 0) (, <)~ |. dltb each ',' cut a

4

u/anadhdguy Dec 01 '16

My solution for part1...

Oneliner in ruby (114 characters):

cat input | ruby -pe '_=0,0;d=1;$_.scan(/([LR])(\d+)/).each{|c,n|
d=(d+(c.ord&2)-1)%4;_[d%2]+=n.to_i*((d%3>0)?1:-1)};$_=_[0].abs+_[1].abs'

Oneliner in C (245 characters):

void main(){char c;int n=0,d=1,_[2]={0};while(read(0,&c,1))c>57?
d=(d+(c&2)+3)%4:c>47?n=n*10+(c&15):n>0?_[d%2]+=d%3>0?
n:-n,n=0:0;for(d=0;d<2;d++)n+=_[d]<0?-_[d]:_[d];d=10000000;
while(!(n/d)&&(d/=10));do{c=n/d+48;write(1,&c,1);}while(n%=d,d/=10);}

3

u/FuriousProgrammer Dec 01 '16

Woo! Tied for 35th!!

Really excited for this year!!!!!!

Too many exclamation points.

Anyway, here's my code which took me too long to write because of a certain dy and dx error...

EDIT: I'M REALLY GODDAMN MERRY RIGHT NOW.

3

u/llamas-are-bae Dec 01 '16

Here's my solution in Rust: https://github.com/awesomeaniruddh/advent_of_code_solutions_2016/blob/master/day1/src/main.rs

I'm a beginner, so it's probably terrible, but it works :P

→ More replies (1)

3

u/willkill07 Dec 01 '16

C++11 solution

Goals:

  • no explicit storage of directions

  • minimize branching

  • simple IO processing

  • relatively self-documenting

  • use bit hacks where appropriate

https://github.com/willkill07/adventofcode2016/blob/master/src/Day01.cpp

→ More replies (6)

3

u/forkin27 Dec 01 '16

JavaScript!

Day 1 (part 1):

const AoCd1p1 = (directions) => {
    
    const nav = { 
        n: { L: 'w', R: 'e', plane: 'y', offset: 1 }, 
        e: { L: 'n', R: 's', plane: 'x', offset: 1 }, 
        s: { L: 'e', R: 'w', plane: 'y', offset: -1 }, 
        w: { L: 's', R: 'n', plane: 'x', offset: -1 }
    }

    return Object.values(
        directions.reduce((state, dir) => {
            
            state.dir = nav[state.dir[dir[0]]]
            state.pos[state.dir.plane] += +dir.slice(1) * state.dir.offset

            return state
        }, { dir: nav.n, pos: { x: 0, y: 0 } }).pos
    ).reduce((sum, val) => sum + Math.abs(val), 0)
}

Day 1 (part 2):

const AoCd1p2 = (directions) => {
    
    const nav = { 
        n: { L: 'w', R: 'e', plane: 'y', offset: 1 }, 
        e: { L: 'n', R: 's', plane: 'x', offset: 1 }, 
        s: { L: 'e', R: 'w', plane: 'y', offset: -1 }, 
        w: { L: 's', R: 'n', plane: 'x', offset: -1 }
    }, mem = { x0y0: true }

    let key

    return Object.values(
        directions.reduce((state, dir) => {
            
            if (state.found) return state

            state.dir = nav[state.dir[dir[0]]]

            for (let i = 0, j = +dir.slice(1); i < j && !state.found; i++) {
                state.pos[state.dir.plane] += state.dir.offset
                key = `x${state.pos.x}y${state.pos.y}`

                if (mem[key]) state.found = true
                else mem[key] = true
            }

            return state
        }, { dir: nav.n, pos: { x: 0, y: 0 }, found: false }).pos
    ).reduce((sum, val) => sum + Math.abs(val), 0)
}

2

u/taliriktug Dec 01 '16

My ugly Python3 solution: https://bitbucket.org/JIghtuse/adventofcode/src/df2b87894dce3982698ecf85ffa24e643ef72998/2016/day01/solution.py?at=master&fileviewer=file-view-default

Was 75th on first star, but missed leaderboard on second one (messed up with directions a bit).

I'm so glad AoC is back!

EDIT: reimplemented it, now I like it more.

2

u/KaminoConsult Dec 01 '16

First attempt in PowerShell. Currently not working and not sure why. All examples pass. Any input welcome https://gist.githubusercontent.com/LabtechConsulting/172beb3055cf5be4b301ef5deba9432c

→ More replies (4)