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/Day07.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
const val MAX_SIZE = 100000 const val TOTAL_SIZE = 70000000 const val FREE_SPACE = 30000000 fun main() { fun String.isCommand(): Boolean = startsWith("$ ") fun String.isLs(): Boolean = startsWith("$ ls") open class File(val name: String, val parent: File?, var size: Int = 0, val isDir: Boolean = false) { private val files = ArrayList<File>(1) val root: File get() { return parent?.root ?: parent ?: this } fun addFile(file: File) { files.add(file) var current: File? = this while (current != null) { current.size += file.size current = current.parent } } fun navigate(name: String): File { if (name == "..") return parent ?: this if (name == "/") return root return files.first { it.name == name } } fun filter(condition: (File) -> Boolean): List<File> { val result = MutableList(0) { File("", null) } if (condition(this)) result.add(this) if (isDir) files.forEach { result.addAll(it.filter(condition)) } return result } } fun parseInput(input: List<String>): File { var current = File("/", null, isDir = true) input.forEach { line -> if (line.isLs()) return@forEach val words = line.split(' ') if (line.isCommand()) current = current.navigate(words.last()) else { if (words[0] == "dir") current.addFile(File(words[1], current, isDir = true)) else current.addFile(File(words[1], current, words[0].toInt())) } } return current.root } fun part1(input: List<String>): Int = parseInput(input).filter { file -> file.isDir && file.size < MAX_SIZE }.sumOf { it.size } fun part2(input: List<String>): Int { val tree = parseInput(input) val needToFree = FREE_SPACE - (TOTAL_SIZE - tree.size) return parseInput(input).filter { file -> file.isDir && file.size >= needToFree }.minOf { it.size } } val testInput = readInputLines("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInputLines(7) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
2,130
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
src/Day08.kt
HaydenMeloche
572,788,925
false
{"Kotlin": 25699}
fun main() { val input = readInput("Day08") val parsed = input.map { it.toList().map { c -> c.toString().toInt() }} val visible = getVisibleCoords(parsed) println("answer one: ${visible.size}") val scenicMeasures = visible.map { calculateScenicMeasure(parsed, it.first, it.second) } println("answer two: ${scenicMeasures.max()}") } private fun getVisibleCoords(parsed: List<List<Int>>): Set<Pair<Int, Int>> { val visible = mutableSetOf<Pair<Int, Int>>() for (x in parsed.indices) { for (y in parsed[x].indices) { if (isVisible(parsed, x, y)) { visible.add(x to y) } } } return visible } fun isVisible(parsed: List<List<Int>>, x: Int, y: Int): Boolean { val ownHeight = parsed[x][y] val leftVisible = (0 until x).all { parsed[it][y] < ownHeight } val rightVisible = (x + 1 until parsed[x].size).all { parsed[it][y] < ownHeight } val topVisible = (0 until y).all { parsed[x][it] < ownHeight } val bottomVisible = (y + 1 until parsed.size).all { parsed[x][it] < ownHeight } return leftVisible || rightVisible || topVisible || bottomVisible || x == 0 || y == 0 || x == parsed[y].size - 1 || y == parsed.size - 1 } fun calculateScenicMeasure(parsed: List<List<Int>>, x: Int, y: Int): Int { val ownHeight = parsed[x][y] val leftVisible = (0 until x).reversed().countUntil { parsed[it][y] >= ownHeight } val rightVisible = (x + 1 until parsed[x].size).countUntil { parsed[it][y] >= ownHeight } val topVisible = (0 until y).reversed().countUntil { parsed[x][it] >= ownHeight } val bottomVisible = (y + 1 until parsed.size).countUntil { parsed[x][it] >= ownHeight } return leftVisible * rightVisible * topVisible * bottomVisible } fun Iterable<Int>.countUntil(pred: (Int) -> Boolean): Int { var res = 0 for (element in this) { res++ if (pred(element)) return res } return res }
0
Kotlin
0
1
1a7e13cb525bb19cc9ff4eba40d03669dc301fb9
1,980
advent-of-code-kotlin-2022
Apache License 2.0
kotlin/src/main/kotlin/AoC_Day10.kt
sviams
115,921,582
false
null
object AoC_Day10 { data class SparseState(val list: List<Int>, val currIdx: Int, val skip: Int) fun createSparse(stepSequence: Sequence<Int>, initial: SparseState) = stepSequence.fold(initial) { state, steps -> val endIndex = (state.currIdx + steps) % initial.list.size val changed = if (endIndex < state.currIdx) (state.list.subList(state.currIdx, state.list.size) + state.list.subList(0, endIndex)).reversed() else state.list.subList(state.currIdx, endIndex).reversed() val newList = if (endIndex < state.currIdx) changed.subList(changed.size-endIndex, changed.size) + state.list.subList(endIndex, state.currIdx) + changed.subList(0, changed.size - endIndex) else state.list.subList(0, state.currIdx) + changed + state.list.subList(endIndex, initial.list.size) SparseState(newList, (endIndex + state.skip) % initial.list.size, state.skip + 1) } fun sparseToDense(input: List<Int>) = (0..15).map { input.subList(it*16, (it+1)*16).fold(0) {acc, value -> acc.xor(value)} } fun denseToString(input: List<Int>) = input.joinToString("") { it.toString(16).padStart(2, '0')} fun solvePt1(input: String, initialState: List<Int>) : Int { val stepSequence = input.split(',').map { it.toInt() }.asSequence() val endState = createSparse(stepSequence, SparseState(initialState, 0, 0)).list return endState[0] * endState[1] } fun solvePt2(input: String, initialState: List<Int>) : String { val stepSequence = input.toCharArray().map { it.toInt()}.asSequence() + sequenceOf(17, 31, 73, 47, 23) return denseToString(sparseToDense((0..63).fold(SparseState(initialState, 0, 0)) { carry, _ -> createSparse(stepSequence, carry) }.list)) } }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
1,787
aoc17
MIT License
src/day05/Day05.kt
pientaa
572,927,825
false
{"Kotlin": 19922}
package day05 import java.io.File fun main() { fun transformStacks(rawStacks: List<String>) = rawStacks.dropLast(1) .map { row -> row.mapIndexedNotNull { index, s -> if ((index - 1) % 4 == 0) s else null } } .asReversed() .transpose() .map { list -> list.filterNot { it == ' ' }.toMutableList() }.toMutableList() fun transformCommands(rawCommands: List<String>) = rawCommands.map { rawCommand -> val (howMany, from, to) = rawCommand.replace(regex = Regex("[A-Za-z]"), "").trim() .split(" ") .map { it.toInt() } Triple(howMany, from, to) } fun transformInput(input: String): Pair<MutableList<MutableList<Char>>, List<Triple<Int, Int, Int>>> { val (rawStacks: List<String>, rawCommands: List<String>) = input.split("\n\n").map { it.split("\n") } return Pair(transformStacks(rawStacks), transformCommands(rawCommands)) } fun part1(input: String): String { val (stacks, commands) = transformInput(input) commands.forEach { (howMany, from, to) -> stacks .transform(howMany, from, to) } return stacks.getLastCrates() } fun part2(input: String): String { val (stacks, commands) = transformInput(input) commands.forEach { (howMany, from, to) -> stacks .transform(howMany, from, to, reversed = false) } return stacks.getLastCrates() } // test if implementation meets criteria from the description, like: val testInput = File("src", "day05/Day05_test.txt").readText() val input = File("src", "day05/Day05.txt").readText() println(part1(input)) println(part2(input)) } private fun <E> MutableList<MutableList<E>>.getLastCrates(): String = fold("") { acc, chars -> acc + if (chars.isNotEmpty()) chars.last() else "" } private fun <E> MutableList<MutableList<E>>.transform( howMany: Int, from: Int, to: Int, reversed: Boolean = true ): MutableList<MutableList<E>> { val load = if (reversed) this[from - 1].takeLast(howMany).reversed() else this[from - 1].takeLast(howMany) load.forEach { this[to - 1].add(it) this[from - 1].removeAt(this[from - 1].size - 1) } return this } fun <T> List<List<T>>.transpose(): List<List<T>> { val ret: MutableList<List<T>> = ArrayList() val n = this[0].size for (i in 0 until n) { val col: MutableList<T> = ArrayList() for (row in this) { col.add(row[i]) } ret.add(col) } return ret }
0
Kotlin
0
0
63094d8d1887d33b78e2dd73f917d46ca1cbaf9c
2,809
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/day10/SyntaxErrors.kt
Arch-vile
433,381,878
false
{"Kotlin": 57129}
package day10 import utils.read fun main( ) { solve().let { println(it) } } fun solve(): List<Long> { val input = read("./src/main/resources/day10Input.txt") .map { it.toCharArray() } val syntaxChecks = input.map { checkSyntax(it) } val failureScore = syntaxChecks .map { when (it.prematureClose) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 } } .sum() val autocompleteScores = syntaxChecks .filter { it.prematureClose == null } .map { balanceChunks(it.openChunks) }.sorted() val autocompleteScore = autocompleteScores[autocompleteScores.size/2] return listOf(failureScore.toLong(), autocompleteScore) } fun balanceChunks(openChunks: List<Char>): Long { return openChunks.reversed() .map { when(it) { '(' -> 1L '[' -> 2L '{' -> 3L '<' -> 4L else -> 0L } } .reduce { acc, next -> acc*5 + next } } data class SyntaxCheck(val prematureClose: Char?, val openChunks: List<Char>) private fun checkSyntax(input: CharArray): SyntaxCheck { val balanced = mutableListOf<Char>() var failedClose: Char? = null for (next in input) { if (failedClose != null) break if (next == ')') { if (balanced.last() == '(') balanced.removeLast() else failedClose = next } else if (next == ']') { if (balanced.last() == '[') balanced.removeLast() else failedClose = next } else if (next == '}') { if (balanced.last() == '{') balanced.removeLast() else failedClose = next } else if (next == '>') { if (balanced.last() == '<') balanced.removeLast() else failedClose = next } else balanced.add(next) } return SyntaxCheck(failedClose, balanced) }
0
Kotlin
0
0
4cdafaa524a863e28067beb668a3f3e06edcef96
2,035
adventOfCode2021
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem336/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem336 /** * LeetCode page: [336. Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/); * * Note1 : There is an implementation of trieNode that also records the indices of all words whose subString start * from there is a palindrome. It provides fast answer needed when finding pairs of unequal length, but requires * checking of subString at each start index of each word is a palindrome. Not sure is a good deal or not, * e.g. if all the words have similar length, this seems not a good option? * See [O(n * k^2) java solution with Trie structure](https://leetcode.com/problems/palindrome-pairs/discuss/79195/O(n-*-k2)-java-solution-with-Trie-structure); * * Note2: There is an algorithm called Manacher's algorithm which seems can improve time complexity; */ class Solution { private class CustomTrieNode(val char: Char?) { init { require(char == null || char in 'a'..'z') } private val _nextNodes = MutableList<CustomTrieNode?>(26) { null } val nextNodes get() = _nextNodes as List<CustomTrieNode?> var wordIndex = -1 val isTermination get() = wordIndex >= 0 fun getNext(char: Char) = _nextNodes[char - 'a'] fun setNext(node: CustomTrieNode): Boolean { val char = node.char ?: return false _nextNodes[char - 'a'] = node return true } } /* Complexity: * Time O(N * K^2) and Aux_Space O(M) where N is the size of words, K the longest length of word in words * and M is the flat length of words; */ fun palindromePairs(words: Array<String>): List<List<Int>> { val trie = createTrie(words) val palindromePairs = mutableListOf<List<Int>>() for (index in words.indices) { val word = words[index] addPairsThatWordIsSuffix(word, index, trie, palindromePairs) } return palindromePairs } private fun createTrie(words: Array<String>): CustomTrieNode { val root = CustomTrieNode(null) for (index in words.indices) { val word = words[index] root.insert(word, index) } return root } private fun CustomTrieNode.insert(lowercaseOnly: String, wordIndex: Int) { var currNode = this for (char in lowercaseOnly) { val nodeNoExist = currNode.getNext(char) == null if (nodeNoExist) currNode.setNext(CustomTrieNode(char)) currNode = checkNotNull(currNode.getNext(char)) } currNode.wordIndex = wordIndex } private fun addPairsThatWordIsSuffix( word: String, wordIndex: Int, wordsTrie: CustomTrieNode, container: MutableList<List<Int>> ) { val lastMatchedNode = addPairsThatWordIsNotShorterAndReturnLastMatchedNode(word, wordIndex, wordsTrie, container) addPairsThatWordIsShorter(wordIndex, lastMatchedNode, container) } private fun addPairsThatWordIsNotShorterAndReturnLastMatchedNode( word: String, wordIndex: Int, wordsTrie: CustomTrieNode, container: MutableList<List<Int>> ): CustomTrieNode? { var currNode = wordsTrie val hasEmpty = currNode.wordIndex >= 0 if (hasEmpty) addPairIfEmptyIsValidPrefix(word, wordIndex, currNode.wordIndex, container) for (index in word.indices.reversed()) { val char = word[index] val nodeNotExist = currNode.getNext(char) == null if (nodeNotExist) return null val nodeOfChar = checkNotNull(currNode.getNext(char)) val isPalindromePairs = nodeOfChar.isTermination && nodeOfChar.wordIndex != wordIndex && word.isPalindrome(0 until index) if (isPalindromePairs) container.add(listOf(nodeOfChar.wordIndex, wordIndex)) currNode = nodeOfChar } return currNode } private fun addPairIfEmptyIsValidPrefix( word: String, wordIndex: Int, indexOfEmpty: Int, container: MutableList<List<Int>> ) { val isPalindromePairs = indexOfEmpty != wordIndex && word.isPalindrome() if (isPalindromePairs) { container.add(listOf(indexOfEmpty, wordIndex)) } } private fun CharSequence.isPalindrome(indexRange: IntRange = this.indices): Boolean { var leftIndex = indexRange.first var rightIndex = indexRange.last while (leftIndex < rightIndex) { if (this[leftIndex] != this[rightIndex]) return false leftIndex++ rightIndex-- } return true } private fun addPairsThatWordIsShorter( wordIndex: Int, lastMatchedNode: CustomTrieNode?, container: MutableList<List<Int>>, accString: StringBuilder = StringBuilder() ) { if (lastMatchedNode == null) return for (nodeOfChar in lastMatchedNode.nextNodes) { if (nodeOfChar != null) { accString.append(nodeOfChar.char) val isPalindromePairs = nodeOfChar.isTermination && accString.isPalindrome() if (isPalindromePairs) container.add(listOf(nodeOfChar.wordIndex, wordIndex)) addPairsThatWordIsShorter(wordIndex, nodeOfChar, container, accString) accString.deleteCharAt(accString.lastIndex) } } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
5,498
hj-leetcode-kotlin
Apache License 2.0
2021/src/main/kotlin/com/trikzon/aoc2021/Day5.kt
Trikzon
317,622,840
false
{"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397}
package com.trikzon.aoc2021 import kotlin.math.max import kotlin.math.min fun main() { val input = getInputStringFromFile("/day5.txt") benchmark(Part.One, ::dayFivePartOne, input, 5442, 500) benchmark(Part.Two, ::dayFivePartTwo, input, 19571, 500) } fun dayFivePartOne(input: String): Int { val points = HashMap<Pair<Int, Int>, Int>() input.lines().forEach { line -> val coords = line.split(" -> ") val x1 = coords[0].split(',')[0].toInt() val y1 = coords[0].split(',')[1].toInt() val x2 = coords[1].split(',')[0].toInt() val y2 = coords[1].split(',')[1].toInt() if (x1 == x2) { // rows for (y in min(y1, y2)..max(y1, y2)) { points[Pair(x1, y)] = points.getOrPut(Pair(x1, y)) { 0 } + 1 } } else if (y1 == y2) { // columns for (x in min(x1, x2)..max(x1, x2)) { points[Pair(x, y1)] = points.getOrPut(Pair(x, y1)) { 0 } + 1 } } } return points.values.count { value -> value >= 2 } } fun dayFivePartTwo(input: String): Int { val points = HashMap<Pair<Int, Int>, Int>() input.lines().forEach { line -> val coords = line.split(" -> ") val x1 = coords[0].split(',')[0].toInt() val y1 = coords[0].split(',')[1].toInt() val x2 = coords[1].split(',')[0].toInt() val y2 = coords[1].split(',')[1].toInt() if (x1 == x2) { // rows for (y in min(y1, y2)..max(y1, y2)) { points[Pair(x1, y)] = points.getOrPut(Pair(x1, y)) { 0 } + 1 } } else if (y1 == y2) { // columns for (x in min(x1, x2)..max(x1, x2)) { points[Pair(x, y1)] = points.getOrPut(Pair(x, y1)) { 0 } + 1 } } else { // diagonals val deltaX = if (x1 > x2) -1 else 1 val deltaY = if (y1 > y2) -1 else 1 for (i in 0..max(x1, x2) - min(x1, x2)) { points[Pair(x1 + (deltaX * i), y1 + (deltaY * i))] = points.getOrPut(Pair(x1 + (deltaX * i), y1 + (deltaY * i))) { 0 } + 1 } } } return points.values.count { value -> value >= 2 } }
0
Kotlin
1
0
d4dea9f0c1b56dc698b716bb03fc2ad62619ca08
2,179
advent-of-code
MIT License
src/Day08.kt
GreyWolf2020
573,580,087
false
{"Kotlin": 32400}
import java.lang.StrictMath.max fun main() { fun part1(input: List<String>): Int { val treesGraph = AdjacencyList<Int>() val verticesOfTreeHeight = treesGraph.parseVertices(input) return verticesOfTreeHeight .fold(0) { acc, vertex -> if (vertex `is max in all directions of` treesGraph) acc + 1 else acc } } fun part2(input: List<String>): Int { val treesGraph = AdjacencyList<Int>() val verticesOfTreeHeight = treesGraph.parseVertices(input) return verticesOfTreeHeight .fold(Int.MIN_VALUE) { maxScenicScoreSoFar, vertex -> max( maxScenicScoreSoFar, vertex `scenic score` treesGraph ) } } // 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 Vertex<T>( val index: Int, val data: T ) data class Edge<T>( val source: Vertex<T>, val destination: Vertex<T>, val direction: Graph.EdgeType, val weight: Double? ) interface Graph<T> { fun createVertex(data: T): Vertex<T> fun addDirectedEdge( source: Vertex<T>, destination: Vertex<T>, direction: EdgeType, weight: Double?, ) fun addUndirectedEdge( source: Vertex<T>, destination: Vertex<T>, direction: EdgeType, weight: Double? ) fun add( edge: EdgeType, source: Vertex<T>, destination: Vertex<T>, weight: Double? ) fun edges(source: Vertex<T>): Map<EdgeType,Edge<T>> fun weight( source: Vertex<T>, destination: Vertex<T> ) : Double? enum class EdgeType { RIGHT, LEFT, ABOVE, BELOW } } fun Graph.EdgeType.opposite(): Graph.EdgeType = when(this) { Graph.EdgeType.RIGHT -> Graph.EdgeType.LEFT Graph.EdgeType.LEFT -> Graph.EdgeType.RIGHT Graph.EdgeType.ABOVE -> Graph.EdgeType.BELOW Graph.EdgeType.BELOW -> Graph.EdgeType.ABOVE } class AdjacencyList <T> : Graph<T> { private val adjacencies: HashMap<Vertex<T>, MutableMap<Graph.EdgeType,Edge<T>>> = HashMap() override fun createVertex(data: T): Vertex<T> { val vertex = Vertex(adjacencies.count(), data) adjacencies[vertex] = mutableMapOf() return vertex } override fun addDirectedEdge( source: Vertex<T>, destination: Vertex<T>, direction: Graph.EdgeType, weight: Double? ) { val edge = Edge(source, destination, direction, weight) adjacencies[source]?.put(edge.direction, edge) } override fun addUndirectedEdge( source: Vertex<T>, destination: Vertex<T>, direction: Graph.EdgeType, weight: Double? ) { addDirectedEdge(source, destination, direction, weight) addDirectedEdge(destination, source, direction.opposite(), weight) } override fun add(edge: Graph.EdgeType, source: Vertex<T>, destination: Vertex<T>, weight: Double?) = addUndirectedEdge(source, destination, edge, weight) override fun edges(source: Vertex<T>): Map<Graph.EdgeType, Edge<T>> = adjacencies[source] ?: mutableMapOf<Graph.EdgeType, Edge<T>>() override fun weight(source: Vertex<T>, destination: Vertex<T>): Double? { return edges(source).map { it.value }.firstOrNull { it.destination == destination }?.weight } override fun toString(): String { return buildString { // 1 adjacencies.forEach { (vertex, edges) -> // 2 val edgeString = edges .map {Pair(it.key,it.value)}.joinToString { it.second.destination.data.toString() + " " + it.first.toString()} // 3 append("${vertex.data} ---> [ $edgeString ]\n") // 4 } } } } fun AdjacencyList<Int>.parseVertices(verticesData: List<String>): List<Vertex<Int>> { val verticesDataMatrix = verticesData.map { verticesDataRow -> verticesDataRow .chunked(1) .map { treeHeight -> treeHeight.toInt() } } val verticesDataRow = verticesDataMatrix.first().size val verticesDataColumn = verticesDataMatrix.size val verticesLastRow = verticesDataRow * verticesDataColumn + 1 - verticesDataRow .. verticesDataRow * verticesDataColumn val verticesList = verticesDataMatrix .flatten() .map { createVertex(it) } for (vertex in verticesList) { val vertexPosition = vertex.index + 1 if (vertexPosition % verticesDataRow != 0) { add(Graph.EdgeType.RIGHT, vertex, verticesList[vertex.index + 1], null) } if (vertexPosition !in verticesLastRow) { add(Graph.EdgeType.BELOW, vertex, verticesList[vertex.index + verticesDataRow], null) } } return verticesList } fun Vertex<Int>.isMax(graph: Graph<Int>, direction: Graph.EdgeType): Boolean { tailrec fun go(direction: Graph.EdgeType, vert: Vertex< Int>, maxSoFar: Int): Int { val destinationVertex = graph.edges(vert)[direction]?.destination return if (destinationVertex == null) maxSoFar else go(direction, destinationVertex, max(maxSoFar, destinationVertex.data)) } val isMaximum by lazy { this.data > go(direction, this, Integer.MIN_VALUE) } return isMaximum } infix fun Vertex<Int>.`is max in all directions of`(graph: Graph<Int>): Boolean = isMax(graph, Graph.EdgeType.RIGHT) || isMax(graph, Graph.EdgeType.LEFT) || isMax(graph, Graph.EdgeType.ABOVE) || isMax(graph, Graph.EdgeType.BELOW) fun Vertex<Int>.countToImmediateMax(graph: Graph<Int>, direction: Graph.EdgeType): Int { fun Int.go(direction: Graph.EdgeType, vert: Vertex<Int>, smallerImmediateVerticesCount: Int): Int { val destinationVertex = graph.edges(vert)[direction]?.destination return when { destinationVertex == null -> smallerImmediateVerticesCount destinationVertex.data >= this -> smallerImmediateVerticesCount + 1 else -> go(direction, destinationVertex, smallerImmediateVerticesCount + 1) } } return data.go(direction, this, 0) } infix fun Vertex<Int>.`scenic score`(graph: Graph<Int>): Int = countToImmediateMax(graph, Graph.EdgeType.RIGHT) * countToImmediateMax(graph, Graph.EdgeType.LEFT) * countToImmediateMax(graph, Graph.EdgeType.ABOVE) * countToImmediateMax(graph, Graph.EdgeType.BELOW)
0
Kotlin
0
0
498da8861d88f588bfef0831c26c458467564c59
6,834
aoc-2022-in-kotlin
Apache License 2.0
src/Day24.kt
cypressious
572,898,685
false
{"Kotlin": 77610}
import java.util.* fun main() { val wall = 0b10000 val u = 0b0001 val r = 0b0010 val d = 0b0100 val l = 0b1000 fun getStates(input: List<String>): List<Array<IntArray>> { val states = mutableListOf<Array<IntArray>>() val height = input.size val width = input[0].length states += Array(height) { y -> IntArray(width) { x -> when (input[y][x]) { '#' -> wall '^' -> u 'v' -> d '<' -> l '>' -> r else -> 0 } } } while (true) { val previous = states.last() val newState = Array(height) { y -> IntArray(width) { x -> if (previous[y][x] == wall) return@IntArray wall if (y == 0 && x == 1 || y == height - 1 && x == width - 2) return@IntArray 0 var value = 0 if (previous[y + 1][x] and u != 0) value = value or u if (y == height - 2 && previous[1][x] and u != 0) value = value or u if (previous[y - 1][x] and d != 0) value = value or d if (y == 1 && previous[height - 2][x] and d != 0) value = value or d if (previous[y][x + 1] and l != 0) value = value or l if (x == width - 2 && previous[y][1] and l != 0) value = value or l if (previous[y][x - 1] and r != 0) value = value or r if (x == 1 && previous[y][width - 2] and r != 0) value = value or r value } } if (states[0] contentDeepEquals newState) { break } states += newState } return states } data class Node(val x: Int, val y: Int, val tick: Int) { var previous: Node? = null fun neighbors(state: Array<IntArray>, maxTicks: Int): List<Node> = buildList { val nextTick = (tick + 1) % maxTicks if (state.getOrNull(y - 1)?.getOrNull(x) == 0) add(copy(y = y - 1, tick = nextTick)) if (state.getOrNull(y + 1)?.getOrNull(x) == 0) add(copy(y = y + 1, tick = nextTick)) if (state.getOrNull(y)?.getOrNull(x - 1) == 0) add(copy(x = x - 1, tick = nextTick)) if (state.getOrNull(y)?.getOrNull(x + 1) == 0) add(copy(x = x + 1, tick = nextTick)) if (state.getOrNull(y)?.getOrNull(x) == 0) add(copy(tick = nextTick)) } } fun shortestPath( start: Node, states: List<Array<IntArray>>, targetY: Int, targetX: Int ): Pair<Node, Int> { val distances = mutableMapOf(start to 0).withDefault { Int.MAX_VALUE } val unvisited = PriorityQueue(compareBy<Node>(distances::getValue)).apply { add(start) } val visited = mutableSetOf<Node>() val maxTicks = states.size while (true) { val node = unvisited.poll() val state = states[(node.tick + 1) % maxTicks] val newDistance = distances.getValue(node) + 1 val neighbors = node.neighbors(state, maxTicks) for (neighbor in neighbors) { if (neighbor.y == targetY && neighbor.x == targetX) { return neighbor to newDistance } if (neighbor !in visited && distances.getValue(neighbor) > newDistance) { unvisited.remove(neighbor) distances[neighbor] = newDistance unvisited.add(neighbor.apply { previous = node }) } } visited += node } } fun part1(input: List<String>): Int { val states = getStates(input) val start = Node(1, 0, 0) return shortestPath(start, states, input.lastIndex, input[0].lastIndex - 1).second } fun part2(input: List<String>): Int { val states = getStates(input) val start = Node(1, 0, 0) val (end, firstDuration) = shortestPath( start, states, input.lastIndex, input[0].lastIndex - 1 ) val (newStart, secondDuration) = shortestPath(end, states, start.y, start.x) val (_, thirdDuration) = shortestPath(newStart, states, end.y, end.x) return firstDuration + secondDuration + thirdDuration } // test if implementation meets criteria from the description, like: val testInput = readInput("Day24_test") check(part1(testInput) == 18) check(part2(testInput) == 54) val input = readInput("Day24") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
4,790
AdventOfCode2022
Apache License 2.0
aoc/src/main/kotlin/com/bloidonia/aoc2023/day16/Main.kt
timyates
725,647,758
false
{"Kotlin": 45518, "Groovy": 202}
package com.bloidonia.aoc2023.day16 import com.bloidonia.aoc2023.text private const val example = """.|...\.... |.-.\..... .....|-... ........|. .......... .........\ ..../.\\.. .-.-/..|.. .|....-|.\ ..//.|....""" private data class Position(var x: Int, var y: Int) { operator fun plus(other: Position) = Position(x + other.x, y + other.y) fun move(direction: Direction) = this + direction.position } private data class Block(val position: Position, val type: String) private data class Ray(val position: Position, val direction: Direction) { fun interact(block: Block?) = when { block?.type == "/" -> listOf( when (direction) { Direction.UP -> Ray(position, Direction.RIGHT) Direction.DOWN -> Ray(position, Direction.LEFT) Direction.LEFT -> Ray(position, Direction.DOWN) Direction.RIGHT -> Ray(position, Direction.UP) } ) block?.type == "\\" -> listOf( when (direction) { Direction.UP -> Ray(position, Direction.LEFT) Direction.DOWN -> Ray(position, Direction.RIGHT) Direction.LEFT -> Ray(position, Direction.UP) Direction.RIGHT -> Ray(position, Direction.DOWN) } ) block?.type == "-" && (direction == Direction.UP || direction == Direction.DOWN) -> listOf( Ray(position, Direction.LEFT), Ray(position, Direction.RIGHT) ) block?.type == "|" && (direction == Direction.LEFT || direction == Direction.RIGHT) -> listOf( Ray(position, Direction.UP), Ray(position, Direction.DOWN) ) else -> listOf(this) } } private enum class Direction(val position: Position) { UP(Position(0, -1)), DOWN(Position(0, 1)), LEFT(Position(-1, 0)), RIGHT(Position(1, 0)); } private fun walk(input: List<String>, width: Int, height: Int, initial: Ray) = input.let { lines -> val world = lines.flatMapIndexed { y, line -> line.mapIndexed { x, c -> when (c) { '.' -> null else -> Position(x, y) to Block(Position(x, y), "$c") } } }.filterNotNull().toMap() val visited = mutableSetOf<Ray>() var rays = listOf(initial) while (rays.isNotEmpty()) { visited.addAll(rays) rays = rays.flatMap { it.interact(world[it.position]) } .map { Ray(it.position.move(it.direction), it.direction) } .filter { it.position.x in 0 until width && it.position.y in 0 until height } .filter { it !in visited } } visited.map { it.position }.distinct().size } private fun part1(input: String) = input.lines().let { val width = it.first().length val height = it.size walk(it, width, height, Ray(Position(0, 0), Direction.RIGHT)) } private fun part2(input: String) = input.lines().let { lines -> val width = lines.first().length val height = lines.size val maxLR = (0 until height).flatMap { y -> listOf( walk(lines, width, height, Ray(Position(0, y), Direction.RIGHT)), walk(lines, width, height, Ray(Position(width - 1, y), Direction.LEFT)) ) }.max() val maxUD = (0 until width).flatMap { x -> listOf( walk(lines, width, height, Ray(Position(x, 0), Direction.DOWN)), walk(lines, width, height, Ray(Position(x, height - 1), Direction.UP)) ) }.max() maxOf(maxLR, maxUD) } fun main() { println(part1(example)) println(part1(text("/day16.input"))) println(part2(example)) println(part2(text("/day16.input"))) }
0
Kotlin
0
0
158162b1034e3998445a4f5e3f476f3ebf1dc952
3,684
aoc-2023
MIT License
src/main/kotlin/_2022/Day09.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readInput import kotlin.math.abs fun main() { fun tooFarAway(h: IntArray, t: IntArray): Boolean { return (abs(h[0] - t[0]) > 1) || (abs(h[1] - t[1]) > 1) } fun part1(input: List<String>): Int { val h = IntArray(2) var t = IntArray(2) val visitedPositions = mutableSetOf<Pair<Int, Int>>() for (command in input) { val (direction, steps) = command.split(" ") repeat(steps.toInt()) { val prevH = h.copyOf() when (direction) { "R" -> h[0]++ "L" -> h[0]-- "U" -> h[1]++ "D" -> h[1]-- } if (tooFarAway(h, t)) { t = prevH } visitedPositions.add(Pair(t[0], t[1])) } } return visitedPositions.size } fun part2(input: List<String>): Int { val snake = MutableList(10) { IntArray(2) } val visitedPositions = mutableSetOf<Pair<Int, Int>>() for (command in input) { val (direction, steps) = command.split(" ") repeat(steps.toInt()) { val h = snake.first() when (direction) { "R" -> h[0]++ "L" -> h[0]-- "U" -> h[1]++ "D" -> h[1]-- } snake.forEachIndexed { index, body -> if (index == 0) { // return 0 } else { val prevHead = snake[index - 1] if (tooFarAway(body, prevHead)) { val addX = prevHead[0] - body[0] val addY = prevHead[1] - body[1] body[0] += addX.coerceIn(-1..1) body[1] += addY.coerceIn(-1..1) } } } val tail = snake.last() visitedPositions.add(Pair(tail[0], tail[1])) } } return visitedPositions.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
2,452
advent-of-code
Apache License 2.0
project/src/problems/CountingElements.kt
informramiz
173,284,942
false
null
package problems object CountingElements { /** * Problem: You are given an integer m (1 <= m <= 1 000 000) and two non-empty, zero-indexed * arrays A and B of n integers, a0, a1, . . . , an−1 and b0, b1, . . . , bn−1 respectively (0 <= ai * , bi <= m). * The goal is to check whether there is a swap operation which can be performed on these * arrays in such a way that the sum of elements in array A equals the sum of elements in * array B after the swap. By swap operation we mean picking one element from array A and * one element from array B and exchanging them. */ fun checkIfSwapMakeTotalsEqual(A: Array<Int>, B: Array<Int>, m: Int): Boolean { /* let's say the elements that needs to be swapped are (ai, bi) from each array respectively then * Bsum + ai - bi = Asum + bi - ai * -> ai = bi - ( (Bsum - Asum)/2 ) * ai = bi - d/2 * * so given an element bi from array B we will get corresponding ai value that needs to be present * in A and needs to be swapped. Note: This ai also must obey 0 <= ai <= m condition as given in question */ val sumA = A.sum() val sumB = B.sum() val d = sumB - sumA //d needs to be even so that d/2 is an integer because both A and B arrays are integer arrays if (d % 2 != 0) { return false } //because m is in range [1, 1,000,000]) so we can count its elements using a count array val elementsCountInA = countArrayElements(A, m) //now find ai for each bi and check if it is in [0, m] and also present in A (elementsCountInA[ai] > 0) B.forEach { bi -> val ai = bi - d/2 if (ai in 0..m && elementsCountInA[ai] > 0) { return true } } return false } private fun countArrayElements(A: Array<Int>, m: Int): Array<Int> { val count = Array(m + 1) {0} A.forEach { count[it]++ } return count } /* * A non-empty array A consisting of N integers is given. * A permutation is a sequence containing each element from 1 to N once, and only once. * For example, array A such that: * A[0] = 4 * A[1] = 1 * A[2] = 3 * A[3] = 2 * is a permutation, but array A such that: * A[0] = 4 * A[1] = 1 * A[2] = 3 * is not a permutation, because value 2 is missing. * The goal is to check whether array A is a permutation. * Write a function: * class Solution { public int solution(int[] A); } * that, given an array A, returns 1 if array A is a permutation and 0 if it is not. * For example, given array A such that: * A[0] = 4 * A[1] = 1 * A[2] = 3 * A[3] = 2 * the function should return 1. * Given array A such that: * A[0] = 4 * A[1] = 1 * A[2] = 3 * the function should return 0. * Write an efficient algorithm for the following assumptions: * N is an integer within the range [1..100,000]; * each element of array A is an integer within the range [1..1,000,000,000]. */ fun checkIfPermutation(A: Array<Int>): Int { if (A.isEmpty()) return 1 //arithmetic series sum val maxA = A.size val expectedSum = A.size * (1 + maxA) / 2 val actualSum = A.sum() val isSumFine = expectedSum == actualSum if (!isSumFine) { return 0 } val areTotalElementsFine = A.size == maxA if (!areTotalElementsFine) { return 0 } val counter = Array(A.size + 1) {0} var distinctElementsCount = 0 A.forEach { value -> if (value >= counter.size) { return 0 } if (counter[value] == 0) { distinctElementsCount++ counter[value]++ } else { return 0 } } return if (distinctElementsCount == A.size) { 1 } else { 0 } } fun factorial(n: Int): Int { var total = 1 for (i in 1..n) { total *= i } return total } fun product(A: Array<Int>): Int { var total = 1 A.forEach { total *= it } return total } /* *A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river. *You are given an array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in seconds. *The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves). You may assume that the speed of the current in the river is negligibly small, i.e. the leaves do not change their positions once they fall in the river. *For example, you are given integer X = 5 and array A such that: * *A[0] = 1 *A[1] = 3 *A[2] = 1 *A[3] = 4 *A[4] = 2 *A[5] = 3 *A[6] = 5 *A[7] = 4 *In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river. * *Write a function: * *fun solution(X: Int, A: IntArray): Int * *that, given a non-empty array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river. * *If the frog is never able to jump to the other side of the river, the function should return −1. * *For example, given X = 5 and array A such that: * *A[0] = 1 *A[1] = 3 *A[2] = 1 *A[3] = 4 *A[4] = 2 *A[5] = 3 *A[6] = 5 *A[7] = 4 *the function should return 6, as explained above. * *Write an efficient algorithm for the following assumptions: * *N and X are integers within the range [1..100,000]; *each element of array A is an integer within the range [1..X]. */ fun frogRiverOne(X: Int, A: Array<Int>): Int { val counter = Array(X + 1) {0} var leavesNeeded = X A.forEachIndexed { index, value -> if (counter[value] == 0) { counter[value]++ leavesNeeded-- } if (leavesNeeded == 0) { return index } } return -1 } /* * MaxCounters: * * Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum. * Programming language: * You are given N counters, initially set to 0, and you have two possible operations on them: * * increase(X) − counter X is increased by 1, * max counter − all counters are set to the maximum value of any counter. * A non-empty array A of M integers is given. This array represents consecutive operations: * * if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X), * if A[K] = N + 1 then operation K is max counter. * For example, given integer N = 5 and array A such that: * * A[0] = 3 * A[1] = 4 * A[2] = 4 * A[3] = 6 * A[4] = 1 * A[5] = 4 * A[6] = 4 * the values of the counters after each consecutive operation will be: * * (0, 0, 1, 0, 0) * (0, 0, 1, 1, 0) * (0, 0, 1, 2, 0) * (2, 2, 2, 2, 2) * (3, 2, 2, 2, 2) * (3, 2, 2, 3, 2) * (3, 2, 2, 4, 2) * The goal is to calculate the value of every counter after all operations. * * Write a function: * * class Solution { public int[] solution(int N, int[] A); } * * that, given an integer N and a non-empty array A consisting of M integers, returns a sequence of integers representing the values of the counters. * * Result array should be returned as an array of integers. * * For example, given: * * A[0] = 3 * A[1] = 4 * A[2] = 4 * A[3] = 6 * A[4] = 1 * A[5] = 4 * A[6] = 4 * the function should return [3, 2, 2, 4, 2], as explained above. * * Write an efficient algorithm for the following assumptions: * * N and M are integers within the range [1..100,000]; * each element of array A is an integer within the range [1..N + 1]. */ fun maxCounters(N: Int, A: IntArray): IntArray { val counters = Array(N) {0} var currentMaxValue = 0 var lastMaxValue = 0 A.forEach { value -> if (value in 1..N) { //increase operation val counterIndex = value - 1 counters[counterIndex] = Math.max(counters[counterIndex], lastMaxValue) counters[counterIndex]++ //keep a track of the max counter value currentMaxValue = Math.max(counters[counterIndex], currentMaxValue) } else if (value == N + 1) { //reset all counters to max counter value operation lastMaxValue = currentMaxValue } } //check if there are any counters for which reset to max counter operation is still pending counters.forEachIndexed { index, value -> counters[index] = Math.max(lastMaxValue, value) } return counters.toIntArray() } /** * ----MissingInteger---- * Find the smallest positive integer that does not occur in a given sequence. * This is a demo task. * * Write a function: * * fun solution(A: IntArray): Int * * that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. * * For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. * * Given A = [1, 2, 3], the function should return 4. * * Given A = [−1, −3], the function should return 1. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [1..100,000]; * each element of array A is an integer within the range [−1,000,000..1,000,000]. */ fun findMissingInteger(A: IntArray): Int { val counter = Array(1_000_000 + 1) {0} //required number should be greater than 0, so ignore number 0 counter[0] = 1 A.forEach { value -> if (value > 0) { counter[value]++ } } counter.forEachIndexed { index, value -> if (value == 0) { return index } } return 1 } }
0
Kotlin
0
0
a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4
10,902
codility-challenges-practice
Apache License 2.0
src/days/Day02.kt
EnergyFusion
572,490,067
false
{"Kotlin": 48323}
fun main() { val playMap = mapOf( "A" to RPS.ROCK, "B" to RPS.PAPER, "C" to RPS.SCISSOR, "X" to RPS.ROCK, "Y" to RPS.PAPER, "Z" to RPS.SCISSOR, ) val myPlayMap = mapOf<String, (RPS) -> RPS>( "X" to { it.beats }, "Y" to { it }, "Z" to { it.loses }, ) fun calculateScore1(line: String): Int { val (theirChar, myChar) = line.split(" ") val theirPlay = playMap[theirChar] val myPlay = playMap[myChar] // println("$myPlay vs $theirPlay = ${myPlay!!.compare(theirPlay!!)}") return myPlay!!.compare(theirPlay!!) + myPlay.score } fun calculateScore2(line: String): Int { val (theirChar, myChar) = line.split(" ") val theirPlay = playMap[theirChar] val myPlay = myPlayMap[myChar]!!(theirPlay!!) // println("$myPlay vs $theirPlay = ${myPlay!!.compare(theirPlay!!)}") return myPlay.compare(theirPlay) + myPlay.score } fun part1(input: List<String>): Int { var score = 0 for (line in input) { score += calculateScore1(line) } return score } fun part2(input: List<String>): Int { var score = 0 for (line in input) { score += calculateScore2(line) } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("tests/Day02") check(part1(testInput) == 15) check(part2(testInput) == 12) println("checks passed") val input = readInput("input/Day02") println(part1(input)) println(part2(input)) } enum class RPS { ROCK { override val beats by lazy { SCISSOR } override val loses by lazy { PAPER } override val score = 1 }, PAPER { override val beats = ROCK override val loses by lazy { SCISSOR } override val score = 2 }, SCISSOR { override val beats = PAPER override val loses = ROCK override val score = 3 }; abstract val beats : RPS abstract val loses: RPS abstract val score: Int fun compare(other: RPS) = when (other) { beats -> 6 loses -> 0 else -> 3 } }
0
Kotlin
0
0
06fb8085a8b1838289a4e1599e2135cb5e28c1bf
2,272
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/de/jball/aoc2022/day12/Day12.kt
fibsifan
573,189,295
false
{"Kotlin": 43681}
package de.jball.aoc2022.day12 import de.jball.aoc2022.Day import java.util.PriorityQueue class Day12(test: Boolean = false): Day<Long>(test, 31, 29) { private val areaMap = input.mapIndexed { line, letters -> letters.chunked(1) .mapIndexed { column, letter -> MountainPosition(Pair(line, column), letter.toCharArray()[0], Int.MAX_VALUE.toLong()) } } private val start = areaMap.flatten().first { pos -> pos.height == 'S' } private val end = areaMap.flatten().first { pos -> pos.height == 'E' } private fun calculatePaths(queue: PriorityQueue<MountainPosition>, reverse: Boolean = false) { while (queue.isNotEmpty()) { val current = queue.poll()!! if (!current.pathLengthIsMinimal) { getReachableNeighbors(current.position, reverse) .also { neighbors -> current.updateOwnDistance(neighbors, reverse) } .filter { !it.pathLengthIsMinimal } .forEach { neighbor -> neighbor.updateOwnDistance(listOf(current), reverse) queue.add(neighbor) } current.pathLengthIsMinimal = true } } } private fun getReachableNeighbors(position: Pair<Int, Int>, reverse: Boolean = false): List<MountainPosition> { return position.let { (line, column) -> neighborCandidates(line, column) .filter { next -> if (reverse) heightDifference(next, position) <= 1 else heightDifference(position, next) <= 1 } .map { areaMap[it.first][it.second] } } } private fun neighborCandidates(line: Int, column: Int) = listOf(Pair(line + 1, column), Pair(line - 1, column), Pair(line, column + 1), Pair(line, column - 1)) .filter { next -> next.first in areaMap.indices && next.second in areaMap[0].indices } private fun heightDifference(current: Pair<Int, Int>, next: Pair<Int, Int>) = heightDifference(areaMap[current.first][current.second], areaMap[next.first][next.second]) private fun heightDifference(current: MountainPosition, next: MountainPosition) = heightDifference(current.height, next.height) override fun part1(): Long { resetPathLengths() start.pathLength = 0 // this is key to being fast (see wikipedia on Dijkstra): val queue = PriorityQueue( compareBy { pos: MountainPosition -> pos.pathLength }) queue.add(start) calculatePaths(queue) return end.pathLength } override fun part2(): Long { resetPathLengths() end.pathLength = 0 // this is key to being fast (see wikipedia on Dijkstra): val queue = PriorityQueue( compareBy { pos: MountainPosition -> pos.pathLength }) queue.add(end) calculatePaths(queue, true) return areaMap.flatten().filter {it.height == 'a'}.minOf {it.pathLength} } private fun resetPathLengths() { areaMap.forEach { it.forEach { mountainPosition -> mountainPosition.pathLength = Int.MAX_VALUE.toLong() mountainPosition.pathLengthIsMinimal = false } } } } fun heightDifference(currentHeight: Char, nextHeight: Char) = actualHeight(nextHeight) - actualHeight(currentHeight) private fun actualHeight(height: Char) = when (height) { 'S' -> 'a' 'E' -> 'z' else -> height } class MountainPosition( val position: Pair<Int, Int>, val height: Char, var pathLength: Long, var pathLengthIsMinimal: Boolean = false ) { fun updateOwnDistance(neighbors: List<MountainPosition>, reverse: Boolean = false) { val newMin = neighbors .filter { neighbor -> if (reverse) heightDifference(height, neighbor.height) <= 1 else heightDifference(neighbor.height, height) <= 1 } .minOfOrNull { it.pathLength + 1 } if (newMin != null && newMin < pathLength) { pathLength = newMin } } } fun main() { Day12().run() }
0
Kotlin
0
3
a6d01b73aca9b54add4546664831baf889e064fb
4,342
aoc-2022
Apache License 2.0
src/main/kotlin/aoc2020/JurassicJigsaw.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2020 import komu.adventofcode.utils.countOccurrences import komu.adventofcode.utils.nonEmptyLines import kotlin.math.sqrt fun jurassicJigsaw1(input: String) = Jigsaw.parse(input).checksum() fun jurassicJigsaw2(input: String): Int { val monster = JigsawPattern( """ # # ## ## ### # # # # # # """.trimIndent() ) val picture = Jigsaw.parse(input).picture() val matches = picture.variations().maxOf { it.countMatches(monster) } return picture.count('#') - (matches * monster.elements) } private class Jigsaw(private val tiles: Collection<JigsawTile>) { private val size = sqrt(tiles.size.toDouble()).toInt() private val pieces = mutableListOf<MutableList<JigsawGrid>>() init { val queue = tiles.toMutableList() for (y in 0 until size) { val row = mutableListOf<JigsawGrid>() pieces += row for (x in 0 until size) row += placePart(x, y, queue) } } private fun placePart(x: Int, y: Int, unusedTiles: MutableCollection<JigsawTile>): JigsawGrid { val it = unusedTiles.iterator() while (it.hasNext()) { val tile = it.next() for (c in tile.configurations) { if (canPlace(x, y, c)) { it.remove() return c } } } error("can't place part") } // We are filling the pieces from top-down, left to right so we only never need to check the right side private fun canPlace(x: Int, y: Int, c: JigsawGrid) = (if (x == 0) !hasMatches(c.left) else c.left == pieces[y][x - 1].right) && (if (y == 0) !hasMatches(c.top) else c.top == pieces[y - 1][x].bottom) && ((x != size - 1) || !hasMatches(c.right)) && ((y != size - 1) || !hasMatches(c.bottom)) private fun hasMatches(border: String) = tiles.count { it.matches(border) } > 1 fun checksum() = pieces.first().first().id.toLong() * pieces.first().last().id * pieces.last().first().id * pieces.last().last().id fun picture(): JigsawGrid { val cellSize = pieces[0][0].size - 2 return JigsawGrid(0, size * cellSize) { x, y -> val cell = pieces[y / cellSize][x / cellSize].withoutBorders() cell[x % cellSize, y % cellSize] } } companion object { fun parse(input: String) = Jigsaw(input.split("\n\n").map { JigsawTile.parse(it) }.toMutableList()) } } private class JigsawGrid(val id: Int, val size: Int, init: (Int, Int) -> Char) { private val data = Array(size) { y -> CharArray(size) { x -> init(x, y) } } val top = String(data.first()) val bottom = String(data.last()) val left = data.map { it.first() }.joinToString("") val right = data.map { it.last() }.joinToString("") operator fun get(x: Int, y: Int) = data[y][x] fun matches(b: String) = b == top || b == bottom || b == left || b == right fun withoutBorders() = JigsawGrid(id, size - 2) { x, y -> data[y + 1][x + 1] } fun rotate() = JigsawGrid(id, size) { x, y -> data[size - x - 1][y] } fun flip() = JigsawGrid(id, size) { x, y -> data[y][size - x - 1] } fun variations(): List<JigsawGrid> { val rots = generateSequence(this) { it.rotate() }.take(4).toList() return rots + rots.map { it.flip() } } override fun toString(): String = data.joinToString("\n") fun countMatches(pattern: JigsawPattern): Int { var matches = 0 for (y in 0 until size - pattern.height) for (x in 0 until size - pattern.length) if (pattern.matchesAt(this, x, y)) matches++ return matches } fun count(c: Char) = data.sumBy { r -> r.count { it == c } } } private class JigsawPattern(input: String) { val lines = input.nonEmptyLines() val length = lines.maxOf { it.length } val height = lines.size val elements = input.countOccurrences('#') fun matchesAt(grid: JigsawGrid, x: Int, y: Int): Boolean { for ((yy, line) in lines.withIndex()) for ((xx, c) in line.withIndex()) if (c == '#' && grid[x + xx, y + yy] != '#') return false return true } } private class JigsawTile(val id: Int, val configurations: List<JigsawGrid>) { fun matches(border: String) = configurations.any { it.matches(border) } companion object { private val headerRegex = Regex("""Tile (\d+):""") fun parse(str: String): JigsawTile { val lines = str.nonEmptyLines() val (_, idStr) = headerRegex.matchEntire(lines[0])?.groupValues ?: error("invalid header") val id = idStr.toInt() val data = lines.drop(1) return JigsawTile(id, JigsawGrid(id, data.size) { x, y -> data[y][x] }.variations()) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
5,074
advent-of-code
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year23/Day12.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year23 import com.grappenmaker.aoc.* fun PuzzleSet.day12() = puzzle(day = 12) { // data class Memo(val left: List<Boolean?>, val sizes: List<Int>) data class Memo(val configIdx: Int, val sizesIdx: Int) data class Entry(val config: List<Boolean?>, val sizes: List<Int>) val s = inputLines.map { l -> val (a, b) = l.split(" ") Entry(a.map { when (it) { '#' -> true '.' -> false '?' -> null else -> error("Impossible") } }, b.split(",").map(String::toInt)) } fun recurse(state: Memo, data: Entry, memo: MutableMap<Memo, Long> = hashMapOf()): Long { // naive/list based solution // fun count() = if (sizes.isEmpty()) 0 else { // val ss = sizes.first() // if ((ss in left.indices && left[ss] == true) || left.size < ss) 0 else memo.getOrPut(this) { // when { // !left.take(ss).all { it != false } -> 0 // left.size == ss -> if (sizes.size == 1) 1 else 0 // else -> Memo(left.drop(ss + 1), sizes.drop(1)).recurse(memo) // } // } // } // // return when { // left.isEmpty() -> if (sizes.isEmpty()) 1 else 0 // else -> when (left.first()) { // false -> Memo(left.drop(1), sizes).recurse(memo) // true -> count() // null -> count() + Memo(left.drop(1), sizes).recurse(memo) // } // } // Uses list tricks to not excessively use RAM fun count() = if (state.sizesIdx !in data.sizes.indices) 0 else { val ss = data.sizes[state.sizesIdx] + state.configIdx if ((ss in data.config.indices && data.config[ss] == true) || data.config.size < ss) 0 else memo.getOrPut(state) { when { !(state.configIdx..<ss).all { data.config[it] != false } -> 0 state.configIdx == ss -> if (data.sizes.size - state.sizesIdx == 1) 1 else 0 else -> recurse(Memo(ss + 1, state.sizesIdx + 1), data, memo) } } } return when { state.configIdx !in data.config.indices -> if (state.sizesIdx !in data.sizes.indices) 1 else 0 else -> when (data.config[state.configIdx]) { false -> recurse(Memo(state.configIdx + 1, state.sizesIdx), data, memo) true -> count() null -> count() + recurse(Memo(state.configIdx + 1, state.sizesIdx), data, memo) } } } fun List<Entry>.solve() = sumOf { recurse(Memo(0, 0), it) }.s() partOne = s.solve() partTwo = s.map { (a, b) -> Entry(listOf(a).asPseudoList(5).joinToList(null), b.asPseudoList(5)) }.solve() // partTwo = s.map { (a, b) -> Entry(a.repeatWithSeparatorExp(5, null), b.asPseudoList(5)) }.solve() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,986
advent-of-code
The Unlicense
src/main/kotlin/problems/Day4.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems class Day4(override val input: String) : Problem { override val number: Int = 4 private val drawNumbers = input.lines().first().split(",").map { i -> i.toInt() } private val boards = input.split("\n\n").drop(1).map { boardStr -> Board.fromBoardString(boardStr) } override fun runPartOne(): String { var newBoards = boards for (number in drawNumbers) { newBoards = newBoards.map { board -> board.play(number) } val bingoBoards = newBoards.filter { board -> board.isBingo() } if (bingoBoards.isNotEmpty()) { return (bingoBoards.single().unmarkedNumbers().sum() * number).toString() } } return "Not found" } override fun runPartTwo(): String { var newBoards = boards var previousRoundBoards = boards for (number in drawNumbers) { newBoards = newBoards .map { board -> board.play(number) } .filter { board -> !board.isBingo() } if (newBoards.isEmpty()) { return ((previousRoundBoards.single().unmarkedNumbers().sum()-number) * number).toString() } previousRoundBoards = newBoards } return "Not found" } private data class Board(val boardMatrix: List<List<Int>>, val playedNumbers: Set<Int>) { private val rows = boardMatrix.size private val columns = boardMatrix.first().size private val numbersCoordinates = getNumbersCoordinates(boardMatrix) companion object { fun fromBoardString(boardStr: String): Board { val boardMatrix = boardStr.lines().map { line -> line .split(" ") .filter { digit -> digit.isNotBlank() } .map { i -> i.toInt() } } return Board(boardMatrix, setOf()) } } private fun getNumbersCoordinates(boardMatrix: List<List<Int>>): Map<Int, Pair<Int, Int>> { return boardMatrix.flatMapIndexed { rowNumber, row -> row.mapIndexed { colNumber, number -> number to Pair(rowNumber, colNumber) } }.toMap() } fun unmarkedNumbers(): Set<Int> { return numbersCoordinates.keys.minus(playedNumbers) } fun play(number: Int): Board { if (!numbersCoordinates.containsKey(number)) { return this } val newBoard = this.copy(playedNumbers = playedNumbers + number) return newBoard } fun isBingo(): Boolean { val playedCoordinates = playedNumbers.map { playedNumber -> numbersCoordinates[playedNumber]!! } val bingoOnRows = playedCoordinates .groupingBy { (row, _) -> row } .eachCount() .any { (_, numberOfMarkedNumbers) -> numberOfMarkedNumbers == rows } val bingoOnColumns = playedNumbers.map { numbersCoordinates[it]!! } .groupingBy { (_, col) -> col } .eachCount() .any { (_, numberOfMarkedNumbers) -> numberOfMarkedNumbers == columns } return bingoOnRows.or(bingoOnColumns) } } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
3,338
AdventOfCode2021
MIT License
04maxpath/src/Main.kt
Minkov
125,619,391
false
null
fun fakeInput() { val test = """10 (5 <- 11) (1 <- 8) (11 <- 3) (8 <- 7) (1 <- 5) (11 <- 2) (8 <- 6) (2 <- 15) (8 <- 4)""" System.setIn(test.byteInputStream()) } fun main(args: Array<String>) { // fakeInput() println(solve()) } data class Result(var node: Int, var path: Long) { override fun toString(): String { return "(${this.node}, ${this.path})" } } fun readGraph(): Map<Int, List<Int>> { val n = readLine()!!.toInt() val nodes = mutableMapOf<Int, MutableList<Int>>() for (i in 0 until n - 1) { val (x, y) = readLine()!!.split("<-") .map { if (it.startsWith("(")) { it.substring(1) } else { it.substring(0, it.length - 1) } } .map { it.trim() } .map { it.toInt() } if (!nodes.containsKey(x)) { nodes[x] = mutableListOf() } nodes[x]!!.add(y) if (!nodes.containsKey(y)) { nodes[y] = mutableListOf() } nodes[y]!!.add(x) } return nodes } fun solve(): Long { val nodes = readGraph() val start = getLeaf(nodes) val tempBest = findBest(start, start.toLong(), nodes, -1) val best = findBest(tempBest.node, tempBest.node.toLong(), nodes, -1) return best.path } fun getLeaf(nodes: Map<Int, List<Int>>): Int { for ((node, children) in nodes) { if (children.size == 1) { return node } } return -1 } fun findBest(node: Int, currentPath: Long, nodes: Map<Int, List<Int>>, parent: Int): Result { val best = Result(node, currentPath) nodes[node]!! .filter { next -> next != parent } .forEach { next -> val current = findBest(next, currentPath + next, nodes, node) if (current.path > best.path) { best.path = current.path best.node = current.node } } return best }
0
JavaScript
4
1
3c17dcadd5aa201166d4fff69d055d7ec0385018
2,068
judge-solved
MIT License
src/Day09.kt
li-xin-yi
573,617,763
false
{"Kotlin": 23422}
import kotlin.math.abs fun main() { val directions = mapOf( "R" to (0 to 1), "L" to (0 to -1), "U" to (1 to 0), "D" to (-1 to 0) ) fun solvePart1(input: List<String>): Int { val seen = mutableSetOf(0 to 0) var (hx, hy) = 0 to 0 var (tx, ty) = 0 to 0 for (line in input) { val (a, b) = line.split(" ") val (dx, dy) = directions[a]!! for (i in 1..b.toInt()) { hx += dx hy += dy if (abs(hx - tx) <= 1 && abs(hy - ty) <= 1) { seen.add(tx to ty) continue } tx += (if (hx > tx) 1 else if (hx < tx) -1 else 0) ty += (if (hy > ty) 1 else if (hy < ty) -1 else 0) seen.add(tx to ty) } } return seen.size } fun solvePart2(input: List<String>): Int { val seen = mutableSetOf(0 to 0) val rope = MutableList(10) { 0 to 0 } fun updateTail(i: Int) { val (preX, preY) = rope[i] val (curX, curY) = rope[i + 1] if (abs(preX - curX) <= 1 && abs(preY - curY) <= 1) { return } val newX = curX + (if (preX > curX) 1 else if (preX < curX) -1 else 0) val newY = curY + (if (preY > curY) 1 else if (preY < curY) -1 else 0) rope[i + 1] = newX to newY } for (line in input) { val (a, b) = line.split(" ") val (dx, dy) = directions[a]!! for (i in 1..b.toInt()) { val (x, y) = rope[0] rope[0] = x + dx to y + dy for (j in 0 until 9) { updateTail(j) } seen.add(rope[9]) } } return seen.size } val testInput1 = readInput("input/Day09_test1") val testInput2 = readInput("input/Day09_test2") check(solvePart1(testInput1) == 13) check(solvePart2(testInput1) == 1) check(solvePart2(testInput2) == 36) val input = readInput("input/Day09_input") println(solvePart1(input)) println(solvePart2(input)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
2,214
AoC-2022-kotlin
Apache License 2.0
src/Day02.kt
mkfsn
573,042,358
false
{"Kotlin": 29625}
fun main() { // Rock: A // Paper: B // Scissors: C val (rock, paper, scissors) = listOf(1, 2, 3); val (win, draw, loss) = listOf(6, 3, 0); fun part1(input: List<String>): Int { // Rock: X // Paper: Y // Scissors: Z val scores = hashMapOf( "A X" to draw + rock, "A Y" to win + paper, "A Z" to loss + scissors, "B X" to loss + rock, "B Y" to draw + paper, "B Z" to win + scissors, "C X" to win + rock, "C Y" to loss + paper, "C Z" to draw + scissors, ) return input.map { scores.getValue(it) }.sumOf { it } } fun part2(input: List<String>): Int { // loss: X // draw: Y // win: Z val scores = hashMapOf( "A X" to loss + scissors, "A Y" to draw + rock, "A Z" to win + paper, "B X" to loss + rock, "B Y" to draw + paper, "B Z" to win + scissors, "C X" to loss + paper, "C Y" to draw + scissors, "C Z" to win + rock, ) return input.map { scores.getValue(it) }.sumOf { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 8 + 1 + 6) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
8c7bdd66f8550a82030127aa36c2a6a4262592cd
1,507
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2017/Day07.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 import kotlin.math.absoluteValue /** * AoC 2017, Day 7 * * Problem Description: http://adventofcode.com/2017/day/7 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day7/ */ class Day07(input: List<String>) { private val headOfTree: Node = parseInput(input) fun solvePart1(): String = headOfTree.name fun solvePart2(): Int = headOfTree.findImbalance() private fun parseInput(input: List<String>): Node { val nodesByName = mutableMapOf<String, Node>() val parentChildPairs = mutableSetOf<Pair<Node, String>>() val rowRegex = """\w+""".toRegex() input.forEach { val groups = rowRegex.findAll(it).toList().map { it.value } val node = Node(groups[0], groups[1].toInt()) nodesByName.put(node.name, node) groups.drop(2).forEach { parentChildPairs.add(Pair(node, it)) } } parentChildPairs.forEach { (parent, childName) -> with(nodesByName.getValue(childName)) { parent.children.add(this) this.parent = parent } } // Find the one node we have without a parent. Or freak out. return nodesByName.values.firstOrNull { it.parent == null } ?: throw IllegalStateException("No head node?!") } } data class Node(val name: String, private val weight: Int, val children: MutableList<Node> = mutableListOf(), var parent: Node? = null) { fun findImbalance(imbalance: Int? = null): Int = if (imbalance != null && childrenAreBalanced) { // We end when I have a positive imbalance and my children are balanced. weight - imbalance } else { // Find the child tree that is off. val subtreesByWeight = children.groupBy { it.totalWeight } // Find the imbalanced child tree (they will be the lone node in the list, when grouped by weight) val badTree = subtreesByWeight.minBy { it.value.size }?.value?.first() ?: throw IllegalStateException("Should not be balanced here.") // Recurse, passing down our imbalance. If we don't know the imbalance, calculate it. // Calculate the imbalance as the absolute value of the difference of all distinct weights badTree.findImbalance(imbalance ?: subtreesByWeight.keys.reduce { a, b -> a - b }.absoluteValue) } private val totalWeight: Int by lazy { weight + children.sumBy { it.totalWeight } } private val childrenAreBalanced: Boolean by lazy { children.map { it.totalWeight }.distinct().size == 1 } }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
2,823
advent-2017-kotlin
MIT License
src/Day11.kt
RogozhinRoman
572,915,906
false
{"Kotlin": 28985}
fun main() { class Monkey( var items: MutableList<Long>, var operation: (old: Long) -> Long, var divisor: Long, var trueReceiver: Int, var falseReceiver: Int, var totalInspected: Long = 0 ) fun getTask2Monkeys(): List<Monkey> { return listOf( Monkey(mutableListOf(83, 62, 93), { old -> old * 17 }, 2, 1, 6), Monkey(mutableListOf(90, 55), { old -> old + 1 }, 17, 6, 3), Monkey(mutableListOf(91, 78, 80, 97, 79, 88), { old -> old + 3 }, 19, 7, 5), Monkey(mutableListOf(64, 80, 83, 89, 59), { old -> old + 5 }, 3, 7, 2), Monkey(mutableListOf(98, 92, 99, 51), { old -> old * old }, 5, 0, 1), Monkey(mutableListOf(68, 57, 95, 85, 98, 75, 98, 75), { old -> old + 2 }, 13, 4, 0), Monkey(mutableListOf(74), { old -> old + 4 }, 7, 3, 2), Monkey(mutableListOf(68, 64, 60, 68, 87, 80, 82), { old -> old * 19 }, 11, 4, 5) ) } fun getTask1Monkeys(): List<Monkey> { return listOf( Monkey(mutableListOf(79, 98), { old -> old * 19 }, 23, 2, 3), Monkey(mutableListOf(54, 65, 75, 74), { old -> old + 6 }, 19, 2, 0), Monkey(mutableListOf(79, 60, 97), { old -> old * old }, 13, 1, 3), Monkey(mutableListOf(74), { old -> old + 3 }, 17, 0, 1) ) } fun getMaxTotal(monkeys: List<Monkey>, reducer: (Long) -> Long): Long { for (i in 0 until 20) { for (monkey in monkeys) { for (item in monkey.items) { monkey.totalInspected++ val newWorryLevel = reducer(monkey.operation(monkey.items.first())) monkey.items = monkey.items.drop(1).toMutableList() val nextReceiver = if (newWorryLevel % monkey.divisor == 0L) { monkey.trueReceiver } else { monkey.falseReceiver } monkeys[nextReceiver].items.add(newWorryLevel) } } } return monkeys .sortedByDescending { it.totalInspected } .take(2) .fold(1) { acc, monkey -> monkey.totalInspected * acc } } fun part1() = getMaxTotal(getTask2Monkeys()) { number -> number / 3 } fun part2() = getMaxTotal( getTask2Monkeys() ) { number -> number % listOf(2, 17, 19, 3, 5, 13, 7, 11).reduce { acc, i -> acc * i }.toLong() } // val testInput = readInput("DayN_test") // check(part1() == 10605) println(part2()) check(part2() == 2713310158) // // val input = readInput("DayN") // println(part1()) // println(part2(input)) }
0
Kotlin
0
1
6375cf6275f6d78661e9d4baed84d1db8c1025de
2,737
AoC2022
Apache License 2.0
year2023/src/main/kotlin/net/olegg/aoc/year2023/day12/Day12.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2023.day12 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.parseInts import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2023.DayOf2023 /** * See [Year 2023, Day 12](https://adventofcode.com/2023/day/12) */ object Day12 : DayOf2023(12) { private val EMPTY = setOf('.', '?', null) private val FILLED = setOf('#', '?') override fun first(): Any? { return lines .map { line -> line.split(" ").toPair() } .map { (line, counts) -> line to counts.parseInts(",") } .sumOf { (line, counts) -> count(line, counts) } } override fun second(): Any? { return lines .map { line -> line.split(" ").toPair() } .map { (line, counts) -> line to counts.parseInts(",") } .map { (line, counts) -> List(5) { line }.joinToString(separator = "?") to List(5) { counts }.flatten() } .sumOf { (line, counts) -> count(line, counts) } } private fun count( line: String, counts: List<Int> ): Long { val dyn = Array(counts.size + 1) { LongArray(line.length + 1) { 0 } } dyn[0][line.length] = 1 line.withIndex() .reversed() .takeWhile { it.value != '#' } .forEach { dyn[0][it.index] = 1 } for (j in 1..counts.size) { val count = counts[counts.size - j] val fix = if (j == 1) 0 else 1 for (i in line.length - 1 downTo 0) { if (line[i] in EMPTY) { dyn[j][i] += dyn[j].getOrElse(i + 1) { 0 } } if (line[i] in FILLED) { if (line.getOrNull(i - 1) in EMPTY && (i + 1..<i + count).all { line.getOrNull(it) in FILLED } && line.getOrNull(i + count) in EMPTY ) { dyn[j][i] += dyn[j - 1].getOrElse(i + count + fix) { 0 } } } } } return dyn.last().first() } } fun main() = SomeDay.mainify(Day12)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,932
adventofcode
MIT License
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day07.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2022 import com.dvdmunckhof.aoc.splitOnce class Day07(private val input: List<String>) { val root = parseTerminalOutput() fun solvePart1(): Int { val results = filterTree(root) { it.size < 100_000 } return results.sumOf { it.size } } fun solvePart2(): Int { val requiredSpace = root.size - 40_000_000 val results = filterTree(root) { it.size > requiredSpace } return results.minOf { it.size } } private fun filterTree(dir: Dir, predicate: (node: Node) -> Boolean): List<Node> { val results = dir.children.filterIsInstance<Dir>() .flatMap { filterTree(it, predicate) } return if (predicate(dir)) results + dir else results } private fun parseTerminalOutput(): Dir { val root = Dir("/", null) var cwd: Dir = root for (line in input) { if (line.startsWith("$ cd")) { val dir = line.substringAfterLast(" ") cwd = when (dir) { "/" -> root ".." -> cwd.parent!! else -> cwd.subDir(dir) } } else if (line != "$ ls") { if (line.startsWith("dir")) { val name = line.substring(4) cwd.children += Dir(name, cwd) } else { val (size, name) = line.splitOnce(" ") cwd.children += File(name, size.toInt(), cwd) } } } return root } sealed class Node(val name: String, val parent: Dir?) { abstract val size: Int abstract fun toString(prefix: String): String } class File(name: String, override val size: Int, parent: Dir?) : Node(name, parent) { override fun toString(prefix: String) = "$prefix $name (file, size=$size)" } class Dir(name: String, parent: Dir?) : Node(name, parent) { val children = mutableListOf<Node>() fun subDir(name: String): Dir { return children.first { it.name == name } as Dir } override val size by lazy { children.sumOf(Node::size) } override fun toString(prefix: String): String { return children.joinToString("\n", "$prefix $name (dir)\n") { it.toString(" $prefix") } } } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
2,388
advent-of-code
Apache License 2.0
src/main/kotlin/year_2023/Day02.kt
krllus
572,617,904
false
{"Kotlin": 97314}
package year_2023 import Day import solve class Day02 : Day(day = 2, year = 2023, "Cube Conundrum") { private fun getGames() : Set<Game> { val games = mutableSetOf<Game>() for(entry in input){ val gameStr = entry.split(":") val id = gameStr.first().split(" ").last().toInt() val rounds = gameStr.last().split(";") for(round in rounds){ val cubes = round.split(",") var red = 0 var green = 0 var blue = 0 for(cube in cubes){ if (cube.contains("red")) red = cube.replace("[^0-9]".toRegex(),"").toInt() if (cube.contains("green")) green = cube.replace("[^0-9]".toRegex(),"").toInt() if (cube.contains("blue")) blue = cube.replace("[^0-9]".toRegex(),"").toInt() } games.add(Game(id, red, green, blue)) } } return games } override fun part1(): Int{ return getGames().groupBy { it.id } .mapNotNull { if(it.value.any {game -> !game.isPossible() }) null else it.key }.sum() } override fun part2(): Int{ return getGames().groupBy { it.id } .map { val maxRed = it.value.maxBy { game -> game.red }.red val maxGreen = it.value.maxBy { game -> game.green }.green val maxBlue = it.value.maxBy { game -> game.blue }.blue maxRed * maxGreen * maxBlue }.sum() } } data class Game( val id : Int, val red : Int, val green : Int, val blue : Int ){ fun isPossible() : Boolean = red <= 12 && green <= 13 && blue <= 14 } fun main() { solve<Day02>(offerSubmit = true) { """ 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 """.trimIndent()(part1 = 8, 2286) } }
0
Kotlin
0
0
b5280f3592ba3a0fbe04da72d4b77fcc9754597e
2,325
advent-of-code
Apache License 2.0
src/main/kotlin/me/astynax/aoc2023kt/Day02.kt
astynax
726,011,031
false
{"Kotlin": 9743}
package me.astynax.aoc2023kt object Day02 { data class Take(val r: Int, val g: Int, val b: Int) { infix fun contains(other: Take): Boolean = r >= other.r && g >= other.g && b >= other.b private infix fun Int.max(other: Int): Int = if (this >= other) this else other infix fun max(other: Take): Take = Take(r max other.r, g max other.g, b max other.b) } private val bag = Take(12, 13, 14) fun step1(games: List<Pair<Int, List<Take>>>): Int = games.filter { (_, ts) -> ts.all { bag contains it } }.sumOf { it.first } fun step2(games: List<Pair<Int, List<Take>>>): Int = games.sumOf { (_, takes) -> takes.fold(Take(1, 1, 1)) { acc, t -> acc max t } .let { t -> t.r * t.g * t.b } } val input = lazy { Input.linesFrom("/Day02.input").map { it.asGame() } } fun String.asGame(): Pair<Int, List<Take>> = this.split(Regex(": ")).let { m -> val id = m.first().removePrefix("Game ").toInt() val takes = m.last().split(Regex("; ")).map { take -> take.split(Regex(", ")).fold(Take(0, 0, 0)) { acc, s -> val part = s.split(" ") val n = part.first().toInt() when (part.last()) { "red" -> acc.copy(r = n) "green" -> acc.copy(g = n) "blue" -> acc.copy(b = n) else -> throw IllegalArgumentException("Bad line part: $s") } } } id to takes } }
0
Kotlin
0
0
9771b5ccde4c591c7edb413578c5a8dadf3736e0
1,449
aoc2023kt
MIT License
archive/2022/Day09.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.sign private const val EXPECTED_1 = 13 private const val EXPECTED_2 = 1 private fun Pair<Int, Int>.update(other: Pair<Int, Int>): Pair<Int, Int> { val d = other.first - first to other.second - second if (max(d.first.absoluteValue, d.second.absoluteValue) <= 1) { return this } return (this.first + d.first.sign to this.second + d.second.sign) } private operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>) = first + other.first to second + other.second private class Day09(isTest: Boolean) : Solver(isTest) { val dMap = mapOf( 'R' to (1 to 0), 'L' to (-1 to 0), 'U' to (0 to 1), 'D' to (0 to -1) ) fun part1(): Any { var pos = 0 to 0 var tailPos = 0 to 0 val tailSet = mutableSetOf(tailPos) for (line in readAsLines()) { repeat(line.substring(2).toInt()) { pos += dMap[line[0]]!! tailPos = tailPos.update(pos) tailSet.add(tailPos) } } return tailSet.size } fun part2(): Any { val pos = (0..9).map { 0 to 0 }.toMutableList() val tailSet = mutableSetOf(pos[9]) for (line in readAsLines()) { repeat(line.substring(2).toInt()) { pos[0] += dMap[line[0]]!! for (i in 1..9) { pos[i] = pos[i].update(pos[i - 1]) } tailSet.add(pos[9]) } } return tailSet.size } } fun main() { val testInstance = Day09(true) val instance = Day09(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println(instance.part1()) testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } } println(instance.part2()) }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
1,925
advent-of-code-2022
Apache License 2.0
src/Day05.kt
xNakero
572,621,673
false
{"Kotlin": 23869}
class Day05 { private val input = readInput("day05") private val commands = readCommands() fun part1(): String = readCrates() .let { commands.fold(it) { c, cmd -> moveCratesByOne(cmd, c) } } .toOutput() fun part2(): String = readCrates() .let { commands.fold(it) { c, cmd -> moveCratesBatch(cmd, c) } } .toOutput() private fun moveCratesByOne(cmd: Command, crates: List<ArrayDeque<String>>): List<ArrayDeque<String>> { repeat((0 until cmd.count).count()) { crates[cmd.destination].add(crates[cmd.source].removeLast()) } return crates } private fun moveCratesBatch(cmd: Command, crates: List<ArrayDeque<String>>): List<ArrayDeque<String>> { crates[cmd.destination].addAll(crates[cmd.source].takeLast(cmd.count)) repeat((0 until cmd.count).count()) { crates[cmd.source].removeLast() } return crates } private fun readCrates() = input .subList(0, input.indexOfFirst { it.isBlank() }) .map { it.chunked(4).map { it1 -> it1.replace(" ", "") } } .let { i -> val crates = i.dropLast(1) List(i.last().size) { index -> crates.map { if (it.size > index) it[index] else "" } } } .map { stack -> stack.filter { it.isNotBlank() }.reversed() } .toArrayDeque() private fun readCommands() = input .subList(input.indexOfFirst { it.isBlank() } + 1, input.lastIndex + 1) .map { line -> line.filter { it.isDigit() || it == ' ' } .split(" ") .filter { it.isNotBlank() } } .map { Command(count = it[0].toInt(), source = it[1].toInt() - 1, destination = it[2].toInt() - 1) } } private fun List<List<String>>.toArrayDeque() = map { ArrayDeque<String>().apply { this.addAll(it) } } private fun List<ArrayDeque<String>>.toOutput() = map { it.last()[1] }.joinToString("") data class Command(val count: Int, val source: Int, val destination: Int) fun main() { val day5 = Day05() println(day5.part1()) println(day5.part2()) }
0
Kotlin
0
0
c3eff4f4c52ded907f2af6352dd7b3532a2da8c5
2,119
advent-of-code-2022
Apache License 2.0
src/main/kotlin/adventofcode2019/Day10MonitoringStation.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2019 import java.lang.Math.toDegrees import kotlin.math.abs import kotlin.math.atan2 class Day10MonitoringStation data class Asteroid( val x: Int, val y: Int, var isVaborized: Boolean = false ) class Ceres(map: List<String>) { val asteroids: List<Asteroid> init { asteroids = map.flatMapIndexed { y, line -> line.mapIndexed { x, element -> if (element == '#') Asteroid(x, y) else null } }.filterNotNull() } fun detectionsFromBestLocation(): Int { val (bestX, bestY) = detectBestLocation() return asteroids.size - 1 - (hiddenAsteroidsFrom(bestX, bestY)) } fun detectBestLocation(): Pair<Int, Int> { val (bestX, bestY) = asteroids.minBy { asteroid -> hiddenAsteroidsFrom(asteroid.x, asteroid.y) } return bestX to bestY } fun vaborize(): Int { val (bestX, bestY) = detectBestLocation() val groupsByAngle = asteroids .filterNot { asteroid -> (asteroid.x == bestX && asteroid.y == bestY) } .groupBy { asteroid -> calculateAngleFromNorth(bestX, bestY, asteroid.x, asteroid.y) }.toSortedMap() var counter = 0 var nextAsteroidToVaborize: Asteroid? while (true) { groupsByAngle.forEach { group -> nextAsteroidToVaborize = group.value .filter { asteroid -> asteroid.isVaborized == false } .sortedBy { asteroid -> manhattanDistance(bestX, bestY, asteroid.x, asteroid.y) }.firstOrNull() nextAsteroidToVaborize?.let { it.isVaborized = true if (counter == 199) { return (it.x * 100) + it.y } counter++ } } } } fun hiddenAsteroidsFrom(x: Int, y: Int): Int { val u = if (upNeighborsCount(x, y) > 0) upNeighborsCount(x, y) - 1 else 0 val d = if (downNeighborsCount(x, y) > 0) downNeighborsCount(x, y) - 1 else 0 val l = if (leftNeighborsCount(x, y) > 0) leftNeighborsCount(x, y) - 1 else 0 val r = if (rightNeighborsCount(x, y) > 0) rightNeighborsCount(x, y) - 1 else 0 val a = hiddenBySameAngleCount(x, y) return u + d + l + r + a } fun upNeighborsCount(x: Int, y: Int) = asteroids.count { asteroid -> asteroid.x == x && asteroid.y < y } fun downNeighborsCount(x: Int, y: Int) = asteroids.count { asteroid -> asteroid.x == x && asteroid.y > y } fun leftNeighborsCount(x: Int, y: Int) = asteroids.count { asteroid -> asteroid.x < x && asteroid.y == y } fun rightNeighborsCount(x: Int, y: Int) = asteroids.count { asteroid -> asteroid.x > x && asteroid.y == y } fun hiddenBySameAngleCount(x: Int, y: Int): Int { val matches = asteroids.filterNot { asteroid -> asteroid.x == x || asteroid.y == y } .groupBy { asteroid -> calculateAngleFromNorth(x, y, asteroid.x, asteroid.y) } var totalCount = 0 matches.forEach { group -> totalCount += if (group.value.size > 1) group.value.size - 1 else 0 } return totalCount } fun calculateAngleFromNorth(referenceX: Int, referenceY: Int, asteroidX: Int, asteroidY: Int): Double { val angle = toDegrees( atan2( (asteroidY - referenceY).toDouble(), (asteroidX - referenceX).toDouble() ) ) + 90 return if (angle < 0) angle + 360 else angle } fun manhattanDistance(referenceX: Int, referenceY: Int, asteroidX: Int, asteroidY: Int) = abs(referenceX - asteroidX) + abs(referenceY - asteroidY) }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
3,719
kotlin-coding-challenges
MIT License
src/main/kotlin/aoc22/Day09.kt
asmundh
573,096,020
false
{"Kotlin": 56155}
package aoc22 import datastructures.Coordinate import readInput enum class Direction { UP, DOWN, LEFT, RIGHT; companion object { fun from(str: String) = when (str) { "U" -> UP "D" -> DOWN "L" -> LEFT "R" -> RIGHT else -> throw Exception("Nei nei nei for $str") } } } data class KnottedRope( val size: Int, val knots: MutableList<Knot> = mutableListOf() ) { init { knots.add(Knot(name = "H", parentKnot = null)) for (i in 1 until size) { knots.add(Knot(name = "$i", parentKnot = knots.last())) } } fun move(direction: Direction) { for (knot in knots) { if (knot.parentKnot == null) knot.move(direction) else knot.follow(knot.parentKnot) } } } data class Knot( var position: Coordinate = Coordinate(0, 0), val name: String, val parentKnot: Knot?, ) { fun move(direction: Direction) { position = when (direction) { Direction.UP -> position.copy(y = position.y + 1) Direction.DOWN -> position.copy(y = position.y - 1) Direction.LEFT -> position.copy(x = position.x - 1) Direction.RIGHT -> position.copy(x = position.x + 1) } } fun follow(parentKnot: Knot?) { if (parentKnot == null || position.touches(parentKnot.position)) return val moveX = parentKnot.position.x.compareTo(position.x) val moveY = parentKnot.position.y.compareTo(position.y) position = position.copy(x = position.x + moveX, y = position.y + moveY) } override fun toString() = "${position.x},${position.y}($name)" } fun day9part1(input: List<String>): Int { val visitedCells: MutableSet<Coordinate> = mutableSetOf() val rope = KnottedRope(2) input.forEach { val command = it.split(" ") repeat(command[1].toInt()) { rope.move(Direction.from(command[0])) visitedCells.add(rope.knots.last().position) } } return visitedCells.size } fun day9part2(input: List<String>): Int { val visitedCells: MutableSet<Coordinate> = mutableSetOf() val rope = KnottedRope(size = 10) input.forEach { val command = it.split(" ") repeat(command[1].toInt()) { rope.move(Direction.from(command[0])) visitedCells.add(rope.knots.last().position) } } return visitedCells.size } fun main() { val input = readInput("Day09") println(day9part1(input)) println(day9part2(input)) }
0
Kotlin
0
0
7d0803d9b1d6b92212ee4cecb7b824514f597d09
2,596
advent-of-code
Apache License 2.0
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day02/day02.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day02 import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input02-test.txt" const val FILENAME = "input02.txt" fun main() { val puzzles = readLines(2023, FILENAME) .map { Puzzle.parse(it) } val possible = puzzles.filter { it.matches(12, 13, 14) }.sumOf { it.id } println(possible) val colorPowers = puzzles.sumOf { it.minColorsNeeded().power() } println(colorPowers) } data class ColorTriplet(val red: Int, val green: Int, val blue: Int) { fun power() = red * green * blue companion object { fun parse(input: String): ColorTriplet { val parts = input.split(",") .map { it.trim().split(" ") } .map { Pair(it[1], it[0].toInt()) } fun findColor(color: String): Int { return parts.find { it.first == color }?.second ?: 0 } return ColorTriplet(findColor("red"), findColor("green"), findColor("blue")) } } } data class Puzzle(val id: Int, val entries: List<ColorTriplet>) { fun matches(totalRed: Int, totalGreen: Int, totalBlue: Int): Boolean { return entries.all { it.red <= totalRed && it.green <= totalGreen && it.blue <= totalBlue } } fun minColorsNeeded() = ColorTriplet( entries.maxOfOrNull { it.red } ?: 0, entries.maxOfOrNull { it.green } ?: 0, entries.maxOfOrNull { it.blue } ?: 0 ) companion object { fun parse(input: String): Puzzle { val parts = input.split(":") val id = parts[0].split(" ")[1].toInt() val entries = parts[1].split(";").map { ColorTriplet.parse(it) } return Puzzle(id, entries) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,527
advent-of-code
Apache License 2.0
src/y2021/d03/Day03.kt
AndreaHu3299
725,905,780
false
{"Kotlin": 31452}
package y2021.d03 import println import readInput fun main() { val classPath = "y2021/d03" fun part1(input: List<String>): Int { val length = input[0].length val halfSize = (input.size / 2) val counts = input.fold(IntArray(length)) { acc, line -> line.forEachIndexed { index, c -> if (c == '1') acc[index]++ } acc } val gamma = counts.map { if (it > halfSize) '1' else '0' }.joinToString("") val epsilon = counts.map { if (it > halfSize) '0' else '1' }.joinToString("") return gamma.toInt(2) * epsilon.toInt(2) } fun part2(input: List<String>): Int { // oxygen var pos = 0 var list = input.toMutableList() while (list.size > 1) { val counts = list.groupingBy { it[pos] }.eachCount() val majority = if (counts['1']!! >= counts['0']!!) '1' else '0' list.removeIf { it[pos] != majority } pos++ } val oxygen = list[0].toInt(2) // co2 pos = 0 list = input.toMutableList() while (list.size > 1) { val counts = list.groupingBy { it[pos] }.eachCount() val minority = if (counts['1']!! < counts['0']!!) '1' else '0' list.removeIf { it[pos] != minority } pos++ } val co2 = list[0].toInt(2) return oxygen * co2 } // test if implementation meets criteria from the description, like: val testInput = readInput("${classPath}/test") part1(testInput).println() part2(testInput).println() val input = readInput("${classPath}/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e
1,728
aoc
Apache License 2.0
src/year2022/day13/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day13 import com.google.gson.JsonElement import io.kotest.matchers.shouldBe import utils.RecursiveList import utils.parseRecursiveList import utils.readInput fun main() { val testInput = readInput("13", "test_input").packetSequence() val realInput = readInput("13", "input").packetSequence() testInput.chunked(2) .withIndex() .sumOf { (index, values) -> val (first, second) = values if (first < second) index + 1 else 0 } .also(::println) shouldBe 13 realInput.chunked(2) .withIndex() .sumOf { (index, values) -> val (first, second) = values if (first < second) index + 1 else 0 } .let(::println) val firstDecoderKey = parseRecursiveList("[[2]]", elementParsing = JsonElement::getAsInt) val secondDecoderKey = parseRecursiveList("[[6]]", elementParsing = JsonElement::getAsInt) testInput.sortedWith(packetOrderComparator) .let { packets -> val indexOfFirstDecoder = packets.indexOfFirst { it >= firstDecoderKey } + 1 val indexOfLastDecoder = packets.drop(indexOfFirstDecoder) .indexOfFirst { it >= secondDecoderKey } .plus(indexOfFirstDecoder + 2) indexOfFirstDecoder * indexOfLastDecoder } .also(::println) shouldBe 140 realInput.sortedWith(packetOrderComparator) .let { packets -> val indexOfFirstDecoder = packets.indexOfFirst { it >= firstDecoderKey } + 1 val indexOfLastDecoder = packets.drop(indexOfFirstDecoder) .indexOfFirst { it >= secondDecoderKey } .plus(indexOfFirstDecoder + 2) indexOfFirstDecoder * indexOfLastDecoder } .let(::println) } private fun List<String>.packetSequence(): Sequence<RecursiveList<Int>> { return asSequence() .filter(String::isNotBlank) .map { parseRecursiveList(it, elementParsing = JsonElement::getAsInt) } } private operator fun RecursiveList<Int>.compareTo(other: RecursiveList<Int>): Int { return if (this is RecursiveList.Element && other is RecursiveList.Element) value.compareTo(other.value) else { val o1List = this.let { it as? RecursiveList.NestedList } ?: RecursiveList.NestedList(listOf(this)) val o2List = other.let { it as? RecursiveList.NestedList } ?: RecursiveList.NestedList(listOf(other)) o1List.asSequence() .zip(o2List.asSequence()) .map { (first, second) -> first.compareTo(second) } .firstOrNull { it != 0 } ?: o1List.size.compareTo(o2List.size) } } private val packetOrderComparator = Comparator(RecursiveList<Int>::compareTo)
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,774
Advent-of-Code
Apache License 2.0
2023/11/eleven.kt
charlottemach
433,765,865
false
{"D": 7911, "Haxe": 5698, "Go": 5682, "Julia": 5361, "R": 5032, "Kotlin": 4670, "Dockerfile": 4516, "C++": 4312, "Haskell": 4113, "Scala": 4080, "OCaml": 3901, "Raku": 3680, "Erlang": 3436, "Swift": 2863, "Groovy": 2861, "Vala": 2845, "JavaScript": 2735, "Crystal": 2210, "Python": 2197, "Clojure": 2172, "Ruby": 2163, "Perl": 2035, "Rust": 2018, "C": 1649, "Nim": 1611, "PHP": 1562, "Java": 1516, "Awk": 1204, "Dart": 1198, "Elixir": 1120, "Racket": 841, "Standard ML": 824, "Shell": 152}
import java.io.File import java.math.BigInteger import java.util.Collections fun main() { val input = File("input.txt").readText() println(cosmicExpansion(input,2)) println(cosmicExpansion(input,1000000)) } fun cosmicExpansion(input: String, times: Int):BigInteger{ var lines = input.split("\n").dropLast(1) var n = lines.size var map = Array(n) {Array(n) {""} } var galaxies = arrayOf<Pair<Int,Int>>() for (y in 0..n-1) { val line = lines[y].split("").drop(1).dropLast(1) for (x in 0..n-1) { var v = line[x] map[y][x] = v if (v == "#") { galaxies += Pair(x,y) } } } //pprint(map) var distSum = 0.toBigInteger() var (xs,ys) = getExpandLines(map,n) for (gi in 0..galaxies.size) { for (gj in gi+1..galaxies.size-1) { var p1 = galaxies[gi] var p2 = galaxies[gj] distSum += getDist(p1,p2,xs,ys,times) } } return distSum } fun getDist(p1:Pair<Int,Int>, p2:Pair<Int,Int>, xs:Array<Int>, ys: Array<Int>, times:Int):BigInteger { var (x1,y1) = p1 var (x2,y2) = p2 var dist = Math.abs(x2-x1) + Math.abs(y2-y1) if (x1 < x2) { x2 = x1.apply{x1 = x2} } if (y1 < y2) { y2 = y1.apply{y1 = y2} } var cnt = 0 for (xx in x2..x1) { if (xs.any({x -> x==xx})) { cnt += 1 } } for (yy in y2..y1) { if (ys.any({y -> y==yy})) { cnt += 1 } } return dist.toBigInteger() + (cnt.toBigInteger() * (times-1).toBigInteger()) } fun getExpandLines(map:Array<Array<String>>, n:Int):Pair<Array<Int>,Array<Int>> { var ys = arrayOf<Int>() for (x in 0..n-1) { var col = arrayOf<String>() for (y in 0..n-1) { col += map[y][x] } if (col.all({y -> y=="."})) { ys += x } } var xs = arrayOf<Int>() for (x in 0..n-1) { if (map[x].all({x -> x!="#"})) { xs += x } } return Pair(ys,xs) } fun pprint(map: Array<Array<String>>) { for (line in map) { for (l in line) { print(l) } print("\n") } }
0
D
0
0
dc839943639282005751b68a7988890dadf00f41
2,245
adventofcode
Apache License 2.0
2021/src/main/kotlin/day23.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import Day23.Cell.EMPTY import utils.Parser import utils.Point3i import utils.Solution fun main() { Day23.run() } object Day23 : Solution<Day23.Burrow>() { override val name = "day23" override val parser = Parser.lines.map { lines -> val roomCells = lines.drop(2).filter { "#########" !in it } .map { it.substring(3, 10).split('#').map { Cell.valueOf(it) } } val rooms = (0..3).map { idx -> Room(roomCells.map { it[idx] }) } Burrow(List(size = 7) { EMPTY }, rooms) } data class Burrow( val hallway: List<Cell>, // always size=7 val rooms: List<Room>, // always size=4 ) { val solved: Boolean get() { for (room in rooms.indices) { for (cell in rooms[room].cells) { if (cell.room != room) { return false } } } return true } fun swap(hallwayIndex: Int, roomIndex: Int): Burrow { val hallwayCell = hallway[hallwayIndex] val cellIndex = if (hallwayCell == EMPTY) { rooms[roomIndex].cells.indexOfFirst { it != EMPTY } } else { rooms[roomIndex].cells.indexOfLast { it == EMPTY } } val roomCell = rooms[roomIndex].cells[cellIndex] require(hallway[hallwayIndex] == EMPTY || rooms[roomIndex].cells[cellIndex] == EMPTY) { "Can't swap if one of the places isn't empty" } return copy( hallway = List(size = 7) { if (it == hallwayIndex) roomCell else hallway[it] }, rooms = List(size = 4) { if (it == roomIndex) { rooms[it].copy(cells = rooms[it].cells.mapIndexed { index, cell -> if (index == cellIndex) hallway[hallwayIndex] else cell }) } else rooms[it] } ) } override fun toString(): String { return buildString { append("#############\n") append("#${hallway[0]}${hallway[1]}.${hallway[2]}.${hallway[3]}.${hallway[4]}.${hallway[5]}${hallway[6]}#\n") val cells = rooms.first().cells.size for (i in 0 until cells) { if (i == 0) { append("###") } else { append(" #") } for (room in rooms) { append("${room.cells[i]}#") } if (i == 0) { append("##\n") } else { append(" \n") } } append(" ######### ") } } } data class Room( val cells: List<Cell> // size = arbitrary ) enum class Cell(val energy: Int, val room: Int) { EMPTY(0, -1), A(1, 0), B(10, 1), C(100, 2), D(1000, 3); override fun toString() = when (this) { EMPTY -> "." else -> this.name } } fun canMove(burrow: Burrow, from: Int, roomIndex: Int): Boolean { val left = roomIndex + 1 val right = roomIndex + 2 if (from <= left) { return burrow.hallway.subList(from + 1, left + 1).all { it == EMPTY } } else { return burrow.hallway.subList(right, from).all { it == EMPTY } } } val hallwayCoords = listOf( Point3i(0, 0, 0), Point3i(1, 0, 0), Point3i(3, 0, 0), Point3i(5, 0, 0), Point3i(7, 0, 0), Point3i(9, 0, 0), Point3i(10, 0, 0), ) val roomCoords = listOf( Point3i(2, 1, 0), Point3i(4, 1, 0), Point3i(6, 1, 0), Point3i(8, 1, 0), ) fun cost(hallway: Int, room: Int, cell: Cell, cellIndex: Int): Long { val dist = hallwayCoords[hallway].distanceManhattan(roomCoords[room]) + cellIndex return (dist.toLong() * cell.energy).also { require(it > 0) } } fun moveHtoR(burrow: Burrow, from: Int): Pair<Burrow, Long>? { val cell = burrow.hallway[from] if (cell == EMPTY) { return null } val room = cell.room val cellIndex = burrow.rooms[room].cells.indexOfLast { it == EMPTY } if (cellIndex == -1) { return null } for (i in cellIndex + 1 until burrow.rooms[room].cells.size) { if (burrow.rooms[room].cells[i] != cell) { return null } } if (canMove(burrow, from, room)) { return burrow.swap(from, room) to cost(from, room, cell, cellIndex) } return null } fun moveRtoH(burrow: Burrow, fromRoom: Int, to: Int): Pair<Burrow, Long>? { val room = burrow.rooms[fromRoom] val cellIndex = burrow.rooms[fromRoom].cells.indexOfFirst { it != EMPTY } if (cellIndex == -1) { return null } if (burrow.hallway[to] != EMPTY) { return null } if (!canMove(burrow, to, fromRoom)) { return null } val cell = burrow.rooms[fromRoom].cells[cellIndex] if (cell.room == fromRoom) { if (burrow.rooms[fromRoom].cells.subList(cellIndex + 1, burrow.rooms[fromRoom].cells.size).all { it.room == fromRoom }) { // all in place return null } } return burrow.swap(to, fromRoom) to cost(to, fromRoom, cell, cellIndex) } fun solve(input: Burrow): Long? { val seenStates = mutableMapOf<Burrow, Long>() val stack = ArrayDeque<Pair<List<Burrow>, Long>>() stack.add(listOf(input) to 0L) var best = input to Long.MAX_VALUE while (stack.isNotEmpty()) { val (burrows, cost) = stack.removeLast() val burrow = burrows.last() val seenCost = seenStates[burrow] if (seenCost != null && seenCost <= cost) { // prune this search path continue } seenStates[burrow] = cost if (cost > best.second) { // prune this search path continue } if (burrow.solved) { if (cost < best.second) { best = burrow to cost } continue } for (index in burrow.hallway.indices) { moveHtoR(burrow, index)?.let { (newBurrow, moveCost) -> stack.add(burrows + newBurrow to cost + moveCost) } } for (room in burrow.rooms.indices) { for (hallway in burrow.hallway.indices) { moveRtoH(burrow, room, hallway)?.let { (newBurrow, moveCost) -> stack.add(burrows + newBurrow to cost + moveCost) } } } } return best.second } override fun part1(input: Burrow): Long? { return solve(input.copy( rooms = input.rooms.map { Room(listOf(it.cells.first(), it.cells.last())) } )) } override fun part2(input: Burrow): Long? { return solve(input) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
6,358
aoc_kotlin
MIT License
src/Day03.kt
trosendo
572,903,458
false
{"Kotlin": 26100}
fun main() { fun getRepeatedInBothLists( list: Collection<Char>, middlePoint: Int ) = list.foldIndexed(emptySet<Char>() to emptySet<Char>()) { index, (firstHalf, repeated), currentChar -> if (index < middlePoint) firstHalf + currentChar to repeated else if (firstHalf.contains(currentChar)) firstHalf to repeated + currentChar else firstHalf to repeated } fun part1(input: List<String>) = input.sumOf { val result = getRepeatedInBothLists(it.toList(), it.length/2) val char = result.second.single() if (char.isLowerCase()) char.code - 96 else char.code - 38 } fun part2(input: List<String>) = input.chunked(3) { elves -> val firstSet = elves[0].toList() val secondSet = elves[1].toList() val thirdSet = elves[2].toList() val firstAndSecond = getRepeatedInBothLists(firstSet + secondSet, firstSet.size).second val char = getRepeatedInBothLists(firstAndSecond.toList() + thirdSet.toList(), firstAndSecond.size).second.single() if (char.isLowerCase()) char.code - 96 else char.code - 38 }.sum() // test if implementation meets criteria from the description, like: val testInput = readInputAsList("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) println(part2(testInput)) val input = readInputAsList("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ea66a6f6179dc131a73f884c10acf3eef8e66a43
1,455
AoC-2022
Apache License 2.0
src/day3/Solution.kt
chipnesh
572,700,723
false
{"Kotlin": 48016}
package day3 import readInput fun main() { fun part1(input: List<String>): Int { return input.sumOf { Rucksack(it).duplicates().priority ?: 0 } } fun part2(input: List<String>): Int { return input .chunked(3) .mapNotNull { group -> group .map(::Rucksack) .reduce(Rucksack::duplicates) .single() ?.priority }.sum() } val input = readInput("test") //val input = readInput("prod") println(part1(input)) println(part2(input)) } @JvmInline value class Item(private val value: Char) { val priority: Int? get() = priorities[value] companion object { val priorities = (('a'..'z') + ('A'..'Z')) .withIndex() .associate { it.value to it.index + 1 } } } @JvmInline value class Compartment(private val value: String) { fun duplicates(other: Compartment): Item { val otherSet = other.value.toSet() return value.first { it in otherSet }.let(::Item) } } @JvmInline value class Rucksack(private val value: String) { private val left get() = Compartment(value.substring(0 until value.length / 2)) private val right get() = Compartment(value.substring(value.length / 2, value.length)) fun duplicates() = left.duplicates(right) fun duplicates(other: Rucksack): Rucksack { val otherSet = other.value.toSet() return value .mapNotNullTo(mutableSetOf()) { item -> if (item in otherSet) item else null } .toCharArray() .concatToString() .let(::Rucksack) } fun single() = value .singleOrNull() ?.let(::Item) }
0
Kotlin
0
1
2d0482102ccc3f0d8ec8e191adffcfe7475874f5
1,766
AoC-2022
Apache License 2.0
src/day5/Day05.kt
francoisadam
573,453,961
false
{"Kotlin": 20236}
package day5 import readInput fun main() { fun part1(input: List<String>): String { val stacks = input.takeWhile { it.isNotBlank() } val crates = stacks.toCrateStacks() val instructions = input.drop(stacks.size + 1).map { it.toInstruction() } instructions.forEach { instruction -> crates.applyInstruction(instruction) } return crates.topValues() } fun part2(input: List<String>): String { val stacks = input.takeWhile { it.isNotBlank() } val crates = stacks.toCrateStacks() val instructions = input.drop(stacks.size + 1).map { it.toInstruction() } instructions.forEach { instruction -> crates.applyNewInstruction(instruction) } return crates.topValues() } // test if implementation meets criteria from the description, like: val testInput = readInput("day5/Day05_test") val testPart1 = part1(testInput) println("testPart1: $testPart1") val testPart2 = part2(testInput) println("testPart2: $testPart2") check(testPart1 == "CMZ") check(testPart2 == "MCD") val input = readInput("day5/Day05") println("part1 : ${part1(input)}") println("part2 : ${part2(input)}") } private fun List<String>.toCrateStacks(): List<MutableList<String>> { val indexRow = this.last() val numberOfStacks = indexRow.dropLast(1).last().digitToInt() val stacks = List<MutableList<String>>(numberOfStacks) { mutableListOf() } this.dropLast(1).forEach { row -> row.toCrateLine(indexRow).forEachIndexed { index, crate -> if (crate != " ") stacks[index].add(crate) } } return stacks } private fun String.toCrateLine(indexRow: String): List<String> = indexRow.mapIndexed { index, char -> if (char != " ".single()) { this[index].toString() } else { "-" } }.filter { it != "-" } private fun List<MutableList<String>>.moveCrate(fromIndex: Int, toIndex: Int) = this.apply { val crate = get(fromIndex).firstOrNull() ?: " " if (crate.isNotBlank()) { get(fromIndex).removeFirst() get(toIndex).add(0, crate) } } private fun List<MutableList<String>>.moveMultipleCrates(numberOfCrates:Int, fromIndex: Int, toIndex: Int) = this.apply { val crates = get(fromIndex).subList(0, numberOfCrates).toList() repeat(numberOfCrates) { get(fromIndex).removeFirst() } get(toIndex).addAll(0, crates) } private fun List<MutableList<String>>.topValues(): String = this.joinToString("") { it.firstOrNull() ?: "" } private data class Instruction( val repeat: Int, val fromIndex: Int, val toIndex: Int, ) private fun String.toInstruction() = this.drop(5) .replace(" from ", ",") .replace(" to ", ",") .split(",") .let { row -> Instruction( repeat = row.first().toInt(), fromIndex = row[1].toInt() - 1, toIndex = row.last().toInt() - 1, ) } private fun List<MutableList<String>>.applyInstruction(instruction: Instruction): List<MutableList<String>> = this.apply { repeat(instruction.repeat) { moveCrate(instruction.fromIndex, instruction.toIndex) } } private fun List<MutableList<String>>.applyNewInstruction(instruction: Instruction): List<MutableList<String>> = this.apply { moveMultipleCrates(instruction.repeat, instruction.fromIndex, instruction.toIndex) }
0
Kotlin
0
0
e400c2410db4a8343c056252e8c8a93ce19564e7
3,417
AdventOfCode2022
Apache License 2.0
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day23.kt
jntakpe
572,853,785
false
{"Kotlin": 72329, "Rust": 15876}
package com.github.jntakpe.aoc2022.days import com.github.jntakpe.aoc2022.shared.Day import com.github.jntakpe.aoc2022.shared.readInputLines import kotlin.math.abs object Day23 : Day { private val dirs = Direction.values().map { it.positions } override val input = parse(readInputLines(23)) override fun part1(): Int { var elves = input repeat(10) { elves = next(elves, it) } val width = abs(elves.maxOf { it.x } - elves.minOf { it.x }) + 1 val length = abs(elves.maxOf { it.y } - elves.minOf { it.y }) + 1 return width * length - elves.size } override fun part2(): Int { var elves = input repeat(Int.MAX_VALUE) { val next = next(elves, it) if (next == elves) { return it + 1 } elves = next } error("No matching result found") } private fun next(elves: Set<Position>, index: Int): Set<Position> { val next = elves .filter { elf -> elf.adjacent().any { it in elves } } .associateWith { nextPosition(index, it, elves) } return HashSet(elves).apply { next .filter { e -> next.none { e.value == it.value && e.key != it.key } } .forEach { remove(it.key) add(it.value) } } } private fun nextPosition(index: Int, elf: Position, elves: Set<Position>): Position { return dirs.indices .map { dirs[(index + it) % dirs.size] } .firstOrNull { dir -> dir.none { elf + it in elves } } ?.first() ?.plus(elf) ?: elf } private fun parse(input: List<String>): Set<Position> { return input .flatMapIndexed { y, l -> l.toCharArray() .withIndex() .filter { it.value == '#' } .map { Position(it.index, -y) } }.toSet() } enum class Direction(val positions: Set<Position>) { NORTH(setOf(Position(0, 1), Position(-1, 1), Position(1, 1))), SOUTH(setOf(Position(0, -1), Position(-1, -1), Position(1, -1))), WEST(setOf(Position(-1, 0), Position(-1, -1), Position(-1, 1))), EAST(setOf(Position(1, 0), Position(1, -1), Position(1, 1))), } data class Position(val x: Int = 0, val y: Int = 0) { operator fun plus(other: Position) = Position(x + other.x, y + other.y) operator fun minus(other: Position) = Position(x - other.x, y - other.y) operator fun times(times: Int) = Position(x * times, y * times) operator fun unaryMinus() = Position(-x, -y) fun adjacent(): List<Position> { return (-1..1) .flatMap { y -> (-1..1).map { Position(it, y) } } .filter { it != Position() } .map { it + this } } } }
1
Kotlin
0
0
63f48d4790f17104311b3873f321368934060e06
2,943
aoc2022
MIT License
src/main/kotlin/com/github/dangerground/aoc2020/Day13.kt
dangerground
317,439,198
false
null
package com.github.dangerground.aoc2020 import com.github.dangerground.aoc2020.util.DayInput fun main() { val process = Day13(DayInput.asStringList(13)) println("result part 1: ${process.part1()}") println("result part 2: ${process.part2()}") } class Day13(val input: List<String>) { val earliestDeparture = input[0].toInt() val busLines = input[1].split(",") .map { it.replace("x", "0") } .map { it.toLong() } init { println(busLines) } fun part1(): Long { //println(busLines.filter { it != 0 }.map { Pair(it, it - earliestDeparture % it) }) val lineDiff = busLines .filter { it != 0L } .map { Pair(it, it - earliestDeparture % it) } .minByOrNull { it.second }!! //println(lineDiff) return lineDiff.first * lineDiff.second } fun part2Linear(): Long { val all = busLines.mapIndexed { idx, it -> Pair(idx, it) } val test = all.filter { it.second != 0L } val diff = test.first().second val begin = System.currentTimeMillis() var i = diff * diff do { if (!test.map { // println("($i + ${it.first}) % ${it.second}") (i + it.first) % it.second == 0L }.contains(false)) { println((System.currentTimeMillis() - begin)) return i * diff } i += diff } while (true) return -1 } fun part2(): Long { var all = busLines.mapIndexed { idx, it -> Pair(idx, it) } val indices = all.map { it.first } var steps = all.map { it.second } var values = all.map { it.second } val testable = all.filter { it.second != 0L } val diff = testable.first().second val begin = System.currentTimeMillis() var i = 0L while (i < 15) { val max = values.maxOf { it } values = indices.map { if (values[it] == 0L) { return@map 0 } if (values[it] == max) { println("m $max") return@map max } val tmp = (values[it]) / steps[it] println("$tmp = $max / ${steps[it]} ((${values[it]}) / ${steps[it]})") return@map (tmp+1) * steps[it] } println("$max - $values") i = values.first() if (!indices.filter { values[it] != 0L }.map { println("(($i + ${it}) == ${values[it]}") (i + it) == values[it] }.contains(false)) { println((System.currentTimeMillis() - begin)) return i } } return -1 } }
0
Kotlin
0
0
c3667a2a8126d903d09176848b0e1d511d90fa79
2,828
adventofcode-2020
MIT License
src/main/kotlin/net/navatwo/adventofcode2023/day8/Day8Solution.kt
Nava2
726,034,626
false
{"Kotlin": 100705, "Python": 2640, "Shell": 28}
package net.navatwo.adventofcode2023.day8 import net.navatwo.adventofcode2023.framework.ComputedResult import net.navatwo.adventofcode2023.framework.Solution sealed class Day8Solution : Solution<Day8Solution.Input> { data object Part1 : Day8Solution() { override fun solve(input: Input): ComputedResult { val tree = Tree.create(input.nodes) val initialNodeName = NodeName("AAA") val result = computeDistanceToEnd(tree, initialNodeName, input) { it == NodeName("ZZZ") } return ComputedResult.Simple(result) } } protected fun computeDistanceToEnd( tree: Tree, initialNodeName: NodeName, input: Input, isEndNode: (NodeName) -> Boolean, ): Long { var currentNode = tree[initialNodeName] val directionsIterator = input.directionsIterator() var result = 0L while (!isEndNode(currentNode.name)) { currentNode = when (directionsIterator.next()) { Direction.Left -> currentNode.left Direction.Right -> currentNode.right } result += 1 } return result } data object Part2 : Day8Solution() { override fun solve(input: Input): ComputedResult { val tree = Tree.create(input.nodes) val currentNodes = tree.keys.asSequence() .filter { it.name.last() == 'A' } .map { tree[it] } .toList() val distanceToFirst = currentNodes.associateWith { node -> computeDistanceToEnd(tree, node.name, input) { it.name.last() == 'Z' } } /** * computes the greatest common divisor of a list of numbers */ fun gcd(a: Long, b: Long): Long { var x = a var y = b while (y > 0) { val temp = y y = x % y x = temp } return x } /** * Compute the least common multiple of two numbers */ fun lcm(a: Long, b: Long): Long { return a * b / gcd(a, b) } // Using the distance it takes to get to one, we know each one will always go to one end. // We can then figure out that cycles happen and push each one _eventually_ back to the end. This assumed // that the _first_ end node is the right one. // // This also assumes it cycles *from beginning* to the end node, such that the cycles traverse the entire space. val result = distanceToFirst.values.reduce(::lcm) return ComputedResult.Simple(result) } } data class Tree private constructor( private val nodes: Map<NodeName, Node>, ) { val keys = nodes.keys operator fun get(name: NodeName): Node = nodes.getValue(name) companion object { fun create(nodes: Map<NodeName, NodeData>): Tree { val tree = mutableMapOf<NodeName, Node>() fun getOrCreate(graph: MutableMap<NodeName, Node>, data: NodeData): Node { val existing = graph[data.name] if (existing != null) return existing val newNode = Node(data.name) graph[data.name] = newNode newNode.left = getOrCreate(graph, nodes.getValue(data.left)) newNode.right = getOrCreate(graph, nodes.getValue(data.right)) return newNode } for (node in nodes.values) { getOrCreate(tree, node) } return Tree(tree) } } } class Node( val name: NodeName, ) { lateinit var left: Node lateinit var right: Node override fun toString(): String { return "${name.name} = (${left.name.name}, ${right.name.name})" } override fun equals(other: Any?): Boolean { return this === other || (other is Node && name == other.name) } override fun hashCode(): Int { return name.hashCode() } companion object { private val nil = Node(NodeName("NIL")).apply { left = this right = this } fun leaf(name: NodeName) = Node(name).apply { left = nil right = nil } } } override fun parse(lines: Sequence<String>): Input { var directions: Directions? = null val nodes = mutableListOf<NodeData>() for (line in lines.filter { it.isNotBlank() }) { if (directions == null) { val directionList = line.map { char -> when (char) { 'L' -> Direction.Left 'R' -> Direction.Right else -> throw IllegalArgumentException("Invalid direction: $char") } } directions = Directions(directionList) } else { val name = NodeName(line.substring(0..2)) val leftFirstIndex = "AAA = (".length val left = NodeName(line.substring(leftFirstIndex, leftFirstIndex + 3)) val rightFirstIndex = line.length - "CCC)".length val right = NodeName(line.substring(rightFirstIndex, rightFirstIndex + 3)) nodes += NodeData(name, left, right) } } return Input(directions!!, nodes.associateBy { it.name }) } data class Input( val directions: Directions, val nodes: Map<NodeName, NodeData>, ) { fun directionsIterator(): Iterator<Direction> = iterator { while (true) { yieldAll(directions.directions) } } } @JvmInline value class Directions(val directions: List<Direction>) @JvmInline value class NodeName(val name: String) { init { require(name.length == 3) } } data class NodeData(val name: NodeName, val left: NodeName, val right: NodeName) { fun isLeaf() = name == left && name == right } enum class Direction { Left, Right, } }
0
Kotlin
0
0
4b45e663120ad7beabdd1a0f304023cc0b236255
5,550
advent-of-code-2023
MIT License
src/Day05.kt
purdyk
572,817,231
false
{"Kotlin": 19066}
data class Command(val move: Int, val from: Int, val to: Int) fun main() { fun makeStacks(input: List<String>): MutableList<MutableList<Char>> { val mid = input.indexOfFirst { it.isEmpty() } val crates = input.take(mid - 1).reversed().map { it.chunked(4).map { it.find { it.isUpperCase() } }} val stacks = MutableList(crates[0].size) { mutableListOf<Char>() } crates.forEach { row -> row.forEachIndexed { index, c -> c?.also { stacks[index].add(it) } } } return stacks } fun makeCommands(input: List<String>): List<Command> { val mid = input.indexOfFirst { it.isEmpty() } val ints = input.drop(mid+1).map { it.split(" ").mapNotNull { it.toIntOrNull() } } return ints.map { Command(it[0], it[1]-1 , it[2]-1 ) } } fun execute9000(command: Command, stacks: MutableList<MutableList<Char>>) { repeat(command.move) { stacks[command.to].add(stacks[command.from].removeLast()) } } fun part1(input: List<String>): String { val stacks = makeStacks(input) makeCommands(input).forEach { execute9000(it, stacks) } return stacks.map { it.last() }.joinToString("") } fun execute9001(command: Command, stacks: MutableList<MutableList<Char>>) { val temp = mutableListOf<Char>() repeat(command.move) { temp.add(stacks[command.from].removeLast()) } stacks[command.to].addAll(temp.reversed()) } fun part2(input: List<String>): String { val stacks = makeStacks(input) makeCommands(input).forEach { execute9001(it, stacks) } return stacks.map { it.last() }.joinToString("") } val day = "05" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test").split("\n") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") println("Test: ") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day${day}").split("\n") println("\nProblem: ") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
02ac9118326b1deec7dcfbcc59db8c268d9df096
2,230
aoc2022
Apache License 2.0
src/Day13.kt
acrab
573,191,416
false
{"Kotlin": 52968}
import com.google.common.truth.Truth.assertThat import kotlinx.serialization.json.* enum class ItemOrdering { Correct, Incorrect, Undecided } fun main() { fun compareIntegers(left: Int, right: Int): ItemOrdering = when { left == right -> ItemOrdering.Undecided left < right -> ItemOrdering.Correct else -> ItemOrdering.Incorrect } fun compareJsonArrays(left: List<JsonElement>, right: List<JsonElement>): ItemOrdering { val comparison = left.zip(right) { l, r -> if (l is JsonPrimitive && r is JsonPrimitive) { compareIntegers(l.int, r.int) } else if (l is JsonArray && r is JsonArray) { compareJsonArrays(l, r) } else { //exactly one is an array, the other is a number if (l is JsonPrimitive) { compareJsonArrays(listOf(l), r.jsonArray) } else { compareJsonArrays(l.jsonArray, listOf(r)) } } } return if (comparison.all { it == ItemOrdering.Undecided }) { when { left.size == right.size -> ItemOrdering.Undecided left.size < right.size -> ItemOrdering.Correct else -> ItemOrdering.Incorrect } } else { comparison.first { it != ItemOrdering.Undecided } } } fun part1(input: List<String>): Int = //3 to consume blank lines between groups input.chunked(3) .mapIndexed { index, strings -> val left = Json.parseToJsonElement(strings[0]).jsonArray val right = Json.parseToJsonElement(strings[1]).jsonArray if (compareJsonArrays(left, right) == ItemOrdering.Correct) { index + 1 } else { 0 } }.sum() fun part2(input: List<String>): Int { val inputWithDividers = input + "[[2]]" + "[[6]]" println("Starting list\n${inputWithDividers.joinToString(separator = "\n")}\n-----") val filteredList = inputWithDividers.filterNot { it.isEmpty() } println("Filtered list\n${filteredList.joinToString(separator = "\n")}\n-----") val sortedList = filteredList.sortedWith { l, r -> val left = Json.parseToJsonElement(l).jsonArray val right = Json.parseToJsonElement(r).jsonArray when (compareJsonArrays(left, right)) { ItemOrdering.Correct -> -1 ItemOrdering.Incorrect -> 1 ItemOrdering.Undecided -> 0 } } println("Sorted list:\n${sortedList.joinToString(separator = "\n")}") val start = sortedList.indexOf("[[2]]")+1 val end = sortedList.indexOf("[[6]]")+1 return start * end } val testInput = readInput("Day13_test") assertThat(part1(testInput)).isEqualTo(13) val input = readInput("Day13") println(part1(input)) assertThat(part2(testInput)).isEqualTo(140) println(part2(input)) }
0
Kotlin
0
0
0be1409ceea72963f596e702327c5a875aca305c
3,121
aoc-2022
Apache License 2.0
src/main/kotlin/Day4.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List import kotlin.math.pow object Day4 { data class CardData(val cardIndex: Int, val winningNumberCount: Int) { companion object { fun parseCardData(input: String): CardData { val (cardInformation, numberInformation) = input.split(":") val cardIndex = cardInformation.trimStart(*"Card ".toCharArray()).toInt() val (winningNumberInformation, cardNumberInformation) = numberInformation.split("|") val winningNumbers = parseNumbers(winningNumberInformation) val cardNumbers = parseNumbers(cardNumberInformation) val winningNumberCount = cardNumbers.filter { winningNumbers.contains(it) }.count() return CardData(cardIndex, winningNumberCount) } private fun parseNumbers(numbers: String): List<Int> { return numbers.trimStart(*" ".toCharArray()) .trimEnd(*" ".toCharArray()) .split(" ") .filter(String::isNotEmpty) .map { it.toInt() } } } fun score(): Int { val exp = winningNumberCount - 1 return 2.0.pow(exp.toDouble()).toInt() } fun cardIndexesToCopy(): IntRange { return (cardIndex + 1..cardIndex + winningNumberCount) } } fun part1(input: List<String>): String = input.map(CardData::parseCardData).map(CardData::score).sum().toString() fun part2(input: List<String>): String = findTotalCards(input.map(CardData::parseCardData)).toString() private fun findTotalCards(cards: List<CardData>): Int { val cardMultiplierCount = mutableMapOf<Int, Int>() return cards.map { val multiplier = (cardMultiplierCount[it.cardIndex] ?: 0) + 1 it.cardIndexesToCopy().forEach { cardMultiplierCount.merge(it, multiplier) { a, b -> a + b } } multiplier }.sum() } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
2,054
kotlin-kringle
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2022/d20/Day20.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2022.d20 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines const val KEY = 811589153 data class Node(val num: Int, var prev: Node?, var next: Node?) { override fun toString() = "Node(num=$num, prev=${prev?.num}, next=${next?.num})" } // creates a new circular doubly linked list of the given values and returns an // array to allow random access to nodes of the linked list, given the original index // in the `sums` list fun toIndexedLinkedList(nums: List<Int>): Array<Node> { val ret = mutableListOf<Node>() var prev: Node? = null nums.forEach { num -> val node = Node(num, prev, null) ret.add(node) prev?.let { it.next = node } prev = node } val firstNode = ret.first() val lastNode = ret.last() firstNode.prev = lastNode lastNode.next = firstNode return Array(nums.size) { ret[it] } } fun toList(linkedList: Array<Node>, zeroIdx: Int): List<Int> = mutableListOf<Int>().apply { add(0) var node = linkedList[zeroIdx].next!! while (node.num != 0) { add(node.num) node = node.next!! } } fun mix(nums: List<Int>, times: Int, key: Int): List<Int> { val linkedList = toIndexedLinkedList(nums) var zeroIdx: Int? = null repeat(times) { linkedList.forEachIndexed { i, node -> if (node.num == 0) zeroIdx = i var delta = (node.num.toLong() * key).mod(nums.size - 1) val forward = delta < nums.size / 2 - 1 delta = if (forward) delta else nums.size - 1 - delta // remove node at its old position node.prev!!.next = node.next node.next!!.prev = node.prev // traverse to new position var newPrev = node.prev!! repeat(delta) { newPrev = if (forward) newPrev.next!! else newPrev.prev!! } // insert node node.prev = newPrev node.next = newPrev.next node.prev!!.next = node node.next!!.prev = node } } return toList(linkedList, zeroIdx!!) } fun main() = timed { val nums = (DATAPATH / "2022/day20.txt") .useLines { it.toList() } .map { it.toInt() } val mixed = mix(nums, 1, 1) // zero is at index 0 of this new list (1000..3000 step 1000).sumOf { mixed[it % mixed.size] }.also { println("Part one: $it") } val mixed2 = mix(nums, 10, KEY) (1000..3000 step 1000).sumOf { mixed2[it % mixed2.size].toLong() * KEY }.also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,685
advent-of-code
MIT License
src/main/kotlin/tr/emreone/kotlin_utils/math/Math.kt
EmRe-One
442,916,831
false
{"Kotlin": 173543}
package tr.emreone.kotlin_utils.math import tr.emreone.kotlin_utils.extensions.safeTimes import kotlin.math.absoluteValue import kotlin.math.pow /** * Euclid's algorithm for finding the greatest common divisor of a and b. */ fun gcd(a: Int, b: Int): Int = if (b == 0) a.absoluteValue else gcd(b, a % b) fun gcd(f: Int, vararg n: Int): Int = n.fold(f, ::gcd) fun Iterable<Int>.gcd(): Int = reduce(::gcd) /** * Euclid's algorithm for finding the greatest common divisor of a and b. */ fun gcd(a: Long, b: Long): Long = if (b == 0L) a.absoluteValue else gcd(b, a % b) fun gcd(f: Long, vararg n: Long): Long = n.fold(f, ::gcd) fun Iterable<Long>.gcd(): Long = reduce(::gcd) /** * Find the least common multiple of a and b using the gcd of a and b. */ fun lcm(a: Int, b: Int) = (a safeTimes b) / gcd(a, b) fun lcm(f: Int, vararg n: Int): Long = n.map { it.toLong() }.fold(f.toLong(), ::lcm) @JvmName("lcmForInt") fun Iterable<Int>.lcm(): Long = map { it.toLong() }.reduce(::lcm) /** * Find the least common multiple of a and b using the gcd of a and b. */ fun lcm(a: Long, b: Long) = (a safeTimes b) / gcd(a, b) fun lcm(f: Long, vararg n: Long): Long = n.fold(f, ::lcm) fun Iterable<Long>.lcm(): Long = reduce(::lcm) /** * Takes a list of base/modulo combinations and returns the lowest number for which the states coincide such that: * * for all i: state(i) == base_state(i). * * E.g. chineseRemainder((3,4), (5,6), (2,5)) == 47 */ fun chineseRemainder(values: List<Pair<Long, Long>>): Pair<Long, Long>? { if (values.isEmpty()) { return null } var (result, lcm) = values[0] outer@ for (i in 1 until values.size) { val (base, modulo) = values[i] val target = base % modulo for (j in 0L until modulo) { if (result % modulo == target) { lcm = lcm(lcm, modulo) continue@outer } result += lcm } return null } return result to lcm } /** * Simple algorithm to find the primes of the given Int. */ fun Int.primes(): Sequence<Int> = sequence { var n = this@primes var j = 2 while (j * j <= n) { while (n % j == 0) { yield(j) n /= j } j++ } if (n > 1) yield(n) } /** * Simple algorithm to find the primes of the given Long. */ fun Long.primes(): Sequence<Long> = sequence { var n = this@primes var j = 2L while (j * j <= n) { while (n % j == 0L) { yield(j) n /= j } j++ } if (n > 1) yield(n) } infix fun Number.pow(power: Number): Double = this.toDouble().pow(power.toDouble()) infix fun Int.pow(power: Int): Int = this.toDouble().pow(power.toDouble()).toInt()
0
Kotlin
0
0
aee38364ca1827666949557acb15ae3ea21881a1
2,776
kotlin-utils
Apache License 2.0
src/Day07.kt
jordanfarrer
573,120,618
false
{"Kotlin": 20954}
fun main() { val day = "Day07" fun parseCommands(input: List<String>): FsDirectory { val fs = FsDirectory(null, "", "", mutableListOf(), mutableListOf()) var currentDir = fs input.forEach { command -> val parts = command.split(" ") if (parts.size < 2) error("Not valid line") if (parts[0] == "$") { if (parts[1] == "ls") { // no-op } else if (parts[1] == "cd") { if (parts[2] == "/") { // no-op } else if (parts[2] == "..") { currentDir = currentDir.parent ?: error("Can't change dir up, no parent directory") } else { currentDir = currentDir.dirs.find { it.name == parts[2] } ?: error("Can't find directory ${parts[2]} in ${currentDir.dirs}") } } else { error("Unknown command: ${parts[1]}") } } else { // result if (parts[0] == "dir") { // directory val name = parts[1] currentDir.addDirectory(name, mutableListOf(), mutableListOf()) } else { val size = parts[0].toInt() val name = parts[1] currentDir.addFile(name, size) } } } return fs } fun part1(input: List<String>): Int { val dir = parseCommands(input) // displayFsDir(dir) return dir.filterChildDirs { it.getSize() <= 100000 }.sumOf { it.getSize() } } fun part2(input: List<String>): Int { val dir = parseCommands(input) val diskSpace = 70000000 val requiredDiskSpace = 30000000 val unusedSpace = diskSpace - dir.getSize() val allSubDirs = dir.getAllSubDirs().sortedBy { it.getSize() } val targetDir = allSubDirs.find { (it.getSize() + unusedSpace) > requiredDiskSpace } ?: error("Can't find dir with appropriate space") return targetDir.getSize() } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val part1Result = part1(testInput) println("Part 1 (test): $part1Result") check(part1Result == 95437) val part2Result = part2(testInput) println("Part 2 (test): $part2Result") // check(part2Result == 45000) val input = readInput(day) println(part1(input)) println(part2(input)) } // FILES data class FsFile(val parent: FsDirectory, val name: String, val size: Int) // DIRS data class FsDirectory( val parent: FsDirectory?, val containingPath: String, val name: String, val files: MutableList<FsFile>, val dirs: MutableList<FsDirectory> ) { override fun toString(): String { return "${getFullPath()} (dir), ${dirs.size} dirs, ${files.size} files" } } fun FsDirectory.getFullPath() = "${this.containingPath}/${this.name}" fun FsDirectory.addFile(name: String, size: Int) { this.files.add(FsFile(this, name, size)) } fun FsDirectory.getAllSubDirs(): List<FsDirectory> { return this.dirs + this.dirs.flatMap { it.getAllSubDirs() } } fun FsDirectory.filterChildDirs(predicate: (FsDirectory) -> Boolean): List<FsDirectory> { val allSubDirs = this.getAllSubDirs() return allSubDirs.filter(predicate) } fun FsDirectory.addDirectory( name: String, files: MutableList<FsFile>, dirs: MutableList<FsDirectory> ) { this.dirs.add(FsDirectory(this, this.getFullPath(), name, files, dirs)) } fun FsDirectory.getSize(): Int { return this.files.sumOf { it.size } + this.dirs.sumOf { it.getSize() } }
0
Kotlin
0
1
aea4bb23029f3b48c94aa742958727d71c3532ac
3,816
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/TreeOfCoprimes.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1766. Tree of Coprimes * @see <a href="https://leetcode.com/problems/tree-of-coprimes/">Source</a> */ fun interface TreeOfCoprimes { operator fun invoke(nums: IntArray, edges: Array<IntArray>): IntArray } class TreeOfCoprimesDFS : TreeOfCoprimes { lateinit var ans: IntArray override fun invoke(nums: IntArray, edges: Array<IntArray>): IntArray { val path: Array<MutableList<Pair>> = Array(LIMIT) { ArrayList() } for (i in 0 until LIMIT) path[i] = ArrayList() val n = nums.size ans = IntArray(n) val graph: Array<MutableList<Int>> = Array(n) { ArrayList() } for (i in 0 until n) graph[i] = ArrayList() for (edge in edges) { graph[edge[0]].add(edge[1]) graph[edge[1]].add(edge[0]) } solve(graph, path, nums, 0, -1, 0) return ans } fun solve( graph: Array<MutableList<Int>>, path: Array<MutableList<Pair>>, nums: IntArray, src: Int, pre: Int, curDepth: Int, ) { // pre-order traversal var closestIdx = -1 var maxDepth = -1 for (i in 1 until LIMIT) { if (gcd(nums[src], i) == 1 && path[i].isNotEmpty() && path[i][path[i].size - 1].depth > maxDepth) { closestIdx = path[i][path[i].size - 1].idx maxDepth = path[i][path[i].size - 1].depth } } ans[src] = closestIdx path[nums[src]].add(Pair(src, curDepth)) // add node to the path for (nei in graph[src]) { if (nei == pre) continue solve(graph, path, nums, nei, src, curDepth + 1) } path[nums[src]].removeAt(path[nums[src]].size - 1) // remove node from the path } private fun gcd(a: Int, b: Int): Int { return if (b == 0) a else gcd(b, a % b) } class Pair(var idx: Int, var depth: Int) companion object { private const val LIMIT = 51 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,617
kotlab
Apache License 2.0
src/Day20.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
fun main() { val testInput = readInput("Day20_test") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Long = solve(input, String::toLong, mixesCount = 1) private fun part2(input: List<String>): Long = solve(input, String::part2Converter, mixesCount = 10) private fun String.part2Converter(): Long = this.toLong() * 811589153L private fun solve(input: List<String>, converter: String.() -> Long, mixesCount: Int): Long { val nodes = input.map { LinkedNode(it.converter()) } var zeroIndex = -1 for (i in nodes.indices) { nodes[i].next = if (i < nodes.lastIndex) nodes[i + 1] else nodes.first() nodes[i].prev = if (i > 0) nodes[i - 1] else nodes.last() if (nodes[i].value == 0L) { zeroIndex = i } } repeat(mixesCount) { nodes.forEach { node -> val count = correctMovesCount(node.value, nodes.size) if (count > 0) { var target = node repeat(count) { target = target.next } //delete node from chain node.prev.next = node.next node.next.prev = node.prev //insert node to the new position node.next = target.next target.next.prev = node target.next = node node.prev = target } } } var node = nodes[zeroIndex] var result = 0L repeat(3_001) { if (it == 1_000 || it == 2_000 || it == 3_000) { result += node.value } node = node.next } return result } private fun correctMovesCount(count: Long, size: Int): Int { return if (count > 0) { //reduce the full cycles (count % (size - 1)).toInt() } else { //(size + (count % (size - 1)) - 1) - this converts negative steps to positive steps // % (size - 1) - this reduce the full cycles when the steps count is more than the items in the chain ((size + (count % (size - 1)) - 1) % (size - 1)).toInt() } } private class LinkedNode(val value: Long) { lateinit var next: LinkedNode lateinit var prev: LinkedNode }
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
2,351
AOC2022
Apache License 2.0
src/day03/Day03.kt
AbolfaZlRezaEe
574,383,383
false
null
package day03 import readInput fun main() { fun alphabetLowercaseCodeList(): HashMap<Char, Int> { return hashMapOf<Char, Int>().apply { put('a', 1) put('b', 2) put('c', 3) put('d', 4) put('e', 5) put('f', 6) put('g', 7) put('h', 8) put('i', 9) put('j', 10) put('k', 11) put('l', 12) put('m', 13) put('n', 14) put('o', 15) put('p', 16) put('q', 17) put('r', 18) put('s', 19) put('t', 20) put('u', 21) put('v', 22) put('w', 23) put('x', 24) put('y', 25) put('z', 26) } } fun alphabetUppercaseCodeList(): HashMap<Char, Int> { return hashMapOf<Char, Int>().apply { alphabetLowercaseCodeList().forEach { (char, code) -> put(char.uppercaseChar(), 26 + code) } } } fun part01(lines: List<String>): Int { val lowerCode = alphabetLowercaseCodeList() val upperCode = alphabetUppercaseCodeList() var result = 0 lines.forEach { line -> val compartmentItems = line.chunked(line.length / 2) val firstCompartment = compartmentItems[0].toCharArray().asIterable().toSet() val secondCompartment = compartmentItems[1].toCharArray().asIterable().toSet() val sharedChar = firstCompartment.intersect(secondCompartment).toList()[0] // Because we only have 1 letter shared! result += if (sharedChar.isUpperCase()) upperCode[sharedChar]!! else lowerCode[sharedChar]!! } return result } fun part02(lines: List<String>): Int { val lowerCode = alphabetLowercaseCodeList() val upperCode = alphabetUppercaseCodeList() val groups = mutableListOf<MutableList<String>>() var group = mutableListOf<String>() var result = 0 lines.forEach { line -> // Creating groups with member size of 3 group.add(line) if (group.size == 3) { groups.add(group) group = mutableListOf() } } groups.forEach { group -> // Check shared char between three member val allCharacters = mutableListOf<Char>() val hashTable = HashMap<Char, Int>() allCharacters.addAll(group[0].toCharArray().toList().toSet()) allCharacters.addAll(group[1].toCharArray().toList().toSet()) allCharacters.addAll(group[2].toCharArray().toList().toSet()) allCharacters.forEach { character -> val frequency = hashTable[character] if (frequency != null) { hashTable[character] = frequency + 1 } else { hashTable[character] = 1 } } val sharedChar = hashTable.filter { it.value == 3 }.keys.toList()[0] result += if (sharedChar.isUpperCase()) upperCode[sharedChar]!! else lowerCode[sharedChar]!! } return result } check(part01(readInput(targetDirectory = "day03", name = "Day03FakeData")) == 157) check(part02(readInput(targetDirectory = "day03", name = "Day03FakeData")) == 70) val part01Answer = part01(readInput(targetDirectory = "day03", name = "Day03RealData")) val part02Answer = part02(readInput(targetDirectory = "day03", name = "Day03RealData")) println("Sum of priorities in part01 is-> $part01Answer") println("Sum of priorities in part02 is-> $part02Answer") }
0
Kotlin
0
0
798ff23eaa9f4baf25593368b62c2f671dc2a010
3,720
AOC-With-Me
Apache License 2.0
src/main/kotlin/Day07.kt
joostbaas
573,096,671
false
{"Kotlin": 45397}
sealed interface FileSystem { val name: String val size: Int get() = when (this) { is Directory -> children.sumOf { it.size } is File -> fileSize } } data class File( override val name: String, val fileSize: Int, ) : FileSystem data class Directory( override val name: String, val children: MutableList<FileSystem>, ) : FileSystem fun Directory.allDirectories(): List<Directory> = this.children.filterIsInstance<Directory>().flatMap { it.allDirectories() } + this fun List<String>.parseFilesystem(): Directory { val rootDirectory = Directory("/", mutableListOf()) val currentDirectory = ArrayDeque<Directory>().apply { add(rootDirectory) } val dirRegex = Regex("""dir ([a-z.]+)""") val fileRegex = Regex("""([0-9]+) ([a-z.]+)""") val cdRegex = Regex("""\$ cd ([a-z]+)""") for (line in this.drop(1)) { with(line) { when { matches(dirRegex) -> dirRegex.find(this)!!.destructured .let { (name) -> currentDirectory.last().children.add(Directory(name, mutableListOf())) } matches(fileRegex) -> fileRegex.find(this)!!.destructured .let { (size, name) -> currentDirectory.last().children.add(File(name, size.toInt())) } equals("$ cd ..") -> currentDirectory.removeLast() matches(cdRegex) -> cdRegex.find(this)!!.destructured .let { (name) -> currentDirectory.addLast( currentDirectory.last().children .filterIsInstance<Directory>() .first { it.name == name }) } else -> { /*doNothing*/ } } } } return rootDirectory } fun day07Part1(input: List<String>): Int = input.parseFilesystem().allDirectories() .filter { it.size < 100_000 } .sumOf { it.size } fun day07Part2(input: List<String>): Int { val root = input.parseFilesystem() val diskSize = 70_000_000 val spaceNeeded = 30_000_000 val spaceAvailable = diskSize - root.size val extraSpaceNeeded = spaceNeeded - spaceAvailable return root.allDirectories().filter { it.size >= extraSpaceNeeded }.minOf { it.size } }
0
Kotlin
0
0
8d4e3c87f6f2e34002b6dbc89c377f5a0860f571
2,439
advent-of-code-2022
Apache License 2.0
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day15.kt
justinhorton
573,614,839
false
{"Kotlin": 39759, "Shell": 611}
package xyz.justinhorton.aoc2022 import kotlin.math.abs /** * https://adventofcode.com/2022/day/15 */ class Day15(override val input: String) : Day() { override fun part1(): String { val fixedy = if (input.startsWith(SAMPLE_START)) 10 else 2_000_000 val sd = parseSensorData() val lowx = sd.minBy { it.closestBeacon.x }.let { it.closestBeacon.x - it.manhattan } val highx = sd.maxBy { it.closestBeacon.x }.let { it.closestBeacon.x + it.manhattan } return (lowx..highx).count { x -> sd.any { val point = GPoint(x, fixedy) point != it.closestBeacon && it.isInManhattanTrapezoid(point) } }.toString() } override fun part2(): String { val upperBound = if (input.startsWith(SAMPLE_START)) 20 else 4_000_000 val sd = parseSensorData() val beaconPos = sd.asSequence() .flatMap { it.trapBorder() } .filter { (x, y) -> x in 0..upperBound && y in 0..upperBound } .first { borderPos -> sd.none { it.isInManhattanTrapezoid(borderPos) } } return (beaconPos.x * TUNING_MULTIPLIER + beaconPos.y).toString() } private fun parseSensorData() = input.trim().lines() .map { line -> val coords = line.split(',', ':', '=') .mapNotNull { it.toIntOrNull() } .zipWithNext() SensorData(GPoint(coords.first()), GPoint(coords.last())) } } private data class SensorData(val pos: GPoint, val closestBeacon: GPoint) { val manhattan = manhattanDistance(pos, closestBeacon) fun trapBorder(): Sequence<GPoint> { val manPlusOne = manhattan + 1 return sequence { yield(GPoint(pos.x, pos.y + manPlusOne)) yield(GPoint(pos.x, pos.y - manPlusOne)) var xoff = 1 for (y in (pos.y - manPlusOne + 1)..(pos.y + manPlusOne - 1)) { yield(GPoint(pos.x + xoff, y)) yield(GPoint(pos.x - xoff, y)) if (y > pos.y) { xoff++ } else { xoff-- } } } } fun isInManhattanTrapezoid(other: GPoint): Boolean = manhattanDistance(pos, other) <= manhattan } private const val SAMPLE_START = "Sensor at x=2" private const val TUNING_MULTIPLIER = 4_000_000L private fun manhattanDistance(p1: GPoint, p2: GPoint): Int = abs(p1.x - p2.x) + abs(p1.y - p2.y)
0
Kotlin
0
1
bf5dd4b7df78d7357291c7ed8b90d1721de89e59
2,491
adventofcode2022
MIT License
src/Day08.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
fun main() { fun isVisible(input: List<String>, element: Char, x: Int, y: Int): Boolean { if ((0 until x).all { element.digitToInt() > input[y][it].digitToInt() }) return true if ((x + 1..input[y].lastIndex).all { element.digitToInt() > input[y][it].digitToInt() }) return true if ((0 until y).all { element.digitToInt() > input[it][x].digitToInt() }) return true if ((y + 1..input.lastIndex).all { element.digitToInt() > input[it][x].digitToInt() }) return true return false } fun getView(input: List<String>, element: Char, x: Int, y: Int): Int { var result = 1 var counter = 0 for (i in x - 1 downTo 0) { counter++ if (element.digitToInt() <= input[i][x].digitToInt()) break } result *= counter counter = 0 for (i in x + 1..input[y].lastIndex) { counter++ if (element.digitToInt() <= input[i][x].digitToInt()) break } result *= counter counter = 0 for (i in y - 1 downTo 0) { counter++ if (element.digitToInt() <= input[i][x].digitToInt()) break } result *= counter counter = 0 for (i in y + 1..input.lastIndex) { counter++ if (element.digitToInt() <= input[i][x].digitToInt()) break } result *= counter return result } fun part1(input: List<String>): Int { return input.mapIndexed { index, line -> line.filterIndexed { cIndex, c -> index == 0 || index == input.lastIndex || cIndex == 0 || cIndex == line.lastIndex || isVisible( input, c, cIndex, index ) } }.sumOf { it.length } } fun part2(input: List<String>): Int { return input.mapIndexed { index, line -> line.mapIndexed { cIndex, c -> if (index == 0 || index == input.lastIndex || cIndex == 0 || cIndex == line.lastIndex) 0 else getView(input, c, cIndex, index) } }.flatten().max() } val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
2,277
Advent-of-code
Apache License 2.0
src/main/kotlin/Puzzle16.kt
namyxc
317,466,668
false
null
import java.math.BigInteger object Puzzle16 { @JvmStatic fun main(args: Array<String>) { val input = Puzzle16::class.java.getResource("puzzle16.txt").readText() val ticketInfo = TicketInfo(input) println(ticketInfo.sumInvalidNumbers()) println(ticketInfo.getProdOfDepartmentFields()) } class TicketInfo(input: String) { private val rules: Rules private val myTicket: List<Int> private val otherTickets : List<List<Int>> init { val parts = input.split("\n\n") rules = Rules(parts.first().split("\n")) myTicket = parts[1].split("\n")[1].split(",").map(String::toInt) val ticketLines = parts.last().split("\n").drop(1) otherTickets = mutableListOf<List<Int>>() ticketLines.forEach { line -> otherTickets.add(line.split(",").map(String::toInt)) } } fun sumInvalidNumbers(): Int{ val invalidFields = rules.getInvalidData(otherTickets) return invalidFields.sum() } fun getProdOfDepartmentFields(): BigInteger{ val validTickets = rules.getValidTickets(otherTickets) rules.findRuleFields(validTickets) return rules.getValuesForFields(myTicket, "departure").fold(BigInteger.ONE) { prod, element -> prod * element.toBigInteger() } } } private class Rules(lines: List<String>) { fun getValidTickets(ticketData: List<List<Int>>): List<List<Int>> { return ticketData.filterNot { ticket -> ticket.any { i -> inValid(i) } } } fun findRuleFields(ticketData: List<List<Int>>){ val maxIndex = ticketData.first().lastIndex for (rule in rules) { for (fieldNumber in 0..maxIndex) { if (ticketData.none { ticket -> rule.inValid(ticket[fieldNumber]) }){ rule.fieldNumbers.add(fieldNumber) } } } while (rules.any { rule -> rule.fieldNumbers.size > 1 }){ rules.filter { rule -> rule.fieldNumbers.size == 1 }.forEach { onlyRule -> val fieldNumberToRemove = onlyRule.fieldNumbers.first() rules.filter { rule -> rule.fieldNumbers.size > 1 && rule.fieldNumbers.contains(fieldNumberToRemove) }.forEach { removeSameFieldRule -> removeSameFieldRule.fieldNumbers.remove(fieldNumberToRemove) } } } } fun getInvalidData(ticketData: List<List<Int>>): List<Int> { val invalidData = mutableListOf<Int>() ticketData.forEach { ticket -> ticket.forEach { value -> if (inValid(value)){ invalidData.add(value) } } } return invalidData } private fun inValid(value: Int): Boolean { return rules.all { rule -> rule.inValid(value) } } fun getValuesForFields(myTicket: List<Int>, fieldStartsWith: String): List<Int> { return rules.filter { rule -> rule.name.startsWith(fieldStartsWith) }.map { rule -> myTicket[rule.fieldNumbers.first()] } } private data class Rule(val name: String, val ranges: List<Pair<Int, Int>>, var fieldNumbers: MutableList<Int>) { fun inValid(value: Int): Boolean { return ranges.all { range -> value < range.first || value > range.second } } } private val rules: MutableList<Rule> = mutableListOf() init { lines.forEach { line -> val nameAndRules = line.split(": ") val name = nameAndRules.first() val rulesString = nameAndRules.last().split(" or ") val rulesArray = rulesString.map { it -> Pair(it.split("-").first().toInt(), it.split("-").last().toInt()) } rules.add(Rule(name, rulesArray, mutableListOf())) } } } }
0
Kotlin
0
0
60fa6991ac204de6a756456406e1f87c3784f0af
4,123
adventOfCode2020
MIT License
src/Day07.kt
george-theocharis
573,013,076
false
{"Kotlin": 10656}
fun main() { val root = Node("/", null) val nodes = mutableListOf<Node>() var currentNode = root fun part1(input: List<String>): Long { input.forEach { command -> when { command == "$ cd /" -> currentNode = root command == "$ cd .." -> currentNode = currentNode.parent!! command.startsWith("$ cd") -> { currentNode = currentNode.children.first { it.name == command.split(" ").last() } } command.startsWith("dir") -> Node(name = command.split(" ").last(), parent = currentNode) .apply { currentNode.children += this nodes += this } command.startsWith("$ ls") -> Unit else -> currentNode.size += command.split(" ").first().toLong() } } return nodes.filter { it.totalSize <= 100000L }.sumOf { it.totalSize } } fun part2(): Long { val spaceNeeded = 30000000 - (70000000 - root.totalSize) return nodes.filter { it.totalSize >= spaceNeeded }.minOf { it.totalSize } } val input = readInput("Day07") println(part1(input)) println(part2()) } class Node( val name: String, val parent: Node?, var children: List<Node> = emptyList() ) { var size: Long = 0L val totalSize: Long get() = size + children.sumOf { it.totalSize } }
0
Kotlin
0
0
7971bea39439b363f230a44e252c7b9f05a9b764
1,475
aoc-2022
Apache License 2.0
src/y2023/Day21.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.Pos import util.neighborsManhattan import util.readInput import util.timingStatistics object Day21 { private fun parse(input: List<String>): Pair<Set<Pair<Int, Int>>, Pair<Int, Int>> { var start = 0 to 0 return input.flatMapIndexed { row, line -> line.mapIndexedNotNull { col, char -> if (char == 'S') { start = row to col } if (char in ".S") { row to col } else { null } } }.toSet() to start } fun part1(input: List<String>, steps: Int): Int { val (positions, start) = parse(input) var frontier = setOf(start) repeat(steps) { frontier = frontier.flatMap { pos -> pos.neighborsManhattan() }.filter { it in positions }.toSet() } return frontier.size } fun part2(input: List<String>, steps: Long): Long { val (positions, start) = parse(input) val tileSize = positions.maxOf { it.first } + 1 to positions.maxOf { it.second } + 1 val garden = Garden(reachablePositions(positions, start), tileSize) val (odds, evens) = garden.oddEvenTilePositions(start) val fullyCoveredTilesInOneDirection = ((start.first + steps) / tileSize.first) val smallCornersPerSide = fullyCoveredTilesInOneDirection val bigCornersPerSide = fullyCoveredTilesInOneDirection - 1 val lastTilePenetration = (start.first + steps) % tileSize.first check(tileSize.first % 2 == 1) { "only works for odd tile sizes" } check(tileSize.first == tileSize.second) { "only works for square tiles" } check(start.first == start.second && start.first == tileSize.first / 2) { "only works for start in the middle of the garden" } val (ringAreasWithStart, ringAreasWithoutStart) = manhattanRingAreas(fullyCoveredTilesInOneDirection) val (withStartTiles, withoutStartTiles) = if (steps % 2L == 1L) { odds to evens } else { evens to odds } val fullyCoveredTiles = ringAreasWithStart * withStartTiles + ringAreasWithoutStart * withoutStartTiles val pointCornerTiles = garden.pointCorners(start, lastTilePenetration) val pointCornerNumbers = pointCornerTiles.sumOf { it.size } val cornersStarts = listOf( 0 to 0, 0 to tileSize.second - 1, tileSize.first - 1 to tileSize.second - 1, tileSize.first - 1 to 0 ) val bigCornerTiles = cornersStarts.map { garden.reachableFromIn(it, lastTilePenetration + lastTilePenetration / 2) } val smallCornerTiles = cornersStarts.map { garden.reachableFromIn(it, lastTilePenetration / 2 - 1) } val bigCornerNumbers = bigCornerTiles.sumOf { it.size } * bigCornersPerSide val smallCornerNumbers = smallCornerTiles.sumOf { it.size } * smallCornersPerSide return fullyCoveredTiles + pointCornerNumbers + bigCornerNumbers + smallCornerNumbers } private fun reachablePositions(positions: Set<Pos>, start: Pos): Set<Pos> { var frontier = setOf(start) val visited = mutableSetOf(start) while (frontier.isNotEmpty()) { frontier = frontier.flatMap { pos -> pos.neighborsManhattan() }.filter { it in positions && it !in visited }.toSet() visited.addAll(frontier) } return visited } private fun manhattanRingAreas(radius: Long): Pair<Long, Long> { if (radius <= 1) { return 1L to 0L } return if (radius % 2 == 0L) { (radius - 1) * (radius - 1) to (radius * radius) } else { (radius * radius) to ((radius - 1) * (radius - 1)) } } data class Garden( val positions: Set<Pos>, val tileSize: Pos, ) { fun oddEvenTilePositions(start: Pos): Pair<Int, Int> { val evens = positions.count { (it.first + it.second) % 2 == (start.first + start.second) % 2 } val odds = positions.size - evens return odds to evens } fun pointCorners(start: Pos, steps: Long): List<Set<Pos>> { val starts = listOf( 0 to start.second, start.first to tileSize.second - 1, tileSize.first - 1 to start.second, start.first to 0 ) return starts.map { reachableFromIn(it, steps) } } fun reachableFromIn(start: Pos, steps: Long): Set<Pos> { var frontier = setOf(start) repeat(steps.toInt()) { frontier = frontier.flatMap { pos -> pos.neighborsManhattan() }.filter { it in positions }.toSet() } return frontier } } } fun main() { val testInput = """ ........... .....###.#. .###.##..#. ..#.#...#.. ....#.#.... .##..S####. .##..#...#. .......##.. .##.#.####. .##..##.##. ........... """.trimIndent().split("\n") val testSteps = 6 val testInput2 = """ ..... ..... ..S.. ..... ..... """.trimIndent().split("\n") println("------Tests------") println(Day21.part1(testInput, testSteps)) listOf(7, 12, 17).forEach { println(Day21.part2(testInput2, it.toLong())) } // too low: 617555274788215 // too low: 617561397599903 println("------Real------") val input = readInput(2023, 21) val steps = 64 val steps2 = 26501365L println("Part 1 result: ${Day21.part1(input, steps)}") println("Part 2 result: ${Day21.part2(input, steps2)}") timingStatistics { Day21.part1(input, steps) } timingStatistics { Day21.part2(input, steps2) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
6,141
advent-of-code
Apache License 2.0
src/Day04.kt
cjosan
573,106,026
false
{"Kotlin": 5721}
fun main() { fun String.toIntRange(): List<IntRange> = this.split(",") .map { it.substringBefore("-").toInt() .. it.substringAfter("-").toInt() } infix fun IntRange.fullyOverlaps(other: IntRange): Boolean = first <= other.first && last >= other.last infix fun IntRange.overlaps(other: IntRange): Boolean = first <= other.last && other.first <= last fun part1(input: List<String>): Int { return input.sumOf { it.toIntRange() .let { (firstElf, secondElf) -> if (firstElf fullyOverlaps secondElf || secondElf fullyOverlaps firstElf) 1 else 0 as Int } } } fun part2(input: List<String>): Int { return input.sumOf { it.toIntRange() .let { (firstElf, secondElf) -> if (firstElf overlaps secondElf) 1 else 0 as Int } } } // 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") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a81f7fb9597361d45ff73ad2a705524cbc64008b
1,191
advent-of-code2022
Apache License 2.0
advent2021/src/main/kotlin/year2021/Day03.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2021 import AdventDay import kotlin.math.pow private operator fun UInt.get(index: Int) = (this shr (UInt.SIZE_BITS - 1 - index)) % 2u private fun UInt.invert(bits: Int) = inv() % 2.0.pow(bits).toUInt() object Day03 : AdventDay(2021, 3) { override fun part1(input: List<String>): Int { val parsed = input.map { it.toUInt(2) } val gamma = (0 until UInt.SIZE_BITS).toList().map { pos -> if (parsed.count { it[pos] == 1u } > (input.size / 2)) { '1' } else '0' }.joinToString("").toUInt(2) val bitSize = UInt.SIZE_BITS - parsed.minOf { it.countLeadingZeroBits() } val epsilon = gamma.invert(bitSize) return gamma.toInt() * epsilon.toInt() } override fun part2(input: List<String>): Int { val parsed = input.map { it.toUInt(2) } val bitSize = parsed.minOf { it.countLeadingZeroBits() } fun List<UInt>.mostCommonBitAtPos(pos: Int) = if (count { it[pos] == 0u } > count { it[pos] == 1u }) 0u else 1u fun List<UInt>.leastCommonBitAtPos(pos: Int) = if (mostCommonBitAtPos(pos) == 0u) 1u else 0u val oxygenRating = generateSequence(parsed to bitSize) { (lastList, pos) -> val mCB = lastList.mostCommonBitAtPos(pos) lastList.filter { it[pos] == mCB } to pos + 1 }.first { it.first.size == 1 }.first[0].toInt() val scrubberRating = generateSequence(parsed to bitSize) { (lastList, pos) -> val mCB = lastList.leastCommonBitAtPos(pos) lastList.filter { it[pos] == mCB } to pos + 1 }.first { it.first.size == 1 }.first[0].toInt() return oxygenRating * scrubberRating } } fun main() = Day03.run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
1,738
advent-of-code
Apache License 2.0
aoc2023/day13.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2023 import utils.InputRetrieval fun main() { Day13.execute() } private object Day13 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<ReflectionPattern>): Long = input.sumOf { it.summarize() } private fun part2(input: List<ReflectionPattern>): Long = input.sumOf { it.summarize(smudges = 1) } private fun readInput(): List<ReflectionPattern> { return InputRetrieval.getFile(2023, 13).readText().split("\n\n").map { ReflectionPattern.parse(it) } } private data class ReflectionPattern(val pattern: List<String>) { fun numberOfReflectedColumns(smudges: Int = 0): Long { // Transpose the pattern to reuse the line reflection method val transposed = List(pattern.first().length) { j -> String(List(pattern.size) { i -> pattern[i][j] }.toCharArray()) } return numberOfReflectedLines(transposed, smudges) } fun numberOfReflectedLines(inputPattern: List<String> = pattern, smudges: Int = 0): Long { val foundReflectionLines = mutableListOf<Int>() for (i in 1..<inputPattern.size) { var errors = 0 for (line in 1..minOf(i, inputPattern.size - i)) { val below = inputPattern[i - line] val above = inputPattern[i + line - 1] errors += above.indices.count { z -> above[z] != below[z] } if (errors > smudges) { break } } if (errors == smudges) { foundReflectionLines.add(i) } } return foundReflectionLines.sum().toLong() } fun summarize(smudges: Int = 0): Long { val columns = this.numberOfReflectedColumns(smudges = smudges) val lines = this.numberOfReflectedLines(smudges = smudges) // println("Column: $columns, Line: $lines") return columns + (lines * 100L) } companion object { fun parse(input: String) = ReflectionPattern(input.split("\n").filter { it.isNotBlank() }) } } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
2,348
Advent-Of-Code
MIT License
aoc-2023/src/main/kotlin/aoc/aoc10.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.* val testInput = """ ........... .S-------7. .|F-----7|. .||.....||. .||.....||. .|L-7.F-J|. .|..|.|..|. .L--J.L--J. ........... """.parselines class Maze(val grid: List<String>) { val xr = grid[0].indices val yr = grid.indices val coords = yr.flatMap { y -> xr.map { x -> Coord(x, y) } } val start = coords.find { at(it) == 'S' }!! fun at(c: Coord) = grid[c.y][c.x] fun pipeNeighbors(c: Coord) = when(at(c)) { 'S' -> if (xr.count() > 20) listOf(c.left, c.bottom) // 7 else listOf(c.right, c.bottom) // F '|' -> listOf(c.top, c.bottom) '-' -> listOf(c.left, c.right) 'J' -> listOf(c.left, c.top) 'L' -> listOf(c.top, c.right) 'F' -> listOf(c.right, c.bottom) '7' -> listOf(c.bottom, c.left) else -> emptyList() } fun tracePipeFromStart(): Map<Coord, Int> { val res = mutableListOf<List<Coord>>(listOf(start)) val all = mutableSetOf(start) var last = setOf(start) while (last.isNotEmpty()) { val newNeighbors = last.flatMap { pipeNeighbors(it) }.filter { it !in all } res += newNeighbors all += newNeighbors last = newNeighbors.toSet() } return res.mapIndexed { i, l -> l.map { it to i } }.flatten().toMap() } fun insideLoop(loop: Set<Coord>, row: Int): Int { // reduce string to just have | and spaces var str = xr.mapNotNull { val c = Coord(it, row) when { c !in loop -> ' ' at(c) == 'S' -> if (xr.count() > 20) '7' else 'F' at(c) == '-' -> null else -> at(c) } }.joinToString("") str = str.replace("F7", "") .replace("LJ", "") .replace("FJ", "|") .replace("L7", "|") // now use even-odd rule to count parts that are inside the loop var res = 0 var index = 0 val search = "\\|(\\s*)\\|".toRegex() var match = search.find(str, index) while (match != null) { res += match.groupValues[1].length index = match.range.last + 1 match = search.find(str, index) } return res } } // part 1 fun List<String>.part1(): Int { val maze = Maze(this) val pipe = maze.tracePipeFromStart() return pipe.values.max() } // part 2 fun List<String>.part2(): Int { val maze = Maze(this) val pipe = maze.tracePipeFromStart().keys return maze.yr.sumOf { maze.insideLoop(pipe, it) } } // calculate answers val day = 10 val input = getDayInput(day, 2023) val testResult = testInput.part1() val testResult2 = testInput.part2() val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
3,037
advent-of-code
Apache License 2.0
LeetCode2020April/week1/src/main/kotlin/net/twisterrob/challenges/leetcode2020april/week1/happy_number/Solution.kt
TWiStErRob
136,539,340
false
{"Kotlin": 104880, "Java": 11319}
package net.twisterrob.challenges.leetcode2020april.week1.happy_number class Solution { fun isHappy(n: Int): Boolean = !n.happySequence().hasRepeatingElement() } /** * Finds if there's a repetition in the sequence. The input has to be in a strict format: * * either all elements are distinct * * or if there's a repetition, that repeats exactly the same elements infinitely */ fun Sequence<*>.hasRepeatingElement(): Boolean { if (this.take(2).count() < 2) { // take() to prevent infinite termination // if we have 0 or 1 elements, there can be no repetition return false } val slow = this.drop(0) val fast = this.drop(1).filterIndexed { i, _ -> i % 2 == 0 } return slow.zip(fast).any { it.first == it.second } } fun Int.happySequence(): Sequence<Int> = generateSequence(this) { if (it != 1) it.squaredSum() else null // terminate sequence } fun Int.squaredSum(): Int = this.digits().sumOf { it * it } fun Int.digits(): Sequence<Int> = when (this@digits) { 0 -> sequenceOf(0) else -> sequence { var n: Int = this@digits while (n > 0) { yield(n % 10) n /= 10 } } }
1
Kotlin
1
2
5cf062322ddecd72d29f7682c3a104d687bd5cfc
1,136
TWiStErRob
The Unlicense
src/main/kotlin/com/ginsberg/advent2021/Day09.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright (c) 2021 by <NAME> */ /** * Advent of Code 2021, Day 9 - Smoke Basin * Problem Description: http://adventofcode.com/2021/day/9 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day9/ */ package com.ginsberg.advent2021 class Day09(input: List<String>) { private val caves: Array<IntArray> = parseInput(input) fun solvePart1(): Int = caves.findLowPoints().sumOf { caves[it] + 1 } fun solvePart2(): Int = caves.findLowPoints() .map { getBasinSize(it) } .sortedDescending() .take(3) .reduce { a, b -> a * b } private fun getBasinSize(point: Point2d): Int { val visited = mutableSetOf(point) val queue = mutableListOf(point) while (queue.isNotEmpty()) { val newNeighbors = queue.removeFirst() .validNeighbors() .filter { it !in visited } .filter { caves[it] != 9 } visited.addAll(newNeighbors) queue.addAll(newNeighbors) } return visited.size } private fun Array<IntArray>.findLowPoints(): List<Point2d> = flatMapIndexed { y, row -> row.mapIndexed { x, height -> Point2d(x, y).takeIf { point -> point.validNeighbors().map { caves[it] }.all { height < it } } }.filterNotNull() } private fun Point2d.validNeighbors(): List<Point2d> = neighbors().filter { it in caves } private operator fun Array<IntArray>.get(point: Point2d): Int = this[point.y][point.x] private operator fun Array<IntArray>.contains(point: Point2d): Boolean = point.y in this.indices && point.x in this[point.y].indices private fun parseInput(input: List<String>): Array<IntArray> = input.map { row -> row.map { it.digitToInt() }.toIntArray() }.toTypedArray() }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
1,981
advent-2021-kotlin
Apache License 2.0
src/main/kotlin/y2023/Day5.kt
juschmitt
725,529,913
false
{"Kotlin": 18866}
package y2023 import utils.Day class Day5 : Day(5, 2023, false) { override fun partOne(): Any { return inputString.parseAlmanac().run { seeds.minOf { seed -> maps.findLocationForSeed(seed) } } } override fun partTwo(): Any { return inputString.parseAlmanac().run { locations().first { val seed = maps.findSeedForLocation(it) seeds.chunked(2).fold(false) { acc, (start, range) -> acc || (start..<(start + range)).contains(seed) } } } } } private fun locations(): Sequence<Long> = generateSequence(1) { it + 1 } private fun List<List<Pair<LongRange, LongRange>>>.findLocationForSeed(seed: Long) = fold(seed) { cur, map -> val mapping = map.find { (source, _) -> source.contains(cur) } mapping?.let { (source, dest) -> dest.first + (cur - source.first) } ?: cur } private fun List<List<Pair<LongRange, LongRange>>>.findSeedForLocation(location: Long) = reversed().fold(location) { cur, map -> val mapping = map.find { (_, dest) -> dest.contains(cur) } mapping?.let { (source, dest) -> source.first + (cur - dest.first) } ?: cur } private fun String.parseAlmanac(): Almanac { val (head, tail) = split("\n\n").run { Pair(first(), drop(1)) } val seeds = head.split(":")[1].trim().split(" ").map { it.toLong() } val maps = tail.parseMappings() return Almanac(seeds, maps) } private fun List<String>.parseMappings() = map { map -> map.split("\n").drop(1).map { line -> val (dest, source, range) = line.split(" ").map { it.toLong() } source..<(source + range) to dest..<(dest + range) } } private data class Almanac( val seeds: List<Long>, val maps: List<List<Pair<LongRange, LongRange>>> )
0
Kotlin
0
0
b1db7b8e9f1037d4c16e6b733145da7ad807b40a
1,866
adventofcode
MIT License
day-11/src/main/kotlin/DumboOctopus.kt
diogomr
433,940,168
false
{"Kotlin": 92651}
fun main() { println("Part One Solution: ${partOne()}") println("Part Two Solution: ${partTwo()}") } private fun partOne(): Int { val matrix = readInputLines() .map { line -> line.toCharArray().map { it.digitToInt() }.toIntArray() } .toTypedArray() var count = 0 for (i in 1..100) { increaseAll(matrix, 1) count += flash(matrix) } return count } fun flash(matrix: Array<IntArray>, flashed: MutableList<Pair<Int, Int>> = mutableListOf()): Int { val original = flashed.size for (i in matrix.indices) { for (j in matrix[0].indices) { if (matrix[i][j] > 9) { matrix[i][j] = 0 flashed.add(Pair(i, j)) increaseAdjacent(matrix = matrix, i = i, j = j, flashed = flashed) } } } if (original == flashed.size) return original return flash(matrix = matrix, flashed = flashed) } fun increaseAdjacent(matrix: Array<IntArray>, i: Int, j: Int, flashed: MutableList<Pair<Int, Int>>) { increase(matrix, i = i - 1, j = j - 1, flashed) increase(matrix, i = i - 1, j = j, flashed) increase(matrix, i = i - 1, j = j + 1, flashed) increase(matrix, i = i, j = j - 1, flashed) increase(matrix, i = i, j = j + 1, flashed) increase(matrix, i = i + 1, j = j - 1, flashed) increase(matrix, i = i + 1, j = j, flashed) increase(matrix, i = i + 1, j = j + 1, flashed) } fun increase(matrix: Array<IntArray>, i: Int, j: Int, flashed: MutableList<Pair<Int, Int>>) { if (i in matrix.indices && j in matrix[0].indices && Pair(i, j) !in flashed) { matrix[i][j]++ } } fun increaseAll(matrix: Array<IntArray>, by: Int) { for (i in matrix.indices) { for (j in matrix[0].indices) { matrix[i][j] += by } } } private fun partTwo(): Int { val matrix = readInputLines() .map { line -> line.toCharArray().map { it.digitToInt() }.toIntArray() } .toTypedArray() for (i in generateSequence(1) { it + 1 }) { increaseAll(matrix, 1) flash(matrix) if (isAllZeroes(matrix)) { return i } } return -1 } private fun isAllZeroes(matrix: Array<IntArray>): Boolean { for (x in matrix.indices) { for (y in matrix[0].indices) { if (matrix[x][y] != 0) { return false } } } return true } private fun readInputLines(): List<String> { return {}::class.java.classLoader.getResource("input.txt")!! .readText() .split("\n") .filter { it.isNotBlank() } }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
2,621
aoc-2021
MIT License
kotlin/src/main/kotlin/year2023/Day14.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 import year2023.Day14.Direction.* fun main() { val input = readInput("Day14") Day14.part1(input).println() Day14.part2(input).println() } object Day14 { fun part1(input: List<String>): Int { return input .rollRocksToNorth() .mapIndexed { row, line -> calculateLoad(line, row, input.size) } .sum() } fun part2(input: List<String>): Int { var rocks = input val beforeCycle = mutableListOf<Int>() beforeCycle.add(rocks.rocksCustomHash()) val cycleMemo = mutableListOf<Pair<Int, Int>>() for (i in 0 until 1_000_000_000L) { rocks = cycle(rocks) val hash = rocks.rocksCustomHash() if (!beforeCycle.contains(hash)) { beforeCycle.add(hash) } else if (!cycleMemo.any { it.first == hash }) { cycleMemo.add(Pair(hash, rocks.mapIndexed { row, line -> calculateLoad(line, row, input.size) }.sum())) } else { break } } return cycleMemo[((1_000_000_000L - beforeCycle.size) % cycleMemo.size).toInt()].second } private fun List<String>.rocksCustomHash(): Int { val rowLength = this[0].length return this .mapIndexed { row, line -> line.mapIndexed { column, char -> if (char == 'O') ((column + 1) + (rowLength * row)) else 0 } } .flatten() .sum() } private val memo = mutableMapOf<Int, List<String>>() private var count = 0 private fun cycle(rocks: List<String>): List<String> { val inputHash = rocks.rocksCustomHash() println("${count}: $inputHash") count++ return memo.getOrPut(inputHash) { rocks.rollRocksToNorth() .rollRocksToWest() .rollRocksToSouth() .rollRocksToEast() } } private fun calculateLoad(line: String, row: Int, numberOfRows: Int): Int { val multiplier = (numberOfRows - row) val count = line.count { it == 'O' } return multiplier * count } private enum class Direction { NORTH, SOUTH, WEST, EAST } private fun List<String>.rollRocksToNorth(): List<String> { val builder = mutableListOf<StringBuilder>() this.forEach { builder.add(StringBuilder(it)) } for (column in 0 until builder[0].length) { while (!areRocksVerticalSorted(builder, column, NORTH)) { applyVerticalBubbleSortOnce(builder, column, NORTH) } } return builder.map { it.toString() } } private fun List<String>.rollRocksToSouth(): List<String> { val builder = mutableListOf<StringBuilder>() this.forEach { builder.add(StringBuilder(it)) } for (column in 0 until builder[0].length) { while (!areRocksVerticalSorted(builder, column, SOUTH)) { applyVerticalBubbleSortOnce(builder, column, SOUTH) } } return builder.map { it.toString() } } private fun applyVerticalBubbleSortOnce(builder: MutableList<StringBuilder>, column: Int, direction: Direction) { assert(direction == NORTH || direction == SOUTH) val first = if (direction == NORTH) 0 else 1 val second = if (first == 0) 1 else 0 for (row in 0 until (builder.size - 1)) { if (builder[row + first][column] == '.' && builder[row + second][column] == 'O') { builder[row + first][column] = 'O' builder[row + second][column] = '.' } } } private fun areRocksVerticalSorted( builder: MutableList<StringBuilder>, column: Int, direction: Direction ): Boolean { assert(direction == NORTH || direction == SOUTH) val it = if (direction == NORTH) builder else builder.reversed() return it .map { it[column] } .zipWithNext() .all { !(it.first == '.' && it.second == 'O') } } private fun List<String>.rollRocksToWest(): List<String> { val builder = mutableListOf<StringBuilder>() this.forEach { builder.add(StringBuilder(it)) } for (row in 0 until builder.size) { while (!areRocksHorizontalSorted(builder[row], WEST)) { applyHorizontalBubbleSortOnce(builder[row], WEST) } } return builder.map { it.toString() } } private fun List<String>.rollRocksToEast(): List<String> { val builder = mutableListOf<StringBuilder>() this.forEach { builder.add(StringBuilder(it)) } for (row in 0 until builder.size) { while (!areRocksHorizontalSorted(builder[row], EAST)) { applyHorizontalBubbleSortOnce(builder[row], EAST) } } return builder.map { it.toString() } } private fun areRocksHorizontalSorted(builder: StringBuilder, direction: Direction): Boolean { assert(direction == WEST || direction == EAST) val it = if (direction == WEST) builder.toString() else builder.reversed() return it .zipWithNext() .all { !(it.first == '.' && it.second == 'O') } } private fun applyHorizontalBubbleSortOnce(builder: StringBuilder, direction: Direction) { assert(direction == WEST || direction == EAST) val first = if (direction == WEST) 0 else 1 val second = if (first == 0) 1 else 0 for (column in 0 until (builder.length - 1)) { if (builder[column + first] == '.' && builder[column + second] == 'O') { builder[column + first] = 'O' builder[column + second] = '.' } } } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
5,939
advent-of-code
MIT License
src/main/kotlin/com/ryanmoelter/advent/day03/Rucksacks.kt
ryanmoelter
573,615,605
false
{"Kotlin": 84397}
package com.ryanmoelter.advent.day03 fun main() { println(calculateBadgePriority(day03input)) } fun calculateBadgePriority(input: String): Int = input.lineSequence() .fold(listOf(emptyList<String>())) { groups, line -> val lastGroup = groups.last() if (lastGroup.size < 3) { groups.minus(element = lastGroup).plus(element = lastGroup + line) } else { groups.plus(element = listOf(line)) } } .map { group -> group.map { line -> line.toSet() } .fold(emptySet<Char>()) { acc, chars -> if (acc.isEmpty()) { chars } else { acc.intersect(chars) } } } .sumOf { set -> assert(set.size == 1) set.sumOf { it.toPriority() } } fun calculateSeparatedPriority(input: String): Int = input.lineSequence() .map { line -> line.take(line.length / 2) to line.takeLast(line.length / 2) } .map { (first, second) -> first.toSet().intersect(second.toSet()) } .map { set -> assert(set.size == 1) set.sumOf { it.toPriority() } } .sum() fun Char.toPriority(): Int = if (this.isUpperCase()) { this - 'A' + 27 } else { this - 'a' + 1 }
0
Kotlin
0
0
aba1b98a1753fa3f217b70bf55b1f2ff3f69b769
1,143
advent-of-code-2022
Apache License 2.0
src/Day18.kt
fedochet
573,033,793
false
{"Kotlin": 77129}
fun main() { data class Dot(val x: Int, val y: Int, val z: Int) { fun move(dx: Int = 0, dy: Int = 0, dz: Int = 0): Dot = Dot(x + dx, y + dy, z + dz) } fun getDotsAround(dot: Dot): Sequence<Dot> = sequence { yield(dot.move(dx = 1)) yield(dot.move(dy = 1)) yield(dot.move(dz = 1)) yield(dot.move(dx = -1)) yield(dot.move(dy = -1)) yield(dot.move(dz = -1)) } fun parseDots(input: List<String>) = input.map { line -> val (x, y, z) = line.split(",", limit = 3).map { it.toInt() } Dot(x, y, z) } fun part1(input: List<String>): Int { val dots = parseDots(input) val pattern = mutableSetOf<Dot>() var sides = 0 for (dot in dots) { require(pattern.add(dot)) val dotsAround = getDotsAround(dot) val sidesDiff = dotsAround.map { if (it in pattern) -1 else 1 }.sum() sides += sidesDiff } return sides } fun part2(input: List<String>): Int { val dots = parseDots(input) val xMin = dots.minOf { it.x } - 1 val yMin = dots.minOf { it.y } - 1 val zMin = dots.minOf { it.z } - 1 val xMax = dots.maxOf { it.x } + 1 val yMax = dots.maxOf { it.y } + 1 val zMax = dots.maxOf { it.z } + 1 fun inBox(dot: Dot): Boolean { val (x, y, z) = dot return x in xMin..xMax && y in yMin..yMax && z in zMin..zMax } val outside = mutableSetOf<Dot>() val start = Dot(xMin, yMin, zMin) val queue = ArrayDeque(listOf(start)) while (queue.isNotEmpty()) { val dot = queue.removeFirst() if (!outside.add(dot)) continue val dotsAround = getDotsAround(dot) val newOutside = dotsAround.filter { inBox(it) && it !in dots && it !in outside } queue.addAll(newOutside) } var areaOutside = 0 for (dot in dots) { val dotsAround = getDotsAround(dot) for (around in dotsAround) { if (around in outside) { areaOutside += 1 } } } return areaOutside } // 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") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
975362ac7b1f1522818fc87cf2505aedc087738d
2,558
aoc2022
Apache License 2.0
src/Day08.kt
rod41732
728,131,475
false
{"Kotlin": 26028}
import java.lang.Exception /** * You can edit, run, and share this code. * play.kotlinlang.org */ fun main() { data class Node(val name: String, val left: String, val right: String); fun gcd(a: Long, b: Long): Long { if (b == 0L) return a return gcd(b, a % b) } fun lcm(a: Long, b: Long): Long { return a / gcd(a, b) * b } fun calculateCount( graph: Map<String, Node>, instruction: String, startNode: String, isEnd: (node: Node) -> Boolean ): Int { var curNode = graph.get(startNode)!! instruction.asSequence().repeat().forEachIndexed { idx, it -> if (isEnd(curNode)) return idx curNode = graph.get( when (it) { 'L' -> curNode.left 'R' -> curNode.right else -> throw Exception("Invalid instruction: '$it'") } )!! } throw Exception("Should be unreachable") } fun parseInput(input: List<String>): Pair<String, Map<String, Node>> { val instruction = input.first() val graph = buildMap { input.drop(2).forEach { val (a, b, c) = Regex("([A-Z]{3}) = \\(([A-Z]{3}), ([A-Z]{3})\\)").find(it)!!.groupValues.drop(1) this[a] = Node(a, b, c) } } return Pair(instruction, graph) } fun part1(input: List<String>): Int { val (instruction, graph) = parseInput(input) return calculateCount(graph, instruction, "AAA", { it.name == "ZZZ" }) } fun part2(input: List<String>): Long { val (instruction, graph) = parseInput(input) val startNodes = graph.values.filter { it.name.last() == 'A' } // from observation, each start node will end at some node ending Z at N, 2N, 3N, ... val cycleSizes = startNodes.map { calculateCount(graph, instruction, it.name, { it.name.last() == 'Z' }) } return cycleSizes.fold(1L) { acc, it -> lcm(acc, it.toLong()) } } val testInput = readInput("Day08_test") val testInput2 = readInput("Day08_test2") assertEqual(part1(testInput), 2) assertEqual(part1(testInput2), 6) val input = readInput("Day08") println("Part1: ${part1(input)}") // 19199 println("Part2: ${part2(input)}") // 13663968099527 }
0
Kotlin
0
0
05a308a539c8a3f2683b11a3a0d97a7a78c4ffac
2,386
aoc-23
Apache License 2.0
src/Day18.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
import java.io.File // Advent of Code 2022, Day 18, Boiling Boulders fun main() { fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim() fun getNeighbors(cube: List<Int>) : List<List<Int>> { return listOf( listOf(cube[0], cube[1], cube[2] + 1), listOf(cube[0], cube[1] + 1, cube[2]), listOf(cube[0] + 1, cube[1], cube[2]), listOf(cube[0], cube[1], cube[2] - 1), listOf(cube[0], cube[1] - 1, cube[2]), listOf(cube[0] - 1, cube[1], cube[2]), ) } fun surfaceArea(cubes: Set<List<Int>>): Int { val touching = cubes.fold(0) { sum, cube -> sum + getNeighbors(cube).count{ cubes.contains(it) } } return cubes.size * 6 - touching } fun part1(input: String): Int { val cubes = input.split("\n").map { it -> it.split(",").map { it.toInt() } }.toSet() return surfaceArea(cubes) } fun part2(input: String): Int { val cubes = input.split("\n").map { it -> it.split(",").map { it.toInt() } }.toSet() val maxX = cubes.maxOfOrNull { it[0] }!! + 1 val minX = cubes.minOfOrNull { it[0] }!! - 1 val maxY = cubes.maxOfOrNull { it[1] }!! + 1 val minY = cubes.minOfOrNull { it[1] }!! - 1 val maxZ = cubes.maxOfOrNull { it[2] }!! + 1 val minZ = cubes.minOfOrNull { it[2] }!! - 1 var currCube = listOf(minX, minY, minZ) val queue = mutableListOf<List<Int>>() queue.add(currCube) val outside = mutableSetOf<List<Int>>() var outsideSurfaces = 0 while (queue.isNotEmpty()) { currCube = queue.removeFirst() if (currCube[0] < minX || currCube[0] > maxX || currCube[1] < minY || currCube[1] > maxY || currCube[2] < minZ || currCube[2] > maxZ) continue if (currCube in outside) continue if (currCube in cubes) continue outside.add(currCube) outsideSurfaces += getNeighbors(currCube).count{ cubes.contains(it) } val neighbors = getNeighbors(currCube) queue.addAll(neighbors) } return outsideSurfaces } val testInput = readInputAsOneLine("Day18_test") check(part1(testInput)==64) check(part2(testInput)==58) val input = readInputAsOneLine("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
2,487
AdventOfCode2022
Apache License 2.0
src/y2021/Day10.kt
Yg0R2
433,731,745
false
null
package y2021 import java.util.ArrayDeque import java.util.Deque private val AUTO_COMPLETE_CHARACTER_SCORE = mapOf( ')' to 1L, ']' to 2L, '}' to 3L, '>' to 4L ) private val ILLEGAL_CHARACTER_SCORE = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137 ) private val TAGS = mapOf( '(' to ')', '[' to ']', '{' to '}', '<' to '>' ) fun main() { fun getCorruptedTag(stack: Deque<Char>) = { corruptedTag: String, currentTag: Char -> if (TAGS.containsKey(currentTag)) { stack.push(currentTag) corruptedTag } else if (TAGS[stack.peek()] == currentTag) { stack.pop() corruptedTag } else if (corruptedTag.isNotBlank()) { corruptedTag } else { currentTag.toString() } } fun part1(input: List<String>): Int { return input .map { it.fold("", getCorruptedTag(ArrayDeque())) } .flatMap { it.toList() } .sumOf { ILLEGAL_CHARACTER_SCORE[it] ?: 0 } } fun part2(input: List<String>): Int { return input .asSequence() .filter { it.fold("", getCorruptedTag(ArrayDeque())).isBlank() } .map { it.fold(ArrayDeque()) { stack: Deque<Char>, currentTag: Char -> if (TAGS.containsKey(currentTag)) { stack.push(currentTag) } else if (TAGS[stack.peek()] == currentTag) { stack.pop() } stack } } .map { it.toList() } .map { it.fold(0L) { acc: Long, tag: Char -> acc * 5 + (AUTO_COMPLETE_CHARACTER_SCORE[TAGS[tag]] ?: 0L) } } .sorted() .toList() .let { it[it.size / 2] } .toInt() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput).also { println(it) } == 26397) check(part2(testInput).also { println(it) } == 288957) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
2,338
advent-of-code
Apache License 2.0
src/Day08.kt
acunap
573,116,784
false
{"Kotlin": 23918}
import kotlin.math.max import kotlin.time.ExperimentalTime import kotlin.time.measureTime @OptIn(ExperimentalTime::class) fun main() { fun part1(input: List<String>) : Int { var count = input.size * 2 + input.first().count() * 2 - 4 for (row in 1 until input.lastIndex) { for (column in 1 until input.first().lastIndex) { val current = input[row][column].digitToInt() val left = input[row].substring(0, column).map { it.digitToInt() }.max() val right = input[row].substring(column + 1).map { it.digitToInt() }.max() val column = input.map { it[column] } val up = column.slice(0 until row).map { it.digitToInt() }.max() val down = column.slice(row + 1 until column.size).map { it.digitToInt() }.max() if (listOf(left, right, up, down).min() < current) { count++ } } } return count } fun part2(input: List<String>) : Int { fun calculateScenicLine(line: List<Int>, current: Int) = line.takeWhile { it < current }.size.let { if (it == line.size) it else it + 1 } var maxScenicScore = 0 for (row in 1 until input.lastIndex) { for (column in 1 until input.first().lastIndex) { val current = input[row][column].digitToInt() val left = calculateScenicLine(input[row].substring(0, column).map { it.digitToInt() }.reversed(), current) val right = calculateScenicLine(input[row].substring(column + 1).map { it.digitToInt() }, current) val column = input.map { it[column] } val up = calculateScenicLine(column.slice(0 until row).map { it.digitToInt() }.reversed(), current) val down = calculateScenicLine(column.slice(row + 1 until column.size).map { it.digitToInt() }, current) val scenicScore = left * right * up * down maxScenicScore = max(maxScenicScore, scenicScore) } } return maxScenicScore } val time = measureTime { val input = readLines("Day08") println(part1(input)) println(part2(input)) } println("Real data time $time") val timeTest = measureTime { val testInput = readLines("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) } println("Test data time $timeTest.") }
0
Kotlin
0
0
f06f9b409885dd0df78f16dcc1e9a3e90151abe1
2,533
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2023/Day03.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2023 import AoCDay // https://adventofcode.com/2023/day/3 object Day03 : AoCDay<Int>( title = "Gear Ratios", part1ExampleAnswer = 4361, part1Answer = 553079, part2ExampleAnswer = 467835, part2Answer = 84363105, ) { private data class Point(val row: Int, val col: Int) private class Number(val value: Int, val row: Int, val startCol: Int, val endCol: Int) private data class EngineSchematic(val numbers: List<Number>, val symbols: Map<Point, Char>) private fun parseEngineSchematic(input: String): EngineSchematic { val numbers = mutableListOf<Number>() val symbols = hashMapOf<Point, Char>() for ((row, line) in input.lineSequence().withIndex()) { var number = 0 var startCol = 0 var endCol = -1 for ((col, char) in line.withIndex()) { if (char in '0'..'9') { number = (number * 10) + (char - '0') endCol = col } else { if (startCol <= endCol) { numbers += Number(number, row, startCol, endCol) number = 0 } startCol = col + 1 if (char != '.') symbols[Point(row, col)] = char } } if (startCol <= endCol) numbers += Number(number, row, startCol, endCol) } return EngineSchematic(numbers, symbols) } private val Number.adjacentPoints get() = sequence { for (col in (startCol - 1)..(endCol + 1)) { yield(Point(row + 1, col)) yield(Point(row - 1, col)) } yield(Point(row, startCol - 1)) yield(Point(row, endCol + 1)) } private val EngineSchematic.partNumbers get() = numbers.filter { it.adjacentPoints.any(symbols::containsKey) } override fun part1(input: String) = parseEngineSchematic(input).partNumbers.sumOf { it.value } override fun part2(input: String): Int { val (numbers, symbols) = parseEngineSchematic(input) val asteriskAdjacent = symbols.filterValues { it == '*' }.keys.associateWith { mutableListOf<Number>() } for (number in numbers) { for (point in number.adjacentPoints) { asteriskAdjacent[point]?.add(number) } } return asteriskAdjacent.values.filter { it.size == 2 }.sumOf { (a, b) -> a.value * b.value } } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
2,505
advent-of-code-kotlin
MIT License
src/Day04.kt
Yasenia
575,276,480
false
{"Kotlin": 15232}
fun main() { fun String.toAssignments(): Pair<Pair<Int, Int>, Pair<Int, Int>> { val assignments = this.split(",") val assignment1 = assignments[0].split("-") val assignment2 = assignments[1].split("-") return Pair(assignment1[0].toInt() to assignment1[1].toInt(), assignment2[0].toInt() to assignment2[1].toInt()) } fun part1(input: List<String>): Int = input .map { it.toAssignments() } .count { (assignment1, assignment2) -> (assignment1.first >= assignment2.first && assignment1.second <= assignment2.second) || (assignment1.first <= assignment2.first && assignment1.second >= assignment2.second) } fun part2(input: List<String>): Int = input .map { it.toAssignments() } .count { (assignment1, assignment2) -> assignment1.first <= assignment2.second && assignment2.first <= assignment1.second } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9300236fa8697530a3c234e9cb39acfb81f913ba
1,143
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/puzzle3/BinaryDiagnostic.kt
tpoujol
436,532,129
false
{"Kotlin": 47470}
package puzzle3 import kotlin.math.pow import kotlin.math.roundToInt fun main() { println("Hello World!") val binaryDiagnostic = BinaryDiagnostic() println("Power consumption is: ${binaryDiagnostic.findPowerConsumption()}, ${binaryDiagnostic.findLifeSupportRating()}") } class BinaryDiagnostic { private val input: List<List<Int>> = BinaryDiagnostic::class.java.getResource("/input/puzzle3.txt") ?.readText() ?.split("\n") ?.filter { it.isNotEmpty() } ?.map { it.fold(MutableList(0) { 0 }) { acc, c -> acc.apply { this.add(c.digitToInt()) } }.toList() } ?: listOf() fun findPowerConsumption():Int { val sums = input.fold(MutableList(input[0].size) { 0 }) { acc: MutableList<Int>, list: List<Int> -> list.forEachIndexed { index, value -> acc[index] += value } acc } println(sums) val binaryGamma = sums .map { (it.toDouble() / input.size).roundToInt() } val binaryEpsilon = sums .map { ((input.size - it).toDouble() / input.size ).roundToInt() } val gamma = convertBinaryToDecimal(binaryGamma) val epsilon = convertBinaryToDecimal(binaryEpsilon) println("binaryGamma: $binaryGamma, gamma: $gamma") println("binaryEpsilon: $binaryEpsilon, epsilon: $epsilon") return epsilon * gamma } fun findLifeSupportRating(): Int{ val oxygenRatingBinary = filterOutInputForLifeSupportValue(input, 0, true) val co2RatingBinary = filterOutInputForLifeSupportValue(input, 0, false) val oxygenRating = convertBinaryToDecimal(oxygenRatingBinary) val co2Rating = convertBinaryToDecimal(co2RatingBinary) println("oxygenRatingBinary: $oxygenRatingBinary, oxygen: $oxygenRating") println("co2RatingBinary: $co2RatingBinary, co2: $co2Rating") return oxygenRating * co2Rating } companion object { private fun convertBinaryToDecimal(binaryValue: List<Int>) = binaryValue .reversed() .foldIndexed(0.0) { index: Int, acc: Double, digit: Int -> acc + 2.0.pow(index) * digit } .toInt() private fun filterOutInputForLifeSupportValue( valuesList: List<List<Int>>, indexOfDiscriminant: Int, shouldTakeMostCommon: Boolean ): List<Int> { val sum = valuesList.fold(0) { acc, list -> acc + list[indexOfDiscriminant] } val discriminant: Int = if (shouldTakeMostCommon) { if (sum > valuesList.size / 2.0) 1 else if (sum < valuesList.size / 2.0) 0 else 1 } else { if (sum > valuesList.size / 2.0) 0 else if (sum < valuesList.size / 2.0) 1 else 0 } val resultList = valuesList.filter { it[indexOfDiscriminant] == discriminant } println("initial size: ${valuesList.size}, sum: $sum, index: $indexOfDiscriminant, discriminant: $discriminant size: ${resultList.size}, $resultList") return if (resultList.size == 1) resultList[0] else filterOutInputForLifeSupportValue( resultList, indexOfDiscriminant + 1, shouldTakeMostCommon ) } } }
0
Kotlin
0
1
6d474b30e5204d3bd9c86b50ed657f756a638b2b
3,222
aoc-2021
Apache License 2.0
src/day8/Day08-solution2.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day8 import readInput private fun part1(input: List<String>): Int { val grid: Array<IntArray> = Array(input.size) { IntArray(input[0].length) } for (row in input.indices) { for (col in 0 until input[row].length) { grid[row][col] = input[row][col].digitToInt() } } val highestInRow: Array<IntArray> = Array(grid.size) { IntArray(grid[0].size) { Int.MIN_VALUE } } val highestInCol: Array<IntArray> = Array(grid.size) { IntArray(grid[0].size) { Int.MIN_VALUE } } val added: MutableSet<String> = hashSetOf() for (row in grid.indices) { highestInRow[row][0] = Int.MIN_VALUE highestInRow[row][1] = grid[row][0] for (col in 2 until grid[0].size) { highestInRow[row][col] = highestInRow[row][col - 1].coerceAtLeast(grid[row][col - 1]) } } for (col in grid[0].indices) { highestInCol[0][col] = Int.MIN_VALUE highestInCol[1][col] = grid[0][col] for (row in 2 until grid.size) { highestInCol[row][col] = highestInCol[row - 1][col].coerceAtLeast(grid[row - 1][col]) } } for (row in grid.size - 2 downTo 1) { var rightMax = grid[row][grid[0].size - 1] for (col in grid[0].size - 2 downTo 1) { val currentItem = grid[row][col] if (currentItem > rightMax || highestInRow[row][col] < currentItem) { added.add("R$row-C$col") } rightMax = rightMax.coerceAtLeast(currentItem) } } for (col in grid[0].size - 2 downTo 1) { var bottomMax = grid[grid.size - 1][col] for (row in grid.size - 2 downTo 1) { val currentItem = grid[row][col] if (currentItem > bottomMax || highestInCol[row][col] < currentItem) { added.add("R$row-C$col") } bottomMax = bottomMax.coerceAtLeast(currentItem) } } return added.size + (2 * grid.size + 2 * (grid.size - 2)) } fun main() { val input = readInput("day8/input") println(part1(input)) }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
2,074
aoc-2022
Apache License 2.0
year2021/src/main/kotlin/net/olegg/aoc/year2021/day22/Day22.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2021.day22 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Vector3D import net.olegg.aoc.year2021.DayOf2021 /** * See [Year 2021, Day 22](https://adventofcode.com/2021/day/22) */ object Day22 : DayOf2021(22) { private val PATTERN = "(on|off) x=(-?\\d+)\\.\\.(-?\\d+),y=(-?\\d+)\\.\\.(-?\\d+),z=(-?\\d+)\\.\\.(-?\\d+)".toRegex() override fun first(): Any? { val ops = lines .mapNotNull { line -> val parsed = PATTERN.find(line)?.groupValues.orEmpty() if (parsed.size == 8) { val op = parsed[1] val from = Vector3D(parsed[2].toInt(), parsed[4].toInt(), parsed[6].toInt()) val to = Vector3D(parsed[3].toInt(), parsed[5].toInt(), parsed[7].toInt()) op to (from to to) } else { null } } val basicCube = Vector3D(-50, -50, -50) to Vector3D(50, 50, 50) return solve(ops.filter { (_, cube) -> intersects(cube, basicCube) }) } override fun second(): Any? { val ops = lines .mapNotNull { line -> val parsed = PATTERN.find(line)?.groupValues.orEmpty() if (parsed.size == 8) { val op = parsed[1] val from = Vector3D(parsed[2].toInt(), parsed[4].toInt(), parsed[6].toInt()) val to = Vector3D(parsed[3].toInt(), parsed[5].toInt(), parsed[7].toInt()) op to (from to to) } else { null } } return solve(ops) } private fun intersects( old: Pair<Vector3D, Vector3D>, new: Pair<Vector3D, Vector3D>, ): Boolean { val (oldFrom, oldTo) = old val (newFrom, newTo) = new return !( oldTo.x < newFrom.x || oldTo.y < newFrom.y || oldTo.z < newFrom.z || oldFrom.x > newTo.x || oldFrom.y > newTo.y || oldFrom.z > newTo.z ) } private fun solve(ops: List<Pair<String, Pair<Vector3D, Vector3D>>>): Long { val finalCubes = ops.fold(emptyList<Pair<Vector3D, Vector3D>>()) { acc, (op, cube) -> acc.flatMap { oldCube -> if (intersects(oldCube, cube)) { split(oldCube, cube) } else { listOf(oldCube) } } + if (op == "on") listOf(cube) else emptyList() } return finalCubes.sumOf { cube -> (cube.second - cube.first).toList().map { it + 1L }.reduce { a, b -> a * b } } } private fun split( old: Pair<Vector3D, Vector3D>, new: Pair<Vector3D, Vector3D>, ): List<Pair<Vector3D, Vector3D>> { val (oldFrom, oldTo) = old val (newFrom, newTo) = new val xParts = buildParts(oldFrom.x, oldTo.x, newFrom.x, newTo.x) val yParts = buildParts(oldFrom.y, oldTo.y, newFrom.y, newTo.y) val zParts = buildParts(oldFrom.z, oldTo.z, newFrom.z, newTo.z) return xParts.flatMap { (fromX, toX, partX) -> yParts.flatMap { (fromY, toY, partY) -> zParts.mapNotNull { (fromZ, toZ, partZ) -> (Vector3D(fromX, fromY, fromZ) to Vector3D(toX, toY, toZ)).takeIf { !partX || !partY || !partZ } } } } } private fun buildParts( oldFrom: Int, oldTo: Int, newFrom: Int, newTo: Int ): List<Triple<Int, Int, Boolean>> { return buildList { var partial = newFrom <= oldFrom var mark = oldFrom if (newFrom in ((mark + 1)..oldTo)) { add(Triple(mark, newFrom - 1, partial)) mark = newFrom partial = true } if (newTo in (mark..oldTo)) { add(Triple(mark, newTo, partial)) mark = newTo + 1 partial = false } if (mark <= oldTo) { add(Triple(mark, oldTo, partial)) } } } } fun main() = SomeDay.mainify(Day22)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
3,640
adventofcode
MIT License
app/src/main/kotlin/aoc2022/day02/Day02.kt
dbubenheim
574,231,602
false
{"Kotlin": 18742}
package aoc2022.day02 import aoc2022.day02.Day02.Result.* import aoc2022.day02.Day02.part1 import aoc2022.day02.Day02.part2 import aoc2022.toFile object Day02 { fun part1() = "input-day02.txt".toFile() .readLines() .map { it.toRound() } .sumOf { it.score } fun part2() = "input-day02.txt".toFile() .readLines() .map { it.toRoundPart2() } .sumOf { it.score } enum class Shape(private val encryption: Set<String>, val score: Int) { ROCK(setOf("A", "X"), 1), PAPER(setOf("B", "Y"), 2), SCISSORS(setOf("C", "Z"), 3); fun vs(shape: Shape): Result { return when (this) { ROCK -> { when (shape) { ROCK -> DRAW PAPER -> LOSS SCISSORS -> WIN } } PAPER -> { when (shape) { ROCK -> WIN PAPER -> DRAW SCISSORS -> LOSS } } SCISSORS -> { when (shape) { ROCK -> LOSS PAPER -> WIN SCISSORS -> DRAW } } } } fun findShape(result: Result): Shape { return when (result) { WIN -> { when (this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } } DRAW -> { when (this) { ROCK -> ROCK PAPER -> PAPER SCISSORS -> SCISSORS } } LOSS -> { when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } } } } companion object { fun from(encryption: String) = values().first { it.encryption.contains(encryption) } } } data class Round(private val opponent: Shape, private val mine: Shape, val score: Int) enum class Result(val value: Int, val encryption: String) { WIN(6, "Z"), DRAW(3, "Y"), LOSS(0, "X"); companion object { fun from(encryption: String) = values().first { it.encryption == encryption } } } private fun String.toRound(): Round { val (opponent, mine) = split(" ") val opponentShape = opponent.toShape() val myShape = mine.toShape() val score = myShape.score + myShape.vs(opponentShape).value return Round(opponentShape, myShape, score) } private fun String.toRoundPart2(): Round { val (opponent, res) = split(" ") val opponentShape = opponent.toShape() val result = res.toResult() val myShape = opponentShape.findShape(result) val score = myShape.score + myShape.vs(opponentShape).value return Round(opponentShape, myShape, score) } private fun String.toShape() = Shape.from(this) private fun String.toResult() = Result.from(this) } fun main() { println(part1()) println(part2()) }
8
Kotlin
0
0
ee381bb9820b493d5e210accbe6d24383ae5b4dc
3,435
advent-of-code-2022
MIT License
src/day3/Day03.kt
mrm1st3r
573,163,888
false
{"Kotlin": 12713}
package day3 import Puzzle fun splitCompartments(s: String): Pair<String, String> { val middle = s.length / 2 return Pair(s.substring(0, middle), s.substring(middle, s.length)) } fun findOverlap(compartments: Pair<String, String>): String { return compartments.first.filter { compartments.second.contains(it) } } fun prioritize(item: Char): Int { return when { item.isLowerCase() -> item.code - 96 else -> item.code - 38 } } fun findBadge(elfs: List<String>): Char { check(elfs.size == 3) val a = findOverlap(Pair(elfs[0], elfs[1])) return findOverlap(Pair(a, elfs[2])).first() } fun main() { fun part1(input: List<String>): Int { return input .asSequence() .map(::splitCompartments) .map(::findOverlap) .map{it.first()} .map(::prioritize) .sum() } fun part2(input: List<String>): Int { return input .windowed(3, 3) .map(::findBadge) .map(::prioritize) .sum() } Puzzle( "day3", ::part1, 157, ::part2, 70 ).test() }
0
Kotlin
0
0
d8eb5bb8a4ba4223331766530099cc35f6b34e5a
1,183
advent-of-code-22
Apache License 2.0
src/main/kotlin/Day02.kt
NielsSteensma
572,641,496
false
{"Kotlin": 11875}
fun main() { val input = readInput("Day02") println("Day 02 Part 1 ${calculateDay02Part1(input)}") println("Day 02 Part 2 ${calculateDay02Part2(input)}") } fun calculateDay02Part1(input: List<String>): Int { return input.sumOf { val opponentPlayerChars = extractChars(it) calculateRockPaperScissorOutput(opponentPlayerChars) } } fun calculateDay02Part2(input: List<String>): Int { return input.sumOf { val (opponent, gameResult) = extractChars(it) val opponentsPick = Pick.forChar(opponent) val playersPick = GameResult.forChar(gameResult).getPlayersPick(opponentsPick) val opponentPlayerChars = Pair(opponent, playersPick.playerChar) calculateRockPaperScissorOutput(opponentPlayerChars) } } private fun extractChars(string: String): Pair<Char, Char> { val splitString = string.split(" ") val opponent = splitString[0].first() val player = splitString[1].first() return Pair(opponent, player) } private fun calculateRockPaperScissorOutput(opponentPlayerChars: Pair<Char, Char>): Int { val (opponentChar, playerChar) = opponentPlayerChars val opponentPick = Pick.forChar(opponentChar) val playerPick = Pick.forChar(playerChar) val score = calculateWinDrawOrLoseScore(playerPick, opponentPick) return score + playerPick.score } fun calculateWinDrawOrLoseScore(player: Pick, opponent: Pick): Int { if (player == opponent) { return 3 } return if (player.beats == opponent) 6 else 0 } enum class Pick { ROCK, PAPER, SCISSOR; val beats: Pick get() = when (this) { ROCK -> SCISSOR PAPER -> ROCK SCISSOR -> PAPER } val loses: Pick get() = when (this) { SCISSOR -> ROCK ROCK -> PAPER PAPER -> SCISSOR } val score: Int get() = when (this) { ROCK -> 1 PAPER -> 2 SCISSOR -> 3 } val playerChar: Char get() = when (this) { ROCK -> 'X' PAPER -> 'Y' SCISSOR -> 'Z' } companion object { fun forChar(char: Char) = when (char) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSOR else -> throw IllegalArgumentException("Char not in PlayerGuide") } } } enum class GameResult { WIN, LOSE, DRAW; fun getPlayersPick(opponent: Pick) = when (this) { DRAW -> opponent WIN -> opponent.loses LOSE -> opponent.beats } companion object { fun forChar(char: Char) = when (char) { 'Z' -> WIN 'X' -> LOSE 'Y' -> DRAW else -> throw IllegalArgumentException("Char not in PlayerGuide") } } }
0
Kotlin
0
0
4ef38b03694e4ce68e4bc08c390ce860e4530dbc
2,925
aoc22-kotlin
Apache License 2.0
src/Day11.kt
6234456
572,616,769
false
{"Kotlin": 39979}
import java.math.BigInteger data class Monkey(var item: java.util.LinkedList<Long> = java.util.LinkedList<Long>(), var operation: (Long)->Long = {it}, var divisor: Int = 1, var ifTrue: Int = -1, var ifFalse: Int = -1) data class Monkey0(var item: java.util.LinkedList<BigInteger> = java.util.LinkedList<BigInteger>(), var operation: (BigInteger)->BigInteger = {it}, var divisor: BigInteger = BigInteger.ONE, var ifTrue: Int = -1, var ifFalse: Int = -1) fun main() { fun part1(input: List<String>): Int { val cnt = (input.size + 1) / 7 val arr = Array<Monkey>(cnt){Monkey()} input.forEachIndexed { index, s -> val line = index.mod(7) + 1 val idx = (index - line + 1) / 7 val m = arr[idx] when(line){ 2 -> m.item.addAll(s.split(": ").last().split(", ").map { it.trim().toLong() }) 3 -> { val a = s.split(" ").takeLast(2) when{ a.last() == "old" -> m.operation = {it * it} else -> { val sec = a.last().toInt() if (a.first() == "+") { m.operation = {it + sec} }else{ m.operation = {it * sec} } } } } 4 -> { m.divisor = s.split(" ").last().toInt() } 5 -> { m.ifTrue = s.split(" ").last().toInt() } 6 -> { m.ifFalse = s.split(" ").last().toInt() } } } val ans = IntArray(cnt){0} repeat(20){ arr.forEachIndexed { indexed, m -> ans[indexed] = ans[indexed] + arr[indexed].item.size while (m.item.isNotEmpty()){ val i = m.item.pop() val v = m.operation(i) / 3 arr[if (v.mod(m.divisor) == 0) m.ifTrue else m.ifFalse].item.add(v) } } } val tmp = ans.sortedByDescending { it }.take(2) return tmp[0] * tmp[1] } fun part2(input: List<String>): Long{ val cnt = (input.size + 1) / 7 val arr = Array<Monkey>(cnt){Monkey()} input.forEachIndexed { index, s -> val line = index.mod(7) + 1 val idx = (index - line + 1) / 7 val m = arr[idx] when(line){ 2 -> m.item.addAll(s.split(": ").last().split(", ").map { it.trim().toLong() }) 3 -> { val a = s.split(" ").takeLast(2) when{ a.last() == "old" -> m.operation = {it * it} else -> { val sec = a.last().toInt() if (a.first() == "+") { m.operation = {it + sec} }else{ m.operation = {it * sec} } } } } 4 -> { m.divisor = s.split(" ").last().toInt() } 5 -> { m.ifTrue = s.split(" ").last().toInt() } 6 -> { m.ifFalse = s.split(" ").last().toInt() } } } val ans = IntArray(cnt) val d = arr.fold(1L){ acc, monkey -> acc * monkey.divisor } repeat(10000){ arr.forEachIndexed { indexed, m -> ans[indexed] = ans[indexed] + arr[indexed].item.size while (m.item.isNotEmpty()){ val i = m.item.pop() val v = m.operation(i) % d arr[if (v.mod(m.divisor) == 0) m.ifTrue else m.ifFalse].item.add(v) } } } val tmp = ans.sortedByDescending { it }.take(2) return tmp[0].toLong()* tmp[1].toLong() } var input = readInput("Test11") println(part1(input)) println(part2(input)) input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b6d683e0900ab2136537089e2392b96905652c4e
4,480
advent-of-code-kotlin-2022
Apache License 2.0
src/Day04.kt
VadimB95
574,449,732
false
{"Kotlin": 19743}
fun main() { // 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") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { var fullyContainedPairsCount = 0 input.forEach { lineInput -> val parsedInput = lineInput.split(",", "-").map(String::toInt) val isFirstContainsSecond = parsedInput[0] <= parsedInput[2] && parsedInput[1] >= parsedInput[3] val isSecondContainsFirst = parsedInput[2] <= parsedInput[0] && parsedInput[3] >= parsedInput[1] if (isFirstContainsSecond || isSecondContainsFirst) fullyContainedPairsCount++ } return fullyContainedPairsCount } private fun part2(input: List<String>): Int { var overlappedPairsCount = 0 input.forEach { lineInput -> val parsedInput = lineInput.split(",", "-").map(String::toInt) val isNotOverlapped = parsedInput[1] < parsedInput[2] || parsedInput[3] < parsedInput[0] if (!isNotOverlapped) overlappedPairsCount++ } return overlappedPairsCount }
0
Kotlin
0
0
3634d1d95acd62b8688b20a74d0b19d516336629
1,189
aoc-2022
Apache License 2.0
src/Day07.kt
arisaksen
573,116,584
false
{"Kotlin": 42887}
import org.assertj.core.api.Assertions.assertThat // https://adventofcode.com/2022/day/7 fun main() { open class File(var size: Long) class Dir : File(size = 0L) { val files = mutableListOf<File>() var parent: Dir? = null operator fun plusAssign(otherFile: File) { size += otherFile.size.also { if (otherFile is Dir) otherFile.parent = this } files += otherFile var parentDir: Dir? = parent while (parentDir != null) { parentDir.size += otherFile.size parentDir = parentDir.parent } } } data class Commands( private val input: List<String>, private val rootDir: Dir = Dir() ) { fun readCommands() { var current = rootDir input.forEachIndexed { index, line -> when { line.startsWith("$ cd") -> current = when (line.split(" ").last()) { ".." -> current.parent as Dir else -> { val dir = Dir() if (dir != current) current.plusAssign(dir) dir } } line.startsWith("$ ls") -> Unit line.startsWith("dir") -> current.plusAssign(Dir()) line.first().isDigit() -> current.plusAssign(File(size = line.split(" ").first().toLong())) else -> error("Error. Check your input $index: $line") } } } private fun getAllFiles(): List<File> = buildList { val tmpList = rootDir.files.toMutableList() while (tmpList.isNotEmpty()) { val file = tmpList.removeFirst() add(file) if (file is Dir) file.files.forEach { tmpList.plusAssign(it) } } } fun getDirectoriesBySize(maxSize: Long): Long = getAllFiles() .filterIsInstance<Dir>() .filter { it.size <= maxSize } .sumOf { it.size } fun getSmallestFileToRemove(maxSize: Long, neededSpace: Long): Long = getAllFiles() .filterIsInstance<Dir>() .filter { it.size >= neededSpace - maxSize + rootDir.size } .minOf { it.size } } fun part1(input: List<String>): Long = Commands(input) .apply { readCommands() } .run { getDirectoriesBySize(100_000) } fun part2(input: List<String>): Long = Commands(input) .apply { readCommands() } .run { getSmallestFileToRemove(maxSize = 70_000_000L, neededSpace = 30_000_000L) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") assertThat(part1(testInput)).isEqualTo(95437) assertThat(part2(testInput)).isEqualTo(24933642) // print the puzzle answer val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
85da7e06b3355f2aa92847280c6cb334578c2463
3,197
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/day13/Day13.kt
daniilsjb
434,765,082
false
{"Kotlin": 77544}
package day13 import java.io.File import kotlin.math.abs fun main() { val (points, folds) = parse("src/main/kotlin/day13/Day13.txt") val answer1 = part1(points, folds) val answer2 = part2(points, folds) println("🎄 Day 13 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer:\n$answer2") } private enum class Axis { X, Y } private data class Point( val x: Int, val y: Int, ) private data class Fold( val axis: Axis, val line: Int, ) private data class Instructions( val points: Set<Point>, val folds: List<Fold>, ) private fun parse(path: String): Instructions { val (pointsPart, foldsPart) = File(path) .readText() .split("""(\n\n)|(\r\n\r\n)""".toRegex()) .map(String::trim) val points = pointsPart .lines() .mapTo(HashSet(), String::toPoint) val folds = foldsPart .lines() .map(String::toFold) return Instructions(points, folds) } private fun String.toPoint(): Point = this.split(",") .let { (lhs, rhs) -> Point(lhs.toInt(), rhs.toInt()) } private fun String.toFold(): Fold = this.removePrefix("fold along ") .split("=") .let { (lhs, rhs) -> Fold(lhs.toAxis(), rhs.toInt()) } private fun String.toAxis(): Axis = when (this) { "x" -> Axis.X "y" -> Axis.Y else -> error("Invalid folding axis") } private fun Point.reflect(axis: Axis, line: Int): Point = when (axis) { Axis.X -> Point(line - abs(x - line), y) Axis.Y -> Point(x, line - abs(y - line)) } private fun part1(points: Set<Point>, folds: List<Fold>): Int { val (axis, line) = folds.first() return points .mapTo(HashSet()) { it.reflect(axis, line) } .count() } private fun part2(points: Set<Point>, folds: List<Fold>): String { val code = folds.fold(points) { dots, (axis, line) -> dots.mapTo(HashSet()) { it.reflect(axis, line) } } return buildString { for (y in 0 until 6) { for (x in 0 until 40) { if (x % 5 == 0) { append(" ") } append(if (code.contains(Point(x, y))) '#' else ' ') } append('\n') } } }
0
Kotlin
0
1
bcdd709899fd04ec09f5c96c4b9b197364758aea
2,347
advent-of-code-2021
MIT License
src/Day05.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
import java.util.Stack fun main() { fun List<Char>.toStack(): Stack<Char> { val result = Stack<Char>() this.reversed().forEach { result.push(it) } return result } fun getStacks(stackInput: List<String>): List<Stack<Char>> { val listsByIndex = stackInput[stackInput.size - 2].chunked(4).map { mutableListOf<Char>() } (0 until stackInput.size - 2).forEach { i -> stackInput[i].chunked(4).forEachIndexed { j, s -> if (s[1] != ' ') listsByIndex[j] += s[1] } } return listsByIndex.map { it.toStack() } } fun doWork(input: List<String>, move: (from: Stack<Char>, to: Stack<Char>, num: Int) -> Unit): String { val (stackInput, commands) = input.partition { !it.startsWith("move") } val stackList = getStacks(stackInput) commands.forEach { command -> val parts = command.split(" ") val num = parts[1].toInt() val from = stackList[parts[3].toInt() - 1] val to = stackList[parts[5].toInt() - 1] move(from, to, num) } return stackList.joinToString("") { if (it.isEmpty()) "" else "" + it.peek() } } fun part1(input: List<String>): String { return doWork(input) { from, to, num -> repeat(num) { to.push(from.pop()) } } } fun part2(input: List<String>): String { return doWork(input) { from, to, num -> val tmp = Stack<Char>() repeat(num) { tmp.push(from.pop()) } repeat(num) { to.push(tmp.pop()) } } } println(part1(readInput("data/Day05_test"))) println(part1(readInput("data/Day05"))) println(part2(readInput("data/Day05_test"))) println(part2(readInput("data/Day05"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
1,643
aoc-2022-in-kotlin
Apache License 2.0
AdventOfCode/2022/aoc22/src/main/kotlin/day8.kt
benhunter
330,517,181
false
{"Rust": 172709, "Python": 143372, "Kotlin": 37623, "Java": 17629, "TypeScript": 3422, "JavaScript": 3124, "Just": 1078}
fun day8() { val day = 8 println("day $day") val filename = "$day-input.txt" // val filename = "$day-test.txt" val text = getTextFromResource(filename).trim() val lines = text.split("\n") debugln(lines) val trees = lines.map { line -> line.map { it.digitToInt() } } debugln(trees) var part1 = 0 trees.forEachIndexed { lineIndex, line -> debug("$line ") line.forEachIndexed { treeIndex, tree -> debugln(tree) part1 += if (Direction.values() .map { direction -> isVisibleFromOutside(direction, lineIndex, treeIndex, trees) } .any { it } ) 1 else 0 debugln("part 1 $part1") } } debugln() println("part 1 $part1") // 1851 debugln("part 2") val scenicScores = trees.mapIndexed { lineindex, line -> List(line.size) { treeindex -> scenicScore(lineindex, treeindex, trees) } } val part2 = scenicScores.flatten().max() println("part 2 $part2") // 574080 } fun scenicScore(lineindex: Int, treeindex: Int, trees: List<List<Int>>): Int { return Direction.values().map { direction -> countVisibleFrom(direction, lineindex, treeindex, trees) } .reduce { acc, i -> acc * i } } fun countVisibleFrom(direction: Direction, lineIndex: Int, treeIndex: Int, trees: List<List<Int>>): Int { val tree = trees[lineIndex][treeIndex] val lineOfSight = when (direction) { Direction.LEFT -> { trees[lineIndex].slice(0 until treeIndex).reversed() } Direction.RIGHT -> { trees[lineIndex].slice(treeIndex + 1 until trees[lineIndex].size) } Direction.TOP -> { trees.mapIndexedNotNull { index, line -> if (index < lineIndex) { line[treeIndex] } else { null } }.reversed() } Direction.BOTTOM -> { trees.mapIndexedNotNull { index, line -> if (index > lineIndex) { line[treeIndex] } else { null } } } } return calculateLineOfSight(lineOfSight, tree) } private fun calculateLineOfSight(lineOfSight: List<Int>, tree: Int): Int { lineOfSight.forEachIndexed { index, current -> if (current >= tree) return index + 1 } return lineOfSight.size } enum class Direction { LEFT, RIGHT, TOP, BOTTOM } fun isVisibleFromOutside(direction: Direction, lineIndex: Int, treeIndex: Int, trees: List<List<Int>>): Boolean { debug("$direction $lineIndex $treeIndex") val tree = trees[lineIndex][treeIndex] debugln(" tree $tree") when (direction) { Direction.LEFT -> { if (lineIndex == 0) return true val lineOfSight = trees[lineIndex].slice(0 until treeIndex) return if (lineOfSight.isEmpty()) true else { tree > lineOfSight.max() } } Direction.RIGHT -> { val lineOfSight = trees[lineIndex].slice(treeIndex + 1 until trees[lineIndex].size) return if (lineOfSight.isEmpty()) true else { tree > lineOfSight.max() } } Direction.TOP -> { if (lineIndex == 0) return true val lineOfSight = trees.mapIndexedNotNull { index, line -> if (index < lineIndex) { line[treeIndex] } else { null } } debugln(lineOfSight) return tree > lineOfSight.max() } Direction.BOTTOM -> { if (lineIndex == trees[lineIndex].size - 1) return true val lineOfSight = trees.mapIndexedNotNull { index, line -> if (index > lineIndex) { line[treeIndex] } else { null } } debugln(lineOfSight) return tree > lineOfSight.max() } } }
0
Rust
0
1
a424c12f4d95f9d6f8c844e36d6940a2ac11d61d
4,187
coding-challenges
MIT License
baparker/15/main.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File data class CavePosition(val level: Int, val x: Int, val y: Int) { var visited = false var distanceFromStart = Int.MAX_VALUE } fun findPathWithLowestRisk( cavePositionMatrix: MutableList<MutableList<CavePosition>>, x: Int = 0, y: Int = 0, counter: Int = -1 ) { val currentNode = cavePositionMatrix.get(y).get(x) val count = currentNode.level + counter if (count < currentNode.distanceFromStart && count < cavePositionMatrix.last().last().distanceFromStart ) { currentNode.distanceFromStart = count if (!(y == cavePositionMatrix.size - 1 && x == cavePositionMatrix.get(0).size - 1)) { val top = cavePositionMatrix.getOrNull(y - 1)?.get(x) val left = cavePositionMatrix.get(y).getOrNull(x - 1) val right = cavePositionMatrix.get(y).getOrNull(x + 1) val bottom = cavePositionMatrix.getOrNull(y + 1)?.get(x) listOf(top, left, right, bottom) .filter { it != null && it.visited == false } .sortedBy { it!!.level } .forEach { it!!.visited = true findPathWithLowestRisk(cavePositionMatrix, it.x, it.y, count) it.visited = false } } } } fun main() { val cavePositionMatrix: MutableList<MutableList<CavePosition>> = mutableListOf() var yIndex = 0 for (y in 0 until 5) { File("input.txt").forEachLine { val line: MutableList<CavePosition> = mutableListOf() for (x in 0 until 5) { it.forEachIndexed { xIndex, pos -> val newPos = pos.digitToInt() + x + y line.add( CavePosition( if (newPos == 9) 9 else newPos % 9, xIndex + (x * 100), yIndex ) ) } } cavePositionMatrix.add(line) yIndex++ } } cavePositionMatrix.last().last().distanceFromStart = cavePositionMatrix.get(0).sumOf { it.level } + cavePositionMatrix.map { it.last().level }.sum() findPathWithLowestRisk(cavePositionMatrix) println(cavePositionMatrix.last().last().distanceFromStart) }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
2,469
advent-of-code-2021
MIT License
src/main/kotlin/kt/kotlinalgs/app/graph/PrimMST.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph import java.util.* println("Test") Solution().test() class Solution { fun test() { //https://www.geeksforgeeks.org/prims-mst-for-adjacency-list-representation-greedy-algo-6/ val vertice0 = Vertice(0) val vertice1 = Vertice(1) val vertice2 = Vertice(2) val vertice3 = Vertice(3) val vertice4 = Vertice(4) val vertice5 = Vertice(5) val vertice6 = Vertice(6) val vertice7 = Vertice(7) val vertice8 = Vertice(8) val graph = WeightedUndirectedGraph( listOf( vertice0, vertice1, vertice2, vertice3, vertice4, vertice5, vertice6, vertice7, vertice8 ) ) graph.addEdge(vertice0, vertice1, 4) graph.addEdge(vertice0, vertice7, 8) graph.addEdge(vertice1, vertice2, 8) graph.addEdge(vertice1, vertice7, 11) graph.addEdge(vertice2, vertice3, 7) graph.addEdge(vertice2, vertice5, 4) graph.addEdge(vertice2, vertice8, 2) graph.addEdge(vertice3, vertice4, 9) graph.addEdge(vertice3, vertice5, 14) graph.addEdge(vertice4, vertice5, 10) graph.addEdge(vertice5, vertice6, 2) graph.addEdge(vertice6, vertice7, 1) graph.addEdge(vertice6, vertice8, 6) graph.addEdge(vertice7, vertice8, 7) val prim = Prim() val vertices = prim.minimumSpanningTree(graph) prim.printMst(vertices) } } data class Vertice(val value: Int, var distance: Int = Int.MAX_VALUE, var prev: Vertice? = null) : Comparable<Vertice> { override fun compareTo(other: Vertice): Int { return distance - other.distance } override fun equals(other: Any?): Boolean { val oth = other as? Vertice ?: return false return value == oth.value } override fun hashCode(): Int { return value.hashCode() } } data class Edge( val from: Vertice, val to: Vertice, val weight: Int ) data class WeightedUndirectedGraph(val vertices: List<Vertice>) { var edges: MutableMap<Vertice, MutableList<Edge>> = mutableMapOf() fun addEdge(first: Vertice, second: Vertice, weight: Int) { val firstList = edges.getOrDefault(first, mutableListOf()) firstList.add(Edge(first, second, weight)) edges[first] = firstList val secondList = edges.getOrDefault(second, mutableListOf()) secondList.add(Edge(second, first, weight)) edges[second] = secondList } } // O(E log V) class Prim { fun minimumSpanningTree(graph: WeightedUndirectedGraph): MutableList<Vertice> { val output: MutableList<Vertice> = mutableListOf() val pq: TreeSet<Vertice> = TreeSet() // PriorityQueue() val inMst: MutableSet<Vertice> = mutableSetOf() graph.vertices.forEach { it.distance = Int.MAX_VALUE } graph.vertices[0].distance = 0 pq.add(graph.vertices[0]) while (!pq.isEmpty()) { // V val cur = pq.pollFirst() // // O(log V) output.add(cur) inMst.add(cur) graph.edges[cur]?.forEach { // E if (!inMst.contains(it.to) && it.weight < it.to.distance) { // O(log V) if (pq.contains(it.to)) { pq.remove(it.to) // O(log V) // important!! oder IndexedPQ / because PQ remove = O(N).. // treeSet add, remove, contains = O(log N) } it.to.distance = it.weight it.to.prev = cur pq.add(it.to) // O(log V) } } } // total = O(E log V + V log V) return output } fun printMst(mst: MutableList<Vertice>) { println("MST:") mst.forEach { println("${it.prev?.value} -> ${it.value}") } } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
3,951
KotlinAlgs
MIT License
src/Day09.kt
razvn
573,166,955
false
{"Kotlin": 27208}
import kotlin.math.abs fun main() { val day = "Day09" fun part1(input: List<String>): Int { val head = createRope(2) input.map { it.split(" ").let { (d, n) -> Direction.valueOf(d) to n.toInt() } }.forEach { head.move(it.first, it.second) } return getTail(head).positions.toSet().size } fun part2(input: List<String>): Int { val head = createRope(10) // println(head) input.map { it.split(" ").let { (d, n) -> Direction.valueOf(d) to n.toInt() } }.forEach { head.move(it.first, it.second) } val tail = getTail(head) // println(tail.positions) return tail.positions.toSet().size } // test if implementation meets criteria from the description, like: val testInput1 = readInput("${day}_test") // println(part1(testInput1)) check(part1(testInput1) == 13) val testInput2 = readInput("${day}_test2") // println(part2(testInput2)) check(part2(testInput2) == 36) val input = readInput(day) println(part1(input)) println(part2(input)) } private fun createRope(elements: Int) = createRope(0, elements) private fun createRope(current: Int, elements: Int): Head2 { return when { current >= elements - 1 -> Head2("$current", null) else -> Head2("$current", createRope(current + 1, elements)) } } private tailrec fun getTail(head: Head2): Head2 { return when (head.tail) { null -> head else -> getTail(head.tail) } } private data class Head2(val name: String, val tail: Head2? = null) { private var currentPosition: Point = Point(0, 0) val positions = mutableListOf(currentPosition) fun move(dir: Direction, value: Int) { // println("MOVE -> $dir: $value") repeat(value) { move(dir) } } private fun move(dir: Direction) { val newX = when (dir) { Direction.R -> currentPosition.x + 1 Direction.L -> currentPosition.x - 1 else -> currentPosition.x } val newY = when (dir) { Direction.U -> currentPosition.y + 1 Direction.D -> currentPosition.y - 1 else -> currentPosition.y } currentPosition = Point(newX, newY) // println("\tcurrentPosition: $currentPosition") positions.add(currentPosition) tail?.moveTail(this) } private fun moveTail(head: Head2) { val moveX = head.currentPosition.x - currentPosition.x val moveY = head.currentPosition.y - currentPosition.y if (abs(moveX) > 1 || abs(moveY) > 1) { val newX = when { moveX > 0 -> currentPosition.x + 1 moveX < 0 -> currentPosition.x - 1 else -> head.currentPosition.x } val newY = when { moveY > 0 -> currentPosition.y + 1 moveY < 0 -> currentPosition.y - 1 else -> head.currentPosition.y } currentPosition = Point(newX, newY) // println("\tnewTail: $currentTail") positions.add(currentPosition) tail?.moveTail(this) } } } private enum class Direction { R, L, U, D} private data class Point(val x: Int, val y: Int)
0
Kotlin
0
0
73d1117b49111e5044273767a120142b5797a67b
3,337
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/adventofcode2023/day19/day19.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day19 import adventofcode2023.readInput import kotlin.math.max import kotlin.math.min import kotlin.reflect.KProperty1 import kotlin.time.measureTime fun main() { println("Day 19") val input = readInput("day19") val time1 = measureTime { println("Puzzle 1 ${puzzle1(input)}") } println("Puzzle 1 took $time1") val time2 = measureTime { println("Puzzle 2 ${puzzle2(input)}") } println("Puzzle 2 took $time2") } data class Part( val x: Int, val m: Int, val a: Int, val s: Int ) { fun sum(): Int = x + m + a + s } fun parseInput(input: List<String>): Pair<Map<String, WorkFlow>, List<Part>> { val emptyLineIndex = input.indexOfFirst { it.isEmpty() } val map = input.subList(0, emptyLineIndex).map { parseCommand(it) } .groupBy(keySelector = { (key, _) -> key }, valueTransform = { (_, v) -> v }) .mapValues { it.value.first } val commands = input.subList(emptyLineIndex + 1, input.size).map { parsePart(it) } return Pair(map, commands) } data class WorkFlow( val rules: List<(Part) -> String?>, val final: String ) { fun invoke(p: Part): String { for (r in rules) { val res = r(p) if (res != null) { return res } } return final } } fun buildMoreRule( propertySupplier: KProperty1<Part, Int>, value: Int, label: String ): (Part) -> String? = fun(p: Part): String? { return if (propertySupplier.get(p) > value) { label } else { null } } fun buildLessRule( propertySupplier: KProperty1<Part, Int>, value: Int, label: String ): (Part) -> String? = fun(p: Part): String? { return if (propertySupplier.get(p) < value) { label } else { null } } fun parseCommand(line: String): Pair<String, WorkFlow> { val openIndex = line.indexOf('{') val closesIndex = line.indexOf('}') val label = line.substring(0, openIndex) val rules = line.substring(openIndex + 1, closesIndex).split(',').map { it.trim() } val rulesList = rules.subList(0, rules.lastIndex).map { r -> r.split(':').let { (s1, ll) -> val (property, number) = s1.split('<', '>') val supplier = when (property) { "a" -> Part::a "x" -> Part::x "m" -> Part::m "s" -> Part::s else -> throw IllegalArgumentException("Could not handle $property") } if (s1.contains('<')) { buildLessRule(supplier, number.toInt(), ll) } else { buildMoreRule(supplier, number.toInt(), ll) } } } return Pair(label, WorkFlow(rulesList, rules.last)) } fun parsePart(line: String): Part { val argMap = line.substring(line.indexOf('{') + 1, line.indexOf('}')) .split(',') .map { it.trim() }.associate { it.split('=').let { (name, value) -> name to value.toInt() } } return Part(a = argMap["a"]!!, x = argMap["x"]!!, m = argMap["m"]!!, s = argMap["s"]!!) } fun puzzle1(input: List<String>): Long { val (map, parts) = parseInput(input) return parts.filter { p -> verify(p, map) }.sumOf { p -> p.sum().toLong() } } fun verify(p: Part, flows: Map<String, WorkFlow>): Boolean { var key = "in" do { key = flows[key]!!.invoke(p) } while (key != "A" && key != "R") return key == "A" } fun puzzle2(input: List<String>): Long { val workflows = input.subList(0, input.indexOfFirst { it.isEmpty() }).map { parseCommand2(it) } .groupBy(keySelector = { (key, _) -> key }, valueTransform = { (_, v) -> v }) .mapValues { it.value.first } return count(workflows) } data class Workflow2( val rules: List<Rule>, val final: String ) { data class Rule( val name: String, val action: String, val number: Int, val label: String ) } fun parseCommand2(line: String): Pair<String, Workflow2> { val openIndex = line.indexOf('{') val closesIndex = line.indexOf('}') val label = line.substring(0, openIndex) val rules = line.substring(openIndex + 1, closesIndex).split(',').map { it.trim() } val rulesList = rules.subList(0, rules.lastIndex).map { r -> r.split(':').let { (s1, ll) -> val (property, number) = s1.split('<', '>') val symbol = if (s1.contains('<')) { "<" } else { ">" } Workflow2.Rule(property, symbol, number.toInt(), ll) } } return Pair(label, Workflow2(rulesList, rules.last)) } fun Map<String, IntRange>.calculate() = this.values.fold(1L) { acc, intRange -> acc * (intRange.last - intRange.first + 1) } fun count( workflows: Map<String, Workflow2>, data: Map<String, IntRange> = mapOf( "x" to IntRange(1, 4000), "m" to IntRange(1, 4000), "a" to IntRange(1, 4000), "s" to IntRange(1, 4000) ), key: String = "in" ): Long { if (key == "R") { return 0 } if (key == "A") { val result = data.calculate() println("$data $result") return result } var total = 0L val currentData = data.toMutableMap() val (rules, final ) = workflows[key]!! for ((name, action, number, label) in rules) { val r = currentData[name]!! val (f, s) = if (action == "<") { Pair( IntRange(r.first, min(r.last, number - 1)), IntRange(max(r.first, number), r.last) ) } else { Pair( IntRange(max(r.first, number + 1), r.last), IntRange(r.first, min(r.last, number)) ) } if (f.first < f.last) { val newData = currentData.toMutableMap().apply { this[name] = f } total += count(workflows, newData, label) } if (s.first < s.last) { currentData[name] = s } } total += count(workflows, currentData, final) return total }
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
6,210
adventofcode2023
MIT License
src/day5/Day05.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day5 import readInput const val NEXT_ELEMENT_DISTANCE = 4 const val ITERATION_NUMBER_INDEX = 1 const val FROM_INDEX = 3 const val TO_INDEX = 5 private fun createInitialStacks(initialInput: List<String>): Array<ArrayDeque<Char>> { val max = initialInput.last().split(" ").last() val stacks = Array(max.toInt()) { ArrayDeque<Char>() } for (index in 0 until initialInput.size - 1) { val line = initialInput[index] var item = 1 while (item < line.length) { if (line[item] != ' ') { stacks[item / NEXT_ELEMENT_DISTANCE].addLast(line[item]) } item += NEXT_ELEMENT_DISTANCE } } return stacks } private fun part1(initialInput: List<String>, input: List<String>): String { val stacks = createInitialStacks(initialInput) for (line in input) { val parts = line.split(" ") for (index in 0 until parts[ITERATION_NUMBER_INDEX].toInt()) { val item = stacks[parts[FROM_INDEX].toInt() - 1].removeFirst() stacks[parts[TO_INDEX].toInt() - 1].addFirst(item) } } return stacks.fold("") { result, stack -> result + stack.firstOrNull()!! } } private fun part2(initialInput: List<String>, input: List<String>): String { val stacks = createInitialStacks(initialInput) for (line in input) { val parts = line.split(" ") val temp = ArrayDeque<Char>() for (index in 0 until parts[ITERATION_NUMBER_INDEX].toInt()) { val item = stacks[parts[FROM_INDEX].toInt() - 1].removeFirst() temp.addFirst(item) } while (temp.isNotEmpty()) { val item = temp.removeFirst() stacks[parts[TO_INDEX].toInt() - 1].addFirst(item) } } return stacks.fold("") { result, stack -> result + stack.firstOrNull()!! } } fun main() { val input = readInput("day5/input") val initialInput = readInput("day5/initial-input") println(part1(initialInput, input)) println(part2(initialInput, input)) }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
2,052
aoc-2022
Apache License 2.0
src/day02/Day02.kt
tobihein
569,448,315
false
{"Kotlin": 58721}
package day02 import readInput class Day02 { fun part1(): Int { val readInput = readInput("day02/input") return part1(readInput) } fun part2(): Int { val readInput = readInput("day02/input") return part2(readInput) } fun part1(input: List<String>): Int = input.map { parse(it) }.map { getScore(it) }.sum() fun part2(input: List<String>): Int = input.map { parsePart2(it) }.map { getScore(it) }.sum() private fun parse(s: String): Pair<Choice, Choice> { val choices = s.split(" ") if (choices.size != 2) { throw IllegalArgumentException("Unknown input $s") } return Pair(toChoice(choices[0]), toChoice(choices[1])) } private fun parsePart2(s: String): Pair<Choice, Choice> { val choices = s.split(" ") if (choices.size != 2) { throw IllegalArgumentException("Unknown input $s") } val other = toChoice(choices[0]) val you = calcRequiredChoice(choices, other) return Pair(other, you) } private fun calcRequiredChoice(choices: List<String>, other: Choice): Choice { var you = toChoice(choices[1]) if (you == Choice.ROCK) you = loseAgainst(other) else if (you == Choice.PAPER) you = other else if (you == Choice.SCISSOR) you = winAgainst(other) return you } private fun winAgainst(other: Choice): Choice { when (other) { Choice.ROCK -> return Choice.PAPER Choice.SCISSOR -> return Choice.ROCK else -> return Choice.SCISSOR } } private fun loseAgainst(other: Any): Choice { when (other) { Choice.ROCK -> return Choice.SCISSOR Choice.SCISSOR -> return Choice.PAPER else -> return Choice.ROCK } } private fun getScore(choices: Pair<Choice, Choice>) = choices.second.score + getRetResultScore(choices.first, choices.second) private fun getRetResultScore(other: Choice, you: Choice): Int { var score = -1 if (other == you) { score = 3 } else if (other == Choice.ROCK) { score = if (you == Choice.SCISSOR) 0 else 6 } else if (other == Choice.PAPER) { score = if (you == Choice.ROCK) 0 else 6 } else if (other == Choice.SCISSOR) { score = if (you == Choice.PAPER) 0 else 6 } return score } private fun toChoice(s: String): Choice { when (s) { "A", "X" -> return Choice.ROCK "B", "Y" -> return Choice.PAPER "C", "Z" -> return Choice.SCISSOR else -> throw RuntimeException("Error on parsing choice $s") } } enum class Choice(val score: Int) { ROCK(1), PAPER(2), SCISSOR(3) } }
0
Kotlin
0
0
af8d851702e633eb8ff4020011f762156bfc136b
2,849
adventofcode-2022
Apache License 2.0
year2018/src/main/kotlin/net/olegg/aoc/year2018/day12/Day12.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day12 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2018.DayOf2018 /** * See [Year 2018, Day 12](https://adventofcode.com/2018/day/12) */ object Day12 : DayOf2018(12) { override fun first(): Any? { return solve(20) } override fun second(): Any? { return solve(50_000_000_000L) } private fun solve(gens: Long): Long { val initialStateRaw = lines .first() .substringAfter(": ") val initialShift = initialStateRaw.indexOf('#').toLong() val initialState = initialStateRaw.trim('.') to (0L to initialShift) val padding = "...." val states = mutableMapOf(initialState) val rules = lines .drop(2) .associate { line -> line.split(" => ").let { it.first() to it.last() } } val finalState = (1..gens).fold(initialState) { state, gen -> val tempState = padding + state.first + padding val newStateRaw = tempState .windowed(size = 5) .map { rules.getOrDefault(it, '.') } .joinToString(separator = "") val shift = newStateRaw.indexOf('#') + state.second.second - 2 val newState = newStateRaw.trim('.') to (gen to shift) if (newState.first in states) { val (oldGen, oldShift) = states[newState.first] ?: (0L to 0L) val cycle = gen - oldGen val cycleShift = shift - oldShift val aggregateShift = shift + cycleShift * ((gens - gen) / cycle) val tail = (gens - gen) % cycle val finalValue = states.entries .find { it.value.first == oldGen + tail } ?.toPair() ?: ("" to (0L to 0L)) val final = finalValue.first to (gens to aggregateShift + finalValue.second.second - oldShift) return final .first .mapIndexed { index, c -> if (c == '#') index + final.second.second else 0L } .sum() } states += newState newState } return finalState .first .mapIndexed { index, c -> if (c == '#') index + finalState.second.second else 0L } .sum() } } fun main() = SomeDay.mainify(Day12)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,110
adventofcode
MIT License
src/main/kotlin/io/math/StringToIntAtoi.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.math import io.utils.runTests import kotlin.math.absoluteValue // https://leetcode.com/problems/string-to-integer-atoi/ class StringToIntAtoi { fun execute(input: String): Int { val firstNoWhiteSpace = input.firstNoWhiteSpace() if (firstNoWhiteSpace !in input.indices) return 0 val firstChar = input[firstNoWhiteSpace] if (!firstChar.isFirstCharValid() || (!firstChar.isDigit() && firstNoWhiteSpace + 1 == input.length)) return 0 var result = 0 val sign = if (firstChar.isPositive() || firstChar.isDigit()) 1 else -1 val firstNumber = if (firstChar.isDigit()) firstNoWhiteSpace else firstNoWhiteSpace + 1 loop@ for (index in firstNumber until input.length) { val char = input[index] val value = (char - '0') when { !char.isDigit() -> break@loop sign.isPositive() && (result > Int.MAX_VALUE / 10 || result == Int.MAX_VALUE / 10 && value > Int.MAX_VALUE.rem(10)) -> { return Int.MAX_VALUE } sign.isNegative() && (result > Int.MAX_VALUE / 10 || result == Int.MAX_VALUE / 10 && value > Int.MIN_VALUE.rem(10).absoluteValue) -> { return Int.MIN_VALUE } else -> result = 10 * result + value } } return sign * result } } private fun Int.isNegative() = this < 0 private fun Int.isPositive() = !isNegative() private fun Char.isFirstCharValid() = when (this) { '-', '+' -> true else -> (this - '0') in 0..9 } private fun Char.isPositive() = this == '+' private fun String.firstNoWhiteSpace(): Int = this.mapIndexed { index, char -> index to char }.firstOrNull { it.second != ' ' }?.first ?: this.length fun main() { runTests(listOf( "42" to 42, " -42" to -42, "4193 with words" to 4193, "words and 987" to 0, "-91283472332" to Int.MIN_VALUE, "-2147483648" to Int.MIN_VALUE, " -1010023630o4" to -1010023630 )) { (input, value) -> value to StringToIntAtoi().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,975
coding
MIT License
src/Day03.kt
jamOne-
573,851,509
false
{"Kotlin": 20355}
fun letterValue(char: Char): Int { return if (char.isLowerCase()) char.minus('a') + 1 else char.minus('A') + 27 } fun main() { fun part1(input: List<String>): Int { var totalPriority = 0 for (rucksack in input) { val compartment1 = rucksack.substring(0, rucksack.length / 2) val compartment2 = rucksack.substring(rucksack.length / 2) val commonLetters = compartment1.asIterable().intersect(compartment2.asIterable().toSet()) check(commonLetters.size == 1) val commonLetter = commonLetters.first() totalPriority += letterValue(commonLetter) } return totalPriority } fun part2(input: List<String>): Int { var totalPriority = 0 val groups = input.chunked(3) for (group in groups) { val commonLetters = group[0].toSet().intersect(group[1].toSet()).intersect(group[2].toSet()) check(commonLetters.size == 1) val commonLetter = commonLetters.first() totalPriority += letterValue(commonLetter) } return totalPriority } 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
77795045bc8e800190f00cd2051fe93eebad2aec
1,337
adventofcode2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/GetMaximumGold.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 1219. Path with Maximum Gold * @see <a href="https://leetcode.com/problems/path-with-maximum-gold/">Source</a> */ fun interface GetMaximumGold { operator fun invoke(grid: Array<IntArray>): Int } class GetMaximumGoldBacktracking : GetMaximumGold { private val dir = intArrayOf(0, 1, 0, -1, 0) override operator fun invoke(grid: Array<IntArray>): Int { if (grid.isEmpty() || grid.first().isEmpty()) return 0 val m: Int = grid.size val n: Int = grid.first().size var maxGold = 0 for (r in 0 until m) for (c in 0 until n) { maxGold = max(maxGold, findMaxGold(grid, m, n, r, c)) } return maxGold } private fun findMaxGold(grid: Array<IntArray>, m: Int, n: Int, r: Int, c: Int): Int { val left = r < 0 || r == m || c < 0 if (left || c == n || grid[r][c] == 0) return 0 val origin = grid[r][c] grid[r][c] = 0 // mark as visited var maxGold = 0 for (i in 0..3) { maxGold = max(maxGold, findMaxGold(grid, m, n, dir[i] + r, dir[i + 1] + c)) } grid[r][c] = origin // backtrack return maxGold + origin } } class GetMaximumGoldDFS : GetMaximumGold { override operator fun invoke(grid: Array<IntArray>): Int { if (grid.isEmpty()) return 0 val m: Int = grid.size val n: Int = grid[0].size val max = IntArray(1) for (i in 0 until m) { for (j in 0 until n) { if (grid[i][j] != 0) { dfs(grid, i, j, 0, max) } } } return max[0] } private fun dfs(grid: Array<IntArray>, i: Int, j: Int, currSum: Int, max: IntArray) { val left = i < 0 || j < 0 || i >= grid.size if (left || j >= grid[0].size || grid[i][j] == 0) { max[0] = max(max[0], currSum) return } val temp = grid[i][j] grid[i][j] = 0 dfs(grid, i - 1, j, currSum + temp, max) dfs(grid, i + 1, j, currSum + temp, max) dfs(grid, i, j - 1, currSum + temp, max) dfs(grid, i, j + 1, currSum + temp, max) grid[i][j] = temp } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,864
kotlab
Apache License 2.0
src/Day07.kt
risboo6909
572,912,116
false
{"Kotlin": 66075}
const val TOTAL_SPACE = 70_000_000 const val SPACE_NEEDED = 30_000_000 enum class NodeType { DIR, FILE, } class INode(val type: NodeType, val name: String, var size: Int, val parent: INode?, val children: MutableSet<INode>?) { fun attachNode(node: INode): Boolean { if (this.type == NodeType.FILE) { throw Exception("can't add children to file: ${this.name}") } // check if node doesn't exists this.children?.forEach { if (it.name == node.name) { return false } } this.children!!.add(node) return true } } fun main() { fun findDir(curDir: INode, dirName: String): INode { curDir.children?.filter{it.type == NodeType.DIR && it.name == dirName}?.forEach { return it } return curDir } fun updateSizes(_curDir: INode?, size: Int) { // update sizes for parents var curDir = _curDir while (curDir != null) { curDir.size += size curDir = curDir.parent } } fun buildHier(input: List<String>): INode { val root = INode(NodeType.DIR, "/", 0, null, mutableSetOf()) var curDir = root for (line in input) { if (line.startsWith("$ cd")) { val (_, _, dirName) = line.split(' ') curDir = if (dirName == "..") { curDir.parent } else { findDir(curDir, dirName) }!! continue } if (!line.startsWith("$")) { val (something, name) = line.split(" ") if (something == "dir") { curDir.attachNode(INode(NodeType.DIR, name, 0, curDir, mutableSetOf())) continue } val size = something.toInt() if (curDir.attachNode(INode(NodeType.FILE, name, size, curDir, null))) { updateSizes(curDir, size) } } } return root } fun part1(input: List<String>): Int { fun inner(curNode: INode): Int { val acc = curNode.children!!.filter{it.type == NodeType.DIR}.sumOf { inner(it) } if (curNode.size < 100_000) { return acc + curNode.size } return acc } return inner(buildHier(input)) } fun part2(input: List<String>): Int { val root = buildHier(input) val spaceLeft = TOTAL_SPACE - root.size val spaceReq = SPACE_NEEDED - spaceLeft fun inner(curNode: INode): Int { var minFound = Int.MAX_VALUE curNode.children!!.filter{it.type == NodeType.DIR}.forEach { minFound = minOf(inner(it), minFound) if (it.size in spaceReq until minFound) { minFound = it.size } } return minFound } return inner(root) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bd6f9b46d109a34978e92ab56287e94cc3e1c945
3,327
aoc2022
Apache License 2.0
src/day21/Day21.kt
HGilman
572,891,570
false
{"Kotlin": 109639, "C++": 5375, "Python": 400}
package day21 import readInput import kotlin.math.abs val addOp = { a: Long, b: Long -> a + b } val subtractOp = { a: Long, b: Long -> a - b } val multiplyOp = { a: Long, b: Long -> a * b } val divideOp = { a: Long, b: Long -> a / b } val symbolToOp = mapOf( '+' to addOp, '-' to subtractOp, '*' to multiplyOp, '/' to divideOp ) sealed class Operand(val name: String) class SimpleOperand(name: String, var num: Long) : Operand(name) class CompositeOperand( name: String, val leftOperandName: String, val rightOperandName: String, opChar: Char ) : Operand(name) { val operation = symbolToOp[opChar]!! } fun calcOperand(operand: String, allOperands: Map<String, Operand>): Long { val op = allOperands[operand]!! return when (op) { is SimpleOperand -> op.num is CompositeOperand -> { op.operation(calcOperand(op.leftOperandName, allOperands), calcOperand(op.rightOperandName, allOperands)) } } } fun main() { val day = 21 val testInput = readInput("day$day/testInput") check(part1(testInput) == 152L) // check(part2(testInput) == 301L) val input = readInput("day$day/input") // println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Long { val opRegexp = """([a-z]{4}) ([+\-*/]) ([a-z]{4})""".toRegex() val operands: List<Operand> = input.map { line -> val operandName = line.substringBefore(":") val secondPart = line.substringAfter(": ") if (secondPart.matches(opRegexp)) { val (_, leftOpName, opChar, rightOpName) = opRegexp.find(secondPart)!!.groupValues CompositeOperand(operandName, leftOpName, rightOpName, opChar.first()) } else { SimpleOperand(operandName, secondPart.toLong()) } } val operandsMap = operands.associateBy { it.name } val res = calcOperand("root", operandsMap) return res } fun part2(input: List<String>): Long { val opRegexp = """([a-z]{4}) ([+\-*/]) ([a-z]{4})""".toRegex() val operands: List<Operand> = input.map { line -> val operandName = line.substringBefore(":") val secondPart = line.substringAfter(": ") if (secondPart.matches(opRegexp)) { val (_, leftOpName, opChar, rightOpName) = opRegexp.find(secondPart)!!.groupValues CompositeOperand(operandName, leftOpName, rightOpName, opChar.first()) } else { SimpleOperand(operandName, secondPart.toLong()) } } val operandsMap = operands.associateBy { it.name } fun calcRootDiff(): Long { val rootOperand = operandsMap["root"] as CompositeOperand val leftResult = calcOperand(rootOperand.leftOperandName, operandsMap) val rightResult = calcOperand(rootOperand.rightOperandName, operandsMap) return rightResult - leftResult } var coeficient = 50 val humnOperand = (operandsMap["humn"]!! as SimpleOperand) var diff = calcRootDiff() var counter = 1 while (diff != 0L) { println("counter: $counter, humn: ${humnOperand.num}, diff: $diff") if (abs(diff) < coeficient) { coeficient /= 2 } val newHumn1 = if (diff == 1L) humnOperand.num - diff else humnOperand.num - diff / coeficient val newHumn2 = if (diff == 1L) humnOperand.num + diff else humnOperand.num + diff / coeficient // setting new humn to humn1 humnOperand.num = newHumn1 val diff1 = calcRootDiff() // setting new humn to humn2 humnOperand.num = newHumn2 val diff2 = calcRootDiff() if (abs(diff1) < abs(diff2)) { diff = diff1 humnOperand.num = newHumn1 } else { diff = diff2 humnOperand.num = newHumn2 } counter++ } val res = humnOperand.num return res }
0
Kotlin
0
1
d05a53f84cb74bbb6136f9baf3711af16004ed12
3,894
advent-of-code-2022
Apache License 2.0
baparker/09/main.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File data class Node(val value: Int) { var visited = false } data class Counter(var value: Int) { fun incCounter() { this.value++ } } fun findMins( heightMatrix: MutableList<MutableList<Node>>, x: Int, y: Int, ) { val current = heightMatrix.get(y).get(x).value listOf(listOf(x - 1, y), listOf(x + 1, y), listOf(x, y - 1), listOf(x, y + 1)).forEach { val xIndex = it.get(0) val yIndex = it.get(1) val newPoint = heightMatrix.getOrNull(yIndex)?.getOrNull(xIndex) if (newPoint != null) { if (newPoint.value <= current) { heightMatrix.get(y).get(x).visited = true if (!newPoint.visited) { findMins( heightMatrix, xIndex, yIndex, ) } } else { if (!newPoint.visited) { heightMatrix.get(yIndex).get(xIndex).visited = true } } } } } fun findBasins(heightMatrix: MutableList<MutableList<Node>>, x: Int, y: Int, counter: Counter) { heightMatrix.get(y).get(x).visited = true counter.incCounter() listOf(listOf(x - 1, y), listOf(x + 1, y), listOf(x, y - 1), listOf(x, y + 1)).forEach { val xIndex = it.get(0) val yIndex = it.get(1) val newPoint = heightMatrix.getOrNull(yIndex)?.getOrNull(xIndex) if (newPoint != null) { if (newPoint.value != 9 && !newPoint.visited) { findBasins(heightMatrix, xIndex, yIndex, counter) } } } } fun main() { val heightMatrixMins: MutableList<MutableList<Node>> = mutableListOf() val heightMatrixBasins: MutableList<MutableList<Node>> = mutableListOf() File("input.txt").forEachLine { heightMatrixMins.add(it.map { Node(it.digitToInt()) }.toMutableList()) heightMatrixBasins.add(it.map { Node(it.digitToInt()) }.toMutableList()) } heightMatrixMins.forEachIndexed { y, heightRow -> heightRow.forEachIndexed { x, height -> if (!height.visited) { findMins(heightMatrixMins, x, y) } } } println( heightMatrixMins.flatten().fold(0) { sum, height -> if (!height.visited) sum + height.value + 1 else sum } ) val counterList: MutableList<Int> = mutableListOf() var counter = Counter(0) heightMatrixBasins.forEachIndexed { y, heightRow -> heightRow.forEachIndexed { x, height -> if (height.value != 9 && !height.visited) { findBasins(heightMatrixBasins, x, y, counter) counterList.add(counter.value) counter.value = 0 } } } println( counterList.sortedDescending().subList(0, 3).fold(1) { product, count -> product * count } ) }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
3,008
advent-of-code-2021
MIT License
src/Day02.kt
rxptr
572,717,765
false
{"Kotlin": 9737}
enum class Hand(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); infix fun draw(other: Hand): Hand? { if (beats[this] == other) return this if (beatenBy[this] == other) return other return null } infix fun expect(outcome: Outcome) : Hand { if (outcome == Outcome.First) return beats[this]!! if (outcome == Outcome.Second) return beatenBy[this]!! return this } companion object { val beats = mapOf( ROCK to SCISSORS, SCISSORS to PAPER, PAPER to ROCK ) val beatenBy = mapOf( SCISSORS to ROCK, ROCK to PAPER, PAPER to SCISSORS ) fun fromInput(char: Char): Hand = when (char) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> throw Exception("Invalid Input [$char]") } } } enum class Outcome { First, Second, Tie; companion object { fun fromInput(char: Char) : Outcome = when(char) { 'X' -> First 'Y' -> Tie 'Z' -> Second else -> throw Exception("Invalid Input [$char]") } } } data class DesiredOutcome(val hand: Hand, val outcome: Outcome) class Game(moves: List<Pair<Hand, Hand>>) { private var opponentScore = 0 var playerScore = 0 private set private val winnerScore = 6 private val tieScore = 3 init { moves.forEach { val outcome = winnerSide(it.first, it.second) var opponentPoints = 0 var playerPoints = 0 when (outcome) { Outcome.First -> opponentPoints += winnerScore Outcome.Second -> playerPoints += winnerScore else -> { opponentPoints += tieScore playerPoints += tieScore } } opponentPoints += it.first.score playerPoints += it.second.score opponentScore += opponentPoints playerScore += playerPoints } } private fun winnerSide(first: Hand, second: Hand): Outcome = when (first draw second) { first -> Outcome.First second -> Outcome.Second else -> Outcome.Tie } } fun main() { fun parsInputAsPairOfHands(input: List<String>): List<Pair<Hand, Hand>> = input.map { val chars = it.toCharArray() Pair(Hand.fromInput(chars[0]), Hand.fromInput(chars[2])) } fun parsInputAsDesiredOutcome(input: List<String>): List<DesiredOutcome> = input.map { val chars = it.toCharArray() DesiredOutcome(Hand.fromInput(chars[0]), Outcome.fromInput(chars[2])) } fun part1(input: List<String>): Int = Game(parsInputAsPairOfHands(input)).playerScore fun part2(input: List<String>): Int { val moves = parsInputAsDesiredOutcome(input).map { Pair(it.hand, it.hand expect it.outcome) } return Game(moves).playerScore } val testInput = readInputLines("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInputLines("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
989ae08dd20e1018ef7fe5bf121008fa1c708f09
3,258
aoc2022
Apache License 2.0
src/day10/Day10.kt
martinhrvn
724,678,473
false
{"Kotlin": 27307, "Jupyter Notebook": 1336}
package day10 import readInput typealias Coord = Pair<Int,Int> enum class Direction(val coord: Coord) { LEFT(Pair(-1, 0)), RIGHT(Pair(1, 0)), TOP(Pair(0, -1)), BOTTOM(Pair(0, 1)) } val rightConnectable = listOf('-', 'F', 'L', 'S') val leftConnectable = listOf('-', '7', 'J', 'S') val bottomConnectable = listOf('|', 'F', '7', 'S') val topConnectable = listOf('|', 'J', 'L', 'S') data class Day10(val input: List<String>){ val map = input.flatMapIndexed { y, row -> row.mapIndexed() { x,cell -> Pair(x, y) to cell}}.toMap() val start = map.filter { it.value == 'S' }.keys.first() val explored = mutableSetOf<Coord>() fun startFindingLoop(coord: Coord): List<Coord> { return getConnectedNeighbor(coord).firstNotNullOf { explored.add(coord) getChain(it, listOf()) } } fun getChain(coord: Coord, chain: List<Coord>): List<Coord>? { var currentCoord = coord var currentChain = chain while (true) { val connections = getConnectedNeighbor(currentCoord) val con = connections.filter { it !in explored } if (connections.contains(start) && con.isEmpty()) { return currentChain } else if (con.isEmpty()) { return null } else { explored.add(currentCoord) currentChain = currentChain + currentCoord currentCoord = con.first() } } } fun getConnectedNeighbor(coord: Coord): List<Coord> { val (x,y) = coord val pipe = map[coord] val neighbors = listOf(Direction.LEFT, Direction.RIGHT, Direction.TOP, Direction.BOTTOM).mapNotNull { dir -> val neighbor = map[Pair(x + dir.coord.first, y + dir.coord.second)] neighbor?.let { if (isConnected(pipe!!, neighbor, dir)) { Pair(x + dir.coord.first, y + dir.coord.second) } else null } } return neighbors } fun isConnected(pipe: Char, other: Char, direction: Direction): Boolean { if (direction == Direction.LEFT && pipe in leftConnectable && other in rightConnectable) { return true } else if (direction == Direction.RIGHT && pipe in rightConnectable && other in leftConnectable) { return true } else if (direction == Direction.TOP && pipe in topConnectable && other in bottomConnectable) { return true } else if (direction == Direction.BOTTOM && pipe in bottomConnectable && other in topConnectable) { return true } return false } fun part1(): Long { return ((startFindingLoop(start).size + 1) / 2 + 1).toLong() } fun part2(): Long { return 0 } } fun main() { val day10 = Day10(readInput("day10/Day10")) println(day10.part1()) println(day10.part2()) }
0
Kotlin
0
0
59119fba430700e7e2f8379a7f8ecd3d6a975ab8
2,988
advent-of-code-2023-kotlin
Apache License 2.0