r/adventofcode • • Dec 04 '18

SOLUTION MEGATHREAD -πŸŽ„- 2018 Day 4 Solutions -πŸŽ„-

--- Day 4: Repose Record ---


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 4

Transcript:

Today’s puzzle would have been a lot easier if my language supported ___.


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!

39 Upvotes

340 comments sorted by

View all comments

1

u/skarlso Dec 04 '18 edited Dec 05 '18

I actually managed to get a pretty decent run time with some math and some thinking. :)

Solution in Go (golang):

❯ time ./part1/main input.txt
95199
./part1/main input.txt  0.01s user 0.00s system 87% cpu 0.010 total
package main

import (
	"fmt"
	"io/ioutil"
	"math"
	"os"
	"strings"
)

func main() {
	filename := os.Args[1]
	content, _ := ioutil.ReadFile(filename)
	lines := strings.Split(string(content), "\n")
	guards := make(map[int][]int, 0)
	mostAsleep := make(map[int]int)
	var year, month, day, hour, minute, id int
	for _, l := range lines {
		if strings.Contains(l, "begins shift") {
			fmt.Sscanf(l, "[%d-%d-%d %d:%d] Guard #%d begins shift", &year, &month, &day, &hour, &minute, &id)
			if _, ok := guards[id]; !ok {
				guards[id] = make([]int, 59)
			}
		}
		if strings.Contains(l, "falls asleep") {
			fmt.Sscanf(l, "[%d-%d-%d %d:%d] falls asleep", &year, &month, &day, &hour, &minute)
		}
		if strings.Contains(l, "wakes up") {
			sleptFrom := minute
			fmt.Sscanf(l, "[%d-%d-%d %d:%d] wakes up", &year, &month, &day, &hour, &minute)
			diff := int(math.Abs(float64(sleptFrom) - float64(minute)))
			for i := 0; i < diff; i++ {
				index := (sleptFrom + i) % 60
				guards[id][index]++
			}
			mostAsleep[id] += diff
		}
	}

	max := 0
	maxID := 0
	for k, v := range mostAsleep {
		if v > max {
			max = v
			maxID = k
		}
	}

	mostDays := 0
	mostDaysIndex := 0
	for i, v := range guards[maxID] {
		if v > mostDays {
			mostDays = v
			mostDaysIndex = i
		}
	}

	fmt.Println(maxID * mostDaysIndex)
}

This is based on the fact that after a sleep there is always a wakeup. I don't really like the max finding at the end but I'm tired and can't bother to refactor it. :)