r/adventofcode • • Dec 03 '16

SOLUTION MEGATHREAD --- 2016 Day 3 Solutions ---

--- Day 3: Squares With Three Sides ---

Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/whatever).


DECKING THE HALLS WITH BOUGHS OF HOLLY IS MANDATORY [?]

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!

17 Upvotes

234 comments sorted by

View all comments

2

u/QshelTier Dec 03 '16

Here’s my take on the problem in Kotlin:

fun main(args: Array<String>) {
	println(first())
	println(second())
}

fun first() = countValidTriangles()

fun second() = countValidTriangles {
	it.fold(FoldResult(emptyList(), emptyList(), emptyList(), emptyList())) { oldFoldResult, columns ->
		getNewFoldResult(oldFoldResult, columns[0], columns[1], columns[2])
	}.results
}

private fun countValidTriangles(triangleProcessor: (List<List<Int>>) -> List<List<Int>> = { it }): Int = getInput(3)
		.map(String::trim)
		.map { it.replace("  *".toRegex(), " ") }
		.map { it.split(" ") }
		.map { it.map(String::toInt) }
		.let { triangleProcessor.invoke(it) }
		.map { it.sorted() }
		.filter { it[0] + it[1] > it[2] }
		.count()

fun getNewFoldResult(oldFoldResult: FoldResult, first: Int, second: Int, third: Int): FoldResult =
		oldFoldResult.run {
			if (firstColumn.size < 2) {
				FoldResult(results, firstColumn + first, secondColumn + second, thirdColumn + third)
			} else {
				FoldResult(results + listOf(firstColumn + first, secondColumn + second, thirdColumn + third), emptyList(), emptyList(), emptyList())
			}
		}

data class FoldResult(val results: List<List<Int>>, val firstColumn: List<Int>, val secondColumn: List<Int>, val thirdColumn: List<Int>)

class Day3

fun getInput(day: Int) = Day3::class.java.getResourceAsStream("day$day.txt")
		.reader()
		.readLines()