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

1

u/philpearl Dec 09 '18

Go (golang). Both parts run in ~95 ms. linked list, but all marbles allocated as a single slice, and int32 for next/prev

package main

import "fmt"

func main() {
	run(477, 70851)
	run(477, 7085100)
}

func run(numPlayers, lastMarble int) {

	players := make([]int, numPlayers)
	marbles := make(marbles, lastMarble+1)
	currentPlayer := -1

	currentMarble := &marbles[0]
	for marbleNum := 1; marbleNum <= lastMarble; marbleNum++ {
		currentPlayer++
		if currentPlayer >= len(players) {
			currentPlayer = 0
		}

		// printMarbles(currentMarble)

		if marbleNum%23 == 0 {
			players[currentPlayer] += int(marbleNum)
			for i := 0; i < 6; i++ {
				currentMarble = &marbles[currentMarble.prev]
			}
			players[currentPlayer] += int(currentMarble.prev)
			marbles.remove(currentMarble.prev)
			continue
		}

		marbles.insertAfter(currentMarble.next, int32(marbleNum))
		currentMarble = &marbles[marbleNum]
	}

	var highScore int
	for _, score := range players {
		if score > highScore {
			highScore = score
		}
	}

	fmt.Println(highScore)
}

func (mm marbles) printMarbles(m int32) {
	fmt.Printf("%d ", m)
	for c := mm[m].next; c != m; c = mm[c].next {
		fmt.Printf("%d ", c)
	}
	fmt.Println()
}

type marble struct {
	next, prev int32
}

type marbles []marble

func (mm marbles) insertAfter(current, newm int32) {
	cm := &mm[current]
	nm := &mm[newm]
	nm.next = cm.next
	nm.prev = current
	mm[cm.next].prev = newm
	cm.next = newm
}

func (mm marbles) remove(mv int32) {
	m := &mm[mv]
	mm[m.prev].next = m.next
	mm[m.next].prev = m.prev
}