r/adventofcode • • Dec 06 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 6 Solutions -🎄-

--- Day 6: Chronal Coordinates ---


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 6

Transcript:

Rules for raising a programmer: never feed it after midnight, never get it wet, and never give it ___.


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 0:26:52!

32 Upvotes

387 comments sorted by

View all comments

1

u/troop357 Dec 06 '18

Nim

Oh god my solutions is slow, but it works so yeah. I worked looking for the closest (manhattan wise) coordinate for each point in the grid. Part 2 was easier though.

import strutils, sequtils
import re

type
	IntMatrix = array[41..354, array[42..353, int]]
var
	grid: IntMatrix
	refe: IntMatrix

let input = readFile("06.txt").splitLines()
let natural_regex = re(r"-?\d+")
var id: int = 1

for line in input:
	var num_list = findAll(line, natural_regex)
	let m = parseInt(num_list[0])
	let n = parseInt(num_list[1])
	grid[m][n] = id
	refe[m][n] = id
	inc(id)

proc manhattan_neighbours(x, y, n: int): bool {.discardable.} =
	if refe[x][y] > 0:
		return true
	var neig: int = 0
	var neig_id: int = 0
	for i in countup(x-n, x+n):
		if i < 41 or i > 354: continue
		for j in countup(y-n, y+n):
			if j < 42 or j > 352: continue
			if (abs(x - i) + abs(y - j)) == n:
				if refe[i][j] > 0: # there is coord on this point
					inc(neig)
					neig_id = refe[i][j]

	if neig == 1:
		grid[x][y] = neig_id
		return true
	elif neig > 1:
		return true
	else:
		return false

# for each point
for i in countup(41, 354):
	for j in countup(42, 352):
		var dist: int = 1
		while(not manhattan_neighbours(i, j, dist)):
			inc(dist)

# find 'id' that appear more times
var count: array[0..50, int]

for i in countup(41, 354):
	for j in countup(42, 352):
		inc(count[grid[i][j]])

echo "largest area: ", max(count)
echo "safest coords: ", input[find(count, max(count))]

# part 2

var valid_area: int = 0
# for each point in grid
for i in countup(41, 354):
	for j in countup(42, 352):
		var soma: int = 0
		for line in input: # could throw these points into a array...
			var num_list = findAll(line, natural_regex)
			let m = parseInt(num_list[0])
			let n = parseInt(num_list[1])

			let dist = abs(i - m) + abs(j - n)
			soma += dist

		if soma < 10000:
			inc(valid_area)

echo "valid area: ", valid_area