path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/day09/Day09_2.kt
ritesh-singh
572,210,598
false
{"Kotlin": 99540}
package day09 import readInput import kotlin.math.abs fun main() { data class Position(val row: Int, val col: Int) val size = 50000000 val middle = size / 2 var headMain = Position(row = middle, col = middle) var tailsMap = hashMapOf<Int, Position>().apply { for (i in 1..9) { put(i, Position(row = middle, col = middle)) } } var answer = 1 // Tracking for tail - 9 val visited = hashSetOf<Position>() fun update() { if (visited.contains(tailsMap[9])) return ++answer visited.add(tailsMap[9]!!) } fun moveTail(tailKey: Int, headKey: Int?, direction: String) { val head = if (headKey == null) headMain else tailsMap[headKey]!! val tail = tailsMap[tailKey]!! // horizontal if (head.row == tail.row) { if (abs(head.col - tail.col) < 2) return tailsMap[tailKey] = if (head.col > tail.col) { // right tail.copy(col = tail.col + 1) } else { // left tail.copy(col = tail.col - 1) } update() return } // vertical if (head.col == tail.col) { if (abs(head.row - tail.row) < 2) return tailsMap[tailKey] = if (head.row < tail.row) { // up tail.copy(row = tail.row - 1) } else { // down tail.copy(row = tail.row + 1) } update() return } // diagonal if (abs(head.row - tail.row) < 2 && abs(head.col - tail.col) < 2) return // up if (head.row < tail.row) { if (head.col > tail.col) { // right tailsMap[tailKey] = tail.copy( row = tail.row - 1, col = tail.col + 1 ) update() return } // left tailsMap[tailKey] = tail.copy( row = tail.row - 1, col = tail.col - 1 ) update() return } // diagonal - down if (head.col > tail.col) { // right tailsMap[tailKey] = tail.copy( row = tail.row + 1, col = tail.col + 1 ) update() return } // left tailsMap[tailKey] = tail.copy( row = tail.row + 1, col = tail.col - 1 ) update() } fun moveTails(direction: String) { for (i in 1..9) { if (i == 1) { moveTail(tailKey = i, headKey = null, direction = direction) continue } moveTail(tailKey = i, headKey = i - 1, direction = direction) } } fun part2(input: List<String>): Int { headMain = Position(middle, middle) answer = 1 visited.clear() visited.add(tailsMap[9]!!) tailsMap = hashMapOf<Int, Position>().apply { for (i in 1..9) { put(i, Position(row = middle, col = middle)) } } input.forEach { val (direction, step) = it.split(" ").map { it.trim() } var stepCount = step.toInt() while (stepCount > 0) { when (direction) { "R" -> { headMain = headMain.copy(col = headMain.col + 1) } "L" -> { headMain = headMain.copy(col = headMain.col - 1) } "U" -> { headMain = headMain.copy(row = headMain.row - 1) } "D" -> { headMain = headMain.copy(row = headMain.row + 1) } } moveTails(direction) --stepCount } } return answer } val testInput = readInput("/day09/Day09_test") println(part2(testInput)) println("----------------------------------------") val input = readInput("/day09/Day09") println(part2(input)) }
0
Kotlin
0
0
17fd65a8fac7fa0c6f4718d218a91a7b7d535eab
4,199
aoc-2022-kotlin
Apache License 2.0
src/Day01.kt
Kietyo
573,293,671
false
{"Kotlin": 147083}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var highestSum = 0 var currentSum = 0 for (s in input) { if (s.isEmpty()) { highestSum = max(highestSum, currentSum) currentSum = 0 } else { currentSum += s.toInt() } } return highestSum } fun part2(input: List<String>): Unit { val highestScores = mutableListOf<Int>() var currentSum = 0 for (s in input) { if (s.isEmpty()) { highestScores.add(currentSum) currentSum = 0 } else { currentSum += s.toInt() } } highestScores.sortDescending() println(highestScores.take(3).sum()) } // test if implementation meets criteria from the description, like: val testInput = readInput("day1_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("day1_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dd5deef8fa48011aeb3834efec9a0a1826328f2e
1,098
advent-of-code-2022-kietyo
Apache License 2.0
src/Day06.kt
brunojensen
572,665,994
false
{"Kotlin": 13161}
// first implementation private fun String.startOfPacketMarker1(size: Int): Int { var index = 0 while ((index + size) < length - 1) { val subSequence = subSequence(index, index + size) if (subSequence.countDistinct() == size) { return index + size } index++ } return -1 } // Using kotlin standard library private fun String.startOfPacketMarker2(size: Int): Int = windowedSequence(size) .indexOfFirst { it.countDistinct() == size } + size private fun CharSequence.countDistinct(): Int { val set = HashSet<Char>() set.addAll(asIterable()) return set.size } fun main() { fun part1(input: String): Int { return input.startOfPacketMarker1(4) } fun part2(input: String): Int { return input.startOfPacketMarker2(14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06.test").first() check(part1(testInput) == 10) check(part2(testInput) == 29) val input = readInput("Day06").first() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2707e76f5abd96c9d59c782e7122427fc6fdaad1
1,048
advent-of-code-kotlin-1
Apache License 2.0
src/main/kotlin/com/ikueb/advent18/Day07.kt
h-j-k
159,901,179
false
null
package com.ikueb.advent18 object Day07 { private const val DEFINITION = "Step (.) must be finished before step (.) can begin." fun getOrderedSteps(input: List<String>, total: Int = 1, effort: (String) -> Int = { 1 }): Pair<String, ElfWorkers> { val steps = input.parseWith(DEFINITION) { (dependsOn, step) -> Step(step = step, dependsOn = dependsOn) } val dependents: Tracker = mutableMapOf() val dependencies: Tracker = mutableMapOf() steps.forEach { dependents.mergeMutableListValues(it.dependsOn, it.step) dependencies.mergeMutableListValues(it.step, it.dependsOn) } val target = steps.flatMap { listOf(it.step, it.dependsOn) }.distinct().count() val toProcess = dependents .filter { (key, _) -> !dependents.flatMap { it.value }.contains(key) }.keys .sorted() .toMutableSet() val workers = ElfWorkers(total, effort) with(mutableListOf<String>()) { while (size < target) { workers.inWith(toProcess) addAll(workers.outAs(dependents, dependencies, toProcess)) } return joinToString("") to workers } } } private fun <T : Comparable<T>> MutableSet<T>.sortAndPop() = sortedBy { it }[0].also { remove(it) } private data class Step(val step: String, val dependsOn: String) private typealias Tracker = MutableMap<String, MutableList<String>> data class ElfWorkers(val total: Int, val effort: (String) -> Int) { private val workload = mutableMapOf<String, Int>() private var counter = 0 fun getTimeTaken() = counter fun inWith(toProcess: MutableSet<String>) { while (total - workload.size > 0 && toProcess.isNotEmpty()) { val n = toProcess.sortAndPop() workload[n] = effort(n) } } fun outAs(dependents: Tracker, dependencies: Tracker, toProcess: MutableSet<String>): List<String> { val done = mutableListOf<String>() workload.keys.toSet().forEach { key -> workload.updateAndIfNull(key, { _, value -> if (value == 1) null else value - 1 }, { (dependents[key] ?: mutableListOf()).forEach { dependent -> dependencies.updateAndIfNull(dependent, { _, value -> value.remove(key) if (value.isEmpty()) null else value }, { toProcess.add(dependent) }) } done.add(key) }) } counter++ return done.toList() } } private fun <K, V> MutableMap<K, V>.updateAndIfNull(key: K, remapping: (K, V) -> V?, processor: () -> Unit) { computeIfPresent(key, remapping).let { if (it == null) processor() } }
0
Kotlin
0
0
f1d5c58777968e37e81e61a8ed972dc24b30ac76
3,024
advent18
Apache License 2.0
src/main/kotlin/cloud/dqn/leetcode/PermutationsKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/permutations/description/ Given a collection of distinct numbers, return all possible permutations. For example, [1,2,3] have the following permutations: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] */ class PermutationsKt { class Solution { /* [a] = [a] [a,b] = [a,b], [b,a] */ fun permute(nums: IntArray): List<List<Int>> { val result = ArrayList<List<Int>>() // backtrack(result, ArrayList(), nums) val possible = HashSet(nums.toSet()) backAgain(result, ArrayList(), possible, nums.size) return result } private fun backtrack(list: ArrayList<List<Int>>, tempList: ArrayList<Int>, nums: IntArray) { if (tempList.size == nums.size) { list.add(ArrayList(tempList)) } else { nums.forEach { if (!tempList.contains(it)) { val newTemp = ArrayList(tempList) newTemp.add(it) backtrack(list, newTemp, nums) } } } } private fun backAgain(result: ArrayList<List<Int>>, current: ArrayList<Int>, possibles: HashSet<Int>, doneSize: Int) { if (current.size == doneSize) { result.add(current) } else { possibles.forEach { val newPossible = HashSet(possibles) newPossible.remove(it) val newCurrent = ArrayList(current) newCurrent.add(it) backAgain(result, newCurrent, newPossible, doneSize) } } } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
1,859
cloud-dqn-leetcode
No Limit Public License
plugin/src/main/kotlin/com/jraska/module/graph/DependencyGraph.kt
jraska
227,907,412
false
{"Kotlin": 63377}
package com.jraska.module.graph import java.io.Serializable class DependencyGraph private constructor() { private val nodes = mutableMapOf<String, Node>() fun findRoot(): Node { require(nodes.isNotEmpty()) { "Dependency Tree is empty" } val rootCandidates = nodes().toMutableSet() nodes().flatMap { it.dependsOn } .forEach { rootCandidates.remove(it) } return rootCandidates.associateBy { heightOf(it.key) } .maxByOrNull { it.key }!!.value } fun nodes(): Collection<Node> = nodes.values fun dependencyPairs(): List<Pair<String, String>> { return nodes() .flatMap { parent -> parent.dependsOn.map { dependency -> parent to dependency } } .map { it.first.key to it.second.key } } fun longestPath(): LongestPath { return longestPath(findRoot().key) } fun longestPath(key: String): LongestPath { val nodeNames = nodes.getValue(key) .longestPath() .map { it.key } return LongestPath(nodeNames) } fun height(): Int { return heightOf(findRoot().key) } fun heightOf(key: String): Int { return nodes.getValue(key).height() } fun statistics(): GraphStatistics { val height = height() val edgesCount = countEdges() return GraphStatistics( modulesCount = nodes.size, edgesCount = edgesCount, height = height, longestPath = longestPath() ) } fun subTree(key: String): DependencyGraph { require(nodes.contains(key)) { "Dependency Tree doesn't contain module: $key" } val connections = mutableListOf<Pair<String, String>>() addConnections(nodes.getValue(key), connections) return if (connections.isEmpty()) { createSingular(key) } else { create(connections) } } fun serializableGraph(): SerializableGraph { return SerializableGraph( ArrayList(dependencyPairs()), nodes.keys.first() ) } private fun addConnections(node: Node, into: MutableList<Pair<String, String>>) { node.dependsOn.forEach { into.add(node.key to it.key) addConnections(it, into) } } private fun countEdges(): Int { return nodes().flatMap { node -> node.dependsOn }.count() } class SerializableGraph( val dependencyPairs: ArrayList<Pair<String, String>>, val firstModule: String ) : Serializable class Node(val key: String) { val dependsOn = mutableSetOf<Node>() private val calculatedHeight by lazy { if (isLeaf()) { 0 } else { 1 + dependsOn.maxOf { it.height() } } } private fun isLeaf() = dependsOn.isEmpty() fun height(): Int { return calculatedHeight } internal fun longestPath(): List<Node> { if (isLeaf()) { return listOf(this) } else { val path = mutableListOf(this) val maxHeightNode = dependsOn.maxByOrNull { it.height() }!! path.addAll(maxHeightNode.longestPath()) return path } } } companion object { fun createSingular(singleModule: String): DependencyGraph { val dependencyGraph = DependencyGraph() dependencyGraph.getOrCreate(singleModule) return dependencyGraph } fun create(dependencies: List<Pair<String, String>>): DependencyGraph { if (dependencies.isEmpty()) { throw IllegalArgumentException("Graph cannot be empty. Use createSingular for cases with no dependencies") } val graph = DependencyGraph() dependencies.forEach { graph.addEdge(it.first, it.second) } return graph } fun create(vararg dependencies: Pair<String, String>): DependencyGraph { return create(dependencies.asList()) } fun create(graph: SerializableGraph): DependencyGraph { if (graph.dependencyPairs.isEmpty()) { return createSingular(graph.firstModule) } else { return create(graph.dependencyPairs) } } private fun DependencyGraph.addEdge(from: String, to: String) { getOrCreate(from).dependsOn.add(getOrCreate(to)) } private fun DependencyGraph.getOrCreate(key: String): Node { return nodes[key] ?: Node(key).also { nodes[key] = it } } } }
2
Kotlin
16
433
c37ef1d9b4b3f2d61abc6c606b3e08715b73097b
4,185
modules-graph-assert
Apache License 2.0
2016/main/day_03/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_03_2016 import java.io.File fun part1(input: List<String>) { input.map { val strings = it.split(" ").filter { it1 -> it1.isBlank() } strings.map { it1 -> it1.toInt() } }.stream() .filter { (it[0] + it[1] > it[2]) && (it[0] + it[2] > it[1]) && (it[1] + it[2] > it[0]) }.count().let { print("The number of valid triangles is $it") } } fun part2(input: List<String>) { input.map { val strings = it.split(" ").filter { it1 -> it1.isBlank() } strings.map { it1 -> it1.toInt() } }.chunked(3).map { var count = 0 for (i in 0 until 3) { if ((it[0][i] + it[1][i] > it[2][i]) && (it[0][i] + it[2][i] > it[1][i]) && (it[1][i] + it[2][i] > it[0][i])) count++ } count }.sum().let { print("The number of valid triangles is $it") } } fun main(){ val inputFile = File("2016/inputs/Day_03.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines()) print("\n----- Part 2 -----\n") part2(inputFile.readLines()) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
1,084
AdventofCode
MIT License
src/Day04.kt
Scholar17
579,871,947
false
{"Kotlin": 24751}
import java.io.File fun main() { fun parseInputCommaAndNewLine(input: String): List<String> { return input.split(",", "\r\n") } fun parseInputDash(input: String): List<Int> { return input.split("-").map { str -> str.toInt() } } val fileName = "src/Day04_sample.txt" // "src/Day04_quiz.txt" val input = File(fileName).readText() val parseComma = parseInputCommaAndNewLine(input) val parseCommaList = parseComma.chunked(1) val parseDashList = mutableListOf<List<Int>>() for (aList in parseCommaList) { for (element in aList) { parseDashList.add(parseInputDash(element)) } } fun comparedList(input: List<Int>): List<Int> { val pairValue = mutableListOf<Int>() if (input.first() == input.last()) { pairValue.add(input.first()) } else if (input.first() < input.last()) { for (i in input.first() until input.last() + 1) { pairValue.add(i) } } return pairValue } val modifiedList = mutableListOf<List<Int>>() for (aList in parseDashList) { modifiedList.add(comparedList(aList)) } fun checkContain(input: List<List<Int>>): Boolean { var isContain = false for (i in input.indices - 1) { if (input[i].containsAll(input[i + 1])) { isContain = true } else if (input[i + 1].containsAll(input[i])) { isContain = true } } return isContain } fun checkOverlap(input: List<List<Int>>): Boolean { var isOverlap = false for (i in input.indices - 1) { if (input[i].intersect(input[i + 1].toSet()).isNotEmpty()) { isOverlap = true } } return isOverlap } val compareListPart1 = modifiedList.chunked(2) val compareListPart2 = modifiedList.chunked(2) var part1Count = 0 var part2Count = 0 for (aList in compareListPart1) { if (checkContain(aList)) { part1Count++ } } for (aList in compareListPart2) { if (checkOverlap(aList)) { part2Count++ } } println(compareListPart1) println(part1Count) println(compareListPart2) println(part2Count) }
0
Kotlin
0
2
d3d79fbeeb640a990dbeccf2404612b4f7922b38
2,363
aoc-2022-in-kotlin
Apache License 2.0
src/Day14.kt
Jintin
573,640,224
false
{"Kotlin": 30591}
import kotlin.math.max import kotlin.math.min fun main() { val factor = 1000 fun Set<Int>.contains(x: Int, y: Int): Boolean { return this.contains(x * factor + y) } fun MutableSet<Int>.add(x: Int, y: Int) { this.add(x * factor + y) } fun drawX(fill: MutableSet<Int>, start: Int, end: Int, y: Int) { for (i in start..end) { fill.add(i, y) } } fun drawY(fill: MutableSet<Int>, start: Int, end: Int, x: Int) { for (i in start..end) { fill.add(x, i) } } fun buildMap(input: List<String>): Pair<MutableSet<Int>, Int> { val fill = mutableSetOf<Int>() var maxY = 0 // var minX = Int.MAX_VALUE // var maxX = Int.MIN_VALUE input.forEach { str -> val list = str.split(" -> ").map { pair -> pair.split(",").map { value -> value.toInt() } } list.windowed(2) { val (x0, y0) = it[0] val (x1, y1) = it[1] maxY = max(max(y0, y1), maxY) // maxX = max(max(x0, x1), maxX) // minX = min(min(x0, x1), minX) if (x0 == x1) { drawY(fill, min(y0, y1), max(y0, y1), x0) } else { drawX(fill, min(x0, x1), max(x0, x1), y0) } } } return Pair(fill, maxY) } fun part1(input: List<String>): Int { val (fill, maxY) = buildMap(input) var count = 0 while (true) { var (x, y) = Pair(500, 0) while (true) { if (!fill.contains(x, y + 1)) { y += 1 } else if (!fill.contains(x - 1, y + 1)) { x -= 1 y += 1 } else if (!fill.contains(x + 1, y + 1)) { x += 1 y += 1 } else { count++ fill.add(x, y) break } if (y > maxY) { return count } } } } fun part2(input: List<String>): Int { val (fill, maxY) = buildMap(input) var count = 0 while (true) { var (x, y) = Pair(500, 0) while (true) { if (!fill.contains(x, y + 1)) { y += 1 } else if (!fill.contains(x - 1, y + 1)) { x -= 1 y += 1 } else if (!fill.contains(x + 1, y + 1)) { x += 1 y += 1 } else { if (fill.contains(x, y)) { return count } count++ fill.add(x, y) break } if (y == maxY + 1) { count++ fill.add(x, y) break } } } } val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
4aa00f0d258d55600a623f0118979a25d76b3ecb
3,212
AdventCode2022
Apache License 2.0
src/day11/Day11.kt
GrzegorzBaczek93
572,128,118
false
{"Kotlin": 44027}
package day11 import readInput import utils.multiply import utils.split import utils.withStopwatch fun main() { val testInput = readInput("input11_test") withStopwatch { println(part1(testInput)) } withStopwatch { println(part2(testInput)) } val input = readInput("input11") withStopwatch { println(part1(input)) } withStopwatch { println(part2(input)) } } private fun part1(input: List<String>) = input.play(20, 3) private fun part2(input: List<String>) = input.play(10000, 1) private fun List<String>.play(numberOfGames: Int = 1, worryLevelDivisor: Int = 1): Long { val monkeys = this.split { it.isBlank() }.map { Monkey.fromString(it) } val normalizationDivisor = monkeys.map { it.getTestDivisor() }.multiply() fun List<Pair<Long, Int>>.distributeItems() { forEach { (item, monkeyId) -> monkeys.first { monkey -> monkey.id == monkeyId }.addItem(item) } } repeat(numberOfGames) { monkeys.forEach { it.inspect(worryLevelDivisor, normalizationDivisor).distributeItems() } } return monkeys .map { it.inspectionCounter } .sortedDescending().take(2) .multiply() }
0
Kotlin
0
0
543e7cf0a2d706d23c3213d3737756b61ccbf94b
1,203
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/aoc2016/AirDuctSpelunking.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2016 import komu.adventofcode.utils.Point import komu.adventofcode.utils.nonEmptyLines import komu.adventofcode.utils.permutations import utils.shortestPathBetween fun airDuctSpelunking(input: String, returnToStart: Boolean): Int { val map = AirDuctMap.parse(input) val start = map.pointsOfInterest['0'] ?: error("no starting point") val otherPoints = map.pointsOfInterest.values - start return otherPoints.permutations().minOf { permutation -> val path = listOf(start) + permutation + if (returnToStart) listOf(start) else emptyList() path.zipWithNext { a, b -> map.distanceBetween(a, b) }.sum() } } private class AirDuctMap(private val rows: List<String>) { private val distanceCache = mutableMapOf<Pair<Point, Point>, Int>() val pointsOfInterest = buildMap { for ((y, row) in rows.withIndex()) for ((x, c) in row.withIndex()) if (c.isDigit()) this[c] = Point(x, y) } fun distanceBetween(p1: Point, p2: Point): Int { val key = minOf(p1, p2, Point.readingOrderComparator) to maxOf(p1, p2, Point.readingOrderComparator) return distanceCache.getOrPut(key) { shortestPathBetween(p1, p2) { p -> p.neighbors.filter { isPassable(it) } }?.size ?: error("no path") } } private fun isPassable(p: Point) = rows[p.y][p.x] != '#' companion object { fun parse(input: String): AirDuctMap = AirDuctMap(input.nonEmptyLines()) } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,570
advent-of-code
MIT License
src/Day03.kt
Scholar17
579,871,947
false
{"Kotlin": 24751}
import java.io.File import kotlin.math.absoluteValue fun main() { fun parseInput(input: String): List<String> { return input.split("\r\n").map { value -> value } } val fileName = // "src/Day03_sample.txt" "src/Day03_quiz.txt" val inputText = File(fileName).readText() val inputList = parseInput(input = inputText) println(inputList) println() val part1ChunkList = mutableListOf<List<String>>() for (aList in inputList) { part1ChunkList.add(aList.chunked(aList.length / 2)) } var part2ChunkList: List<List<String>> = inputList.chunked(3) println(part2ChunkList) fun findCommonWord(inputList: List<String>): String { val first = inputList.first().toCharArray() val second = inputList.last().toCharArray() var index = "" for (aList in first) { if (second.contains(aList)) { index = aList.toString() } } return index } fun findCommonWordPart2(inputList: List<String>): String { println(inputList) val result = inputList.map { it.chunked(1) } var commonResult = "" for (aList in result) { for (element in aList) { if (result.all { it.contains(element) }) commonResult = element } } println("result") println(result) return commonResult } val commonResultList = mutableListOf<String>() for (aList in part2ChunkList) { commonResultList.add(findCommonWordPart2(aList)) } println(commonResultList) val resultList = mutableListOf<String>() for (aList in part1ChunkList) { resultList.add(findCommonWord(aList)) } println() // println(resultList) fun findNumericPosition(input: String): Int { val charArray = input.toCharArray() var position = 0 for (aList in charArray) { val temp = aList.code val lowerMinus = 96 //for lower case val upperMinus = 38 //for upper case position = if ((temp <= 122) and (temp >= 97)) temp - lowerMinus else temp - upperMinus } return position } var sumNumberPart1 = 0 for (aList in resultList) { sumNumberPart1 += findNumericPosition(aList) } println(sumNumberPart1) var sumNumberPart2 = 0 for (aList in commonResultList) { sumNumberPart2 += findNumericPosition(aList) } println(sumNumberPart2) }
0
Kotlin
0
2
d3d79fbeeb640a990dbeccf2404612b4f7922b38
2,622
aoc-2022-in-kotlin
Apache License 2.0
src/pj_euler/pj57.kt
BenjiDayan
287,910,169
false
{"Kotlin": 19944}
package pj_euler import kotlin.math.floor import kotlin.math.sqrt import kotlin.comparisons.minOf import kotlin.comparisons.maxOf import java.math.BigInteger import kotlin.Boolean //TODO pj 64 fun main(args: Array<String>) { val frac = Fraction(BigInteger.valueOf(6), BigInteger.valueOf(4)) println(frac) frac.reduce() println(frac) val frac2 = Fraction(BigInteger.valueOf(1),BigInteger.valueOf(3)) println(frac.add(frac2)) var idk = CFE(sqrt(2.0)) idk.convergents.add(1) var num = 0 var outputs = mutableListOf(Fraction(BigInteger.valueOf(1),BigInteger.valueOf(4))) for (i in 1..1000) { println(i) //idk.addNextConvergent() //this is inacurrate idk.convergents.add(2) val frac = idk.getFrac() //println(frac) if (frac.top.toString().length > frac.bot.toString().length) { num += 1 outputs.add(frac) println("$i frac was up") } } println("Found $num fractions with top more digits than bot") println(outputs.subList(0, 9)) println(outputs.lastIndex) println(idk.convergents) } class CFE(val target: Double) { var theta_i = target var convergents: MutableList<Int> = mutableListOf() fun addNextConvergent() { convergents.add(floor(theta_i).toInt()) theta_i = 1/(theta_i - convergents.last()) } fun add_many(rep_list: List<Int>, times: Int=1) { for (i in 1..times) { convergents.addAll(rep_list) } } //Returns the approximation of target given by the convergents fun getApproxDouble(): Double { var result = convergents.last().toDouble() for (conv in convergents.subList(0, convergents.lastIndex).reversed()) { result = conv.toDouble() + (1/(result)) } return result } fun getFrac(): Fraction { var result = Fraction(BigInteger(convergents.last().toString())) for (conv in convergents.subList(0, convergents.lastIndex).reversed()) { result = Fraction(BigInteger(conv.toString())).add(result.flipped()) } return result } } class Fraction(var top: BigInteger, var bot: BigInteger = BigInteger.ONE) { fun add(frac: Fraction): Fraction { val topNew = top * frac.bot + bot * frac.top val botNew = bot * frac.bot val newFrac = Fraction(topNew, botNew) newFrac.reduce() return newFrac } fun reduce() { val d = hcf(top, bot) top = top/d bot = bot/d } fun flipped(): Fraction { return Fraction(bot, top) } override fun toString(): String{ return "$top/$bot" } } fun hcf(a: BigInteger, b: BigInteger): BigInteger { var a_i = maxOf(a, b) var b_i = minOf(a, b) while (!b_i.equals(BigInteger.ZERO)) { val q = a_i/b_i val r = a_i - q * b_i a_i = b_i b_i = r } return a_i } fun getFracExplicit(cfe: CFE): Fraction { var result = Fraction(BigInteger(cfe.convergents.last().toString())) println(result) val lastIndex = cfe.convergents.lastIndex for ((i, conv) in cfe.convergents.subList(0, lastIndex).reversed().withIndex()) { println("conv index ${lastIndex-i-1}: $conv + 1/frac = ") result = Fraction(BigInteger(conv.toString())).add(result.flipped()) println(result) } return result }
0
Kotlin
0
0
cde700c0249c115bc305afd7094ce07a2f9963b7
3,555
hello_kotlin
MIT License
year2020/day06/part2/src/main/kotlin/com/curtislb/adventofcode/year2020/day06/part2/Year2020Day06Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- As you finish the last group's customs declaration, you notice that you misread one word in the instructions: You don't need to identify the questions to which anyone answered "yes"; you need to identify the questions to which everyone answered "yes"! Using the same example as above: abc a b c ab ac a a a a b This list represents answers from five groups: - In the first group, everyone (all 1 person) answered "yes" to 3 questions: a, b, and c. - In the second group, there is no question to which everyone answered "yes". - In the third group, everyone answered yes to only 1 question, a. Since some people did not answer "yes" to b or c, they don't count. - In the fourth group, everyone answered yes to only 1 question, a. - In the fifth group, everyone (all 1 person) answered "yes" to 1 question, b. In this example, the sum of these counts is 3 + 0 + 1 + 1 + 1 = 6. For each group, count the number of questions to which everyone answered "yes". What is the sum of those counts? */ package com.curtislb.adventofcode.year2020.day06.part2 import com.curtislb.adventofcode.common.io.forEachSection import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 6, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { val file = inputPath.toFile() var total = 0 val lowerLetters = ('a'..'z').toSet() file.forEachSection { lines -> total += lines.fold(lowerLetters) { answers, line -> answers intersect line.toSet() }.size } return total } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
1,696
AdventOfCode
MIT License
src/main/kotlin/days/Day21.kt
julia-kim
569,976,303
false
null
package days import readInput import kotlin.math.absoluteValue fun main() { fun evaluateExpression(val1: Long, val2: Long, op: Char): Long { return when (op) { '+' -> val1 + val2 '-' -> val1 - val2 '*' -> val1 * val2 '/' -> val1 / val2 else -> throw IllegalStateException() } } fun part1(input: List<String>): Long { val monkeyNumbers = mutableMapOf<String, Long>() val monkeyOperations = mutableMapOf<String, String>() input.forEach { val (name, job) = it.split(": ") if (job.all { it.isDigit() }) monkeyNumbers[name] = job.toLong() else monkeyOperations[name] = job } while (!monkeyNumbers.containsKey("root")) { monkeyOperations.forEach { val (name, job) = it if (!monkeyNumbers.containsKey(name)) { val monkey1 = job.take(4) val monkey2 = job.takeLast(4) val mathOperator = job[5] if (monkeyNumbers.containsKey(monkey1) && monkeyNumbers.containsKey(monkey2)) { monkeyNumbers[name] = evaluateExpression(monkeyNumbers[monkey1]!!, monkeyNumbers[monkey2]!!, mathOperator) } } } } return monkeyNumbers["root"]!! } fun part2(input: List<String>): Long { val monkeyNumbers = mutableMapOf<String, Long>() val monkeyOperations = mutableMapOf<String, String>() input.forEach { val (name, job) = it.split(": ") if (name == "humn") return@forEach if (job.all { it.isDigit() }) monkeyNumbers[name] = job.toLong() else monkeyOperations[name] = job } val monkeyRoot = mutableListOf(monkeyOperations["root"]!!.take(4), monkeyOperations["root"]!!.takeLast(4)) monkeyOperations.remove("root") var magicNumber = 0L while (magicNumber == 0L) { monkeyOperations.forEach { val (name, job) = it if (!monkeyNumbers.containsKey(name)) { val monkey1 = job.take(4) val monkey2 = job.takeLast(4) val mathOperator = job[5] if (monkeyNumbers.containsKey(monkey1) && monkeyNumbers.containsKey(monkey2)) { monkeyNumbers[name] = evaluateExpression(monkeyNumbers[monkey1]!!, monkeyNumbers[monkey2]!!, mathOperator) if (monkeyRoot.contains(name)) magicNumber = monkeyNumbers[name]!! monkeyRoot.remove(name) } } } } monkeyNumbers.keys.forEach { monkeyOperations.remove(it) } monkeyNumbers[monkeyRoot[0]] = magicNumber while (!monkeyNumbers.containsKey("humn")) { monkeyOperations.forEach { val (name, job) = it val monkey1 = job.take(4) val monkey2 = job.takeLast(4) val mathOperator = job[5] when { monkeyNumbers.containsKey(name) && monkeyNumbers.containsKey(monkey1) -> { monkeyNumbers[monkey2] = when (mathOperator) { '+' -> monkeyNumbers[name]!! - monkeyNumbers[monkey1]!! '-' -> (monkeyNumbers[name]!! - monkeyNumbers[monkey1]!!).absoluteValue '*' -> monkeyNumbers[name]!! / monkeyNumbers[monkey1]!! '/' -> monkeyNumbers[name]!! * (1 / monkeyNumbers[monkey1]!!) else -> { throw IllegalStateException() } } } monkeyNumbers.containsKey(name) && monkeyNumbers.containsKey(monkey2) -> { monkeyNumbers[monkey1] = when (mathOperator) { '+' -> monkeyNumbers[name]!! - monkeyNumbers[monkey2]!! '-' -> monkeyNumbers[name]!! + monkeyNumbers[monkey2]!! '*' -> monkeyNumbers[name]!! / monkeyNumbers[monkey2]!! '/' -> monkeyNumbers[name]!! * monkeyNumbers[monkey2]!! else -> { throw IllegalStateException() } } } } } } return monkeyNumbers["humn"]!! } val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
65188040b3b37c7cb73ef5f2c7422587528d61a4
4,888
advent-of-code-2022
Apache License 2.0
day7/src/main/kotlin/be/swsb/aoc2020/Day7.kt
Sch3lp
318,098,967
false
null
package be.swsb.aoc2020 import be.swsb.aoc.common.WeightedGraph class BagRules(stringList: List<String>) : WeightedGraph<Color, Amount>() { init { stringList.map(String::toBagRule) .associateBy { it.color } .mapValues { (_, value) -> value.containedBags } .forEach { (color, vertices) -> vertices?.forEach { v -> addEdge(color, v.first, v.second) } ?: addEdge(color) } } fun traverseDown(node: Color): List<Pair<Color, Amount>> { val edges = _nodes[node] return if (edges == null) { emptyList() } else { edges .fold(emptyList()) { acc, edge -> val mutableAcc = acc.toMutableList() mutableAcc.add(edge) mutableAcc.addAll(traverseDown(edge.first).map { (n, w) -> n to edge.second.times(w) }) mutableAcc } } } } typealias Amount = Int typealias Color = String fun String.toBagRule(): BagRule = BagRule.fromString(this) data class BagRule( val color: Color, val containedBags: List<Pair<Color, Amount>>? ) { companion object { fun fromString(s: String): BagRule { val (color, nestedBagsString) = s.split("bags contain") val nestedBags = if (nestedBagsString.trim().startsWith("no")) { null } else { nestedBagsString.split(", ").flatMap { nestedBagRule(it) } } return BagRule(color.trim(), nestedBags) } private fun nestedBagRule(nestedBagRuleString: String): List<Pair<Color, Amount>> { return nestedBagRuleString.split(",") .map { oneBagRuleString -> val (_, amountOfBags, bagColor) = "(\\d+) (.+) bag".toRegex().findAll(oneBagRuleString).toList() .flatMap { match -> match.groupValues } bagColor to amountOfBags.toInt() } } } }
0
Kotlin
0
0
32630a7efa7893b4540fd91d52c2ff3588174c96
2,040
Advent-of-Code-2020
MIT License
src/Day03.kt
pimtegelaar
572,939,409
false
{"Kotlin": 24985}
fun main() { fun Char.priority() = if (isLowerCase()) code - 96 else code - 38 fun part1(input: List<String>) = input.sumOf { rucksack -> val (first, second) = rucksack.chunked(rucksack.length / 2) second.first { first.contains(it) }.priority() } fun part2(input: List<String>) = input.chunked(3).sumOf { group -> group[0].first { group[1].contains(it) && group[2].contains(it) }.priority() } val testInput = readInput("Day03_test") val input = readInput("Day03") val part1 = part1(testInput) check(part1 == 157) { part1 } println(part1(input)) val part2 = part2(testInput) check(part2 == 70) { part2 } println(part2(input)) }
0
Kotlin
0
0
16ac3580cafa74140530667413900640b80dcf35
709
aoc-2022
Apache License 2.0
src/Day05.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
import java.lang.IllegalArgumentException class CratesState(private val rows: MutableList<MutableList<Char>>) { fun move(count: Int, from: Int, to: Int, reverse: Boolean) { val buffer = mutableListOf<Char>() for (i in 0 until count) { buffer.add(rows[from - 1].removeLast()) } rows[to - 1].addAll(if (reverse) buffer.reversed() else buffer) } fun topCrates(): String = rows.map { it.last() }.joinToString(separator = "") companion object { fun from(serialized: List<String>): CratesState { val rows: MutableList<MutableList<Char>> = mutableListOf() for (i in 0 until (serialized[0].length + 1) / 4) { rows.add(mutableListOf()) } for (line in serialized) { line.chunked(4).forEachIndexed {index: Int, crate: String -> if (crate.isNotBlank()) { rows[index].add(crate[1]) } } } return CratesState(rows) } } } fun main() { fun part1(input: List<String>, reversed: Boolean = false): String { val serializedRows = mutableListOf<String>() var index = 0 while (!input[index].startsWith(" 1")) { serializedRows.add(0, input[index++]) } val state = CratesState.from(serializedRows) val commandPattern = "^move (\\d+) from (\\d+) to (\\d+)$".toRegex() input.subList(index + 2, input.size).forEach { val matcher = commandPattern.find(it) ?: throw IllegalArgumentException(it) val (count, fromRow, toRow) = matcher.destructured state.move(count = count.toInt(), from = fromRow.toInt(), to = toRow.toInt(), reversed) } return state.topCrates() } fun part2(input: List<String>): String { return part1(input, true) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") check(part1(input) == "BZLVHBWQF") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
2,239
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day-2.kt
joebutler2
577,057,170
false
{"Kotlin": 5432}
enum class Move { ROCK, PAPER, SCISSORS } val translations = mapOf( "A" to Move.ROCK, "X" to Move.ROCK, "B" to Move.PAPER, "Y" to Move.PAPER, "C" to Move.SCISSORS, "Z" to Move.SCISSORS, ) fun main(args: Array<String>) { val input = object {}.javaClass.getResourceAsStream("day-2.txt")?.bufferedReader()?.readLines() var score = 0 input?.forEach { val (opponent, me) = it.split(" ") score += calculateRoundScore(translations[opponent]!!, translations[me]!!) } println("And the score is... $score") } fun calculateRoundScore(opponent: Move, me: Move): Int { val base = when (me) { Move.ROCK -> 1 Move.PAPER -> 2 Move.SCISSORS -> 3 } return base + calculateRoundPoints(opponent, me) } const val LOSE_POINTS = 0 const val TIE_POINTS = 3 const val WIN_POINTS = 6 private fun calculateRoundPoints(opponent: Move, me: Move): Int { var roundPoints = 0 when (opponent) { Move.ROCK -> { roundPoints = when (me) { Move.ROCK -> TIE_POINTS Move.PAPER -> WIN_POINTS Move.SCISSORS -> LOSE_POINTS } } Move.PAPER -> { roundPoints = when (me) { Move.ROCK -> LOSE_POINTS Move.PAPER -> TIE_POINTS Move.SCISSORS -> WIN_POINTS } } Move.SCISSORS -> { roundPoints = when (me) { Move.ROCK -> WIN_POINTS Move.PAPER -> LOSE_POINTS Move.SCISSORS -> TIE_POINTS } } } return roundPoints }
0
Kotlin
0
0
7abdecbc4a4397f917c84bd8d8b9f05fb7079c75
1,637
advent-of-code-kotlin
MIT License
src/aoc2022/Day10.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import java.util.* fun main() { fun List<String>.designEachCycleAddedX() = flatMap { line -> val instructionSplit = line.split(" ") return@flatMap if (instructionSplit.first() == "noop") listOf(0) else listOf(0, instructionSplit[1].toInt()) } fun part1(input: List<String>): Int = signalStrengths@ buildList<Int> { input.designEachCycleAddedX().foldIndexed(1) { index, registerX, add -> if (index + 1 in listOf(20, 60, 100, 140, 180, 220)) add((index + 1) * registerX) return@foldIndexed registerX + add } }.sum() fun part2(input: List<String>): String = buildString { var spiritMiddleIndex = 1 input.designEachCycleAddedX().forEachIndexed { index, add -> val rowDrawingIndex = (index % 40) append( // like "i in (-1..1)" if (spiritMiddleIndex - 1 <= rowDrawingIndex && rowDrawingIndex <= spiritMiddleIndex + 1) '#' else '.' ) if ((index + 1) % 40 == 0) appendLine() spiritMiddleIndex += add } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput).also(::println) == 13140) // check(part2(testInput).also(::println) == part2ExampleResult) val input = readInput("Day10") println(part1(input)) println(part2(input)) fun part2Variant(input: List<String>): String = buildString { val spiritPosition = List(40) { if (it < 3) "#" else "." }.toMutableList() input.designEachCycleAddedX().forEachIndexed { index, add -> append(spiritPosition[index % 40]) if ((index + 1) % 40 == 0) { appendLine() } Collections.rotate(spiritPosition, add) } } } private const val part2ExampleResult = """##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######....."""
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
2,288
Kotlin-AOC-2023
Apache License 2.0
leetcode/src/daily/Q811.kt
zhangweizhe
387,808,774
false
null
package daily fun main() { // 811. 子域名访问计数 // https://leetcode.cn/problems/subdomain-visit-count/ println(subdomainVisits(arrayOf("900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"))) } fun subdomainVisits(cpdomains: Array<String>): List<String> { val map = HashMap<String ,Int>() for (cp in cpdomains) { val split = cp.split(" ") val count = split[0].toInt() val domain = split[1] val subDomains = domain.split(".") // 域名最后一段计数 val dLast = subDomains[subDomains.size - 1] var lastCount = map[dLast] if (lastCount == null) { lastCount = count }else { lastCount += count } map[dLast] = lastCount // 域名中间段计数 val dMid = subDomains[subDomains.size - 2] + "." + dLast var midCount = map[dMid] if (midCount == null) { midCount = count }else { midCount += count } map[dMid] = midCount // 域名第一段计数,可能没有 if (subDomains.size > 2) { val dFirst = subDomains[subDomains.size - 3] + "." + dMid var firstCount = map[dFirst] if (firstCount == null) { firstCount = count }else { firstCount += count } map[dFirst] = firstCount } } val result = ArrayList<String>() map.forEach { result.add("${it.value} ${it.key}") } return result }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,577
kotlin-study
MIT License
src/Lesson4CountingElements/FrogRiverOne.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
import java.util.HashSet /** * 100/100 * @param X * @param A * @return */ fun solution(X: Int, A: IntArray): Int { val steps: HashSet<Int> = HashSet<Int>() val result = -1 for (i in A.indices) { steps.add(A[i]) if (steps.size == X) { return i } } return result } /** * A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river. * * You are given an array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in seconds. * * The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves). You may assume that the speed of the current in the river is negligibly small, i.e. the leaves do not change their positions once they fall in the river. * * For example, you are given integer X = 5 and array A such that: * * A[0] = 1 * A[1] = 3 * A[2] = 1 * A[3] = 4 * A[4] = 2 * A[5] = 3 * A[6] = 5 * A[7] = 4 * In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river. * * Write a function: * * class Solution { public int solution(int X, int[] A); } * * that, given a non-empty array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river. * * If the frog is never able to jump to the other side of the river, the function should return −1. * * For example, given X = 5 and array A such that: * * A[0] = 1 * A[1] = 3 * A[2] = 1 * A[3] = 4 * A[4] = 2 * A[5] = 3 * A[6] = 5 * A[7] = 4 * the function should return 6, as explained above. * * Write an efficient algorithm for the following assumptions: * * N and X are integers within the range [1..100,000]; * each element of array A is an integer within the range [1..X]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
2,263
Codility-Kotlin
Apache License 2.0
src/Day10.kt
shoresea
576,381,520
false
{"Kotlin": 29960}
import Command.Instruction.addx import Command.Instruction.noop fun main() { fun part1(inputs: List<String>): Int { val cpu = CPU() for (input in inputs) { val command = Command.parseFrom(input) cpu.process(command) } return cpu.strength() } fun part2(inputs: List<String>): String { val cpu = CPU() for (input in inputs) { val command = Command.parseFrom(input) cpu.process(command) } return cpu.CRT() } val input = readInput("Day10") part1(input).println() part2(input).println() } data class Command(val instruction: Instruction, val value: Int?) { enum class Instruction { addx, noop } companion object { fun parseFrom(input: String): Command = input.split(" ").let { Command( instruction = Instruction.valueOf(it[0]), value = if (it.size == 1) null else it[1].toInt(), ) } } } data class CPU( private var cycle: Int = 0, private var X: Int = 1, private var strength: Int = 0, private var crt: MutableList<Char> = MutableList(240) { '.' }, ) { fun process(command: Command) { when (command.instruction) { noop -> { completeCycle(1) } addx -> { completeCycle(2) addValue(command.value!!) } } } private fun completeCycle(times: Int = 1) { repeat(times) { drawOnCrt() cycle++ updateStrength() } } private fun drawOnCrt() { if (doesSpriteCollidesWithCRTCycle()) crt[cycle] = '#' } private fun doesSpriteCollidesWithCRTCycle(): Boolean = ((X - 1)..(X + 1)).contains(cycle % 40) private fun updateStrength() { val additionalStrength = when (cycle) { 20, 60, 100, 140, 180, 220 -> { cycle * X } else -> 0 } strength += additionalStrength } private fun addValue(value: Int) { X += value } fun strength() = strength fun CRT() = (0..5).joinToString("\n") { val start = it * 40 val end = (it + 1) * 40 crt.subList(start, end).joinToString(" ") } }
0
Kotlin
0
0
e5d21eac78fcd4f1c469faa2967a4fd9aa197b0e
2,365
AOC2022InKotlin
Apache License 2.0
day01/src/main/kotlin/Main.kt
rstockbridge
225,212,001
false
null
fun main() { val inputAsInts = resourceFile("input.txt") .readLines() .map(String::toInt) println("Part I: the solution is ${solvePartI(inputAsInts)}.") println("Part II: the solution is ${solvePartII(inputAsInts)}.") } fun solvePartI(inputAsInts: List<Int>): Int { return calculateTotalFuel(inputAsInts) } fun solvePartII(inputAsInts: List<Int>): Int { return calculateTotalFuelWithAddedFuel(inputAsInts) } fun calculateTotalFuel(masses: List<Int>): Int { return masses.map { calculateModuleFuel(it) }.sum() } fun calculateModuleFuel(mass: Int): Int { return mass / 3 - 2; } fun calculateTotalFuelWithAddedFuel(masses: List<Int>): Int { return masses.map { calculateModuleFuelWithAddedFuel(it) }.sum() } fun calculateModuleFuelWithAddedFuel(mass: Int): Int { var result = 0 var fuelRequirement = calculateModuleFuel(mass) while (fuelRequirement > 0) { result += fuelRequirement fuelRequirement = calculateModuleFuel(fuelRequirement) } return result }
0
Kotlin
0
0
bcd6daf81787ed9a1d90afaa9646b1c513505d75
1,045
AdventOfCode2019
MIT License
src/main/kotlin/aoc2020/HandyHaversacks.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2020 import komu.adventofcode.utils.nonEmptyLines private val rulePattern = Regex("""(.+) bags contain (.+)\.""") private val countPattern = Regex("""(\d+) (.+) bags?""") fun handyHaversacks1(data: String): Int { val rules = parseHaversackRules(data) val work = mutableListOf("shiny gold") val seen = mutableSetOf<String>() var count = 0 while (work.isNotEmpty()) { val bag = work.removeLast() for ((otherBag, contains) in rules) { if (contains.any { it.second == bag } && seen.add(otherBag)) { count++ work += otherBag } } } return count } fun handyHaversacks2(data: String): Int { val rules = parseHaversackRules(data) fun countNested(bag: String): Int = rules[bag]!!.sumBy { (count, b) -> count * (1 + countNested(b)) } return countNested("shiny gold") } private fun parseHaversackRules(data: String): Map<String, Collection<Pair<Int, String>>> { val rules = mutableMapOf<String, Collection<Pair<Int, String>>>() for (line in data.nonEmptyLines()) { val (_, color, contains) = rulePattern.matchEntire(line)?.groupValues ?: error("no match '$line'") rules[color] = if (contains == "no other bags") emptyList() else contains.split(", ").map { val (_ , count, type) = countPattern.matchEntire(it)?.groupValues ?: error("no match '$it'") Pair(count.toInt(), type) } } return rules }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,581
advent-of-code
MIT License
bio-common/src/main/kotlin/bio/relatives/common/utils/MathUtils.kt
SHvatov
325,566,887
false
null
package bio.relatives.common.utils import kotlin.math.pow import kotlin.math.roundToInt import kotlin.math.sqrt /** * Based on the provided [values] calculates the median value. * @author Created by <NAME> on 28.01.2021 */ fun <T : Number> calculateMedianVale(values: List<T>): Double = with(values.map { it.toDouble() }.sorted()) { val middle = size / 2 return@with when { size % 2 != 0 -> get(middle) isNotEmpty() -> (get(middle) - get(middle - 1)) / 2.0 else -> 0.0 } } /** * For provided [values] array calculates the root mean square value. */ fun <T : Number> calculateRootMeanSquare(values: List<T>): Double { values.ifEmpty { return 0.0 } val squareSum = values.map { it.toDouble().pow(2) }.sum() return sqrt(squareSum / values.size) } /** * Returns the average quality value of the [values] list. */ fun <T : Number> calculateAverageQuality(values: List<T>): Double { return values.map { it.toDouble() }.sum() / values.size } /** * Takes a map, where key is some arithmetic value, and value is its calculation error, * and calculates the relative error rate of addition of all this values. */ fun <T : Number> calculateAdditionRelativeErrorRate(valueToError: Map<T, T>): Double { return valueToError.map { it.value.toDouble() }.sum() / valueToError.map { it.key.toDouble() }.sum() } /** * Rounds a [valueToRound] to [placesNum] decimal places */ fun round(valueToRound: Double, placesNum: Byte): Double = (valueToRound * 10.0.pow(placesNum.toDouble())).roundToInt() / 10.0.pow(placesNum.toDouble())
1
Kotlin
0
0
f85c14499c53569ed0cddfd110c20178defaa1f2
1,651
bio-relatives-kt
MIT License
Kotlin/BreadthFirstPaths.kt
lprimeroo
41,106,663
false
null
class BreadthFirstPaths { private var marked: BooleanArray? = null // marked[v] = is there an s-v path private var edgeTo: IntArray? = null // edgeTo[v] = previous edge on shortest s-v path private var distTo: IntArray? = null // distTo[v] = number of edges shortest s-v path /** * Computes the shortest path between the source vertex `s` * and every other vertex in the graph `G`. * @param G the graph * @param s the source vertex */ constructor(G: Graph, s: Int) { marked = BooleanArray(G.V()) distTo = IntArray(G.V()) edgeTo = IntArray(G.V()) bfs(G, s) assert(check(G, s)) } /** * Computes the shortest path between any one of the source vertices in `sources` * and every other vertex in graph `G`. * @param G the graph * @param sources the source vertices */ constructor(G: Graph, sources: Iterable<Integer>) { marked = BooleanArray(G.V()) distTo = IntArray(G.V()) edgeTo = IntArray(G.V()) for (v in 0 until G.V()) distTo[v] = INFINITY bfs(G, sources) } // breadth-first search from a single source private fun bfs(G: Graph, s: Int) { val q = Queue<Integer>() for (v in 0 until G.V()) distTo[v] = INFINITY distTo[s] = 0 marked[s] = true q.enqueue(s) while (!q.isEmpty()) { val v = q.dequeue() for (w in G.adj(v)) { if (!marked!![w]) { edgeTo[w] = v distTo[w] = distTo!![v] + 1 marked[w] = true q.enqueue(w) } } } } // breadth-first search from multiple sources private fun bfs(G: Graph, sources: Iterable<Integer>) { val q = Queue<Integer>() for (s in sources) { marked[s] = true distTo[s] = 0 q.enqueue(s) } while (!q.isEmpty()) { val v = q.dequeue() for (w in G.adj(v)) { if (!marked!![w]) { edgeTo[w] = v distTo[w] = distTo!![v] + 1 marked[w] = true q.enqueue(w) } } } } /** * Is there a path between the source vertex `s` (or sources) and vertex `v`? * @param v the vertex * @return `true` if there is a path, and `false` otherwise */ fun hasPathTo(v: Int): Boolean { return marked!![v] } /** * Returns the number of edges in a shortest path between the source vertex `s` * (or sources) and vertex `v`? * @param v the vertex * @return the number of edges in a shortest path */ fun distTo(v: Int): Int { return distTo!![v] } /** * Returns a shortest path between the source vertex `s` (or sources) * and `v`, or `null` if no such path. * @param v the vertex * @return the sequence of vertices on a shortest path, as an Iterable */ fun pathTo(v: Int): Iterable<Integer>? { if (!hasPathTo(v)) return null val path = Stack<Integer>() var x: Int x = v while (distTo!![x] != 0) { path.push(x) x = edgeTo!![x] } path.push(x) return path } // check optimality conditions for single source private fun check(G: Graph, s: Int): Boolean { // check that the distance of s = 0 if (distTo!![s] != 0) { StdOut.println("distance of source " + s + " to itself = " + distTo!![s]) return false } // check that for each edge v-w dist[w] <= dist[v] + 1 // provided v is reachable from s for (v in 0 until G.V()) { for (w in G.adj(v)) { if (hasPathTo(v) != hasPathTo(w)) { StdOut.println("edge $v-$w") StdOut.println("hasPathTo(" + v + ") = " + hasPathTo(v)) StdOut.println("hasPathTo(" + w + ") = " + hasPathTo(w)) return false } if (hasPathTo(v) && distTo!![w] > distTo!![v] + 1) { StdOut.println("edge $v-$w") StdOut.println("distTo[" + v + "] = " + distTo!![v]) StdOut.println("distTo[" + w + "] = " + distTo!![w]) return false } } } // check that v = edgeTo[w] satisfies distTo[w] = distTo[v] + 1 // provided v is reachable from s for (w in 0 until G.V()) { if (!hasPathTo(w) || w == s) continue val v = edgeTo!![w] if (distTo!![w] != distTo!![v] + 1) { StdOut.println("shortest path edge $v-$w") StdOut.println("distTo[" + v + "] = " + distTo!![v]) StdOut.println("distTo[" + w + "] = " + distTo!![w]) return false } } return true } companion object { private val INFINITY = Integer.MAX_VALUE /** * Unit tests the `BreadthFirstPaths` data type. * * @param args the command-line arguments */ fun main(args: Array<String>) { val `in` = In(args[0]) val G = Graph(`in`) // StdOut.println(G); val s = Integer.parseInt(args[1]) val bfs = BreadthFirstPaths(G, s) for (v in 0 until G.V()) { if (bfs.hasPathTo(v)) { StdOut.printf("%d to %d (%d): ", s, v, bfs.distTo(v)) for (x in bfs.pathTo(v)!!) { if (x == s) StdOut.print(x) else StdOut.print("-$x") } StdOut.println() } else { StdOut.printf("%d to %d (-): not connected\n", s, v) } } } } }
56
C++
186
99
16367eb9796b6d4681c5ddf45248e2bcda72de80
6,117
DSA
MIT License
Continuous_Subarray_Sum.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
// Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer. class Solution { fun checkSubarraySum(nums: IntArray, k: Int): Boolean { val map = HashMap<Int, Int>() var curSum = 0 // for the case [0,0] 0 map[0] = -1 for (i in 0..nums.lastIndex) { curSum += nums[i] for (s in map.keys) { if (k == 0) { if (curSum - s == 0 && i - (map[s] ?: i) > 1) { return true } } else if ((curSum - s) % k == 0 && i - (map[s] ?: i) > 1) { return true } } map[curSum] = map[curSum] ?: i } return false } } fun main(args: Array<String>) { val solution = Solution() val testset = arrayOf( intArrayOf(23, 2, 4, 6, 7), intArrayOf(23, 2, 6, 4, 7), intArrayOf(2, 1, 1, 1, 2), intArrayOf(5, 2, 4), intArrayOf(23, 2, 6, 4, 7), intArrayOf(1, 0, 0), intArrayOf(0, 1, 0), intArrayOf(0, 0), intArrayOf(0, 0), intArrayOf(1, 5), intArrayOf(0) ) val ks = intArrayOf(6, 6, 1, 5, 0, 0, 0, 0, 100, -6, 0) for (i in 0..testset.lastIndex) { println(solution.checkSubarraySum(testset[i], ks[i])) } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,498
leetcode
MIT License
src/main/kotlin/aoc2021/day2/DepthOnARoll.kt
arnab
75,525,311
false
null
package aoc2021.day2 object DepthOnARoll { data class Command(val direction: String, val units: Int) { companion object { fun from(data: String): Command { val direction = data.split(" ")[0] val units = data.split(" ")[1].toInt() return Command(direction, units) } } fun execute(position: Position): Position = when(this.direction) { "forward" -> Position(position.distance + this.units, position.depth) "up" -> Position(position.distance, position.depth - this.units) "down" -> Position(position.distance, position.depth + this.units) else -> throw IllegalArgumentException("Unknown command: $this") } fun executeWithAim(position: Position): Position = when(this.direction) { "forward" -> Position( position.distance + this.units, position.depth + (position.aim * this.units), position.aim ) "up" -> Position(position.distance, position.depth, position.aim - this.units) "down" -> Position(position.distance, position.depth, position.aim + this.units) else -> throw IllegalArgumentException("Unknown command: $this") } } data class Position(val distance: Int, val depth: Int, val aim: Int = 0) fun parse(data: String) = data.split("\n").map { Command.from(it) } fun calculate(commands: List<Command>): Int { val finalPosition = commands.fold(Position(0, 0)) { currentPosition, command -> command.execute(currentPosition) } return finalPosition.depth * finalPosition.distance } fun calculateWithAim(commands: List<Command>): Int { val finalPosition = commands.fold(Position(0, 0, 0)) { currentPosition, command -> command.executeWithAim(currentPosition) } return finalPosition.depth * finalPosition.distance } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
2,005
adventofcode
MIT License
src/Day01.kt
jordan-thirus
573,476,470
false
{"Kotlin": 41711}
fun main() { fun getElves(input: List<String>): List<Int> { val elves = mutableListOf(0) var index = 0 input.forEach { line -> when (line) { "" -> { elves.add(0) index++ } else -> { elves[index] += (line.toInt()) } } } return elves } fun part1(input: List<String>): Int { val elves = getElves(input) return elves.max() } fun part2(input: List<String>): Int { val elves = getElves(input) return elves .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e
1,004
advent-of-code-2022
Apache License 2.0
src/cn/leetcode/codes/simple11/Simple11_2.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple11 import kotlin.math.max import kotlin.math.min class Simple11_2 { /** * 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 说明:你不能倾斜容器。   示例 1: 输入:[1,8,6,2,5,4,8,3,7] 输出:49 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 示例 2: 输入:height = [1,1] 输出:1 示例 3: 输入:height = [4,3,2,1,4] 输出:16 示例 4: 输入:height = [1,2,1] 输出:2   提示: n = height.length 2 <= n <= 3 * 104 0 <= height[i] <= 3 * 104 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/container-with-most-water 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * */ //双指针解法 fun maxArea(height: IntArray): Int { var maxArea = 0 var i = 0 //左指针 var j = height.size - 1 //右指针 //控制在两根柱子之间求出最大面积 while (i < j){ //求出当前面积 最小的一根柱子高度 决定着面积大小 val area = min(height[i],height[j]) * (j - i) maxArea = max(area,maxArea) //缩小两根柱子的距离 if (height[i] < height[j]){ i++ }else{ j-- } } return maxArea } }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
1,814
LeetCodeSimple
Apache License 2.0
src/main/kotlin/net/dilius/daily/coding/problem/n00x/003.kt
diliuskh
298,020,928
false
null
package net.dilius.daily.coding.problem.n00x import net.dilius.daily.coding.problem.Problem import java.util.StringTokenizer /* Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. For example, given the following Node class class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right The following test should pass: node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left' */ data class Node(val value: String, val left: Node? = null, val right: Node? = null) class BinaryTreeSerializer : Problem<Node, String> { override fun solve(input: Node): String { return serialize(input) } private fun serialize(node: Node?): String { return if (node == null) "{}" else "{\"${node.value}\",${serialize(node.left)},${serialize(node.right)}}" } } class BinaryTreeDeserializer : Problem<String, Node> { override fun solve(input: String): Node { return deserialize(input)!! } private fun deserialize(input: String): Node? { if (input.isEmpty()) throw IllegalArgumentException("Input is empty") if (input[0] != '{') throw IllegalArgumentException("Invalid token at 0") if (input == "{}") return null if (input.length < 3) throw IllegalArgumentException("Invalid token at 3") val substring = input.substring(2) val valEnding = substring.indexOfFirst { it == '"' } val value = substring.substring(0, valEnding) val (left, right) = getSubNodes(input) return Node(value, deserialize(left), deserialize(right)) } private fun getSubNodes(input: String): Pair<String, String> { val indexOfLeftNodeBeginning = input.indexOfNth(2) { c -> c == '{' } if (indexOfLeftNodeBeginning == -1) throw IllegalArgumentException("Invalid input") val indexOfLeftNodeEnding = input.findBalancingBracketEnd(indexOfLeftNodeBeginning) if (indexOfLeftNodeEnding == -1) throw IllegalArgumentException("Invalid input") val indexOfRightNodeBeginning = indexOfLeftNodeEnding+2 if (input[indexOfRightNodeBeginning] != '{') throw IllegalArgumentException("Invalid input") val indexOfRightNodeEnding = input.findBalancingBracketEnd(indexOfRightNodeBeginning) if (indexOfRightNodeEnding == -1) throw IllegalArgumentException("Invalid input") return input.substring(indexOfLeftNodeBeginning, indexOfLeftNodeEnding+1) to input.substring(indexOfRightNodeBeginning, indexOfRightNodeEnding+1) } } inline fun CharSequence.indexOfNth(n:Int, predicate: (Char) -> Boolean): Int { var found = 0 for (index in indices) { if (predicate(this[index])) { found++ if (found == n) return index } } return -1 } inline fun CharSequence.findBalancingBracketEnd(beginningBracketIndex:Int): Int { var found = 0 for (index in beginningBracketIndex..length) { if (this[index] == '{') found++ if (this[index] == '}') { found-- if (found == 0) { return index } } } return -1 }
0
Kotlin
0
0
7e5739f87dbce2b56d24e7bab63b6cee6bbc54bc
3,388
dailyCodingProblem
Apache License 2.0
src/Day06/Day06.kt
martin3398
436,014,815
false
{"Kotlin": 63436, "Python": 5921}
fun main() { fun calc(input: List<Int>, iterations: Int): Long { val counts = MutableList<Long>(9) { 0 } input.forEach { counts[it]++ } for (i in 0 until iterations) { val numNew = counts.removeFirst() counts[6] += numNew counts.add(numNew) } return counts.sum() } fun part1(input: List<Int>): Long { return calc(input, 80) } fun part2(input: List<Int>): Long { return calc(input, 256) } val testInput = readInput(6, true)[0].split(',').map { it.toInt() } val input = readInput(6)[0].split(',').map { it.toInt() } check(part1(testInput) == 5934L) println(part1(input)) check(part2(testInput) == 26984457539) println(part2(input)) }
0
Kotlin
0
0
085b1f2995e13233ade9cbde9cd506cafe64e1b5
778
advent-of-code-2021
Apache License 2.0
src/main/kotlin/g1701_1800/s1739_building_boxes/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1739_building_boxes // #Hard #Math #Greedy #Binary_Search #2023_06_16_Time_133_ms_(100.00%)_Space_32.8_MB_(100.00%) class Solution { fun minimumBoxes(n: Int): Int { val k: Int = findLargestTetrahedralNotGreaterThan(n) val used: Int = tetrahedral(k) val floor: Int = triangular(k) val unused: Int = (n - used) if (unused == 0) { return floor } val r: Int = findSmallestTriangularNotLessThan(unused) return (floor + r) } private fun findLargestTetrahedralNotGreaterThan(te: Int): Int { var a: Int = Math.ceil(Math.pow(product(6, te.toLong()).toDouble(), ONE_THIRD)).toInt() while (tetrahedral(a) > te) { a-- } return a } private fun findSmallestTriangularNotLessThan(t: Int): Int { var a: Int = -1 + Math.floor(Math.sqrt(product(t.toLong(), 2).toDouble())).toInt() while (triangular(a) < t) { a++ } return a } private fun tetrahedral(a: Int): Int { return ratio(product(a.toLong(), (a + 1).toLong(), (a + 2).toLong()), 6).toInt() } private fun triangular(a: Int): Int { return ratio(product(a.toLong(), (a + 1).toLong()), 2).toInt() } private fun product(vararg vals: Long): Long { var product: Long = 1L for (`val`: Long in vals) { product *= `val` } return product } private fun ratio(a: Long, b: Long): Long { return (a / b) } companion object { val ONE_THIRD: Double = 1.0 / 3.0 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,618
LeetCode-in-Kotlin
MIT License
src/main/kotlin/io/binarysearch/SearchRange.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.binarysearch // https://leetcode.com/explore/learn/card/binary-search/135/template-iii/944/ class SearchRange { fun execute(nums: IntArray, target: Int): IntArray = intArrayOf(find(nums, target) { it < target }, find(nums, target) { it <= target }) private fun find(nums: IntArray, target: Int, evaluator: (Int) -> Boolean): Int { var index = -1 var start = 0 var end = nums.lastIndex while (start <= end) { val mid = start + (end - start) / 2 if (nums[mid] == target) index = mid if (evaluator(nums[mid])) { start = mid + 1 } else { end = mid - 1 } } return index } } fun main() { val searchRange = SearchRange() listOf( Triple(intArrayOf(5, 7, 7, 8, 8, 10), 8, listOf(3, 4)), Triple(intArrayOf(5, 7, 7, 8, 8, 10), 6, listOf(-1, -1)), Triple(intArrayOf(1, 2, 3, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 7, 7, 8, 8, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 14, 15, 15, 15, 15), 7, listOf(9, 14)), Triple(intArrayOf(1, 4), 4, listOf(1, 1)), Triple(intArrayOf(1), 1, listOf(0, 0)), Triple(intArrayOf(1, 3), 1, listOf(0, 0)) ).map { (input, target, output) -> val solution = searchRange.execute(input, target).toList() println("$solution is valid ${solution == output}") } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,316
coding
MIT License
src/day04/Day04.kt
elenavuceljic
575,436,628
false
{"Kotlin": 5472}
package day04 import java.io.File fun main() { fun String.asIntRange() = substringBefore('-').toInt()..substringAfter('-').toInt() infix fun IntRange.contains(other: IntRange) = first <= other.first && last >= other.last infix fun IntRange.overlaps(other: IntRange) = first <= other.last && last >= other.first fun part1(input: String): Int { val pairs = input.lines().map { it.substringBefore(",").asIntRange() to it.substringAfter(",").asIntRange() } return pairs.count { it.first contains it.second || it.second contains it.first } } fun part2(input: String): Int { val pairs = input.lines().map { it.substringBefore(",").asIntRange() to it.substringAfter(",").asIntRange() } return pairs.count { it.first overlaps it.second || it.second overlaps it.first } } val testInput = File("src/day04/Day04_test.txt").readText().trim() val part1Solution = part1(testInput) val part2Solution = part2(testInput) println(part1Solution) check(part1Solution == 2) check(part2Solution == 4) val input = File("src/day04/Day04.txt").readText().trim() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c5093b111fd02e28823d31f2edddb7e66c295add
1,276
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day6.kt
kevinrobayna
436,414,545
false
{"Ruby": 195446, "Kotlin": 42719, "Shell": 1288}
import java.util.stream.Collectors fun day6ProblemReader(string: String): List<List<Set<String>>> { val problemSplit = string.split("\n") val problem = mutableListOf<List<Set<String>>>() var group = mutableListOf<Set<String>>() for (lineCount in problemSplit.indices) { val line = problemSplit[lineCount] if (line.isNotBlank()) { val individualVotes = mutableSetOf<String>() line.split("").forEach { if (it.isNotBlank()) { individualVotes.add(it) } } group.add(individualVotes) } val isLastLine = lineCount == (problemSplit.size - 1) if (line.isBlank() || isLastLine) { problem.add(group) group = mutableListOf() continue } } return problem } // https://adventofcode.com/2020/day/6 class Day6( private val quiz: List<List<Set<String>>>, ) { fun solveAnyone(): Long { return quiz .stream() .map { personResponses -> val responses = mutableSetOf<String>() personResponses.forEach { responses.addAll(it) } responses }.map { it.size.toLong() } .collect(Collectors.toList()) .sum() } fun solveEveryone(): Long { return quiz .stream() .map { personResponses: List<Set<String>> -> val firstPerson = personResponses.first() firstPerson .stream() .filter { response -> personResponses.stream().filter { it.contains(response) } .count() == personResponses.size.toLong() } .map { it.length.toLong() } .collect(Collectors.toList()) } .map { it.size.toLong() } .collect(Collectors.toList()).sum() } } fun main() { val problem = day6ProblemReader(Day6::class.java.getResource("day6.txt").readText()) println("solution anyone = ${Day6(problem).solveAnyone()}") println("solution everyone = ${Day6(problem).solveEveryone()}") }
0
Kotlin
0
0
9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577
2,335
adventofcode_2020
MIT License
src/utils/Dijkstra.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package utils import arrow.core.NonEmptyList import arrow.core.nonEmptyListOf import java.util.PriorityQueue fun <T> findShortestRoute( map: List<List<T>>, start: Point, end: Point, includeDiagonalRoutes: Boolean = false, movementCost: (movementStart: MapDetails<T>, movementEnd: MapDetails<T>) -> Int?, ): ShortestRouteMetadata<Point>? { val unvisitedPoints = map.coordinates().toMutableSet() val priorityQueue = PriorityQueue<ShortestRouteMetadata<Point>> { a, b -> a.cost - b.cost } .apply { add(ShortestRouteMetadata(nonEmptyListOf(start), 0)) } return generateSequence { priorityQueue.poll() } .onEach { unvisitedPoints.remove(it.route.last()) } .flatMap { currentRouteMetadata -> currentRouteMetadata.currentPosition .neighbors(includeDiagonal = includeDiagonalRoutes) .filter { it in unvisitedPoints } .associateWith { movementCost( map.detailsAt(currentRouteMetadata.currentPosition), map.detailsAt(it), ) } .mapNotNull { (movementEnd, cost) -> if (cost == null) null else ShortestRouteMetadata( route = currentRouteMetadata.route + movementEnd, cost = currentRouteMetadata.cost + cost, ) } .groupBy { it.cost } .minByOrNull { it.key }?.value .orEmpty() } .filter { newPath -> priorityQueue.none { it.currentPosition == newPath.currentPosition } } .onEach(priorityQueue::add) .firstOrNull { it.currentPosition == end } } data class ShortestRouteMetadata<T>( val route: NonEmptyList<T>, val cost: Int, ) { val currentPosition get() = route.last() } fun findShortestRoute( graph: Graph<out Identifiable>, start: Identifier, end: Identifier, ): ShortestRouteMetadata<Identifier>? { val unvisitedNodes: MutableSet<Identifiable> = graph.nodes.toMutableSet() val priorityQueue = PriorityQueue<ShortestRouteMetadata<Identifier>> { a, b -> a.cost - b.cost } .apply { add(ShortestRouteMetadata(nonEmptyListOf(start), 0)) } return generateSequence { priorityQueue.poll() } .onEach { subject -> unvisitedNodes.first { it.identifier == subject.currentPosition } .let(unvisitedNodes::remove) } .flatMap { currentRouteMetadata -> currentRouteMetadata.currentPosition .let(graph.neighbors::getValue) .filter { neighbor -> unvisitedNodes.any { it.identifier == neighbor } } .associateWith { graph.costs.getValue(currentRouteMetadata.currentPosition to it) } .map { (movementEnd, cost) -> ShortestRouteMetadata( route = currentRouteMetadata.route + movementEnd, cost = currentRouteMetadata.cost + cost.toInt(), ) } .groupBy { it.cost } .minByOrNull { it.key }?.value .orEmpty() } .filter { newPath -> priorityQueue.none { it.currentPosition == newPath.currentPosition } } .onEach(priorityQueue::add) .firstOrNull { it.currentPosition == end } }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
3,446
Advent-of-Code
Apache License 2.0
src/main/aoc2020/Day20.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2020 import Direction import Grid import Pos import xRange import yRange class Day20(input: List<String>) { private data class Tile(val id: Long, val data: Grid) { var rotation: Grid.Transformation.Rotation = Grid.Transformation.NoRotation var flip: Grid.Transformation.Flip = Grid.Transformation.NoFlip /** * Get this tile as a grid without any borders and it's transformations applied */ fun withoutBorders() = data.subGrid(listOf(rotation, flip), Pos(1, 1), data.size - 2) fun getSide(dir: Direction) = data.getSide(dir, listOf(rotation, flip)) /** * Test all rotation/flip combinations and see if any match. * If it does update the rotation/flip info for this tile and return true */ fun anyTransformationMatchingSide(side: String, direction: Direction): Boolean { Grid.possibleTransformations.forEach { transformations -> if (side == data.getSide(direction, transformations)) { rotation = transformations.filterIsInstance<Grid.Transformation.Rotation>().single() flip = transformations.filterIsInstance<Grid.Transformation.Flip>().single() return true } } return false } } private val tiles = input.map { rawTile -> val lines = rawTile.split("\n") val id = lines.first().substringAfter("Tile ").dropLast(1).toLong() val tile = Grid.parse(lines.drop(1).dropLastWhile { it.isEmpty() }) // real input has a trailing blank line Tile(id, tile) } /** * Returns a Pos to tile id map that orders the tiles in the correct order. * Coordinates of the tiles forms a square and Pos(0,0) is located somewhere inside the square. */ private fun sortTiles(): Map<Pos, Long> { val tilesLeft = tiles.associateBy { it.id }.toMutableMap() // id to tile map // Start with the first tile without rotating it, and fix it's location to (0, 0) val found = mutableMapOf(Pos(0, 0) to tiles.first().id) val positionsToFindNeighboursOf = mutableListOf(Pos(0, 0)) while (tilesLeft.isNotEmpty()) { val currentPos = positionsToFindNeighboursOf.removeFirst() val matchAgainst = tilesLeft.remove(found[currentPos])!! // check in all directions from the current tile for (direction in Direction.entries) { val checkPos = currentPos.move(direction) if (found.containsKey(checkPos)) { // skip this direction if it's already been identified continue } // Check among all remaining tiles for the one that matches in this direction for ((id, otherTile) in tilesLeft) { val sideToMatch = matchAgainst.getSide(direction) if (otherTile.anyTransformationMatchingSide(sideToMatch, direction.opposite())) { found[checkPos] = id positionsToFindNeighboursOf.add(checkPos) break } } } } return found } private fun getMergedImage(): Grid { val sorted = sortTiles() val tileDataSize = tiles.first().data.size - 2 val numTilesInARow = kotlin.math.sqrt(tiles.size.toDouble()).toInt() val mergedGrid = Grid(tileDataSize * numTilesInARow) // tileY, tileX are the coordinates within the the sorted tiles map // indexY, indexX is rebased so that (0, 0) is in the top left corner for ((indexY, tileY) in (sorted.yRange()).withIndex()) { for ((indexX, tileX) in (sorted.xRange()).withIndex()) { val tileId = sorted[Pos(tileX, tileY)]!! val currentTile = tiles.find { it.id == tileId }!! val data = currentTile.withoutBorders() val offset = Pos(indexX * tileDataSize, indexY * tileDataSize) mergedGrid.writeAllWithOffset(data, offset) } } return mergedGrid } private val monsterString = """ ..................#. #....##....##....### .#..#..#..#..#..#... """.trimIndent() private fun getSeaMonsterPattern(): Set<Pos> { val pattern = mutableSetOf<Pos>() val monster = monsterString.split("\n") for (y in monster.indices) { for (x in monster[0].indices) { if (monster[y][x] == '#') { pattern.add(Pos(x, y)) } } } return pattern } private fun countMonsters(grid: Grid): Int { var count = 0 val pattern = getSeaMonsterPattern() // pattern is 3 times 20 in size for (y in 0 until grid.size - 3) { for (x in 0 until grid.size - 20) { if (pattern.all { grid[y + it.y][x + it.x] == '#' }) { count++ } } } return count } fun solvePart1(): Long { val sorted = sortTiles() val minx = sorted.xRange().first val maxx = sorted.xRange().last val miny = sorted.yRange().first val maxy = sorted.yRange().last return sorted[Pos(minx, miny)]!! * sorted[Pos(minx, maxy)]!! * sorted[Pos(maxx, miny)]!! * sorted[Pos(maxx, maxy)]!! } fun solvePart2(): Int { val mergedImage = getMergedImage() val numberOfMonsters = Grid.possibleTransformations .map { mergedImage.transformed(it) }.maxOf { countMonsters(it) } return mergedImage.count('#') - monsterString.count { it == '#' } * numberOfMonsters } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
5,830
aoc
MIT License
src/Day01.kt
azat-ismagilov
573,217,326
false
{"Kotlin": 75114}
fun main() { fun splitInput(input: List<String>): List<List<String>> { val result = mutableListOf<List<String>>() var current = mutableListOf<String>() for (line in input) { if (line == "") { result.add(current) current = mutableListOf() } else current.add(line) } if (current.isNotEmpty()) result.add(current) return result } fun part1(input: List<String>): Int = splitInput(input).maxOf { it.sumOf { it.toInt() } } fun part2(input: List<String>): Int = splitInput(input).map { it.sumOf { it.toInt() } }.sortedDescending().take(3).sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
abdd1b8d93b8afb3372cfed23547ec5a8b8298aa
978
advent-of-code-kotlin-2022
Apache License 2.0
jvm/src/main/kotlin/io/prfxn/aoc2021/day06.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Lanternfish (https://adventofcode.com/2021/day/6) package io.prfxn.aoc2021 fun main() { val initialCountsByDaysUntilRepro = textResourceReader("input/06.txt").readText().trim().split(",") .map { it.toInt() } .groupBy { it } .map { (daysUntilRepro, instances) -> daysUntilRepro to instances.size.toLong() } .toMap() fun processDay(countsByDaysUntilRepro: MutableMap<Int, Long>) { val count0 = countsByDaysUntilRepro[0] ?: 0 for (daysUntilRepro in (1..8)) countsByDaysUntilRepro[daysUntilRepro - 1] = countsByDaysUntilRepro[daysUntilRepro] ?: 0 countsByDaysUntilRepro[8] = count0 countsByDaysUntilRepro[6] = (countsByDaysUntilRepro[6] ?: 0) + count0 } val answer1 = initialCountsByDaysUntilRepro.toMutableMap().let { countsByDaysUntilRepro -> repeat(80) { processDay(countsByDaysUntilRepro) } countsByDaysUntilRepro.values.sum() } val answer2 = initialCountsByDaysUntilRepro.toMutableMap().let { countsByDaysUntilRepro -> repeat(256) { processDay(countsByDaysUntilRepro) } countsByDaysUntilRepro.values.sum() } sequenceOf(answer1, answer2).forEach(::println) } /** output * 388739 * 1741362314973 */
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
1,307
aoc2021
MIT License
codeforces/round580/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round580 fun main() { val n = readInt() val nei = List(n) { mutableListOf<Int>() } repeat(n - 1) { val (a, b) = readInts().map { it - 1 } nei[a].add(b) nei[b].add(a) } nei.indices.flatMap { v -> val (sizes, vertices) = nei[v].map { Pair(dfs(it, setOf(v), 0, nei), it) }.sortedBy { it.first }.unzip() sizes.indices.map { i -> val size = sizes.take(i).sum() Pair((size + 1) * (n - size)) { dfs(v, vertices.drop(i), 1, nei); dfs(v, vertices.take(i), size + 1, nei) } } }.maxByOrNull { it.first }?.second?.invoke() } private fun dfs(v: Int, p: Collection<Int>, k: Int, nei: List<List<Int>>): Int { var sum = 1 for (u in nei[v].minus(p)) { if (k > 0) println("${u + 1} ${v + 1} ${k * sum}") sum += dfs(u, setOf(v), k, nei) } return sum } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
970
competitions
The Unlicense
src/day11/Day11.kt
gr4cza
572,863,297
false
{"Kotlin": 93944}
@file:Suppress("MagicNumber") package day11 import readInput fun main() { data class Monkey( val number: Int, val items: MutableList<Item>, val operation: (Long) -> Long, val testValue: Int, val favoredMonkey: Int, val hatedMonkey: Int, var inspectCount: Long = 0L, ) fun readOperation(line: String): (Long) -> Long = line.removePrefix("Operation: new = ") .split(" ").let { (_, op, b) -> when (op) { "*" -> { if (b == "old") { { it * it } } else { { it * b.toInt() } } } "+" -> { if (b == "old") { { it + it } } else { { it + b.toInt() } } } else -> error("unknown input: $op") } } fun parseInput(input: List<String>): List<Monkey> { val monkeys = mutableListOf<Monkey>() var monkeyNumber: Int = -1 var currentItems = mutableListOf<Item>() var operation: (Long) -> Long = { it } var testValue = 0 var favoredMonkey = -1 var hatedMonkey = -1 input.map { it.trim() }.forEachIndexed { index, line -> if (line.startsWith("day21.Monkey")) { monkeyNumber = line.replace(":", "").split(" ").last().toInt() } if (line.startsWith("Starting items:")) { currentItems = line.removePrefix("Starting items: ") .split(", ").map { Item(it.toLong()) }.toMutableList() } if (line.startsWith("Operation:")) { operation = readOperation(line) } if (line.startsWith("Test:")) { testValue = line.split(" ").last().toInt() } if (line.startsWith("If true:")) { favoredMonkey = line.split(" ").last().toInt() } if (line.startsWith("If false: ")) { hatedMonkey = line.split(" ").last().toInt() } if (line.isBlank() || index == input.size - 1) { monkeys.add( Monkey( number = monkeyNumber, items = currentItems, operation = operation, testValue = testValue, favoredMonkey = favoredMonkey, hatedMonkey = hatedMonkey, ) ) } } return monkeys } fun List<Monkey>.game( times: Int, worryReducingOp: (Long) -> Long, ) { repeat(times) { this.forEach { monkey -> monkey.items.forEach { item -> item.worryLvl = worryReducingOp(monkey.operation(item.worryLvl)) if (item.worryLvl % monkey.testValue == 0L) { this[monkey.favoredMonkey].items.add(item) } else { this[monkey.hatedMonkey].items.add(item) } monkey.inspectCount++ } monkey.items.clear() } } } fun part1(input: List<String>): Long { val monkeys = parseInput(input) monkeys.game(20) { it / 3 } return monkeys.map { it.inspectCount }.sortedDescending() .take(2).reduce(Long::times) } fun part2(input: List<String>): Long { val monkeys = parseInput(input) val fakeLkkt = monkeys.map { it.testValue }.reduce { acc, i -> acc * i } monkeys.game(10000) { it % fakeLkkt } return monkeys.map { it.inspectCount }.sortedDescending() .take(2).reduce(Long::times) } // test if implementation meets criteria from the description, like: val testInput = readInput("day11/Day11_test") println(part1(testInput)) check(part1(testInput) == 10605L) println(part2(testInput)) check(part2(testInput) == 2713310158L) val input = readInput("day11/Day11") println(part1(input)) println(part2(input)) } data class Item( var worryLvl: Long )
0
Kotlin
0
0
ceca4b99e562b4d8d3179c0a4b3856800fc6fe27
4,447
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day17.kt
clechasseur
567,968,171
false
{"Kotlin": 493887}
package io.github.clechasseur.adventofcode.y2022 import io.github.clechasseur.adventofcode.util.Direction import io.github.clechasseur.adventofcode.util.Pt import io.github.clechasseur.adventofcode.y2022.data.Day17Data object Day17 { private val shapes = Day17Data.shapes.map { it.toShape() } private const val jets = Day17Data.jets fun part1(): Int = caveSequence().take(2022).last().height fun part2(): Long { val seq = caveSequence().iterator() val seen = mutableMapOf<String, Pair<Int, Int>>() var i = 0 var loopStart = 0 var loopSize = 0 var loopHeight = 0 while (loopStart == 0) { val cave = seq.next() val s = cave.toString() val prev = seen[s] if (prev != null) { loopStart = prev.first loopSize = i - prev.first loopHeight = cave.height - prev.second } else { seen[s] = i++ to cave.height } } val numLoops = (1_000_000_000_000L - loopStart.toLong()) / loopSize.toLong() val extra = ((1_000_000_000_000L - loopStart.toLong()) % loopSize.toLong()).toInt() return caveSequence().take(loopStart + extra).last().height.toLong() + (numLoops * loopHeight.toLong()) } private data class Shape(val pts: Set<Pt>) { val height: Int get() = pts.maxOf { it.y } + 1 fun move(displacement: Pt): Shape = Shape(pts.map { it + displacement }.toSet()) } private data class Cave(val rocks: Set<Pt> = emptySet()) { val height: Int get() = rocks.maxOfOrNull { -it.y }?.plus(1) ?: 0 fun blocked(pt: Pt): Boolean = rocks.contains(pt) || pt.x < 0 || pt.x >= 7 || pt.y > 0 fun fits(shape: Shape): Boolean = shape.pts.none { blocked(it) } fun land(shape: Shape): Cave = Cave(rocks + shape.pts) fun crop(): Cave = copy(rocks = rocks.filter { it.y in -height..-(height - 107) }.toSet()) override fun toString(): String = (rocks.minOf { it.y }..rocks.maxOf { it.y }).joinToString("\n") { y -> val middle = (0..6).joinToString("") { x -> if (rocks.contains(Pt(x, y))) "#" else "." } "|$middle|" } } private fun shapeSequence(): Sequence<Shape> = generateSequence(0) { it + 1 }.map { i -> shapes[i % shapes.size] } private fun jetSequence(): Sequence<Direction> = generateSequence(0) { it + 1 }.map { i -> when (jets[i % jets.length]) { '<' -> Direction.LEFT '>' -> Direction.RIGHT else -> error("Wrong jet: ${jets[i % jets.length]}") } } private fun caveSequence(): Sequence<Cave> = sequence { var cave = Cave() val shapeIt = shapeSequence().iterator() val jetIt = jetSequence().iterator() while (true) { var shape = shapeIt.next() shape = shape.move(Pt(2, -(cave.height + 3 + shape.height - 1))) while (true) { val jet = jetIt.next() val pushedShape = shape.move(jet.displacement) if (cave.fits(pushedShape)) { shape = pushedShape } val fallenShape = shape.move(Direction.DOWN.displacement) if (cave.fits(fallenShape)) { shape = fallenShape } else { cave = cave.land(shape).crop() yield(cave) break } } } } private fun String.toShape(): Shape = Shape(lines().withIndex().flatMap { (y, line) -> line.withIndex().mapNotNull { (x, c) -> if (c == '#') Pt(x, y) else null } }.toSet()) }
0
Kotlin
0
0
7ead7db6491d6fba2479cd604f684f0f8c1e450f
3,800
adventofcode2022
MIT License
src/main/kotlin/symbolik/parser/tokenize.kt
Andlon
55,359,009
false
null
package symbolik.parser class TokenizationException(message: String) : Exception(message) fun tokenize(str: String) : List<Token> = processUnaryOperators(recursivelyTokenize(emptyList(), str)) tailrec private fun recursivelyTokenize(tokens: List<Token>, remaining: String): List<Token> { // By ignoring leading whitespace we effectively make whitespace only work as separators of tokens val trimmedRemaining = remaining.trimStart() if (trimmedRemaining.isEmpty()) return tokens val result = longestTokenWithRemainder(trimmedRemaining) return when (result) { null -> throw TokenizationException("Invalid token " + remaining) else -> recursivelyTokenize(tokens + result.token, result.remainder) } } private fun convertToUnary(token: Token) = when(token) { Token.BinaryOperator.Plus -> Token.UnaryOperator.Plus Token.BinaryOperator.Minus -> Token.UnaryOperator.Minus else -> token } private fun processUnaryOperators(tokens: List<Token>): List<Token> { val firstElement = tokens.take(1).map(::convertToUnary) val remainingElements = tokens.zip(tokens.drop(1)) .map { when (it.first) { is Token.Constant -> it.second is Token.Name -> it.second is Token.RightParenthesis -> it.second else -> convertToUnary(it.second) } } return firstElement + remainingElements } private fun parseSingleToken(str: String): Token? = when (str) { "*" -> Token.BinaryOperator.Times "+" -> Token.BinaryOperator.Plus "-" -> Token.BinaryOperator.Minus "/" -> Token.BinaryOperator.Division "(" -> Token.LeftParenthesis ")" -> Token.RightParenthesis else -> when { isValidName(str) -> Token.Name(str) isValidInteger(str) -> Token.Integer(str.toInt()) isValidDecimal(str) -> Token.Decimal(str.toDouble()) else -> null } } private data class TokenWithRemainder(val token: Token, val remainder: String) private fun createTokenWithRemainder(token: Token?, remainder: String) = when(token) { null -> null else -> TokenWithRemainder(token, remainder) } private fun longestTokenWithRemainder(str: String): TokenWithRemainder? = (1 .. str.length) .map { numChars -> createTokenWithRemainder(parseSingleToken(str.take(numChars)), str.drop(numChars)) } .filterNotNull() .lastOrNull()
0
Kotlin
0
0
9711157eda9a56ba622475bf994cef8ff9d16946
2,635
symbolik
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/Intersection.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 /** * Given two arrays, write a function to compute their intersection. */ fun interface IntersectionStrategy { operator fun invoke(p: Pair<IntArray, IntArray>): IntArray } /** * Use two hash sets * Time complexity: O(n) */ class IntersectionTwoSets : IntersectionStrategy { override operator fun invoke(p: Pair<IntArray, IntArray>): IntArray { val set = p.first.toSet() val intersect: MutableSet<Int> = HashSet() for (num in p.second) { if (set.contains(num)) { intersect.add(num) } } val result = IntArray(intersect.size) var i = 0 for (num in intersect) { result[i++] = num } return result } } /** * Sort both arrays, use two pointers * Time complexity: O(nlogn) */ class IntersectionTwoPointers : IntersectionStrategy { override operator fun invoke(p: Pair<IntArray, IntArray>): IntArray { val set: MutableSet<Int> = HashSet() p.first.sort() p.second.sort() var i = 0 var j = 0 while (i < p.first.size && j < p.second.size) { when { p.first[i] < p.second[j] -> { i++ } p.first[i] > p.second[j] -> { j++ } else -> { set.add(p.first[i]) i++ j++ } } } val result = IntArray(set.size) var k = 0 for (num in set) { result[k++] = num } return result } } /** * */ class IntersectionBinarySearch : IntersectionStrategy { override operator fun invoke(p: Pair<IntArray, IntArray>): IntArray { val set: MutableSet<Int> = HashSet() p.second.sort() for (num in p.first) { if (binarySearch(p.second, num)) { set.add(num) } } var i = 0 val result = IntArray(set.size) for (num in set) { result[i++] = num } return result } private fun binarySearch(nums: IntArray, target: Int): Boolean { var low = 0 var high = nums.size - 1 while (low <= high) { val mid = low + (high - low) / 2 if (nums[mid] == target) { return true } if (nums[mid] > target) { high = mid - 1 } else { low = mid + 1 } } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,227
kotlab
Apache License 2.0
src/main/kotlin/solved/p672/Solution.kt
mr-nothing
469,475,608
false
{"Kotlin": 162430}
package solved.p672 class Solution { class BruteForceSolution { // This was the first idea: generate all possible combinations of button presses // and simulate it on given bulbs. Clearly it does't fit any time limits :D fun flipLights(n: Int, presses: Int): Int { val states = HashSet<MutableList<Boolean>>() val combinations = mutableListOf<MutableList<Int>>() generatePressesCombinations(combinations, MutableList(presses) { -1 }, presses) for (combination in combinations) { val lights = MutableList(n) { true } for (button in combination) { when (button) { 1 -> { for (i in 1..lights.size) { toggle(lights, i) } } 2 -> { for (i in 1..lights.size) { if (i % 2 == 0) { toggle(lights, i) } } } 3 -> { for (i in 1..lights.size) { if (i % 2 == 1) { toggle(lights, i) } } } 4 -> { for (i in 1..lights.size) { if ((i - 1) % 3 == 0) { toggle(lights, i) } } } } } states.add(lights) } return states.count() } private fun toggle(lights: MutableList<Boolean>, i: Int) { lights[i - 1] = lights[i - 1].not() } private fun generatePressesCombinations( combinations: MutableList<MutableList<Int>>, combination: MutableList<Int>, pressesRemaining: Int ) { if (pressesRemaining > 0) { for (button in 1..4) { val tempCombination = mutableListOf(*combination.toTypedArray()) tempCombination[tempCombination.size - pressesRemaining] = button generatePressesCombinations(combinations, tempCombination, pressesRemaining - 1) } } else { combinations.add(combination) } } } class GodHelpMeSolution { // I'm crying xD // This solution came to my mind when I realised there is a finite number of states for given bulbs for every n. // For different n it is different. So I built a table/graph representing this state machine. // What bulbs are switched on: // A - all // N - none // E - evens // O - odds // A# - all but thirds // N# - none but thirds // E# - evens except thirds // O# - odds except thirds // ___| 1B | 2B | 3B | 4B | // A | N | O | E | A# | // N | A | E | O | N# | // O | E | N | A | O# | // E | O | A | N | E# | // A# | N# | O# | E# | A | // N# | A# | E# | O# | N | // O# | E# | N# | A# | O | // E# | O# | A# | N# | E | // Starting from 3 bulbs and 3 presses this system can be in 8 different states described in this table. // When bulbs and presses are lower than 3 we can count number of states we can reach with use of table above. fun flipLights(bulbs: Int, presses: Int): Int { return when (bulbs) { 0 -> 1 1 -> when (presses) { 0 -> 1 else -> 2 } 2 -> when (presses) { 0 -> 1 1 -> 3 else -> 4 } else -> when (presses) { 0 -> 1 1 -> 4 2 -> 7 else -> 8 } } } } }
0
Kotlin
0
0
0f7418ecc8675d8361ef31cbc1ee26ea51f7708a
4,304
leetcode
Apache License 2.0
src/main/kotlin/aoc2021/Day19.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2021 import readInput import kotlin.math.abs import kotlin.math.max private enum class Axis { X, Y, Z } private const val OVERLAPPING_BEACONS_REQUIRED = 12 /** * A beacon scanner * * @property name the name of the scanner * @property beacons the position of all beacons within range of this scanner, with their position relative to the * scanners center */ private data class Scanner(val name: String, val beacons: Collection<Vector>) { companion object { /** * Parses the scanner from some string lines */ fun parseString(input: List<String>) = Scanner(input.first().replace("---", "").trim(), input.drop(1).map { line -> line.split(",").map { it.toInt() }.toIntArray() }.map { Vector(it) } .toMutableSet() ) /** * Tries to overlay the beacons in the given [scanner] with given [beacons] to find a 'movement' vector, by which * the center of the [scanner] must be moved to align with at least [OVERLAPPING_BEACONS_REQUIRED] [beacons] * * @param scanner the scanner to check * @param beacons the existing beacons * @return a vector by which the [scanner] must be moved so that at least [OVERLAPPING_BEACONS_REQUIRED] beacons * are at an identical position in with the given [beacons], or null if not enough overlapping beacons could be found */ private fun getMovementToOverlapBeacons(scanner: Scanner, beacons: Collection<Vector>): Vector? { for (beacon1 in beacons) { val fromBeacon1 = beacons.map { beacon1 - it }.toSet() for (beacon2 in scanner.beacons) { val fromBeacon2 = scanner.beacons.map { beacon2 - it }.toSet() val common = fromBeacon1.intersect(fromBeacon2) if (common.size >= OVERLAPPING_BEACONS_REQUIRED) { return beacon1 - beacon2 } } } return null } /** * Tries to locate the given scanner * * @param scanner the scanner to search for * @param beacons the currently beacons * @return a pair containing the scanner's position and the new beacon locations, or null, if the scanner can not * be located with the given world data yet */ fun tryLocateScanner(scanner: Scanner, beacons: Collection<Vector>) = // check all possible orientations of the scanner and see if in any we can overlay the required number of beacons scanner.getOrientations().firstNotNullOfOrNull { rotatedScanner -> getMovementToOverlapBeacons(rotatedScanner, beacons)?.let { newCenter -> Pair(newCenter, rotatedScanner.beacons.map { it + newCenter }.filterNot { it in beacons }) } } } private fun rotate(axis: Axis) = Scanner(name, beacons.map { it.rotate(axis) }.toMutableSet()) private fun getOrientations(): Sequence<Scanner> { // this can probably be optimized... var current = this val set = sequence { yield(current) Axis.values().forEach { axis -> current = current.rotate(axis) yield(current) Axis.values().forEach { axis2 -> current = current.rotate(axis2) yield(current) Axis.values().forEach { axis3 -> current = current.rotate(axis3) yield(current) Axis.values().forEach { axis4 -> current = current.rotate(axis4) yield(current) } } } } } return set.distinct() } override fun toString() = name } private data class Vector(val x: Int, val y: Int, val z: Int) { constructor(array: IntArray) : this(array[0], array[1], array[2]) fun rotate(axis: Axis) = when (axis) { Axis.X -> Vector(x, -z, y) Axis.Y -> Vector(z, y, -x) Axis.Z -> Vector(-y, x, z) } operator fun plus(other: Vector) = Vector(x + other.x, y + other.y, z + other.z) operator fun minus(other: Vector) = Vector(x - other.x, y - other.y, z - other.z) fun manhattanDistanceTo(other: Vector) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) override fun toString() = "$x,$y,$z" } private data class World(val scanners: Collection<Vector>, val beacons: Collection<Vector>) { companion object { fun fromScannerData(input: List<String>): World { val scanners = parseAllScanners(input) val origin = scanners.first() val scannersToLocate = scanners.drop(1).toMutableSet() val beacons = origin.beacons.toMutableList() val scannerPositions = mutableListOf(Vector(0, 0, 0)) while (scannersToLocate.isNotEmpty()) { var newScannerFound = false val iterator = scannersToLocate.iterator() while (iterator.hasNext()) { val scanner = iterator.next() Scanner.tryLocateScanner(scanner, beacons)?.let { (scannerPosition, newBeacons) -> println("Found $scanner at $scannerPosition (adding ${newBeacons.size} new beacons)") scannerPositions.add(scannerPosition) beacons.addAll(newBeacons) iterator.remove() newScannerFound = true } } if (!newScannerFound) break } return World(scannerPositions, beacons) } /** * Parses the input into a list of scanners with beacons relative to their center */ private fun parseAllScanners(input: List<String>): List<Scanner> { val scannerInput = mutableListOf<String>() return buildList { for (line in input) { if (line.isBlank()) { add(Scanner.parseString(scannerInput)) scannerInput.clear() } else { scannerInput.add(line) } } // input file does not end with a blank line if (scannerInput.isNotEmpty()) { add(Scanner.parseString(scannerInput)) } } } } } private fun part1(world: World) = world.beacons.size private fun part2(world: World): Int { val scanners = world.scanners var maxDistance = 0 for (s1 in scanners) { for (s2 in scanners) { maxDistance = max(maxDistance, s1.manhattanDistanceTo(s2)) } } return maxDistance } fun main() { // test if implementation meets criteria from the description, like: val testInput = World.fromScannerData(readInput("Day19_test")) check(part1(testInput) == 79) check(part2(testInput) == 3621) val input = World.fromScannerData(readInput("Day19")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
7,290
adventOfCode
Apache License 2.0
src/test/kotlin/amb/aoc2020/day16.kt
andreasmuellerbluemlein
318,221,589
false
null
package amb.aoc2020 import org.junit.jupiter.api.Test class Day16 : TestBase() { data class Input( var validValues: Map<String, List<Int>>, var myTicket: List<Int>, var nearbyTickets: List<List<Int>> ) fun getInput(file: String): Input { val validValues = emptyMap<String, List<Int>>().toMutableMap() val myTicket = emptyList<Int>().toMutableList() val nearbyTickets = emptyList<List<Int>>().toMutableList() var section = "rules:" getTestData(file).filter { it.isNotEmpty() }.forEach { line -> if (line == "your ticket:" || line == "nearby tickets:") section = line else when (section) { "rules:" -> { val parts = line.split(": ", " or ") validValues[parts[0]] = parts.drop(1).flatMap { val numberStrings = it.split("-") numberStrings[0].toInt()..numberStrings[1].toInt() } } "your ticket:" -> { myTicket.addAll(line.split(",").map { it.toInt() }) } "nearby tickets:" -> { nearbyTickets.add(line.split(",").map { it.toInt() }) } else -> throw NotImplementedError() } } return Input(validValues, myTicket, nearbyTickets) } fun findInvalidTicketValues(validValues: Map<String, List<Int>>, ticket: List<Int>): List<Int> { return ticket.filter { ticketValue -> !validValues.any { rule -> rule.value.contains(ticketValue) } } } fun isTicketValid(validValues: Map<String, List<Int>>, ticket: List<Int>): Boolean { return ticket.all { ticketValue -> validValues.any { rule -> rule.value.contains(ticketValue) } } } @Test fun task1() { val input = getInput("input16") logger.info { input.toString() } val sumOfInvalidTicketValues = input.nearbyTickets.flatMap { ticket -> findInvalidTicketValues(input.validValues, ticket) }.sum() logger.info { "sum of invalid ticket values: $sumOfInvalidTicketValues" } } fun findRuleIndexCandidates( validValues: List<Int>, validTickets: List<List<Int>>, assignedIndices: List<Int> ): List<Int> { return (0 until validTickets.first().count()).minus(assignedIndices).filter { ticketValueIndex -> validTickets.all { ticket -> validValues.contains(ticket[ticketValueIndex]) } } } @Test fun task2() { val input = getInput("input16") logger.info { input.toString() } logger.info { "count of nearbyTickets: ${input.nearbyTickets.count()}" } val invalidTickets = input.nearbyTickets.filter { !isTicketValid(input.validValues, it) } val validTickets = input.nearbyTickets.union(listOf(input.myTicket)).minus(invalidTickets).toList() logger.info { "count of validTickets: ${validTickets.count()}" } val unassignedRules = input.validValues.keys.toMutableList() val ruleIndexMap = emptyMap<String, Int>().toMutableMap() while (unassignedRules.any()) { unassignedRules.toList().forEach { rule -> val indexCandidates = findRuleIndexCandidates(input.validValues[rule]!!, validTickets, ruleIndexMap.values.toList()) if (indexCandidates.count() == 1) { unassignedRules.remove(rule) ruleIndexMap[rule] = indexCandidates.first() } } } logger.info{"ruleIndexMap: $ruleIndexMap"} val multiplyDeparture = ruleIndexMap.filter { it.key.startsWith("departure") }.map{input.myTicket[it.value].toLong()}.reduce{ acc, element -> acc * element } logger.info { "multiplied departure values : $multiplyDeparture" } } }
1
Kotlin
0
0
dad1fa57c2b11bf05a51e5fa183775206cf055cf
4,130
aoc2020
MIT License
src/main/kotlin/y2016/day02/Day02.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2016.day02 import AoCGenerics fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } fun input(): List<String> { return AoCGenerics.getInputLines("/y2016/day02/input.txt") } val SQUARE_FIELD = listOf( listOf(1, 2, 3), listOf(4, 5, 6), listOf(7, 8, 9) ) val STAR_FIELD = listOf( listOf(null, null, "1", null, null), listOf(null, "2", "3", "4", null), listOf("5", "6", "7", "8", "9"), listOf(null, "A", "B", "C", null), listOf(null, null, "D", null, null), ) fun part1(): String { val commands = input() var x = 1 var y = 1 var result = "" commands.forEach { command -> command.forEach { step -> when (step) { 'U' -> if (y != 0) y -= 1 'R' -> if (x != 2) x += 1 'D' -> if (y != 2) y += 1 'L' -> if (x != 0) x -= 1 } } result += SQUARE_FIELD[y][x].toString() } return result } fun part2(): String { val commands = input() var x = 0 var y = 2 var result = "" commands.forEach { command -> command.forEach { step -> when (step) { 'U' -> if (y != 0 && STAR_FIELD[y-1][x] != null) y -= 1 'R' -> if (x != 4 && STAR_FIELD[y][x+1] != null) x += 1 'D' -> if (y != 4 && STAR_FIELD[y+1][x] != null) y += 1 'L' -> if (x != 0 && STAR_FIELD[y][x-1] != null) x -= 1 } } result += STAR_FIELD[y][x].toString() } return result }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
1,648
AdventOfCode
MIT License
src/Day04.kt
felldo
572,233,925
false
{"Kotlin": 76496}
fun main() { val testInput = readInput("Day04") val input = testInput .map { it.split(",") } .map { listOf( Pair(it[0].split("-")[0].toInt(), it[0].split("-")[1].toInt()), Pair(it[1].split("-")[0].toInt(), it[1].split("-")[1].toInt()) ) } println("Part 1: " + input.count { it[0].first <= it[1].first && it[0].second >= it[1].second || it[0].first >= it[1].first && it[0].second <= it[1].second }) println("Part 2: " + input.count { it[0].first in it[1].first..it[1].second || it[0].second in it[1].first..it[1].second || it[1].first in it[0].first..it[0].second || it[1].second in it[0].first..it[0].second }) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
727
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/g1001_1100/s1001_grid_illumination/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1001_1100.s1001_grid_illumination // #Hard #Array #Hash_Table #2023_05_14_Time_801_ms_(100.00%)_Space_121_MB_(100.00%) class Solution { fun gridIllumination(n: Int, lamps: Array<IntArray>, queries: Array<IntArray>): IntArray { val rowIlluminations: MutableMap<Int, Int> = HashMap() val colIlluminations: MutableMap<Int, Int> = HashMap() val posDiagIlluminations: MutableMap<Int, Int> = HashMap() val negDiagIlluminations: MutableMap<Int, Int> = HashMap() val lampPlacements: MutableSet<Long> = HashSet() for (lamp in lamps) { val row = lamp[0] val col = lamp[1] var key = row.toLong() key = key * n + col if (lampPlacements.contains(key)) { continue } incr(rowIlluminations, row) incr(colIlluminations, col) incr(posDiagIlluminations, row + col) incr(negDiagIlluminations, row + (n - 1 - col)) lampPlacements.add(key) } val ans = IntArray(queries.size) for (i in ans.indices) { val row = queries[i][0] val col = queries[i][1] if (rowIlluminations.containsKey(row) || colIlluminations.containsKey(col) || posDiagIlluminations.containsKey(row + col) || negDiagIlluminations.containsKey(row + (n - 1 - col)) ) { ans[i] = 1 } val topRow = 0.coerceAtLeast(row - 1) val bottomRow = (n - 1).coerceAtMost(row + 1) val leftCol = 0.coerceAtLeast(col - 1) val rightCol = (n - 1).coerceAtMost(col + 1) for (r in topRow..bottomRow) { for (c in leftCol..rightCol) { var key = r.toLong() key = key * n + c if (lampPlacements.contains(key)) { decr(rowIlluminations, r) decr(colIlluminations, c) decr(posDiagIlluminations, r + c) decr(negDiagIlluminations, r + (n - 1 - c)) lampPlacements.remove(key) } } } } return ans } private fun incr(map: MutableMap<Int, Int>, key: Int) { map[key] = map.getOrDefault(key, 0) + 1 } private fun decr(map: MutableMap<Int, Int>, key: Int) { val v = map.getValue(key) if (map[key] == 1) { map.remove(key) } else { map[key] = v - 1 } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,619
LeetCode-in-Kotlin
MIT License
kotlin/src/main/kotlin/be/swsb/aoc2023/day6/Day6.kt
Sch3lp
724,797,927
false
{"Kotlin": 44815, "Rust": 14075}
package be.swsb.aoc2023.day6 fun parse(input: String): Races { val (times, distances) = input.lines() .map { line -> """\d{1,4}""".toRegex().findAll(line).map { it.value.toLong() } } return Races(times.zip(distances).toList()) } fun parse2(input: String): Races { val (time, distance) = input.lines() .map { line -> """\d{1,4}""".toRegex().findAll(line).joinToString("") { it.value } }.map { it.toLong() } return Races(listOf(time to distance)) } class Races(val highscores: List<Pair<Time, Distance>>) { private val boatSpeedPerHoldTime = 1 fun raceImprovements(): List<ButtonHoldTime> = highscores.map { (time, distance) -> raceImprovement(time, distance) } private fun raceImprovement(time: Time, distanceToBeat: Distance): ButtonHoldTime { val distances = (0..time).map { holdTime -> (time - holdTime) * (holdTime * boatSpeedPerHoldTime) } return distances.reduce { acc, cur -> if (cur > distanceToBeat) acc + 1 else acc } } } typealias Time = Long typealias Distance = Long typealias ButtonHoldTime = Long
0
Kotlin
0
1
dec9331d3c0976b4de09ce16fb8f3462e6f54f6e
1,086
Advent-of-Code-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/codingbat/recursion2/GroupSum5.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2024 <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.codingbat.recursion2 import java.util.Stack /** * Recursion-2 > groupSum5 * @see <a href="https://codingbat.com/prob/p138907">Source</a> */ fun interface GroupSum5 { operator fun invoke(start: Int, nums: IntArray, target: Int): Boolean } class GroupSum5Iterative : GroupSum5 { override fun invoke(start: Int, nums: IntArray, target: Int): Boolean { val stack = Stack<Group5>() stack.push(Group5(start, target, false)) while (stack.isNotEmpty()) { val (index, currentTarget, multipleOf5Included) = stack.pop() if (index >= nums.size) { if (currentTarget == 0) { return true } continue } if (nums[index] % 5 == 0) { stack.push(Group5(index + 1, currentTarget - nums[index], true)) } else if (index > 0 && nums[index - 1] % 5 == 0 && nums[index] == 1) { stack.push(Group5(index + 1, currentTarget, multipleOf5Included)) } else { stack.push(Group5(index + 1, currentTarget - nums[index], multipleOf5Included)) stack.push(Group5(index + 1, currentTarget, multipleOf5Included)) } } return false } private data class Group5( val index: Int, val target: Int, val multipleOf5Included: Boolean, ) } class GroupSum5Recursive : GroupSum5 { override fun invoke(start: Int, nums: IntArray, target: Int): Boolean { return groupSum5Helper(start, nums, target, false) } private fun groupSum5Helper(start: Int, nums: IntArray, target: Int, multipleOf5Included: Boolean): Boolean { // Base case if (start >= nums.size) { return target == 0 } // Check if the current number is a multiple of 5 if (nums[start] % 5 == 0) { return groupSum5Helper(start + 1, nums, target - nums[start], true) } // If the current number is not a multiple of 5 and the previous number was a multiple of 5 // and the current number is 1, skip this number if (multipleOf5Included && nums[start] == 1) { return groupSum5Helper(start + 1, nums, target, multipleOf5Included) } // Include the current number in the sum if (groupSum5Helper(start + 1, nums, target - nums[start], multipleOf5Included)) { return true } // Exclude the current number from the sum return groupSum5Helper(start + 1, nums, target, multipleOf5Included) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,222
kotlab
Apache License 2.0
src/Day03/Day03.kt
brhliluk
572,914,305
false
{"Kotlin": 16006}
fun main() { val backpackItems = ('a'..'z' union 'A'..'Z') val itemValues = (1..52).toMutableList() val valuedItems = backpackItems.associateWith { itemValues.removeFirst() } var totalGroupValue = 0 fun part1(input: List<String>) = input.map { backpack -> val firstHalf = backpack.take(backpack.length / 2).toSet() val secondHalf = backpack.takeLast(backpack.length / 2).toSet() valuedItems[(firstHalf intersect secondHalf).first()]!! }.sumOf { it } fun part2(input: List<String>): Int { input.chunked(3).map { group -> group.map { it.toSet() } }.forEach { group -> totalGroupValue += valuedItems[(group[0] intersect group[1] intersect group[2]).first()]!! } return totalGroupValue } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
96ac4fe0c021edaead8595336aad73ef2f1e0d06
868
kotlin-aoc
Apache License 2.0
src/commonMain/kotlin/io/github/z4kn4fein/semver/constraints/ComparatorBuilder.kt
z4kn4fein
444,514,222
false
{"Kotlin": 112810, "CSS": 380}
package io.github.z4kn4fein.semver.constraints import io.github.z4kn4fein.semver.Version import io.github.z4kn4fein.semver.nextMajor import io.github.z4kn4fein.semver.nextMinor import io.github.z4kn4fein.semver.nextPatch internal interface ComparatorBuilder { val acceptedOperators: Array<String> fun buildComparator(operatorString: String, versionDescriptor: VersionDescriptor): VersionComparator } internal class RegularComparatorBuilder : ComparatorBuilder { override val acceptedOperators: Array<String> = arrayOf("=", "!=", ">", ">=", "=>", "<", "<=", "=<", "") override fun buildComparator(operatorString: String, versionDescriptor: VersionDescriptor): VersionComparator = versionDescriptor.toComparator(operatorString.toOperator()) } internal class TildeComparatorBuilder : ComparatorBuilder { override val acceptedOperators: Array<String> = arrayOf("~>", "~") override fun buildComparator(operatorString: String, versionDescriptor: VersionDescriptor): VersionComparator = when { versionDescriptor.isWildcard -> versionDescriptor.toComparator() else -> { val version = Version( versionDescriptor.major, versionDescriptor.minor, versionDescriptor.patch, versionDescriptor.preRelease, versionDescriptor.buildMetadata ) Range( start = Condition(Op.GREATER_THAN_OR_EQUAL, version), end = Condition(Op.LESS_THAN, version.nextMinor(preRelease = "")), Op.EQUAL ) } } } internal class CaretComparatorBuilder : ComparatorBuilder { override val acceptedOperators: Array<String> = arrayOf("^") override fun buildComparator(operatorString: String, versionDescriptor: VersionDescriptor): VersionComparator = when { versionDescriptor.isMajorWildcard -> VersionComparator.greaterThanMin versionDescriptor.isMinorWildcard -> fromMinorWildcardCaret(versionDescriptor) versionDescriptor.isPatchWildcard -> fromPatchWildcardCaret(versionDescriptor) else -> { val version = Version( versionDescriptor.major, versionDescriptor.minor, versionDescriptor.patch, versionDescriptor.preRelease, versionDescriptor.buildMetadata ) val endVersion = when { versionDescriptor.majorString != "0" -> version.nextMajor(preRelease = "") versionDescriptor.minorString != "0" -> version.nextMinor(preRelease = "") versionDescriptor.patchString != "0" -> version.nextPatch(preRelease = "") else -> Version(patch = 1, preRelease = "") // ^0.0.0 -> <0.0.1-0 } Range( start = Condition(Op.GREATER_THAN_OR_EQUAL, version), end = Condition(Op.LESS_THAN, endVersion), Op.EQUAL ) } } private fun fromMinorWildcardCaret(versionDescriptor: VersionDescriptor): VersionComparator = when (versionDescriptor.majorString) { "0" -> Range( VersionComparator.greaterThanMin, Condition(Op.LESS_THAN, Version(major = 1, preRelease = "")), Op.EQUAL ) else -> versionDescriptor.toComparator() } private fun fromPatchWildcardCaret(versionDescriptor: VersionDescriptor): VersionComparator = when { versionDescriptor.majorString == "0" && versionDescriptor.minorString == "0" -> Range( VersionComparator.greaterThanMin, Condition(Op.LESS_THAN, Version(minor = 1, preRelease = "")), Op.EQUAL ) versionDescriptor.majorString != "0" -> { val version = Version(major = versionDescriptor.major, minor = versionDescriptor.minor) Range( Condition(Op.GREATER_THAN_OR_EQUAL, version), Condition(Op.LESS_THAN, version.nextMajor(preRelease = "")), Op.EQUAL ) } else -> versionDescriptor.toComparator() } }
0
Kotlin
0
76
ad9da0fc82a213acbb0e1b174db05c0fa0e8f2ba
4,481
kotlin-semver
MIT License
src/main/kotlin/g0001_0100/s0023_merge_k_sorted_lists/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0001_0100.s0023_merge_k_sorted_lists // #Hard #Top_100_Liked_Questions #Top_Interview_Questions #Heap_Priority_Queue #Linked_List // #Divide_and_Conquer #Merge_Sort #Big_O_Time_O(k*n*log(k))_Space_O(log(k)) // #2023_07_03_Time_198_ms_(93.77%)_Space_37.6_MB_(97.03%) import com_github_leetcode.ListNode /* * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun mergeKLists(lists: Array<ListNode>): ListNode? { return if (lists.isEmpty()) { null } else mergeKLists(lists, 0, lists.size) } private fun mergeKLists(lists: Array<ListNode>, leftIndex: Int, rightIndex: Int): ListNode? { return if (rightIndex > leftIndex + 1) { val mid = (leftIndex + rightIndex) / 2 val left = mergeKLists(lists, leftIndex, mid) val right = mergeKLists(lists, mid, rightIndex) mergeTwoLists(left, right) } else { lists[leftIndex] } } private fun mergeTwoLists(leftLocal: ListNode?, rightLocal: ListNode?): ListNode? { var left = leftLocal var right = rightLocal if (left == null) { return right } if (right == null) { return left } val res: ListNode if (left.`val` <= right.`val`) { res = left left = left.next } else { res = right right = right.next } var node: ListNode? = res while (left != null || right != null) { if (left == null) { node!!.next = right right = right!!.next } else if (right == null) { node!!.next = left left = left.next } else { if (left.`val` <= right.`val`) { node!!.next = left left = left.next } else { node!!.next = right right = right.next } } node = node.next } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,211
LeetCode-in-Kotlin
MIT License
src/main/kotlin/uk/co/skipoles/eventmodeller/visualisation/render/CenteredMultiLineStringRenderer.kt
skipoleschris
506,202,133
false
{"Kotlin": 119832}
package uk.co.skipoles.eventmodeller.visualisation.render import java.awt.Graphics2D import java.awt.geom.Rectangle2D internal fun Graphics2D.drawCentredMultiLineString( s: String, x: Int, y: Int, width: Int, height: Int ) { val lines = divideIntoLines("", s, width, areaForString(this)) val linesThatFit = mostLinesThatFitHeight(lines, height) val totalHeight = linesThatFit.sumOf { it.area.height }.toInt() var yPosition = y + ((height - totalHeight) / 2) linesThatFit.forEach { drawString(it.s, (x + ((width - it.area.width.toInt()) / 2)), yPosition) yPosition += it.area.height.toInt() } } private data class LineWithArea(val s: String, val area: Rectangle2D) private fun divideIntoLines( current: String, remainder: String, maxWidth: Int, findArea: (String) -> Rectangle2D ): List<LineWithArea> { if (remainder.isEmpty()) return listOf(LineWithArea(current, findArea(current))) val nextWord = remainder.takeWhile { it != ' ' } val line = if (current.isEmpty()) nextWord else "$current $nextWord" val lineArea = findArea(line) return if (lineArea.width < (maxWidth - 2)) { // Line is shorter than max width divideIntoLines(line, remainder.drop(nextWord.length + 1), maxWidth, findArea) } else if (current.isEmpty()) { // Line is longer than max width and is a single word val longestSubstring = longestSubstringThatFitsWidth(line, maxWidth, findArea) listOf(LineWithArea(longestSubstring, findArea(longestSubstring))) + divideIntoLines("", remainder.drop(longestSubstring.length), maxWidth, findArea) } else { // Line is longer than max width, so needs a line break listOf(LineWithArea(current, findArea(current))) + divideIntoLines("", remainder.trim(), maxWidth, findArea) } } private fun longestSubstringThatFitsWidth( word: String, maxWidth: Int, findArea: (String) -> Rectangle2D ) = word .fold(Pair("", false)) { res, ch -> val (s, state) = res if (state) res else { val test = s + ch val testArea = findArea(test) if (testArea.width < (maxWidth - 2)) Pair(test, false) else Pair(s, true) } } .first private fun mostLinesThatFitHeight(lines: List<LineWithArea>, maxHeight: Int) = lines .fold(Pair(listOf<LineWithArea>(), false)) { result, line -> val (validLines, done) = result if (done) result else { val newHeight = validLines.sumOf { it.area.height } + line.area.height if (newHeight < (maxHeight - 2)) Pair(validLines + line, false) else Pair(validLines, true) } } .first private fun areaForString(graphics: Graphics2D): (String) -> Rectangle2D = fun(s: String) = graphics.font.getStringBounds(s, graphics.fontRenderContext)
0
Kotlin
0
0
4e7fe756d0c203cd7e781cc40c2b16776aa9f3ab
2,877
event-modeller
Apache License 2.0
src/main/java/io/github/lunarwatcher/aoc/day10/Day10.kt
LunarWatcher
160,042,659
false
null
package io.github.lunarwatcher.aoc.day10 import io.github.lunarwatcher.aoc.commons.Vector2i import io.github.lunarwatcher.aoc.commons.readFile val regex = "pos=<(-?\\d*),(-?\\d*)>velocity=<(-?\\d*),(-?\\d*)>".toRegex(); fun parseVectors(raw: List<String>) : List<Pair<Vector2i, Vector2i>>{ return raw.map { val groups = regex.find(it.replace(" ", ""))!!.groupValues val x = groups[1].toInt(); val y = groups[2].toInt() val velX = groups[3].toInt() val velY = groups[4].toInt() Vector2i(x, y) to Vector2i(velX, velY) } } fun day10part1processor(raw: List<String>){ val pairs = parseVectors(raw) var lastIndex = 0; // This was a literal hell xd Using Int.MAX_VALUE will print too much. Anything over 1000 will in general. // These were set based on observations; The final output is generally tiny in span, which means the right // answer is likely at one of the time steps with the lowest spread of points. var minXVal = 100; var minYVal = 100; for(i in 0..10E6.toInt()){ var minX = Integer.MAX_VALUE var minY = Integer.MAX_VALUE var maxX = Integer.MIN_VALUE var maxY = Integer.MIN_VALUE for(pair in pairs){ pair.first += pair.second if(pair.first.x > maxX) maxX = pair.first.x; if(pair.first.x < minX) minX = pair.first.x; if(pair.first.y > maxY) maxY = pair.first.y; if(pair.first.y < minY){ minY = pair.first.y; } } var printed = false; if(maxX - minX < minXVal){ minXVal = maxX - minX lastIndex = i; printed = true; println(i + 1) // Seconds don't start from 0 (hopefully) pairs.print() } if(maxY - minY < minYVal){ minYVal = maxY - minY; lastIndex = i; if(!printed) { println(i + 1); // Seconds don't start from 0 (hopefully) pairs.print() } } if(i - lastIndex > 30000) break; } } private fun List<Pair<Vector2i, Vector2i>>.print(){ val mapping = this.sortedWith (compareBy ({ it.first.x }, { it.first.y })) .map { it.first } val xes = mapping.map { it.x }.sorted() val ys = mapping.map { it.y }.sorted() val minX = xes.first(); val maxX = xes.last(); val minY = ys.first(); val maxY = ys.last(); for(y in minY..maxY){ for(x in minX..maxX){ print(if(mapping.any { it.x == x && it.y == y }) "#" else ".") } println() } println() } fun day10(part: Boolean){ val raw = readFile("day10.txt"); day10part1processor(raw) }
0
Kotlin
0
1
99f9b05521b270366c2f5ace2e28aa4d263594e4
2,809
AoC-2018
MIT License
src/iii_conventions/MyDate.kt
splendie
104,372,378
false
null
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { if (this.year < other.year) return -1 else if (this.year > other.year) return 1 else { if (this.month < other.month) return -1 else if (this.month > other.month) return 1 else { if (this.dayOfMonth < other.dayOfMonth) return -1 else if (this.dayOfMonth > other.dayOfMonth) return 1 else return 0 } } } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) operator fun MyDate.plus(timeInterval: TimeInterval) : MyDate { var result: MyDate when (timeInterval) { TimeInterval.DAY -> result = this.addTimeIntervals(iii_conventions.TimeInterval.DAY, 1) TimeInterval.WEEK -> result = this.addTimeIntervals(iii_conventions.TimeInterval.WEEK, 1) TimeInterval.YEAR -> result = this.addTimeIntervals(iii_conventions.TimeInterval.YEAR, 1) } return result } operator fun MyDate.plus(rti: RepeatedTimeInterval): MyDate { var result: MyDate when (rti.ti) { TimeInterval.DAY -> result = this.addTimeIntervals(iii_conventions.TimeInterval.DAY, rti.n) TimeInterval.WEEK -> result = this.addTimeIntervals(iii_conventions.TimeInterval.WEEK, rti.n) TimeInterval.YEAR -> result = this.addTimeIntervals(iii_conventions.TimeInterval.YEAR, rti.n) } return result } operator fun DateRange.iterator(): DateRangeIterator = object : DateRangeIterator() { private var current: MyDate = start override fun nextDate(): MyDate { if (!hasNext()) throw NoSuchElementException() val result = current current = current.nextDay() return result } override fun hasNext(): Boolean = current <= endInclusive } abstract class DateRangeIterator : Iterator<MyDate> { override final fun next() = nextDate() /** Returns the next value in the sequence without boxing. */ abstract fun nextDate(): MyDate } enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>
0
Kotlin
0
0
44f5da525b197525508bf5e6063a32b48cd52530
2,424
kotlin_koans_exercise
MIT License
src/Day14.kt
uekemp
575,483,293
false
{"Kotlin": 69253}
enum class CaveType(val char: Char) { OPEN('.'), ROCK('#'), SAND('o') } class Cave { val data = mutableMapOf<Coordinate, CaveType>() private val left: Int get() = data.keys.minOf { it.x } private val right: Int get() = data.keys.maxOf { it.x } private val top: Int get() = data.keys.minOf { it.y } private val bottom: Int get() = data.keys.maxOf { it.y } private var lowestRock = Int.MIN_VALUE // Used for part 1 private var floor = Int.MAX_VALUE // Used for part 2 operator fun get(c: Coordinate): CaveType { return if (c.y >= floor) { CaveType.ROCK } else { data[c] ?: CaveType.OPEN } } operator fun set(c: Coordinate, type: CaveType) { data[c] = type } private fun isBlocked(c: Coordinate) = this[c] != CaveType.OPEN fun addRocks(coordinates: List<Coordinate>) { coordinates.zipWithNext { start, end -> for (rockCoordinate in start..end) { this[rockCoordinate] = CaveType.ROCK if (rockCoordinate.y > lowestRock) { lowestRock = rockCoordinate.y floor = lowestRock + 2 } } } } fun nextPart1(): Boolean { var sand = Coordinate(500, 0) while (sand.y < lowestRock) { val next = tryToMove(sand) if (next == sand) { break } else { sand = next } } return if (sand.y >= lowestRock) { false } else { this[sand] = CaveType.SAND true } } fun nextPart2(): Boolean { var sand = Coordinate(500, 0) if (isBlocked(sand)) { return false } while (true) { val next = tryToMove(sand) if (next == sand) { this[sand] = CaveType.SAND break } else { sand = next } } return true } private fun tryToMove(sand: Coordinate): Coordinate { val down = sand.moveBy(dy = 1) return if (!isBlocked(down)) { down } else { val left = sand.moveBy(dx = -1, dy = 1) if (!isBlocked(left)) { left } else { val right = sand.moveBy(dx = 1, dy = 1) if (!isBlocked(right)) { right } else { sand } } } } override fun toString(): String { return buildString { for (y in top .. bottom) { for (x in left..right) { append(this@Cave[Coordinate(x, y)].char) } appendLine() } } } companion object { fun of(input: List<String>): Cave { return Cave().apply { input.forEach { line -> val rocks = line.split(" -> ") .map { text -> text.split(",") } .map { numbers -> Coordinate(numbers[0].toInt(), numbers[1].toInt()) } addRocks(rocks) } } } } } fun main() { fun part1(input: List<String>): Int { return with(Cave.of(input)) { generateSequence { if (nextPart1()) 1 else null }.sum() } } fun part2(input: List<String>): Int { return with(Cave.of(input)) { generateSequence { if (nextPart2()) 1 else null }.sum() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) val input = readInput("Day14") check(part1(input) == 672) check(part2(input) == 26831) }
0
Kotlin
0
0
bc32522d49516f561fb8484c8958107c50819f49
3,945
advent-of-code-kotlin-2022
Apache License 2.0
kotlin/src/main/kotlin/de/p58i/advent-08.kt
mspoeri
573,120,274
false
{"Kotlin": 31279}
package de.p58i import java.io.File data class Tree( val height: Int ) { var visible: Boolean = false var scenicScore: Int = 0 } val lowTree = Tree(-1) fun main() { val forest = ArrayList<Array<Tree>>() File("./task-inputs/advent-08.input").forEachLine { forest.add( it.map { treeInput -> Tree(Integer.parseInt(treeInput.toString())) }.toTypedArray() ) } lookFromLeft(forest) printForest(forest) println() lookFromRight(forest) printForest(forest) println() lookFromTop(forest) printForest(forest) println() lookFromBottom(forest) printForest(forest) println() calcScenicScores(forest) printScenicScores(forest) val mostScenicTrees = forest.flatMap { it.asList() }.filter { it.visible } println(""" Marker Count: ${forest.flatMap { it.asList() }.count { it.visible }} Max Scenic Score: ${mostScenicTrees.maxBy { it.scenicScore }.scenicScore} """.trimIndent()) } private fun printForest(forest: ArrayList<Array<Tree>>) { println(forest.joinToString(separator = "\n") { forrestRow -> forrestRow.joinToString(separator = "") { if (it.visible) { "v" } else { it.height.toString() } } }) } private fun printScenicScores(forest: ArrayList<Array<Tree>>) { println(forest.joinToString(separator = "\n") { forrestRow -> forrestRow.joinToString(separator = " ") { if (it.visible) { String.format("%06d", it.scenicScore) } else { String.format("%06d", it.scenicScore) } } }) } fun lookFromLeft(forest: ArrayList<Array<Tree>>) { for (row in 0 until forest.size) { var highestTree = lowTree for (column in (0 until forest[row].size)) { val tree = forest[row][column] if (tree.height > highestTree.height) { highestTree = tree forest[row][column].visible = true } } } } fun lookFromRight(forest: ArrayList<Array<Tree>>) { for (row in 0 until forest.size) { var highestTree = lowTree for (column in (0 until forest[row].size).reversed()) { val tree = forest[row][column] if (tree.height > highestTree.height) { highestTree = tree forest[row][column].visible = true } } } } fun lookFromTop(forest: ArrayList<Array<Tree>>) { val columns = forest.first().size for (column in 0 until columns) { var highestTree = lowTree for (row in 0 until forest.size) { val tree = forest[row][column] if (tree.height > highestTree.height) { highestTree = tree forest[row][column].visible = true } } } } fun lookFromBottom(forest: ArrayList<Array<Tree>>) { val columns = forest.first().size for (column in 0 until columns) { var highestTree = lowTree for (row in (0 until forest.size).reversed()) { val tree = forest[row][column] if (tree.height > highestTree.height) { highestTree = tree forest[row][column].visible = true } } } } fun calcScenicScores(forest: ArrayList<Array<Tree>>) { forest.forEachIndexed { row, trees -> trees.forEachIndexed { column, tree -> tree.calcScenicScore(forest, row, column) } } } fun Tree.calcScenicScore(forest: ArrayList<Array<Tree>>, row: Int, column: Int) { val upTrees = (column - 1 downTo 0).map { forest[row][it] } val downTrees = (column + 1 until forest[row].size).map { forest[row][it] } val leftTrees = (row - 1 downTo 0).map { forest[it][column] } val rightTrees = (row + 1 until forest.size).map { forest[it][column] } val upScore = calcScenicForTreeRange(upTrees) val downScore = calcScenicForTreeRange(downTrees) val leftScore = calcScenicForTreeRange(leftTrees) val rightScore = calcScenicForTreeRange(rightTrees) this.scenicScore = upScore * downScore * leftScore * rightScore } private fun Tree.calcScenicForTreeRange(upTrees: List<Tree>): Int { var scenicScore = 0 for (currentTree in upTrees) { if (currentTree.height < this.height) { scenicScore += 1 } if (currentTree.height >= this.height) { scenicScore += 1 break } } return scenicScore }
0
Kotlin
0
1
62d7f145702d9126a80dac6d820831eeb4104bd0
4,611
Advent-of-Code-2022
MIT License
src/Day06.kt
afranken
572,923,112
false
{"Kotlin": 15538}
fun main() { fun part1(input: List<String>): Int { val count = 4 return input[0] .windowed(count) .mapIndexed { index, chunk -> if (chunk.toSet().size == count) { index + count } else { //chunk contains duplicate chars 0 } }.first { it != 0 } } fun part2(input: List<String>): Int { val count = 14 return input[0] .windowed(count) .mapIndexed { index, chunk -> if (chunk.toSet().size == count) { index + count } else { //chunk contains duplicate chars 0 } }.first { it != 0 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 5) val input = readInput("Day06") check(part1(input) == 1480) check(part2(input) == 2746) }
0
Kotlin
0
0
f047d34dc2a22286134dc4705b5a7c2558bad9e7
1,109
advent-of-code-kotlin-2022
Apache License 2.0
aoc2023/day10.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2023 import utils.InputRetrieval fun main() { Day10.execute() } private object Day10 { fun execute() { val input = readInput() val foundPositions = mutableMapOf<Position, Int>() println("Part 1: ${part1(input, foundPositions)}") println("Part 2: The answer is one of these, just try both: ${part2(input, foundPositions)}") } private fun part1(input: List<String>, foundPositions: MutableMap<Position, Int>): Int { val startIndex: Position = getStartPosition(input) foundPositions[startIndex] = 0 for (i in input.findConnectedPipes(startIndex)) { var moveNumber = 1 // For each visited move, just store the number of steps that we took to get there input.navigatePipes(i) { move -> val (pos, _) = move if (moveNumber < (foundPositions[pos] ?: Integer.MAX_VALUE)) { foundPositions[pos] = moveNumber } moveNumber += 1 } } return foundPositions.values.max() } private fun part2(initialInput: List<String>, pipePositions: Map<Position, Int>): List<Int> { // Filter the input, to replace all unconnected pipes with a blank symbol ('.') val filteredInput = initialInput.mapIndexed { y, row -> String(row.mapIndexed { x, c -> if (pipePositions.contains(Position(x, y))) { c } else { '.' } }.toCharArray()) } // Just calculate both directions, checking with side is the correct one is too big of a PITA val startIndex: Position = getStartPosition(filteredInput) return filteredInput.findConnectedPipes(startIndex).map { val foundPositions = mutableMapOf<Position, MutableSet<DIRECTION>>() // Check the starting position neighbours filteredInput.checkPart2(Move(startIndex, it.fromDirection), foundPositions) // For each visited move, just check the neighbours, and if it is a corner piece, to something special filteredInput.navigatePipes(it) { move -> filteredInput.checkPart2(move, foundPositions) if (filteredInput.getPos(move.pos) in listOf('L', '7', 'F', 'J')) { val (_, nextDirection) = filteredInput.getNextPosition(move) filteredInput.checkPart2(Move(move.pos, nextDirection), foundPositions) } } foundPositions.filter { c -> c.value.size == 4 }.count() } } private fun readInput(): List<String> = InputRetrieval.getFile(2023, 10).readLines() private fun List<String>.checkPart2( tmpMove: Move, foundPositions: MutableMap<Position, MutableSet<DIRECTION>>, ) { val (pos, _) = tmpMove when (tmpMove.fromDirection) { DIRECTION.DOWN -> { ((pos.x + 1)..<this.first().length).map { Position(it, pos.y) } .takeWhile { getPos(it) == '.' } .forEach { foundPositions.getOrPut(it) { mutableSetOf() }.add(DIRECTION.RIGHT) } } DIRECTION.LEFT -> { ((pos.y + 1)..<this.size).map { Position(pos.x, it) } .takeWhile { getPos(it) == '.' } .forEach { foundPositions.getOrPut(it) { mutableSetOf() }.add(DIRECTION.DOWN) } } DIRECTION.UP -> { (0..<(pos.x)).reversed().map { Position(it, pos.y) } .takeWhile { getPos(it) == '.' } .forEach { foundPositions.getOrPut(it) { mutableSetOf() }.add(DIRECTION.LEFT) } } DIRECTION.RIGHT -> { (0..<(pos.y)).reversed().map { Position(pos.x, it) } .takeWhile { getPos(it) == '.' } .forEach { foundPositions.getOrPut(it) { mutableSetOf() }.add(DIRECTION.UP) } } } } private fun getStartPosition(input: List<String>): Position = input.mapIndexed { index, line -> index to line.indexOfFirst { it == 'S' } }.first { it.second != -1 }.let { Position(it.second, it.first) } private fun List<String>.navigatePipes(move: Move, calculate: (Move) -> Unit) { var tmpMove = move while (getPos(tmpMove.pos) != 'S') { calculate.invoke(tmpMove) tmpMove = getNextPosition(tmpMove) } } private fun List<String>.getNextPosition(previousPosition: Move): Move { val (pos, fromDirection) = previousPosition return when (getPos(pos)) { '|' -> if (fromDirection == DIRECTION.DOWN) { Move(Position(pos.x, pos.y - 1), DIRECTION.DOWN) } else { Move(Position(pos.x, pos.y + 1), DIRECTION.UP) } '-' -> if (fromDirection == DIRECTION.LEFT) { Move(Position(pos.x + 1, pos.y), DIRECTION.LEFT) } else { Move(Position(pos.x - 1, pos.y), DIRECTION.RIGHT) } 'L' -> if (fromDirection == DIRECTION.UP) { Move(Position(pos.x + 1, pos.y), DIRECTION.LEFT) } else { Move(Position(pos.x, pos.y - 1), DIRECTION.DOWN) } 'J' -> if (fromDirection == DIRECTION.UP) { Move(Position(pos.x - 1, pos.y), DIRECTION.RIGHT) } else { Move(Position(pos.x, pos.y - 1), DIRECTION.DOWN) } '7' -> if (fromDirection == DIRECTION.DOWN) { Move(Position(pos.x - 1, pos.y), DIRECTION.RIGHT) } else { Move(Position(pos.x, pos.y + 1), DIRECTION.UP) } 'F' -> if (fromDirection == DIRECTION.DOWN) { Move(Position(pos.x + 1, pos.y), DIRECTION.LEFT) } else { Move(Position(pos.x, pos.y + 1), DIRECTION.UP) } else -> { throw Exception("invalid transition") } } } private fun List<String>.findConnectedPipes(pos: Position): List<Move> { val linkedPipes = mutableListOf<Move>() val up = Position(pos.x, pos.y - 1) if (this.getPos(up) in listOf('|', '7', 'F')) { linkedPipes.add(Move(up, DIRECTION.DOWN)) } val down = Position(pos.x, pos.y + 1) if (this.getPos(down) in listOf('|', 'L', 'J')) { linkedPipes.add(Move(down, DIRECTION.UP)) } val left = Position(pos.x - 1, pos.y) if (this.getPos(left) in listOf('-', 'L', 'F')) { linkedPipes.add(Move(left, DIRECTION.RIGHT)) } val right = Position(pos.x + 1, pos.y) if (this.getPos(right) in listOf('-', '7', 'J')) { linkedPipes.add(Move(right, DIRECTION.LEFT)) } return linkedPipes } private fun List<String>.getPos(pos: Position): Char = if (pos.y in indices && pos.x in this.first().indices) { this[pos.y][pos.x] } else { '.' } private enum class DIRECTION { UP, DOWN, LEFT, RIGHT } private data class Position(val x: Int, val y: Int) private data class Move(val pos: Position, val fromDirection: DIRECTION) }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
7,353
Advent-Of-Code
MIT License
src/main/kotlin/com/ginsberg/advent2023/Day15.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 15 - Lens Library * Problem Description: http://adventofcode.com/2023/day/15 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day15/ */ package com.ginsberg.advent2023 class Day15(input: String) { private val instructions = input.split(',') fun solvePart1(): Int = instructions.sumOf { it.hash() } fun solvePart2(): Int { val boxes = List<MutableMap<String, Int>>(256) { mutableMapOf() } instructions.forEach { instruction -> if (instruction.endsWith("-")) { val label = instruction.substringBefore('-') boxes[label.hash()].remove(label) } else { val label = instruction.substringBefore('=') boxes[label.hash()][label] = instruction.substringAfter("=").toInt() } } return boxes.withIndex().sumOf { (boxNumber, lenses) -> lenses.values.withIndex().sumOf { (lensNumber, lens) -> (boxNumber + 1) * (lensNumber + 1) * lens } } } private fun String.hash(): Int = this.fold(0) { carry, char -> ((carry + char.code) * 17).rem(256) } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
1,279
advent-2023-kotlin
Apache License 2.0
src/main/kotlin/pl/klemba/aoc/day10/Main.kt
aklemba
726,935,468
false
{"Kotlin": 16373}
package pl.klemba.aoc.day10 import java.io.File fun main() { // ----- PART 1 ----- val pipeField = File(inputPath) .readLines() // Find starting point val startingIndex: Coordinates = pipeField.findStartingIndex() println("Starting index: ${startingIndex}") // Find one of the pipes that create the loop with starting point // Check top first as it is clearly visible that is starts from top val topCoordinates = startingIndex.copy(y = startingIndex.y - 1) println("Top coordinates: ${topCoordinates}") val char: Char = pipeField[topCoordinates.y][topCoordinates.x] val actor = char.mapToActor() // Go through the pipes var nextStep = NextStep(Direction.N, actor as Actor.Pipe, topCoordinates) var pipeCount = 1 while(nextStep.pipe !is Actor.StartingPoint) { pipeCount++ nextStep = pipeField.followThePipeAndCount(nextStep.originDirection, nextStep.pipe as Actor.Pipe, nextStep.pipeCoordinates) } println(pipeCount/2) } private fun List<String>.followThePipeAndCount( originDirection: Direction, pipe: Actor.Pipe, pipeCoordinates: Coordinates, ): NextStep { val nextDirection = when (originDirection.oppositeDirection) { pipe.direction1 -> pipe.direction2 pipe.direction2 -> pipe.direction1 else -> throw IllegalStateException("One direction has to be the same as origin") } val nextCoordinates = calculateNextCoordinates(nextDirection, pipeCoordinates) println("Symbol: ${this[nextCoordinates.y][nextCoordinates.x]}") val actor = this[nextCoordinates.y][nextCoordinates.x].mapToActor() println("Next direction: ${nextDirection}, next coordinates: ${nextCoordinates}") return NextStep(nextDirection, actor, nextCoordinates) } class NextStep(val originDirection: Direction, val pipe: Actor, val pipeCoordinates: Coordinates) private fun calculateNextCoordinates(nextDirection: Direction, pipeCoordinates: Coordinates): Coordinates { val coordinatesChange = when (nextDirection) { Direction.N -> Coordinates(0, -1) Direction.W -> Coordinates(-1, 0) Direction.S -> Coordinates(0, 1) Direction.E -> Coordinates(1, 0) } return pipeCoordinates.copyWithCoordinatesChange(coordinatesChange) } private fun Char.mapToActor(): Actor { if (this == 'S') return Actor.StartingPoint return Actor.Pipe .getByChar(this) ?: throw IllegalStateException("It has to be a pipe!") } private fun List<String>.findStartingIndex(): Coordinates { map { startingPointRegex.find(it) } .forEachIndexed { lineIndex, matchResult -> if (matchResult != null) return Coordinates( matchResult.range.first, lineIndex ) } throw IllegalStateException("Missing starting point!") } data class Coordinates(val x: Int, val y: Int) { fun copyWithCoordinatesChange(coordinatesChange: Coordinates) = copy(x = this.x + coordinatesChange.x, y = this.y + coordinatesChange.y) } private val startingPointRegex = Regex("S") private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day10/input.txt" enum class Direction { N, W, S, E; val oppositeDirection: Direction get() = when (this) { N -> S W -> E E -> W S -> N } } sealed class Actor { object StartingPoint : Actor() sealed class Pipe(val direction1: Direction, val direction2: Direction, val charEquivalent: Char) : Actor() { object N_S : Pipe(Direction.N, Direction.S, '|') object N_E : Pipe(Direction.N, Direction.E, 'L') object W_E : Pipe(Direction.W, Direction.E, '-') object W_N : Pipe(Direction.W, Direction.N, 'J') object S_W : Pipe(Direction.S, Direction.W, '7') object E_S : Pipe(Direction.E, Direction.S, 'F') companion object { fun getByChar(char: Char): Pipe? = when (char) { N_S.charEquivalent -> N_S N_E.charEquivalent -> N_E W_E.charEquivalent -> W_E W_N.charEquivalent -> W_N S_W.charEquivalent -> S_W E_S.charEquivalent -> E_S else -> null } } } }
0
Kotlin
0
1
2432d300d2203ff91c41ffffe266e19a50cca944
4,155
adventOfCode2023
Apache License 2.0
src/main/kotlin/g2801_2900/s2858_minimum_edge_reversals_so_every_node_is_reachable/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2801_2900.s2858_minimum_edge_reversals_so_every_node_is_reachable // #Hard #Dynamic_Programming #Depth_First_Search #Breadth_First_Search #Graph // #2023_12_21_Time_1161_ms_(100.00%)_Space_139.8_MB_(100.00%) import java.util.LinkedList import java.util.Queue class Solution { fun minEdgeReversals(n: Int, edges: Array<IntArray>): IntArray { val nexts: Array<MutableList<IntArray>> = Array(n) { ArrayList() } for (edge in edges) { val u = edge[0] val v = edge[1] nexts[u].add(intArrayOf(1, v)) nexts[v].add(intArrayOf(-1, u)) } val res = IntArray(n) for (i in 0 until n) { res[i] = -1 } res[0] = dfs(nexts, 0, -1) val queue: Queue<Int> = LinkedList() queue.add(0) while (queue.isNotEmpty()) { val index = queue.remove() val `val` = res[index] val next: List<IntArray> = nexts[index] for (node in next) { if (res[node[1]] == -1) { if (node[0] == 1) { res[node[1]] = `val` + 1 } else { res[node[1]] = `val` - 1 } queue.add(node[1]) } } } return res } private fun dfs(nexts: Array<MutableList<IntArray>>, index: Int, pre: Int): Int { var res = 0 val next: List<IntArray> = nexts[index] for (node in next) { if (node[1] != pre) { if (node[0] == -1) { res++ } res += dfs(nexts, node[1], index) } } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,744
LeetCode-in-Kotlin
MIT License
src/main/aoc2020/Day4.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2020 class Day4(input: List<String>) { private data class Field(private val key: String, private val value: String) { private fun String.splitAt(index: Int) = take(index) to substring(index) fun isMandatory() = key != "cid" fun isValid() = when (key) { "byr" -> value.toInt() in 1920..2002 "iyr" -> value.toInt() in 2010..2020 "eyr" -> value.toInt() in 2020..2030 "ecl" -> value in listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") "hcl" -> "^#[0-9a-f]{6}$".toRegex().matches(value) "pid" -> "^[0-9]{9}$".toRegex().matches(value) "hgt" -> { val (number, unit) = value.splitAt(value.length - 2) when (unit) { "cm" -> number.toInt() in 150..193 "in" -> number.toInt() in 59..76 else -> false } } else -> true } } private data class Passport(private val fields: List<Field>) { val hasAllMandatoryFields = fields.count { it.isMandatory() } == 7 val isValid = hasAllMandatoryFields && fields.all { it.isValid() } } private val passports = parseInput(input) private fun parseInput(input: List<String>): List<Passport> { return input.map { passport -> passport.split(" ", "\n") .map { it.split(":").let { (key, value) -> Field(key, value) } } .let { Passport(it) } } } fun solvePart1(): Int { return passports.count { it.hasAllMandatoryFields } } fun solvePart2(): Int { return passports.count { it.isValid } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,721
aoc
MIT License
src/main/kotlin/BeaconScanner_19.kt
Flame239
433,046,232
false
{"Kotlin": 64209}
import kotlin.math.abs val scanners: List<Scanner> by lazy { val lines = readFile("BeaconScanner").split("\n") val scanners = mutableListOf<Scanner>() var curLine = 1 var curScanerId = 0 var curBeacons = mutableListOf<V3>() var curScanner = Scanner(curScanerId, curBeacons) while (curLine < lines.size) { if (lines[curLine].isEmpty()) { scanners.add(curScanner) curScanerId++ curBeacons = mutableListOf() curScanner = Scanner(curScanerId, curBeacons) curLine++ } else { curBeacons.add(parseV3(lines[curLine])) } curLine++ } scanners.add(curScanner) scanners } fun main() { val mainScanner = scanners[0] val scannersLeft = scanners.toMutableList() val scannerTranslations = mutableListOf<V3>() scannersLeft.removeAt(0) while (scannersLeft.isNotEmpty()) { for (i in scannersLeft.indices) { val curTranslation = overlap(mainScanner, scannersLeft[i]) if (curTranslation != null) { scannerTranslations.add(curTranslation) scannersLeft.removeAt(i) break } } } println(mainScanner.beacons.size) val maxDist = scannerTranslations.maxOf { s1 -> scannerTranslations.maxOf { s2 -> s1.manhattanDistance(s2) } } println(maxDist) } fun overlap(s1: Scanner, s2: Scanner): V3? { val originBSet = s1.beacons.toHashSet() val s2rotations = getAllRotations(s2.beacons) for (originB in s1.beacons) { for (rotation in 0 until 24) { val curRotation: List<V3> = s2rotations[rotation] for (curB in curRotation) { val translation = V3(originB.x - curB.x, originB.y - curB.y, originB.z - curB.z) val curRotationTranslated = curRotation.map { it.translate(translation) } val overlap = curRotationTranslated.count { originBSet.contains(it) } if (overlap >= 12) { s1.beacons.addAll(curRotationTranslated.filter { !originBSet.contains(it) }) return translation } } } } return null } fun parseV3(s: String): V3 { val (x, y, z) = s.split(",").map { it.toInt() } return V3(x, y, z) } fun getAllRotations(beacons: List<V3>): List<List<V3>> { val allRotationsT = beacons.map { it.rotations() } val allRotations = mutableListOf<List<V3>>() for (rotation in 0 until 24) { allRotations.add(allRotationsT.map { it[rotation] }) } return allRotations } data class Scanner(val id: Int, val beacons: MutableList<V3>) data class V3(val x: Int, val y: Int, val z: Int) { override fun toString(): String { return "($x,$y,$z)" } fun manhattanDistance(other: V3) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) fun translate(translation: V3) = V3(x + translation.x, y + translation.y, z + translation.z) fun rotations(): List<V3> = listOf( V3(x, y, z), V3(-y, x, z), V3(-x, -y, z), V3(y, -x, z), V3(x, -y, -z), V3(y, x, -z), V3(-x, y, -z), V3(-y, -x, -z), V3(x, -z, y), V3(z, x, y), V3(-x, z, y), V3(-z, -x, y), V3(-y, -z, x), V3(z, -y, x), V3(y, z, x), V3(-z, y, x), V3(y, -z, -x), V3(z, y, -x), V3(-y, z, -x), V3(-z, -y, -x), V3(-x, -z, -y), V3(z, -x, -y), V3(x, z, -y), V3(-z, x, -y), ) }
0
Kotlin
0
0
ef4b05d39d70a204be2433d203e11c7ebed04cec
3,609
advent-of-code-2021
Apache License 2.0
src/Day01.kt
kmes055
577,555,032
false
{"Kotlin": 35314}
fun main() { fun List<String>.sumSplit(predicate: (String) -> Boolean): List<Int> { if (this.isEmpty()) return listOf() val left = this.takeWhile(predicate).sumOf { it.toInt() } val right = this.dropWhile(predicate).drop(1) return listOf(left) + right.sumSplit(predicate) } fun part1(input: List<String>): Int { return input.sumSplit { it.isNotBlank() } .sortedDescending()[0] } fun part2(input: List<String>): Int { return input.sumSplit { it.isNotBlank() } .sortedDescending() .subList(0, 3) .sum() } val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
84c2107fd70305353d953e9d8ba86a1a3d12fe49
718
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/aoc2020/day3/Forest.kt
arnab
75,525,311
false
null
package aoc2020.day3 object Forest { /** * Forest is organized as a 2D array where, Y -> 1st dim, X -> 2nd dim. * Each spot can be analyzed with [isOccupied] to see if there is a tree there. */ fun parse(data: String): List<List<Char>> = data.split("\n") .reversed() .map { it.toCharArray().toList() } fun walkAndCount(forest: List<List<Char>>, stepX: Int, stepY: Int) = walkAndCountRecursively( currentTreeCount = 0, currentX = 0, currentY = forest.size -1, stepX, stepY, forest ) private fun walkAndCountRecursively( currentTreeCount: Int, currentX: Int, currentY: Int, stepX: Int, stepY: Int, forest: List<List<Char>> ): Int { val nextGenForest = expandForestIfRequired(currentX, forest) val currentSpot = nextGenForest[currentY][currentX] val nextTreeCount = currentTreeCount + if (currentSpot.isOccupied()) 1 else 0 val nextX = currentX + stepX val nextY = currentY - stepY if (nextY < 0) { // we have passed through the end/bottom of the forest return nextTreeCount } return walkAndCountRecursively( currentTreeCount = nextTreeCount, currentX = nextX, currentY = nextY, stepX, stepY, nextGenForest ) } private fun Char.isOccupied() = this == '#' /** * Expand the forest, by duplicating it along the X-axis (the 2nd dim) for each Y (row), if we are out of the * currently known bounds of the forest (along the X-axis). */ private fun expandForestIfRequired(currentX: Int, forest: List<List<Char>>) = if (currentX < forest[0].size) { forest } else { forest.map { it + it } } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
1,891
adventofcode
MIT License
src/day01/Day01.kt
MaxBeauchemin
573,094,480
false
{"Kotlin": 60619}
package day01 import readInput fun main() { fun batchSumAndSort(input: List<String>): List<Int> { val batches = mutableListOf<List<String>>() val currList = mutableListOf<String>() input.forEach { entry -> if (entry == "") { batches.add(currList.toList()) currList.clear() } else { currList.add(entry) } } return batches.map { batch -> batch.sumOf { entry -> entry.toInt() } }.sortedByDescending { it } } fun part1(input: List<String>): Int { return batchSumAndSort(input).first() } fun part2(input: List<String>): Int { return batchSumAndSort(input).filterIndexed { index, _ -> index < 3 }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println(part1(testInput)) check(part1(testInput) == 24000) val input = readInput("day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
38018d252183bd6b64095a8c9f2920e900863a79
1,112
advent-of-code-2022
Apache License 2.0
src/Day04.kt
thelmstedt
572,818,960
false
{"Kotlin": 30245}
import java.io.File typealias Range = Pair<Int, Int> fun main() { fun range(l: String): Range { val (l1, l2) = l.split("-") return Pair(l1.toInt(), l2.toInt()) } fun fullyContains(r1: Range, r2: Range): Boolean { val rr1 = (r1.first..r1.second).toSet() val rr2 = (r2.first..r2.second).toSet() return rr1.minus(rr2).isEmpty() || rr2.minus(rr1).isEmpty() } fun overlap(r1: Range, r2: Range): Boolean { val rr1 = (r1.first..r1.second).toSet() val rr2 = (r2.first..r2.second).toSet() return rr1.intersect(rr2).isNotEmpty() } fun part1(file: File) = file .readText() .lineSequence() .filter { it.isNotBlank() } .filter { val (l, r) = it.split(",") fullyContains(range(l), range(r)) } .count() fun part2(file: File) = file .readText() .lineSequence() .filter { it.isNotBlank() } .filter { val (l, r) = it.split(",") overlap(range(l), range(r)) } .count() println(part1(File("src", "Day04_test.txt"))) println(part1(File("src", "Day04.txt"))) println(part2(File("src", "Day04_test.txt"))) println(part2(File("src", "Day04.txt"))) }
0
Kotlin
0
0
e98cd2054c1fe5891494d8a042cf5504014078d3
1,292
advent2022
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day22.kt
EmRe-One
433,772,813
false
{"Kotlin": 118159}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.automation.Day import tr.emreone.kotlin_utils.extensions.intersect import tr.emreone.kotlin_utils.extensions.intersects import tr.emreone.kotlin_utils.extensions.size class Day22 : Day(22, 2021, "Reactor Reboot") { private class Cuboid(val on: Boolean, val x: IntRange, val y: IntRange, val z: IntRange) { fun volume(): Long = (if (on) 1 else -1) * (x.size().toLong() * y.size().toLong() * z.size().toLong()) fun intersect(other: Cuboid): Cuboid? = if (!intersects(other)) null else Cuboid(!on, x intersect other.x, y intersect other.y, z intersect other.z) fun intersects(other: Cuboid): Boolean = x.intersects(other.x) && y.intersects(other.y) && z.intersects(other.z) companion object { const val ON = true const val OFF = false private val pattern = """^(on|off) x=(-?\d+)..(-?\d+),y=(-?\d+)..(-?\d+),z=(-?\d+)..(-?\d+)$""".toRegex() fun of(input: String): Cuboid { val (l, x1, x2, y1, y2, z1, z2) = pattern.matchEntire(input)?.destructured ?: error("Cannot parse input: $input") return Cuboid( l == "on", x1.toInt()..x2.toInt(), y1.toInt()..y2.toInt(), z1.toInt()..z2.toInt(), ) } } } private fun calcVolume(cuboids: List<Cuboid>): Long { val volumes = mutableListOf<Cuboid>() cuboids.forEach { cube -> volumes.addAll(volumes.mapNotNull { it.intersect(cube) }) if (cube.on) { volumes.add(cube) } } return volumes.sumOf { it.volume() } } override fun part1(): Int { val initCuboid = Cuboid(Cuboid.ON, -50..50, -50..50, -50..50) val lights = inputAsList .map { Cuboid.of(it) } .filter { it.intersects(initCuboid) } return calcVolume(lights).toInt() } override fun part2(): Long { val lights = inputAsList.map { Cuboid.of(it) } return calcVolume(lights) } }
0
Kotlin
0
0
516718bd31fbf00693752c1eabdfcf3fe2ce903c
2,293
advent-of-code-2021
Apache License 2.0
src/Day03.kt
daletools
573,114,602
false
{"Kotlin": 8945}
fun main() { fun part1(input: List<String>): Int { var score = 0 for (line in input) { val pockets = line.chunked(line.length / 2) for (char in pockets[0]) { if (pockets[1].contains(char)) { score += char.lowercaseChar() - '`' if (char.isUpperCase()) score += 26 break } } } return score } fun part2(input: List<String>): Int { var score = 0 val groups = input.chunked(3) for (group in groups) { for (char in group[0]) { if (group[1].contains(char) && group[2].contains(char)) { score += char.lowercaseChar() - '`' if (char.isUpperCase()) score += 26 break } } } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") println("Part 1 Test:") println(part1(testInput)) println("Part 2 Test:") println(part2(testInput)) val input = readInput("Day03") println("Part 1:") println(part1(input)) println("Part 2:") println(part2(input)) }
0
Kotlin
0
0
c955c5d0b5e19746e12fa6a569eb2b6c3bc4b355
1,286
adventOfCode2022
Apache License 2.0
src/day16/day.kt
LostMekka
574,697,945
false
{"Kotlin": 92218}
package day16 import util.extractStringGroups import util.readInput import util.shouldBe fun main() { val testInput = readInput(Input::class, testInput = true).parseInput() testInput.part1() shouldBe 1651 testInput.part2() shouldBe 1707 val input = readInput(Input::class).parseInput() println("output for part1: ${input.part1()}") println("output for part2: ${input.part2()}") } class Valve( val name: String, val rate: Int, connections: () -> Map<Valve, Int>, ) { val connections by lazy(connections) override fun equals(other: Any?) = this === other // instances are unique private val hash = name.hashCode() override fun hashCode() = hash } private val lineRegex = Regex("""^Valve (..) has flow rate=(\d+); tunnels? leads? to valves? (.+)$""") private class Input( val valves: Map<String, Valve>, ) { val start = valves.getValue("AA") } private fun List<String>.parseInput(): Input { val fullConnections = mutableMapOf<String, MutableMap<String, Int>>() val valves = mutableMapOf<String, Valve>() for (line in this) { val (name, rate, connections) = line.extractStringGroups(lineRegex) fullConnections[name] = connections .split(", ") .associateWith { 1 } .toMutableMap() .apply { put(name, 0) } valves[name] = Valve(name, rate.toInt()) { fullConnections.getValue(name).mapKeys { valves.getValue(it.key) } } } do { var done = true for ((_, targets) in fullConnections) { val newTargets = mutableMapOf<String, Int>() for ((target1, cost1) in targets) { for ((target2, cost2) in fullConnections.getValue(target1)) { if (target2 in targets) continue newTargets[target2] = cost1 + cost2 done = false } } targets += newTargets } } while (!done) return Input(valves) } private data class State( val time: Int = 1, val pressureReleased: Int = 0, val pressureRate: Int = 0, val interestingValves: Set<Valve>, val currIdle: List<Valve>, val currMoving: Map<Valve, Int> = emptyMap(), val currActivating: Set<Valve> = emptySet(), val lastState: State? = null, ) // wow, this turned out to be uglier than i thought :D // halfway through implementing this i realized there's a more efficient way of doing this, // but at that point i didn't want to start over again ^^ private fun State.search(maxTime: Int): State { if (time == maxTime) return this var bestResultState: State? = null fun callRecursive(newState: State) { val result = newState.search(maxTime) val best = bestResultState if (best == null || best.pressureReleased < result.pressureReleased) { bestResultState = result } } if (currIdle.isNotEmpty()) { for (source in currIdle) { var foundTarget = false for (target in interestingValves) { val walkCost = source.connections.getValue(target) if (time + walkCost >= maxTime) continue foundTarget = true callRecursive(copy( interestingValves = interestingValves - target, currIdle = currIdle - source, currMoving = currMoving + (target to time + walkCost), lastState = this, )) } if (!foundTarget) { callRecursive(copy( currIdle = currIdle - source, lastState = this, )) } } } else if (currActivating.isNotEmpty()) { val newPressureRate = pressureRate + currActivating.sumOf { it.rate } callRecursive(copy( time = time + 1, pressureReleased = pressureReleased + newPressureRate, pressureRate = newPressureRate, interestingValves = interestingValves - currActivating, currIdle = currIdle + currActivating, currActivating = emptySet(), lastState = this, )) } else if (currMoving.isNotEmpty()) { val arrivalTime = currMoving.minOf { it.value } val elapsedTime = arrivalTime - time val allTargets = currMoving.filter { it.value == arrivalTime }.keys callRecursive(copy( time = arrivalTime, pressureReleased = pressureReleased + elapsedTime * pressureRate, currMoving = currMoving - allTargets, currActivating = currActivating + allTargets, lastState = this, )) } return bestResultState ?: copy( time = maxTime, pressureReleased = pressureReleased + (maxTime - time) * pressureRate, lastState = this, ) } private fun printPlan(best: State) { val list = mutableListOf(best) while (true) list.last().lastState?.let { list += it } ?: break list.asReversed().forEach { state -> val idles = state.currIdle.joinToString { it.name } val activating = state.currActivating.joinToString { it.name } val moving = state.currMoving.entries.joinToString { it.key.name + "/" + it.value } println("${state.time} -- idle: $idles | activating: $activating | moving: $moving") } } private fun Input.part1(): Int { val start = State( currIdle = listOf(start), interestingValves = valves.values.filter { it.rate > 0 }.toSet() ) val best = start.search(30) printPlan(best) return best.pressureReleased } private fun Input.part2(): Int { val start = State( currIdle = listOf(start, start), interestingValves = valves.values.filter { it.rate > 0 }.toSet() ) val best = start.search(26) printPlan(best) return best.pressureReleased }
0
Kotlin
0
0
58d92387825cf6b3d6b7567a9e6578684963b578
5,944
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/TwoSum4.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 java.util.LinkedList import java.util.Queue /** * 653. Two Sum IV - Input is a BST * @see <a href="https://leetcode.com/problems/two-sum-iv-input-is-a-bst/">Source</a> */ fun interface TwoSum4 { operator fun invoke(root: TreeNode, k: Int): Boolean } /** * Approach #1 Using HashSet * Time complexity : O(n). * Space complexity : O(n). */ class TwoSum4HashSet : TwoSum4 { override fun invoke(root: TreeNode, k: Int): Boolean { val set: MutableSet<Int?> = HashSet() return find(root, k, set) } private fun find(root: TreeNode?, k: Int, set: MutableSet<Int?>): Boolean { if (root == null) return false if (set.contains(k - root.value)) return true set.add(root.value) return find(root.left, k, set) || find(root.right, k, set) } } /** * Approach #2 Using BFS and HashSet * Time complexity : O(n). * Space complexity : O(n). */ class TwoSum4BFS : TwoSum4 { override fun invoke(root: TreeNode, k: Int): Boolean { val set: MutableSet<Int?> = HashSet() val queue: Queue<TreeNode> = LinkedList() queue.add(root) while (queue.isNotEmpty()) { if (queue.peek() != null) { val node: TreeNode = queue.remove() if (set.contains(k - node.value)) return true set.add(node.value) queue.add(node.right) queue.add(node.left) } else { queue.remove() } } return false } } /** * Approach #3 Using BST * Time complexity : O(n). * Space complexity : O(n). */ class TwoSum4BST : TwoSum4 { override fun invoke(root: TreeNode, k: Int): Boolean { val list: MutableList<Int> = ArrayList() inorder(root, list) var l = 0 var r = list.size - 1 while (l < r) { val sum = list[l] + list[r] if (sum == k) return true if (sum < k) l++ else r-- } return false } private fun inorder(root: TreeNode?, list: MutableList<Int>) { if (root == null) return inorder(root.left, list) list.add(root.value) inorder(root.right, list) } } class TwoSum4DFS : TwoSum4 { override fun invoke(root: TreeNode, k: Int): Boolean { return dfs(root, root, k) } fun dfs(root: TreeNode?, cur: TreeNode?, k: Int): Boolean { return if (cur == null) { false } else { search(root, cur, k - cur.value) || dfs(root, cur.left, k) || dfs( root, cur.right, k, ) } } fun search(root: TreeNode?, cur: TreeNode, value: Int): Boolean { return if (root == null) { false } else { root.value == value && root != cur || root.value < value && search( root.right, cur, value, ) || root.value > value && search(root.left, cur, value) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,675
kotlab
Apache License 2.0
src/main/kotlin/com/colinodell/advent2023/Extensions.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 import kotlin.math.max import kotlin.math.min import kotlin.math.pow fun <T> Iterable<T>.chunkedBy(separator: (T) -> Boolean): List<List<T>> = fold(mutableListOf(mutableListOf<T>())) { acc, t -> if (separator(t)) { acc.add(mutableListOf()) } else { acc.last().add(t) } acc } fun <T> T?.default(default: T) = this ?: default fun <T> Iterable<T>.firstOr(default: T) = firstOrNull() ?: default /** * Counts through the first matching element. */ fun <T> Sequence<T>.countUntil(predicate: (T) -> Boolean): Int { var count = 0 for (t in this@countUntil) { count++ if (predicate(t)) { break } } return count } inline fun <T> Iterable<T>.productOf(predicate: (T) -> Long): Long = fold(1L) { acc, t -> acc * predicate(t) } fun Int.clamp(min: Int, max: Int) = maxOf(min, minOf(max, this)) fun Long.clamp(min: Long, max: Long) = maxOf(min, minOf(max, this)) fun Double.clamp(min: Double, max: Double) = maxOf(min, minOf(max, this)) fun Int.pow(n: Int) = toDouble().pow(n).toInt() fun Int.safeMod(other: Int) = ((this % other) + other) % other fun Long.gcd(other: Long): Long { var a = this var b = other while (b != 0L) { val temp = b b = a % b a = temp } return a } fun Long.lcm(other: Long) = (this * other) / gcd(other) fun Collection<Long>.lcm(): Long { return when (this.size) { 1 -> this.first() 2 -> this.first().lcm(this.last()) else -> this.first().lcm(this.drop(1).lcm()) } } operator fun LongRange.plus(offset: Long): LongRange { return (first + offset)..(last + offset) } fun <T : Comparable<T>> Iterable<T>.compareTo(other: Iterable<T>): Int { val otherI = other.iterator() for (e in this) { if (!otherI.hasNext()) { // other has run out of elements, so `this` is larger return 1 } val c = e.compareTo(otherI.next()) if (c != 0) { // found a position with a difference return c } } if (otherI.hasNext()) { // `this` has run out of elements, but other has some more, so other is larger return -1 } // they're the same return 0 } fun <T> List<T>.asRepeatedSequence() = generateSequence(0) { (it + 1) % this.size }.map(::get) val IntRange.size get() = endInclusive - start + 1 /** * Returns a new list with the ranges condensed into the smallest possible set of ranges. * * For example, given the ranges [4..6, 1..3, 7..9], this will return [1..9]. */ fun Iterable<IntRange>.simplify(): List<IntRange> { val sortedRanges = sortedBy { it.first } val nonOverlappingRanges = mutableListOf<IntRange>() for (range in sortedRanges) { if (nonOverlappingRanges.isEmpty()) { nonOverlappingRanges.add(range) } else { val lastRange = nonOverlappingRanges.last() if (lastRange.last >= range.first) { nonOverlappingRanges[nonOverlappingRanges.lastIndex] = lastRange.first..max(lastRange.last, range.last) } else { nonOverlappingRanges.add(range) } } } return nonOverlappingRanges } fun Iterable<IntRange>.intersect(range: IntRange): Collection<IntRange> { return buildList { for (r in this@intersect) { if (r.first >= range.last || r.last <= range.first) { continue } else { add(max(r.first, range.first)..min(r.last, range.last)) } } } } fun Iterable<IntRange>.subtract(range: IntRange): Collection<IntRange> { return buildList { for (r in this@subtract) { if (r.first > range.last || r.last < range.first) { add(r) } else { if (r.first < range.first) { add(r.first until range.first) } if (r.last > range.last) { add(range.last + 1 until r.last + 1) } } } } } fun <T> Collection<T>.permutations() = buildList<Pair<T, T>> { val p = this@permutations for (i in p.indices) { for (j in i + 1 until p.size) { add(p.elementAt(i) to p.elementAt(j)) } } }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
4,373
advent-2023
MIT License
src/day10/Day10.kt
robin-schoch
572,718,550
false
{"Kotlin": 26220}
package day10 import AdventOfCodeSolution fun main() { Day10.run() } object Day10 : AdventOfCodeSolution<Int, Unit> { override val testSolution1 = 13140 override val testSolution2 = Unit private operator fun String.component1() = split(" ")[0] private operator fun String.component2() = split(" ").let { if (it.size == 2) it[1].toInt() else 0 } private infix fun Pair<Int, Int>.execute(instruction: String): List<Pair<Int, Int>> { val (instructionType, value) = instruction return when (instructionType) { "noop" -> listOf(first + 1 to second) "addx" -> listOf(first + 1 to second, first + 2 to second + value) else -> error("illegal instruction") } } private fun buildInstructionSequen(input: List<String>) = sequence { var lastInstruction = Pair(1, 1).also { yield(it) } for (instruction in input) (lastInstruction execute instruction).let { lastInstruction = it.last() it.forEach { state -> yield(state) } } } override fun part1(input: List<String>): Int { return buildInstructionSequen(input) .filter { it.first % 40 == 20 } .sumOf { it.first * it.second } } @OptIn(ExperimentalStdlibApi::class) override fun part2(input: List<String>) { buildInstructionSequen(input) .take(240) .chunked(40) { val line = IntArray(40) for (i in 0..<40) { when (i) {in it[i].second - 1..it[i].second + 1 -> line[i] = 1 } } line.joinToString(separator = "") { lit -> if (lit == 0) "." else "#" } }.forEach { println(it) } repeat(40) { print("-") } println() } }
0
Kotlin
0
0
fa993787cbeee21ab103d2ce7a02033561e3fac3
1,797
aoc-2022
Apache License 2.0
src/main/kotlin/Day6.kt
ivan-gusiev
726,608,707
false
{"Kotlin": 34715, "Python": 2022, "Makefile": 50}
import util.AocDay import util.AocInput import java.math.BigInteger typealias Day6InputType = List<String>; class Day6 : Runner { var TEST_INPUT = """ Time: 7 15 30 Distance: 9 40 200 """.trimIndent() data class TimeDistance(val time: BigInteger, val distance: BigInteger) { companion object { fun parsePart1(input: List<String>): List<TimeDistance> { val lists = input.map { s -> s.replace("Time:", "") .replace("Distance:", "") .trim() }.map { s -> s.split(Regex("\\s+")).map(String::toBigInteger) } return lists[0].zip(lists[1]).map { (time, distance) -> TimeDistance(time, distance) } } fun parsePart2(input: List<String>): TimeDistance { val lists = input.map { s -> s.replace("Time:", "") .replace("Distance:", "") .trim() }.map { s -> s.replace(Regex("\\s+"), "").toBigInteger() } return TimeDistance(lists[0], lists[1]) } } } override fun run() { val day = AocDay("2023".toInt(), "6".toInt()) val lines = AocInput.lines(day) //val lines = TEST_INPUT.split("\n") part1(lines) part2(lines) } private fun part1(lines: Day6InputType) { val input = TimeDistance.parsePart1(lines) var result = 1 for (record in input) { val winnerCount = winnerCount(record) println("$record -> $winnerCount") result *= winnerCount } println(result) } private fun part2(lines: Day6InputType) { val input = TimeDistance.parsePart2(lines) println(winnerCount(input)) } private fun winnerCount(record: TimeDistance): Int { val range = sequence<BigInteger> { var cur = BigInteger.ZERO while (cur < record.time) { yield(cur) cur += BigInteger.ONE } } return range.map { time: BigInteger -> TimeDistance(time, travelDistance(time, record.time)) } .count { it.distance > record.distance } } private fun travelDistance(startupMs: BigInteger, totalMs: BigInteger): BigInteger { val travelMs = totalMs - startupMs val result = startupMs * travelMs return if (result < BigInteger.ZERO) { BigInteger.ZERO } else { result } } }
0
Kotlin
0
0
5585816b435b42b4e7c77ce9c8cabc544b2ada18
2,696
advent-of-code-2023
MIT License
lab10/src/main/kotlin/cs/put/pmds/lab10/MinHash.kt
Azbesciak
153,350,976
false
null
package cs.put.pmds.lab10 import java.util.Random import kotlin.math.min data class HashFunction(val a: Long, val b: Long, val mod: Int = LARGE_PRIME) { companion object { private const val LARGE_PRIME = 1299827 infix fun create(r: Random) = HashFunction(nextVal(r), nextVal(r)) private fun nextVal(r: Random) = (r.nextInt(LARGE_PRIME - 1) + 1).toLong() } operator fun get(x: Int) = ((a * x.toLong() + b) % mod).toInt() } class MinHash(private val hashFunctions: List<HashFunction>) { init { require(hashFunctions.isNotEmpty()) {"expected at least one hash function"} } constructor(n: Int, random: Random = Random()): this((0 until n).map { HashFunction create random }) { require(n > 0) { "Signature size should be positive" } } fun signature(values: IntArray): IntArray { val sig = IntArray(hashFunctions.size) { Int.MAX_VALUE } values.forEach { value -> sig.forEachIndexed { si, sval -> sig[si] = min(sval, hashFunctions[si][value]) } } return sig } companion object { /** * Computes an estimation of Jaccard similarity (the number of elements in * common) between two sets, using the MinHash signatures of these two sets. * * @param sig1 MinHash signature of set1 * @param sig2 MinHash signature of set2 (produced using the same * hashFunctions) * @return the estimated similarity */ fun similarity(sig1: IntArray, sig2: IntArray): Double { require(sig1.size == sig2.size) { "Size of signatures should be the same" } var sim = 0.0 for (i in sig1.indices) { if (sig1[i] == sig2[i]) { sim += 1.0 } } return sim / sig1.size } } }
0
Kotlin
0
0
f1d3cf4d51ad6588e39583f7b958c92b619799f8
1,902
BigDataLabs
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/SumOfDistancesInTree.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 /** * 834. Sum of Distances in Tree * @see <a href="https://leetcode.com/problems/sum-of-distances-in-tree">Source</a> */ class SumOfDistancesInTree { private lateinit var ans: IntArray private lateinit var count: IntArray private var graph: MutableList<MutableSet<Int>> = ArrayList() private var n = 0 operator fun invoke(n: Int, edges: Array<IntArray>): IntArray { this.n = n ans = IntArray(n) count = IntArray(n) { 1 } for (i in 0 until n) { graph.add(HashSet()) } for (edge in edges) { graph[edge[0]].add(edge[1]) graph[edge[1]].add(edge[0]) } dfs(0, -1) dfs2(0, -1) return ans } private fun dfs(node: Int, parent: Int) { for (child in graph[node]) if (child != parent) { dfs(child, node) count[node] += count[child] ans[node] += ans[child] + count[child] } } private fun dfs2(node: Int, parent: Int) { for (child in graph[node]) if (child != parent) { ans[child] = ans[node] - count[child] + n - count[child] dfs2(child, node) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,836
kotlab
Apache License 2.0
src/main/kotlin/com/rtarita/days/Day9.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.sign import kotlinx.datetime.LocalDate import kotlin.math.abs import kotlin.math.max object Day9 : AoCDay { private data class Coord(val x: Int, val y: Int) override val day: LocalDate = day(9) private fun getMovements(input: String): Sequence<Pair<Char, Int>> { return input.lineSequence() .map { it.split(' ') } .map { (c, i) -> c.first() to i.toInt() } } private fun calculateHeadMovement(hpos: Coord, dir: Char): Coord { return when (dir) { 'L' -> Coord(hpos.x - 1, hpos.y) 'U' -> Coord(hpos.x, hpos.y - 1) 'R' -> Coord(hpos.x + 1, hpos.y) 'D' -> Coord(hpos.x, hpos.y + 1) else -> error("unknown direction: $dir") } } private fun calculateTailMovement(tpos: Coord, hpos: Coord): Coord { val xdelta = hpos.x - tpos.x val ydelta = hpos.y - tpos.y return when { abs(xdelta) > 1 && abs(ydelta) > 1 -> Coord( tpos.x + sign(xdelta) * max(0, abs(xdelta) - 1), tpos.y + sign(ydelta) * max(0, abs(ydelta) - 1) ) abs(xdelta) > 1 -> Coord( tpos.x + sign(xdelta) * max(0, abs(xdelta) - 1), tpos.y + ydelta ) abs(ydelta) > 1 -> Coord( tpos.x + xdelta, tpos.y + sign(ydelta) * max(0, abs(ydelta) - 1) ) abs(xdelta) <= 1 && abs(ydelta) <= 1 -> tpos else -> error("invalid game state, tpos($tpos), hpos($hpos)") } } override fun executePart1(input: String): Int { val visited = mutableSetOf<Coord>() getMovements(input) .fold(Pair(Coord(0, 0), Coord(0, 0))) { (hpos, tpos), (dir, dist) -> visited += tpos var currentH = hpos var currentT = tpos repeat(dist) { currentH = calculateHeadMovement(currentH, dir) currentT = calculateTailMovement(currentT, currentH) visited += currentT } currentH to currentT } return visited.size } override fun executePart2(input: String): Any { val visited = mutableSetOf<Coord>() getMovements(input) .fold(List(10) { Coord(0, 0) }) { knotPositions, (dir, dist) -> visited += knotPositions.last() val newKnots = knotPositions.toMutableList() repeat(dist) { newKnots[0] = calculateHeadMovement(newKnots[0], dir) for (i in 1..knotPositions.lastIndex) { newKnots[i] = calculateTailMovement(newKnots[i], newKnots[i - 1]) } visited += newKnots.last() } newKnots } return visited.size } }
0
Kotlin
0
9
491923041fc7051f289775ac62ceadf50e2f0fbe
3,073
AoC-2022
Apache License 2.0
app/src/main/kotlin/io/github/andrewfitzy/day04/Task01.kt
andrewfitzy
747,793,365
false
{"Kotlin": 60159, "Shell": 1211}
package io.github.andrewfitzy.day04 class Task01(puzzleInput: List<String>) { private val input: List<String> = puzzleInput fun solve(): Int { var checksumTotal = 0 for (entry in input) { val splits = entry.split("-") val name = splits.subList(0, splits.size - 1).joinToString(separator = "") val lastItem = splits[splits.size - 1] val sectorId = lastItem.substring(0, lastItem.indexOf("[")).toInt() val checksum = lastItem.substring(lastItem.indexOf("[") + 1, lastItem.indexOf("]")) if (isValidInput(name, checksum)) { println(name) checksumTotal += sectorId } } return checksumTotal } private fun isValidInput( name: String, checksum: String, ): Boolean { val charCount = name.groupingBy { it }.eachCount() val entries = ArrayList(charCount.entries) val sortedList = entries.sortedWith { a, b -> when { a.value < b.value -> 1 a.value > b.value -> -1 a.value == b.value && a.key > b.key -> 1 a.value == b.value && a.key < b.key -> -1 else -> 0 } } return checksum == sortedList.subList(0, checksum.length).joinToString(separator = "") { it.key.toString() } } }
0
Kotlin
0
0
15ac072a14b83666da095b9ed66da2fd912f5e65
1,443
2016-advent-of-code
Creative Commons Zero v1.0 Universal
year2023/src/main/kotlin/net/olegg/aoc/year2023/day16/Day16.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2023.day16 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions import net.olegg.aoc.utils.Directions.D import net.olegg.aoc.utils.Directions.L import net.olegg.aoc.utils.Directions.R import net.olegg.aoc.utils.Directions.U import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.fit import net.olegg.aoc.utils.get import net.olegg.aoc.utils.set import net.olegg.aoc.year2023.DayOf2023 /** * See [Year 2023, Day 16](https://adventofcode.com/2023/day/16) */ object Day16 : DayOf2023(16) { override fun first(): Any? { return countEnergy(Vector2D(), R) } override fun second(): Any? { return buildList { addAll(List(matrix.size) { Vector2D(0, it) to R }) addAll(List(matrix.size) { Vector2D(matrix.first().lastIndex, it) to L }) addAll(List(matrix.first().size) { Vector2D(it, 0) to D }) addAll(List(matrix.last().size) { Vector2D(it, matrix.lastIndex) to U }) }.maxOf { countEnergy(it.first, it.second) } } private fun countEnergy( start: Vector2D, direction: Directions ): Int { val energized = matrix.map { it.map { 0 }.toMutableList() } val queue = ArrayDeque(listOf(start to direction)) val seen = mutableSetOf<Pair<Vector2D, Directions>>() while (queue.isNotEmpty()) { val curr = queue.removeFirst() if (curr in seen) continue seen += curr val (pos, dir) = curr if (!energized.fit(pos)) continue energized[pos] = 1 when (matrix[pos]) { '.' -> queue.add(pos + dir.step to dir) '|' -> when (dir) { L, R -> { queue.add(pos + U.step to U) queue.add(pos + D.step to D) } U, D -> queue.add(pos + dir.step to dir) else -> Unit } '-' -> when (dir) { U, D -> { queue.add(pos + L.step to L) queue.add(pos + R.step to R) } L, R -> queue.add(pos + dir.step to dir) else -> Unit } '/' -> when (dir) { L -> queue.add(pos + D.step to D) R -> queue.add(pos + U.step to U) D -> queue.add(pos + L.step to L) U -> queue.add(pos + R.step to R) else -> Unit } '\\' -> when (dir) { L -> queue.add(pos + U.step to U) R -> queue.add(pos + D.step to D) D -> queue.add(pos + R.step to R) U -> queue.add(pos + L.step to L) else -> Unit } } } return energized.sumOf { it.sum() } } } fun main() = SomeDay.mainify(Day16)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,591
adventofcode
MIT License
src/Day02.kt
matheusfinatti
572,935,471
false
{"Kotlin": 12612}
import kotlin.math.abs fun main() { val input = readInput("Day02").trim().split("\n") input .map { round -> round.split(" ").map(String::single) } .map { round -> listOf(round[0] - 'A', round[1] - 'X') } .also { game -> game.sumOf { round -> val (p1, p2) = round listOf( when { (p1 + 1) % 3 == p2 -> 6 p1 == p2 -> 3 else -> 0 }, p2 + 1, ).sum() }.also(::println) } .also { game -> game.sumOf { round -> val (p1, p2) = round // 1, 2, 3 // p1=1, p2=1 -> 3 // p1=1, p2=2 -> 1 // p1=1, p2=3 -> 2 // -- // p1=2, p2=1 -> 1 // p1=2, p2=2 -> 2 // p1=2, p2=3 -> 3 // -- // p1=3, p2=1 -> 2 // p1=3, p2=2 -> 3 // p1=3, p2=3 -> 1 listOf( when (p1) { 0 -> when (p2) { 0 -> 3 1 -> 1 else -> 2 } 1 -> when (p2) { 0 -> 1 1 -> 2 else -> 3 } else -> when (p2) { 0 -> 2 1 -> 3 else -> 1 } }, p2 * 3, ).sum() }.also(::println) } }
0
Kotlin
0
0
a914994a19261d1d81c80e0ef8e196422e3cd508
1,794
adventofcode2022
Apache License 2.0
logicsolver/src/main/kotlin/nl/hiddewieringa/logicsolver/Strategy.kt
hiddewie
147,922,971
false
null
package nl.hiddewieringa.logicsolver /** * A conclusion is either a found value, or a value which is not allowed somewhere */ typealias Conclusion = OneOf<Value, NotAllowed> fun concludeNotAllowed(coordinate: Coordinate, value: Int): Conclusion { return OneOf.right(NotAllowed(coordinate, value)) } fun <T> Collection<T>.concludeNotAllowed(coordinate: (T) -> Coordinate, value: (T) -> Int): List<Conclusion> { return map { concludeNotAllowed(coordinate(it), value(it)) } } fun concludeValue(coordinate: Coordinate, value: Int): Conclusion { return OneOf.left(Value(coordinate, value)) } /** * A strategy takes some input and generates a set of conclusions */ typealias Strategy<I, C> = (I) -> Set<C> /** * The value in a sudoku cell */ data class Value(val coordinate: Coordinate, val value: Int) /** * A value which is not allowed in a sudoku cell */ data class NotAllowed(val coordinate: Coordinate, val value: Int) /** * A group transforms the working puzzle data into a working list of data */ typealias Group<M, T> = (M) -> Set<T> typealias SudokuGroup = Group<Map<Coordinate, SudokuSolveData>, SudokuSolveData> typealias GroupsWithData = Triple<Set<SudokuGroup>, Map<Coordinate, SudokuSolveData>, Set<Int>> typealias DataWithValues = Pair<Set<SudokuSolveData>, Set<Int>> fun Collection<SudokuSolveData>.coordinates(): List<Coordinate> { return map { it.coordinate } } fun <T> List<Coordinate>.toValues(data: Map<Coordinate, T>): List<T> { return map { data[it]!! } } fun Collection<SudokuSolveData>.ignoreCoordinates(coordinates: Set<Coordinate>, data: Map<Coordinate, SudokuSolveData>): List<SudokuSolveData> { return (coordinates() - coordinates).toValues(data) } /** * Finds the missing value if all but one value is filled in the group */ class MissingValueGroupStrategy : Strategy<DataWithValues, Conclusion> { override fun invoke(dataWithValues: DataWithValues): Set<Conclusion> { val (data, values) = dataWithValues val m = values.map { i -> i to data.find { it.value == i } }.toMap() return if (values.filter { m[it] == null }.size == 1) { val coordinate = data.find { it.value == null }!!.coordinate val value = values.find { m[it] == null }!! setOf(concludeValue(coordinate, value)) } else { setOf() } } } /** * If a value is given in a cell, than all other cells in the group are not allowed to contain that value */ class FilledValueNotAllowedInGroupStrategy : Strategy<DataWithValues, Conclusion> { override fun invoke(dataWithValues: DataWithValues): Set<Conclusion> { val (data, _) = dataWithValues return data.filter(SudokuSolveData::hasValue) .flatMap { hasValue -> data.filter { hasValue.coordinate != it.coordinate && !it.notAllowed.contains(hasValue.value!!) }.concludeNotAllowed({ it.coordinate }, { hasValue.value!! }) }.toSet() } } /** * If all but one value is not allowed in a cell, then that value must be true */ class SingleValueAllowedStrategy : Strategy<DataWithValues, Conclusion> { override fun invoke(dataWithValues: DataWithValues): Set<Conclusion> { val (data, values) = dataWithValues return data.filter(SudokuSolveData::isEmpty) .flatMap { solveData -> val m = values.map { i -> i to solveData.notAllowed.contains(i) }.toMap() if (m.values.filter { !it }.size == 1) { val value = m.filterValues { !it }.keys.first() setOf(concludeValue(solveData.coordinate, value)) } else { setOf() } }.toSet() } } /** * If a value is given in a cell, then all other values are not allowed in that cell */ class FilledValueRestNotAllowedStrategy : Strategy<DataWithValues, Conclusion> { override fun invoke(dataWithValues: DataWithValues): Set<Conclusion> { val (data, values) = dataWithValues return data.filter(SudokuSolveData::hasValue) .flatMap { hasValue -> val missingNotAllowed = values - setOf(hasValue.value!!) - hasValue.notAllowed missingNotAllowed.concludeNotAllowed({ hasValue.coordinate }, { it }) }.toSet() } } /** * If a value is given in a cell, then all other values are not allowed in that cell */ class TwoNumbersTakeTwoPlacesStrategy : Strategy<DataWithValues, Conclusion> { override fun invoke(dataWithValues: DataWithValues): Set<Conclusion> { val (data, values) = dataWithValues return values.flatMap { a -> values.filter { b -> a != b }.flatMap { b -> twoNumbers(data, a, b, values) } }.toSet() } private fun twoNumbers(data: Set<SudokuSolveData>, a: Int, b: Int, values: Set<Int>): List<Conclusion> { val allowedA = data.whereValueIsAllowed(a) val allowedB = data.whereValueIsAllowed(b) if (allowedA.size != 2 || allowedB.size != 2 || allowedA != allowedB) { return listOf() } return allowedA.findByCoordinate(data) .flatMap { solveData -> (values - solveData.notAllowed - listOf(a, b)) .concludeNotAllowed({ solveData.coordinate }, { it }) } } private fun Collection<SudokuSolveData>.whereValueIsAllowed(value: Int): Set<Coordinate> { return filter { !it.notAllowed.contains(value) }.coordinates().toSet() } private fun Set<Coordinate>.findByCoordinate(data: Collection<SudokuSolveData>): List<SudokuSolveData> { return map { coordinate -> data.find { it.coordinate == coordinate }!! } } } /** * If two numbers are only allowed in exactly two places, they are not allowed in any other places. */ class TwoNumbersOnlyInTwoPlacesStrategy : Strategy<DataWithValues, Conclusion> { override fun invoke(dataWithValues: DataWithValues): Set<Conclusion> { val (data, values) = dataWithValues val twoAllowed = data.filter { it.notAllowed.size == values.size - 2 } return twoAllowed.flatMap { a -> twoAllowed.filter { b -> a.coordinate != b.coordinate }.filter { b -> a.notAllowed.toSet() == b.notAllowed.toSet() }.flatMap { b -> conclusionsForTwoPlaces(data, a, b, values) } }.toSet() } private fun conclusionsForTwoPlaces(data: Set<SudokuSolveData>, a: SudokuSolveData, b: SudokuSolveData, values: Set<Int>): List<Conclusion> { val allowed = values.toList() - a.notAllowed return allowed.flatMap { allowedValue -> data.filter { !it.notAllowed.contains(allowedValue) } .filter { it.coordinate != a.coordinate && it.coordinate != b.coordinate } .concludeNotAllowed({ it.coordinate }, { allowedValue }) } } } class OverlappingGroupsStrategy : Strategy<GroupsWithData, Conclusion> { override fun invoke(groupsWithData: GroupsWithData): Set<Conclusion> { val (groups, data, values) = groupsWithData val evaluatedGroups = groups.map { it(data) } return evaluatedGroups.flatMap { group1 -> (evaluatedGroups - setOf(group1)).flatMap { group2 -> overlappingConclusionsForGroups(group1, group2, data, values) } }.toSet() } fun overlappingConclusionsForGroups(group1: Set<SudokuSolveData>, group2: Set<SudokuSolveData>, data: Map<Coordinate, SudokuSolveData>, values: Set<Int>): Set<Conclusion> { val overlappingCoordinates = group1.coordinates().intersect(group2.coordinates()) if (overlappingCoordinates.size < 2) { return setOf() } if (overlappingCoordinates.all { data[it]!!.hasValue() }) { return setOf() } return values.flatMap { i -> overlappingConclusionsForGroupsAndValue( group1.ignoreCoordinates(overlappingCoordinates, data), group2.ignoreCoordinates(overlappingCoordinates, data), i ) }.toSet() } private fun overlappingConclusionsForGroupsAndValue(group1Other: List<SudokuSolveData>, group2Other: List<SudokuSolveData>, value: Int): List<Conclusion> { return if (group1Other.all { it.isNotAllowed(value) }) { group2Other.filter { it.isEmpty() && it.isAllowed(value) }.concludeNotAllowed({ it.coordinate }, { value }) } else { listOf() } } } /** * The group strategy gathers conclusions about cells in a group */ class GroupStrategy : Strategy<DataWithValues, Conclusion> { /** * The substrategies that are used */ private val strategies: Set<Strategy<DataWithValues, Conclusion>> = setOf( MissingValueGroupStrategy(), FilledValueNotAllowedInGroupStrategy(), SingleValueAllowedStrategy(), FilledValueRestNotAllowedStrategy(), TwoNumbersTakeTwoPlacesStrategy(), TwoNumbersOnlyInTwoPlacesStrategy() ) /** * Gathers all conclusions from the substrategies */ override fun invoke(data: DataWithValues): Set<OneOf<Value, NotAllowed>> { return strategies.flatMap { strategy -> strategy(data) }.toSet() } }
0
Kotlin
0
0
bcf12c102f4ab77c5aa380dbf7c98a1cc3e585c0
10,128
LogicSolver
MIT License
day_07/src/main/kotlin/io/github/zebalu/advent2020/BagRuleReader.kt
zebalu
317,448,231
false
null
package io.github.zebalu.advent2020 typealias Rules = Map<String, Set<Pair<Int, String>>> object BagRuleReader { fun readRules(lines: List<String>): Rules { val result = mutableMapOf<String, MutableSet<Pair<Int, String>>>() lines.forEach { line -> val parts = line.split(" bags contain ") val type = parts[0] parts[1].split(", ").map { s -> s.split(" bag")[0] }.forEach { bag -> val split = bag.split(" ") if (split.size != 2 && split.size != 3) { throw IllegalStateException("split is not 2 or 3 long: " + split) } val count = if ("no".equals(split[0])) 0 else split[0].toInt() val bagName = if (count == 0) "no other" else split[1] + " " + split[2] result.computeIfAbsent(type, { _ -> mutableSetOf<Pair<Int, String>>() }).add(Pair(count, bagName)) } } return result } fun countWaysToShinyGold(rules: Map<String, Set<Pair<Int, String>>>) = rules.keys.count { name -> (!("shiny gold".equals(name))) && isThereWayToShinyGold( name, rules, setOf(name) ) } fun countContentInShinyGold(rules: Rules) = countContent("shiny gold", rules) private fun countContent(name: String, rules: Rules): Int { return rules.get(name)?.map { pair -> pair.first + pair.first * countContent(pair.second, rules) }?.sum() ?: 0 } private fun isThereWayToShinyGold(name: String, rules: Rules, visited: Set<String>): Boolean { if ("shiny gold".equals(name)) { return true } val col = rules.get(name)?.map { pair -> if (pair.first == 0) false else if ("shiny gold".equals(pair.second)) true else if (visited.contains(pair.second)) false else isThereWayToShinyGold( pair.second, rules, visited + pair.second ) } return if (col == null || col.isEmpty()) false else col.reduce { acc, next -> acc || next } } }
0
Kotlin
0
1
ca54c64a07755ba044440832ba4abaa7105cdd6e
1,813
advent2020
Apache License 2.0
src/Day02.kt
derkalaender
433,927,806
false
{"Kotlin": 4155}
fun main() { class Values(var x: Int, var y: Int, var aim: Int) fun part1(input: List<String>): Int { return input .map { l -> l.split(' ').let { Pair(it[0], it[1].toInt()) } } .fold(Values(0, 0, 0)) { acc, cmd -> when (cmd.first) { "forward" -> acc.apply { x += cmd.second } "down" -> acc.apply { y += cmd.second } "up" -> acc.apply { y -= cmd.second } else -> error("Command not recognized") } } .run { x * y } } fun part2(input: List<String>): Int { return input .map { l -> l.split(' ').let { Pair(it[0], it[1].toInt()) } } .fold(Values(0, 0, 0)) { acc, cmd -> when (cmd.first) { "forward" -> acc.apply { x += cmd.second y += aim * cmd.second } "down" -> acc.apply { aim += cmd.second } "up" -> acc.apply { aim -= cmd.second } else -> error("Command not recognized") } } .run { x * y } } readInput("Day02").let { println("Answer 1: ${part1(it)}") println("Answer 2: ${part2(it)}") } }
0
Kotlin
0
0
bf258ea0cf7cada31288a91d2204d5c7b3492433
1,437
aoc2021
The Unlicense
src/main/kotlin/ProblemSolution.kt
YaroslavGamayunov
299,554,569
false
null
import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.math.min /** * The problem: * Given a regex in Reverse Polish Notation and numbers k and l satisfying the property: 0 <= l < k * The task is to find minimal n which equals to l modulo k * such that language of regex contains n-character long words */ fun solveProblem(regex: String, k: Int, l: Int): Int { val machine = FiniteStateMachine.buildFromRegex(regex.byteInputStream()) val dp = HashMap<FiniteStateMachine.State, ArrayList<TreeSet<Int>>>() for (state in machine.states) { fillDpCell(dp, state, k) } dp[machine.startState]!![0].add(0) for (i in 0..(machine.states.size * k)) { for (state in machine.states) { if (dp[state]!![i % k].contains(i)) { for ((_, nextState) in state.transitions) { dp[nextState]!![(i + 1) % k].add(i + 1) } } } } var minimalAnswer = Int.MAX_VALUE for (state in machine.finalStates) { if (!state.type.contains(FiniteStateMachine.StateType.FINAL)) { continue } dp[state]!![l].min()?.let { minimalAnswer = min(minimalAnswer, it) } } return minimalAnswer } fun fillDpCell( dp: HashMap<FiniteStateMachine.State, ArrayList<TreeSet<Int>>>, state: FiniteStateMachine.State, k: Int ) { dp[state] = ArrayList(k) for (i in 1..k) { dp[state]!!.add(TreeSet()) } }
0
Kotlin
0
0
8fb282f5be75fc8b7e0ff999fcd9e419860aea15
1,535
FiniteStateMachine
MIT License
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/longs.kt
dave08
371,333,515
true
{"Kotlin": 2920151, "CSS": 352, "Java": 145}
package io.kotest.property.arbitrary import io.kotest.property.Arb import io.kotest.property.Shrinker import kotlin.math.abs import kotlin.random.nextLong import kotlin.random.nextULong /** * Returns an [Arb] that produces [Long]s, where the edge cases are [min], -1, 0, 1 and [max]. * -1, 0 and 1 will only be included if they are within the specified min and max bounds. */ fun Arb.Companion.long(min: Long = Long.MIN_VALUE, max: Long = Long.MAX_VALUE) = long(min..max) /** * Returns an [Arb] that produces [Long]s, where the edge cases are [IntRange.first], -1, 0, 1 and [IntRange.last]. * -1, 0 and 1 will only be included if they are within the specified min and max bounds. */ fun Arb.Companion.long(range: LongRange = Long.MIN_VALUE..Long.MAX_VALUE): Arb<Long> { val edgecases = longArrayOf(range.first, -1, 0, 1, range.last).filter { it in range }.distinct() return arbitrary(edgecases, LongShrinker(range)) { it.random.nextLong(range) } } class LongShrinker(private val range: LongRange) : Shrinker<Long> { override fun shrink(value: Long): List<Long> = when (value) { 0L -> emptyList() 1L, -1L -> listOf(0L).filter { it in range } else -> { val a = listOf(0, 1, -1, abs(value), value / 3, value / 2, value * 2 / 3) val b = (1..5).map { value - it }.reversed().filter { it > 0 } (a + b).distinct() .filterNot { it == value } .filter { it in range } } } } /** * Returns an [Arb] that produces [Long]s, where the edge cases are [min], 1 and [max]. * 1 will only be included if they are within the specified min and max bounds. */ fun Arb.Companion.ulong(min: ULong = ULong.MIN_VALUE, max: ULong = ULong.MAX_VALUE) = ulong(min..max) /** * Returns an [Arb] that produces [Long]s, where the edge cases are [IntRange.first], 1 and [IntRange.last]. * 1 will only be included if they are within the specified min and max bounds. */ fun Arb.Companion.ulong(range: ULongRange = ULong.MIN_VALUE..ULong.MAX_VALUE): Arb<ULong> { val edgecases = listOf(range.first, 1uL, range.last).filter { it in range }.distinct() return arbitrary(edgecases, ULongShrinker(range)) { it.random.nextULong(range) } } class ULongShrinker(val range: ULongRange) : Shrinker<ULong> { override fun shrink(value: ULong): List<ULong> = when (value) { 0uL -> emptyList() 1uL -> listOf(0uL).filter { it in range } else -> { val a = listOf(0uL, 1uL, value / 3u, value / 2u, value * 2u / 3u) val b = (1u..5u).map { value - it }.reversed().filter { it > 0u } (a + b).distinct() .filterNot { it == value } .filter { it in range } } } }
0
Kotlin
0
0
77ce26af5690956fc29b8adf4ff14abbdda188ec
2,766
kotest
Apache License 2.0
kotlin/1968-array-with-elements-not-equal-to-average-of-neighbors.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
/* * O(nlogn) solution (similar to wiggle sort) */ class Solution { fun rearrangeArray(nums: IntArray): IntArray { nums.sort() val res = IntArray(nums.size) var i = 0 var left = 0 var right = nums.lastIndex while (i < res.size) { res[i++] = nums[left++] if (left <= right) res[i++] = nums[right--] } return res } } /* * O(n) solution, check for any increasing/decreasing subarrays at i - i to i + 1, if found i with i + 1 to remove the increasing/decreasing subarray */ class Solution { fun rearrangeArray(nums: IntArray): IntArray { for (i in 1 until nums.lastIndex) { if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1] || nums[i - 1] > nums[i] && nums[i] > nums[i + 1]) nums[i] = nums[i + 1].also { nums[i + 1] = nums[i] } } return nums } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
938
leetcode
MIT License
advent-of-code2015/src/main/kotlin/day16/Advent16.kt
REDNBLACK
128,669,137
false
null
package day16 import parseInput import splitToLines /** --- Day 16: Aunt Sue --- Your Aunt Sue has given you a wonderful gift, and you'd like to send her a thank you card. However, there's a small problem: she signed it "From, <NAME>". You have 500 Aunts named "Sue". So, to avoid sending the card to the wrong person, you need to figure out which Aunt Sue (which you conveniently number 1 to 500, for sanity) gave you the gift. You open the present and, as luck would have it, good ol' Aunt Sue got you a My First Crime Scene Analysis Machine! Just what you wanted. Or needed, as the case may be. The My First Crime Scene Analysis Machine (MFCSAM for short) can detect a few specific compounds in a given sample, as well as how many distinct kinds of those compounds there are. According to the instructions, these are what the MFCSAM can detect: children, by human DNA age analysis. cats. It doesn't differentiate individual breeds. Several seemingly random breeds of dog: samoyeds, pomeranians, akitas, and vizslas. goldfish. No other kinds of fish. trees, all in one group. cars, presumably by exhaust or gasoline or something. perfumes, which is handy, since many of your Aunts Sue wear a few kinds. In fact, many of your Aunts Sue have many of these. You put the wrapping from the gift into the MFCSAM. It beeps inquisitively at you a few times and then prints out a message on ticker tape: children: 3 cats: 7 samoyeds: 2 pomeranians: 3 akitas: 0 vizslas: 0 goldfish: 5 trees: 3 cars: 2 perfumes: 1 You make a list of the things you can remember about each Aunt Sue. Things missing from your list aren't zero - you simply don't remember the value. What is the number of the Sue that got you the gift? --- Part Two --- As you're about to send the thank you note, something in the MFCSAM's instructions catches your eye. Apparently, it has an outdated retroencabulator, and so the output from the machine isn't exact values - some of them indicate ranges. In particular, the cats and trees readings indicates that there are greater than that many (due to the unpredictable nuclear decay of cat dander and tree pollen), while the pomeranians and goldfish readings indicate that there are fewer than that many (due to the modial interaction of magnetoreluctance). What is the number of the real Aunt Sue? */ fun main(args: Array<String>) { val search1 = hashMapOf( "children" to 3..3, "cats" to 7..7, "samoyeds" to 2..2, "pomeranians" to 3..3, "akitas" to 0..0, "vizslas" to 0..0, "goldfish" to 5..5, "trees" to 3..3, "cars" to 2..2, "perfumes" to 1..1 ) val search2 = hashMapOf( "children" to 3..3, "cats" to 8..999, "samoyeds" to 2..2, "pomeranians" to 0..2, "akitas" to 0..0, "vizslas" to 0..0, "goldfish" to 0..4, "trees" to 4..999, "cars" to 2..2, "perfumes" to 1..1 ) val input = parseInput("day16-input.txt") println(findAuntNumber(input, search1)) println(findAuntNumber(input, search2)) } fun findAuntNumber(input: String, search: Map<String, IntRange>): Int? { return parseMFCSAM(input) .map { m -> m.number to search.count { m.items[it.key] in it.value } } .maxBy { it.second } ?.first } data class MFCSAM(val number: Int, val items: Map<String, Int>) private fun parseMFCSAM(input: String) = input.splitToLines() .map { val number = Regex("""Sue (\d+):""").find(it)!!.groups[1]!!.value.toInt() val items = Regex("""(?:(\w+):\s(\d+),?)+""") .findAll(it) .map { it.groups[1]!!.value to it.groups[2]!!.value.toInt() } .toMap() MFCSAM(number, items) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
3,907
courses
MIT License
test/leetcode/PrisonCellsAfterNDays.kt
andrej-dyck
340,964,799
false
null
package leetcode import lib.* import misc.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.* import org.junit.jupiter.params.converter.* import org.junit.jupiter.params.provider.* /** * https://leetcode.com/problems/prison-cells-after-n-days/ * * 957. Prison Cells After N Days * [Medium] * * There are 8 prison cells in a row, and each cell is either occupied or vacant. * * Each day, whether the cell is occupied or vacant changes according to the following rules: * - If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * - Otherwise, it becomes vacant. * * (Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.) * * We describe the current state of the prison in the following way: * cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0. * * Given the initial state of the prison, return the state of the prison after N days * (and N such changes described above.) * * Note: * - cells.length == 8 * - cells[i] is in {0, 1} * - 1 <= N <= 10^9 */ fun prisonAfterNDays(initialCells: Array<Int>, n: Long): Array<Int> { tailrec fun cycleStates(cells: Array<Int>, n: Long): Array<Int> = if (n <= 0) cells else cycleStates(prisonNextDayState(cells), n - 1) val cyclesNeeded = (n - 1) % maxPrisonCycle(initialCells.size) + 1 return cycleStates(initialCells, cyclesNeeded) } /* * for 8 cells, this gives us a max cycle of 14. * note that we could have a cycles of length 1 or 7 as wells */ private fun maxPrisonCycle(numberOfCells: Int) = (numberOfCells - 2) /* the outer cells are never occupied */ .chose(2) /* as we have only occupied or vacant */ .minus(1) /* since the outer cells become and/or stay vacant, their adjacent cells have 1 less possibility to flip */ private fun prisonNextDayState(cells: Array<Int>) = cells.mapIndexed { i, _ -> if (cells.leftOf(i) == cells.rightOf(i)) 1 else 0 }.toTypedArray() private fun <T> Array<T>.leftOf(i: Int): T? = getOrNull(i - 1) private fun <T> Array<T>.rightOf(i: Int): T? = getOrNull(i + 1) /** * Unit tests */ class PrisonCellsAfterNDaysTest { @ParameterizedTest @CsvSource( "[0,1,0,1,1,0,0,1]; [0,1,1,0,0,0,0,0]", "[0,1,1,0,0,0,0,0]; [0,0,0,0,1,1,1,0]", "[0,0,0,0,1,1,1,0]; [0,1,1,0,0,1,0,0]", "[0,1,1,0,0,1,0,0]; [0,0,0,0,0,1,0,0]", "[0,0,0,0,0,1,0,0]; [0,1,1,1,0,1,0,0]", "[0,1,1,1,0,1,0,0]; [0,0,1,0,1,1,0,0]", "[0,0,1,0,1,1,0,0]; [0,0,1,1,0,0,0,0]", delimiter = ';' ) fun `next day's cell becomes occupied iff both adjacent cells are either vacant or occupied`( @ConvertWith(IntArrayArg::class) initialCells: Array<Int>, @ConvertWith(IntArrayArg::class) expectedCellsNextDay: Array<Int>, ) { assertThat( prisonNextDayState(initialCells) ).containsExactly( *expectedCellsNextDay ) } @ParameterizedTest @CsvSource( "[0,1,0,1,1,0,0,1]; 7; [0,0,1,1,0,0,0,0]", "[1,0,0,1,0,0,1,0]; 1000000000; [0,0,1,1,1,1,1,0]", delimiter = ';' ) fun `returns the state of the prison after n days`( @ConvertWith(IntArrayArg::class) initialCells: Array<Int>, n: Long, @ConvertWith(IntArrayArg::class) expectedStateAfterNDays: Array<Int>, ) { assertThat( prisonAfterNDays(initialCells, n) ).containsExactly( *expectedStateAfterNDays ) } }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
3,639
coding-challenges
MIT License
src/Day02.kt
gylee2011
573,544,473
false
{"Kotlin": 9419}
import day02.* fun main() { fun part1(input: List<String>): Int = input .map(String::toShapePair) .sumOf { (opponent, me) -> Outcome.of(opponent, me).score + me.score } fun part2(input: List<String>): Int = input .map { val (opponent, expectedOutcome) = it.split(" ") opponent.toShape() to expectedOutcome.toOutcome() } .sumOf { (opponent, expectedOutcome) -> val myShape = when (expectedOutcome) { Outcome.WIN -> opponent.winner Outcome.DRAW -> opponent Outcome.LOSE -> opponent.loser } myShape.score + expectedOutcome.score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
339e0895fd2484b7f712b966a0dae8a4cfebc2fa
957
aoc2022-kotlin
Apache License 2.0
app/src/main/kotlin/solution/Solution947.kt
likexx
559,794,763
false
{"Kotlin": 136661}
package solution import solution.annotation.Leetcode class Solution947 { @Leetcode(947) class Solution { fun removeStones(stones: Array<IntArray>): Int { // union find. remove all connected components val N = stones.size val parents = IntArray(N) { -1 } val sizes = IntArray(N) { 1 } fun getParent(i: Int): Int { if (parents[i]==-1) { return i } val p = getParent(parents[i]) parents[i]=p return p } fun union(i: Int, j: Int) { val p1 = getParent(i) val p2 = getParent(j) if (p1==p2) { return } val s1=sizes[p1] val s2=sizes[p2] if (s1>=s2) { parents[p2]=p1 sizes[p1]+=sizes[p2] } else { parents[p1]=p2 sizes[p2]+=sizes[p1] } } for (i in stones.indices) { for (j in 0..i-1) { if (stones[i][0]==stones[j][0] || stones[i][1]==stones[j][1]) { union(i, j) } } } val groups = hashSetOf<Int>() for (i in stones.indices) { groups.add(getParent(i)) } return stones.size - groups.size } fun removeStonesDFS(stones: Array<IntArray>): Int { val rows = hashMapOf<Int, HashSet<Int>>() val cols = hashMapOf<Int, HashSet<Int>>() for ((i,s) in stones.withIndex()) { val y = s[0] val x = s[1] val v1 = rows.getOrDefault(y, hashSetOf()) v1.add(i) rows[y]=v1 val v2 = cols.getOrDefault(x, hashSetOf()) v2.add(i) cols[x]=v2 } val visited = hashSetOf<Int>() fun dfs(i: Int) { if (visited.contains(i)) { return } visited.add(i) for (j in rows[stones[i][0]]!!) { dfs(j) } for (j in cols[stones[i][1]]!!) { dfs(j) } } var count=0 for (i in stones.indices) { if (!visited.contains(i)) { count+=1 dfs(i) } } return stones.size - count } fun removeStonesNaive(stones: Array<IntArray>): Int { val adjs = hashMapOf<Int, HashSet<Int>>() for (i in 0..stones.size-1) { adjs[i] = adjs.getOrDefault(i, hashSetOf()) for (j in i+1..stones.size-1) { if (stones[i][0]==stones[j][0] || stones[i][1]==stones[j][1]) { val v1 = adjs.getOrDefault(i, hashSetOf()) v1.add(j) adjs[i]=v1 val v2 = adjs.getOrDefault(j, hashSetOf()) v2.add(i) adjs[j]=v2 } } } val visited = hashSetOf<Int>() fun dfs(i: Int) { if (visited.contains(i)) { return } visited.add(i) for (j in adjs[i]!!) { dfs(j) } } var count=0 for (i in stones.indices) { if (!visited.contains(i)) { count+=1 dfs(i) } } return stones.size - count } } }
0
Kotlin
0
0
376352562faf8131172e7630ab4e6501fabb3002
3,919
leetcode-kotlin
MIT License
src/main/kotlin/day02/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day02 import java.io.File fun main() { val lines = File("src/main/kotlin/day02/input.txt").readLines() val submarineV1 = lines .fold(SubmarineV1()) { submarine, commandString -> submarine.execute(commandString.toCommand()) } println(submarineV1.x * submarineV1.y) val submarineV2 = lines .fold(SubmarineV2()) { submarine, commandString -> submarine.execute(commandString.toCommand()) } println(submarineV2.x * submarineV2.y) } sealed class Command class Forward(val amount: Int): Command() class Down(val amount: Int): Command() class Up(val amount: Int): Command() fun String.toCommand(): Command { val moveType = this.substringBefore(" ") val amount = this.substringAfter(" ").toInt() return when (moveType) { "forward" -> Forward(amount) "down" -> Down(amount) "up" -> Up(amount) else -> Forward(0) } } class SubmarineV1(var x: Int = 0, var y: Int = 0) { fun execute(command: Command): SubmarineV1 = when (command) { is Forward -> apply { x += command.amount } is Down -> apply { y += command.amount } is Up -> apply { y -= command.amount } } } class SubmarineV2(var x: Int = 0, var y: Int = 0, var aim: Int = 0) { fun execute(command: Command): SubmarineV2 = when (command) { is Forward -> apply { x += command.amount; y += aim * command.amount } is Down -> apply { aim += command.amount } is Up -> apply { aim -= command.amount } } }
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
1,545
aoc-2021
MIT License
src/Day17.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
import kotlin.math.absoluteValue suspend fun main() { val testInput = readInput("Day17_test") check(part1(testInput.first()) == 3068) check(part2(testInput.first()) == 1514285714288L) val input = readInput("Day17") measureAndPrintResult { part1(input.first()) } measureAndPrintResult { part2(input.first()) } } private fun part1(input: String): Int { val jets = parseJets(input) val (cave, _, _) = simulateSteps(2022, jets, Step(cave = wall.toMutableList())) return cave.height } private fun part2(input: String, targetBlocks: Long = 1000000000000): Long { val jets = parseJets(input) val cache = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() var step = Step(wall.toMutableList()) while (true) { step = simulateStep(jets, step) val state = step.blockIndex to step.jetIndex if (state !in cache) { cache[state] = step.blockCount - 1 to step.cave.height continue } val (blocksAtStartOfLoop, heightAtStartOfLoop) = cache.getValue(state) val blocksPerLoop = step.blockCount - 1L - blocksAtStartOfLoop val heightPerLoop = step.cave.height - heightAtStartOfLoop val loopsNeeded = (targetBlocks - blocksAtStartOfLoop) / blocksPerLoop val remainingBlocks = (targetBlocks - blocksAtStartOfLoop) % blocksPerLoop val loopedHeight = (heightPerLoop * (loopsNeeded - 1L)) - 1L val (cave, _, _) = simulateSteps(remainingBlocks.toInt(), jets, step) return cave.height + loopedHeight } } data class Step(val cave: MutableList<Point>, val blockCount: Int = 0, val jetCount: Int = 0, val blockIndex: Int = 0, val jetIndex: Int = 0) private fun simulateSteps(blocks: Int, jets: List<Point>, previous: Step): Step { return (0 until blocks).fold(previous) { acc, _ -> simulateStep(jets, acc) } } private fun simulateStep(jets: List<Point>, previous: Step): Step { val cave = previous.cave var blockCount = previous.blockCount var jetCount = previous.jetCount var shape = shapes.nth(blockCount++).startingPosition(cave.minY) do { val movedShape = shape + jets.nth(jetCount++) if (movedShape inBoundsOf 0..6 && !movedShape.collides(cave)) { shape = movedShape } shape = shape.moveDown() } while (!shape.collides(cave)) cave += shape.moveUp() return Step(cave, blockCount, jetCount, blockCount % shapes.size, jetCount % jets.size) } private fun parseJets(input: String): List<Point> = input.map { when (it) { '>' -> Point(1, 0) else -> Point(-1, 0) } } private val wall = List(7) { Point(it, 0) } private val shapes = listOf( setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0)), setOf(Point(1, 0), Point(0, -1), Point(1, -1), Point(2, -1), Point(1, -2)), setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, -1), Point(2, -2)), setOf(Point(0, 0), Point(0, -1), Point(0, -2), Point(0, -3)), setOf(Point(0, 0), Point(1, 0), Point(0, -1), Point(1, -1)) ) private fun Set<Point>.startingPosition(minY: Int): Set<Point> = map { it + Point(2, minY - 4) }.toSet() private fun Set<Point>.moveDown(): Set<Point> = map { it + Point(0, 1) }.toSet() private fun Set<Point>.moveUp(): Set<Point> = map { it + Point(0, -1) }.toSet() private operator fun Set<Point>.plus(other: Point): Set<Point> = map { it + other }.toSet() private fun Set<Point>.collides(other: Collection<Point>) = intersect(other.toSet()).isNotEmpty() private infix fun Set<Point>.inBoundsOf(range: IntRange) = all { it.x in range } private val List<Point>.minY get() = minOf { it.y } private val List<Point>.height get() = minY.absoluteValue data class Point(val x: Int, val y: Int) { operator fun plus(other: Point) = Point(x + other.x, y + other.y) }
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
3,864
aoc-22
Apache License 2.0
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/leetcode/medium/22_generateParentheses.kt
aquatir
76,377,920
false
{"Java": 674809, "Python": 143889, "Kotlin": 112192, "Haskell": 57852, "Elixir": 33284, "TeX": 20611, "Scala": 17065, "Dockerfile": 6314, "HTML": 4714, "Shell": 387, "Batchfile": 316, "Erlang": 269, "CSS": 97}
package com.codesample.leetcode.medium import java.lang.StringBuilder /** 22. Generate Parentheses https://leetcode.com/problems/generate-parentheses/ * * Given n, output every correct parenthesis sequence with size 2*n. Input should be sorted lexicographically * e.g: * n = 1: () * n = 2: (()),()() * n = 3: ((())),(()()),(())(),()(()),()()() * */ fun generateParenthesis(n: Int): List<String> { val opened = 1 val good = mutableListOf<String>(); fun allGoodParenthesis(opened: Int, parenthesisLeft: Int, current: String) { if (parenthesisLeft == 0) { good.add(current) return } if (opened > 0 && parenthesisLeft > opened) { // some opened, but can open more allGoodParenthesis(opened + 1, parenthesisLeft - 1, "$current(") } if (opened == 0 && parenthesisLeft >= 2) { // none opened, but can open + close allGoodParenthesis(opened + 1, parenthesisLeft - 1, "$current(") } if (opened > 0) { // close opened allGoodParenthesis(opened - 1, parenthesisLeft - 1, "$current)") } } allGoodParenthesis(opened, n*2 - 1, "(") return good.map { "\"$it\"" } } fun main() { println(generateParenthesis(1)) // () println(generateParenthesis(2)) // (()),()() println(generateParenthesis(3)) // ((())),(()()),(())(),()(()),()()() }
1
Java
3
6
eac3328ecd1c434b1e9aae2cdbec05a44fad4430
1,393
code-samples
MIT License
aoc2022/day14.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval fun main() { Day14.execute() } object Day14 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: Set<Pair<Int, Int>>): Int { val map = input.toMutableSet() var iteration = 0 val minX = input.minOf { it.first } val maxX = input.maxOf { it.first } val maxY = input.maxOf { it.second } while (true) { iteration++ var newSand = 500 to 0 while (true) { if (newSand.first < minX || newSand.first > maxX || newSand.second > maxY) { // Out-of-bounds! return iteration - 1 // Remove one because this sand doesn't count } newSand = if (!map.contains(newSand.first to newSand.second + 1)) { // Go down newSand.first to newSand.second + 1 } else if (!map.contains(newSand.first - 1 to newSand.second + 1)) { // Go Left and down newSand.first - 1 to newSand.second + 1 } else if (!map.contains(newSand.first + 1 to newSand.second + 1)) { // Go Right and down newSand.first + 1 to newSand.second + 1 } else { // reached final position map.add(newSand) break } } } } private fun part2(input: Set<Pair<Int, Int>>): Int { val map = input.toMutableSet() var iteration = 0 val maxY = input.maxOf { it.second } while (true) { iteration++ var newSand = 500 to 0 while (true) { newSand = if (!map.contains(newSand.first to newSand.second + 1)) { // Go down newSand.first to newSand.second + 1 } else if (!map.contains(newSand.first - 1 to newSand.second + 1)) { // Go Left and down newSand.first - 1 to newSand.second + 1 } else if (!map.contains(newSand.first + 1 to newSand.second + 1)) { // Go Right and down newSand.first + 1 to newSand.second + 1 } else { // reached final position if (newSand == 500 to 0) { // Reached the source return iteration } map.add(newSand) break } if (newSand.second == (maxY + 2)) { // Reached the floor iteration-- // These don't count for the final count, it's just to build a dummy floor map.add(newSand) break } } } } private fun readInput(): Set<Pair<Int, Int>> = InputRetrieval.getFile(2022, 14).readLines().flatMap { trace -> trace.split(" -> ").asSequence().map { value -> value.split(',').map { pos -> pos.toInt() } }.windowed(2, 1) .map { val (start, end) = it val finalSet = mutableSetOf<Pair<Int, Int>>() (start.first()..end.first()).map { pos -> pos to start.last() }.toSet().let { list -> finalSet.addAll(list) } // going right (end.first()..start.first()).map { pos -> pos to start.last() }.toSet().let { list -> finalSet.addAll(list) } // going left (start.last()..end.last()).map { pos -> start.first() to pos }.toSet().let { list -> finalSet.addAll(list) } // going up (end.last()..start.last()).map { pos -> start.first() to pos }.toSet().let { list -> finalSet.addAll(list) } // going down finalSet }.flatten().toSet() }.toSet() }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
3,990
Advent-Of-Code
MIT License