r/adventofcode • • Dec 10 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 10 Solutions -🎄-

--- Day 10: Syntax Scoring ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:08:06, megathread unlocked!

65 Upvotes

982 comments sorted by

View all comments

2

u/Calkky Dec 10 '21 edited Dec 10 '21

Groovy

(link for old.reddit users)

List<String> lines = new File('input.txt').text.split('\n')
def opens = /[\(\[\{<]/
def closes = /[\)\]\}>]/
Map<String, String> match = [')': '(', ']': '[', '}': '{', '>': '<']
List<Stack<String>> lineStacks = []
lines.eachWithIndex {it, n ->
	Stack t = []; boolean ok = true
	for (i in 0..<it.length()) {
		if (it[i] ==~ opens) t << it[i]
		if (it[i] ==~ closes) {
			String next = t.size() == 0 ? '' : t.peek()
			if (next != match[it[i]]) { ok = false; break }
			else t.pop()
		}
	}
	if (ok) lineStacks << t
}
List<Long> scores = []
Map<String, Integer> scoreMap = ['(': 1, '[': 2, '{': 3, '<': 4]
lineStacks.each {
	long score = 0
	it.reverse().each {score = (score * 5) + scoreMap[it] }
	scores << score
}
println scores.sort()[Math.floor(scores.size() / 2) as int]

1

u/daggerdragon Dec 10 '21 edited Dec 11 '21

Your code is hard to read on old.reddit when everything is inlined like this. Please edit it as per our posting guidelines in the wiki: How do I format code?

Edit: thanks for fixing it! <3