r/adventofcode • • Dec 08 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 8 Solutions -🎄-

--- Day 8: Memory Maneuver ---


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

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 8

Sigh, imgur broke again. Will upload when it unborks.

Transcript:

The hottest programming book this year is "___ For Dummies".


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 at 00:12:10!

32 Upvotes

301 comments sorted by

View all comments

1

u/alcinos Dec 09 '18

Ocaml Another solution heavily exploiting the nice recursive structure

type node = {
  children : node list;
  metadata : int list;
  };;

let rec parse_metadata = function
  | 0 -> []
  | n -> try let a = Scanf.scanf " %d" (fun x -> x) in
      a :: (parse_metadata (n-1))
    with e -> Printf.printf "failed to parse metadata"; raise e;;

let rec parse_node =  function
  |0 -> []
  |n -> try let nbChildren, nbMetadata = Scanf.scanf " %d %d" (fun x y -> (x,y)) in
      let children = parse_node nbChildren in
      let meta = parse_metadata nbMetadata in
      {children = children; metadata = meta} :: (parse_node (n-1))
  with e -> Printf.printf "failed to parse node"; raise e;;

let rec sum_metadata = function
  |[] -> 0
  | a::r -> (List.fold_left (+) 0 a.metadata) + (sum_metadata a.children) + (sum_metadata r);;

let rec value_node = function
  | n when (List.length n.children) == 0 -> List.fold_left (+) 0 n.metadata
  | n ->
    List.fold_left (fun old id -> old + (if id <= (List.length n.children) then (value_node (List.nth n.children (id - 1))) else 0)) 0 n.metadata;;

let nodes = parse_node 1;;

Printf.printf "meta sum = %d\n" (sum_metadata nodes);;
Printf.printf "value = %d\n" (value_node (List.hd nodes));;

1

u/Fletch_to_99 Dec 14 '18

Awesome job! I've been trying to solve this solution in OCaml (my first time ever touching the language) and have really been struggling. I was wondering if you could take a look at what I've got. I'd sent you a chat message via reddit :)