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
examples/src/main/kotlin/Coins.kt
alexbaryzhikov
201,620,351
false
null
import com.alexb.constraints.Problem import com.alexb.constraints.core.constraints.ExactSumConstraint import kotlin.system.measureTimeMillis /* 100 coins must sum to $5.00 That's kind of a country-specific problem, since depending on the country there are different values for coins. Here is presented the solution for a given set. */ fun coins(): Pair<List<Map<String, Int>>, List<String>> { fun Double.round(n: Int): Double { var m = 1.0 repeat(n) { m *= 10 } return kotlin.math.round(this * m) / m } val total = 5.0 val variables = listOf("0.01", "0.05", "0.10", "0.50", "1.00") val values = variables.map { it.toDouble() } val problem = Problem<String, Int>().apply { for ((variable, value) in variables.zip(values)) { addVariable(variable, (0..(total / value).toInt()).toList()) } addConstraint(ExactSumConstraint(100)) addConstraint({ amounts -> var sum = 0.0 for ((value, amount) in values.zip(amounts)) { sum += value * amount sum = sum.round(2) } sum == 5.0 }, variables) } val solutions = problem.getSolutions() return Pair(solutions, variables) } fun main() { lateinit var result: Pair<List<Map<String, Int>>, List<String>> val t = measureTimeMillis { result = coins() } println("Found ${result.first.size} solution(s) in $t ms\n") val (solutions, variables) = result for ((i, solution) in solutions.withIndex()) { print(String.format("Solution %03d: ", i + 1)) for (v in variables) { print("${v}x${solution[v]}, ") } println() } }
0
Kotlin
0
0
e67ae6b6be3e0012d0d03988afa22236fd62f122
1,709
kotlin-constraints
Apache License 2.0
src/Day11.kt
jwalter
573,111,342
false
{"Kotlin": 19975}
import java.math.BigInteger class Monkey( val items: MutableList<BigInteger>, val operation: (BigInteger) -> BigInteger, val testValue: Int, val router: (Boolean) -> Int ) { var inspections: Long = 0 fun play() { inspections += items.size items.forEach { println(" Inspect $it") var i = operation(it) println(" Worry level updated to $i") i = i.mod(divideBy.toBigInteger()) println(" Divided by three to $i") val divisible = i.mod(testValue.toBigInteger()) == 0.toBigInteger() val n = router(divisible) println(" Item with worry level $i thrown to monkey $n") monkeys[n].accept(i) } items.clear() } fun accept(item: BigInteger) = items.add(item) } var monkeys = mutableListOf<Monkey>() var divideBy = 3 fun main() { fun part1(input: List<String>): BigInteger { monkeys = mutableListOf( Monkey( mutableListOf(56, 56, 92, 65, 71, 61, 79).big(), { it * 7.toBigInteger() }, 3, { if (it) 3 else 7 } ), Monkey( mutableListOf(61,85).big(), { it + 5.toBigInteger() }, 11, { if (it) 6 else 4 } ), Monkey( mutableListOf(54, 96, 82, 78, 69).big(), { it * it }, 7, { if (it) 0 else 7 } ), Monkey( mutableListOf(57, 59, 65, 95).big(), { it + 4.toBigInteger() }, 2, { if (it) 5 else 1 } ), Monkey( mutableListOf(62, 67, 80).big(), { it * 17.toBigInteger() }, 19, { if (it) 2 else 6 } ), Monkey( mutableListOf(91).big(), { it + 7.toBigInteger() }, 5, { if (it) 1 else 4 } ), Monkey( mutableListOf(79, 83, 64, 52, 77, 56, 63, 92).big(), { it + 6.toBigInteger() }, 17, { if (it) 2 else 0 } ), Monkey( mutableListOf(50, 97, 76, 96, 80, 56).big(), { it + 3.toBigInteger() }, 13, { if (it) 3 else 5 } ) ) divideBy = monkeys.map { it.testValue }.reduce(Math::multiplyExact) repeat(10000) { _ -> monkeys.forEachIndexed { idx, m -> println("Monkey $idx:") m.play() } println() monkeys.forEachIndexed { idx, m -> println("Monkey $idx: ${m.items}") } println() } monkeys.sortByDescending { it.inspections } return monkeys.take(2).map{it.inspections}.reduce(Math::multiplyExact).toBigInteger() } fun part2(input: List<String>): BigInteger { return 2.toBigInteger() } val testInput = readInput("Day11_test") //check(part1(testInput) == 10605) //check(part2(testInput) == 2) val input = readInput("Day11") println(part1(input)) //println(part2(input)) } private fun List<Int>.big(): MutableList<BigInteger> { return this.map { it.toBigInteger() }.toMutableList() }
0
Kotlin
0
0
576aeabd297a7d7ee77eca9bb405ec5d2641b441
3,453
adventofcode2022
Apache License 2.0
src/day20/Day20.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day20 import readInput fun main() { fun simulate(input: List<Pair<Int, Long>>, factor: Long = 1L, iterations: Int = 1): Long { val inputFactorized = input.map { it.first to it.second * factor } val list = inputFactorized.toMutableList() repeat(iterations) { inputFactorized.forEach { val index = list.indexOf(it) list.removeAt(index) list.add((index + it.second).mod(list.size), it) } } val zeroPos = list.indexOfFirst { it.second == 0L } return listOf(1000, 2000, 3000).sumOf { list[(zeroPos + it) % list.size].second } } fun part1(input: List<Pair<Int, Long>>) = simulate(input).toInt() fun part2(input: List<Pair<Int, Long>>) = simulate(input, 811589153L, 10) fun preprocess(input: List<String>): List<Pair<Int, Long>> = input.mapIndexed { index, s -> index to s.toLong() } // test if implementation meets criteria from the description, like: val testInput = readInput(20, true) check(part1(preprocess(testInput)) == 3) val input = readInput(20) println(part1(preprocess(input))) check(part2(preprocess(testInput)) == 1623178306L) println(part2(preprocess(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
1,256
advent-of-code-2022
Apache License 2.0
src/Day04.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
fun main() { fun readAssignmentPairs(input: List<String>): List<Pair<IntRange, IntRange>> = input.map { line -> line.split(',').map { range -> val (from, to) = range.split('-').map { it.toInt() } from..to }.toPair() } fun IntRange.isFullyContainedWithin(other: IntRange) = first >= other.first && last <= other.last fun IntRange.hasOverlap(other: IntRange) = first in other || last in other || other.first in this || other.last in this fun part1(input: List<String>): Int = readAssignmentPairs(input).count { (fst, snd) -> fst.isFullyContainedWithin(snd) || snd.isFullyContainedWithin(fst) } fun part2(input: List<String>): Int = readAssignmentPairs(input).count { (fst, snd) -> fst.hasOverlap(snd) } // 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
afbcec6a05b8df34ebd8543ac04394baa10216f0
1,042
advent-of-code-22
Apache License 2.0
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day14.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2020 import nl.dirkgroot.adventofcode.util.Input import nl.dirkgroot.adventofcode.util.Puzzle class Day14(input: Input) : Puzzle() { private interface Instruction private class SetMask(val xMask: Long, val nMask: Long) : Instruction private class SetMem(val address: Long, val value: Long) : Instruction private val program by lazy { input.lines().map { when { it.startsWith("mask") -> parseMask(it) else -> parseMem(it) } } } private fun parseMask(mask: String) = mask.drop(7).let { maskValue -> val xMask = maskValue.replace('1', '0').replace('X', '1') val nMask = maskValue.replace('X', '0') SetMask(xMask.toLong(2), nMask.toLong(2)) } private fun parseMem(mem: String) = "mem\\[(\\d+)] = (\\d+)".toRegex().matchEntire(mem)!!.let { match -> SetMem(match.groupValues[1].toLong(), match.groupValues[2].toLong()) } override fun part1() = sumOfMemory(::setMemWithMaskedValue) private fun setMemWithMaskedValue(setMask: SetMask, setMem: SetMem) = sequenceOf(SetMem(setMem.address, (setMem.value and setMask.xMask) or setMask.nMask)) override fun part2() = sumOfMemory(::setMemPermutations) private fun setMemPermutations(mask: SetMask, instruction: SetMem) = (instruction.address and mask.xMask.inv()) .let { fixedBits -> addressPermutations(mask).map { address -> fixedBits or mask.nMask or address } } .map { SetMem(it, instruction.value) } private fun addressPermutations(mask: SetMask) = generateSequence(mask.xMask) { prev -> if (prev > 0) (prev - 1) and mask.xMask else null } private fun sumOfMemory(setMemInstructions: (SetMask, SetMem) -> Sequence<SetMem>) = program .runningFold(SetMask(0, 0) to sequenceOf<SetMem>()) { (mask, previous), next -> when (next) { is SetMask -> next to previous is SetMem -> mask to setMemInstructions(mask, next) else -> throw IllegalStateException() } } .flatMap { (_, instructions) -> instructions } .groupBy { it.address } .entries.map { (_, instructions) -> instructions.last().value } .sum() }
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
2,318
adventofcode-kotlin
MIT License
datastructures/src/main/kotlin/com/kotlinground/datastructures/arrays/intersectionofarrays/intersectionOfArrays.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.datastructures.arrays.intersectionofarrays fun setIntersection(setOne: Set<Int>, setTwo: Set<Int>): IntArray { return setOne.intersect(setTwo).toIntArray() } /** * Returns the intersection of two arrays. Uses a set to solve the problem in linear time. A set provides in/contains * operation in O(1) time in average case. This converts both arrays to sets and iterates over the smallest set * checking the presence of each element in the other larger set. The time complexity is O(n+m) where n is the size of * the first array and m is the size of the second array. */ fun intersectionOne(nums1: IntArray, nums2: IntArray): IntArray { val setOne = nums1.toSet() val setTwo = nums2.toSet() return if (setOne.size < setTwo.size) { setIntersection(setOne, setTwo) } else { setIntersection(setTwo, setOne) } } fun intersectionTwo(nums1: IntArray, nums2: IntArray): IntArray { val counter = hashMapOf<Int, Int>() val result = arrayListOf<Int>() nums1.forEach { counter[it] = counter.getOrDefault(it, 0) + 1 } nums2.forEach { if (counter.containsKey(it) && counter[it]!! > 0) { result.add(it) counter[it] = counter[it]!! - 1 } } return result.toIntArray() }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
1,292
KotlinGround
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxUncrossedLines.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <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 /** * Uncrossed Lines * @see <a href="https://leetcode.com/problems/uncrossed-lines/">Source</a> */ fun interface UncrossedLines { fun maxUncrossedLines(nums1: IntArray, nums2: IntArray): Int } /** * Approach 1: Recursive Dynamic Programming */ class UncrossedLinesRecursiveDP : UncrossedLines { override fun maxUncrossedLines(nums1: IntArray, nums2: IntArray): Int { val n1: Int = nums1.size val n2: Int = nums2.size val memo = Array(n1 + 1) { IntArray(n2 + 1) { -1 } } return solve(n1, n2, nums1, nums2, memo) } private fun solve(i: Int, j: Int, nums1: IntArray, nums2: IntArray, memo: Array<IntArray>): Int { if (i <= 0 || j <= 0) { return 0 } if (memo[i][j] != -1) { return memo[i][j] } if (nums1[i - 1] == nums2[j - 1]) { memo[i][j] = 1 + solve(i - 1, j - 1, nums1, nums2, memo) } else { memo[i][j] = max(solve(i, j - 1, nums1, nums2, memo), solve(i - 1, j, nums1, nums2, memo)) } return memo[i][j] } } /** * Approach 2: Iterative Dynamic Programming */ class UncrossedLinesIterativeDP : UncrossedLines { override fun maxUncrossedLines(nums1: IntArray, nums2: IntArray): Int { val n1: Int = nums1.size val n2: Int = nums2.size val dp = Array(n1 + 1) { IntArray(n2 + 1) } for (i in 1..n1) { for (j in 1..n2) { if (nums1[i - 1] == nums2[j - 1]) { dp[i][j] = 1 + dp[i - 1][j - 1] } else { dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]) } } } return dp[n1][n2] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,374
kotlab
Apache License 2.0
src/main/kotlin/org/example/adventofcode/puzzle/Day04.kt
peterlambrechtDev
573,146,803
false
{"Kotlin": 39213}
package org.example.adventofcode.puzzle import org.example.adventofcode.util.FileLoader class Range(private val beginning: Int, private val ending: Int) { fun fullyOverlap(range: Range): Boolean { return (beginning <= range.beginning && ending >= range.ending) } fun partialOverlap(range: Range): Boolean { return (range.beginning in beginning..ending || range.ending in beginning..ending) } } object Day04 { fun part1(filePath: String): Int { val stringLines = FileLoader.loadFromFile<String>(filePath) val pairs = createPairs(stringLines) var count = 0 pairs.forEach { if (it.first.fullyOverlap(it.second) || it.second.fullyOverlap(it.first)) count++ } return count } private fun createPairs( stringLines: List<String> ): List<Pair<Range, Range>> { val pairs = mutableListOf<Pair<Range, Range>>() for (line in stringLines) { val assignments = line.trim().split(",") val firstAssignment = assignments[0].split("-") val secondAssignment = assignments[1].split("-") pairs.add( Pair( Range(firstAssignment.first().toInt(), firstAssignment.last().toInt()), Range(secondAssignment.first().toInt(), secondAssignment.last().toInt()) ) ) } return pairs } fun part2(filePath: String): Int { val stringLines = FileLoader.loadFromFile<String>(filePath) val pairs = createPairs(stringLines) var count = 0 pairs.forEach { if (it.first.partialOverlap(it.second) || it.second.partialOverlap(it.first)) count++ } return count } } fun main() { val day = "day04" val dayObj = Day04 println("Example 1: ${dayObj.part1("/${day}_example.txt")}") println("Solution 1: ${dayObj.part1("/${day}.txt")}") println("Example 2: ${dayObj.part2("/${day}_example.txt")}") println("Solution 2: ${dayObj.part2("/${day}.txt")}") }
0
Kotlin
0
0
aa7621de90e551eccb64464940daf4be5ede235b
2,048
adventOfCode2022
MIT License
src/Day07.kt
OskarWalczak
573,349,185
false
{"Kotlin": 22486}
class TreeNode(val name: String) { var size: Int = 0 var parent: TreeNode? = null val children: MutableList<TreeNode> = ArrayList() val files: MutableMap<String, Int> = HashMap() fun addToSize(num: Int){ size += num parent?.addToSize(num) } } fun main() { var root = TreeNode("/") fun executeCommand(command: String, currentNode: TreeNode): TreeNode{ var com = command.substring(2) var curr = currentNode if(com.startsWith("cd")){ com = com.substring(3).trim() if(com == ".."){ if(curr.parent != null) curr = curr.parent!! } else if(com == "/"){ curr = root } else { val child = curr.children.find { node -> node.name == com } if(child != null) curr = child } } return curr } fun readInputIntoTree(input: List<String>){ root = TreeNode("/") var currentNode = root input.forEach { line -> if(line.startsWith("$")) { currentNode = executeCommand(line, currentNode) } else if(line.startsWith("dir")){ val dirname = line.substring(4).trim() val newNode = TreeNode(dirname) newNode.parent = currentNode currentNode.children.add(newNode) } else { val fileInfo = line.split(' ') if(fileInfo.first().toIntOrNull() != null){ currentNode.files[fileInfo.last()] = fileInfo.first().toInt() currentNode.addToSize(fileInfo.first().toInt()) } } } } fun part1(input: List<String>): Int { readInputIntoTree(input) val sizeLimit = 100000 var sizeSum = 0 fun checkChildren(node: TreeNode){ if(node.size <= sizeLimit) sizeSum += node.size node.children.forEach { child -> checkChildren(child) } } checkChildren(root) return sizeSum } fun part2(input: List<String>): Int { val spaceNeeded = 30000000 - (70000000 - root.size) var currentSize = root.size fun checkChildren(node: TreeNode){ if(node.size in spaceNeeded until currentSize) currentSize = node.size node.children.forEach { child -> checkChildren(child) } } checkChildren(root) return currentSize } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d34138860184b616771159984eb741dc37461705
2,919
AoC2022
Apache License 2.0
src/Day25.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
fun main() { fun part1(input: List<String>): String { return input.map { SnafuNumber(it) }.reduce{ num1, num2 -> num1.add(num2) }.toString() } // fun part2(input: List<String>): String { // return input.size // } val testInput = readInput("Day25_test") check(part1(testInput) == "2=-1=0") val input = readInput("Day25") println(part1(input)) // println(part2(input)) } data class SnafuNumber( val digits: List<SnafuDigit> ) { constructor(number: String) : this(number.map { SnafuDigit(it) }.reversed()) fun add (other: SnafuNumber): SnafuNumber { val result = mutableListOf<SnafuDigit>() var overflow = SnafuDigit(0) val maxIndex = maxOf(this.digits.size, other.digits.size) // (max index + 1 is intended to account for overflow in last digit) for(i in 0 .. maxIndex) { val digit1 = if (i < this.digits.size) this.digits[i] else SnafuDigit(0) val digit2 = if (i < other.digits.size) other.digits[i] else SnafuDigit(0) val digitResult = digit1.add(digit2, overflow) result.add(digitResult.result) overflow = digitResult.overflow } // Trim trailing 0's while (result[result.size-1].value == 0) { result.removeAt(result.size-1) } return SnafuNumber(result.toList()) } override fun toString(): String { return digits.map { it.toString() }.reversed().joinToString("") } } data class SnafuDigit( val value: Int ) { init { require(value in -2 .. 2) } constructor(digit: Char) : this(when(digit) { '2' -> 2 '1' -> 1 '0' -> 0 '-' -> -1 '=' -> -2 else -> throw IllegalArgumentException("Unknown SnafuDigit: $digit") }) fun add(other1: SnafuDigit, other2: SnafuDigit = SnafuDigit(0)): SnafuDigitResult { var result = this.value + other1.value + other2.value var overflow = 0 if (result < -2) { result += 5 overflow-- } else if (result > 2) { result -= 5 overflow++ } return SnafuDigitResult(SnafuDigit(result), SnafuDigit(overflow)) } override fun toString(): String { return when(value) { 2 -> "2" 1 -> "1" 0 -> "0" -1 -> "-" -2 -> "=" else -> throw IllegalArgumentException("Unknown value for SnafuDigit: $value") } } } data class SnafuDigitResult( val result: SnafuDigit, val overflow: SnafuDigit )
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
2,609
aoc2022
Apache License 2.0
src/main/kotlin/Day23.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List import Day17.Coordinate import java.util.* import kotlin.math.max object Day23 { /** * A more compact representation of a path than a list of coordinates. */ data class Segment(val steps: Int, val start: Coordinate, val end: Coordinate) fun part1(input: List<String>): String { val startIndex = input[0].indexOf(".") val endIndex = input.last().indexOf(".") val startCoordinate = Coordinate(startIndex, 0) val endCoordinate = Coordinate(endIndex, input.size - 1) return maxSteps(startCoordinate, startCoordinate, endCoordinate, input, 0).toString() } data class StepInformation( val node: Segment, val visited: Set<Segment>, val steps: Int ) private fun maxStepsExpanded( start: Segment, end: Segment, nodes: Set<Segment>, input: List<String> ): Int { val queue = PriorityQueue<StepInformation> { a, b -> -a.steps.compareTo(b.steps) } queue.add(StepInformation(start, setOf(start), start.steps)) val startMap = nodes.associate { it.start to it } val endMap = nodes.associate { it.end to it } val nodeBeforeExit = getNeighbors(end.start, input).map { it.first }.filter { it in endMap } .map { endMap[it] }.filterNotNull().distinct().first() var max = 0 var count = 0 val startMemo = mutableMapOf<Segment, List<Segment>>() val endMemo = mutableMapOf<Segment, List<Segment>>() while (queue.isNotEmpty()) { count++ if (count % 1000000 == 0) { println("Count: $count, queue size: ${queue.size}, current max: $max") } val stepInformation = queue.poll() val node = stepInformation.node val steps = stepInformation.steps val visited = stepInformation.visited if (node == end) { max = max(steps, max) continue } if (nodeBeforeExit in visited) { continue } val startNeighbors = startMemo.getOrPut(node) { getNeighbors(node.start, input).map { it.first }.filter { it in endMap } .map { endMap[it]!! } }.filter { it !in visited } val endNeighbors = endMemo.getOrPut(node) { getNeighbors(node.end, input).map { it.first }.filter { it in startMap } .map { startMap[it]!! } }.filter { it !in visited } queue.addAll( (startNeighbors + endNeighbors).distinct() .map { StepInformation(it, visited + node, steps + it.steps) }) } return max } private tailrec fun maxSteps( previousCoordinate: Coordinate, currentCoordinate: Coordinate, endCoordinate: Coordinate, input: List<String>, currentSteps: Int ): Int { if (currentCoordinate == endCoordinate) { return currentSteps } val nextCoordinates = getNeighborsDirectionally(previousCoordinate, currentCoordinate, input) val nextOpenSpace = nextCoordinates.find { it.second == '.' } if (nextOpenSpace != null) { return maxSteps( currentCoordinate, nextOpenSpace.first, endCoordinate, input, currentSteps + 1 ) } return nextCoordinates.maxOf { maxSteps(currentCoordinate, it.first, endCoordinate, input, currentSteps + 1) } } fun part2(input: List<String>): String { val startIndex = input[0].indexOf(".") val endIndex = input.last().indexOf(".") val startCoordinate = Coordinate(startIndex, 0) val endCoordinate = Coordinate(endIndex, input.size - 1) val nodes = buildSegments(startCoordinate, endCoordinate, input, 0) val start = nodes.find { it.start == startCoordinate } return maxStepsExpanded(start!!, nodes.find { it.end == endCoordinate }!!, nodes, input).toString() } data class SegmentBuildingInformation( val coordinate: Coordinate, val previousCoordinate: Coordinate, val steps: Int, val runningSegment: Segment ) private fun buildSegments( startCoordinate: Coordinate, endCoordinate: Coordinate, input: List<String>, length: Int ): Set<Segment> { val queue = ArrayDeque<SegmentBuildingInformation>() queue.add( SegmentBuildingInformation( startCoordinate, startCoordinate, length, Segment(length, startCoordinate, startCoordinate) ) ) val segments = mutableSetOf<Segment>() while (queue.isNotEmpty()) { val stepInformation = queue.poll() val currentCoordinate = stepInformation.coordinate val previousCoordinate = stepInformation.previousCoordinate val length = stepInformation.steps val runningNode = stepInformation.runningSegment if (currentCoordinate == endCoordinate) { val updatedNode = runningNode.copy(end = endCoordinate, steps = length) if (updatedNode !in segments) { segments.add(updatedNode) } } val nextCoordinates = getNeighborsDirectionally(previousCoordinate, currentCoordinate, input) val nextOpenSpace = nextCoordinates.find { it.second == '.' } if (nextOpenSpace != null) { val currentCharacter = input[currentCoordinate.y][currentCoordinate.x] // We have to treat >, < etc as their own segment because otherwise we can lead to duplicate counting if (currentCharacter != '.') { val updatedNode = runningNode.copy(end = currentCoordinate, steps = length) if (updatedNode !in segments) { segments.add(updatedNode) } queue.addFirst( SegmentBuildingInformation( nextOpenSpace.first, currentCoordinate, 1, Segment(1, nextOpenSpace.first, nextOpenSpace.first) ) ) } else { queue.addFirst(SegmentBuildingInformation(nextOpenSpace.first, currentCoordinate, length + 1, runningNode)) } } else { val updatedNode = runningNode.copy(end = currentCoordinate, steps = length) if (updatedNode !in segments) { segments.add(updatedNode) } val neighbors = nextCoordinates.map { SegmentBuildingInformation( it.first, currentCoordinate, 1, Segment(1, it.first, it.first) ) } for (nextNeighbor in neighbors) { queue.addFirst(nextNeighbor) } } } return segments } fun getNeighborsDirectionally( previousCoordinate: Coordinate, currentCoordinate: Coordinate, input: List<String> ): List<Pair<Coordinate, Char>> { val left = currentCoordinate.copy(x = currentCoordinate.x - 1) val right = currentCoordinate.copy(x = currentCoordinate.x + 1) val up = currentCoordinate.copy(y = currentCoordinate.y - 1) val down = currentCoordinate.copy(y = currentCoordinate.y + 1) val nextCoordinates = getNeighbors(currentCoordinate, input) .filter { it.first != previousCoordinate } .filter { if (it.first == left) { it.second != '>' } else if (it.first == right) { it.second != '<' } else if (it.first == up) { it.second != 'v' } else if (it.first == down) { it.second != '^' } else { throw Exception("Unknown direction") } } return nextCoordinates } fun getNeighbors(currentCoordinate: Coordinate, input: List<String>): List<Pair<Coordinate, Char>> { val left = currentCoordinate.copy(x = currentCoordinate.x - 1) val right = currentCoordinate.copy(x = currentCoordinate.x + 1) val up = currentCoordinate.copy(y = currentCoordinate.y - 1) val down = currentCoordinate.copy(y = currentCoordinate.y + 1) val nextCoordinates = listOf( left, right, up, down ).filter { it.x >= 0 && it.x < input[0].length && it.y >= 0 && it.y < input.size } .map { it to input[it.y][it.x] } .filter { it.second != '#' } return nextCoordinates } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
9,183
kotlin-kringle
Apache License 2.0
src/main/kotlin/com/rtarita/days/Day13.kt
RaphaelTarita
570,100,357
false
{"Kotlin": 79822}
package com.rtarita.days import com.rtarita.structure.AoCDay import com.rtarita.util.day import com.rtarita.util.splitTopLevel import kotlinx.datetime.LocalDate object Day13 : AoCDay { override val day: LocalDate = day(13) private fun parseList(list: String): List<*> { if (list == "[]") return emptyList<Any?>() return list.substring(1 until list.lastIndex) .splitTopLevel() .map { it.toIntOrNull() ?: parseList(it) } } private fun getListPairs(input: String): List<Pair<List<*>, List<*>>> { return input.split("\n\n") .map { it.lines() } .map { (a, b) -> parseList(a) to parseList(b) } } private fun compare(left: List<*>, right: List<*>): Int { for ((i, lElem) in left.withIndex()) { if (right.lastIndex < i) return 1 val comparison = when (lElem) { is Int -> when (val rElem = right[i]) { is Int -> lElem - rElem is List<*> -> compare(listOf(lElem), rElem) else -> error("invalid type for element $rElem") } is List<*> -> when (val rElem = right[i]) { is Int -> compare(lElem, listOf(rElem)) is List<*> -> compare(lElem, rElem) else -> error("invalid type for element $rElem") } else -> error("invalid type for element $lElem") } if (comparison != 0) return comparison } return left.size - right.size } override fun executePart1(input: String): Int { return getListPairs(input).withIndex() .filter { (_, pair) -> compare(pair.first, pair.second) < 0 } .sumOf { (idx, _) -> idx + 1 } } override fun executePart2(input: String): Int { val divider1 = listOf(listOf(2)) val divider2 = listOf(listOf(6)) val sorted = getListPairs(input).flatMap { (a, b) -> listOf(a, b) } .plus(listOf(divider1, divider2)) .sortedWith { a, b -> compare(a, b) } return (sorted.indexOfFirst { compare(it, divider1) == 0 } + 1) * (sorted.indexOfFirst { compare(it, divider2) == 0 } + 1) } }
0
Kotlin
0
9
491923041fc7051f289775ac62ceadf50e2f0fbe
2,254
AoC-2022
Apache License 2.0
src/main/kotlin/solutions/constantTime/iteration6/RegionTaxCalculator.kt
daniel-rusu
669,564,782
false
{"Kotlin": 70755}
package solutions.constantTime.iteration6 import dataModel.v3.AccumulatedTaxBracketV2 import dataModel.v3.AccumulatedTaxBracketV2.Companion.toAccumulatedBracketsV2 import dataModel.base.Money import dataModel.base.TaxBracket import dataModel.base.TaxCalculator import solutions.constantTime.iteration5.MinBracketTaxCalculator import kotlin.math.sqrt /** * A tax calculator that splits the tax range into uniformly-sized regions where each region has its own chunk size. * This is much more efficient than [MinBracketTaxCalculator] as the negative effect of a tiny bracket is confined to * a single region instead of affecting the entire tax range resulting in significantly fewer chunks. */ class RegionTaxCalculator(taxBrackets: List<TaxBracket>) : TaxCalculator { private val highestBracket: AccumulatedTaxBracketV2 private val regionSize = computeRegionSize(taxBrackets) private val regions: List<Region> private val bracketChunks: List<AccumulatedTaxBracketV2> init { val accumulatedBrackets = taxBrackets.toAccumulatedBracketsV2() highestBracket = accumulatedBrackets.last() val (regionList, chunkList) = createRegionsAndChunks(regionSize, accumulatedBrackets) regions = regionList bracketChunks = chunkList } override fun computeTax(income: Money): Money { return getTaxBracket(income).computeTotalTax(income) } private fun getTaxBracket(income: Money): AccumulatedTaxBracketV2 { if (income >= highestBracket.from) return highestBracket val regionIndex = (income.cents / regionSize).toInt() val region = regions[regionIndex] val regionBoundary = regionSize * regionIndex val remainder = income.cents - regionBoundary val chunkIndex = region.getChunkIndex(remainder) return getCorrectBracket(income, bracketChunks[chunkIndex]) } } private fun createRegionsAndChunks( regionSize: Long, taxBrackets: List<AccumulatedTaxBracketV2>, ): Pair<List<Region>, List<AccumulatedTaxBracketV2>> { val highestBracket = taxBrackets.last() val regionList = mutableListOf<Region>() val bracketChunkList = mutableListOf<AccumulatedTaxBracketV2>() var regionStart = 0L var currentBracket = taxBrackets.first() while (regionStart < highestBracket.from.cents) { val regionEnd = regionStart + regionSize val chunkSize = computeChunkSizeForRegion(regionStart, regionEnd, currentBracket) regionList += Region(bracketChunkList.size, chunkSize) var chunkBoundary = regionStart while (chunkBoundary < regionEnd) { bracketChunkList += currentBracket chunkBoundary = (chunkBoundary + chunkSize).coerceAtMost(regionEnd) // prepare for the next chunk by advancing to the bracket that overlaps into the next chunk while (currentBracket.to != null && currentBracket.to!!.cents <= chunkBoundary) { currentBracket = currentBracket.next!! } } regionStart += regionSize } return Pair(regionList, bracketChunkList) } private fun getCorrectBracket( income: Money, approximateBracket: AccumulatedTaxBracketV2, ): AccumulatedTaxBracketV2 { val upperBound = approximateBracket.to return when { upperBound == null || income < upperBound -> approximateBracket else -> approximateBracket.next!! // boundary scenario } } private fun computeRegionSize(taxBrackets: List<TaxBracket>): Long { if (taxBrackets.size == 1) return 1L val narrowestBracketSize = taxBrackets.asSequence() .filter { it.to != null } .minOf { it.to!!.cents - it.from.cents } val range = taxBrackets.last().from.cents val multiplier = 5 // close to optimal based on a Monte Carlo simulation across a large distribution of datasets return multiplier * sqrt(range * narrowestBracketSize / sqrt(taxBrackets.size.toDouble())).toLong() } private fun computeChunkSizeForRegion( regionStart: Long, regionEnd: Long, currentBracket: AccumulatedTaxBracketV2, ): Long { return generateSequence(currentBracket) { it.next } .dropWhile { it.from.cents <= regionStart } .filter { it.to != null } .takeWhile { it.to!!.cents < regionEnd } .minOfOrNull { it.to!!.cents - it.from.cents } ?: (regionEnd - regionStart) }
0
Kotlin
0
1
166d8bc05c355929ffc5b216755702a77bb05c54
4,406
tax-calculator
MIT License
src/Day05.kt
punx120
573,421,386
false
{"Kotlin": 30825}
import java.lang.StringBuilder fun main() { fun parseMove(line: String) : Triple<Int, Int, Int> { val regex = "move (\\d+) from (\\d+) to (\\d+)".toRegex() val (cnt, from, to) = regex.find(line)!!.destructured return Triple(cnt.toInt(), from.toInt(), to.toInt() ) } fun buildFromInput(input: List<String>): Pair<Int, Array<ArrayList<Char>>> { var br = 0 for(i in input.indices) { if (input[i].trim() == "") { br = i break } } val n = input[br - 1].split(' ').filter { c -> c != " " && c != ""}.size val stacks = Array(n) { _ -> ArrayList<Char>()} for(i in br - 2 downTo 0) { for (j in 0 until n) { val idx = 1 + 4 * j if (idx < input[i].length && input[i][idx] != ' ') { stacks[j].add(input[i][idx]) } } } return Pair(br, stacks) } fun printOutput(stacks: Array<ArrayList<Char>>): String { val sb = StringBuilder() for (stack in stacks) { sb.append(stack.last()) } return sb.toString() } fun part1(input: List<String>): String { val (br, stacks) = buildFromInput(input) for(l in br + 1 until input.size) { val (cnt, from, to) = parseMove(input[l]) for (i in 0 until cnt) { if (stacks[from-1].isNotEmpty()) { stacks[to-1].add(stacks[from-1].removeLast()) } else { break } } } return printOutput(stacks) } fun part2(input: List<String>): String { val (br, stacks) = buildFromInput(input) for (l in br+1 until input.size) { val (cnt, from, to) = parseMove(input[l]) val fromIdx = stacks[from-1].size - cnt stacks[to-1].addAll(stacks[from-1].subList(fromIdx, stacks[from-1].size)) for (j in 0 until cnt) { stacks[from-1].removeLast() } } return printOutput(stacks) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
eda0e2d6455dd8daa58ffc7292fc41d7411e1693
2,438
aoc-2022
Apache License 2.0
src/main/kotlin/aoc2022/Day12.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2022 import AoCDay // https://adventofcode.com/2022/day/12 object Day12 : AoCDay<Int>( title = "Hill Climbing Algorithm", part1ExampleAnswer = 31, part1Answer = 462, part2ExampleAnswer = 29, part2Answer = 451, ) { private class Position(val x: Int, val y: Int) private class Heightmap private constructor(private val grid: Array<CharArray>) { val xSize = grid[0].size val ySize = grid.size operator fun get(x: Int, y: Int) = grid[y][x] companion object { fun parse(input: String): Triple<Heightmap, Position, Position> { val heightmap = input.lines().map(String::toCharArray).toTypedArray().let(::Heightmap) val current = heightmap.positionsOf('S').single() heightmap.grid[current.y][current.x] = 'a' val bestSignal = heightmap.positionsOf('E').single() heightmap.grid[bestSignal.y][bestSignal.x] = 'z' return Triple(heightmap, current, bestSignal) } } } private fun Heightmap.positionsOf(elevation: Char) = sequence { for (y in 0..<ySize) { for (x in 0..<xSize) { if (get(x, y) == elevation) yield(Position(x, y)) } } } private fun Heightmap.fewestStepsWithBFS(start: Position, end: Position): Int? { val visited = Array(ySize) { BooleanArray(xSize) } operator fun Array<BooleanArray>.get(x: Int, y: Int) = this[y][x] operator fun Array<BooleanArray>.set(x: Int, y: Int, value: Boolean) { this[y][x] = value } visited[start.x, start.y] = true data class Path(val x: Int, val y: Int, val steps: Int) val queue = ArrayDeque<Path>() var currentPath: Path? = Path(start.x, start.y, steps = 0) while (currentPath != null) { val (x, y, steps) = currentPath if (x == end.x && y == end.y) return steps val elevation = this[x, y] val nextSteps = steps + 1 fun addAdjacentToQueue(x: Int, y: Int) { if (!visited[x, y] && this[x, y] - elevation <= 1) { visited[x, y] = true queue.addLast(Path(x, y, nextSteps)) } } if (x > 0) addAdjacentToQueue(x = x - 1, y) if (x < xSize - 1) addAdjacentToQueue(x = x + 1, y) if (y > 0) addAdjacentToQueue(x, y = y - 1) if (y < ySize - 1) addAdjacentToQueue(x, y = y + 1) currentPath = queue.removeFirstOrNull() } return null } override fun part1(input: String): Int { val (heightmap, current, bestSignal) = Heightmap.parse(input) return heightmap.fewestStepsWithBFS(current, bestSignal) ?: error("There is no path from current position to location with best signal") } override fun part2(input: String): Int { // more efficient way would be to search from bestSignal to nearest 'a' instead of from all 'a's to bestSignal val (heightmap, _, bestSignal) = Heightmap.parse(input) return heightmap .positionsOf('a') .mapNotNull { position -> heightmap.fewestStepsWithBFS(position, bestSignal) } .min() } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
3,325
advent-of-code-kotlin
MIT License
src/year_2023/day_14/Day14.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2023.day_14 import readInput import util.* import javax.xml.transform.Source data class TheField( val verticalSize: Int, val horizontalSize: Int, val movableRocks: List<Point>, val immovableRocks: List<Point> ) object Day14 { /** * */ fun solutionOne(text: List<String>): Int { val theField = parseRocks(text) var newLocations = theField.movableRocks.map { it } while (true) { val old = newLocations.map { it } newLocations = moveRocks(theField, newLocations, Direction.NORTH) if (old == newLocations) { break } } return newLocations.sumOf { point -> theField.verticalSize - point.second } } val mem = mutableMapOf<List<Point>, Int>() /** * */ fun solutionTwo(text: List<String>): Int { val theField = parseRocks(text) var newLocations = theField.movableRocks.map { it } var cycle = 0 var total = 1_000_000_000 var length = 0 while (cycle < total) { println(cycle) if (mem.containsKey(newLocations)) { println("I remember this.") length = cycle - mem[newLocations]!! break } else { mem[newLocations] = cycle newLocations = moveRocks(theField, newLocations, Direction.NORTH) newLocations = moveRocks(theField, newLocations, Direction.WEST) newLocations = moveRocks(theField, newLocations, Direction.SOUTH) newLocations = moveRocks(theField, newLocations, Direction.EAST) cycle += 1 } } if (length > 0) { val remainingCycles = (total - cycle) % length for (i in 0 until remainingCycles) { newLocations = moveRocks(theField, newLocations, Direction.NORTH) newLocations = moveRocks(theField, newLocations, Direction.WEST) newLocations = moveRocks(theField, newLocations, Direction.SOUTH) newLocations = moveRocks(theField, newLocations, Direction.EAST) } } val totalVerticalSize = text.size return newLocations.sumOf { point -> totalVerticalSize - point.second } } private fun parseRocks(text: List<String>): TheField { val movableRocks = mutableListOf<Point>() val immovableRocks = mutableListOf<Point>() text.forEachIndexed { y, line -> line.forEachIndexed { x, char -> when (char) { 'O' -> movableRocks.add(x to y) '#' -> immovableRocks.add(x to y) } } } val totalVerticalSize = text.size val totalHorizontalSize = text.first().length return TheField(totalVerticalSize, totalHorizontalSize, movableRocks, immovableRocks) } private fun moveRocks(theField: TheField, currentRocks: List<Point>, direction: Direction): List<Point> { var anyChanges = true var newLocations = currentRocks.map { it } while(anyChanges) { var tempAnyChanges = false val tempNewLocations = mutableListOf<Point>() when (direction) { Direction.NORTH -> { newLocations.sortedBy { it.second }.forEach { point -> if (point.second > 0) { val up = point.up() if (up !in theField.immovableRocks && up !in newLocations) { tempNewLocations.add(up) tempAnyChanges = true } else { tempNewLocations.add(point) } } else { tempNewLocations.add(point) } } } Direction.WEST -> { newLocations.sortedBy { it.first }.forEach { point -> if (point.first > 0) { val left = point.left() if (left !in theField.immovableRocks && left !in newLocations) { tempNewLocations.add(left) tempAnyChanges = true } else { tempNewLocations.add(point) } } else { tempNewLocations.add(point) } } } Direction.SOUTH -> { newLocations.sortedByDescending { it.second }.forEach { point -> if (point.second < theField.verticalSize - 1) { val down = point.down() if (down !in theField.immovableRocks && down !in newLocations) { tempNewLocations.add(down) tempAnyChanges = true } else { tempNewLocations.add(point) } } else { tempNewLocations.add(point) } } } Direction.EAST -> { newLocations.sortedByDescending { it.first }.forEach { point -> if (point.first < theField.horizontalSize - 1) { val right = point.right() if (right !in theField.immovableRocks && right !in newLocations) { tempNewLocations.add(right) tempAnyChanges = true } else { tempNewLocations.add(point) } } else { tempNewLocations.add(point) } } } else -> throw IllegalArgumentException("bad direction") } newLocations = tempNewLocations anyChanges = tempAnyChanges } return newLocations } } fun main() { val text = readInput("year_2023/day_14/Day14.txt") val solutionOne = Day14.solutionOne(text) println("Solution 1: $solutionOne") val solutionTwo = Day14.solutionTwo(text) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
6,677
advent_of_code
Apache License 2.0
src/Day13.kt
SergeiMikhailovskii
573,781,461
false
{"Kotlin": 32574}
fun main() { abstract class Item class Value(val value: Int) : Item() class Sequence(val items: List<Item>) : Item() fun findClosingBracket(index: Int, str: String): Int { var count = 1 var i = index while (i < str.length) { i++ if (str[i] == '[') { count++ } else if (str[i] == ']') { count-- } if (count == 0) break } return i } fun parseIntoSequence(str: String): Sequence { val list = mutableListOf<Item>() if (str.isEmpty()) return Sequence(emptyList()) var index = 0 while (index < str.length) { val c = str[index] if (c == '[') { val end = findClosingBracket(index, str) list.add(parseIntoSequence(str.substring(index + 1, end))) index = end } else if (c != ',') { var numberStr = "" var current = c while (current.isDigit()) { numberStr += current index++ if (index == str.length) { break } current = str[index] } list.add(Value(numberStr.toInt())) } index++ } return Sequence(list) } fun compare(first: Value, second: Value) = if (first.value == second.value) 0 else if (second.value > first.value) 1 else -1 fun compare(first: Sequence, second: Sequence): Int { val firstIterator = first.items.iterator() val secondIterator = second.items.iterator() while (firstIterator.hasNext() && secondIterator.hasNext()) { val firstItem = firstIterator.next() val secondItem = secondIterator.next() if (firstItem is Value && secondItem is Value) { val result = compare(firstItem, secondItem) if (result == -1 || result == 1) return result } else if (firstItem is Sequence && secondItem is Sequence) { val result = compare(firstItem, secondItem) if (result == -1 || result == 1) return result } else if (firstItem is Value && secondItem is Sequence) { val result = compare(Sequence(listOf(firstItem)), secondItem) if (result == -1 || result == 1) return result } else if (firstItem is Sequence && secondItem is Value) { val result = compare(firstItem, Sequence(listOf(secondItem))) if (result == -1 || result == 1) return result } } return if (firstIterator.hasNext() && !secondIterator.hasNext()) -1 else if (secondIterator.hasNext() && !firstIterator.hasNext()) 1 else 0 } val input = readInput("Day13_test") var total = 0 input.filter { it.isNotEmpty() }.chunked(2).forEachIndexed { index, pair -> val first = parseIntoSequence(pair.first()) val second = parseIntoSequence(pair.last()) if (compare(first, second) == 1) { total += index + 1 } } val arr = input.filter { it.isNotEmpty() }.toMutableList().apply { addAll(listOf("[[2]]", "[[6]]")) }.toTypedArray() for (i in 0 until arr.size - 1) { for (j in i + 1 until arr.size) { val first = parseIntoSequence(arr[i]) val second = parseIntoSequence(arr[j]) if (compare(second, first) > 0) { val temp = arr[i] arr[i] = arr[j] arr[j] = temp } } } println((arr.indexOf("[[2]]") + 1) * (arr.indexOf("[[6]]") + 1)) }
0
Kotlin
0
0
c7e16d65242d3be6d7e2c7eaf84f90f3f87c3f2d
3,766
advent-of-code-kotlin
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2023/Day06.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2023 import com.kingsleyadio.adventofcode.util.readInput fun main() { part1() part2() } private fun part1() { val sum = readInput(2023, 6, sample = false).useLines { sequence -> val lines = sequence.iterator() val times = lines.next().substringAfter(":").trim().split(" +".toRegex()).map { it.toInt() } val distances = lines.next().substringAfter(":").trim().split(" +".toRegex()).map { it.toInt() } times.zip(distances) }.map { (time, distance) -> (1..<time).count { a -> (time - a) * a > distance } }.fold(1) { acc, n -> acc * n } println(sum) } private fun part2() { val possibilities = readInput(2023, 6, sample = false).useLines { sequence -> val lines = sequence.iterator() val time = lines.next().substringAfter(":").replace(" ", "").toLong() val distance = lines.next().substringAfter(":").replace(" ", "").toLong() (1..<time).count { a -> (time - a) * a > distance } } println(possibilities) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,055
adventofcode
Apache License 2.0
kotlin/src/main/kotlin/year2023/Day03.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 fun main() { val input = readInput("Day03") Day03.part1(input).println() Day03.part2(input).println() } object Day03 { data class Point(val row: Int, val column: Int, val value: Int) fun part1(input: List<String>): Int { val matrix = encapsulateMatrixWithDots(input) return matrix .flatMapIndexed { rowIndex, row -> row.flatMapIndexed { columnIndex, cell -> when { !cell.isDigit() && cell != '.' -> findAdjacentPointsTo(matrix, rowIndex, columnIndex) else -> setOf() } } } .toSet() .sumOf { it.value } } fun part2(input: List<String>): Int { val matrix = encapsulateMatrixWithDots(input) return matrix .flatMapIndexed { rowIndex, row -> row.mapIndexed { columnIndex, cell -> if (cell != '*') { return@mapIndexed 0 } val points = findAdjacentPointsTo(matrix, rowIndex, columnIndex) if (points.size != 2) { return@mapIndexed 0 } return@mapIndexed points.first().value * points.last().value } } .sum() } /** * This way we should not care about "searching" outside the limits of the matrix, * as we will find a '.' in the border. Not efficient for a large dataset, but enough for this problem */ fun encapsulateMatrixWithDots(matrix: List<String>): List<String> { val newLineSize = matrix.first().length + 2 return listOf( CharArray(newLineSize) { '.' }.joinToString(""), *matrix.map { ".$it." }.toTypedArray(), CharArray(newLineSize) { '.' }.joinToString("") ) } fun findPointAt(matrix: List<String>, row: Int, column: Int): Point? { val cell = matrix[row][column] if (!cell.isDigit()) { return null } var beginningColumn = column while (matrix[row][beginningColumn - 1].isDigit()) { beginningColumn-- } val value = "[0-9]+".toRegex() .find(matrix[row], beginningColumn) ?.value ?.toInt() ?: 0 return Point(row, beginningColumn, value) } fun findAdjacentPointsTo(matrix: List<String>, row: Int, column: Int): Set<Point> { val points = mutableSetOf<Point>() val westPoint = findPointAt(matrix, row, column - 1) if (westPoint != null) points.add(westPoint) val eastPoint = findPointAt(matrix, row, column + 1) if (eastPoint != null) points.add(eastPoint) val northPoint = findPointAt(matrix, row - 1, column) if (northPoint != null) { points.add(northPoint) } else { val northWestPoint = findPointAt(matrix, row - 1, column - 1) if (northWestPoint != null) points.add(northWestPoint) val northEastPoint = findPointAt(matrix, row - 1, column + 1) if (northEastPoint != null) points.add(northEastPoint) } val southPoint = findPointAt(matrix, row + 1, column) if (southPoint != null) { points.add(southPoint) } else { val southWestPoint = findPointAt(matrix, row + 1, column - 1) if (southWestPoint != null) points.add(southWestPoint) val southEastPoint = findPointAt(matrix, row + 1, column + 1) if (southEastPoint != null) points.add(southEastPoint) } return points } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
3,737
advent-of-code
MIT License
src/2021/Day13_2.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File var switched = false val points = ArrayList<Pair<Int, Int>>() val instructions = ArrayList<Pair<String, Int>>() File("input/2021/day13").forEachLine { line -> if (line.isEmpty()) { switched = true } else { if (!switched) { val (x,y) = line.split(",").map { it.toInt() } points.add(Pair(x,y)) } else { val inst = line.split(" ") val (dim,v) = inst[2].split("=") instructions.add(Pair(dim,v.toInt())) } } } val xMax = points.maxOf { it.first } val yMax = points.maxOf { it.second } var grid = ArrayList<ArrayList<String>>() fun List<List<String>>.printGrid() = forEach { it.forEach { print(it) } println() } for (y in 0..yMax) { val row = ArrayList<String>() for (x in 0..xMax) { if (points.any { it.first == x && it.second == y }) row.add("#") else row.add(".") } grid.add(row) } fun List<List<String>>.merge(other: List<List<String>>) = mapIndexed { y, row -> val mappedRow = row.mapIndexed { x, v -> if (other[y][x] == "#" || v == "#") "#" else "." } ArrayList<String>().apply { addAll(mappedRow) } } fun ArrayList<ArrayList<String>>.fold(dim: String, value: Int): ArrayList<ArrayList<String>> { val newGrid = ArrayList<ArrayList<String>>() if (dim == "y") { val top = subList(0,value) val bottom = subList(value+1,grid.size).reversed() newGrid.addAll(top.merge(bottom)) } else if (dim == "x") { val left = map { row -> row.subList(0,value) } val right = map { row -> row.subList(value+1,row.size).reversed() } newGrid.addAll(left.merge(right)) } return newGrid } instructions.forEach { grid = grid.fold(it.first, it.second) } println() grid.printGrid()
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
1,793
adventofcode
MIT License
src/Day02.kt
chrisjwirth
573,098,264
false
{"Kotlin": 28380}
fun main() { fun part1AsChoice(letter: Char): String? { return when (letter) { 'A', 'X' -> "Rock" 'B', 'Y' -> "Paper" 'C', 'Z' -> "Scissors" else -> null } } fun part2AsChoice(ourLetter: Char, opponentChoice: String): String? { val winningMatch = mapOf( "Rock" to "Paper", "Paper" to "Scissors", "Scissors" to "Rock" ) val loosingMatch = mapOf( "Rock" to "Scissors", "Paper" to "Rock", "Scissors" to "Paper" ) return when(ourLetter) { 'X' -> loosingMatch[opponentChoice] 'Y' -> opponentChoice 'Z' -> winningMatch[opponentChoice] else -> null } } fun pointsForOutcome(ourChoice: String, opponentChoice: String): Int { return if ( ourChoice == "Rock" && opponentChoice == "Scissors" || ourChoice == "Paper" && opponentChoice == "Rock" || ourChoice == "Scissors" && opponentChoice == "Paper" ) { 6 } else if (ourChoice == opponentChoice) { 3 } else { 0 } } fun pointsForChoice(choice: String): Int { return when (choice) { "Rock" -> 1 "Paper" -> 2 "Scissors" -> 3 else -> 0 } } fun totalPointsForGame(ourChoice: String, opponentChoice: String): Int { return pointsForOutcome(ourChoice, opponentChoice) + pointsForChoice(ourChoice) } fun part1(input: List<String>): Int { var score = 0 input.forEach { val ourChoice = part1AsChoice(it[2]) val opponentChoice = part1AsChoice(it[0]) score += totalPointsForGame(ourChoice!!, opponentChoice!!) } return score } fun part2(input: List<String>): Int { var score = 0 input.forEach { val opponentChoice = part1AsChoice(it[0]) val ourChoice = part2AsChoice(it[2], opponentChoice!!) score += totalPointsForGame(ourChoice!!, opponentChoice) } return score } // Test val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) // Final val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8b1f2a0d0f579dd23fa1dc1f7b156f728152c2d
2,437
AdventOfCode2022
Apache License 2.0
y2021/src/main/kotlin/adventofcode/y2021/Day09.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution import adventofcode.util.vector.Vec2 import adventofcode.util.vector.neighbors object Day09 : AdventSolution(2021, 9, "Smoke Basin") { override fun solvePartOne(input: String): Int { val grid = parseInput(input) val lowPoints = grid.covering().filter { it.neighbors().all { n -> grid[n] > grid[it] } } return lowPoints.sumOf { grid[it] + 1 } } override fun solvePartTwo(input: String): Int { val grid = parseInput(input) val lowPoints = grid.covering().filter { it.neighbors().all { n -> grid[n] > grid[it] } } fun next(source: Vec2) = source.neighbors().filter { n -> grid[n] in grid[source] until grid.maxHeight } return lowPoints.map { start -> findReachable(start, ::next).size }.sorted().takeLast(3).reduce(Int::times) } private fun parseInput(input: String) = input.lines().map { it.toList().map { it - '0' } }.let(::Grid) private data class Grid(private val grid: List<List<Int>>) { val maxHeight = 9 operator fun get(v: Vec2) = grid.getOrNull(v.y)?.getOrNull(v.x) ?: maxHeight fun covering() = grid.indices.flatMap { y -> grid[0].indices.map { x -> Vec2(x, y) } } } } private fun <T> findReachable(start: T, next: (source: T) -> Iterable<T>): Set<T> { val open = mutableListOf(start) val closed = mutableSetOf<T>() while (open.isNotEmpty()) { val candidate = open.removeLast() closed += candidate open += next(candidate).filter { it !in closed } } return closed }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,594
advent-of-code
MIT License
src/day02/Day02.kt
Puju2496
576,611,911
false
{"Kotlin": 46156}
package day02 import readInput fun main() { // test if implementation meets criteria from the description, like: val input = readInput("src/day02", "Day02") println("Part1") part1(input) println("Part2") part2(input) } private fun part1(inputs: List<String>) { var sum = 0 inputs.forEach { val input: List<String> = it.split(" ") sum += when (input[1]) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } sum += when { input[0] == "A" && input[1] == "Y" -> 6 input[0] == "C" && input[1] == "X" -> 6 input[0] == "B" && input[1] == "Z" -> 6 input[0] == "A" && input[1] == "X" -> 3 input[0] == "B" && input[1] == "Y" -> 3 input[0] == "C" && input[1] == "Z" -> 3 else -> 0 } println("this: ${input[0]} - ${input[1]} $sum") } println("sum: $sum") } private fun part2(inputs: List<String>) { var sum = 0 inputs.forEach { var selection = "" var game = 0 val input: List<String> = it.split(" ") selection = when { input[1] == "X" -> { game = 0 when (input[0]) { "A" -> "Z" "B" -> "X" "C" -> "Y" else -> "" } } input[1] == "Y" -> { game = 3 when (input[0]) { "A" -> "X" "B" -> "Y" "C" -> "Z" else -> "" } } input[1] == "Z" -> { game = 6 when (input[0]) { "A" -> "Y" "B" -> "Z" "C" -> "X" else -> "" } } else -> "" } val mine: Int = when (selection) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } println("this: ${input[0]} - ${input[1]} - $mine - $game - $sum") sum += mine + game } println("sum: $sum") }
0
Kotlin
0
0
e04f89c67f6170441651a1fe2bd1f2448a2cf64e
2,217
advent-of-code-2022
Apache License 2.0
src/main/kotlin/adventofcode2019/Day12TheNbodyProblem.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2019 import kotlin.math.abs import kotlin.math.max import kotlin.math.sqrt class Day12TheNbodyProblem data class MoonVelocity(var x: Int, var y: Int, var z: Int) { val kineticEnergy: Int get() = abs(x) + abs(y) + abs(z) } data class JupiterMoon(val id: Int, var x: Int, var y: Int, var z: Int, val velocity: MoonVelocity) { val totalEnergy: Int get() = (abs(x) + abs(y) + abs(z)) * velocity.kineticEnergy val currentState: List<Int> get() = listOf(x, y, z, velocity.x, velocity.y, velocity.z) val currentCoordinates: List<Int> get() = listOf(x, y, z) fun applyGravityFromPeer(peer: JupiterMoon) { if (x < peer.x) velocity.x++ else if (x > peer.x) velocity.x-- if (y < peer.y) velocity.y++ else if (y > peer.y) velocity.y-- if (z < peer.z) velocity.z++ else if (z > peer.z) velocity.z-- } fun adjustCoordinatesByVelocity() { x += velocity.x y += velocity.y z += velocity.z } } class JupiterOrbit(moonCoordinates: List<String>) { val moons: List<JupiterMoon> init { moons = moonCoordinates.mapIndexed { index, coordinates -> parseMoon(index, coordinates) } } private fun parseMoon(id: Int, coordinates: String): JupiterMoon { val x = coordinates.substringAfter("x=").substringBefore(",").toInt() val y = coordinates.substringAfter("y=").substringBefore(",").toInt() val z = coordinates.substringAfter("z=").substringBefore(">").toInt() return JupiterMoon(id, x, y, z, MoonVelocity(0, 0, 0)) } fun step(stepCount: Int) { repeat(stepCount) { applyGravity() applyVelocity() } } fun stepsUntilCircle(): Long { val startingX: List<Pair<Int, Int>> = moons.map { it.x to it.velocity.x } val startingY: List<Pair<Int, Int>> = moons.map { it.y to it.velocity.y } val startingZ: List<Pair<Int, Int>> = moons.map { it.z to it.velocity.z } var foundX: Long? = null var foundY: Long? = null var foundZ: Long? = null var stepCount = 0L do { stepCount++ step(1) foundX = if (foundX == null && startingX == moons.map { it.x to it.velocity.x }) stepCount else foundX foundY = if (foundY == null && startingY == moons.map { it.y to it.velocity.y }) stepCount else foundY foundZ = if (foundZ == null && startingZ == moons.map { it.z to it.velocity.z }) stepCount else foundZ } while (foundX == null || foundY == null || foundZ == null) return lcm(foundX, foundY, foundZ) } fun lcm(vararg numbers: Long): Long { val groups = mutableListOf<List<Pair<Long, Long>>>() for (n in numbers) { groups.add(groupNumbers(factorize(n))) } val numberGroups = groups.flatMap { it } val orderedGroups = numberGroups.map { g -> g.first to numberGroups.filter { it.first == g.first }.maxOf { it.second } }.toSet() return orderedGroups.fold(1) { acc, pair -> acc * (pair.first.pow(pair.second)) } } private fun Long.pow(exponent: Long) = Math.pow(this.toDouble(), exponent.toDouble()).toInt() fun factorize(number: Long): List<Long> { val result: ArrayList<Long> = arrayListOf() var n = number while (n % 2L == 0L) { result.add(2) n /= 2 } val squareRoot = sqrt(number.toDouble()).toInt() for (i in 3..squareRoot step 2) { while (n % i == 0L) { result.add(i.toLong()) n /= i } } if (n > 2) { result.add(n) } return result } fun groupNumbers(nums: List<Long>): List<Pair<Long, Long>> { val groups = nums.groupBy { it } val groupCounts = groups.map { it.key to it.value.size.toLong() } return groupCounts } private fun applyGravity() { val oldState = moons.toList() moons.forEach { moon -> oldState.filter { it.id != moon.id }.forEach { moon.applyGravityFromPeer(it) } } } private fun applyVelocity() { moons.forEach { it.adjustCoordinatesByVelocity() } } fun totalEnergy() = moons.sumOf { moon -> moon.totalEnergy } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
4,380
kotlin-coding-challenges
MIT License
src/main/kotlin/adventofcode/year2021/Day09SmokeBasin.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2021 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.neighbors import adventofcode.common.product class Day09SmokeBasin(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val heightMap by lazy { input.lines().map { row -> row.map { col -> col.toString().toInt() } } } private fun List<List<Int>>.basin(x: Int, y: Int) = generateSequence(setOf(x to y)) { previous -> val new = previous.flatMap { (x, y) -> neighbors(x, y, false).filter { (x, y) -> this[y][x] < 9 } + setOf(x to y) }.toSet() if (new.size > previous.size) new else null } .last() private fun Int.isLowPoint(neighbors: List<Int>) = neighbors.all { neighbor -> this < neighbor } private fun Int.riskLevel() = this + 1 override fun partOne() = heightMap .flatMapIndexed { y, row -> row.filterIndexed { x, col -> col.isLowPoint(heightMap.neighbors(x, y, false).map { (x, y) -> heightMap[y][x] }) } } .sumOf { height -> height.riskLevel() } override fun partTwo() = heightMap .flatMapIndexed { y, row -> row.mapIndexedNotNull { x, col -> if (col.isLowPoint(heightMap.neighbors(x, y, false).map { (x, y) -> heightMap[y][x] })) x to y else null } } .map { (x, y) -> heightMap.basin(x, y).size } .sorted() .takeLast(3) .product() }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,477
AdventOfCode
MIT License
src/Day07.kt
Narmo
573,031,777
false
{"Kotlin": 34749}
fun main() { data class Entry(val name: String, var size: Int, val isDirectory: Boolean, val children: MutableList<Entry> = mutableListOf()) fun findEntries(start: Entry, maxSize: Int): List<Entry> { val result = mutableListOf<Entry>() if (start.isDirectory && start.size < maxSize) { result.add(start) } start.children.forEach { result.addAll(findEntries(it, maxSize)) } return result.filter { it.size < maxSize } } fun calcSizes(entry: Entry) { if (!entry.isDirectory) { return } entry.children.forEach { calcSizes(it) } entry.size += entry.children.sumOf { it.size } } fun printTree(entry: Entry, indent: String = "") { println("$indent${entry.name.trim('/')}${if (entry.isDirectory) "/ (${entry.size})" else " (${entry.size})"}") for (child in entry.children) { printTree(child, "$indent ") } } fun buildTree(input: List<String>): Entry { val deque = ArrayDeque(input) val currentPath = mutableListOf<Entry>() var root: Entry? = null while (deque.isNotEmpty()) { val currentLine = deque.removeFirst() when { currentLine.startsWith("$") -> { // process command val commandContents = currentLine.split(" ") val command = commandContents[1] val argument = if (commandContents.size > 2) commandContents[2] else null print("Command: $command") if (argument != null) { print(", argument: $argument\n") } else { print("\n") } when (command) { "cd" -> { when (argument) { ".." -> { currentPath.removeLast() } null -> { // skip } else -> { val entry = currentPath.lastOrNull()?.children?.firstOrNull { it.name == argument } ?: Entry(argument, 0, true) currentPath.add(entry) if (argument == "/") { root = entry } } } } "ls" -> { // ignore this command and skip to next line } } println("Current path: ${currentPath.joinToString("/") { it.name }.substring(1)}") } currentLine.first().isDigit() -> { // process file val (size, name) = currentLine.split(" ") println("Adding file: $name, Size: $size to ${currentPath.joinToString("/") { it.name }.replace("//", "/")}") currentPath.last().children.add(Entry(name, size.toInt(), false)) } currentLine.startsWith("dir") -> { // process directory val (_, name) = currentLine.split(" ") currentPath.last().children.add(Entry(name, 0, true)) } } } return root?.also { calcSizes(it) } ?: throw IllegalStateException("No root found") } fun part1(input: List<String>): Int { println("\n=== Starting traverse ===\n") val root = buildTree(input) println("\n=== Finished traverse ===\n\nResulting tree:\n") printTree(entry = root) return findEntries(root, 100_000).sumOf { it.size } } fun part2(input: List<String>): Int { val total = 70_000_000 val minReq = 30_000_000 val root = buildTree(input) val spaceLeft = total - root.size return findEntries(root, Int.MAX_VALUE).sortedBy { it.size }.first { spaceLeft + it.size >= minReq }.size } 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
335641aa0a964692c31b15a0bedeb1cc5b2318e0
3,372
advent-of-code-2022
Apache License 2.0
y2019/src/main/kotlin/adventofcode/y2019/Day25.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import adventofcode.language.intcode.IntCodeProgram fun main() { Day25.solve() } object Day25 : AdventSolution(2019, 25, "Cryostasis") { override fun solvePartOne(input: String): String { val foundItems = listOf("fixed point", "whirled peas", "hologram", "shell", "fuel cell", "polygon", "antenna", "candy cane") return testItems(foundItems) .map { val cmds = it.joinToString("\n") { "drop $it" } val p = runAdventure(input, cmds) p.readline("west") p.execute() p } .map { generateSequence(it::output).map(Long::toInt).map(Int::toChar).joinToString("") } .first { "heavier" !in it && "lighter" !in it } } private const val n = "north" private const val e = "east" private const val s = "south" private const val w = "west" private fun runAdventure(input: String, items: String): IntCodeProgram { return IntCodeProgram.fromData(input).apply { readline(listOf( s, "take fixed point", n, w, w, w, "take hologram", e, e, e, n, "take candy cane", w, "take antenna", s, "take whirled peas", n, w, "take shell", e, e, n, n, "take polygon", s, w, "take fuel cell", w).joinToString("\n")) readline(items) execute() generateSequence(this::output).count() } } private fun testItems(rem: List<String>): Sequence<List<String>> = if (rem.isEmpty()) sequenceOf(emptyList()) else testItems(rem.drop(1)) + testItems(rem.drop(1)).map { it + rem[0] } private fun IntCodeProgram.readline(s: String) { (s + '\n').map { it.code.toLong() }.forEach(this::input) } override fun solvePartTwo(input: String) = "Free star!" }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,070
advent-of-code
MIT License
src/main/kotlin/days/Day11.kt
andilau
399,220,768
false
{"Kotlin": 85768}
package days typealias Seat = Pair<Int, Int> typealias Seats = Map<Seat, Day11.State> typealias SeatsMapNeighbours = Map<Seat, Set<Seat>> @AdventOfCodePuzzle( name = "Seating System", url = "https://adventofcode.com/2020/day/11", date = Date(day = 11, year = 2020) ) class Day11(input: List<String>) : Puzzle { private val col = input.first().length private val row = input.size private val seats: Seats = getSeats(input) override fun partOne(): Int { return generateStableMap(seats.getMapSeatsToNeighboursNear(), 4).occupied() } override fun partTwo(): Int { return generateStableMap(seats.getMapSeatsToNeighboursSight(), 5).occupied() } private fun generateStableMap(map: SeatsMapNeighbours, limit: Int) = generateSequence(seats) { it.generateNext(map, limit) } .zipWithNext() .first { it.first == it.second } .first private fun Seats.getMapSeatsToNeighboursNear() = keys.associateWith { seat -> neighbors.map { seat + it } .filter { containsKey(it) } .toSet() } private fun Seats.getMapSeatsToNeighboursSight() = keys.associateWith { seat -> neighbors.mapNotNull { direction -> generateSequence(seat + direction) { it + direction } .takeWhile { it.inBounds() } .firstOrNull { containsKey(it) } } .toSet() } private fun Seat.inBounds() = (first in 0..col) && (second in 0..row) private fun Seats.generateNext( mapSeatsToNeighbours: Map<Seat, Set<Seat>>, limit: Int ): Seats { val next: MutableMap<Seat, State> = mutableMapOf() for (seat in keys) { val type = getValue(seat) val occupied = this.countNeighbors(mapSeatsToNeighbours, seat) next[seat] = when { type == State.EMPTY && occupied == 0 -> State.OCCUPIED type == State.OCCUPIED && occupied >= limit -> State.EMPTY else -> type } } return next.toMap() } private fun Seats.occupied() = values.count { it == State.OCCUPIED } private fun Seats.countNeighbors(map: SeatsMapNeighbours, seat: Seat) = map.getValue(seat) .count { this[it] == State.OCCUPIED } private fun getSeats(input: List<String>): Seats { val seats: MutableMap<Seat, State> = mutableMapOf() for ((y, line) in input.withIndex()) { line.indices.map { x -> if (line[x] == State.EMPTY.char) seats[x to y] = State.EMPTY } } return seats } private operator fun Seat.plus(that: Seat): Seat = Seat(this.first + that.first, this.second + that.second) companion object { private val neighbors = sequenceOf( -1 to -1, -1 to 0, -1 to 1, 0 to -1, 0 to 1, 1 to -1, 1 to 0, 1 to 1 ) } enum class State(val char: Char) { EMPTY('L'), OCCUPIED('#') } }
7
Kotlin
0
0
2809e686cac895482c03e9bbce8aa25821eab100
3,159
advent-of-code-2020
Creative Commons Zero v1.0 Universal
Kotlin/problems/0055_spiral_matrix_i.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
// Problem Statement // Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. // Input: // [ // [ 1, 2, 3 ], // [ 4, 5, 6 ], // [ 7, 8, 9 ] // ] // Output: [1,2,3,6,9,8,7,4,5] class Solution constructor(){ fun canWalk(row:Int,col:Int,limits:IntArray) : Boolean { return row>=limits[0] && row<limits[1] && col>=limits[2] && col<limits[3]; } fun spiralOrder(matrix: Array<IntArray>): List<Int> { var result:MutableList<Int> = mutableListOf<Int>(); if(matrix.isEmpty()) return result; var limits:IntArray = intArrayOf(0,matrix.size,0,matrix[0].size); var directions:Array<Pair<Int,Int>> = arrayOf<Pair<Int,Int>>(Pair(0,1),Pair(1,0),Pair(0,-1),Pair(-1,0)); var strech:Array<Pair<Int,Int>> = arrayOf<Pair<Int,Int>>(Pair(0,1),Pair(3,-1),Pair(1,-1),Pair(2,1)); var row:Int = 0; var col:Int = 0; var dir:Int = 0; var maxResultSize: Int = matrix.size * matrix[0].size; while(result.size < maxResultSize){ result.add(matrix[row][col]); while(result.size < maxResultSize && !canWalk(row+directions[dir].first,col+directions[dir].second,limits)){ limits[strech[dir].first]+=strech[dir].second; dir = (dir+1)%directions.size; } row+=directions[dir].first; col+=directions[dir].second; } return result; } }; fun main(args:Array<String>){ var matrix:Array<IntArray> = arrayOf(intArrayOf(1,2,3,4),intArrayOf(5,6,7,8),intArrayOf(9,10,11,12),intArrayOf(13,14,15,16)); var sol:Solution = Solution(); println(sol.spiralOrder(matrix).joinToString()); }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
1,726
algorithms
MIT License
src/day7/puzzle07.kt
brendencapps
572,821,792
false
{"Kotlin": 70597}
package day7 import Puzzle import PuzzleInput import java.io.File class FileSystemEntry(val name: String, val parent: FileSystemEntry? = null, private var size: Long = 0) { val children = mutableListOf<FileSystemEntry>() val isDir = size == 0.toLong() fun getEntrySize(): Long { if(size == 0.toLong() && children.isNotEmpty()) { size = children.sumOf { child -> child.getEntrySize() } } return size } } class Day7PuzzleInput(input: String, expectedResult: Long? = null) : PuzzleInput<Long>(expectedResult) { val root: FileSystemEntry = FileSystemEntry("/") init { val filePattern = "(\\d+) (.*)".toRegex() var currentDir = root File(input).readLines().forEach { line -> if(line.startsWith("$ cd ..")) { currentDir = currentDir.parent ?: currentDir } else if(line.startsWith("$ cd ")) { val dir = line.substring("$ cd ".length) currentDir = currentDir.children.find { it.name == dir } ?: currentDir } else if(line.startsWith("dir ")) { currentDir.children.add(FileSystemEntry(line.substring("dir ".length), currentDir)) } else if(filePattern.matches(line)) { val (size, name) = filePattern.find(line)!!.destructured currentDir.children.add(FileSystemEntry(name, currentDir, size.toLong())) } } root.getEntrySize() } } class Day7PuzzleInputList(input: String, expectedResult: Long? = null) : PuzzleInput<Long>(expectedResult) { val root = FileSystemEntry("/") val dirQueue = mutableListOf<FileSystemEntry>() init { val filePattern = "(\\d+) (.*)".toRegex() var currentDir = root File(input).readLines().forEach { line -> if(line.startsWith("$ cd ..")) { currentDir = currentDir.parent ?: currentDir } else if(line.startsWith("$ cd ")) { val dir = line.substring("$ cd ".length) currentDir = currentDir.children.find { it.name == dir } ?: currentDir } else if(line.startsWith("dir ")) { val dir = FileSystemEntry(line.substring("dir ".length), currentDir) currentDir.children.add(dir) dirQueue.add(dir) } else if(filePattern.matches(line)) { val (size, name) = filePattern.find(line)!!.destructured currentDir.children.add(FileSystemEntry(name, currentDir, size.toLong())) } } root.getEntrySize() } } class Day7PuzzleSolution(private val targetDirSize: Long) : Puzzle<Long, Day7PuzzleInput>() { override fun solution(input: Day7PuzzleInput): Long { return getTotalSizeSmallDirectories(targetDirSize, input.root) } private fun getTotalSizeSmallDirectories(size: Long, entry: FileSystemEntry): Long { val sizeOfSmallChildren = entry.children.sumOf { child -> getTotalSizeSmallDirectories(size, child) } if(entry.isDir && entry.getEntrySize() <= size) { return sizeOfSmallChildren + entry.getEntrySize() } return sizeOfSmallChildren } } class Day7PuzzleSolutionList(private val targetDirSize: Long) : Puzzle<Long, Day7PuzzleInputList>() { override fun solution(input: Day7PuzzleInputList): Long { return input.dirQueue.sumOf {dir -> if(dir.getEntrySize() <= targetDirSize) { dir.getEntrySize() } else { 0 } } } } class Day7Puzzle2Solution : Puzzle<Long, Day7PuzzleInput>() { override fun solution(input: Day7PuzzleInput): Long { val targetDirSize = 30000000 - (70000000 - input.root.getEntrySize()) val result = findDirectoryToDelete(targetDirSize, input.root) return result?.getEntrySize() ?: error("Did not find a directory") } private fun findDirectoryToDelete(size: Long, entry: FileSystemEntry): FileSystemEntry? { if(!entry.isDir || entry.getEntrySize() < size) return null var potentialDir: FileSystemEntry? = null for(child in entry.children) { val potentialChildDir = findDirectoryToDelete(size, child) if(potentialChildDir != null) { if(potentialDir == null || potentialDir.getEntrySize() > potentialChildDir.getEntrySize()) { potentialDir = potentialChildDir } } } if(potentialDir != null) { return potentialDir } return entry } } class Day7Puzzle2SolutionList : Puzzle<Long, Day7PuzzleInputList>() { override fun solution(input: Day7PuzzleInputList): Long { val targetDirSize = 30000000 - (70000000 - input.root.getEntrySize()) var currentBest = input.root for (dir in input.dirQueue) { if (dir.getEntrySize() < currentBest.getEntrySize() && dir.getEntrySize() > targetDirSize) { currentBest = dir } } return currentBest.getEntrySize() } } fun day7Puzzle() { Day7PuzzleSolution(100000).solve(Day7PuzzleInput("inputs/day7/exampleCommands.txt", 95437)) Day7PuzzleSolution(100000).solve(Day7PuzzleInput("inputs/day7/inputCommands.txt",1428881)) Day7PuzzleSolutionList(100000).solve(Day7PuzzleInputList("inputs/day7/exampleCommands.txt", 95437)) Day7PuzzleSolutionList(100000).solve(Day7PuzzleInputList("inputs/day7/inputCommands.txt",1428881)) Day7Puzzle2Solution().solve(Day7PuzzleInput("inputs/day7/exampleCommands.txt", 24933642)) Day7Puzzle2Solution().solve(Day7PuzzleInput("inputs/day7/inputCommands.txt", 10475598)) Day7Puzzle2SolutionList().solve(Day7PuzzleInputList("inputs/day7/exampleCommands.txt", 24933642)) Day7Puzzle2SolutionList().solve(Day7PuzzleInputList("inputs/day7/inputCommands.txt", 10475598)) }
0
Kotlin
0
0
00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3
6,207
aoc_2022
Apache License 2.0
src/Day15.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
import kotlin.math.absoluteValue fun main() { data class Sensor( val x: Int, val y: Int, val beaconX: Int, val beaconY: Int, val rawData: String ) { val range: Int = (x - beaconX).absoluteValue + (y - beaconY).absoluteValue } fun List<String>.parseSensors(): List<Sensor> { return map { line -> // line format: Sensor at x=2, y=18: closest beacon is at x=-2, y=15 // x=<value>, y=<value> val sensorData = line.substringAfter("Sensor at ").substringBefore(":") val (sensorX, sensorY) = with(sensorData.split(", ")) { val x = this[0].split("=")[1].toInt() val y = this[1].split("=")[1].toInt() x to y } val beaconData = line.substringAfter(": closest beacon is at ") val (beaconX, beaconY) = with(beaconData.split(", ")) { val x = this[0].split("=")[1].toInt() val y = this[1].split("=")[1].toInt() x to y } Sensor(sensorX, sensorY, beaconX, beaconY, line) } } fun List<Sensor>.getBounds(): Bounds { var left = Int.MAX_VALUE var right = Int.MIN_VALUE var top = Int.MAX_VALUE var bottom = Int.MIN_VALUE forEach { sensor -> left = minOf(left, sensor.x - sensor.range) right = maxOf(right, sensor.x + sensor.range) top = minOf(top, sensor.y - sensor.range) bottom = maxOf(bottom, sensor.y + sensor.range) } return Bounds(top, left, bottom, right) } fun part1(input: List<String>, rowNumber: Int): Int { val sensors = input.parseSensors() .filter {rowNumber in (it.y - it.range)..(it.y + it.range) } // filter out sensors not in range of the target row val bounds = sensors.getBounds() .copy(top = rowNumber, bottom = rowNumber) // limit grid and thus size required to only interested line val grid = Grid(bounds, '.') grid.debugInfo() sensors.forEach { sensor -> grid.trySetGridValue(sensor.x, sensor.y, 'S') grid.trySetGridValue(sensor.beaconX, sensor.beaconY, 'B') fun inRange(x: Int, y: Int): Boolean { val range = (sensor.x - x).absoluteValue + (sensor.y - y).absoluteValue return range <= sensor.range } val xRange = (sensor.x - sensor.range)..(sensor.x + sensor.range) xRange.forEach { x -> if (inRange(x, rowNumber) && grid.getGridValue(x, rowNumber) == '.') { grid.trySetGridValue(x, rowNumber, '#') } } } val noBeaconPositions = (grid.bounds.left .. grid.bounds.right).count { x -> grid.getGridValue(x, rowNumber) == '#' } return noBeaconPositions } fun Sensor.getCoverageRange(x: Int, maxYRange: IntRange): IntRange? { val columnOffset = (x - this.x).absoluteValue if (columnOffset > range) return null val remainingRange = range - columnOffset val actualRange = (y - remainingRange)..(y + remainingRange) return maxOf(actualRange.first, maxYRange.first)..minOf(actualRange.last, maxYRange.last) } fun part2(input: List<String>, xRange: IntRange, yRange: IntRange): Long { val sensors = input.parseSensors() xRange.forEach { x -> var currentYPosition = 0 sensors.mapNotNull { it.getCoverageRange(x, yRange) } .sortedBy { it.first } .forEach { coverageRange -> if (currentYPosition + 1 >= coverageRange.first) { currentYPosition = maxOf(currentYPosition, coverageRange.last) } else { println("result x: $x, y: ${currentYPosition + 1}") return (x * 4000000L) + currentYPosition + 1 } } } return 0L } fun drawFullSampleData() { val sensors = readInput("Day15_test").parseSensors() val bounds = sensors.getBounds() val grid = Grid(bounds, '.') grid.debugInfo() sensors.forEach { sensor -> val debugGrid = Grid(listOf(sensor).getBounds(), '.') grid.trySetGridValue(sensor.x, sensor.y, 'S') grid.trySetGridValue(sensor.beaconX, sensor.beaconY, 'B') debugGrid.trySetGridValue(sensor.x, sensor.y, 'S') debugGrid.trySetGridValue(sensor.beaconX, sensor.beaconY, 'B') fun inRange(x: Int, y: Int): Boolean { val range = (sensor.x - x).absoluteValue + (sensor.y - y).absoluteValue return range <= sensor.range } val xRange = (sensor.x - sensor.range)..(sensor.x + sensor.range) val yRange = (sensor.y - sensor.range)..(sensor.y + sensor.range) xRange.forEach { x -> yRange.forEach { y -> if (inRange(x, y) && grid.getGridValue(x, y) == '.') { grid.trySetGridValue(x, y, '#') debugGrid.trySetGridValue(x, y, '#') } } } debugGrid.debugDraw() } grid.debugInfo() grid.debugDraw() } // test if implementation meets criteria from the description, like: drawFullSampleData() val dayNumber = 15 val testInput = readInput("Day${dayNumber}_test") val testResultPart1 = part1(testInput, 10) val testAnswerPart1 = 26 check(testResultPart1 == testAnswerPart1) { "Part 1: got $testResultPart1 but expected $testAnswerPart1" } val testResultPart2 = part2(testInput, 0..20, 0..20) val testAnswerPart2 = 56000011L check(testResultPart2 == testAnswerPart2) { "Part 2: got $testResultPart2 but expected $testAnswerPart2" } val input = readInput("Day$dayNumber") println(part1(input, 2000000)) println(part2(input, 0..4000000, 0..4000000)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
6,173
advent-of-code-2022-kotlin
Apache License 2.0
src/Day10.kt
jimmymorales
572,156,554
false
{"Kotlin": 33914}
fun main() { fun List<String>.parseInstructions(operation: (Int, String) -> Unit) { var x = 1 forEach { line -> val (inst, n) = line.split(" ").let { it[0] to it.getOrNull(1)?.toInt() } operation(x, inst) n?.let { x += it } } } fun part1(input: List<String>): Int { var cycle = 0 var signalStrength = 0 input.parseInstructions { x, inst -> if (inst == "noop") { cycle++ } else { cycle++ signalStrength += if ((cycle + 20) % 40 == 0) cycle * x else 0 cycle++ } signalStrength += if ((cycle + 20) % 40 == 0) cycle * x else 0 } return signalStrength } fun Pair<Int, Int>.movePixel(size: Int) = let { (x, y) -> var newY = y + 1 var newX = x if (newY >= size) { newY = 0 newX++ } newX to newY } fun part2(input: List<String>) { val crt = Array(6) { Array(40) { '.' } } var pixelIndex = 0 to 0 input.parseInstructions { x, inst -> crt[pixelIndex.first][pixelIndex.second] = if (pixelIndex.second in x-1..x+1) '#' else '.' if (inst == "addx") { pixelIndex = pixelIndex.movePixel(crt[0].size) crt[pixelIndex.first][pixelIndex.second] = if (pixelIndex.second in x-1..x+1) '#' else '.' } pixelIndex = pixelIndex.movePixel(crt[0].size) } crt.forEach { println(it.joinToString("")) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) val input = readInput("Day10") println(part1(input)) // part 2 part2(testInput) part2(input) }
0
Kotlin
0
0
fb72806e163055c2a562702d10a19028cab43188
1,879
advent-of-code-2022
Apache License 2.0
src/Day12.kt
TheGreatJakester
573,222,328
false
{"Kotlin": 47612}
package day12 import utils.forForEach import utils.readInputAsText import utils.runSolver import utils.string.asLines private typealias SolutionType = Int private const val defaultSolution = 0 private const val dayNumber: String = "12" private val testSolution1: SolutionType? = 31 private val testSolution2: SolutionType? = 29 private val startCode = 'S'.code private val endCode = 'E'.code private val lowcode = 'a'.code private val highCode = 'z'.code private class Node(val x: Int, val y: Int, code: Int) { var distance = Int.MAX_VALUE val elevation: Int val isStart: Boolean val isEnd: Boolean init { when (code) { startCode -> { isStart = true isEnd = false elevation = lowcode } endCode -> { isEnd = true isStart = false elevation = highCode } else -> { isStart = false isEnd = false elevation = code } } } lateinit var upHillEdges: List<Node> lateinit var downHillEdges: List<Node> fun setUp(grid: List<List<Node>>) { fun nodeAt(x: Int, y: Int): Node? = grid.getOrNull(y)?.getOrNull(x) val down = nodeAt(x, y + 1) val up = nodeAt(x, y - 1) val left = nodeAt(x - 1, y) val right = nodeAt(x + 1, y) val upHill = listOfNotNull(up, down, left, right).filter { return@filter it.elevation <= this.elevation + 1 } val downHill = listOfNotNull(up, down, left, right).filter { return@filter it.elevation >= this.elevation - 1 } upHillEdges = upHill downHillEdges = downHill } } /** @returns start [Node] */ private fun parseGraph(input: String): List<Node> { val lines = input.asLines() val nodes = lines.mapIndexed { y, line -> line.mapIndexed { x, char -> Node(x, y, char.code) } } nodes.forForEach { _, _, el -> el.setUp(nodes) } return nodes.flatten() } private fun start(input: String): Node { return parseGraph(input).first { it.isStart }.apply { distance = 0 } } private fun end(input: String): Node { return parseGraph(input).first { it.isEnd }.apply { distance = 0 } } private fun part1(input: String): SolutionType { val firstNode = start(input) var searchQueue = ArrayDeque(listOf(firstNode)) val searched = mutableSetOf<Node>() while (searchQueue.isNotEmpty()) { searchQueue = ArrayDeque(searchQueue.toSet().sortedBy { it.distance }) val next = searchQueue.removeFirst() if (next.isEnd) { return next.distance } searched.add(next) val canGo = next.upHillEdges.filter { it !in searched } canGo.forEach { it.distance = next.distance + 1 } searchQueue.addAll(canGo) } throw Exception("No path found") } private fun part2(input: String): SolutionType { val firstNode = end(input) var searchQueue = ArrayDeque(listOf(firstNode)) val searched = mutableSetOf<Node>() while (searchQueue.isNotEmpty()) { searchQueue = ArrayDeque(searchQueue.toSet().sortedBy { it.distance }) val next = searchQueue.removeFirst() if (next.elevation == lowcode) { return next.distance } searched.add(next) val canGo = next.downHillEdges.filter { it !in searched } canGo.forEach { it.distance = next.distance + 1 } searchQueue.addAll(canGo) } throw Exception("No path found") } fun main() { runSolver("Test 1", readInputAsText("Day${dayNumber}_test"), testSolution1, ::part1) runSolver("Part 1", readInputAsText("Day${dayNumber}"), null, ::part1) runSolver("Test 2", readInputAsText("Day${dayNumber}_test"), testSolution2, ::part2) runSolver("Part 2", readInputAsText("Day${dayNumber}"), null, ::part2) }
0
Kotlin
0
0
c76c213006eb8dfb44b26822a44324b66600f933
3,984
2022-AOC-Kotlin
Apache License 2.0
src/main/kotlin/TrickShot_17.kt
Flame239
433,046,232
false
{"Kotlin": 64209}
import kotlin.math.abs private val area = Area(211, 232, -124, -69) private val hittingV0xPerStep = findHittingV0xPerStep() fun findHittingV0xPerStep(): Map<Int, List<Int>> { val possibleXSteps = mutableListOf<AxisHit>() for (Vx0 in 0..area.maxX) { var curX = 0 for (step in 0..Vx0) { curX += (Vx0 - step) if (area.containsX(curX)) { possibleXSteps.add(AxisHit(Vx0, step)) } } if (area.containsX(curX)) { println("Would stay forever when Vx0 = $Vx0") } } return possibleXSteps.groupBy { it.step }.mapValues { it.value.map { axisHit -> axisHit.v0 } } } fun getHittingV0xPerStep(steps: Int): List<Int> = if (steps >= 21) listOf(21) else hittingV0xPerStep[steps] ?: emptyList() fun findAllPossibleVelocitiesCount(maxVY: Int): Int { var total = 0 for (Vy0 in area.minY..maxVY) { var curStep = 0 var curY = 0 val complementaryVx0 = mutableSetOf<Int>() while (curY >= area.minY) { curY += (Vy0 - curStep) if (area.containsY(curY)) { complementaryVx0.addAll(getHittingV0xPerStep(curStep)) } curStep++ } total += complementaryVx0.size } return total } // if Vy > 0 => we end up in 0 again after 2*Vy steps. Then we should hit the area with maximum possible next step // For this we should make a step of `area.minY` and end up in `area.minY`(inside the area). // We can't take step which is more, because we will not end up in area, // And if we take step less, then highest height will be less. // So Vy0 = |area.minY| - 1 fun findHighestPossibleTrajectoryPosition(): Int { // for ANY step we can find xV such as after this number of steps we end up in area by x // for ex: 21 -> when we reach curXV = 0 we will be in area and will stay forever // for other steps we could find such xV as well val maxVY = abs(area.minY) - 1 // max Y will be when Y velocity will drop to 0, and = sum of geom progression return maxVY * (maxVY + 1) / 2 } fun main() { println(findHighestPossibleTrajectoryPosition()) println(findAllPossibleVelocitiesCount(abs(area.minY) - 1)) } data class Area(val minX: Int, val maxX: Int, val minY: Int, val maxY: Int) { fun containsX(x: Int): Boolean = x in minX..maxX fun containsY(y: Int): Boolean = y in minY..maxY } data class AxisHit(val v0: Int, val step: Int)
0
Kotlin
0
0
ef4b05d39d70a204be2433d203e11c7ebed04cec
2,481
advent-of-code-2021
Apache License 2.0
src/Day14.kt
janbina
112,736,606
false
null
package day14 import getInput import java.util.* import kotlin.test.assertEquals fun main(args: Array<String>) { val input = getInput(14).readLines().first() assertEquals(8194, part1(input)) assertEquals(1141, part2(input)) } fun part1(input: String): Int { return makeMatrix(input).map { it.count { it } }.sum() } fun part2(input: String): Int { var groups = 0 val queue = LinkedList<Pair<Int, Int>>() val matrix = makeMatrix(input) for (i in 0..127) { for (j in 0..127) { if (matrix[i][j]) { queue.add(i to j) groups++ while (queue.isNotEmpty()) { val current = queue.pop() if (current.first in 0..127 && current.second in 0..127 && matrix[current.first][current.second]) { matrix[current.first][current.second] = false queue.add(current.first-1 to current.second) queue.add(current.first+1 to current.second) queue.add(current.first to current.second-1) queue.add(current.first to current.second+1) } } } } } return groups } fun makeMatrix(input: String): Array<BooleanArray> { val matrix = Array(128) { BooleanArray(128) } (0..127).map { i -> val hash = day10.part2("$input-$i") var j = 0 hash.forEach { val num = it.toString().toInt(16) matrix[i][j++] = num and 8 > 0 matrix[i][j++] = num and 4 > 0 matrix[i][j++] = num and 2 > 0 matrix[i][j++] = num and 1 > 0 } } return matrix }
0
Kotlin
0
0
71b34484825e1ec3f1b3174325c16fee33a13a65
1,795
advent-of-code-2017
MIT License
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day10.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.adventofcode.twentytwenty import org.jgrapht.Graph import org.jgrapht.alg.shortestpath.AllDirectedPaths import org.jgrapht.graph.DefaultDirectedGraph import org.jgrapht.graph.DefaultEdge import sh.weller.adventofcode.util.product fun List<Int>.findPathsInGraph(): Int { val sorted = (listOf(0) + sorted() + listOf(maxOf { it } + 3)) val graph: Graph<Int, DefaultEdge> = DefaultDirectedGraph(DefaultEdge::class.java) sorted.forEach { graph.addVertex(it) } sorted.forEachIndexed { index, i -> sorted.take(index).takeLast(3).filter { j -> (i - 3 <= j) }.forEach { j -> graph.addEdge(j, i) } } val allDirectedPaths = AllDirectedPaths(graph) return allDirectedPaths.getAllPaths(sorted.first(), sorted.last(), true, Int.MAX_VALUE).count() } fun List<Int>.findPathsInSplitGraph(): Long { val sorted = (listOf(0) + sorted() + listOf(maxOf { it } + 3)) val subGraphList = mutableListOf<List<Int>>() var tmpList = mutableListOf<Int>() sorted.forEachIndexed { index, i -> tmpList.add(i) if (i - sorted.getOrElse(index - 1) { 0 } == 3) { subGraphList.add(tmpList) tmpList = mutableListOf() tmpList.add(i) } } val subGraphResults = subGraphList.map { it.findPathsInSubGraph().toLong() } return subGraphResults.product() } private fun List<Int>.findPathsInSubGraph(): Int { val graph: Graph<Int, DefaultEdge> = DefaultDirectedGraph(DefaultEdge::class.java) this.forEach { graph.addVertex(it) } this.forEachIndexed { index, i -> this.take(index).takeLast(3).filter { j -> (i - 3 <= j) }.forEach { j -> graph.addEdge(j, i) } } val allDirectedPaths = AllDirectedPaths(graph) return allDirectedPaths.getAllPaths(this.first(), this.last(), true, Int.MAX_VALUE).count() } fun List<Int>.findPathsBruteForce(): Long { val sorted = (listOf(0) + this.sorted() + listOf(this.maxOf { it } + 3)) return sorted.rec().size.toLong() } private fun List<Int>.rec(): List<Int> { if (this.size == 1) { return this } val withoutFirst = this.drop(1) val filtered = withoutFirst.filter { it - 3 <= this.first() } return filtered.flatMap { drop(indexOf(it)).rec() } } fun List<Int>.findPathsSmart(): Long { val sorted = (listOf(0) + this.sorted() + listOf(this.maxOf { it } + 3)) val depthList = mutableListOf<Long>(1) sorted.forEachIndexed { index, i -> var counter = 0L sorted.take(index).takeLast(3).forEachIndexed { innerIndex, j -> if (i - 3 <= j) { val atPoint = depthList.getOrElse(index - innerIndex) { 0L } counter += atPoint } } depthList.add(maxOf(counter, depthList[index])) } return depthList.last() } fun List<Int>.countJoltDifferences(startJoltage: Int = 0): Long { var currentJoltage = startJoltage var oneDifference: Long = 0 var threeDifference: Long = 1 this.sorted().forEach { value -> val difference = value - currentJoltage if (difference >= 1 || difference <= 3) { when (difference) { 1 -> oneDifference++ 3 -> threeDifference++ } currentJoltage += difference } } return oneDifference * threeDifference }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
3,342
AdventOfCode
MIT License
src/main/kotlin/aoc2022/Day23.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import Point import readInput object Day23 { private enum class Direction { NORTH, SOUTH, WEST, EAST; fun getNext() = values()[(this.ordinal + 1) % values().size] } /** * Moves this point into the given [Direction] */ private fun Point.moveTo(direction: Direction) = when (direction) { Direction.NORTH -> this.move(0, -1) Direction.SOUTH -> this.move(0, 1) Direction.EAST -> this.move(1, 0) Direction.WEST -> this.move(-1, 0) } /** * Gets the minimum area which covers all the given [Point]s */ private fun getAreaOfEnclosingRectangle(map: Collection<Point>): Int { val width = map.maxOf { it.x } - map.minOf { it.x } + 1 val height = map.maxOf { it.y } - map.minOf { it.y } + 1 return height * width } @Suppress("unused") private fun printMap(map: Collection<Point>) { for (y in map.minOf { it.y }..map.maxOf { it.y }) { for (x in map.minOf { it.x }..map.maxOf { it.x }) { print(if (map.contains(Point(x, y))) '#' else '.') } println() } } /** * Finds the new position, to which [position] can move to * * @param position the origin position * @param direction the first direction to look for new positions * @param neighbours all the neighbouring position for [position] * @param map the map of all the elves' positions before any * @return the new position or null, if none is found */ private fun findNextPoint( position: Point, direction: Direction, neighbours: Collection<Point>, map: Collection<Point> ): Point? { var newPosition: Point? = null var currentDirection = direction while (newPosition == null) { val canMove = when (currentDirection) { Direction.NORTH -> neighbours.filter { it.y == position.y - 1 }.all { !map.contains(it) } Direction.SOUTH -> neighbours.filter { it.y == position.y + 1 }.all { !map.contains(it) } Direction.EAST -> neighbours.filter { it.x == position.x + 1 }.all { !map.contains(it) } Direction.WEST -> neighbours.filter { it.x == position.x - 1 }.all { !map.contains(it) } } if (canMove) { newPosition = position.moveTo(currentDirection) } else { currentDirection = currentDirection.getNext() if (currentDirection == direction) { break } } } return newPosition } /** * Gets a map of (current elf position) to (new elf position) for all the elves, that can move in this round * @param map the map of all the elves before any movement * @param currentDirection the current "start" direction */ private fun getNewElfPositions(map: Collection<Point>, currentDirection: Direction): Map<Point, Point> { // key = origin, value = target val proposedPositions = mutableMapOf<Point, Point>() val duplicates = mutableSetOf<Point>() // points to which multiple elves want to move map.map { it to it.getNeighbours(withDiagonal = true).filter { n -> map.contains(n) } } .filter { it.second.isNotEmpty() } .forEach { (elf, neighbours) -> val nextPosition = findNextPoint(elf, currentDirection, neighbours, map) if (nextPosition != null) { if (proposedPositions.containsValue(nextPosition)) { duplicates.add(nextPosition) } else { proposedPositions[elf] = nextPosition } } } return proposedPositions.filterValues { !duplicates.contains(it) } } fun part1(input: List<String>): Int { var map = input.withIndex().flatMap { (y, line) -> line.withIndex().filter { it.value == '#' }.map { it.index }.map { x -> Point(x, y) } } var currentDirection = Direction.NORTH repeat(10) { val newPositions = getNewElfPositions(map, currentDirection) map = map.map { if (newPositions.containsKey(it)) newPositions[it]!! else it } currentDirection = currentDirection.getNext() } return getAreaOfEnclosingRectangle(map) - map.size } fun part2(input: List<String>): Int { var map = input.withIndex().flatMap { (y, line) -> line.withIndex().filter { it.value == '#' }.map { it.index }.map { x -> Point(x, y) } } var currentDirection = Direction.NORTH var round = 0 var elvesMoved = -1 while (elvesMoved != 0) { round++ val newPositions = getNewElfPositions(map, currentDirection) elvesMoved = newPositions.size map = map.map { if (newPositions.containsKey(it)) newPositions[it]!! else it } currentDirection = currentDirection.getNext() } return round } } fun main() { val testInput = readInput("Day23_test", 2022) check(Day23.part1(testInput) == 110) check(Day23.part2(testInput) == 20) val input = readInput("Day23", 2022) println(Day23.part1(input)) println(Day23.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
5,393
adventOfCode
Apache License 2.0
src/Day05.kt
thiyagu06
572,818,472
false
{"Kotlin": 17748}
package aoc22.day05 import aoc22.printIt import java.io.File import java.util.TreeMap fun main() { fun parseInput(file: String): List<String> { return File(file).readLines() } fun part1(): String { val lines = parseInput("input/day05.txt") val (stacks, commands) = parseStacksAndCommands(lines) commands.forEach { val (crateFrom, crateTo, crateCount) = parseCommand(it) val temp = ArrayList<Char>() for (i in 0 until crateCount) { temp.add(stacks[crateFrom].removeFirst()) } temp.forEach { el -> stacks[crateTo].addFirst(el) } } val result = StringBuilder() stacks.forEach { result.append(it.first()) } return result.toString().printIt() } fun part2(): String { val lines = parseInput("input/day05.txt") val (stacks, commands) = parseStacksAndCommands(lines) commands.forEach { val (crateFrom, crateTo, crateCount) = parseCommand(it) val temp = ArrayList<Char>() for (i in 0 until crateCount) { temp.add(stacks[crateFrom].removeFirst()) } stacks[crateTo].addAll(0, temp) } val result = StringBuilder() stacks.forEach { result.append(it.first()) } return result.toString().printIt() } // test if implementation meets criteria from the description, like: check(part1() == "TPGVQPFDH") check(part2() == "DMRDFRHHH") } private fun parseStacksAndCommands(input: List<String>): Pair<ArrayList<ArrayDeque<Char>>, List<String>> { val stacks = ArrayList<ArrayDeque<Char>>() val indexOfInputSplit = input.indexOf("") var stacksInput = input.subList(0, indexOfInputSplit) val commands = input.subList(indexOfInputSplit + 1, input.size) val stacksCount = getStacksCount(stacksInput) stacksInput = stacksInput.subList(0, stacksInput.size - 1) initStacks(stacksCount, stacks) populateStacks(stacksCount, input, indexOfInputSplit, stacksInput, stacks) return Pair(stacks, commands) } private fun initStacks(stacksCount: Int, stacks: ArrayList<ArrayDeque<Char>>) { for (i in 0 until stacksCount) { stacks.add(ArrayDeque()) } } private fun getStacksCount(stacksInput: List<String>) = stacksInput.last().split(" ").last { it.isNotBlank() }.toInt() private fun populateStacks( stacksCount: Int, input: List<String>, indexOfInputSplit: Int, stacksInput: List<String>, stacks: ArrayList<ArrayDeque<Char>> ) { val indexMap = TreeMap<Int, Int>() for (i in 1..stacksCount) { indexMap[i] = input[indexOfInputSplit - 1].indexOf(i.toString()) } for (i in stacksInput.size - 1 downTo 0) { var lineStack = stacksInput[i] while (lineStack.length <= indexMap.get(stacksCount)!!) { lineStack += " " } for ((k, j) in (1..stacksCount).withIndex()) { val element = lineStack[indexMap[j]!!] if (element != ' ') { stacks[k].addFirst(element) } } } } private fun parseCommand(it: String): Triple<Int, Int, Int> { val crateFrom = (it.substringAfter("from ").substringBefore(" to")).toInt() - 1 val crateTo = (it.substringAfter("to ")).toInt() - 1 val crateCount = it.substringAfter("move ").substringBefore(" from").toInt() return Triple(crateFrom, crateTo, crateCount) }
0
Kotlin
0
0
55a7acdd25f1a101be5547e15e6c1512481c4e21
3,514
aoc-2022
Apache License 2.0
day-03/src/main/kotlin/BinaryDiagnostic.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 lines = readLines() val columns = readColumns(lines) val mostCommonBits = columns.map { findMostCommonBit(it) }.toCharArray().concatToString() val gammaRate = mostCommonBits.toInt(2) val epsilonRate = invertBits(mostCommonBits).toInt(2) return gammaRate * epsilonRate } private fun partTwo(): Int { val lines = readLines() val o2GeneratorRating = getO2GeneratorRating(lines.toMutableList()) val cO2ScrubberRating = getCO2ScrubberRating(lines.toMutableList()) return o2GeneratorRating * cO2ScrubberRating } private fun getO2GeneratorRating(lines: MutableList<String>): Int { return findRating(lines) { findMostCommonBit(it) } } private fun getCO2ScrubberRating(lines: MutableList<String>): Int { return findRating(lines) { invertBit(findMostCommonBit(it)) } } private fun findRating( lines: MutableList<String>, bitCriteria: (List<Char>) -> Char ): Int { var index = 0 while (lines.size > 1) { val columns = readColumns(lines) val bit = bitCriteria.invoke(columns[index]) lines.removeIf { it[index] != bit } index++ } return lines[0].toInt(2) } private fun readColumns(lines: List<String>): List<MutableList<Char>> { val columns = List(lines[0].length) { mutableListOf<Char>() } lines.forEach { it.forEachIndexed { charIndex, char -> columns[charIndex].add(char) } } return columns } private fun findMostCommonBit(column: Collection<Char>): Char { val ones = column.count { it == '1' } return if (ones >= column.size - ones) '1' else '0' } private fun invertBits(bits: String) = bits.map { invertBit(it) }.toCharArray().concatToString() private fun invertBit(bit: Char) = if (bit == '1') '0' else '1' private fun readLines(): List<String> { return {}::class.java.classLoader.getResource("input.txt") .readText() .split("\n") .filter { it.isNotBlank() } }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
2,162
aoc-2021
MIT License
src/Day09.kt
Sasikuttan2163
647,296,570
false
null
import java.awt.Point import kotlin.math.sign import kotlin.math.sqrt fun main() { val input = readInput("Day09") val head = Point(0, 0) val tail = Point(0, 0) var visitedPoints = mutableListOf(Point(0, 0)) input.forEach { line -> line.substringAfter(" ").toInt().let { repeat(it) { when (line[0]) { 'R' -> head.x++ 'L' -> head.x-- 'U' -> head.y++ 'D' -> head.y-- } if (head.distance(tail) > sqrt(2.0)) { tail.translate(sign(head.x - tail.x.toDouble()).toInt(), sign(head.y - tail.y.toDouble()).toInt()) visitedPoints.add(tail.clone() as Point) } } } } val part1 = visitedPoints.toSet().count() part1.println() visitedPoints = mutableListOf(Point(0,0)) val points = List(10) { Point(0, 0) } // points[0] is the head and points[9] is the tail input.forEach { line -> line.substringAfter(" ").toInt().let { repeat(it) { when (line[0]) { 'R' -> points[0].x++ 'L' -> points[0].x-- 'U' -> points[0].y++ 'D' -> points[0].y-- } for (i in 1..9) { if (points[i - 1].distance(points[i]) > sqrt(2.0)) { points[i].translate( sign(points[i - 1].x - points[i].x.toDouble()).toInt(), sign(points[i - 1].y - points[i].y.toDouble()).toInt() ) } } visitedPoints.add(points[9].clone() as Point) } } } val part2 = visitedPoints.toSet().count() part2.println() }
0
Kotlin
0
0
fb2ade48707c2df7b0ace27250d5ee240b01a4d6
1,872
AoC-2022-Solutions-In-Kotlin
MIT License
src/day10/Day10.kt
Regiva
573,089,637
false
{"Kotlin": 29453}
package day10 import readLines import kotlin.math.absoluteValue fun main() { val id = "10" val testOutput = 13140 val testInput = readInput("day$id/Day${id}_test") println(solve(testInput)) check(solve(testInput) == testOutput) val input = readInput("day$id/Day$id") println(solve(input)) } private fun readInput(fileName: String): List<Command> { return readLines(fileName).map { val splitted = it.split(" ") when (splitted.first()) { "noop" -> Command.Noop "addx" -> Command.Add(count = splitted[1].toInt()) else -> Command.Noop } } } private fun solve(input: List<Command>): Int { var cycle = 0 val keyCycles = generateSequence(seed = 20, nextFunction = { it + 40 }).take(6) var register = 1 var strength = 0 val width = 40 fun tick(change: Int = 0) { cycle++ // part 1 if (cycle in keyCycles) strength += cycle * register // part 2 print(if (((cycle - 1) % width - register).absoluteValue <= 1) "#" else " ") if (cycle % width == 0) println() register += change } for (command in input) { tick() when (command) { is Command.Add -> tick(command.count) is Command.Noop -> {} } } return strength } private sealed class Command { object Noop : Command() data class Add(val count: Int) : Command() }
0
Kotlin
0
0
2d9de95ee18916327f28a3565e68999c061ba810
1,465
advent-of-code-2022
Apache License 2.0
src/y2015/Day03.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2015 import util.Direction import util.readInput object Day03 { private fun parse(input: List<String>): List<Direction> { return input.first() .replace('>', 'R') .replace('<', 'L') .replace('^', 'U') .replace('v', 'D') .map { Direction.fromChar(it) } } fun part1(input: List<String>): Int { val parsed = parse(input) val visited = allVisited(parsed) return visited.size } private fun allVisited(parsed: List<Direction>): MutableSet<Pair<Int, Int>> { val visited = mutableSetOf(0 to 0) //var lastPos = 0 to 0 parsed.fold(0 to 0) { acc, dir -> val new = dir.move(acc) visited.add(new) new } return visited } fun part2(input: List<String>): Int { val parsed = parse(input) val chunks = parsed.chunked(2) val santa = chunks.map { it.first() } val robo = chunks.map { it.last() } val visited = allVisited(santa) + allVisited(robo) return visited.size } } fun main() { val testInput = """ ^>v< """.trimIndent().split("\n") println("------Tests------") println(Day03.part1(testInput)) println(Day03.part2(testInput)) println("------Real------") val input = readInput("resources/2015/day03") println(Day03.part1(input)) println(Day03.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,450
advent-of-code
Apache License 2.0
tonilopezmr/day 3/SpiralNeighbors.kt
CloudCoders
112,667,277
false
{"Mathematica": 37090, "Python": 36924, "Scala": 26540, "Kotlin": 24988, "Ruby": 5084, "Java": 4495, "JavaScript": 3440, "MATLAB": 3013}
package day3 import org.junit.Assert.* import org.junit.Test class SpiralNeighbors { private fun sumNeighbors(spiral: Map<Dimens, Int>, dimen: Dimens): Int = (spiral[Pair(dimen.first + 1, dimen.second)] ?: 0) + (spiral[Pair(dimen.first + 1, dimen.second + 1)] ?: 0) + (spiral[Pair(dimen.first, dimen.second + 1)] ?: 0) + (spiral[Pair(dimen.first - 1, dimen.second + 1)] ?: 0) + (spiral[Pair(dimen.first - 1, dimen.second)] ?: 0) + (spiral[Pair(dimen.first - 1, dimen.second - 1)] ?: 0) + (spiral[Pair(dimen.first, dimen.second - 1)] ?: 0) + (spiral[Pair(dimen.first + 1, dimen.second - 1)] ?: 0) + (spiral[Pair(dimen.first, dimen.second)] ?: 0) fun nextTo(input: Int): Map<Dimens, Int> { var displacementX = 0 var displacementY = -1 var x = 0 var y = 0 var number = 1 val spiral = mutableMapOf(Dimens(0, 0) to 1) while (number <= input) { val currentPosition = Dimens(x, y) number = sumNeighbors(spiral, currentPosition) spiral.put(currentPosition, number) if (x == y || (x < 0 && x == -y) || (x > 0 && x == 1 - y)) { val t = displacementX displacementX = -displacementY displacementY = t } x += displacementX y += displacementY } return spiral } @Test fun `sum of all neighbors when you are on center should be 8`() { val map = mapOf( Dimens(0, 0) to 1, Dimens(1, 0) to 1, Dimens(2, 0) to 1, Dimens(0, 1) to 1, Dimens(2, 1) to 1, Dimens(0, 2) to 1, Dimens(1, 2) to 1, Dimens(2, 2) to 1 ) assertEquals(8, sumNeighbors(map, Dimens(1, 1))) } @Test fun `sum half neighbors when you are on center should be 5`() { val map = mapOf( Dimens(0, 0) to 1, Dimens(1, 0) to 1, Dimens(2, 0) to 1, Dimens(0, 1) to 1, Dimens(2, 1) to 1 ) assertEquals(5, sumNeighbors(map, Dimens(1, 1))) } @Test fun `sum two neighbors when you are on a corner should be 5`() { val map = mapOf( Dimens(2, 0) to 1, Dimens(2, 1) to 1 ) assertEquals(2, sumNeighbors(map, Dimens(1, 1))) } @Test fun `sum itself should be 1`() { val map = mapOf( Dimens(1, 1) to 1 ) assertEquals(1, sumNeighbors(map, Dimens(1, 1))) } @Test fun `generate spiral to find next to 23 number`() { val expected = arrayOf(1, 1, 2, 4, 5, 10, 11, 23, 25) assertArrayEquals(expected, nextTo(23).values.toTypedArray()) } @Test fun `generate spiral to find next to 200`() { val expected = arrayOf(1, 1, 2, 4, 5, 10, 11, 23, 25, 26, 54, 57, 59, 122, 133, 142, 147, 304) assertArrayEquals(expected, nextTo(200).values.toTypedArray()) assertEquals(304, nextTo(200).values.toTypedArray().last()) } @Test fun `find the solution next to 277678`() { assertEquals(279138, nextTo(277678).values.toTypedArray().last()) } }
2
Mathematica
0
8
5a52d1e89076eccb55686e4af5848de289309813
2,939
AdventOfCode2017
MIT License
src/main/kotlin/Day14.kt
pavittr
317,532,861
false
null
import java.io.File import java.nio.charset.Charset fun main() { val testDocs = File("test/day14").readLines(Charset.defaultCharset()) val puzzles = File("puzzles/day14").readLines(Charset.defaultCharset()) fun applyMask(mask: String, number: Long): Long { val maskCommands = mask.mapIndexed { index, c -> Pair(index, c) }.filter { it.second != 'X' } var returnedNumber = number.toString(2).padStart(36, '0').toCharArray() maskCommands.forEach { returnedNumber[it.first] = it.second } return returnedNumber.joinToString("").toLong(2) } fun part1(input: List<String>) { val indexedEntries = input.mapIndexed { index, i -> Pair(index, i) } val masks = indexedEntries.filter { it.second.startsWith("mask") } .map { Pair(it.first, it.second.substringAfter("mask = ")) } val slotInstructions = indexedEntries.filter { it.second.startsWith("mem") } .map { Triple(it.first, it.second.drop(4).split("]")[0].toLong(), it.second.split("= ")[1].toLong()) } var slotMachine = mutableMapOf<Long, Long>() slotInstructions.forEach { instruction -> val mask = masks.filter { it.first < instruction.first }.maxByOrNull { it.first }?.second ?: "" slotMachine[instruction.second] = applyMask(mask, instruction.third) } println(slotMachine.values.sum()) } part1(testDocs) part1(puzzles) fun getSlots(startingIndex: Long, mask: String): List<Long> { var maskedIndex = startingIndex.toString(2).padStart(36, '0').toCharArray() maskedIndex = maskedIndex.mapIndexed { index, c -> when (mask[index]) { 'X' -> 'X'.toChar() '0' -> c.toChar() '1' -> '1'.toChar() else -> 'X' } }.toCharArray() var returnedArrays = mutableListOf(maskedIndex) var nextX = returnedArrays.first().indexOf('X') while (nextX >= 0) { val initialSize = returnedArrays.size for (i in 0..initialSize) { val zeroValue = returnedArrays[i] zeroValue[nextX] = '0' returnedArrays[i] = zeroValue val oneValue = zeroValue.clone() oneValue[nextX] = '1' returnedArrays.add(oneValue) } nextX = returnedArrays.first().indexOf('X') } return returnedArrays.map { it.joinToString("").toLong(2) } } fun part2(input: List<String>) { val indexedEntries = input.mapIndexed { index, i -> Pair(index, i) } val masks = indexedEntries.filter { it.second.startsWith("mask") } .map { Pair(it.first, it.second.substringAfter("mask = ")) } val slotInstructions = indexedEntries.filter { it.second.startsWith("mem") } .map { Triple(it.first, it.second.drop(4).split("]")[0].toLong(), it.second.split("= ")[1].toLong()) } var slotMachine = mutableMapOf<Long, Long>() slotInstructions.forEach { instruction -> val mask = masks.filter { it.first < instruction.first }.maxByOrNull { it.first }?.second ?: "" val affectedSlots = getSlots(instruction.second, mask) affectedSlots.forEach { slotMachine[it] = instruction.third } } println(slotMachine.values.sum()) } val test = listOf( "mask = 000000000000000000000000000000X1001X", "mem[42] = 100", "mask = 00000000000000000000000000000000X0XX", "mem[26] = 1" ) part2(test) part2(puzzles) }
0
Kotlin
0
0
3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04
3,636
aoc2020
Apache License 2.0
src/Day05.kt
PauliusRap
573,434,850
false
{"Kotlin": 20299}
private const val INDICATOR_BOX = '[' fun main() { fun parseBoxConfig(input: List<String>): MutableList<MutableList<Char>> { val boxes = input.takeWhile { it.contains(INDICATOR_BOX) } val output = MutableList<MutableList<Char>>( boxes.last().count { it == INDICATOR_BOX} ) { mutableListOf() } boxes.forEach { string -> (1 until string.length step 4).forEachIndexed { index, boxPosition -> val content = string[boxPosition] if (content.isLetter()) { output[index].add(content) } } } return output.onEach { it.reverse() } } fun parseInstructions(input: List<String>, instructionActions: (Int, Int, Int) -> Unit) { val instructionTemplate = "move (\\d+) from (\\d+) to (\\d+)".toRegex() val instructions = input.takeLastWhile { it.matches(instructionTemplate) } instructions.forEach { instructionTemplate.find(it)?.let { match -> val amountToMove = match.groups[1]?.value?.toInt() ?: 0 val moveFrom = match.groups[2]?.value?.toInt()!! - 1 val moveTo = match.groups[3]?.value?.toInt()!! - 1 instructionActions(amountToMove, moveFrom, moveTo) } } } fun followInstructions9000(input: List<String>): List<List<Char>> { val boxConfig = parseBoxConfig(input) parseInstructions(input) { amountToMove, moveFrom, moveTo -> for (i in 1..amountToMove) { boxConfig[moveTo].add( boxConfig[moveFrom].removeAt( boxConfig[moveFrom].lastIndex ) ) } } return boxConfig } fun followInstructions9001(input: List<String>): List<List<Char>> { val boxConfig = parseBoxConfig(input) parseInstructions(input) { amountToMove, moveFrom, moveTo -> val movedBoxes = boxConfig[moveFrom].takeLast(amountToMove) repeat(movedBoxes.size) { boxConfig[moveFrom].removeLast() } boxConfig[moveTo].addAll(movedBoxes) } return boxConfig } fun getTopCrates(boxConfig: List<List<Char>>): String { val topCrates = StringBuilder() boxConfig.forEach { topCrates.append(it.lastOrNull() ?: "") } return topCrates.toString() } fun part1(input: List<String>) = getTopCrates(followInstructions9000(input)) fun part2(input: List<String>) = getTopCrates(followInstructions9001(input)) // test if implementation meets criteria from the description: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
df510c3afb104c03add6cf2597c433b34b3f7dc7
2,945
advent-of-coding-2022
Apache License 2.0
src/main/kotlin/y2022/day12/Day12.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2022.day12 import Coord import Coordinated import Matrix import MatrixUtils import MatrixUtils.filterMatrixElement import MatrixUtils.forEachMatrixElement import MatrixUtils.move import java.lang.IllegalStateException fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } data class Field( val elevation: Int, var seen: Boolean = false, ) fun input(): Triple<Matrix<Coordinated<Field>>, Coordinated<Field>, Coordinated<Field>> { var start: Coordinated<Field>? = null var target: Coordinated<Field>? = null val field = MatrixUtils.createMatrix(AoCGenerics.getInputLines("/y2022/day12/input.txt")) { y, row -> row.mapIndexed { x, char -> val currentCoord = Coordinated( coord = Coord(x,y), data = Field( elevation = when (char) { 'S' -> 0 'E' -> 25 else -> char.code - 97 } ) ) if (char == 'S') start = currentCoord if (char == 'E') target = currentCoord currentCoord } } if (start == null || target == null) { throw IllegalStateException("No start or target found!") } else { return Triple(field, start!!, target!!) } } fun getLevel(board: Matrix<Coordinated<Field>>, start:Coordinated<Field>, target: Coordinated<Field>): Int { board.forEachMatrixElement { field -> field.data.seen = false } var level = 0 val toBeVisited = ArrayDeque<Coordinated<Field>?>() toBeVisited.add(start) toBeVisited.add(null) start.data.seen = true while (toBeVisited.isNotEmpty()) { val curField = toBeVisited.removeFirst() if (curField == null) { level++ toBeVisited.add(null) if (toBeVisited.first() == null) break else continue } if (curField.coord == target.coord) { return level } val possibleTargetFields = MatrixUtils.SimpleDirection.values() .mapNotNull { move -> board.move(curField, move) } possibleTargetFields .filter { f -> f.data.elevation <= curField.data.elevation + 1 } .forEach { usefulField -> if (!usefulField.data.seen) { toBeVisited.add(usefulField) usefulField.data.seen = true } } } return Int.MAX_VALUE } fun part1(): Int { val input = input() val board = input.first val startPosition = input.second val target = input.third return getLevel(board, startPosition, target) } fun part2(): Int { val input = input() val board = input.first val startPositions = input.first.filterMatrixElement { field -> field.data.elevation == 0 } val target = input.third val distances = startPositions.map { getLevel(board, it, target) } return distances.minOrNull()!! }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
3,081
AdventOfCode
MIT License
src/day01/Day01_01.kt
scottpeterson
573,109,888
false
{"Kotlin": 15611}
fun main() { data class Elf( val calories: List<Int> ) { val totalCalories: Int get() = calories.sum() } fun constructElves(input: List<String>): List<Elf> { val elves = mutableListOf<Elf>() var dynamicCalorieList = mutableListOf<Int>() input.forEach {string -> if (string.isEmpty()) { elves.add(Elf(dynamicCalorieList)) dynamicCalorieList = mutableListOf() } else { dynamicCalorieList.add(string.toInt()) } } elves.add(Elf(dynamicCalorieList)) return elves } val elvesInput = readInput("Day01_test") val elves = constructElves(elvesInput) val sortedElves = elves .mapIndexed { index, elf -> index to elf} .sortedByDescending { (_, elf) -> elf.totalCalories } println("Day 1, Part 1 Solution: Elf: ${sortedElves.first().first}; Total Calories: ${sortedElves.first().second.totalCalories}") val topThreeElves = sortedElves .subList(0, 3) .sumOf{ (_, elf) -> elf.totalCalories} println("Day 1, Part 2, Solution: Total 3 in Calories: $topThreeElves") }
0
Kotlin
0
0
0d86213c5e0cd5403349366d0f71e0c09588ca70
1,183
advent-of-code-2022
Apache License 2.0
src/2021/Day03.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2021` import java.io.File import java.util.* fun main() { Day03().solve() } data class Count(val i: Int, var all: Int = 0, var ones: Int = 0) { fun apply(s: String): Count { ++all if (s[i] == '1') { ++ones } return this } fun o2filter(ss: List<String>): List<String> { ss.forEach{apply(it)} return ss.filter{o2(it)} } fun co2filter(ss: List<String>): List<String> { ss.forEach{apply(it)} return ss.filter{co2(it)} } fun o2(s: String): Boolean { if (ones*2 >= all) { return s[i] == '1' } return s[i] == '0' } fun co2(s: String): Boolean { if (ones*2 >= all) { return s[i] == '0' } return s[i] == '1' } } fun List<String>.o2Rate(): Int { var l = List(this.size){this[it]} for (i in 0 until this.first().length) { l = Count(i).o2filter(l) if (l.size == 1) { return l[0].toInt(2) } } return l[0].toInt(2) } fun List<String>.co2Rate(): Int { var l = List(this.size){this[it]} for (i in 0 until this.first().length) { l = Count(i).co2filter(l) if (l.size == 1) { return l[0].toInt(2) } } return l[0].toInt(2) } data class BinStrCount(val length: Int) { var count = 0 val oneCounts = MutableList(length){0} fun add(binStr: String): BinStrCount { binStr.forEachIndexed { ix, c -> if (c == '1') ++oneCounts[ix] } ++count return this } fun gammaRate(): Int { val binStr = oneCounts.mapIndexed{ix, c -> if (count/2 < c) "1" else "0" }.joinToString("") return binStr.toInt(2) } fun epsilonRate(): Int { val binStr = oneCounts.mapIndexed{ix, c -> if (count/2 < c) "0" else "1" }.joinToString("") return binStr.toInt(2) } } class Day03 { fun solve() { val f = File("src/2021/inputs/day03.in") val s = Scanner(f) val binStrs = mutableListOf<String>() while (s.hasNextLine()) { binStrs.add(s.nextLine().trim()) } val b = binStrs.fold(BinStrCount(binStrs.first().length)){b, it -> b.add(it)} println("${b.epsilonRate() * b.gammaRate()} (${b.gammaRate()} * ${b.epsilonRate()})") println("${binStrs.o2Rate() * binStrs.co2Rate()} (${binStrs.o2Rate()} * ${binStrs.co2Rate()})") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
2,444
advent-of-code
Apache License 2.0
src/main/kotlin/endredeak/aoc2023/Day02.kt
edeak
725,919,562
false
{"Kotlin": 26575}
package endredeak.aoc2023 fun main() { data class GameSet(val r: Long, val g: Long, val b: Long) data class Game(val id: Long, val sets: List<GameSet>) { fun isPossible(r: Long, g: Long, b: Long) = sets.all { s -> s.r <= r && s.g <= g && s.b <= b } fun fewestCubes() = Triple(sets.maxOf { it.r }, sets.maxOf { it.g }, sets.maxOf { it.b }) } solve("Cube Conundrum") { val input = lines .map { it.replace(": ", ":") .replace(", ", ",") .replace("; ", ";")} .map { line -> line.split(":").let { (f, s) -> val gameId = f.split(" ")[1].toLong() val sets = s.split(";").map { set -> var r = 0L var g = 0L var b = 0L set.split(",").forEach { cubes -> cubes.split(" ").let { (n, c) -> n.toLong().let { when (c) { "red" -> { r = it } "green" -> { g = it } "blue" -> { b = it } else -> error("waat") } } } } GameSet(r, g, b) } Game(gameId, sets) } } part1(3035) { input.filter { it.isPossible(12, 13, 14) }.sumOf { it.id } } part2(66027) { input.map { it.fewestCubes() }.sumOf { it.first * it.second * it.third } } } }
0
Kotlin
0
0
92c684c42c8934e83ded7881da340222ff11e338
1,792
AdventOfCode2023
Do What The F*ck You Want To Public License
src/Day05.kt
SnyderConsulting
573,040,913
false
{"Kotlin": 46459}
import java.util.* fun main() { fun part1(input: List<String>): String { val (crateRows, instructions) = input.separateFileSections() val stackList = mutableListOf<Stack<String>>() getCrateList(crateRows).forEach { crateList -> crateList.forEachIndexed { index, string -> if (stackList.size <= index) { stackList.add(Stack()) } if (string.isNotBlank()) { stackList[index].push(string) } } } getInstructions(instructions).forEach { instruction -> val toStack = stackList[instruction.to] val fromStack = stackList[instruction.from] repeat(instruction.qty) { toStack.push(fromStack.pop()) } } return getTopCrates(stackList.toMutableList()) } fun part2(input: List<String>): String { val (crateRows, instructions) = input.separateFileSections() val stackList = mutableListOf<MutableList<String>>() getCrateList(crateRows).forEach { it.forEachIndexed { index, string -> if (stackList.size <= index) { stackList.add(mutableListOf()) } if (string.isNotBlank()) { stackList[index].add(string) } } } getInstructions(instructions).forEach { instruction -> val toStack = stackList[instruction.to] val fromStack = stackList[instruction.from] toStack.addAll(fromStack.takeLast(instruction.qty)) repeat(instruction.qty) { fromStack.removeLast() } } return getTopCrates(stackList) } val input = readInput("Day05") println(part1(input)) println(part2(input)) } fun getCrateList(crateRows: List<String>): List<List<String>> { return crateRows.map { row -> row.chunked(4).map { crate -> crate.replace("[", "").replace("]", "").trim() } }.reversed() } fun getInstructions(instructions: List<String>): List<Instruction> { return instructions.map { val splitString = it.split(" ") val qty = splitString[1].toInt() val from = splitString[3].toInt() - 1 val to = splitString[5].toInt() - 1 Instruction(qty, from, to) } } fun List<String>.separateFileSections(): Pair<List<String>, List<String>> { val group1End = indexOfFirst { !it.contains("[") } val group2Start = indexOfFirst { it.contains("move") } return Pair( subList(0, group1End), subList(group2Start, size) ) } fun getTopCrates(stackList: MutableList<MutableList<String>>): String { return stackList.joinToString("") { it.last() } } data class Instruction(val qty: Int, val from: Int, val to: Int)
0
Kotlin
0
0
ee8806b1b4916fe0b3d576b37269c7e76712a921
2,913
Advent-Of-Code-2022
Apache License 2.0
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day09/Day09.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day09 import eu.janvdb.aocutil.kotlin.readLines import kotlin.math.abs //const val FILENAME = "input09-test.txt" //const val FILENAME = "input09-test2.txt" const val FILENAME = "input09.txt" val ORIGIN = Location(0, 0) fun main() { runWithSize(2) runWithSize(10) } private fun runWithSize(size: Int) { var state = State(List(size) { ORIGIN }) val locations = mutableSetOf(ORIGIN) readLines(2022, FILENAME) .map(String::toInstruction) .forEach { for (i in 0 until it.steps) { state = state.move(it.direction) locations += state.locations.last() } } println(locations.size) } data class Location(val x: Int, val y: Int) { fun move(direction: Direction): Location { return when (direction) { Direction.L -> Location(x - 1, y) Direction.R -> Location(x + 1, y) Direction.U -> Location(x, y - 1) Direction.D -> Location(x, y + 1) } } fun follow(head: Location): Location { val dx = head.x - x val dy = head.y - y val absX = abs(dx) val absY = abs(dy) val dirX = if (dx == 0) 0 else dx / absX val dirY = if (dy == 0) 0 else dy / absY val valX = if (absX == 2 || (absX == 1 && absY == 2)) 1 else 0 val valY = if (absY == 2 || (absX == 2 && absY == 1)) 1 else 0 return Location(x + valX * dirX, y + valY * dirY) } } data class State(val locations: List<Location>) { fun move(direction: Direction): State { val newLocations = locations.toMutableList() newLocations[0] = locations[0].move(direction) for (i in 1 until locations.size) { newLocations[i] = locations[i].follow(newLocations[i - 1]) } return State(newLocations) } } enum class Direction { L, U, R, D } data class Instruction(val direction: Direction, val steps: Int) fun String.toInstruction(): Instruction = Instruction( Direction.valueOf(substring(0, 1)), substring(2).toInt() )
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,857
advent-of-code
Apache License 2.0
aoc-2022/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentytwo/Day07.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwentytwo import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.head import fr.outadoc.aoc.scaffold.readDayInput class Day07 : Day<Int> { private sealed class Node { abstract val name: String abstract val size: Int data class Directory( override val name: String, val children: MutableList<Node> = mutableListOf() ) : Node() { override val size: Int get() = children.sumOf { child -> child.size } override fun toString(): String = "$name (dir)" } data class File( override val name: String, override val size: Int ) : Node() { override fun toString(): String = "$name (file, size=$size)" } } private sealed class Command { data class ChangeDir(val path: String) : Command() data class ListDir(val contents: List<String>) : Command() } private val commands: List<Command> = readDayInput() .split("$ ") .map { commandBlock -> commandBlock.replace("$ ", "") .lines() .filterNot { line -> line == "" } } .filter { it.isNotEmpty() } .map { command -> val (cmdLine, results) = command.head() when (val cmd = cmdLine.take(2)) { "ls" -> Command.ListDir(results) "cd" -> Command.ChangeDir(path = cmdLine.drop(3)) else -> error("unknown command: $cmd") } } private fun buildFs(commands: List<Command>): Node.Directory { val root = Node.Directory("/") val currentPath = ArrayDeque<Node.Directory>() commands.forEach { command -> when (command) { is Command.ChangeDir -> { when (command.path) { "/" -> { currentPath.clear() currentPath.addLast(root) } ".." -> { currentPath.removeLast() } else -> { currentPath.addLast( currentPath.last() .children .filterIsInstance<Node.Directory>() .first { child -> child.name == command.path } ) } } } is Command.ListDir -> { command.contents.map { node -> val (a, fileName) = node.split(' ') when (a) { "dir" -> { currentPath.last().children.add( Node.Directory(fileName) ) } else -> { currentPath.last().children.add( Node.File( name = fileName, size = a.toInt() ) ) } } } } } } return root } private fun Node.print(depth: Int = 0) { repeat(depth * 2) { print(" ") } println("- ${toString()}") if (this is Node.Directory) { children.forEach { child -> child.print(depth = depth + 1) } } } private fun Node.Directory.listAllSubDirs(): List<Node.Directory> { return listOf(this) + children.filterIsInstance<Node.Directory>().flatMap { it.listAllSubDirs() } } override fun step1(): Int { val root = buildFs(commands) val maxSize = 100_000 return root.listAllSubDirs() .filter { it.size < maxSize } .sumOf { it.size } } override val expectedStep1 = 1_084_134 override fun step2(): Int { val root = buildFs(commands) val totalSpace = 70_000_000 val requiredSpace = 30_000_000 val usedSpace = root.size val unusedSpace = totalSpace - usedSpace val maxSize = requiredSpace - unusedSpace return root.listAllSubDirs() .filter { it.size >= maxSize } .minOf { it.size } } override val expectedStep2 = 6_183_184 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
4,826
adventofcode
Apache License 2.0
src/Day01.kt
rod41732
572,917,438
false
{"Kotlin": 85344}
import java.util.* fun main() { val elfCalories = readInputRaw("Day01").trim() // prevent trailing endline from causing problem .split("\n\n") .map { it.split("\n").sumOf { it.toInt() } } fun part1(eachElfCalories: List<Int>) = eachElfCalories.max() fun part2(eachElfCalories: List<Int>) = eachElfCalories.sortedDescending().take(3).sum() fun part2Faster(eachElfCalories: List<Int>): Int { val heap = PriorityQueue(Int::compareTo) eachElfCalories.forEach { if (heap.size != 0 && it < heap.peek()) return@forEach heap.add(it) if (heap.size > 3) heap.remove() } return heap.sum() } // test cases val testElfCalories = readInputRaw("Day01_test").trim() // prevent trailing endline from causing problem .split("\n\n") .map { it.split("\n").sumOf { it.toInt() } } check(part1(testElfCalories) == 24000) check(part2(testElfCalories) == 45000) println("Part 1") println(part1(elfCalories)) println("Part 2") println(part2(elfCalories)) println("Part 2 - O(N) solution") println(part2Faster(elfCalories)) }
0
Kotlin
0
0
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
1,168
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day13.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2021 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readText import se.brainleech.adventofcode.verify class Aoc2021Day13 { companion object { private const val DOUBLE_LINE = "\n\n" private const val NUMBER_SEPARATOR = "," private const val FOLD_ALONG = "fold along " private const val EMPTY = "" private const val EQUAL_SIGN = "=" private const val GRID_DOT = "#" private const val GRID_NOT = "." } data class Dot(var x: Int, var y: Int) : Comparable<Dot> { companion object { fun toKey(x: Int, y: Int): String = "$x,$y" } override operator fun compareTo(other: Dot): Int { return when { this === other -> 0 this.y > other.y -> 1 this.y < other.y -> -1 this.x > other.x -> 1 this.x < other.x -> -1 else -> 0 } } fun toKey(): String = toKey(x, y) } enum class Axis { X, Y } data class Fold(val axis: Axis, val pointOnAxis: Int) class Paper(private val dots: List<Dot>, private val folds: List<Fold>) { private var width: Int = maxX() private var height: Int = maxY() private fun maxX(): Int { return dots.maxOf { it.x } } private fun maxY(): Int { return dots.maxOf { it.y } } private fun foldAlong(fold: Fold) { when (fold.axis) { Axis.X -> { dots.filter { dot -> dot.x > fold.pointOnAxis }.forEach { it.x = width - it.x } width = fold.pointOnAxis - 1 } Axis.Y -> { dots.filter { dot -> dot.y > fold.pointOnAxis }.forEach { it.y = height - it.y } height = fold.pointOnAxis - 1 } } } fun distinctDots(): List<Dot> { return dots.sorted().distinct() } fun foldOnce(): Paper { return foldAtMost(1) } fun foldAll(): Paper { return foldAtMost(Int.MAX_VALUE) } private fun foldAtMost(maxSteps: Int): Paper { folds .take(maxSteps) .forEach { fold -> foldAlong(fold) } return this } fun toAsciiArt(): String { return buildString { val grid = distinctDots() .groupBy(keySelector = { it.toKey() }, valueTransform = { it }) .mapValues { GRID_DOT } .withDefault { GRID_NOT } for (y in 0..height) { for (x in 0..width) { append(grid.getValue(Dot.toKey(x, y))) } appendLine() } }.trim() } } private fun String.asPaper(): Paper { val (dotPositions, foldingInstructions) = this.split(DOUBLE_LINE) val paper = Paper( dotPositions.lines().map { line -> val (x, y) = line.split(NUMBER_SEPARATOR).map { it.toInt() } Dot(x, y) }.sorted().toList(), foldingInstructions.lines() .map { it.replace(FOLD_ALONG, EMPTY).split(EQUAL_SIGN) } .map { fold -> Fold(Axis.valueOf(fold.first().uppercase()), fold.last().toInt()) } .toList() ) return paper } fun part1(input: String): Int { return input.asPaper().foldOnce().distinctDots().size } fun part2(input: String): String { return input.asPaper().foldAll().toAsciiArt() } } fun main() { val solver = Aoc2021Day13() val prefix = "aoc2021/aoc2021day13" val testData = readText("$prefix.test.txt") val realData = readText("$prefix.real.txt") val square = """ ##### #...# #...# #...# ##### ..... ..... """.trimIndent() verify(17, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(square, solver.part2(testData)) compute({ solver.part2(realData).replace('#', '█') }, "$prefix.part2 = \n") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
4,341
adventofcode
MIT License
src/main/kotlin/day22.kt
Gitvert
433,947,508
false
{"Kotlin": 82286}
fun day22() { val lines: List<String> = readFile("day22.txt") day22part1(lines) day22part2(lines) } fun day22part1(lines: List<String>) { val rebootSteps = mutableListOf<RebootStep>() lines.forEach { rebootSteps.add(RebootStep( it.split(" ")[0] == "on", findRange(it, 'x'), findRange(it, 'y'), findRange(it, 'z') )) } val reactor = Array (150) {Array(150) { IntArray(150) { 0 } } } rebootSteps.filter { it.xRange.first >= 0 && it.xRange.first <= 100 && it.xRange.second >= 0 && it.xRange.second <= 100 && it.yRange.first >= 0 && it.yRange.first <= 100 && it.yRange.second >= 0 && it.yRange.second <= 100 && it.zRange.first >= 0 && it.zRange.first <= 100 && it.zRange.second >= 0 && it.zRange.second <= 100 }.forEach { val xFrom = if (it.xRange.first < it.xRange.second) {it.xRange.first} else {it.xRange.second} val xTo = if (it.xRange.first > it.xRange.second) {it.xRange.first} else {it.xRange.second} val yFrom = if (it.yRange.first < it.yRange.second) {it.yRange.first} else {it.yRange.second} val yTo = if (it.yRange.first > it.yRange.second) {it.yRange.first} else {it.yRange.second} val zFrom = if (it.zRange.first < it.zRange.second) {it.zRange.first} else {it.zRange.second} val zTo = if (it.zRange.first > it.zRange.second) {it.zRange.first} else {it.zRange.second} val newNumber = if (it.on) {1} else {0} for (x in xFrom..xTo) { for (y in yFrom..yTo) { for (z in zFrom..zTo) { reactor[x][y][z] = newNumber } } } } val answer = reactor.flatMap { it.asIterable() }.flatMap { it.asIterable() }.sumOf { it } println("22a: $answer") } fun day22part2(lines: List<String>) { val answer = "---" println("22b: $answer") } fun findRange(line: String, direction: Char): Pair<Int, Int> { val startIndex = line.indexOf(direction) val endIndex = line.indexOf(',', startIndex + 1) val range = if (endIndex > 0) {line.substring(startIndex + 2, endIndex)} else {line.substring(startIndex + 2)} return Pair(Integer.valueOf(range.split("..")[0]) + 50, Integer.valueOf(range.split("..")[1]) + 50) } data class RebootStep(val on: Boolean, val xRange: Pair<Int, Int>, val yRange: Pair<Int, Int>, var zRange: Pair<Int, Int>)
0
Kotlin
0
0
02484bd3bcb921094bc83368843773f7912fe757
2,436
advent_of_code_2021
MIT License
src/main/kotlin/com/groundsfam/advent/y2023/d04/Day04.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2023.d04 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.pow import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines import kotlin.math.min data class Card(val winners: Set<Int>, val yourNumbers: List<Int>) fun Card.numMatches() = yourNumbers.count { it in winners } fun partOne(cards: List<Card>) = cards.sumOf { when (val matches = it.numMatches()) { 0 -> 0 else -> 2.pow(matches - 1).toInt() } } fun partTwo(cards: List<Card>): Long { // initially we have one of each card val cardCounts = cards.mapTo(mutableListOf<Long>()) { 1 } cards.forEachIndexed { i, card -> val matches = card.numMatches() // indices of cards that get copied, making sure to stop at the end of the table of cards (i + 1..min(i + matches, cards.size - 1)).forEach { j -> // example: if we have 5 of card i, then card j gets 5 more copies cardCounts[j] += cardCounts[i] } } return cardCounts.sum() } fun main() = timed { (DATAPATH / "2023/day04.txt").useLines { lines -> lines.mapTo(mutableListOf()) { line -> val (winners, yourNumbers) = line.split("""\s+\|\s+""".toRegex(), limit = 2) Card( winners.split("""\s+""".toRegex()) .drop(2) // Drop the "Game #:" part .mapTo(mutableSetOf(), String::toInt), yourNumbers.split("""\s+""".toRegex()) .map(String::toInt) ) } } .also { println("Part one: ${partOne(it)}") } .also { println("Part two: ${partTwo(it)}") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,699
advent-of-code
MIT License
src/Day02.kt
Kietyo
573,293,671
false
{"Kotlin": 147083}
enum class Result { WIN, LOSE, DRAW } sealed interface Option { object Rock : Option { override val points: Int = 1 override fun battle(other: Option): Result { return when (other) { Paper -> Result.LOSE Rock -> Result.DRAW Scissors -> Result.WIN } } } object Scissors : Option { override val points: Int = 3 override fun battle(other: Option): Result { return when(other) { Paper -> Result.WIN Rock -> Result.LOSE Scissors -> Result.DRAW } } } object Paper : Option { override val points: Int = 2 override fun battle(other: Option): Result { return when(other) { Paper -> Result.DRAW Rock -> Result.WIN Scissors -> Result.LOSE } } } fun battle(other: Option): Result fun getOtherOptionToGetResult(result: Result): Option { return ALL.first { it.battle(this) == result } } abstract val points: Int companion object { val ALL = listOf(Rock, Paper, Scissors) } } fun String.toOption(): Option { return when { this == "A" || this == "X" -> Option.Rock this == "B" || this == "Y"-> Option.Paper this == "C" || this == "Z"-> Option.Scissors else -> TODO("This string isn't supported: ${this}") } } fun String.toResult(): Result { return when { this == "X" -> Result.LOSE this == "Y"-> Result.DRAW this == "Z"-> Result.WIN else -> TODO("This string isn't supported: ${this}") } } fun main() { fun part1(input: List<String>): Unit { var myTotalScore = 0 for (line in input) { val (otherOption, myOption) = line.split(" ").map { it.toOption() } println("otherOption: $otherOption, myOption: $myOption") val result = myOption.battle(otherOption) myTotalScore += when (result) { Result.WIN -> 6 Result.LOSE -> 0 Result.DRAW -> 3 } + myOption.points } println(myTotalScore) } fun part2(input: List<String>): Unit { var myTotalScore = 0 for (line in input) { val split = line.split(" ") val otherOption = split[0].toOption() val wantedResult = split[1].toResult() val myOption = otherOption.getOtherOptionToGetResult(wantedResult) println("otherOption: $otherOption, wantedResult: $wantedResult, myOption: $myOption") myTotalScore += when (wantedResult) { Result.WIN -> 6 Result.LOSE -> 0 Result.DRAW -> 3 } + myOption.points } println(myTotalScore) } // test if implementation meets criteria from the description, like: val testInput = readInput("day2_test") part1(testInput) part2(testInput) val input = readInput("day2_input") // part1(input) // part2(input) }
0
Kotlin
0
0
dd5deef8fa48011aeb3834efec9a0a1826328f2e
3,172
advent-of-code-2022-kietyo
Apache License 2.0
src/Day05.kt
rmyhal
573,210,876
false
{"Kotlin": 17741}
fun main() { fun part1(input: List<String>): String { return crateMover9000(input) } fun part2(input: List<String>): String { return crateMover9001(input) } val input = readInput("Day05") println(part1(input)) println(part2(input)) } private fun crateMover9000(input: List<String>): String { val crates = crates(input) return input.asCommands() .forEach { command -> for (i in 0 until command.count) { crates[command.to].addFirst( element = crates[command.from].removeFirst() ) } } .let { crates } .joinToString("") { crate -> crate.first() } } private fun crateMover9001(input: List<String>): String { val crates = crates(input) return input.asCommands() .forEach { command -> val toMove = crates[command.from].subList(0, command.count) toMove .reversed() .forEach { element -> crates[command.to].addFirst(element) crates[command.from].removeFirst() } } .let { crates } .joinToString("") { crate -> crate.first() } } private const val cratesAmount = 9 // based on input private const val crateSize = 7 // based on input private const val commandsStartIndex = 10 private fun crates(input: List<String>): Array<ArrayDeque<String>> { val crates = Array<ArrayDeque<String>>(cratesAmount) { ArrayDeque() } input .slice(0..crateSize) .forEach { line -> val chunks = line .chunked(4) .map { it.replace("[", "").replace("]", "").replace(" ", "") } for (i in crates.indices) { if (chunks.getOrNull(i) != null && chunks[i].isNotEmpty()) { crates[i].apply { add(chunks[i]) } } } } return crates } private fun List<String>.asCommands() = this .slice(commandsStartIndex until size) .map { it.toCommand() } private fun String.toCommand(): Command { val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() val (count, from, to) = regex.matchEntire(this)!!.destructured return Command( from = from.toInt() - 1, // shift to adjust to input indexes to = to.toInt() - 1, // shift to adjust to input indexes count = count.toInt(), ) } private data class Command(val from: Int, val to: Int, val count: Int)
0
Kotlin
0
0
e08b65e632ace32b494716c7908ad4a0f5c6d7ef
2,256
AoC22
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day13.kt
clechasseur
567,968,171
false
{"Kotlin": 493887}
package io.github.clechasseur.adventofcode.y2022 import io.github.clechasseur.adventofcode.y2022.data.Day13Data object Day13 { private val input = Day13Data.input fun part1(): Int = input.toPairs().withIndex().filter { (_, pair) -> pair.first <= pair.second }.sumOf { it.index + 1 } fun part2(): Int { val dividerPacket1 = ListElement(listOf(ListElement(listOf(IntElement(2))))) val dividerPacket2 = ListElement(listOf(ListElement(listOf(IntElement(6))))) val packets = (input.toPairs().flatMap { listOf(it.first, it.second) } + dividerPacket1 + dividerPacket2).sorted() val index1 = packets.indexOf(dividerPacket1) + 1 val index2 = packets.indexOf(dividerPacket2) + 1 return index1 * index2 } private sealed interface Element : Comparable<Element> private data class IntElement(val value: Int) : Element { override fun compareTo(other: Element): Int = when (other) { is IntElement -> value.compareTo(other.value) is ListElement -> ListElement(listOf(this)).compareTo(other) } } private data class ListElement(val elements: List<Element>) : Element { override fun compareTo(other: Element): Int = when (other) { is IntElement -> compareTo(ListElement(listOf(other))) is ListElement -> { val cmp = elements.zip(other.elements).map { (a, b) -> a.compareTo(b) }.firstOrNull { it != 0 } ?: 0 if (cmp != 0) cmp else elements.size.compareTo(other.elements.size) } } } private fun String.toPairs(): List<Pair<Element, Element>> = lineSequence().filter { it.isNotBlank() }.chunked(2).map { (a, b) -> a.toElement() to b.toElement() }.toList() private fun String.toElement(): Element = when (first()) { '[' -> substring(1 until length - 1).toListElement() else -> toIntElement() } private fun String.toIntElement(): Element = IntElement(toInt()) private fun String.toListElement(): Element { var i = 0 val elements = mutableListOf<Element>() while (i in indices) { if (this[i] == '[') { var j = i + 1 var depth = 1 while (depth > 0) { require(j in indices) { "Mismatched list at position $i in $this" } if (this[j] == '[') { depth++ } else if (this[j] == ']') { depth-- } j++ } elements.add(substring(i until j).toElement()) i = j + 1 } else { var j = i + 1 while (j in indices && this[j] != ',') { j++ } elements.add(substring(i until j).toElement()) i = j + 1 } } return ListElement(elements) } }
0
Kotlin
0
0
7ead7db6491d6fba2479cd604f684f0f8c1e450f
3,060
adventofcode2022
MIT License
src/Day09.kt
msernheim
573,937,826
false
{"Kotlin": 32820}
import kotlin.math.sign fun main() { fun moveTail(head: Coord, tail: Coord): Coord { var tailX = tail.X var tailY = tail.Y val dx = (head.X - tail.X) val dy = (head.Y - tail.Y) if (dx * dx > 1 || dy * dy > 1) { tailX += dx.sign tailY += dy.sign } return Coord(tailX, tailY) } fun part1(input: List<String>): Int { val tailVisits = mutableListOf<Coord>() var currentHead = Coord(0, 0) var currentTail = Coord(0, 0) input.forEach { instruction -> val dir = instruction.split(" ").first() val length = instruction.split(" ").last().toInt() for (i in 0 until length) { when (dir) { "R" -> currentHead.X++ "L" -> currentHead.X-- "U" -> currentHead.Y++ "D" -> currentHead.Y-- else -> break } currentTail = moveTail(currentHead, currentTail) tailVisits.add(currentTail) } } val coordSet = tailVisits.toSet() return coordSet.size } fun moveRope(rope: MutableList<Coord>) { for (i in 0 until rope.size - 1) { val dx = (rope[i].X - rope[i + 1].X) val dy = (rope[i].Y - rope[i + 1].Y) if (dx * dx > 1 || dy * dy > 1) { rope[i + 1].X += dx.sign rope[i + 1].Y += dy.sign } } } fun part2(input: List<String>): Int { val tailVisits = mutableSetOf<Pair<Int,Int>>() val rope = MutableList(10) { Coord(0, 0) } input.forEach { instruction -> val dir = instruction.split(" ").first() val length = instruction.split(" ").last().toInt() for (i in 0 until length) { when (dir) { "R" -> rope[0].X++ "L" -> rope[0].X-- "U" -> rope[0].Y++ "D" -> rope[0].Y-- else -> break } moveRope(rope) tailVisits.add(rope[9].toPair()) } } return tailVisits.size } val input = readInput("Day09") val part1 = part1(input) val part2 = part2(input) println("Result part1: $part1") println("Result part2: $part2") }
0
Kotlin
0
3
54cfa08a65cc039a45a51696e11b22e94293cc5b
2,431
AoC2022
Apache License 2.0
src/main/kotlin/Day004.kt
teodor-vasile
573,434,400
false
{"Kotlin": 41204}
class Day004 { var counter = 0 fun part1(elfPairs: List<List<String>>): Int { for (elfPair in elfPairs) { val firstElf = elfPair[0].split('-').map { it.toInt() } val secondElf = elfPair[1].split('-').map { it.toInt() } countContainingRanges(firstElf, secondElf) } return counter } fun part1Functional(elfPairs: List<List<String>>): Int { elfPairs.forEach { elfPair -> val firstElf = elfPair[0].split('-').map { it.toInt() } val secondElf = elfPair[1].split('-').map { it.toInt() } countContainingRanges(firstElf, secondElf) } return counter } private fun countContainingRanges(firstElf: List<Int>, secondElf: List<Int>) { if ((firstElf[0] >= secondElf[0] && firstElf[1] <= secondElf[1]) || (secondElf[0] >= firstElf[0] && secondElf[1] <= firstElf[1]) ) { counter++ } } fun part2(elfPairs: List<List<String>>): Int { for (elfPair in elfPairs) { val firstElf = elfPair[0].split('-').map { it.toInt() } val secondElf = elfPair[1].split('-').map { it.toInt() } if ((firstElf[1] >= secondElf[0] && firstElf[1] <= secondElf[1]) || (secondElf[1] >= firstElf[0] && secondElf[1] <= firstElf[1]) ) { counter++ } } return counter } fun test() { val pair = Pair("primu", "ultimu") pair.first } // transform to Pair<IntRange, IntRange> -> you can use first and last in an IntRange // substringBefore() method also useful // .count() -> how many of the items in the set match the predicate // https://todd.ginsberg.com/post/advent-of-code/2022/day4/ }
0
Kotlin
0
0
2fcfe95a05de1d67eca62f34a1b456d88e8eb172
1,805
aoc-2022-kotlin
Apache License 2.0
src/Day05.kt
Intex32
574,086,443
false
{"Kotlin": 3973}
import kotlin.math.ceil typealias Stack = List<Crate> @JvmInline value class Crate(val value: String) { override fun toString() = "<$value>" } data class Instr( val amount: Int, val from: Int, val to: Int, ) fun main() { val (rawStacks, rawInstructions) = readInput("Day05") .filter { it.isNotBlank() } .partition { !it.startsWith("move") } // split input file into two halves val stackCount = ceil(rawStacks.maxBy { it.length }.length / 4f).toInt() val stacks: List<Stack> = rawStacks .subList(0, rawStacks.size - 1) .map { it.windowed(size = 4, step = 4, partialWindows = true) } .map { it + (if (it.size < stackCount) List(stackCount - it.size) { null } else emptyList()) } // make sure all columns have the same size .swapRowsAndColumns() // consider stacks rather than horizontal layers of crates .map { stack -> stack .filterNotNull() .filter { it.isNotBlank() } // remove empty cells .map { Crate(it[1].toString()) } } // .onEach { println(it) } val instructions = rawInstructions .map { it.substring(5).split(" from ", " to ") } .map { it.map { it.toInt() } } .map { Instr(amount = it[0], from = it[1], to = it[2]) } // .onEach { println(it) } determineTopCrates(instructions, stacks, keepOrder = false) .also { printP1(it.joinToString("") { it.value }) } determineTopCrates(instructions, stacks, keepOrder = true) .also { printP2(it.joinToString("") { it.value }) } } fun determineTopCrates(instructions: List<Instr>, initialStacks: List<Stack>, keepOrder: Boolean): List<Crate> = instructions.fold(initialStacks) { acc, instruction -> val fromCrate = acc[instruction.from - 1] val movableCrates = fromCrate.subList(0, instruction.amount) .let { if (!keepOrder) it.reversed() else it } val newFromCrate = fromCrate.subList(instruction.amount, fromCrate.size) val newToCrate = acc[instruction.to - 1].toMutableList() .also { it.addAll(0, movableCrates) } acc.mapIndexed { i, stack -> when (i) { instruction.from - 1 -> newFromCrate instruction.to - 1 -> newToCrate else -> stack } } }.map { it.first() } fun <T> List<List<T>>.swapRowsAndColumns() = (0 until first().size) .map { row -> indices.map { col -> this[col][row] } }
0
Kotlin
0
0
6b6f12db6b970afc428787b55ba812ce3eeb85eb
2,456
aoc-kotlin-2022
Apache License 2.0
src/year2022/day07/standardlibrary/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day07.standardlibrary import io.kotest.matchers.shouldBe import utils.readInput fun main() { val testInput = readInput("07", "test_input") val realInput = readInput("07", "input") val testFileSystem = buildFileSystem(testInput) val realFileSystem = buildFileSystem(realInput) testFileSystem.asSequence() .filter { it.size <= 100000 } .sumOf { it.size } .also(::println) shouldBe 95437 realFileSystem.asSequence() .filter { it.size <= 100000 } .sumOf { it.size } .let(::println) val testSpaceToFree = testFileSystem.size - 40_000_000 testFileSystem.asSequence() .sortedBy { it.size } .first { it.size >= testSpaceToFree } .size .also(::println) shouldBe 24933642 val realSpaceToFree = realFileSystem.size - 40_000_000 realFileSystem.asSequence() .sortedBy { it.size } .first { it.size >= realSpaceToFree } .size .let(::println) } private fun buildFileSystem(commands: List<String>) = Folder("/", null).apply { commands.fold(this) { currentFolder, command -> if (command == "$ ls") currentFolder else changeDirectoryRegex.matchEntire(command)?.groupValues?.get(1)?.let { directory -> when (directory) { "/" -> this ".." -> currentFolder.parent!! else -> Folder(directory, currentFolder) .also { currentFolder + it } } } ?: directoryListRegex.matchEntire(command)?.groupValues?.get(1)?.let { name -> currentFolder + Folder(name, currentFolder) } ?: fileListRegex.matchEntire(command)!!.groupValues.let { (_, size, name) -> currentFolder + File(name, size.toLong()) } } } private val changeDirectoryRegex = "\\A\\$ cd (.+)\\z".toRegex() private val directoryListRegex = "\\Adir (.+)\\z".toRegex() private val fileListRegex = "\\A(\\d+) (.+)\\z".toRegex() private sealed interface System { val name: String val size: Long } private class File( override val name: String, override val size: Long, ): System { override fun equals(other: Any?): Boolean = other is File && other.name == name override fun hashCode(): Int = name.hashCode() } private class Folder( override val name: String, val parent: Folder?, ): System, Iterable<System> { val content = mutableSetOf<System>() override val size: Long by lazy { content.sumOf { it.size } } operator fun plus(part: System): Folder = apply { content.add(part) } override fun iterator() = iterator { yield(this@Folder) yieldAll( content.flatMap { system -> system.let { it as? Folder }?.asSequence().orEmpty() } ) } override fun equals(other: Any?): Boolean = other is File && other.name == name override fun hashCode(): Int = name.hashCode() }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,923
Advent-of-Code
Apache License 2.0
src/twentytwo/Day03.kt
mihainov
573,105,304
false
{"Kotlin": 42574}
package twentytwo import readInputTwentyTwo // ext fun to get the priority of the char according to the task fun Char.priority(): Int { val ascii = this.code return if (this.isUpperCase()) { ascii - 38 } else { ascii - 96 } } fun main() { fun part1(input: List<String>): Int { var sum = 0 input.forEach { val firstComp = it.substring(0, it.length / 2).toSet() val secondComp = it.substring(it.length / 2, it.length).toSet() val intersection = firstComp.intersect(secondComp) sum += intersection.single().priority() } return sum } fun part2(input: List<String>): Int { var sum = 0 for (i in input.indices step 3) { sum += (input[i].toSet() intersect input[i + 1].toSet() intersect input[i + 2].toSet()) .single().priority() } return sum } // test if implementation meets criteria from the description, like: val testInput = readInputTwentyTwo("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInputTwentyTwo("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a9aae753cf97a8909656b6137918ed176a84765e
1,265
kotlin-aoc-1
Apache License 2.0
src/Day02.kt
jamOne-
573,851,509
false
{"Kotlin": 20355}
enum class Shape(val value: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun fromChar(inputChar: Char): Shape { return when(inputChar) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> throw IllegalArgumentException() } } } } fun weakerShape(shape: Shape): Shape { return when(shape) { Shape.ROCK -> Shape.SCISSORS Shape.PAPER -> Shape.ROCK Shape.SCISSORS -> Shape.PAPER } } fun strongerShape(shape: Shape): Shape { return when(shape) { Shape.ROCK -> Shape.PAPER Shape.PAPER -> Shape.SCISSORS Shape.SCISSORS -> Shape.ROCK } } const val LOSE_POINTS = 0 const val DRAW_POINTS = 3 const val WIN_POINTS = 6 fun gameResult(me: Shape, opponent: Shape): Int { return if (me == opponent) DRAW_POINTS else if (weakerShape(me) == opponent) WIN_POINTS else LOSE_POINTS; } fun main() { fun part1(input: List<String>): Int { var totalScore = 0 for (line in input) { val opponent = Shape.fromChar(line[0]) val me = Shape.fromChar(line[2]) totalScore += me.value + gameResult(me, opponent); } return totalScore; } fun part2(input: List<String>): Int { var totalScore = 0 for (line in input) { val opponent = Shape.fromChar(line[0]) val result = line[2] if (result == 'X') { // Lose val me = weakerShape(opponent) totalScore += me.value } else if (result == 'Y') { // Draw totalScore += opponent.value + DRAW_POINTS } else { // Win val me = strongerShape(opponent) totalScore += me.value + WIN_POINTS } } return totalScore } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
77795045bc8e800190f00cd2051fe93eebad2aec
2,154
adventofcode2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinDistance.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <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 import kotlin.math.min /** * 583. Delete Operation for Two Strings * @see <a href="https://leetcode.com/problems/delete-operation-for-two-strings/">Source</a> */ fun interface MinDistance { operator fun invoke(word1: String, word2: String): Int } /** * Approach #1 Using Longest Common Subsequence * Time complexity : O(2^{max(m,n)}). * Space complexity : O(max (m,n))). */ class MinDistanceLCS : MinDistance { override operator fun invoke(word1: String, word2: String): Int { return word1.length + word2.length - 2 * lcs(word1, word2, word1.length, word2.length) } private fun lcs(s1: String, s2: String, m: Int, n: Int): Int { if (m == 0 || n == 0) return 0 return if (s1[m - 1] == s2[n - 1]) { 1 + lcs(s1, s2, m - 1, n - 1) } else { max(lcs(s1, s2, m, n - 1), lcs(s1, s2, m - 1, n)) } } } /** * Approach #2 Longest Common Subsequence with Memoization * Time complexity : O(m*n). * Space complexity : O(m*n). */ class MinDistanceLCSMemo : MinDistance { override operator fun invoke(word1: String, word2: String): Int { val memo = Array(word1.length + 1) { IntArray(word2.length + 1) } return word1.length + word2.length - 2 * lcs(word1, word2, word1.length, word2.length, memo) } private fun lcs(s1: String, s2: String, m: Int, n: Int, memo: Array<IntArray>): Int { if (m == 0 || n == 0) { return 0 } if (memo[m][n] > 0) { return memo[m][n] } if (s1[m - 1] == s2[n - 1]) { memo[m][n] = 1 + lcs(s1, s2, m - 1, n - 1, memo) } else { memo[m][n] = max(lcs(s1, s2, m, n - 1, memo), lcs(s1, s2, m - 1, n, memo)) } return memo[m][n] } } /** * Approach #3 Using The Longest Common Subsequence- Dynamic Programming * Time complexity : O(m*n). * Space complexity : O(m*n). */ class MinDistanceLCSDP : MinDistance { override operator fun invoke(word1: String, word2: String): Int { val dp = Array(word1.length + 1) { IntArray(word2.length + 1) } for (i in 0..word1.length) { for (j in 0..word2.length) { if (i == 0 || j == 0) { continue } if (word1[i - 1] == word2[j - 1]) { dp[i][j] = 1 + dp[i - 1][j - 1] } else { dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) } } } return word1.length + word2.length - 2 * dp[word1.length][word2.length] } } /** * Approach #4 Without using LCS Dynamic Programming * Time complexity : O(m*n). * Space complexity : O(m*n). */ class MinDistanceDP : MinDistance { override operator fun invoke(word1: String, word2: String): Int { val dp = Array(word1.length + 1) { IntArray( word2.length + 1, ) } for (i in 0..word1.length) { for (j in 0..word2.length) { if (i == 0 || j == 0) { dp[i][j] = i + j } else if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] } else { dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]) } } } return dp[word1.length][word2.length] } } /** * Approach #5 1-D Dynamic Programming * Time complexity : O(m*n). * Space complexity : O(n). */ class MinDistance1DDP : MinDistance { override operator fun invoke(word1: String, word2: String): Int { var dp = IntArray(word2.length + 1) for (i in 0..word1.length) { val temp = IntArray(word2.length + 1) for (j in 0..word2.length) { if (i == 0 || j == 0) { temp[j] = i + j } else if (word1[i - 1] == word2[j - 1]) { temp[j] = dp[j - 1] } else { temp[j] = 1 + min(dp[j], temp[j - 1]) } } dp = temp } return dp[word2.length] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,841
kotlab
Apache License 2.0
src/Day10.kt
konclave
573,548,763
false
{"Kotlin": 21601}
fun main() { fun solve1(input: List<String>): Int { var total = 0 val ticks = listOf(20, 60, 100, 140, 180, 220) input.flatMap { it.split(" ") }.foldIndexed(1) { i, acc, str -> var res = acc when (str) { "noop", "addx" -> {} else -> { res = acc + str.toInt() } } if (ticks.contains(i + 1)) { val strength = (i + 1) * acc total += strength } res } return total } fun solve2(input: List<String>) { val screen: MutableList<String> = mutableListOf() input.flatMap { it.split(" ") }.foldIndexed(1) { i, acc, str -> var res = acc when (str) { "noop", "addx" -> {} else -> { res = acc + str.toInt() } } val isBeamInPixel = i.mod(40) <= acc + 1 && i.mod(40) >= acc - 1 screen.add(if (isBeamInPixel) "#" else ".") res } screen.chunked(40).map { it.joinToString("") }.forEach { println(it) } } val input = readInput("Day10") println(solve1(input)) println(solve2(input)) }
0
Kotlin
0
0
337f8d60ed00007d3ace046eaed407df828dfc22
1,277
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/niemeyer/aoc2022/Day14.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
/** * Advent of Code 2022, Day 14: * Problem Description: https://adventofcode.com/2022/day/14 */ package de.niemeyer.aoc2022 import de.niemeyer.aoc.points.Point2D import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName typealias ReservoirMap = Map<Point2D, Char> fun main() { val sand = Point2D(500, 0) val air = '.' val moveDown = Point2D(0, 1) val moveLeft = Point2D(-1, 1) val moveRight = Point2D(1, 1) fun parse(input: List<String>): Map<Point2D, Char> = input.map { line -> line.split("->") .map { Point2D.of(it.trim()) } .zipWithNext() .map { (a, b) -> (a lineTo b).map { rock -> rock to '#' } } }.flatten().flatten().toMap() fun getElement(map: MutableMap<Point2D, Char>, point: Point2D, floor: Int): Char { if (point.y == floor) { return '#' // floor } return map.getOrDefault(point, air) } fun solve(reservoir: ReservoirMap, infiniteFloor: Boolean = false): Int { val map = reservoir.toMutableMap() val abyssBeginn = map.keys.maxBy { it.y }.y val floor = if (infiniteFloor) abyssBeginn + 2 else -1 var currentPos = sand var units = 0 var loops = 0 while (currentPos.y <= abyssBeginn || infiniteFloor) { val down = currentPos + moveDown if (getElement(map, down, floor) == air) { currentPos = down } else { val left = currentPos + moveLeft if (getElement(map, left, floor) == air) { currentPos = left } else { val right = currentPos + moveRight if (getElement(map, right, floor) == air) { currentPos = right } else { map[currentPos] = 'o' units++ if (currentPos == sand) { break } currentPos = sand } } } loops++ } return units } fun part1(map: ReservoirMap): Int = solve(map) fun part2(map: ReservoirMap): Int = solve(map, infiniteFloor = true) val name = getClassName() val testInput = parse(resourceAsList(fileName = "${name}_test.txt")).toMap() val puzzleInput = parse(resourceAsList(fileName = "${name}.txt")).toMap() check(part1(testInput) == 24) val testResultPart1 = part1(puzzleInput) println(testResultPart1) check(testResultPart1 == 1001) check(part2(testInput) == 93) val testResultPart2 = part2(puzzleInput) println(testResultPart2) check(testResultPart2 == 27_976) }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
2,889
AoC-2022
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[124]二叉树中的最大路径和.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个非空二叉树,返回其最大路径和。 // // 本题中,路径被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。 // // // // 示例 1: // // 输入:[1,2,3] // // 1 // / \ // 2 3 // //输出:6 // // // 示例 2: // // 输入:[-10,9,20,null,null,15,7] // //  -10 //   / \ //  9  20 //    /  \ //   15   7 // //输出:42 // Related Topics 树 深度优先搜索 递归 // 👍 844 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { var maxSum = Int.MIN_VALUE fun maxPathSum(root: TreeNode?): Int { //递归 获取路径最大值 分别计算 当前节点 和左右子树相加 //时间空间复杂度 O(n) maxPath(root) return maxSum } private fun maxPath(root: TreeNode?) :Int{ //递归结束条件 if(root == null) return 0 //逻辑处理 进入下层循环 var leftmax = Math.max(maxPath(root.left),0) var rightmax = Math.max(maxPath(root.right),0) //当前层最大值 var curMax = root.`val` + leftmax + rightmax //更加最大值记录 maxSum = Math.max(curMax,maxSum) //返回最大值 return root.`val`+Math.max(leftmax,rightmax) } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,701
MyLeetCode
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxNumOfSubstrings.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 dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT import java.util.Stack import kotlin.math.max import kotlin.math.min /** * 1520. Maximum Number of Non-Overlapping Substrings * @see <a href="https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/">Source</a> */ fun interface MaxNumOfSubstrings { operator fun invoke(s: String): List<String> } class MaxNumOfSubstringsGreedy : MaxNumOfSubstrings { override operator fun invoke(s: String): List<String> { val len: Int = s.length val range = Array(ALPHABET_LETTERS_COUNT) { IntArray(2) } for (i in 0 until ALPHABET_LETTERS_COUNT) range[i] = intArrayOf(len, 0) val st: Stack<IntArray> = Stack() val res: MutableList<String> = ArrayList() for (i in 0 until len) { val idx: Int = s[i] - 'a' range[idx][0] = min(i, range[idx][0]) range[idx][1] = max(i, range[idx][1]) } for (i in 0 until len) { val idx: Int = s[i] - 'a' if (range[idx][0] != i) continue val l = range[idx][0] val tail = range[idx][1] val r = getRightMost(l, tail, range, s) if (r < 0) continue while (st.isNotEmpty() && l >= st.peek()[0] && r <= st.peek()[1]) st.pop() st.push(intArrayOf(l, r)) } while (st.isNotEmpty()) res.add(s.substring(st.peek()[0], st.pop()[1] + 1)) return res } private fun getRightMost(l: Int, r: Int, range: Array<IntArray>, s: String): Int { var right = r for (i in l + 1 until right) { val idx = s[i].code - 'a'.code if (range[idx][0] < l) return -1 right = max(right, range[idx][1]) } return right } } class MaxNumOfSubstringsKosaraju : MaxNumOfSubstrings { override operator fun invoke(s: String): List<String> { // some nasty pre-compute in order to build the graph in O(N) time val mins = IntArray(ALPHABET_LETTERS_COUNT) { Int.MAX_VALUE } val maxs = IntArray(ALPHABET_LETTERS_COUNT) { -1 } val exists = BooleanArray(ALPHABET_LETTERS_COUNT) val prefixSum = Array(s.length + 1) { IntArray( ALPHABET_LETTERS_COUNT, ) } for (i in s.indices) { System.arraycopy(prefixSum[i], 0, prefixSum[i + 1], 0, ALPHABET_LETTERS_COUNT) prefixSum[i + 1][s[i] - 'a'] += 1 mins[s[i] - 'a'] = min(mins[s[i] - 'a'], i) maxs[s[i] - 'a'] = maxs[s[i] - 'a'].coerceAtLeast(i) exists[s[i] - 'a'] = true } // build graph, using adjacency matrix val graph = Array(ALPHABET_LETTERS_COUNT) { BooleanArray(ALPHABET_LETTERS_COUNT) } for (i in 0 until ALPHABET_LETTERS_COUNT) { if (exists[i]) { for (j in 0 until ALPHABET_LETTERS_COUNT) { if (prefixSum[maxs[i] + 1][j] - prefixSum[mins[i]][j] > 0) { graph[i][j] = true } } } } // kosaraju algorithm to find scc val stack = Stack() val visited = BooleanArray(ALPHABET_LETTERS_COUNT) for (i in 0 until ALPHABET_LETTERS_COUNT) { if (exists[i] && !visited[i]) { dfs(i, graph, stack, visited) } } var batch = 0 // 'id' of each SCC val batches = IntArray(ALPHABET_LETTERS_COUNT) { -1 } val degree = IntArray(ALPHABET_LETTERS_COUNT) // out-degree of each SCC while (!stack.isEmpty) { val v = stack.pop() if (batches[v] < 0) { dfs(v, graph, batches, batch, degree) batch++ } } val res: MutableList<String> = ArrayList() for (i in batch - 1 downTo 0) { if (degree[i] == 0) { var min = Int.MAX_VALUE var max = -1 for (j in 0 until ALPHABET_LETTERS_COUNT) { if (batches[j] == i) { min = min(mins[j], min) max = max(maxs[j], max) } } res.add(s.substring(min, max + 1)) } } return res } private fun dfs(v: Int, graph: Array<BooleanArray>, stack: Stack, visited: BooleanArray) { if (!visited[v]) { visited[v] = true for (i in 0 until ALPHABET_LETTERS_COUNT) { if (graph[v][i] && !visited[i]) { dfs(i, graph, stack, visited) } } stack.push(v) } } private fun dfs(v: Int, graph: Array<BooleanArray>, batches: IntArray, batch: Int, degree: IntArray) { if (batches[v] < 0) { batches[v] = batch for (i in 0 until ALPHABET_LETTERS_COUNT) { if (graph[i][v]) { dfs(i, graph, batches, batch, degree) } } } else { if (batches[v] != batch) { degree[batches[v]] += 1 } } } private class Stack { var values = IntArray(ALPHABET_LETTERS_COUNT) var top = 0 fun push(value: Int) { values[top++] = value } fun pop(): Int { top-- return values[top] } val isEmpty: Boolean get() = top == 0 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
6,142
kotlab
Apache License 2.0
src/Day07_part1.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { fun part1(input: List<String>): Int { data class Directory( val name: String, var size: Int = 0, val subDirectories: MutableList<Directory> = mutableListOf() ) fun changeDirectory(directory: Directory, name: String): Directory { return directory.subDirectories.find { it.name == name } ?: Directory(name = name) } fun updateSize(directory: Directory): Int { if (directory.subDirectories.isEmpty()) { return directory.size } for (d in directory.subDirectories) { directory.size += updateSize(d) } return directory.size } val limit = 100000 fun totalLimit(directory: Directory): Int { var total = 0 for (d in directory.subDirectories) { total += totalLimit(d) } if (directory.size < limit) { total += directory.size } return total } val history = mutableListOf(Directory(name = "/")) for (i in input.indices) { val split = input[i].split(' ') if (split[0] == "$") { if (split[1] == "cd") { when (split[2]) { ".." -> history.removeLast() "/" -> while (history.size > 1) history.removeLast() else -> history.add(changeDirectory(history.last(), split[2])) } } } else { val split = input[i].split(' ') if (split[0] == "dir") { history.last().subDirectories.add(Directory(name = split[1])) } else { history.last().size += split[0].toInt() } } } updateSize(history.first()) return totalLimit(history.first()) } val testInput = readInput("Day07_test") check(part1(testInput) == 95437) val input = readInput("Day07") println(part1(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
2,127
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day16/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day16 import java.io.File fun main() { val lines = File("src/main/kotlin/day16/input.txt").readLines() val bitsIterator = lines.first().map { hexToBinary(it) }.joinToString(separator = "").iterator() val packet = Packet.parse(bitsIterator) println(packet.versionAggregate()) println(packet.evaluate()) } sealed class Packet(val version: Int) { abstract fun versionAggregate(): Int abstract fun evaluate(): Long class Literal(version: Int, val value: Long) : Packet(version) { override fun versionAggregate() = version override fun evaluate(): Long = value companion object { fun parse(version: Int, iterator: CharIterator): Literal { var lastBitChunk = false var numberBits = "" while (!lastBitChunk) { lastBitChunk = iterator.take(1) == "0" numberBits += iterator.take(4) } return Literal(version, numberBits.toLong(2)) } } } class Operator(version: Int, val type: Int, val subPackets: List<Packet>) : Packet(version) { override fun versionAggregate(): Int = version + subPackets.sumOf { it.versionAggregate() } override fun evaluate(): Long = when (type) { 0 -> subPackets.sumOf { it.evaluate() } 1 -> subPackets.fold(1L) { acc, packet -> acc * packet.evaluate() } 2 -> subPackets.minOf { it.evaluate() } 3 -> subPackets.maxOf { it.evaluate() } 5 -> if (subPackets[0].evaluate() > subPackets[1].evaluate()) 1 else 0 6 -> if (subPackets[0].evaluate() < subPackets[1].evaluate()) 1 else 0 7 -> if (subPackets[0].evaluate() == subPackets[1].evaluate()) 1 else 0 else -> 0L } companion object { fun parse(version: Int, type: Int, iterator: CharIterator): Operator { val lengthType = iterator.take(1) return when (lengthType) { "0" -> { val numberOfBits = iterator.take(15).toInt(2) val subPacketsIterator = iterator.take(numberOfBits).iterator() val packets = mutableListOf<Packet>() while (subPacketsIterator.hasNext()) { packets.add(parse(subPacketsIterator)) } Operator(version, type, packets) } else -> { val numberOfPackets = iterator.take(11).toInt(2) val packets = (1..numberOfPackets).map { parse(iterator) } Operator(version, type, packets) } } } } } companion object { fun parse(iterator: CharIterator): Packet { val version = iterator.take(3).toInt(2) val type = iterator.take(3).toInt(2) return when (type) { 4 -> Literal.parse(version, iterator) else -> Operator.parse(version, type, iterator) } } } } fun CharIterator.take(n: Int): String = this.asSequence().take(n).joinToString("") fun hexToBinary(hex: Char): String { return when (hex) { '0' -> "0000" '1' -> "0001" '2' -> "0010" '3' -> "0011" '4' -> "0100" '5' -> "0101" '6' -> "0110" '7' -> "0111" '8' -> "1000" '9' -> "1001" 'A' -> "1010" 'B' -> "1011" 'C' -> "1100" 'D' -> "1101" 'E' -> "1110" 'F' -> "1111" else -> "" } }
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
3,722
aoc-2021
MIT License
src/main/kotlin/d20/d20.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d20 import readInput fun part1(input: List<String>): Int { val numbers = input.map { it.toInt() }.toList() val list = MutableList(numbers.size) { it } println(numbers) println(list) for (number in numbers.withIndex()) { val pos = list.indexOf(number.index) var newPos = (pos + number.value) % (numbers.size - 1 ) while (newPos < 0) newPos += numbers.size-1 // before first and after last are the same if (pos != newPos) { list.removeAt(pos) list.add(newPos, number.index) } println(list) } var sum = 0 val posZero = list.indexOf(numbers.indexOf(0)) println("zero is at $posZero") var newPos = (posZero+1000) % (list.size) println("1000th = ${numbers[list[newPos]]}") sum += numbers[list[newPos]] newPos = (posZero+2000) % (list.size) println("2000th = ${numbers[list[newPos]]}") sum += numbers[list[newPos]] newPos = (posZero+3000) % (list.size) println("3000th = ${numbers[list[newPos]]}") sum += numbers[list[newPos]] return sum } fun part2(input: List<String>): Long { val numbers = input.map { it.toLong() * 811589153 }.toList() val list = MutableList(numbers.size) { it } println(numbers) println(list) repeat(10) { round -> for (number in numbers.withIndex()) { val pos = list.indexOf(number.index) var newPos = (pos + number.value) % (numbers.size - 1) while (newPos < 0) newPos += numbers.size - 1 // before first and after last are the same if (pos != newPos.toInt()) { list.removeAt(pos) list.add(newPos.toInt(), number.index) } // println(list) } println("$round : ${list.map { numbers[it] }}") } var sum = 0L val posZero = list.indexOf(numbers.indexOf(0)) println("zero is at $posZero") var newPos = (posZero+1000) % (list.size) println("1000th = ${numbers[list[newPos]]}") sum += numbers[list[newPos]] newPos = (posZero+2000) % (list.size) println("2000th = ${numbers[list[newPos]]}") sum += numbers[list[newPos]] newPos = (posZero+3000) % (list.size) println("3000th = ${numbers[list[newPos]]}") sum += numbers[list[newPos]] return sum } fun main() { //val input = readInput("d20/test") //val input = readInput("d20/test2") val input = readInput("d20/input1") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
2,536
aoc2022
Creative Commons Zero v1.0 Universal
src/Day14.kt
zirman
572,627,598
false
{"Kotlin": 89030}
import kotlin.math.max import kotlin.math.min sealed interface Mat { object Air : Mat object Rock : Mat object Sand : Mat } fun main() { fun part1(input: List<String>): Int { val rockRanges = input .map { line -> line.split(" -> ").map { sqrStr -> val (x, y) = sqrStr.split(",") Sqr(y.toInt(), x.toInt()) } } val maxY = max(rockRanges.maxOf { row -> row.maxOf { it.rowIndex } }, 0) + 2 val minX = min(rockRanges.minOf { row -> row.minOf { it.colIndex } }, 500) val maxX = max(rockRanges.maxOf { row -> row.maxOf { it.colIndex } }, 500) val minY = min(rockRanges.minOf { row -> row.minOf { it.rowIndex } }, 0) val width = maxX - minX + 1 val height = maxY - minY + 1 val xRange = minX..maxX val yRange = minY..maxY operator fun Array<Mat>.get(x: Int, y: Int): Mat { return if (x in xRange && y in yRange) this[width * (y - minY) + (x - minX)] else Mat.Air } operator fun Array<Mat>.set(x: Int, y: Int, t: Mat) { this[width * (y - minY) + (x - minX)] = t } val rocks = Array<Mat>(width * height) { Mat.Air } // fun Array<Mat>.toString(width: Int): String { // return toList().chunked(width).joinToString("\n") { row -> // row.joinToString("") { // when (it) { // Mat.Air -> "." // Mat.Rock -> "#" // Mat.Sand -> "o" // } // } // } // } rockRanges.forEach { r -> r.windowed(2, 1).forEach { (a, b) -> val (y1, x1) = a val (y2, x2) = b if (y1 == y2) { (min(x1, x2)..max(x1, x2)).forEach { x -> rocks[x, y1] = Mat.Rock } } else if (x1 == x2) { (min(y1, y2)..max(y1, y2)).forEach { y -> rocks[x1, y] = Mat.Rock } } } } tailrec fun addSand(x: Int, y: Int): Boolean { if ((x in xRange).not() || (y in yRange).not() || rocks[x, y] != Mat.Air) return false return when (Mat.Air) { rocks[x, y + 1] -> { addSand(x, y + 1) } rocks[x - 1, y + 1] -> { addSand(x - 1, y + 1) } rocks[x + 1, y + 1] -> { addSand(x + 1, y + 1) } else -> { rocks[x, y] = Mat.Sand true } } } tailrec fun addSandRec() { if (addSand(500, 0)) { addSandRec() } } addSandRec() return rocks.count { it == Mat.Sand } } fun part2(input: List<String>): Int { val rockRanges = input .map { line -> line.split(" -> ").map { sqrStr -> val (x, y) = sqrStr.split(",") Sqr(y.toInt(), x.toInt()) } } val maxY = max(rockRanges.maxOf { row -> row.maxOf { it.rowIndex } }, 0) + 2 val minX = min(min(rockRanges.minOf { row -> row.minOf { it.colIndex } }, 500), 500 - maxY) val maxX = max(max(rockRanges.maxOf { row -> row.maxOf { it.colIndex } }, 500), 500 + maxY) val minY = min(rockRanges.minOf { row -> row.minOf { it.rowIndex } }, 0) val width = maxX - minX + 1 val height = maxY - minY + 1 val xRange = minX..maxX val yRange = minY..maxY operator fun Array<Mat>.get(x: Int, y: Int): Mat { return if (x in xRange && y in yRange) this[width * (y - minY) + (x - minX)] else Mat.Air } operator fun <T> Array<T>.set(x: Int, y: Int, t: T) { this[width * (y - minY) + (x - minX)] = t } val rocks = Array<Mat>(width * height) { Mat.Air } xRange.forEach { rocks[it, maxY] = Mat.Rock } // fun Array<Mat>.toString(width: Int): String { // return toList().chunked(width).joinToString("\n") { row -> // row.joinToString("") { // when (it) { // Mat.Air -> "." // Mat.Rock -> "#" // Mat.Sand -> "o" // } // } // } // } rockRanges.forEach { r -> r.windowed(2, 1).forEach { (a, b) -> val (y1, x1) = a val (y2, x2) = b if (y1 == y2) { (min(x1, x2)..max(x1, x2)).forEach { x -> rocks[x, y1] = Mat.Rock } } else if (x1 == x2) { (min(y1, y2)..max(y1, y2)).forEach { y -> rocks[x1, y] = Mat.Rock } } } } tailrec fun addSand(x: Int, y: Int): Boolean { if ((x in xRange).not() || (y in yRange).not() || rocks[x, y] != Mat.Air) return false return when (Mat.Air) { rocks[x, y + 1] -> { addSand(x, y + 1) } rocks[x - 1, y + 1] -> { addSand(x - 1, y + 1) } rocks[x + 1, y + 1] -> { addSand(x + 1, y + 1) } else -> { rocks[x, y] = Mat.Sand true } } } tailrec fun addSandRec() { if (addSand(500, 0)) { addSandRec() } } addSandRec() return rocks.count { it == Mat.Sand } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) val input = readInput("Day14") println(part1(input)) check(part2(testInput) == 93) println(part2(input)) }
0
Kotlin
0
1
2ec1c664f6d6c6e3da2641ff5769faa368fafa0f
6,290
aoc2022
Apache License 2.0
src/day07/Day07.kt
molundb
573,623,136
false
{"Kotlin": 26868}
package day07 import readInput fun main() { val input = readInput(parent = "src/day07", name = "Day07_input") println(solvePartOne(input)) println(solvePartTwo(input)) } private fun solvePartOne(input: List<String>): Int { val b = solve(input, calc1()) return b[0] } private fun solvePartTwo(input: List<String>): Int { val a = solve(input, calc2()) a.sort() return a.find { it > a.last() - 40000000 }!! } private fun solve(input: List<String>, calc: (Directory, MutableList<Int>) -> Unit): MutableList<Int> { val directorySizes = mutableListOf<Int>() val rootDir = Directory(name = "/") var currDir = rootDir for (l in input) { if (l == "$ cd /") { currDir = rootDir } else if (l == "$ cd ..") { calc(currDir, directorySizes) currDir = currDir.parent!! } else if (l == "$ ls") { } else if (l.startsWith(prefix = "$ cd")) { currDir = currDir.subDirs.find { it.name == l.split(' ')[2] }!! } else if (l.startsWith(prefix = "dir")) { currDir.subDirs.add(Directory(parent = currDir, name = l.split(' ')[1])) } else { currDir.size += l.split(' ')[0].toInt() } } while (currDir != rootDir) { calc(currDir, directorySizes) currDir = currDir.parent!! } directorySizes.add(rootDir.size) return directorySizes } private fun calc1() = { currDir: Directory, directorySizes: MutableList<Int> -> if (directorySizes.isEmpty()) { directorySizes.add(0) } if (currDir.size <= 100000) { directorySizes[0] += currDir.size } currDir.parent!!.size += currDir.size } private fun calc2() = { currDir: Directory, directorySizes: MutableList<Int> -> directorySizes.add(currDir.size) currDir.parent!!.size += currDir.size } class Directory( val parent: Directory? = null, var name: String, var size: Int = 0, val subDirs: MutableList<Directory> = mutableListOf() )
0
Kotlin
0
0
a4b279bf4190f028fe6bea395caadfbd571288d5
2,022
advent-of-code-2022
Apache License 2.0
src/main/kotlin/org/wow/learning/PlanetFeatures.kt
WonderBeat
22,673,830
false
null
package org.wow.learning import com.epam.starwors.galaxy.Planet fun Planet.enemiesNeighbours(): List<Planet> = this.getNeighbours()!!.filter { it.getOwner() != this.getOwner() && it .getOwner().isNotEmpty() } fun Planet.friendsNeighbours(): List<Planet> = this.getNeighbours()!!.filter { it.getOwner() == this.getOwner() } fun Planet.neutralNeighbours(): List<Planet> = this.getNeighbours()!!.filter { it.getOwner()!!.isEmpty() } fun Collection<Planet>.sumUnits(): Int = this.fold(0) { acc, it -> acc + it.getUnits() } /** * Enemies around percentage */ fun Planet.friendsAroundPercentage(): Double { val allUnits = this.getNeighbours()!!.sumUnits() val friendUnits = this.friendsNeighbours().sumUnits() return when { allUnits == 0 -> 0.0 else -> (100.0 * friendUnits) / allUnits } } fun Planet.neutralAroundPercentage(): Double { val allUnits = this.getNeighbours()!!.size val neutral = this.neutralNeighbours().size return when { allUnits == 0 -> 0.0 else -> (100.0 * neutral) / allUnits } } /** * Enemies around percentage */ fun Planet.enemiesAroundPercentage(): Double { val allUnits = this.getNeighbours()!!.sumUnits() val enemyUnits = this.enemiesNeighbours().sumUnits() return when { allUnits == 0 -> 0.0 else -> (100.0 * enemyUnits) / allUnits } } fun Planet.volumePercentage(): Double = this.getUnits() * 100.0 / this.getType()!!.getLimit() /** * Planet power */ fun Planet.planetPower(): Double = this.getUnits().toDouble() /** * Isolation level % * enemy num / friends num */ fun Planet.isolationLevel(): Double = this.enemiesAroundPercentage().toDouble() / this.friendsAroundPercentage() fun Planet.unitsAfterRegeneration(): Int { val expected = (this.getUnits() + this.getType()!!.getIncrement() * 0.01 * this.getUnits()).toInt() return when { expected > this.getType()!!.getLimit() -> this.getType()!!.getLimit() else -> expected } } fun Planet.percentUsers(percent: Int): Int = (((this.getUnits() * percent).toDouble() / 100.0) + 0.5).toInt()
0
Kotlin
0
0
92625c1e4031ab4439f8d8a47cfeb107c5bd7e31
2,134
suchmarines
MIT License
src/main/kotlin/Day11.kt
brigham
573,127,412
false
{"Kotlin": 59675}
import java.math.BigInteger val pattern = Regex( """Monkey (\d): {2}Starting items: (.*) {2}Operation: new = old ([+*]) (old|\d+) {2}Test: divisible by (.*) {4}If true: throw to monkey (.*) {4}If false: throw to monkey (.*)""" ) enum class Operator { PLUS { override fun apply(a: BigInteger, b: BigInteger): BigInteger { return a + b } }, TIMES { override fun apply(a: BigInteger, b: BigInteger): BigInteger { return a * b } }; abstract fun apply(a: BigInteger, b: BigInteger): BigInteger } sealed class Operand { abstract fun value(op: BigInteger): BigInteger } object SelfOperand : Operand() { override fun value(op: BigInteger) = op } data class IntOperand(val v: BigInteger) : Operand() { override fun value(op: BigInteger) = v } data class Monkey( val which: Int, val items: MutableList<BigInteger>, val operator: Operator, val operand: Operand, val divCheck: BigInteger, val ifTrue: Int, val ifFalse: Int, var score: BigInteger = BigInteger.ZERO ) fun main() { fun parse(input: String): List<Monkey> { val result = mutableListOf<Monkey>() for (match in pattern.findAll(input)) { val g = match.groups result.add( Monkey( g[1]!!.value.toInt(), g[2]!!.value.split(", ").map { it.toBigInteger() }.toMutableList(), when (g[3]!!.value) { "*" -> Operator.TIMES "+" -> Operator.PLUS else -> error("huh") }, when (g[4]!!.value) { "old" -> SelfOperand else -> IntOperand(g[4]!!.value.toBigInteger()) }, g[5]!!.value.toBigInteger(), g[6]!!.value.toInt(), g[7]!!.value.toInt() ) ) } return result } fun part1(input: String): BigInteger { val monkeys = parse(input).toMutableList() println(monkeys) for (round in 0 until 20) { for (monkeyIdx in monkeys.indices) { val monkey = monkeys[monkeyIdx] for (item in monkey.items) { val newWorry = (monkey.operator.apply(item, monkey.operand.value(item))) / BigInteger.valueOf(3L) val check = newWorry % monkey.divCheck val passTo = if (check == BigInteger.ZERO) monkey.ifTrue else monkey.ifFalse monkeys[passTo].items.add(newWorry) } monkeys[monkeyIdx].score += monkey.items.size.toBigInteger() monkeys[monkeyIdx].items.clear() } } println(monkeys) val heap = descendingHeap<BigInteger>() heap.addAll(monkeys.map { it.score }) println(heap) return heap.poll() * heap.poll() } fun part2(input: String): BigInteger { val monkeys = parse(input).toMutableList() val divisor = monkeys.map { it.divCheck }.reduce { a, b -> a * b } println(monkeys) for (round in 0 until 10000) { for (monkeyIdx in monkeys.indices) { val monkey = monkeys[monkeyIdx] for (item in monkey.items) { val newWorry = (monkey.operator.apply(item, monkey.operand.value(item))) % divisor val check = newWorry % monkey.divCheck val passTo = if (check == BigInteger.ZERO) monkey.ifTrue else monkey.ifFalse monkeys[passTo].items.add(newWorry) } monkeys[monkeyIdx].score += monkey.items.size.toBigInteger() monkeys[monkeyIdx].items.clear() } } println(monkeys) val heap = descendingHeap<BigInteger>() heap.addAll(monkeys.map { it.score }) println(heap) val result = heap.poll() * heap.poll() println(result) return result } // test if implementation meets criteria from the description, like: val testInput = slurp("Day11_test") check(part1(testInput) == BigInteger.valueOf(10605L)) check(part2(testInput) == BigInteger.valueOf(2713310158)) val input = slurp("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b87ffc772e5bd9fd721d552913cf79c575062f19
4,382
advent-of-code-2022
Apache License 2.0
src/day04/day04.kt
Dr4kn
575,092,295
false
{"Kotlin": 12652}
package day04 import readInput fun main() { fun stringToIntArray(sections: String): Array<Int> { return sections .split(',', '-') .map { section -> section.toInt() } .toTypedArray() } fun findFullyContained(sections: Array<Int>): Int { // the sections of the first elf fully contain the second one if (sections[0] <= sections[2]) { if (sections[1] >= sections[3]) { return 1 } } // the second one fully contains the first if (sections[2] <= sections[0]) { if (sections[3] >= sections[1]) { return 1 } } return 0 } fun part1(input: List<String>): Int { var sum = 0 input.forEach { sections -> sum += findFullyContained(stringToIntArray(sections)) } return sum } fun findOverlap(sections: Array<Int>): Int { val start1 = sections[0] val end1 = sections[1] val start2 = sections[2] val end2 = sections[3] if (start1 < start2) { if (end1 >= start2) { return 1 } } if (start2 < start1) { if (end2 >= start1) { return 1 } } if (start1 == start2) { return 1 } if (end1 == end2) { return 1 } return 0 } fun part2(input: List<String>): Int { var sum = 0 input.forEach { sections -> sum += findOverlap(stringToIntArray(sections)) } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6de396cb4eeb27ff0dd9a98b56e68a13c2c90cd5
1,988
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/day17/Day17.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day17 import days.Day import java.util.* import kotlin.collections.HashMap class Day17 : Day() { private val heatMap = parseInput(readInput()) override fun partOne(): Any { val size = readInput().size - 1 val start = Coordinate(0, 0) //val result = findShortestPath(start, Coordinate(readInput().first().length - 1, size), 0, 3)!! //printResult(result) //return result.sumOf { it.getWeight() }-start.getWeight() return 0 } override fun partTwo(): Any { val size = readInput().size - 1 val start = Coordinate(0, 0) val result = findShortestPath(start, Coordinate(readInput().first().length - 1, size), 3, 10)!! printResult(result) return result.sumOf { it.getWeight() }-start.getWeight() } fun parseInput(input: List<String>): Map<Coordinate, Int> { val mirrorMap = mutableMapOf<Coordinate, Int>() for (i in input.indices) { for (j in input[i].indices) { mirrorMap[Coordinate(j, i)] = input[i][j].digitToInt() } } return mirrorMap } fun findShortestPath( start: Coordinate, target: Coordinate, minBlocks: Int, maxBlocks: Int ): List<Coordinate>? { val priorityQueue = PriorityQueue<Pair<Pair<Coordinate, Int>, Int>>(compareBy { it.second }) val distance = HashMap<Pair<Coordinate, Int>, Int>() val previous = HashMap<Pair<Coordinate, Int>, Pair<Coordinate, Int>>() var result = mutableListOf<List<Coordinate>>() priorityQueue.add(start to 0 to 0) distance[start to 0] = 0 while (priorityQueue.isNotEmpty()) { val (current, currentDistance) = priorityQueue.poll() val path = getPath(current, previous, start) val neighbours = path.getNextFields(minBlocks, maxBlocks) .filter { heatMap.containsKey(it.first) } for (neighbor in neighbours) { val newDistance = currentDistance + neighbor.first.getWeight() val currentValues = distance.getOrDefault(neighbor, Int.MAX_VALUE) if (newDistance == currentValues) { val lenghtSinceBiegung = current.second val otherLenghtSinceBiegung = getPath(neighbor, previous, start).dropLast(1).last().second if (lenghtSinceBiegung < otherLenghtSinceBiegung) { distance[neighbor] = newDistance previous[neighbor] = current priorityQueue.add(neighbor to newDistance) } } if (newDistance < currentValues) { distance[neighbor] = newDistance previous[neighbor] = current priorityQueue.add(neighbor to newDistance) } } if (current.first == target) { if (current.second in minBlocks+1..maxBlocks) { result.add(getPath(current, previous, start).map { it.first }) } } } val finals = previous.filter { it.key.first == target }.keys val res = finals.map{ getPath(it, previous, start).map { it.first } } return res.last() } fun getPath( curret: Pair<Coordinate, Int>, previous: HashMap<Pair<Coordinate, Int>, Pair<Coordinate, Int>>, start: Coordinate ): List<Pair<Coordinate, Int>> { var node = curret val path = mutableListOf<Pair<Coordinate, Int>>() while (node.first != start) { path.add(node) if (previous[node]!!.second == 0 && previous[node]!!.second > node.second - 1) { println() } node = previous[node]!! } path.add(start to 1) return path.reversed() } private fun Coordinate.getWeight() = heatMap[this]!! fun printResult(result: List<Coordinate>) { for (y in 0 until readInput().size) { for (x in 0 until readInput().first().length) { if (result.contains(Coordinate(x, y))) { print("\u001B[35m${heatMap[Coordinate(x, y)]}\u001B[0m") } else { print(heatMap[Coordinate(x, y)]) } } println() } } } fun List<Pair<Coordinate, Int>>.getNextFields(minBlocks: Int, maxBlocks: Int): List<Pair<Coordinate, Int>> { if (this.size == 1) { return this.last().first.getNeighbours().filter { !this.map { it.first }.contains(it) }.map { it to this.last().second+1 } } if (this.last().second == maxBlocks - 1) { val result = mutableListOf<Pair<Coordinate, Int>>() if (this.last().first.x != this[this.size - 2].first.x) { result.add(Coordinate(this.last().first.x, this.last().first.y - 1) to 0) result.add(Coordinate(this.last().first.x, this.last().first.y + 1) to 0) } else { result.add(Coordinate(this.last().first.x + 1, this.last().first.y) to 0) result.add(Coordinate(this.last().first.x - 1, this.last().first.y) to 0) } return result.filter { !this.map { it.first }.contains(it.first) } } val result = mutableListOf<Pair<Coordinate, Int>>() var newXRowLength = if (this.last().first.x == this[this.size - 2].first.x) this.last().second + 1 else 0 var newYRowLength = if (this.last().first.y == this[this.size - 2].first.y) this.last().second + 1 else 0 if (this.last().second == 0) { newXRowLength = 1 newYRowLength = 1 } if (this.last().second < minBlocks && this.last().first.x == this[this.size - 2].first.x) { result.add(Coordinate(this.last().first.x, this.last().first.y - 1) to newXRowLength) result.add(Coordinate(this.last().first.x, this.last().first.y + 1) to newXRowLength) } else if (this.last().second < minBlocks && this.last().first.y == this[this.size - 2].first.y) { result.add(Coordinate(this.last().first.x + 1, this.last().first.y) to newYRowLength) result.add(Coordinate(this.last().first.x - 1, this.last().first.y) to newYRowLength) } else { result.add(Coordinate(this.last().first.x, this.last().first.y - 1) to newXRowLength) result.add(Coordinate(this.last().first.x, this.last().first.y + 1) to newXRowLength) result.add(Coordinate(this.last().first.x + 1, this.last().first.y) to newYRowLength) result.add(Coordinate(this.last().first.x - 1, this.last().first.y) to newYRowLength) } return result.filter { !this.map { it.first }.contains(it.first) } } class Coordinate(val x: Int, val y: Int) { fun getNeighbours(): List<Coordinate> { return listOf( Coordinate(x - 1, y), Coordinate(x, y - 1), Coordinate(x, y + 1), Coordinate(x + 1, y), ) } override fun toString(): String { return "($x, $y)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Coordinate if (x != other.x) return false if (y != other.y) return false return true } override fun hashCode(): Int { var result = x result = 31 * result + y return result } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
7,510
advent-of-code_2023
The Unlicense
src/main/kotlin/days/Day1.kt
MisterJack49
729,926,959
false
{"Kotlin": 31964}
package days class Day1(alternate: Boolean = false) : Day(1, alternate) { override fun partOne(): Any { return inputList .map { "${it.findFirstDigit()}${it.findLastDigit()}" } .sumOf { it.toInt() } } override fun partTwo(): Any { return inputList .map { val first: Char = it.findFirstDigitComplex() val last: Char = it. findLastDigitComplex() "$first$last" } .sumOf { it.toInt() } } } private fun String.findFirstDigit() = first { it.isDigit() } private fun String.findLastDigit() = last { it.isDigit() } private fun String.firstDigitIndex() = indexOfFirst { it.isDigit() } private fun String.lastDigitIndex() = indexOfLast { it.isDigit() } private fun String.findFirstDigitComplex() = if (firstDigitIndex() == -1) Digit.fromString(findFirstSpelled(firstSpelledIndex())) else if (firstSpelledIndex() == -1) findFirstDigit() else if (firstDigitIndex() < firstSpelledIndex()) findFirstDigit() else Digit.fromString(findFirstSpelled(firstSpelledIndex())) private fun String.findLastDigitComplex() = if (lastDigitIndex() == -1) Digit.fromString(findLastSpelled(lastSpelledIndex())) else if (lastSpelledIndex() == -1) findLastDigit() else if (lastDigitIndex() > lastSpelledIndex()) findLastDigit() else Digit.fromString(findLastSpelled(lastSpelledIndex())) private fun String.firstSpelledIndex() = spelled.map { indexOf(it) } .filter { it > -1 } .run { if(isEmpty()) -1 else min() } private fun String.lastSpelledIndex() = spelled.map { lastIndexOf(it) } .run { if(isEmpty()) -1 else max() } private fun String.findFirstSpelled(idx: Int) = spelled.first { this.startsWith(it, idx) } private fun String.findLastSpelled(idx: Int) = spelled.last { this.startsWith(it, idx) } private val spelled = Digit.values().map { it.spelling } private enum class Digit(val spelling: String, val digit: Char) { One("one", '1'), Two("two", '2'), Three("three", '3'), Four("four", '4'), Five("five", '5'), Six("six", '6'), Seven("seven", '7'), Eight("eight", '8'), Nine("nine", '9'); companion object { fun fromString(string: String) = Digit.values().first { it.spelling == string }.digit } }
0
Kotlin
0
0
807a6b2d3ec487232c58c7e5904138fc4f45f808
2,535
AoC-2023
Creative Commons Zero v1.0 Universal
src/year2022/day22/Day22.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2022.day22 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2022", "Day22_test") check(part1(testInput), 6032) check(part2(testInput), 5031) val input = readInput("2022", "Day22") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val board = parseBoard(input.subList(0, input.size - 2)) val instructions = parseInstructions(input.last()) val (pos, dir) = followPathOnBoard(board, instructions) return (pos.y + 1) * 1000 + (pos.x + 1) * 4 + dir.ordinal } private fun part2(input: List<String>): Int { val board = parseBoard(input.subList(0, input.size - 2)) val instructions = parseInstructions(input.last()) val (pos, dir) = followPathOnCube(board, instructions) return (pos.y + 1) * 1000 + (pos.x + 1) * 4 + dir.ordinal } private fun followPathOnBoard(board: Array<Array<Char>>, instructions: List<Instruction>): Pair<Pos, Direction> { var pos = Pos(board.first().indexOfFirst { it == '.' }, 0) var dir = Direction.Right for (instruction in instructions) { dir = dir.turn(instruction) if (instruction is Instruction.Move) { var steps = instruction.steps while (steps > 0) { val nextPos = board.stepOnBoard(pos, dir) if (nextPos == pos) break pos = nextPos steps-- } } } return pos to dir } private fun followPathOnCube(board: Array<Array<Char>>, instructions: List<Instruction>): Pair<Pos, Direction> { var pos = Pos(board.first().indexOfFirst { it == '.' }, 0) var dir = Direction.Right for (instruction in instructions) { dir = dir.turn(instruction) if (instruction is Instruction.Move) { var steps = instruction.steps while (steps > 0) { val (nextPos, nextDir) = board.stepOnCube(pos, dir) if (nextPos == pos) break dir = nextDir pos = nextPos steps-- } } } return pos to dir } private fun Array<Array<Char>>.stepOnCube(pos: Pos, dir: Direction): Pair<Pos, Direction> { if (size < 50) return stepOnCubeTestPattern(pos, dir) var nextDir = dir var nextPos = when (dir) { Direction.Right -> Pos(pos.x + 1, pos.y) Direction.Down -> Pos(pos.x, pos.y + 1) Direction.Left -> Pos(pos.x - 1, pos.y) Direction.Up -> Pos(pos.x, pos.y - 1) } if (nextPos.y < 0 || (dir == Direction.Up && this[nextPos.y][nextPos.x] == ' ')) { if (nextPos.x in 0..49) { nextPos = Pos(50, 50 + nextPos.x) nextDir = Direction.Right } else if (nextPos.x in 50..99) { nextPos = Pos(0, 100 + nextPos.x) nextDir = Direction.Right } else { nextPos = Pos(nextPos.x - 100, lastIndex) nextDir = Direction.Up } } if (nextPos.y > lastIndex || (dir == Direction.Down && this[nextPos.y][nextPos.x] == ' ')) { if (nextPos.x in 0..49) { nextPos = Pos(nextPos.x + 100, 0) nextDir = Direction.Down } else if (nextPos.x in 50..99) { nextPos = Pos(49, 100 + nextPos.x) nextDir = Direction.Left } else { nextPos = Pos(99, nextPos.x - 50) nextDir = Direction.Left } } if (nextPos.x < 0 || (dir == Direction.Left && this[nextPos.y][nextPos.x] == ' ')) { if (nextPos.y in 0..49) { nextPos = Pos(0, 149 - nextPos.y) nextDir = Direction.Right } else if (nextPos.y in 50..99) { nextPos = Pos(nextPos.y - 50, 100) nextDir = Direction.Down } else if (nextPos.y in 100..149) { nextPos = Pos(50, 49 - (nextPos.y - 100)) // 100 -> 49 ; 149 -> 0 nextDir = Direction.Right } else { nextPos = Pos(nextPos.y - 100, 0) nextDir = Direction.Down } } if (nextPos.x > this[nextPos.y].lastIndex || (dir == Direction.Right && this[nextPos.y][nextPos.x] == ' ')) { if (nextPos.y in 0..49) { nextPos = Pos(99, 100 + (49 - nextPos.y)) nextDir = Direction.Left } else if (nextPos.y in 50..99) { nextPos = Pos(50 + nextPos.y, 49) nextDir = Direction.Up } else if (nextPos.y in 100..149) { nextPos = Pos(149, 49 - (nextPos.y - 100)) // 100 -> 49 ; 149 -> 0 nextDir = Direction.Left } else { nextPos = Pos(nextPos.y - 100, 149) nextDir = Direction.Up } } val c = this[nextPos.y][nextPos.x] if (c == ' ') error("!") if (c == '#') return pos to dir return nextPos to nextDir } private fun Array<Array<Char>>.stepOnCubeTestPattern(pos: Pos, dir: Direction): Pair<Pos, Direction> { var nextDir = dir var nextPos = when (dir) { Direction.Right -> Pos(pos.x + 1, pos.y) Direction.Down -> Pos(pos.x, pos.y + 1) Direction.Left -> Pos(pos.x - 1, pos.y) Direction.Up -> Pos(pos.x, pos.y - 1) } if (nextPos.y < 0 || (dir == Direction.Up && this[nextPos.y][nextPos.x] == ' ')) { if (nextPos.x in 0..3) { nextPos = Pos(11 - nextPos.x, 0) nextDir = Direction.Down } else if (nextPos.x in 4..7) { // This one is required nextPos = Pos(8, nextPos.x - 4) nextDir = Direction.Right } else if (nextPos.x in 8..11) { nextPos = Pos(3 - (nextPos.x - 8), 4) nextDir = Direction.Down } else { nextPos = Pos(11, 7 - (nextPos.x - 12)) nextDir = Direction.Left } } if (nextPos.y > lastIndex || (dir == Direction.Down && this[nextPos.y][nextPos.x] == ' ')) { if (nextPos.x in 0..3) { nextPos = Pos(11 - nextPos.x, 11) nextDir = Direction.Up } else if (nextPos.x in 4..7) { nextPos = Pos(8, 11 - (nextPos.x - 4)) nextDir = Direction.Right } else if (nextPos.x in 8..11) { // This one is required nextPos = Pos(3 - (nextPos.x - 8), 7) nextDir = Direction.Up } else { nextPos = Pos(0, 7 - (nextPos.x - 12)) nextDir = Direction.Right } } if (nextPos.x < 0 || (dir == Direction.Left && this[nextPos.y][nextPos.x] == ' ')) { if (nextPos.y in 0..3) { nextPos = Pos(4 + nextPos.y, 4) nextDir = Direction.Down } else if (nextPos.y in 4..7) { nextPos = Pos(15 - (nextPos.y - 4), 11) nextDir = Direction.Up } else { nextPos = Pos(7 - (nextPos.y - 8), 7) nextDir = Direction.Up } } if (nextPos.x > this[nextPos.y].lastIndex || (dir == Direction.Right && this[nextPos.y][nextPos.x] == ' ')) { if (nextPos.y in 0..3) { nextPos = Pos(15, 11 - nextPos.y) nextDir = Direction.Left } else if (nextPos.y in 4..7) { // This one is required nextPos = Pos(15 - (nextPos.y - 4), 8) nextDir = Direction.Down } else { nextPos = Pos(11, 3 - (nextPos.y - 8)) nextDir = Direction.Left } } val c = this[nextPos.y][nextPos.x] if (c == ' ') error("!") if (c == '#') return pos to dir return nextPos to nextDir } private fun Array<Array<Char>>.stepOnBoard(pos: Pos, dir: Direction): Pos { var nextPos = when (dir) { Direction.Right -> Pos(pos.x + 1, pos.y) Direction.Down -> Pos(pos.x, pos.y + 1) Direction.Left -> Pos(pos.x - 1, pos.y) Direction.Up -> Pos(pos.x, pos.y - 1) } if (nextPos.y < 0 || (dir == Direction.Up && this[nextPos.y][nextPos.x] == ' ')) { nextPos = Pos(nextPos.x, indexOfLast { it[nextPos.x] != ' ' }) } if (nextPos.y > lastIndex || (dir == Direction.Down && this[nextPos.y][nextPos.x] == ' ')) { nextPos = Pos(nextPos.x, indexOfFirst { it[nextPos.x] != ' ' }) } if (nextPos.x < 0 || (dir == Direction.Left && this[nextPos.y][nextPos.x] == ' ')) { nextPos = Pos(this[nextPos.y].indexOfLast { it != ' ' }, nextPos.y) } if (nextPos.x > this[nextPos.y].lastIndex || (dir == Direction.Right && this[nextPos.y][nextPos.x] == ' ')) { nextPos = Pos(this[nextPos.y].indexOfFirst { it != ' ' }, nextPos.y) } val c = this[nextPos.y][nextPos.x] if (c == ' ') error("!") if (c == '#') return pos return nextPos } private data class Pos(val x: Int, val y: Int) private fun parseBoard(input: List<String>): Array<Array<Char>> { val sizeX = input.maxOf { it.length } val sizeY = input.size val board = Array(sizeY) { Array(sizeX) { ' ' } } input.forEachIndexed { y, line -> line.forEachIndexed { x, c -> board[y][x] = c } } return board } private enum class Direction { Right, Down, Left, Up; fun turn(instruction: Instruction): Direction { return when (instruction) { Instruction.TurnRight -> when (this) { Up -> Right Right -> Down Down -> Left Left -> Up } Instruction.TurnLeft -> when (this) { Up -> Left Right -> Up Down -> Right Left -> Down } else -> this } } } private interface Instruction { data class Move(val steps: Int) : Instruction object TurnRight : Instruction object TurnLeft : Instruction } private fun parseInstructions(line: String): List<Instruction> { val parts = "(\\d+|R|L)".toRegex().findAll(line).toList().map { it.value } return parts.map { when (it) { "L" -> Instruction.TurnLeft "R" -> Instruction.TurnRight else -> Instruction.Move(it.toInt()) } } }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
10,129
AdventOfCode
Apache License 2.0
src/Day10.kt
icoffiel
572,651,851
false
{"Kotlin": 29350}
import kotlin.math.ceil private const val DAY = "Day10" fun main() { fun List<String>.parse() = map { when { it.startsWith("noop") -> Command.NoOp() it.startsWith("addx") -> Command.AddX(it.split(" ")[1].toInt()) else -> error("Invalid command: $it") } } .flatMap { when (it) { is Command.AddX -> listOf<Command>(it, it.copy(numberOfOps = it.numberOfOps - 1)) is Command.NoOp -> listOf(it) } } .fold(listOf(State())) { acc: List<State>, command -> when (command) { is Command.AddX -> { when (command.numberOfOps) { 1 -> acc + State( x = acc.last().x + command.number, command = command, xDuring = acc.last().x, cycle = acc.last().cycle + 1 ) else -> acc + State( x = acc.last().x, command = command, xDuring = acc.last().x, cycle = acc.last().cycle + 1 ) } } is Command.NoOp -> acc + State( x = acc.last().x, command = command, xDuring = acc.last().x, cycle = acc.last().cycle + 1 ) } } /** * Work out the row that something falls on given the amount of columns (adjusted for 0 based index) */ fun Int.cycleRow(width: Int = 40): Int { return if (this == 0) { 0 } else { ceil(this.toDouble() / width).toInt() - 1 } } /** * Work out if the register overlaps given a column width. * Register takes up 3 spaces, the current register pointer, 1 before, and 1 after * Register does not wrap to the next line */ fun Int.overlaps(register: Int, columns: Int = 40): Boolean { val modReg = register % columns return (this % columns) in modReg - 1..modReg + 1 } /** * Create a mutable grid of a certain size with an initial default value in each */ fun createGrid(rows: Int, columns: Int, defaultValue: String) = Array(rows) { Array(columns) { defaultValue }.toMutableList() }.toMutableList() fun part1(input: List<String>): Int { return input .parse() .filter { it.cycle in listOf(20, 60, 100, 140, 180, 220) } .sumOf { it.xDuring * it.cycle } } fun MutableList<MutableList<String>>.printGrid() { forEach { row -> row.forEachIndexed { index, column -> print(String.format("%2s", column)) if (index == row.size - 1) { println() } } } } fun part2(input: List<String>): Int { val crt: MutableList<MutableList<String>> = createGrid(6, 40, "") input .parse() .forEach { cycle -> val cycleRow = cycle.cycle.cycleRow() val column = cycle.cycle % 40 when { cycle.x.overlaps(cycle.cycle) -> crt[cycleRow][column] = "#" else -> crt[cycleRow][column] = "." } } crt.printGrid() return input.size } val testInput = readInput("${DAY}_test") check(part1(testInput) == 13140) check(part2(testInput) == 146) val input = readInput(DAY) println("Part One: ${part1(input)}") check(part1(input) == 15140) println("Part Two: ${part2(input)}") check(part2(input) == 137) } sealed class Command { abstract var numberOfOps: Int data class NoOp(override var numberOfOps: Int = 1) : Command() data class AddX(val number: Int, override var numberOfOps: Int = 2) : Command() } data class State(val cycle: Int = 0, val x: Int = 1, val command: Command = Command.NoOp(), val xDuring: Int = 1)
0
Kotlin
0
0
515f5681c385f22efab5c711dc983e24157fc84f
4,238
advent-of-code-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2022/day01/day1.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day01 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val elves = parseElvesCalories(inputFile.bufferedReader().readLines()) println("Elf with most calories has: ${findElfWithMostCalories(elves)?.totalCalories}") val top3ElvesWithMostCalories = findTopElvesWithMostCalories(elves, count = 3) println("Top 3 elves with most calories have: ${top3ElvesWithMostCalories.sumOf { it.totalCalories }}") } data class Elf(val calories: List<Int> = listOf()) { val totalCalories = calories.sum() fun addCalories(calorie: Int) = copy(calories = calories + calorie) } fun parseElvesCalories(lines: Iterable<String>): List<Elf> = lines .fold(listOf(Elf())) { elves, line -> when { line.isEmpty() -> elves + Elf() else -> elves.dropLast(1) + elves.last().addCalories(line.toInt()) } } .filter { it.calories.isNotEmpty() } fun findElfWithMostCalories(elves: List<Elf>): Elf? = elves.maxByOrNull { it.totalCalories } fun findTopElvesWithMostCalories(elves: List<Elf>, count: Int): List<Elf> = elves .sortedByDescending { it.totalCalories } .take(count)
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
1,271
advent-of-code
MIT License
2023/11/solve-1.kts
gugod
48,180,404
false
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
import java.io.File import kotlin.math.abs class Cosmos ( val observation: List<String>, ) { private fun String.allIndicesOf(c: Char) = indices.filter { this[it] == c } val observedEmptyRows : List<Int> = observation.indices .filter { j -> observation[j].all { it == '.' } } val observedEmptyCols : List<Int> = observation[0].indices .filter { i -> observation.indices.all { j -> observation[j][i] == '.' } } val observedGalaxies : List<Pair<Int,Int>> = observation.flatMapIndexed { j, line -> line.allIndicesOf('#').map { Pair(j,it) } } val galaxies : List<Pair<Int,Int>> = observedGalaxies.map { (y,x) -> Pair( y + observedEmptyRows.filter { it < y }.count(), x + observedEmptyCols.filter { it < x }.count() ) } fun sumOfPairwiseGalaticManhattonDistances() : Int { return galaxies.indices.map { i -> (i..galaxies.lastIndex).map { j -> abs(galaxies[i].first - galaxies[j].first) + abs(galaxies[i].second - galaxies[j].second) }.sum() }.sum() return 0 } } println( Cosmos( observation = File("input").readLines().toList() ) .sumOfPairwiseGalaticManhattonDistances() .toString() )
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
1,271
advent-of-code
Creative Commons Zero v1.0 Universal
src/poyea/aoc/mmxxii/day10/Day10.kt
poyea
572,895,010
false
{"Kotlin": 68491}
package poyea.aoc.mmxxii.day10 import poyea.aoc.utils.readInput private const val WIDTH = 40 fun part1(input: String): Int { var cycle = 1 var register = 1 var sum = 0 var flags = 0 input.split("\n").map { it.split(" ") }.forEach { when (it[0]) { "noop" -> cycle += 1 else -> { for (j in 0..1) { cycle += 1 if (j == 1) { register += it[1].toInt() } for (i in 0..5) { if (cycle >= 20 + i * 40 && (flags and (1 shl i)) == 0) { sum += (20 + i * 40) * register flags = flags or (1 shl i) } } } } } } return sum } fun part2(input: String): String { var cycle = 1 var register = 1 var crtImage = "" input.split("\n").map { it.split(" ") }.forEach { when (it[0]) { "noop" -> { crtImage += if ((cycle - 1) % WIDTH in register - 1..register + 1) "#" else "." crtImage += if (cycle % WIDTH == 0) "\n" else "" cycle += 1 } else -> { for (j in 0..1) { crtImage += if ((cycle - 1) % WIDTH in register - 1..register + 1) "#" else "." crtImage += if (cycle % WIDTH == 0) "\n" else "" if (j == 1) { register += it[1].toInt() } cycle += 1 } } } } return crtImage } fun main() { println(part1(readInput("Day10"))) println(part2(readInput("Day10"))) }
0
Kotlin
0
1
fd3c96e99e3e786d358d807368c2a4a6085edb2e
1,780
aoc-mmxxii
MIT License
src/algorithmdesignmanualbook/sorting/KSum.kt
realpacific
234,499,820
false
null
package algorithmdesignmanualbook.sorting import kotlin.test.assertTrue /** * Given a set S of n integers and an integer T, * give an algorithm to test whether k of the integers in S add up to T. * * [Another way](https://www.geeksforgeeks.org/find-the-k-th-permutation-sequence-of-first-n-natural-numbers/) * * ### IDEA: * * ``` * For target=21, k=3 i.e. 21/3 and array: * * ! 5 ! 6 ! 8 ! 10 ! 12 ! * * <------- 21/3 ------> * * ^ <--- 16/2 ---> * * ^ <--- 10/1 ---> * ``` */ class KSum(_input: Array<Int>, private val target: Int, private val k: Int) { val result = mutableListOf<MutableList<Int>>() // Sort it first val array: Array<Int> = _input.sortedArray() fun execute(): List<List<Int>> { for (i in 0..array.lastIndex) { val temp = mutableListOf<Int>() kSumHelper(k, target, i, temp) } println(result) return result } private fun kSumHelper( remainingKCount: Int, remainingSum: Int, currentIndex: Int, temp: MutableList<Int> ) { // array out of bound if (currentIndex > array.lastIndex) { return } // Only 1 item remains if (remainingKCount == 1) { // When you have 1 item remaining, just find if from current index to end, there exists an item == [remainingSum] if (array.sliceArray(currentIndex..array.lastIndex).contains(remainingSum)) { temp.add(remainingSum) // Since sum( [temp] + remainingSum ) == target result.add(temp) return } } temp.add(array[currentIndex]) kSumHelper( remainingKCount = remainingKCount - 1, // Since you consider current element, then decrease the [remainingKCount] remainingSum = remainingSum - array[currentIndex], // Remove it from sum currentIndex = currentIndex + 1, temp = temp ) } } fun main() { val input = arrayOf(-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8) run { KSum(input, 6, 3).execute().forEach { assertTrue { it.sum() == 6 && it.size == 3 } } } run { KSum(input, 8, 2).execute().forEach { assertTrue { it.sum() == 8 && it.size == 2 } } } run { KSum(input, 11, 3).execute().forEach { assertTrue { it.sum() == 11 && it.size == 3 } } } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,574
algorithms
MIT License
src/main/kotlin/ru/timakden/aoc/year2023/Day04.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2023 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import kotlin.math.pow /** * [Day 4: Scratchcards](https://adventofcode.com/2023/day/4). */ object Day04 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2023/Day04") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Int { return input.sumOf { card -> val winningNumbersCount = card.getWinningNumbersCount() 2.0.pow(winningNumbersCount - 1).toInt() } } fun part2(input: List<String>): Int { val cardToTotalCount = mutableMapOf<Int, Int>() val cardToWinningNumbersCount = input.map { card -> val cardNumber = card.substringAfter("Card") .substringBefore(":") .trim() .toInt().also { cardToTotalCount[it] = 1 } cardNumber to card.getWinningNumbersCount() } cardToWinningNumbersCount.forEach { (cardNumber, winningNumbersCount) -> repeat(winningNumbersCount) { cardToTotalCount[cardNumber + it + 1] = checkNotNull(cardToTotalCount[cardNumber + it + 1]) + checkNotNull(cardToTotalCount[cardNumber]) } } return cardToTotalCount.map { it.value }.sum() } private fun String.getWinningNumbersCount(): Int { val digits = "\\d+".toRegex() val (cardNumbers, winningNumbers) = this.substringAfter(":") .split("|") .map { s -> digits.findAll(s).map { it.value.toInt() }.toList() } return cardNumbers.count { it in winningNumbers } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
1,825
advent-of-code
MIT License
jvm/src/main/kotlin/io/prfxn/aoc2021/day05.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Hydrothermal Venture (https://adventofcode.com/2021/day/5) package io.prfxn.aoc2021 import kotlin.math.min import kotlin.math.max import kotlin.math.abs fun main() { val lines = textResourceReader("input/05.txt").readLines() fun part1() { val visited = mutableSetOf<Pair<Int, Int>>() val visitedMulti = mutableSetOf<Pair<Int, Int>>() fun process(x: Int, y: Int,) { val xy = x to y if (xy !in visitedMulti) if (xy in visited) visitedMulti.add(xy) else visited.add(xy) } lines .forEach { line -> val (x1, y1, x2, y2) = line.split(" -> ").map { it.split(",") }.flatten().map { it.toInt() } when { (x1 == x2) -> (min(y1, y2)..max(y1, y2)).forEach { y -> process(x1, y) } (y1 == y2) -> (min(x1, x2)..max(x1, x2)).forEach { x -> process(x, y1) } } } println(visitedMulti.size) } fun part2() { val visited = mutableSetOf<Pair<Int, Int>>() val visitedMulti = mutableSetOf<Pair<Int, Int>>() fun process(x: Int, y: Int) { val xy = x to y if (xy !in visitedMulti) if (xy in visited) visitedMulti.add(xy) else visited.add(xy) } lines .forEach { line -> val (x1, y1, x2, y2) = line.split(" -> ").map { it.split(",") }.flatten().map { it.toInt() } when { (x1 == x2) -> { (min(y1, y2)..max(y1, y2)).forEach { y -> process(x1, y) } } (y1 == y2) -> { (min(x1, x2)..max(x1, x2)).forEach { x -> process(x, y1) } } (abs(y2 - y1) == abs(x2 -x1)) -> { val xStep = if (x2 > x1) 1 else -1 val yStep = if (y2 > y1) 1 else -1 var x = x1 var y = y1 while (true) { process(x, y) if (x == x2) break x += xStep y += yStep } } } } println(visitedMulti.size) } part1() part2() } /** output * 4421 * 18674 */
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
2,709
aoc2021
MIT License
src/Day03.kt
georgiizorabov
573,050,504
false
{"Kotlin": 10501}
fun main() { fun read(input: List<String>): List<Pair<String, String>> { return input.map { str -> Pair( str.substring(0 until str.length / 2), str.substring(str.length / 2 until str.length) ) } } fun read1(input: List<String>): List<List<Char>> { return input.map { str -> str.toCharArray().distinct() }.chunked(3) .map { elems -> elems[0].filter { elem -> elem in elems[1] && elem in elems[2] } } } val charsToAlphabetSum = { elems: List<Char> -> elems.sumOf { elem -> Character.getNumericValue(elem) + if (elem.isUpperCase()) 17 else -9 } } fun part1(input: List<String>): Int { val matches = read(input).map { pair -> pair.first.toCharArray().distinct().filter { it in pair.second.toCharArray().distinct() } } return matches.sumOf { charsToAlphabetSum(it) } } fun part2(input: List<String>): Int { return read1(input).sumOf { charsToAlphabetSum(it) } } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bf84e55fe052c9c5f3121c245a7ae7c18a70c699
1,160
aoc2022
Apache License 2.0
src/day09/Day09.kt
TheRishka
573,352,778
false
{"Kotlin": 29720}
package day09 import readInput import kotlin.math.pow import kotlin.math.roundToInt import kotlin.math.sqrt fun main() { val input = readInput("day09/Day09") val movements = input.flatMap { val movementAmount = it.drop(1).trim().toInt() val movement = when (it.first()) { 'R' -> Movement.RIGHT 'U' -> Movement.UP 'L' -> Movement.LEFT 'D' -> Movement.DOWN else -> error("Invalid input") } buildList { for (amount in 1..movementAmount) { add(movement) } } } fun debugPrint(snakeHead: Point, snakePoints: ArrayList<Point>) { for (y in -4..0) { for (x in 0..5) { val point = Point(x, y) if (point == snakeHead) { print(" H ") } else { val index = snakePoints.indexOfFirst { snakePoint -> snakePoint == point } if (index != -1) { print(" $index ") } if (snakePoints.none { it == point }) { print(" . ") } } } println() } } fun part1(movements: List<Movement>): Int { var tail = Point() var head = Point() val tailMovesHistory = mutableMapOf<Point, Int>() tailMovesHistory[tail] = 0 movements.forEach { movement -> head = when (movement) { Movement.RIGHT -> head.copy(x = head.x + movement.changeX) Movement.LEFT -> head.copy(x = head.x + movement.changeX) Movement.UP -> head.copy(y = head.y + movement.changeY) Movement.DOWN -> head.copy(y = head.y + movement.changeY) } calculateNewPointToMove(head, tail)?.let { tail = it tailMovesHistory[tail] = tailMovesHistory.getOrDefault(it, 0) + 1 } } return tailMovesHistory.size } fun part2(movements: List<Movement>): Int { val snakePoints = ArrayList<Point>() for (count in 0..8) { snakePoints.add(Point()) } var tail = snakePoints.last() var snakeHead = Point() val tailMovesHistory = mutableMapOf<Point, Int>() tailMovesHistory[tail] = 0 movements.forEach { movement -> snakeHead = when (movement) { Movement.RIGHT -> snakeHead.copy(x = snakeHead.x + movement.changeX) Movement.LEFT -> snakeHead.copy(x = snakeHead.x + movement.changeX) Movement.UP -> snakeHead.copy(y = snakeHead.y + movement.changeY) Movement.DOWN -> snakeHead.copy(y = snakeHead.y + movement.changeY) } snakePoints.forEachIndexed { index, snakePoint -> val snakePartHead = if (index == 0) { snakeHead } else { snakePoints[index - 1] } calculateNewPointToMove(snakePartHead, snakePoint)?.let { snakePoints[index] = it if (index == snakePoints.lastIndex) { tail = it tailMovesHistory[tail] = tailMovesHistory.getOrDefault(it, 0) + 1 } } } //debugPrint(snakeHead, snakePoints) } return tailMovesHistory.size } println(part1(movements)) println(part2(movements)) } fun calculateNewPointToMove(head: Point, tail: Point) = when { //vertical/horizontal distance > 1 head.y == tail.y && head.x - 2 == tail.x -> { Point(head.x - 1, head.y) } head.y == tail.y && head.x + 2 == tail.x -> { Point(head.x + 1, head.y) } head.x == tail.x && head.y + 2 == tail.y -> { Point(head.x, head.y + 1) } head.x == tail.x && head.y - 2 == tail.y -> { Point(head.x, head.y - 1) } // diagonal distance > 2 head.distanceTo(tail) > 1 -> { val suitablePointsToMove = listOf( Point(head.x - 1, head.y), Point(head.x + 1, head.y), Point(head.x, head.y - 1), Point(head.x, head.y + 1), Point(head.x - 1, head.y + 1), Point(head.x - 1, head.y - 1), Point(head.x + 1, head.y + 1), Point(head.x + 1, head.y - 1), ).sortedBy { suitablePoint -> suitablePoint.distanceTo(tail) } val newTailPoints = listOf( Point(tail.x + 1, tail.y + 1), // Up-Right Point(tail.x - 1, tail.y + 1), // Up-Left Point(tail.x + 1, tail.y - 1), // Down-Right Point(tail.x - 1, tail.y - 1), // Down-Left ) val newTailPoint = newTailPoints.first { it == suitablePointsToMove[0] || it == suitablePointsToMove[1] } newTailPoint } else -> null } data class Point( val x: Int = 0, val y: Int = 0, ) { fun distanceTo(to: Point): Int { return sqrt(((x - to.x).toFloat().pow(2)) + ((y - to.y).toFloat().pow(2))).roundToInt() } } enum class Movement(val changeX: Int = 0, val changeY: Int = 0) { RIGHT(changeX = 1), LEFT(changeX = -1), UP(changeY = -1), DOWN(changeY = 1), }
0
Kotlin
0
1
54c6abe68c4867207b37e9798e1fdcf264e38658
5,422
AOC2022-Kotlin
Apache License 2.0
src/main/kotlin/divine/brothers/pizza/CandidateSetsApproach.kt
AarjavP
450,892,849
false
{"Kotlin": 28300}
package divine.brothers.pizza import java.math.BigInteger import java.util.* class CandidateSetsApproach(input: Sequence<String>) : PizzaApproach(input) { data class CandidateSetsSolution( override val ingredients: BitSet, val customersSatisfied: Int, val customersSet: CustomersSet ): PizzaSolution class CustomersSet { val likes = BitSet() val dislikes = BitSet() val customers = BitSet() var size = 0 fun offer(customer: Customer): Boolean { if (likes.intersects(customer.dislikes) || dislikes.intersects(customer.likes)) return false likes += customer.likes dislikes += customer.dislikes customers.set(customer.id.id) size++ return true } } fun toValidCombinationOrNull(combination: BitSet): CustomersSet? { val currentSet = CustomersSet() for (index in combination.stream()) { val customer = customers[index] if (!currentSet.offer(customer)) return null } return currentSet } override fun findIngredients(): PizzaSolution { val topCombination = mostBitsSetOrder(customers.size).mapNotNull { val combination = it.toBitSet() toValidCombinationOrNull(combination) }.first() return CandidateSetsSolution(topCombination.likes, topCombination.size, topCombination) } } /** * Converts from BigInteger to BitSet. The BigInteger must be non-negative, * otherwise an IllegalArgumentException is thrown. */ fun BigInteger.toBitSet(): BitSet = BitSet.valueOf(toByteArray().apply { reverse() }) // http://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation fun mostBitsSetOrder(count: Int): Sequence<BigInteger> = sequence { val maxNumber = BigInteger.ONE.shiftLeft(count) for (k in count downTo 1) { println("new k = $k") var currentNumber = BigInteger.ONE.shiftLeft(k) - BigInteger.ONE while(currentNumber < maxNumber) { yield(currentNumber) val temp = currentNumber.or(currentNumber - BigInteger.ONE) currentNumber = (temp + BigInteger.ONE).or( temp.not().and(temp.not().negate()).minus(BigInteger.ONE).shiftRight(currentNumber.lowestSetBit + 1) ) } } } operator fun BitSet.plusAssign(other: BitSet) = this.or(other)
0
Kotlin
0
0
3aaaefc04d55b1e286dde0895fa32f9c34f5c945
2,425
google-hash-code-2022
MIT License
src/Day04.kt
TrevorSStone
573,205,379
false
{"Kotlin": 9656}
fun main() { fun part1(input: List<String>): Int = input .asSequence() .flatMap { line -> line.split('-', ',') } .chunked(2) .map { (first, second) -> first.toInt()..second.toInt() } .chunked(2) .map { (first, second) -> first.intersect(second).let { it.size == first.count() || it.size == second.count() } } .count { it } fun part2(input: List<String>): Int = input .asSequence() .flatMap { line -> line.split('-', ',') } .chunked(2) .map { (first, second) -> first.toInt()..second.toInt() } .chunked(2) .map { (first, second) -> first.intersect(second).isNotEmpty() } .count { it } 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
2a48776f8bc10fe1d7e2bbef171bf65be9939400
957
advent-of-code-2022-kotlin
Apache License 2.0
2020/day19/day19.kt
flwyd
426,866,266
false
{"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398}
/* * Copyright 2021 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package day19 import kotlin.time.ExperimentalTime import kotlin.time.TimeSource import kotlin.time.measureTimedValue /* Input: Two sections, blank line delimited. First section is rules with an int rule ID followed by colon and then rule definition. Rules can be a string ("x"), a space-separated sequence of rule IDs, or a pipe-delimited disjunction of sequences. The second section are strings; check if the whole string matches rule 0. */ /* This would probably by parsing the rules as a BNF-style lexer. */ sealed class Rule { abstract fun matches(text: CharSequence, rules: Map<Int, Rule>): List<Int> companion object { private val orPattern = Regex("""\s*\|\s*""") private val seqPattern = Regex("""\s+""") fun parse(text: String): Rule { return when { text.startsWith("\"") -> Str(text.removeSurrounding("\"")) text.contains("|") -> Or(text.split(orPattern).map { parse(it) }.toList()) else -> Seq(text.split(seqPattern).map(String::toInt).toList()) } } } data class Str(val str: String) : Rule() { override fun matches(text: CharSequence, rules: Map<Int, Rule>): List<Int> { return if (str == text.take(str.length)) listOf(str.length) else listOf() } } data class Seq(val ruleIndices: List<Int>) : Rule() { override fun matches(text: CharSequence, rules: Map<Int, Rule>): List<Int> { if (text.isEmpty() || ruleIndices.isEmpty()) { return listOf() } val rule = rules.getValue(ruleIndices[0]) if (ruleIndices.size == 1) { return rule.matches(text, rules) } return rules.getValue(ruleIndices[0]) .matches(text, rules) .flatMap { len -> Seq(ruleIndices.drop(1)).matches(text.drop(len), rules).map { len + it } } } } data class Or(val choices: List<Rule>) : Rule() { override fun matches(text: CharSequence, rules: Map<Int, Rule>): List<Int> { return choices.asSequence().flatMap { it.matches(text, rules) }.toList() } } } val linePattern = Regex("""(\d+):\s*(.*)""") /* Rules can't create cycles. */ object Part1 { fun solve(input: Sequence<String>): String { val rules = mutableMapOf<Int, Rule>() val iter = input.iterator() while (iter.hasNext()) { val line = iter.next() if (line.isBlank()) { break } linePattern.matchEntire(line)!!.let { match -> val id = match.groupValues[1].toInt() val rule = Rule.parse(match.groupValues[2]) rules[id] = rule } } return Iterable { iter }.filter(String::isNotBlank) .flatMap { line -> rules.getValue(0).matches(line, rules).filter { it == line.length } } .count().toString() } } /* Rules can create cycles in some circumstances; problem statement has two rule replacements. */ object Part2 { fun solve(input: Sequence<String>): String { val replacements = mapOf(8 to "42 | 42 8", 11 to "42 31 | 42 11 31") val rules = mutableMapOf<Int, Rule>() val iter = input.iterator() while (iter.hasNext()) { val line = iter.next() if (line.isBlank()) { break } linePattern.matchEntire(line)!!.let { match -> val id = match.groupValues[1].toInt() val rule = Rule.parse( if (id in replacements) replacements.getValue(id) else match.groupValues[2] ) rules[id] = rule } } return Iterable { iter }.filter(String::isNotBlank) .flatMap { line -> rules.getValue(0).matches(line, rules).filter { it == line.length } } .count().toString() } } @ExperimentalTime @Suppress("UNUSED_PARAMETER") fun main(args: Array<String>) { val lines = generateSequence(::readLine).toList() print("part1: ") TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } print("part2: ") TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } }
0
Julia
1
5
f2d6dbb67d41f8f2898dbbc6a98477d05473888f
4,258
adventofcode
MIT License
src/main/kotlin/Day02.kt
ripla
573,901,460
false
{"Kotlin": 19599}
object Day2 { sealed interface Play { val score: Int val beats: Play val loses: Play } object ROCK : Play { override val score = 1 override val beats = SCISSORS override val loses = PAPER } object PAPER : Play { override val score = 2 override val beats = ROCK override val loses = SCISSORS } object SCISSORS : Play { override val score = 3 override val beats = PAPER override val loses = ROCK } enum class PlayResult(val score: Int) { WIN(6), TIE(3), LOSE(0) } private fun stringPlayToEnum(input: String): Play { return when (input) { in "AX" -> ROCK in "BY" -> PAPER in "CZ" -> SCISSORS else -> { throw Error() } } } private fun calculateScore(opponentPlay: Play, myPlay: Play): Int { val playResult = calculateResult(opponentPlay, myPlay) return playResult.score + myPlay.score } private fun calculateResult(opponentPlay: Play, myPlay: Play): PlayResult { if (myPlay == opponentPlay) { return PlayResult.TIE } if (myPlay.beats == opponentPlay) { return PlayResult.WIN; } return PlayResult.LOSE } private fun playByStrategy(opponentPlayString: String, myStrategy: String): Pair<Play, Play> { val opponentPlay = stringPlayToEnum(opponentPlayString) return when (myStrategy) { "Y" -> Pair(opponentPlay, opponentPlay) "X" -> Pair(opponentPlay, opponentPlay.beats) "Z" -> Pair(opponentPlay, opponentPlay.loses) else -> throw Error() } } fun part1(input: List<String>): Int { return input .map { it.split(" ").toPair() } .map { stringPair -> stringPair.map { stringPlayToEnum(it) }} .sumOf { playPair -> calculateScore(playPair.first, playPair.second) } } fun part2(input: List<String>): Int { return input .map { it.split(" ").toPair() } .map { playPair -> playByStrategy(playPair.first, playPair.second) } .sumOf { playPair -> calculateScore(playPair.first, playPair.second) } } }
0
Kotlin
0
0
e5e6c0bc7a9c6eaee1a69abca051601ccd0257c8
2,316
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2023/day14/Day14.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day14 import com.jacobhyphenated.advent2023.Day /** * Day 14: Parabolic Reflector Dish * * A platform has a bunch of rocks on it. There are controls to tilt the platform in any direction. * Round rocks ('O') will roll while square rocks ('#') will not move. * * The weight on the north pillar is calculated by looking at how many rocks are close to the north edge. * A rock on the farthest south edge is 0. One row up is 1, etc. */ class Day14: Day<List<List<Char>>> { override fun getInput(): List<List<Char>> { return readInputFile("14").lines().map { it.toCharArray().toList() } } /** * Part 1: Tilt the platform north. All rocks move as far as they are able in the north direction. * What is the weight on the north pillar? */ override fun part1(input: List<List<Char>>): Int { val modified = moveRocksNorth(input) return modified.flatMapIndexed{ i, row -> row.map { c -> if (c == 'O') { modified.size - i } else { 0 } } }.sum() } /** * Part 2: A full cycle tilts north, west, south, then east. * Do 1 billion (1_000_000_000) cycles. What is the weight on the north pillar? */ override fun part2(input: List<List<Char>>): Int { var rocks = input val previousRocks = mutableMapOf(input to -1) val cycle = listOf(this::moveRocksNorth, this::moveRocksWest, this::moveRocksSouth, this::moveRocksEast) var i = 0 var foundPattern = false while( i < 1_000_000_000) { rocks = cycle.fold(rocks){ r, tilt -> tilt(r) } if (!foundPattern && rocks in previousRocks) { foundPattern = true val patternDiff = i - previousRocks.getValue(rocks) val patternAdjust = (1_000_000_000 - i ) % patternDiff i = 1_000_000_000 - patternAdjust + 1 continue } previousRocks[rocks] = i i++ } return rocks.flatMapIndexed{ index, row -> row.map { c -> if (c == 'O') { rocks.size - index } else { 0 } } }.sum() } /** * Tilt all rocks north. I really want to come up with a nice functional programming solution * that doesn't require each of these to look so similar. * * Start at the top most row, we can greedily adjust each rock we find. */ private fun moveRocksNorth(grid: List<List<Char>>): List<List<Char>> { val modified = grid.toMutableList().map { it.toMutableList() } for (r in modified.indices) { for (c in modified[r].indices) { if (modified[r][c] == 'O') { var rowIndex = r // go back up the rows until we find an occupied space for (checkRowIndex in r - 1 downTo 0) { if (modified[checkRowIndex][c] != '.') { break } rowIndex = checkRowIndex } modified[rowIndex][c] = 'O' if(r != rowIndex) { modified[r][c] = '.' } } } } return modified } private fun moveRocksSouth(grid: List<List<Char>>): List<List<Char>> { val modified = grid.toMutableList().map { it.toMutableList() } for (r in modified.size - 1 downTo 0) { for (c in modified[r].indices) { if (modified[r][c] == 'O') { var rowIndex = r for (checkRowIndex in r + 1 until modified.size) { if (modified[checkRowIndex][c] != '.') { break } rowIndex = checkRowIndex } modified[rowIndex][c] = 'O' if(r != rowIndex) { modified[r][c] = '.' } } } } return modified } private fun moveRocksWest(grid: List<List<Char>>): List<List<Char>> { val modified = grid.toMutableList().map { it.toMutableList() } for (c in modified[0].indices) { for (r in modified.indices) { if (modified[r][c] == 'O') { var colIndex = c for (checkColIndex in c - 1 downTo 0) { if (modified[r][checkColIndex] != '.') { break } colIndex = checkColIndex } modified[r][colIndex] = 'O' if(c != colIndex) { modified[r][c] = '.' } } } } return modified } private fun moveRocksEast(grid: List<List<Char>>): List<List<Char>> { val modified = grid.toMutableList().map { it.toMutableList() } for (c in modified[0].size - 1 downTo 0) { for (r in modified.indices) { if (modified[r][c] == 'O') { var colIndex = c for (checkColIndex in c + 1 until modified.size) { if (modified[r][checkColIndex] != '.') { break } colIndex = checkColIndex } modified[r][colIndex] = 'O' if(c != colIndex) { modified[r][c] = '.' } } } } return modified } override fun warmup(input: List<List<Char>>) { part1(input) } } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day14().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
5,009
advent2023
The Unlicense
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day13.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2021 import se.saidaspen.aoc.util.* fun main() = Day13.run() object Day13 : Day(2021, 13) { override fun part1(): Any { var dots = input.split("\n\n")[0].lines().map { P(ints(it)[0], ints(it)[1]) }.toSet() val folds = input.split("\n\n")[1].lines() val fold = folds[0].replace("fold along ", "") val dir = fold[0] val amt = ints(fold)[0] dots = if (dir == 'x') foldX(dots, amt) else foldY(dots, amt) return dots.size } override fun part2(): Any { var dots = input.split("\n\n")[0].lines().map { P(ints(it)[0], ints(it)[1]) }.toSet() val folds = input.split("\n\n")[1].lines() for (f in folds) { val fold = f.replace("fold along ", "") val dir = fold[0] val amt = ints(fold)[0] dots = if (dir == 'x') foldX(dots, amt) else foldY(dots, amt) } dots.associateWith { '#' }.printArea() return "JGAJEFKU" } private fun foldX(dots: Set<P<Int, Int>>, amt: Int) = dots.map { if (it.first <= amt) { it } else { P(amt - (it.first - amt), it.second) } }.distinct().toSet() private fun foldY(dots: Set<P<Int, Int>>, amt: Int) = dots.map { if (it.second <= amt) { it } else { val newY = amt - (it.second - amt) P(it.first, newY) } }.distinct().toSet() }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,480
adventofkotlin
MIT License
y2021/src/main/kotlin/adventofcode/y2021/Day15.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution import adventofcode.util.vector.Vec2 import adventofcode.util.vector.neighbors import java.util.* object Day15 : AdventSolution(2021, 15, "Chitons") { override fun solvePartOne(input: String): Int { val grid = parse(input) return findAllPaths(grid, Vec2.origin)[Vec2(grid[0].lastIndex, grid.lastIndex)] } override fun solvePartTwo(input: String): Int { val grid = parse(input) val size = grid.size val bigGrid = List(size * 5) { y -> IntArray(grid[0].size * 5) { x -> (grid[y % size][x % size] + y / size + x / size - 1) % 9 + 1 } } return findAllPaths(bigGrid, Vec2.origin)[Vec2(bigGrid[0].lastIndex, bigGrid.lastIndex)] } private fun parse(input: String) = input.lines().map { it.map { it - '0' }.toIntArray() } private fun findAllPaths(costs: List<IntArray>, start: Vec2): List<IntArray> { val distances = costs.map { IntArray(it.size) { Int.MAX_VALUE } } distances[start] = 0 val open = PriorityQueue(compareBy<Vec2> { distances[it] }) open += start while (open.isNotEmpty()) { val edge = open.poll() for (neighbor in edge.neighbors()) { if (neighbor !in costs) continue val newDistance = distances[edge] + costs[neighbor] if (distances[neighbor] > newDistance) { distances[neighbor] = newDistance open += neighbor } } } return distances } private operator fun List<IntArray>.contains(v: Vec2) = v.y in indices && v.x in get(0).indices private operator fun List<IntArray>.get(v: Vec2) = this[v.y][v.x] private operator fun List<IntArray>.set(v: Vec2, value: Int) { this[v.y][v.x] = value } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,917
advent-of-code
MIT License
src/day05/day05.kt
Dr4kn
575,092,295
false
{"Kotlin": 12652}
package day05 import readInputAsString import java.util.NoSuchElementException fun main() { fun buildInstructionSet(instructions: String): List<List<Int>> { return instructions .replace("(move )|(from )|(to )".toRegex(), "") .lines().map { it.split(" ").map { number -> number.toInt() - 1 } } } fun buildStack(cargo: String): MutableList<MutableList<Char>> { val list: MutableList<MutableList<Char>> = MutableList(cargo.lines().max().length + 1) { mutableListOf() } cargo.lines().dropLast(1).reversed().forEach { for (i in 1 until it.length step 4) { if (it[i] != ' ') { // expects letters list[i / 4].add(it[i]) } } } return list } fun getResult(stack: MutableList<MutableList<Char>>): String { var firstCrates = "" stack.forEach { try { firstCrates += it.last() } catch (e: NoSuchElementException) { // MutableArrays are at least of size 12 return@forEach } } return firstCrates } fun part1(input: String): String { val inputSplit = input.split("\n\n") val stack = buildStack(inputSplit[0]) val instructions = buildInstructionSet(inputSplit[1]) instructions.forEach { list -> for (i in 0..list[0]) { stack[list[2]].add(stack[list[1]].last()) stack[list[1]].removeLast() } } return getResult(stack) } fun part2(input: String): String { val inputSplit = input.split("\n\n") val stack = buildStack(inputSplit[0]) val instructions = buildInstructionSet(inputSplit[1]) instructions.forEach { list -> if (list[0] == 0) { stack[list[2]].add(stack[list[1]].last()) stack[list[1]].removeLast() } else { for ((offset, i) in (stack[list[1]].size - list[0] - 1 until stack[list[1]].size).withIndex()) { stack[list[2]].add(stack[list[1]][i - offset]) stack[list[1]].removeAt(i - offset) } } } return getResult(stack) } // test if implementation meets criteria from the description, like: val testInput = readInputAsString("Day05_test") check(part1(testInput) == "CMZ") val input = readInputAsString("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6de396cb4eeb27ff0dd9a98b56e68a13c2c90cd5
2,692
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2017/Day24.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 /** * AoC 2017, Day 24 * * Problem Description: http://adventofcode.com/2017/day/24 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day24/ */ class Day24(input: List<String>) { private val components = parseInput(input) fun solvePart1(): Int = makeBridges(components).maxBy { it.strength() }?.strength() ?: 0 fun solvePart2(): Int = makeBridges(components) .maxWith( compareBy({ it.size }, { it.strength() }) )?.strength() ?: 0 private fun makeBridges(components: Set<Component>, bridge: List<Component> = emptyList(), port: Int = 0): List<List<Component>> { val compatible = components.filter { it.fits(port) } return when (compatible.size) { 0 -> listOf(bridge) else -> compatible.flatMap { pick -> makeBridges( components - pick, bridge + pick, pick.opposite(port) ) } } } private fun parseInput(input: List<String>): Set<Component> = input.map { it.split("/") }.map { Component(it[0].toInt(), it[1].toInt()) }.toSet() data class Component(private val x: Int, private val y: Int) { val strength = x + y fun fits(port: Int): Boolean = x == port || y == port fun opposite(port: Int): Int = if (port == x) y else x } private fun List<Component>.strength(): Int = this.sumBy { it.strength } }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
1,684
advent-2017-kotlin
MIT License
src/Day03.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
fun main() { val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { return input.sumOf(::calculatePriority) } private fun part2(input: List<String>): Int { return input .chunked(3) { group -> commonPriority(group[0], group[1], group[2]) } .sum() } private fun calculatePriority(row: String): Int { val second = row.takeLast(row.length / 2).toSet() row.forEach { ch -> if (ch in second) { return ch.toPriority() } } error("Not found") } private fun commonPriority(first: String, second: String, third: String): Int { val secondSet = second.toSet() val thirdSet = third.toSet() first.forEach { ch -> if (ch in secondSet && ch in thirdSet) { return ch.toPriority() } } error("Not found") } private fun Char.toPriority(): Int { return if (this.isLowerCase()) { 1 + code - 'a'.code } else { 27 + code - 'A'.code } }
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
1,177
AOC2022
Apache License 2.0