path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day08.kt
jorander
571,715,475
false
{"Kotlin": 28471}
typealias Trees = Grid2D<Char> typealias TreePosition = Position2D typealias Direction = (TreePosition, Trees) -> List<TreePosition> fun main() { val day = "Day08" val up: Direction = { tp: TreePosition, _: Trees -> (0 until tp.y).map { TreePosition(tp.x, it) }.reversed() } val down: Direction = { tp: TreePosition, trees: Trees -> (tp.y + 1 until trees.height).map { TreePosition(tp.x, it) } } val left: Direction = { tp: TreePosition, _: Trees -> (0 until tp.x).map { TreePosition(it, tp.y) }.reversed() } val right: Direction = { tp: TreePosition, trees: Trees -> (tp.x + 1 until trees.width).map { TreePosition(it, tp.y) } } val directions = listOf(up, down, left, right) fun part1(input: List<String>): Int { val trees = Trees.from(input) fun TreePosition.canBeSeenFrom(direction: Direction) = direction(this, trees).none { (trees[this]) <= trees[it] } fun TreePosition.isVisibleFromAnyDirection() = directions.any { this.canBeSeenFrom(it) } fun TreePosition.isOnOuterEdge() = isOnOuterEdgeIn(trees) fun Trees.numberOfTreesOnOuterEdge() = allPositions.filter { it.isOnOuterEdge() }.size return (trees.allPositions .filter { !it.isOnOuterEdge() } .count { it.isVisibleFromAnyDirection() } + trees.numberOfTreesOnOuterEdge()) } fun part2(input: List<String>): Int { val trees = Trees.from(input) fun List<TreePosition>.thatCanBeSeenFrom(treePosition: TreePosition): Int { fun addViewOfTreeThatCantBeSeenPassed(numberOfLowerTreesCounted: Int) = if (isNotEmpty() && numberOfLowerTreesCounted < size) 1 else 0 return takeWhile { (trees[treePosition] > trees[it]) } .count().let { it + addViewOfTreeThatCantBeSeenPassed(it) } } fun TreePosition.numberOfTreesInViewPerDirection() = directions.map { direction -> val treesInDirection = direction(this, trees) treesInDirection.thatCanBeSeenFrom(this) } fun TreePosition.scenicValue() = numberOfTreesInViewPerDirection() .reduce(Int::times) return trees.allPositions .maxOf { it.scenicValue() } } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 21) val result1 = part1(input) println(result1) check(result1 == 1717) check(part2(testInput) == 8) val result2 = part2(input) println(result2) check(result2 == 321975) }
0
Kotlin
0
0
1681218293cce611b2c0467924e4c0207f47e00c
2,709
advent-of-code-2022
Apache License 2.0
src/main/kotlin/be/inniger/euler/problems01to10/Problem05.kt
bram-inniger
135,620,989
false
{"Kotlin": 20003}
package be.inniger.euler.problems01to10 import be.inniger.euler.util.EratosthenesSieve import be.inniger.euler.util.pow private const val MAX_VALUE = 20 /** * Smallest multiple * * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? */ fun solve05() = (1..MAX_VALUE) // Iterate over all numbers from 1 to 20 .flatMap { number -> primes.map { prime -> Factor(prime, getFrequency(number, prime)) } // Decompose every number into its Factors .filter { factor -> factor.frequency > 0 } // Remove all the Factors that never occur (frequency = 0) } .groupingBy { it.prime } // Group all these Factors by prime .reduce { _, acc, factor -> maxOf(acc, factor, compareBy(Factor::frequency)) } // Per prime pick the factor with the highest frequency .map { it.value } // Map the Map.Entry<Int, Factor> back onto Factor .map { pow(it.prime, it.frequency) } // Get the power of each prime factor back with its frequency .reduce { acc, factor -> factor * acc } // Make the product of all these powers to get the smallest number evenly divisible by all numbers private val primes = EratosthenesSieve(MAX_VALUE).getPrimes() // Pre-calculate all potential prime factors up until 20 /** * Calculate how many times a given prime "fits" in a number. * Start by checking if it fits once, twice, thrice, ... * The first time "nr times it fits + 1" does not fit any more, then the answer is found! */ private fun getFrequency(number: Int, prime: Int) = generateSequence(1, Int::inc) .first { number % pow(prime, it + 1) != 0 } /** * Store which prime occurred how many times in a number. */ private data class Factor(val prime: Int, val frequency: Int)
0
Kotlin
0
0
8fea594f1b5081a824d829d795ae53ef5531088c
1,866
euler-kotlin
MIT License
src/Day08.kt
sebastian-heeschen
572,932,813
false
{"Kotlin": 17461}
fun main() { fun plantTrees(input: List<String>) = input .map { line -> line.map { it.digitToInt() } } .let { grid -> grid.flatMapIndexed { y: Int, row: List<Int> -> row.mapIndexed { x, height -> Tree( x = x, y = y, height = height, allToTheLeft = (0 until x).map { grid[y][it] }, allToTheTop = (0 until y).map { grid[it][x] }, allToTheRight = (x + 1 until row.size).map { grid[y][it] }, allToTheBottom = (y + 1 until grid.size).map { grid[it][x] } ) } } } fun part1(input: List<String>): Int { val side = plantTrees(input) .filter { tree -> listOf(tree.allToTheLeft, tree.allToTheTop, tree.allToTheRight, tree.allToTheBottom) .any { side -> side.all { it < tree.height } || side.isEmpty() } } return side.size } fun part2(input: List<String>): Int { val scores = plantTrees(input).map { tree -> listOf(tree.allToTheLeft.reversed(), tree.allToTheTop.reversed(), tree.allToTheRight, tree.allToTheBottom) .map { side -> side.indexOfFirst { it >= tree.height }.takeIf { it != -1 }?.let { it + 1 } ?: side.size } .fold(1, Int::times) } return scores.max() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) } data class Tree( val x: Int, val y: Int, val height: Int, val allToTheLeft: List<Int>, val allToTheTop: List<Int>, val allToTheRight: List<Int>, val allToTheBottom: List<Int>, )
0
Kotlin
0
0
4432581c8d9c27852ac217921896d19781f98947
2,031
advent-of-code-2022
Apache License 2.0
src/Day02.kt
Soykaa
576,055,206
false
{"Kotlin": 14045}
private fun moveToPoints(move: String): Int = when (move) { "A", "X" -> 1 "B", "Y" -> 2 "C", "Z" -> 3 else -> 0 } private fun resToPoints(gameResult: String): Int = when (gameResult) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> 0 } private fun currentResult(gameMove: List<Int>): Int = if (gameMove[0] == gameMove[1]) 3 else if ((gameMove[0] == 2 && gameMove[1] == 1) || (gameMove[0] == 3 && gameMove[1] == 2) || (gameMove[0] == 1 && gameMove[1] == 3) ) { 0 } else { 6 } private fun findSolution(gameMove: List<String>): String = if ((gameMove[1] == "X" && gameMove[0] == "A") || (gameMove[1] == "Z" && gameMove[0] == "B")) { "C" } else if ((gameMove[1] == "X" && gameMove[0] == "B") || (gameMove[1] == "Z" && gameMove[0] == "C")) { "A" } else if ((gameMove[1] == "X" && gameMove[0] == "C") || (gameMove[1] == "Z" && gameMove[0] == "A")) { "B" } else { gameMove[0] } fun main() { fun part1(input: List<String>): Int = input .map { i -> i.split("\\s".toRegex()).toTypedArray().map { moveToPoints(it) } } .sumOf { currentResult(it) + it[1] } fun part2(input: List<String>): Int { var gameSum = 0 for (i in input) { val gameMove = i.split("\\s".toRegex()).toTypedArray() val ourChoice = findSolution(gameMove.toList()) gameSum += resToPoints(gameMove[1]) + moveToPoints(ourChoice) } return gameSum } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1e30571c475da4db99e5643933c5341aa6c72c59
1,576
advent-of-kotlin-2022
Apache License 2.0
src/Day08.kt
ty-garside
573,030,387
false
{"Kotlin": 75779}
// Day 08 - Treetop Tree House // https://adventofcode.com/2022/day/8 import Direction.* fun main() { data class Tree( val row: Int, val column: Int, val height: Int ) class Trees(input: List<String>) { private val trees = input.mapIndexed { row, line -> line.mapIndexed { col, ch -> Tree(row, col, ch - '0') } } val rows = trees.size val cols = trees[0].size operator fun get(row: Int, col: Int) = trees[row][col] fun all() = sequence { for (row in 0 until rows) { for (col in 0 until cols) { yield(trees[row][col]) } } } fun look(tree: Tree, direction: Direction) = sequence { with(tree) { when (direction) { Up -> for (r in row - 1 downTo 0) { yield(trees[r][column]) } Down -> for (r in row + 1 until rows) { yield(trees[r][column]) } Left -> for (c in column - 1 downTo 0) { yield(trees[row][c]) } Right -> for (c in column + 1 until cols) { yield(trees[row][c]) } } } } } val dirs = Direction.values().asSequence() fun part1(input: List<String>): Int { with(Trees(input)) { return all().count { tree -> // is visible? dirs.filter { dir -> look(tree, dir) .firstOrNull { it.height >= tree.height } == null }.firstOrNull() != null } } } fun part2(input: List<String>): Int { with(Trees(input)) { return all().maxOf { tree -> // scenic score dirs.map { dir -> var seen = 0 look(tree, dir) .onEach { seen++ } .firstOrNull { it.height >= tree.height } seen }.reduce(Math::multiplyExact) } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) val input = readInput("Day08") println(part1(input)) println(part2(input)) } /* --- Day 8: Treetop Tree House --- The expedition comes across a peculiar patch of tall trees all planted carefully in a grid. The Elves explain that a previous expedition planted these trees as a reforestation effort. Now, they're curious if this would be a good location for a tree house. First, determine whether there is enough tree cover here to keep a tree house hidden. To do this, you need to count the number of trees that are visible from outside the grid when looking directly along a row or column. The Elves have already launched a quadcopter to generate a map with the height of each tree (your puzzle input). For example: 30373 25512 65332 33549 35390 Each tree is represented as a single digit whose value is its height, where 0 is the shortest and 9 is the tallest. A tree is visible if all of the other trees between it and an edge of the grid are shorter than it. Only consider trees in the same row or column; that is, only look up, down, left, or right from any given tree. All of the trees around the edge of the grid are visible - since they are already on the edge, there are no trees to block the view. In this example, that only leaves the interior nine trees to consider: The top-left 5 is visible from the left and top. (It isn't visible from the right or bottom since other trees of height 5 are in the way.) The top-middle 5 is visible from the top and right. The top-right 1 is not visible from any direction; for it to be visible, there would need to only be trees of height 0 between it and an edge. The left-middle 5 is visible, but only from the right. The center 3 is not visible from any direction; for it to be visible, there would need to be only trees of at most height 2 between it and an edge. The right-middle 3 is visible from the right. In the bottom row, the middle 5 is visible, but the 3 and 4 are not. With 16 trees visible on the edge and another 5 visible in the interior, a total of 21 trees are visible in this arrangement. Consider your map; how many trees are visible from outside the grid? Your puzzle answer was 1787. --- Part Two --- Content with the amount of tree cover available, the Elves just need to know the best spot to build their tree house: they would like to be able to see a lot of trees. To measure the viewing distance from a given tree, look up, down, left, and right from that tree; stop if you reach an edge or at the first tree that is the same height or taller than the tree under consideration. (If a tree is right on the edge, at least one of its viewing distances will be zero.) The Elves don't care about distant trees taller than those found by the rules above; the proposed tree house has large eaves to keep it dry, so they wouldn't be able to see higher than the tree house anyway. In the example above, consider the middle 5 in the second row: 30373 25512 65332 33549 35390 Looking up, its view is not blocked; it can see 1 tree (of height 3). Looking left, its view is blocked immediately; it can see only 1 tree (of height 5, right next to it). Looking right, its view is not blocked; it can see 2 trees. Looking down, its view is blocked eventually; it can see 2 trees (one of height 3, then the tree of height 5 that blocks its view). A tree's scenic score is found by multiplying together its viewing distance in each of the four directions. For this tree, this is 4 (found by multiplying 1 * 1 * 2 * 2). However, you can do even better: consider the tree of height 5 in the middle of the fourth row: 30373 25512 65332 33549 35390 Looking up, its view is blocked at 2 trees (by another tree with a height of 5). Looking left, its view is not blocked; it can see 2 trees. Looking down, its view is also not blocked; it can see 1 tree. Looking right, its view is blocked at 2 trees (by a massive tree of height 9). This tree's scenic score is 8 (2 * 2 * 1 * 2); this is the ideal spot for the tree house. Consider each tree on your map. What is the highest scenic score possible for any tree? Your puzzle answer was 440640. Both parts of this puzzle are complete! They provide two gold stars: ** */
0
Kotlin
0
0
49ea6e3ad385b592867676766dafc48625568867
6,718
aoc-2022-in-kotlin
Apache License 2.0
src/Day07.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
import kotlin.math.min fun main() { val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val rootNode = buildTree(input) return sumDirectories(rootNode) } private fun part2(input: List<String>): Int { val rootNode = buildTree(input) val missingSpace = 30_000_000 - (70_000_000 - rootNode.totalSize) return findMinimumRequiredDirectorySize(rootNode, missingSpace) } private fun sumDirectories(node: Directory): Int { val dirSize = node.totalSize.takeIf { it < 100_000 } ?: 0 return dirSize + node.directories.sumOf(::sumDirectories) } private fun findMinimumRequiredDirectorySize(node: Directory, missingSpace: Int): Int { val dirSize = node.totalSize.takeIf { it >= missingSpace } ?: Int.MAX_VALUE val subDirSize = node.directories .ifEmpty { return dirSize } .minOf { findMinimumRequiredDirectorySize(it, missingSpace) } return min(dirSize, subDirSize) } private fun buildTree(input: List<String>): Directory { val root = Directory(name = "/", parent = null) var currentDir = root input.forEach { line -> val parts = line.split(" ") when (parts[0]) { "$" -> when (parts[1]) { "ls" -> Unit "cd" -> currentDir = when (parts[2]) { "/" -> root ".." -> currentDir.parent ?: root else -> currentDir.directories.first { it.name == parts[2] } } } "dir" -> currentDir.children += Directory(name = parts[1], parent = currentDir) else -> currentDir.children += File(name = parts[1], size = parts[0].toInt(), parent = currentDir) } } return root } private sealed class Node(open val name: String, open val parent: Directory?) { val totalSize: Int by lazy { when (this) { is File -> size is Directory -> children.sumOf(Node::totalSize) } } } private data class File(override val name: String, override val parent: Directory?, val size: Int) : Node(name, parent) private data class Directory(override val name: String, override val parent: Directory?, val children: MutableList<Node> = mutableListOf()) : Node(name, parent) { val directories by lazy { children.filterIsInstance<Directory>() } }
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
2,502
aoc-22
Apache License 2.0
src/main/kotlin/Day4.kt
Filipe3xF
433,908,642
false
{"Kotlin": 30093}
import utils.Day fun main() = Day(4, ::extractBingo, { it.play().let { (lastNumberCalled, winningBoard) -> winningBoard.calculateScore(lastNumberCalled) } }, { it.playLastManStanding() .let { (lastNumberCalled, winningBoard) -> winningBoard.calculateScore(lastNumberCalled) } } ).printResult() fun extractBingo(input: List<String>): Bingo { val bingoNumbers = extractBingoNumbers(input) val bingoBoards = extractBingoBoards(input) return Bingo(bingoNumbers, bingoBoards) } fun extractBingoNumbers(input: List<String>): List<Int> = input[0].split(",").map { it.toInt() } fun extractBingoBoards(input: List<String>): List<BingoBoard> = input.asSequence() .drop(1) .filter { it.isNotBlank() } .map { line -> line.split(" ").filter { it.isNotBlank() }.map { BingoBoardNumber(it.toInt()) } } .chunked(5) .map { BingoBoard(it) }.toList() data class Bingo(val numbers: List<Int>, val boards: List<BingoBoard>) { fun play(): Pair<Int, BingoBoard> { numbers.forEach { number -> boards.forEach { it.mark(number) } boards.find { it.hasBingo() }?.let { return number to it } } return numbers.last() to boards.last() } fun playLastManStanding(): Pair<Int, BingoBoard> { val playingBoards: MutableList<BingoBoard> = boards.toMutableList() numbers.forEach { number -> playingBoards.forEach { it.mark(number) } val boardsWithBingo = playingBoards.filter { it.hasBingo() } playingBoards.removeAll(boardsWithBingo) if (playingBoards.isEmpty()) return number to boardsWithBingo.last() } return numbers.last() to boards.last() } } data class BingoBoard(val lines: List<List<BingoBoardNumber>>) { fun mark(number: Int) { lines.forEach { line -> line.filter { it.value == number }.onEach { it.marked = true } } } fun hasBingo(): Boolean = hasBingoInLines() || hasBingoInColumns() fun hasBingoInLines(): Boolean = lines.doesAnyLineHaveBingo() fun hasBingoInColumns(): Boolean = lines.transpose().doesAnyLineHaveBingo() fun calculateScore(number: Int): Int = if (hasBingo()) lines.sumOf { line -> line.filter { !it.marked }.sumOf { it.value } } * number else 0 companion object { fun List<List<BingoBoardNumber>>.doesAnyLineHaveBingo() = any { line -> line.all { it.marked } } } } data class BingoBoardNumber(val value: Int, var marked: Boolean = false) fun <T> List<List<T>>.transpose(): List<List<T>> { require(all { it.size == first().size }) return first().indices.map { index -> map { it[index] } } }
0
Kotlin
0
1
7df9d17f0ac2b1c103b5618ca676b5a20eb43408
2,769
advent-of-code-2021
MIT License
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day04/Day04.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.aoc2021.day04 import nl.sanderp.aoc.common.measureDuration import nl.sanderp.aoc.common.prettyPrint import nl.sanderp.aoc.common.readResource fun main() { val (numbers, boards) = parse(readResource("Day04.txt").lines()) val (answer1, duration1) = measureDuration<Int> { partOne(numbers, boards) } println("Part one: $answer1 (took ${duration1.prettyPrint()})") val (answer2, duration2) = measureDuration<Int> { partTwo(numbers, boards) } println("Part two: $answer2 (took ${duration2.prettyPrint()})") } private fun parse(input: List<String>): Pair<List<Int>, List<Board>> { val numbers = input.first().split(",").map { it.toInt() } val boards = input.drop(1).chunked(6).map { lines -> Board(lines.drop(1).map { l -> l.split(" ").filterNot { it == "" }.map { it.toInt() } }) } return numbers to boards } class Board(numbers: List<List<Int>>) { private val rows = numbers.map { row -> row.map { it to false }.toTypedArray() }.toTypedArray() private val cols get() = rows.indices.map { i -> rows.indices.map { j -> rows[j][i] } } val unmarked get() = rows.flatMap { row -> row.filterNot { it.second } }.map { it.first } fun mark(number: Int): Boolean { for (i in rows.indices) { for (j in rows[i].indices) { if (rows[i][j].first == number) { rows[i][j] = number to true } } } return rows.any { row -> row.all { it.second } } || cols.any { col -> col.all { it.second }} } } private fun partOne(numbers: List<Int>, boards: List<Board>): Int { for (number in numbers) { for (board in boards) { if (board.mark(number)) { return board.unmarked.sum() * number } } } return -1 } private fun partTwo(numbers: List<Int>, boards: List<Board>): Int { val playing = boards.toMutableList() for (number in numbers) { val wonRound = mutableListOf<Board>() for (board in playing) { if (board.mark(number)) { if (playing.size - wonRound.size == 1) { return board.unmarked.sum() * number } wonRound.add(board) } } playing.removeAll(wonRound) } return -1 }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
2,362
advent-of-code
MIT License
src/main/kotlin/day8/CrossedWires.kt
Arch-vile
433,381,878
false
{"Kotlin": 57129}
package day8 import utils.permutations import utils.read import utils.sort data class SegmentData(val input: List<String>, val output: List<String>) fun main() { solve() .let { println(it) } } const val allSegments = "abcdefg" const val zero = "abcefg" const val one = "cf" const val two = "acdeg" const val three = "acdfg" const val four = "bcdf" const val five = "abdfg" const val six = "abdefg" const val seven = "acf" const val eight = "abcdefg" const val nine = "abcdfg" val allNumbers = listOf(zero, one, two, three, four, five, six, seven, eight, nine) fun solve(): List<Int> { return listOf(solvePart1(), solvePart2()) } fun solvePart2(): Int { var readings = read("./src/main/resources/day8Input.txt") .map { it.split(" | ") } .map { SegmentData( it[0].split(" ").map { sort(it) }, it[1].split(" ").map { sort(it) }) } val decodeKeyCandidates = permutations(allSegments.toSet()) val decodedOutputs = readings.map { decodeOutput(decodeKeyCandidates, it) } val asNumbers = decodedOutputs.map { it.map { allNumbers.indexOf(it) }.joinToString("").toInt() } return asNumbers.sum() } fun decodeOutput(decoders: Set<List<Char>>, reading: SegmentData): List<String> { val correctDecoder = decoders.first { decoder -> val decodedInput = reading.input.map { messedNumber -> decode(messedNumber, decoder) } decodedInput.containsAll(allNumbers) } return reading.output.map { decode(it, correctDecoder) } } private fun decode( messedNumber: String, decoder: List<Char> ) = sort( messedNumber .replace(decoder[0], 'A') .replace(decoder[1], 'B') .replace(decoder[2], 'C') .replace(decoder[3], 'D') .replace(decoder[4], 'E') .replace(decoder[5], 'F') .replace(decoder[6], 'G').toLowerCase() ) fun solvePart1(): Int { var segmentData = read("./src/main/resources/day8Input.txt") .map { it.split(" | ") } .map { SegmentData(it[0].split(" "), it[1].split(" ")) } return segmentData .map { it.output } .flatten() .filter { it.length == 7 || it.length == 4 || it.length == 3 || it.length == 2 } .count(); }
0
Kotlin
0
0
4cdafaa524a863e28067beb668a3f3e06edcef96
2,323
adventOfCode2021
Apache License 2.0
src/day16/Day16.kt
gautemo
317,316,447
false
null
package day16 import shared.getLines enum class ReadMode{ RULES, MY_TICKET, NEARBY_TICKETS } fun ticketInvalid(input: List<String>): Int{ val sections = NotesSections(input) val invalids = mutableListOf<Int>() for(ticket in sections.otherTickets){ invalids.addAll(ticket.split(',').map { it.toInt() }.filter { field -> !sections.rules.any { rule -> rule.valid(field) } }) } return invalids.sum() } class NotesSections(input: List<String>){ val rules = mutableListOf<Rule>() lateinit var myTicket: String val otherTickets = mutableListOf<String>() init { var readmode = ReadMode.RULES for(line in input){ when{ line.isBlank() -> continue line == "your ticket:" -> readmode = ReadMode.MY_TICKET line == "nearby tickets:" -> readmode = ReadMode.NEARBY_TICKETS readmode == ReadMode.MY_TICKET -> myTicket = line readmode == ReadMode.NEARBY_TICKETS -> otherTickets.add(line) else -> rules.add(Rule(line)) } } } } class Rule(line: String){ val name: String private val ranges: List<Range> init { val colonSplit = line.split(':').map { it.trim() } val rules = colonSplit[1].split("or").map { val (min, max) = it.trim().split('-').map { number -> number.toInt() } Range(min, max) } ranges = rules name = colonSplit[0] } fun valid(field: Int):Boolean{ for(range in ranges){ if(field >= range.min && field <= range.max) return true } return false } } data class Range(val min: Int, val max: Int) fun departure(input: List<String>): Long{ val sections = NotesSections(input) val possibleRules = mutableMapOf<Int, List<Rule>>() val myFields = sections.myTicket.split(',').map { it.toInt() } val validTickets = sections.otherTickets.filter { ticket -> ticket.split(',').map { it.toInt() }.all { field -> sections.rules.any { rule -> rule.valid(field) } } } for(i in myFields.indices){ val fieldsForOthers = validTickets.map { ticket -> ticket.split(',').map { it.toInt() }[i] } val matchRules = sections.rules.filter { rule -> fieldsForOthers.all { rule.valid(it) } } possibleRules[i] = matchRules } while(possibleRules.any { it.value.size != 1 }){ possibleRules.forEach { (index, rules) -> if(rules.size == 1){ for(i in myFields.indices){ if(index != i){ possibleRules[i] = possibleRules[i]!!.filter { it.name != rules[0].name } } } } } } var departure = 1L possibleRules.forEach { (index, rules) -> if(rules[0].name.startsWith("departure")){ departure *= myFields[index] } } return departure } fun main(){ val input = getLines("day16.txt") val errorRate = ticketInvalid(input) println(errorRate) val departure = departure(input) println(departure) }
0
Kotlin
0
0
ce25b091366574a130fa3d6abd3e538a414cdc3b
3,141
AdventOfCode2020
MIT License
src/main/kotlin/days/Day16.kt
mstar95
317,305,289
false
null
package days import util.groupByEmpty class Day16 : Day(16) { override fun partOne(): Any { val input = prepareInput(inputList) //println(input) val (validators, myTicket, otherTickets) = input val bad = otherTickets.flatMap { getInvalidFields(it, validators) } //println(bad) return bad.sum() } override fun partTwo(): Any { val input = prepareInput(inputList) val (validators, myTicket, otherTickets) = input val good = otherTickets.filter { validateTickets(it, validators) } val columns = collectColumns(good + listOf(myTicket)) val filter = findValidators(columns, validators) .filter { it.value.startsWith("departure") } val ticket = filter .map { myTicket[it.key] } val found = ticket .fold(1L){x,y -> x*y} println(filter) println(ticket) println(found) return found } fun findValidators(columns: List<List<Int>>, validators: List<Validator>): Map<Int, String> { val seen = mutableListOf<Validator>() return columns.mapIndexed { idx, column -> idx to validators.filter { validator -> column.all { validator.validate(it) } } }.sortedBy { it.second.size } .map { pair -> pair.first to pair.second.first { !seen.contains(it) }.also { seen.add(it) }} .map { it.first to it.second.field }.toMap() } fun getInvalidFields(ticket: List<Int>, validators: List<Validator>) = ticket.filter { number -> validators.all { !it.validate(number) } } fun validateTickets(ticket: List<Int>, validators: List<Validator>) = ticket.all { number -> validators.any { it.validate(number) } } private fun prepareInput(input: List<String>): Triple<List<Validator>, List<Int>, List<List<Int>>> { val groups: List<List<String>> = groupByEmpty(input) val validators: List<Validator> = groups[0].map { it.split(": ") }.map { val field = it[0] val ranges = it[1].split(" or ").map { f -> val splitted = f.split('-') splitted[0].toInt() to splitted[1].toInt() } Validator(field, ranges) } assert(groups[1][0] == "your ticket:") val myTicket = groups[1][1].split(",").map { it.toInt() } assert(groups[2][0] == "nearby tickets:") val otherTickets = groups[2].drop(1).map { row -> row.split(",").map { it.toString().toInt() } } return Triple(validators, myTicket, otherTickets) } private fun collectColumns(tickets: List<List<Int>>): List<List<Int>> { val rows: MutableList<MutableList<Int>> = mutableListOf() tickets[0].forEach { rows.add(mutableListOf()) } tickets.forEach { ticket -> ticket.forEachIndexed { idx, it -> rows[idx].add(it) } } return rows } } data class Validator(val field: String, val ranges: List<Pair<Int, Int>>) { fun validate(value: Int): Boolean { return ranges.any { it.first <= value && it.second >= value } } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
3,138
aoc-2020
Creative Commons Zero v1.0 Universal
2021/src/main/kotlin/Day15.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
import java.util.PriorityQueue class Day15(val input: Grid) { private fun cost(grid: Grid): Int { val dist = Array(grid.size) { Array(grid.first().size) { Int.MAX_VALUE } }.apply { this[0][0] = 0 } val toVisit = PriorityQueue<Pair<Int, Int>> { (pY, pX), (rY, rX) -> dist[pY][pX].compareTo(dist[rY][rX]) } val visited = mutableSetOf(0 to 0) toVisit.add(0 to 0) while (toVisit.isNotEmpty()) { val (y, x) = toVisit.poll().also { visited.add(it) } neighbours(y, x, grid).forEach { (nY, nX) -> if (!visited.contains(nY to nX)) { val newDistance = dist[y][x] + grid[nY][nX] if (newDistance < dist[nY][nX]) { dist[nY][nX] = newDistance toVisit.add(nY to nX) } } } } return dist[dist.lastIndex][dist.last().lastIndex] } private fun neighbours(y: Int, x: Int, grid: List<List<Int>>): List<Pair<Int, Int>> { return arrayOf((-1 to 0), (1 to 0), (0 to -1), (0 to 1)).map { (dy, dx) -> y + dy to x + dx } .filter { (y, x) -> y in grid.indices && x in grid.first().indices } } private fun List<List<Int>>.expand(times: Int): List<List<Int>> { val expandedRight = map { row -> (1 until times).fold(row) { acc, step -> acc + row.increasedAndCapped(step) } } return (1 until times).fold(expandedRight) { acc, step -> acc + expandedRight.increased(step) } } private fun Grid.increased(by: Int) = map { row -> row.increasedAndCapped(by) } private fun List<Int>.increasedAndCapped(by: Int) = map { level -> (level + by).let { if (it > 9) it - 9 else it } } fun solve1(): Int { return cost(input) } fun solve2(): Int { return cost(input.expand(5)) } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
1,872
adventofcode-2021-2025
MIT License
src/main/kotlin/com/briarshore/aoc2022/day12/HillClimbingPuzzle.kt
steveswing
579,243,154
false
{"Kotlin": 47151}
package com.briarshore.aoc2022.day12 import com.briarshore.aoc2022.day12.ParcelKind.END import com.briarshore.aoc2022.day12.ParcelKind.START import com.briarshore.aoc2022.day12.Terrain.Companion.parse import println import readInput typealias Coordinates = Pair<Int, Int> enum class ParcelKind { START, BETWEEN, END; companion object { fun from(c: Char) = when (c) { 'S' -> START 'E' -> END else -> BETWEEN } } } fun Int.Companion.elevation(c: Char) = when (c) { 'S' -> 0 'E' -> 'z' - 'a' else -> c - 'a' } data class Parcel(val x: Int, val y: Int, val elevation: Int, val kind: ParcelKind) { val adjacentCoordinates: List<Coordinates> = listOf(x to y - 1, x to y + 1, x - 1 to y, x + 1 to y) companion object { fun from(x: Int, y: Int, c: Char) = Parcel( x, y, Int.elevation(c), ParcelKind.from(c) ) } } data class PathSegment(val parcel: Parcel, val distance: Int = 0) { fun advance(parcel: Parcel): PathSegment = PathSegment(parcel, distance + 1) } class Terrain(private val parcels: List<List<Parcel>>) { private val eastWestBounds = parcels.first().indices private val northSouthBounds = parcels.indices private val destination = findParcel { it.kind == END } fun shortestDistance(isDestination: (Parcel) -> Boolean): Int { val frontier = ArrayDeque(listOf(PathSegment(destination))) val reached = mutableSetOf(destination) while (frontier.isNotEmpty()) { val path = frontier.removeFirst() if (isDestination(path.parcel)) return path.distance path.parcel.adjacentCoordinates.mapNotNull(::getParcel) .filter { it.elevation >= path.parcel.elevation - 1 } .filter { it !in reached } .forEach { frontier.addLast(path.advance(it)) reached.add(it) } } error("Failed to find a path") } private fun findParcel(predicate: (Parcel) -> Boolean): Parcel = parcels.flatten().first(predicate) private fun getParcel(coordinates: Coordinates) = coordinates.takeIf { it.withinBounds() }?.let { (x, y) -> parcels[y][x] } private fun Coordinates.withinBounds() = first in eastWestBounds && second in northSouthBounds companion object { fun parse(lines: List<String>): Terrain = lines.mapIndexed { y: Int, xs: String -> xs.mapIndexed { x: Int, c: Char -> Parcel.from(x, y, c) } }.let(::Terrain) } } fun main() { fun part1(lines: List<String>): Int { return parse(lines).shortestDistance { it.kind == START } } fun part2(lines: List<String>): Int { return parse(lines).shortestDistance { it.elevation == 0 } } val sampleInput = readInput("d12-sample") val samplePart1 = part1(sampleInput) "samplePart1 $samplePart1".println() check(samplePart1 == 31) val samplePart2 = part2(sampleInput) "samplePart2 $samplePart2".println() check(samplePart2 == 29) val input = readInput("d12-input") val part1 = part1(input) "part1 $part1".println() check(part1 == 534) val part2 = part2(input) "part2 $part2".println() check(part2 == 525) }
0
Kotlin
0
0
a0d19d38dae3e0a24bb163f5f98a6a31caae6c05
3,340
2022-AoC-Kotlin
Apache License 2.0
year2021/src/main/kotlin/net/olegg/aoc/year2021/day8/Day8.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2021.day8 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2021.DayOf2021 /** * See [Year 2021, Day 8](https://adventofcode.com/2021/day/8) */ object Day8 : DayOf2021(8) { override fun first(): Any? { return lines .map { it.split(" | ").last() } .flatMap { it.split(" ") } .count { it.length in setOf(2, 3, 4, 7) } } override fun second(): Any? { val sets = mapOf( "abcefg" to "0", "cf" to "1", "acdeg" to "2", "acdfg" to "3", "bcdf" to "4", "abdfg" to "5", "abdefg" to "6", "acf" to "7", "abcdefg" to "8", "abcdfg" to "9", ).mapKeys { it.key.toSet() } return lines .sumOf { line -> val (sourceLine, fourLine) = line.split(" | ") val sources = sourceLine.split(" ").map { it.toSet() } val mappings = mutableMapOf<Char, Char>() val digits = Array(10) { emptySet<Char>() } digits[1] = sources.first { it.size == 2 } digits[4] = sources.first { it.size == 4 } digits[7] = sources.first { it.size == 3 } digits[8] = sources.first { it.size == 7 } mappings['a'] = (digits[7] - digits[1]).first() digits[6] = sources.filter { it.size == 6 } .first { (it + digits[1]).size == 7 } mappings['c'] = (digits[8] - digits[6]).first() mappings['f'] = (digits[1] - mappings['c']!!).first() digits[5] = sources.filter { it.size == 5 } .first { (digits[6] - it).size == 1 } mappings['e'] = (digits[6] - digits[5]).first() digits[9] = sources.filter { it.size == 6 } .first { (it + mappings['e']).size == 7 } digits[0] = sources.filter { it.size == 6 } .first { it != digits[9] && it != digits[6] } mappings['d'] = (digits[8] - digits[0]).first() mappings['g'] = digits[8].first { char -> val noG = setOf(digits[1], digits[4], digits[7]) (sources - noG).all { char in it } && noG.none { char in it } } mappings['b'] = digits[8].first { it !in mappings.values } val reverse = sets.mapKeys { (key, _) -> key.map { mappings[it]!! }.toSet() } return@sumOf fourLine.split(" ") .joinToString("") { digit -> reverse[digit.toSet()].orEmpty() } .toInt() } } } fun main() = SomeDay.mainify(Day8)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,387
adventofcode
MIT License
src/Day03.kt
EemeliHeinonen
574,062,219
false
{"Kotlin": 6073}
fun splitSack(sack: String): Pair<String, String> { val split = sack.chunked(sack.length/2) return Pair(split[0], split[1]) } fun generatePriorities(): Map<Char, Int> { var lettersAndPriorities = mutableMapOf<Char, Int>() var lowerCasePriority = 1 var upperCasePriority = 27 // map lowercase values a-z for (i in 97..122) { lettersAndPriorities[Char(i)] = lowerCasePriority lowerCasePriority += 1 } // map uppercase values A-Z for (i in 65..90) { lettersAndPriorities[Char(i)] = upperCasePriority upperCasePriority += 1 } return lettersAndPriorities.toMap() } fun getCommonItem(sack: String): Char? { val (firstCompartment, secondCompartment) = splitSack(sack) val firstCompartmentChars = firstCompartment.chunked(1).toSet() for (item in secondCompartment) { if (firstCompartmentChars.contains(item.toString())) { return item } } return null } fun getCommonItemsPriorityTotal(input: List<String>, prioritiesMap: Map<Char, Int>): Int = input.fold(0) { total, currentRucksack -> val commonItem = getCommonItem(currentRucksack) val priority = commonItem?.let { prioritiesMap[commonItem] } ?: 0 total + priority } fun main() { fun part1(input: List<String>): Int { val lettersAndPriorities = generatePriorities() return getCommonItemsPriorityTotal(input, lettersAndPriorities) } fun part2(input: List<String>): Int { return TODO() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) // check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
33775d9e6e848ab0efae0e3f00f43368c036799d
1,802
aoc-22-kotlin
Apache License 2.0
src/Day08.kt
jalex19100
574,686,993
false
{"Kotlin": 19795}
fun main() { fun buildGrid(input: List<String>): Array<IntArray> { val trees = Array(input[0].length) { IntArray(input.size) } var rowNum = 0 input.forEach { line -> val rowOfTrees = line.toCharArray().map { c -> c.digitToInt() } trees[rowNum++] = rowOfTrees.toIntArray() } return trees } fun getSurroundingTrees(trees: Array<IntArray>, colPos: Int, rowPos: Int, rows: Int, columns: Int): List<List<Int>> { // west, east, north, south outward from perspective of the current position return listOf( (0..(colPos - 1)).toList().reversed().map { col -> trees[rowPos][col] }, (colPos + 1..columns - 1).toList().map { col -> trees[rowPos][col] }, (0..rowPos - 1).toList().reversed().map { row -> trees[row][colPos] }, (rowPos + 1..rows - 1).toList().map { row -> trees[row][colPos] } ) } fun isTreeVisibleFromOutside(trees: Array<IntArray>, rowNum: Int, colNum: Int): Boolean { var visible = false val tree = trees[rowNum][colNum] // west, east, north, south val peripheralTrees = getSurroundingTrees(trees, colNum, rowNum, trees.size, trees[rowNum].size) if (tree > peripheralTrees[0].max() || tree > peripheralTrees[1].max() || tree > peripheralTrees[2].max() || tree > peripheralTrees[3].max() ) visible = true return visible } fun numberOfTreesVisibleFromInside(heightOfCurrentPosition: Int, treeLine: List<Int>): Int { val limitingTreePosition = treeLine.indexOfFirst { nextTree -> nextTree >= heightOfCurrentPosition } return if (limitingTreePosition == -1) treeLine.size else limitingTreePosition + 1 } fun getScenicScore(trees: Array<IntArray>, rowNum: Int, colNum: Int): Int { val tree = trees[rowNum][colNum] var score = 1 // west, east, north, south val peripheralTrees = getSurroundingTrees(trees, colNum, rowNum, trees.size, trees[rowNum].size) peripheralTrees.forEach { treeLine -> score *= numberOfTreesVisibleFromInside(tree, treeLine) } return score } fun part1(input: List<String>): Int { val trees = buildGrid(input) val exteriorTreeCount = (trees.size - 1) * 2 + (trees[0].size - 1) * 2 var interiorVisibleTreeCount = 0 for (i1 in 1..trees.size - 2) { for (i2 in 1..trees[i1].size - 2) { if (isTreeVisibleFromOutside(trees, i1, i2)) interiorVisibleTreeCount++ } } return exteriorTreeCount + interiorVisibleTreeCount } fun part2(input: List<String>): Int { val trees = buildGrid(input) var maxScenicScore = 1 val i1 = 1 val i2 = 1 for (i1 in 1..trees.size - 2) { for (i2 in 1..trees[i1].size - 2) { val scenicScore = getScenicScore(trees, i1, i2) maxScenicScore = maxOf(maxScenicScore, scenicScore) } } return maxScenicScore } val testInput = readInput("Day08_test") check(part1(testInput) == 21) println("Part 1 test: ${part1(testInput)}") println("Part 2 test: ${part2(testInput)}") val input = readInput("Day08") println("Part 1: ${part1(input)}") println("part 2: ${part2(input)}") }
0
Kotlin
0
0
a50639447a2ef3f6fc9548f0d89cc643266c1b74
3,408
advent-of-code-kotlin-2022
Apache License 2.0
src/Day15.kt
jbotuck
573,028,687
false
{"Kotlin": 42401}
import kotlin.math.abs import kotlin.math.max fun main() { val sensors = readInput("Day15") .map { Sensor.of(it) } //part1 val row = 2000000 sensors .map { it.ruleOutForRow(row) } .run { (minOf { it.first }..maxOf { it.last }) .count { x -> any { x in it } } }.let { println(it) } //part2 val beacons = sensors.map { it.beacon }.toSet() val space = 4_000_000 (0..space).firstNotNullOf { y -> val ruleOuts = sensors .asSequence() .map { it.ruleOutForRow(y) } .filter { !it.isEmpty() } .filter { it.last >= 0 } .filter { it.first <= space } .sortedBy { it.first } .fold(mutableListOf<IntRange>()) { acc, intRange -> val lastRange = acc.lastOrNull() when { lastRange == null -> mutableListOf(intRange) intRange.first in lastRange -> acc.apply { set( lastIndex, lastRange.first..max(lastRange.last, intRange.last) ) } else -> acc.apply { add(intRange) } } } var lastVisited = -1 ruleOuts.firstNotNullOfOrNull { ruleOut -> (lastVisited.inc() until ruleOut.first()) .firstOrNull { it to y !in beacons } .also { lastVisited = ruleOut.last } }?.let { it to y } }.let { println(it) println(it.first.toLong() * 4000000 + it.second) } } data class Sensor(val location: Pair<Int, Int>, val beacon: Pair<Int, Int>) { fun ruleOutForRow(y: Int): IntRange { val distanceToBeacon = distanceToBeacon val remainingDistance = distanceToBeacon - abs(y - location.second) return when { beacon.second == y -> { if (beacon.first < location.first) beacon.first.inc()..location.first + remainingDistance else location.first - remainingDistance until beacon.first } remainingDistance < 0 -> IntRange.EMPTY remainingDistance == 0 -> location.first..location.first else -> ((location.first - remainingDistance)..(location.first + remainingDistance)) } } private val distanceToBeacon = abs(location.first - beacon.first) + abs(location.second - beacon.second) companion object { fun of(input: String) = input .split(':') .map { s -> s.filter { it.isDigit() || it in listOf('-', ',') } } .map { coordinates -> coordinates.split(',').map { it.toInt() } } .map { it.first() to it.last() } .let { Sensor(it.first(), it.last()) } } }
0
Kotlin
0
0
d5adefbcc04f37950143f384ff0efcd0bbb0d051
2,977
aoc2022
Apache License 2.0
src/main/kotlin/dec16/Main.kt
dladukedev
318,188,745
false
null
package dec16 data class ValidationInformation( val name: String, val ranges: List<IntRange> ) data class TicketInformation( val validation: List<ValidationInformation>, val myTicket: List<Int>, val otherTickets: List<List<Int>> ) fun parseValidation(input: String): List<ValidationInformation> { return input.lines() .map { val parts = it.split(": ") val name = parts.first() val ranges = parts[1].split(" or ") .map { range -> val pair = range.split("-") .map { num -> num.toInt() } IntRange(pair.first(), pair.last()) } ValidationInformation(name, ranges) } } fun parseTicket(input: String): List<Int> { return input.split(',').map { it.toInt() } } fun parseMyTicket(input: String): List<Int> { val ticketString = input.lines().last() return parseTicket(ticketString) } fun parseOtherTickets(input: String): List<List<Int>> { return input .lines() .drop(1) .map { parseTicket(it) } } fun parseInput(input: String): TicketInformation { val parts = input.split("\n\n") return TicketInformation( parseValidation(parts[0]), parseMyTicket(parts[1]), parseOtherTickets(parts[2]) ) } fun isValidTicketNumber(ticketNumber: Int, validation: ValidationInformation): Boolean { return validation.ranges.any { range -> range.contains(ticketNumber) } } fun getInvalidDigits(ticket: List<Int>, validations: List<ValidationInformation>): List<Int> { return ticket.filter { !validations.any { validation -> isValidTicketNumber(it, validation) } } } fun isValidTicket(ticket: List<Int>, validations: List<ValidationInformation>): Boolean { return ticket.all { ticketNumber -> validations.any { isValidTicketNumber(ticketNumber, it) } } } fun removeKnownPlacements(locations: List<List<String>>): List<String> { val singleLocations = locations.filter { it.count() == 1 }.flatten() val reducedLocations = locations.map { location -> if(location.count() == 1) { location } else { location.filter { !singleLocations.contains(it) } } } if(reducedLocations.all { it.count() == 1 }) { return reducedLocations.flatten() } return removeKnownPlacements(reducedLocations) } fun getTicketInputOrder(info: TicketInformation): List<String> { val validTickets = info.otherTickets.filter { isValidTicket(it, info.validation) } val names = validTickets.map { ticket -> ticket.map { info.validation.filter { validation -> isValidTicketNumber(it, validation) }.map { validation -> validation.name } } } val groupedByTicketNumberLocation = (0 until info.myTicket.count()).map { names.map { name -> name[it] } } val validLocations = groupedByTicketNumberLocation.map { info.validation.filter {validation -> it.all { x -> x.contains(validation.name) } }.map { it.name } } return removeKnownPlacements(validLocations) } fun productOfDepartureFieldValues(myTicket: List<Int>, locations: List<String>): Long { val departureIndexed = locations.mapIndexed { index, location -> if(location.contains("departure")) { index } else { -1 } }.filter { it != -1 } return departureIndexed.fold(1L) { acc, i -> acc * myTicket[i] } } fun main() { val info = parseInput(input) println("------------ PART 1 ------------") val result = info.otherTickets .map { getInvalidDigits(it, info.validation) } .flatten() .sum() println("result: $result") println("------------ PART 2 ------------") val ticketOrder = getTicketInputOrder(info) val result2 = productOfDepartureFieldValues(info.myTicket, ticketOrder) println("result: $result2") }
0
Kotlin
0
0
d4591312ddd1586dec6acecd285ac311db176f45
4,112
advent-of-code-2020
MIT License
y2021/src/main/kotlin/adventofcode/y2021/Day12.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution object Day12 : AdventSolution(2021, 12, "Passage Pathing") { override fun solvePartOne(input: String) = solve(input, Path::visit1) override fun solvePartTwo(input: String) = solve(input, Path::visit2) private inline fun solve(input: String, visit: Path.(cave: String) -> Path?): Int { val graph = parseToGraph(input) var open = mapOf(Path("start", emptySet(), false) to 1) var complete = 0 while (open.isNotEmpty()) { open = open.flatMap { (path, count) -> graph[path.current].orEmpty().mapNotNull { path.visit(it) }.map { it to count } } .groupingBy { it.first } .fold(0) { sum, (_, count) -> sum + count } complete += open.asSequence().filter { it.key.current == "end" }.sumOf { it.value } } return complete } private fun parseToGraph(input: String): Map<String, List<String>> = input.lineSequence().map { it.substringBefore('-') to it.substringAfter('-') } .flatMap { (a, b) -> listOf(a to b, b to a) } .filter { it.second != "start" } .filter { it.first != "end" } .groupBy({ it.first }, { it.second }) private data class Path(val current: String, val history: Set<String>, val doubled: Boolean) { fun visit1(cave: String) = when { cave.lowercase() != cave -> copy(current = cave) cave !in history -> copy(current = cave, history = history + cave) else -> null } fun visit2(cave: String) = when { cave.lowercase() != cave -> copy(current = cave) cave !in history -> copy(current = cave, history = history + cave) !doubled -> copy(current = cave, doubled = true) else -> null } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,889
advent-of-code
MIT License
src/main/kotlin/kt/kotlinalgs/app/sorting/crack/AnagramSorter.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.sorting val strings = listOf( "lampe", "tor", "hendl", "palme", "ronaldo", "ampel", "rot", "abc", "z" ) val sorted = sortAnagrams(strings) println(sorted) val fast = strings.toMutableList() sortAnagramsFast(fast) println(fast) class AnagramComparator : Comparator<String> { // O(S) runtime + space override fun compare(str1: String, str2: String): Int { if (str1.length != str2.length) return str1.compareTo(str2) val counts: MutableMap<Char, Int> = mutableMapOf() for (char1 in str1) { val count = counts.getOrDefault(char1, 0) counts[char1] = count + 1 } var diff = 0 for (char2 in str2) { val count = counts[char2] if (count == null || count <= 0) return str1.compareTo(str2) counts[char2] = count - 1 } return 0 } } class AnagramSortingComparator : Comparator<String> { // sorting in O(N log N) time + O(1) if quicksort used override fun compare(str1: String, str2: String): Int { val s1 = str1.toCharArray().sorted().toString() val s2 = str2.toCharArray().sorted().toString() return s1.compareTo(s2) } } // Sort so that anagrams are grouped together fun sortAnagrams(strings: List<String>): List<String> { return strings.sortedWith(AnagramComparator()) } // time complexity: O(N * S log S), where N = # of strings & S = len of longest string // space complexity: O(N*S) fun sortAnagramsFast(strings: MutableList<String>) { // modification of bucket sort val anagramMap: MutableMap<String, MutableList<String>> = mutableMapOf() strings.forEach { val sorted = it.toCharArray().sorted().toString() val list = anagramMap.getOrDefault(sorted, mutableListOf()) list.add(it) anagramMap[sorted] = list } var index = 0 for (anagrams in anagramMap.values) { anagrams.forEach { strings[index] = it index++ } } } // optimization with hashmap + string representation: O(N*S) time + space // --> https://leetcode.com/problems/group-anagrams/solution/
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
2,163
KotlinAlgs
MIT License
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day02.kt
JamJaws
725,792,497
false
{"Kotlin": 30656}
package com.jamjaws.adventofcode.xxiii.day import com.jamjaws.adventofcode.xxiii.readInput class Day02 { fun part1(text: List<String>): Int = text.map(::parseRow).let(::getPossibleGames).map(Game::id).sum() fun part2(text: List<String>): Int = text.map(::parseRow) .map { game -> listOf( game.sets.mapNotNull(Set::red).max(), game.sets.mapNotNull(Set::green).max(), game.sets.mapNotNull(Set::blue).max(), ) } .sumOf { (red, green, blue) -> red * green * blue } private fun parseRow(line: String): Game { val id = line.removePrefix("Game ").split(":").first().toInt() val sets = line.split(";").map { Set( red = it.getNumberOfCubes("red"), green = it.getNumberOfCubes("green"), blue = it.getNumberOfCubes("blue"), ) } return Game(id, sets) } private fun getPossibleGames(games: List<Game>): List<Game> = games.filter { game -> game.sets.all { set -> (set.red ?: 0) <= MAX_RED && (set.green ?: 0) <= MAX_GREEN && (set.blue ?: 0) <= MAX_BLUE } } private fun String.getNumberOfCubes(color: String): Int? = Regex("(\\d+) $color").find(this)?.groupValues?.get(1)?.toInt() companion object { private const val MAX_RED = 12 private const val MAX_GREEN = 13 private const val MAX_BLUE = 14 } } data class Game( val id: Int, val sets: List<Set>, ) data class Set( val red: Int? = null, val green: Int? = null, val blue: Int? = null, ) fun main() { val answer1 = Day02().part1(readInput("Day02")) println(answer1) val answer2 = Day02().part2(readInput("Day02")) println(answer2) }
0
Kotlin
0
0
e2683305d762e3d96500d7268e617891fa397e9b
1,853
advent-of-code-2023
MIT License
src/main/kotlin/com/oocode/ScratchCard.kt
ivanmoore
725,978,325
false
{"Kotlin": 42155}
package com.oocode fun scratchCardScoreFrom(input: String): Int = input.split("\n").mapIndexed { index, line -> scratchCardComparisonFrom(index + 1, line).score() }.sum() fun scratchCardsFrom(input: String): Map<Int, List<ScratchCardComparison>> { val scratchCardComparisons = input.split("\n").mapIndexed { index, line -> scratchCardComparisonFrom(index + 1, line) } val scratchCardComparisonsByCardNumber = scratchCardComparisons.associateBy { it.cardNumber } val withCopies = mutableListOf<ScratchCardComparison>() IntRange(1, scratchCardComparisons.size).forEach { iterateWithCopies(it, scratchCardComparisonsByCardNumber) { scratchCard -> withCopies.add(scratchCard) } } return withCopies.groupBy { it.cardNumber } } fun scratchCardNumberFrom(input: String) = scratchCardsFrom(input).values.sumOf { it.size } fun iterateWithCopies( cardNumber: Int, scratchCards: Map<Int, ScratchCardComparison>, f: (scratchCard: ScratchCardComparison) -> Any ) { if (cardNumber > scratchCards.size) return val head = scratchCards[cardNumber]!! f(head) val rangeOfCardsToCopy = IntRange(cardNumber + 1, cardNumber + head.numberOfCorrectGuesses()) rangeOfCardsToCopy.forEach { iterateWithCopies(it, scratchCards, f) } } fun scratchCardComparisonFrom(cardNumber: Int, line: String): ScratchCardComparison = line.split(":")[1].split("|").let { val winningNumbers = numbersFrom(it[0]) val guesses = numbersFrom(it[1]) return ScratchCardComparison(cardNumber, winningNumbers, guesses) } private fun numbersFrom(s: String) = s.trim().split(Regex("\\s+")) .map { it.toInt() } .toSet() data class ScratchCardComparison( val cardNumber: Int, private val winningNumbers: Set<Int>, private val guesses: Set<Int> ) { fun score() = numberOfCorrectGuesses().let { if (it == 0) 0 else twoToPowerOf(it - 1) } fun numberOfCorrectGuesses() = winningNumbers.intersect(guesses).size } fun twoToPowerOf(i: Int) = IntRange(0, i - 1) .fold(1, { accumlator, _ -> accumlator * 2 })
0
Kotlin
0
0
36ab66daf1241a607682e7f7a736411d7faa6277
2,151
advent-of-code-2023
MIT License
lib/src/main/kotlin/com/bloidonia/advent/day04/Day04.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day04 import com.bloidonia.advent.BaseDay import com.bloidonia.advent.readText import java.util.regex.Pattern data class Square(val number: Int, var seen: Boolean = false) data class Board(val grid: List<List<Square>>) { val width = grid.first().size private fun transpose() = Board((0 until width).map { index -> grid.map { it[index] } }.toList()) private fun verticalWin(): Boolean = transpose().horizontalWin() private fun horizontalWin(): Boolean = grid.any { it.all { it.seen } } fun unmarkedSum() = grid.flatten().filter { !it.seen }.sumOf { it.number } fun hasWon() = verticalWin() or horizontalWin() fun mark(ball: Int) = grid.flatten().forEach { s -> s.seen = s.seen or (s.number == ball) } } data class BingoGame(val balls: List<Int>, val boards: List<Board>) { fun playPart1(): Int { for (ball in balls) { boards.forEach { it.mark(ball) } val winner = boards.find { it.hasWon() } if (winner != null) { return winner.unmarkedSum() * ball } } return 0; } fun playPart2(): Int { var lastBoard: Board? = null; for (ball in balls) { boards.forEach { it.mark(ball) } val losers = boards.filter { !it.hasWon() } if (losers.size == 1) { lastBoard = losers.first(); } if (losers.isEmpty()) { return lastBoard!!.unmarkedSum() * ball } } return 0; } } fun readBoards(input: String) = input.split("\n", limit = 2).let { (balls, boardDef) -> val boards = boardDef .split("\n\n") .map { board -> Board( board.split("\n") .filter { it != "" } .map { line -> line.trim().split(Pattern.compile("\\s+")).map { Square(it.toInt()) } } .toList() ) } BingoGame(balls.split(",").map { it.toInt() }, boards) } fun main() { println(readBoards(readText("/day04input.txt")).playPart1()) println(readBoards(readText("/day04input.txt")).playPart2()) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
2,181
advent-of-kotlin-2021
MIT License
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day05.kt
JamJaws
725,792,497
false
{"Kotlin": 30656}
package com.jamjaws.adventofcode.xxiii.day import com.jamjaws.adventofcode.xxiii.readInput class Day05 { fun part1(text: List<String>): Long { val seeds = text.first().substringAfter("seeds: ").split(' ').map(String::toLong) val maps = parseMaps(text) return seeds.minOf { getLocation(maps, it) } } fun part2(text: List<String>): Long { val maps = parseMaps(text) val seedRanges = getSeedRanges(text) return seedRanges.minOf { range -> range.minOf { getLocation(maps, it) } } } private fun getLocation(maps: List<List<ConvertMap>>, seed: Long): Long { val seedToSoil = maps.first() val soilToFertilizer = maps[1] val fertilizerToWater = maps[2] val waterToLight = maps[3] val lightToTemperature = maps[4] val temperatureToHumidity = maps[5] val humidityToLocation = maps[6] val soil = seed + (seedToSoil.find { seed in it.range }?.diff ?: 0) val fertilizer = soil + (soilToFertilizer.find { soil in it.range }?.diff ?: 0) val water = fertilizer + (fertilizerToWater.find { fertilizer in it.range }?.diff ?: 0) val light = water + (waterToLight.find { water in it.range }?.diff ?: 0) val temperature = light + (lightToTemperature.find { light in it.range }?.diff ?: 0) val humidity = temperature + (temperatureToHumidity.find { temperature in it.range }?.diff ?: 0) return humidity + (humidityToLocation.find { humidity in it.range }?.diff ?: 0) } private fun parseMaps(text: List<String>) = text.drop(2).fold(listOf<MutableList<ConvertMap>>()) { acc, line -> when { line.contains("-to-") -> acc + mutableListOf(mutableListOf()) line.isNotBlank() -> acc.apply { last().add(line.split(' ').map(String::toLong).let { ConvertMap(it.first(), it[1], it[2]) }) } else -> acc } } private fun getSeedRanges(text: List<String>) = text.first() .substringAfter("seeds: ") .split(' ') .map(String::toLong) .chunked(2) .map { (start, length) -> start until (start + length) } } data class ConvertMap(val destinationRangeStart: Long, val sourceRangeStart: Long, val rangeLength: Long) { val range get() = sourceRangeStart until (sourceRangeStart + rangeLength) val diff get() = destinationRangeStart - sourceRangeStart } fun main() { val answer1 = Day05().part1(readInput("Day05")) println(answer1) val answer2 = Day05().part2(readInput("Day05")) println(answer2) }
0
Kotlin
0
0
e2683305d762e3d96500d7268e617891fa397e9b
2,633
advent-of-code-2023
MIT License
src/Day08.kt
robinpokorny
572,434,148
false
{"Kotlin": 38009}
class Tree(val value: Int, val i: Int, val j: Int) {} typealias Forrest = List<List<Tree>> private fun parse(input: List<String>): Forrest = input.mapIndexed { i, line -> line.toList().mapIndexed { j, char -> Tree(char.digitToInt(), i, j) } } private fun findIn1D(seen: MutableSet<Tree>) = { highest: Int, tree: Tree -> if (tree.value > highest) { seen.add(tree) tree.value } else highest } private fun findVisible(forest: Forrest): Int { val seen = mutableSetOf<Tree>() forest.forEach { it.fold(-1, findIn1D(seen)) it.foldRight(-1) { tree, highest -> findIn1D(seen)(highest, tree) } } forest[0].forEachIndexed { j, _ -> val column = forest.map { it[j] } column.fold(-1, findIn1D(seen)) column.foldRight(-1) { tree, highest -> findIn1D(seen)(highest, tree) } } return seen.size } private fun canSeeFrom(tree: Tree, skip: (Tree) -> Boolean) = { prev: Pair<Int, Boolean>, current: Tree -> if (!prev.second || skip(current)) prev else if (current.value >= tree.value) prev.first + 1 to false else prev.first + 1 to true } private fun findHighestScenic(forest: Forrest): Int = forest.flatten().maxOf { tree -> val (right) = forest[tree.i].fold( Pair(0, true), canSeeFrom(tree) { d -> d.j <= tree.j } ) val (left) = forest[tree.i].foldRight(Pair(0, true)) { c, prev -> canSeeFrom(tree) { d -> d.j >= tree.j }(prev, c) } val column = forest.map { it[tree.j] } val (bottom) = column.fold( Pair(0, true), canSeeFrom(tree) { d -> d.i <= tree.i } ) val (top) = column.foldRight(Pair(0, true)) { c, prev -> canSeeFrom(tree) { d -> d.i >= tree.i }(prev, c) } right * left * bottom * top } fun main() { val input = parse(readDayInput(8)) val testInput = parse(rawTestInput) // PART 1 assertEquals(findVisible(testInput), 21) println("Part1: ${findVisible(input)}") // PART 2 assertEquals(findHighestScenic(testInput), 8) println("Part2: ${findHighestScenic(input)}") } private val rawTestInput = """ 30373 25512 65332 33549 35390 """.trimIndent().lines()
0
Kotlin
0
2
56a108aaf90b98030a7d7165d55d74d2aff22ecc
2,341
advent-of-code-2022
MIT License
src/Day09.kt
JanTie
573,131,468
false
{"Kotlin": 31854}
import kotlin.math.absoluteValue fun main() { fun parseInput(input: List<String>, amountOfNodes: Int): List<List<Point>> { val initial = listOf(List(amountOfNodes) { Point(0, 0) }) return input.flatMap { val (direction, moves) = it.split(" ") List(moves.toInt()) { direction } }.fold(initial) { listMutations, direction -> val currentList = listMutations.last() listMutations + listOf( currentList.mapIndexed { index, point -> if (index == 0) { // move head return@mapIndexed when (direction) { "L" -> point.copy(x = point.x - 1) "U" -> point.copy(y = point.y + 1) "R" -> point.copy(x = point.x + 1) "D" -> point.copy(y = point.y - 1) else -> point } } else { return@mapIndexed point.movedTowards(currentList[index - 1]) } } ) } } fun part1(input: List<String>): Int { return parseInput(input, 2).map { it.last() }.distinct().size } fun part2(input: List<String>): Int { return parseInput(input, 10).map { it.last() }.distinct().size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val input = readInput("Day09") check(part1(testInput) == 13) println(part1(input)) check(part2(testInput) == 1) println(part2(input)) } data class Point( val x: Int, val y: Int, ) { fun movedTowards(other: Point): Point { return when { (x - other.x).absoluteValue + (y - other.y).absoluteValue > 2 -> { this.copy( x = x + if ((other.x - x).isPositive) 1 else -1, y = y + if ((other.y - y).isPositive) 1 else -1, ) } (x - other.x).absoluteValue > 1 -> { this.copy( x = x + (other.x - x) / 2, ) } (y - other.y).absoluteValue > 1 -> { this.copy( y = y + (other.y - y) / 2, ) } else -> this } } } private val Int.isPositive: Boolean get() = this > 0
0
Kotlin
0
0
3452e167f7afe291960d41b6fe86d79fd821a545
2,486
advent-of-code-2022
Apache License 2.0
codeforces/educationalround95/e.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.educationalround95 fun main() { val M = 998244353 val (n, m) = readInts() val d = readInts().sorted() val sum = d.sumOf { it.toLong() } val ab = List(m) { readInts() }.withIndex().sortedBy { -it.value[1] } var i = n - 1 var large = 0 var sumLarge = 0L val ans = IntArray(m) for (p in ab) { val (a, b) = p.value while (i >= 0 && d[i] >= b) { large++ sumLarge += d[i] i-- } // val large = d.count { it >= b } // val sumLarge = d.filter { it >= b }.sumOf { it.toLong() } val sumSmall = sum - sumLarge val pLarge = if (large == 0) 0 else (1 - minOf(a, large).toLong() * modInverse(large, M)) % M val pSmall = (1 - minOf(a, large + 1).toLong() * modInverse(large + 1, M)) % M ans[p.index] = (((sumLarge % M * pLarge + sumSmall % M * pSmall) % M + M) % M).toInt() } println(ans.joinToString("\n")) } fun gcdExtended(a: Int, b: Int, xy: IntArray): Int { if (a == 0) { xy[0] = 0 xy[1] = 1 return b } val d = gcdExtended(b % a, a, xy) val t = xy[0] xy[0] = xy[1] - b / a * xy[0] xy[1] = t return d } fun modInverse(x: Int, p: Int): Int { val xy = IntArray(2) val gcd = gcdExtended(x, p, xy) require(gcd == 1) { "$x, $p" } var result = xy[0] % p if (result < 0) { result += p } return result } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,449
competitions
The Unlicense
src/day05/Day05.kt
Harvindsokhal
572,911,840
false
{"Kotlin": 11823}
package day05 import readInput data class Step(val amount: Int, val takeFrom: Int, val moveTo: Int) { companion object { fun detail(line: String): Step { return line.split(" ").filterIndexed { index, _ -> index % 2 == 1 }.map { it.toInt()}.let{ Step(it[0], it[1]-1, it[2]-1) } } } } fun main() { val data = readInput("day05/day05_data") val numberOfStacks = data.dropWhile { it.contains("[") }.first().split(" ").filter { it.isNotBlank() }.maxOf { it.toInt() } val stacks = List(numberOfStacks) {ArrayDeque<Char>()} val steps = mutableListOf<Step>() data.filter { it.contains("[") }.map{ line -> line.mapIndexed{ index, char -> if (char.isLetter()) stacks[index/4].addLast(line[index])}} data.filter { it.contains("move")}.map { steps.add(Step.detail(it))} fun sortCrates(stacks: List<ArrayDeque<Char>>, steps: List<Step>): String { steps.map { step -> repeat(step.amount) { stacks[step.moveTo].addFirst(stacks[step.takeFrom].removeFirst())} } return stacks.map { it.first() }.joinToString(separator = "") } fun sortCrates9001(stacks: List<ArrayDeque<Char>>, steps: List<Step>): String { steps.map { step -> stacks[step.takeFrom].subList(0, step.amount).asReversed() .map { stacks[step.moveTo].addFirst(it) } .map { stacks[step.takeFrom].removeFirst() } } return stacks.map { it.first() }.joinToString(separator = "") } fun part1(stacks: List<ArrayDeque<Char>>, steps: List<Step>) = sortCrates(stacks.map { ArrayDeque(it) }.toList(), steps) fun part2(stacks: List<ArrayDeque<Char>>, steps: List<Step>) = sortCrates9001(stacks, steps) println(part1(stacks, steps)) println(part2(stacks, steps)) }
0
Kotlin
0
0
7ebaee4887ea41aca4663390d4eadff9dc604f69
1,783
aoc-2022-kotlin
Apache License 2.0
src/Day13.kt
jimmymorales
572,156,554
false
{"Kotlin": 33914}
fun main() { fun CharArray.parseInput(currentIndex: Int = 0): Pair<Input, Int> { val current = this[currentIndex] var nextIndex = currentIndex + 1 return if (current == '[') { val items = mutableListOf<Input>() while (this[nextIndex] != ']') { if (this[nextIndex] == ',') { nextIndex++ continue } val result = parseInput(currentIndex = nextIndex) items.add(result.first) nextIndex = result.second } Input.Packet(items) to nextIndex + 1 } else { var intInput = current.toString() while (this[nextIndex] != ',' && this[nextIndex] != ']') { intInput += this[nextIndex] nextIndex++ } Input.IntInput(intInput.toInt()) to nextIndex } } fun Input.toPacketInput(): Input.Packet = when (this) { is Input.IntInput -> Input.Packet(listOf(this)) is Input.Packet -> this } fun compareInputsOrder(left: Input, right: Input): Int { fun comparePacketsOrder(left: Input.Packet, right: Input.Packet): Int { val leftSize = left.values.size val rightSize = right.values.size var i = 0 while (i < minOf(leftSize, rightSize)) { val res = compareInputsOrder(left.values[i], right.values[i]) if (res != 0) return res i++ } return rightSize - leftSize } return when (left) { is Input.Packet -> comparePacketsOrder(left, right.toPacketInput()) is Input.IntInput -> when (right) { is Input.IntInput -> right.value - left.value is Input.Packet -> comparePacketsOrder(left.toPacketInput(), right) } } } fun part1(input: List<String>): Int = input.asSequence() .map { val (left, right) = it.split('\n') left.toCharArray().parseInput().first to right.toCharArray().parseInput().first } .map { (left, right) -> compareInputsOrder(left, right) } .withIndex() .filter { it.value > 0 } .sumOf { it.index + 1 } fun part2(input: List<String>): Int = input.flatMap { val (left, right) = it.split('\n') listOf(left.toCharArray().parseInput().first, right.toCharArray().parseInput().first) }.asSequence() .plus(listOf(twoDivider, sixDivider)) .sortedWith { o1, o2 -> compareInputsOrder(o2, o1) } .filterIsInstance<Input.Packet>() .withIndex() .filter { it.value.isDivider } .map { it.index + 1 } .toList() .product() // test if implementation meets criteria from the description, like: val testInput = readLinesSplitedbyEmptyLine("Day13_test") check(part1(testInput) == 13) val input = readLinesSplitedbyEmptyLine("Day13") println(part1(input)) // part 2 check(part2(testInput) == 140) println(part2(input)) } private val twoDivider = Input.Packet( values = listOf(Input.Packet(values = listOf(Input.IntInput(2)))), isDivider = true, ) private val sixDivider = Input.Packet( values = listOf(Input.Packet(values = listOf(Input.IntInput(6)))), isDivider = true, ) private sealed class Input { data class IntInput(val value: Int) : Input() data class Packet(val values: List<Input>, val isDivider: Boolean = false) : Input() }
0
Kotlin
0
0
fb72806e163055c2a562702d10a19028cab43188
3,561
advent-of-code-2022
Apache License 2.0
src/Day05.kt
jorgecastrejon
573,097,701
false
{"Kotlin": 33669}
fun main() { fun part1(input: List<String>): String { val (stacks, movementSet) = input.parse() movementSet.forEach { (amount, from, to) -> repeat(amount) { stacks[from]?.removeLast()?.let { stacks[to]?.addLast(it) } } } return stacks.values.map(ArrayDeque<Char>::removeLast).joinToString("") } fun part2(input: List<String>): String { val (stacks, movementSet) = input.parse() movementSet.forEach { (amount, from, to) -> (0 until amount).map { stacks[from]!!.removeLast() }.reversed().forEach { stacks[to]?.addLast(it) } } return stacks.values.map(ArrayDeque<Char>::removeLast).joinToString("") } val input = readInput("Day05") println(part1(input)) println(part2(input)) } private fun List<String>.parse(): Pair<Map<Int, ArrayDeque<Char>>, List<Triple<Int, Int, Int>>> { val index = indexOfFirst { it.trim().first().isDigit() } return subList(0, index).getStacks() to subList(index + 2, size).getMovements() } private fun List<String>.getStacks(): Map<Int, ArrayDeque<Char>> = reversed().fold(mutableMapOf() ) { stacks, line -> line.windowed(size = 3, step = 4, transform = { string -> string[1].toString() }) .forEachIndexed { index, cargo -> cargo.takeUnless(String::isBlank)?.let { stacks.getOrPut(index) { ArrayDeque() }.run { addLast(it.single()) } } } stacks } private fun List<String>.getMovements(): List<Triple<Int, Int, Int>> = map { line -> line.filter { char -> char.isDigit() || char.isWhitespace() }.split(" ").filter(String::isNotBlank) } .map { Triple(it[0].toInt(), it[1].toInt() - 1, it[2].toInt() - 1) }
0
Kotlin
0
0
d83b6cea997bd18956141fa10e9188a82c138035
1,736
aoc-2022
Apache License 2.0
kotlin/src/main/kotlin/year2021/Day08.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2021 private val SEGMENTS_TO_DIGITS = mapOf( setOf('a', 'b', 'c', 'e', 'f', 'g') to 0, setOf('c', 'f') to 1, setOf('a', 'c', 'd', 'e', 'g') to 2, setOf('a', 'c', 'd', 'f', 'g') to 3, setOf('b', 'c', 'd', 'f') to 4, setOf('a', 'b', 'd', 'f', 'g') to 5, setOf('a', 'b', 'd', 'e', 'f', 'g') to 6, setOf('a', 'c', 'f') to 7, setOf('a', 'b', 'c', 'd', 'e', 'f', 'g') to 8, setOf('a', 'b', 'c', 'd', 'f', 'g') to 9 ) private fun part1(input: List<String>): Int { val outputs = input.map { line -> line.split(" | ").last() } val digits = outputs.flatMap { it.split(" ") } // 1 -> 2 segment // 4 -> 4 segment // 7 -> 3 segment // 8 -> 7 segment return digits.count { it.length == 2 || it.length == 4 || it.length == 3 || it.length == 7 } } private fun part2(input: List<String>): Int { val lines = input.map { val line = it.split(" | ") val signal = line.first() val output = line.last() Pair(first = signal.split(" "), second = output.split(" ")) } return lines.sumOf { (signal, output) -> translateConfiguration(signal, output) } } private fun translateConfiguration(signals: List<String>, output: List<String>): Int { val cables = setOf('a', 'b', 'c', 'd', 'e', 'f', 'g') val decoder = getDecoder(cables, signals) return output .joinToString("") { encodeCables -> val decodedCables = encodeCables.map { decoder[it]!! }.toSet() val digit = SEGMENTS_TO_DIGITS[decodedCables]!! "$digit" } .toInt() } private fun getDecoder( cables: Set<Char>, signals: List<String> ): Map<Char, Char> { var found = false var randomPermutation = mapOf<Char, Char>() while (!found) { randomPermutation = getRandomPermutation(cables) found = signals.all { signal -> val originalCables = signal.map { randomPermutation[it]!! }.toSet() SEGMENTS_TO_DIGITS.containsKey(originalCables) } } return randomPermutation } //TODO This is inefficient as we are trusting in randomness private fun getRandomPermutation(cables: Set<Char>): Map<Char, Char> { return cables .zip(cables.shuffled()) .toMap() } fun main() { val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
2,394
advent-of-code
MIT License
src/day16/Day16.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day16 import com.github.shiguruikai.combinatoricskt.combinations import com.github.shiguruikai.combinatoricskt.permutations import readLines private data class ValveRoom(val name: String, val flowRate: Int, val paths: List<String>) { companion object { fun of(input: String): ValveRoom = // e.g. Valve AV has flow rate=0; tunnels lead to valves AX, PI ValveRoom( input.substringAfter(" ").substringBefore(" "), // AV input.substringAfter("=").substringBefore(";").toInt(), // 0 input.substringAfter("valve").substringAfter(" ").split(", ") // ["AX", "PI"] ) } } private operator fun Map<String, MutableMap<String, Int>>.set(key1: String, key2: String, value: Int) { getValue(key1)[key2] = value } private operator fun Map<String, Map<String, Int>>.get(key1: String, key2: String, defaultValue: Int = 100000): Int = get(key1)?.get(key2) ?: defaultValue // Find the cost of moving from one room to any other room, but only for rooms that have a flow rate > 0 and are // reachable by AA private fun calculateShortestPaths(rooms: Map<String, ValveRoom>): Map<String, Map<String, Int>> { // Create a Map<String, Map<String, Int>> where the key to the first map is the name of a room, and the value is // another map whose key is a destination room, and its value is the cost to move to that room and turn on the valve. // e.g. {"AA": {"DD": 1, "II": 1", "BB": 1}} var shortestPaths = mutableMapOf<String, MutableMap<String, Int>>() for (room in rooms.values) { val paths = room.paths.associateWith { 1 }.toMutableMap() shortestPaths[room.name] = paths } // A simple way to get the shortest path from one room to any other room is to generate permutations of all room // names in groups of 3. Destructure these into "waypoint", "to", and "from". If we can go from "to" -> "waypoint" and // from "waypoint" to "from" cheaper than our previous answer of going directly from "to" to "from", take and store // that in the shortestPath map. shortestPaths.keys.permutations(3).forEach { (waypoint, from, to) -> shortestPaths[from, to] = minOf( shortestPaths[from, to], // existing path shortestPaths[from, waypoint] + shortestPaths[waypoint, to] // new path ) } // Find all the zero flow rooms and remove them; we don't care about these as they will never be a final destination val zeroFlowRooms = rooms.values.filter { it.flowRate == 0}.map { it.name }.toSet() shortestPaths.values.forEach { it.keys.removeAll(zeroFlowRooms) } // Filter out anything that isn't AA itself, or accessible from AA val accessibleFromAA: Set<String> = shortestPaths.getValue("AA").keys return shortestPaths.filter { it.key in accessibleFromAA || it.key == "AA" } } private fun searchPaths(rooms: Map<String, ValveRoom>, paths: Map<String, Map<String, Int>>, room: String, timeAllowed: Int, seen: Set<String> = emptySet(), timeTaken: Int = 0, totalFlow: Int = 0): Int { var possibleNextRooms = paths.getValue(room) // find a room we haven't already been to .filterNot { (nextRoom, _) -> nextRoom in seen } // make sure we can get to the room in time (< and not <= because if we get there at exactly 30 the flow rate is irrelevant) .filter { (_, traversalCost) -> timeTaken + traversalCost + 1 < timeAllowed } var totalFlow = possibleNextRooms.maxOfOrNull { (nextRoom, traversalCost) -> // recursively call searchPath from each next room searchPaths( rooms, paths, nextRoom, timeAllowed, seen + nextRoom, // add this room to seen set timeTaken + traversalCost + 1, // increment time taken by how long it will take to get there + 1 for opening the valve totalFlow + ((timeAllowed - timeTaken - traversalCost - 1) * rooms.getValue(nextRoom).flowRate) // calculate flow given remaining time and flow rate of next room ) } ?: totalFlow // eventually we'll exhaust all entries in the map and return the total flow return totalFlow } private fun part1(input: List<String>): Int { val rooms = input.map { ValveRoom.of(it) }.associateBy { it.name } val paths: Map<String, Map<String, Int>> = calculateShortestPaths(rooms) return searchPaths(rooms, paths, "AA", 30) } private fun part2(input: List<String>): Int { val rooms = input.map { ValveRoom.of(it) }.associateBy { it.name } val paths: Map<String, Map<String, Int>> = calculateShortestPaths(rooms) return paths.keys .combinations(paths.size / 2) .map { it.toSet() } .maxOf { halfOfTheRooms -> searchPaths(rooms, paths, "AA", 26, halfOfTheRooms) + searchPaths(rooms, paths,"AA", 26, paths.keys - halfOfTheRooms) } } fun main() { println(part1(readLines("day16/test"))) println(part1(readLines("day16/input"))) println(part2(readLines("day16/test"))) println(part2(readLines("day16/input"))) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
5,294
aoc2022
Apache License 2.0
src/main/kotlin/dev/paulshields/aoc/Day8.kt
Pkshields
433,609,825
false
{"Kotlin": 133840}
/** * Day 8: Seven Segment Search */ package dev.paulshields.aoc import dev.paulshields.aoc.common.readFileAsStringList fun main() { println(" ** Day 8: Seven Segment Search ** \n") val rawCorruptedDisplays = readFileAsStringList("/Day8CorruptedDisplays.txt") val corruptedOutputs = rawCorruptedDisplays.map { it.split(" | ")[1] } val easyToFindDigitsCount = countEasyToFindDigits(corruptedOutputs) println("There are $easyToFindDigitsCount instances of 1, 4, 7 or 8 in the corrupted outputs.") val corruptedDisplays = rawCorruptedDisplays.map { val splitData = it.split(" | ") val uniqueSignalPatterns = splitData[0].split(" ") CorruptedDisplay(uniqueSignalPatterns, splitData[1]) } val sumOfDecodedValues = sumAllDecodedOutputValues(corruptedDisplays) println("The sum of all decoded output values from the corrupted displays is $sumOfDecodedValues") } fun countEasyToFindDigits(outputValues: List<String>) = outputValues .flatMap { it.trim().split(" ") } .count { it.length == 2 || it.length == 3 || it.length == 4 || it.length == 7 } fun sumAllDecodedOutputValues(corruptedDisplays: List<CorruptedDisplay>) = corruptedDisplays.sumOf { it.decodedOutputValue } data class CorruptedDisplay(val uniqueSignalPatterns: List<String>, val fourDigitOutputValue: String) { val matchedDigitPatterns = findMatchingDigitPatterns() val decodedOutputValue = decodeOutputValue() private fun findMatchingDigitPatterns(): Map<String, Int> { val patternsByLength = uniqueSignalPatterns.groupBy { it.length } val one = patternsByLength[2].firstOrEmpty() val four = patternsByLength[4].firstOrEmpty() val seven = patternsByLength[3].firstOrEmpty() val eight = patternsByLength[7].firstOrEmpty() val six = patternsByLength[6].firstOrEmpty { !it.containsAllChars(one) } val five = patternsByLength[5].firstOrEmpty { six.containsAllChars(it) } val three = patternsByLength[5].firstOrEmpty { it.containsAllChars(one) } val two = patternsByLength[5].firstOrEmpty { it != five && it != three } val nine = patternsByLength[6].firstOrEmpty { it.containsAllChars(three) } val zero = patternsByLength[6].firstOrEmpty { it != six && it != nine } return mapOf( zero to 0, one to 1, two to 2, three to 3, four to 4, five to 5, six to 6, seven to 7, eight to 8, nine to 9) } private fun decodeOutputValue() = fourDigitOutputValue .split(" ") .map { digit -> matchedDigitPatterns .filterKeys { digit.length == it.length && digit.containsAllChars(it) } .values.first() } .joinToString("") .toIntOrNull() ?: 0 } private fun String.containsAllChars(chars: String) = chars.toCharArray().all { this.contains(it) } private fun List<String>?.firstOrEmpty() = this?.first() ?: "" private fun List<String>?.firstOrEmpty(predicate: (String) -> Boolean) = this?.first(predicate) ?: ""
0
Kotlin
0
0
e3533f62e164ad72ec18248487fe9e44ab3cbfc2
3,167
AdventOfCode2021
MIT License
src/y2021/Day14.kt
Yg0R2
433,731,745
false
null
package y2021 import kotlin.collections.Map.Entry fun main() { fun part1(input: List<String>): Long { return input.runSteps(10) } fun part2(input: List<String>): Long { return input.runSteps(40) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput).also { println(it) } == 1588L) check(part2(testInput).also { println(it) } == 2188189693529L) val input = readInput("Day14") println(part1(input).also { check(it == 2587L) }) println(part2(input)) } private fun List<String>.runSteps(stepsCount: Int): Long { var polymerCounts: Map<String, Long> = this[0] .windowed(2) .groupingBy { it } .eachCount() .map { it.key to it.value.toLong() } .toMap() val pairInsertionRule = this .drop(1) .filter { it.isNotBlank() } .map { it.split("->") } .associate { it[0].trim() to it[1].trim() } val polymerCounter = this[0] .groupingBy { it } .eachCount() .map { it.key.toString() to it.value.toLong() } .toMap() .toMutableMap() for (i in 1..stepsCount) { polymerCounts = polymerCounts.entries .fold(mutableMapOf()) { acc: MutableMap<String, Long>, polymerPair: Entry<String, Long> -> val insertPolymer = pairInsertionRule[polymerPair.key] polymerCounter.compute(insertPolymer!!) { _, v -> (v ?: 0) + polymerPair.value } val key1 = "${polymerPair.key[0]}$insertPolymer" val key2 = "$insertPolymer${polymerPair.key[1]}" acc.compute(key1) { _, v -> (v ?: 0) + polymerPair.value } acc.compute(key2) { _, v -> (v ?: 0) + polymerPair.value } acc } .toMap() } return polymerCounter.values.maxOf { it } - polymerCounter.values.minOf { it } }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
1,966
advent-of-code
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/word_ladder_2/WordLadderTests.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.word_ladder_2 import datsok.* import org.junit.* /** * https://leetcode.com/problems/word-ladder-ii/ * * Given two words (beginWord and endWord), and a dictionary's word list, * find all shortest transformation sequence(s) from beginWord to endWord, such that: * - Only one letter can be changed at a time * - Each transformed word must exist in the word list. Note that beginWord is not a transformed word. * * Note: * - Return an empty list if there is no such transformation sequence. * - All words have the same length. * - All words contain only lowercase alphabetic characters. * - You may assume no duplicates in the word list. * - You may assume beginWord and endWord are non-empty and are not the same. */ class WordLadderTests { @Test fun `some examples`() { findLadders(beginWord = "hit", endWord = "cog", wordList = emptyList()) shouldEqual emptySet() findLadders( beginWord = "hit", endWord = "cog", wordList = listOf("hot", "dot", "dog", "lot", "log") ) shouldEqual emptySet() findLadders( beginWord = "hit", endWord = "cog", wordList = listOf("hot", "dot", "dog", "lot", "log", "cog") ) shouldEqual setOf( listOf("hit", "hot", "dot", "dog", "cog"), listOf("hit", "hot", "lot", "log", "cog") ) } } private typealias Solution = List<String> private fun findLadders(beginWord: String, endWord: String, wordList: List<String>): Set<Solution> { val ladders = findAllLadders(beginWord, endWord, wordList) val minSize = ladders.minByOrNull { it: Solution -> it.size }?.size ?: return emptySet() return ladders.filterTo(HashSet()) { it.size == minSize } } private fun findAllLadders(beginWord: String, endWord: String, wordList: List<String>): Set<Solution> { if (beginWord == endWord) return setOf(listOf(endWord)) val nextWords = wordList.filter { it.diff(beginWord) == 1 } return nextWords .flatMap { findLadders(it, endWord, wordList - it) } .mapTo(HashSet()) { listOf(beginWord) + it } } private fun String.diff(that: String) = zip(that).sumBy { if (it.first != it.second) 1 else 0 }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,252
katas
The Unlicense
src/Day13.kt
erikthered
572,804,470
false
{"Kotlin": 36722}
enum class Order { CORRECT, INCORRECT, UNDECIDED } fun main() { fun parsePacketData(line: String): Pair<List<Any>, Int> { val data = mutableListOf<Any>() var idx = 1 var buffer = "" var done = false while(!done) { when (val c = line[idx]) { '[' -> { val (nested, offset) = parsePacketData(line.substring(idx)) data.add(nested) idx += offset } ']' -> { if(buffer.isNotEmpty()) data.add(buffer.toInt()) buffer = "" idx++ done = true } ',' -> { if(buffer.isNotEmpty()) data.add(buffer.toInt()) buffer = "" idx++ } else -> { buffer += c idx++ } } } return data to idx } fun checkOrder(left: Any, right: Any) : Order { when { left is Int && right is Int -> { return when { left < right -> Order.CORRECT left > right -> Order.INCORRECT else -> Order.UNDECIDED } } left is List<*> && right is List<*> -> { left.mapIndexed { index, value -> if (index > right.lastIndex) return Order.INCORRECT val order = checkOrder(value!!, right[index]!!) if(order != Order.UNDECIDED) return order } if(left.size < right.size) return Order.CORRECT return Order.UNDECIDED } left is Int && right is List<*> -> return checkOrder(listOf(left), right) left is List<*> && right is Int -> return checkOrder(left, listOf(right)) } return Order.UNDECIDED } fun part1(input: List<String>): Int { val packets = input.windowed(2, 3).mapIndexed { packet, (left, right) -> packet to (parsePacketData(left).first to parsePacketData(right).first) }.toMap() val ordering = packets.mapValues { e -> checkOrder(e.value.first, e.value.second) } return ordering.filter { it.value == Order.CORRECT }.keys.sumOf { it + 1 } } class PacketComparator: Comparator<Any> { override fun compare(o1: Any?, o2: Any?): Int { if(o1 == null || o2 == null) return 0 return when(checkOrder(o1, o2)) { Order.CORRECT -> -1 Order.INCORRECT -> 1 else -> 0 } } } fun part2(input: List<String>): Int { val packets = input .asSequence() .plus("[[2]]").plus("[[6]]") .filter { it.isNotBlank() } .map { parsePacketData(it).first } .sortedWith(PacketComparator()) .map { it.toString() } .toList() val div1 = packets.indexOfFirst { it == "[[2]]" } + 1 val div2 = packets.indexOfFirst { it == "[[6]]" } + 1 return div1 * div2 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3946827754a449cbe2a9e3e249a0db06fdc3995d
3,517
aoc-2022-kotlin
Apache License 2.0
src/day12.kts
miedzinski
434,902,353
false
{"Kotlin": 22560, "Shell": 113}
sealed class Cave { val paths = mutableSetOf<Cave>() object Start : Cave() object End : Cave() data class Small(val id: String) : Cave() data class Big(val id: String) : Cave() } val allCaves = mutableMapOf<String, Cave>( "start" to Cave.Start, "end" to Cave.End, ) generateSequence(::readLine).forEach { val (first, second) = it.split('-').map { allCaves.getOrPut(it) { when (it.all(Char::isUpperCase)) { true -> Cave.Big(it) else -> Cave.Small(it) } } } first.paths.add(second) second.paths.add(first) } interface Strategy { fun next(cave: Cave): Sequence<Strategy> } class SmallAtMostOnceStrategy(val visited: Set<Cave>) : Strategy { override fun next(cave: Cave): Sequence<Strategy> = when (cave) { is Cave.Big, !in visited -> sequenceOf(SmallAtMostOnceStrategy(visited union setOf(cave))) else -> emptySequence() } } class SingleSmallTwice(val visited: Set<Cave>) : Strategy { override fun next(cave: Cave): Sequence<Strategy> = when (cave) { is Cave.Big, !in visited -> sequenceOf(SingleSmallTwice(visited union setOf(cave))) is Cave.Small -> { val nextVisited = visited union setOf(cave) val next = sequenceOf(SmallAtMostOnceStrategy(nextVisited)) when (cave) { in visited -> next else -> next + sequenceOf(SingleSmallTwice(nextVisited)) } } else -> emptySequence() } } fun visit(cave: Cave, strategy: Strategy): Int = when (cave) { is Cave.End -> 1 else -> cave.paths.asSequence() .flatMap { nextCave -> strategy.next(nextCave).map { nextCave to it } } .sumOf { (cave, strategy) -> visit(cave, strategy) } } val part1 = visit(Cave.Start, SmallAtMostOnceStrategy(setOf(Cave.Start))) val part2 = visit(Cave.Start, SingleSmallTwice(setOf(Cave.Start))) println("part1: $part1") println("part2: $part2")
0
Kotlin
0
0
6f32adaba058460f1a9bb6a866ff424912aece2e
2,004
aoc2021
The Unlicense
src/Day04.kt
afranken
572,923,112
false
{"Kotlin": 15538}
fun main() { fun part1(input: List<String>): Int { val overlaps = input .asSequence() .filterNot(String::isBlank) .map { //6-6,4-6 it.split(",") // 6-6 4-6 .map {// 6-6 it.split("-") // 6 6 }.map { (it[0].toInt()..it[1].toInt()).toSet() } }.map { val section1 = it[0] val section2 = it[1] if (section1.containsAll(section2) || section2.containsAll(section1)) { 1 } else { 0 } } val sum = overlaps.sum() println(sum) return sum } fun part2(input: List<String>): Int { val overlaps = input .asSequence() .filterNot(String::isBlank) .map { //6-6,4-6 it.split(",") // 6-6 4-6 .map {// 6-6 it.split("-") // 6 6 }.map { (it[0].toInt()..it[1].toInt()).toSet() } }.map { val section1 = it[0] val section2 = it[1] if (section1.intersect(section2).isNotEmpty()) { 1 } else { 0 } } val sum = overlaps.sum() println(sum) return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") check(part1(input) == 595) check(part2(input) == 952) }
0
Kotlin
0
0
f047d34dc2a22286134dc4705b5a7c2558bad9e7
1,795
advent-of-code-kotlin-2022
Apache License 2.0
advent-of-code-2023/src/Day12.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import lib.repeat private const val DAY = "Day12" private typealias Record = Pair<String, List<Int>> fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { part1(testInput()) shouldBe 21 measureAnswer { part1(input()) } } "Part 2" { part2(testInput()) shouldBe 525152 measureAnswer { part2(input()) } } } private fun part1(input: List<Record>) = input.sumOf { (pattern, numbers) -> countArrangements(pattern, numbers) } private fun part2(input: List<Record>) = input.sumOf { (pattern, numbers) -> val multiPattern = listOf(pattern).repeat(5).joinToString("?") val multiNumbers = numbers.repeat(5) countArrangements(multiPattern, multiNumbers) } private val memory = mutableMapOf<Pair<String, List<Int>>, Long>() private fun countArrangements(pattern: String, numbers: List<Int>): Long { when { !pattern.canFitNumbers(numbers) -> return 0 pattern.isEmpty() -> return 1 } fun countDotWays() = countArrangements(pattern.drop(1), numbers) fun countHashWays(): Long = memory.getOrPut(pattern to numbers) { val nextNumber = numbers.firstOrNull() if (nextNumber != null && pattern.canFitNumber(nextNumber)) { countArrangements(pattern.drop(nextNumber + 1), numbers.drop(1)) } else { 0 } } return when (pattern.first()) { '.' -> countDotWays() '#' -> countHashWays() '?' -> countDotWays() + countHashWays() else -> error("Unexpected pattern: $pattern") } } private fun String.canFitNumbers(numbers: List<Int>): Boolean = length >= numbers.sum() + numbers.size - 1 private fun String.canFitNumber(number: Int): Boolean { return length >= number && take(number).none { it == '.' } && getOrNull(number) != '#' } private fun readInput(name: String) = readLines(name).map { line -> val (pattern, rawNumbers) = line.split(" ") pattern to rawNumbers.splitInts() }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,036
advent-of-code
Apache License 2.0
src/Day04.kt
ranveeraggarwal
573,754,764
false
{"Kotlin": 12574}
fun main() { fun contains(first: String, second: String): Boolean { return ((first.split("-")[0].toInt() <= second.split("-")[0].toInt()) and (first.split("-")[1].toInt() >= second.split("-")[1].toInt())) or ((first.split("-")[0].toInt() >= second.split("-")[0].toInt()) and (first.split("-")[1].toInt() <= second.split("-")[1].toInt())) } fun part1(input: List<String>): Int { return input.fold(0) {sum, line -> sum + line.split(",").let { pair -> if (contains(pair[0], pair[1])) 1 else 0}} } fun overlaps(first: String, second: String): Boolean { return ((first.split("-")[0].toInt() <= second.split("-")[0].toInt()) and (first.split("-")[1].toInt() >= second.split("-")[0].toInt())) or ((first.split("-")[0].toInt() >= second.split("-")[0].toInt()) and (first.split("-")[0].toInt() <= second.split("-")[1].toInt())) } fun part2(input: List<String>): Int { return input.fold(0) {sum, line -> sum + line.split(",").let { pair -> if (overlaps(pair[0], pair[1])) 1 else 0}} } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c8df23daf979404f3891cdc44f7899725b041863
1,423
advent-of-code-2022-kotlin
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year23/Day19.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year23 import com.grappenmaker.aoc.* fun PuzzleSet.day19() = puzzle(day = 19) { val (rules, parts) = input.doubleLines() val ps = parts.lines().map { l -> l.drop(1).dropLast(1).split(",").associate { p -> val (c, d) = p.split("=") c to d.toLong() } } data class Rule(val p: String, val range: LongRange, val inverseRange: LongRange, val to: String) data class Workflow(val name: String, val rules: List<Rule>, val to: String) val wf = rules.lines().associate { l -> val name = l.substringBefore('{') val rls = l.drop(name.length + 1).dropLast(1).split(",") name to Workflow(name, rls.dropLast(1).map { rr -> val (rest, to) = rr.split(":") val p = rest.first().toString() val op = rest[1] val comp = rest.drop(2).toLong() Rule( p, when (op) { '>' -> comp + 1..4000 '<' -> 1..<comp else -> error("IMP $op") }, when (op) { '>' -> 1..comp // <= '<' -> comp..4000 // >= else -> error("IMP $op") }, to ) }, rls.last()) } val start = wf.getValue("in") fun find(e: Map<String, Long>): Boolean { var curr = start while (true) when (val to = curr.rules.find { e.getValue(it.p) in it.range }?.to ?: curr.to) { "A" -> return true "R" -> return false else -> curr = wf.getValue(to) } } partOne = ps.sumOf { m -> if (find(m)) m.values.sum() else 0 }.s() val default = "xmas".associate { it.toString() to 1..4000L } fun Map<String, LongRange>.merge(p: String, nr: LongRange): Map<String, LongRange>? { val new = toMutableMap() new[p] = nr.overlap(new.getValue(p)) ?: return null return new } fun solve(cw: Workflow, r: Map<String, LongRange>): List<Map<String, LongRange>> = when (cw.to) { "A" -> listOf(r) "R" -> emptyList() else -> { fun solve(cw: String, r: Map<String, LongRange>): List<Map<String, LongRange>> = when (cw) { "A" -> listOf(r) "R" -> emptyList() else -> solve(wf.getValue(cw), r) } var curr = r val res = mutableListOf<Map<String, LongRange>>() for (rule in cw.rules) { curr.merge(rule.p, rule.range)?.let { res += solve(rule.to, it) } curr = curr.merge(rule.p, rule.inverseRange) ?: curr } res + solve(cw.to, curr) } } partTwo = (solve(start, default).sumOf { m -> m.values.map { it.width().toBigInteger() }.product() }).s() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,834
advent-of-code
The Unlicense
src/commonMain/kotlin/advent2020/day22/Day22Puzzle.kt
jakubgwozdz
312,526,719
false
null
package advent2020.day22 import advent2020.utils.groups fun part1(input: String): String { val (p1, p2) = decks(input) combat(p1, p2) return score(p1, p2).toString() } fun part2(input: String): String { val (p1, p2) = decks(input) games = 0 checks = 0 recursiveCombat(p1, p2) println("; games $games checks $checks; ") return score(p1, p2).toString() } fun decks(input: String): Pair<MutableList<Int>, MutableList<Int>> = input.trim() .lineSequence() .groups { it.isBlank() } .map { l -> l.drop(1).map { it.toInt() }.toMutableList() } .toList() .let { (p1, p2) -> p1 to p2 } fun score(p1: List<Int>, p2: List<Int>): Long { val p1sum = p1.reversed().mapIndexed { index, i -> (index + 1).toLong() * i }.sum() val p2sum = p2.reversed().mapIndexed { index, i -> (index + 1).toLong() * i }.sum() return p1sum + p2sum } fun combat(p1: MutableList<Int>, p2: MutableList<Int>) { while (p1.isNotEmpty() && p2.isNotEmpty()) { val card1 = p1.removeFirst() val card2 = p2.removeFirst() when { card1 > card2 -> p1 += listOf(card1, card2) card2 > card1 -> p2 += listOf(card2, card1) else -> error("same card $card1") } } } var games = 0L var checks = 0L fun recursiveCombat(p1: MutableList<Int>, p2: MutableList<Int>): Int { games++ val memory = HashSet<Pair<List<Int>, List<Int>>>() while (p1.isNotEmpty() && p2.isNotEmpty()) { checks++ val state = p1.toList() to p2.toList() if (state in memory) return 1 memory += state val card1 = p1.removeFirst() val card2 = p2.removeFirst() val winner = when { card1 <= p1.size && card2 <= p2.size -> recursiveCombat( p1.take(card1).toMutableList(), p2.take(card2).toMutableList(), ) card1 > card2 -> 1 card1 < card2 -> 2 else -> error("same card $card1") } when (winner) { 1 -> p1 += listOf(card1, card2) 2 -> p2 += listOf(card2, card1) } } return if (p1.isNotEmpty()) 1 else 2 }
0
Kotlin
0
2
e233824109515fc4a667ad03e32de630d936838e
2,177
advent-of-code-2020
MIT License
src/Day14.kt
AxelUser
572,845,434
false
{"Kotlin": 29744}
fun main() { fun List<String>.getStones(): Set<Point<Int>> { val map = mutableSetOf<Point<Int>>() for (path in this.map { it.split("->").map { it.trim().split(",").let { (x, y) -> Point(y.toInt(), x.toInt()) } } }) { for ((from, to) in path.windowed(2)) { val points = if (from.y == to.y) { (minOf(from.x, to.x)..maxOf(from.x, to.x)).map { Point(from.y, it) } } else { (minOf(from.y, to.y)..maxOf(from.y, to.y)).map { Point(it, from.x) } } points.forEach { map.add(it) } } } return map } fun Map<Point<Int>, Char>.simulate(start: Point<Int>, imaginaryFloor: Int): Point<Int> { var current = start while (true) { val next = arrayOf( Point(current.y + 1, current.x), Point(current.y + 1, current.x - 1), Point(current.y + 1, current.x + 1) ).firstOrNull { !this.containsKey(it) && it.y != imaginaryFloor } ?: return current current = next } } fun part1(input: List<String>): Int { val map = input.getStones().associateWith { '#' }.toMutableMap() val maxY = map.keys.maxOf { it.y } var count = 0 while (true) { if (map.simulate(Point(0, 500), maxY + 1).takeIf { it.y != maxY }?.also { map[it] = 'o' } == null) break count++ } return count } fun part2(input: List<String>): Int { val map = input.getStones().associateWith { '#' }.toMutableMap() val imaginaryFloor = map.keys.maxOf { it.y } + 2 val start = Point(0, 500) var count = 0 while (map.simulate(start, imaginaryFloor).also { map[it] = 'o' } != start) { count++ } return count + 1 } check(part1(readInput("Day14_test")) == 24) check(part2(readInput("Day14_test")) == 93) println(part1(readInput("Day14"))) println(part2(readInput("Day14"))) }
0
Kotlin
0
1
042e559f80b33694afba08b8de320a7072e18c4e
2,061
aoc-2022
Apache License 2.0
src/Day12.kt
robinpokorny
572,434,148
false
{"Kotlin": 38009}
import java.util.PriorityQueue private fun parse(input: List<String>): Triple<Map<Point, Int>, Point, Point> { var start = Point(0, 0) var end = Point(0, 0) val map = input .flatMapIndexed { i, row -> row.mapIndexed { j, item -> val point = Point(i, j) val value = when (item) { 'S' -> 0.also { start = point } 'E' -> 25.also { end = point } else -> item - 'a' } Pair(point, value) } } .toMap() return Triple(map, start, end) } private fun shortestPath( map: Map<Point, Int>, start: Point, isEnd: (Point) -> Boolean, isValidPath: (Point, Point) -> Boolean ): Int { val processed = mutableSetOf<Point>() val costMap = mutableMapOf<Point, Int>() val queue = PriorityQueue<Point> { a, b -> costMap[a]!! - costMap[b]!! } // Init costMap.set(start, 0) queue.add(start) while (queue.isNotEmpty()) { val next = queue.remove() if (processed.contains(next)) continue else processed.add(next) val adjacent = listOf( next.copy(x = next.x + 1), next.copy(x = next.x - 1), next.copy(y = next.y - 1), next.copy(y = next.y + 1), ) .filter { it in map && isValidPath(next, it) } adjacent.forEach { costMap.set(it, costMap[next]!! + 1) queue.add(it) } adjacent.find { isEnd(it) }?.also { return costMap[it]!! } } return 0 } private fun part1(input: Triple<Map<Point, Int>, Point, Point>): Int { val (map, start, end) = input return shortestPath( map, start, { it == end }, { from, to -> map[to]!! - map[from]!! <= 1 }) } private fun part2(input: Triple<Map<Point, Int>, Point, Point>): Int { val (map, _, end) = input return shortestPath( map, end, { map[it]!! == 0 }, { from, to -> map[from]!! - map[to]!! <= 1 }) } fun main() { val input = parse(readDayInput(12)) val testInput = parse(rawTestInput) // PART 1 assertEquals(part1(testInput), 31) println("Part1: ${part1(input)}") // PART 2 assertEquals(part2(testInput), 29) println("Part2: ${part2(input)}") } private val rawTestInput = """ Sabqponm abcryxxl accszExk acctuvwj abdefghi """.trimIndent().lines()
0
Kotlin
0
2
56a108aaf90b98030a7d7165d55d74d2aff22ecc
2,476
advent-of-code-2022
MIT License
src/Day02.kt
Redstonecrafter0
571,787,306
false
{"Kotlin": 19087}
enum class Move(val score: Int) { Rock(1), Paper(2), Scissors(3); fun vs(other: Move): Result { return when (this) { Rock -> when (other) { Rock -> Result.Draw Paper -> Result.Lost Scissors -> Result.Won } Paper -> when (other) { Rock -> Result.Won Paper -> Result.Draw Scissors -> Result.Lost } Scissors -> when (other) { Rock -> Result.Lost Paper -> Result.Won Scissors -> Result.Draw } } } } enum class Result(val score: Int) { Won(6), Lost(0), Draw(3); fun requires(other: Move): Move { return when (this) { Won -> when (other) { Move.Rock -> Move.Paper Move.Paper -> Move.Scissors Move.Scissors -> Move.Rock } Lost -> when (other) { Move.Rock -> Move.Scissors Move.Paper -> Move.Rock Move.Scissors -> Move.Paper } Draw -> other } } } fun main() { fun part1(input: List<String>): Int { val moves = input.map { it.split(" ") }.map { it[0] to it[1] }.map { (theirs, yours) -> when (theirs) { "A" -> Move.Rock "B" -> Move.Paper "C" -> Move.Scissors else -> error("invalid move") } to when (yours) { "X" -> Move.Rock "Y" -> Move.Paper "Z" -> Move.Scissors else -> error("invalid move") } } return moves.sumOf { (theirs, yours) -> yours.vs(theirs).score + yours.score } } fun part2(input: List<String>): Int { val moves = input.map { it.split(" ") }.map { it[0] to it[1] }.map { (theirs, result) -> when (theirs) { "A" -> Move.Rock "B" -> Move.Paper "C" -> Move.Scissors else -> error("invalid move") } to when (result) { "X" -> Result.Lost "Y" -> Result.Draw "Z" -> Result.Won else -> error("invalid move") } } return moves.sumOf { (theirs, result) -> result.requires(theirs).score + result.score } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e5dbabe247457aabd6dd0f0eb2eb56f9e4c68858
2,703
Advent-of-Code-2022
Apache License 2.0
src/Day12.kt
tsschmidt
572,649,729
false
{"Kotlin": 24089}
typealias Coord = Pair<Int,Int> fun main() { fun findSList(map: List<List<Char>>): List<Pair<Int, Int>> { val start = mutableListOf<Pair<Int,Int>>() for(i in map.indices) { for (j in 0 until map[i].size) { if (map[i][j] == 'S' || map[i][j] == 'a') { start.add(i to j) } } } return start } fun findS(map: List<List<Char>>): Coord { val start = mutableListOf<Pair<Int,Int>>() for(i in map.indices) { for (j in 0 until map[i].size) { if (map[i][j] == 'S') { return i to j } } } error("e not found") } fun letter(ch: Char): Char { return when (ch) { 'S' -> 'a' 'E' -> 'z' else -> ch } } data class Step(val c: Coord, val distance: Int, val parent: Step?) fun findShortest(S: Coord, map: List<List<Char>>): Int { val queue = ArrayDeque<Step>() val visited = mutableSetOf(S) queue.addFirst(Step(S, 0, null)) while (queue.isNotEmpty()) { val v = queue.removeFirst() if (map[v.c.first][v.c.second] == 'E') { return v.distance } setOf( if (v.c.second < map[v.c.first].size - 1) v.c.first to v.c.second + 1 else null, if (v.c.second > 0) v.c.first to v.c.second - 1 else null, if (v.c.first > 0) v.c.first - 1 to v.c.second else null, if (v.c.first < map.size - 1) v.c.first + 1 to v.c.second else null) .filterNotNull() .filter {letter(map[it.first][it.second]) - letter(map[v.c.first][v.c.second]) <= 1 } .filter { !visited.contains(it) } .forEach { visited.add(it) queue.add(Step(it, v.distance + 1, v)) } } return Int.MAX_VALUE } fun part1(input: List<String>): Int { val map = input.map{ it.toList() } val starts = findS(map) return findShortest(starts, map) } fun part2(input: List<String>): Int { val map = input.map{ it.toList() } val starts = findSList(map) return starts.minOf { findShortest(it, map) } } val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7bb637364667d075509c1759858a4611c6fbb0c2
2,490
aoc-2022
Apache License 2.0
src/Day08_optimized.kt
Venkat-juju
572,834,602
false
{"Kotlin": 27944}
import kotlin.math.max //1825 //235200 fun main() { fun List<Int>.indexOfMax(): Int { var max = Integer.MIN_VALUE var maxIndex = -1 forEachIndexed { index, value -> if (max <= value) { max = index maxIndex = index } } return maxIndex } fun isVisible(treeIndex: Int, treeLine: List<Int>, indexOfMax: Int): Boolean { val treeHeight = treeLine[treeIndex] var isVisibleOnTheStart = treeLine.slice(0 until treeIndex).all{it < treeHeight} var isVisibleOnTheEnd = treeLine.slice(treeIndex + 1 .. treeLine.lastIndex).all{it < treeHeight} return isVisibleOnTheStart || isVisibleOnTheEnd } fun lineScenicScore(treeIndex: Int, treeLine: List<Int>): Int { val leftTrees = treeLine.slice(treeIndex - 1 downTo 0) val rightTrees = treeLine.slice(treeIndex + 1 .. treeLine.lastIndex) val treeHeight = treeLine[treeIndex] var leftVisibleTrees = leftTrees.indexOfFirst { it >= treeHeight } + 1 var rightVisibleTrees = rightTrees.indexOfFirst { it >= treeHeight } + 1 if (leftVisibleTrees == 0) leftVisibleTrees = leftTrees.size if (rightVisibleTrees == 0) rightVisibleTrees = rightTrees.size return leftVisibleTrees * rightVisibleTrees } fun part1(input: List<String>): Int { val treeGrid = mutableListOf<List<Int>>() input.forEach { treeGrid.add(it.split("").filterNot(String::isBlank).map(String::toInt)) } var numberOfVisibleTrees = (2 * treeGrid.size + 2 * treeGrid.first().size) - 4 for(i in 1 until treeGrid.lastIndex) { val maxIndexOfCurrentRow = treeGrid[i].indexOfMax() for(j in 1 until treeGrid[i].lastIndex) { val columnValues = treeGrid.map { it[j] } val maxIndexOfCurrentColumn = columnValues.indexOfMax() if (isVisible(j, treeGrid[i], maxIndexOfCurrentRow) || isVisible(i, treeGrid.map { it[j] }, maxIndexOfCurrentColumn)) { numberOfVisibleTrees++ } } } return numberOfVisibleTrees } fun part2(input: List<String>): Int { val treeGrid = mutableListOf<List<Int>>() input.forEach { treeGrid.add(it.split("").filterNot(String::isBlank).map(String::toInt)) } var maxScenicScore = 0 for(i in 1 until treeGrid.lastIndex) { for(j in 1 until treeGrid[i].lastIndex) { val currentTreeScenicScore = lineScenicScore(j, treeGrid[i]) * lineScenicScore(i, treeGrid.map { it[j] }) maxScenicScore = max(currentTreeScenicScore, maxScenicScore) } } return maxScenicScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
785a737b3dd0d2259ccdcc7de1bb705e302b298f
3,086
aoc-2022
Apache License 2.0
aoc/src/main/kotlin/com/bloidonia/aoc2023/day02/Main.kt
timyates
725,647,758
false
{"Kotlin": 45518, "Groovy": 202}
package com.bloidonia.aoc2023.day02 import com.bloidonia.aoc2023.lines const val example1 = """Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green""" private data class Move(val red: Long, val green: Long, val blue: Long) { operator fun plus(other: Move) = Move(red + other.red, green + other.green, blue + other.blue) fun power() = red * green * blue } private data class Game(val id: Int, val moves: List<Move>) { fun max() = moves.reduce { a, b -> Move(maxOf(a.red, b.red), maxOf(a.green, b.green), maxOf(a.blue, b.blue)) } } private fun parseGame(s: String) = Regex("""Game (\d+): (.+)""").matchEntire(s)!!.let { val (game, moves) = it.destructured Game(game.toInt(), moves.split("; ").map { move -> Regex("""(\d+) (blue|red|green)""").findAll(move).map { match -> val (count, color) = match.destructured when (color) { "red" -> Move(count.toLong(), 0, 0) "green" -> Move(0, count.toLong(), 0) "blue" -> Move(0, 0, count.toLong()) else -> throw Exception("Unknown color: $color") } }.reduce { a, b -> a + b } }) } private fun part1(game: Game) = game.moves.all { it.red <= 12 && it.green <= 13 && it.blue <= 14 } fun main() { val result1 = example1.lines().map(::parseGame).filter(::part1).sumOf { it.id } println(result1) val lines = lines("/day02.input") println("part1: ${lines.map(::parseGame).filter(::part1).sumOf { it.id }}") println(example1.lines().map(::parseGame).map(Game::max).map(Move::power).sum()) println("part2: ${lines.map(::parseGame).map(Game::max).map(Move::power).sum()}") }
0
Kotlin
0
0
158162b1034e3998445a4f5e3f476f3ebf1dc952
1,943
aoc-2023
MIT License
src/Day09.kt
nguyendanv
573,066,311
false
{"Kotlin": 18026}
import kotlin.math.abs fun main() { fun follow(moved: Int, follower: Int, positions: List<IntArray>) { val touching = abs(positions[moved][0] - positions[follower][0]) <= 1 && abs(positions[moved][1] - positions[follower][1]) <= 1 when { touching -> {} else -> { when { positions[moved][0] > positions[follower][0] -> positions[follower][0]++ positions[moved][0] < positions[follower][0] -> positions[follower][0]-- } when { positions[moved][1] > positions[follower][1] -> positions[follower][1]++ positions[moved][1] < positions[follower][1] -> positions[follower][1]-- } } } } fun solve(input: List<String>, length: Int): Int { val positions = (0 until length).map { intArrayOf(0, 0) } return input .map { it.split(" ") } .map { (direction, numSteps) -> direction to numSteps.toInt() } .flatMap { (direction, numSteps) -> (0 until numSteps).map { when (direction) { "L" -> positions.first()[0]-- "R" -> positions.first()[0]++ "U" -> positions.first()[1]++ "D" -> positions.first()[1]-- } positions.indices.windowed(2) .forEach { (moved, follower) -> follow(moved, follower, positions) } positions.last()[0] to positions.last()[1] } } .toSet() .count() } fun part1(input: List<String>): Int { return solve(input, 2) } fun part2(input: List<String>): Int { return solve(input, 10) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput)==13) check(part2(testInput)==1) val testInput2 = readInput("Day09_test2") check(part2(testInput2)==36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
376512583af723b4035b170db1fa890eb32f2f0f
2,223
advent2022
Apache License 2.0
src/y2021/Day07.kt
Yg0R2
433,731,745
false
null
package y2021 import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { val sortedInput = input.flatMap { it.split(",") } .toIntList() .sorted() val avgHeight = sortedInput.average().toInt() val avgFuelConsumption = sortedInput.sumOf { abs(avgHeight - it) } return (sortedInput[0]..sortedInput[sortedInput.size - 1]) .map { position -> position to sortedInput.sumOf { abs(position - it) } } .filter { it.second < avgFuelConsumption } .fold(avgFuelConsumption) { currentFuelConsumption: Int, heightToFuelConsumption: Pair<Int, Int> -> if (heightToFuelConsumption.second > currentFuelConsumption) { currentFuelConsumption } else { heightToFuelConsumption.second } } } fun part2(input: List<String>): Int { val sortedInput = input.flatMap { it.split(",") } .toIntList() .sorted() val avgHeight = sortedInput.average().toInt() val avgFuelConsumption = sortedInput.sumOf { (0..abs(avgHeight - it)).sum() } return (sortedInput[0]..sortedInput[sortedInput.size - 1]) .map { position -> position to sortedInput.sumOf { (0..abs(position - it)).sum() } } .filter { it.second < avgFuelConsumption } .fold(avgFuelConsumption) { currentFuelConsumption: Int, heightToFuelConsumption: Pair<Int, Int> -> if (heightToFuelConsumption.second > currentFuelConsumption) { currentFuelConsumption } else { heightToFuelConsumption.second } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput).also { println(it) } == 37) check(part2(testInput).also { println(it) } == 168) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
2,094
advent-of-code
Apache License 2.0
day8/src/main/kotlin/Main.kt
joshuabrandes
726,066,005
false
{"Kotlin": 47373}
import java.io.File fun main() { println("------ Advent of Code 2023 - Day 8 -----") val puzzleInput = getPuzzleInput() val (instructions, nodes) = getInstructionsAndNodes(puzzleInput) val stepsFromAAAToZZZ = stepsFromTo("AAA", { it.name == "ZZZ" }, instructions, nodes.associateBy { it.name }) println("Part 1: Steps from AAA to ZZZ: $stepsFromAAAToZZZ") val shortestPathForGhosts = shortestPathForGhosts("A", "Z", instructions, nodes) println("Part 2: Shortest path for ghosts: $shortestPathForGhosts") println("----------------------------------------") } fun shortestPathForGhosts( start: String, end: String, instructions: List<Char>, nodes: List<Node>, withLogging: Boolean = false ): Long { val startNodes = nodes.filter { it.name.endsWith(start) }.map { it.name }.toSet() val nodeMap = nodes.associateBy { it.name } val allSteps = startNodes .map { stepsFromTo(it, { node -> node.name.endsWith(end) }, instructions, nodeMap, withLogging) } .lcm() return allSteps } fun stepsFromTo( startNode: String, isEndNode: (Node) -> Boolean, instructions: List<Char>, nodeMap: Map<String, Node>, withLogging: Boolean = false ): Long { var currentNode = nodeMap[startNode]!! var steps = 0L while (true) { for (instruction in instructions) { if (isEndNode(currentNode)) { if (withLogging) println("Step $steps: $currentNode") return steps } currentNode = when (instruction) { 'L' -> nodeMap[currentNode.left]!! 'R' -> nodeMap[currentNode.right]!! else -> error("Unknown instruction: $instruction") } steps++ } } } fun getInstructionsAndNodes(puzzleInput: List<String>): Pair<List<Char>, List<Node>> { val instructions = puzzleInput.first().trim().toCharArray().toList() // example: VTM = (VPB, NKT) val nodes = puzzleInput.drop(2) .map { it.split(" = ", limit = 2) } .map { Node(it[0], it[1].substring(1, 4), it[1].substring(6, 9)) } return instructions to nodes } fun getPuzzleInput(): List<String> { val fileUrl = ClassLoader.getSystemResource("input.txt") return File(fileUrl.toURI()).readLines() } fun gcd(a: Long, b: Long): Long { return if (b == 0L) a else gcd(b, a % b) } fun lcm(a: Long, b: Long): Long { return a / gcd(a, b) * b } fun List<Long>.lcm(): Long { return this.reduce { acc, num -> lcm(acc, num) } } data class Node(val name: String, val left: String, val right: String) { override fun toString() = "$name: ($left, $right)" }
0
Kotlin
0
1
de51fd9222f5438efe9a2c45e5edcb88fd9f2232
2,693
aoc-2023-kotlin
The Unlicense
src/y2015/Day09.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2015 import util.readInput object Day09 { private fun parse(input: List<String>): MutableMap<String, MutableMap<String, Int>> { val edges = mutableMapOf<String, MutableMap<String, Int>>() input.forEach { str -> val (a, _, b, _, d) = str.split(' ') val distance = d.toInt() if (edges[a] == null) { edges[a] = mutableMapOf(b to distance) } else { edges[a]!![b] = distance } if (edges[b] == null) { edges[b] = mutableMapOf(a to distance) } else { edges[b]!![a] = distance } } return edges } fun part1(input: List<String>): Int { val edges = parse(input) return shortest(edges, edges.keys) } private fun shortest( edges: Map<String, Map<String, Int>>, unvisited: Set<String>, current: String? = null, distance: Int = 0 ): Int { if (unvisited.isEmpty()) { return distance } return if (current == null) { unvisited.minOf { shortest( edges, unvisited - it, it ) } } else { unvisited.minOf { shortest( edges, unvisited - it, it, edges[current]!![it]!! + distance ) } } } fun part2(input: List<String>): Int { val edges = parse(input) return longest(edges, edges.keys) } private fun longest( edges: Map<String, Map<String, Int>>, unvisited: Set<String>, current: String? = null, distance: Int = 0 ): Int { if (unvisited.isEmpty()) { return distance } return if (current == null) { unvisited.maxOf { longest( edges, unvisited - it, it ) } } else { unvisited.maxOf { longest( edges, unvisited - it, it, edges[current]!![it]!! + distance ) } } } } fun main() { val testInput = """ London to Dublin = 464 London to Belfast = 518 Dublin to Belfast = 141 """.trimIndent().split("\n") println("------Tests------") println(Day09.part1(testInput)) println(Day09.part2(testInput)) println("------Real------") val input = readInput("resources/2015/day09") println(Day09.part1(input)) println(Day09.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,816
advent-of-code
Apache License 2.0
src/Day13.kt
ka1eka
574,248,838
false
{"Kotlin": 36739}
data class ListOrInt(val list: List<ListOrInt>? = null, val int: Int? = null) { fun wrap(): ListOrInt = when (int) { null -> this else -> ListOrInt(listOf(this)) } } fun main() { fun isCorrectOrder(left: ListOrInt, right: ListOrInt?): Boolean? { when { right == null -> return false left.int != null && right.int != null -> return when { left.int < right.int -> true left.int == right.int -> null else -> false } left.list != null && right.list != null -> return when { left.list.isEmpty() && right.list.isNotEmpty() -> true else -> left .list .asSequence() .mapIndexed { index, it -> isCorrectOrder(it, right.list.getOrNull(index)) }.firstNotNullOfOrNull { it } ?: (if (left.list.size == right.list.size) null else true) } else -> return isCorrectOrder(left.wrap(), right.wrap()) } } fun isCorrectOrder(left: List<ListOrInt>, right: List<ListOrInt>): Boolean = left .asSequence() .mapIndexed { index, it -> isCorrectOrder(it, right.getOrNull(index)) }.firstNotNullOfOrNull { it } ?: true fun compare(left: List<ListOrInt>, right: List<ListOrInt>): Int = when (isCorrectOrder(left, right)) { true -> -1 false -> 1 } fun parseMessage(line: String): List<ListOrInt> { if (line.isBlank()) { return listOf() } val path = ArrayDeque<MutableList<ListOrInt>>() path.add(mutableListOf()) var index = 1 var accumulator = "" fun accumulate() { if (accumulator.isNotBlank()) { path.last().add(ListOrInt(int = accumulator.toInt())) accumulator = "" } } while (index < line.length - 1) { when (val current = line[index]) { '[' -> path.addLast(mutableListOf()) ']' -> { accumulate() val list = path.removeLast() path.last().add(ListOrInt(list)) } ',' -> accumulate() else -> accumulator += current } index++ } accumulate() return path.first() } fun part1(input: List<String>): Int = input .asSequence() .map { parseMessage(it) } .chunked(3) .withIndex() .filter { isCorrectOrder(it.value[0], it.value[1]) } .sumOf { it.index + 1 } val marker1 = listOf(ListOrInt(listOf(ListOrInt(int = 2)))) val marker2 = listOf(ListOrInt(listOf(ListOrInt(int = 6)))) fun part2(input: List<String>): Int = ( input .asSequence() .filter { it.isNotBlank() } .map { parseMessage(it) } + sequenceOf(marker1, marker2) ) .sortedWith(::compare) .withIndex() .filter { it.value == marker1 || it.value == marker2 } .fold(1) { acc, it -> acc * (it.index + 1) } val testInput = readInput("Day13_test") check(part1(testInput) == 13) val part2 = part2(testInput) check(part2 == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4f7893448db92a313c48693b64b3b2998c744f3b
3,526
advent-of-code-2022
Apache License 2.0
y2018/src/main/kotlin/adventofcode/y2018/Day23.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution import kotlin.math.abs object Day23 : AdventSolution(2018, 23, "Experimental Emergency Teleportation") { override fun solvePartOne(input: String): Int { val bots = parse(input) val best = bots.maxByOrNull(NanoBot::r)!! return bots.count { it.p in best } } override fun solvePartTwo(input: String): Long? { val bots = parse(input) //guessing there's one clique val cluster = bots.filter { bots.count { b -> it.overlaps(b) } > 500 }.toSet() require(cluster.all { c -> cluster.all(c::overlaps) }) //guessing there's at least one point in the remaining swarm that's covered by all bots. //also guessing this area is small. return cluster .map(::PlanarRepresentation) .reduce(PlanarRepresentation::intersection) .boundingCube() .filter { p -> cluster.all { p in it } } .map { abs(it.x) + abs(it.y) + abs(it.z) } .minOrNull() } private fun parse(input: String): List<NanoBot> = input .filter { it in "-0123456789,\n" } .splitToSequence(",", "\n") .map(String::toLong) .chunked(4) { (x, y, z, r) -> NanoBot(Point3D(x, y, z), r) } .toList() private data class Point3D(val x: Long, val y: Long, val z: Long) { fun distance(other: Point3D) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) infix operator fun plus(other: Point3D) = Point3D(x + other.x, y + other.y, z + other.z) } private data class NanoBot(val p: Point3D, val r: Long) { fun overlaps(other: NanoBot) = p.distance(other.p) <= r + other.r operator fun contains(other: Point3D) = p.distance(other) <= r } /* planar representation of axis-oriented octahedra: z- z+ y+ L3|L0 H1|H2 0 x+ --+-- --+-- L2|L1 H0|H3 The planes are represented by the z-value of the point on the plane where x=0 and y=0 */ private data class PlanarRepresentation(val low: List<Long>, val high: List<Long>) { constructor(b: NanoBot) : this( listOf( -b.p.x - b.p.y + b.p.z - b.r, -b.p.x + b.p.y + b.p.z - b.r, b.p.x + b.p.y + b.p.z - b.r, b.p.x - b.p.y + b.p.z - b.r), listOf( -b.p.x - b.p.y + b.p.z + b.r, -b.p.x + b.p.y + b.p.z + b.r, b.p.x + b.p.y + b.p.z + b.r, b.p.x - b.p.y + b.p.z + b.r)) init { check(isValid()) } fun intersection(o: PlanarRepresentation) = PlanarRepresentation( low.zip(o.low, ::maxOf), high.zip(o.high, ::minOf) ) fun isValid() = low.zip(high).all { (l, h) -> l <= h } fun x() = (low[2] + low[3] - high[0] - high[2]) / 2..(high[2] + high[3] - low[0] - low[2]) / 2 fun y() = (low[1] + low[2] - high[0] - high[2]) / 2..(high[1] + high[2] - low[0] - low[2]) / 2 fun z() = (low[0] + low[2]) / 2..(high[0] + high[2]) / 2 fun boundingCube() = sequence { for (x in x()) for (y in y()) for (z in z()) yield(Point3D(x, y, z)) } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
3,480
advent-of-code
MIT License
src/main/kotlin/aoc2020/ex16.kt
noamfree
433,962,392
false
{"Kotlin": 93533}
fun main() { val input = readInputFile("aoc2020/input16") // val input = """ // class: 1-3 or 5-7 // row: 6-11 or 33-44 // seat: 13-40 or 45-50 // // your ticket: // 7,1,14 // // nearby tickets: // 7,3,47 // 40,4,50 // 55,2,20 // 38,6,12 // """.trimIndent() // val input = """ // class: 0-1 or 4-19 // row: 0-5 or 8-19 // seat: 0-13 or 16-19 // // your ticket: // 11,12,13 // // nearby tickets: // 3,9,18 // 15,1,5 // 5,14,9 // """.trimIndent() val parts = input.split("\n\n") require(parts.size == 3) val rulesPart = parts[0].lines() val ticketsPart = parts[2].lines() require(ticketsPart[0] == "nearby tickets:") val requirements = parseRequirement(rulesPart) val tickets = parseTickets(ticketsPart.drop(1)) val validTickets = validTickets(requirements, tickets) val numberOfFields = tickets.first().fields.size var requirementsOptions = List(numberOfFields) { requirements } validTickets.forEach { ticket -> requirementsOptions = requirementsOptions.filterForTicket(ticket) } var iter = 0 while (requirementsOptions.any { it.size > 1 } && iter < 1000) { iter++ println("removing iteration $iter") requirementsOptions.forEachIndexed { index, list -> if (list.size == 1) { requirementsOptions = chooseOption(requirementsOptions, index) } } } val finalRequirements = requirementsOptions.map { it[0] } val myTicket = parseTicket(parts[1].lines()[1]) myTicket.fields.filterIndexed {index, value -> finalRequirements[index].name.contains("departure") } .fold(1L) {acc, i -> acc*i.toLong() }.let { print(it) } //print(requirementsOptions.map { it.map { it.name }.joinToString(",") }.joinToString("\n")) } private typealias RequirementOptions = List<List<TicketRequirement>> private fun RequirementOptions.filterForTicket(ticket: Ticket): List<List<TicketRequirement>> { return ticket.fields.mapIndexed { index, value -> filterForField(index, value) } } private fun RequirementOptions.filterForField(index: Int, value: Int): List<TicketRequirement> { val optionalRequirements = get(index) if (optionalRequirements.size == 1) return optionalRequirements return optionalRequirements.filter { it.holds(value) }.toList() } private fun chooseOption(requirementsOptions: List<List<TicketRequirement>>, index: Int): List<List<TicketRequirement>> { require(requirementsOptions[index].size == 1) val optionToChoose = requirementsOptions[index][0] return requirementsOptions.mapIndexed { i, list -> if (i == index) return@mapIndexed list val place = list.indexOf(optionToChoose) return@mapIndexed if (place != -1) { list.toMutableList().apply { removeAt(place) } } else list } } private fun validTickets( requirements: List<TicketRequirement>, tickets: List<Ticket> ): List<Ticket> { val allRequirement = unifyAllRequirements(requirements) return tickets .filter { it.fields.all { allRequirement.holds(it) } } } private data class Ticket(val fields: List<Int>) private fun parseTickets(ticketsString: List<String>): List<Ticket> { return ticketsString.map { parseTicket(it) } } private fun parseTicket(ticketsString: String): Ticket { require(ticketsString.lines().size == 1) return Ticket(ticketsString.split(",").map { it.toInt() }) } private fun unifyAllRequirements(requirements: List<TicketRequirement>): TicketRequirement { return TicketRequirement("fake all", requirements.flatMap { it.optionalRanges }) } private data class TicketRequirement( val name: String, val optionalRanges: List<IntRange> ) { fun holds(field: Int): Boolean { return optionalRanges.any { field in it } } } private fun parseRequirement(rulesPart: List<String>) = rulesPart.map { row -> val s = row.split(": ") require(s.size == 2) val name = s[0] val rangesTexts = s[1].split(" or ") require(rangesTexts.size == 2) val ranges: List<IntRange> = rangesTexts.map { rangeText -> val se = rangeText.split("-") require(se.size == 2) val start = se[0].toInt() val end = se[1].toInt() require(start < end) start..end } TicketRequirement( name, ranges ) }
0
Kotlin
0
0
566cbb2ef2caaf77c349822f42153badc36565b7
4,524
AOC-2021
MIT License
src/year2021/day3/Day03.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2021.day3 import readInput fun main() { fun maxFrequency(eachCount: Map<Char, Int>): Char { return eachCount.entries.maxByOrNull { it.value }!!.key } fun minFrequency(eachCount: Map<Char, Int>): Char { return eachCount.entries.minByOrNull { it.value }!!.key } fun part1(input: List<CharSequence>): Int { val values = input.flatMap { it.indices.map { idx -> idx to it[idx] } } .groupBy({ it.first }, { it.second }) .values val a = values.map { maxFrequency(it.groupingBy { it }.eachCount()) }.joinToString("").let { Integer.parseInt(it, 2) } val b = values.map { minFrequency(it.groupingBy { it }.eachCount()) }.joinToString("").let { Integer.parseInt(it, 2) } return a * b } fun extracted(input: List<String>): Int { var f = input for (i in 0..input[0].length) { f = f.groupBy { it[i] }.toSortedMap(comparator = {a,b -> b-a}).maxByOrNull { entry -> entry.value.size }?.value ?: emptyList() if (f.size == 1) break } return Integer.parseInt(f[0], 2) } fun extracted2(input: List<String>): Int { var f = input for (i in 0..input[0].length) { f = f.groupBy { it[i] }.toSortedMap(comparator = {a,b -> a-b}).minByOrNull { entry -> entry.value.size }?.value ?: emptyList() if (f.size == 1) break } return Integer.parseInt(f[0], 2) } fun part2(input: List<String>): Int { return extracted(input) * extracted2(input) } // test if implementation meets criteria from the description, like: val testInput = readInput("year2021/Day03_test") println(part1(testInput)) check(part1(testInput) == 198) val input = readInput("year2021/Day03") println(part1(input)) check(part2(testInput) == 230) println(part2(input)) }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
1,937
adventOfCode
Apache License 2.0
src/Day15.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
import java.lang.IllegalArgumentException import java.util.LinkedList import java.util.regex.Pattern import kotlin.math.abs import kotlin.math.max import kotlin.math.min class IntervalComparator : Comparator<Interval> { override fun compare(t: Interval, other: Interval): Int { val startDiff = t.from - other.from if (startDiff != 0) { return startDiff } return t.toIncl - other.toIncl } } val comparator: Comparator<Interval> = IntervalComparator() data class Interval(val from: Int, val toIncl: Int) { fun toList(): List<Int> { return (from..toIncl).toList() } fun canMerge(other: Interval): Boolean { val (left, right) = if (comparator.compare(this, other) < 0) this to other else other to this return left.toIncl - right.from == 1 || right.from <= left.toIncl } fun merge(other: Interval): Interval = Interval(min(from, other.from), max(toIncl, other.toIncl)) fun contains(x: Int): Boolean = x in from..toIncl } fun main() { val inputRegexp = Pattern.compile("^Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)$") fun parse(input: String): Pair<Point, Point> { val matcher = inputRegexp.matcher(input) if (!matcher.matches()) { throw IllegalArgumentException("Wrong regexp") } val sensor = Point(matcher.group(1).toInt(), matcher.group(2).toInt()) val beacon = Point(matcher.group(3).toInt(), matcher.group(4).toInt()) return sensor to beacon } fun Point.distance(other: Point): Int = abs(this.x - other.x) + abs(this.y - other.y) fun toInterval(sensor: Point, beacon: Point, y: Int): Interval? { val dist = sensor.distance(beacon) val left = dist - abs(sensor.y - y) if (left < 0) return null return Interval(sensor.x - left, sensor.x + left) } fun part1(input: List<String>, row: Int = 10): Int { val sensorsAndBeacons = input.map { parse(it) } val points = sensorsAndBeacons.mapNotNull { toInterval(it.first, it.second, row) }.flatMap { it.toList() }.toSet() return points.size - 1 } fun part2(input: List<String>, maxCoord: Int): Long { val sensorsAndBeacons = input.map { parse(it) } for (y in 1..maxCoord) { val intervals = sensorsAndBeacons.mapNotNull { toInterval(it.first, it.second, y) }.sortedWith(comparator) .toCollection(LinkedList()) while (intervals.size != 1) { val first = intervals.removeFirst() val second = intervals.removeFirst() if (!first.canMerge(second)) { return (first.toIncl + 1).toLong() * 4000000L + y.toLong() } intervals.addFirst(first.merge(second)) } } return -1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput) == 26) println(part2(testInput, 20)) check(part2(testInput, 20) == 56000011L) // check(part2(testInput) == 2713358) //your answer is too low val input = readInput("Day15") println(part1(input, 2000000)) check(part1(input, 2000000) == 5832528) println("started with p2") println(part2(input, 4000000)) check(part2(input, 4000000) == 13360899249595L) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
3,452
advent-of-code-2022
Apache License 2.0
src/Day16.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
import com.github.shiguruikai.combinatoricskt.combinations import java.lang.Integer.min data class Valve( val name: String, val rate: Int, val ways: List<String>, var isOpened: Boolean = false, var waysDistances: MutableMap<String, Int> = mutableMapOf() ) fun wayDistances(start: String, current: String, visited: Set<String>, valves: Map<String, Valve>, wayLength: Int = 0) { if (current in visited) return if (current == start && wayLength != 0) return if (valves[current]!!.rate != 0) if (!valves[start]!!.waysDistances.contains(current)) valves[start]!!.waysDistances[current] = wayLength else valves[start]!!.waysDistances[current] = min(valves[start]!!.waysDistances[current]!!, wayLength) valves[current]!!.ways.forEach { wayDistances(start, it, visited + setOf(current), valves, wayLength + 1) } } fun find( valves: Map<String, Valve>, remainingTime: Int, visited: Set<String>, current: String, total: Int ): Int { val candidates = valves.filter { it.key in valves[current]!!.waysDistances && it.key !in visited }.asSequence() .filter { remainingTime - valves[current]!!.waysDistances[it.key]!! - 1 > 0 } return candidates.maxOfOrNull { val rateTime = remainingTime - valves[current]!!.waysDistances[it.key]!! - 1 find( valves, rateTime, visited + setOf(it.key), it.key, total + ((rateTime) * valves[it.key]!!.rate) ) } ?: total } fun main() { fun part1(input: List<String>): Int { val valves = mutableMapOf<String, Valve>() input.forEach { val split = it.split(" ") val name = split[1] val rate = split[4].substring(5, split[4].lastIndex).toInt() val ways = split.subList(9, split.size).map { way -> way.replace(",", "") } valves[name] = Valve(name, rate, ways) } val start = "AA" valves.keys.forEach { wayDistances(it, it, emptySet(), valves) } val startPosition = valves.values.filter { it.rate == 0 || it.name == "AA" }.map { it.name }.toSet() startPosition.forEach { flow -> valves.values.forEach { it.waysDistances.remove(flow) } } val starts = valves[start]!!.waysDistances.keys valves.values.forEach { it.waysDistances = it.waysDistances.filter { way -> way.key in starts || way.key == start }.toMutableMap() } return find(valves, 30, emptySet(), start, 0) } fun part2(input: List<String>): Int { val valves = mutableMapOf<String, Valve>() input.forEach { val split = it.split(" ") val name = split[1] val rate = split[4].substring(5, split[4].lastIndex).toInt() val ways = split.subList(9, split.size).map { way -> way.replace(",", "") } valves[name] = Valve(name, rate, ways) } val start = "AA" valves.keys.forEach { wayDistances(it, it, emptySet(), valves) } val startPosition = valves.values.filter { it.rate == 0 || it.name == "AA" }.map { it.name }.toSet() startPosition.forEach { flow -> valves.values.forEach { it.waysDistances.remove(flow) } } val starts = valves[start]!!.waysDistances.keys valves.values.forEach { it.waysDistances = it.waysDistances.filter { way -> way.key in starts || way.key == start }.toMutableMap() } val combinations = starts.filterNot { it == start }.combinations(starts.size / 2) return combinations.maxOf { find(valves, 26, it.toSet(), start, 0) + find(valves, 26, starts.toSet() - it.toSet(), start, 0) } } val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
3,942
Advent-of-code
Apache License 2.0
src/Day02.kt
leeturner
572,659,397
false
{"Kotlin": 13839}
import DesiredResult.* import GameChoice.* typealias Game = Pair<GameChoice, GameChoice> typealias FixedGame = Pair<GameChoice, DesiredResult> enum class GameChoice(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3) } enum class DesiredResult { WIN, DRAW, LOSE } fun String.toGameChoice() = when (this) { in listOf("A", "X") -> ROCK in listOf("B", "Y") -> PAPER in listOf("C", "Z") -> SCISSORS else -> throw IllegalArgumentException("GameChoice character not supported - $this") } fun String.toDesiredResult() = when (this) { "X" -> LOSE // need to lose "Y" -> DRAW // need draw "Z" -> WIN // need to win else -> throw IllegalArgumentException("DesiredResult character not supported - $this") } fun DesiredResult.toGameChoice(opponent: GameChoice): GameChoice { return when (this) { WIN -> { when (opponent) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } } DRAW -> { when (opponent) { ROCK -> ROCK PAPER -> PAPER SCISSORS -> SCISSORS } } LOSE -> { when (opponent) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } } } } fun Game.isDraw() = this.first == this.second fun Game.isWin() = when { this.second == ROCK && this.first == SCISSORS -> true this.second == PAPER && this.first == ROCK -> true this.second == SCISSORS && this.first == PAPER -> true else -> false } fun main() { fun part1(input: List<String>): Int { return input .map { gameString -> gameString.split(' ').map { it.toGameChoice() } } .map { Game(it[0], it[1]) } .sumOf { game -> when { game.isWin() -> 6 + game.second.score game.isDraw() -> 3 + game.second.score else -> 0 + game.second.score } } } fun part2(input: List<String>): Int { return input .map { gameString -> gameString.split(' ') } .map { FixedGame(it[0].toGameChoice(), it[1].toDesiredResult()) } .map { Game(it.first, it.second.toGameChoice(it.first)) } .sumOf { game -> when { game.isWin() -> 6 + game.second.score game.isDraw() -> 3 + game.second.score else -> 0 + game.second.score } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8da94b6a0de98c984b2302b2565e696257fbb464
2,649
advent-of-code-2022
Apache License 2.0
src/year2023/day02/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2023.day02 import arrow.core.nonEmptyListOf import kotlin.math.max import utils.ProblemPart import utils.readInputs import utils.runAlgorithm fun main() { val (realInput, testInputs) = readInputs(2023, 2, transform = ::parseInput) runAlgorithm( realInput = realInput, testInputs = testInputs, part1 = ProblemPart( expectedResultsForTests = nonEmptyListOf(8), algorithm = ::part1, ), part2 = ProblemPart( expectedResultsForTests = nonEmptyListOf(2286), algorithm = ::part2, ), ) } private fun parseInput(input: List<String>): List<Match> = input.mapIndexed { index, match -> Match( number = index + 1, games = match.replace(prefixRegex, "") .splitToSequence(';') .map(colorResultRegex::findAll) .map { games -> games.associate { it.groupValues[2] to it.groupValues[1].toInt() } } .toList() ) } private val prefixRegex = "Game \\d+: ".toRegex() private val colorResultRegex = "(\\d+) (red|green|blue)".toRegex() private fun part1(input: List<Match>): Int { return input.asSequence() .filterNot { match -> match.games.any { it.getOrDefault("red", 0) > 12 || it.getOrDefault("green", 0) > 13 || it.getOrDefault("blue", 0) > 14 } } .sumOf { it.number } } private fun part2(input: List<Match>): Long { return input.asSequence() .map { match -> match.games.fold(Triple(0L, 0L, 0L)) { accumulator, game -> Triple( max(accumulator.first, game.getOrDefault("red", 0).toLong()), max(accumulator.second, game.getOrDefault("green", 0).toLong()), max(accumulator.third, game.getOrDefault("blue", 0).toLong()), ) } } .sumOf { it.first * it.second * it.third } } private data class Match( val number: Int, val games: List<GameResult>, ) private typealias GameResult = Map<String, Int>
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,157
Advent-of-Code
Apache License 2.0
src/Day04.kt
graesj
572,651,121
false
{"Kotlin": 10264}
fun IntRange.size(): Int = this.last - this.first fun stringToSections(it: String): Pair<IntRange, IntRange> { val split = it.split("-") return split.first().toInt()..split[1].substringBefore(",").toInt() to split[1].substringAfter(",").toInt()..split.last().toInt() } fun partitionBySize(rangePair: Pair<IntRange, IntRange>): Pair<IntRange, IntRange> { val (firstRange, secondRange) = rangePair return if (firstRange.size() <= secondRange.size()) firstRange to secondRange else secondRange to firstRange } fun main() { fun part1(input: List<String>): Int { return input.map { stringToSections(it) }.count { sectionPair -> val (smallestSection, largestSection) = partitionBySize(sectionPair) smallestSection.first >= largestSection.first && smallestSection.last <= largestSection.last } } fun part2(input: List<String>): Int { return input.map { stringToSections(it) }.count { sectionPair -> val (smallestSection, largestSection) = partitionBySize(sectionPair) largestSection.contains(smallestSection.first) || largestSection.contains(smallestSection.last) } } // test if implementation meets criteria from the description, like: val testInput = readLines("Day04_test") check(part1(testInput) == 2) val input = readLines("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
df7f855a14c532f3af7a8dc86bd159e349cf59a6
1,471
aoc-2022
Apache License 2.0
src/Day02.kt
esp-er
573,196,902
false
{"Kotlin": 29675}
package patriker.day02 import patriker.utils.* operator fun String.component1(): Char { return this[0] } operator fun String.component2(): Char { return this[1] } operator fun String.component3(): Char { return this[2] } enum class GameResult(val score: Int){ LOSS(0), DRAW(3), WIN(6) } enum class Hand{ ROCK, PAPER, SCISSOR } fun Hand.losesAgainst(): Hand{ return when(this){ Hand.ROCK -> Hand.PAPER Hand.PAPER -> Hand.SCISSOR Hand.SCISSOR -> Hand.ROCK } } fun Hand.winsAgainst(): Hand{ return when(this){ Hand.ROCK -> Hand.SCISSOR Hand.PAPER -> Hand.ROCK Hand.SCISSOR -> Hand.PAPER } } fun Char.toHand(): Hand{ return when(this){ 'A', 'X' -> Hand.ROCK 'B', 'Y' -> Hand.PAPER 'C', 'Z' -> Hand.SCISSOR else -> Hand.ROCK } } fun playGame(playerHand: Hand, opponentHand: Hand): GameResult{ val result = when{ playerHand == opponentHand -> GameResult.DRAW playerHand.losesAgainst() == opponentHand -> GameResult.LOSS playerHand.winsAgainst() == opponentHand -> GameResult.WIN else -> GameResult.DRAW } return result } fun calcPlayerScore(playerHand: Hand, result: GameResult): Int{ val handScore = playerHand.ordinal + 1 val gameScore = result.score return handScore + gameScore } fun handToPlay(playerResult: Char, opponentHand: Hand): Hand{ return when(playerResult){ 'X' -> opponentHand.winsAgainst() 'Y' -> opponentHand 'Z' -> opponentHand.losesAgainst() else -> opponentHand } } fun solvePart1(inputList: List<String>): Int{ val gamesScores = inputList.asSequence().filter(String::isNotBlank).map{ gameInput -> val (opponentChar, _, playerChar) = gameInput val gameResult = playGame(playerChar.toHand(), opponentChar.toHand()) calcPlayerScore(playerChar.toHand(), gameResult) } return gamesScores.sum() } fun solvePart2(inputList: List<String>): Int{ val gamesScores = inputList.asSequence().filter(String::isNotBlank).map{ gameInput -> val (opponentChar, _, playerResult) = gameInput val opponentHand = opponentChar.toHand() val playerHand = handToPlay(playerResult, opponentHand) val gameResult = playGame(playerHand, opponentHand) calcPlayerScore(playerHand, gameResult) } return gamesScores.sum() } fun main() { // test if implementation meets criteria from the description, like: println("::day2:: part 1 :: ") val testInput = readInput("Day02_test") check(solvePart1(testInput) == 15) val input = readInput("Day02_input") println(solvePart1(input)) println("::day2:: part 2 :: ") check(solvePart2(testInput) == 12) println(solvePart2(input)) }
0
Kotlin
0
0
f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362
2,798
aoc2022
Apache License 2.0
src/Day07a.kt
palex65
572,937,600
false
{"Kotlin": 68582}
private typealias Device = Map<String,Int> private fun part1(dev: Device): Int = dev.values.sumOf { if (it<=100000) it else 0 } private fun part2(dev: Device): Int { val toFree = 30000000 - (70000000 - (dev[""]?:0)) return dev.values.filter { it>=toFree }.min() } private fun Device(lines: List<String>): Map<String,Int> = buildMap { var wd = "" val idxCmds = lines.mapIndexedNotNull { idx, line -> if (line[0]=='$' && idx>0) idx else null } idxCmds.forEachIndexed { idx, idxCmd -> val cmdLine = lines[idxCmd].substringAfter("$ ") when (cmdLine.substringBefore(' ')) { "ls" -> { val size = lines .subList(idxCmd + 1, if (idx < idxCmds.lastIndex) idxCmds[idx + 1] else lines.size) .filter { !it.startsWith("dir") }.sumOf { it.substringBefore(' ').toInt() } var dir = wd while(true) { put(dir, (get(dir) ?: 0) + size) if (dir=="" || size==0) break dir = dir.substringBeforeLast('/') } } "cd" -> wd = when (val name = cmdLine.substringAfter(' ')) { ".." -> wd.substringBeforeLast('/') else -> "$wd/$name" } } } } fun main() { val dev_test = Device(readInput("Day07_test")) check(part1(dev_test) == 95437) check(part2(dev_test) == 24933642) val dev = Device(readInput("Day07")) println(part1(dev)) // 1306611 println(part2(dev)) // 13210366 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
1,567
aoc2022
Apache License 2.0
2021/src/main/kotlin/day20_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.Parser import utils.Solution fun main() { Day20Func.run() } object Day20Func : Solution<Pair<IntGrid, List<Int>>>() { override val name = "day20" override val parser = Parser { input -> val (lookupString, imageString) = input.split("\n\n", limit = 2) val lookup = lookupString.replace("\n", "").trim().map { if (it == '#') 1 else 0 } val gridLines = imageString.split("\n").map { it.trim() }.filter { it.isNotBlank() } val gridW = gridLines.first().length val gridH = gridLines.size val grid = IntGrid(gridW, gridH) { (x, y) -> if (gridLines[y][x] == '#') 1 else 0 } return@Parser grid.borderWith(0, borderWidth = 2) to lookup } fun enhance(input: IntGrid, lookup: List<Int>): IntGrid { val padding = if (input[0][0] == 0) lookup[0] else lookup[511] return IntGrid(input.width, input.height) { coord -> if (coord.x < 1 || coord.y < 1 || coord.x >= input.width - 1 || coord.y >= input.height - 1) { return@IntGrid padding } val lookupIndex = (coord.y - 1 .. coord.y + 1).flatMapIndexed { yPos, y -> (coord.x - 1 .. coord.x + 1).mapIndexed { xPos, x -> val shift = (8 - (yPos * 3 + xPos)) require(shift in 0 .. 8) { "Shift out of bounds" } input[x][y] shl shift } }.sum() require(lookupIndex <= lookup.size) { "Lookup index too large!" } return@IntGrid lookup[lookupIndex] }.borderWith(padding) } override fun part1(input: Pair<IntGrid, List<Int>>): Int { val (grid, lookup) = input val round2 = (0 until 2).fold(grid) { acc, _ -> enhance(acc, lookup) } return round2.values.count { it > 0 } } override fun part2(input: Pair<IntGrid, List<Int>>): Int { val (grid, lookup) = input val result = (0 until 50).fold(grid) { acc, _ -> enhance(acc, lookup) } return result.values.count { it > 0 } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,914
aoc_kotlin
MIT License
src/Day15.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
import kotlin.math.abs import kotlin.math.absoluteValue // Lots of inspiration for both parts taken from here: https://nickymeuleman.netlify.app/garden/aoc2022-day15 fun main() { data class Position(val x: Long, val y: Long) { fun manhattanDistance(to: Position): Long { return abs(x - to.x) + abs(y - to.y) } } data class Sensor(val position: Position, val beacon: Position) { fun findCoverageAlongY(y: Long): LongRange? { val radius = position.manhattanDistance(beacon) val offset = radius - (position.y - y).absoluteValue if (offset < 0) return null return (position.x - offset)..(position.x + offset) } } fun processInput(input: List<String>): List<Sensor> { val sensors = mutableListOf<Sensor>() val indices = listOf(2, 3, 8, 9) val regex = Regex("-?\\d+") for (line in input) { val parts = line.split(' ').withIndex() .filter { indices.contains(it.index) } .map { regex.find(it.value)!!.value.toLong() } sensors.add(Sensor( Position(parts[0], parts[1]), Position(parts[2], parts[3]) )) } return sensors } fun findCoveredRangesAlongY(sensors: List<Sensor>, y: Long): List<LongRange> { val ranges: List<LongRange> = sensors .mapNotNull { it.findCoverageAlongY(y) } .sortedBy { it.first } val mergedRanges = mutableListOf(ranges[0]) for (i in 1 until ranges.size) { val range = ranges[i] val lastMerged = mergedRanges.last() // Attempt to merge this range with the previous if they overlap, otherwise just add the range to the list if (!(range.first > lastMerged.last || range.last < lastMerged.first)) { if (range.last > lastMerged.last) { mergedRanges[mergedRanges.lastIndex] = lastMerged.first..range.last } } else { mergedRanges.add(range) } } return mergedRanges } fun part1(sensors: List<Sensor>, atY: Long): Long { val covered = findCoveredRangesAlongY(sensors, atY).sumOf { it.count() }.toLong() val beacons = sensors.filter { it.beacon.y == atY }.map { it.beacon.x }.distinct().size.toLong() return covered - beacons } fun part2(sensors: List<Sensor>, max: Long): Long { val result = (0..max) .map { Pair(it, findCoveredRangesAlongY(sensors, it)) } .find { it.second.size > 1 }!! val y = result.first val x = result.second.first().last + 1 return x * 4_000_000 + y } val testInput = processInput(readInput("Day15_test")) check(part1(testInput.toList(), 10L) == 26L) check(part2(testInput, 20L) == 56000011L) val input = processInput(readInput("Day15")) println(part1(input, 2000000L)) println(part2(input, 4_000_000L)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
3,045
aoc-2022
Apache License 2.0
src/Day14meilisearch1.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
class PathNode(val parent: PathNode?) { var left: PathNode? = null var right: PathNode? = null var name: String? = null fun path(): String { return (parent?.path() ?: "") + when (this) { parent?.left -> "L" parent?.right -> "R" else -> "" } } fun stops(): Int { return (parent?.stops() ?: 0) + if (parent?.left != null && parent?.right != null) 1 else 0 } fun minStops(): Pair<PathNode, Int> { println(this) val leftStops = left?.minStops() val rightStops = right?.minStops() val thisStops = this.minStops() val min = minOf( left?.minStops(), right?.minStops(), this.minStops(), compareBy(nullsLast()) { it?.second }) if (left == null && right == null) return Pair(this, stops()) if (left != null && right != null) { val leftPair = left!!.minStops() val rightPair = right!!.minStops() if (leftPair.second < rightPair.second) return Pair(leftPair.first, leftPair.second + 1) if (leftPair.second > rightPair.second) return Pair(rightPair.first, rightPair.second + 1) return if (left!!.path() < right!!.path()) Pair(leftPair.first, leftPair.second + 1) else Pair(rightPair.first, rightPair.second + 1) } return if (left != null) left!!.minStops() else right!!.minStops() } override fun toString(): String { return path() + " : " + (name ?: "") + stops() } fun add(path: String, name: String) { if (path.isEmpty()) this.name = name else when (path.first()) { 'L' -> left = (left ?: PathNode(this)).apply { add(path.drop(1), name) } 'R' -> right = (right ?: PathNode(this)).apply { add(path.drop(1), name) } } } } fun main() { fun part1(input: List<String>): String { val root = PathNode(null) input.forEach { line -> val (name, path) = line.split(" - ") root.add(path, name) } val result = root.minStops().first return result.name!! } fun part2(input: List<String>): String { return "" } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14meilisearch1_test") println(part1(testInput)) // check(part1(testInput) == "caro") // println(part2(testInput)) // check(part2(testInput) == 0) val input = readInput("Day14meilisearch1") // println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
2,713
AoC-2022
Apache License 2.0
2023/src/main/kotlin/net/daams/solutions/7b.kt
Michiel-Daams
573,040,288
false
{"Kotlin": 39925, "Nim": 34690}
package net.daams.solutions import net.daams.Solution class `7b`(input: String): Solution(input) { override fun run() { val hands = mutableListOf<Pair<Hand, Int>>() input.split("\n").forEach { val hand = it.split(" ") hands.add(Pair(Hand(hand[0]), hand[1].toInt())) } val winnings = mutableListOf<Int>() hands.sortedBy { it.first }.forEachIndexed{ index, pair -> winnings.add(pair.second * (index + 1)) } println(winnings.sum()) } private class Hand(val hand: String): Comparable<Hand> { private val sortedHand = sortHand(hand) private var tier = 0 init { var sameCards = 0 sortedHand.forEach { if (it == sortedHand[0] || it == 'J') sameCards ++ } this.tier = sameCards if (sameCards >= 3) this.tier++ if (sameCards >= 4) this.tier++ if (sameCards == 2 && sortedHand[2] == sortedHand[3]) this.tier = 3 if (sameCards == 3 && sortedHand[3] == sortedHand[4]) this.tier = 5 } override operator fun compareTo(other: Hand): Int { if (this.tier == other.tier) { for (i in 0 .. 4) { if (Card(this.hand[i]).compareTo(Card(other.hand[i])) == 0) continue return Card(this.hand[i]).compareTo(Card(other.hand[i])) } } return this.tier.compareTo(other.tier) } private fun sortHand(hand: String): String { val frequencyMap = hashMapOf<Char, Int>() hand.forEach { frequencyMap[it] = frequencyMap.getOrDefault(it, 0) + 1 } var output = "" val nonJ = frequencyMap.toList().filter { it.first != 'J' }.sortedByDescending { it.second } val j = frequencyMap.getOrDefault('J', 0) if (nonJ.isNotEmpty()) { for (i in 1 .. nonJ[0].second) { output += nonJ[0].first } } for (i in 1 .. j) { output += 'J' } if (nonJ.size > 1) { nonJ.subList(1, nonJ.size).forEachIndexed { index, pair -> for (i in 1 .. nonJ[index + 1].second) { output += pair.first } } } return output } } private class Card(private val card: Char): Comparable<Card> { private val valueMap = hashMapOf( Pair('A', 13), Pair('K', 12), Pair('Q', 11), Pair('T', 10), Pair('9', 9), Pair('8', 8), Pair('7', 7), Pair('6', 6), Pair('5', 5), Pair('4', 4), Pair('3', 3), Pair('2', 2), Pair('J', 1)) override operator fun compareTo(other: Card): Int { return valueMap[this.card]!!.compareTo(this.valueMap[other.card]!!) } } }
0
Kotlin
0
0
f7b2e020f23ec0e5ecaeb97885f6521f7a903238
3,097
advent-of-code
MIT License
src/Day11.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
import java.util.LinkedList fun main() { class Monkey( val items: LinkedList<Long> = LinkedList(), val ops: Array<String> = Array(3) { "" }, val tests: Array<Int> = Array(3) { 0 }, ) fun List<String>.toMonkeys(): List<Monkey> { return chunked(7).map { ms -> val monkey = Monkey() ms[1].split(":")[1].split(",").map { it.trim().toLong() }.forEach { monkey.items.add(it) } ms[2].split(" ").takeLast(3).forEachIndexed { i, s -> monkey.ops[i] = s } monkey.tests[0] = ms[3].split(" ").last().toInt() monkey.tests[1] = ms[4].split(" ").last().toInt() monkey.tests[2] = ms[5].split(" ").last().toInt() monkey } } fun solve(monkeys: List<Monkey>, repeatNum: Int, transfer: (a: Long) -> Long): Long { val cnt = Array(monkeys.size) { 0 } fun inspect() { monkeys.forEachIndexed { index, monkey -> cnt[index] += monkey.items.size val items = monkey.items val ops = monkey.ops val tests = monkey.tests for (item in items) { val a = if (ops[0] == "old") item else ops[0].toLong() val b = if (ops[2] == "old") item else ops[2].toLong() val newValue = transfer(if (ops[1] == "+") a + b else a * b) if (newValue % tests[0] == 0L) { monkeys[tests[1]].items.add(newValue) } else { monkeys[tests[2]].items.add(newValue) } } monkey.items.clear() } } repeat(repeatNum) { inspect() } return cnt.sortedDescending().take(2).let { 1L * it[0] * it[1] } } fun part1(input: List<String>): Long { return solve(input.toMonkeys(), 20) { it / 3 } } fun part2(input: List<String>): Long { val monkeys = input.toMonkeys() val mod = monkeys.map { it.tests[0] }.reduce { acc, i -> acc * i } return solve(monkeys, 10000) { it % mod } } println(part1(readInput("data/Day11_test"))) println(part1(readInput("data/Day11"))) println(part2(readInput("data/Day11_test"))) println(part2(readInput("data/Day11"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
2,422
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/aoc2015/KnightsOfTheDinnerTable.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2015 import komu.adventofcode.utils.nonEmptyLines import komu.adventofcode.utils.permutations private val dinnerTablePattern = Regex("""(.+) would (lose|gain) (\d+) happiness units by sitting next to (.+).""") private fun dinnerTableScore(permutation: List<String>, rulesByPerson: Map<String, List<DinnerTableRule>>): Int { var score = 0 for ((i, person) in permutation.withIndex()) { val left = permutation[(i + permutation.size - 1) % permutation.size] val right = permutation[(i + 1) % permutation.size] score += rulesByPerson[person]!!.filter { it.other == left || it.other == right }.sumOf { it.change } } return score } private fun bestDinnerTableScore(rules: List<DinnerTableRule>): Int { val rulesByPerson = rules.groupBy { it.person } var bestScore = Int.MIN_VALUE for (permutation in rulesByPerson.keys.toList().permutations()) bestScore = maxOf(bestScore, dinnerTableScore(permutation, rulesByPerson)) return bestScore } fun knightsOfTheDinnerTable1(input: String) = bestDinnerTableScore(input.nonEmptyLines().map { DinnerTableRule.parse(it) }) fun knightsOfTheDinnerTable2(input: String): Int { val rules = input.nonEmptyLines().map { DinnerTableRule.parse(it) }.toMutableList() for (person in rules.map { it.person }.distinct()) { rules.add(DinnerTableRule("me", 0, person)) rules.add(DinnerTableRule(person, 0, "me")) } return bestDinnerTableScore(rules) } private data class DinnerTableRule(val person: String, val change: Int, val other: String) { companion object { fun parse(s: String): DinnerTableRule { val (_, person, op, num, other) = dinnerTablePattern.matchEntire(s)?.groupValues ?: error("no match '$s'") val change = if (op == "gain") num.toInt() else -num.toInt() return DinnerTableRule(person, change, other) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,945
advent-of-code
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2023/day03/day3.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day03 import biz.koziolek.adventofcode.* import kotlin.math.log10 fun main() { val inputFile = findInput(object {}) val engineSchematic = parseEngineSchematic(inputFile.bufferedReader().readLines()) println("Sum of numbers adjacent to a symbol: ${engineSchematic.numbersAdjacentToSymbol.sumOf { it.number }}") println("Sum of all of the gear ratios: ${engineSchematic.gears.sumOf { it.ratio }}") } data class EngineSchematic(val numbers: List<EngineNumber>) { val numbersAdjacentToSymbol: List<EngineNumber> get() = numbers.filter { it.symbols.isNotEmpty() } val gears: List<EngineGear> get() = numbers .flatMap { number -> number.symbols .filter { it.symbol.isGear() } .map { it to number } } .groupBy( keySelector = { it.first }, valueTransform = { it.second } ) .filter { it.value.size == 2 } .map { EngineGear(it.key.coord, it.value[0], it.value[1]) } } data class EngineNumber(val number: Int, val coord: Coord, val symbols: List<EngineSymbol>) data class EngineSymbol(val symbol: Char, val coord: Coord) data class EngineGear(val coord: Coord, val num1: EngineNumber, val num2: EngineNumber) { val ratio = num1.number * num2.number } fun parseEngineSchematic(lines: Iterable<String>): EngineSchematic { val map = lines.parse2DMap().toMap() val width = map.getWidth() val height = map.getHeight() val numbers = buildList { var y = 0 while (y < height) { var x = 0 while (x < width) { var number = 0 val startCoord = Coord(x, y) var coord = startCoord while (coord.x < width && map[coord]?.isDigit() == true) { number = number * 10 + map[coord]!!.digitToInt() coord += Coord(1, 0) } if (number > 0) { val numDigits = log10(number.toDouble()).toInt() + 1 val symbols = (startCoord.x until (startCoord.x + numDigits)) .flatMap { xx -> map.getAdjacentCoords(Coord(x = xx, y = startCoord.y), includeDiagonal = true) } .toSet() .mapNotNull { adjCoord -> map[adjCoord] ?.takeIf { it.isSymbol() } ?.let { symbol -> EngineSymbol(symbol, adjCoord) } } add(EngineNumber(number, startCoord, symbols)) x += numDigits } else { x++ } } y++ } } return EngineSchematic(numbers) } private const val EMPTY = '.' private const val GEAR = '*' private fun Char.isSymbol() = !this.isDigit() && this != EMPTY // What about letters? private fun Char.isGear() = this == GEAR
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
3,088
advent-of-code
MIT License
src/day2/Day02.kt
omarshaarawi
573,867,009
false
{"Kotlin": 9725}
package day2 import day2.Move.Companion.relationships import day2.Move.X import day2.Move.Y import day2.Move.Z import day2.Result.DRAW import day2.Result.LOSE import day2.Result.WIN import readInput enum class Move(val point: Int, val move: String) { A(1, "rock"), B(2, "paper"), C(3, "scissors"), X(1, "rock"), Y(2, "paper"), Z(3, "scissors"); companion object { val relationships = listOf( RelationShip(A, X, DRAW), // rock vs rock RelationShip(A, Y, WIN), // rock vs paper RelationShip(A, Z, LOSE), // rock vs scissors RelationShip(B, X, LOSE), // paper vs rock RelationShip(B, Y, DRAW), // paper vs paper RelationShip(B, Z, WIN), // paper vs scissors RelationShip(C, X, WIN), // scissor vs rock RelationShip(C, Y, LOSE), // scissor vs paper RelationShip(C, Z, DRAW) // scissor vs scissor ) } } enum class Result(val points: Int) { WIN(6), LOSE(0), DRAW(3) } data class RelationShip(val opponent: Move, val me: Move, val result: Result) fun main() { fun part1(): Int { val input = readInput("day2/Day02").map { val (a, b) = it.split(" ") Move.valueOf(a.first().toString()) to Move.valueOf(b.first().toString()) } val points = input.map { match -> val relationship = relationships.firstOrNull { it.opponent == match.first && it.me == match.second } relationship!!.me.point.plus(relationship.result.points) } return points.sum() } fun part2(): Int { val input = readInput("day2/Day02").map { val (a, b) = it.split(" ") Move.valueOf(a.first().toString()) to Move.valueOf(b.first().toString()) } val points = input.map { match -> val relationship = relationships.filter { when (match.second) { X -> { it.opponent == match.first && it.result == LOSE } Y -> { it.opponent == match.first && it.result == DRAW } Z -> { it.opponent == match.first && it.result == WIN } else -> throw Exception("Invalid move") } }.first() relationship.me.point.plus(relationship.result.points) } return points.sum() } println(part1()) println(part2()) }
0
Kotlin
0
0
4347548045f12793a8693c4d31fe3d3dade5100a
2,574
advent-of-code-kotlin-2022
Apache License 2.0
src/day18/Main.kt
nikwotton
572,814,041
false
{"Kotlin": 77320}
package day18 import java.io.File import kotlin.math.abs const val workingDir = "src/day18" data class Position(val x: Int, val y: Int, val z: Int) { val immediatelyNextTo: List<Position> by lazy { listOf( Position(x-1, y, z), Position(x+1, y, z), Position(x, y-1, z), Position(x, y+1, z), Position(x, y, z-1), Position(x, y, z+1), ) } } typealias Air = Position typealias Rock = Position fun File.toRocks(): List<Rock> = readLines().map { it.split(",").map { it.toInt() } }.map { (x, y, z) -> Position(x, y, z) } fun main() { val sample = File("$workingDir/sample.txt") val input1 = File("$workingDir/input_1.txt") println("Step 1a: ${runStep1(sample)}") // 64 println("Step 1b: ${runStep1(input1)}") // 3494 println("Step 2a: ${runStep2(sample)}") // 58 println("Step 2b: ${runStep2(input1)}") // 2062 } fun runStep1(input: File): String { val rocks: List<Rock> = input.toRocks() val totalSides = rocks.size * 6 require(rocks.size == rocks.toSet().size) { "Found duplicate: ${rocks - rocks.toSet()}" } val sharedSides = rocks.sumOf { rock -> rocks.map { it in rock.immediatelyNextTo }.count { it } } return (totalSides - sharedSides).toString() } fun runStep2(input: File): String { val rocks: List<Rock> = input.toRocks() val totalSides = rocks.size * 6 require(rocks.size == rocks.toSet().size) { "Found duplicate: ${rocks - rocks.toSet()}" } val minX = rocks.minOf { it.x } - 1 val maxX = rocks.maxOf { it.x } + 1 val minY = rocks.minOf { it.y } - 1 val maxY = rocks.maxOf { it.y } + 1 val minZ = rocks.minOf { it.z } - 1 val maxZ = rocks.maxOf { it.z } + 1 val airs: List<Air> = (minX..maxX).flatMap { x -> (minY..maxY).flatMap { y -> (minZ..maxZ).map { z -> Position(x, y, z) } } }.filter { it !in rocks } fun Position.isBorderPosition() = x in listOf(minX, maxX) || y in listOf(minY, maxY) || z in listOf(minZ, maxZ) tailrec fun canEscape(possibilities: List<Position>, seen: List<Position> = listOf()): Boolean { if (possibilities.isEmpty()) return false val checking = possibilities.first() return if (checking in rocks) canEscape(possibilities - checking, seen + checking) else if (checking.isBorderPosition()) true else canEscape(possibilities + checking.immediatelyNextTo.filter { it !in possibilities && it !in seen } - checking, seen + checking) } fun Air.canEscape() = canEscape(listOf(this)) val enclosedAirs = airs.filter { !it.canEscape() } val sharedSides = rocks.sumOf { rock -> (rocks + enclosedAirs).map { it in rock.immediatelyNextTo }.count { it } } return (totalSides - sharedSides).toString() }
0
Kotlin
0
0
dee6a1c34bfe3530ae6a8417db85ac590af16909
2,810
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2023/Day24.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import PointL import readInput import withEachOf import java.lang.IllegalArgumentException import kotlin.math.abs object Day24 { private data class Hailstone(val position: PointL, val velocity: PointL) { companion object { // 19, 13, 30 @ -2, 1, -2 private val regex = """(?<x>-?\d+),\s+(?<y>-?\d+),\s+(?<z>-?\d+)\s+@\s+(?<dx>-?\d+),\s+(?<dy>-?\d+),\s+(?<dz>-?\d+)""".toRegex() fun fromString(input: String): Hailstone { val match = regex.matchEntire(input) if (match != null) { val get = { key: String -> match.groups[key]!!.value.toLong() } return Hailstone(PointL(get("x"), get("y")), PointL(get("dx"), get("dy"))) } else throw IllegalArgumentException("Does not match: $input") } } // private val b = ((position.x / velocity.x.toDouble())) * -velocity.y.toDouble() + position.y private val a = velocity.y / velocity.x.toDouble() /** * @return the point where this and [other] intersect or null, if they never do */ fun intersect(other: Hailstone): Pair<Double, Double>? { if (this.a == other.a) return null // intersection: x, y // -> this.a * x + this.b = y // -> other.a * x + other.b = y // -> this.a * x + this.b = other.a * x + other.b // -> this.a * x + this.b - other.a * x = other.b // -> (this.a - other.a) * x + this.b = other.b // -> (this.a - other.a) * x = other.b - this.b // -> x = (other.b - this.b) / (this.a - other.a) val x = (other.b - this.b) / (this.a - other.a) val y = this.a * x + this.b return x to y } /** * @return true, if the [point] was already past some time ago by this hailstone */ fun inThePast(point: Pair<Double, Double>) = abs(position.x + velocity.x - point.first) > abs(position.x - point.first) } fun part1(input: List<String>, min: Long, max: Long): Int { val range = min.toDouble()..max.toDouble() val hailstones = input.map { Hailstone.fromString(it) }.asSequence() return hailstones.withEachOf(hailstones) .filter { it.first != it.second } .filter { val intersection = it.first.intersect(it.second) intersection != null // they do intersect... && intersection.first in range && intersection.second in range // ...in the given range && !it.first.inThePast(intersection) && !it.second.inThePast(intersection)// ...in the future } .count() / 2 // if A hits B, then B also hits A -> divide result by 2 } fun part2(input: List<String>): Int { return 0 } } fun main() { val testInput = readInput("Day24_test", 2023) check(Day24.part1(testInput, 7L, 27L) == 2) check(Day24.part2(testInput) == 0) val input = readInput("Day24", 2023) println(Day24.part1(input, 200000000000000L, 400000000000000L)) println(Day24.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
3,229
adventOfCode
Apache License 2.0
src/Day02.kt
Miguel1235
726,260,839
false
{"Kotlin": 21105}
data class Game(val id: Int, val cubes: List<Cubes>) { fun isGamePossible(): Boolean { for (cube in cubes) { val (blue, red, green) = cube if (red > 12 || green > 13 || blue > 14) return false } return true } fun maxColor(color: String): Int { var maxValue = 0 for (bag in cubes) { if (bag[color] > maxValue) maxValue = bag[color] } return maxValue } } data class Cubes(var blue: Int, var red: Int, var green: Int) { operator fun get(color: String): Int { return when (color) { "blue" -> blue "red" -> red "green" -> green else -> 0 } } } private fun makeGame(line: String): Game { val colorsRegex = Regex("""(\d+) (red|green|blue)""") val cubes: MutableList<Cubes> = mutableListOf() val inputBags = line.split(":")[1].split(";") for (ibag in inputBags) { val bagCount = mutableMapOf("green" to 0, "red" to 0, "blue" to 0) val results = colorsRegex.findAll(ibag) for (r in results) { val color = r.groupValues[2] val count = r.groupValues[1].toInt() bagCount[color] = bagCount[color]!! + count } cubes.add(Cubes(bagCount["blue"]!!, bagCount["red"]!!, bagCount["green"]!!)) } val gameId = Regex("""Game \d+""").find(line)!!.value.split(" ")[1].toInt() return Game(gameId, cubes) } private val part1 = { games: List<Game> -> games.fold(0) { acc, game -> if (game.isGamePossible()) acc + game.id else acc } } private val part2 = { games: List<Game> -> games.fold(0) { acc, game -> acc + (game.maxColor("red") * game.maxColor("green") * game.maxColor("blue")) } } fun main() { val testInput = readInput("Day02_test") val gamesTest = testInput.map { game -> makeGame(game) } check(part1(gamesTest) == 8) check(part2(gamesTest) == 2286) val input = readInput("Day02") val games = input.map { game -> makeGame(game) } part1(games).println() part2(games).println() }
0
Kotlin
0
0
69a80acdc8d7ba072e4789044ec2d84f84500e00
2,100
advent-of-code-2023
MIT License
src/main/kotlin/Day14.kt
Vampire
572,990,104
false
{"Kotlin": 57326}
import kotlin.math.max typealias Node = Pair<Int, Int> fun main() { fun part1(input: List<String>, withFloor: Boolean = false): Int { val structures = input .map { structure -> structure .split(" -> ") .map { node -> node .split(",") .map(String::toInt) .let { (x, y) -> Node(x, y) } } } val maxX = structures.maxOf { structure -> structure.maxOf(Node::first) } val minX = structures.minOf { structure -> structure.minOf(Node::first) } val maxY = structures.maxOf { structure -> structure.maxOf(Node::second) } val floorY = maxY + 2 val cave = arrayOf( *((0..max(maxX, 500 + (floorY + 1))).map { booleanArrayOf( *((0..floorY).map { false }.toBooleanArray()) ) }.toTypedArray()) ) structures .toMutableList() .apply { add(listOf(Node(500 - (floorY + 1), floorY), Node(500 + (floorY + 1), floorY))) } .forEach { structure -> var lastNode = structure.first() cave[lastNode.first][lastNode.second] = true for (node in structure.drop(1)) { when { lastNode.first == node.first -> listOf(lastNode, node) .map(Node::second) .sorted() .also { (from, to) -> (from..to).forEach { cave[node.first][it] = true } } lastNode.second == node.second -> listOf(lastNode, node) .map(Node::first) .sorted() .also { (from, to) -> (from..to).forEach { cave[it][node.second] = true } } else -> error("Broken structure $lastNode -> $node") } lastNode = node } } var sandAmount = -1 while (true) { sandAmount++ var sandX = 500 var sandY = 0 while (true) { if (withFloor && (sandX == 500) && (sandY == 0) && cave[sandX][sandY]) { return sandAmount } when { !cave[sandX][sandY + 1] -> sandY++ !cave[sandX - 1][sandY + 1] -> { sandX-- sandY++ } !cave[sandX + 1][sandY + 1] -> { sandX++ sandY++ } else -> { cave[sandX][sandY] = true break } } if (!withFloor && ((sandX !in (minX..maxX)) || (sandY >= maxY))) { return sandAmount } } } } fun part2(input: List<String>) = part1(input, withFloor = true) val testInput = readStrings("Day14_test") check(part1(testInput) == 24) val input = readStrings("Day14") println(part1(input)) check(part2(testInput) == 93) println(part2(input)) }
0
Kotlin
0
0
16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f
3,694
aoc-2022
Apache License 2.0
src/main/day15/day15.kt
rolf-rosenbaum
572,864,107
false
{"Kotlin": 80772}
package day15 import Point import day15.CavePoint.Sensor import kotlin.math.abs import readInput import union val regex = """.+x=(-?\d+).*y=(-?\d+):.*x=(-?\d+).*y=(-?\d+)""".toRegex() const val prd_row = 2_000_000 const val test_row = 10 val prd_range = 0..4000000 val test_range = 0..20 typealias Cave = MutableSet<CavePoint> sealed class CavePoint(open val location: Point) { data class BeaconExcluded(override val location: Point) : CavePoint(location) data class Sensor(override val location: Point, val beacon: Point) : CavePoint(beacon) { val beaconDistance get() = location.distanceTo(beacon) } override fun equals(other: Any?): Boolean { return if (other is CavePoint) location == other.location else false } override fun hashCode(): Int { return location.hashCode() } } fun main() { val input = readInput("main/day15/Day15_test") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int { val cave = input.parse() val row = if (input.size < 20) test_row else prd_row cave.markNoBeaconArea(row) val beaconLocations = cave.filterIsInstance<Sensor>().map { it.beacon }.toSet() return cave.count { it.location.y == row && it.location !in beaconLocations } } fun part2(input: List<String>): Long { val cave = input.parse() val range = if (input.size > 20) prd_range else test_range range.forEach { row -> cave.lineRangesFor(row).reduce { acc, range -> (acc.union(range)) ?: return (acc.last + 1) * 4_000_000L + row } } return -1 } fun Cave.markNoBeaconArea(row: Int) { val sensors = filterIsInstance<Sensor>() sensors.forEach { sensor -> (sensor.location.x - sensor.beaconDistance..sensor.location.x + sensor.beaconDistance).forEach { x -> val candidate = Point(x, row) if (candidate.distanceTo(sensor.location) <= sensor.beaconDistance) add(CavePoint.BeaconExcluded(candidate)) } } } fun Cave.lineRangesFor(row: Int): List<IntRange> { return filterIsInstance<Sensor>().map { sensor -> val distance = sensor.beaconDistance - abs(row - sensor.location.y) sensor.location.x - distance..sensor.location.x + distance }.sortedBy { it.first } } fun List<String>.parse(): Cave = map { regex.matchEntire(it)?.destructured?.let { (sX, sY, bX, bY) -> Sensor(location = Point(x = sX.toInt(), y = sY.toInt()), beacon = Point(bX.toInt(), bY.toInt())) } ?: error("PARSER PROBLEM") }.toMutableSet()
0
Kotlin
0
2
59cd4265646e1a011d2a1b744c7b8b2afe482265
2,546
aoc-2022
Apache License 2.0
src/Day08.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
fun main() { fun part1(input: List<String>): Int { val grid = input.map { it.toList() } val size = grid.size var visibleTrees = (size * 4) - 4 for (x in 1 until size - 1) { for (y in 1 until size - 1) { val tree = grid[y][x] val north = grid.subList(0, y).map { it[x] } val east = grid[y].subList(x + 1, size) val south = grid.subList(y + 1, size).map { it[x] } val west = grid[y].subList(0, x) val blockedNorth = north.any { it >= tree } val blockedEast = east.any { it >= tree } val blockedSouth = south.any { it >= tree } val blockedWest = west.any { it >= tree } if (!blockedNorth || !blockedEast || !blockedSouth || !blockedWest) visibleTrees++ } } return visibleTrees } fun part2(input: List<String>): Int { val grid = input.map { it.toList() } val size = grid.size var highestScore = 0 fun countVisible(trees: List<Char>, height: Char): Int { var visible = 0 for (tree in trees) { visible++ if (tree >= height) break } return visible } for (x in 1 until size - 1) { for (y in 1 until size - 1) { val tree = grid[y][x] val north = grid.subList(0, y).map { it[x] }.reversed() val east = grid[y].subList(x + 1, size) val south = grid.subList(y + 1, size).map { it[x] } val west = grid[y].subList(0, x).reversed() val visibleNorth = countVisible(north, tree) val visibleEast = countVisible(east, tree) val visibleSouth = countVisible(south, tree) val visibleWest = countVisible(west, tree) val score = visibleNorth * visibleEast * visibleSouth * visibleWest if (score > highestScore) highestScore = score } } return highestScore } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
2,346
aoc-2022
Apache License 2.0
src/Day12.kt
mihansweatpants
573,733,975
false
{"Kotlin": 31704}
import java.lang.RuntimeException fun main() { val input = readInput("Day12").lines() fun part1(input: List<String>): Int { return shortestPathLength(input, getPoint(input, 'S'), getPoint(input, 'E')) ?: throw RuntimeException("Path not found") } fun part2(input: List<String>): Int { return getPoints(input, setOf('a', 'S')) .mapNotNull { shortestPathLength(input, it, getPoint(input, 'E')) } .minOrNull() ?: throw RuntimeException("Path not found") } println(part1(input)) println(part2(input)) } private fun shortestPathLength(input: List<String>, startPoint: Point, endPoint: Point): Int? { val visited = mutableSetOf<Point>() val queue = ArrayDeque<Pair<Point, Int>>().apply { add(startPoint to 0) } while (queue.isNotEmpty()) { val (currentPoint, currentStepsTaken) = queue.removeFirst() if (currentPoint in visited) continue visited.add(currentPoint) if (currentPoint == endPoint) { return currentStepsTaken } currentPoint.getAdjacentPoints(input).forEach { adjacentPoint -> if (currentPoint.canClimb(adjacentPoint) && adjacentPoint !in visited) { queue.add(adjacentPoint to currentStepsTaken + 1) } } } return null } private data class Point( val x: Int, val y: Int, val elevation: Char ) { fun getHeight(): Int { return when (elevation) { 'E' -> 'z' 'S' -> 'a' else -> elevation }.code } fun canClimb(to: Point) = to.getHeight() <= getHeight() + 1 fun getAdjacentPoints(grid: List<String>): List<Point> { val maxX = grid[0].lastIndex val maxY = grid.lastIndex return mutableListOf<Point>().apply { if (x + 1 <= maxX) add(copy(x = x + 1, elevation = grid[y][x + 1])) if (x - 1 >= 0) add(copy(x = x - 1, elevation = grid[y][x - 1])) if (y + 1 <= maxY) add(copy(y = y + 1, elevation = grid[y + 1][x])) if (y - 1 >= 0) add(copy(y = y - 1, elevation = grid[y - 1][x])) } } } private fun getPoint(input: List<String>, target: Char): Point = getPoints(input, setOf(target)).first() private fun getPoints(input: List<String>, targets: Set<Char>): List<Point> = input.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, char -> if (char in targets) Point(x, y, char) else null } }
0
Kotlin
0
0
0de332053f6c8f44e94f857ba7fe2d7c5d0aae91
2,518
aoc-2022
Apache License 2.0
src/Day15.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
import kotlin.math.abs private fun pos(): List<Sensor> { return readInput("Day15").map { it.split(": ") }.map { val sensor = parseC(it[0].substring("Sensor at ".length)) val beacon = parseC(it[1].substring("closest beacon is at ".length)) Sensor(sensor, beacon, sensor.manhattan(beacon)) } } // For each sensor we can calculate intersection segment of its area and given row. // Then we take a length of union of those segments and subtract any beacons or sensors which happens to be in the union private fun part1(sensors: List<Sensor>): Int { val row = 2000000 // val row = 10 val sSorted: List<IntRange> = sensors.filter { abs(it.sensor.y - row) <= it.dist }.map { s -> val diff = s.dist - abs(s.sensor.y - row) IntRange(s.sensor.x - diff, s.sensor.x + diff) }.sortedBy { it.first } val sUnion = mutableListOf<IntRange>() var start = sSorted[0].first var end = sSorted[0].last sSorted.forEach { s -> if (s.first > end) { sUnion.add(IntRange(start, end)) start = s.first end = s.last } if (s.first <= end && s.last > end) { end = s.last } } sUnion.add(IntRange(start, end)) var noBPos = sUnion.sumOf(IntRange::count) noBPos -= sensors.count { s -> s.sensor.y == row && sUnion.any { it.contains(s.sensor.x) } } noBPos -= sensors.map { s -> s.beacon }.toSet().count { b -> b.y == row && sUnion.any { it.contains(b.x) } } return noBPos } // Observation: point should be between 2 pairs of areas which are on a distance 1 of each other, like so // / * / // / * / // / * / // and // \ * \ // \ * \ // \ * \ // their intersection gives exactly 1 possible point. // We can calculate intersection point: // knowing that one line has y = -x + b1 and another y = x + b2 => y = (b1 + b2) / 2, x = (b1 - b2) / 2 // b1 and b2 could be found simply from the points which we know are on the lines: // \ // \ <- for example that point on the right angle with coords (sensor.x + 1 + dist; sensor.y) // / *<-/ and then b2 = y - x // / * / similar for b1 = x + y // / * / private fun part2(sensors: List<Sensor>): Long { val pairs: MutableList<Pair<Sensor, Sensor>> = mutableListOf() for (i in sensors.indices) { for (j in i + 1..sensors.lastIndex) { val centerDist = sensors[i].sensor.manhattan(sensors[j].sensor) val beaconDist = sensors[i].dist + sensors[j].dist if (centerDist - beaconDist == 2) pairs.add(Pair(sensors[i], sensors[j])) } } val xOrdPairs = pairs.map { (p1, p2) -> if (p1.sensor.x < p2.sensor.x) Pair(p1, p2) else Pair(p2, p1) } // y = -x + b1 val leftDown = xOrdPairs.find { (p1, p2) -> (p1.sensor.y < p2.sensor.y) }!!.first val b1 = leftDown.sensor.x + leftDown.dist + 1 + leftDown.sensor.y // y = x + b2 val leftUp = xOrdPairs.find { (p1, p2) -> (p1.sensor.y > p2.sensor.y) }!!.first val b2 = leftUp.sensor.y - (leftUp.sensor.x + leftUp.dist + 1) // intersection point val y = (b1 + b2) / 2 val x = (b1 - b2) / 2 return if (!withinRange(C(x, y), sensors)) x * 4000000L + y else -1 } private fun withinRange(c: C, sensors: List<Sensor>): Boolean = sensors.any { (c.manhattan(it.sensor) <= it.dist) } fun main() { measure { part1(pos()) } measure { part2(pos()) } } data class Sensor(val sensor: C, val beacon: C, val dist: Int)
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
3,577
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch8/Problem88.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch8 import kotlin.math.sqrt /** * Problem 88: Product-Sum Numbers * * https://projecteuler.net/problem=88 * * Goal: Find the sum of all unique product-sum numbers for 2 <= k <= N. * * Constraints: 10 <= N <= 2e5 * * Product-Sum Number: A natural number that can be written as both the sum and the product of a * given set of at least 2 natural numbers, such that N = a1+a2+..+ak = a1*a2*..*ak. * * Minimal Product-Sum Number: For a given set of size k, the smallest N that is a product-sum * number; e.g. k = 2: 4 = 2 + 2 + 2 * 2 * k = 3: 6 = 1 + 2 + 3 = 1 * 2 * 3 * k = 4: 8 = 1 + 1 + 2 + 4 = 1 * 1 * 2 * 4 * k = 5: 8 = 1 + 1 + 2 + 2 + 2 = 1 * 1 * 2 * 2 * 2 * k = 6: 12 = 1 + 1 + 1 + 1 + 2 + 6 = 1 * 1 * 1 * 1 * 2 * 6 * Therefore, for 2 <= k <= 6, the sum of unique minimal product-sum numbers is 30. * * e.g.: N = 12 * 2 <= k <= 12 -> {4, 6, 8, 8, 12, 12, 12, 15, 16, 16, 16} * sum = 61 */ class ProductSumNumbers { private val limit = 200_000 // exclude 0 and 1 from cache, so minimalPS for k found at cache[k-2] private val minimalPSCache = IntArray(limit - 1) { Int.MAX_VALUE } fun sumOfPSNumbers(maxK: Int): Int { return minimalPSCache.sliceArray(0..maxK-2).toSet().sum() } fun generatePSNumbers() { var generated = 0 var num = 4 // minimalPSNum for k = 2 while (generated < limit - 1) { // a number can be a minimalPSNum for multiple k generated += countKIfPS(num, num, num) num++ } } /** * Recursively remove factors from a number (and from its corresponding sum) & store it if it * is a valid product-sum number for any k. */ private fun countKIfPS( n: Int, product: Int, sum: Int, factors: Int = 0, minFactor: Int = 2 ): Int { if (product == 1) { // remaining sum must be all 1s return if (isMinimalPSNum(n, factors + sum)) 1 else 0 } var result = 0 if (factors > 0) { // at least 1 factor has been removed if (product == sum) { return if (isMinimalPSNum(n, factors + 1)) 1 else 0 } if (isMinimalPSNum(n, factors + sum - product + 1)) { result++ } } for (i in minFactor..sqrt(1.0 * product).toInt()) { if (product % i == 0) { result += countKIfPS(n, product / i, sum - i, factors + 1, i) } } return result } private fun isMinimalPSNum(n: Int, k: Int): Boolean { if (k > limit) return false return if (n < minimalPSCache[k-2]) { minimalPSCache[k-2] = n true } else false } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,815
project-euler-kotlin
MIT License
src/Day11.kt
psy667
571,468,780
false
{"Kotlin": 23245}
fun plus(a: Long, b: String): Long { return if (b == "old") { a + a } else { a + b.toLong() } } fun prod(a: Long, b: String): Long { return if (b == "old") { a * a } else { a * b.toLong() } } data class Monkey(val id: Long, var items: MutableList<Long>, val op: (a: Long, b: String) -> Long, val opArg: String, val divBy: Long, val ifTrue: Long, val ifFalse: Long, var inspectedItems: Long) fun main() { val id = "11" fun parse(input: List<String>): List<Monkey> { return input.joinToString("\n").split("\n\n").map { val d = it.split("\n") val id = d[0].substring(7, 8).toLong() val items = d[1].substring(18).split(", ").map(String::toLong).toMutableList() val op = d[2][23] val opFn = if (op == '+') ::plus else ::prod val opArg = d[2].substring(25) val div = d[3].substring(21).toLong() val ifT = d[4].substring(29).toLong() val ifF = d[5].substring(30).toLong() Monkey(id,items,opFn,opArg,div,ifT,ifF,0) } } fun part1(input: List<String>): Long { val monkeys = parse(input) repeat(20) { monkeys.forEach { monkey -> monkey.items.forEach { item -> monkey.inspectedItems++ val new = monkey.op(item, monkey.opArg) val newDiv = new / 3 if (newDiv % monkey.divBy == 0L) { monkeys.find { it.id == monkey.ifTrue }!!.items.add(newDiv) } else { monkeys.find { it.id == monkey.ifFalse }!!.items.add(newDiv) } } monkey.items = mutableListOf() } } return monkeys .map { it.inspectedItems } .sortedDescending() .take(2) .reduce { acc, cur -> acc * cur } } fun part2(input: List<String>): Long { val monkeys = parse(input) val div = monkeys.map{it.divBy}.reduce { acc, cur -> acc * cur } repeat(10000) { monkeys.forEach { monkey -> monkey.items.forEach { item -> monkey.inspectedItems++ val new = monkey.op(item, monkey.opArg) val newDiv = new % div if (newDiv % monkey.divBy == 0L) { val m = monkeys.find { it.id == monkey.ifTrue }!! m.items.add(newDiv) } else { val m = monkeys.find { it.id == monkey.ifFalse }!! m.items.add(newDiv) } } monkey.items = mutableListOf() } } return monkeys .map { it.inspectedItems } .sortedDescending() .take(2) .reduce { acc, cur -> acc * cur } } val testInput = readInput("Day${id}_test") check(part2(testInput) == 2713310158L) val input = readInput("Day${id}") println("==== DAY $id ====") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
73a795ed5e25bf99593c577cb77f3fcc31883d71
3,244
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day7.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.* fun main() { val input = Input.day(7) println(day7A(input)) println(day7B(input)) } fun day7A(input: Input): Int { val hands = input.lines.map { Hand(it) } return totalWinnings(hands) } fun day7B(input: Input): Int { val hands = input.lines.map { Hand(it, true) } return totalWinnings(hands) } private fun totalWinnings(hands: List<Hand>): Int { return hands.sorted().mapIndexed { index, hand -> hand.bid * (index + 1) }.sum() } private class Hand(input: String, private val jokerMode: Boolean = false): Comparable<Hand> { val hand = input.split(' ')[0] val bid = input.split(' ')[1].toInt() val type = if(jokerMode) Type.fromWithJokers(hand) else Type.from(hand) private fun Char.value(): Int { return when(this) { 'T' -> 10 'J' -> if(jokerMode) 1 else 11 'Q' -> 12 'K' -> 13 'A' -> 15 else -> digitToInt() } } override fun compareTo(other: Hand): Int { type.sortValue.compareTo(other.type.sortValue).let { if(it != 0) return it } hand.forEachIndexed { index, c -> c.value().compareTo(other.hand[index].value()).let { if(it != 0) return it } } return 0 } } private enum class Type(val nextWithJoker: Type?, val sortValue: Int) { FiveOfAKind(null, 7), FourOfAKind(FiveOfAKind, 6), FullHouse(FourOfAKind, 5), ThreeOfAKind(FourOfAKind, 4), TwoPair(FullHouse, 3), OnePair(ThreeOfAKind, 2), HighCard(OnePair, 1); companion object { fun from(hand: String): Type { val times = hand.groupBy { it }.map { it.value.size } return when { times.contains(5) -> FiveOfAKind times.contains(4) -> FourOfAKind times.contains(3) && times.contains(2) -> FullHouse times.contains(3) -> ThreeOfAKind times.count { it == 2 } == 2 -> TwoPair times.contains(2) -> OnePair else -> HighCard } } fun fromWithJokers(hand: String): Type { if(hand == "JJJJJ") return FiveOfAKind var type = from(hand.filter { it != 'J' }) repeat(hand.count { it == 'J' }) { type = type.nextWithJoker ?: throw Exception("FiveOfAKind can't have more jokers") } return type } } }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
2,500
AdventOfCode2023
MIT License
src/Day02.kt
Xacalet
576,909,107
false
{"Kotlin": 18486}
/** * ADVENT OF CODE 2022 (https://adventofcode.com/2022/) * * Solution to day 2 (https://adventofcode.com/2022/day/2) * */ private enum class Hand(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3) } fun main() { fun resolveRound(myHand: Hand, opponentsHand: Hand): Int { val pointsFromChosenHand = myHand.points val pointsFromRoundOutcome = if (myHand == opponentsHand) { 3 } else if (myHand == Hand.PAPER && opponentsHand == Hand.ROCK || myHand == Hand.SCISSORS && opponentsHand == Hand.PAPER || myHand == Hand.ROCK && opponentsHand == Hand.SCISSORS) { 6 } else { 0 } return pointsFromChosenHand + pointsFromRoundOutcome } fun part1(strategy: List<Pair<String, String>>): Int { return strategy.map { (h1, h2) -> val opponentsHand = when (h1) { "A" -> Hand.ROCK "B" -> Hand.PAPER "C" -> Hand.SCISSORS else -> throw IllegalArgumentException("Unknown input: $h1") } val myHand = when (h2) { "X" -> Hand.ROCK "Y" -> Hand.PAPER "Z" -> Hand.SCISSORS else -> throw IllegalArgumentException("Unknown input: $h2") } Pair(opponentsHand, myHand) }.sumOf { (opponentsHand, myHand) -> resolveRound(myHand, opponentsHand) } } fun part2(strategy: List<Pair<String, String>>): Int { return strategy.map { (h1, h2) -> val opponentsHand = when (h1) { "A" -> Hand.ROCK "B" -> Hand.PAPER "C" -> Hand.SCISSORS else -> throw IllegalArgumentException("Unknown input: $h1") } val myHand = when (h2) { "X" -> when(opponentsHand) { Hand.ROCK -> Hand.SCISSORS Hand.PAPER -> Hand.ROCK Hand.SCISSORS -> Hand.PAPER } "Y" -> opponentsHand "Z" -> when(opponentsHand) { Hand.ROCK -> Hand.PAPER Hand.PAPER -> Hand.SCISSORS Hand.SCISSORS -> Hand.ROCK } else -> throw IllegalArgumentException("Unknown input: $h2") } Pair(opponentsHand, myHand) }.sumOf { (opponentsHand, myHand) -> resolveRound(myHand, opponentsHand) } } val strategy = readInputLines("day02_dataset").map { line -> line.split(" ").let { (h1, h2) -> Pair(h1, h2) } } part1(strategy).println() part2(strategy).println() }
0
Kotlin
0
0
5c9cb4650335e1852402c9cd1bf6f2ba96e197b2
2,727
advent-of-code-2022
Apache License 2.0
src/day_2/kotlin/Day2.kt
Nxllpointer
573,051,992
false
{"Kotlin": 41751}
// AOC Day 2 enum class Move(val score: Int, defeats: () -> Move) { ROCK(1, { SCISSORS }), PAPER(2, { ROCK }), SCISSORS(3, { PAPER }); val defeats by lazy { defeats() } } data class Round(val opponentMove: Move, val myMove: Move) { enum class Result(val score: Int) { LOOSE(0), WIN(6), DRAW(3) } val result = when { opponentMove.defeats == myMove -> Result.LOOSE myMove.defeats == opponentMove -> Result.WIN else -> Result.DRAW } val myScore = myMove.score + result.score } fun moveLetterToMove(letter: String): Move? = when (letter) { "A", "X" -> Move.ROCK "B", "Y" -> Move.PAPER "C", "Z" -> Move.SCISSORS else -> null } fun resultLetterToResult(letter: String): Round.Result? = when (letter) { "X" -> Round.Result.LOOSE "Y" -> Round.Result.DRAW "Z" -> Round.Result.WIN else -> null } fun part1(roundsRaw: List<List<String>>) { val rounds = roundsRaw .map { it.map { moveLetter -> moveLetterToMove(moveLetter) } } .map { Round(it[0]!!, it[1]!!) } val totalScore = rounds.sumOf { it.myScore } println("Part 1: The total score of all rounds is $totalScore") } fun part2(roundsRaw: List<List<String>>) { val rounds = roundsRaw.map { val opponentMove = moveLetterToMove(it[0])!! val neededResult = resultLetterToResult(it[1])!! val neededMove = when (neededResult) { Round.Result.LOOSE -> Move.values().first { move -> opponentMove.defeats == move } Round.Result.DRAW -> opponentMove Round.Result.WIN -> Move.values().first { move -> move.defeats == opponentMove } } Round(opponentMove, neededMove) .apply { check(result == neededResult) { "Needed move was not chosen correctly" } } } val totalScore = rounds.sumOf { it.myScore } println("Part 2: The total score of all rounds is $totalScore") } fun main() { val roundsRaw = getAOCInput { rawInput -> rawInput .trim() .split("\n") .map { it.split(" ") } } part1(roundsRaw) part2(roundsRaw) }
0
Kotlin
0
0
b6d7ef06de41ad01a8d64ef19ca7ca2610754151
2,183
AdventOfCode2022
MIT License
src/Day08.kt
StephenVinouze
572,377,941
false
{"Kotlin": 55719}
data class OuterTrees( val topTrees: List<Int>, val leftTrees: List<Int>, val rightTrees: List<Int>, val bottomTrees: List<Int>, ) fun main() { fun List<String>.toTrees(): List<List<Int>> = map { it.toCharArray().toList().map { treeChar -> treeChar.digitToInt() } } fun isTreeVisible(tree: Int, outerTrees: OuterTrees): Boolean = listOf(outerTrees.topTrees, outerTrees.leftTrees, outerTrees.rightTrees, outerTrees.bottomTrees) .any { sideTrees -> sideTrees.isEmpty() || sideTrees.all { it < tree } } fun computeScenicScore(tree: Int, outerTrees: OuterTrees): Int = listOf(outerTrees.topTrees, outerTrees.leftTrees, outerTrees.rightTrees, outerTrees.bottomTrees) .map { sideTrees -> val visibleTrees = sideTrees.takeWhile { it < tree }.size if (visibleTrees != 0 && visibleTrees < sideTrees.size) visibleTrees + 1 else visibleTrees } .fold(1) { total, scenicScore -> total * scenicScore } fun outerTrees( trees: List<List<Int>>, treeRow: List<Int>, treeRowIndex: Int, treeIndex: Int, ): OuterTrees { val topTrees = mutableListOf<Int>() val leftTrees = mutableListOf<Int>() val rightTrees = mutableListOf<Int>() val bottomTrees = mutableListOf<Int>() (0 until treeRow.lastIndex).forEachIndexed { index, _ -> trees.getOrNull(treeRowIndex - 1 - index)?.getOrNull(treeIndex)?.let { topTrees += it } trees.getOrNull(treeRowIndex)?.getOrNull(treeIndex - 1 - index)?.let { leftTrees += it } trees.getOrNull(treeRowIndex)?.getOrNull(treeIndex + 1 + index)?.let { rightTrees += it } trees.getOrNull(treeRowIndex + 1 + index)?.getOrNull(treeIndex)?.let { bottomTrees += it } } return OuterTrees(topTrees, leftTrees, rightTrees, bottomTrees) } fun part1(input: List<String>): Int { var scenicScore = 0 val trees = input.toTrees() trees.forEachIndexed { treeRowIndex, treeRow -> treeRow.forEachIndexed { treeIndex, tree -> val outerTrees = outerTrees(trees, treeRow, treeRowIndex, treeIndex) if (isTreeVisible(tree, outerTrees)) { scenicScore++ } } } return scenicScore } fun part2(input: List<String>): Int { var maxScenicScore = 0 val trees = input.toTrees() trees.forEachIndexed { treeRowIndex, treeRow -> treeRow.forEachIndexed { treeIndex, tree -> val outerTrees = outerTrees(trees, treeRow, treeRowIndex, treeIndex) val scenicScore = computeScenicScore(tree, outerTrees) if (scenicScore > maxScenicScore) { maxScenicScore = scenicScore } } } return maxScenicScore } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
11b9c8816ded366aed1a5282a0eb30af20fff0c5
3,252
AdventOfCode2022
Apache License 2.0
src/Day17.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import java.util.PriorityQueue import kotlin.math.min private const val EXPECTED_1 = 102 private const val EXPECTED_2 = 94 private class Day17(isTest: Boolean) : Solver(isTest) { val field = readAsLines().map { it.toCharArray() } val Y = field.size val X = field[0].size data class Point(val y: Int, val x: Int, val dir: Int, val sameDir: Int, val score: Int) val dirs = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1) fun bestPath(minLen: Int, maxLen: Int): Int { val best = mutableMapOf<Point, Int>() val q = PriorityQueue<Point>(Comparator.comparing { it.score }) for (dir in 0..3) { val start = Point(0, 0, dir, 0, 0) q.add(start) best[start] = 0 } var ans = Int.MAX_VALUE while (!q.isEmpty()) { val p = q.remove() if (p.score > ans) { break } if (p.sameDir < maxLen) { val nx = p.x + dirs[p.dir].second val ny = p.y + dirs[p.dir].first if (nx in 0 until X && ny in 0 until Y) { val newScore = p.score + field[ny][nx].code - '0'.code if (nx == X - 1 && ny == Y - 1) { ans = min(ans, newScore) } fun tryAdd(np: Point) { if (np.score > ans) { return } val c = np.copy(score = 0) val current = best[c] if (current == null || current > newScore) { best[c] = newScore q.add(np) } } tryAdd(Point(ny, nx, p.dir, p.sameDir + 1, newScore)) if (p.sameDir + 1 >= minLen) { for (plusDir in listOf(1, 3)) { tryAdd(Point(ny, nx, (p.dir + plusDir) % 4, 0, newScore)) } } } } } return ans } fun part1() = bestPath(1, 3) fun part2() = bestPath(4, 10) } fun main() { val testInstance = Day17(true) val instance = Day17(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
2,589
advent-of-code-2022
Apache License 2.0
src/Day18.kt
maewCP
579,203,172
false
{"Kotlin": 59412}
fun main() { fun adjacent(coordinate: Triple<Int, Int, Int>): List<Triple<Int, Int, Int>> { val (x, y, z) = coordinate.toList() return listOf( Triple(x - 1, y, z), Triple(x + 1, y, z), Triple(x, y - 1, z), Triple(x, y + 1, z), Triple(x, y, z - 1), Triple(x, y, z + 1) ) } fun prepareInput(input: List<String>): MutableSet<Triple<Int, Int, Int>> { val droplets = mutableSetOf<Triple<Int, Int, Int>>() input.forEach { line -> val (x, y, z) = line.split(",").map { it.toInt() } droplets.add(Triple(x, y, z)) } return droplets } fun part1(input: List<String>): Int { val droplets = prepareInput(input) return droplets.sumOf { droplet -> adjacent(droplet).sumOf { adjacentDroplet -> (if (droplets.contains(adjacentDroplet)) 0 else 1) as Int } } } fun part2(input: List<String>): Int { val droplets = prepareInput(input) val xRange = (droplets.minOf { it.first } - 1..droplets.maxOf { it.first } + 1) val yRange = (droplets.minOf { it.second } - 1..droplets.maxOf { it.second } + 1) val zRange = (droplets.minOf { it.third } - 1..droplets.maxOf { it.third } + 1) val waterLeaked = mutableSetOf<Triple<Int, Int, Int>>() val checkQueue = mutableListOf(Triple(xRange.toList().first(), yRange.toList().first(), zRange.toList().first())) var leakedSurfaceCount = 0 while (checkQueue.size > 0) { val checkNext = checkQueue.removeAt(0) waterLeaked.add(checkNext) adjacent(checkNext).forEach { adjacent -> if (droplets.contains(adjacent)) { leakedSurfaceCount++ } else if (!waterLeaked.contains(adjacent) && !checkQueue.contains(adjacent) && adjacent.first in xRange && adjacent.second in yRange && adjacent.third in zRange ) { checkQueue.add(adjacent) } } } return leakedSurfaceCount } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") part1(input).println() part2(input).println() }
0
Kotlin
0
0
8924a6d913e2c15876c52acd2e1dc986cd162693
2,488
advent-of-code-2022-kotlin
Apache License 2.0
src/Day12.kt
frungl
573,598,286
false
{"Kotlin": 86423}
import java.util.* fun main() { fun bfs(graph: List<String>, sX: Int, sY: Int, eX: Int, eY: Int): Int { val n = graph.size val m = graph[0].length val dist = mutableMapOf<Pair<Int, Int>, Int>() val q = LinkedList<Pair<Int, Int>>() dist[sX to sY] = 0 q.addFirst(sX to sY) val go = listOf( 0 to 1, 1 to 0, 0 to -1, -1 to 0 ) while (!q.isEmpty()) { val (x, y) = q.last q.removeLast() for ((dx, dy) in go) { if(x + dx < 0 || x + dx >= n) continue if(y + dy < 0 || y + dy >= m) continue if(dist.containsKey(x + dx to y + dy)) continue val ch = graph[x + dx][y + dy] if (ch - graph[x][y] > 1) continue dist[x + dx to y + dy] = dist[x to y]!! + 1 q.addFirst(x + dx to y + dy) } } return dist[eX to eY] ?: 1000000000 } fun part1(input: List<String>): Int { val sX = input.indexOfFirst { it.contains('S') } val sY = input[sX].indexOfFirst { it == 'S' } val eX = input.indexOfFirst { it.contains('E') } val eY = input[eX].indexOfFirst { it == 'E' } val graph = input.map { it.replace('S', 'a').replace('E', 'z') } return bfs(graph, sX, sY, eX, eY) } fun part2(input: List<String>): Int { val eX = input.indexOfFirst { it.contains('E') } val eY = input[eX].indexOfFirst { it == 'E' } val graph = input.map { it.replace('S', 'a').replace('E', 'z') } val posX = graph.mapIndexedNotNull { i, s -> if(s.contains('a')) i else null } return posX.flatMap { graph[it].mapIndexedNotNull { i, c -> if(c == 'a') (it to i) else null } }.minOf { val (sX, sY) = it bfs(graph, sX, sY, eX, eY) } } val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
2,122
aoc2022
Apache License 2.0
src/Day07.kt
freszu
573,122,040
false
{"Kotlin": 32507}
private sealed interface FileSystem { data class File(val name: String, val size: Int) : FileSystem data class Dir(val parent: Dir?, val name: String, val content: MutableList<FileSystem>) : FileSystem { fun contentFromLsOutput(line: List<String>) = line.map { fromLsOutputLine(it) } private fun fromLsOutputLine(line: String): FileSystem = when { line.startsWith("dir") -> { val (_, name) = line.split(" ") Dir(this@Dir, name, mutableListOf()) } else -> { val (size, name) = line.split(" ") File(name, size.toInt()) } } } } fun main() { fun parseFs(input: String): FileSystem { var lines = input.lines().drop(1).dropLast(1) val fs = FileSystem.Dir(null, "/", mutableListOf()) var currentDir = fs while (lines.isNotEmpty()) { val lineSplit = lines.first().split(" ") lines = when (lineSplit[1]) { "ls" -> { lines = lines.drop(1) val resultEnd = lines.indexOfFirst { it.startsWith("$") } val lsOutput = lines.subList(0, if (resultEnd == -1) lines.size else resultEnd) val content = currentDir.contentFromLsOutput(lsOutput) currentDir.content.addAll(content) lines.drop(lsOutput.size) } "cd" -> { currentDir = when (val arg = lineSplit[2]) { ".." -> currentDir.parent!! else -> currentDir.content.first { it is FileSystem.Dir && it.name == arg } as FileSystem.Dir } lines.drop(1) } else -> error("Unknown command ${lineSplit[1]}") } } return fs } fun FileSystem.walk(): Sequence<FileSystem> = sequence { yield(this@walk) if (this@walk is FileSystem.Dir) { yieldAll(content.asSequence().flatMap { it.walk() }) } } fun FileSystem.size(): Int = this.walk().filterIsInstance<FileSystem.File>().sumOf { it.size } fun FileSystem.findSmallestDirectoryAboveLimit(min: Int, limit: Int): Int { if (this is FileSystem.Dir) { val size = size() val currentMin = if (size in limit until min) size else min return content.minOf { it.findSmallestDirectoryAboveLimit(currentMin, limit) } } return min } fun part1(fs: FileSystem): Int { if (fs is FileSystem.Dir) { val filesSize = fs.walk().filterIsInstance<FileSystem.File>().sumOf { it.size } return (if (filesSize < 100000) filesSize else 0).plus(fs.content.sumOf { part1(it) }) } return 0 } fun part2(fs: FileSystem): Int { val limit = 30000000 - (70000000 - fs.size()) return fs.findSmallestDirectoryAboveLimit(Int.MAX_VALUE, limit) } // test if implementation meets criteria from the description, like: val testInput = readInputAsString("Day07_test") val dayInput = readInputAsString("Day07") val testFs = parseFs(testInput) val dayFs = parseFs(dayInput) check(part1(testFs) == 95437) println(part1(dayFs)) check(part2(testFs) == 24933642) println(part2(dayFs)) }
0
Kotlin
0
0
2f50262ce2dc5024c6da5e470c0214c584992ddb
3,447
aoc2022
Apache License 2.0
2k23/aoc2k23/src/main/kotlin/13.kt
papey
225,420,936
false
{"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117}
package d13 import input.raw import kotlin.math.min fun main() { val input = parseInput(raw("13.txt")) println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } fun part1(notes: List<Note>): Int = notes.sumOf { it.findRowReflection(0) * 100 + it.findColumnReflection(0) } fun part2(notes: List<Note>): Int = notes.sumOf { it.findRowReflection(1) * 100 + it.findColumnReflection(1) } fun parseInput(input: String): List<Note> = input.split("\n\n").map { Note(it) } class Note(input: String) { private val patterns = input.split("\n").filter { it.isNotBlank() }.map { it.toCharArray() } private val transposed = patterns[0].indices.map { i -> patterns.map { it[i] }.toCharArray() } fun findRowReflection(smudge: Int = 0): Int = (1..<patterns.size).find { patternIndex -> val differences = (0..<min(patterns.size - patternIndex, patternIndex)).sumOf { indexInPattern -> rowDiff(patternIndex - indexInPattern - 1, patternIndex + indexInPattern) } differences == smudge } ?: 0 fun findColumnReflection(smudge: Int = 0): Int = (1..<transposed.size).find { patternIndex -> val differences = (0..<min(transposed.size - patternIndex, patternIndex)).sumOf { indexInPattern -> columnDiff(patternIndex - indexInPattern - 1, patternIndex + indexInPattern) } differences == smudge } ?: 0 private fun rowDiff(indexA: Int, indexB: Int): Int = patterns[indexA].filterIndexed { index, c -> c != patterns[indexB][index] }.count() private fun columnDiff(indexA: Int, indexB: Int): Int = transposed[indexA].filterIndexed { index, c -> c != transposed[indexB][index] }.count() }
0
Rust
0
3
cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5
1,782
aoc
The Unlicense
src/Day02.kt
simonitor
572,972,937
false
{"Kotlin": 8461}
import GameResult.* fun main() { // first val games = readInput("inputDay2").map { it.split(" ") }.map { Pair(Move.translateMove(it[1]), Move.translateMove(it[0])) } println(calculatePoints(games)) // second val games2 = readInput("inputDay2").map { it.split(" ") }.map { val enemyMove = Move.translateMove(it[0]) Pair(Move.translateMoveSecondRuleSet(enemyMove, it[1]), enemyMove) } println(calculatePoints(games2)) } fun calculatePoints(games: List<Pair<Move, Move>>): Int { return games.sumOf { winMatrix[it.first.index][it.second.index].points + it.first.points } } val winMatrix = arrayOf( //******rock****paper***scissors******* arrayOf(DRA, LOS, WIN), // rock arrayOf(WIN, DRA, LOS), // paper arrayOf(LOS, WIN, DRA) // scissors ) enum class GameResult(val points: Int) { WIN(6), DRA(3), LOS(0); companion object { fun fromMove(encryptedMove: String): GameResult { return when (encryptedMove) { "X" -> LOS "Y" -> DRA "Z" -> WIN else -> throw IllegalArgumentException() } } } } enum class Move(val index: Int, val points: Int) { ROCK(0, 1), PAPER(1, 2), SCISSORS(2, 3); companion object { fun translateMove(encryptedMove: String): Move { return when (encryptedMove) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> throw IllegalArgumentException() } } fun translateMoveSecondRuleSet(enemyMove: Move, encryptedMove: String): Move { return when (GameResult.fromMove(encryptedMove)) { LOS -> Move.values()[(winMatrix[enemyMove.index].indexOf(WIN))] DRA -> Move.values()[(winMatrix[enemyMove.index].indexOf(DRA))] WIN -> Move.values()[winMatrix[enemyMove.index].indexOf(LOS)] } } } }
0
Kotlin
0
0
11d567712dd3aaf3c7dee424a3442d0d0344e1fa
2,042
AOC2022
Apache License 2.0
leetcode2/src/leetcode/kth-smallest-element-in-a-sorted-matrix.kt
hewking
68,515,222
false
null
package leetcode /** * 378. 有序矩阵中第K小的元素 * https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/ * Created by test * Date 2020/2/2 18:24 * Description * 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。 请注意,它是排序后的第k小元素,而不是第k个元素。 示例: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, 返回 13。 说明: 你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n2 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object KthSmallestElementInASortedMatrix { class Solution { /** * 思路: * 错误解法,只能覆盖 从小到大排列的一种情形 */ fun kthSmallest2(matrix: Array<IntArray>, k: Int): Int { val numSize = matrix.map { it.size }.reduce({ pre,cur -> pre + cur }) val n = Math.sqrt(numSize.toDouble()) val row = Math.ceil(k.div(n)) val a = Math.floor(k.div(n)) val col = k - a * n return matrix[row.toInt() - 1][col.toInt() - 1] } /** * 思路: * https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/solution/on-java-by-bumblebee/ * 二分查找解法 */ fun kthSmallest(matrix: Array<IntArray>, k: Int): Int { var low = matrix[0][0] var high = matrix[matrix.size - 1][matrix.size - 1] while (low < high) { var mid = low + (high - low) / 2 val count = countLessOrEquals(matrix,mid) if (count < k) { low = mid + 1 } else { high = mid } } return low } fun countLessOrEquals(matrix: Array<IntArray>, k:Int) :Int { var i = matrix.size - 1 var j = 0 var count = 0 while (i >= 0 && j < matrix[0].size) { if (k < matrix[i][j]) { i-- } else { count += i + 1 j++ } } return count } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,497
leetcode
MIT License
src/Day07.kt
hufman
573,586,479
false
{"Kotlin": 29792}
data class Dir(val subdirs: MutableMap<String, Dir>, val filesizes: MutableMap<String, Long>, var size: Long = 0) { companion object { fun empty(): Dir = Dir(mutableMapOf(), mutableMapOf() ) } fun updateSize() { size = subdirs.values.fold(0L) {total, dir -> dir.updateSize() total + dir.size } + filesizes.values.sum() } } fun main() { fun parse(input: List<String>): Dir { val path: MutableList<Dir> = listOf(Dir.empty()).toMutableList() input.forEach { line -> val parts = line.split(' ') if (line.startsWith("$")) { if (parts[1] == "cd" && parts[2] == "/") { while (path.size > 1) { path.removeAt(1) } } else if (parts[1] == "cd" && parts[2] == "..") { path.removeAt(path.size-1) } else if (parts[1] == "cd") { path.add(path.last().subdirs.getOrPut(parts[2]){Dir.empty()}) } else if (parts[1] == "dir") { } } else { if (parts[0] == "dir") { path.last().subdirs.getOrPut(parts[1]){Dir.empty()} } else { path.last().filesizes[parts[1]] = parts[0].toLong() } } } path[0].updateSize() return path[0] } fun walkSizes(root: Dir): Sequence<Dir> = sequence { yield(root) root.subdirs.values.forEach { yieldAll(walkSizes(it)) } } fun part1(input: List<String>): Long { val dir = parse(input) return walkSizes(dir).filter {it.size <= 100000}.sumOf { it.size } } fun part2(input: List<String>): Long { val dir = parse(input) val max = 70000000 val needed = 30000000 val free = max - dir.size val toDelete = needed - free return walkSizes(dir).sortedBy { it.size }.first {it.size > toDelete}.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1bc08085295bdc410a4a1611ff486773fda7fcce
1,898
aoc2022-kt
Apache License 2.0
src/day12/Day12.kt
xxfast
572,724,963
false
{"Kotlin": 32696}
package day12 import readLines import kotlin.collections.ArrayDeque typealias Grid<T> = List<List<T>> operator fun <T> Grid<T>.get(x: Int, y: Int): T? = getOrNull(y)?.getOrNull(x) fun <T> Grid<T>.firstByDepth( from: T, next: Grid<T>.(current: T) -> List<T>, evaluate: Grid<T>.(current: T, next: T) -> Boolean, until: (List<T>) -> Boolean, ): List<T> = sequence { val visited = mutableSetOf(from) val queue = ArrayDeque(listOf(listOf(from))) while (queue.isNotEmpty()) { val current = queue.removeFirst() yield(current) next(current.last()) .filter { it !in visited && evaluate(current.last(), it) } .forEach { visited.add(it) queue.add(current.plus(it)) } } }.first { until(it) } data class Cell(val x: Int, val y: Int, val value: Char) val Cell.elevation: Int get() = when (value) { 'S' -> 0 'E' -> 26 else -> value - 'a' } val Grid<Cell>.start: Cell get() = flatten().first { it.value == 'S' } val Grid<Cell>.end: Cell get() = flatten().first { it.value == 'E' } fun Grid<Cell>.neighbours(x: Int, y: Int): List<Cell> = listOfNotNull(this[x, y - 1], this[x + 1, y], this[x, y + 1], this[x - 1, y]) fun Grid<Cell>.neighbours(cell: Cell): List<Cell> = neighbours(cell.x, cell.y) fun Grid(input: List<String>): Grid<Cell> = input.mapIndexed { y, line -> line.toCharArray().toList().mapIndexed { x, c -> Cell(x, y, c) } } fun Grid<Cell>.firstByDepth( from: Cell, to: Cell, next: Grid<Cell>.(current: Cell) -> List<Cell> = { current -> neighbours(current) }, evaluate: Grid<Cell>.(current: Cell, next: Cell) -> Boolean = { current, next -> current.elevation <= next.elevation + 1 }, ) = firstByDepth(from, next, evaluate) { it.contains(to) } fun Grid<Cell>.firstByDepth( from: Cell, until: (List<Cell>) -> Boolean, next: Grid<Cell>.(current: Cell) -> List<Cell> = { current -> neighbours(current) }, evaluate: Grid<Cell>.(current: Cell, next: Cell) -> Boolean = { current, next -> current.elevation <= next.elevation + 1 }, ) = firstByDepth(from, next, evaluate, until) fun main() { fun part1(input: List<String>): Int { val grid = Grid(input) val solution = grid.firstByDepth(from = grid.end, to = grid.start) return solution.size - 1 } fun part2(input: List<String>): Int { val grid = Grid(input) val solution = grid.firstByDepth( from = grid.end, until = { it.any { cell -> cell.value == 'a' } } ) return solution.size - 1 } val testInput = readLines("day12/test.txt") val input = readLines("day12/input.txt") check(part1(testInput) == 31) println(part1(input)) check(part2(testInput) == 29) println(part2(input)) }
0
Kotlin
0
1
a8c40224ec25b7f3739da144cbbb25c505eab2e4
2,696
advent-of-code-22
Apache License 2.0
src/year2023/Day15.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2023 import readLines fun main() { check(hash("H") == 200) check(hash("HA") == 153) check(hash("HAS") == 172) check(hash("HASH") == 52) val input = parseInput(readLines("2023", "day15")) val testInput = parseInput(readLines("2023", "day15_test")) check(part1(testInput) == 1320) { "Incorrect result for part 1: ${part1(testInput)}" } println("Part 1:" + part1(input)) check(part2(testInput) == 145) { "Incorrect result for part 2: ${part2(testInput)}" } println("Part 2:" + part2(input)) } private fun parseInput(input: List<String>): List<String> { return input.first().split(",") } private fun part1(input: List<String>): Int { return input.sumOf { hash(it) } } private fun part2(inputs: List<String>): Int { val steps: List<Step> = inputs.map { input -> val label = input.takeWhile { it.isLetter() } val operation = input.find { it == '-' || it == '=' }.toString() if (operation == "=") { val focalLength = input.dropWhile { !it.isDigit() }.toInt() Step.Value(label, focalLength) } else { Step.Remove(label) } } val boxes = mutableListOf<MutableList<Step.Value>>() repeat(256) { boxes.add(mutableListOf()) } for (step in steps) { when (step) { is Step.Value -> { val hash = hash(step.label) val sameLabeledLens = boxes[hash].indexOfFirst { it.label == step.label } if (sameLabeledLens == -1) { boxes[hash].add(step) } else { boxes[hash] = boxes[hash].map { if (it.label == step.label) { step } else { it } }.toMutableList() } } is Step.Remove -> { boxes[hash(step.label)].removeAll { it.label == step.label } } } } return boxes .withIndex() .sumOf { (boxNumber, boxContent) -> boxContent .withIndex() .map { (slot, lens) -> (slot + 1) * lens.focalLength } .sumOf { it * (boxNumber + 1) } } } private fun hash(str: String): Int { var result = 0 for (char in str.chars()) { result += char result *= 17 result %= 256 } return result } private sealed interface Step { data class Value(val label: String, val focalLength: Int) : Step data class Remove(val label: String) : Step }
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
2,639
advent_of_code
MIT License
src/Day11.kt
hijst
572,885,261
false
{"Kotlin": 26466}
fun main() { class Monkey(startingItems: List<Long>, val rule: (Long) -> Long, val targets: Pair<Int, Int>, val modulus: Long ){ val items = startingItems.toMutableList() var inspectCount = 0L fun playTurn(monkeys: List<Monkey>) { items.forEach { item -> inspectCount += 1L val worry = rule(item) / 3L if (worry % modulus == 0L) monkeys[targets.first].items.add(worry) else monkeys[targets.second].items.add(worry) } items.clear() } fun playOtherTurn(monkeys: List<Monkey>) { items.forEach { item -> inspectCount += 1L val worry = rule(item) % 9699690L // product of all moduli if (worry % modulus == 0L) monkeys[targets.first].items.add(worry) else monkeys[targets.second].items.add(worry) } items.clear() } } fun String.toMonkey(): Monkey { val lines = split("\n").map { it.trim() } val startingItems = lines[1].split(": ")[1].split(", ").map { it.toLong() } val operationValueRaw = lines[2].split(" ").last() val operator = lines[2].split(" ")[4] val modulus: Long = lines[3].split(" ").last().toLong() val rule: (Long) -> Long = { worry -> val operationValue = if (operationValueRaw == "old") worry else operationValueRaw.toLong() when (operator) { "*" -> (worry * operationValue) else -> (worry + operationValue) } } val targets = lines[4].split(" ").last().toInt() to lines[5].split(" ").last().toInt() return Monkey(startingItems, rule, targets, modulus) } fun String.toMonkeys(): List<Monkey> = split("\n\n").map { it.toMonkey() } fun part1(monkeys: List<Monkey>): Long { (1..20).forEach { _ -> monkeys.forEach { monkey -> monkey.playTurn(monkeys) } } val monkeyBusiness = monkeys.map { it.inspectCount }.sorted() return monkeyBusiness[monkeyBusiness.size-2] * monkeyBusiness.last() } fun part2(monkeys: List<Monkey>): Long { (1..10000).forEach { turn -> monkeys.forEach { monkey -> monkey.playOtherTurn(monkeys) } } val monkeyBusinessRaw = monkeys.map { it.inspectCount } val monkeyBusiness = monkeyBusinessRaw.sorted() return monkeyBusiness[monkeyBusiness.size - 2] * monkeyBusiness.last() } val testInput = readInputString("Day11_test").toMonkeys() val testInputSecond = readInputString("Day11_test").toMonkeys() check(part1(testInput) == 10605L) //check(part2(testInputSecond) == 2713310158L) val input = readInputString("Day11_input").toMonkeys() val inputSecond = readInputString("Day11_input").toMonkeys() println(part1(input)) println(part2(inputSecond)) }
0
Kotlin
0
0
2258fd315b8933642964c3ca4848c0658174a0a5
2,873
AoC-2022
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2018/Day6.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2018 import kotlin.math.abs import kotlin.math.max import kotlin.math.min object Day6 { data class Point(val x: Int, val y: Int) { fun dist(other: Point) = abs(x - other.x) + abs(y - other.y) fun onEdge(topLeft: Point, bottomRight: Point): Boolean { return x == topLeft.x || x == bottomRight.x || y == topLeft.y || y == bottomRight.y } } fun inputToPoints(input: List<String>): List<Point> { return input.map { it.toPoint() } } fun findTopLeftAndTopRight(points: List<Point>): Pair<Point, Point> { return points.fold(Pair(points.first(), points.first())) { (upperLeft, lowerRight), p -> Pair(Point(min(upperLeft.x, p.x), min(upperLeft.y, p.y)), Point(max(lowerRight.x, p.x), max(lowerRight.y, p.y))) } } fun grid(topLeft: Point, bottomRight: Point): List<Point> { return (topLeft.x..bottomRight.x).flatMap { x -> (topLeft.y..bottomRight.y).map { y -> Point(x, y) } } } fun chronalArea(input: List<String>): Int { val points = inputToPoints(input) val (topLeft, bottomRight) = findTopLeftAndTopRight(points) val grid = grid(topLeft, bottomRight) val allDistances = grid.associateWith { g -> val distances = points.associateWith { it.dist(g) } val minDist = distances.minByOrNull { it.value }!!.value val closest = distances.filterValues { it == minDist }.keys if (closest.count() == 1) { closest.single() } else { null } } val verticesWithInfinite = allDistances .filter { it.key.onEdge(topLeft, bottomRight) } .map { it.value } .distinct() return points.filterNot { it in verticesWithInfinite } .associateWith { v -> allDistances.count { it.value == v } } .maxByOrNull { it.value }?.value ?: throw IllegalStateException("Could not find solution") } fun totalArea(input: List<String>): Int { val points = inputToPoints(input) val (topLeft, bottomRight) = findTopLeftAndTopRight(points) val grid = grid(topLeft, bottomRight) return grid.associateWith { p -> points.sumBy { it.dist(p) } }.filter { it.value < 10000 } .count() } fun String.toPoint(): Point { val (x, y) = this.split(",").map { it.trim() } return Point(x.toInt(), y.toInt()) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,614
adventofcode
MIT License
kotlin/src/main/kotlin/year2023/Day22.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 fun main() { val input = readInput("Day22") Day22.part1(input).println() Day22.part2(input).println() } object Day22 { fun part1(input: List<String>): Int { val bricks = getBricks(input) val brickSupportedBy = getSupportedBy(bricks) return bricks.size - brickSupportedBy.values .filter { it.size == 1 } .map { it.toSet() } .reduce(Set<Int>::union) .size } fun part2(input: List<String>): Int { val bricks = getBricks(input) val bricksSupportedBy = getSupportedBy(bricks) val bricksSupporting = bricksSupportedBy.reverse() return bricks.sumOf { brick -> val bricksThatWouldFall = mutableSetOf(brick.id) var nextBricksFalling = bricksSupporting[brick.id] ?: emptySet() while (nextBricksFalling.isNotEmpty()) { val builder = mutableSetOf<Int>() for (next in nextBricksFalling) { if ((bricksSupportedBy.getValue(next) - bricksThatWouldFall).isEmpty()) { bricksThatWouldFall += next builder.addAll(bricksSupporting[next] ?: emptySet()) } } nextBricksFalling = builder } bricksThatWouldFall.size - 1 } } data class Brick(val rowRange: IntRange, val columnRange: IntRange, var heightRange: IntRange, val id: Int) { fun eagleView(): List<Pair<Int, Int>> { return rowRange.flatMap { x -> columnRange.map { y -> Pair(x, y) } } } fun startHeightAt(height: Int) { heightRange = height..<(height + heightRange.last() - heightRange.first() + 1) } } private fun getBricks(input: List<String>): List<Brick> { val bricks = input .mapIndexed { id, line -> val (part1, part2) = line.split("~") val (row1, column1, height1) = part1.split(",").map { it.toInt() } val (row2, column2, height2) = part2.split(",").map { it.toInt() } Brick(row1..row2, column1..column2, height1..height2, id) } .sortedBy { it.heightRange.first } return bricks } private fun getSupportedBy(bricks: List<Brick>): Map<Int, Set<Int>> { val supportedBy = mutableMapOf<Int, MutableSet<Int>>() val surfaceToHeight = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() for (brick in bricks) { val surface = brick.eagleView() val maxHeight = surface.map { surfaceToHeight[it]?.second ?: 0 }.maxOf { it } brick.startHeightAt(maxHeight + 1) for (point in surface) { val (id, height) = surfaceToHeight[point] ?: Pair(-1, 0) if (height == maxHeight && id != -1) { supportedBy.getOrPut(brick.id) { mutableSetOf() }.add(id) } surfaceToHeight[point] = brick.id to brick.heightRange.last } } return supportedBy } private fun Map<Int, Set<Int>>.reverse(): Map<Int, Set<Int>> { val reversed = mutableMapOf<Int, MutableSet<Int>>() this.forEach { (key, value) -> value.forEach { reversed.getOrPut(it) { mutableSetOf() }.add(key) } } return reversed } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
3,463
advent-of-code
MIT License
src/Day03.kt
BenHopeITC
573,352,155
false
null
inline infix fun String.intersect(other: String) = toSet() intersect other.toSet() inline infix fun Set<Char>.intersect(other: String) = toSet() intersect other.toSet() fun main() { fun valueOfItem(item: Char): Int = if (item.isLowerCase()) item - 'a' + 1 else item - 'A' + 27 fun part1(input: List<String>): Int { return input.fold(0) { acc, rucksack -> val compartment1 = rucksack.substring(0, rucksack.length / 2) val compartment2 = rucksack.substring(rucksack.length / 2) val commonItem = compartment1 intersect compartment2 acc + valueOfItem(commonItem.single()) } } fun part2(input: List<String>): Int { return input.chunked(3).fold(0) { acc, groupRucksacks -> val (a, b, c) = groupRucksacks val badge = a intersect b intersect c acc + valueOfItem(badge.single()) } } fun part1old2(input: List<String>): Int { return input.fold(0) { acc, rucksack -> val compartment1 = rucksack.toCharArray(0, rucksack.length / 2) val compartment2 = rucksack.toCharArray(rucksack.length / 2) val commonItem = compartment1.intersect(compartment2.toSet()).single() acc + valueOfItem(commonItem) } } fun part1old(input: List<String>): Int { return input.fold(0) { acc, rucksack -> val parts = rucksack.substring(0, rucksack.length / 2) to rucksack.substring(rucksack.length / 2) var inBoth: Char = 'a' parts.first.forEach { item -> if (parts.second.contains(item)) { inBoth = item } } acc + valueOfItem(inBoth) } } fun part2Old2(input: List<String>): Int { return input.chunked(3).fold(0) { acc, groupRucksacks -> val badge = groupRucksacks[0].toCharArray() .intersect(groupRucksacks[1].toSet()) .intersect(groupRucksacks[2].toSet()) .single() acc + valueOfItem(badge) } } fun part2old(input: List<String>): Int { return (1..input.size / 3).map { val startIndex = (it - 1) * 3 Triple(input[startIndex], input[startIndex + 1], input[startIndex + 2]) }.fold(0) { acc, group -> var badge: Char = 'a' group.first.forEach { item -> if (group.second.contains(item) && group.third.contains(item)) { badge = item } } acc + valueOfItem(badge) } } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day03_test") // println(part1(testInput)) // check(part1(testInput) == 157) // test if implementation meets criteria from the description, like: // val testInput2 = readInput("Day03_test") // println(part2(testInput2)) // check(part2(testInput2) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) check(part1(input) == 7446) check(part1old(input) == 7446) check(part2(input) == 2646) }
0
Kotlin
0
0
851b9522d3a64840494b21ff31d83bf8470c9a03
3,198
advent-of-code-2022-kotlin
Apache License 2.0
src/Day12.kt
dcbertelsen
573,210,061
false
{"Kotlin": 29052}
import java.io.File import kotlin.math.min fun main() { val c0 = '`' fun getNodes(input: List<String>): List<List<Node>> = input.map { row -> row.map { c -> val height = when (c) { 'S' -> 0; 'E' -> 'z' - c0; else -> c - c0 } Node(height, isStart = c == 'S', isEnd = c == 'E') } } fun buildNeighbors(nodes: List<List<Node>>) { nodes.forEachIndexed { y, row -> row.forEachIndexed { x, node -> listOf(x to y-1, x to y+1, x+1 to y, x-1 to y).forEach { if (it.first in row.indices && it.second in nodes.indices && nodes[it.second][it.first].height <= node.height + 1) node.neighbors.add(nodes[it.second][it.first]) } } } } fun dijkstra(data: MutableList<Node>) { while(data.any()) { val v = data.removeFirst() v.neighbors.forEach { if (v.distance + 1 < it.distance) { it.distance = v.distance + 1 data.add(it) } data.sortBy { n -> n.distance } } } } fun part1(input: List<String>): Int { val nodes = getNodes(input) val start = nodes.flatten().first { it.isStart } buildNeighbors(nodes) start.distance = 0 val toProcess = mutableListOf(start) dijkstra(toProcess) // nodes.forEach {row -> // row.forEach { print(if (it.distance == Int.MAX_VALUE) " . " else String.format("%3d", it.distance) + if (it.isEnd) "*" else " ")} // println() // } // println() return nodes.flatten().firstOrNull { it.isEnd }?.distance ?: 0 } fun part2(input: List<String>): Int { val nodes = getNodes(input) val start = nodes.flatten().first { it.isStart } val end = nodes.flatten().first { it.isEnd } buildNeighbors(nodes) start.distance = 0 val toProcess = mutableListOf(start) dijkstra(toProcess) val starts = nodes.flatten().filter { it.height == 'a' - c0 && it.distance < Int.MAX_VALUE }.sortedByDescending { it.distance }.toMutableList() var shortest = Int.MAX_VALUE starts.forEach { newStart -> nodes.flatten().forEach { it.distance = Int.MAX_VALUE } newStart.distance = 0 toProcess.add(newStart) dijkstra(toProcess) shortest = min(shortest, end.distance) } return shortest } val testInput = listOf( "Sabqponm", "abcryxxl", "accszExk", "acctuvwj", "abdefghi" ) // test if implementation meets criteria from the description, like: check(part1(testInput) == 31) check(part2(testInput) == 29) val input = File("./src/resources/Day12.txt").readLines() println(part1(input)) println(part2(input)) } data class Node( val height: Int, var distance: Int = Int.MAX_VALUE, val neighbors: MutableList<Node> = mutableListOf(), val isStart: Boolean = false, val isEnd: Boolean = false)
0
Kotlin
0
0
9d22341bd031ffbfb82e7349c5684bc461b3c5f7
3,189
advent-of-code-2022-kotlin
Apache License 2.0