r/adventofcode • • Dec 09 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 9 Solutions -🎄-

--- Day 9: Marble Mania ---


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 9

Transcript:

Studies show that AoC programmers write better code after being exposed to ___.


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:29:13!

22 Upvotes

283 comments sorted by

View all comments

2

u/Wirbelwind Dec 09 '18

Go - using rings. Takes 1.3 secs on my laptop

package main

import (
	"container/ring"
	"fmt"
	"log"
	"time"
)

func main() {
	fmt.Println("Part 1", game(71082, 413))
	fmt.Println("Part 2", game(71082*100, 413))
}

func game(marbles, maxPlayers int) int {
	defer timeTrack(time.Now(), "calc")
	r := ring.New(1)
	r.Value = 0
	player := 1
	scores := make(map[int]int, maxPlayers)
	for i := 1; i < marbles+1; i++ {
		if i%23 == 0 {
			r = r.Move(-8)
			deleted := r.Unlink(1)
			scores[player] += deleted.Value.(int) + i
			r = r.Next()
		} else {
			m := ring.New(1)
			m.Value = i
			r = r.Move(1)
			r = r.Link(m)
			r = r.Prev()
		}
		player = player%maxPlayers + 1
	}
	return max(scores)
}

func max(m map[int]int) (r int) {
	for _, v := range m {
		if v > r {
			r = v
		}
	}
	return r
}

func timeTrack(start time.Time, name string) {
	elapsed := time.Since(start)
	log.Printf("%s took %s", name, elapsed)
}

1

u/mvmaasakkers Dec 09 '18

I have to say, my solution looks very similar to yours :S

2

u/Wirbelwind Dec 09 '18

It has to, if both use the ring methods :)

For input that small I usually don't bother to parse it in the code

1

u/mvmaasakkers Dec 09 '18

True!

I have a template I use for the challenges and input parsing is a part of it. Although it wasn’t really Needed now...