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/Day19.kt
LauwiMeara
572,498,129
false
{"Kotlin": 109923}
enum class Element { ORE, CLAY, OBSIDIAN, GEODE } data class Blueprint (val id: Int, val costs: Map<Element, List<Material>>) data class Material (val quantity: Int, val element: Element) data class ElementInfo (var collected: Int, var numRobots: Int, val maxNeededRobots: Int) const val MINUTES_DAY_19_PART_1 = 24 const val MINUTES_DAY_19_PART_2 = 32 fun main() { fun getMaxNeededRobots(blueprint: Blueprint, element: Element): Int { return blueprint.costs.values.flatten().filter{it.element == element}.maxOf{it.quantity} } fun robotCanBeMade(costRobot: List<Material>, scenario: Map<Element, ElementInfo>): Boolean { for (material in costRobot) { val collectedBeforeThisRound = scenario[material.element]!!.collected - scenario[material.element]!!.numRobots if (collectedBeforeThisRound < material.quantity) { return false } } return true } fun hasSimilarScenario(possibleScenarios: List<Map<Element, ElementInfo>>, newScenario: Map<Element, ElementInfo>): Boolean { return possibleScenarios.any{scenario -> scenario.keys.all{element -> scenario[element]!!.numRobots >= newScenario[element]!!.numRobots && scenario[element]!!.collected >= newScenario[element]!!.collected}} } fun collectElements(scenario: Map<Element, ElementInfo>) { for (element in scenario.keys) { scenario[element]!!.collected += scenario[element]!!.numRobots } } fun getNewScenario(scenario: Map<Element, ElementInfo>, blueprint: Blueprint, element: Element): Map<Element, ElementInfo> { val newScenario = scenario.map { it.key to it.value.copy() }.toMap() for (material in blueprint.costs[element]!!) { newScenario[material.element]!!.collected -= material.quantity } newScenario[element]!!.numRobots += 1 return newScenario } fun getMaxGeodes(blueprint: Blueprint, maxMinutes: Int): Int { println("----- Blueprint: ${blueprint.id} -----") var possibleScenarios = mutableListOf(mapOf( Element.ORE to ElementInfo(0, 1, getMaxNeededRobots(blueprint, Element.ORE)), Element.CLAY to ElementInfo(0, 0, getMaxNeededRobots(blueprint, Element.CLAY)), Element.OBSIDIAN to ElementInfo(0, 0, getMaxNeededRobots(blueprint, Element.OBSIDIAN)), Element.GEODE to ElementInfo(0, 0, Int.MAX_VALUE))) var minutes = 0 while (minutes < maxMinutes) { minutes++ println("Minute: $minutes") // Greedy search when (minutes) { maxMinutes - 10 -> possibleScenarios = possibleScenarios.filter{scenario -> scenario[Element.OBSIDIAN]!!.numRobots > 0}.toMutableList() maxMinutes - 5 -> { val maxGeodeRobots = possibleScenarios.maxOf { scenario -> scenario[Element.GEODE]!!.numRobots } possibleScenarios = possibleScenarios.filter { scenario -> scenario[Element.GEODE]!!.numRobots == maxGeodeRobots }.toMutableList() } } // Collect elements for (scenario in possibleScenarios) { collectElements(scenario) } // Create new robots (if possible) val newScenarios = mutableListOf<Map<Element, ElementInfo>>() for (scenario in possibleScenarios) { for (element in scenario.keys) { if (scenario[element]!!.numRobots < scenario[element]!!.maxNeededRobots && robotCanBeMade(blueprint.costs[element]!!, scenario)) { val newScenario = getNewScenario(scenario, blueprint, element) if (!hasSimilarScenario(possibleScenarios, newScenario)) { newScenarios.add(newScenario) } } } } possibleScenarios += newScenarios possibleScenarios = possibleScenarios.distinct().toMutableList() } return possibleScenarios.maxOf{ scenario -> scenario[Element.GEODE]!!.collected } } fun part1(input: List<Blueprint>): Int { val maxGeodesPerBlueprint = mutableMapOf<Int, Int>() for (blueprint in input) { maxGeodesPerBlueprint[blueprint.id] = getMaxGeodes(blueprint, MINUTES_DAY_19_PART_1) } return maxGeodesPerBlueprint.entries.fold(0) { sum, it -> sum + (it.key * it.value) } } fun part2(input: List<Blueprint>): Int { val remainingBlueprints = input.subList(0, 3) var productMaxGeodes = 1 for (blueprint in remainingBlueprints) { productMaxGeodes *= getMaxGeodes(blueprint, MINUTES_DAY_19_PART_2) } return productMaxGeodes } fun getElement(str: String): Element { return when(str) { "ore" -> Element.ORE "clay" -> Element.CLAY "obsidian" -> Element.OBSIDIAN else -> Element.GEODE } } val input = readInputAsStrings("Day19") .map{line -> line.split(": ", ".") .map{sentence -> sentence.split( "Blueprint", " ", "and", "Each", "costs", "ore robot", "clay robot", "obsidian robot", "geode robot" ) .filter{it.isNotEmpty()} .filter{it.isNotEmpty()}}} .map{Blueprint( it[0].single().toInt(), mapOf( Element.ORE to it[1].chunked(2).map{x -> Material(x.first().toInt(), getElement(x.last()))}, Element.CLAY to it[2].chunked(2).map{x -> Material(x.first().toInt(), getElement(x.last()))}, Element.OBSIDIAN to it[3].chunked(2).map{x -> Material(x.first().toInt(), getElement(x.last()))}, Element.GEODE to it[4].chunked(2).map{x -> Material(x.first().toInt(), getElement(x.last()))}))} println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
34b4d4fa7e562551cb892c272fe7ad406a28fb69
6,177
AoC2022
Apache License 2.0
src/main/kotlin/championofgoats/advent/utils/functions.kt
ChampionOfGoats
225,446,764
false
null
package championofgoats.advent.utils // Get the greatest common divisor of two digits fun gcd(a: Int, b: Int) : Int = if (b == 0) a else gcd(b, a % b) // Get an identity matrix // Points P where the 1-dimensional index i = (i % size) * size (i % size) have value 1.0 // All other points Q are 0.0 fun identity(size: Int) : List<Double> = (1..size * size).mapIndexed { i, _ -> if (i == (i % size) * size + (i % size)) 1.0 else 0.0 } // Compute the Gauss-Jordan Elimination inverse matrix of the input // NB: This function doesn't confirm whether or not a given matrix can be inverted! fun invertMatrix(size: Int, input: List<Double>) : List<Double> { var inMatrix = input.toMutableList() // lhs var inverse = identity(size).toMutableList() // rhs for (y in 0..size - 1) { // project 1D array to 2D var rowOff = y * size // divisor is the number required to get 1 in our desired position var divisor = inMatrix[size * y + y] // for each value in row[y], divide by $divisor for (x in rowOff..(rowOff + size - 1)) { inMatrix[x] /= divisor inverse[x] /= divisor } // for each subsequent row... for (j in 0..size - 1) { // that is *not* row[y] if (j != y) { // The $subtractor is the value such that row[j][y] - $subtractor = 0 var subtractor = inMatrix[j * size + y] // For each value in the row... for (k in 0..size- 1) { // f(j,k) = Row[j][k] - ( $subtractor * row[y][k] ) inMatrix[j * size + k] = inMatrix[j * size + k] - (subtractor * inMatrix[y * size + k]) } /// For each value in the row... for (k in 0..size - 1) { // f(j,k) = Row[j][k] - ( $subtractor * row[y][k] ) inverse[j * size + k] = inverse[j * size + k] - (subtractor * inverse[y * size + k]) } } } } return inverse }
0
Kotlin
0
0
4f69de1579f40928c1278c3cea4e23e0c0e3b742
2,081
advent-of-code
MIT License
src/main/kotlin/com/colinodell/advent2016/Day03.kt
colinodell
495,627,767
false
{"Kotlin": 80872}
package com.colinodell.advent2016 class Day03(private val input: String) { fun solvePart1() = parsePart1(input).count { it.isValid() } fun solvePart2() = parsePart2(input).count { it.isValid() } private fun parseRow(row: String): List<Int> = row.trim().split("\\s+".toRegex()).map { it.toInt() } private fun parsePart1(input: String): List<Triangle> { return input.split("\n").map { parseRow(it) }.map { Triangle(it[0], it[1], it[2]) } } private fun parsePart2(input: String): List<Triangle> { val rows = input.split("\n").map { parseRow(it) } val triangles = mutableListOf<Triangle>() for (c in 0..2) { for (r in rows.indices step 3) { triangles.add(Triangle(rows[r][c], rows[r + 1][c], rows[r + 2][c])) } } return triangles } private class Triangle(val a: Int, val b: Int, val c: Int) { fun isValid() = a + b > c && a + c > b && b + c > a } }
0
Kotlin
0
0
8a387ddc60025a74ace8d4bc874310f4fbee1b65
985
advent-2016
Apache License 2.0
src/day11/Main.kt
nikwotton
572,814,041
false
{"Kotlin": 77320}
package day11 import java.io.File const val workingDir = "src/day11" fun main() { val sample = File("$workingDir/sample.txt") val input1 = File("$workingDir/input_1.txt") println("Step 1a: ${runStep1(sample)}") println("Step 1b: ${runStep1(input1)}") println("Step 2a: ${runStep2(sample)}") println("Step 2b: ${runStep2(input1)}") } @JvmInline value class Item(val worryLevel: Long) @JvmInline value class MonkeyId(val id: Long) data class Monkey( val id: MonkeyId, val items: MutableList<Item>, val operation: (old: Item) -> Item, val test: (Item) -> MonkeyId, var inspectionCounter: Long = 0 ) fun runStep1(input: File): String { val monkeys: MutableList<Monkey> = mutableListOf() input.readText().split("\n\n").forEach { val lines = it.split("\n") val monkeyId = MonkeyId(lines[0].removeSurrounding("Monkey ", ":").toLong()) val startingItems = lines[1].removePrefix(" Starting items: ") .let { if (it.contains(",")) it.split(", ").map { Item(it.toLong()) }.toMutableList() else mutableListOf(Item(it.toLong())) } val operation = lines[2].removePrefix(" Operation: new = ").split(" ").let { { old: Item -> val a = if (it[0] == "old") old else Item(it[0].toLong()) val b = if (it[2] == "old") old else Item(it[2].toLong()) Item( when (it[1]) { "+" -> a.worryLevel + b.worryLevel "*" -> a.worryLevel * b.worryLevel else -> TODO("Need to handle ${it[0]}") } ) } } val divisibleBy = lines[3].removePrefix(" Test: divisible by ").toLong() val ifTrue = lines[4].removePrefix(" If true: throw to monkey ").toLong() val ifFalse = lines[5].removePrefix(" If false: throw to monkey ").toLong() val test = { item: Item -> if (item.worryLevel % divisibleBy == 0L) MonkeyId(ifTrue) else MonkeyId(ifFalse) } monkeys.add(Monkey(monkeyId, startingItems, operation, test)) } repeat(20) { monkeys.sortedBy { it.id.id }.forEach { monkey -> // inspect item monkey.items.forEach { monkey.inspectionCounter++ val newWorryLevel = Item(monkey.operation(it).worryLevel / 3) val newMonkeyId = monkey.test(newWorryLevel) monkeys.first { it.id == newMonkeyId }.items.add(newWorryLevel) } monkey.items.clear() } } return monkeys.map { it.inspectionCounter }.sortedDescending().take(2).let { (a, b) -> a * b }.toString() } fun runStep2(input: File): String { val monkeys: MutableList<Monkey> = mutableListOf() var masterDivisor = 1L input.readText().split("\n\n").forEach { val lines = it.split("\n") val monkeyId = MonkeyId(lines[0].removeSurrounding("Monkey ", ":").toLong()) val startingItems = lines[1].removePrefix(" Starting items: ") .let { if (it.contains(",")) it.split(", ").map { Item(it.toLong()) }.toMutableList() else mutableListOf(Item(it.toLong())) } val operation = lines[2].removePrefix(" Operation: new = ").split(" ").let { { old: Item -> val a = if (it[0] == "old") old else Item(it[0].toLong()) val b = if (it[2] == "old") old else Item(it[2].toLong()) Item( when (it[1]) { "+" -> a.worryLevel + b.worryLevel "*" -> a.worryLevel * b.worryLevel else -> TODO("Need to handle ${it[0]}") } ) } } val divisibleBy = lines[3].removePrefix(" Test: divisible by ").toLong() masterDivisor *= divisibleBy val ifTrue = lines[4].removePrefix(" If true: throw to monkey ").toLong() val ifFalse = lines[5].removePrefix(" If false: throw to monkey ").toLong() val test = { item: Item -> if (item.worryLevel % divisibleBy == 0L) MonkeyId(ifTrue) else MonkeyId(ifFalse) } monkeys.add(Monkey(monkeyId, startingItems, operation, test)) } repeat(10_000) { index -> monkeys.sortedBy { it.id.id }.forEach { monkey -> // inspect item monkey.items.forEach { monkey.inspectionCounter++ val newWorryLevel = Item(monkey.operation(it).worryLevel % masterDivisor) val newMonkeyId = monkey.test(newWorryLevel) monkeys.first { it.id == newMonkeyId }.items.add(newWorryLevel) } monkey.items.clear() } } return monkeys.map { it.inspectionCounter }.sortedDescending().take(2).let { (a, b) -> a * b }.toString() }
0
Kotlin
0
0
dee6a1c34bfe3530ae6a8417db85ac590af16909
5,015
advent-of-code-2022
Apache License 2.0
src/Day05.kt
RogozhinRoman
572,915,906
false
{"Kotlin": 28985}
fun main() { fun getCrates(input: List<String>): List<ArrayDeque<String>> { val cratesTemp = input.takeWhile { !it.startsWith("move") }.dropLast(1) val stacks = List<ArrayDeque<String>>(cratesTemp.last().last().toString().toInt()) { ArrayDeque() } val crates = cratesTemp.dropLast(1) for (line in crates.reversed()) { for ((counter, crate) in line.chunked(4).withIndex()) { if (crate.startsWith("[")) { stacks[counter].addLast(crate[1].toString()) } } } return stacks } fun getCommands(input: List<String>): List<Triple<Int, Int, Int>> { val commands = input.dropWhile { !it.startsWith("move") } return commands.map { val splitted = it.split("move ", " from ", " to ") Triple(splitted[1].toInt(), splitted[2].toInt(), splitted[3].toInt()) } } fun transfer1( command: Triple<Int, Int, Int>, from: ArrayDeque<String>, to: ArrayDeque<String> ) { for (i in 0 until command.first) { val elem = from.removeLast() to.addLast(elem) } } fun transfer2( command: Triple<Int, Int, Int>, from: ArrayDeque<String>, to: ArrayDeque<String> ) { val toTransfer = ArrayDeque<String>() for (i in 0 until command.first) { toTransfer.addLast(from.removeLast()) } for (i in 0 until command.first) { to.addLast(toTransfer.removeLast()) } } fun handleTransfers( input: List<String>, transferFunc: (command: Triple<Int, Int, Int>, from: ArrayDeque<String>, to: ArrayDeque<String>) -> Unit ): String { val crates = getCrates(input) val commands = getCommands(input) for (command in commands) { val from = crates[command.second - 1] val to = crates[command.third - 1] transferFunc(command, from, to) } return crates.joinToString("") { it.last() } } fun part1(input: List<String>) = handleTransfers(input, ::transfer1) fun part2(input: List<String>) = handleTransfers(input, ::transfer2) val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
6375cf6275f6d78661e9d4baed84d1db8c1025de
2,455
AoC2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch6/Problem67.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch6 import dev.bogwalk.util.custom.PyramidTree /** * Problem 67: Maximum Path Sum 2 * * https://projecteuler.net/problem=67 * * Goal: Find the maximum sum from tree root to leaf node of an N-rowed tree, which contains i * integers on each ith row, by moving to an adjacent number on the row below. This goal is * identical to Problem 18, but the constraints have been increased from N = 15 to N = 100. * * Constraints: 1<= N <= 100, numbers in [0,100] * * e.g.: N = 4 * 3 * 7 4 * 2 4 6 * 8 5 9 3 * max path -> 3+7+4+9 * output = 23 */ class MaximumPathSum2 { /** * Generates a graph using custom PyramidTree class & finds the largest valued route using * post-order traversal. * * While acceptable for Problem 18, this solution is impossible for pyramids with more than * 30 rows, as shown by the 27x longer speed taken to find the solution when only 5 more rows * were added to the same pyramid. A 100 row pyramid would have 2^99 possible routes and even * if 1e12 routes could be assessed every second, it would take ~> 20e9 years to iterate * through them all. * * SPEED (WORSE) 3.72s for N = 30 * SPEED (WORSE) 102.33s for N = 35 */ fun maxPathSum(rows: Int, vararg elements: Int): Int { val tree = PyramidTree(rows, *elements) return tree.maxSumPostOrderTraversal() } /** * This solution is identical to the Problem 18 solution. * * Rather than create a custom tree, this solution starts from the bottom of the tree (last * nested list), repeatedly finding the maximum of adjacent values and adding it to the * parent value 1 row above, until the tree root is reached. This new root value is returned * as the maximum path value. * * SPEED (BETTER) 1.7e5ns for N = 30 * SPEED (BETTER) 1.3e5ns for N = 35 * SPEED (BETTER) 7.3e5ns for N = 100 */ fun maxPathSumDynamic(rows: Int, elements: Array<IntArray>): Int { for (row in (rows - 1) downTo 1) { for (col in 0 until row) { elements[row-1][col] += maxOf(elements[row][col], elements[row][col+1]) } } return elements[0][0] } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,291
project-euler-kotlin
MIT License
aoc2022/day23.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval fun main() { Day23.execute() } object Day23 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<Point>): Int { var board = input val checkOrder = mutableListOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST) repeat(10) { _ -> board = processElvesMoves(board, checkOrder) // 3 - Update direction order: move the first element to the end checkOrder.removeFirst().apply { checkOrder.add(this) } } return board.calculateResult() } /** * Optimizations? Don't know that word! Let's turn my laptop into a heater! */ private fun part2(input: List<Point>): Int { var round = 1 var move = true var board = input val checkOrder = mutableListOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST) while (move) { val newBoard = processElvesMoves(board, checkOrder).toSet() // 3 - Update direction order: move the first element to the end checkOrder.removeFirst().apply { checkOrder.add(this) } if (board.intersect(newBoard.toSet()).size == board.size) { // No changes move = false } else { board = newBoard.toList() round++ } } return round } private fun processElvesMoves(board: List<Point>, checkOrder: List<Direction>): List<Point> { val newPositions = mutableListOf<Pair<Point, Point>>() // 1- Propose next moves board.forEach { elf -> var newPos = elf if (checkOrder.flatMap { it.deltaPositions }.map { Point(elf.x + it.first, elf.y + it.second) }.any { board.contains(it) }) { for (i in checkOrder) { val freeDirection = !i.deltaPositions.map { Point(elf.x + it.first, elf.y + it.second) }.any { board.contains(it) } if (freeDirection) { val targetPosition = Point(elf.x + i.targetDelta.first, elf.y + i.targetDelta.second) newPos = targetPosition break // No need to check other direction } } } newPositions.add(newPos to elf) } // 2- Move, and if conflict arise, block the move for those elves return if (newPositions.map { it.first }.toSet().size != newPositions.size) { val newBoard = mutableListOf<Point>() // Houston, we have a conflict! newPositions.groupBy { it.first }.forEach { if (it.value.size == 1) { newBoard.add(it.key) } else { it.value.forEach { pos -> newBoard.add(pos.second) } } } newBoard } else { newPositions.map { it.first } } } private fun List<Point>.printBoard() { val minX = this.minOf { it.x } val maxX = this.maxOf { it.x } + 1 val minY = this.minOf { it.y } val maxY = this.maxOf { it.y } + 1 for (y in minY until maxY) { for (x in minX until maxX) { if (this.contains(Point(x, y))) { print("#") } else { print(".") } } println() } } enum class Direction(val deltaPositions: List<Pair<Int, Int>>, val targetDelta: Pair<Int, Int>) { NORTH(listOf(-1 to -1, 0 to -1, 1 to -1), 0 to -1), SOUTH(listOf(-1 to 1, 0 to 1, 1 to 1), 0 to 1), WEST(listOf(-1 to -1, -1 to 0, -1 to 1), -1 to 0), EAST(listOf(1 to -1, 1 to 0, 1 to 1), 1 to 0); } private fun List<Point>.calculateResult(): Int { val minX = this.minOf { it.x } val maxX = this.maxOf { it.x } + 1 val minY = this.minOf { it.y } val maxY = this.maxOf { it.y } + 1 val width = maxX - minX val height = maxY - minY return (width * height) - this.size } data class Point(val x: Int, val y: Int) fun readInput(): List<Point> { val elfList = mutableListOf<Point>() InputRetrieval.getFile(2022, 23).readLines().forEachIndexed { y, s -> s.forEachIndexed { x, c -> if (c == '#') { elfList.add(Point(x, y)) } } } return elfList } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
4,662
Advent-Of-Code
MIT License
src/Day03.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
fun main() { fun getPriorityOfAnItem(item: Char): Int { if (item.isLowerCase()) return item.code - 'a'.code + 1 return item.code - 'A'.code + 27 } fun getPriorityOf1Rucksack(items: String): Int { val compartment1 = items.subSequence(0, items.length / 2).toSet() val compartment2 = items.subSequence(items.length / 2, items.length).toSet() return getPriorityOfAnItem(compartment1.intersect(compartment2).first()) } fun part1(input: List<String>): Int { return input.map(::getPriorityOf1Rucksack).sum() } fun getCommonLetter(s1: String, s2: String, s3: String): Char { return s1.toSet().intersect(s2.toSet()).intersect(s3.toSet()).first() } fun part2(input: List<String>): Int { return input.chunked(3) { (a, b, c) -> getPriorityOfAnItem(getCommonLetter(a, b, c)) }.sum() } val input = readInput("Day03") println("Day 3") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
1,002
aoc-2022
Apache License 2.0
2022/src/Day11.kt
Saydemr
573,086,273
false
{"Kotlin": 35583, "Python": 3913}
package src open class Monkey { var id: Int = 0 var items: MutableList<Long> = mutableListOf() var operator: String = "" var operand : String = "" var test : Long = 0 var passAction: Int = 0 var failAction: Int = 0 var numInspected: Long = 0 @Override override fun toString(): String { return "src.Monkey(id=$id, items=$items, operator='$operator', operand='$operand', test=$test, passAction=$passAction, failAction=$failAction, numInspected=$numInspected)" } } fun readMonkey(monkeyInfo: MutableList<String>): Monkey { val monkey = Monkey() monkey.id = monkeyInfo[0].trim() .replace("src.Monkey ", "") .replace(":","") .toInt() monkey.items = monkeyInfo[1].trim() .replace("Starting items: ", "") .split(", ") .map { it.trim().toLong() } .toMutableList() val operation = monkeyInfo[2] .trim() .replace("Operation: new = old ", "") .split(" ") monkey.operator = operation[0] monkey.operand = operation[1] monkey.test = monkeyInfo[3] .trim() .replace("Test: divisible by ", "") .toLong() monkey.passAction = monkeyInfo[4].trim() .replace("If true: throw to monkey ", "") .toInt() monkey.failAction = monkeyInfo[5] .trim() .replace("If false: throw to monkey ", "") .toInt() return monkey } var bigModulus = 1L fun worryLevelCalculator(worryLevel: Long, operator: String, operand: String): Long { val operandInt = if (operand == "old") worryLevel else operand.toLong() val result = when (operator) { "+" -> (worryLevel) + (operandInt) else -> (worryLevel) * (operandInt) } return result } fun main() { val monkeys = mutableListOf<Monkey>() readInput("input11") .chunked(7) .forEach { monkeys.add(readMonkey(it.toMutableList())) bigModulus *= monkeys.last().test } for (i in 0..9999) { monkeys.forEach { monkey -> monkey.items.forEach { val worryLevel = worryLevelCalculator(it, monkey.operator, monkey.operand) if ((worryLevel % monkey.test).toInt() == 0) monkeys[monkey.passAction].items.add((worryLevel % bigModulus)) else monkeys[monkey.failAction].items.add(worryLevel % bigModulus) monkey.numInspected += 1 } monkey.items.clear() } monkeys.forEach { println("src.Monkey number: ${it.id} \nInspected ${it.numInspected} items") } } monkeys.map { it.numInspected } .sorted() .takeLast(2) .reduce { acc, i -> acc * i } .let { println(it) } }
0
Kotlin
0
1
25b287d90d70951093391e7dcd148ab5174a6fbc
2,793
AoC
Apache License 2.0
src/aoc2023/Day07.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2023 import readInput fun main() { fun isFiveOfAKind(hand: String): Boolean { val grouped = hand.groupBy { it }.mapValues { it.value.size } return grouped.size == 1 } fun isFiveOfAKindWithJoker(hand: String): Boolean { if (isFiveOfAKind(hand)) return true val grouped = hand.groupBy { it }.mapValues { it.value.size } return grouped.contains('J') && grouped.size == 2 } fun isFourOfAKind(hand: String): Boolean { val grouped = hand.groupBy { it }.mapValues { it.value.size } return grouped.size == 2 && (grouped[hand[0]] == 4 || grouped[hand[0]] == 1) } fun isFourOfAKindWithJoker(hand: String): Boolean { if (isFourOfAKind(hand)) return true val grouped = hand.groupBy { it }.mapValues { it.value.size } if (grouped.contains('J')) { val jokers = grouped['J']!! for ((char, count) in grouped) { if (char != 'J' && count + jokers >= 4) { return true } } } return false } fun isFullHouse(hand: String): Boolean { val grouped = hand.groupBy { it }.mapValues { it.value.size } return grouped.size == 2 && (grouped[hand[0]] == 2 || grouped[hand[0]] == 3) } fun isFullHouseWithJoker(hand: String): Boolean { if (isFullHouse(hand)) return true val grouped = hand.groupBy { it }.mapValues { it.value.size } if (grouped.contains('J')) { val jokers = grouped['J']!! if (jokers >= 3) return true if (jokers == 2) return grouped.size - 1 < 3 if (jokers == 1) { if (grouped.size - 1 == 2) return true } } return false } fun isThreeOfAKind(hand: String): Boolean { val grouped = hand.groupBy { it }.mapValues { it.value.size } return grouped.size == 3 && (grouped[hand[0]] == 3 || grouped[hand[1]] == 3 || grouped[hand[2]] == 3) } fun isThreeOfAKindWithJoker(hand: String): Boolean { if (isThreeOfAKind(hand)) return true val grouped = hand.groupBy { it }.mapValues { it.value.size } if (grouped.contains('J')) { val jokers = grouped['J']!! if (jokers >= 2) return true if (grouped.values.contains(2)) return true } return false } fun isTwoPair(hand: String): Boolean { val grouped = hand.groupBy { it }.mapValues { it.value.size } return grouped.size == 3 && (grouped[hand[0]] != 3 || grouped[hand[1]] != 3 || grouped[hand[2]] != 3) } fun isTwoPairWithJoker(hand: String): Boolean { if (isTwoPair(hand)) return true val grouped = hand.groupBy { it }.mapValues { it.value.size } if (grouped.contains('J')) { val jokers = grouped['J']!! if (jokers > 1) return true if (grouped.values.contains(2)) return true } return false } fun isOnePair(hand: String): Boolean { val grouped = hand.groupBy { it }.mapValues { it.value.size } return grouped.size == 4 } fun isOnePairWithJoker(hand: String): Boolean { if (isOnePair(hand)) return true return hand.contains('J') } fun rank(hand: String): Int { return if (isFiveOfAKind(hand)) 7 else if (isFourOfAKind(hand)) 6 else if (isFullHouse(hand)) 5 else if (isThreeOfAKind(hand)) 4 else if (isTwoPair(hand)) 3 else if (isOnePair(hand)) 2 else 1 } fun rankWithJoker(hand: String): Int { return if (isFiveOfAKindWithJoker(hand)) 7 else if (isFourOfAKindWithJoker(hand)) 6 else if (isFullHouseWithJoker(hand)) 5 else if (isThreeOfAKindWithJoker(hand)) 4 else if (isTwoPairWithJoker(hand)) 3 else if (isOnePairWithJoker(hand)) 2 else 1 } val cardStrength = mapOf( 'A' to 14, 'K' to 13, 'Q' to 12, 'J' to 11, 'T' to 10, '9' to 9, '8' to 8, '7' to 7, '6' to 6, '5' to 5, '4' to 4, '3' to 3, '2' to 2 ) fun compareSameType(hand1: String, hand2: String): Int { return if (hand1[0] != hand2[0]) (cardStrength[hand1[0]]!! - cardStrength[hand2[0]]!!) else if (hand1[1] != hand2[1]) (cardStrength[hand1[1]]!! - cardStrength[hand2[1]]!!) else if (hand1[2] != hand2[2]) (cardStrength[hand1[2]]!! - cardStrength[hand2[2]]!!) else if (hand1[3] != hand2[3]) (cardStrength[hand1[3]]!! - cardStrength[hand2[3]]!!) else if (hand1[4] != hand2[4]) (cardStrength[hand1[4]]!! - cardStrength[hand2[4]]!!) else 0 } val cardStrengthWithJoker = mapOf( 'A' to 14, 'K' to 13, 'Q' to 12, 'J' to 1, 'T' to 10, '9' to 9, '8' to 8, '7' to 7, '6' to 6, '5' to 5, '4' to 4, '3' to 3, '2' to 2 ) fun compareSameTypeWithJoker(hand1: String, hand2: String): Int { return if (hand1[0] != hand2[0]) (cardStrengthWithJoker[hand1[0]]!! - cardStrengthWithJoker[hand2[0]]!!) else if (hand1[1] != hand2[1]) (cardStrengthWithJoker[hand1[1]]!! - cardStrengthWithJoker[hand2[1]]!!) else if (hand1[2] != hand2[2]) (cardStrengthWithJoker[hand1[2]]!! - cardStrengthWithJoker[hand2[2]]!!) else if (hand1[3] != hand2[3]) (cardStrengthWithJoker[hand1[3]]!! - cardStrengthWithJoker[hand2[3]]!!) else if (hand1[4] != hand2[4]) (cardStrengthWithJoker[hand1[4]]!! - cardStrengthWithJoker[hand2[4]]!!) else 0 } fun compare(hand1: String, hand2: String): Int { val rank1 = rank(hand1) val rank2 = rank(hand2) if (rank1 != rank2) return rank1 - rank2 return compareSameType(hand1, hand2) } fun compareWithJoker(hand1: String, hand2: String): Int { val rank1 = rankWithJoker(hand1) val rank2 = rankWithJoker(hand2) if (rank1 != rank2) return rank1 - rank2 return compareSameTypeWithJoker(hand1, hand2) } fun part1(hands: List<String>): Long { val sorted = hands.sortedWith { hand1, hand2 -> compare(hand1.substring(0, 5), hand2.substring(0, 5)) } var total = 0L for ((index, hand) in sorted.withIndex()) { total += (index + 1) * hand.substring(6).trim().toInt() } return total } fun part2(hands: List<String>): Long { val sorted = hands.sortedWith { hand1, hand2 -> compareWithJoker(hand1.substring(0, 5), hand2.substring(0, 5)) } var total = 0L for ((index, hand) in sorted.withIndex()) { total += (index + 1) * hand.substring(6).trim().toInt() } return total } println(part1(readInput("aoc2023/Day07_test"))) println(part1(readInput("aoc2023/Day07"))) println(part2(readInput("aoc2023/Day07_test"))) println(part2(readInput("aoc2023/Day07"))) }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
6,864
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/solutions/Main.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions import solutions.day01.Day1 import solutions.day02.Day2 import solutions.day03.Day3 import solutions.day04.Day4 import solutions.day05.Day5 import solutions.day06.Day6 import solutions.day07.Day7 import solutions.day08.Day8 import solutions.day09.Day9 import solutions.day10.Day10 import solutions.day11.Day11 import solutions.day12.Day12 import solutions.day13.Day13 import solutions.day14.Day14 import solutions.day15.Day15 import solutions.day16.Day16 import solutions.day18.Day18 import solutions.day20.Day20 import solutions.day21.Day21 import solutions.day22.Day22 import solutions.day23.Day23 import solutions.day24.Day24 import solutions.day25.Day25 import utils.readFile import kotlin.system.measureNanoTime enum class Days { Day01, Day02, Day03, Day04, Day05, Day06, Day07, Day08, Day09, Day10, Day11, Day12, Day13, Day14, Day15, Day16, Day18, Day20, Day22, Day21, Day23, Day24, Day25 } fun Long.toSeconds(): Double = this / (10e8) fun Long.toMilliseconds(): Double = this / (10e5) fun main(args: Array<String>) { val time = measureNanoTime { val partTwo = false val day = Days.Day16 val input = getInput(day) val solver = when (day) { Days.Day01 -> Day1() Days.Day02 -> Day2() Days.Day03 -> Day3() Days.Day04 -> Day4() Days.Day05 -> Day5() Days.Day06 -> Day6() Days.Day07 -> Day7() Days.Day08 -> Day8() Days.Day09 -> Day9() Days.Day10 -> Day10() Days.Day11 -> Day11() Days.Day12 -> Day12() Days.Day13 -> Day13() Days.Day14 -> Day14() Days.Day15 -> Day15() Days.Day16 -> Day16() Days.Day18 -> Day18() Days.Day20 -> Day20() Days.Day21 -> Day21() Days.Day22 -> Day22() Days.Day23 -> Day23() Days.Day24 -> Day24() Days.Day25 -> Day25() } printAnswer(day.name, solver.solve(input, partTwo)) } println("Took ${time.toSeconds()} seconds") println("Took ${time.toMilliseconds()} milliseconds") } fun getInput(day: Days): List<String> { val solutions = "src/main/kotlin/solutions" return readFile("$solutions/${day.name.toLowerCase()}/input") } fun printAnswer(msg: String, answer: String) { println("$msg: $answer") }
0
Kotlin
0
2
975695cc49f19a42c0407f41355abbfe0cb3cc59
2,497
Advent-of-Code-2022
MIT License
src/Day02.kt
yalematta
572,668,122
false
{"Kotlin": 8442}
fun main() { fun getRounds(input: List<String>): List<List<CharArray>> { return input.windowed(1).map { round -> round.map { it.toCharArray() } } } fun part1(input: List<String>): Int { var score = 0 val rounds = getRounds(input) for (line in rounds.indices) { rounds[line].forEach { score += when (it[0]) { 'A' -> when (it[2]) { 'X' -> 1 + 3 'Y' -> 2 + 6 'Z' -> 3 + 0 else -> 0 } 'B' -> when (it[2]) { 'X' -> 1 + 0 'Y' -> 2 + 3 'Z' -> 3 + 6 else -> 0 } 'C' -> when (it[2]) { 'X' -> 1 + 6 'Y' -> 2 + 0 'Z' -> 3 + 3 else -> 0 } else -> 0 } } } return score } fun part2(input: List<String>): Int { var score = 0 val rounds = getRounds(input) for (line in rounds.indices) { rounds[line].forEach { score += when (it[0]) { 'A' -> when (it[2]) { 'X' -> 3 //lose 'Y' -> 4 //draw 'Z' -> 8 //win else -> 0 } 'B' -> when (it[2]) { 'X' -> 1 'Y' -> 5 'Z' -> 9 else -> 0 } 'C' -> when (it[2]) { 'X' -> 2 'Y' -> 6 'Z' -> 7 else -> 0 } else -> 0 } } } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2b43681cc2bd02e4838b7ad1ba04ff73c0422a73
2,361
advent-of-code-2022
Apache License 2.0
src/main/kotlin/mytechtoday/aoc/year2022/Day2.kt
mytechtoday
572,836,399
false
{"Kotlin": 15268, "Java": 1717}
package mytechtoday.aoc.year2022 import mytechtoday.aoc.util.readInput fun main() { fun getValue(inputChar: Char):Int = when (inputChar) { 'X' -> 1 'Y' -> 2 else -> 3 } fun getValueProblem2(inputChar: String):Int = when (inputChar) { // Rock 1 , paper- 2, sessior 3 //x is loose //y is draw //z is win "AX"->3 //3+0 R - s "BX"->1 //1+0 P -r "CX"->2// S - p "AY"->4 //1+3 R - R "BY"->5 // P - P "CY"->6 // s -S "AZ"->8 // R - p "BZ"->9 // p - S "CZ"->7 //1+6 s ; R else -> 0 } fun getPoint(opponent: Char, own: Char):Int { var point =getValue(own) if((own=='X' && opponent=='A') ||(own=='Y' && opponent=='B') || (own=='Z' && opponent=='C')){ point+=3; } else if((own=='X' && opponent=='C') ||(own=='Y' && opponent=='A') || (own=='Z' && opponent=='B')) { point+=6; } return point; } fun part1(input: List<String>): Int { var totalPoint = 0; for(item in input){ var trim : CharArray= item.trim().toCharArray() totalPoint+=getPoint(trim[0],trim[2]) } return totalPoint; } fun part2(input: List<String>): Int { var totalPoint = 0; for(item in input){ var trim : CharArray= item.trim().toCharArray() totalPoint+=getValueProblem2(""+trim[0]+trim[2]) } return totalPoint; } val input = readInput(2022,"day2") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3f25cb010e6367af20acaa2906aff17a80f4e623
1,653
aoc2022
Apache License 2.0
src/Day09.kt
aaronbush
571,776,335
false
{"Kotlin": 34359}
import java.lang.Integer.max import kotlin.math.abs fun main() { val moveFuns = mapOf( "R" to fun(h: RopePoint) = h.copy(first = h.first + 1), "L" to fun(h: RopePoint) = h.copy(first = h.first - 1), "U" to fun(h: RopePoint) = h.copy(second = h.second + 1), "D" to fun(h: RopePoint) = h.copy(second = h.second - 1), ) fun part1(input: List<String>): Int { val startPoint = RopePoint(0, 0) var headAt = startPoint.copy() var tailAt = startPoint.copy() val tailPoints = mutableSetOf(startPoint) input.forEach { motion -> val (dir, len) = motion.split(" ", limit = 2) val f = moveFuns[dir]!! repeat(len.toInt()) { headAt = f(headAt) if (headAt - tailAt == 2) { tailAt = tailAt.advanceTo(headAt) tailPoints += tailAt } // println("tailPoints = ${tailPoints}") } } return tailPoints.size } fun part2(input: List<String>): Int { val startPoint = RopePoint(0, 0) val headAt = startPoint.copy() val pointLocations = (mutableListOf(headAt) + MutableList(9) { startPoint.copy() }).toMutableList() // 9-tails val tailPoints = mutableSetOf(startPoint) input.forEach { motion -> val (dir, len) = motion.split(" ", limit = 2) // println("dir = ${dir} / len = $len") val f = moveFuns[dir]!! repeat(len.toInt()) { val headPoint = f(pointLocations.first()) pointLocations[0] = headPoint // store updated head var pointToFollow = headPoint pointLocations.drop(1).forEachIndexed { n, tail -> // all tail points var newTailPosition = tail while (pointToFollow - newTailPosition > 1) { newTailPosition = tail.advanceTo(pointToFollow) // println("advancing ${n+1} to ${newTailPosition}") // moving the final tail -> update tail points along the way if (n + 1 == 9) { tailPoints += newTailPosition } } pointLocations[n + 1] = newTailPosition pointToFollow = pointLocations[n + 1] } } // println("nextLocations = ${pointLocations}") // println("tailPoints = ${tailPoints}") } return tailPoints.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test2") // check(part1(testInput) == 13) check(part2(testInput) == 36) val input = readInput("Day09") // println("p1: ${part1(input)}") println("p2: ${part2(input)}") // some 'tests' /* println(RopePoint(0, 2) - RopePoint(0, 0)) // 2 println(RopePoint(2, 0) - RopePoint(0, 0)) // 2 println(RopePoint(2, 1) - RopePoint(0, 0)) // 2 println(RopePoint(1, 2) - RopePoint(0, 0)) // 2 println(RopePoint(1, 1) - RopePoint(0, 0)) // 1 println(RopePoint(0, 0) - RopePoint(0, 0)) // 0 println(RopePoint(2, 0) - RopePoint(0, 0)) // 2 println(RopePoint(0, 0) - RopePoint(2, 2)) // 2 */ /* println(RopePoint(0, 0).advanceTo(RopePoint(0, 2))) // 0,1 println(RopePoint(0, 0).advanceTo(RopePoint(0, -2))) // 0,-1 println(RopePoint(0, 0).advanceTo(RopePoint(2, 0))) // 1,0 println(RopePoint(0, 0).advanceTo(RopePoint(-2, 0))) // -1,0 println(RopePoint(0, 0).advanceTo(RopePoint(1, 2))) // 1,1 println(RopePoint(0, 0).advanceTo(RopePoint(1, -2))) // 1,-1 println(RopePoint(0, 0).advanceTo(RopePoint(-1, -2))) // -1,-1 println(RopePoint(0, 0).advanceTo(RopePoint(-1, 2))) // -1,1 */ } typealias RopePoint = Pair<Int, Int> // what new coordinate should 'this' advance to get close to the other fun RopePoint.advanceTo(other: RopePoint): RopePoint { // TODO: what if locations are equal? if (this == other) { return this } val delta1 = other.first - first val delta2 = other.second - second return if (delta1 == 0) { // mov v if (delta2 > 0) { RopePoint(first, second + 1) } else { RopePoint(first, second - 1) } } else if (delta2 == 0) { // move h if (delta1 > 0) { RopePoint(first + 1, second) } else { RopePoint(first - 1, second) } } else { if (delta1 > 0 && delta2 > 0) { // add one to each RopePoint(first + 1, second + 1) } else if (delta1 > 0) { // && delta2 < 0) { // add to delta1 // sub delta2 RopePoint(first + 1, second - 1) } else if (delta2 < 0) { // && delta2 < 0) { // sub from both RopePoint(first - 1, second - 1) } else { // sub delta1 // add delta2 RopePoint(first - 1, second + 1) } } } operator fun RopePoint.minus(other: RopePoint): Int { // this is a bit weird val delta1 = abs(this.first - other.first) val delta2 = abs(this.second - other.second) val diff = if (delta1 == 0 || delta2 == 0) { // same row or col max(delta1, delta2) } else if (delta1 + delta2 in 3..4)// diag 2 else delta1 + delta2 - 1 check(diff in 0..2) { "$diff ($delta1, $delta2) outside range for $this - $other" } return diff }
0
Kotlin
0
0
d76106244dc7894967cb8ded52387bc4fcadbcde
5,679
aoc-2022-kotlin
Apache License 2.0
src/test/kotlin/year2015/Day15.kt
abelkov
47,995,527
false
{"Kotlin": 48425}
package year2015 import kotlin.math.max import kotlin.test.* private data class Ingredient( val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int ) private const val MAX_SPOONS = 100 class Day15 { @Test fun part1() { // Sugar: capacity 3, durability 0, flavor 0, texture -3, calories 2 val regex = """(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""".toRegex() val ingredients = mutableListOf<Ingredient>() for (line in readInput("year2015/Day15.txt").lines()) { val matchResult = regex.matchEntire(line) val (_, capacity, durability, flavor, texture, calories) = matchResult!!.groupValues.drop(1) ingredients += Ingredient(capacity.toInt(), durability.toInt(), flavor.toInt(), texture.toInt(), calories.toInt()) } val bestScore = computeBestScore(ingredients) assertEquals(222870, bestScore) } private fun computeBestScore(ingredients: List<Ingredient>): Int { require(ingredients.size == 4) var bestScore = 0 for (a in 0..MAX_SPOONS) { for (b in 0..MAX_SPOONS) { for (c in 0..MAX_SPOONS) { for (d in 0..MAX_SPOONS) { if (a + b + c + d > MAX_SPOONS) break val capacity = ingredients[0].capacity * a + ingredients[1].capacity * b + ingredients[2].capacity * c + ingredients[3].capacity * d val durability = ingredients[0].durability * a + ingredients[1].durability * b + ingredients[2].durability * c + ingredients[3].durability * d val flavor = ingredients[0].flavor * a + ingredients[1].flavor * b + ingredients[2].flavor * c + ingredients[3].flavor * d val texture = ingredients[0].texture * a + ingredients[1].texture * b + ingredients[2].texture * c + ingredients[3].texture * d val score = capacity.coerceAtLeast(0) * durability.coerceAtLeast(0) * flavor.coerceAtLeast(0) * texture.coerceAtLeast(0) bestScore = max(bestScore, score) } } } } return bestScore } @Test fun part2() { // Sugar: capacity 3, durability 0, flavor 0, texture -3, calories 2 val regex = """(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""".toRegex() val ingredients = mutableListOf<Ingredient>() for (line in readInput("year2015/Day15.txt").lines()) { val matchResult = regex.matchEntire(line) val (_, capacity, durability, flavor, texture, calories) = matchResult!!.groupValues.drop(1) ingredients += Ingredient(capacity.toInt(), durability.toInt(), flavor.toInt(), texture.toInt(), calories.toInt()) } val bestScore = computeBestScore2(ingredients) assertEquals(117936, bestScore) } private fun computeBestScore2(ingredients: List<Ingredient>): Int { require(ingredients.size == 4) var bestScore = 0 for (a in 0..MAX_SPOONS) { for (b in 0..MAX_SPOONS) { for (c in 0..MAX_SPOONS) { for (d in 0..MAX_SPOONS) { if (a + b + c + d > MAX_SPOONS) break val calories = ingredients[0].calories * a + ingredients[1].calories * b + ingredients[2].calories * c + ingredients[3].calories * d if (calories != 500) continue val capacity = ingredients[0].capacity * a + ingredients[1].capacity * b + ingredients[2].capacity * c + ingredients[3].capacity * d val durability = ingredients[0].durability * a + ingredients[1].durability * b + ingredients[2].durability * c + ingredients[3].durability * d val flavor = ingredients[0].flavor * a + ingredients[1].flavor * b + ingredients[2].flavor * c + ingredients[3].flavor * d val texture = ingredients[0].texture * a + ingredients[1].texture * b + ingredients[2].texture * c + ingredients[3].texture * d val score = capacity.coerceAtLeast(0) * durability.coerceAtLeast(0) * flavor.coerceAtLeast(0) * texture.coerceAtLeast(0) bestScore = max(bestScore, score) } } } } return bestScore } } private operator fun <E> List<E>.component6(): E = this[5]
0
Kotlin
0
0
0e4b827a742322f42c2015ae49ebc976e2ef0aa8
5,671
advent-of-code
MIT License
year2023/src/main/kotlin/net/olegg/aoc/year2023/day4/Day4.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2023.day4 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.parseInts import net.olegg.aoc.utils.parseLongs import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2023.DayOf2023 /** * See [Year 2023, Day 4](https://adventofcode.com/2023/day/4) */ object Day4 : DayOf2023(4) { private val GAME_PATTERN = "Game \\d+: ".toRegex() override fun first(): Any? { return lines .asSequence() .map { line -> line.replace(GAME_PATTERN, "") } .map { it.split("|").toPair() } .map { it.first.parseInts(" ") to it.second.parseInts(" ") } .map { it.second.count { my -> my in it.first } } .sumOf { if (it == 0) 0 else (1 shl (it - 1)) } } override fun second(): Any? { val cards = lines .map { line -> line.replace(GAME_PATTERN, "") } .map { it.split("|").toPair() } .map { it.first.parseLongs(" ") to it.second.parseLongs(" ") } .map { (good, mine) -> mine.count { my -> my in good } } return cards.foldIndexed(List(cards.size) { 1L }) { index, acc, card -> val count = acc[index] val add = List(cards.size) { if (it in (index + 1..index + card)) count else 0 } acc.zip(add, Long::plus) }.sum() } } fun main() = SomeDay.mainify(Day4)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,290
adventofcode
MIT License
src/Day08.kt
er453r
572,440,270
false
{"Kotlin": 69456}
fun main() { fun part1(input: List<String>): Int { val grid = Grid(input.map { it.toCharArray().asList().map(Char::digitToInt) }) val outside = 2 * grid.width + 2 * (grid.height - 2) var otherVisible = 0 for (x in 1 until grid.width - 1) for (y in 1 until grid.height - 1) { var visible = false val cell = grid.get(x, y) dirs@ for (direction in Vector2d.DIRECTIONS) { var neighbour = cell.position + direction while (neighbour in grid) { if (grid[neighbour].value >= cell.value) // not visible - check other directions continue@dirs neighbour += direction if (neighbour !in grid) { // we reached the end - it is visible! visible = true break@dirs } } } if (visible) otherVisible += 1 } return outside + otherVisible } fun part2(input: List<String>): Int { val grid = Grid(input.map { it.toCharArray().asList().map(Char::digitToInt) }) var bestScore = 0 for (x in 1 until grid.width - 1) for (y in 1 until grid.height - 1) { val cell = grid.get(x, y) val score = Vector2d.DIRECTIONS.map { direction -> var dirScore = 0 var neighbour = cell.position + direction while (neighbour in grid) { dirScore += 1 if (grid[neighbour].value >= cell.value) break neighbour += direction } dirScore }.reduce(Int::times) if (score > bestScore) bestScore = score } return bestScore } test( day = 8, testTarget1 = 21, testTarget2 = 8, part1 = ::part1, part2 = ::part2, ) }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
2,181
aoc2022
Apache License 2.0
src/main/kotlin/leet/1-array.kt
dzca
581,929,762
false
{"Kotlin": 75573}
package leet /** * - hard * Given two strings s and t of lengths m and n respectively, * return the minimum window substring of s such that * every character in t (including duplicates) is included in the window. * If there is no such substring, return the empty string "". */ fun minWindow(a: String, b: String): String{ return a } fun max(a: Int, b: Int): Int { return if(a>b) a else b } /** * - easy * hash map impl */ fun longestSubStr1(s: String): Int { val t = HashMap<Char, Int>() var m = 0 var l = 0 var r = 0 var n = s.length if(n==0) return 0 while(r < n && l <= r){ if(t.contains(s[r])){ t.remove(s[l]) l +=1 } else { t.put(s[r], r) m = max(m, r-l + 1) r +=1 } } return m } fun contains(s: String, c: Char, l:Int, r:Int): Boolean{ for(i in l..r){ if(s[i] == c) return true } return false } /** * tow pointer impl */ fun longestSubStr2(s: String): Int { var m = 0 var l = 0 var r = 0 var n = s.length if(n <=0) return n while(r in l until n){ if(contains(s, s[r], l, r-1)){ l +=1 } else { m = max(m, r-l + 1) r +=1 } } return m } /** * - medium * Given an array of positive integers nums and a positive integer * target, return the minimal length of a subarray whose sum is * greater than or equal to target. If there is no such subarray, * return 0 instead. * * Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 * Explanation: The subarray [4,3] has the minimal length under the problem constraint. * * Input: target = 4, nums = [1,4,4] => 1 * Input: target = 11, nums = [1,1,1,1,1,1,1,1] => 0 */ fun min(a: Int, b: Int):Int{ return if(a>b) b else a } /** * v1 - 2 pointer */ fun minSubArrayLen(k: Int, a: IntArray): Int { val n = a.size var m = 0 if(n == 1) return if(a[0]>=k) 1 else 0 var l = 0 var r = 0 var s = a[0] while(l < n){ if(s >= k){ if(m > 0){ m = min(m, r-l+1) } else { m = r-l+1 } s=s-a[l] l+=1 } else { if(r == n-1 && s < k){ return m } else { r+=1 s+=a[r] } } } return m } /** * answer */ fun minLen(k:Int, a: IntArray):Int{ var m = 0 val n = a.size var l = 0 var s = 0 for(i in 0 until n){ s += a[i] while(s >= k){ if(m > 0){ m = min(m, i-l+1) } else { m = i-l+1 } s -= a[l] l+=1 } } return m }
0
Kotlin
0
0
b1e7d1cb739e21ed7e8b7484d6efcd576857830f
2,809
kotlin-algrithm
MIT License
src/main/day07/Day07.kt
rolf-rosenbaum
543,501,223
false
{"Kotlin": 17211}
package day07 import readInput typealias Steps = MutableMap<String, MutableList<String>> fun part1(input: List<String>): String { val steps = parseSteps(input) val done = mutableListOf<String>() while (true) { val nextStep = steps.filter { (_, pres) -> pres.isEmpty() }.keys.minOfOrNull { it } ?: return done.joinToString("") steps.execute(nextStep) done.add(nextStep) } } private fun parseSteps(input: List<String>): MutableMap<String, MutableList<String>> { val steps = mutableMapOf<String, MutableList<String>>() input.forEach { val foo = it.split(" ").drop(1) val pre = foo.first() val step = foo.dropLast(2).last() if (steps[step] == null) { steps[step] = mutableListOf(pre) } else { steps[step]!!.add(pre) } if (steps[pre] == null) { steps[pre] = mutableListOf() } } return steps } fun Steps.execute(step: String) { forEach { (_, pres) -> pres.remove(step) } if (this[step]?.isEmpty() != false) this.remove(step) } fun part2(input: List<String>): Int { return 0 } fun Char.executionTime() = 60 + ('A' - this + 1) fun main() { val input = readInput("main/day07/Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dfd7c57afa91dac42362683291c20e0c2784e38e
1,345
aoc-2018
Apache License 2.0
src/Day02.kt
makobernal
573,037,099
false
{"Kotlin": 16467}
enum class OpponentChoice(val code: String) { Rock("A"), Paper("B"), Scissors("C"); companion object { infix fun from(value: String): OpponentChoice = OpponentChoice.values().firstOrNull { it.code == value }!! } } enum class ResponseChoice(val code: String) { Rock("X"), Paper("Y"), Scissors("Z"); companion object { infix fun from(value: String): ResponseChoice = ResponseChoice.values().firstOrNull { it.code == value }!! } } enum class ExpectedAction(val code: String) { Lose("X"), Draw("Y"), Win("Z"); companion object { infix fun from(value: String): ExpectedAction = ExpectedAction.values().firstOrNull { it.code == value }!! } } typealias Round = Pair<OpponentChoice, ResponseChoice> typealias Strategy = Pair<OpponentChoice, ExpectedAction> fun main() { fun inputSplitted(input: List<String>) = input.map { it.split(" ") } fun transformInputPart1(input: List<String>): List<Round> { return inputSplitted(input).map { Pair(OpponentChoice.from(it[0]), ResponseChoice.from(it[1])) } } fun transformInputPart2(input: List<String>): List<Strategy> { return inputSplitted(input).map { Pair(OpponentChoice.from(it[0]), ExpectedAction.from(it[1])) } } fun shapeScore(choice: ResponseChoice) = when (choice) { ResponseChoice.Rock -> 1 ResponseChoice.Paper -> 2 ResponseChoice.Scissors -> 3 } val youLose = 0 val youDraw = 3 val youWin = 6 fun outcomeScore(round: Round): Int { return when (round.first) { OpponentChoice.Rock -> when (round.second) { ResponseChoice.Rock -> youDraw ResponseChoice.Paper -> youWin ResponseChoice.Scissors -> youLose } OpponentChoice.Paper -> when (round.second) { ResponseChoice.Rock -> youLose ResponseChoice.Paper -> youDraw ResponseChoice.Scissors -> youWin } OpponentChoice.Scissors -> when (round.second) { ResponseChoice.Rock -> youWin ResponseChoice.Paper -> youLose ResponseChoice.Scissors -> youDraw } } } fun singleRoundScorePart1(round: Round): Int = outcomeScore(round) + shapeScore(round.second) fun part1(input: List<String>): Int { val transformed = transformInputPart1(input) val allScores = transformed.map { singleRoundScorePart1(it) } return allScores.sum() } fun playRound(strategy: Pair<OpponentChoice, ExpectedAction>): Pair<OpponentChoice, ResponseChoice> { val choice = when (strategy.second) { ExpectedAction.Lose -> when (strategy.first) { OpponentChoice.Rock -> ResponseChoice.Scissors OpponentChoice.Paper -> ResponseChoice.Rock OpponentChoice.Scissors -> ResponseChoice.Paper } ExpectedAction.Draw -> when (strategy.first) { OpponentChoice.Rock -> ResponseChoice.Rock OpponentChoice.Paper -> ResponseChoice.Paper OpponentChoice.Scissors -> ResponseChoice.Scissors } ExpectedAction.Win -> when (strategy.first) { OpponentChoice.Rock -> ResponseChoice.Paper OpponentChoice.Paper -> ResponseChoice.Scissors OpponentChoice.Scissors -> ResponseChoice.Rock } } return Pair(strategy.first, choice) } fun part2(input: List<String>): Int { val strategies = transformInputPart2(input) val rounds = strategies.map { playRound(it) } val allScores = rounds.map { singleRoundScorePart1(it) } return allScores.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") val testResult = part1(testInput) val testResult2 = part2(testInput) check(testResult == 15) { "wrong input loco $testResult is not 15" } check(testResult2 == 12) { "wrong input loco $testResult is not 12" } val input = readInput("Day02") val result1 = part1(input) val result2 = part2(input) println("solution for your input, part 1 = $result1") println("solution for your input, part 2 = $result2") }
0
Kotlin
0
0
63841809f7932901e97465b2dcceb7cec10773b9
4,371
kotlin-advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day05.kt
N-Silbernagel
573,145,327
false
{"Kotlin": 118156}
import java.util.* fun main() { fun parseCrates( stackChunks: List<String>, stacks: TreeMap<Int, Stack<Char>> ): Boolean { for ((index, stackChunk) in stackChunks.withIndex()) { if (stackChunk.trim() == "1") { return true } if (stackChunk.isBlank()) { continue } if (!stacks.containsKey(index + 1)) { stacks[index + 1] = Stack<Char>() } val stackChar = stackChunk.trim('[', ']', ' ')[0] stacks[index + 1]?.add(0, stackChar) } return false } fun part1(input: List<String>): String { var isInstructionsPart = false val stacks = TreeMap<Int, Stack<Char>>() for (line in input) { if (line.isBlank()) { continue } val stackChunks = line.chunked(4) if (!isInstructionsPart) { isInstructionsPart = parseCrates(stackChunks, stacks) } else { val instructionRegex = Regex("move (\\d+) from (\\d+) to (\\d+)") val match = instructionRegex.find(line) ?: continue val crateCount = match.groupValues[1].toInt() val originStack = match.groupValues[2].toInt() val destinationStack = match.groupValues[3].toInt() for (i in 1..crateCount) { val poppedCrate = stacks[originStack]!!.pop() stacks[destinationStack]!!.add(poppedCrate) } } } var answer = "" for (stack in stacks.values) { answer += stack.pop() } return answer } fun part2(input: List<String>): String { var isInstructionsPart = false val stacks = TreeMap<Int, Stack<Char>>() for (line in input) { if (line.isBlank()) { continue } val stackChunks = line.chunked(4) if (!isInstructionsPart) { isInstructionsPart = parseCrates(stackChunks, stacks) } else { val instructionRegex = Regex("move (\\d+) from (\\d+) to (\\d+)") val match = instructionRegex.find(line) ?: continue val crateCount = match.groupValues[1].toInt() val originStackIndex = match.groupValues[2].toInt() val destinationStackIndex = match.groupValues[3].toInt() val crates = Stack<Char>() val originStack = stacks[originStackIndex]!! for (i in 1..crateCount) { crates.add(0, originStack.pop()) } stacks[destinationStackIndex]!!.addAll(crates) } } var answer = "" for (stack in stacks.values) { answer += stack.pop() } return answer } val input = readFileAsList("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b0d61ba950a4278a69ac1751d33bdc1263233d81
3,066
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-10.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import com.github.ferinagy.adventOfCode.toBooleanGrid fun main() { val input = readInputLines(2022, "10-input") val testInput1 = readInputLines(2022, "10-test1") println("Part1:") part1(testInput1).println() part1(input).println() println() println("Part2:") part2(testInput1).println() part2(input).println() } private fun part1(input: List<String>): Int { val signals = calculateCycles(input) return (0 until 6).sumOf { signals.signalStrength(20 + it * 40) } } private fun part2(input: List<String>): String { val signals = calculateCycles(input) val pixels = signals.drop(1).mapIndexed { index, pos -> (index % 40) in pos - 1..pos + 1 } return pixels.windowed(40, 40).toBooleanGrid().toString() // ZFBFHGUP } private fun calculateCycles(input: List<String>): MutableList<Int> { val signals = mutableListOf(1) var x = 1 input.forEach { line -> val parts = line.split(' ') when (parts[0]) { "addx" -> { signals += x signals += x x += parts[1].toInt() } "noop" -> { signals += x } } } return signals } private fun List<Int>.signalStrength(cycle: Int): Int = cycle * get(cycle)
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,452
advent-of-code
MIT License
src/main/kotlin/kt/kotlinalgs/app/sorting/RadixSort.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.sorting import kotlin.math.pow println("test") val array1 = intArrayOf(2, 6, 4) val array2 = intArrayOf(15, 13, 1, 10, 17, 0, 2, 2, 100) RadixSort().sort(array1) RadixSort().sort(array2) // runtime: O(D*(N + B)), for finite ranges where N = array size, B = base (decimal=10), D = # of 10's places (=calls to counting sort subroutine) // space: O(N + K), aux arrays counts (K) + output (N) // stable when 3rd pass of counting sort backwards println(array1.map { it }) println(array2.map { it }) // https://www.geeksforgeeks.org/radix-sort/ // https://www.geeksforgeeks.org/counting-sort/ class RadixSort { fun sort(array: IntArray) { // (2,6,10) if (array.size <= 1) return var maxValue = array.max() ?: return //maxOrNull() ?: return var maxLen = 0 // 2 while (maxValue > 0) { // 6 maxLen++ maxValue /= 10 } // sort from LS to MS digits for (digitPlace in 1 until maxLen + 1) { // 1,2 countingSort(array, digitPlace) } } private fun countingSort(array: IntArray, digitPlace: Int) { // 1 val range = 10 // base 10, decimal system // e.g. 10^(1) = 10, 10^(2) = 100 val exponent = range.toDouble().pow(digitPlace - 1).toInt() // 1 // 1. pass: Calculate counts val counts = IntArray(range) // 0 1 2 3 4 5 6 7 8 9 // 1 0 1 0 0 0 1 0 0 0 array.forEach { // 2,6,10 // (132 / 10 * (digitPlace - 1)) % 10 // (132/10^0) % 10 = 2 // (132/10^1) % 10 = 3 // (132/10^2) % 10 = 1 val index = (it / exponent) % range //2 counts[index]++ } // 2. pass: Cumulate counts // 0 1 2 3 4 5 6 7 8 9 index // 1 0 1 0 0 0 1 0 0 0 ori // 1 1 2 2 2 2 3 3 3 3 cum. for (index in 1 until counts.size) { counts[index] += counts[index - 1] } // 3. pass: put back in original array (count = index!) // stable, if we iterate backwards (because we are decreasing indices): // https://stackoverflow.com/questions/2572195/how-is-counting-sort-a-stable-sort val output = IntArray(array.size) // (10,2,6) // array: 2,6,10 // counts: // 0 1 2 3 4 5 6 7 8 9 index // 1 1 2 2 2 2 3 3 3 3 orig. cum. // 0 1 1 2 2 2 2 3 3 3 decr. for (index in array.size - 1 downTo 0) { // 2,1,0 val value = (array[index] / exponent) % range // 2 val finalIndex = counts[value] - 1 //1 output[finalIndex] = array[index] counts[value]-- } output.forEachIndexed { index, value -> array[index] = value } } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
2,772
KotlinAlgs
MIT License
src/main/kotlin/day09/Day09.kt
dustinconrad
572,737,903
false
{"Kotlin": 100547}
package day09 import geometry.Coord import geometry.distance import geometry.plus import readResourceAsBufferedReader import kotlin.math.sign fun main() { println("part 1: ${part1(readResourceAsBufferedReader("9_1.txt").readLines())}") println("part 2: ${part2(readResourceAsBufferedReader("9_1.txt").readLines())}") } fun part1(input: List<String>): Int { val instructions = input.map { Dir.parse(it) } val rp = RopeBridge() instructions.forEach { rp.move(it) } return rp.tailSeen.size } fun part2(input: List<String>): Int { val instructions = input.map { Dir.parse(it) } val rp = RopeBridge(10) instructions.forEach { rp.move(it) } return rp.tailSeen.size } sealed class Dir(private val vector: Coord) { fun move(input: Coord): Coord { return input + vector } abstract fun steps(): List<Dir> class Right(private val magnitude: Int) : Dir(0 to magnitude) { override fun steps(): List<Dir> { return List(magnitude) { Right(1) } } } class Left(private val magnitude: Int) : Dir(0 to -magnitude) { override fun steps(): List<Dir> { return List(magnitude) { Left(1) } } } class Up(private val magnitude: Int) : Dir(-magnitude to 0) { override fun steps(): List<Dir> { return List(magnitude) { Up(1) } } } class Down(private val magnitude: Int) : Dir(magnitude to 0) { override fun steps(): List<Dir> { return List(magnitude) { Down(1) } } } companion object { fun parse(line: String): Dir { val (d, m) = line.split(" ") return when(d) { "R" -> Right(m.toInt()) "L" -> Left(m.toInt()) "U" -> Up(m.toInt()) "D" -> Down(m.toInt()) else -> throw IllegalArgumentException("Invalid line: $line") } } } } class RopeBridge( size: Int ) { private val _tailSeen: MutableSet<Coord> = mutableSetOf(0 to 0) private val knots = Array(size) { 0 to 0 } val tailSeen: Set<Coord> = _tailSeen constructor(): this(2) fun move(dir: Dir) { for (step in dir.steps()) { var newHead = step.move(knots[0]) knots[0] = newHead for (i in 1 until knots.size) { val currTail = knots[i] val newTail = follow(newHead, currTail) if (newTail == currTail) { break } knots[i] = newTail newHead = newTail } _tailSeen.add(knots.last()) } } private fun follow(head: Coord, tail: Coord): Coord { val deltaY = head.first - tail.first val deltaX = head.second - tail.second val dist = (deltaY to deltaX).distance() val move = deltaY.sign to deltaX.sign return if (dist > 1.5) { tail + move } else { tail } } }
0
Kotlin
0
0
1dae6d2790d7605ac3643356b207b36a34ad38be
3,046
aoc-2022
Apache License 2.0
src/main/kotlin/com/staricka/adventofcode2023/days/Day18.kt
mathstar
719,656,133
false
{"Kotlin": 107115}
package com.staricka.adventofcode2023.days import com.staricka.adventofcode2023.days.DigInstruction.Companion.toDigInstruction import com.staricka.adventofcode2023.days.DigInstruction.Companion.toDigInstructionFromHex import com.staricka.adventofcode2023.framework.Day import com.staricka.adventofcode2023.util.Direction import kotlin.math.abs val digInstructionRegex = Regex("([LRUD]) ([0-9]+) \\(#([0-9a-f]+)\\)") data class DigInstruction(val direction: Direction, val steps: Int) { companion object { fun String.toDigInstruction(): DigInstruction { val match = digInstructionRegex.matchEntire(this) return DigInstruction( when(match!!.groups[1]!!.value) { "L" -> Direction.LEFT "R" -> Direction.RIGHT "U" -> Direction.UP "D" -> Direction.DOWN else -> throw Exception() }, match.groups[2]!!.value.toInt() ) } fun String.toDigInstructionFromHex(): DigInstruction { val hex = digInstructionRegex.matchEntire(this)!!.groups[3]!!.value return DigInstruction( when(hex[5]) { '0' -> Direction.RIGHT '1' -> Direction.DOWN '2' -> Direction.LEFT '3' -> Direction.UP else -> throw Exception() }, hex.substring(0, 5).toInt(16) ) } } } class Day18: Day { override fun part1(input: String): Long { val instructions = input.lines().filter { it.isNotBlank() }.map { it.toDigInstruction() } return calculateArea(instructions) } override fun part2(input: String): Long { val instructions = input.lines().filter { it.isNotBlank() }.map { it.toDigInstructionFromHex() } return calculateArea(instructions) } private fun calculateArea(instructions: List<DigInstruction>): Long { val x = ArrayList<Long>() val y = ArrayList<Long>() x += 0 y += 0 for (instruction in instructions) { when (instruction.direction) { Direction.UP -> { y += y.last() + instruction.steps; x += x.last() } Direction.DOWN -> { y += y.last() - instruction.steps; x += x.last() } Direction.LEFT -> { x += x.last() - instruction.steps; y += y.last() } Direction.RIGHT -> { x += x.last() + instruction.steps; y += y.last() } } } var area = 0L var boundary = 0L for (i in x.indices) { if (i == x.size - 1) break area += (x[i] * y[i + 1]) - (x[i + 1] * y[i]) boundary += if (x[i] == x[i + 1]) abs(y[i] - y[i + 1]) else abs(x[i] - x[i + 1]) } area = abs(area / 2) + boundary / 2 + 1 return area } }
0
Kotlin
0
0
8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa
3,086
adventOfCode2023
MIT License
2021/src/main/kotlin/day24_real.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution fun main() { Day24Real.run(skipTest = true) } object Day24Real : Solution<String>() { override val name = "day24" override val parser = Parser { it } data class Regs(var x: Int = 0, var y: Int = 0, var z: Int = 0, var w: Int = 0) fun checkDigit(input: Int, args: Args, regZ: Int): Int { var z = regZ var x = z x %= 26 z /= args.zDiv x += args.xAdd x = if (x != input) 1 else 0 var y = 25 y *= x y += 1 z *= y y = input y += args.yAdd y *= x z += y return z } data class Args(val zDiv: Int, val xAdd: Int, val yAdd: Int) // TODO parse this out of the input val argsList = listOf( Args(1, 11, 3), Args(1, 14, 7), Args(1, 13, 1), Args(26, -4, 6), Args(1, 11, 14), Args(1, 10, 7), Args(26, -4, 9), Args(26, -12, 9), Args(1, 10, 6), Args(26, -11, 4), Args(1, 12, 0), Args(26, -1, 7), Args(26, 0, 12), Args(26, -11, 1), ) private fun solve(argsList: List<Args>): List<String> { var zRange = setOf(0) var idx = argsList.size - 1 val constrained = Array<MutableMap<Int, MutableSet<Int>>>(14) { mutableMapOf() } argsList.reversed().forEach { args -> val validZ = mutableSetOf<Int>() for (input in 1 .. 9) { for (z in 0 .. 1000000) { if (checkDigit(input, args, z) in zRange) { val set = constrained[idx].getOrPut(input) { mutableSetOf() } set.add(z) validZ.add(z) } } } if (validZ.isEmpty()) { println("No valid z for input input[$idx]?") } idx-- zRange = validZ } fun findSerial(index: Int, z: Int): List<String> { if (index == 14) return listOf("") val opts = constrained[index].entries.filter { z in it.value } return opts.flatMap { (digit, _) -> val newZ = checkDigit(digit, argsList[index], z) findSerial(index + 1, newZ).map { digit.toString() + it } } } return findSerial(0, 0) } override fun part1(input: String): Long { return solve(argsList).maxOf { it.toLong() } } override fun part2(input: String): Long { return solve(argsList).minOf { it.toLong() } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,284
aoc_kotlin
MIT License
leetcode2/src/leetcode/SortArrayByParityII.kt
hewking
68,515,222
false
null
package leetcode /** * 922. 按奇偶排序数组 II * https://leetcode-cn.com/problems/sort-array-by-parity-ii/ * Created by test * Date 2019/6/3 1:27 * Description * 给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。 对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。 你可以返回任何满足上述条件的数组作为答案。 示例: 输入:[4,2,5,7] 输出:[4,5,2,7] 解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。 提示: 2 <= A.length <= 20000 A.length % 2 == 0 0 <= A[i] <= 1000 */ object SortArrayByParityII{ class Solution { /** * 思路: * 1.遍历数组,偶数位如果是奇数则往后遍历找到偶数交换 * 2.奇数同理 */ fun sortArrayByParityII(A: IntArray): IntArray { for (i in A.indices) { if (i % 2 == 0) { if (A[i] % 2 != 0) { for (j in (i + 1) until A.size) { if (A[j].rem(2) == 0) { val tmp = A[j] A[j] = A[i] A[i] = tmp } } } } else { if (A[i] % 2 == 0) { for (j in (i + 1) until A.size) { if (A[j].rem(2) != 0) { val tmp = A[j] A[j] = A[i] A[i] = tmp } } } } } return A } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,789
leetcode
MIT License
src/Day03.kt
spaikmos
573,196,976
false
{"Kotlin": 83036}
fun main() { fun getScore(input: Char) : Int { val value: Int if(input > 'Z') { value = input - 'a' + 1 } else { value = input - 'A' + 27 } return value } fun part1(input: List<String>): Int { var total = 0 for (i in input) { val str1 = i.substring(0, i.length/2) val str2 = i.substring(i.length/2, i.length) val inter = str1.toCharArray().intersect(str2.toCharArray().toList()).toCharArray()[0] total += getScore(inter) } return total } fun part2(input: List<String>): Int { var it = input.iterator() var total = 0 while (it.hasNext()) { val str1 = it.next() val str2 = it.next() val str3 = it.next() var inter = str1.toCharArray().intersect(str2.toCharArray().toList()) inter = (inter.toSet()).intersect(str3.toCharArray().toList()) total += getScore(inter.toCharArray()[0]) } return total } val input = readInput("../input/Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6fee01bbab667f004c86024164c2acbb11566460
1,175
aoc-2022
Apache License 2.0
src/Day05.kt
ostersc
572,991,552
false
{"Kotlin": 46059}
enum class States { READING_CRATES, READY_FOR_INSTRUCTIONS, READING_INSTRUCTIONS } fun main() { fun processInput(input: List<String>, usePopForMove: Boolean): String { val stacks = arrayListOf<ArrayDeque<Char>>() var state = States.READING_CRATES for (line in input) { if (state == States.READING_CRATES && (line.startsWith("[") || line.startsWith(" "))) { line.toCharArray().withIndex().chunked(4) { it -> val index = it[0].index / 4 val c = it[1].value if (c != ' ') { while (index >= stacks.size) { stacks.add(ArrayDeque<Char>()) } stacks[index].addFirst(c) } } } else if (line.isBlank() && state == States.READY_FOR_INSTRUCTIONS) { state = States.READING_INSTRUCTIONS } else if (line.startsWith("move") && state == States.READING_INSTRUCTIONS) { val (count, from, to) = """move (\d+) from (\d+) to (\d+)""".toRegex() .find(line)!!.destructured.toList().map { it.toInt() - 1 } for (i in count downTo 0) { if (usePopForMove) { stacks[to].addLast(stacks[from].removeLast()) } else { stacks[to].addLast(stacks[from].removeAt(stacks[from].lastIndex - i)) } } } else if (line.startsWith(" 1 ") && state == States.READING_CRATES) { state = States.READY_FOR_INSTRUCTIONS } else { throw IllegalStateException("In invalid state (${state}) for line:${line}") } } return stacks.fold("") { result, q -> result.plus(q.last()) } } fun part1(input: List<String>): String { return processInput(input, true) } fun part2(input: List<String>): String { return processInput(input, false) } // 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") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9
2,348
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch3/Problem37.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch3 import dev.bogwalk.util.maths.primeNumbers import dev.bogwalk.util.search.binarySearch /** * Problem 37: Truncatable Primes * * https://projecteuler.net/problem=37 * * Goal: Find the sum of all primes less than N that are truncatable both from left to right and * from right to left (single-digit primes are not considered). * * Constraints: 100 <= N <= 1e6 * * Truncatable Prime: A prime that remains prime as digits are continuously removed from LTR or RTL. * e.g. 3797 -> 797 -> 97 -> 7 and 3797 -> 379 -> 37 -> 3 * * e.g.: N = 50 * truncatable primes = {23, 37} * sum = 60 */ class TruncatablePrimes { /** * Solution speed optimised based on the following: * * - There are only 11 such qualifying numbers. * * - A number must start and end with a single-digit prime. * * - No point in considering double-digit primes less than 23. * * - Above 100, pattern shows that qualifying numbers must start and end in a 3 or 7. * * - Above 1000, pattern shows that qualifying numbers must have their first & last 3 digits * be a prime number. * * - No need to check first & last digits again in final loop. * * - A binary search algorithm is used to check the primes list. */ fun sumOfTruncPrimes(n: Int): Int { val primes = primeNumbers(n - 1) var sum = 0 var count = 0 outer@for (prime in primes.subList(8, primes.size)) { val p = prime.toString() val digits = p.length if (digits == 2) { if (p.take(1) !in "2357" || p.takeLast(1) !in "2357") continue } else { if (p.take(1) !in "37" || p.takeLast(1) !in "37") continue if (digits >= 4) { if ( !binarySearch(p.take(3).toInt(), primes) || !binarySearch(p.takeLast(3).toInt(), primes) ) continue } } if (digits > 2) { for (i in 2 until digits) { if (!binarySearch(p.take(i).toInt(), primes) || !binarySearch(p.takeLast(i).toInt(), primes) ) continue@outer } } sum += prime count++ if (count == 11) break@outer } return sum } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,453
project-euler-kotlin
MIT License
src/main/kotlin/kr/co/programmers/P92341.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers import kotlin.math.ceil // https://github.com/antop-dev/algorithm/issues/396 class P92341 { fun solution(fees: IntArray, records: Array<String>): IntArray { // 차량의 마지막 입차 시간을 가지고 있는 맵 val inMap = mutableMapOf<String, Int>() // 차량의 누적 주차 시간을 가지고 있는 맵 val timeMap = mutableMapOf<String, Int>() // 차량의 주차 요금 val moneyMap = mutableMapOf<String, Int>() // 누적 주차시간 계산 for (record in records) { val split = record.split(" ") val t = split[0].split(":") val time = t[0].toInt() * 60 + t[1].toInt() // 숫자로 변환한 시각 val carNumber = split[1] // 차량번호 val inOut = split[2] // 내역 // 누적 주차 시간 0으로 세팅 if (!timeMap.containsKey(carNumber)) { timeMap[carNumber] = 0 } // "OUT" 전에는 반드시 "IN"이 있다. if (inOut == "IN") { inMap[carNumber] = time } else { // "OUT" timeMap[carNumber] = timeMap[carNumber]!! + (time - inMap.remove(carNumber)!!) } } // 타임맵에 남아있다면 23:59분 출차로 계산한다. for ((carNumber, time) in inMap.entries) { timeMap[carNumber] = timeMap[carNumber]!! + (1439 - time) } // 주차 요금 계산 for ((carNumber, time) in timeMap.entries) { var money = 0.0 + fees[1] if (time - fees[0] > 0) { money += ceil((time - fees[0]).toDouble() / fees[2]) * fees[3] } moneyMap[carNumber] = money.toInt() } // 차량번호로 정렬 후 금액만 리턴 return moneyMap.toSortedMap().values.toIntArray() } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,917
algorithm
MIT License
AlgorithmSamples/src/com/frewen/algorithm/demo/binarytree/DiameterOfBinaryTree.kt
FrewenWang
278,597,737
false
{"Java": 341763, "Kotlin": 3400}
package com.frewen.algorithm.demo.binarytree import com.frewen.algorithm.demo.binarytree.base.TreeNode /** * LeetCode第543题目. 二叉树的直径 * https://leetcode-cn.com/problems/diameter-of-binary-tree/ * * 给定一棵二叉树,你需要计算它的直径长度。 * 一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。 * * 示例 : * 给定二叉树 * 1 * / \ * 2 3 * / \ * 4 5 * 返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。 * * 注意:两结点之间的路径长度是以它们之间边的数目表示。 * * 其实我们思考这道题目,我们就可以发现其实我们只要计算左右子树的深度 * * */ class DiameterOfBinaryTree { var result = 1 /** * @param root * @return */ fun diameterOfBinaryTree(root: TreeNode<*>?): Int { if (null == root) { return 0 } depthOfTreeNode(root) return result - 1 } /** * * @param node */ private fun depthOfTreeNode(node: TreeNode<*>?): Int { if (node == null) { return 0 } val leftDepth = depthOfTreeNode(node.left) val rightDepth = depthOfTreeNode(node.right) result = Math.max(result, leftDepth + rightDepth + 1) return Math.max(leftDepth, rightDepth) + 1 } }
0
Java
0
0
41d3ef56dea45599bdf5b27122787b4a08f9c7f4
1,399
AliceJava
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem81/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem81 /** * LeetCode page: [81. Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the size of nums; */ fun search(nums: IntArray, target: Int): Boolean { return search(nums, target, 0, nums.lastIndex) } /** * Return if there is [target] in [nums] from [fromIndex] to [toIndex] (both ends inclusive). * * [nums] should be a sorted array or a rotated sorted array. */ private tailrec fun search(nums: IntArray, target: Int, fromIndex: Int, toIndex: Int): Boolean { if (fromIndex == toIndex) { return nums[fromIndex] == target } val noRotation = nums[fromIndex] < nums[toIndex] if (noRotation) { return nums.binarySearch(target, fromIndex, toIndex + 1) >= 0 } // Guarantee that value >= nums[fromIndex] is always to the left of the pivot if (nums[fromIndex] == nums[toIndex]) { return search(nums, target, fromIndex, toIndex - 1) } val mid = fromIndex + (toIndex - fromIndex) / 2 val isMidLeftSide = nums[fromIndex] <= nums[mid] val isTargetLeftSide = nums[fromIndex] <= target if (isMidLeftSide && !isTargetLeftSide) { return search(nums, target, mid + 1, toIndex) } if (!isMidLeftSide && isTargetLeftSide) { return search(nums, target, fromIndex, mid - 1) } return when { target < nums[mid] -> search(nums, target, fromIndex, mid - 1) target > nums[mid] -> search(nums, target, mid + 1, toIndex) else -> true } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,777
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2020/d12/Day12.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2020.d12 import com.groundsfam.advent.DATAPATH import kotlin.io.path.div import kotlin.io.path.useLines import kotlin.math.abs private enum class Direction { NORTH, SOUTH, EAST, WEST, LEFT, RIGHT, FORWARD; fun turnLeft(): Direction = when (this) { NORTH -> WEST WEST -> SOUTH SOUTH -> EAST EAST -> NORTH else -> this } fun turnRight(): Direction = when (this) { NORTH -> EAST EAST -> SOUTH SOUTH -> WEST WEST -> NORTH else -> this } } private fun Char.toDirection(): Direction? = when (uppercase()) { "N" -> Direction.NORTH "S" -> Direction.SOUTH "E" -> Direction.EAST "W" -> Direction.WEST "L" -> Direction.LEFT "R" -> Direction.RIGHT "F" -> Direction.FORWARD else -> null } private data class Instruction(val direction: Direction, val value: Int) private fun parseInstruction(line: String): Instruction { if (line.length < 2) throw RuntimeException("Cannot parse instruction from \"$line\"") val direction = line[0].toDirection() ?: throw RuntimeException("Unknown direction: ${line[0]}") val value = line.substring(1).toInt() return Instruction(direction, value) } private fun applyInstructions1(instructions: List<Instruction>, initialDirection: Direction = Direction.EAST): Pair<Int, Int> { var x = 0 var y = 0 var direction = initialDirection instructions.forEach { (dir, value) -> when (dir) { Direction.NORTH -> y += value Direction.SOUTH -> y -= value Direction.EAST -> x -= value Direction.WEST -> x += value Direction.LEFT -> repeat(value / 90) { direction = direction.turnLeft() } Direction.RIGHT -> repeat(value / 90) { direction = direction.turnRight() } Direction.FORWARD -> when (direction) { Direction.NORTH -> y += value Direction.SOUTH -> y -= value Direction.EAST -> x -= value Direction.WEST -> x += value else -> {} // do nothing } } } return x to y } private fun applyInstructions2(instructions: List<Instruction>, initialWaypoint: Pair<Int, Int> = -10 to 1): Pair<Int, Int> { var x = 0 var y = 0 var (wayX, wayY) = initialWaypoint instructions.forEach { (dir, value) -> when (dir) { Direction.NORTH -> wayY += value Direction.SOUTH -> wayY -= value Direction.EAST -> wayX -= value Direction.WEST -> wayX += value Direction.LEFT -> repeat(value / 90) { val tmp = wayX wayX = wayY wayY = -tmp } Direction.RIGHT -> repeat(value / 90) { val tmp = wayX wayX = -wayY wayY = tmp } Direction.FORWARD -> { x += value * wayX y += value * wayY } } } return x to y } fun main() { val instructions = (DATAPATH / "2020/day12.txt").useLines { it.map(::parseInstruction).toList() } applyInstructions1(instructions) .also { (x, y) -> println("Part one: ${abs(x) + abs(y)}") } applyInstructions2(instructions) .also { (x, y) -> println("Part two: ${abs(x) + abs(y)}") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
3,497
advent-of-code
MIT License
src/main/kotlin/days/Day10.kt
hughjdavey
433,597,582
false
{"Kotlin": 53042}
package days import java.util.Stack class Day10 : Day(10) { override fun partOne(): Any { return inputList.mapNotNull { getFirstIllegalChar(it) }.sumOf { it.getIllegalScore() } } override fun partTwo(): Any { val missing = inputList.filter { getFirstIllegalChar(it) == null } .map { getMissing(it).fold(0L) { score, c -> score * 5 + c.getIncompleteScore() } } return missing.sorted()[(missing.size / 2)] } private fun getMissing(s: String): String { return s.fold(Stack<Char>()) { unmatched, char -> if (listOf('(', '[', '{', '<').contains(char)) unmatched.push(char) else unmatched.pop() unmatched }.toList().map { it.getMirror() }.joinToString("").reversed() } private fun getFirstIllegalChar(s: String): Char? { val unmatched = Stack<Char>() for (char in s) { when { listOf('(', '[', '{', '<').contains(char) -> unmatched.push(char) unmatched.isNotEmpty() && listOf("()", "[]", "{}", "<>").contains("${unmatched.peek()}$char") -> unmatched.pop() else -> return char } } return null } private fun Char.getIllegalScore(): Int = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137).getOrDefault(this, 0) private fun Char.getIncompleteScore(): Long = mapOf(')' to 1L, ']' to 2L, '}' to 3L, '>' to 4L).getOrDefault(this, 0) private fun Char.getMirror(): Char = mapOf('(' to ')', ')' to '(', '[' to ']', ']' to '[', '{' to '}', '}' to '{', '<' to '>', '>' to '<').getOrDefault(this, this) }
0
Kotlin
0
0
a3c2fe866f6b1811782d774a4317457f0882f5ef
1,622
aoc-2021
Creative Commons Zero v1.0 Universal
src/day01/Day01.kt
CodeLock85
573,182,143
false
{"Kotlin": 1766}
package day01 import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("day01/Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("day01/Day01") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val elvenInventories = elvenInventoriesFrom(input) return elvenInventories.max() } fun part2(input: List<String>): Int { val elvenInventories = elvenInventoriesFrom(input) return elvenInventories .sortedDescending() .take(3) .sum() } private fun elvenInventoriesFrom(input: List<String>): List<Int> { val elvenInventories = mutableListOf<Int>() var currentInventory = 0 input.forEach { if (it.isBlank()) { elvenInventories.add(currentInventory) currentInventory = 0 } else { val currentValue = it.toInt() currentInventory += currentValue } } elvenInventories.add(currentInventory) return elvenInventories }
0
Kotlin
0
0
1381b8e39cba25dec23776d3fe2a25b6f77351ff
1,131
aoc221
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2022/Day16.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import java.util.concurrent.atomic.AtomicInteger /** * [Day 16: Proboscidea Volcanium](https://adventofcode.com/2022/day/16). */ object Day16 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day16") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Int { val spaces = input.map { Space.from(it) } val distanceMap = spaces.map { it.name to it.getOtherDistances(spaces) } val startingSpace = checkNotNull(spaces.find { it.name == "AA" }) val valveOptions = spaces.filter { it.flowRate > 0 } val paths = getPathPermutations(startingSpace, valveOptions, distanceMap, 30) return paths.maxOf { it.second } } fun part2(input: List<String>): Int { val spaces = input.map { Space.from(it) } val distanceMap = spaces.map { it.name to it.getOtherDistances(spaces) } val startingSpace = checkNotNull(spaces.find { it.name == "AA" }) val valveOptions = spaces.filter { it.flowRate > 0 } val myPaths = getPathPermutations(startingSpace, valveOptions, distanceMap, 26) val bestScore = AtomicInteger() runBlocking { withContext(Dispatchers.Default) { myPaths.forEach { path -> launch { getPathPermutations(startingSpace, valveOptions, distanceMap, 26, path.first).forEach { if (path.second + it.second > bestScore.get()) bestScore.set(path.second + it.second) } } } } } return bestScore.get() } private fun getPathPermutations( startingSpace: Space, spaces: List<Space>, distanceMap: List<Pair<String, List<Pair<String, Int>>>>, time: Int, visitedSpaces: List<String> = listOf() ): List<Pair<List<String>, Int>> { val permutations = mutableListOf<Pair<List<String>, Int>>() fun getAllPaths( pathHead: Space, currentPath: Pair<List<String>, Int>, minutesRemaining: Int ): Set<Pair<List<String>, Int>> { val remainingSpaces = spaces.filter { !visitedSpaces.contains(it.name) && !currentPath.first.contains(it.name) && minutesRemaining >= (distanceMap.distanceBetween( pathHead.name, it.name ) + 1) } return if (remainingSpaces.isNotEmpty()) { remainingSpaces.flatMap { getAllPaths( it, Pair( currentPath.first.plus(it.name), currentPath.second + ((minutesRemaining - (distanceMap.distanceBetween( pathHead.name, it.name ) + 1)) * it.flowRate) ), minutesRemaining - (distanceMap.distanceBetween(pathHead.name, it.name) + 1) ).plus(setOf(currentPath)) }.toSet() } else setOf(currentPath) } val allPaths = getAllPaths(startingSpace, emptyList<String>() to 0, time) permutations.addAll(allPaths) return permutations } private fun List<Pair<String, List<Pair<String, Int>>>>.distanceBetween(source: String, destination: String) = checkNotNull(find { key -> key.first == source }?.second?.find { it.first == destination }?.second) private data class Space( val name: String, val flowRate: Int, val connections: List<String> ) { fun getOtherDistances(spaces: List<Space>): List<Pair<String, Int>> { val currentSpace = name to 0 val otherDistances = mutableListOf(currentSpace) fun getNestedDistances(key: String, distance: Int): List<Pair<String, Int>> { val space = checkNotNull(spaces.find { it.name == key }) space.connections.forEach { connection -> val x = otherDistances.find { connection == it.first } x?.let { if (distance < it.second) otherDistances.remove(it) } } val unmappedDistances = space.connections.filter { connection -> otherDistances.none { connection == it.first } } return if (unmappedDistances.isNotEmpty()) { otherDistances.addAll(unmappedDistances.map { it to distance }) unmappedDistances.flatMap { getNestedDistances(it, distance + 1) } } else emptyList() } otherDistances.addAll(getNestedDistances(this.name, 1)) return otherDistances.minus(currentSpace) } companion object { fun from(line: String): Space { val (part1, part2) = line.split(';') val name = part1.split(' ')[1] val rate = part1.split('=')[1].toInt() val connections = part2.split("valves", "valve")[1].split(',').map { it.trim() } return Space(name, rate, connections) } } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
5,689
advent-of-code
MIT License
src/main/java/Exercise13-part2.kt
cortinico
317,667,457
false
null
import kotlin.math.absoluteValue fun main() { val input = object {}.javaClass.getResource("input-13.txt").readText().split("\n") val busses = input[1].split(",") var indexes = busses .mapIndexed { index, code -> index to code } .filter { (_, code) -> code != "x" } .map { (index, code) -> index to code.toLong() } val last = indexes.last() indexes = indexes.map { (value, code) -> (value - last.first).absoluteValue to code } val product = indexes.map { it.second }.reduce { acc, next -> acc * next } val partials = indexes.map { it.second }.map { product / it } val inverses = indexes.map { it.second }.mapIndexed { i, value -> modInverse(partials[i], value) } val sum = inverses.mapIndexed { i, inverse -> partials[i] * inverse * indexes[i].first }.sum() println(sum % product - (busses.size - 1)) } // Find the modular multiplicative inverse between number and m. fun modInverse(number: Long, m: Long): Long { val x = number % m for (i in 1 until m) { if ((x * i) % m == 1L) return i } return 1 }
1
Kotlin
0
4
a0d980a6253ec210433e2688cfc6df35104aa9df
1,124
adventofcode-2020
MIT License
src/main/kotlin/g1801_1900/s1803_count_pairs_with_xor_in_a_range/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1803_count_pairs_with_xor_in_a_range // #Hard #Array #Bit_Manipulation #Trie #2023_06_19_Time_427_ms_(100.00%)_Space_40.6_MB_(100.00%) class Solution { fun countPairs(nums: IntArray, low: Int, high: Int): Int { val root = Trie() var pairsCount = 0 for (num in nums) { val pairsCountHigh = countPairsWhoseXorLessThanX(num, root, high + 1) val pairsCountLow = countPairsWhoseXorLessThanX(num, root, low) pairsCount += pairsCountHigh - pairsCountLow root.insertNumber(num) } return pairsCount } private fun countPairsWhoseXorLessThanX(num: Int, root: Trie, x: Int): Int { var pairs = 0 var curr: Trie? = root var i = 14 while (i >= 0 && curr != null) { val numIthBit = num shr i and 1 val xIthBit = x shr i and 1 if (xIthBit == 1) { if (curr.child[numIthBit] != null) { pairs += curr.child[numIthBit]!!.count } curr = curr.child[1 - numIthBit] } else { curr = curr.child[numIthBit] } i-- } return pairs } private class Trie { var child: Array<Trie?> = arrayOfNulls(2) var count: Int = 0 fun insertNumber(num: Int) { var curr = this for (i in 14 downTo 0) { val ithBit = num shr i and 1 if (curr.child[ithBit] == null) { curr.child[ithBit] = Trie() } curr.child[ithBit]!!.count++ curr = curr.child[ithBit]!! } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,721
LeetCode-in-Kotlin
MIT License
src/tree/LeetCode208.kt
Alex-Linrk
180,918,573
false
null
package tree import java.io.File /** * 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。 * * 示例: * * Trie trie = new Trie(); * * trie.insert("apple"); * trie.search("apple"); // 返回 true * trie.search("app"); // 返回 false * trie.startsWith("app"); // 返回 true * trie.insert("app"); * trie.search("app"); // 返回 true * 说明: * * 你可以假设所有的输入都是由小写字母 a-z 构成的。 * 保证所有输入均为非空字符串。 **/ class Trie() { /** Initialize your data structure here. */ class TrieNode { var isTire = false var children = arrayOfNulls<TrieNode>(26) } var root = TrieNode() /** Inserts a word into the trie. */ fun insert(word: String) { var p = root for (item in word) { val index = item.toLowerCase().toInt()-'a'.toInt() if (p.children[index] == null) { p.children[index] = TrieNode() } p = p.children[index]!! } p.isTire = true } /** Returns if the word is in the trie. */ fun search(word: String): Boolean { val findWord = findWord(word) return findWord!=null && findWord.isTire } /** Returns if there is any word in the trie that starts with the given prefix. */ fun startsWith(prefix: String): Boolean { return findWord(prefix)!=null } fun findWord(word:String):TrieNode?{ var p = root for (itemChar in word) { val index = itemChar.toLowerCase().toInt()-'a'.toInt() if (p.children[index] == null){ return null } p = p.children[index]!! } return p } } /** * ["Trie","startsWith"] [[],["a"]] */ fun main() { val trie = Trie() trie.insert("Trie") trie.insert("startsWith") println(trie.search("")) println(trie.search("a")) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
1,990
LeetCode
Apache License 2.0
src/Day02.kt
richardmartinsen
572,910,850
false
{"Kotlin": 14993}
import java.util.IllegalFormatException // rules // A = Rock // B = Paper // C = SCissors // // X = Rock 1 // Y = Paper 2 // Z = Scissors 3 // looses = 0 // draw = 3 // win = 6 fun main() { val ROCK = 1 val PAPER = 2 val SCISSORS = 3 val LOOSE = 0 val DRAW = 3 val WIN = 6 fun calculateScore(input: List<List<String>>): Int { var sum = 0 input.forEach { when (it[1]) { "X" -> { sum += ROCK when (it[0]) { "A" -> sum += DRAW "B" -> sum += LOOSE "C" -> sum += WIN } } "Y" -> { sum += PAPER when (it[0]) { "A" -> sum += WIN "B" -> sum += DRAW "C" -> sum += LOOSE } } "Z" -> { sum += SCISSORS when (it[0]) { "A" -> sum += LOOSE "B" -> sum += WIN "C" -> sum += DRAW } } } } return sum } fun part1(input: List<String>): Int { var arr = input.map{ it.split(" ") } return calculateScore(arr) } fun part2(input: List<String>): Int { var arr = input.map{ it.split(" ") } // X -> loose // Y -> draw // Z -> win val strategy = arr.map { x -> when (x[1]) { "X" -> { // loose when (x[0]) { "A" -> listOf("A", "Z") "B" -> listOf("B", "X") "C" -> listOf("C", "Y") else -> throw IllegalArgumentException("unknown") } } "Y" -> { // draw when (x[0]) { "A" -> listOf("A", "X") "B" -> listOf("B", "Y") "C" -> listOf("C", "Z") else -> throw IllegalArgumentException("unknown") } } "Z" -> { // win when (x[0]) { "A" -> listOf("A", "Y") "B" -> listOf("B", "Z") "C" -> listOf("C", "X") else -> throw IllegalArgumentException("unknown") } } else -> throw IllegalArgumentException("unknown") } } return calculateScore(strategy) } val input = readInput("Day02") check(part1(input) == 13268) check(part2(input) == 15508) }
0
Kotlin
0
0
bd71e11a2fe668d67d7ee2af5e75982c78cbe193
2,987
adventKotlin
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions17.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test17() { printlnResult("ADDBANCAD", "ABC") printlnResult("ADDBANCADCBA", "ABC") printlnResult("ADDBANCADCBAXY", "ABC") } /** * Given two strings s and t, find the shortest substring in s that contains all alphabets in t */ private fun findShortestSubstring(s: String, t: String): String { if (s.isEmpty() || t.isEmpty()) return "" val charHashSet = HashSet<Char>(t.length) t.forEach { charHashSet.add(it) } val copySet = HashSet<Char>(t.length) var start = 0 var end: Int var shortest = "" while (start < s.length) { charHashSet.forEach { copySet.add(it) } while (start < s.length) { if (copySet.contains(s[start])) break else start++ } end = start val currentHashMap = HashMap<Char, Int>(t.length) while (end < s.length && copySet.isNotEmpty()) { val c = s[end++] if (charHashSet.contains(c)) { copySet.remove(c) currentHashMap[c] = if (currentHashMap[c] == null) 1 else currentHashMap[c]!! + 1 } } if (copySet.isNotEmpty()) return shortest while (start < end) { val c = s[start++] if (currentHashMap.contains(c)) { if (currentHashMap[c]!! > 1) currentHashMap[c] = currentHashMap[c]!! - 1 else break } } if (shortest.isEmpty() || end - start - 1 < shortest.length) shortest = s.substring(start - 1, end) } return shortest } private fun printlnResult(s: String, t: String) = println("The shortest substring in $s that contains all alphabets in $t is ${findShortestSubstring(s, t)}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,882
Algorithm
Apache License 2.0
src/main/kotlin/leetcode/Problem2013.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode import kotlin.math.abs /** * https://leetcode.com/problems/detect-squares/ */ class Problem2013 { class DetectSquares() { private val map = mutableMapOf<Int, MutableMap<Int, Int>>() fun add(point: IntArray) { val x = point[0] val y = point[1] val m = map[x] ?: mutableMapOf() m[y] = (m[y] ?: 0) + 1 map[x] = m } fun count(point: IntArray): Int { var count = 0 val x1 = point[0] val y1 = point[1] for ((y2, _) in map[x1] ?: mapOf<Int, Int>()) { val length = abs(y1 - y2) if (length == 0) { continue } count += numSquares(x1 = x1, y1 = y1, x2 = x1 - length, y2 = y2) count += numSquares(x1 = x1, y1 = y1, x2 = x1 + length, y2 = y2) } return count } private fun numSquares(x1: Int, y1: Int, x2: Int, y2: Int): Int { val p1 = if (map[x1] != null) map[x1]!![y2] ?: 0 else 0 val p2 = if (map[x2] != null) map[x2]!![y1] ?: 0 else 0 val p3 = if (map[x2] != null) map[x2]!![y2] ?: 0 else 0 return p1 * p2 * p3 } } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,275
leetcode
MIT License
src/main/kotlin/co/csadev/advent2021/Day19.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2021 by <NAME> * Advent of Code 2021, Day 19 * Problem Description: http://adventofcode.com/2021/day/19 */ package co.csadev.advent2021 import co.csadev.advent2021.Day19.Beacon.Companion.minus import co.csadev.advent2021.Day19.Beacon.Companion.plus import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsText import com.github.shiguruikai.combinatoricskt.combinations import kotlin.math.abs class Day19(override val input: String = resourceAsText("21day19.txt")) : BaseDay<String, Int, Int> { private val scannerViews = input.split("\n\n").mapIndexed { idx, each -> each.lines().drop(1).map { l -> l.split(",").let { p -> Beacon(p[0].toInt(), p[1].toInt(), p[2].toInt()) } }.run { Scanner("$idx", toMutableList()) } }.toMutableList() private var scanners: List<Beacon> private val combined = scannerViews.removeAt(0).apply { combine(scannerViews).also { scanners = it } } override fun solvePart1() = combined.beacons.size override fun solvePart2() = scanners.combinations(2).maxOf { abs(it.first().distanceTo(it.last())) } data class Beacon(val x: Int, val y: Int, val z: Int) { val rotations: List<Beacon> get() { var moved = this val r = mutableListOf<Beacon>() repeat(2) { repeat(3) { moved = moved.roll r.add(moved) repeat(3) { moved = moved.turn r.add(moved) } } moved = moved.roll.turn.roll } return r } fun distanceTo(other: Beacon) = abs(other.x - x) + abs(other.y - y) + abs(other.z - z) private val roll: Beacon get() = copy(y = z, z = -y) private val turn: Beacon get() = copy(x = -y, y = x) companion object { operator fun Beacon.minus(other: Beacon) = Beacon(x - other.x, y - other.y, z - other.z) operator fun Beacon.plus(other: Beacon) = Beacon(x + other.x, y + other.y, z + other.z) } } internal inner class Scanner(private val name: String, val beacons: MutableList<Beacon>) { fun combine(scanList: MutableList<Scanner>): List<Beacon> { val scanners = mutableListOf(Beacon(0, 0, 0)) while (scanList.isNotEmpty()) { for (sc in scanList.toList()) { val t = sc.rotations.mapNotNull { r -> findTranslation(r)?.let { r to it } }.firstOrNull() ?: continue add(t.first, t.second) scanners.add(t.second) scannerViews.remove(sc) } } return scanners } private fun findTranslation(peer: Scanner): Beacon? { val diffs = beacons.flatMap { c -> peer.beacons.map { d -> c - d } } .groupingBy { it }.eachCount() return diffs.keys.firstOrNull { (diffs[it] ?: -1) >= 12 } } private val rotations: List<Scanner> get() = beacons.map { it.rotations }.run { (0 until first().size).map { idx -> Scanner("$name:rot:$idx", map { r -> r[idx] }.toMutableList()) } } private fun add(t: Scanner, trans: Beacon) = beacons.addAll(t.beacons.map { c -> c + trans }.filter { !beacons.contains(it) }) } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
3,662
advent-of-kotlin
Apache License 2.0
src/Day02.kt
haitekki
572,959,197
false
{"Kotlin": 24688}
fun main() { fun part1(input: String): Int { return input.lines().map { it.split(" ") .zipWithNext() .first() .let { pair -> when (pair.second) { "X" -> { when (pair.first) { "A" -> 4 "B" -> 1 "C" -> 7 else -> 0 } } "Y" -> { when (pair.first) { "A" -> 8 "B" -> 5 "C" -> 2 else -> 0 } } "Z" -> { when (pair.first) { "A" -> 3 "B" -> 9 "C" -> 6 else -> 0 } } else -> 0 } } }.sum() } fun part2(input: String): Int { return input.lines().map { it.split(" ") .zipWithNext() .first() .let { pair -> when (pair.first) { "A" -> { when (pair.second) { "Y" -> 4 "X" -> 3 "Z" -> 8 else -> 0 } } "B" -> { when (pair.second) { "Y" -> 5 "X" -> 1 "Z" -> 9 else -> 0 } } "C" -> { when (pair.second) { "Y" -> 6 "X" -> 2 "Z" -> 7 else -> 0 } } else -> 0 } } }.sum() } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b7262133f9115f6456aa77d9c0a1e9d6c891ea0f
2,560
aoc2022
Apache License 2.0
src/main/kotlin/y2022/Day03.kt
jforatier
432,712,749
false
{"Kotlin": 44692}
package y2022 class Day03(private val data: List<String>) { // region Letter values private val abc = "abcdefghijklmnopqrstuvwxyz" private fun Char.letterValue(): Int { val index = abc.indexOf(this.lowercase()) return if (this.isUpperCase()) { index + 27 } else { index + 1 } } // endregion data class Rucksack(val leftCompartment: String, val rightCompartment: String) { fun findCommonChar(): Char { leftCompartment.forEach { value -> if (rightCompartment.any { it == value }) { return value } } return '*' } } private fun getGrids(input: List<String>): List<Rucksack> { return input .map { line -> Rucksack(line.substring(0, line.length / 2), line.substring(line.length / 2, line.length)) } .toList() } fun part1(): Int { val rucksackList = getGrids(data) return rucksackList.sumOf { it.findCommonChar().letterValue() } } fun part2(): Int { return data.chunked(3) { group -> // <= For each chunk/bloc of 3 lines : Treat them as Team / List<Rucksack> val firstLine = group[0].toSet() group .drop(1) // ignore first line .fold(firstLine) { acc, rucksack -> acc.intersect(rucksack.toSet()) } .sumOf { it.letterValue() } }.sum() } }
0
Kotlin
0
0
2a8c0b4ccb38c40034c6aefae2b0f7d4c486ffae
1,543
advent-of-code-kotlin
MIT License
src/com/kingsleyadio/adventofcode/y2022/day17/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2022.day17 import com.kingsleyadio.adventofcode.util.readInput fun main() { val input = parseInput() part1(input) part2(input) } fun part1(input: String) { println(simulation(input, 2022)) } fun part2(input: String) { println(simulation(input, 1_000_000_000_000)) } fun simulation(jet: String, rockCount: Long): Long { val towerWidth = 7 var tower = mutableListOf(List(towerWidth) { true }) var jetIndex = -1 var partialTowerHeight = 0L fun nextDirection(): Int { jetIndex = (jetIndex + 1) % jet.length return if (jet[jetIndex] == '<') -1 else 1 } fun isClear(rock: Array<BooleanArray>, left: Int, depth: Int): Boolean { for (i in rock.lastIndex downTo 0) { val rSection = rock[i] val tSection = tower.getOrNull(rock.lastIndex - i + depth) ?: return true tSection.forEachIndexed { ti, t -> val r = rSection.getOrNull(ti - left) ?: false if (t && r) return false } } return true } fun checkHorizontalMove(rock: Array<BooleanArray>, left: Int, depth: Int, direction: Int): Boolean { if (left + direction < 0 || left + rock[0].size + direction > towerWidth) return false return isClear(rock, left + direction, depth) } fun checkDownwardMove(rock: Array<BooleanArray>, left: Int, depth: Int): Boolean { return isClear(rock, left, depth - 1) } for (rc in 1..rockCount) { val nextRockIndex = ((rc - 1) % ROCKS.size).toInt() val nextRock = ROCKS[nextRockIndex] var depth = tower.size + 3 var left = 2 while (true) { val jetDirection = nextDirection() if (checkHorizontalMove(nextRock, left, depth, jetDirection)) left += jetDirection if (checkDownwardMove(nextRock, left, depth)) depth-- else break } var potentialCutOff = 0 // Add rock to tower for (i in depth until depth + nextRock.size) { val rSection = nextRock[nextRock.lastIndex - i + depth] val tSection = tower.getOrNull(i) val newSection = List(7) { index -> (rSection.getOrNull(index - left) ?: false) || (tSection?.get(index) ?: false) } if (tSection == null) tower.add(newSection) else tower[i] = newSection if (tower[i].all { it }) potentialCutOff = i } if (potentialCutOff > 0) { partialTowerHeight += potentialCutOff println("Full row index: $partialTowerHeight") depth -= potentialCutOff tower = tower.subList(potentialCutOff, tower.size).toMutableList() } } return partialTowerHeight + tower.lastIndex } fun parseInput(): String { return readInput(2022, 17).readText().trim() } val ROCKS = listOf( arrayOf(booleanArrayOf(true, true, true, true)), arrayOf( booleanArrayOf(false, true, false), booleanArrayOf(true, true, true), booleanArrayOf(false, true, false) ), arrayOf( booleanArrayOf(false, false, true), booleanArrayOf(false, false, true), booleanArrayOf(true, true, true) ), arrayOf(booleanArrayOf(true), booleanArrayOf(true), booleanArrayOf(true), booleanArrayOf(true)), arrayOf(booleanArrayOf(true, true), booleanArrayOf(true, true)), )
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
3,430
adventofcode
Apache License 2.0
src/main/kotlin/days/Day10.kt
julia-kim
435,257,054
false
{"Kotlin": 15771}
package days import readInput import java.util.* fun main() { fun part1(input: List<String>): Int { var syntaxErrorScore = 0 val map = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') var illegalChars: MutableList<Char> = mutableListOf() input.forEach line@{ line -> val stack = Stack<Char>() // last in first out line.forEach { ch -> if (map.containsKey(ch)) { stack.push(map[ch]) } else if (ch != stack.pop()) { illegalChars.add(ch) return@line } } } illegalChars.forEach { when (it) { ')' -> syntaxErrorScore += 3 ']' -> syntaxErrorScore += 57 '}' -> syntaxErrorScore += 1197 '>' -> syntaxErrorScore += 25137 } } return syntaxErrorScore } fun part2(input: List<String>): Long { val map = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') val mutableInput = input.toMutableList() val completionStrings: MutableList<String> = mutableListOf() val scores: MutableList<Long> = mutableListOf() mutableInput.forEach line@{ line -> val stack = Stack<Char>() // last in first out line.forEachIndexed { i, ch -> if (map.containsKey(ch)) { stack.push(map[ch]) } else if (ch != stack.pop()) { return@line } if (i == line.lastIndex) { var string = "" stack.reverse() stack.forEach { string += it } completionStrings.add(string) } } } completionStrings.forEach { var totalScore = 0L it.forEach { ch -> when (ch) { ')' -> totalScore = (totalScore * 5) + 1 ']' -> totalScore = (totalScore * 5) + 2 '}' -> totalScore = (totalScore * 5) + 3 '>' -> totalScore = (totalScore * 5) + 4 } } scores.add(totalScore) } scores.sort() val middle = scores.size / 2 return scores[middle] } val testInput = readInput("Day10_test") check(part1(testInput) == 26397) check(part2(testInput) == 288957L) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5febe0d5b9464738f9a7523c0e1d21bd992b9302
2,583
advent-of-code-2021
Apache License 2.0
2018/kotlin/day6p1/src/main.kt
sgravrock
47,810,570
false
{"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488}
import java.util.* import kotlin.math.abs data class Coord(val x: Int, val y: Int) sealed class Area { object Infinite : Area() data class Finite(val coords: Set<Coord>) : Area() } fun main(args: Array<String>) { val start = Date() val input = "292, 73\n" + "204, 176\n" + "106, 197\n" + "155, 265\n" + "195, 59\n" + "185, 136\n" + "54, 82\n" + "209, 149\n" + "298, 209\n" + "274, 157\n" + "349, 196\n" + "168, 353\n" + "193, 129\n" + "94, 137\n" + "177, 143\n" + "196, 357\n" + "272, 312\n" + "351, 340\n" + "253, 115\n" + "109, 183\n" + "252, 232\n" + "193, 258\n" + "242, 151\n" + "220, 345\n" + "336, 348\n" + "196, 203\n" + "122, 245\n" + "265, 189\n" + "124, 57\n" + "276, 204\n" + "309, 125\n" + "46, 324\n" + "345, 228\n" + "251, 134\n" + "231, 117\n" + "88, 112\n" + "256, 229\n" + "49, 201\n" + "142, 108\n" + "150, 337\n" + "134, 109\n" + "288, 67\n" + "297, 231\n" + "310, 131\n" + "208, 255\n" + "246, 132\n" + "232, 45\n" + "356, 93\n" + "356, 207\n" + "83, 97" println(largestFiniteArea(parseInput(input))) println("in ${Date().time - start.time}ms") } fun parseInput(input: String): List<Coord> { return input.split('\n') .map { line -> val nums = line.split(", ") .map { t -> t.toInt() } Coord(nums[0], nums[1]) } } fun largestFiniteArea(srcCoords: List<Coord>): Int? { return findAreas(srcCoords) .filter { when (it) { is Area.Infinite -> false is Area.Finite -> true } } .map { (it as Area.Finite).coords.size } .max() } fun findAreas(srcCoords: List<Coord>): List<Area> { val visited = mutableSetOf<Coord>() val pendingPoints = srcCoords .map { PendingPoint(it, null) } .toMutableList() val builders = srcCoords.map { AreaBuilder() } while (!pendingPoints.isEmpty()) { val p = pendingPoints.removeAt(pendingPoints.size - 1); val distances = srcCoords .mapIndexed { i, s -> DistanceFrom(i, distanceBetween(s, p.point)) } .sortedBy { it.distance } if (distances[0].distance != distances[1].distance) { val region = distances[0].srcIx visited.add(p.point) builders[region].coords.add(p.point) val nextPoints = listOf( Coord(p.point.x - 1, p.point.y), Coord(p.point.x + 1, p.point.y), Coord(p.point.x, p.point.y - 1), Coord(p.point.x, p.point.y + 1) ) .filter { !visited.contains(it) } for (np in nextPoints) { if (p.predecessorDistances != null && allGreater(distances, p.predecessorDistances)) { builders[region].isFinite = false } else { pendingPoints.add(PendingPoint(np, distances)) } } } } return builders.map { it.build() } } fun distanceBetween(a: Coord, b: Coord): Int { return abs(a.x - b.x) + abs(a.y - b.y) } fun allGreater(a: List<DistanceFrom>, b: List<DistanceFrom>): Boolean { return a.all { ae -> ae.distance > b.find { be -> be.srcIx == ae.srcIx }!!.distance } } data class PendingPoint(val point: Coord, val predecessorDistances: List<DistanceFrom>?) data class DistanceFrom(val srcIx: Int, val distance: Int) class AreaBuilder { val coords: MutableSet<Coord> = HashSet() var isFinite = true fun build(): Area { return if (isFinite) { Area.Finite(coords) } else { Area.Infinite } } }
0
Rust
0
0
ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3
4,309
adventofcode
MIT License
src/main/kotlin/day4/day4part2.kts
avrilfanomar
433,723,983
false
null
import java.io.File val matrixSize = 5 val lines = File("input.txt").readLines() val integers = lines[0].split(',').map { it.toInt() } val matrixList = ArrayList<Array<IntArray>>() val selectionMatrixList = ArrayList<Array<IntArray>>() readMatrixList() var wonMatrixSet = mutableSetOf<Int>() var finalMatrixIdx = 0 var finalValue = 0 mainLoop@ for (nextChosenValue in integers) { for ((matrixIndex, selectionMatrix) in selectionMatrixList.withIndex()) { if (wonMatrixSet.contains(matrixIndex)) { continue } for (i in 0 until matrixSize) { for (j in 0 until matrixSize) { if (matrixList[matrixIndex][i][j] == nextChosenValue) { selectionMatrix[i][j] = 1 if (horizontalStrike(selectionMatrix, i) || verticalStrike(selectionMatrix, j) ) { wonMatrixSet.add(matrixIndex) if (wonMatrixSet.size == matrixList.size) { finalValue = nextChosenValue finalMatrixIdx = matrixIndex break@mainLoop } } } } } } } var unmarkedSum = 0 for (row in 0 until matrixSize) { for (col in 0 until matrixSize) { if (selectionMatrixList[finalMatrixIdx][row][col] == 0) { unmarkedSum += matrixList[finalMatrixIdx][row][col] } } } println(unmarkedSum * finalValue) fun readMatrixList() { var matrixIdx = -1 var i = 0 var j = 0 for (line in lines.subList(1, lines.size)) { line.split(' ').forEach { try { val nextInt = it.trim().toInt() if (i == 0 && j == 0) { matrixList.add(Array(matrixSize) { IntArray(matrixSize) }) selectionMatrixList.add(Array(matrixSize) { IntArray(matrixSize) { 0 } }) matrixIdx++ } matrixList[matrixIdx][i][j] = nextInt if (i == matrixSize - 1 && j == matrixSize - 1) { i = 0 j = 0 } else if (j != matrixSize - 1) { j++ } else if (j == matrixSize - 1) { i++ j = 0 } } catch (_: Exception) { } } } } fun horizontalStrike(matrix: Array<IntArray>, i: Int): Boolean { return matrix[i].sum() == matrixSize } fun verticalStrike(matrix: Array<IntArray>, j: Int): Boolean { var sum = 0 for (i in 0 until matrixSize) { sum += matrix[i][j] } return sum == matrixSize }
0
Kotlin
0
0
266131628b7a58e9b577b7375d3ad6ad88a00954
2,758
advent-of-code-2021
Apache License 2.0
src/Day03/Day03.kt
SelenaChen123
573,253,480
false
{"Kotlin": 14884}
import java.io.File fun main() { fun part1(input: List<String>): Int { var priorities = 0 for (line in input) { val firstHalf = line.substring(0..line.length / 2 - 1).toSet() val secondHalf = line.substring(line.length / 2).toSet() val intersect = (firstHalf intersect secondHalf).first() if (intersect.isLowerCase()) { priorities += intersect - 'a' + 1 } else { priorities += intersect - 'A' + 27 } } return priorities } fun part2(input: List<String>): Int { var priorities = 0 for (index in 0..input.size - 1 step 3) { val group1 = input[index].substring(0..input[index].length - 1).toSet() val group2 = input[index + 1].substring(0..input[index + 1].length - 1).toSet() val group3 = input[index + 2].substring(0..input[index + 2].length - 1).toSet() val intersect = (group1 intersect group2 intersect group3).first() if (intersect.isLowerCase()) { priorities += intersect - 'a' + 1 } else { priorities += intersect - 'A' + 27 } } return priorities } val testInput = File("input", "Day03_test.txt").readLines() val input = File("input", "Day03.txt").readLines() val part1TestOutput = part1(testInput) check(part1TestOutput == 157) println(part1(input)) val part2TestOutput = part2(testInput) check(part2TestOutput == 70) println(part2(input)) }
0
Kotlin
0
0
551af4f0efe11744f918d1ff5bb2259e34c5ecd3
1,590
AdventOfCode2022
Apache License 2.0
numberTheory.kt
mikhail-dvorkin
93,333,859
false
{"Java": 99023, "Kotlin": 10032, "Python": 1664}
private fun largestPrimeDivisors(n: Int): IntArray { val largestPrimeDivisors = IntArray(n + 1) { it } for (i in 2..n) { if (largestPrimeDivisors[i] < i) continue var j = i * i if (j > n) break do { largestPrimeDivisors[j] = i j += i } while (j <= n) } return largestPrimeDivisors } private fun divisorsOf(n: Int, largestPrimeDivisors: IntArray): IntArray { if (n == 1) return intArrayOf(1) val p = largestPrimeDivisors[n] if (p == n) return intArrayOf(1, n) var m = n / p var counter = 2 while (m % p == 0) { m /= p counter++ } val divisorsOfM = divisorsOf(m, largestPrimeDivisors) val result = IntArray(divisorsOfM.size * counter) for (i in divisorsOfM.indices) { var d = divisorsOfM[i] for (j in 0 until counter) { result[i * counter + j] = d d *= p } } return result }
0
Java
0
12
5ad1705636322d642d1fbc515e9254e6f979f154
822
algorithms
The Unlicense
advent-of-code-2022/src/test/kotlin/Day 23 Unstable Diffusion.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import io.kotest.matchers.shouldBe import kotlinx.collections.immutable.persistentListOf import org.junit.jupiter.api.Test class `Day 23 Unstable Diffusion` { fun Point.around(): List<Point> = listOf( up().left(), down().left(), up().right(), down().right(), up(), left(), down(), right()) fun Point.n() = up() fun Point.ne() = up().right() fun Point.nw() = up().left() fun Point.s() = down() fun Point.se() = down().right() fun Point.sw() = down().left() fun Point.w() = left() fun Point.e() = right() @Test fun silverTest() { countEmptySpaces(testInput) shouldBe 110 } @Test fun silver() { countEmptySpaces(loadResource("day23")) shouldBe 3882 } @Test fun goldTest() { runSimulation(testInput).count() shouldBe 20 } @Test fun gold() { runSimulation(loadResource("day23")).count() shouldBe 1116 } private fun countEmptySpaces(input: String): Int { val after10 = runSimulation(input).take(11).last() val maxX = after10.maxOf { it.x } val minX = after10.minOf { it.x } val maxY = after10.maxOf { it.y } val minY = after10.minOf { it.y } return (minY..maxY).sumOf { y -> (minX..maxX).count { x -> Point(x, y) !in after10 } } } private fun runSimulation(input: String): Sequence<Set<Point>> { val evalsSeed = persistentListOf<Pair<(Point, Set<Point>) -> Boolean, (Point) -> Point>>( { elf: Point, elves: Set<Point> -> elf.n() !in elves && elf.ne() !in elves && elf.nw() !in elves } to { elf -> elf.n() }, { elf: Point, elves: Set<Point> -> elf.s() !in elves && elf.se() !in elves && elf.sw() !in elves } to { elf -> elf.s() }, { elf: Point, elves: Set<Point> -> elf.w() !in elves && elf.nw() !in elves && elf.sw() !in elves } to { elf -> elf.w() }, { elf: Point, elves: Set<Point> -> elf.e() !in elves && elf.ne() !in elves && elf.se() !in elves } to { elf -> elf.e() }, ) return generateSequence(parseMap(input).filterValues { it == '#' }.keys.toSet() to evalsSeed) { (elves, evals) -> val proposals = elves.map { elf -> elf to if (elf.around().none { it in elves }) { elf } else { evals.firstNotNullOfOrNull { (predicate, transform) -> if (predicate(elf, elves)) transform(elf) else null } ?: elf } } val newMap = proposals .map { (current, proposed) -> when { current == proposed -> current proposals.count { (_, otherProposal) -> otherProposal == proposed } == 1 -> proposed else -> current } } .toSet() if (elves == newMap) null else newMap to evals.removeAt(0).add(evals.first()) } .map { it.first } } private val testInput = """ ....#.. ..###.# #...#.# .#...## #.###.. ##.#.## .#..#.. """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
3,291
advent-of-code
MIT License
src/lib/Grid.kt
djleeds
572,720,298
false
{"Kotlin": 43505}
package lib import kotlin.math.max import kotlin.math.min class Grid<T>(private val cells: MutableMap<Coordinates, T>, private val default: T) { private val flat get() = cells.map { (key, value) -> Cell(key, value) } private val xMin get() = flat.minOf { it.coordinates.x } private val xMax get() = flat.maxOf { it.coordinates.x } private val yMin get() = flat.minOf { it.coordinates.y } private val yMax get() = flat.maxOf { it.coordinates.y } val bounds: Bounds get() = Bounds(xMin..xMax, yMin..yMax) operator fun get(x: Int, y: Int): T = cells.getOrDefault(Coordinates(x, y), default) operator fun get(coordinates: Coordinates): T = cells.getOrDefault(coordinates, default) operator fun set(coordinates: Coordinates, item: T) = cells.put(coordinates, item) operator fun set(x: Int, y: Int, item: T) = cells.put(Coordinates(x, y), item) fun find(predicate: (Cell<T>) -> Boolean) = flat.first(predicate) fun print(mapping: (T) -> Char) { bounds.northSouthBounds.forEach { y -> bounds.eastWestBounds.forEach { x -> print(mapping(this[x, y])) } println() } } class Bounds(val eastWestBounds: IntRange, val northSouthBounds: IntRange) { operator fun contains(coordinates: Coordinates) = coordinates.x in eastWestBounds && coordinates.y in northSouthBounds } companion object { fun <T> parseCharacters(input: List<String>, transform: (Char) -> T, default: T): Grid<T> { val map = mutableMapOf<Coordinates, T>() input.mapIndexed { y, row -> row.mapIndexed { x, char -> map.put(Coordinates(x, y), transform(char)) } } return Grid(map, default) } } } data class Cell<T>(val coordinates: Coordinates, val item: T) data class Coordinates(val x: Int, val y: Int) { val adjacent: List<Coordinates> by lazy { listOf(step(Direction.NORTH), step(Direction.SOUTH), step(Direction.EAST), step(Direction.WEST)) } fun step(direction: Direction) = when (direction) { Direction.NORTH -> copy(y = y - 1) Direction.SOUTH -> copy(y = y + 1) Direction.EAST -> copy(x = x + 1) Direction.WEST -> copy(x = x - 1) Direction.NORTHWEST -> copy(x = x - 1, y = y - 1) Direction.NORTHEAST -> copy(x = x + 1, y = y - 1) Direction.SOUTHWEST -> copy(x = x - 1, y = y + 1) Direction.SOUTHEAST -> copy(x = x + 1, y = y + 1) } infix fun through(other: Coordinates): Iterable<Coordinates> = Iterable { val (minimum, maximum) = canonicalizedWith(other) iterator { for (x in minimum.x..maximum.x) { for (y in minimum.y..maximum.y) { yield(Coordinates(x, y)) } } } } private fun canonicalizedWith(other: Coordinates): Pair<Coordinates, Coordinates> = Coordinates(min(x, other.x), min(y, other.y)) to Coordinates(max(x, other.x), max(y, other.y)) fun manhattanDistanceTo(other: Coordinates): Int { val (minimum, maximum) = canonicalizedWith(other) return (maximum.x - minimum.x) + (maximum.y - minimum.y) } companion object { fun parse(string: String) = string.split(",").map { it.trim() }.let { Coordinates(it[0].toInt(), it[1].toInt()) } } } operator fun <T> List<List<T>>.get(coordinates: Coordinates): T = this[coordinates.y][coordinates.x] enum class Direction { NORTH, SOUTH, EAST, WEST, NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST; companion object { val UP = NORTH val DOWN = SOUTH val RIGHT = EAST val LEFT = WEST val UP_LEFT = NORTHWEST val UP_RIGHT = NORTHEAST val DOWN_LEFT = SOUTHWEST val DOWN_RIGHT = SOUTHEAST } }
0
Kotlin
0
4
98946a517c5ab8cbb337439565f9eb35e0ce1c72
3,918
advent-of-code-in-kotlin-2022
Apache License 2.0
src/test/kotlin/ch/ranil/aoc/aoc2023/Day08.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import ch.ranil.aoc.AbstractDay import ch.ranil.aoc.aoc2023.Day08.Direction.* import ch.ranil.aoc.lcm import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day08 : AbstractDay() { @Test fun part1Test() { assertEquals(2, compute1(testInput)) } @Test fun part1Puzzle() { assertEquals(21883, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(6, compute2(test2Input)) } @Test fun part2Puzzle() { assertEquals(12833235391111, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { val (sequence, map) = parse(input) var hops = 0 var node = "AAA" while (node != "ZZZ") { node = when (sequence.next()) { LEFT -> map.getValue(node).first RIGHT -> map.getValue(node).second } hops++ } return hops } private fun compute2(input: List<String>): Long { val (sequence, map) = parse(input) val startNodes = map.keys.filter { it.endsWith("A") } val hops = startNodes.map { node -> sequence.reset() var hops = 0L var n = node while (!n.endsWith("Z")) { n = when (sequence.next()) { LEFT -> map.getValue(n).first RIGHT -> map.getValue(n).second } hops++ } hops } return hops.reduceRight { a, b -> lcm(a, b) } } enum class Direction { LEFT, RIGHT; companion object { fun of(c: Char): Direction = when (c) { 'R' -> RIGHT 'L' -> LEFT else -> throw IllegalArgumentException() } } } fun parse(input: List<String>): Pair<Sequence, Map<String, Pair<String, String>>> { val s = Sequence(input.first()) val m = input .drop(2) .map { it.split(" = ") } .associateBy( keySelector = { (k, _) -> k }, valueTransform = { (_, v) -> val vals = Regex("\\((\\w{3}), (\\w{3})\\)").find(v)!!.groupValues vals[1] to vals[2] } ) return s to m } class Sequence(private val s: String) { private var i = 0 fun next(): Direction { val d = Direction.of(s[i++ % s.length]) return d } fun reset() { i = 0 } } @Test fun sequenceTest() { val s = Sequence("LR") assertEquals(LEFT, s.next()) assertEquals(RIGHT, s.next()) assertEquals(LEFT, s.next()) } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
2,812
aoc
Apache License 2.0
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day04.kt
MichalChomo
572,214,942
false
{"Kotlin": 56758}
package eu.michalchomo.adventofcode.year2022 import eu.michalchomo.adventofcode.toInt fun main() { fun String.getPairOfRanges() = this.split(",") .map { r -> r.split("-") } .map { r -> IntRange(r[0].toInt(), r[1].toInt()) } .zipWithNext() .single() fun IntRange.fullyContains(other: IntRange) = other.first in this && other.last in this fun IntRange.containsOrIsContained(other: IntRange) = this.fullyContains(other) || other.fullyContains(this) fun part1(input: List<String>): Int = input.sumOf { it.getPairOfRanges().let { p -> p.first.containsOrIsContained(p.second).toInt() } } fun part2(input: List<String>): Int = input.sumOf { it.getPairOfRanges().let { p -> p.first.intersect(p.second).isNotEmpty().toInt() } } val testInput = readInputLines("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInputLines("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a95d478aee72034321fdf37930722c23b246dd6b
1,038
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxScoreOfGoodSubarray.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <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.Stack import kotlin.math.max import kotlin.math.min /** * 1793. Maximum Score of a Good Subarray * @see <a href="https://leetcode.com/problems/maximum-score-of-a-good-subarray">Source</a> */ fun interface MaxScoreOfGoodSubarray { operator fun invoke(nums: IntArray, k: Int): Int } /** * Approach 1: Binary Search */ class MaxScoreBS : MaxScoreOfGoodSubarray { override fun invoke(nums: IntArray, k: Int): Int { val ans = solve(nums, k) for (i in 0 until nums.size / 2) { val temp = nums[i] nums[i] = nums[nums.size - i - 1] nums[nums.size - i - 1] = temp } return max(ans, solve(nums, nums.size - k - 1)) } private fun solve(nums: IntArray, k: Int): Int { val n = nums.size val left = IntArray(k) var currMin = Int.MAX_VALUE for (i in k - 1 downTo 0) { currMin = min(currMin, nums[i]) left[i] = currMin } val right: MutableList<Int> = ArrayList() currMin = Int.MAX_VALUE for (i in k until n) { currMin = min(currMin, nums[i]) right.add(currMin) } var ans = 0 for (j in right.indices) { currMin = right[j] val i = binarySearch(left, currMin) val size = k + j - i + 1 ans = max(ans, currMin * size) } return ans } private fun binarySearch(nums: IntArray, num: Int): Int { var left = 0 var right = nums.size while (left < right) { val mid = (left + right) / 2 if (nums[mid] < num) { left = mid + 1 } else { right = mid } } return left } } /** * Approach 2: Monotonic Stack */ class MaxScoreStack : MaxScoreOfGoodSubarray { override fun invoke(nums: IntArray, k: Int): Int { val n: Int = nums.size val left = IntArray(n) { -1 } var stack: Stack<Int> = Stack() for (i in n - 1 downTo 0) { while (stack.isNotEmpty() && nums[stack.peek()] > nums[i]) { left[stack.pop()] = i } stack.push(i) } val right = IntArray(n) { n } stack = Stack() for (i in 0 until n) { while (stack.isNotEmpty() && nums[stack.peek()] > nums[i]) { right[stack.pop()] = i } stack.push(i) } var ans = 0 for (i in 0 until n) { if (left[i] < k && right[i] > k) { ans = max(ans, nums[i] * (right[i] - left[i] - 1)) } } return ans } } /** * Approach 3: Greedy */ class MaxScoreGreedy : MaxScoreOfGoodSubarray { override fun invoke(nums: IntArray, k: Int): Int { val n: Int = nums.size var left = k var right = k var ans = nums[k] var currMin = nums[k] while (left > 0 || right < n - 1) { currMin = if ((if (left > 0) nums[left - 1] else 0) < (if (right < n - 1) nums[right + 1] else 0)) { right++ min(currMin, nums[right]) } else { left-- min(currMin, nums[left]) } ans = max(ans, currMin * (right - left + 1)) } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,027
kotlab
Apache License 2.0
src/main/kotlin/ch/petikoch/examples/tictactoe_fp/TicTacToe.kt
Petikoch
288,920,597
false
null
package ch.petikoch.examples.tictactoe_fp import ch.petikoch.examples.tictactoe_fp.Field.* fun main() { var gameState = GameState() // "store" while (gameState.winner == null && !gameState.board.values.any { it == null }) { println(gameState) // "view" val textInput = readLine() val field = convertTextInput(textInput) // "action" gameState = play(gameState, field) // "reduce" } println(gameState) } private fun convertTextInput(textInput: String?): Field { return Field.values().find { it.name == textInput }!! } fun play(gameState: GameState, field: Field): GameState { val newBoard = gameState.board.plus(field to gameState.currentPlayer) return GameState( currentPlayer = gameState.currentPlayer.other(), board = newBoard, winner = findWinner(newBoard) ) } private fun findWinner(newBoard: Map<Field, Player?>): Player? { return winningConditions.firstOrNull { areSame(newBoard, it) }?.let { newBoard[it.first] } } private val winningConditions: List<Triple<Field, Field, Field>> = listOf( Triple(TL, TM, TR), Triple(ML, MM, MR) // ... ) private fun areSame(board: Map<Field, Player?>, triple: Triple<Field, Field, Field>): Boolean { return board[triple.first] == board[triple.second] && board[triple.first] == board[triple.third] } data class GameState( val currentPlayer: Player = Player.X, val board: Map<Field, Player?> = mapOf(), val winner: Player? = null ) enum class Player { X, O; fun other(): Player = if (this == X) O else X } enum class Field { TL, TM, TR, ML, MM, MR, BL, BM, BR }
0
Kotlin
0
0
f24fa2ec39d85509bfa6eec69ac5277d955bd3c8
1,764
TicTacToe_FP_CTDD_Kotlin
The Unlicense
src/main/kotlin/biz/koziolek/adventofcode/year2022/day22/day22.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day22 import biz.koziolek.adventofcode.Coord import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val forceFieldNotes = parseForceFieldNotes(inputFile.bufferedReader().readLines()) val (position, facing) = followPath(forceFieldNotes.board, forceFieldNotes.path) val password = getPassword(position, facing) println("Password for $position and $facing is: $password") } enum class TurnDirection { RIGHT, LEFT, } enum class Facing(val value: Int, val symbol: Char) { RIGHT(0, '>'), DOWN(1, 'v'), LEFT(2, '<'), TOP(3, '^'); fun turn(turnDirection: TurnDirection): Facing = when (turnDirection) { TurnDirection.RIGHT -> when (this) { RIGHT -> DOWN DOWN -> LEFT LEFT -> TOP TOP -> RIGHT } TurnDirection.LEFT -> when (this) { RIGHT -> TOP DOWN -> RIGHT LEFT -> DOWN TOP -> LEFT } } } const val VOID = ' ' const val OPEN = '.' const val WALL = '#' data class ForceFieldNotes( val board: Map<Coord, Char>, val path: List<Pair<Int, TurnDirection?>>, ) fun parseForceFieldNotes(lines: Iterable<String>): ForceFieldNotes { val board = lines .takeWhile { it.isNotEmpty() } .flatMapIndexed { y: Int, line: String -> line.mapIndexed { x, c -> if (c != VOID) { Coord(x + 1, y + 1) to c } else { null } }.filterNotNull() } .toMap() val path = Regex("([0-9]+)([RL])?") .findAll(lines.last()) .map { result -> val steps = result.groups[1]!!.value.toInt() val turn = result.groups[2]?.value.let { when (it) { null -> null "R" -> TurnDirection.RIGHT "L" -> TurnDirection.LEFT else -> throw IllegalArgumentException("Unsupported turn direction: '$it'") } } steps to turn } .toList() return ForceFieldNotes(board, path) } fun visualizeForceShieldBoard(board: Map<Coord, Char>, highlight: Coord? = null): String { val minX = board.keys.minOf { it.x } val maxX = board.keys.maxOf { it.x } val minY = board.keys.minOf { it.y } val maxY = board.keys.maxOf { it.y } return buildString { for (y in minY..maxY) { for (x in minX..maxX) { val coord = Coord(x, y) val symbol = board[coord] if (coord == highlight) { append('X') } else if (symbol != null) { append(symbol) } else { append(VOID) } } if (y < maxY) { append('\n') } } } } fun followPath( board: Map<Coord, Char>, path: List<Pair<Int, TurnDirection?>>, ): Pair<Coord, Facing> { val startPos = Coord( y = 1, x = board.keys.filter { it.y == 1 }.minOf { it.x } ) return path.fold(Pair(startPos, Facing.RIGHT)) { (currentPos, currentFacing), (steps, turn) -> var newPos = currentPos val (dx, dy) = when (currentFacing) { Facing.RIGHT -> 1 to 0 Facing.DOWN -> 0 to 1 Facing.LEFT -> -1 to 0 Facing.TOP -> 0 to -1 } // println("$steps$turn") for (step in 1..steps) { var potentialNewPos = newPos + Coord(dx, dy) // println("$newPos -> $potentialNewPos") // println(visualizeForceShieldBoard(board, highlight = potentialNewPos)) if (board[potentialNewPos] == WALL) { break } if (potentialNewPos !in board) { potentialNewPos = when (currentFacing) { Facing.RIGHT -> potentialNewPos.copy( x = board.keys.filter { it.y == potentialNewPos.y }.minOf { it.x } ) Facing.DOWN -> potentialNewPos.copy( y = board.keys.filter { it.x == potentialNewPos.x }.minOf { it.y } ) Facing.LEFT -> potentialNewPos.copy( x = board.keys.filter { it.y == potentialNewPos.y }.maxOf { it.x } ) Facing.TOP -> potentialNewPos.copy( y = board.keys.filter { it.x == potentialNewPos.x }.maxOf { it.y } ) } } if (board[potentialNewPos] == WALL) { break } newPos = potentialNewPos } val newFacing = turn?.let { currentFacing.turn(it) } ?: currentFacing Pair(newPos, newFacing) } } fun getPassword(position: Coord, facing: Facing): Int = 1000 * position.y + 4 * position.x + facing.value
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
5,134
advent-of-code
MIT License
src/commonMain/kotlin/chriscoomber/manydice/Theory.kt
chriscoomber
342,409,431
false
{"Kotlin": 136477}
package chriscoomber.manydice /** * A probability is close enough to another one if it's within this threshold. */ const val PROBABILITY_FLOAT_THRESHOLD = 0.0000001f /** * A probability is a real number between 0 and 1 inclusive. Users of this type * should check it is within those bounds. */ typealias Probability = Float /** * Check whether a probability is "equal" to another one - or as close as is * possible with floats. */ fun Probability.equalsWithinThreshold(other: Probability): Boolean { return this > other - PROBABILITY_FLOAT_THRESHOLD || this < other + PROBABILITY_FLOAT_THRESHOLD } /** * Check that this function is a probability measure on the given space. I.e., check that * it is non-negative and sums to 1. * * Returns true if and only if it's a probability measure. */ fun <Outcome> ((Outcome) -> Probability).isProbabilityMeasure(space: Set<Outcome>): Boolean { val sum = space.fold(0f) { totalProb, outcome -> val probability = this.invoke(outcome) if (probability < 0f || probability > 1f) return false totalProb + probability } return sum.equalsWithinThreshold(1f) } fun <Outcome> ((Outcome) -> Probability).requireIsProbabilityMeasure(space: Set<Outcome>) = this.isProbabilityMeasure(space) || error("Not a probability measure.") /** * A sample space is a set of "outcomes" equipped with: * * - A sigma-algebra of "events", i.e. sets of outcomes. * This is a bit mathematically technical but in general not all * sets are necessarily "measurable". However, we will only be * dealing with finite spaces, so the sigma-algebra just contains * every possible subset of the space. We don't need to declare * this in code. * * - A probability measure which assigns an event to a * "probability", i.e. a real number between 0 and 1 inclusive. * The measure must satisfy some sensible properties such as: * - The measure of the empty event (no outcomes) is 0 * - The measure of the whole space (all outcomes) is 1 * - The measure of a disjoint union of events is equal to * the sum of the measures of the events. (Technical note: * this is only required for countable unions. However, this being * a computer and us being mortals bound by the restrictions * of time, I don't think we'll be calculating any infinite * unions anyway, countable or not.) */ interface SampleSpace<Outcome> { // TODO iterator instead of set? val space: Set<Outcome> fun measure(event: Set<Outcome>): Probability } /** * A random variable is a function from a sample space to some measurable space E */ interface RandomVariable<Outcome, E> { /** * The sample space that this random variable is defined on. */ val sampleSpace: SampleSpace<Outcome> /** * Evaluate the random variable at a particular outcome. */ fun evaluate(outcome: Outcome): E }
0
Kotlin
0
0
88b482384989bb877142cec1ba5b51133c75916d
2,910
manydice
MIT License
src/org/aoc2021/Day14.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day14 { private const val iterationsPart1 = 10 private const val iterationsPart2 = 40 private fun solve(lines: List<String>, iterations: Int): Long { val start = lines[0] val rules = lines.drop(2).map { it.split(" -> ") }.associate { it[0] to it[1] } val startMap = start.windowed(2).groupBy { it }.mapValues { (_, values) -> values.size.toLong() } val processed = (1..iterations).fold(startMap) { polymer, _ -> doIteration(polymer, rules) } val countsByChar = processed.entries.flatMap { (pair, count) -> listOf( pair[0] to count, pair[1] to count ) } .groupBy(Pair<Char, Long>::first, Pair<Char, Long>::second) .mapValues { (_, counts) -> counts.sum() } .mapValues { (c, count) -> if (c == start.first() || c == start.last()) { if (start.first() == start.last()) { (count + 2) / 2 } else { (count + 1) / 2 } } else { count / 2 } } return countsByChar.values.maxOrNull()!! - countsByChar.values.minOrNull()!! } private fun doIteration(polymer: Map<String, Long>, rules: Map<String, String>): Map<String, Long> { val newMap = mutableMapOf<String, Long>() polymer.forEach { (pair, count) -> val rule = rules[pair] if (rule != null) { newMap.merge(pair[0] + rule, count) { a, b -> a + b } newMap.merge(rule + pair[1], count) { a, b -> a + b } } else { newMap.merge(pair, count) { a, b -> a + b } } } return newMap.toMap() } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input14.txt"), Charsets.UTF_8) val solution1 = solve(lines, iterationsPart1) println(solution1) val solution2 = solve(lines, iterationsPart2) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
2,155
advent-of-code-2021
The Unlicense
codeforces/deltix2021summer/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.deltix2021summer import kotlin.math.abs private fun solve(a: List<Int>, first: Int): Long { val aIndices = a.indices.filter { a[it] == 1 } val neededIndices = a.indices.filter { it % 2 == 1 - first } return aIndices.zip(neededIndices) { x, y -> abs(x - y).toLong() }.sum() } private fun solve(): Long { readLn() val a = readInts().map { it and 1 } val n = a.size val balance = a.sum() - n / 2 if (n % 2 == 0) { if (balance == 0) return minOf(solve(a, 0), solve(a, 1)) } else { if (balance in 0..1) return solve(a, balance) } return -1 } fun main() { repeat(readInt()) { println(solve()) } } 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
813
competitions
The Unlicense
src/main/kotlin/Day12.kt
Walop
573,012,840
false
{"Kotlin": 53630}
import java.io.InputStream data class HeightMap(val start: List<Int>, val end: Int, val width: Int, val graph: List<List<Boolean>>) class Day12 { companion object { private fun readMap(input: InputStream?, startTile: Char, endTile: Char): HeightMap { if (input == null) { throw Exception("Input missing") } var start = mutableListOf<Int>() var end = 0 var width = 0 val map = input.bufferedReader().readLines().flatMapIndexed { i, row -> width = row.length row.mapIndexed { j, tile -> if (tile == startTile) { start.add(i * width + j) } if (tile == endTile) { end = i * width + j } when (tile) { 'S' -> { 'a' } 'E' -> { 'z' } else -> { tile } } } } val graph = MutableList(map.size) { MutableList(map.size) { false } } map.forEachIndexed { i, tile -> if (i % width + 1 < width) { if (tile.code >= map[i + 1].code - 1) { graph[i][i + 1] = true } if (tile.code <= map[i + 1].code + 1) { graph[i + 1][i] = true } } if (i + width < map.size) { if (tile.code >= map[i + width].code - 1) { graph[i][i + width] = true } if (tile.code <= map[i + width].code + 1) { graph[i + width][i] = true } } } return HeightMap(start, end, width, graph) } private fun findPath(graph: List<List<Boolean>>, width: Int, start: Int, end: Int): Int { val numOfVertices = graph.size val visitedAndDistance = List(numOfVertices) { mutableListOf(0, Int.MAX_VALUE) } visitedAndDistance[start][1] = 0 fun nextToVisit(): Int { var v = -1 for (i in 0 until numOfVertices) { if (visitedAndDistance[i][0] == 0 && (v < 0 || visitedAndDistance[i][1] <= visitedAndDistance[v][1])) { v = i } } return v } repeat(numOfVertices) { val toVisit = nextToVisit() for (i in listOf(toVisit - 1, toVisit + 1, toVisit + width, toVisit - width)) { if (i in 0 until numOfVertices && graph[toVisit][i] && visitedAndDistance[i][0] == 0) { val newDistance = visitedAndDistance[toVisit][1] + 1 if (visitedAndDistance[i][1] > newDistance) { visitedAndDistance[i][1] = newDistance if (i == end) { return newDistance } } } visitedAndDistance[toVisit][0] = 1 } } return -1 } fun process(input: InputStream?): Int { val heightMap = readMap(input, 'S', 'E') //heightMap.graph.forEach { println(it) } return findPath(heightMap.graph, heightMap.width, heightMap.start[0], heightMap.end) } fun process2(input: InputStream?): Int { val heightMap = readMap(input, 'a', 'E') var i = 0 val lengths = heightMap.start.parallelStream().map { findPath(heightMap.graph, heightMap.width, it, heightMap.end) }.map { i++ println("$i of ${heightMap.start.size} Done: $it") it } .filter { it > 0 } return lengths.min(Integer::compare).get() } } }
0
Kotlin
0
0
7a13f6500da8cb2240972fbea780c0d8e0fde910
4,285
AdventOfCode2022
The Unlicense
src/main/kotlin/dev/claudio/adventofcode2021/Day11Part2.kt
ClaudioConsolmagno
434,559,159
false
{"Kotlin": 78336}
package dev.claudio.adventofcode2021 fun main() { Day11Part2().main() } private class Day11Part2 { fun main() { val input: List<String> = Support.readFileAsListString("day11-input.txt") val map: MutableList<MutableList<Int>> = input .map { it.toCharArray().map { it2 -> it2.titlecase().toInt() }.toMutableList() }.toMutableList() val boardSize: Long = (map.size * map[0].size).toLong() (0 until map.size).forEach { map[it].add(0, Int.MIN_VALUE) map[it].add(Int.MIN_VALUE) } map.add(0, (0 until map[0].size).map { Int.MIN_VALUE }.toMutableList()) map.add((0 until map[0].size).map { Int.MIN_VALUE }.toMutableList()) // map.forEach{ println(it) } (0 until 1000).forEach { it -> var flashed = step(map) val allFlashed: MutableSet<Pair<Int, Int>> = flashed.toMutableSet() while (flashed.isNotEmpty()) { flashed = flashed.flatMap { stepNeighbours(map, it, allFlashed) }.toMutableSet() allFlashed.addAll(flashed) } if(cleanStep(map) == boardSize) { println(it+1) return } } } private fun cleanStep(map: MutableList<MutableList<Int>>): Long { var sum = 0L (0 until map.size).forEach { x -> (0 until map[x].size).forEach { y -> if (map[x][y] > 9) { sum++ map[x][y] = 0 } } } return sum } private fun step(map: MutableList<MutableList<Int>>): MutableSet<Pair<Int, Int>> { val flashed: MutableSet<Pair<Int, Int>> = mutableSetOf() // flash (0 until map.size).forEach { x -> (0 until map[x].size).forEach { y -> map[x][y] += 1 if (map[x][y] > 9) { flashed.add(Pair(x, y)) } } } return flashed } private fun stepNeighbours( map: MutableList<MutableList<Int>>, pair: Pair<Int, Int>, flashedPairs: MutableSet<Pair<Int, Int>>, ): MutableSet<Pair<Int, Int>> { val neighbours: MutableSet<Pair<Int, Int>> = mutableSetOf() (-1 .. 1).forEach { x -> (-1 .. 1).forEach { y -> if (!(x == 0 && y == 0)) { val candidatePair = Pair(pair.first + x, pair.second +y) if (candidatePair !in flashedPairs) { map[pair.first + x][pair.second +y] += 1 val candidate = map[pair.first + x][pair.second +y] if (candidate > 9) { neighbours.add(candidatePair) } } } } } return neighbours } }
0
Kotlin
0
0
5f1aff1887ad0a7e5a3af9aca7793f1c719e7f1c
2,939
adventofcode-2021
Apache License 2.0
2021/src/main/kotlin/aoc2016/Day20.kt
dkhawk
433,915,140
false
{"Kotlin": 170350}
package aoc2016 import java.io.File import kotlin.math.max import kotlin.math.min import kotlin.system.measureTimeMillis class Day20 { companion object { fun run() { val time = measureTimeMillis { // Day20().part1() Day20().part2() } println("millis: $time") } } private fun part1() { val badList = listOf( "5-8", "0-2", "4-7", ) val input = File("/Users/dkhawk/Documents/advent-of-code/2021/src/main/resources/2016/20.txt").readLines() val r = input val ranges = r.map { val numbs = it.split('-') numbs.first().toLong()..numbs.last().toLong() } val mergedRanges = mergeRanges(ranges) println(mergedRanges) val smallest = mergedRanges.first().last + 1 println(smallest) } private fun mergeRanges(ranges: List<LongRange>): List<LongRange> { val sortedByFirst = ranges.sortedBy { it.first } val mergedRanges = mutableListOf<LongRange>() var merged = sortedByFirst.first() sortedByFirst.drop(1).forEach { candidate -> merged = if (candidate.first <= merged.last) { merged.merge(candidate) } else { mergedRanges.add(merged) candidate } } mergedRanges.add(merged) return mergedRanges } private fun part2() { val badList = listOf( "5-8", "0-2", "4-7", ) val input = File("/Users/dkhawk/Documents/advent-of-code/2021/src/main/resources/2016/20.txt").readLines() val r = input val ranges = r.map { val numbs = it.split('-') numbs.first().toLong()..numbs.last().toLong() } val mergedRanges = mergeRanges(ranges) println(mergedRanges) val sum = mergedRanges.windowed(2, 1).map { (it.last().first - it.first().last) -1 }.sum() println(sum) } } private fun LongRange.merge(candidate: LongRange): LongRange = min(first, candidate.first)..max(last, candidate.last)
0
Kotlin
0
0
64870a6a42038acc777bee375110d2374e35d567
1,941
advent-of-code
MIT License
src/Day10_02.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
fun d10t1(lines: List<String>) { var registerX = 1 var sum = 0 var cycle = 0 for (line in 1 .. lines.size ) { val op = lines[line - 1].split(" ") sum += executeCycle1(++cycle, registerX) if (op[0] == "addx") { sum += executeCycle1(++cycle, registerX) registerX += op[1].toInt() } } println(cycle) println(sum) } fun executeCycle1(cycle: Int, registerX: Int): Int { if (listOf(20, 60, 100, 140, 180, 220).contains(cycle)) { return registerX * cycle } return 0 } fun d10t2(lines: List<String>) { var registerX = 1 val sb = StringBuffer() var cycle = 0 for (line in 1 .. lines.size ) { val op = lines[line - 1].split(" ") sb.append(executeCycle2(++cycle, registerX)) if (op[0] == "addx") { sb.append(executeCycle2(++cycle, registerX)) registerX += op[1].toInt() } } println(sb.toString()) } fun executeCycle2(cycle: Int, registerX: Int): StringBuffer { val tempBuffer = StringBuffer() tempBuffer.append(if (listOf(registerX - 1, registerX, registerX + 1).contains((cycle - 1) % 40)) "##" else " ") if (listOf(40, 80, 120, 160, 200, 240).contains(cycle)) { tempBuffer.append(System.lineSeparator()) } return tempBuffer } fun main() { val day = "day10_input" println(d10t2(readInput(day))) }
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
1,417
advent22
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestPathAllKeys.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <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 /** * 864. Shortest Path to Get All Keys * @see <a href="https://leetcode.com/problems/shortest-path-to-get-all-keys/">Source</a> */ fun interface ShortestPathAllKeys { operator fun invoke(grid: Array<String>): Int } /** * Approach: Breadth-First Search */ class ShortestPathAllKeysBFS : ShortestPathAllKeys { override operator fun invoke(grid: Array<String>): Int { val m: Int = grid.size val n: Int = grid[0].length val queue: Queue<IntArray> = LinkedList() val moves = arrayOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, -1)) // seen['key'] is only for BFS with key state equals 'keys' val seen: MutableMap<Int, MutableSet<Pair<Int, Int>>> = HashMap() val keySet: MutableSet<Char> = HashSet() val lockSet: MutableSet<Char> = HashSet() var allKeys = 0 var startR = -1 var startC = -1 for (i in 0 until m) { for (j in 0 until n) { val cell: Char = grid[i][j] if (cell in 'a'..'f') { allKeys += 1 shl cell.code - 'a'.code keySet.add(cell) } if (cell in 'A'..'F') { lockSet.add(cell) } if (cell == '@') { startR = i startC = j } } } // [row, column, key state, distance] queue.offer(intArrayOf(startR, startC, 0, 0)) seen[0] = HashSet() seen[0]?.add(Pair(startR, startC)) while (queue.isNotEmpty()) { val cur: IntArray = queue.poll() val curR = cur[0] val curC = cur[1] val keys = cur[2] val dist = cur[3] for (move in moves) { val newR = curR + move[0] val newC = curC + move[1] // If this cell (newR, newC) is reachable. if (newR in 0 until m && newC >= 0 && newC < n && grid[newR][newC] != '#') { val cell: Char = grid[newR][newC] // If it is a key: if (keySet.contains(cell)) { // If we have collected it before, no need to revisit this cell. if (1 shl cell.code - 'a'.code and keys != 0) { continue } // Otherwise, we can walk to this cell and pick it up. val newKeys = keys or (1 shl cell.code - 'a'.code) // If we collect all keys, return dist + 1. // Otherwise, just add this state to seen and queue. if (newKeys == allKeys) { return dist + 1 } seen.putIfAbsent(newKeys, HashSet()) seen[newKeys]?.add(Pair(newR, newC)) queue.offer(intArrayOf(newR, newC, newKeys, dist + 1)) } // If it is a lock, and we don't have its key, continue. if (lockSet.contains(cell) && keys and (1 shl cell.code - 'A'.code) == 0) { continue } else if (seen[keys]?.contains(Pair(newR, newC)) == false) { seen[keys]?.add(Pair(newR, newC)) queue.offer(intArrayOf(newR, newC, keys, dist + 1)) } } } } return -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,278
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SumSubarrayMins.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD import java.util.Stack /** * 907. Sum of Subarray Minimums * @see <a href="https://leetcode.com/problems/sum-of-subarray-minimums/">Source</a> */ fun interface SumSubarrayMins { operator fun invoke(arr: IntArray): Int } /** * Approach 2: Monotonic Stack + Dynamic Programming */ class SumSubarrayMinsDP : SumSubarrayMins { override operator fun invoke(arr: IntArray): Int { val stack: Stack<Int> = Stack() // make a dp array of the same size as the input array `arr` val dp = IntArray(arr.size) // making a monotonic increasing stack for (i in arr.indices) { // pop the stack until it is empty or // the top of the stack is greater than or equal to // the current element while (!stack.empty() && arr[stack.peek()] >= arr[i]) { stack.pop() } // either the previousSmaller element exists if (stack.isNotEmpty()) { val previousSmaller: Int = stack.peek() dp[i] = dp[previousSmaller] + (i - previousSmaller) * arr[i] } else { // or it doesn't exist, in this case the current element // contributes with all subarrays ending at i dp[i] = (i + 1) * arr[i] } // push the current index stack.push(i) } // Add all elements of the dp to get the answer var sumOfMinimums: Long = 0 for (count in dp) { sumOfMinimums += count.toLong() sumOfMinimums %= MOD.toLong() } return sumOfMinimums.toInt() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,328
kotlab
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch7/Problem78.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch7 import kotlin.math.pow import kotlin.math.sign /** * Problem 78: Coin Partitions * * https://projecteuler.net/problem=78 * * Goal: Count the number of ways (mod 1e9 + 7) that N coins can be separated into piles. * * Constraints: 2 <= N <= 6e4 * * e.g.: N = 5 * count = 7 * if @ represents a coin, 5 coins can be separated in 7 different ways: * @@@@@ * @@@@ @ * @@@ @@ * @@@ @ @ * @@ @@ @ * @@ @ @ @ * @ @ @ @ @ */ class CoinPartitions { private val modulus = 1_000_000_007 /** * Solution is identical to the bottom-up approach used in Batch 7 - Problem 76 (and is * similar to solutions for Problems 31 & 77). * * SPEED (WORSE) 15.43ms for N = 1e3 * This solution does not scale at all well for N > 1e3. * * @return IntArray of partitions (mod 1e9 + 7) of all N <= limit, with index == N. */ fun coinPileCombos(n: Int): IntArray { val combosByCoin = IntArray(n + 2).apply { this[0] = 1 } for (i in 1..n) { for (j in i..n + 1) { combosByCoin[j] += combosByCoin[j - i] combosByCoin[j] %= modulus } } return combosByCoin } /** * Project Euler specific implementation that requests the first integer N for which the number * of ways N can be partitioned is divisible by 1e6. */ fun firstCoinCombo(): Int { val smallMod = 1_000_000 var limit = 0 var result = -1 while (result == -1) { limit += 10_000 val allPartitions = coinPileCombosTheorem(limit, smallMod) result = allPartitions.indexOfFirst { it.mod(smallMod) == 0 } } return result } /** * Solution is based on the Pentagonal Number Theorem that states: * * (1 - x)(1 - x^2)(1 - x^3)... = 1 - x - x^2 + x^5 + x^7 - x^12 - x^15 + x^22 + x^26 - ... * * The right-side exponents are generalised pentagonal numbers given by the formula: * * g_k = k(3k - 1) / 2, for k = 1, -1, 2, -2, 3, -3, ... * * This holds as an identity for calculating the number of partitions of [limit] based on: * * p(n) = p(n - 1) + p(n - 2) - p(n - 5) - p(n - 7) + ..., which is expressed as: * * p(n) = Sigma{k!=0} ((-1)^{k-1} * p(n - g_k)) * * SPEED (BETTER) 2.51ms for N = 1e3 * SPEED (using BigInteger) 5.50s for N = 6e4 * SPEED (using Long) 1.05s for N = 6e4 * * N.B. This solution originally calculated count using BigInteger & used the modulus after * every summation to allow an integer value to be cached for every N. Using Long instead * improved performance speed by 5x. Because of this change, the count could occasionally * become negative, so a check was placed to reverse the modulus if this occurs. * * @return IntArray of partitions (mod 1e9 + 7) of all N <= limit, with index == N. */ fun coinPileCombosTheorem(limit: Int, modValue: Int = modulus): IntArray { val partitions = IntArray(limit + 1).apply { this[0] = 1 } for (n in 1..limit) { var count = 0L var k = 1 while (true) { val pentagonal = k * (3 * k - 1) / 2 if (pentagonal > n) break val unary = (-1.0).pow(k-1).toLong() count += unary * partitions[n-pentagonal] count %= modValue if (count < 0L) count += modValue k *= -1 if (k.sign == 1) k++ } partitions[n] = count.toInt() } return partitions } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,740
project-euler-kotlin
MIT License
src/Day02.kt
buongarzoni
572,991,996
false
{"Kotlin": 26251}
fun solveDay02() { val input = readInput("Day02").map { ElveMatch.parse(it) } println(input.sumOf { it.points }) val input2 = readInput("Day02").map { NewElveMatch.parse(it) } println(input2.sumOf { it.points }) } data class ElveMatch(val first: String, val second: String) { val points = getResult() + pointsForElection() companion object { fun parse(string: String) = ElveMatch( first = string.take(1), second = string.drop(2), ) } private fun getResult() = when(first) { "A" -> when(second) { "X" -> 3 "Y" -> 6 else -> 0 } "B" -> when(second) { "X" -> 0 "Y" -> 3 else -> 6 } else -> when(second) { "X" -> 6 "Y" -> 0 else -> 3 } } private fun pointsForElection() = when(second) { "X" -> 1 "Y" -> 2 else -> 3 } } data class NewElveMatch(val first: String, val second: String) { val points = getResult() + pointsForElection() companion object { fun parse(string: String) = NewElveMatch( first = string.take(1), second = string.drop(2), ) } private fun getResult() = when(second) { "X" -> 0 "Y" -> 3 else -> 6 } private fun pointsForElection() = when(first) { "A" -> when(second) { "X" -> 3 "Y" -> 1 else -> 2 } "B" -> when(second) { "X" -> 1 "Y" -> 2 else -> 3 } else -> when(second) { "X" -> 2 "Y" -> 3 else -> 1 } } }
0
Kotlin
0
0
96aadef37d79bcd9880dbc540e36984fb0f83ce0
1,741
AoC-2022
Apache License 2.0
src/main/kotlin/problems/Day21.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems import kotlin.math.max class Day21(override val input: String) : Problem { override val number: Int = 21 private val startingPositions = input.lines().map { it.split(": ")[1].toInt() - 1 } override fun runPartOne(): String { var currentPlayer = 0 val scores = mutableListOf(0, 0) val currentPositions = startingPositions.toMutableList() val dice = DeterministicDice() while (!scores.any { it >= 1000 }) { val roll = dice.rollThree() currentPositions[currentPlayer] = (currentPositions[currentPlayer] + roll) % 10 scores[currentPlayer] += currentPositions[currentPlayer] + 1 currentPlayer = (currentPlayer + 1) % 2 } return (dice.rolls * scores.filter { it < 1000 }.single()).toString() } private class DeterministicDice { var rolls = 0 private var currentNumber = 0 fun rollThree(): Int { val roll = 3 * (currentNumber + 1) + 3 currentNumber = (currentNumber + 3) % 100 rolls += 3 return roll } } override fun runPartTwo(): String { val toVisit = mutableSetOf<GameState>() val toVisitHash = mutableMapOf<GameState, Long>() var player1Won = 0L var player2Won = 0L val targetScore = 21 val startingPosition = GameState(0, startingPositions[0].toByte(), 0, startingPositions[1].toByte(), 1) toVisit.add(startingPosition) toVisitHash[startingPosition] = 1 while (toVisit.isNotEmpty()) { val currentGame = toVisit.first() toVisit.remove(currentGame) val next = playerRound(currentGame) val p1Won = next.count { it.player1Score >= targetScore } val p2Won = next.count { it.player2Score >= targetScore } val toVisitNext = next.filter { it.player1Score < targetScore && it.player2Score < targetScore } val count = toVisitHash[currentGame] ?: 0 toVisitHash[currentGame] = 0 player1Won += count * p1Won player2Won += count * p2Won toVisitNext.forEach { toVisitHash[it] = (toVisitHash[it] ?: 0) + count } toVisit.addAll(toVisitNext) } return max(player1Won, player2Won).toString() } private fun playerRound(starting: GameState, round: Int = 1): List<GameState> { return if (round == 3) { listOf( starting.movePlayer(starting.nextPlayer, 1, true), starting.movePlayer(starting.nextPlayer, 2, true), starting.movePlayer(starting.nextPlayer, 3, true) ) } else { playerRound(starting.movePlayer(starting.nextPlayer, 1, false), round + 1) + playerRound(starting.movePlayer(starting.nextPlayer, 2, false), round + 1) + playerRound(starting.movePlayer(starting.nextPlayer, 3, false), round + 1) } } private data class GameState( val player1Score: Byte = 0, val player1Position: Byte, val player2Score: Byte = 0, val player2Position: Byte, val nextPlayer: Byte = 1 ) { fun movePlayer(playerNo: Byte, moves: Byte, finalRoll: Boolean): GameState { return when (playerNo) { 1.toByte() -> { val newPosition = (player1Position + moves) % 10 if (finalRoll) { val newScore = player1Score + newPosition + 1 this.copy( player1Position = newPosition.toByte(), player1Score = newScore.toByte(), nextPlayer = 2 ) } else { this.copy(player1Position = newPosition.toByte()) } } else -> { val newPosition = (player2Position + moves) % 10 if (finalRoll) { val newScore = player2Score + newPosition + 1 this.copy( player2Position = newPosition.toByte(), player2Score = newScore.toByte(), nextPlayer = 1 ) } else { this.copy(player2Position = newPosition.toByte()) } } } } } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
4,580
AdventOfCode2021
MIT License
aoc_2023/src/main/kotlin/problems/day8/DesertMap.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day8 import problems.utils.Utils class DesertMap(val directions: List<Int>, val connections: Map<String, Pair<String, String>>) { companion object { val inputRegex = Regex("""(.*) = \((.*), (.*)\)""") } constructor(lines: List<String>) : this(lines[0].map { when (it) { 'L' -> 0 'R' -> 1 else -> 2 } }, lines.drop(2).map { val valuesRegex = inputRegex.findAll(it).first().groupValues valuesRegex[1] to Pair(valuesRegex[2], valuesRegex[3]) }.toMap()) fun stepsSolution(): Int { var steps = 0 var state = "AAA" while (state != "ZZZ") { val stepVal = this.directions[steps % this.directions.count()] steps++ state = this.connections[state]!!.toList()[stepVal] } return steps } fun ghostSolutions(state: String): List<GhostMapSolution> { val solutions: MutableList<GhostMapSolution> = mutableListOf() var initialStep = 0 var initialState = state var steps = 0 var currentState = state while (true) { val stepVal = this.directions[steps % this.directions.count()] currentState = this.connections[currentState]!!.toList()[stepVal] steps++ if (currentState.last() == 'Z') { val sol = GhostMapSolution(initialState, initialStep, currentState, steps) solutions.add(sol) initialState = currentState initialStep = steps if (solutions.any { it.startSite == currentState && it.startIndex % this.directions.count() == steps % this.directions.count() }) break } } return solutions } fun ghostStepsSolution(): Long { val states = this.connections.keys.filter { it.last() == 'A' } val solutionsEachState = states.map { ghostSolutions(it) } val repeatingLengths = solutionsEachState.map { (it.last().endIndex - it.last().startIndex).toLong() } val solutionLength = Utils.calculateLCM(repeatingLengths) return solutionLength } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
2,188
advent-of-code-2023
MIT License
src/day05/Day05.kt
voom
573,037,586
false
{"Kotlin": 12156}
package day05 import readInput /** * --- Day 5: Supply Stacks --- */ fun main() { val p = Regex("\\d+") fun parseMoves(input: List<String>): List<List<Int>> { return input .map { record -> p.findAll(record) .map { it.value.toInt() - 1 } .toList() } } fun part1(stacks: List<ArrayDeque<String>>, input: List<String>): String { parseMoves(input) .map { (n, from, to) -> for (i in 0..n) { stacks[from].removeLastOrNull()?.let { stacks[to].addLast(it) } } } return stacks .map { it.last() } .reduce { acc, c -> acc + c } } fun part2(stacks: List<ArrayDeque<String>>, input: List<String>): String { parseMoves(input) .map { (n, from, to) -> val fromLast = stacks[from].lastIndex stacks[from].subList(fromLast - n, fromLast + 1) .let { stacks[to].addAll(it) } for (i in 0..n) { stacks[from].removeLastOrNull() } } return stacks .map { it.last() } .reduce { acc, c -> acc + c } } // test if implementation meets criteria from the description, like: val testInput = readInput("day05/test_input") /* [D] [N] [C] [Z] [M] [P] 1 2 3 */ val testStacks = listOf( ArrayDeque(listOf("Z", "N")), ArrayDeque(listOf("M", "C", "D")), ArrayDeque(listOf("P")), ) // stacks are mutable, therefore running one at a time // check(part1(testStacks, testInput) == "CMZ") check(part2(testStacks, testInput) == "MCD") val input = readInput("day05/input") /* [H] [S] [D] [S] [C] [C] [Q] [L] [C] [R] [Z] [R] [H] [Z] [G] [N] [H] [S] [B] [R] [F] [D] [T] [Q] [F] [Q] [Z] [Z] [N] [Z] [W] [F] [N] [F] [W] [J] [V] [G] [T] [R] [B] [C] [L] [P] [F] [L] [H] [H] [Q] [P] [L] [G] [V] [Z] [D] [B] 1 2 3 4 5 6 7 8 9 */ val stacks = listOf( ArrayDeque(listOf("D", "Z", "T", "H").reversed()), ArrayDeque(listOf("S", "C", "G", "T", "W", "R", "Q").reversed()), ArrayDeque(listOf("H", "C", "R", "N", "Q", "F", "B", "P").reversed()), ArrayDeque(listOf("Z", "H", "F", "N", "C", "L").reversed()), ArrayDeque(listOf("S", "Q", "F", "L", "G").reversed()), ArrayDeque(listOf("S", "C", "R", "B", "Z", "W", "P", "V").reversed()), ArrayDeque(listOf("J", "F", "Z").reversed()), ArrayDeque(listOf("Q", "H", "R", "Z", "V", "L", "D").reversed()), ArrayDeque(listOf("D", "L", "Z", "F", "N", "G", "H", "B").reversed()), ) // stacks are mutable, therefore running one at a time // println(part1(stacks, input)) println(part2(stacks, input)) }
0
Kotlin
0
1
a8eb7f7b881d6643116ab8a29177d738d6946a75
2,986
aoc2022
Apache License 2.0
src/main/kotlin/year2022/day16/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2022.day16 import IProblem import sublst import substr import kotlin.math.max class Problem : IProblem { private val valves = linkedMapOf<String, Valve>() private val dist: Array<IntArray> init { val parents = mutableMapOf<String, MutableSet<Valve>>() var i = 0 javaClass .getResourceAsStream("/2022/16.txt")!! .bufferedReader() .forEachLine { line -> val split = line.split(' ') val name = split[1] val rate = split[4].substr(5, -1).toInt() val adjs = split.sublst(9, -1).map { it.substr(0, -1) } + split[split.lastIndex] val valve = Valve(i++, name, rate) valves[name] = valve parents[name]?.forEach { it.adjs.add(valve) } for (key in adjs) { val parentSet = parents.computeIfAbsent(key) { mutableSetOf() } val adj = valves[key] if (adj == null) { parentSet.add(valve) } else { valve.adjs.add(adj) } } } dist = Array(valves.size) { IntArray(valves.size) { INFINITY } } floydWarshall() } private fun floydWarshall() { val n = valves.size for (valve in valves.values) { dist[valve.id][valve.id] = 0 for (adj in valve.adjs) { dist[valve.id][adj.id] = 1 } } for (k in 0 until n) { for (i in 0 until n) { for (j in 0 until n) { if (dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j] } } } } } private fun maxFlow(source: Valve, time: Int, closed: Collection<Valve>): Int { if (time > TIME) { return 0 } var flow = 0 for (dest in closed) { val copy = closed.toMutableSet().also { it.remove(dest) } flow = max(flow, maxFlow(dest, time + dist[source.id][dest.id] + 1, copy)) } return source.rate * (TIME - time) + flow } private fun allPaths(source: Valve, time: Int, closed: Collection<Valve>, flow: Int, path: List<Valve>, paths: MutableList<Pair<Int, List<Valve>>>) { if (time > TIME) { return } val flow0 = flow + source.rate * (TIME - time) for (dest in closed) { val time0 = time + dist[source.id][dest.id] + 1 val closed0 = closed.toMutableSet().also { it.remove(dest) } val path0 = path.toMutableList().also { it.add(dest) } allPaths(dest, time0, closed0, flow0, path0, paths) } paths.add(Pair(flow0, path)) } override fun part1(): Int { val start = valves[START]!! val closed = valves.values.filter { it.rate != 0 } return maxFlow(start, 0, closed) } override fun part2(): Int { val start = valves[START]!! val closed = valves.values.filter { it.rate != 0 } val paths = mutableListOf<Pair<Int, List<Valve>>>() var flow = 0 allPaths(start, 4, closed, 0, listOf(), paths) paths.sortByDescending(Pair<Int, List<Valve>>::first) for (i in paths.indices) { val s = paths[i].second.toSet() for (j in i + 1 until paths.size) { if (paths[i].first + paths[j].first <= flow) { break } if (paths[j].second.none { it in s }) { flow = paths[i].first + paths[j].first } } } return flow } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
3,819
advent-of-code
The Unlicense
src/Day09.kt
nordberg
573,769,081
false
{"Kotlin": 47470}
import java.lang.IllegalArgumentException import kotlin.math.abs enum class Direction { UP, UPRIGHT, UPLEFT, DOWN, DOWNRIGHT, DOWNLEFT, LEFT, RIGHT } data class Move(val direction: Direction, val steps: Int) data class Point(val x: Int, val y: Int) { fun distanceTo(otherPoint: Point): Int { return abs(x - otherPoint.x) + abs(y - otherPoint.y) } } data class Rope(val head: Point, val tail: Point) { operator fun plus(move: Move): List<Rope> { val newPositions = mutableListOf<Rope>() var updatingRope = this.copy() for (step in 1..move.steps) { val newHead = applyMoveToKnot(move.direction, updatingRope.head) val headToTailDist = newHead.distanceTo(updatingRope.tail) val tailNeedsToMove = ((headToTailDist > 1 && (newHead.x == updatingRope.tail.x || newHead.y == updatingRope.tail.y) || headToTailDist > 2)) val newTail = if (tailNeedsToMove) { val dirToMove = Direction.values().reduce { acc, dir -> val distIfMoveAcc = newHead.distanceTo(applyMoveToKnot(acc, updatingRope.tail)) val distIfMoveDir = newHead.distanceTo(applyMoveToKnot(dir, updatingRope.tail)) val bestDiagonalMove = applyDiagonalMoves(updatingRope.tail, newHead) val newPointIfBestDiagonalMove = applyMoveToKnot(bestDiagonalMove, updatingRope.tail) val distIfBestDiagonal = newPointIfBestDiagonalMove.distanceTo(newHead) val listOfDists = listOf(distIfMoveAcc, distIfBestDiagonal, distIfMoveDir) when (listOfDists.sorted().first { it > 0 }) { distIfMoveAcc -> acc distIfMoveDir -> dir distIfBestDiagonal -> bestDiagonalMove else -> throw IllegalStateException() } } applyMoveToKnot(dirToMove, updatingRope.tail) } else { tail } updatingRope = Rope(newHead, newTail) newPositions.add(updatingRope) //println("Move was \n\t${move}, \nold rope was \n\t$this\n and new rope was \n\t$updatingRope") } return newPositions } private fun applyDiagonalMoves(point: Point, targetPoint: Point): Direction { val validPairs = listOf( Direction.UPLEFT, Direction.DOWNLEFT, Direction.DOWNRIGHT, Direction.UPRIGHT ) val directionMinimizingDistanceToTarget = validPairs.reduce { acc, it -> val distAcc = applyMoveToKnot(acc, point).distanceTo(targetPoint) val distIt = applyMoveToKnot(it, point).distanceTo(targetPoint) if (distAcc < distIt) { acc } else { it } } return directionMinimizingDistanceToTarget } private fun applyMoveToKnot(direction: Direction, point: Point): Point { return when (direction) { Direction.UP -> Point(point.x, point.y - 1) Direction.DOWN -> Point(point.x, point.y + 1) Direction.LEFT -> Point(point.x - 1, point.y) Direction.RIGHT -> Point(point.x + 1, point.y) Direction.UPRIGHT -> Point(point.x + 1, point.y - 1) Direction.DOWNRIGHT -> Point(point.x + 1, point.y + 1) Direction.DOWNLEFT -> Point(point.x - 1, point.y + 1) Direction.UPLEFT -> Point(point.x - 1, point.y - 1) } } } data class RopePt2(val head: Point, val tail: List<Point>) { fun wholeRope(): List<Point> { return listOf(head) + tail } operator fun plus(move: Move): List<Rope> { // if (tail.isEmpty()) { // return listOf() // } // val newPositions = mutableListOf<Rope>() // var updatingRope = this.copy() // for (step in 1..move.steps) { // val newHead = applyMoveToKnot(move.direction, updatingRope.head) // val firstKnot = updatingRope.tail.first() // // val headToTailDist = newHead.distanceTo(firstKnot) // val tailNeedsToMove = // ((headToTailDist > 1 && (newHead.x == firstKnot.x || newHead.y == firstKnot.y) || headToTailDist > 2)) // val newTail = if (tailNeedsToMove) { // val dirToMove = Direction.values().reduce { acc, dir -> // val distIfMoveAcc = newHead.distanceTo(applyMoveToKnot(acc, firstKnot)) // val distIfMoveDir = newHead.distanceTo(applyMoveToKnot(dir, updatingRope.tail)) // val bestDiagonalMove = applyDiagonalMoves(updatingRope.tail, newHead) // val newPointIfBestDiagonalMove = applyMoveToKnot(bestDiagonalMove, updatingRope.tail) // val distIfBestDiagonal = newPointIfBestDiagonalMove.distanceTo(newHead) // // val listOfDists = listOf(distIfMoveAcc, distIfBestDiagonal, distIfMoveDir) // when (listOfDists.sorted().first { it > 0 }) { // distIfMoveAcc -> acc // distIfMoveDir -> dir // distIfBestDiagonal -> bestDiagonalMove // else -> throw IllegalStateException() // } // } // applyMoveToKnot(dirToMove, updatingRope.tail) // } else { // tail // } // // val tailRope = RopePt2(tail.first(), tail.drop(1) // // //updatingRope = RopePt2(newHead, newTail) // //newPositions.add(updatingRope) // //println("Move was \n\t${move}, \nold rope was \n\t$this\n and new rope was \n\t$updatingRope") // } // // return newPositions return emptyList() } private fun applyDiagonalMoves(point: Point, targetPoint: Point): Direction { val validPairs = listOf( Direction.UPLEFT, Direction.DOWNLEFT, Direction.DOWNRIGHT, Direction.UPRIGHT ) val directionMinimizingDistanceToTarget = validPairs.reduce { acc, it -> val distAcc = applyMoveToKnot(acc, point).distanceTo(targetPoint) val distIt = applyMoveToKnot(it, point).distanceTo(targetPoint) if (distAcc < distIt) { acc } else { it } } return directionMinimizingDistanceToTarget } private fun applyMoveToKnot(direction: Direction, point: Point): Point { return when (direction) { Direction.UP -> Point(point.x, point.y - 1) Direction.DOWN -> Point(point.x, point.y + 1) Direction.LEFT -> Point(point.x - 1, point.y) Direction.RIGHT -> Point(point.x + 1, point.y) Direction.UPRIGHT -> Point(point.x + 1, point.y - 1) Direction.DOWNRIGHT -> Point(point.x + 1, point.y + 1) Direction.DOWNLEFT -> Point(point.x - 1, point.y + 1) Direction.UPLEFT -> Point(point.x - 1, point.y - 1) } } } fun main() { fun part1(moves: List<Move>): Int { var currentPos = Rope(Point(0, 0), Point(0, 0)) val visitedPointsOnMap = moves.flatMap { val newRopes = currentPos + it currentPos = newRopes.last() newRopes.map { i -> i.tail } }.toSet() + setOf(Point(0, 0)) println(visitedPointsOnMap.size) return visitedPointsOnMap.size } fun part2(input: List<Move>): Int { // val tailPoints = (1..9).map { Point(0, 0) }.toList() // var currentPos = RopePt2(Point(0, 0), tailPoints) // val visitedPointsOnMap = moves.flatMap { // val newRopes = currentPos + it // currentPos = TODO() // newRopes.map { i -> i.tail } // }.toSet() + setOf(Point(0, 0)) // println(visitedPointsOnMap.size) // return visitedPointsOnMap.size return 5 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val moves = parseMoves(testInput) check(part1(moves) == 13) val input = readInput("Day09") println(part1(parseMoves(input))) println(part2(parseMoves(input))) } private fun parseMoves(input: List<String>): List<Move> { val moves = input.map { val (direction, dist) = it.split(" ") val dirDir = when (direction) { "R" -> Direction.RIGHT "L" -> Direction.LEFT "U" -> Direction.UP "D" -> Direction.DOWN else -> throw IllegalArgumentException("$direction is error") } Move(dirDir, dist.toInt()) }.toList() return moves }
0
Kotlin
0
0
3de1e2b0d54dcf34a35279ba47d848319e99ab6b
8,861
aoc-2022
Apache License 2.0
src/main/kotlin/aoc2020/day1.kt
sodaplayer
434,841,315
false
{"Kotlin": 31068}
package aoc2020.day1 import aoc2020.utils.loadInput fun main() { val numbers = loadInput("/2020/day1") .bufferedReader() .readLines() .map(String::toInt) val complements = numbers.associateBy { 2020 - it } val allPairs = sequence { for ((i, m) in numbers.withIndex()) { for (n in numbers.subList(i, numbers.size)) { if (n + m > 2020) { continue } yield(Triple(m, n, m+n)) } } } val asdf = allPairs.firstNotNullOf { (a, b, sum) -> complements[sum]?.let { Triple(a, b, it) } } asdf.let { (a, b, c) -> { println(a * b * c) } } val forTwo = numbers.findPairOfSum(2020) println(forTwo) println(forTwo.first * forTwo.second) } private fun List<Int>.findPairOfSum(sum: Int): Pair<Int, Int> { val complements = associateBy { sum - it } return firstNotNullOf { number -> complements[number]?.let { Pair(it, number) } } }
0
Kotlin
0
0
2d72897e1202ee816aa0e4834690a13f5ce19747
1,066
aoc-kotlin
Apache License 2.0
day21/src/main/kotlin/de/havox_design/aoc2023/day21/Day21.kt
Gentleman1983
715,778,541
false
{"Kotlin": 163912, "Python": 1048}
package de.havox_design.aoc2023.day21 import kotlin.math.pow class Day21(private var filename: String) { private val ICON_ROCK = '#' private val ICON_START = 'S' fun solvePart1(steps: Int = 64): Long { val rocks = HashSet<Pair<Int, Int>>() var start = Pair(0, 0) for ((row, inputRow) in getResourceAsText(filename).withIndex()) { inputRow.forEachIndexed { col, ch -> when (ch) { ICON_START -> start = Pair(col, row) ICON_ROCK -> rocks.add(Pair(col, row)) } } } var reachablePlots = HashSet<Pair<Int, Int>>() reachablePlots.add(start) for (i in 1..steps) { val next = HashSet<Pair<Int, Int>>() for (position in reachablePlots) { move(position, Direction.UP, rocks) ?.let { next.add(it) } move(position, Direction.RIGHT, rocks) ?.let { next.add(it) } move(position, Direction.DOWN, rocks) ?.let { next.add(it) } move(position, Direction.LEFT, rocks) ?.let { next.add(it) } } reachablePlots = next } return reachablePlots .size .toLong() } fun solvePart2(steps: Long = 26501365L): Long { val rocks = HashSet<Pair<Int, Int>>() var start = Pair(0, 0) var rows = 0 for (inputRows in getResourceAsText(filename)) { inputRows.forEachIndexed { col, ch -> val row = rows when (ch) { ICON_START -> start = Pair(col, row) ICON_ROCK -> rocks.add(Pair(col, row)) } } rows++ } val grids = steps / rows - 1 val oddGrids = (grids / 2 * 2 + 1) .toDouble() .pow(2) .toLong() val evenGrids = ((grids + 1) / 2 * 2) .toDouble() .pow(2) .toLong() return sumUpReachablePlots(oddGrids, start, rows, rocks, evenGrids, grids) } private fun sumUpReachablePlots( oddGrids: Long, start: Pair<Int, Int>, rows: Int, rocks: HashSet<Pair<Int, Int>>, evenGrids: Long, grids: Long ) = oddGrids * reachable(start, rows * 2 + 1, rocks, rows) + evenGrids * reachable(start, rows * 2, rocks, rows) + reachable(Pair(start.first, rows - 1), rows - 1, rocks, rows) + reachable(Pair(0, start.second), rows - 1, rocks, rows) + reachable(Pair(start.first, 0), rows - 1, rocks, rows) + reachable(Pair(rows - 1, start.second), rows - 1, rocks, rows) + ( (grids + 1) * (reachable(Pair(0, rows - 1), rows / 2 - 1, rocks, rows) + reachable(Pair(rows - 1, rows - 1), rows / 2 - 1, rocks, rows) + reachable(Pair(0, 0), rows / 2 - 1, rocks, rows) + reachable(Pair(rows - 1, 0), rows / 2 - 1, rocks, rows)) ) + ( grids * (reachable(Pair(0, rows - 1), rows * 3 / 2 - 1, rocks, rows) + reachable(Pair(rows - 1, rows - 1), rows * 3 / 2 - 1, rocks, rows) + reachable(Pair(0, 0), rows * 3 / 2 - 1, rocks, rows) + reachable(Pair(rows - 1, 0), rows * 3 / 2 - 1, rocks, rows)) ) private fun move( position: Pair<Int, Int>, direction: Direction, rocks: HashSet<Pair<Int, Int>> ): Pair<Int, Int>? = when { !rocks.contains( Pair( position.first + direction.direction.first, position.second + direction.direction.second ) ) -> { Pair( position.first + direction.direction.first, position.second + direction.direction.second ) } else -> { null } } private fun reachable(from: Pair<Int, Int>, steps: Int, rocks: HashSet<Pair<Int, Int>>, rows: Int): Int { var reachablePlots = HashSet<Pair<Int, Int>>() reachablePlots.add(from) for (i in 1..steps) { val next = HashSet<Pair<Int, Int>>() fun move(p: Pair<Int, Int>, dir: Pair<Int, Int>) { if (!rocks.contains(Pair(p.first + dir.first, p.second + dir.second))) { next.add(Pair(p.first + dir.first, p.second + dir.second)) } } for (position in reachablePlots) { move(position, Direction.UP, rocks) ?.let { next.add(it) } move(position, Direction.RIGHT, rocks) ?.let { next.add(it) } move(position, Direction.DOWN, rocks) ?.let { next.add(it) } move(position, Direction.LEFT, rocks) ?.let { next.add(it) } } reachablePlots = next } return reachablePlots.count { it.first >= 0 && it.second >= 0 && it.first < rows && it.second < rows } } private fun getResourceAsText(path: String): List<String> = this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines() }
1
Kotlin
0
0
eac8ff77420f061f5cef0fd4b8d05e7805c4cc5a
5,538
aoc2023
Apache License 2.0
solutions/src/CountLuck.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://www.hackerrank.com/challenges/count-luck/problem */ class CountLuck { // Complete the countLuck function below. fun countLuck(matrix: Array<String>, k: Int): String { return if (determineStepDirectionSwitches(matrix, k)) "Impressed" else "Oops!" } private fun determineStepDirectionSwitches(matrix: Array<String>, k: Int) : Boolean { val m = matrix.size val n = matrix[0].length val queue = mutableListOf<Step>() val visited = mutableSetOf<Pair<Int,Int>>() for (i in 0 until m) { for (j in 0 until n) { if (matrix[i][j] == 'M') { queue.add(Step(Pair(i,j),0,DIRECTION.NONE)) } } } while (queue.isNotEmpty()) { val current = queue.removeAt(0) val currentCoordinates = current.coordinates //Check if at destination if (matrix[currentCoordinates.first][currentCoordinates.second] == '*') { return current.changes == k } //Add Coordinates to Visited visited.add(currentCoordinates) //UP val upStep = Step( Pair(currentCoordinates.first-1,currentCoordinates.second), current.changes, DIRECTION.UP ) //Down val downStep = Step( Pair(currentCoordinates.first+1,currentCoordinates.second), current.changes, DIRECTION.DOWN ) //Left val leftStep = Step( Pair(currentCoordinates.first,currentCoordinates.second-1), current.changes, DIRECTION.LEFT ) //Right val rightStep = Step( Pair(currentCoordinates.first,currentCoordinates.second+1), current.changes, DIRECTION.RIGHT ) var possibleSteps = listOf( upStep, downStep, leftStep, rightStep ).filter { val stepCoordinates = it.coordinates stepCoordinates.first >= 0 && stepCoordinates.second >= 0 && stepCoordinates.first < m && stepCoordinates.second < n && matrix[stepCoordinates.first][stepCoordinates.second] != 'X' && !visited.contains(stepCoordinates) } if (possibleSteps.size > 1) { possibleSteps = possibleSteps.map { it.copy(changes = it.changes+1) } } possibleSteps.forEach { queue.add(it) } } return false } private enum class DIRECTION { UP, DOWN, LEFT, RIGHT, NONE } private data class Step(val coordinates: Pair<Int,Int>, val changes: Int,val direction: DIRECTION ) }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
3,077
leetcode-solutions
MIT License
src/main/kotlin/days/Day10.kt
andilau
429,206,599
false
{"Kotlin": 113274}
package days import kotlin.math.PI import kotlin.math.atan2 import kotlin.math.sqrt @AdventOfCodePuzzle( name = "Monitoring Station", url = "https://adventofcode.com/2019/day/10", date = Date(day = 10, year = 2019) ) class Day10(input: List<String>) : Puzzle { private val asteroids: List<Asteroid> = parseAsteroids(input) override fun partOne() = asteroids .findOptimalBase().asteroidsInSight() override fun partTwo() = asteroids .findOptimalBase() .targets() .drop(199).first() .let { (it.x * 100) + it.y } fun findOptimalBase() = asteroids.findOptimalBase() fun targetsAsteroids(base: Asteroid) = base.targets() private fun List<Asteroid>.findOptimalBase() = maxByOrNull { base -> base.asteroidsInSight() } ?: throw IllegalStateException("Best Base not found") private fun Asteroid.asteroidsInSight() = asteroids.filter { it != this } .map { relativeTo(it) } .distinctBy { it.angle() } .size private fun Asteroid.targets() = asteroids .filter { it != this } .groupBy { it.relativeTo(this).angle() } .mapValues { (_, asteroids) -> asteroids.sortedBy { it.relativeTo(this).distance() } } .toSortedMap() .values .flattenByIndex() private fun parseAsteroids(input: List<String>) = input.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, what -> if (what == ASTEROID) Asteroid(x, y) else null } } data class Asteroid(val x: Int, val y: Int) { infix fun Int.to(that: Int): Asteroid = Asteroid(this, that) fun relativeTo(base: Asteroid): Asteroid = x - base.x to y - base.y private operator fun plus(base: Asteroid): Asteroid = x + base.x to y + base.y private operator fun minus(that: Asteroid): Asteroid = x - that.x to y - that.y fun distance() = sqrt((x * x) + (y * y).toDouble()) /* https://math.stackexchange.com/questions/1201337/finding-the-angle-between-two-points" */ fun angle() = (PI / 2 + atan2(y.toDouble(), x.toDouble())) .let { if (it >= 0) it else it + 2 * PI } } companion object { const val ASTEROID = '#' } }
2
Kotlin
0
0
f51493490f9a0f5650d46bd6083a50d701ed1eb1
2,359
advent-of-code-2019
Creative Commons Zero v1.0 Universal
src/main/kotlin/championofgoats/advent/2019/day3/day3.kt
ChampionOfGoats
225,446,764
false
null
package championofgoats.advent.twentynineteen.day3 import java.io.File import java.util.* import championofgoats.advent.Problem import championofgoats.advent.utils.Point import championofgoats.advent.utils.logging.Logger object Day3 : Problem { override fun solve(inputDir: String, outputDir: String, log: Logger) { // given a two points describing an edge, append to l all points that are touched by the edge // return l fun appendEdge(l: MutableList<Point>, origin: Point, instruction: String) : MutableList<Point> { var offset = when (instruction.first()) { 'U' -> Point(0, 1) 'R' -> Point(1, 0) 'D' -> Point(0, -1) 'L' -> Point(-1, 0) else -> Point(0, 0) } var totalPoints = instruction.drop(1).toInt() // the number of steps for (i in 1..totalPoints) { var p = Point(origin.x + (offset.x * i), origin.y + (offset.y * i)) l.add(p) } return l } // read the input, parse to point lists var wires = mutableListOf<MutableList<Point>>() File("$inputDir/day3.input").forEachLine { var edges = it.split(",") var wire = mutableListOf<Point>() var origin = Point(0, 0) for (edge in edges) { wire = appendEdge(wire, origin, edge) origin = wire.last() } wires.add(wire) } // create a hashmap, keyed by points // initially, populate with each point passed by the first wire // do so once for each point, such that each k -> v is k -> 1 var stepMap = hashMapOf<Point, Int>() var hashMap = hashMapOf<Point, Int>() var firstWire = wires.get(0) for (i in 0..firstWire.size-1) { var p = firstWire.get(i) if (!hashMap.containsKey(p)) { hashMap.set(p, 1) // initially, step map value for p is indexOf(p) + 1 stepMap.set(p, i+1) } } // then, for the second wire, increment any points that already appear at least once var totalWires = wires.size - 1 for (w in 1..totalWires) { var wire = wires.get(w) for (i in 0..wire.size-1) { var p = wire.get(i) if (hashMap.containsKey(p)) { // v = w if wire not yet counted for p var v = hashMap.getValue(p) if (v == w) { hashMap.set(p, v + 1) var s = stepMap.getValue(p) // each additional point is step map v(p) + indexOf(p) + 1 stepMap.set(p, s + i + 1) } } } } // filter out any values which don't occur at least as many times as there are wires var output = hashMap.filterValues { it == wires.size } // reduce keys to list, sorting ascending by rectilinear distance log.Solution("DAY3p1 ans = %s".format(output.map{ (k,_) -> k.x + k.y }.sorted().first())) // filter out any points from steps that don't appear in the output candidates // map down to values and sort ascending log.Solution("DAY3p2 ans = %s".format(stepMap.filterKeys{ output.containsKey(it) }.map{ (_,v) -> v }.sorted().first())) } }
0
Kotlin
0
0
4f69de1579f40928c1278c3cea4e23e0c0e3b742
3,537
advent-of-code
MIT License
src/main/kotlin/QuicksortDualPivot.kt
Codextor
453,514,033
false
{"Kotlin": 26975}
/** * Swap two elements in an array. */ private fun swap(arr: Array<Int>, i: Int, j: Int) { val temp = arr[i] arr[i] = arr[j] arr[j] = temp } /** * Partition the array around two pivots. * Return the indices of the pivots. */ private fun partition(arr: Array<Int>, left: Int, right: Int): Pair<Int, Int> { if (arr[left] > arr[right]) swap(arr, left, right) val leftPivot = arr[left] val rightPivot = arr[right] var leftPivotIndex = left var rightPivotIndex = right for (index in leftPivotIndex+1 until rightPivotIndex) { if (arr[index] < leftPivot) { leftPivotIndex++ swap(arr, leftPivotIndex, index) } else if (arr[index] >= rightPivot) { while (arr[rightPivotIndex-1] > rightPivot && index < rightPivotIndex-1) rightPivotIndex-- rightPivotIndex-- swap(arr, rightPivotIndex, index) if (arr[index] < leftPivot) { leftPivotIndex++ swap(arr, leftPivotIndex, index) } } } swap(arr, left, leftPivotIndex) swap(arr, right, rightPivotIndex) return Pair(leftPivotIndex, rightPivotIndex) } /** * Quick sort the array using two pivots. */ private fun quickSortDualPivot(arr: Array<Int>, left: Int, right: Int) { if (left < right) { val pivotIndices = partition(arr, left, right) quickSortDualPivot(arr, left, pivotIndices.first - 1) quickSortDualPivot(arr, pivotIndices.first + 1, pivotIndices.second - 1) quickSortDualPivot(arr, pivotIndices.second + 1, right) } } fun main() { val arrayOfIntegers = readLine()?.trimEnd()?.split(" ")?.map { it.toInt() }?.toTypedArray() ?: return quickSortDualPivot(arrayOfIntegers, 0, arrayOfIntegers.size-1) arrayOfIntegers.forEach { print("$it ") } }
0
Kotlin
1
0
68b75a7ef8338c805824dfc24d666ac204c5931f
1,842
kotlin-codes
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2022/Day15.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2022 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.XY import com.s13g.aoc.manhattan import com.s13g.aoc.resultFrom import com.s13g.aoc.subtract import kotlin.math.abs import kotlin.math.max /** * --- Day 15: Beacon Exclusion Zone --- * https://adventofcode.com/2022/day/15 */ class Day15 : Solver { private val re = """x=(-?\d+), y=(-?\d+): .* x=(-?\d+), y=(-?\d+)$""".toRegex() override fun solve(lines: List<String>): Result { val sensors = lines.map { parse(it) }.toSet() val beaconPos = sensors.map { it.clBeacon }.toSet() val minX = sensors.minOf { it.pos.x - it.radius() } val maxX = sensors.maxOf { it.pos.x + it.radius() } var countA = 0 for (x in minX..maxX) { val probe = XY(x, 2000000) if (isEmpty(probe, sensors) && (probe !in beaconPos)) countA++ } return resultFrom(countA.toLong(), findBeaconFreq(sensors)) } private fun findBeaconFreq(sensors: Set<Sensor>): Long { for (y in 0..4000000) { val pos = XY(0, y) while (pos.x <= 4000000) { // Which sensors can see us right now? val inRangeOf = sensors.filter { dist(it.pos, pos).manhattan() <= it.radius() } if (inRangeOf.isEmpty()) { // We found the gap! return pos.x.toLong() * 4000000L + pos.y.toLong() } // Skip forward by looking at the width of that sensor on our line. for (sensor in inRangeOf) { val diffY = abs(sensor.pos.y - pos.y) val width = sensor.radius() - diffY // Skip to this based on remaining width. pos.x = max(sensor.pos.x + width + 1, pos.y) } } } throw RuntimeException("Cannot find beacon") } private fun isEmpty(pos: XY, sensors: Set<Sensor>): Boolean { for (sensor in sensors) { if (pos.subtract(sensor.pos).manhattan() <= sensor.radius()) { return true } } return false } private fun dist(pos: XY, loc: XY) = XY(abs(loc.x - pos.x), abs(loc.y - pos.y)) private fun parse(line: String): Sensor { val (posX, posY, bX, bY) = re.find(line)!!.destructured return Sensor(XY(posX.toInt(), posY.toInt()), XY(bX.toInt(), bY.toInt())) } } data class Sensor(val pos: XY, val clBeacon: XY) { fun radius() = clBeacon.subtract(pos).manhattan() }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,345
euler
Apache License 2.0
scratch/src/main/kotlin/x/scratch/problem6.kt
binkley
184,655,460
false
null
package x.scratch import com.github.ajalt.mordant.AnsiCode import com.github.ajalt.mordant.TermColors import x.scratch.Problem6.Companion.problem6 import kotlin.math.log import kotlin.math.round import kotlin.math.sqrt /** * Empirically, the first 50 are quickly computable before becoming too * sparse. */ private const val MAX_N = 50L /** * A quick and dirty cutoff for recognizing floating point rounding errors * in computing the exponent of "a=b^EXP". */ private const val ROUND_AT = 0.000001 fun main() { println("a >= b (UPPER DIAGONAL)") println("(a,b) → a²+b²⁄ab+1 [square²] [log_b(a)]") println("----------------------------------------") // Tracking how sparse the squares become val sparseness = mutableListOf<Pair<Long, Long>>() // Tracking exponents for "a=b^EXP" val exponents = mutableListOf<Any>() var i = 0L var n = 0L var a = 0L loop@ while (true) { ++a for (b in 1..a) { ++i val value = problem6(a, b) if (!value.integral) continue // Non-integer result ++n val exponent = roundIfClose(value.exponent()) println(value.format(n, exponent)) sparseness += n to i exponents += exponent if (n == MAX_N) break@loop } } println() println("Nth⁄CHECKED → FREQ%") println("--------------------") sparseness.forEach { (n, i) -> println("$n⁄$i → ${n.toDouble() * 100 / i}%") } println() println("COUNT → a=b^EXP") println("---------------") // Sort by count descending; sub-sort by exponent descending // Casting business is unfortunate to support typing for comparison with(TermColors()) { exponents .map { when (it) { is Long -> it.toDouble() else -> it as Double } } .groupingBy { it }.eachCount().toList() .sortedBy { (exp, _) -> exp } .sortedBy { (_, count) -> count } .reversed().forEach { (exponent, count) -> val exp = roundIfClose(exponent) println("$count → ${exponentColor(exp)(exp.toString())}") } } } /** * See https://youtu.be/Y30VF3cSIYQ * See https://youtu.be/L0Vj_7Y2-xY */ class Problem6 private constructor(val a: Long, val b: Long) { val numerator: Long = a * a + b * b val denominator: Long = a * b + 1 /** Checks that this is an integral value. */ val integral = 0L == numerator % denominator /** Returns the square root. */ fun sqrt() = sqrt(numerator.toDouble() / denominator).toLong() /** * Returns the integral _or_ floating point exponent `EXP` such that * `a=b^EXP`. * * @return Int or Double */ fun exponent() = if (a == b) 0.0 else log(a.toDouble(), b.toDouble()) companion object { fun problem6(a: Long, b: Long) = Problem6(a, b) } } private fun Problem6.format(n: Long, exp: Any) = with(TermColors()) { val sqrt = sqrt() "#$n: ($a,${bColor(b, sqrt)( b.toString() )}) → $numerator⁄$denominator [${sqrtColor(b, sqrt)( sqrt.toString() )}²] [^${ exponentColor(exp)(exp.toString())}]" } private fun TermColors.bColor(b: Long, sqrt: Long) = when (b) { sqrt * sqrt * sqrt -> green sqrt -> blue else -> reset } private fun TermColors.sqrtColor(b: Long, sqrt: Long) = when (b) { sqrt * sqrt * sqrt -> green sqrt -> blue else -> reset } private fun TermColors.exponentColor(exp: Any): AnsiCode { if (exp is Double) return yellow // non-integral return when (exp as Long) { 2L -> green // b == sqrt^3 3L -> blue // b == sqrt else -> reset } } private fun roundIfClose(d: Double): Any { val rounded = round(d) return if (d - rounded <= ROUND_AT) rounded.toLong() else d }
0
Kotlin
1
2
4787a43f8e27dbde3a967b35f5a3363864cbd51f
4,005
spikes
The Unlicense
src/main/kotlin/Day02.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.time.LocalDateTime import java.time.ZoneOffset fun main() { fun gameNumber(line: String) = line.substringBefore(":").substringAfter("Game ").toInt() fun games(line: String) = line.substringAfter(": ").split("; ") fun cubeCounts(gameStrings: List<String>) = gameStrings.map { game -> game.split(", ").map { cubeString -> val count = cubeString.substringBefore(" ").toInt() val colour = cubeString.substringAfter(" ") colour to count } }.flatten() fun part1(input: List<String>): Int { val limits = mapOf("red" to 12, "green" to 13, "blue" to 14) return input.sumOf { val gameNumber = gameNumber(it) val games = games(it) val cubeCounts = cubeCounts(games) if (cubeCounts.any { pair -> limits[pair.first]!! < pair.second }) 0 else gameNumber } } fun part2(input: List<String>): Int { return input.sumOf { line -> val games = games(line) val cubeCounts = cubeCounts(games) cubeCounts.groupBy( { it.first }, { it.second } ).entries.map { it.value.max() }.fold(1) { acc: Int, i: Int -> acc * i } } } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val input = readLines("day02-input.txt") val result1 = part1(input) "Result1: $result1".println() val result2 = part2(input) "Result2: $result2".println() println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms") }
0
Kotlin
0
0
41f376bd71a8449e05bbd5b9dd03b3019bde040b
1,665
aoc-2023-in-kotlin
Apache License 2.0
2015/src/main/kotlin/com/koenv/adventofcode/Day17.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode import java.util.* object Day17 { public fun getCombinationsThatFit(required: Int, buckets: List<Int>): Int { return findValidCombinations(required, buckets).size } public fun getCombinationsThatFit(required: Int, buckets: String): Int { return getCombinationsThatFit(required, buckets.lines().map { it.toInt() }) } public fun getSizeOfMinimumContainers(required: Int, buckets: List<Int>): Int { val combinations = findValidCombinations(required, buckets) val minimum = combinations.minBy { it.size }!!.size return combinations.filter { it.size == minimum }.size } public fun getSizeOfMinimumContainers(required: Int, buckets: String): Int { return getSizeOfMinimumContainers(required, buckets.lines().map { it.toInt() }) } public fun findValidCombinations(required: Int, buckets: List<Int>): List<List<Int>> { val combinations = ArrayList<Boolean>() buckets.forEach { combinations.add(true) } val validCombinations = arrayListOf<List<Int>>() while (combinations.contains(true)) { val thisIterationCombinations = combinations.mapIndexed { i, b -> if (b) buckets[i] else 0 } if (thisIterationCombinations.sum() == required) { validCombinations.add(thisIterationCombinations.filter { it != 0 }) } for (i in (buckets.size - 1 ) downTo 0) { if (combinations[i]) { combinations[i] = false break } else { combinations[i] = true } } } return validCombinations } }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
1,735
AdventOfCode-Solutions-Kotlin
MIT License
src/Day05.kt
remidu
573,452,090
false
{"Kotlin": 22113}
fun main() { var map: HashMap<Int, ArrayList<Char>> = HashMap() fun parseStacks(input: List<String>) { for (line in input) { if (line.contains('[')) { var id = 1 for (i in 1..line.length step 4) { if (!map.contains(id)) { map.put(id, ArrayList()) } if (line.get(i).isLetter()) map.get(id)?.add(line.get(i)) id++ } } } } fun parseNumber(line: String, prefix: String, suffix: String): Int { return line.substring(line.indexOf(prefix) + prefix.length+1, line.indexOf(suffix)-1) .toInt() } fun parseDigit(line: String, prefix: String): Int { return line.substring(line.indexOf(prefix) + prefix.length+1, line.indexOf(prefix) + prefix.length+2) .toInt() } fun move(from: Int, to: Int) { val thing = map.get(from)?.removeFirst() if (thing != null) { map.get(to)?.add(0, thing) } } fun move(number: Int, from: Int, to: Int) { val buffer: ArrayList<Char> = ArrayList() for (i in 0 until number) { val thing = map.get(from)?.removeFirst() if (thing != null) { buffer.add(thing) } } map.get(to)?.addAll(0, buffer) } fun readTop(): String { var result = "" for (e:Map.Entry<Int, ArrayList<Char>> in map) { val value = e.value if (value.isNotEmpty()) { val letter = value.first() result += letter } } return result } fun part1(input: List<String>): String { map = HashMap() parseStacks(input) for (line in input) { if (line.contains("move")) { val number = parseNumber(line, "move", "from") val from = parseDigit(line, "from") val to = parseDigit(line, "to") repeat(number) { move(from, to) } } } return readTop() } fun part2(input: List<String>): String { map = HashMap() parseStacks(input) for (line in input) { if (line.contains("move")) { val number = parseNumber(line, "move", "from") val from = parseDigit(line, "from") val to = parseDigit(line, "to") move(number, from, to) } } return readTop() } // test if implementation meets criteria from the description, like: val testInput = readInput("Data_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Data") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ecda4e162ab8f1d46be1ce4b1b9a75bb901bc106
2,857
advent-of-code-2022
Apache License 2.0
Day 12/src/main/kotlin/main.kt
TimBo93
434,023,800
false
{"C": 662683, "Objective-C": 18803, "TypeScript": 17001, "C++": 16492, "Dart": 11944, "Cuda": 10189, "C#": 9276, "Visual Basic .NET": 8923, "JavaScript": 8261, "Scala": 7729, "Fortran": 6947, "Groovy": 6001, "PHP": 4984, "Java": 4945, "Lua": 4694, "MATLAB": 4594, "F#": 4309, "Haskell": 3884, "Python": 3704, "Kotlin": 3441, "Pascal": 3290, "Go": 2791, "Ada": 2454, "Rust": 2051, "BlitzBasic": 1961, "GLSL": 235}
import java.io.File class Route ( val from: String, val to: String ){ fun reverse(): Route { return Route(to, from) } } class Transitions { private var allTransitions = mutableMapOf<String, MutableList<String>>() fun addTransition (r: Route) { addRoute(r) addRoute(r.reverse()) } private fun addRoute(r: Route) { if(allTransitions.containsKey(r.from)) { allTransitions[r.from]!!.add(r.to) return } allTransitions[r.from] = mutableListOf(r.to) } fun getTransitionFrom(node: String): List<String> { return allTransitions[node]!!.toList() } } fun initStatePartOne() : State = State("start", listOf("start"), true) fun initStatePartTwo() : State = State("start", listOf("start"), false) class State(val agentPosition: String, private val alreadyVisitedNodes: List<String>, private val hasAlreadyVisitedOneCaveTwice: Boolean) { fun moveTo(target: String) : State { val newList = alreadyVisitedNodes.toMutableList() val hasAlreadyVisitedOneCaveTwiceNow = hasAlreadyVisitedOneCaveTwice || hasAlreadyVisited(target) if(canVisitOnlyTwice(target)) { newList.add(target) } return State(target, newList, hasAlreadyVisitedOneCaveTwiceNow) } fun canVisitNode(node: String): Boolean { if(node == "start") { return false } if(canVisitOnlyTwice(node) && hasAlreadyVisitedOneCaveTwice && hasAlreadyVisited(node)) { return false } return true } private fun hasAlreadyVisited(node: String) = alreadyVisitedNodes.contains(node) private fun canVisitOnlyTwice(node: String) = node.lowercase() == node } var numPathes = 0 class TravelEngine(private val transitions: Transitions) { fun travel(initState: State) { val route = "start" travel(initState, route) } private fun travel(currentState: State, route: String) { if(currentState.agentPosition == "end") { numPathes += 1 println(route) return } getAllPossibleMoves(currentState).forEach { val newState = currentState.moveTo(it) travel(newState, "$route -> $it") } } private fun getAllPossibleMoves(state: State) = sequence<String> { transitions.getTransitionFrom(state.agentPosition).forEach{ if(state.canVisitNode(it)) { yield (it) } } } } fun main(args: Array<String>) { val transitions = Transitions() File("input.txt").forEachLine { val parts = it.split("-") transitions.addTransition(Route(parts[0], parts[1])) } val travelEngine = TravelEngine(transitions) travelEngine.travel(initStatePartOne()) println("Number of paths: $numPathes") numPathes = 0 travelEngine.travel(initStatePartTwo()) println("Number of paths (Part Two): $numPathes") }
0
C
0
0
69950107dfb96681020f3e27cc3e762d762945c6
3,006
AdventOfCode2021
MIT License
src/main/java/leetcode/binarytreefromstring/Solution.kt
thuytrinh
106,045,038
false
null
package leetcode.binarytreefromstring import leetcode.binarytreeboundary.TreeNode import java.util.* typealias NextIndex = Int typealias IntValue = Int /** * https://leetcode.com/problems/construct-binary-tree-from-string/description/ */ class Solution { private fun String.nextInt(index: Int): Pair<IntValue, NextIndex> { // Ex: // index = 1 // s = "(234)", s(2) = 2. // -> (234, 4) with 4 is sum of (index + s.length). val s = ((index + 1) until length) .map { this[it] } .takeWhile { it == '-' || it.isDigit() } .joinToString(separator = "") return Pair(s.toInt(), index + s.length) } // node = (3) private fun Stack<TreeNode>.addNode(node: TreeNode) { when { isEmpty() -> push(node) peek().left == null -> { peek().left = node push(node) } else -> { peek().right = node push(node) } } } // str = "4(2)(3)" fun str2tree(str: String): TreeNode? { if (str.isEmpty()) { return null } val s = "($str)" // s = "(4(2)(3))" val parents = Stack<TreeNode>() // parents = [] var root: TreeNode? = null // root = null var i = 0 while (i < s.length) { // i = 9, length = 9 when (s[i]) { // s[i] = '(' '(' -> { val p = s.nextInt(i) // p = (3, 6) i = p.second // i = 6 parents.addNode(TreeNode(p.first)) // parents = [4,3] } ')' -> root = parents.pop() // root = (4), parents = [] } i++ // i = 9 } return root // root = (4) } }
0
Kotlin
0
1
23da0286a88f855dcab1999bcd7174343ccc1164
1,594
algorithms
MIT License
kotlin/src/katas/kotlin/leetcode/first_missing_positive/FirstMissingPositive.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.first_missing_positive import datsok.shouldEqual import org.junit.jupiter.api.Test // // https://leetcode.com/problems/first-missing-positive // // Given an unsorted integer array, find the smallest missing positive integer. // // Example 1: // Input: [1,2,0] // Output: 3 // // Example 2: // Input: [3,4,-1,1] // Output: 2 // // Example 3: // Input: [7,8,9,11,12] // Output: 1 // // Follow up: // Your algorithm should run in O(n) time and uses constant extra space. // fun firstMissingPositive(nums: IntArray): Int { nums.indices.filter { nums[it] == 0 }.forEach { nums[it] = -1 } nums.filter { it - 1 in nums.indices }.forEach { nums[it - 1] = 0 } return (nums.indices.find { nums[it] != 0 } ?: nums.size) + 1 } fun firstMissingPositive_2(nums: IntArray): Int { val numbers = nums.sorted().filter { it > 0 }.toSet() numbers.forEachIndexed { i, n -> if (i + 1 != n) return i + 1 } return (numbers.lastOrNull() ?: 0) + 1 } fun firstMissingPositive_1(nums: IntArray): Int { val positiveNumbers = nums.filter { it > 0 } val max = positiveNumbers.maxOrNull() ?: 0 return 1.until(max).find { it !in positiveNumbers } ?: max + 1 } fun firstMissingPositive_0(nums: IntArray): Int { return (1..Int.MAX_VALUE).find { it !in nums } ?: -1 } class FirstMissingPositiveTests { private val f: (IntArray) -> Int = ::firstMissingPositive @Test fun `some examples`() { f(intArrayOf()) shouldEqual 1 f(intArrayOf(-1)) shouldEqual 1 f(intArrayOf(0)) shouldEqual 1 f(intArrayOf(123)) shouldEqual 1 f(intArrayOf(Int.MAX_VALUE)) shouldEqual 1 f(intArrayOf(1)) shouldEqual 2 f(intArrayOf(1, 2, 0)) shouldEqual 3 f(intArrayOf(1, 1, 2, 2, 0)) shouldEqual 3 f(intArrayOf(3, 4, -1, 1)) shouldEqual 2 f(intArrayOf(7, 8, 9, 11, 12)) shouldEqual 1 } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,907
katas
The Unlicense
src/main/kotlin/sk/mkiss/algorithms/generator/PermutationsGenerator.kt
marek-kiss
430,858,906
false
{"Kotlin": 85343}
package sk.mkiss.algorithms.generator object PermutationsGenerator { /** * Generate all permutations of elements in the given set * * @param T - the type of elements in the input set * @param input - the input set * @return list containing all permutations */ fun <T> generateAll(input: Set<T>): List<List<T>> { if (input.isEmpty()) return emptyList() val inputAsList = input.toList() val permutations = mutableListOf<List<T>>() var indexPermutation: Array<Int>? = Array(input.size) { i -> i } do { permutations.add(indexPermutation!!.map { inputAsList[it] }) indexPermutation = nextGreaterOrNull(indexPermutation) } while (indexPermutation != null) return permutations } private fun nextGreaterOrNull(number: Array<Int>): Array<Int>? { if (number.size <= 1) return null var i = number.size - 2 while (i >= 1 && number[i] >= number[i + 1]) { i-- } if (number[i] >= number[i + 1]) return null var indexOfSmallestGreater = i + 1 for (j in i + 1 until number.size) { if (number[j] > number[i] && number[j] < number[indexOfSmallestGreater]) { indexOfSmallestGreater = j } } swap(number, i, indexOfSmallestGreater) val sorted = number.sliceArray(i + 1 until number.size).apply { reverse() } return number.sliceArray(0..i) + sorted } private fun <T> swap(array: Array<T>, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } }
0
Kotlin
0
0
296cbd2e04a397597db223a5721b6c5722eb0c60
1,656
algo-in-kotlin
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day6.kt
clechasseur
568,233,589
false
{"Kotlin": 242914}
package io.github.clechasseur.adventofcode.y2015 import io.github.clechasseur.adventofcode.util.Pt import io.github.clechasseur.adventofcode.y2015.data.Day6Data import kotlin.math.max object Day6 { private val input = Day6Data.input private val commandRegex = """(turn (?:on|off)|toggle) (\d+),(\d+) through (\d+),(\d+)""".toRegex() fun part1(): Int { val grid = mutableMapOf<Pt, Boolean>() input.lines().map { it.toCommand() }.forEach { it.actOn(grid) } return grid.count { (_, state) -> state } } fun part2(): Int { val grid = mutableMapOf<Pt, Int>() input.lines().map { it.toCommand() }.forEach { it.actOnIntensity(grid) } return grid.values.sum() } private enum class Action(val description: String) { TURN_ON("turn on"), TURN_OFF("turn off"), TOGGLE("toggle"), } private fun String.toAction(): Action = Action.values().first { it.description == this } private class Command(val action: Action, val topLeft: Pt, val bottomRight: Pt) { val lights: Sequence<Pt> get() = generateSequence(topLeft) { prev -> if (prev.x < bottomRight.x) { prev + Pt(1, 0) } else { Pt(topLeft.x, prev.y + 1) } }.takeWhile { it.y <= bottomRight.y } fun actOn(grid: MutableMap<Pt, Boolean>) { lights.forEach { grid[it] = actOn(grid.getOrDefault(it, false)) } } fun actOnIntensity(grid: MutableMap<Pt, Int>) { lights.forEach { grid[it] = actOnIntensity(grid.getOrDefault(it, 0)) } } private fun actOn(light: Boolean): Boolean = when (action) { Action.TURN_ON -> true Action.TURN_OFF -> false Action.TOGGLE -> !light } private fun actOnIntensity(intensity: Int): Int = when (action) { Action.TURN_ON -> intensity + 1 Action.TURN_OFF -> max(intensity - 1, 0) Action.TOGGLE -> intensity + 2 } } private fun String.toCommand(): Command { val match = commandRegex.matchEntire(this) ?: error("Wrong command format: $this") val (ac, tx, ty, bx, by) = match.destructured return Command(ac.toAction(), Pt(tx.toInt(), ty.toInt()), Pt(bx.toInt(), by.toInt())) } }
0
Kotlin
0
0
e5a83093156cd7cd4afa41c93967a5181fd6ab80
2,468
adventofcode2015
MIT License
src/aoc2023/Day01.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInput fun main() { val (year, day) = "2023" to "Day01" val digitsMap = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9", ) fun String.filterDigits(withWords: Boolean): String { return if (!withWords) { this.filter { it.isDigit() } } else { val line = this buildString { for (i in line.indices) { if (line[i].isDigit()) { append(line[i]) } else { val sub = line.substring(startIndex = i) for ((word, num) in digitsMap) { if (sub.startsWith(word)) { append(num) break } } } } } } } fun List<String>.sumFilteredDigits(withWords: Boolean) = this.sumOf { line -> val digits = line.filterDigits(withWords) "${digits.first()}${digits.last()}".toInt() } fun part1(input: List<String>) = input.sumFilteredDigits(withWords = false) fun part2(input: List<String>) = input.sumFilteredDigits(withWords = true) val testInput1 = readInput(name = "${day}_p1_test", year = year) val testInput2 = readInput(name = "${day}_p2_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput1), 142) println(part1(input)) checkValue(part2(testInput2), 281) println(part2(input)) }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
1,804
aoc-kotlin
Apache License 2.0
src/Day05.kt
flexable777
571,712,576
false
{"Kotlin": 38005}
import java.util.* fun main() { fun loadStack(stackNumber: Int, crate: Char, arrayOfStacks: Array<Stack<Char>>) { arrayOfStacks[stackNumber].add(0, crate) } fun moveFromStack(stackNumberFrom: Int, stackNumberTo: Int, arrayOfStacks: Array<Stack<Char>>) { arrayOfStacks[stackNumberTo].push(arrayOfStacks[stackNumberFrom].pop()) } fun moveFromStack(stackNumberFrom: Int, stackNumberTo: Int, amount: Int, arrayOfStacks: Array<Stack<Char>>) { //is there a pop(), but for multiple elements? val stackFrom = arrayOfStacks[stackNumberFrom] val cratesToMove = stackFrom.takeLast(amount) val newStackFrom = Stack<Char>() newStackFrom.addAll(arrayOfStacks[stackNumberFrom].subList(0, stackFrom.size - amount)) arrayOfStacks[stackNumberFrom] = newStackFrom arrayOfStacks[stackNumberTo].addAll(cratesToMove) } fun readInputAndFillStacks( input: String, arrayOfStacks: Array<Stack<Char>> ) { input.lines().forEach { line -> line.chunked(4).forEachIndexed { index, s -> if (s.isNotBlank() && s[1].isLetter()) { loadStack( stackNumber = index, crate = s[1], arrayOfStacks = arrayOfStacks ) } } } } fun part1(input: String): String { val (stacksInput, instructionsInput) = input.split("\n\n") val arrayOfStacks = Array(9) { Stack<Char>() } readInputAndFillStacks(stacksInput, arrayOfStacks) //perform instructions instructionsInput.lines().forEach { instruction -> val c = instruction .replace("move ", "") .replace("from ", "") .replace("to ", "") val (move, from, to) = c.split(" ").map { it.toInt() } repeat(move) { moveFromStack( stackNumberFrom = from - 1, stackNumberTo = to - 1, arrayOfStacks = arrayOfStacks ) } } return arrayOfStacks.joinToString("") { if (it.isNotEmpty()) it.peek().toString() else "" } } fun part2(input: String): String { val (stacksInput, instructionsInput) = input.split("\n\n") val arrayOfStacks = Array(9) { Stack<Char>() } readInputAndFillStacks(stacksInput, arrayOfStacks) //perform instructions instructionsInput.lines().forEach { instruction -> val c = instruction .replace("move ", "") .replace("from ", "") .replace("to ", "") val (move, from, to) = c.split(" ").map { it.toInt() } moveFromStack( stackNumberFrom = from - 1, stackNumberTo = to - 1, amount = move, arrayOfStacks = arrayOfStacks ) } return arrayOfStacks.joinToString("") { if (it.isNotEmpty()) it.peek().toString() else "" } } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9a739eb203c535a3d83bc5da1b6a6a90a0c7bd6
3,328
advent-of-code-2022
Apache License 2.0
2021/src/Day20.kt
Bajena
433,856,664
false
{"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454}
import kotlin.math.abs import kotlin.math.max // https://adventofcode.com/2021/day/20 fun main() { class Image(cols: Int, rows: Int, numbers: Array<Int>, mask: String) { val cols = cols val rows = rows var numbers = numbers val mask = mask fun getMaskAt(index : Int) : Int { val point = indexToPoint(index) val x = point.first val y = point.second val values = listOf( Pair(x, y), Pair(x + 1, y), Pair(x + 2, y), Pair(x, y + 1), Pair(x + 1, y + 1), Pair(x + 2, y + 1), Pair(x, y + 2), Pair(x + 1, y + 2), Pair(x + 2, y + 2), ).map { get(it.first, it.second)!! } val maskIndex = values.joinToString("").toInt(2) return if (mask[maskIndex] == '#') 1 else 0 } fun applyMask() : Image { var newNumbers = mutableListOf<Int>() numbers.forEachIndexed { index, v -> val point = indexToPoint(index) if (point.first >= cols - 2 || point.second >= rows - 2) return@forEachIndexed newNumbers.add(getMaskAt(index)) } return Image(cols - 2, rows - 2, newNumbers.toTypedArray(), mask) } fun grow(growBy: Int = 2, fillWith: Int = 0) : Image { val newCols = cols + 2 * growBy val newNumbers = mutableListOf<Int>() newNumbers.addAll((1..(newCols * growBy)).map { fillWith }) for (row in getRows()) { newNumbers.addAll((1..growBy).map { fillWith }) newNumbers.addAll(row) newNumbers.addAll((1..growBy).map { fillWith }) } newNumbers.addAll((1..(newCols * growBy)).map { fillWith }) return Image(newCols, rows + 2 * growBy, newNumbers.toTypedArray(), mask) } fun pointToIndex(x : Int, y : Int) : Int { return y * cols + x } fun indexToPoint(index : Int) : Pair<Int, Int> { return Pair(index % cols, index / cols) } fun get(x : Int, y : Int) : Int? { return numbers.elementAtOrNull(y * cols + x) } fun getRows() : List<List<Int>> { val result = mutableListOf<List<Int>>() for (row in 0 until rows) { result.add(numbers.slice((row * cols) until row * cols + cols)) } return result } fun printMe() { numbers.forEachIndexed { index, v -> if (index % cols == 0) { println("") print("${index / rows }: ") } if (v == 0) { print(".") } else { print("#") } } println() } } fun readImage() : Image { var mask: String? = null val numbers = mutableListOf<Int>() var cols = 0 for (line in readInput("Day20")) { if (mask == null) { mask = line continue } if (line.isEmpty()) { continue } var nums = line.split("").filter { it != "" }.map { if (it == ".") 0 else 1 } cols = nums.count() numbers.addAll(nums) } return Image(cols, numbers.count() / cols, numbers.toTypedArray(), mask!!) } fun maskStep(image: Image, step: Int) : Image { return image.grow(3, if (step == 0 && image.mask.first() == '#') 1 else 0).applyMask() // return image.grow(3 , 0).applyMask() } fun part1() { val image = readImage() image.printMe() val imageAfterOneStep = maskStep(image, 0) imageAfterOneStep.printMe() val imageAfterTwoSteps = maskStep(imageAfterOneStep, 1) imageAfterTwoSteps.printMe() println(imageAfterTwoSteps.numbers.count { it == 1 }) } fun part2() { var image = readImage() // image.printMe() for (step in 0 until 50) { println("") print("Step $step:") image = image.grow(2, if (image.mask.first() == '.' || step % 2 == 0) 0 else 1) // image.printMe() image = image.applyMask() // image.printMe() } println(image.numbers.count { it == 1 }) } // part1() part2() }
0
Kotlin
0
0
a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a
3,932
advent-of-code
Apache License 2.0
src/main/kotlin/codes/hanno/adventofcode/day2/Day2.kt
hannotify
572,944,980
false
{"Kotlin": 7464}
import Day2.Choice.ChoiceCategory.* import Day2.Outcome.WDL.* import java.nio.file.Files import java.nio.file.Path fun main(args: Array<String>) { Day2().run(Path.of("src/main/resources/day2/input.txt")) } class Day2 { fun run(input: Path) { val scores = Files.lines(input).map { val split = it.split(" ") return@map Turn(Choice.valueOf(split[0]), Outcome.valueOf(split[1])).ourScore() }.toList(); println(scores.sum()) } data class Turn(val theirChoice: Choice, val outcome: Outcome) { fun ourScore(): Int = outcome.score() + theirChoice.determineOurChoice(outcome).choiceCategory.score() } enum class Choice(val choiceCategory: ChoiceCategory) { A(ROCK), B(PAPER), C(SCISSORS); fun determineOurChoice(outcome: Outcome): Choice = when (outcome.wdl) { WIN -> when (this.choiceCategory) { ROCK -> B PAPER -> C SCISSORS -> A } DRAW -> this LOSE -> when (this.choiceCategory) { ROCK -> C PAPER -> A SCISSORS -> B } } enum class ChoiceCategory { ROCK, PAPER, SCISSORS; fun score(): Int = when (this) { ROCK -> 1 PAPER -> 2 SCISSORS -> 3 } } } enum class Outcome(val wdl: WDL) { X(LOSE), Y(DRAW), Z(WIN); fun score(): Int = when(this.wdl) { LOSE -> 0 DRAW -> 3 WIN -> 6 } enum class WDL { WIN, DRAW, LOSE } } }
0
Kotlin
0
0
ccde130e52f5637f140b331416634b8ce86bc401
1,760
advent-of-code
Apache License 2.0
src/main/kotlin/me/circuitrcay/euler/challenges/oneToTwentyFive/Problem12.kt
adamint
134,989,381
false
null
package me.circuitrcay.euler.challenges.oneToTwentyFive import me.circuitrcay.euler.Problem class Problem12 : Problem<String>() { override fun calculate(): Any { return factorsOfNumber() } private fun factorsOfNumber(): Long { var numFactors: Int var counter = 2L while (true) { val triangleNumber = counter * (counter + 1) / 2 val temp = generatePrimeFactorsWithFrequency(triangleNumber)?.values?.map { it + 1 } numFactors = temp!!.reduce { acc, i -> acc * i } if (numFactors > 500) break counter++ } return (counter * (counter + 1) / 2) } fun <K> frequencyMapOf(vararg pairs: Pair<K, kotlin.Int>): FrequencyMap<K> { val mMap = mutableMapOf<K, Int>() val freqMap = FrequencyMap(mMap) for (pair in pairs) { freqMap.add(pair) } return freqMap } fun generatePrimeFactorsWithFrequency( _n: Number, action: (FrequencyMap<Long>) -> Unit = {} ): FrequencyMap<Long>? { when (_n) { is Long -> { } is Int -> { } else -> throw IllegalArgumentException("Only Int and Long are supported.") } var n = _n.toLong() if (n < 2) return null val primeFactors = frequencyMapOf<Long>() while (n % 2L == 0L) { primeFactors.add(2L, 1) n /= 2L } for (i in 3L..Math.sqrt(n.toDouble()).toLong()) { while (n % i == 0L) { primeFactors.add(i, 1) n /= i } } if (n > 2L) primeFactors.add(n, 1) action(primeFactors) return primeFactors } } /** * Found this on Github oof https://github.com/tocttou/project-euler-kotlin/blob/master/main/src/utils/FrequencyMap.kt */ class FrequencyMap<K>(private val b: MutableMap<K, kotlin.Int>) : MutableMap<K, kotlin.Int> by b { fun add(key: K, freq: kotlin.Int = 1) { b.computeIfPresent(key) { _, b -> b + freq } b.putIfAbsent(key, freq) } fun add(vararg pairs: Pair<K, kotlin.Int>) { for (pair in pairs) { val (key, freq) = pair add(key, freq) } } fun addAll(iter: Iterable<FrequencyMap<K>>) { for (i in iter) { for (j in i.keys) { add(j, i[j]!!) } } } fun removeFreq(key: K, freq: kotlin.Int = 1) { if (b.get(key) == null || freq < 1) return else if (b.get(key)!! - freq < 1) b.remove(key) b.computeIfPresent(key) { _, b -> b - freq } } override fun hashCode(): kotlin.Int { return super.hashCode() } override fun equals(other: Any?): Boolean { if (!(other is FrequencyMap<*>)) return false return generateMutableMapFromFrequencyMap(this) .equals(generateMutableMapFromFrequencyMap(other)) } fun generateMutableMapFromFrequencyMap(obj: FrequencyMap<*>): MutableMap<Any?, Any?> { val mMap = mutableMapOf<Any?, Any?>() obj.forEach { t, u -> mMap.put(t, u) } return mMap } }
0
Kotlin
0
0
cebe96422207000718dbee46dce92fb332118665
3,210
project-euler-kotlin
Apache License 2.0
src/main/kotlin/aoc/day5/SupplyStacks.kt
moosolutions
571,461,075
false
{"Kotlin": 12616}
package aoc.day5 class SupplyStacks(private val input: List<String>) { val stacks = mutableListOf<Stack>() init { val rawStacks = input.slice(0..input.indexOf("")) .filter { line -> line.isNotEmpty() } .map { it.split(",") } .flatten() .map { it.chunked(4).map { s -> s.trim().removePrefix("[").removeSuffix("]") } } val s = rawStacks.toMutableList() s.removeLast() for (i in 0 until rawStacks.last().count()) { stacks.add(i, Stack()) s.forEach { if (i in it.indices && it[i]!!.isNotEmpty()) { stacks[i].addCrate(Crate(it[i])) } } } stacks.map { it.crates.reverse() } } fun rearrangeStacksBySingle(): String { val moves = input.slice(input.indexOf("") + 1 until input.count()).map { val move = it.split(" ") val quantity = move[1].toInt() val from = move[3].toInt() - 1 val to = move[5].toInt() - 1 stacks[to].crates.addAll(stacks[from].crates.takeLast(quantity).reversed()) stacks[from].crates = stacks[from].crates.dropLast(quantity).toMutableList() } return stacks.map { it.crates.last().toString() }.joinToString("") } fun useCrateMover9001(): String { val moves = input.slice(input.indexOf("") + 1 until input.count()).map { val move = it.split(" ") val quantity = move[1].toInt() val from = move[3].toInt() - 1 val to = move[5].toInt() - 1 stacks[to].crates.addAll(stacks[from].crates.takeLast(quantity)) stacks[from].crates = stacks[from].crates.dropLast(quantity).toMutableList() stacks.forEach { println(it.crates.toString()) } } return stacks.map { it.crates.last().toString() }.joinToString("") } } class Stack { public var crates = mutableListOf<Crate>() fun addCrate(crate: Crate) { crates.add(crate) } } class Crate(public val crateCode: String) { override fun toString(): String { return crateCode } }
0
Kotlin
0
0
6ef815df5c196ccf86041fcb0b76e3a2c14584af
2,339
advent-of-code-2022
Apache License 2.0
src/Day04.kt
samorojy
572,624,502
false
{"Kotlin": 5094}
fun main() { fun part1(input: List<String>) = input.parsedPairs().count { (p1, p2) -> (p1.first in p2 && p1.last in p2) || (p2.first in p1 && p2.last in p1) } fun part2(input: List<String>) = input.parsedPairs().count { (p1, p2) -> p1.first in p2 || p1.last in p2 || p2.first in p1 || p2.last in p1 } val inputs = readInput("Day04") println("first=${part1(inputs)}") println("part2=${part2(inputs)}") } fun List<String>.parsedPairs() = this.map { line -> line.split(",").map { pairs -> val (a, b) = pairs.split("-").map { it.toInt() } a..b } }
0
Kotlin
0
0
7a38657c4ff7b42c5d49379014f88d054183bd2b
649
advent-of-code
Apache License 2.0
lib/src/main/kotlin/utils/math.kt
madisp
434,510,913
false
{"Kotlin": 388138}
package utils import kotlin.math.sqrt fun solveQuadratic(a: Double, b: Double, c: Double): Pair<Double, Double> { val x1 = (-b + sqrt(b * b - 4 * a * c)) / 2 * a val x2 = (-b - sqrt(b * b - 4 * a * c)) / 2 * a return minOf(x1, x2) to maxOf(x1, x2) } val Int.prime: Boolean get() { return (2 .. sqrt(this.toDouble()).toInt() + 1).none { this % it == 0 } } // TODO(madis) optimize? val Int.factors: List<Int> get() { val divisor = (2 until this).firstOrNull { this % it == 0 } if (divisor == null) return listOf(this) return listOf(divisor) + (this / divisor).factors } // TODO(madis) optimize? fun lcm(numbers: List<Int>): Long { return numbers.flatMap { it.factors.withCounts().entries } .groupBy { (k, _) -> k } .map { (k, v) -> k to v.maxOf { it.value } } .fold(1L) { acc, (n, e) -> acc * n.toLong().pow(e) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
852
aoc_kotlin
MIT License
src/year_2023/day_05/Day05.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2023.day_05 import readInput data class SourceToDestination( val source: Long, val destination: Long, val length: Long ) { fun containsSource(source: Long): Boolean { return source >= this.source && source < this.source + length } fun containsDestination(destination: Long): Boolean { return destination >= this.destination && destination < this.destination + length } fun destinationFor(value: Long): Long { return destination + (value - source) } fun sourceFor(value: Long): Long { return source + (value - destination) } } fun List<SourceToDestination>.getDestination(source: Long): Long { return firstOrNull { it.containsSource(source) }?.destinationFor(source) ?: source } fun List<SourceToDestination>.getSource(destination: Long): Long { return firstOrNull { it.containsDestination(destination) }?.sourceFor(destination) ?: destination } data class Almanac( val seeds: List<Long>, val seedToSoilMap: List<SourceToDestination>, val soilToFertilizerMap: List<SourceToDestination>, val fertilizerToWaterMap: List<SourceToDestination>, val waterToLightMap: List<SourceToDestination>, val lightToTemperatureMap: List<SourceToDestination>, val temperatureToHumidityMap: List<SourceToDestination>, val humidityToLocationMap: List<SourceToDestination>, ) { fun containsSeed(seed: Long): Boolean { for (i in seeds.indices step 2) { if (seed >= seeds[i] && seed < seeds[i] + seeds[i+1]) { return true } } return false } } object Day05 { /** * */ fun solutionOne(text: List<String>): Long { val almanac = parseAlmanac(text) return almanac.seeds.map { seed -> val soil = almanac.seedToSoilMap.getDestination(seed) val fertilizer = almanac.soilToFertilizerMap.getDestination(soil) val water = almanac.fertilizerToWaterMap.getDestination(fertilizer) val light = almanac.waterToLightMap.getDestination(water) val temp = almanac.lightToTemperatureMap.getDestination(light) val humidity = almanac.temperatureToHumidityMap.getDestination(temp) val location = almanac.humidityToLocationMap.getDestination(humidity) location }.min() } /** * */ fun solutionTwo(text: List<String>): Long { val almanac = parseAlmanac(text) var location = 0L while (true) { val humidity = almanac.humidityToLocationMap.getSource(location) val temp = almanac.temperatureToHumidityMap.getSource(humidity) val light = almanac.lightToTemperatureMap.getSource(temp) val water = almanac.waterToLightMap.getSource(light) val fertilizer = almanac.fertilizerToWaterMap.getSource(water) val soil = almanac.soilToFertilizerMap.getSource(fertilizer) val seed = almanac.seedToSoilMap.getSource(soil) if (almanac.containsSeed(seed)) { return location } location += 1 } } private fun parseAlmanac(text: List<String>): Almanac { val seedsLine = text.first { it.contains("seeds: ") }.split(" ") val seeds = seedsLine.subList(1, seedsLine.size).map { it.toLong() } val seedToSoilMap = mutableListOf<SourceToDestination>() val soilToFertilizerMap = mutableListOf<SourceToDestination>() val fertilizerToWaterMap = mutableListOf<SourceToDestination>() val waterToLightMap = mutableListOf<SourceToDestination>() val lightToTemperatureMap = mutableListOf<SourceToDestination>() val temperatureToHumidityMap = mutableListOf<SourceToDestination>() val humidityToLocationMap = mutableListOf<SourceToDestination>() var currentList: MutableList<SourceToDestination>? = null text.forEach { line -> if (line.isEmpty()) { currentList = null } currentList?.let { populateList(it, line) } when (line) { "seed-to-soil map:" -> currentList = seedToSoilMap "soil-to-fertilizer map:" -> currentList = soilToFertilizerMap "fertilizer-to-water map:" -> currentList = fertilizerToWaterMap "water-to-light map:" -> currentList = waterToLightMap "light-to-temperature map:" -> currentList = lightToTemperatureMap "temperature-to-humidity map:" -> currentList = temperatureToHumidityMap "humidity-to-location map:" -> currentList = humidityToLocationMap } } return Almanac( seeds = seeds, seedToSoilMap = seedToSoilMap, soilToFertilizerMap = soilToFertilizerMap, fertilizerToWaterMap = fertilizerToWaterMap, waterToLightMap = waterToLightMap, lightToTemperatureMap = lightToTemperatureMap, temperatureToHumidityMap = temperatureToHumidityMap, humidityToLocationMap = humidityToLocationMap ) } private fun populateList(list: MutableList<SourceToDestination>, line: String) { val split = line.split(" ").filter { it.isNotEmpty() } val destination = split[0].toLong() val source = split[1].toLong() val length = split[2].toLong() list.add( SourceToDestination( source = source, destination = destination, length = length ) ) } } fun main() { val text = readInput("year_2023/day_05/Day05.txt") val solutionOne = Day05.solutionOne(text) println("Solution 1: $solutionOne") val solutionTwo = Day05.solutionTwo(text) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
5,917
advent_of_code
Apache License 2.0