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/main/kotlin/endredeak/aoc2022/Day12.kt
edeak
571,891,076
false
{"Kotlin": 44975}
package endredeak.aoc2022 fun main() { solve("Hill Climbing Algorithm") { fun Char.value(): Int = when (this) { 'S' -> 0 'E' -> 25 else -> this - 'a' } val dirs = setOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) data class P(val x: Int, val y: Int, val c: Char) { fun neighbours(grid: List<List<P>>, cond: (Int, Int) -> Boolean) = dirs .mapNotNull { (x1, y1) -> grid.getOrNull(this.y + y1)?.getOrNull(this.x + x1) } .filter { cond(this.c.value(), it.c.value()) } } val input = lines.mapIndexed { y, line -> line.mapIndexed { x, c -> P(x, y, c) } } fun bfs(start: Char, terminateIf: (P) -> Boolean, isValidNeighbour: (Int, Int) -> Boolean): Int { val startPoint = input.flatten().first { it.c == start } val discovered = mutableMapOf(startPoint to 0) val q = ArrayDeque<P>().apply { add(startPoint) } while (q.isNotEmpty()) { q.removeFirst().let { v -> val neighbours = v.neighbours(input, isValidNeighbour) if (neighbours.any { terminateIf(it) }) return discovered[v]!! + 1 neighbours .filter { it !in discovered } .forEach { discovered[it] = discovered[v]!! + 1 q.add(it) } } } error("waat") } part1(440) { bfs('S', { p -> p.c == 'E' }) { f, t -> t - f <= 1 } } part2(439) { bfs('E', { p -> p.c == 'a' }) { f, t -> f - t <= 1 } } } }
0
Kotlin
0
0
e0b95e35c98b15d2b479b28f8548d8c8ac457e3a
1,744
AdventOfCode2022
Do What The F*ck You Want To Public License
src/Day03.kt
jarmstrong
572,742,103
false
{"Kotlin": 5377}
fun main() { val scores = (('a'..'z') + ('A'..'Z')) .zip(1..52) .toMap() fun part1(input: List<String>): Int { return input.sumOf { rucksack -> val firstCompartment = rucksack.substring(0, rucksack.length / 2).toSet() val secondCompartment = rucksack.substring(rucksack.length / 2).toSet() firstCompartment .intersect(secondCompartment) .sumOf { scores[it]!! } } } fun part2(input: List<String>): Int { return input .chunked(3) .sumOf { it[0].toSet() .intersect(it[1].toSet()) .intersect(it[2].toSet()) .sumOf { scores[it]!! } } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bba73a80dcd02fb4a76fe3938733cb4b73c365a6
943
aoc-2022
Apache License 2.0
src/Day03/Day03.kt
Trisiss
573,815,785
false
{"Kotlin": 16486}
fun main() { fun Char.getPriorities() = when { isUpperCase() -> code - 38 isLowerCase() -> code - 96 else -> error("Unknown char!!") } fun part1(input: List<String>): Int = input.sumOf { line -> line.chunked(line.length/2).map { it.toSet() }.reduce { acc, chars -> acc.intersect(chars) }.sumOf { it.getPriorities() } } fun part2(input: List<String>): Int = input.chunked(3).sumOf { chunk -> chunk.windowed(2).map { it[0].toSet().intersect(it[1].toSet()) } .reduce { acc, chars -> acc.intersect(chars) } .sumOf { it.getPriorities() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03/Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03/Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
cb81a0b8d3aa81a3f47b62962812f25ba34b57db
916
AOC-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinStoneSum.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 java.util.PriorityQueue import kotlin.math.max /** * 1962. Remove Stones to Minimize the Total * @see <a href="https://leetcode.com/problems/remove-stones-to-minimize-the-total/">Source</a> */ fun interface MinStoneSum { operator fun invoke(piles: IntArray, k: Int): Int } class MinStoneSumHeap : MinStoneSum { override operator fun invoke(piles: IntArray, k: Int): Int { val pq: PriorityQueue<Int> = PriorityQueue { a, b -> b - a } var res = 0 piles.forEach { pq.add(it) res += it } repeat(k) { val a: Int = pq.poll() pq.add(a - a / 2) res -= a / 2 } return res } } class MinStoneSumFast : MinStoneSum { override operator fun invoke(piles: IntArray, k: Int): Int { val frequency = IntArray(FREQ) var max = -1 for (p in piles) { frequency[p]++ max = max(max, p) } var i = max var k0 = k while (i >= 1 && k0 > 0) { while (frequency[i] != 0 && k0 > 0) { frequency[i]-- frequency[(i + 1) / 2]++ k0-- } i-- } var ans = 0 for (j in max downTo 1) { ans += frequency[j] * j } return ans } private companion object { private const val FREQ = 10001 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,069
kotlab
Apache License 2.0
src/main/kotlin/day02/day02.kt
andrew-suprun
725,670,189
false
{"Kotlin": 18354, "Python": 17857, "Dart": 8224}
package day02 import java.io.File import kotlin.math.max data class Game(val id: Int, val colors: Colors) data class Colors(val red: Int, val green: Int, val blue: Int) fun main() { println(run(::part1)) println(run(::part2)) } fun run(score: (Game) -> Int): Int = File("input.data").readLines().sumOf { score(parseGame(it)) } fun parseGame(line: String): Game { val (gameIdStr, gameDataStr) = line.split(": ") val gameId = gameIdStr.split(" ")[1].toInt() return Game(id = gameId, colors = parseColors(gameDataStr)) } fun parseColors(gameDataStr: String): Colors { var red = 0 var green = 0 var blue = 0 for (setStr in gameDataStr.split("; ")) { val colorsStr = setStr.split(", ") for (colorStr in colorsStr) { val (cubesStr, color) = colorStr.split(" ") val cubes = cubesStr.toInt() when (color) { "red" -> red = max(red, cubes) "green" -> green = max(green, cubes) "blue" -> blue = max(blue, cubes) } } } return Colors(red = red, green = green, blue = blue) } fun part1(game: Game): Int { val colors = game.colors if (colors.red <= 12 && colors.green <= 13 && colors.blue <= 14) return game.id return 0 } fun part2(game: Game): Int { return game.colors.red * game.colors.green * game.colors.blue }
0
Kotlin
0
0
dd5f53e74e59ab0cab71ce7c53975695518cdbde
1,391
AoC-2023
The Unlicense
2021/src/main/kotlin/day5_imp.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Segment import utils.Solution import utils.Vec2i import utils.mapItems fun main() { Day5Imp.run() } object Day5Imp : Solution<List<Segment>>() { override val name = "day5" override val parser = Parser.lines .mapItems(Segment::parse) .mapItems { if (it.start.x > it.end.x) Segment(it.end, it.start) else it } override fun part1(input: List<Segment>): Int { return solve(input.filter { it.isHorizontal || it.isVertical }) } override fun part2(input: List<Segment>): Int { return solve(input) } private fun solve(lines: List<Segment>): Int { val intersections = mutableSetOf<Vec2i>() lines.forEachIndexed { i, line -> for (j in (i + 1 until lines.size)) { val other = lines[j] if (line.isVertical) { for (y in minOf(line.start.y, line.end.y) .. maxOf(line.start.y, line.end.y)) { val p = Vec2i(line.start.x, y) if (p in other) { intersections.add(p) } } } else { val start = maxOf(line.start.x, other.start.x) val end = minOf(line.end.x, other.end.x) for (x in start .. end) { val p = line[x] if (p in other) { intersections.add(p) } } } } } return intersections.count() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,368
aoc_kotlin
MIT License
src/Day05.kt
psabata
573,777,105
false
{"Kotlin": 19953}
fun main() { fun part1(stacks: MutableList<MutableList<Char>>, instructions: List<Instruction>): String { instructions.forEach { instruction -> instruction.execute1(stacks) } return stacks.fold("") { acc, stack -> acc + (stack.lastOrNull() ?: "") } } fun part2(stacks: MutableList<MutableList<Char>>, instructions: List<Instruction>): String { instructions.forEach { instruction -> instruction.execute2(stacks) } return stacks.fold("") { acc, stack -> acc + (stack.lastOrNull() ?: "") } } fun test() { val input = InputHelper("Day05_test.txt").readStringGroups() val stacks = input[0].split(System.lineSeparator()).dropLast(1) val crane = input[1].split(System.lineSeparator()).drop(1) val instructions = parseCrane(crane) check(part1(parseStacks(stacks), instructions) == "CMZ") check(part2(parseStacks(stacks), instructions) == "MCD") } fun prod() { val input = InputHelper("Day05.txt").readStringGroups() val stacks = input[0].split(System.lineSeparator()).dropLast(1) val crane = input[1].split(System.lineSeparator()).drop(1) val instructions = parseCrane(crane) println("Part 1: ${part1(parseStacks(stacks), instructions)}") println("Part 2: ${part2(parseStacks(stacks), instructions)}") } test() prod() } private fun parseStacks(crates: List<String>): MutableList<MutableList<Char>> { val stacks: MutableList<MutableList<Char>> = mutableListOf() crates.reversed().forEach { row -> row.forEachIndexed { index, char -> if (char.isLetter()) { val stackIndex = (index - 1) / 4 + 1 if (stackIndex >= stacks.size) { stacks.add(mutableListOf()) } stacks[stackIndex - 1].add(char) } } } return stacks } private fun parseCrane(crane: List<String>): List<Instruction> { val instructions = crane.map { instruction -> val values = Regex("\\D*(\\d+)\\D*(\\d+)\\D*(\\d+)").matchEntire(instruction)!!.groupValues Instruction(values[1].toInt(), values[2].toInt(), values[3].toInt()) } return instructions } data class Instruction( val howMany: Int, val from: Int, val to: Int, ) { fun execute1(stacks: MutableList<MutableList<Char>>) { for (i in 1..howMany) { val crate = stacks[from - 1].removeLast() stacks[to - 1].add(crate) } } fun execute2(stacks: MutableList<MutableList<Char>>) { val crates: MutableList<Char> = mutableListOf() for (i in 1..howMany) { crates.add(stacks[from - 1].removeLast()) } stacks[to - 1].addAll(crates.reversed()) } }
0
Kotlin
0
0
c0d2c21c5feb4ba2aeda4f421cb7b34ba3d97936
2,853
advent-of-code-2022
Apache License 2.0
src/Day05.kt
cornz
572,867,092
false
{"Kotlin": 35639}
fun main() { fun getStartIndexAndNumberOfStacks(input: List<String>): Pair<Int, Int>? { for ((index, value) in input.reversed().withIndex()) { if (value.startsWith(" 1")) { return Pair(index, value.split(" ").last().toInt()) } } return null } fun createStacks(input: List<String>): List<MutableList<String>> { val startIndexAndNumberOfStacks = getStartIndexAndNumberOfStacks(input) val stacks = List(startIndexAndNumberOfStacks!!.second) { mutableListOf<String>() } val numberOfStacks = startIndexAndNumberOfStacks.second for (line in input.reversed().slice(startIndexAndNumberOfStacks.first + 1 until input.size)) { val chunks = line.chunked(4) for (i in 0 until minOf(numberOfStacks, chunks.size)) { val char = chunks[i].trim() if (char != "") { stacks[i].add(0, char.replace("[", "").replace("]", "")) } } } return stacks } fun getInstruction(input: String): Triple<Int, Int, Int> { // move 1 from 2 to 1 val inputs = input.split(" ") return Triple(inputs[1].toInt(), inputs[3].toInt() - 1, inputs[5].toInt() - 1) } fun part1(input: List<String>): String { val stacks = createStacks(input) for (line in input) { if (!line.startsWith("move")) { continue } val instruction = getInstruction(line) val howManyToMove = instruction.first val fromStack = instruction.second val toStack = instruction.third for (i in 0 until howManyToMove) { val takeThis = stacks[fromStack][0] stacks[fromStack].removeFirstOrNull() stacks[toStack].add(0, takeThis) } } var ret = "" for (stack in stacks) { ret += stack[0] } return ret } fun part2(input: List<String>): String { val stacks = createStacks(input) for (line in input) { if (!line.startsWith("move")) { continue } val instruction = getInstruction(line) val howManyToMove = instruction.first val fromStack = instruction.second val toStack = instruction.third val takeThis = stacks[fromStack].take(howManyToMove) stacks[toStack].addAll(0, takeThis) for (i in 0 until howManyToMove) { stacks[fromStack].removeFirstOrNull() } } var ret = "" for (stack in stacks) { ret += stack[0] } return ret } // test if implementation meets criteria from the description, like: val testInput = readInput("input/Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("input/Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2800416ddccabc45ba8940fbff998ec777168551
3,063
aoc2022
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/largest_subarray_length_k/LargestSubarrayLengthK.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.largest_subarray_length_k import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/discuss/interview-question/352459/Google-or-OA-Fall-Internship-2019-or-Largest-Subarray-Length-K */ class LargestSubarrayLengthKTests { @Test fun examples() { largestSubarray(emptyArray(), k = 0) shouldEqual emptyArray() largestSubarray(arrayOf(1, 2, 3, 4, 5), k = 5) shouldEqual arrayOf(1, 2, 3, 4, 5) largestSubarray(arrayOf(1, 2, 3, 4, 5), k = 4) shouldEqual arrayOf(2, 3, 4, 5) largestSubarray(arrayOf(1, 2, 3, 4, 5), k = 3) shouldEqual arrayOf(3, 4, 5) largestSubarray(arrayOf(1, 2, 3, 4, 5), k = 2) shouldEqual arrayOf(4, 5) largestSubarray(arrayOf(1, 2, 3, 4, 5), k = 1) shouldEqual arrayOf(5) largestSubarray(arrayOf(1, 4, 3, 2, 5), k = 4) shouldEqual arrayOf(4, 3, 2, 5) largestSubarray(arrayOf(1, 4, 3, 2, 5), k = 3) shouldEqual arrayOf(4, 3, 2) } @Test fun `array comparison`() { arrayOf<Int>().compareTo(arrayOf()) shouldEqual 0 arrayOf(1).compareTo(arrayOf(1)) shouldEqual 0 arrayOf(0, 1).compareTo(arrayOf(0, 1)) shouldEqual 0 arrayOf(0, 1).compareTo(arrayOf(0, 1, 2)) shouldEqual 0 arrayOf(1).compareTo(arrayOf(2)) shouldEqual -1 arrayOf(0, 1).compareTo(arrayOf(0, 2)) shouldEqual -1 arrayOf(0, 1).compareTo(arrayOf(0, 2)) shouldEqual -1 arrayOf(0, 1, 2).compareTo(arrayOf(0, 2)) shouldEqual -1 arrayOf(0, 1).compareTo(arrayOf(0, 2, 0)) shouldEqual -1 arrayOf(2).compareTo(arrayOf(1)) shouldEqual 1 arrayOf(2).compareTo(arrayOf(1, 2)) shouldEqual 1 arrayOf(1, 2, 4, 3, 5).compareTo(arrayOf(1, 2, 3, 4, 5)) shouldEqual 1 } } private fun largestSubarray(array: Array<Int>, k: Int): Array<Int> { if (k == 0) return emptyArray() if (k < 0 || k > array.size) error("") val max = Array(k) { Int.MIN_VALUE } (array.size - k).downTo(0).forEach { i -> if (array[i] > max[0]) { array.copyInto(max, startIndex = i, endIndex = i + k) } else if (array[i] == max[0]) { var j = 1 while (j < k) { if (array[i + j] > max[j]) { array.copyInto(max, startIndex = i + j, endIndex = i + j + k) break } j++ } } } return max } @Suppress("unused") private fun largestSubarray_(array: Array<Int>, k: Int): Array<Int> { if (k == 0) return emptyArray() if (k < 0 || k > array.size) error("") return array.toList().windowed(size = k, step = 1) .sortedWith(Comparator { left, right -> left.compareTo(right) }) .last().toTypedArray() } private fun Array<Int>.compareTo(other: Array<Int>): Int { val pair = zip(other).find { it.first != it.second } ?: return 0 return pair.first.compareTo(pair.second) } private fun List<Int>.compareTo(other: List<Int>): Int { val pair = zip(other).find { it.first != it.second } ?: return 0 return pair.first.compareTo(pair.second) }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
3,102
katas
The Unlicense
src/day01/Day01.kt
Mini-Stren
573,128,699
false
null
package day01 import readInputText fun main() { val day = 1 fun part1(input: String): Int { return input.elves.maxOf { it.foods.sumOf(Day01.Food::calories) } } fun part2(input: String): Int { return input.elves.map { it.foods.sumOf(Day01.Food::calories) } .sortedDescending() .take(3) .sum() } val testInput = readInputText("/day%02d/input_test".format(day)) val input = readInputText("/day%02d/input".format(day)) check(part1(testInput) == 24000) println("part1 answer is ${part1(input)}") check(part2(testInput) == 45000) println("part2 answer is ${part2(input)}") } object Day01 { data class Elf( val foods: List<Food>, ) data class Food( val calories: Int, ) } private val String.elves: List<Day01.Elf> get() = split("\n\n") .map(String::foods) .map(Day01::Elf) private val String.foods: List<Day01.Food> get() = split("\n") .map(String::toInt) .map(Day01::Food)
0
Kotlin
0
0
40cb18c29089783c9b475ba23c0e4861d040e25a
1,048
aoc-2022-kotlin
Apache License 2.0
src/Day02.kt
Inn0
573,532,249
false
{"Kotlin": 16938}
data class RPSAnswer( val name: String, val keys: List<String>, val value: Int ) fun main() { val Rock = RPSAnswer("rock", listOf("A", "X"), 1) val Paper = RPSAnswer("paper", listOf("B", "Y"), 2) val Scissors = RPSAnswer("scissors", listOf("C", "Z"), 3) fun inputToAnswer(input: String): RPSAnswer { return if(Rock.keys.contains(input)){ Rock } else if(Paper.keys.contains(input)){ Paper } else { Scissors } } fun readStrategyGuide(input: List<String>): MutableList<MutableList<RPSAnswer>> { val output = mutableListOf<MutableList<RPSAnswer>>() input.forEach { val game = mutableListOf<RPSAnswer>() val encryptedMoves = it.split(" ") game.add(inputToAnswer(encryptedMoves[0])) game.add(inputToAnswer(encryptedMoves[1])) output.add(game) } return output } fun calculateGame(opponent: RPSAnswer, player: RPSAnswer): Int { var score = player.value when (player.name) { "rock" -> { when (opponent.name) { "rock" -> score += 3 "paper" -> score += 0 "scissors" -> score += 6 } } "paper" -> { when (opponent.name) { "rock" -> score += 6 "paper" -> score += 3 "scissors" -> score += 0 } } "scissors" -> { when (opponent.name) { "rock" -> score += 0 "paper" -> score += 6 "scissors" -> score += 3 } } } return score } fun calculateMove(opponent: RPSAnswer, player: String): Int { val rock = 1 val paper = 2 val scissors = 3 var score = 0 when(player){ "Z" -> { score += 6 when (opponent.name) { "rock" -> score += paper "paper" -> score += scissors "scissors" -> score += rock } } "Y" -> { score += 3 when (opponent.name) { "rock" -> score += rock "paper" -> score += paper "scissors" -> score += scissors } } "X" -> { when (opponent.name) { "rock" -> score += scissors "paper" -> score += rock "scissors" -> score += paper } } } return score } fun part1(input: List<String>): Int { val strategyGuide = readStrategyGuide(input) var total = 0 strategyGuide.forEach { total += calculateGame(it[0], it[1]) } return total } fun part2(input: List<String>): Int { val strategyGuide = readStrategyGuide(input) var total = 0 strategyGuide.forEach { total += calculateMove(it[0], it[1].keys[1]) } return total } // 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("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
f35b9caba5f0c76e6e32bc30196a2b462a70dbbe
3,556
aoc-2022
Apache License 2.0
src/aoc2018/kot/Day03.kt
Tandrial
47,354,790
false
null
package aoc2018.kot import getNumbers import itertools.times import java.io.File object Day03 { data class Claim(val id: Int, val x: Int, val y: Int, val xsize: Int, val ysize: Int) fun partOne(input: List<String>): Int = putClaims(parse(input)).sumBy { it.count { it > 1 } } fun partTwo(input: List<String>): Int { val claims = parse(input) val grid = putClaims(claims) return claims.first { claim -> (claim.x until claim.x + claim.xsize).times((claim.y until claim.y + claim.ysize)).all { (x, y) -> grid[x][y] == 1 } }.id } private fun parse(input: List<String>): List<Claim> = input.map { val (id, x, y, xSize, ySize) = it.getNumbers() Claim(id, x, y, xSize, ySize) } private fun putClaims(claims: List<Claim>): Array<IntArray> { val array = Array(1000) { IntArray(1000) } for (claim in claims) { for (x in (claim.x until claim.x + claim.xsize)) for (y in (claim.y until claim.y + claim.ysize)) array[x][y]++ } return array } } fun main(args: Array<String>) { val input = File("./input/2018/Day03_input.txt").readLines() println("Part One = ${Day03.partOne(input)}") println("Part Two = ${Day03.partTwo(input)}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,225
Advent_of_Code
MIT License
src/main/kotlin/aoc08/Solution08.kt
rainer-gepardec
573,386,353
false
{"Kotlin": 13070}
package aoc08 import java.nio.file.Paths inline fun <T> Iterable<T>.takeWhileInclusive( predicate: (T) -> Boolean ): List<T> { var shouldContinue = true return takeWhile { val result = shouldContinue shouldContinue = predicate(it) result } } fun main() { val lines = Paths.get("src/main/resources/aoc_08.txt").toFile().useLines { it.toList() } val map = lines .map { line -> line.toCharArray().map { it.digitToInt() } } .map { it.toIntArray() } .toTypedArray() val width = map.first().size val height = map.size println(solution1(map, width, height)) println(solution2(map, width, height)) } fun solution1(map: Array<IntArray>, width: Int, height: Int): Int { val treeMap = solve(map, width, height) return treeMap.asSequence().filter { tree -> tree.value.any { edge -> edge.all { it < map[tree.key.second][tree.key.first] } } }.count() + (width * 2) + (height * 2) - 4 } fun solution2(map: Array<IntArray>, width: Int, height: Int): Int { val treeMap = solve(map, width, height) return treeMap.asSequence().map { tree -> tree.value.map { edge -> edge.takeWhileInclusive { map[tree.key.second][tree.key.first] > it }.toList() }.map { it.size } }.maxOf { it.reduce { result, value -> result.times(value) } } } fun solve(map: Array<IntArray>, width: Int, height: Int): Map<Pair<Int, Int>, List<List<Int>>> { val treeMap = mutableMapOf<Pair<Int, Int>, List<List<Int>>>() // create map of path to edge for all trees except the outer circle for (y in 1 until height - 1) { for (x in 1 until width - 1) { val leftEdgeValues = mutableListOf<Int>() val rightEdgeValues = mutableListOf<Int>() val topEdgeValues = mutableListOf<Int>() val bottomEdgeValues = mutableListOf<Int>() for (l in 0 until x) leftEdgeValues.add(map[y][l]) for (r in x + 1 until width) rightEdgeValues.add(map[y][r]) for (t in 0 until y) topEdgeValues.add(map[t][x]) for (b in y + 1 until height) bottomEdgeValues.add(map[b][x]) treeMap[Pair(x, y)] = listOf(leftEdgeValues.reversed(), rightEdgeValues, topEdgeValues.reversed(), bottomEdgeValues) } } return treeMap }
0
Kotlin
0
0
c920692d23e8c414a996e8c1f5faeee07d0f18f2
2,361
aoc2022
Apache License 2.0
src/main/kotlin/days/Solution14.kt
Verulean
725,878,707
false
{"Kotlin": 62395}
package days import adventOfCode.InputHandler import adventOfCode.Solution import adventOfCode.util.PairOf import adventOfCode.util.Point2D import adventOfCode.util.plus typealias RockSet = Set<Point2D> typealias ReflectorMirror = Triple<RockSet, RockSet, PairOf<Int>> private class RockAndRoll( private val roundRocks: RockSet, private val cubeRocks: RockSet, private val shape: PairOf<Int> ) { private val directions = arrayOf(-1 to 0, 0 to -1, 1 to 0, 0 to 1) private val roundToIteration = mutableMapOf((roundRocks to directions.last()) to 0L) private val iterationToRound = mutableMapOf(0L to roundRocks) private var cycleStart = 0L private var cycleLength = 0L private fun roll(round: RockSet, direction: Point2D): RockSet { var curr = round var changed: Boolean do { changed = false val temp = mutableSetOf<Point2D>() for (pos in curr) { val nextPos = pos + direction val (i, j) = nextPos when { i !in 0 until shape.first -> temp.add(pos) j !in 0 until shape.second -> temp.add(pos) nextPos in cubeRocks -> temp.add(pos) nextPos in curr -> temp.add(pos) else -> { temp.add(nextPos) changed = true } } } curr = temp } while (changed) return curr } fun findCycle() { var round = roundRocks for (i in 0 until Int.MAX_VALUE) { val d = directions[i % 4] round = roll(round, d) roundToIteration[round to d]?.let { j -> cycleStart = j cycleLength = i - j + 1 return } roundToIteration[round to d] = i + 1L iterationToRound[i + 1L] = round } } private fun getCycleIndex(iteration: Long): Long { if (iteration < cycleStart + cycleLength) return iteration return (iteration - cycleStart) % cycleLength + cycleStart } fun getTotalLoad(iteration: Long) = iterationToRound.getValue(getCycleIndex(iteration)) .sumOf { (i, _) -> (shape.first - i) } } object Solution14 : Solution<ReflectorMirror>(AOC_YEAR, 14) { override fun getInput(handler: InputHandler): ReflectorMirror { val lines = handler.getInput("\n") val roundRocks = mutableSetOf<Point2D>() val cubeRocks = mutableSetOf<Point2D>() lines.forEachIndexed { i, line -> line.forEachIndexed { j, c -> when (c) { 'O' -> roundRocks.add(i to j) '#' -> cubeRocks.add(i to j) } } } return Triple(roundRocks, cubeRocks, lines.size to lines[0].length) } override fun solve(input: ReflectorMirror): PairOf<Int> { val (round, cube, shape) = input val rockAndRoll = RockAndRoll(round, cube, shape) rockAndRoll.findCycle() return rockAndRoll.getTotalLoad(1) to rockAndRoll.getTotalLoad(4_000_000_000) } }
0
Kotlin
0
1
99d95ec6810f5a8574afd4df64eee8d6bfe7c78b
3,203
Advent-of-Code-2023
MIT License
src/Day01.kt
KliminV
573,758,839
false
{"Kotlin": 19586}
fun main() { fun part1(input: List<String>): Int { if (input.isEmpty()) return 0; var curIdx: Int = 1; var maxIdx: Int = 0; var curWeight: Int = 0 var maxTotalCalories: Int = 0; for (line in input) { when (line) { "" -> { maxTotalCalories = if (maxTotalCalories > curWeight) maxTotalCalories else curWeight maxIdx = if (maxTotalCalories > curWeight) maxIdx else curIdx curIdx++ curWeight = 0 } else -> { curWeight += line.toInt() } } } if (curWeight!=0) { maxTotalCalories = if (maxTotalCalories > curWeight) maxTotalCalories else curWeight } return maxTotalCalories } fun part2(input: List<String>): Int { if (input.isEmpty()) return 0; var curWeight: Int = 0 var maxTotalCalories: Int = 0; var secondTotalCalories: Int = 0 var thirdTotalCalories: Int = 0 for (line in input) { when (line) { "" -> { if (curWeight > thirdTotalCalories) { if (curWeight > secondTotalCalories) { if (curWeight > maxTotalCalories) { val storage = curWeight curWeight = maxTotalCalories maxTotalCalories = storage } val storage = curWeight curWeight = secondTotalCalories secondTotalCalories = storage } thirdTotalCalories = curWeight } curWeight = 0 } else -> { curWeight += line.toInt() } } } if (curWeight!=0) { if (curWeight > thirdTotalCalories) { if (curWeight > secondTotalCalories) { if (curWeight > maxTotalCalories) { val storage = curWeight curWeight = maxTotalCalories maxTotalCalories = storage } val storage = curWeight curWeight = secondTotalCalories secondTotalCalories = storage } thirdTotalCalories = curWeight } } return maxTotalCalories + secondTotalCalories + thirdTotalCalories } fun List<List<Int>>.topNElfes(n: Int): Int { return map { it.sum() } .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
542991741cf37481515900894480304d52a989ae
3,123
AOC-2022-in-kotlin
Apache License 2.0
src/main/kotlin/adventofcode2018/Day18SettlersOfTheNorthPole.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2018 import adventofcode2018.AreaElement.* import java.lang.Math.min import java.util.* import kotlin.math.max class Day18SettlersOfTheNorthPole sealed class AreaElement(val sign: Char) { object Open : AreaElement('.') object Tree : AreaElement('|') object Lumberyard : AreaElement('#') override fun toString(): String = sign.toString() } fun List<List<AreaElement>>.hash(): Int { return Arrays.deepHashCode(this.toTypedArray()) } class NorthPoleArea(input: List<String>) { var elements: List<List<AreaElement>> val rounds = mutableMapOf<Int, List<List<AreaElement>>>() val roundHashes = mutableMapOf<Int, Int>() val totalResource: Int get() { val treeCount = elements.flatten().filter { it is Tree }.count() val lumberyardCount = elements.flatten().filter { it is Lumberyard }.count() return treeCount * lumberyardCount } init { elements = input.map { line -> line.toCharArray().map { sign -> elementFromSign(sign) } } } private fun elementFromSign(sign: Char): AreaElement { return when (sign) { '|' -> Tree '#' -> Lumberyard else -> Open } } fun transform(count: Long) { var loop = 0 var counter = 0 while (loop == 0) { val transformedElements = List(elements.size) { elements[it].mapIndexed { x, element -> transformElement(element, it, x) } } if (roundHashes.values.contains(transformedElements.hash())) { println("Loop found via hash at $counter") } if (rounds.values.contains(transformedElements)) { loop = counter println("Loop at iteration: $counter") } else { rounds[counter] = transformedElements roundHashes[counter] = transformedElements.hash() counter++ } elements = transformedElements } if (loop > 0) { val effectiveRound = Math.floorMod(count, loop) - 1 println("Effective round: $effectiveRound") elements = rounds[effectiveRound]!! } } private fun transformElement(element: AreaElement, posY: Int, posX: Int): AreaElement { return when (element) { is Open -> transformOpen(posY, posX) is Tree -> transformTree(posY, posX) is Lumberyard -> transformLumberyard(posY, posX) } } private fun transformTree(posY: Int, posX: Int) = if (neighborsAt(posY, posX).filter { it is Lumberyard }.count() > 2) Lumberyard else Tree private fun transformOpen(posY: Int, posX: Int) = if (neighborsAt(posY, posX).filter { it is Tree }.count() > 2) Tree else Open private fun transformLumberyard(posY: Int, posX: Int): AreaElement { val containsLumberyard = neighborsAt(posY, posX).any { it is Lumberyard } val containsTree = neighborsAt(posY, posX).any { it is Tree } return if (containsLumberyard && containsTree) Lumberyard else Open } fun neighborsAt(posY: Int, posX: Int): List<AreaElement> { val minX = max(0, posX - 1) val maxX = min(elements[0].size - 1, posX + 1) val minY = max(0, posY - 1) val maxY = min(elements.size - 1, posY + 1) val result = mutableListOf<AreaElement>() (minY..maxY).forEach { y -> (minX..maxX).forEach { x -> if (!(y == posY && x == posX)) result.add(elements[y][x]) } } return result.toList() } fun printArea() { println() elements.forEach { println(it.joinToString(separator = "")) } println() } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
3,838
kotlin-coding-challenges
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[2]两数相加.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 // // 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 // // 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 // // 示例: // // 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) //输出:7 -> 0 -> 8 //原因:342 + 465 = 807 // // Related Topics 链表 数学 // 👍 5357 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { //两数相加 迭代 时间复杂度 O(max(m,n)) m n 为两个链表长度 return dfs(l1, l2, 0) } fun dfs(l: ListNode?, r: ListNode?, i: Int): ListNode? { if (l == null && r == null && i == 0) return null val sum: Int = (l?.`val` ?: 0) + (r?.`val` ?: 0) + i val node: ListNode = ListNode(sum % 10) node.next = dfs(l?.next, r?.next, sum / 10) return node } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,406
MyLeetCode
Apache License 2.0
src/main/kotlin/aoc/year2022/Day08.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2022 import aoc.Puzzle private typealias Tree = Pair<Int, Int> /** * [Day 8 - Advent of Code 2022](https://adventofcode.com/2022/day/8) */ object Day08 : Puzzle<Int, Int> { override fun solvePartOne(input: String): Int { val grid = input.lines().map { it.map(Char::digitToInt) } val hiddenHorizontal = grid .dropLast(1) .withIndex() .asSequence() .drop(1) .flatMap { getHidden(it) { row, col -> row to col } } .toSet() val rows = grid.size val cols = grid.first().size val hiddenVertical = (0 until cols) .asSequence() .drop(1) .map { col -> IndexedValue(col, (0 until rows).map { row -> grid[row][col] }) } .flatMap { getHidden(it) { col, row -> row to col } } .toSet() val hidden = hiddenHorizontal.intersect(hiddenVertical).size return (rows * cols) - hidden } override fun solvePartTwo(input: String): Int { TODO() } private fun getHidden( indexedValue: IndexedValue<Iterable<Int>>, treeBuilder: (Int, Int) -> Tree, ): Set<Tree> { val (index, list) = indexedValue var max = list.first() val ltr = list.withIndex() .asSequence() .drop(1) .filter { (_, n) -> (n <= max).also { if (!it) max = n } } .map { treeBuilder(index, it.index) } .toSet() max = list.last() val rtl = list.withIndex() .reversed() .asSequence() .drop(1) .filter { (_, n) -> (n <= max).also { if (!it) max = n } } .map { treeBuilder(index, it.index) } .toSet() return ltr.intersect(rtl) } }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,815
advent-of-code
Apache License 2.0
src/main/kotlin/d18/D18_2.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d18 import d16.Direction import input.Input import kotlin.math.abs val INT_TO_DIR = mapOf( Pair(0, Direction.RIGHT), Pair(2, Direction.LEFT), Pair(3, Direction.ABOVE), Pair(1, Direction.BELOW) ) data class BigInstruction( val dir: Direction, val count: Long ) fun parseRealInput(lines: List<String>): List<BigInstruction> { return lines.map { val parts = it.split(" ") val hex = parts[2].replace("[()#]".toRegex(), "") val dir = INT_TO_DIR[hex[5].digitToInt()]!! val countStr = hex.substring(0, 5) BigInstruction( dir, countStr.toLong(16) ) } } fun shoelaceArea(coordinates: List<Pair<Long, Long>>): Long { var sum = 0L for (i in 1..coordinates.lastIndex) { val c0 = coordinates[i - 1] val c1 = coordinates[i] val p = c0.first * c1.second - c0.second * c1.first sum += p } return abs(sum / 2) } fun main() { val lines = Input.read("input.txt") val instructions = parseRealInput(lines) var previous = Pair(0L, 0L) val coordinates = mutableListOf(previous) for (instruction in instructions) { val next = when (instruction.dir) { Direction.LEFT -> Pair(previous.first, previous.second - instruction.count) Direction.RIGHT -> Pair(previous.first, previous.second + instruction.count) Direction.BELOW -> Pair(previous.first + instruction.count, previous.second) Direction.ABOVE -> Pair(previous.first - instruction.count, previous.second) } previous = next.copy() coordinates.add(next) } val length = instructions.sumOf { it.count } val shoelaceArea = shoelaceArea(coordinates) val area = shoelaceArea + length / 2 + 1 println(area) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
1,824
aoc2023-kotlin
MIT License
2015/src/main/kotlin/day14.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parse import utils.Parser import utils.Solution import utils.mapItems fun main() { Day14.run() } object Day14: Solution<List<Day14.Reindeer>>() { override val name = "day14" override val parser = Parser.lines.mapItems { parseReindeer(it) } private const val ROUNDS = 2503 @Parse("{name} can fly {speed} km/s for {activeDuration} seconds, but then must rest for {restDuration} seconds.") data class Reindeer( val name: String, val speed: Int, val activeDuration: Int, val restDuration: Int, ) { fun traveledAt(time: Int): Int { val cycleTime = activeDuration + restDuration val cycleTravel = (time / cycleTime) * activeDuration * speed val travelRest = minOf(activeDuration, time % cycleTime) * speed return cycleTravel + travelRest } } override fun part1(input: List<Reindeer>): Int { return input.maxOf { it.traveledAt(ROUNDS) } } override fun part2(input: List<Reindeer>): Int { val startScores = input.associate { it.name to 0 } return (1 .. ROUNDS).fold(startScores) { scores, time -> val leading = input.maxBy { it.traveledAt(time) } scores + mapOf(leading.name to scores[leading.name]!! + 1) }.entries.maxOf { (_, v) -> v } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,253
aoc_kotlin
MIT License
src/main/kotlin/leetcode/google/Problem329.kt
Magdi
390,731,717
false
null
package leetcode.google import java.util.* class Problem329 { private val di = listOf(0, 0, -1, 1) private val dj = listOf(1, -1, 0, 0) fun longestIncreasingPath(matrix: Array<IntArray>): Int { if (matrix.isEmpty() || matrix[0].isEmpty()) return 0 val n = matrix.size val m = matrix[0].size val queue = PriorityQueue<Node>() matrix.forEachIndexed { i, row -> row.forEachIndexed { j, cell -> queue.add(Node(cell, i, j)) } } var max = 1 val ans = Array(n) { IntArray(m) { 1 } } while (queue.isNotEmpty()) { val node = queue.poll() (0..3).forEach { d -> val ni = node.x + di[d] val nj = node.y + dj[d] if (ni in 0 until n && nj in 0 until m && matrix[ni][nj] > matrix[node.x][node.y]) { ans[node.x][node.y] = Math.max(ans[node.x][node.y], ans[ni][nj] + 1) max = Math.max(max, ans[node.x][node.y]) } } } return max } private data class Node(val value: Int, val x: Int, val y: Int) : Comparable<Node> { override fun compareTo(other: Node): Int { return other.value.compareTo(value) } } }
0
Kotlin
0
0
63bc711dc8756735f210a71454144dd033e8927d
1,307
ProblemSolving
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2021/Day25.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.Pos import com.chriswk.aoc.util.report class Day25 : AdventDay(2021, 25) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day25() report { day.part1() } report { day.part2() } } } fun parseInput(input: List<String>): Seabottom { return Seabottom(cucumbers = input.flatMapIndexed { y, l -> l.mapIndexedNotNull { x, c -> if (c == '.') { null } else if (c == 'v') { Pos(x, y) to Cucumber(Pos(x, y), Direction.SOUTH) } else if (c == '>') { Pos(x, y) to Cucumber(Pos(x, y), Direction.EAST) } else { null } } }.toMap(), maxX = input[0].length, maxY = input.size) } fun makeMoves(initial: Seabottom): Sequence<Seabottom> { return generateSequence(initial) { prev -> prev.move() } } data class Cucumber(val pos: Pos, val facing: Direction) data class Seabottom( val cucumbers: Map<Pos, Cucumber>, val movesLastGeneration: Int = 0, val generation: Int = 0, val maxX: Int, val maxY: Int ) { fun move(): Seabottom { return moveEast().moveSouth() } private fun moveEast(): Seabottom { val notMoving = cucumbers.values.filter { it.facing == Direction.SOUTH || cucumbers.containsKey(it.pos.east(maxX)) }.toSet() val moving = cucumbers.values.toSet() - notMoving val moved = moving.map { it.copy(pos = it.pos.east(maxX)) }.toSet() val newCucumbers = (moved + notMoving).associateBy { it.pos } return copy(cucumbers = newCucumbers, movesLastGeneration = moved.size) } private fun moveSouth(): Seabottom { val notMoving = cucumbers.values.filter { it.facing == Direction.EAST || cucumbers.containsKey(it.pos.south(maxY)) }.toSet() val moving = cucumbers.values.toSet() - notMoving val moved = moving.map { it.copy(pos = it.pos.south(maxY)) }.toSet() val newCucumbers = (moved + notMoving).associateBy { it.pos } return copy(cucumbers = newCucumbers, movesLastGeneration = movesLastGeneration + moved.size, generation = generation + 1) } } enum class Direction { EAST, SOUTH } fun stopsMoving(input: List<String>): Int { return makeMoves(parseInput(input)).dropWhile { it.movesLastGeneration > 0 || it.generation == 0 }.first().generation } fun part1(): Int { return stopsMoving(inputAsLines) } fun part2(): Int { return 0 } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,953
adventofcode
MIT License
src/Day07.kt
robotfooder
573,164,789
false
{"Kotlin": 25811}
class MyDir( val name: String, val subDirs: MutableList<MyDir> = mutableListOf(), val parent: MyDir?, private val files: MutableList<MyFile> = mutableListOf(), var dirSize: Int = 0, ) { fun addFile(size: Int, name: String) { files.add(MyFile(size, name)) dirSize += size var parentDir = parent while (parentDir != null) { parentDir.dirSize += size parentDir = parentDir.parent } } fun addDirectory(name: String) { subDirs.add(MyDir(name = name, parent = this)) } fun getDirectoriesBySize(sizeTest: (Int) -> Boolean): List<MyDir> { return subDirs.filter { sizeTest(it.dirSize) } + subDirs.flatMap { it.getDirectoriesBySize(sizeTest) } } } data class MyFile(val size: Int, val name: String) fun main() { fun changeDir(cwd: MyDir, dir: String): MyDir { return if (dir == "..") cwd.parent ?: throw IllegalStateException("No parent") else cwd.subDirs .find { it.name == dir } ?: if (cwd.name == dir) cwd else throw IllegalArgumentException("Could not find $dir in ${cwd.name}") } fun doCommand(data: List<String>, cwd: MyDir): MyDir { return if (data[1] == "cd") changeDir(cwd, data[2]) else cwd } fun parseFileSystem(input: List<String>): MyDir { val root = MyDir(name = "/", parent = null) var cwd = root input.forEach { row -> val data = row.split(" ") when (data[0]) { "$" -> cwd =doCommand(data, cwd) "dir" -> cwd.addDirectory(data[1]) else -> cwd.addFile(data[0].toInt(), data[1]) } } return root } fun part1(input: List<String>): Int { val dirLimit = 100000 val fileSystem: MyDir = parseFileSystem(input) return fileSystem .getDirectoriesBySize { it <= dirLimit } .sumOf(MyDir::dirSize) } fun part2(input: List<String>): Int { val totDiscSpace = 70000000 val updateReqSpace = 30000000 val fileSystem = parseFileSystem(input) val freeSpace = totDiscSpace - fileSystem.dirSize val spaceNeeded = updateReqSpace - freeSpace return fileSystem .getDirectoriesBySize { it >= spaceNeeded } .minBy(MyDir::dirSize).dirSize } fun runTest(expected: Int, day: String, testFunction: (List<String>) -> Int) { val actual = testFunction(readTestInput(day)) check(expected == actual) { "Failing for day $day, ${testFunction}. " + "Expected $expected but got $actual" } } val day = "07" // test if implementation meets criteria from the description, like: runTest(95437, day, ::part1) runTest(24933642, day, ::part2) val input = readInput(day) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9876a52ef9288353d64685f294a899a58b2de9b5
2,986
aoc2022
Apache License 2.0
src/main/kotlin/days/Day9.kt
hughjdavey
433,597,582
false
{"Kotlin": 53042}
package days import util.Utils class Day9 : Day(9) { private val points = inputList.flatMapIndexed { y, s -> s.mapIndexed { x, c -> Point(c.toString().toInt(), Utils.Coord(x, y)) } } override fun partOne(): Any { return points.filter { it.isLowPoint(points) }.map(Point::riskLevel).sum() } override fun partTwo(): Any { return findBasins(points).map { it.size }.sorted().takeLast(3).reduce { a, e -> a * e } } private fun findBasins(points: List<Point>): List<Set<Point>> { return points.filter { it.isLowPoint(points) }.map { findBasin(points, it) } } private fun findBasin(allPoints: List<Point>, point: Point, basin: Set<Point> = setOf(point)): Set<Point> { val adjacentAndHigher = point.getAdjacent(allPoints).filter { it.height != 9 && it.height > point.height } return basin.plus(adjacentAndHigher).plus(adjacentAndHigher.flatMap { findBasin(allPoints, it) }) } data class Point(val height: Int, val location: Utils.Coord) { val riskLevel = height + 1 fun isLowPoint(points: List<Point>): Boolean { return getAdjacent(points).all { it.height > height } } fun getAdjacent(points: List<Point>): List<Point> { val minX = points.minOf { it.location.x } val minY = points.minOf { it.location.y } return location.getAdjacent(false).filter { it.x >= minX && it.y >= minY } .mapNotNull { loc -> points.find { it.location == loc } } } } }
0
Kotlin
0
0
a3c2fe866f6b1811782d774a4317457f0882f5ef
1,535
aoc-2021
Creative Commons Zero v1.0 Universal
src/Day07.kt
Ajimi
572,961,710
false
{"Kotlin": 11228}
typealias Path = String fun main() { fun part1(input: List<String>): Long { return input.toDirSizes().values.filter { it <= 100000 }.sum() } fun part2(input: List<String>): Long { val sizeMap = input.toDirSizes() val sizeNeeded = 30000000 - (70000000 - sizeMap[""]!!) return sizeMap.values.filter { it >= sizeNeeded }.min() } val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) } private fun List<String>.toFullPath(): Path = this.joinToString("/") fun List<String>.toDirSizes(): Map<String, Long> { val currentDir = mutableListOf<String>() val mapSize = mutableMapOf<Path, Long>() forEach { line -> when { line.startsWith("$ cd ") -> { when (line) { "$ cd /" -> currentDir.clear() "$ cd .." -> currentDir.removeLast() else -> currentDir.add(line.removePrefix("$ cd ")) } } line.first().isDigit() -> { val size = line.substringBefore(' ').toLong() val dirCopy = currentDir.toMutableList() while (true) { val fullPath = dirCopy.toFullPath() mapSize[fullPath] = size + (mapSize[fullPath] ?: 0L) if (dirCopy.isEmpty()) { break } dirCopy.removeLast() } } } } return mapSize }
0
Kotlin
0
0
8c2211694111ee622ebb48f52f36547fe247be42
1,649
adventofcode-2022
Apache License 2.0
src/Day09/day09.kt
NST-d
573,224,214
false
null
package Day09 import utils.* import kotlin.math.abs import kotlin.math.sign fun main() { data class Point(var x: Int, var y: Int){ fun follow(other: Point){ if(abs(other.x-this.x) > 1){ //move in the right direction this.x += sign((other.x - this.x).toDouble()).toInt() //diagonal joining if(this.y != other.y){ this.y += sign((other.y - this.y).toDouble()).toInt() } }else if(abs(other.y- this.y) > 1){ //move in the right direction this.y += sign((other.y - this.y).toDouble()).toInt() //diagonal joining if(this.x != other.x){ this.x += sign((other.x - this.x).toDouble()).toInt() } } } } fun printField(points: List<Point>, sizeX: Int, sizeY : Int){ val field = Array(sizeY) { CharArray(sizeX){'.'} } points.forEachIndexed { index, point -> field[point.y][point.x] = "$index"[0] } field.reversed().forEach { println(String(it)) } } fun part1(input: List<String>):Int{ val h = Point(0,0) val t = Point(0,0) val visitedPosition = LinkedHashSet<Point>() input.forEach { println(it) val (direction, amount) = it.split(" ") //loop invariant: t and h are adjacent repeat(amount.toInt()){ when(direction){ "R" -> h.x++ "L" -> h.x-- "U" -> h.y++ "D" -> h.y-- } t.follow(h) visitedPosition.add(t.copy()) println("h $h, t $t") } } return visitedPosition.count() } fun part2(input: List<String>):Int{ val points = List<Point>(10) { Point(0,0)} val visitedPosition = LinkedHashSet<Point>() input.forEach { println(it) val (direction, amount) = it.split(" ") //loop invariant: t and h are adjacent repeat(amount.toInt()){ when(direction){ "R" -> points[0].x++ "L" -> points[0].x-- "U" -> points[0].y++ "D" -> points[0].y-- } points.drop(1).forEachIndexed { i, point -> point.follow(points[i]) } visitedPosition.add(points.last().copy()) //println(points) //printFiled(points, 6,5) } } return visitedPosition.count() } val test = readTestLines("Day09") val input = readInputLines("Day09") println(part2(input)) }
0
Kotlin
0
0
c4913b488b8a42c4d7dad94733d35711a9c98992
2,843
aoc22
Apache License 2.0
calendar/day08/Day8.kt
rocketraman
573,845,375
false
{"Kotlin": 45660}
package day08 import Day import Lines class Day8 : Day() { data class Position(val row: Int, val col: Int) class Grid(val matrix: List<List<Int>>) { fun Position.valueAt() = matrix[row][col] fun Position.leftOf() = matrix[row].subList(0, col) fun Position.rightOf() = matrix[row].slice((col + 1) until matrix[row].size) fun Position.topOf() = matrix.map { it[col] }.subList(0, row) fun Position.bottomOf() = matrix.map { it[col] }.slice((row + 1) until matrix[col].size) } fun matrix(input: Lines) = input.map { line -> line.toCharArray().map { it.digitToInt() } } override fun part1(input: Lines): Any { return with(Grid(matrix(input))) { fun Position.visible(others: List<Int>): Boolean = others.isEmpty() || others.all { it < valueAt() } fun Position.visibleLeft(): Boolean = visible(leftOf()) fun Position.visibleRight(): Boolean = visible(rightOf()) fun Position.visibleTop(): Boolean = visible(topOf()) fun Position.visibleBottom(): Boolean = visible(bottomOf()) fun Position.visibleFromOutside(): Boolean = visibleLeft() || visibleRight() || visibleTop() || visibleBottom() matrix.withIndex().sumOf { (row, rowValues) -> rowValues.withIndex().sumOf { (col, _) -> val pos = Position(row, col) if (pos.visibleFromOutside()) 1L else 0L } } } } override fun part2(input: Lines): Any { return with(Grid(matrix(input))) { matrix.withIndex().maxOf { (row, rowValues) -> rowValues.indices.maxOf { col -> val pos = Position(row, col) fun List<Int>.takeWhileVisible(): List<Int> { val value = pos.valueAt() return fold(emptyList()) { acc, elem -> if (acc.isNotEmpty() && acc.last() >= value) acc else acc + elem } } val left = pos.leftOf().reversed().takeWhileVisible().count() val right = pos.rightOf().takeWhileVisible().count() val top = pos.topOf().reversed().takeWhileVisible().count() val bottom = pos.bottomOf().takeWhileVisible().count() left * right * top * bottom } } } } }
0
Kotlin
0
0
6bcce7614776a081179dcded7c7a1dcb17b8d212
2,218
adventofcode-2022
Apache License 2.0
src/main/kotlin/days/Day16.kt
sicruse
315,469,617
false
null
package days import days.Day import kotlin.math.absoluteValue class Day16 : Day(16) { private val rules: List<Rule> by lazy { inputString .split("\\n\\n".toRegex()) .first() .split("\\n".toRegex()) .map{ ruleText -> Rule.deserialize(ruleText) } } private val myTicket: List<Int> by lazy { inputString .split("your ticket:\\n".toRegex()) .last() .split("\\n".toRegex()) .first() .split(",") .map { it.toInt() } } private val tickets: List<List<Int>> by lazy { inputString .split("nearby tickets:\\n".toRegex()) .last() .split("\\n".toRegex()) .map{ ticket -> ticket.split(",") .map { it.toInt() } } } private val validTickets = tickets.filter { ticket -> ticket.all { field -> rules.any { rule -> rule.isValid(field) } } } private val validTicketFields: Sequence<List<Int>> = sequence { // We will assume that myTicket has the same number of fields as every other valid ticket for ((index, _) in myTicket.withIndex()) { val values = validTickets.map { ticket -> ticket[index] } yield(values) } } private val rulesInOrder: List<Rule> by lazy { // Map Rules to possible field columns val ruleMap: Map<Rule, MutableList<Int>> = rules.map { rule -> rule to validTicketFields.mapIndexed { index, fields -> if (fields.all{ rule.isValid(it) }) index else null } .filterNotNull() .toMutableList() }.toMap() // Rules may be valid for more than one field therefore we need to rationalize the mapping // While there are multiple field mappings per rule while (ruleMap.values.any {it.count() > 1}) // For each rule that maps to one and ONLY one field ruleMap.filter { it.value.count() == 1 } .forEach { map -> // visit each rule that has multiple field mappings ruleMap.filter { it.value.count() > 1 && it.value.contains( map.value.first() ) } // and remove reference to the single field .forEach{ ruleMapping -> ruleMapping.value.remove( map.value.first() ) } } // Sort the rules according to field sequence ruleMap.entries .sortedBy { ruleMapping -> ruleMapping.value.first() } .map{ ruleMapping -> ruleMapping.key } } class Rule(val name: String, val lower: IntRange, val upper: IntRange) { fun isValid(value: Int): Boolean = value in lower || value in upper companion object { val destructuredRegex = "([\\s\\w]+): (\\d+)-(\\d+) or (\\d+)-(\\d+)".toRegex() fun deserialize(text: String): Rule { destructuredRegex.matchEntire(text) ?.destructured ?.let { (_name, _lowerFrom, _lowerTo, _upperFrom, _upperTo) -> return Rule(_name, _lowerFrom.toInt() .. _lowerTo.toInt(), _upperFrom.toInt() .. _upperTo.toInt()) } ?: throw IllegalArgumentException("Bad input '$text'") } } } override fun partOne(): Any { // for all tickets val badValues = tickets.flatMap { ticket -> // check each field ticket.filterNot { field -> // and roll-up any values that don't meet ALL of the rules rules.any { rule -> rule.isValid(field) } } } return badValues.sum() } override fun partTwo(): Any { // for all rules that start with "departure" figure out the index of field it applies too return rulesInOrder.withIndex().mapNotNull { (i, rule) -> if (rule.name.startsWith("departure")) i else null } // grab the field values in my own ticket .map{ fieldIndex -> myTicket[fieldIndex] } // calculate the product (don't forget to coerce type to Long [initial value as 1L] // otherwise result will be Integer based and therefore too low!) .fold(1L) { acc, v -> acc * v } } }
0
Kotlin
0
0
9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f
4,481
aoc-kotlin-2020
Creative Commons Zero v1.0 Universal
src/Day07.kt
Tiebe
579,377,778
false
{"Kotlin": 17146}
fun main() { fun List<String>.parseFilesystem(): Directory { val structure = Directory("") var currentDirectory = "" for (line in this) { if (line.startsWith("$ ")) { val command = line.replace("$ ", "") if (command == "cd /") currentDirectory = "" else if (command.startsWith("cd")) { val newDirectory = command.replace("cd ", "") currentDirectory = if (newDirectory == "..") { currentDirectory.replaceAfterLast("/", "", "").removeSuffix("/") } else currentDirectory.plus("/$newDirectory").removePrefix("/") } } else { val directoryPath = currentDirectory.split("/").filter { it.isNotEmpty() } var directory = structure directoryPath.forEachIndexed { _, s -> directory = directory.directories[directory.directories.indexOfFirst { it.name == s }] } val file = line.split(" ") if (file[0] == "dir") { if (directory.directories.none { it.name == file[1] }) { directory.directories.add(Directory(file[1])) } } else { directory.files.add(File(file[1], file[0].toInt())) } } } return structure } fun Directory.getDirectoryList(directories: MutableList<Directory> = mutableListOf()): MutableList<Directory> { directories.add(this) for (directory in this.directories) { directory.getDirectoryList(directories) } return directories } fun Directory.getDirectorySize(): Int { var size = 0 for (file in this.files) { size += file.size } for (directory in this.directories) { size += directory.getDirectorySize() } return size } fun part1(input: List<String>): Int { val directoryStructure = input.parseFilesystem() val directories = directoryStructure.getDirectoryList() var totalSize = 0 directories.forEach { if (it.getDirectorySize() <= 100000) { totalSize += it.getDirectorySize() } } return totalSize } fun part2(input: List<String>): Int { val directoryStructure = input.parseFilesystem() val directories = directoryStructure.getDirectoryList() val spaceNeeded = 30000000 - (70000000 - directoryStructure.getDirectorySize()) val directorySizes = directories.map { it.getDirectorySize() }.filter { it >= spaceNeeded } return directorySizes.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") part1(input).println() part2(input).println() } data class Directory(val name: String, var directories: MutableList<Directory> = mutableListOf(), var files: MutableList<File> = mutableListOf()) data class File(val name: String, val size: Int)
1
Kotlin
0
0
afe9ac46b38e45bd400e66d6afd4314f435793b3
3,327
advent-of-code
Apache License 2.0
src/aoc2023/Day15.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2023 import readInput fun main() { fun hash(step: String): Int { var hash = 0 for (c in step) { hash += c.code hash *= 17 hash %= 256 } return hash } fun part1(lines: List<String>): Int { val steps = lines[0].split(',') var sum = 0 for (step in steps) { sum += hash(step) } return sum } fun part2(input: String): Int { val steps = input.split(',') val boxes = Array(256) { mutableListOf<Pair<String, Int>>() } for (step in steps) { if (step.contains('=')) { val splitted = step.split('=') val label = splitted[0] val box = hash(label) val focalLength = splitted[1].toInt() val index = boxes[box].indexOfFirst { it.first == label } if (index == -1) { boxes[box].add(Pair(label, focalLength)) } else { boxes[box][index] = Pair(label, focalLength) } } else { val label = step.substring(0, step.length - 1) val box = hash(label) val index = boxes[box].indexOfFirst { it.first == label } if (index != -1) { boxes[box].removeAt(index) } } } var sum = 0 for (i in boxes.indices) { for (slotIndex in boxes[i].indices) { sum += (i + 1) * (slotIndex + 1) * boxes[i][slotIndex].second } } return sum } println(part1(readInput("aoc2023/Day15_test"))) println(part1(readInput("aoc2023/Day15"))) println(part2(readInput("aoc2023/Day15_test")[0])) println(part2(readInput("aoc2023/Day15")[0])) }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
1,867
advent-of-code-kotlin
Apache License 2.0
src/day-18.kt
drademacher
160,820,401
false
null
import Ground.* import java.io.File fun main(args: Array<String>) { println("part 1: " + partOne()) println("part 2: " + partTwo()) } private enum class Ground { OPEN, TREE, LUMBERYARD } private data class Area(val area: Array<Array<Ground>>) { fun getHeight() = area.size fun getWidth() = area[0].size fun deepCopy() = Area(Array(getWidth()) { it -> area[it].copyOf() }) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Area if (!area.contentDeepEquals(other.area)) return false return true } override fun hashCode(): Int { return area.contentDeepHashCode() } } private fun partOne(): Int { var area = parseInputFile() val generations = 10 area = simulate(area, generations) return calculateAnswerFromArea(area) } private fun partTwo(): Int { var area = parseInputFile() val generations = 1000000000 area = simulateWithCycleDetection(area, generations) return calculateAnswerFromArea(area) } private fun calculateAnswerFromArea(area: Area): Int { val trees = area.area.map { it.count { ground -> ground == TREE } }.sum() val lumberyards = area.area.map { it.count { ground -> ground == LUMBERYARD } }.sum() return trees * lumberyards } private fun simulateWithCycleDetection(area: Area, generations: Int): Area { var newArea = area val previousGenerations = mutableListOf(area) var foundCycleAt = 0 for (i in 0 until generations) { newArea = simulateStep(newArea) if (newArea in previousGenerations) { foundCycleAt = i + 1 break } previousGenerations.add(newArea) } val cycleLength = foundCycleAt - previousGenerations.indexOf(newArea) val fastForward = (generations - foundCycleAt) % cycleLength return simulate(newArea, fastForward) } private fun simulate(area: Area, generations: Int): Area { var newArea = area for (i in 0 until generations) { newArea = simulateStep(newArea) } return newArea } private fun simulateStep(area: Area): Area { val nextArea = area.deepCopy() for (x in 0 until area.getWidth()) { for (y in 0 until area.getHeight()) { nextArea.area[y][x] = when (area.area[y][x]) { OPEN -> if (countSurroundingGround(area, x, y, TREE) >= 3) TREE else OPEN TREE -> if (countSurroundingGround(area, x, y, LUMBERYARD) >= 3) LUMBERYARD else TREE LUMBERYARD -> if (countSurroundingGround(area, x, y, LUMBERYARD) >= 1 && countSurroundingGround(area, x, y, TREE) >= 1) LUMBERYARD else OPEN } } } return nextArea } private fun countSurroundingGround(area: Area, x: Int, y: Int, whatToCount: Ground): Int { var res = 0 for (curX in x - 1..x + 1) { for (curY in y - 1..y + 1) { val validArrayIndex = curX in 0 until area.getWidth() && curY in 0 until area.getHeight() val isNotCenter = curX != x || curY != y if (validArrayIndex && isNotCenter && area.area[curY][curX] == whatToCount) { res += 1 } } } return res } private fun printArea(area: Area) { area.area.forEach { println(it.map(::mapToChar).joinToString(separator = "")) } } private fun parseInputFile(): Area { val rawFile = File("res/day-18.txt").readText() return Area( rawFile .split("\n") .filter { it != "" } .map { it.map(::mapToGround).toTypedArray() } .toTypedArray() ) } private fun mapToGround(char: Char): Ground { return when (char) { '.' -> OPEN '|' -> TREE '#' -> LUMBERYARD else -> throw Exception("invalid symbol at parsing input") } } private fun mapToChar(ground: Ground): Char { return when (ground) { OPEN -> '.' TREE -> '|' LUMBERYARD -> '#' } }
0
Kotlin
0
0
a7f04450406a08a5d9320271148e0ae226f34ac3
4,081
advent-of-code-2018
MIT License
src/Day12.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.io.Reader fun main() { val testInput = """ Sabqponm abcryxxl accszExk acctuvwj abdefghi """.trimIndent() val testCliff = getCliffNodes(testInput.reader()) val testGraph = testCliff.nodes.flatten() val testDj = djikstra(testGraph, testCliff.start) check(testDj.first[testCliff.end] == 31) val cliff = getCliffNodes(reader("Day12.txt")) val graph = cliff.nodes.flatten() val dj = djikstra(graph, cliff.start) println(dj.first[cliff.end]) // brute force // val aList = graph.filter { it.char == 'a' } // var minSteps = Int.MAX_VALUE // aList.forEachIndexed { index, a -> // val endSteps = djikstra(graph, a).first[cliff.end]!! // if (endSteps in 0 until minSteps) { // minSteps = endSteps // } // println("${index * 100f / aList.size.toFloat()} %") // } // println(minSteps) val reverseCliff = getCliffNodes(reader("Day12.txt"), true) val reverseGraph = reverseCliff.nodes.flatten() val reverseDj = djikstra(reverseGraph, reverseCliff.start) reverseDj.first .filter { cliffDist -> cliffDist.key.char == 'z' && cliffDist.value > 0 } .values .min() .also { println(it) } } private fun getCliffNodes(src: Reader, isReverse: Boolean = false): CliffGraph { val cliffs = mutableListOf<MutableList<CliffNode>>() lateinit var start: CliffNode lateinit var end: CliffNode var rowIx = 0 src.forEachLine { row -> val cliffRow = mutableListOf<CliffNode>() row.forEachIndexed { column, c -> when (isReverse) { true -> when (c) { 'S' -> CliffNode('z', column, rowIx).also { end = it } 'E' -> CliffNode('a', column, rowIx).also { start = it } else -> CliffNode(('a'.code + 'z'.code - c.code).toChar(), column, rowIx) }.also { it.graph = cliffs cliffRow += it } false -> when (c) { 'S' -> CliffNode('a', column, rowIx).also { start = it } 'E' -> CliffNode('z', column, rowIx).also { end = it } else -> CliffNode(c, column, rowIx) }.also { it.graph = cliffs cliffRow += it } } } cliffs += cliffRow rowIx++ } return CliffGraph(start, end, cliffs) } data class CliffGraph( val start: CliffNode, val end: CliffNode, val nodes: List<List<CliffNode>> ) data class CliffNode( val char: Char, val x: Int, val y: Int ) { private val height = char.code val neighbours: List<CliffNode> by lazy { val list = ArrayList<CliffNode>(4) // left if (x != 0) list += graph[y][x-1] // right if (x < graph[y].lastIndex) list += graph[y][x+1] // up if (y != 0) list += graph[y-1][x] // down if (y < graph.lastIndex) list += graph[y+1][x] list.filter { cliff -> (this.height + 1) >= cliff.height } } lateinit var graph: List<List<CliffNode>> } private fun djikstra(graph: List<CliffNode>, source: CliffNode): Pair<Map<CliffNode, Int>, Map<CliffNode, CliffNode?>> { val distances: MutableMap<CliffNode, Int> = graph.associateWith { Int.MAX_VALUE }.toMutableMap() val prev: MutableMap<CliffNode, CliffNode?> = graph.associateWith { null }.toMutableMap() distances[source] = 0 val queue = ArrayList(graph) val seen = mutableListOf<CliffNode>() while (queue.isNotEmpty()) { val u = run { var currentMin = queue[0] queue.forEach { if (distances[it]!! < distances[currentMin]!!) { currentMin = it } } currentMin } queue -= u seen += u u.neighbours.forEach { v -> if (distances[v]!! > distances[u]!! + 1) { distances[v] = distances[u]!! + 1 prev[v] = u } } } return distances to prev }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
4,193
advent-of-code-2022-kotlin
Apache License 2.0
src/day02/Day02.kt
apeinte
574,487,528
false
{"Kotlin": 47438}
package day02 import readDayInput const val OPPONENT_ROCK = "A" const val OPPONENT_PAPER = "B" const val OPPONENT_SCISSOR = "C" const val MY_ROCK = "X" const val MY_PAPER = "Y" const val MY_SCISSORS = "Z" enum class OpponentRockPaperScissors(val choice: String, val score: Int) { ROCK(OPPONENT_ROCK, 1), PAPER(OPPONENT_PAPER, 2), SCISSORS(OPPONENT_SCISSOR, 3); companion object { fun stringToMRPS(value: String): OpponentRockPaperScissors { return when (value) { ROCK.choice -> ROCK PAPER.choice -> PAPER else -> SCISSORS } } } } enum class MyRockPaperScissors(val choice: String, val score: Int) { ROCK(MY_ROCK, 1), PAPER(MY_PAPER, 2), SCISSORS(MY_SCISSORS, 3); companion object { fun stringToMRPS(value: String): MyRockPaperScissors { return when (value) { ROCK.choice -> ROCK PAPER.choice -> PAPER else -> SCISSORS } } } } enum class MyRoundRockPaperScissors(val choice: String) { WIN(MY_SCISSORS), DRAW(MY_PAPER), LOOSE(MY_ROCK); companion object { fun myChoiceToMyResult(choice: MyRockPaperScissors): MyRoundRockPaperScissors { return when(choice.choice) { WIN.choice -> WIN DRAW.choice -> DRAW else -> LOOSE } } } } fun main() { fun parseTournament(input: List<String>): List<RoundRockPaperScissors> { val result = mutableListOf<RoundRockPaperScissors>() input.forEach { val round = it.split(" ") val opponentChoice = round[0] val myChoice = round[1] result.add( RoundRockPaperScissors( OpponentRockPaperScissors.stringToMRPS(opponentChoice), MyRockPaperScissors.stringToMRPS(myChoice) ) ) } return result } fun parts1(input: List<RoundRockPaperScissors>): Int { var result = 0 input.forEach { result += it.rockPaperScissors().myScore } return result } fun parts2(input: List<RoundRockPaperScissors>): Int { var result = 0 input.forEach { println("----- New Round -----") when(MyRoundRockPaperScissors.myChoiceToMyResult(it.myChoice)) { MyRoundRockPaperScissors.WIN -> it.needToWin() MyRoundRockPaperScissors.DRAW -> it.needToDraw() MyRoundRockPaperScissors.LOOSE -> it.needToLoose() } result += it.rockPaperScissors().myScore println("----------------------") } return result } val parsedTournament = parseTournament(readDayInput(2)) println( "What would your total score be if everything goes exactly according to your strategy guide?" + "\n${parts1(parsedTournament)}" ) println("Following the Elf's instructions for the second column, what would your total score be if everything goes exactly according to your strategy guide?\n${parts2(parsedTournament)}") } class RoundRockPaperScissors( var opponentChoice: OpponentRockPaperScissors, var myChoice: MyRockPaperScissors ) { var myScore = 0 var opponentScore = 0 fun rockPaperScissors(): RoundRockPaperScissors { println("ROCK PAPER SCISSORS! $opponentChoice VS $myChoice") if (opponentChoice.name == myChoice.name) { itsADraw() return this } when (opponentChoice) { OpponentRockPaperScissors.ROCK -> { if (myChoice == MyRockPaperScissors.PAPER) { iWin() } else { iLoose() } } OpponentRockPaperScissors.PAPER -> { if (myChoice == MyRockPaperScissors.SCISSORS) { iWin() } else { iLoose() } } OpponentRockPaperScissors.SCISSORS -> { if (myChoice == MyRockPaperScissors.ROCK) { iWin() } else { iLoose() } } } return this } fun needToWin(): RoundRockPaperScissors { println("I need to win $opponentChoice VS $myChoice") myChoice = when(opponentChoice) { OpponentRockPaperScissors.ROCK -> { MyRockPaperScissors.PAPER } OpponentRockPaperScissors.PAPER -> { MyRockPaperScissors.SCISSORS } OpponentRockPaperScissors.SCISSORS -> { MyRockPaperScissors.ROCK } } println("change to $myChoice") return this } fun needToLoose(): RoundRockPaperScissors { println("I need to loose $opponentChoice VS $myChoice") myChoice = when(opponentChoice) { OpponentRockPaperScissors.ROCK -> { MyRockPaperScissors.SCISSORS } OpponentRockPaperScissors.PAPER -> { MyRockPaperScissors.ROCK } OpponentRockPaperScissors.SCISSORS -> { MyRockPaperScissors.PAPER } } println("change to $myChoice") return this } fun needToDraw() { println("I need to draw $opponentChoice VS $myChoice") myChoice = MyRockPaperScissors.valueOf(opponentChoice.name) println("change to $myChoice") } private fun itsADraw() { myScore = myChoice.score + 3 opponentScore = opponentChoice.score + 3 println("It's a draw and I get $myScore points.") } private fun iWin() { myScore = myChoice.score + 6 opponentScore = opponentChoice.score println("I win and get $myScore points.") } private fun iLoose() { myScore = myChoice.score opponentScore = opponentChoice.score + 6 println("I loose and get $myScore points.") } }
0
Kotlin
0
0
4bb3df5eb017eda769b29c03c6f090ca5cdef5bb
6,174
my-advent-of-code
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch9/Problem100.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch9 import java.math.BigInteger import kotlin.math.sqrt /** * Problem 100: Arranged Probability * * https://projecteuler.net/problem=100 * * Goal: Find the first arrangement (of blue and red discs) to contain > D total discs, where the * probability of taking 2 blue discs is exactly P/Q. Output the number of blue discs followed by * the total amount of discs. * * Constraints: 2 <= D <= 1e15, 0 < P < Q <= 1e7 * * e.g. A box has 21 total discs, of which 15 are blue and 6 are red. The probability of taking 2 * blue discs at random is P(BB) = 15/21 * 14/20 = 1/2. The next arrangement to also have exactly * 50% chance involves a box with 120 total discs, of which 85 must be blue. * * e.g.: D = 2, P/Q = 1/2 * output = 3 4 */ class ArrangedProbability { /** * Solution based on the equation: * * X^2 - X = p * (b^2 - b), where p = probability of picking 2 blue discs * * If a value of X is assumed (& valid), the value of b is found by solving for the positive * integer solution of the quadratic equation: * * 0 = b^2 - b - ((X^2 - X) / p) * * A quadratic solution is solved using the formula: * * (-b +/- sqrt(b^2 - 4ac)) / 2a, with a = 1, b = -1, and c = -(X^2 - X) / p * * Since the value of a and b never change & only the positive integer solution is required & * c is always negative, the formula becomes: * * (1 + sqrt(4c + 1)) / 2 * * This means that 2 requirements are needed for a positive solution to be possible: * - 4c must be a whole positive integer to be a square number when incremented. * - the square root must be odd to be divisible by 2 when incremented. * * Brute force of the solutions also brought to light that [totalDiscs] switched between even * and odd values, with the first arrangement always having an even total, but this is only * useful if generating all arrangements. Brute force also shows that some fractions (e.g. * 1/2, 3/4, 11/12) can be easily found using the following: * * given initial values determined using the equations above: * red_{n+1} = 2 * blue_n + red_n - 1 * blue_{n+1} = blue_n + (pNum + pDenom - 1) * red_{n+1} * * Certain fractions deviate from this norm (e.g. 3/8, 2/5) by toggling between 2 distinct * fractions to use in the multiplication, e.g.: * * given p = 3/8 * red_{n+1} = 2 * blue_n + red_n - 1 * blue_{n+1} = blue_n + (6/5 OR ~189/125) * red_{n+1} */ fun getNextArrangement(limit: Long, probNum: Int, probDenom: Int): Pair<String, String>? { val (p, q) = probNum.toBigInteger() to probDenom.toBigInteger() val (zero, one, two, four) = listOf(BigInteger.ZERO, BigInteger.ONE, BigInteger.TWO, 4.toBigInteger()) var blueDiscs = zero val maxTotal = BigInteger.valueOf(Long.MAX_VALUE) var totalDiscs = (limit + 1).toBigInteger() while (totalDiscs < maxTotal) { // divideAndRemainder() returns quotient and remainder as array // is this necessary? BI don't seem to ever leave a remainder? val (c, cRem) = (totalDiscs * (totalDiscs - one) * p).divideAndRemainder(q) // must have integer value if (cRem == zero) { // sqrtAndRemainder() returns integer root and remainder as array val (root, rRem) = (four * c + one).sqrtAndRemainder() // must have integer root, which must be odd if (rRem == zero && root.mod(two) == one) { blueDiscs = (root + one) / two break } } totalDiscs++ } return if (blueDiscs == zero) null else { blueDiscs.toString() to totalDiscs.toString() } } /** * Original PE problem (p = 1/2) results in a known integer sequence of [blueDiscs] based on * the solution to X(X-1) = 2b(b-1), such that: * * when p = 1/2 -> b(n) = 6b(n-1) - b(n-2) - 2, with b(0) = 1, b(1) = 3 * * Some other fractions can be observed to follow a similar pattern: * * when p = 3/4 -> b(n) = 14b(n-1) - b(n-2) - 6 * when p = 5/7 -> b(n) = 12b(n-1) - b(n-2) - 5 * * @see <a href="https://oeis.org/A011900">Sequence</a> */ fun getNextHalfArrangement(limit: Long): Pair<String, String> { if (limit <= 3L) return "3" to "4" var blueNMinus2 = 1L var blueNMinus1 = 3L var blueDiscs: Long var totalDiscs: Long do { blueDiscs = 6 * blueNMinus1 - blueNMinus2 - 2 val rhs = 2 * blueDiscs * (blueDiscs - 1) val root = sqrt(1.0 + 4 * rhs).toLong() totalDiscs = (1 + root) / 2 blueNMinus2 = blueNMinus1 blueNMinus1 = blueDiscs } while (totalDiscs <= limit) return blueDiscs.toString() to totalDiscs.toString() } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
5,077
project-euler-kotlin
MIT License
src/Day12.kt
er453r
572,440,270
false
{"Kotlin": 69456}
fun main() { val aCode = 'a'.code val (startCode, endCode) = arrayOf('S'.code - aCode, 'E'.code - aCode) fun neighbours(cell: GridCell<Int>, grid: Grid<Int>) = grid.crossNeighbours(cell.position).filter { it.value < cell.value + 2 } fun prepareData(input: List<String>): Triple<Grid<Int>, GridCell<Int>, GridCell<Int>> { val grid = Grid(input.map { it.toCharArray().asList().map { char -> char.code - aCode } }) val start = grid.data.flatten().first { it.value == startCode }.also { it.value = 0 } val end = grid.data.flatten().first { it.value == endCode }.also { it.value = 26 } return Triple(grid, start, end) } fun part1(input: List<String>) = prepareData(input).let { (grid, start, end) -> grid.path(start, end, neighbours = { neighbours(it, grid) }).size - 1 } fun part2(input: List<String>) = prepareData(input).let { (grid, _, end) -> grid.data.asSequence().flatten().filter { it.value == 0 }.map { cell -> grid.path(cell, end, neighbours = { neighbours(it, grid) }) }.filter { it.isNotEmpty() }.minOf { it.size - 1 } } test( day = 12, testTarget1 = 31, testTarget2 = 29, part1 = ::part1, part2 = ::part2, ) }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
1,288
aoc2022
Apache License 2.0
src/main/kotlin/com/leonra/adventofcode/advent2023/day09/Day9.kt
LeonRa
726,688,446
false
{"Kotlin": 30456}
package com.leonra.adventofcode.advent2023.day09 import com.leonra.adventofcode.shared.readResource /** https://adventofcode.com/2023/day/9 */ private object Day9 { fun partOne(): Int { val histories = mutableListOf<List<Int>>() readResource("/2023/day09/part1.txt") { line -> val history = line.split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.toInt() } .toList() histories.add(history) } var sum = 0 for (history in histories) { val steps = mutableListOf<List<Int>>() steps.add(history) while (steps.last().any { it != 0 }) { val nextStep = mutableListOf<Int>() for (index in 0 until steps.last().size - 1) { nextStep.add(steps.last()[index + 1] - steps.last()[index]) } steps.add(nextStep) } var previous = steps.last().last() for (index in (0 until steps.size - 1).reversed()) { previous += steps[index].last() } sum += previous } return sum } fun partTwo(): Int { val histories = mutableListOf<List<Int>>() readResource("/2023/day09/part1.txt") { line -> val history = line.split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.toInt() } .toList() histories.add(history) } var sum = 0 for (history in histories) { val steps = mutableListOf<List<Int>>() steps.add(history) while (steps.last().any { it != 0 }) { val nextStep = mutableListOf<Int>() for (index in 0 until steps.last().size - 1) { nextStep.add(steps.last()[index + 1] - steps.last()[index]) } steps.add(nextStep) } var previous = steps.last().first() for (index in (0 until steps.size - 1).reversed()) { previous = steps[index].first() - previous } sum += previous } return sum } } private fun main() { println("Part 1 sum: ${Day9.partOne()}") println("Part 2 sum: ${Day9.partTwo()}") }
0
Kotlin
0
0
46bdb5d54abf834b244ba9657d0d4c81a2d92487
2,407
AdventOfCode
Apache License 2.0
src/com/ncorti/aoc2022/Day02.kt
cortinico
571,724,497
false
{"Kotlin": 5773}
package com.ncorti.aoc2022 fun scoreForInput(input: String) = when(input) { "X" -> 1 "Y" -> 2 else -> 3 } fun playLose(input: String) = when(input) { "A" -> "Z" "B" -> "X" else -> "Y" } fun playDraw(input: String) = when(input) { "A" -> "X" "B" -> "Y" else -> "Z" } fun playWin(input: String) = when(input) { "A" -> "Y" "B" -> "Z" else -> "X" } fun main() { fun part1() = getInputAsText("02") { split("\n") } .map { it.split(" ") } .sumOf { (opponent, you) -> val selectedScore = scoreForInput(you) val outcomeScore = when { (opponent == "A" && you == "X") || (opponent == "B" && you == "Y") || (opponent == "C" && you == "Z") -> 3 (you == "X" && opponent == "C") || (you == "Y" && opponent == "A") || (you == "Z" && opponent == "B") -> 6 else -> 0 } selectedScore + outcomeScore } fun part2() = getInputAsText("02") { split("\n") } .map { it.split(" ") } .sumOf { (opponent, you) -> val outcomeScore = when (you) { "X" -> 0 "Y" -> 3 else -> 6 } val selectedLetter = when(outcomeScore) { 0 -> playLose(opponent) 3 -> playDraw(opponent) else -> playWin(opponent) } outcomeScore+ scoreForInput(selectedLetter) } println(part1()) println(part2()) }
4
Kotlin
0
1
cd9ad108a1ed1ea08f9313c4cad5e52a200a5951
1,375
adventofcode-2022
MIT License
src/main/kotlin/days/Day14.kt
andilau
429,206,599
false
{"Kotlin": 113274}
package days import kotlin.math.max @AdventOfCodePuzzle( name = "Space Stoichiometry", url = "https://adventofcode.com/2019/day/14", date = Date(day = 14, year = 2019) ) class Day14(input: List<String>) : Puzzle { private val reactions: Map<String, Pair<Long, List<Quantity>>> = input.parseReactions() override fun partOne(): Long = calculateOreFor("FUEL", 1L) override fun partTwo(): Long = calculateMaximumFuelWith(one_trillion) { fuel -> calculateOreFor(amount = fuel) } private fun calculateOreFor( chemical: String = "FUEL", amount: Long = 1, inventory: MutableMap<String, Long> = mutableMapOf() ): Long { if (chemical == "ORE") return amount // base case val inventoryAmount = inventory.getOrDefault(chemical, 0) if (inventoryAmount > 0) { // got it or some inventory[chemical] = max(inventoryAmount - amount, 0) } val neededAmount = amount - inventoryAmount if (neededAmount > 0) { val formula = reactions[chemical] ?: error("Cant produce chemical: $chemical") val producesAmount = formula.first val recipe = formula.second val factor = ceil(neededAmount, producesAmount) val producesWithExcess = producesAmount * factor val excess = producesWithExcess - neededAmount if (excess > 0) { inventory.merge(chemical, excess) { a, b -> a + b } } return recipe.sumOf { inputQuantity -> calculateOreFor( inputQuantity.chemical, inputQuantity.amount * factor, inventory ) } } return 0 } private fun calculateMaximumFuelWith(maxQuantityOre: Long, function: (Long) -> Long): Long { var low = 1L var high = maxQuantityOre while (low + 1 < high) { val guess = (low + high) / 2 val ore = function(guess) if (ore > maxQuantityOre) high = guess else low = guess } return low } private fun ceil(a: Long, b: Long) = (a + b - 1) / b private fun List<String>.parseReactions() = associate { line -> val from = line.substringAfter("=>").let { Quantity.from(it) } val receipt = line .substringBefore("=>") .split(',') .map { Quantity.from(it) } from.chemical to Pair(from.amount, receipt) } data class Quantity(val chemical: String, val amount: Long) { companion object { private val REGEX_QUANTITY_SYMBOL = Regex("""\s*(\d+)\s+(\w+)\s*""") fun from(string: String): Quantity { return REGEX_QUANTITY_SYMBOL.matchEntire(string)?.let { val (quantity, symbol) = it.destructured Quantity(symbol, quantity.toLong()) } ?: throw IllegalArgumentException("Unable to parse $string into Quantity") } } } companion object { private const val one_trillion = 1_000_000_000_000 } }
2
Kotlin
0
0
f51493490f9a0f5650d46bd6083a50d701ed1eb1
3,253
advent-of-code-2019
Creative Commons Zero v1.0 Universal
src/Day04.kt
undermark5
574,819,802
false
{"Kotlin": 67472}
fun main() { fun part1(input: List<String>): Int { val mapped: List<Boolean> = input.map { val ranges: List<IntRange> = it.split(",").map { it.toIntRange("-") } val first: IntRange = ranges.first() val second: IntRange = ranges.last() first in second || second in first } return mapped.count { it } } fun part2(input: List<String>): Int { return input.map { val ranges = it.split(",").map { it.toIntRange("-") } val first = ranges.first() val second = ranges.last() first.any { it in second } || second.any { it in first } }.count {it} } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e9cf715b922db05e1929f781dc29cf0c7fb62170
932
AoC_2022_Kotlin
Apache License 2.0
src/day02/Day02.kt
banshay
572,450,866
false
{"Kotlin": 33644}
package day02 import day02.FixedOutcome.* import readInput fun main() { fun part1(input: List<String>): Int { return input.sumOf { it.toRound().score() } } fun part2(input: List<String>): Int { return input.sumOf { it.toFixedRound().score() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println("test part1: ${part1(testInput)}") println("test part2: ${part2(testInput)}") val input = readInput("Day02") println("result part1: ${part1(input)}") println("result part2: ${part2(input)}") } interface Scoring { fun score(): Int } enum class OpponentChoice(val code: String) { ROCK("A") { override fun fixOutcome(fixedOutcome: FixedOutcome): PlayerChoice { return when (fixedOutcome) { LOSE -> PlayerChoice.SCISSOR DRAW -> PlayerChoice.ROCK WIN -> PlayerChoice.PAPER } } }, PAPER("B") { override fun fixOutcome(fixedOutcome: FixedOutcome): PlayerChoice { return when (fixedOutcome) { LOSE -> PlayerChoice.ROCK DRAW -> PlayerChoice.PAPER WIN -> PlayerChoice.SCISSOR } } }, SCISSOR("C") { override fun fixOutcome(fixedOutcome: FixedOutcome): PlayerChoice { return when (fixedOutcome) { LOSE -> PlayerChoice.PAPER DRAW -> PlayerChoice.SCISSOR WIN -> PlayerChoice.ROCK } } }; abstract fun fixOutcome(fixedOutcome: FixedOutcome): PlayerChoice companion object { private val map = OpponentChoice.values().associateBy { it.code } infix fun from(code: String): OpponentChoice = map[code] ?: throw RuntimeException("OpponentChoice with value $code does not exist") } } enum class Outcome : Scoring { LOSS { override fun score() = 0 }, DRAW { override fun score() = 3 }, WIN { override fun score() = 6 } } enum class FixedOutcome(val code: String) : Scoring { LOSE("X") { override fun score() = 0 }, DRAW("Y") { override fun score() = 3 }, WIN("Z") { override fun score() = 6 }; companion object { private val map = values().associateBy { it.code } infix fun from(code: String): FixedOutcome = map[code] ?: throw RuntimeException("FixedOutcome with value $code does not exist") } } enum class PlayerChoice(val code: String) : Scoring { ROCK("X") { override fun score() = 1 override fun outcome(opponentChoice: OpponentChoice): Outcome { return when (opponentChoice) { OpponentChoice.ROCK -> Outcome.DRAW OpponentChoice.PAPER -> Outcome.LOSS OpponentChoice.SCISSOR -> Outcome.WIN } } }, PAPER("Y") { override fun score() = 2 override fun outcome(opponentChoice: OpponentChoice): Outcome { return when (opponentChoice) { OpponentChoice.ROCK -> Outcome.WIN OpponentChoice.PAPER -> Outcome.DRAW OpponentChoice.SCISSOR -> Outcome.LOSS } } }, SCISSOR("Z") { override fun score() = 3 override fun outcome(opponentChoice: OpponentChoice): Outcome { return when (opponentChoice) { OpponentChoice.ROCK -> Outcome.LOSS OpponentChoice.PAPER -> Outcome.WIN OpponentChoice.SCISSOR -> Outcome.DRAW } } }; abstract fun outcome(opponentChoice: OpponentChoice): Outcome companion object { private val map = PlayerChoice.values().associateBy { it.code } infix fun from(code: String): PlayerChoice = map[code] ?: throw RuntimeException("PlayerChoice with value $code does not exist") } } data class Round(val opponentChoice: OpponentChoice, val playerChoice: PlayerChoice) : Scoring { override fun score(): Int { return playerChoice.score() + playerChoice.outcome(opponentChoice).score() } } data class FixedRound(val opponentChoice: OpponentChoice, val fixedOutcome: FixedOutcome) : Scoring { override fun score(): Int { return opponentChoice.fixOutcome(fixedOutcome).score() + fixedOutcome.score() } } fun String.toRound() = Round(OpponentChoice from substringBefore(" "), PlayerChoice from substringAfter(" ")) fun String.toFixedRound() = FixedRound(OpponentChoice from substringBefore(" "), FixedOutcome from substringAfter(" "))
0
Kotlin
0
0
c3de3641c20c8c2598359e7aae3051d6d7582e7e
4,716
advent-of-code-22
Apache License 2.0
src/Day06.kt
allwise
574,465,192
false
null
fun main() { fun part1(input: List<String>): Int { val signals = Signals(input) return signals.process() } fun part2(input: List<String>): Int { val signals = Signals(input) return signals.process2() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) } class Signals(val input:List<String>){ fun process():Int{ val a:Int = input.map { str: String -> findUnique(str,4) }.single() return a } fun process2():Int{ val a:Int = input.map { str: String -> findUnique(str,14) }.single() return a } private fun findUnique(str: String, size:Int):Int { str.forEachIndexed { idx: Int, _ -> if (str.subSequence(idx, idx + size).toSet().size == size) { println("""${str.subSequence(idx, idx + size)} (${idx + size})""") return (idx + size) } } return -1 } }
0
Kotlin
0
0
400fe1b693bc186d6f510236f121167f7cc1ab76
1,204
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/WordFilter.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * Prefix and Suffix Search * @see <a href="https://leetcode.com/problems/prefix-and-suffix-search/">Source</a> */ fun interface WordFilter { operator fun invoke(prefix: String, suffix: String): Int } /** * Approach #1: Trie + Set Intersection [Time Limit Exceeded] */ class WordFilterTrie(words: Array<String>) : WordFilter { private val trie1: WFTrieNode = WFTrieNode() private val trie2: WFTrieNode = WFTrieNode() private var wt = 0 init { words.forEach { word -> val ca = word.toCharArray() insertWord(ca, trie1) insertWord(ca.reversedArray(), trie2) wt++ } } private fun insertWord(charArray: CharArray, root: WFTrieNode) { var cur = root cur.weight.add(wt) for (letter in charArray) { val index = letter - 'a' if (cur.children[index] == null) { cur.children[index] = WFTrieNode() } cur = cur.children[index]!! cur.weight.add(wt) } } override operator fun invoke(prefix: String, suffix: String): Int { val cur1 = getNodeWithPrefix(prefix, trie1) val cur2 = getNodeWithPrefix(suffix.reversed(), trie2) return cur1.weight.intersect(cur2.weight).maxOrNull() ?: -1 } private fun getNodeWithPrefix(prefix: String, root: WFTrieNode): WFTrieNode { var cur = root for (letter in prefix.toCharArray()) { val index = letter - 'a' cur = cur.children[index] ?: return WFTrieNode() } return cur } class WFTrieNode { var children: Array<WFTrieNode?> = arrayOfNulls(ALPHABET_LETTERS_COUNT) var weight: MutableSet<Int> = HashSet() } companion object { private const val ALPHABET_LETTERS_COUNT = 26 } } class WordFilterWrappedWords(words: Array<String>) : WordFilter { private var trie: TrieNode = TrieNode() init { for (weight in words.indices) { val word: String = words[weight] + "{" for (i in word.indices) { var cur: TrieNode = trie cur.weight = weight for (j in i until 2 * word.length - 1) { val k = word[j % word.length] - 'a' if (cur.children[k] == null) { cur.children[k] = TrieNode() } cur = cur.children[k]!! cur.weight = weight } } } } override operator fun invoke(prefix: String, suffix: String): Int { var cur: TrieNode = trie for (letter in "$suffix{$prefix".toCharArray()) { if (cur.children[letter - 'a'] == null) return -1 cur = cur.children[letter - 'a']!! } return cur.weight } class TrieNode { var children: Array<TrieNode?> = arrayOfNulls(27) var weight: Int = 0 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,623
kotlab
Apache License 2.0
src/Day12.kt
uekemp
575,483,293
false
{"Kotlin": 69253}
data class HeightMap(val destination: Point, val nodes: Array<MutableList<Node>>) { private val width = nodes[0].size private val height = nodes.size operator fun get(point: Point): Node { return nodes[point.y][point.x] } operator fun get(x: Int, y: Int): Node { return nodes[y][x] } fun applyToAll(apply: (Node) -> Unit) { nodes.forEach { row -> row.forEach { node -> apply(node) } } } fun neighboursOf(point: Point): List<Node> { return buildList<Node> { if ((point.x > 0) && canMoveTo(point, point.x - 1, point.y)) { add(this@HeightMap[point.x - 1, point.y]) } if ((point.x < width - 1) && canMoveTo(point, point.x + 1, point.y)) { add(this@HeightMap[point.x + 1, point.y]) } if ((point.y > 0) && canMoveTo(point, point.x, point.y - 1)) { add(this@HeightMap[point.x, point.y - 1]) } if ((point.y < height - 1) && canMoveTo(point, point.x, point.y + 1)) { add(this@HeightMap[point.x, point.y + 1]) } } } fun createShortestPath(): List<Node> { check(this[destination].predecessor != null) { "Shortest path not found yet" } val shortestPath = ArrayDeque<Node>() var current = this[destination] shortestPath.add(current) while (current.predecessor != null) { current = current.predecessor!! shortestPath.addFirst(current) } return shortestPath } private fun canMoveTo(start: Point, x: Int, y: Int) = this[start].canMoveTo(this[x, y]) fun resetMap() { applyToAll { it.distance = Int.MAX_VALUE it.predecessor = null } } class Node( val position: Point, val height: Int, var distance: Int = Int.MAX_VALUE, var predecessor: Node? = null ) { fun canMoveTo(other: Node): Boolean = this.height + 1 >= other.height override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Node if (position != other.position) return false return true } override fun hashCode(): Int { return position.hashCode() } } data class Point(val x: Int, val y: Int) } fun parseHeightMap(input: List<String>): HeightMap { val rows = Array(input.size) { mutableListOf<HeightMap.Node>() } var start: HeightMap.Point? = null var destination: HeightMap.Point? = null input.forEachIndexed { row, line -> line.toCharArray().forEachIndexed { col, char -> val position = HeightMap.Point(col, row) val height = if (char == 'S') { start = position 'a' } else if (char == 'E') { destination = position 'z' } else { char } rows[row].add(HeightMap.Node(position, height - 'a')) } } rows[start!!.y][start!!.x].distance = 0 return HeightMap(destination!!, rows) } fun findShortestPath(map: HeightMap): List<HeightMap.Node> { val nonVisitedNodes = mutableSetOf<HeightMap.Node>() map.applyToAll { nonVisitedNodes.add(it) } while (map[map.destination].predecessor == null && nonVisitedNodes.isNotEmpty()) { val current = nonVisitedNodes.minBy { node -> node.distance } val distanceToNext = current.distance + 1 for (neighbour in map.neighboursOf(current.position)) { if (nonVisitedNodes.contains(neighbour) && distanceToNext < neighbour.distance) { neighbour.distance = distanceToNext neighbour.predecessor = current } } nonVisitedNodes.remove(current) } return map.createShortestPath() } fun main() { fun part1(input: List<String>): Int { val map = parseHeightMap(input) val shortestPath = findShortestPath(map) // println(shortestPath.map { node -> node.position }) return shortestPath.size - 1 } fun part2(input: List<String>): Int { val map = parseHeightMap(input) val lowestNodes = mutableListOf<HeightMap.Node>() map.applyToAll { if (it.height == 0) lowestNodes.add(it) } // println("Number of nodes with height 0=${lowestNodes.size}") var min = Int.MAX_VALUE while (lowestNodes.isNotEmpty()) { val node = lowestNodes.removeFirst() map.resetMap() map[node.position].distance = 0 // This defines the starting point! val shortestPath = findShortestPath(map) if (shortestPath.size - 1 < min) { min = shortestPath.size - 1 } // println("Checked: $node, shortestPath=${shortestPath.size - 1}, remaining=${lowestNodes.size}") } return min } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") val steps = part1(testInput) check(steps == 31) check(part2(testInput) == 29) println("-----------------------") val input = readInput("Day12") check(part1(input) == 380) check(part2(input) == 375) }
0
Kotlin
0
0
bc32522d49516f561fb8484c8958107c50819f49
5,443
advent-of-code-kotlin-2022
Apache License 2.0
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day14.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.adventofcode.twentytwenty import kotlin.math.pow fun List<String>.day14Part2(): Long { val memory: MutableMap<Long, Long> = mutableMapOf() var mask: List<Char> = "".toCharArray().toList() this.forEach { instructionLine -> if (instructionLine.isMask()) { mask = instructionLine.getMask() } else { val instruction = instructionLine.getInstruction() val binaryAddress = Integer.toBinaryString(instruction.first).padStart(36, '0').toCharArray().toMutableList() mask.forEachIndexed { index, c -> if (c == 'X') { binaryAddress[index] = 'X' } else if (c == '1') { binaryAddress[index] = '1' } } val numOfVariations = binaryAddress.count { it == 'X' } val memoryLocations = mutableListOf<Long>() val binaryCombinations = numOfVariations.getBinaryCombinations() binaryCombinations.forEach { binaryCombination -> var currentIndex = 0 val changedAddress = binaryAddress.map { if (it == 'X') { currentIndex++ return@map binaryCombination[currentIndex - 1] } return@map it }.fold("") { acc, c -> "$acc$c" } memoryLocations.add(java.lang.Long.parseLong(changedAddress, 2)) } memoryLocations.forEach { memory[it] = instruction.second.toLong() } } } return memory.values.sum() } private fun Int.getBinaryCombinations(): List<List<Char>> { val combinations = mutableListOf<List<Char>>() val numCombinations = (2.0).pow(this).toInt() for (i in (0 until numCombinations)) { combinations.add(Integer.toBinaryString(i).padStart(this, '0').toCharArray().toList()) } return combinations } fun List<String>.day14Part1(): Long { val memory: MutableMap<Int, List<Char>> = mutableMapOf() var mask: List<Char> = "".toCharArray().toList() this.forEach { if (it.isMask()) { mask = it.getMask() } else { val instruction = it.getInstruction() val binaryValue = Integer.toBinaryString(instruction.second).padStart(36, '0').toCharArray().toMutableList() mask.forEachIndexed { index, i -> if (i != 'X') { binaryValue[index] = i } } memory[instruction.first] = binaryValue } } val integerValues = memory .mapValues { it.value.fold("") { acc, c -> "$acc$c" } } .mapValues { java.lang.Long.parseLong(it.value, 2) } return integerValues.values.sum() } private fun String.isMask(): Boolean = this.startsWith("mask") private fun String.getMask(): List<Char> = this.split("=")[1].trim().toCharArray().toList() private fun String.getInstruction(): Pair<Int, Int> { val memoryAddress = this.split("=")[0].trim().removePrefix("mem[").removeSuffix("]").toInt() val value = this.split("=")[1].trim().toInt() return Pair(memoryAddress, value) }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
3,250
AdventOfCode
MIT License
2023/day04-25/src/main/kotlin/Day17.kt
CakeOrRiot
317,423,901
false
{"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417}
import java.io.File import java.util.PriorityQueue class Day17 { fun solve1() { val grid = File("inputs/17.txt").inputStream().bufferedReader().lineSequence() .map { it.map { x -> x.digitToInt() }.toList() }.toList() val res = dijkstra1(grid, Point(0, 0)) println(res.filter { it.key.point == Point(grid.size - 1, grid[0].size - 1) }.minOf { it.value }) } fun solve2() { val grid = File("inputs/17.txt").inputStream().bufferedReader().lineSequence() .map { it.map { x -> x.digitToInt() }.toList() }.toList() val res = dijkstra2(grid, Point(0, 0)) println(res.filter { it.key.point == Point(grid.size - 1, grid[0].size - 1) && it.key.sameDirectionCnt >= 4 } .minOf { it.value }) } data class Node(val point: Point, val direction: Point, val sameDirectionCnt: Int) data class Point(val x: Int, val y: Int) { operator fun plus(other: Point): Point { return Point(x + other.x, y + other.y) } } operator fun List<List<Int>>.get(p: Point): Int { return this[p.x][p.y] } fun dijkstra1(grid: List<List<Int>>, startPoint: Point): MutableMap<Node, Int> { val compareByWeight: Comparator<Pair<Int, Node>> = compareBy { it.first } val q = PriorityQueue(compareByWeight) val dist = emptyMap<Node, Int>().toMutableMap() val startRight = Node(startPoint, Point(0, 1), 0) val startDown = Node(startPoint, Point(1, 0), 0) dist[startRight] = 0 dist[startDown] = 0 q.add(Pair(0, startRight)) q.add(Pair(0, startDown)) while (!q.isEmpty()) { val cur = q.poll().second for (direction in listOf( cur.direction, Point( cur.direction.y, cur.direction.x ), Point(cur.direction.y * -1, cur.direction.x * -1) )) { val newPoint = cur.point + direction var directionCnt = 1 if (direction == cur.direction) { if (cur.sameDirectionCnt == 3) continue directionCnt = cur.sameDirectionCnt + 1 } if (!(newPoint.x >= 0 && newPoint.y >= 0 && newPoint.x < grid.size && newPoint.y < grid[0].size)) { continue } val node = Node(newPoint, direction, directionCnt) val curDistToNode = dist.getOrDefault(node, Int.MAX_VALUE) val updDistToNode = dist.getValue(cur) + grid[node.point] if (curDistToNode > updDistToNode) { q.add(Pair(updDistToNode, node)) dist[node] = updDistToNode } } } return dist } fun dijkstra2(grid: List<List<Int>>, startPoint: Point): MutableMap<Node, Int> { val compareByWeight: Comparator<Pair<Int, Node>> = compareBy { it.first } val q = PriorityQueue(compareByWeight) val dist = emptyMap<Node, Int>().toMutableMap() val startRight = Node(startPoint, Point(0, 1), 0) val startDown = Node(startPoint, Point(1, 0), 0) dist[startRight] = 0 dist[startDown] = 0 q.add(Pair(0, startRight)) q.add(Pair(0, startDown)) while (!q.isEmpty()) { val cur = q.poll().second val directions = emptyList<Point>().toMutableList() if (cur.sameDirectionCnt == 10) { directions.add(Point(cur.direction.y, cur.direction.x)) directions.add(Point(cur.direction.y * -1, cur.direction.x * -1)) } else if (cur.sameDirectionCnt < 4) { directions.add(cur.direction) } else { directions.add(cur.direction) directions.add(Point(cur.direction.y, cur.direction.x)) directions.add(Point(cur.direction.y * -1, cur.direction.x * -1)) } for (direction in directions) { val newPoint = cur.point + direction var directionCnt = 1 if (direction == cur.direction) { directionCnt = cur.sameDirectionCnt + 1 } if (!(newPoint.x >= 0 && newPoint.y >= 0 && newPoint.x < grid.size && newPoint.y < grid[0].size)) { continue } val node = Node(newPoint, direction, directionCnt) val curDistToNode = dist.getOrDefault(node, Int.MAX_VALUE) val updDistToNode = dist.getValue(cur) + grid[node.point] if (curDistToNode > updDistToNode) { q.add(Pair(updDistToNode, node)) dist[node] = updDistToNode } } } return dist } }
0
Kotlin
0
0
8fda713192b6278b69816cd413de062bb2d0e400
4,844
AdventOfCode
MIT License
src/Day11.kt
mihansweatpants
573,733,975
false
{"Kotlin": 31704}
import java.util.LinkedList fun main() { fun part1(monkeys: List<Monkey>): Long { repeat(20) { for (monkey in monkeys) { while (monkey.hasItems()) { val (item, throwTo) = monkey.inspectAndThrowAnItem() monkeys[throwTo].catchItem(item) } } } return monkeys .map { it.totalItemsInspected() } .sortedDescending() .take(2) .reduce(Long::times) } fun part2(monkeys: List<Monkey>): Long { val divisor = monkeys.map { it.worryLevelDivisor() }.reduce(Int::times) repeat(10_000) { for (monkey in monkeys) { while (monkey.hasItems()) { val (item, throwTo) = monkey.inspectAndThrowAnItem { it % divisor } monkeys[throwTo].catchItem(item) } } } return monkeys .map { it.totalItemsInspected() } .sortedDescending() .take(2) .reduce(Long::times) } val input = (readInput("Day11")) println(part1(parseInputMonkeys(input))) println(part2(parseInputMonkeys(input))) } private class Monkey( private val items: LinkedList<Long>, private val worryLevelFunction: (worryLevel: Long) -> Long, private val worryLevelDivisor: Int, private val throwStuffTo: Pair<Int, Int>, private var inspectedItemsCount: Long = 0 ) { fun hasItems(): Boolean = items.isNotEmpty() fun inspectAndThrowAnItem(calmDown: (worryLevel: Long) -> Long = { it / 3 }): Pair<Long, Int> { val oldWorryLevel = items.removeFirst() val newWorryLevel = calmDown(worryLevelFunction(oldWorryLevel)) inspectedItemsCount++ return if (newWorryLevel % worryLevelDivisor == 0L) { Pair(newWorryLevel, throwStuffTo.first) } else { Pair(newWorryLevel, throwStuffTo.second) } } fun catchItem(item: Long) { items.addLast(item) } fun totalItemsInspected(): Long = inspectedItemsCount fun worryLevelDivisor(): Int = worryLevelDivisor } private fun parseInputMonkeys(input: String): List<Monkey> { val monkeyConfigs = mutableListOf<MutableList<String>>() monkeyConfigs.add(mutableListOf()) for (line in input.lines()) { if (line.isBlank()) { monkeyConfigs.add(mutableListOf()) } else { monkeyConfigs.last().add(line) } } return monkeyConfigs.map { it.parseMonkey() } } private fun List<String>.parseMonkey(): Monkey { val (startingItems, operation, test, ifTrue, ifFalse) = this.drop(1) val items = LinkedList<Long>() startingItems .slice(startingItems.indexOf(":") + 2..startingItems.lastIndex) .split(",") .map { it.trim() } .filterNot { it.isBlank() } .mapTo(items) { it.toLong() } val (operator, argument) = operation.slice(operation.indexOf("old") + 4..operation.lastIndex) .split(" ") val worryLevelFunction = createWorryLevelFunction(operator, argument) val worryLevelDivisor = test.substring(test.lastIndexOf(" ") + 1).toInt() val leftMonkey = ifTrue.substring(ifTrue.lastIndexOf(" ") + 1).toInt() val rightMonkey = ifFalse.substring(ifFalse.lastIndexOf(" ") + 1).toInt() return Monkey( items, worryLevelFunction, worryLevelDivisor, leftMonkey to rightMonkey ) } private fun createWorryLevelFunction(operator: String, argument: String): (old: Long) -> Long { return { val arg = if (argument == "old") it else argument.toLong() when(operator) { "*" -> arg * it "+" -> arg + it else -> throw IllegalArgumentException("Unknown operator $operator") } } }
0
Kotlin
0
0
0de332053f6c8f44e94f857ba7fe2d7c5d0aae91
3,892
aoc-2022
Apache License 2.0
src/Day04.kt
gomercin
572,911,270
false
{"Kotlin": 25313}
/* * searches I needed to make: * kotlin tuple * */ fun main() { class Assignment(line: String) { var first: Pair<Int, Int> var second: Pair<Int, Int> init { val parts = line.split(",") val firstAsStr = parts[0].split("-") val secondAsStr = parts[1].split("-") first = Pair(firstAsStr[0].toInt(), firstAsStr[1].toInt()) second = Pair(secondAsStr[0].toInt(), secondAsStr[1].toInt()) } fun fullOverlap(): Boolean { // hehe, looks like using first and second as var names made things a bit weird // and repeating first this many times made me realize it is a weird word on its own return (first.first <= second.first && first.second >= second.second) || (first.first >= second.first && first.second <= second.second) } fun partialOverlap(): Boolean { return fullOverlap() || (first.first >= second.first && first.first <= second.second) || (first.second >= second.first && first.second <= second.second) } } fun part1(input: List<String>): Int { var numFullOverlap = 0 for (line in input) { val assignment = Assignment(line) if (assignment.fullOverlap()) { numFullOverlap++ } } return numFullOverlap } fun part2(input: List<String>): Int { var numPartialOverlap = 0 for (line in input) { val assignment = Assignment(line) if (assignment.partialOverlap()) { numPartialOverlap++ } } return numPartialOverlap } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
30f75c4103ab9e971c7c668f03f279f96dbd72ab
1,808
adventofcode-2022
Apache License 2.0
topsis-distance-ranking/src/main/kotlin/pl/poznan/put/topsis/DistanceRankingCalculator.kt
sbigaret
164,424,298
true
{"Kotlin": 93061, "R": 67629, "Shell": 24899, "Groovy": 24559}
package pl.poznan.put.topsis import pl.poznan.put.xmcda.ranking.RankEntry import pl.poznan.put.xmcda.ranking.Ranking import kotlin.math.pow import kotlin.math.sqrt class DistanceRankingCalculator( alternatives: List<TopsisAlternative>, criteria: List<Criterion>, private val idealAlternatives: IdealAlternatives ) : AlternativesCalculator<TopsisRanking>(alternatives, criteria) { override fun calculate(): TopsisRanking { val negIdealVector = idealAlternatives.negative.extractCriteriaValues() val posIdealVector = idealAlternatives.positive.extractCriteriaValues() val distanceToNeg = calculateDistanceToIdealSolution(negIdealVector) val distanceToPos = calculateDistanceToIdealSolution(posIdealVector) val coef = calculateClosenessCoefficient(distanceToPos, distanceToNeg) return TopsisRanking(alternatives, coef) } private fun calculateDistanceToIdealSolution(idealSol: DoubleArray): DoubleArray { val distanceToIdealSol = DoubleArray(alternativeNo) for (row in 0 until alternativeNo) { var temp = 0.0 for (col in 0 until criteriaNo) { temp += (decisionMatrix[row][col] - idealSol[col]).pow(2) } distanceToIdealSol[row] = sqrt(temp) } return distanceToIdealSol } private fun calculateClosenessCoefficient(distToPosIdealSol: DoubleArray, distToNegIdealSol: DoubleArray) = distToNegIdealSol .zip(distToPosIdealSol) .map { (neg, pos) -> neg / (neg + pos) } } data class TopsisRankEntry( override val alternative: TopsisAlternative, override val value: Double ) : RankEntry<TopsisAlternative> { override fun toString() = "${alternative.name} - $value" } class TopsisRanking private constructor( private val ranking: List<TopsisRankEntry> ) : Ranking<TopsisAlternative>, List<RankEntry<TopsisAlternative>> by ranking { constructor(alternatives: List<TopsisAlternative>, coef: List<Double>) : this( alternatives.zip(coef) .asSequence() .sortedByDescending { it.second } .map { TopsisRankEntry(it.first, it.second) } .toList() ) }
0
Kotlin
0
0
96c182d7e37b41207dc2da6eac9f9b82bd62d6d7
2,301
DecisionDeck
MIT License
src/main/kotlin/cloud/dqn/leetcode/FourSum2Kt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/4sum-ii/description/ Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -2^28 to 2^28 - 1 and the result is guaranteed to be at most 2^31 - 1. Example: Input: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2] Output: 2 Explanation: The two tuples are: 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 */ class FourSum2Kt { companion object { val MAX_VALUE = Math.pow(2.0, 28.0).toInt() val MIN_VALUE = (MAX_VALUE * -1) -1 } class Solution { fun fourSumCount(A: IntArray, B: IntArray, C: IntArray, D: IntArray): Int { var count = 0 val diffAB = HashMap<Int, Int>(A.size * B.size) A.forEach { aValue -> B.forEach { bValue -> val diff = 0 - (aValue + bValue) diffAB[diff] = (diffAB[diff] ?: 0) + 1 } } C.forEach { cValue -> D.forEach { dValue -> diffAB[cValue + dValue]?.let { count += it } } } return count } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
1,514
cloud-dqn-leetcode
No Limit Public License
src/day_03/Day03.kt
the-mgi
573,126,158
false
{"Kotlin": 5720}
package day_03 import readInput import java.io.File import java.util.* fun main() { fun getPriority(character: Char) = if (character.isLowerCase()) (character.code - 97) % 26 + 1 else (character.code - 65) % 26 + 1 + 26 fun characterTransform(character: Char, map: MutableMap<Char, Int>) { map.also { hashMap -> hashMap[character] = getPriority(character) } } fun questionOne(): Int { return readInput("day_03/input").map { val mid = it.length / 2 val firstPartMap = mutableMapOf<Char, Int>() val secondPartMap = mutableMapOf<Char, Int>() it.subSequence(0, mid).forEach { character -> characterTransform(character, firstPartMap) } it.subSequence(mid, it.length).forEach { character -> characterTransform(character, secondPartMap) } val commonKey = firstPartMap.keys.find { mapKey -> secondPartMap.containsKey(mapKey) } if (commonKey != null) return@map firstPartMap[commonKey]!! else return@map 0 }.sum() } fun questionTwo(): Int { val scanner = Scanner(File("/media/themgi/Local Disk/aoc-2022-kotlin/src/day_03/input.txt")) var indexGroupCount = 0 val inputList = ArrayList<String>() while (scanner.hasNextLine()) { if (indexGroupCount != 0 && indexGroupCount % 3 != 0) { inputList[inputList.size - 1] = "${inputList.last()};${scanner.nextLine()}" } else { inputList.add(scanner.nextLine()) } indexGroupCount += 1 } return inputList.map { val (first, second, third) = it.split(";").map { singleString -> val map = mutableMapOf<Char, Int>() singleString.forEach { character -> characterTransform(character, map) } map } val commonKey = first.keys.find { mapKey -> second.containsKey(mapKey) && third.containsKey(mapKey) } if (commonKey != null) return@map first[commonKey]!! else return@map 0 }.sum() } println("Question 01: ${questionOne()}") println("Question 02: ${questionTwo()}") }
0
Kotlin
0
0
c7f9e9727ccdef9231f0cf125e678902e2d270f7
2,200
aoc-2022-kotlin
Apache License 2.0
17/part_one.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File fun readInput() : Target { val input = File("input.txt") .readText() val xRegex = """x=(-?\d+)..(-?\d+)""".toRegex() val yRegex = """y=(-?\d+)..(-?\d+)""".toRegex() val (miniX, maxiX) = xRegex.find(input)?.destructured!! val (miniY, maxiY) = yRegex.find(input)?.destructured!! return Target(miniX.toInt(), maxiX.toInt(), miniY.toInt(), maxiY.toInt()) } class Target(private val miniX: Int, private val maxiX : Int, private val miniY : Int, private val maxiY : Int) { fun calcMaxYWithHit() : Int { var result = 0 for (initialVx in 1..maxiX) { for (initialVy in 0..10 * (maxiY - miniY)) { // heuristic initialVy values result = maxOf(result, maxHeightIfHit(initialVx, initialVy)) } } return result } private fun maxHeightIfHit(initialVx : Int, initialVy : Int) : Int { var vx = initialVx var vy = initialVy var curX = 0 var curY = 0 var result = 0 var throwMaxY = 0 while(curY >= miniY) { curX += vx curY += vy throwMaxY = maxOf(throwMaxY, curY) vx = maxOf(0, vx - 1) vy -= 1 if (isHit(curX, curY)) { result = maxOf(result, throwMaxY) } } return result } private fun isHit(curX : Int, curY : Int) : Boolean { return curX in miniX..maxiX && curY in miniY..maxiY } } fun solve(target : Target) : Int { return target.calcMaxYWithHit() } fun main() { val target = readInput() val ans = solve(target) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
1,682
advent-of-code-2021
MIT License
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day03.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part3A : PartSolution() { lateinit var lines: List<String> override fun parseInput(text: String) { lines = text.trimEnd().split("\n") } override fun compute(): Int { val mostCommon = getMostCommon(lines) val gamma = binToDec(mostCommon) val epsilon = binToDec(invertBits(mostCommon)) return gamma * epsilon } fun getMostCommon(data: List<String>): String { val oneBits = getOneBits(data) val num = data.size var mostCommon = "" for (i in oneBits.indices) { val zeroBits = num - oneBits[i] mostCommon += if (oneBits[i] > zeroBits) { '1' } else if (oneBits[i] < zeroBits) { '0' } else { '1' } } return mostCommon } private fun getOneBits(data: List<String>): List<Int> { val numBits = data.first().length val oneBits = MutableList(numBits) { 0 } for (number in data) { for (i in number.indices) { if (number[i] == '1') { oneBits[i] += 1 } } } return oneBits } fun binToDec(number: String): Int { return number.toInt(2) } private fun invertBits(number: String): String { return number.map { if (it == '1') '0' else '1' }.joinToString(separator = "") } override fun getExampleAnswer(): Int { return 198 } } class Part3B : Part3A() { override fun compute(): Int { val oxygenStr = getOxygen() val oxygen = binToDec(oxygenStr) val co2Str = getCo2() val co2 = binToDec(co2Str) return oxygen * co2 } private fun getOxygen(): String { var data = lines.toList() for (i in data.first().indices) { data = getMostCommonNumbers(data, i) } return data.first() } private fun getMostCommonNumbers(data: List<String>, i: Int): List<String> { val mostCommon = getMostCommon(data) return data.filter { it[i] == mostCommon[i] } } private fun getCo2(): String { var data = lines.toList() for (i in data.first().indices) { data = getLeastCommonNumbers(data, i) if (data.size == 1) { break } } return data.first() } private fun getLeastCommonNumbers(data: List<String>, i: Int): List<String> { val mostCommon = getMostCommon(data) return data.filter { it[i] != mostCommon[i] } } override fun getExampleAnswer(): Int { return 230 } } fun main() { Day(2021, 3, Part3A(), Part3B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
2,857
advent-of-code-kotlin
MIT License
src/Day02.kt
skarlman
572,692,411
false
{"Kotlin": 4076}
import java.io.File // Problem: // https://adventofcode.com/2022/day/2 // More solutions: // https://www.competitivecoders.com/ProgrammingCompetitions/advent-of-code/advent-of-code/2022/day-2/ fun main() { fun part1(input: List<String>): Int { val scores = mapOf( Pair("A", "X") to 1 + 3, Pair("A", "Y") to 2 + 6, Pair("A", "Z") to 3 + 0, Pair("B", "X") to 1 + 0, Pair("B", "Y") to 2 + 3, Pair("B", "Z") to 3 + 6, Pair("C", "X") to 1 + 6, Pair("C", "Y") to 2 + 0, Pair("C", "Z") to 3 + 3, ) return input.map { row -> row.split(" ") .let { scores.getValue(Pair(it[0], it[1])) } }.sum() } fun part2(input: List<String>): Int { val scores = mapOf( Pair("A", "X") to 3 + 0, Pair("A", "Y") to 1 + 3, Pair("A", "Z") to 2 + 6, Pair("B", "X") to 1 + 0, Pair("B", "Y") to 2 + 3, Pair("B", "Z") to 3 + 6, Pair("C", "X") to 2 + 0, Pair("C", "Y") to 3 + 3, Pair("C", "Z") to 1 + 6, ) return input.map { row -> row.split(" ") .let { scores.getValue(Pair(it[0], it[1])) } }.sum() } val input = readInput("Day02") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun readInput(name: String) = File("src", "$name.txt") .readLines()
0
Kotlin
0
0
ef15752cfa6878ce2740a86c48b47597b8d5cabc
1,653
AdventOfCode2022_kotlin
Apache License 2.0
src/Day01.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
import java.util.regex.Pattern fun main() { fun part1(input: List<String>): Int { return input.sumOf { it.replace("\\D".toRegex(), "").let { "${it.first()}${it.last()}".toInt() } } } fun replaceNumber(r:String): String { return when (r) { "one" -> "1" "two" -> "2" "three" -> "3" "four" -> "4" "five" -> "5" "six" -> "6" "seven" -> "7" "eight" -> "8" "nine" -> "9" else -> r } } fun findFirstAndLast(inputString: String): Int { val regex = "(?=(one|two|three|four|five|six|seven|eight|nine|\\d))" val pattern = Pattern.compile(regex) val matcher = pattern.matcher(inputString) val found = mutableListOf<String>() while (matcher.find()) { found.add(matcher.group(1)) } val first = replaceNumber(found.first()).toInt() val last = replaceNumber(found.last()).toInt() return first * 10 + last } fun part2(input: List<String>): Int { return input.sumOf {orig -> findFirstAndLast(orig).also { println("$orig: $it") } } } val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
1,375
aoc-2023
Apache License 2.0
2022/src/main/kotlin/Day11.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import Day11.Operand.Value object Day11 { fun part1(input: String): Long { val monkeys = parseMonkeys(input) repeat(20) { simulateRound(monkeys) { it / 3L } } return calculateMonkeyBusiness(monkeys) } fun part2(input: String): Long { val monkeys = parseMonkeys(input) val divisorProduct = monkeys.map { it.divisor }.fold(1L, Long::times) repeat(10_000) { simulateRound(monkeys) { it % divisorProduct } } return calculateMonkeyBusiness(monkeys) } private fun simulateRound(monkeys: List<Monkey>, worryReducer: (Long) -> Long) { monkeys.forEach { monkey -> while (monkey.items.isNotEmpty()) { val itemWorryLevel = monkey.items.removeFirst() val newWorryLevel = worryReducer(monkey.worry(itemWorryLevel)) val passTo = monkey.test(newWorryLevel) monkeys[passTo].items.add(newWorryLevel) monkey.numItemsInspected++ } } } private fun calculateMonkeyBusiness(monkeys: List<Monkey>): Long { return monkeys .map { it.numItemsInspected } .sortedDescending() .take(2) .fold(1L, Long::times) } private fun parseMonkeys(input: String): List<Monkey> { return input.split("\n\n") .map { monkeyDefinition -> val monkeyLines = monkeyDefinition.splitNewlines() val operationSplit = monkeyLines[2].drop(19).splitWhitespace() return@map Monkey( items = monkeyLines[1].drop(18).splitCommas().map { it.trim().toLong() }.toMutableList(), function = if (operationSplit[1] == "+") Long::plus else Long::times, operand = operationSplit[2].parseOperand(), divisor = monkeyLines[3].drop(21).toLong(), ifTrue = monkeyLines[4].drop(29).toInt(), ifFalse = monkeyLines[5].drop(30).toInt() ) } } private fun String.parseOperand() = if (this == "old") Operand.Old else Value(this.toLong()) private data class Monkey( var items: MutableList<Long>, val function: (Long, Long) -> Long, val operand: Operand, val divisor: Long, val ifTrue: Int, val ifFalse: Int, ) { var numItemsInspected: Long = 0 fun worry(old: Long) = function(old, if (operand is Value) operand.value else old) fun test(item: Long) = if (item % divisor == 0L) ifTrue else ifFalse } private sealed class Operand { data class Value(val value: Long) : Operand() object Old : Operand() } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
2,451
advent-of-code
MIT License
src/day03/Day03.kt
taer
573,051,280
false
{"Kotlin": 26121}
package day03 import readInput fun main() { val codeOfA = 'a'.code fun Set<Char>.priorityValue(): Int { val dupeChar = this.single() val upperCase = if (dupeChar.isUpperCase()) 26 else 0 return dupeChar.lowercaseChar().code - codeOfA + upperCase + 1 } fun part1(input: List<String>): Int { return input.asSequence() .map { val middle = it.length / 2 it.substring(0, middle).toSet() to it.substring(middle).toSet() }.map { it.first.intersect(it.second) }.map { it.priorityValue() }.sum() } fun part2(input: List<String>): Int { return input.asSequence() .map { it.toSet() } .chunked(3) .map { it.reduce { acc, chars -> acc.intersect(chars) } }.map { it.priorityValue() } .sum() } val testInput = readInput("day03", true) val input = readInput("day03") check(part1(testInput) == 157) println(part1(input)) check(part2(testInput) == 70) println(part2(input)) }
0
Kotlin
0
0
1bd19df8949d4a56b881af28af21a2b35d800b22
1,183
aoc2022
Apache License 2.0
src/main/kotlin/g2301_2400/s2333_minimum_sum_of_squared_difference/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2333_minimum_sum_of_squared_difference // #Medium #Array #Math #Sorting #Heap_Priority_Queue // #2023_07_01_Time_502_ms_(100.00%)_Space_50.6_MB_(100.00%) import kotlin.math.abs import kotlin.math.pow class Solution { fun minSumSquareDiff(nums1: IntArray, nums2: IntArray, k1: Int, k2: Int): Long { var minSumSquare: Long = 0 val diffs = IntArray(100001) var totalDiff: Long = 0 var kSum = k1.toLong() + k2 var currentDiff: Int var maxDiff = 0 for (i in nums1.indices) { // get current diff. currentDiff = abs(nums1[i] - nums2[i]) // if current diff > 0, count/store it. If not,then ignore it. if (currentDiff > 0) { totalDiff += currentDiff.toLong() diffs[currentDiff]++ maxDiff = maxDiff.coerceAtLeast(currentDiff) } } // if kSum (k1 + k2) < totalDifferences, it means we can make all numbers/differences 0s if (totalDiff <= kSum) { return 0 } // starting from the back, from the highest difference, lower that group one by one to the // previous group. // we need to make all n diffs to n-1, then n-2, as long as kSum allows it. run { var i = maxDiff while (i > 0 && kSum > 0) { if (diffs[i] > 0) { // if current group has more differences than the totalK, we can only move k of them // to the lower level. if (diffs[i] >= kSum) { diffs[i] -= kSum.toInt() diffs[i - 1] += kSum.toInt() kSum = 0 } else { // else, we can make this whole group one level lower. diffs[i - 1] += diffs[i] kSum -= diffs[i].toLong() diffs[i] = 0 } } i-- } } for (i in 0..maxDiff) { if (diffs[i] > 0) { minSumSquare += i.toDouble().pow(2.0).toLong() * diffs[i] } } return minSumSquare } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,261
LeetCode-in-Kotlin
MIT License
src/Day01.kt
WaatzeG
573,594,703
false
{"Kotlin": 7476}
fun main() { /** * Return sum of top elf */ fun part1(input: List<String>): Int { return split(input) .maxOf { it.sumOf(String::toInt) } } /** * Return sum of top 3 elves */ fun part2(input: List<String>): Int { return split(input) .map { it.sumOf(String::toInt) } .sortedByDescending { it } .take(3) .sum() } val testInput = readInput("Day01_input") val solutionPart1 = part1(testInput) println("Solution part 1: $solutionPart1") val solutionPart2 = part2(testInput) println("Solution part 2: $solutionPart2") } /** * Split a list of strings into a sequence of lists by using an empty string as the separator. */ fun split(input: List<String>): Sequence<List<String>> { return sequence { var index = 0 do { val subList = mutableListOf<String>() do { val string = input[index] if (string != "") { subList.add(string) } index++ } while (string != "" && index < input.size) yield(subList) } while (index < input.size) } }
0
Kotlin
0
0
324a98c51580b86121b6962651f1ba9eaad8f468
1,231
advent_of_code_2022_kotlin
Apache License 2.0
src/Day03.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
fun change(symbol: Char) = if (symbol.isUpperCase()) symbol.lowercase().first().code - 70 else symbol.uppercase().first().code - 64 fun main() { fun part1(input: List<String>): Int { return input.sumOf { val strings = it.chunked(it.length / 2) val set = strings[0] val element = strings[1].first { symbol -> set.contains(symbol) } change(element) } } fun part2(input: List<String>): Int { val sets = input.map { it.toSet() } var sum = 0 for (i in input.indices step 3) { val element = sets[i].intersect(sets[i + 1].intersect(sets[i + 2])).first() sum += change(element) } return sum } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
825
Advent-of-code
Apache License 2.0
src/day01/Day01.kt
violabs
576,367,139
false
{"Kotlin": 10620}
package day01 import readInput fun main() { test1("day-01-test-input-01", 24000) test2("day-01-test-input-01", 45000) } private fun test1(filename: String, expected: Int) { val input = readInput("day01/$filename") val actual: Int = findHighestCalorieSet(input) println("EXPECT: $expected") println("ACTUAL: $actual") check(expected == actual) } private fun test2(filename: String, expected: Int) { val input = readInput("day01/$filename") val actual: Int = findTop3HighestCalorieSets(input) println("EXPECT: $expected") println("ACTUAL: $actual") check(expected == actual) } const val E = "" private fun findHighestCalorieSet(input: List<String>): Int { val tracker = ElfCalorieTracker() processInput(tracker, input) return tracker.sumOfCalorieAmounts(1) } private fun findTop3HighestCalorieSets(input: List<String>): Int { val tracker = ElfCalorieTracker() processInput(tracker, input) return tracker.sumOfCalorieAmounts(3) } private fun processInput(tracker: ElfCalorieTracker, input: List<String>) { for (calories in input) { if (calories == E) { tracker.moveToNextElf() continue } tracker.addCaloriesToSum(calories) } } class ElfCalorieTracker( var currentSum: Int = 0, var caloriesList: MutableList<Int> = mutableListOf() ) { fun moveToNextElf() { caloriesList.add(currentSum) currentSum = 0 } fun addCaloriesToSum(calories: String) { currentSum += calories.toInt() } fun sumOfCalorieAmounts(takeAmount: Int): Int = caloriesList .also { it.add(currentSum) } .sortedDescending() .take(takeAmount) .sum() }
0
Kotlin
0
0
be3d6bb2aef1ebd44bbd8e62d3194c608a5b3cc1
1,770
AOC-2022
Apache License 2.0
src/day02/Day02.kt
benjaminknauer
574,102,077
false
{"Kotlin": 6414}
package day02 import java.io.File import java.lang.IllegalArgumentException enum class Move(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun fromShortcode(shortcode: String): Move { return when (shortcode) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> throw IllegalArgumentException("Ungültiger Code %s".format(shortcode)) } } } } enum class RoundOutcome(val score: Int) { WIN(6), DRAW(3), LOOSE(0); companion object { fun fromShortcode(shortcode: String): RoundOutcome { return when (shortcode) { "X" -> LOOSE "Y" -> DRAW "Z" -> WIN else -> throw IllegalArgumentException("Ungültiger Code %s".format(shortcode)) } } } } class Game(private val gameRounds: List<GameRound>) { fun getScore(): Int { return gameRounds.sumOf { it.getScore() } } } class GameRound(private val yourMove: Move, private val opponentMove: Move) { constructor(opponentMove: Move, expectedOutcome: RoundOutcome) : this( calculateYourOption( opponentMove, expectedOutcome ), opponentMove ) fun getScore(): Int { return calculateOutcome().score + yourMove.score } companion object { fun calculateYourOption(opponentMove: Move, expectedOutcome: RoundOutcome): Move { return when (expectedOutcome) { RoundOutcome.WIN -> { when (opponentMove) { Move.ROCK -> Move.PAPER Move.PAPER -> Move.SCISSORS Move.SCISSORS -> Move.ROCK } } RoundOutcome.DRAW -> opponentMove RoundOutcome.LOOSE -> { when (opponentMove) { Move.ROCK -> Move.SCISSORS Move.PAPER -> Move.ROCK Move.SCISSORS -> Move.PAPER } } } } } private fun calculateOutcome(): RoundOutcome { return when (yourMove) { Move.ROCK -> { when (opponentMove) { Move.ROCK -> RoundOutcome.DRAW Move.PAPER -> RoundOutcome.LOOSE Move.SCISSORS -> RoundOutcome.WIN } } Move.PAPER -> { when (opponentMove) { Move.ROCK -> RoundOutcome.WIN Move.PAPER -> RoundOutcome.DRAW Move.SCISSORS -> RoundOutcome.LOOSE } } Move.SCISSORS -> { when (opponentMove) { Move.ROCK -> RoundOutcome.LOOSE Move.PAPER -> RoundOutcome.WIN Move.SCISSORS -> RoundOutcome.DRAW } } } } } fun parseInputPart1(input: String): Game { val gameRounds = input.split("\n") .map { gameround: String -> val selectedOptions = gameround.split(" ") val opponentMove = Move.fromShortcode(selectedOptions[0]) val yourMove = Move.fromShortcode(selectedOptions[1]) return@map GameRound(yourMove, opponentMove) } return Game(gameRounds) } fun parseInputPart2(input: String): Game { val gameRounds = input.split("\n") .map { gameround: String -> val shortcodes = gameround.split(" ") val opponentMove = Move.fromShortcode(shortcodes[0]) val expectedOutcome = RoundOutcome.fromShortcode(shortcodes[1]) return@map GameRound(opponentMove, expectedOutcome) } return Game(gameRounds) } fun part1(input: String): Int { val game = parseInputPart1(input) return game.getScore() } fun part2(input: String): Int { val game = parseInputPart2(input) return game.getScore() } fun main() { // test if implementation meets criteria from the description, like: val testInput = File("src/day02/Day02_test.txt").readText() check(part1(testInput) == 15) check(part2(testInput) == 12) val input = File("src/day02/Day02.txt").readText() println("Result Part 1: %s".format(part1(input))) println("Result Part 2: %s".format(part2(input))) }
0
Kotlin
0
0
fcf41bed56884d777ff1f95eddbecc5d8ef731d1
4,466
advent-of-code-22-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortIntegersByThePowerValue.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.PriorityQueue /** * 1387. Sort Integers by The Power Value * @see <a href="https://leetcode.com/problems/sort-integers-by-the-power-value/">Source</a> */ fun interface SortIntegersByThePowerValue { fun getKth(lo: Int, hi: Int, k: Int): Int } class SortIntegersByThePowerValueDP : SortIntegersByThePowerValue { private val map: MutableMap<Int, Int> = HashMap() override fun getKth(lo: Int, hi: Int, k: Int): Int { val queue: PriorityQueue<IntArray> = PriorityQueue label@{ a, b -> if (a[1] != b[1]) { return@label b[1] - a[1] } b[0] - a[0] } for (i in lo..hi) { queue.add(intArrayOf(i, solve(i))) if (queue.size > k) { queue.remove() } } return queue.poll()[0] } private fun solve(x: Int): Int { if (x == 1) { return 0 } if (map.containsKey(x)) { return map[x] ?: 0 } val res = (if (x % 2 == 0) solve(x / 2) else solve(x * 3 + 1)) + 1 map[x] = res return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,777
kotlab
Apache License 2.0
src/main/kotlin/g2401_2500/s2458_height_of_binary_tree_after_subtree_removal_queries/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2458_height_of_binary_tree_after_subtree_removal_queries // #Hard #Array #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_07_05_Time_951_ms_(80.00%)_Space_118.6_MB_(80.00%) import com_github_leetcode.TreeNode class Solution { fun treeQueries(root: TreeNode?, queries: IntArray): IntArray { val levels: MutableMap<Int, IntArray> = HashMap() val map: MutableMap<Int, IntArray> = HashMap() val max = dfs(root, 0, map, levels) - 1 val n = queries.size for (i in 0 until n) { val q = queries[i] val node = map[q] val height = node!![0] val level = node[1] val lev = levels[level] if (lev!![0] == height) { if (lev[1] != -1) { queries[i] = max - Math.abs(lev[0] - lev[1]) } else { queries[i] = max - height - 1 } } else { queries[i] = max } } return queries } private fun dfs( root: TreeNode?, level: Int, map: MutableMap<Int, IntArray>, levels: MutableMap<Int, IntArray> ): Int { if (root == null) { return 0 } val left = dfs(root.left, level + 1, map, levels) val right = dfs(root.right, level + 1, map, levels) val height = Math.max(left, right) val lev = levels.getOrDefault(level, intArrayOf(-1, -1)) if (height >= lev[0]) { lev[1] = lev[0] lev[0] = height } else { lev[1] = Math.max(lev[1], height) } levels[level] = lev map[root.`val`] = intArrayOf(height, level) return Math.max(left, right) + 1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,799
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-22.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.Coord3D import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import kotlin.math.max import kotlin.math.min fun main() { val input = readInputLines(2021, "22-input") val test1 = readInputLines(2021, "22-test1") val test2 = readInputLines(2021, "22-test2") println("Part1:") part1(test1).println() part1(test2).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(test2).println() part2(input).println() } private fun part1(input: List<String>): Int { val ops = input.map { val (op, x1, x2, y1, y2, z1, z2) = regex.matchEntire(it)!!.destructured val cuboid = Cuboid(Coord3D(x1.toInt(), y1.toInt(), z1.toInt()), Coord3D(x2.toInt(), y2.toInt(), z2.toInt())) Operation(op == "on", cuboid) } val cubes = mutableMapOf<Coord3D, Boolean>().withDefault { false } ops.forEach { for (x in it.cuboid.start.x.coerceAtLeast(-50) .. it.cuboid.end.x.coerceAtMost(50)) { for (y in it.cuboid.start.y.coerceAtLeast(-50) .. it.cuboid.end.y.coerceAtMost(50)) { for (z in it.cuboid.start.z.coerceAtLeast(-50) .. it.cuboid.end.z.coerceAtMost(50)) { val cube = Coord3D(x, y, z) cubes[cube] = it.turnOn } } } } return cubes.count { it.value } } private fun part2(input: List<String>): Long { val ops = input.map { val (op, x1, x2, y1, y2, z1, z2) = regex.matchEntire(it)!!.destructured val cuboid = Cuboid(Coord3D(x1.toInt(), y1.toInt(), z1.toInt()), Coord3D(x2.toInt(), y2.toInt(), z2.toInt())) Operation(op == "on", cuboid) } val cuboidsOn = mutableSetOf<Cuboid>() val queue = ArrayDeque<Cuboid>() ops.forEach { op -> queue += op.cuboid while (queue.isNotEmpty()) { val current = queue.removeFirst() var didIntersect = false for (c in cuboidsOn) { if (!current.intersects(c)) continue didIntersect = true val (inter, first, second) = current.intersect(c) cuboidsOn.remove(c) if (op.turnOn) { cuboidsOn += inter } cuboidsOn += second queue += first break } if (!didIntersect && op.turnOn) cuboidsOn += current } } return cuboidsOn.sumOf { it.size() } } private data class Cuboid(val start: Coord3D, val end: Coord3D) private fun Cuboid.size(): Long = xRange.count().toLong() * yRange.count() * zRange.count() private val Cuboid.xRange get() = start.x..end.x private val Cuboid.yRange get() = start.y..end.y private val Cuboid.zRange get() = start.z..end.z private data class IntersectionResult(val intersect: Cuboid, val fromFirst: List<Cuboid>, val fromSecond: List<Cuboid>) private fun Cuboid.intersects(other: Cuboid): Boolean { val startX = max(start.x, other.start.x) val startY = max(start.y, other.start.y) val startZ = max(start.z, other.start.z) val endX = min(end.x, other.end.x) val endY = min(end.y, other.end.y) val endZ = min(end.z, other.end.z) return startX <= endX && startY <= endY && startZ <= endZ } private fun Cuboid.intersect(other: Cuboid): IntersectionResult { val c1 = Coord3D(max(start.x, other.start.x), max(start.y, other.start.y), max(start.z, other.start.z)) val c2 = Coord3D(min(end.x, other.end.x), min(end.y, other.end.y), min(end.z, other.end.z)) val intersect = Cuboid(c1, c2) val first = this - intersect val second = other - intersect return IntersectionResult(intersect, first, second) } private operator fun Cuboid.minus(other: Cuboid): List<Cuboid> { return listOf( Cuboid( Coord3D(start.x, start.y, start.z), Coord3D(other.start.x - 1, end.y, end.z), ), Cuboid( Coord3D(other.start.x, start.y, start.z), Coord3D(other.end.x, end.y, other.start.z - 1), ), Cuboid( Coord3D(other.start.x, start.y, other.start.z), Coord3D(other.end.x, other.start.y - 1, other.end.z), ), Cuboid( Coord3D(other.start.x, other.end.y + 1, other.start.z), Coord3D(other.end.x, end.y, other.end.z), ), Cuboid( Coord3D(other.start.x, start.y, other.end.z + 1), Coord3D(other.end.x, end.y, end.z), ), Cuboid( Coord3D(other.end.x + 1, start.y, start.z), Coord3D(end.x, end.y, end.z), ) ).filter { it.size() != 0L } } private data class Operation(val turnOn: Boolean, val cuboid: Cuboid) private val regex = """(on|off) x=(-?\d+)..(-?\d+),y=(-?\d+)..(-?\d+),z=(-?\d+)..(-?\d+)""".toRegex()
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
4,987
advent-of-code
MIT License
src/day11/Day11.kt
tobihein
569,448,315
false
{"Kotlin": 58721}
package day11 import readInput class Day11 { fun part1(): Long { val readInput = readInput("day11/input") return part1(readInput) } fun part2(): Long { val readInput = readInput("day11/input") return part2(readInput) } fun part1(input: List<String>): Long { val monkeys = input.chunked(7).map { toMonkey(it) } letMonkeysWork(monkeys, 20) { it.floorDiv(3) } println(monkeys.map { it.getThrownItems() }) return monkeys.map { it.getThrownItems() }.sortedDescending().take(2).reduce { acc, next -> acc * next } } fun part2(input: List<String>): Long { val monkeys = input.chunked(7).map { toMonkey(it) } val lcm = monkeys.map { it.getDivisibleBy() }.fold(1L) { acc, divisibleBy -> acc * divisibleBy } letMonkeysWork(monkeys, 10000) { it.mod(lcm) } return monkeys.map { it.getThrownItems() }.sortedDescending().take(2).reduce { acc, next -> acc * next } } private fun toMonkey(input: List<String>): Monkey { val monkey = Monkey() for ((index, line) in input.withIndex()) { if (index == 0) { monkey.setId(line) } if (index == 1) { monkey.addItems(line) } if (index == 2) { monkey.setOperation(line) } if (index == 3) { monkey.setDivideBy(line) } if (index == 4) { monkey.setThrowToIfTrue(line) } if (index == 5) { monkey.setThrowToIfFalse(line) } } return monkey } private fun letMonkeysWork(monkeys: List<Monkey>, times: Int, post: (Long) -> Long) { for (i in 0 until times) { monkeys.forEach { monkey -> val throwItemsTo = monkey.throwItemsTo(post) throwItemsTo.forEach { throwTo -> monkeys[throwTo.first].addItem(throwTo.second) } } } } }
0
Kotlin
0
0
af8d851702e633eb8ff4020011f762156bfc136b
2,067
adventofcode-2022
Apache License 2.0
src/main/kotlin/org/sjoblomj/adventofcode/day9/Day9.kt
sjoblomj
161,537,410
false
null
package org.sjoblomj.adventofcode.day9 import org.sjoblomj.adventofcode.readFile import kotlin.system.measureTimeMillis private const val inputFile = "src/main/resources/inputs/day9.txt" private const val marbleThatAddsToScore = 23 private const val positionThatGetsAdded = -7 private const val positionToPlaceAt = 1 fun day9() { println("== DAY 9 ==") val timeTaken = measureTimeMillis { calculateAndPrintDay9() } println("Finished Day 9 in $timeTaken ms\n") } private fun calculateAndPrintDay9() { val (numberOfPlayers, numberOfMarbles) = parseIndata(readFile(inputFile)[0]) val players0 = (1 .. numberOfPlayers).map { Player(it, 0) } playGame(players0, numberOfMarbles) println("The highest score was ${calculateHighestScore(players0)}") val players1 = (1 .. numberOfPlayers).map { Player(it, 0) } playGame(players1, numberOfMarbles * 100) println("Playing with a hundred times more marbles, the highest score is ${calculateHighestScore(players1)}") } private fun parseIndata(indata: String): Pair<Int, Int> { fun parse(group: String) = "(?<players>[0-9]*) players; last marble is worth (?<points>[0-9]*) points".toRegex() .matchEntire(indata) ?.groups ?.get(group) ?.value ?: throw IllegalArgumentException("Can't find $group in input '$indata'") return parse("players").toInt() to parse("points").toInt() } internal fun calculateHighestScore(players: List<Player>) = players.map { it.score }.max() internal fun playGame(players: List<Player>, numberOfMarbles: Int): Turn { val turn = Turn(0) for (currentMarble in 1 .. numberOfMarbles) { val player = players[(currentMarble - 1) % players.size] performTurn(currentMarble, turn, player) } return turn } internal fun performTurn(currentMarble: Marble, turn: Turn, player: Player) { if (currentMarble % marbleThatAddsToScore == 0) { val removedMarble = turn.remove(positionThatGetsAdded) player.score += removedMarble + currentMarble } else turn.add(currentMarble, positionToPlaceAt) } internal data class Player(val id: Int, var score: Long) typealias Marble = Int
0
Kotlin
0
0
80db7e7029dace244a05f7e6327accb212d369cc
2,114
adventofcode2018
MIT License
src/chapter1/section4/PermutationAndCombination.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter1.section4 /** * 计算从total数量数据中取select个数据的排列数 * 从n个数中取m个数排列的公式为 P(n,m)=n*(n-1)*(n-2)*...*(n-m+1)=n!/(n-m)! (规定0!=1) * n个数的全排列公式(m=n) P(n)=n*(n-1)*(n-2)*...*1=n! */ fun permutation(total: Int, select: Int): Long { require(select in 0..total) var count = 1L repeat(select) { count *= total - it } return count } /** * 计算从total数量数据中取select个数据的组合数 * 从n个数中取m个数组合的公式为 C(n,m)=P(n,m)/m! */ fun combination(total: Int, select: Int): Long { require(select in 0..total) return permutation(total, select) / factorial(select) } /** * 计算n的阶乘 */ fun factorial(n: Int): Long { require(n >= 0) return permutation(n, n) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
824
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/day04/Problem.kt
xfornesa
572,983,494
false
{"Kotlin": 18402}
package day04 fun solveProblem01(input: List<String>): Long { return input.stream() .map { it.split(",") } .map { val (left, right) = it val (left_l, left_h) = left.split("-").map { it.toInt() } val (right_l, right_h) = right.split("-").map { it.toInt() } left_l <= right_l && right_h <= left_h || right_l <= left_l && left_h <= right_h } .filter { it } .count() } fun solveProblem02(input: List<String>): Long { return input.stream() .map { it.split(",") } .map { val (left, right) = it val (left_l, left_h) = left.split("-").map { it.toInt() } val (right_l, right_h) = right.split("-").map { it.toInt() } right_l in left_l..left_h || right_h in left_l..left_h || left_l in right_l..right_h || left_h in right_l..right_h } .filter { it } .count() }
0
Kotlin
0
0
dc142923f8f5bc739564bc93b432616608a8b7cd
996
aoc2022
MIT License
src/main/kotlin/mirecxp/aoc23/day03/Day03.kt
MirecXP
726,044,224
false
{"Kotlin": 42343}
package mirecxp.aoc23.day03 import java.io.File //https://adventofcode.com/2023/day/3 class Day03(inputPath: String) { private val lines: List<String> = File(inputPath).readLines() data class Coord(val r: Int, val c: Int) data class Gear(val coord: Coord, val parts: MutableList<Long>) fun solve() { println("Solving day 3 for ${lines.size} lines") var sum = 0L var gears = mutableMapOf<Coord, Gear>() lines.forEachIndexed { row: Int, line: String -> var partNumberStr = "" var adjacentCoords = mutableListOf<Coord>() line.forEachIndexed { col: Int, c: Char -> if (c.isDigit()) { if (partNumberStr.isEmpty()) { //first num digit, check coordinates to the left adjacentCoords.add(Coord(row, col-1)) adjacentCoords.add((Coord(row-1, col-1))) adjacentCoords.add((Coord(row+1, col-1))) } adjacentCoords.add((Coord(row-1, col))) //above adjacentCoords.add((Coord(row+1, col))) //below partNumberStr += c if (col == line.length - 1) { //part number is at the end of line extractPartNumber(partNumberStr, adjacentCoords, gears)?.let { partNumber -> sum += partNumber } partNumberStr = "" } } else { if (partNumberStr.isNotEmpty()) { //reading number was finished, check coordinates to its right adjacentCoords.add(Coord(row, col)) adjacentCoords.add((Coord(row-1, col))) adjacentCoords.add((Coord(row+1, col))) //process num extractPartNumber(partNumberStr, adjacentCoords, gears)?.let { partNumber -> sum += partNumber } partNumberStr = "" } } } } val gearSum = gears.filter { it.value.parts.size == 2 }.map { it.value.parts[0] * it.value.parts[1] }.sum() println("Sum is $sum / $gearSum") } private fun extractPartNumber( partNumberStr: String, adjacentCoords: MutableList<Coord>, gears: MutableMap<Coord, Gear> ): Long? { var partNumber = partNumberStr.toLong() val validCoords = adjacentCoords.filter { (it.r in lines.indices) && (it.c in lines[0].indices) } //filter out coordinates outside the plan var isAdjacent = false validCoords.forEach { validCoord -> val adjacentChar = lines[validCoord.r][validCoord.c] if (!adjacentChar.isDigit() && adjacentChar != '.') { isAdjacent = true if (adjacentChar == '*') { val gear = gears[validCoord] if (gear == null || gear.parts.isEmpty()) { gears[validCoord] = Gear(validCoord, mutableListOf(partNumber)) } else { gears[validCoord]!!.parts.add(partNumber) } } } } adjacentCoords.clear() return if (isAdjacent) { println("Valid part number found $partNumber") partNumber } else { println("Invalid part number found $partNumber") null } } } fun main(args: Array<String>) { // val problem = Day03("/Users/miro/projects/AoC23/input/day03t.txt") val problem = Day03("/Users/miro/projects/AoC23/input/day03a.txt") problem.solve() }
0
Kotlin
0
0
6518fad9de6fb07f28375e46b50e971d99fce912
3,869
AoC-2023
MIT License
src/cn/leetcode/codes/simple100/Simple100.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple100 import cn.leetcode.codes.common.TreeNode import cn.leetcode.codes.createTreeNode import cn.leetcode.codes.out fun main() { val p = createTreeNode(arrayOf(1,2)) val q = createTreeNode(arrayOf(1,null,3)) // val p = createTreeNode(arrayOf(1,2,3)) // val q = createTreeNode(arrayOf(1,2,3)) val isSame = isSameTree(p,q) out(isSame) } /* 100. 相同的树 给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 示例 1: 输入:p = [1,2,3], q = [1,2,3] 输出:true 示例 2: 输入:p = [1,2], q = [1,null,2] 输出:false 示例 3: 输入:p = [1,2,1], q = [1,1,2] 输出:false 提示: 两棵树上的节点数目都在范围 [0, 100] 内 -104 <= Node.val <= 104 */ //递归解法 fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean { if (p == null && q == null) return true return p != null && q != null && p.`val` == q.`val` && isSameTree(p.left, q.left) && isSameTree(p.right, q.right) }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
1,135
LeetCodeSimple
Apache License 2.0
src/Day01.kt
riegersan
572,637,157
false
{"Kotlin": 4377}
fun main() { fun getElveCals( input: List<String>, ): List<Int> { val snackSeparator = mutableListOf<Int>() input.withIndex().forEach { if(it.value.isEmpty()){ snackSeparator.add(it.index) } } val elves = mutableListOf<Int>() var current = 0 snackSeparator.forEach { var sum = 0 input.subList(current, it).forEach { sum += it.toInt() } elves.add(sum) current = it + 1 } var sum = 0 val fromIndex = snackSeparator.last() + 1 val toIndex = input.size input.subList(fromIndex, toIndex).forEach { sum += it.toInt() } elves.add(sum) return elves } fun part1(input: List<String>): Int { val elves = getElveCals(input) val highestCal = elves.max() return highestCal } fun part2(input: List<String>): Int { val elves = getElveCals(input) var calsOfTopThreeElves = 0 elves.sortedDescending().subList(0, 3).forEach{ calsOfTopThreeElves += it } return calsOfTopThreeElves } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d89439eb4d4d736d783c77cec873ac6e697e6ee9
1,509
advent-of-code-22-kotlin
Apache License 2.0
src/main/kotlin/day24/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day24 import util.Coord import util.Direction import util.readTestInput import java.lang.IllegalArgumentException data class Blizzard(val coord: Coord, val direction: Direction) { fun move(lastFreeX: Int, lastFreeY: Int): Blizzard { var newCoord = this.coord.move(this.direction) when { newCoord.x == 0 -> newCoord = Coord(lastFreeX, coord.y) newCoord.x > lastFreeX -> newCoord = Coord(1, coord.y) newCoord.y == 0 -> newCoord = Coord(coord.x, lastFreeY) newCoord.y > lastFreeY -> newCoord = Coord(coord.x, 1) } return this.copy(coord = newCoord) } } data class Path(val steps: Int, val playerPos: Coord) private fun parseBlizzards(inputLines: List<String>) = inputLines.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, char -> when (char) { '<' -> Blizzard(Coord(x, y), Direction.LEFT) '>' -> Blizzard(Coord(x, y), Direction.RIGHT) 'v' -> Blizzard(Coord(x, y), Direction.DOWN) '^' -> Blizzard(Coord(x, y), Direction.UP) else -> null } } }.toSet() data class Map(val blizzards: Set<Blizzard>, val lastFreeX: Int, val lastFreeY: Int) { private val blizzardCoords = blizzards.map { it.coord }.toSet() fun moveBlizzards(): Map { return this.copy(blizzards = blizzards.map { it.move(this.lastFreeX, this.lastFreeY) }.toSet()) } private fun isInBounds(coord: Coord) = coord.x in 1..lastFreeX && coord.y in 1..lastFreeY fun hasBlizzard(coord: Coord) = coord in blizzardCoords fun isMovable(coord: Coord) = isInBounds(coord) && coord !in blizzardCoords } fun searchPath( startPos: Coord, endPos: Coord, map: Map ): Pair<Path, Map> { val mapStates = mutableMapOf(0 to map) // steps to map val queue = mutableListOf(Path(0, startPos)) val seen = mutableSetOf<Path>() while (queue.isNotEmpty()) { val path = queue.removeFirst() if (path.playerPos == endPos) { return Pair(path, mapStates[path.steps]!!) } if (path !in seen) { seen += path // the map constantly changes because of blizzards var nextMap = mapStates[path.steps + 1] if (nextMap == null) { nextMap = mapStates[path.steps]!!.moveBlizzards() mapStates[path.steps + 1] = nextMap } //draw(mapStates[path.steps]!!, path, queue) // wait, if still possible and not occupied by a blizzard: if (!nextMap.hasBlizzard(path.playerPos)) { queue.add(Path(path.steps + 1, path.playerPos)) } // move: path.playerPos.neighbors() .filter { it == startPos || it == endPos || nextMap.isMovable(it) } .forEach { neighbor -> queue.add(Path(path.steps + 1, neighbor)) } } } throw IllegalArgumentException("No route to end") } // Debug print (the same way as in the assignment): fun draw(theMap: Map, path: Path, queue: MutableList<Path>) { println("queue $queue") val coords = setOf(Coord(0,0), Coord(theMap.lastFreeX + 1, theMap.lastFreeY + 1)) println("Minute ${path.steps}") util.drawGrid(coords) { val blizzards = theMap.blizzards.filter { b -> b.coord == it } when { path.playerPos == it -> 'E' blizzards.size > 1 -> blizzards.size.digitToChar() blizzards.size == 1 -> blizzards.first().direction.symbol theMap.hasBlizzard(it) -> 'o' else -> '.' } } } fun part1(startPos: Coord, endPos: Coord, map: Map): Path { val (path, _) = searchPath(startPos, endPos, map) return path } fun part2(startPos: Coord, endPos: Coord, initialMap: Map): Int { val (pathToEnd, mapAtEnd) = searchPath(startPos, endPos, initialMap) val (pathToStart, mapAtStart) = searchPath(endPos, startPos, mapAtEnd) val (backToEnd, _) = searchPath(startPos, endPos, mapAtStart) return pathToEnd.steps + pathToStart.steps + backToEnd.steps } fun main() { val inputLines = readTestInput("day24") val blizzards = parseBlizzards(inputLines) val startPos = Coord(inputLines.first().indexOfFirst { it == '.' }, 0) val endPos = Coord(inputLines.last().indexOfFirst { it == '.' }, inputLines.lastIndex) val lastFreeX = inputLines.first().length - 2 val lastFreeY = inputLines.size - 2 val initialMap = Map(blizzards, lastFreeX, lastFreeY) println(part1(startPos, endPos, initialMap)) println(part2(startPos, endPos, initialMap)) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
4,681
advent-of-code-2022
MIT License
src/Day11.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.util.* import java.util.function.IntUnaryOperator import java.util.function.LongToIntFunction import java.util.function.LongUnaryOperator import kotlin.collections.HashMap fun main() { val testInput = """ Monkey 0: Starting items: 79, 98 Operation: new = old * 19 Test: divisible by 23 If true: throw to monkey 2 If false: throw to monkey 3 Monkey 1: Starting items: 54, 65, 75, 74 Operation: new = old + 6 Test: divisible by 19 If true: throw to monkey 2 If false: throw to monkey 0 Monkey 2: Starting items: 79, 60, 97 Operation: new = old * old Test: divisible by 13 If true: throw to monkey 1 If false: throw to monkey 3 Monkey 3: Starting items: 74 Operation: new = old + 3 Test: divisible by 17 If true: throw to monkey 0 If false: throw to monkey 1 """.trimIndent() check(partOne(createMonkeys(testInput)) == 10605L) println(partOne(createMonkeys(readString("Day11.txt")))) check(partTwo(createMonkeys(testInput)) == 2713310158L) println(partTwo(createMonkeys(readString("Day11.txt")))) } private fun partOne(monkeys: Map<Int, Monkey>): Long { return performRounds(monkeys, 20) { it / 3 } } private fun partTwo(monkeys: Map<Int, Monkey>): Long { val lcd = getLCD(monkeys.values) return performRounds(monkeys, 10_000) { it % lcd } } private fun performRounds(monkeys: Map<Int, Monkey>, rounds: Int, worryHandler: LongUnaryOperator): Long { for (round in 1..rounds) { monkeys.forEach { val (_, monkey) = it val moves = monkey.inspect(worryHandler) moves.forEach { item -> monkeys[item.toMonkeyId]!! + item.worryLevel } } } println(monkeys.values.map(Monkey::inspectedItems)) val (testHigh1, testHigh2) = monkeys.values.map { it.inspectedItems }.sortedDescending() return testHigh1.toLong() * testHigh2.toLong() } private fun getLCD(monkeys: Collection<Monkey>): Long { return monkeys .map(Monkey::divisor) .reduce { acc, l -> acc * l } } private fun createMonkeys(src: String): SortedMap<Int, Monkey> { val monkeyMap = sortedMapOf<Int, Monkey>() val monkeys = src.split("\n\n") monkeys.forEach { m -> val split = m.split("\n") val id = split[0].filter { it.isDigit() }[0].digitToInt() val startingItems = split[1] .replace(" Starting items: ", "") .replace(" ", "") .split(',') .map(String::toLong) val splitOperation = split[2].replace(" Operation: new = ", "").split(' ') val a = splitOperation[0].toLongOrNull() val b: Long.(Long) -> Long = when (splitOperation[1]) { "*" -> Long::times "+" -> Long::plus "-" -> Long::minus "/" -> Long::div else -> TODO() } val c = splitOperation[2].toLongOrNull() val operation = LongUnaryOperator { b(a ?: it, c ?: it) } val divisibleBy = split[3].split(' ').last().toLong() val trueThrowTo = split[4].last().digitToInt() val falseThrowTo = split[5].last().digitToInt() val monkey = Monkey( id = id, operation = operation, divisor = divisibleBy, ifDividableId = trueThrowTo, ifNotDividableId = falseThrowTo ) startingItems.forEach { monkey + it } monkeyMap[monkey.id] = monkey } return monkeyMap } data class ItemThrown( val worryLevel: Long, val toMonkeyId: Int ) class Monkey( val id: Int, private val operation: LongUnaryOperator, val divisor: Long, private val ifDividableId: Int, private val ifNotDividableId: Int ) { var inspectedItems = 0 private set val items: Queue<Long> = LinkedList() operator fun plus(item: Long) = apply { items.offer(item) } fun inspect(worryHandler: LongUnaryOperator): List<ItemThrown> { val result = items.map { worryLevel -> inspectedItems++ val newWorryLevel = operation.andThen(worryHandler).applyAsLong(worryLevel) val monkeyId = if (newWorryLevel % divisor == 0L) ifDividableId else ifNotDividableId ItemThrown( worryLevel = newWorryLevel, toMonkeyId = monkeyId ) } items.clear() return result } override fun toString(): String { return "Monkey(id=$id, inspected=$inspectedItems, items=$items)" } }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
4,624
advent-of-code-2022-kotlin
Apache License 2.0
src/Day11.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
class Remainder(divisors: List<Int>, value: Int) { val map: MutableMap<Int, Int> = divisors.associateWith { 0 }.toMutableMap() var full: Long = 0 init { add(value) } fun put(divisor: Int, value: Int) { if (map.containsKey(divisor)) map[divisor] = value else error("no such key $divisor") } fun add(value: Int) { map.forEach { (divisor, reminder) -> this.put(divisor, (reminder + value) % divisor) } full += value } fun multiply(value: Int) { map.forEach { (divisor, reminder) -> this.put(divisor, (reminder * value) % divisor) } full *= value } fun square() { map.forEach { (divisor, reminder) -> this.put(divisor, (reminder * reminder) % divisor) } full *= full } fun value(divisor: Int): Int { if (map.containsKey(divisor)) return map[divisor] ?: error("null") else error("no value for key $divisor") } fun isDividedBy(divisor: Int): Boolean { if (map.containsKey(divisor)) return map[divisor] == 0 else error("no such key $divisor") } } data class Monkey( val items: MutableList<Remainder>, val op: Char, val num: String, val divisor: Int, val ifTrue: Int, val ifFalse: Int, var count: Long, ) fun main() { fun parse(chunk: List<String>, divisors: List<Int>): Monkey { val list = chunk[1].removePrefix(" Starting items: ").split(", ").map { Remainder(divisors, it.toInt()) } val op = chunk[2].removePrefix(" Operation: new = old ").first() val num = chunk[2].removePrefix(" Operation: new = old ").substring(2) val divisor = chunk[3].removePrefix(" Test: divisible by ").toInt() val ifTrue = chunk[4].removePrefix(" If true: throw to monkey ").toInt() val ifFalse = chunk[5].removePrefix(" If false: throw to monkey ").toInt() return Monkey(list.toMutableList(), op, num, divisor, ifTrue, ifFalse, 0, ) } fun part1(input: List<String>): Int { fun processRound(monkeys: MutableList<Monkey>) { monkeys.forEach { monkey -> with(monkey) { while (items.isNotEmpty()) { val item = items.removeAt(0) val operand = if (num == "old") item.value(Int.MAX_VALUE) else num.toInt() when(op) { '*' -> item.multiply(operand) '+' -> item.add(operand) else -> error("bad op $op") } item.put(Int.MAX_VALUE, item.value(Int.MAX_VALUE) / 3) item.full /= 3 // (if (item.value(Int.MAX_VALUE) % divisor == 0) monkeys[ifTrue] else monkeys[ifFalse]).items.add(item) (if (item.full % divisor.toLong() == 0L) monkeys[ifTrue] else monkeys[ifFalse]).items.add(item) count++ } } } } val monkeys = mutableListOf<Monkey>() val divisors = listOf(Int.MAX_VALUE) input.chunked(7).forEach { chunk -> val monkey = parse(chunk, divisors) monkeys.add(monkey) } repeat(20) { processRound(monkeys) } // println(monkeys) return monkeys.map { it.count.toInt() }.sortedDescending().take(2).reduce { acc, elem -> acc * elem } } fun part2(input: List<String>): Long { fun processRound(monkeys: MutableList<Monkey>) { monkeys.forEachIndexed { index, monkey -> with(monkey) { print("Monkey $index ($divisor$op$num) ") while (items.isNotEmpty()) { val item = items.removeAt(0) print(item.value(divisor)) if (num == "old") item.square() else { val operand = num.toInt() when(op) { '*' -> item.multiply(operand) '+' -> item.add(operand) else -> error("bad op $op") } } print(op) print(num.toIntOrNull() ?: "old") print("=") print(item.value(divisor)) // item /= divider val test = item.isDividedBy(divisor) // val test = item.full % divisor == 0L (if (test) monkeys[ifTrue] else monkeys[ifFalse]).items.add(item) count++ print("(${if (test) "YES" else "no"}->${if (test) ifTrue else ifFalse}), ") } } println() } } val monkeys = mutableListOf<Monkey>() val divisors = input.chunked(7).map { chunk -> chunk[3].removePrefix(" Test: divisible by ").toInt() } input.chunked(7).forEach { chunk -> val monkey = parse(chunk, divisors) monkeys.add(monkey) } repeat(10_000) { // if (it == 1) println(monkeys.map { it.count }) // if (it + 1 == 20) println(monkeys.map { it.count }) // if (it + 1 % 1000 == 0) println(monkeys.map { it.count }) println(monkeys.map { it.count }) println("Round ${it + 1}") println(monkeys.map { it.items.map { it.full } }) println(monkeys.map { it.items.map { it.map } }.joinToString("\n")) processRound(monkeys) } println(monkeys.map { it.count }) println(monkeys.map { it.items.map { it.full } }) // println(monkeys) return monkeys.map { it.count }.sortedDescending().take(2).reduce { acc, elem -> acc * elem } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") // println(part1(testInput)) check(part1(testInput) == 10605) //println(part2(testInput)) check(part2(testInput) == 2713310158) val input = readInput("Day11") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
6,486
AoC-2022
Apache License 2.0
calendar/day11/Day11.kt
rocketraman
573,845,375
false
{"Kotlin": 45660}
package day11 import Day import Lines class Day11 : Day() { data class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, val test: MonkeyTest, var inspections: Long = 0, ) data class MonkeyTest( val testDivisibleBy: Long, val nextTrue: Int, val nextFalse: Int, ) val startingItemRegex = """ Starting items: (.*)""".toRegex() val operationRegex = """ Operation: new = old (.) (.*)""".toRegex() val testRegex = """ Test: divisible by (.*)""".toRegex() val throwRegex = """ If (?:true|false): throw to monkey (.*)""".toRegex() override fun part1(input: Lines): Any { return solve(input, 20) { _ -> { it / 3 } } } override fun part2(input: Lines): Any { return solve(input, 10_000) { monkeys -> // had to check the subreddit for this -- I noticed all the divisors were primes but too rusty on math // for the implication to sink in :-( val primesLcm = monkeys .map { it.test.testDivisibleBy } .reduce { acc, l -> acc * l } return@solve { it.mod(primesLcm) } } } private fun solve(input: Lines, rounds: Int, worryReducerOf: (List<Monkey>) -> (Long) -> Long): Long { val items = input .filter { startingItemRegex.matches(it) } .mapNotNull { startingItemRegex .matchEntire(it)!!.groups[1]?.value ?.split(", ") ?.map { it.toLong() } } val operations = input .filter { operationRegex.matches(it) } .map { val (operand, multiplier) = operationRegex .matchEntire(it)!!.destructured val multiplierFn = when (multiplier) { "old" -> { old: Long -> old } else -> { _ -> multiplier.toLong() } } when (operand) { "*" -> { old: Long -> old * multiplierFn(old) } "+" -> { old: Long -> old + multiplierFn(old) } else -> error("Invalid operand $operand") } } val tests = input .filter { testRegex.matches(it) || it.startsWith(" If ") } .chunked(3) .map { val divisibleBy = testRegex .matchEntire(it[0])!!.groups[1]?.value ?.toLong() val (monkeyTrue) = throwRegex.matchEntire(it[1])!!.destructured val (monkeyFalse) = throwRegex.matchEntire(it[2])!!.destructured MonkeyTest(divisibleBy!!, monkeyTrue.toInt(), monkeyFalse.toInt()) } val monkeys = items.indices.map { Monkey( items = items[it].toMutableList(), operation = operations[it], test = tests[it], ) } val worryReducer = worryReducerOf(monkeys) (1..rounds).forEach { _ -> monkeys.forEach { monkey -> val listIterator = monkey.items.listIterator() for (item in listIterator) { monkey.inspections++ listIterator.remove() val worry = worryReducer(monkey.operation(item)) val testResult = worry.mod(monkey.test.testDivisibleBy) == 0L monkeys[if (testResult) monkey.test.nextTrue else monkey.test.nextFalse].items.add(worry) } } } val twoActive = monkeys.map { it.inspections }.sortedByDescending { it }.take(2) return twoActive[0] * twoActive[1] } }
0
Kotlin
0
0
6bcce7614776a081179dcded7c7a1dcb17b8d212
3,247
adventofcode-2022
Apache License 2.0
src/main/kotlin/nl/meine/aoc/_2022/Day5.kt
mtoonen
158,697,380
false
{"Kotlin": 201978, "Java": 138385}
package nl.meine.aoc._2022 data class Instruction(val num: Int, val from: Int, val to : Int) class Day5 { fun one(start: String, instructions: String): String { val pos = parsePositions(start) var ins = instructions .split("\n") .map{parseProcedure(it)} .map { moveStack(it, pos)} return pos .map{it.last()} .joinToString ("") } fun moveStack(instruction: Instruction, stacks: List<List<String>>): Unit{ for(ind in 0..<instruction.num){ val crate = stacks[instruction.from].removeLast() stacks[instruction.to].addLast(crate) } } fun moveStack2(instruction: Instruction, stacks: List<List<String>>): Unit{ val temp = ArrayList<String>() for(ind in 0..<instruction.num){ val crate = stacks[instruction.from].removeLast() temp.add(crate) } temp.reversed().forEach{ stacks[instruction.to].addLast(it)} var a = 0 } fun parseProcedure(input : String): Instruction { var temp = input.substring(5); val num = temp.substringBefore(" ").toInt() temp = temp.substringAfter(" from ") var from = temp.substringBefore(" ").toInt() -1 temp = temp.substringAfter(" to ") var to = temp.substringAfter(" ").toInt() -1 return Instruction(num, from, to) } private fun parsePositions(input: String): List<List<String>> { val parsed = input.split("\n") .reversed() .drop(1) .map { it.split("") } .chunked(4) .flatten() .map { processLine(it) } .dropLast(1) val positions: List<List<String>> = ArrayList(); for (index in 0..<parsed[0].size) { val stack = parsed.map { it[index] } .filter { it.isNotBlank() } positions.addLast(stack) } return positions } fun processLine(input: List<String>): List<String> { return input .chunked(4) .filter { it.size == 4 } .map { it[2] } } fun two(start: String, instructions: String): String { val pos = parsePositions(start) var ins = instructions .split("\n") .map{parseProcedure(it)} .map { moveStack2(it, pos)} return pos .map{it.last()} .joinToString ("") } } fun main() { val start = """ [P] [L] [T] [L] [M] [G] [G] [S] [M] [Q] [W] [H] [R] [G] [N] [F] [M] [D] [V] [R] [N] [W] [G] [Q] [P] [J] [F] [M] [C] [V] [H] [B] [F] [H] [M] [B] [H] [B] [B] [Q] [D] [T] [T] [B] [N] [L] [D] [H] [M] [N] [Z] [M] [C] [M] [P] [P] 1 2 3 4 5 6 7 8 9 """ val instructions = """move 8 from 3 to 2 move 1 from 9 to 5 move 5 from 4 to 7 move 6 from 1 to 4 move 8 from 6 to 8 move 8 from 4 to 5 move 4 from 9 to 5 move 4 from 7 to 9 move 7 from 7 to 2 move 4 from 5 to 2 move 11 from 8 to 3 move 3 from 9 to 7 move 11 from 2 to 8 move 13 from 8 to 4 move 11 from 5 to 6 move 8 from 2 to 4 move 1 from 5 to 4 move 1 from 3 to 2 move 2 from 2 to 1 move 2 from 8 to 5 move 3 from 7 to 5 move 1 from 4 to 7 move 9 from 6 to 7 move 1 from 6 to 5 move 1 from 1 to 4 move 3 from 1 to 9 move 15 from 4 to 3 move 2 from 4 to 1 move 1 from 1 to 9 move 3 from 4 to 5 move 1 from 4 to 1 move 1 from 7 to 2 move 1 from 6 to 3 move 5 from 7 to 1 move 19 from 3 to 9 move 7 from 1 to 2 move 24 from 9 to 7 move 23 from 7 to 1 move 1 from 4 to 6 move 3 from 7 to 3 move 1 from 6 to 1 move 6 from 2 to 1 move 21 from 1 to 9 move 5 from 3 to 8 move 2 from 2 to 5 move 10 from 9 to 5 move 1 from 2 to 1 move 5 from 1 to 3 move 6 from 3 to 4 move 1 from 2 to 8 move 3 from 5 to 2 move 4 from 9 to 3 move 13 from 5 to 9 move 2 from 7 to 2 move 3 from 4 to 7 move 1 from 7 to 8 move 5 from 1 to 3 move 1 from 7 to 5 move 1 from 8 to 1 move 2 from 2 to 7 move 19 from 9 to 2 move 5 from 2 to 3 move 7 from 5 to 9 move 1 from 1 to 9 move 5 from 9 to 2 move 4 from 9 to 3 move 20 from 3 to 9 move 1 from 3 to 9 move 3 from 7 to 3 move 16 from 2 to 3 move 12 from 3 to 4 move 2 from 2 to 5 move 1 from 2 to 4 move 2 from 4 to 1 move 4 from 8 to 1 move 15 from 9 to 3 move 2 from 5 to 3 move 3 from 2 to 8 move 5 from 8 to 5 move 7 from 3 to 4 move 2 from 9 to 6 move 15 from 3 to 1 move 3 from 1 to 8 move 3 from 9 to 5 move 9 from 4 to 1 move 3 from 3 to 5 move 2 from 6 to 5 move 9 from 1 to 3 move 1 from 9 to 4 move 1 from 5 to 2 move 3 from 8 to 5 move 10 from 1 to 6 move 12 from 4 to 8 move 1 from 2 to 7 move 2 from 5 to 6 move 1 from 1 to 4 move 7 from 3 to 6 move 1 from 7 to 2 move 2 from 4 to 9 move 3 from 1 to 7 move 1 from 9 to 8 move 1 from 2 to 3 move 3 from 1 to 7 move 5 from 8 to 2 move 5 from 7 to 1 move 9 from 6 to 8 move 6 from 6 to 9 move 8 from 8 to 6 move 1 from 7 to 4 move 5 from 2 to 4 move 7 from 5 to 1 move 5 from 8 to 9 move 11 from 6 to 7 move 9 from 9 to 1 move 2 from 7 to 5 move 1 from 9 to 5 move 1 from 3 to 6 move 3 from 4 to 6 move 1 from 8 to 2 move 2 from 3 to 6 move 6 from 5 to 2 move 3 from 5 to 9 move 3 from 2 to 1 move 1 from 4 to 3 move 3 from 2 to 7 move 1 from 8 to 9 move 1 from 2 to 8 move 8 from 7 to 5 move 1 from 7 to 8 move 3 from 5 to 6 move 5 from 5 to 2 move 1 from 4 to 1 move 1 from 3 to 2 move 4 from 1 to 5 move 4 from 2 to 6 move 6 from 1 to 2 move 5 from 9 to 3 move 2 from 5 to 3 move 3 from 3 to 6 move 10 from 6 to 4 move 4 from 8 to 5 move 5 from 5 to 1 move 21 from 1 to 7 move 3 from 2 to 9 move 1 from 5 to 2 move 4 from 2 to 9 move 8 from 4 to 8 move 1 from 2 to 1 move 7 from 8 to 2 move 2 from 6 to 1 move 2 from 1 to 5 move 1 from 1 to 5 move 4 from 3 to 7 move 1 from 9 to 3 move 4 from 6 to 3 move 1 from 3 to 8 move 1 from 3 to 4 move 2 from 2 to 6 move 2 from 9 to 7 move 14 from 7 to 8 move 10 from 8 to 7 move 3 from 4 to 6 move 5 from 2 to 3 move 3 from 9 to 8 move 3 from 3 to 4 move 1 from 2 to 4 move 1 from 9 to 4 move 1 from 9 to 5 move 1 from 5 to 2 move 3 from 5 to 7 move 1 from 4 to 6 move 5 from 3 to 8 move 1 from 6 to 8 move 5 from 7 to 6 move 14 from 8 to 5 move 2 from 6 to 7 move 18 from 7 to 2 move 3 from 6 to 1 move 5 from 5 to 4 move 5 from 6 to 2 move 7 from 2 to 1 move 1 from 8 to 4 move 1 from 5 to 1 move 8 from 1 to 9 move 10 from 4 to 3 move 8 from 5 to 3 move 1 from 4 to 3 move 2 from 1 to 5 move 1 from 5 to 3 move 5 from 3 to 1 move 1 from 1 to 3 move 5 from 1 to 6 move 13 from 3 to 1 move 3 from 9 to 4 move 2 from 9 to 6 move 5 from 6 to 5 move 6 from 5 to 1 move 7 from 7 to 9 move 7 from 9 to 6 move 1 from 9 to 3 move 1 from 7 to 9 move 3 from 9 to 1 move 12 from 2 to 7 move 7 from 6 to 2 move 22 from 1 to 7 move 1 from 6 to 5 move 4 from 7 to 6 move 1 from 5 to 6 move 2 from 4 to 1 move 1 from 4 to 1 move 23 from 7 to 9 move 4 from 6 to 2 move 4 from 7 to 3 move 1 from 1 to 9 move 6 from 2 to 1 move 1 from 7 to 2 move 7 from 2 to 8 move 2 from 3 to 8 move 3 from 1 to 9 move 1 from 2 to 8 move 5 from 8 to 3 move 3 from 2 to 1 move 2 from 7 to 8 move 10 from 9 to 8 move 4 from 1 to 3 move 14 from 3 to 4 move 7 from 4 to 5 move 1 from 6 to 9 move 5 from 5 to 8 move 1 from 6 to 4 move 6 from 9 to 4 move 3 from 8 to 4 move 1 from 5 to 1 move 3 from 4 to 3 move 9 from 4 to 3 move 5 from 3 to 6 move 5 from 1 to 5 move 4 from 6 to 2 move 8 from 9 to 2 move 2 from 6 to 5 move 3 from 4 to 7 move 2 from 2 to 7 move 2 from 5 to 4 move 3 from 5 to 9 move 3 from 4 to 2 move 10 from 2 to 5 move 1 from 9 to 8 move 2 from 2 to 9 move 3 from 7 to 2 move 1 from 2 to 9 move 13 from 5 to 1 move 2 from 2 to 7 move 8 from 9 to 2 move 1 from 4 to 6 move 1 from 9 to 5 move 14 from 8 to 4 move 7 from 4 to 5 move 4 from 7 to 5 move 2 from 3 to 8 move 4 from 1 to 5 move 2 from 5 to 4 move 6 from 5 to 6 move 7 from 2 to 5 move 1 from 2 to 6 move 1 from 5 to 2 move 2 from 2 to 8 move 2 from 1 to 3 move 8 from 4 to 7 move 1 from 4 to 3 move 6 from 1 to 6 move 7 from 3 to 9 move 3 from 7 to 1 move 2 from 8 to 7 move 7 from 6 to 9 move 2 from 3 to 6 move 6 from 8 to 3 move 9 from 5 to 3 move 2 from 7 to 8 move 2 from 6 to 4 move 7 from 6 to 9 move 5 from 3 to 8 move 10 from 9 to 1 move 11 from 1 to 8 move 1 from 3 to 2 move 4 from 5 to 6 move 2 from 6 to 2 move 2 from 7 to 9 move 3 from 1 to 7 move 6 from 3 to 9 move 2 from 7 to 2 move 2 from 6 to 9 move 1 from 5 to 9 move 11 from 9 to 8 move 1 from 4 to 5 move 6 from 9 to 8 move 31 from 8 to 9 move 1 from 3 to 6 move 1 from 7 to 1 move 1 from 4 to 3 move 1 from 5 to 2 move 1 from 1 to 8 move 1 from 8 to 9 move 1 from 7 to 3 move 11 from 9 to 6 move 2 from 3 to 1 move 2 from 3 to 5 move 1 from 5 to 4 move 1 from 4 to 1 move 6 from 8 to 3 move 1 from 1 to 4 move 1 from 4 to 6 move 2 from 3 to 6 move 17 from 9 to 2 move 23 from 2 to 9 move 14 from 9 to 4 move 1 from 1 to 7 move 1 from 5 to 6 move 8 from 6 to 2 move 1 from 3 to 2 move 4 from 9 to 8 move 5 from 4 to 7 move 3 from 7 to 2 move 1 from 1 to 2 move 2 from 9 to 4 move 3 from 6 to 9 move 8 from 4 to 9 move 2 from 4 to 2 move 4 from 7 to 2 move 1 from 7 to 9 move 4 from 6 to 2 move 16 from 2 to 1 move 2 from 3 to 2 move 18 from 9 to 8 move 1 from 4 to 2 move 1 from 6 to 8 move 1 from 3 to 9 move 3 from 9 to 5 move 4 from 9 to 8 move 6 from 2 to 8 move 1 from 5 to 1 move 4 from 2 to 8 move 1 from 5 to 1 move 17 from 1 to 4 move 1 from 5 to 8 move 10 from 4 to 3 move 10 from 3 to 1 move 4 from 4 to 9 move 1 from 4 to 6 move 1 from 4 to 8 move 38 from 8 to 1 move 27 from 1 to 5 move 1 from 8 to 2 move 1 from 6 to 3 move 1 from 4 to 8 move 1 from 8 to 4 move 14 from 1 to 9 move 1 from 3 to 1 move 1 from 5 to 1 move 1 from 2 to 5 move 2 from 5 to 4 move 17 from 5 to 8 move 3 from 4 to 9 move 2 from 9 to 1 move 3 from 5 to 7 move 3 from 7 to 4 move 2 from 4 to 7 move 12 from 1 to 4 move 1 from 7 to 4 move 1 from 7 to 6 move 1 from 6 to 9 move 11 from 4 to 3 move 1 from 5 to 3 move 11 from 3 to 9 move 1 from 3 to 2 move 3 from 5 to 4 move 1 from 2 to 4 move 1 from 5 to 8 move 13 from 9 to 3 move 16 from 9 to 1 move 4 from 8 to 9 move 2 from 1 to 4 move 1 from 9 to 1 move 1 from 9 to 7 move 1 from 7 to 2 move 6 from 8 to 3 move 8 from 4 to 2 move 4 from 9 to 6 move 3 from 2 to 3 move 3 from 6 to 1 move 3 from 8 to 6 move 1 from 6 to 8 move 3 from 6 to 4 move 11 from 3 to 5 move 4 from 8 to 2 move 6 from 3 to 5 move 3 from 5 to 1 move 2 from 8 to 3 move 14 from 5 to 3 move 4 from 3 to 4 move 6 from 3 to 5 move 3 from 2 to 9 move 4 from 1 to 8 move 3 from 9 to 6 move 2 from 6 to 9 move 6 from 4 to 3 move 15 from 1 to 4 move 1 from 6 to 7 move 5 from 5 to 1 move 11 from 3 to 1 move 2 from 9 to 7 move 1 from 5 to 6 move 2 from 1 to 3 move 7 from 2 to 6 move 4 from 8 to 1 move 8 from 4 to 2 move 3 from 6 to 4 move 5 from 1 to 4 move 17 from 4 to 8 move 3 from 3 to 7 move 4 from 3 to 4 move 4 from 4 to 2 move 9 from 8 to 7 move 1 from 3 to 8 move 10 from 2 to 4 move 1 from 6 to 2 move 2 from 8 to 4 move 2 from 6 to 9 move 2 from 6 to 2 move 1 from 2 to 3 move 3 from 1 to 4 move 1 from 3 to 2 move 1 from 9 to 3 move 1 from 9 to 7 move 4 from 8 to 4 move 10 from 4 to 8 move 5 from 4 to 3 move 1 from 2 to 8 move 5 from 3 to 7 move 3 from 7 to 8 move 3 from 4 to 3 move 8 from 7 to 2 move 8 from 7 to 8 move 1 from 3 to 2 move 3 from 2 to 8 move 9 from 2 to 5 move 12 from 1 to 7 move 21 from 8 to 3 move 5 from 8 to 6 move 8 from 7 to 5 move 6 from 7 to 4 move 12 from 5 to 7 move 1 from 8 to 5 move 2 from 4 to 2 move 1 from 7 to 6 move 14 from 3 to 8 move 5 from 6 to 2 move 7 from 2 to 6 move 6 from 8 to 4 move 11 from 7 to 4 move 8 from 3 to 7 move 4 from 5 to 7 move 9 from 8 to 2 move 6 from 4 to 1 move 2 from 5 to 2 move 1 from 7 to 2 move 11 from 2 to 3 move 1 from 2 to 1 move 7 from 4 to 1 move 5 from 6 to 8 move 1 from 2 to 3 move 2 from 8 to 7 move 14 from 3 to 7 move 15 from 7 to 6 move 4 from 4 to 6 move 2 from 8 to 3 move 12 from 1 to 3 move 1 from 8 to 2 move 1 from 2 to 3 move 1 from 3 to 9 move 1 from 9 to 7 move 1 from 1 to 4 move 18 from 6 to 8 move 3 from 3 to 2 move 17 from 8 to 3 move 3 from 7 to 6 move 3 from 2 to 6 move 25 from 3 to 7 move 2 from 4 to 1 move 9 from 6 to 5 move 2 from 3 to 1 move 1 from 3 to 9 move 5 from 5 to 2 move 1 from 8 to 3 move 2 from 4 to 7 move 1 from 9 to 4 move 1 from 6 to 7 move 2 from 5 to 2 move 2 from 4 to 8 move 2 from 5 to 8 move 5 from 7 to 9 move 27 from 7 to 5 move 2 from 9 to 6""" val ins = Day5(); println("one: ${ins.one(start, instructions)}") println("two: ${ins.two(start, instructions)}") }
0
Kotlin
0
0
a36addef07f61072cbf4c7c71adf2236a53959a5
12,621
advent-code
MIT License
src/Day04.kt
kedvinas
572,850,757
false
{"Kotlin": 15366}
import kotlin.math.max import kotlin.math.min fun main() { fun part1(input: List<String>): Int { var sum = 0 for (i in input) { val (a, b) = i.split(",") val (ax, ay) = a.split("-").map { it.toInt() } val (bx, by) = b.split("-").map { it.toInt() } if (ax <= bx && ay >= by || bx <= ax && by >= ay) { sum++ } } return sum } fun part2(input: List<String>): Int { var sum = 0 for (i in input) { val (a, b) = i.split(",") val (ax, ay) = a.split("-").map { it.toInt() } val (bx, by) = b.split("-").map { it.toInt() } if (max(ax, bx) <= min(ay, by)) { sum++ } } return sum } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
04437e66eef8cf9388fd1aaea3c442dcb02ddb9e
1,012
adventofcode2022
Apache License 2.0
src/main/kotlin/day09/day09.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package main.day09 import utils.readFile import utils.readLines import utils.separator import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sign fun main() { val test = """R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2""" val test2 = """R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20""" val input = readFile("day09") data class Step(val direction: Char, val distance: Int) data class Position(val row: Int, val col: Int) { fun left() = Position(row, col - 1) fun right() = Position(row, col + 1) fun above() = Position(row - 1, col) fun below() = Position(row + 1, col) fun distance(pos: Position): Int = max(abs(pos.row - row), abs(pos.col - col)) operator fun minus(pos: Position) = Position(row - pos.row, col - pos.col) operator fun plus(pos: Position) = Position(row + pos.row, col + pos.col) fun sign(): Position = Position(row.sign,col.sign) fun move(direction: Char): Position { return when (direction) { 'U' -> above() 'D' -> below() 'L' -> left() 'R' -> right() else -> error("Expected one of U,D,L,R not ${direction}") } } override fun toString(): String { return "(col=$col, row=$row)" } } fun parseSteps(input: List<String>): List<Step> { return input.map { val words = it.split(" ") Step(words[0][0], words[1].toInt()) } } class Rope(val knots: Array<Position>) { val head: Position get() = knots[0] val tail: Position get() = knots[knots.lastIndex] operator fun set(index: Int, pos: Position) { knots[index] = pos } operator fun get(index: Int) = knots[index] fun indexOf(pos: Position) = knots.indexOf(pos) override fun toString(): String { return knots.contentToString() } } fun print( steps: List<Step>, visited: Set<Position>, start: Position, rope: Rope, knots: Int, visitsOnly: Boolean = false ) { var maxRow = 0 var minRow = 0 var maxCol = 0 var minCol = 0 var dummy = Position(0, 0) steps.forEach { step -> repeat(step.distance) { dummy = dummy.move(step.direction) maxRow = max(maxRow, dummy.row) maxCol = max(maxCol, dummy.col) minRow = min(minRow, dummy.row) minCol = min(minCol, dummy.col) } } for (row in minRow..maxRow) { val covered = mutableSetOf<Int>() for (col in minCol..maxCol) { val pos = Position(row, col) if (visitsOnly) { if (pos == start) { print('s') } else { print(if (visited.contains(pos)) '#' else '.') } } else { val index = rope.indexOf(pos) when { index == 0 -> print('H') index > 0 -> print(if (knots == 2) 'T' else index.toString()) pos == start -> print('s') else -> print(if (visited.contains(pos)) '#' else '.') } if(index >= 0 && covered.isEmpty()) { if(pos == start) { covered.add(rope.knots.size) // indicate 's' } covered.add(index) for (i in index..rope.knots.lastIndex) { if (pos == rope[i]) { covered.add(i) } } if(covered.size == 1) { covered.clear() } } } } if(covered.size > 1) { print(" (") val coveredKnots = covered.sorted() coveredKnots.forEachIndexed { index, knot -> if(index == 1) { print(" covers ") } else if(index > 1) { print(" ,") } when(knot) { 0 -> print('H') rope.knots.lastIndex -> print('T') rope.knots.size -> print('s') else -> print("$knot") } } println(')') } println() } } fun calcVisits(steps: List<Step>, knots: Int, printStep: Boolean): Int { val rope = Rope(Array(knots) { Position(0, 0) }) val start = rope.head val visited = mutableSetOf<Position>() visited.add(rope.tail) steps.forEach { step -> for (i in 0 until step.distance) { rope[0] = rope.head.move(step.direction) for (index in 1 until knots) { val prev = rope[index - 1] val next = rope[index] if (prev != next && prev.distance(next) > 1) { val diff = prev - next rope[index] = next + diff.sign() } } visited.add(rope.tail) if (printStep) { println() print(steps, visited, start, rope, knots, false) } } } println() print(steps, visited, start, rope, knots, true) return visited.size } fun part1() { val testResult = calcVisits(parseSteps(readLines(test)), 2, true) println("Part 1 Answer = $testResult") check(testResult == 13) val result = calcVisits(parseSteps(input), 2, false) println("Part 1 Answer = $result") check(result == 6503) } fun part2() { check(calcVisits(parseSteps(readLines(test)), 10, true) == 1) val testResult = calcVisits(parseSteps(readLines(test2)), 10, true) println("Part 2 Answer = $testResult") check(testResult == 36) val result = calcVisits(parseSteps(input), 10, false) println("Part 2 Answer = $result") check(result == 2724) } println("Day - 09") separator() part1() separator() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
5,519
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin2023/Day004.kt
teodor-vasile
573,434,400
false
{"Kotlin": 41204}
package main.kotlin2023 import kotlin.math.pow class Day004 { fun part1(lines: List<String>): Int { val objects = lines.map { line -> line.dropWhile { it != ':' } .split('|') .map { subString -> subString.split(' ') .filter { it.isNotEmpty() && it.all(Character::isDigit) } .map(String::toInt) } } val sumOf = objects.map { it[0].intersect(it[1]).size } .filter { !it.equals(0) } .sumOf { 2.0.pow(it - 1) }.toInt() return sumOf } fun part2(lines: List<String>): Int { data class Card(val winningNumbers: List<Int>, val ourNumbers: List<Int>) return lines.map { line -> val (_, winningNumbersText, ourNumbersText) = line.split(":", " | ") val winningNumbers = winningNumbersText.chunked(3).map { it.trim().toInt() } val ourNumbers = ourNumbersText.chunked(3).map { it.trim().toInt() } val count = winningNumbers.count { it in ourNumbers } Card(winningNumbers, ourNumbers)to count }.let { pairs -> val countByCard = MutableList(pairs.size) { 1 } pairs.mapIndexed { index, (_, count) -> (1..count).forEach { countByCard[index + it] += countByCard[index] } } countByCard } .onEach(::println) .sum() } }
0
Kotlin
0
0
2fcfe95a05de1d67eca62f34a1b456d88e8eb172
1,520
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/Day11.kt
SimonMarquis
570,868,366
false
{"Kotlin": 50263}
class Day11(input: List<String>) { private val monkeys: List<Monkey> = input.windowed(size = 6, 7).map { Monkey( items = it[1].substringAfter("Starting items: ").split(", ") .map(String::toLong).let(::ArrayDeque), operation = it[2].run { val strings = substringAfter("new = old ").split(" ") val operation = strings.first().single() val number = strings.last().toLongOrNull() when (operation) { '+' -> { it -> it + (number ?: it) } '*' -> { it -> it * (number ?: it) } else -> error(operation) } }, action = it.slice(3..5).run { Monkey.Action( divisor = this[0].substringAfter("Test: divisible by ").toInt(), ifTrue = this[1].substringAfter("If true: throw to monkey ").toInt(), ifFalse = this[2].substringAfter("If false: throw to monkey ").toInt(), ) }, ) } fun part1(): Long = monkeys .rounds(20, relief = 3) .businessLevel() fun part2(): Long = monkeys .rounds(10000, relief = 1, divisor = monkeys.map { it.action.divisor }.fold(1L) { acc, value -> acc * value }) .businessLevel() data class Monkey( var inspections: Long = 0L, private val items: ArrayDeque<Long> = ArrayDeque(), private val operation: (item: Long) -> Long, val action: Action, ) { fun receive(item: Long) = items.add(item) fun steps(relief: Long, divisor: Long? = null) = sequence { while (items.isNotEmpty()) { inspections++ val item = items.removeFirst() var worryLevel = operation(item) worryLevel /= relief if (divisor != null) worryLevel %= divisor yield(action(worryLevel)) } } class Action(val divisor: Int, private val ifTrue: Int, private val ifFalse: Int) { operator fun invoke(item: Long) = IndexedValue( index = if (item % divisor == 0L) ifTrue else ifFalse, value = item, ) } } private fun List<Monkey>.rounds(times: Int, relief: Long, divisor: Long? = null) = repeat(times) { forEach { monkey -> monkey.steps(relief, divisor).forEach { this[it.index].receive(it.value) } } }.let { this } private fun List<Monkey>.businessLevel() = map(Monkey::inspections) .sortedDescending() .take(2) .fold(1L) { acc, value -> acc * value } }
0
Kotlin
0
0
a2129cc558c610dfe338594d9f05df6501dff5e6
2,699
advent-of-code-2022
Apache License 2.0
src/day02/kotlin/aoc2023-02/src/main/kotlin/Main.kt
JoubaMety
726,095,975
false
{"Kotlin": 17724}
/** * Loads input text-file from src/main/resources */ fun getResourceAsText(path: String): String? = object {}.javaClass.getResource(path)?.readText() fun main() { /* val input = "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green\n" + "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue\n" + "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red\n" + "Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red\n" + "Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green" */ val input = getResourceAsText("adventofcode.com_2023_day_2_input.txt")!! val pattern = arrayOf(12, 13, 14) println(getSumOfIDsFromGames(input, pattern)) println(getSumOfPowersFromGames(input)) } /** * Splits String into elements, is put into a List */ fun convertStringToList(input: String): List<String> = input.split(regex = "[\r\n]+".toRegex()).toList() // do you see what I see? lmfao fun convertGamesStringToList(input: String): List<List<String>> { val inputLines = convertStringToList(input) val mutableOutput = mutableListOf("") val outputMutableList: MutableList<List<String>> = mutableListOf() inputLines.forEach { inputLine -> val splitLine = inputLine .replace("^Game (0|[1-9][0-9]?|100): ".toRegex(), "") .split("; ".toRegex()) outputMutableList.add(splitLine) } return outputMutableList } /** * Finds index of color for the getSum functions * Red - 0; Green - 1; Blue - 2 */ fun findColorIndexFromString(input: String): Int { val colorList = listOf("red", "green", "blue") for (i in colorList.indices) if (input.contains(colorList[i])) return i return -1 } /** * Gets sum of IDs from Games, that are valid * a.k.a. if the number of cubes in pattern match the number of cubes that could be played in each game/set */ fun getSumOfIDsFromGames(input: String, pattern: Array<Int>): Int { val gameList = convertGamesStringToList(input) var i = 1 var sum = 0 gameList.forEach { setList -> var valid = true setList.forEach { set -> val colorList = set.split(", ".toRegex()) colorList.forEach { color -> val colorIndex = findColorIndexFromString(color) val count = color.replace(" ((red)|(green)|(blue))".toRegex(), "").toInt() if (count > pattern[colorIndex]) valid = false } } if (valid) sum += i i++ } return sum } /** * Gets sum of powers of the least amount of colored cubes required for each game. */ fun getSumOfPowersFromGames(input: String): Int { val gameList = convertGamesStringToList(input) var sum = 0 gameList.forEach { setList -> val minimumRequiredCubes : MutableList<Int> = mutableListOf(0,0,0) setList.forEach { set -> val colorList = set.split(", ".toRegex()) colorList.forEach { color -> val colorIndex = findColorIndexFromString(color) val count = color.replace(" ((red)|(green)|(blue))".toRegex(), "").toInt() if (count > minimumRequiredCubes[colorIndex]) minimumRequiredCubes[colorIndex] = count } } sum += (minimumRequiredCubes[0] * minimumRequiredCubes[1] * minimumRequiredCubes[2]) } return sum }
0
Kotlin
0
0
1f883bbbbed64f285b0d3cf7f51f6fb3a1a0e966
3,563
AdventOfCode-2023
MIT License
src/main/kotlin/twenty/three/03.kt
itsabdelrahman
726,503,458
false
{"Kotlin": 8123}
package twenty.three import java.io.File import utilities.andThen fun main() { val characterMatrix: List<List<EngineSchematicCharacter>> = File("src/main/resources/twenty/three/03/1.txt") .readLines() .map { row -> row.toCharArray().map(EngineSchematicCharacter::from) } val symbolAdjacentIndicesMatrix: List<Set<Int>> = characterMatrix.flatMapIndexed { rowIndex, rowOfCharacters -> rowOfCharacters.flatMapIndexed { columnIndex, character -> (character is EngineSchematicCharacter.Symbol).andThen { calculateAdjacentIndices(rowIndex to columnIndex) }.orEmpty() } }.groupBy({ (rowIndex) -> rowIndex }) { (_, columnIndex) -> columnIndex }.map { (_, columnIndices) -> columnIndices.toSet() } val consecutiveDigitIndicesMatrix: List<List<IntRange>> = characterMatrix.map { rowOfCharacters -> rowOfCharacters.indicesOfConsecutive { character -> character is EngineSchematicCharacter.Digit } } val consecutiveDigitIndicesAdjacentToSymbols: List<List<IntRange>> = consecutiveDigitIndicesMatrix.mapIndexed { rowIndex, rowOfConsecutiveDigitIndices: List<IntRange> -> rowOfConsecutiveDigitIndices.filter { consecutiveDigitIndices: IntRange -> val rowOfSymbolAdjacentIndices: Set<Int> = symbolAdjacentIndicesMatrix.getOrNull(rowIndex) ?: emptySet() rowOfSymbolAdjacentIndices.any { it in consecutiveDigitIndices } } } val output = consecutiveDigitIndicesAdjacentToSymbols.mapIndexed { rowIndex, rowOfConsecutiveDigitIndices -> rowOfConsecutiveDigitIndices.sumOf { consecutiveDigitIndices -> val rowOfCharacters: List<EngineSchematicCharacter> = characterMatrix.getOrNull(rowIndex) ?: emptyList() val number: String = rowOfCharacters.slice(consecutiveDigitIndices) .filterIsInstance<EngineSchematicCharacter.Digit>() .joinToString(separator = "") { character -> character.value.toString() } number.toIntOrNull() ?: 0 } }.sum() println(output) } fun <T> Collection<T>.indicesOfConsecutive(predicate: (T) -> Boolean): List<IntRange> = foldIndexed<T, List<IntRange>>(listOf()) { index, clustersSoFar, element -> val isClusterElement = predicate(element) val lastCluster = clustersSoFar.lastOrNull() ?: IntRange.EMPTY val isFirstElementInCluster = isClusterElement && lastCluster.isEmpty() val isRightAfterLastElementInCluster = index - lastCluster.last == 1 when { isFirstElementInCluster -> clustersSoFar.dropLast(1).plusElement((index..index)) isClusterElement -> clustersSoFar.dropLast(1).plusElement((lastCluster.first..index)) isRightAfterLastElementInCluster -> clustersSoFar.plusElement(IntRange.EMPTY) else -> clustersSoFar } }.filterNot { cluster -> cluster.isEmpty() } fun calculateAdjacentIndices(index: TwoDimensionalIndex): Set<TwoDimensionalIndex> { val (rowIndex, columnIndex) = index val horizontalIndices = setOf( rowIndex to columnIndex - 1, // left rowIndex to columnIndex + 1, // right ) val verticalIndices = setOf( rowIndex - 1 to columnIndex, // top rowIndex + 1 to columnIndex, // bottom ) val diagonalIndices = setOf( rowIndex - 1 to columnIndex - 1, // top left rowIndex + 1 to columnIndex - 1, // bottom left rowIndex + 1 to columnIndex + 1, // bottom right rowIndex - 1 to columnIndex + 1, // top right ) return horizontalIndices + verticalIndices + diagonalIndices } sealed class EngineSchematicCharacter { companion object { fun from(value: Char): EngineSchematicCharacter = when { value == '.' -> Dot value.isDigit() -> Digit(value) else -> Symbol } } data object Dot : EngineSchematicCharacter() data object Symbol : EngineSchematicCharacter() data class Digit(val value: Char) : EngineSchematicCharacter() } typealias TwoDimensionalIndex = Pair<Int, Int>
0
Kotlin
0
0
81765d658ca1dd77b5e5418167ee519460baa4a5
4,161
advent-of-code
Creative Commons Zero v1.0 Universal
17/part_two.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File fun readInput() : Target { val input = File("input.txt") .readText() val xRegex = """x=(-?\d+)..(-?\d+)""".toRegex() val yRegex = """y=(-?\d+)..(-?\d+)""".toRegex() val (miniX, maxiX) = xRegex.find(input)?.destructured!! val (miniY, maxiY) = yRegex.find(input)?.destructured!! return Target(miniX.toInt(), maxiX.toInt(), miniY.toInt(), maxiY.toInt()) } class Target(private val miniX: Int, private val maxiX : Int, private val miniY : Int, private val maxiY : Int) { fun calcVelocitiesWithHit() : List<Pair<Int, Int>> { var result = mutableListOf<Pair<Int, Int>>() for (initialVx in 1..maxiX) { val windowY = 10 * (maxiY - miniY) for (initialVy in -windowY..windowY) { // heuristic initialVy values if (hitAfterSomeTime(initialVx, initialVy)) { result.add(Pair(initialVx, initialVy)) } } } return result.toList() } private fun hitAfterSomeTime(initialVx : Int, initialVy : Int) : Boolean { var vx = initialVx var vy = initialVy var curX = 0 var curY = 0 while(curY >= miniY) { curX += vx curY += vy vx = maxOf(0, vx - 1) vy -= 1 if (isHit(curX, curY)) { return true } } return false } private fun isHit(curX : Int, curY : Int) : Boolean { return curX in miniX..maxiX && curY in miniY..maxiY } } fun solve(target : Target) : Int { return target.calcVelocitiesWithHit().size } fun main() { val target = readInput() val ans = solve(target) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
1,745
advent-of-code-2021
MIT License
src/main/kotlin/com/colinodell/advent2021/Day08.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 class Day08 (input: List<String>) { private val inputs = input.map { Entry(it) } private val uniqueSegmentLengths = setOf(2, 3, 4, 7) // 1, 7, 4, and 8 each have a unique segment length compared to other numbers fun solvePart1(): Int = inputs.sumOf { it.outputValues.count { v -> uniqueSegmentLengths.contains(v.length) } } // I was not clever enough to solve this for myself, so I adapted the solution from @mkloserboer // which can be found here: https://github.com/mklosterboer/AdventOfCode2021/tree/ae559ea4d28c1b5624ae82ce0fc0b910abc2c873/AdventOfCode2021/Problems/Day08 fun solvePart2(): Int = inputs.sumOf { it.translateOutputValue().toInt() } private inner class Entry(line: String) { val signalPatterns: List<String> val outputValues: List<String> val knownSegments: MutableMap<Char, Char> = mutableMapOf() init { with (line.split(" | ")) { signalPatterns = this[0].split(" ") outputValues = this[1].split(" ") } solveKnownSegments() } private fun solveKnownSegments() { val counts = "abcdefg".associateWith { 0 }.toMutableMap() signalPatterns.forEach() { pattern -> pattern.forEach { letter -> counts[letter] = counts[letter]!! + 1 } } knownSegments['e'] = counts.filter { it.value == 4 }.keys.first() knownSegments['b'] = counts.filter { it.value == 6 }.keys.first() knownSegments['f'] = counts.filter { it.value == 9 }.keys.first() knownSegments['c'] = signalPatterns.first { it.length == 2 }.replace(knownSegments['f']!!.toString(), "").first() } fun translateOutputValue(): String { return outputValues.map { when { isZero(it) -> "0" isOne(it) -> "1" isTwo(it) -> "2" isThree(it) -> "3" isFour(it) -> "4" isFive(it) -> "5" isSix(it) -> "6" isSeven(it) -> "7" isEight(it) -> "8" isNine(it) -> "9" else -> throw IllegalArgumentException("Failed to decode: $it") } }.joinToString("") } private fun isZero(input: String) = input.length == 6 && input.contains(knownSegments['c']!!) && input.contains(knownSegments['e']!!) private fun isOne(input: String) = input.length == 2 private fun isTwo(input: String) = input.length == 5 && !input.contains(knownSegments['f']!!) private fun isThree(input: String) = input.length == 5 && input.contains(knownSegments['c']!!) && input.contains(knownSegments['f']!!) private fun isFour(input: String) = input.length == 4 private fun isFive(input: String) = input.length == 5 && input.contains(knownSegments['b']!!) private fun isSix(input: String) = input.length == 6 && !input.contains(knownSegments['c']!!) && input.contains(knownSegments['e']!!) private fun isSeven(input: String) = input.length == 3 private fun isEight(input: String) = input.length == 7 private fun isNine(input: String) = input.length == 6 && !input.contains(knownSegments['e']!!) } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
3,412
advent-2021
Apache License 2.0
src/main/java/com/ncorti/aoc2021/Exercise10.kt
cortinico
433,486,684
false
{"Kotlin": 36975}
package com.ncorti.aoc2021 import java.util.Stack object Exercise10 { fun part1() = getInputAsTest("10") { split("\n") } .map { val stack = Stack<Char>() val chars = it.toCharArray().toMutableList() stack.push(chars.removeFirst()) while (chars.isNotEmpty() && stack.isNotEmpty()) { when (val next = chars.removeFirst()) { '<', '(', '[', '{' -> stack.push(next) '>' -> if (stack.peek() == '<') stack.pop() else return@map 25137 ')' -> if (stack.peek() == '(') stack.pop() else return@map 3 ']' -> if (stack.peek() == '[') stack.pop() else return@map 57 '}' -> if (stack.peek() == '{') stack.pop() else return@map 1197 } } 0 } .sum() fun part2(): Long { val scores = getInputAsTest("10") { split("\n") } .map { val stack = Stack<Char>() val chars = it.toCharArray().toMutableList() stack.push(chars.removeFirst()) while (chars.isNotEmpty()) { when (val next = chars.removeFirst()) { '<', '(', '[', '{' -> stack.push(next) '>' -> if (stack.peek() == '<') stack.pop() else return@map Stack() ')' -> if (stack.peek() == '(') stack.pop() else return@map Stack() ']' -> if (stack.peek() == '[') stack.pop() else return@map Stack() '}' -> if (stack.peek() == '{') stack.pop() else return@map Stack() } } stack } .filter { it.isNotEmpty() } .map { var tempScore = 0L while (it.isNotEmpty()) { tempScore *= 5L tempScore += when (it.pop()) { '(' -> 1L '[' -> 2L '{' -> 3L else -> 4L } } tempScore } .sorted() return scores[(scores.size / 2)] } } fun main() { println(Exercise10.part1()) println(Exercise10.part2()) }
0
Kotlin
0
4
af3df72d31b74857201c85f923a96f563c450996
2,575
adventofcode-2021
MIT License
src/Day10.kt
thelmstedt
572,818,960
false
{"Kotlin": 30245}
import java.io.File sealed class Instruction { object Noop : Instruction() data class Addx(val x: Int) : Instruction() } fun main() { fun part1(text: String) { val instructions = text.lineSequence() .filter { it.isNotBlank() } .map { when (it) { "noop" -> Instruction.Noop else -> { val (inst, arg) = it.split(" ") when (inst) { "addx" -> Instruction.Addx(arg.toInt()) else -> error(it) } } } } val placed = mutableMapOf<Int, Int>() var cycle = 1 var X = 1 instructions.forEach { when (it) { is Instruction.Addx -> { placed[cycle] = X placed[cycle + 1] = X X += it.x placed[cycle + 2] = X cycle += 2 } Instruction.Noop -> { placed[cycle] = X cycle += 1 } } } println(placed) listOf(20, 60, 100, 140, 180, 220) .sumOf { placed[it]!! * it } .let { println(it) } } fun part2(text: String) { val instructions = text.lineSequence() .filter { it.isNotBlank() } .map { when (it) { "noop" -> Instruction.Noop else -> { val (inst, arg) = it.split(" ") when (inst) { "addx" -> Instruction.Addx(arg.toInt()) else -> error(it) } } } } val placed = mutableMapOf<Int, Int>() var cycle = 0 var X = 1 instructions.forEach { when (it) { is Instruction.Addx -> { placed[cycle] = X placed[cycle + 1] = X X += it.x placed[cycle + 2] = X cycle += 2 } Instruction.Noop -> { placed[cycle] = X cycle += 1 } } } println(placed) // listOf(20, 60, 100, 140, 180, 220) // .sumOf { placed[it]!! * it } // .let { println(it) } val width = 40 val height = 6 val screen = " ".repeat(240).toMutableList() var sprite = (0..2) (0 until height).forEach { row -> placed.entries.forEach { e -> val (cycle, X) = e sprite = (X - 1..X + 1) if (sprite.contains(cycle - (width * row))) { screen[cycle] = '#' } } } println(screen.chunked(40).map { it.joinToString("") }.joinToString("\n")) } val testInput = File("src", "Day10_test.txt").readText() val input = File("src", "Day10.txt").readText() // part1(testInput) // part1(input) // part2(testInput) part2(input) }
0
Kotlin
0
0
e98cd2054c1fe5891494d8a042cf5504014078d3
3,298
advent2022
Apache License 2.0
src/main/kotlin/days/aoc2016/Day1.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2016 import days.Day import kotlin.math.absoluteValue class Day1 : Day(2016, 1) { override fun partOne(): Any { return calculateDistanceForDirections(inputString) } override fun partTwo(): Any { return findFirstLocationVisitedTwice(inputString) } fun calculateDistanceForDirections(directions: String): Int { var heading = Heading.NORTH var position = Pair(0,0) directions.split(", ".toRegex()).forEach { step -> Regex("([RL])(\\d+)").matchEntire(step.trim())?.destructured?.let { (direction, distance) -> heading = when (heading) { Heading.NORTH -> if (direction == "R") Heading.EAST else Heading.WEST Heading.SOUTH -> if (direction == "R") Heading.WEST else Heading.EAST Heading.EAST -> if (direction == "R") Heading.SOUTH else Heading.NORTH Heading.WEST -> if (direction == "R") Heading.NORTH else Heading.SOUTH } position = Pair(position.first + vectors[heading]!!.first * distance.toInt(), position.second + vectors[heading]!!.second * distance.toInt()) } } return position.first.absoluteValue + position.second.absoluteValue } fun findFirstLocationVisitedTwice(directions: String): Int { var heading = Heading.NORTH var position = Pair(0,0) val setOfVisitedLocations = mutableSetOf<Pair<Int,Int>>() directions.split(", ".toRegex()).forEach { step -> Regex("([RL])(\\d+)").matchEntire(step.trim())?.destructured?.let { (direction, distance) -> heading = when (heading) { Heading.NORTH -> if (direction == "R") Heading.EAST else Heading.WEST Heading.SOUTH -> if (direction == "R") Heading.WEST else Heading.EAST Heading.EAST -> if (direction == "R") Heading.SOUTH else Heading.NORTH Heading.WEST -> if (direction == "R") Heading.NORTH else Heading.SOUTH } for (block in 1..distance.toInt()) { position = Pair( position.first + vectors[heading]!!.first, position.second + vectors[heading]!!.second ) if (setOfVisitedLocations.contains(position)) { return position.first.absoluteValue + position.second.absoluteValue } else { setOfVisitedLocations.add(position) } } } } throw Exception("No position visited twice") } private enum class Heading { NORTH, EAST, SOUTH, WEST; } private val vectors = mapOf( Heading.NORTH to Pair(0,-1), Heading.SOUTH to Pair(0,1), Heading.EAST to Pair(1,0), Heading.WEST to Pair(-1,0) ) }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
2,958
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/aoc23/day04.kt
asmundh
573,096,020
false
{"Kotlin": 56155}
package aoc23 import getIntegerListsSplitBy import pow import runTask import toOnlyInteger import toSets import utils.InputReader import kotlin.math.max fun day4part1(input: List<String>): Int = input.sumOf { getScratchCard(it).getScore() } fun day4part2(input: List<String>): Int { val scratchCards = input.map { getScratchCard(it) }.associateBy { it.id } val counts: MutableMap<Int, Int> = mutableMapOf() val backlog: MutableList<ScratchCard> = scratchCards.values.toMutableList() var index = 0 while (index < backlog.size) { val card = backlog[index++] counts[card.id] = max((counts[card.id]?.plus(1)) ?: -1, 1) for (i in 1..card.amountOfWinningCards) { scratchCards[card.id + i]?.let { newCard -> backlog.add(newCard) } } } return counts.values.sum() } fun getScratchCard(card: String): ScratchCard { val (winningNumbers, scratchedNumbers) = card.substringAfter(':').getIntegerListsSplitBy('|').toSets() return ScratchCard( card.substringBefore(":").toOnlyInteger(), winningNumbers, scratchedNumbers, winningNumbers.intersect(scratchedNumbers).size ) } data class ScratchCard( val id: Int, val winningNumbers: Set<Int>, val scratchedNumbers: Set<Int>, val amountOfWinningCards: Int, ) { fun getScore(): Int { val wins = scratchedNumbers.filter { winningNumbers.contains(it) }.size return if (wins < 2) wins else 2.pow(wins) } } fun main() { val input: List<String> = InputReader.getInputAsList(4) runTask("D4p1") { day4part1(input) } runTask("D4p2") { day4part2(input) } }
0
Kotlin
0
0
7d0803d9b1d6b92212ee4cecb7b824514f597d09
1,697
advent-of-code
Apache License 2.0
src/main/kotlin/g2501_2600/s2503_maximum_number_of_points_from_grid_queries/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2501_2600.s2503_maximum_number_of_points_from_grid_queries // #Hard #Array #Sorting #Breadth_First_Search #Heap_Priority_Queue #Union_Find // #2023_07_04_Time_581_ms_(100.00%)_Space_62.6_MB_(100.00%) import java.util.ArrayDeque import java.util.Arrays import java.util.PriorityQueue import java.util.Queue class Solution { private val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1)) fun maxPoints(grid: Array<IntArray>, queries: IntArray): IntArray { val r = grid.size val c = grid[0].size val res = IntArray(queries.size) val index = arrayOfNulls<Int>(queries.size) for (i in queries.indices) { index[i] = i } Arrays.sort(index, { o: Int?, m: Int? -> queries[o!!].compareTo(queries[m!!]) }) val q1: Queue<IntArray> = ArrayDeque() val q2 = PriorityQueue({ a: IntArray, b: IntArray -> a[2].compareTo(b[2]) }) q2.offer(intArrayOf(0, 0, grid[0][0])) val visited = Array(r) { BooleanArray(c) } var count = 0 visited[0][0] = true for (i in queries.indices) { val currLimit = queries[index[i]!!] while (q2.isNotEmpty() && q2.peek()[2] < currLimit) { q1.offer(q2.poll()) } while (q1.isNotEmpty()) { val curr = q1.poll() count++ for (dir in dirs) { val x = dir[0] + curr[0] val y = dir[1] + curr[1] if (x < 0 || y < 0 || x >= r || y >= c || visited[x][y]) { continue } if (!visited[x][y] && grid[x][y] < currLimit) { q1.offer(intArrayOf(x, y, grid[x][y])) } else { q2.offer(intArrayOf(x, y, grid[x][y])) } visited[x][y] = true } } res[index[i]!!] = count } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,054
LeetCode-in-Kotlin
MIT License
src/Day11.kt
jorander
571,715,475
false
{"Kotlin": 28471}
private data class Item(val worryLevel: Long) { fun relieved(): Item { return Item(worryLevel / 3L) } } private data class TestedItem(val item: Item, val action: (Item, Array<Monkey>) -> Unit) private data class Monkey( val items: List<Item>, val operation: (Item) -> Item, val testValue: Long, val ifTrue: (Item, Array<Monkey>) -> Unit, val ifFalse: (Item, Array<Monkey>) -> Unit ) { fun takeTurn(afterInspection: (Item) -> Item) = items.size to items .map(::inspect) .map(afterInspection) .map(::testItem) .map(::throwItem) private fun inspect(item: Item): Item { return operation(item) } private fun testItem(item: Item) = TestedItem( item, if (item.worryLevel % testValue == 0L) { ifTrue } else { ifFalse } ) private fun throwItem(testedItem: TestedItem): (Array<Monkey>) -> Unit = { monkeys: Array<Monkey> -> testedItem.action(testedItem.item, monkeys) } fun receive(item: Item) = this.copy(items = items + item) fun leaveItem() = this.copy(items= items.drop(1)) } private fun List<String>.toMonkeys() = chunked(String::isEmpty) .mapIndexed{ index, monkeyConfiguration -> Monkey( items = monkeyConfiguration[1].removePrefix(" Starting items: ").split(", ").map { Item(it.toLong()) }, operation = monkeyConfiguration[2].removePrefix(" Operation: new = old ").split(" ").let { val (operation, valueStr) = it val value = if (valueStr != "old") valueStr.toLong() else 0 when (operation) { "*" -> { item: Item -> Item(item.worryLevel * if (valueStr == "old") item.worryLevel else value) } "+" -> { item: Item -> Item(item.worryLevel + if (valueStr == "old") item.worryLevel else value) } else -> { throw IllegalArgumentException("Unknown operation $operation") } } }, testValue = monkeyConfiguration[3].removePrefix(" Test: divisible by ").toLong(), ifTrue = monkeyConfiguration[4].removePrefix(" If true: throw to monkey ").toInt().let { { item: Item, monkeys: Array<Monkey> -> monkeys[index] = monkeys[index].leaveItem(); monkeys[it] = monkeys[it].receive(item) } }, ifFalse = monkeyConfiguration[5].removePrefix(" If false: throw to monkey ").toInt().let { { item: Item, monkeys: Array<Monkey> -> monkeys[index] = monkeys[index].leaveItem(); monkeys[it] = monkeys[it].receive(item) } } ) }.toTypedArray() fun main() { val day = "Day11" fun IntRange.run(monkeys: Array<Monkey>, afterInspection: (Item) -> Item): Long { val afterExecution = fold(List(monkeys.size) { 0L }) { numberOfItemsInspected, _ -> val numberOfItemsInspectedInRound = monkeys .map { monkey -> val (numberOfItems, throwsToExecute) = monkey.takeTurn(afterInspection) throwsToExecute.forEach { it(monkeys) } numberOfItems } numberOfItemsInspected.zip(numberOfItemsInspectedInRound) .map { (i1, i2) -> i1 + i2 } } return afterExecution.sortedDescending().take(2).reduce(Long::times) } fun part1(input: List<String>): Long { val monkeys = input.toMonkeys() val rounds = 1..20 return rounds.run(monkeys,Item::relieved) } fun part2(input: List<String>): Long { val monkeys = input.toMonkeys() val rounds = 1..10000 return rounds.run(monkeys) { item: Item -> Item(item.worryLevel % monkeys.map { it.testValue }.reduce(Long::times)) } } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 10605L) val result1 = part1(input) println(result1) check(result1 == 121450L) check(part2(testInput) == 2713310158L) val result2 = part2(input) println(result2) check(result2 == 28244037010L) }
0
Kotlin
0
0
1681218293cce611b2c0467924e4c0207f47e00c
4,289
advent-of-code-2022
Apache License 2.0
src/day09/Day09.kt
PoisonedYouth
571,927,632
false
{"Kotlin": 27144}
package day09 import readInput import kotlin.math.sign private data class Point( val x: Int, val y: Int, ) { private fun move(x: Int = 0, y: Int = 0): Point { return this.copy( x = this.x + x, y = this.y + y ) } fun isNotTouching(other: Point): Boolean { return this !in setOf( other, other.move(x = 1), other.move(y = 1), other.move(x = -1), other.move(y = -1), other.move(x = 1, y = 1), other.move(x = -1, y = 1), other.move(x = 1, y = -1), other.move(x = -1, y = -1), ) } fun moveDirection(direction: String): Point { return when (direction) { "U" -> move(y = 1) "L" -> move(x = -1) "R" -> move(x = 1) "D" -> move(y = -1) else -> error("Invalid input!") } } companion object { val START = Point(x = 0, y = 0) } } fun main() { fun part1(input: List<String>): Int { var head = Point.START var tail = head val visited = mutableSetOf(tail) for (line in input) { val (direction, steps) = line.split(" ") repeat(steps.toInt()) { head = head.moveDirection(direction) if (tail.isNotTouching(head)) { tail = Point(tail.x + (head.x - tail.x).sign, tail.y + (head.y - tail.y).sign) visited += tail } } } return visited.size } fun part2(input: List<String>): Int { val rope = MutableList(10) { Point.START } val visited = mutableSetOf(Point.START) for (line in input) { val (direction, steps) = line.split(" ") repeat(steps.toInt()) { rope[0] = rope[0].moveDirection(direction) rope.drop(1).indices.forEach { index -> val head = rope[index] var tail = rope[index + 1] if (tail.isNotTouching(head)) { tail = Point(tail.x + (head.x - tail.x).sign, tail.y + (head.y - tail.y).sign) visited += rope.last() } rope[index + 1] = tail } } } return visited.size } val input = readInput("day09/Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
dbcb627e693339170ba344847b610f32429f93d1
2,499
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/sorts/QuickSort.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.sorts import dev.shtanko.algorithms.extensions.swap /** * Developed by <NAME> in 1959, with his work published in 1961, Quicksort is an efficient sort algorithm using * divide and conquer approach. Quicksort first divides a large array into two smaller sub-arrays: the low elements * and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are: * 1) Pick an element, called a pivot, from the array. * 2) Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, * while all elements with values greater than the pivot come after it (equal values can go either way). * After this partitioning, the pivot is in its final position. This is called the partition operation. * 3) Recursively apply the above steps to the sub-array of elements with smaller values and separately to * the sub-array of elements with greater values. * * Worst-case performance O(n^2) * Best-case performance O(nLogn) * Average performance O(nLogn) * Worst-case space complexity O(1) */ class QuickSort : AbstractSortStrategy { override fun <T : Comparable<T>> perform(arr: Array<T>) { sort(arr, 0, arr.size - 1) } private fun <T : Comparable<T>> sort(arr: Array<T>, low: Int, high: Int) { if (arr.isEmpty()) return val divideIndex = partition(arr, low, high) if (low < divideIndex - 1) { // 2) Sorting left half sort(arr, low, divideIndex - 1) } if (divideIndex < high) { // 3) Sorting right half sort(arr, divideIndex, high) } } private fun <T : Comparable<T>> partition(array: Array<T>, low: Int, high: Int): Int { var left = low var right = high val pivot = array[(left + right) / 2] // 4) Pivot Point while (left <= right) { while (array[left] < pivot) left++ // 5) Find the elements on left that should be on right while (array[right] > pivot) right-- // 6) Find the elements on right that should be on left // 7) Swap elements, and move left and right indices if (left <= right) { array.swap(left, right) left++ right-- } } return left } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,941
kotlab
Apache License 2.0
src/Day02.kt
szymon-kaczorowski
572,839,642
false
{"Kotlin": 45324}
private const val SCISSORS_RESP = "Z" private const val ROCK_RESP = "X" private const val PAPER__RESP = "Y" private const val PAPER = "B" private const val ROCK = "A" private const val SCISSORS = "C" private const val WIN = "Z" private const val LOSE = "X" private const val DRAW = "Y" fun main() { fun part1(input: List<String>): Int { var sum = 0 for (single in input) { val split = single.split(" ") val first = split[0] val response = split[1] val pair = first to response sum += when (pair) { PAPER to PAPER__RESP -> 3 + 2 ROCK to PAPER__RESP -> 6 + 2 SCISSORS to PAPER__RESP -> 0 + 2 PAPER to ROCK_RESP -> 0 + 1 ROCK to ROCK_RESP -> 3 + 1 SCISSORS to ROCK_RESP -> 6 + 1 PAPER to SCISSORS_RESP -> 6 + 3 ROCK to SCISSORS_RESP -> 0 + 3 SCISSORS to SCISSORS_RESP -> 3 + 3 else -> 0 } } return sum } fun part2(input: List<String>): Int { var sum = 0 for (single in input) { val split = single.split(" ") val first = split[0] val response = split[1] val pair = first to response sum += when (pair) { PAPER to LOSE -> 0 + 1 ROCK to LOSE -> 0 + 3 SCISSORS to LOSE -> 0 + 2 PAPER to DRAW -> 3 + 2 ROCK to DRAW -> 3 + 1 SCISSORS to DRAW -> 3 + 3 PAPER to WIN -> 6 + 3 ROCK to WIN -> 6 + 2 SCISSORS to WIN -> 6 + 1 else -> 0 } } return sum } // 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
1d7ab334f38a9e260c72725d3f583228acb6aa0e
2,069
advent-2022
Apache License 2.0
src/Day18.kt
frango9000
573,098,370
false
{"Kotlin": 73317}
import javax.swing.JOptionPane fun main() { val input = readInput("Day18") printTime { print(Day18.part1(input)) } printTime { print(Day18.part1Bitwise(input)) } printTime { print(Day18.part2(input)) } } class Day18 { companion object { fun part1(input: List<String>): Int { val cubes = input.map { it.split(",").map { it.toInt() } }.map { (x, y, z) -> Position(x, y, z) } return cubes.getNumberOfSidesArrayImpl() } fun part1Bitwise(input: List<String>): Int { val cubes = input.map { it.split(",").map { it.toInt() } }.map { (x, y, z) -> Position(x, y, z) } return cubes.getNumberOfSides() } fun part2(input: List<String>): Int { val cubes = input.map { it.split(",").map { it.toInt() } }.map { (x, y, z) -> Position(x, y, z) } return cubes.withoutBubbles().getNumberOfSides() } } } private fun List<Position>.withoutBubbles(): List<Position> { val maxX = maxOf { it.x } val maxY = maxOf { it.y } val maxZ = maxOf { it.z } val occupiedArea = Array(maxX + 1) { Array(maxY + 1) { Array(maxZ + 1) { false } } } for ((x, y, z) in this) { occupiedArea[x][y][z] = true } // showSlice(occupiedArea) val floodedArea = Array(maxX + 1) { Array(maxY + 1) { Array(maxZ + 1) { false } } } val queue = ArrayDeque<Position>() queue.add(Position(0, 0, 0)) while (queue.isNotEmpty()) { val (x, y, z) = queue.removeFirst() if (!floodedArea[x][y][z] && !occupiedArea[x][y][z]) { floodedArea[x][y][z] = true if (x > 0) { queue.add(Position(x - 1, y, z)) } if (x < maxX) { queue.add(Position(x + 1, y, z)) } if (y > 0) { queue.add(Position(x, y - 1, z)) } if (y < maxY) { queue.add(Position(x, y + 1, z)) } if (z > 0) { queue.add(Position(x, y, z - 1)) } if (z < maxZ) { queue.add(Position(x, y, z + 1)) } } } // showSlice(floodedArea) return floodedArea.mapIndexed { x, table -> table.mapIndexed { y, row -> row.mapIndexed { z, flooded -> if (flooded) null else Position( x, y, z ) } } }.flatten().flatten().filterNotNull() } data class Position(val x: Int, val y: Int, val z: Int) fun List<Position>.getNumberOfSides(): Int { val maxX = maxOf { it.x } val maxY = maxOf { it.y } val maxZ = maxOf { it.z } val sideX = (0..maxY).map { (0..maxZ).map { 0 }.toMutableList() } val sideY = (0..maxZ).map { (0..maxX).map { 0 }.toMutableList() } val sideZ = (0..maxX).map { (0..maxY).map { 0 }.toMutableList() } for (cube in this) { sideX[cube.y][cube.z] = sideX[cube.y][cube.z] xor (1 shl cube.x) sideX[cube.y][cube.z] = sideX[cube.y][cube.z] xor (1 shl cube.x + 1) sideY[cube.z][cube.x] = sideY[cube.z][cube.x] xor (1 shl cube.y) sideY[cube.z][cube.x] = sideY[cube.z][cube.x] xor (1 shl cube.y + 1) sideZ[cube.x][cube.y] = sideZ[cube.x][cube.y] xor (1 shl cube.z) sideZ[cube.x][cube.y] = sideZ[cube.x][cube.y] xor (1 shl cube.z + 1) } val numOfSidesX = sideX.sumOf { it.sumOf { Integer.bitCount(it) } } val numOfSidesY = sideY.sumOf { it.sumOf { Integer.bitCount(it) } } val numOfSidesZ = sideZ.sumOf { it.sumOf { Integer.bitCount(it) } } return numOfSidesX + numOfSidesY + numOfSidesZ } fun List<Position>.getNumberOfSidesArrayImpl(): Int { val maxX = maxOf { it.x } val maxY = maxOf { it.y } val maxZ = maxOf { it.z } val sideX = (0..maxY).map { (0..maxZ).map { (0..maxX + 1).map { false }.toMutableList() } } val sideY = (0..maxZ).map { (0..maxX).map { (0..maxY + 1).map { false }.toMutableList() } } val sideZ = (0..maxX).map { (0..maxY).map { (0..maxZ + 1).map { false }.toMutableList() } } for (cube in this) { sideX[cube.y][cube.z][cube.x] = !sideX[cube.y][cube.z][cube.x] sideX[cube.y][cube.z][cube.x + 1] = !sideX[cube.y][cube.z][cube.x + 1] sideY[cube.z][cube.x][cube.y] = !sideY[cube.z][cube.x][cube.y] sideY[cube.z][cube.x][cube.y + 1] = !sideY[cube.z][cube.x][cube.y + 1] sideZ[cube.x][cube.y][cube.z] = !sideZ[cube.x][cube.y][cube.z] sideZ[cube.x][cube.y][cube.z + 1] = !sideZ[cube.x][cube.y][cube.z + 1] } val numOfSidesX = sideX.sumOf { it.sumOf { it.filter { it }.count() } } val numOfSidesY = sideY.sumOf { it.sumOf { it.filter { it }.count() } } val numOfSidesZ = sideZ.sumOf { it.sumOf { it.filter { it }.count() } } return numOfSidesX + numOfSidesY + numOfSidesZ } fun showSlice(area: Array<Array<Array<Boolean>>>) { var x = 0 var result: Int = -1 while (true) { val slice = area[x].map { it.map { if (it) "_" else "#" }.joinToString("") }.joinToString("\n") result = JOptionPane.showConfirmDialog(null, "$x \n\n$slice\n\n Next Slice?") when (result) { JOptionPane.YES_OPTION -> if (x > 0) x-- JOptionPane.NO_OPTION -> if (x < area.lastIndex) x++ JOptionPane.CANCEL_OPTION -> break } } }
0
Kotlin
0
0
62e91dd429554853564484d93575b607a2d137a3
5,410
advent-of-code-22
Apache License 2.0
src/main/kotlin/aoc2023/Day25.kt
Ceridan
725,711,266
false
{"Kotlin": 110767, "Shell": 1955}
package aoc2023 import org.jgrapht.alg.clustering.GirvanNewmanClustering import org.jgrapht.graph.DefaultEdge import org.jgrapht.graph.DefaultUndirectedGraph import java.lang.IllegalStateException class Day25 { fun part1(input: List<String>): Int { val parsedGraph = parseInput(input) val vertices = parsedGraph.map { (k, v) -> v + k }.flatten().toSet() val edges = parsedGraph.map { (k, v) -> v.map { k to it } }.flatten().toSet() val graph = DefaultUndirectedGraph<String, DefaultEdge>(DefaultEdge::class.java) vertices.forEach { graph.addVertex(it) } edges.forEach { graph.addEdge(it.first, it.second) } // https://en.wikipedia.org/wiki/Girvan%E2%80%93Newman_algorithm val clustering = GirvanNewmanClustering(graph, 2).clustering if (clustering.numberClusters != 2) throw IllegalStateException("Can't build exactly 2 clusters.") return clustering.clusters[0].size * clustering.clusters[1].size } private fun parseInput(lines: List<String>): Map<String, Set<String>> { val graph = mutableMapOf<String, MutableSet<String>>() lines.forEach { line -> val (src, rest) = line.split(':') if (src !in graph) { graph[src] = mutableSetOf() } val destinations = rest.split(' ').filter { it.isNotEmpty() } destinations.forEach { dest -> graph[src]!!.add(dest) } } return graph } } fun main() { val day25 = Day25() val input = readInputAsStringList("day25.txt") println("25, part 1: ${day25.part1(input)}") println("25, part 2: -") }
0
Kotlin
0
0
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
1,683
advent-of-code-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumProduct.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * Given an integer array, find three numbers whose product is maximum and output the maximum product. */ fun interface AbstractMaximumProductStrategy { operator fun invoke(products: IntArray): Int } /** * Time complexity : O(n^3). * We need to consider every triplet from nums array of length n. * Space complexity : O(1). Constant extra space is used. */ class MaximumProductBrutForce : AbstractMaximumProductStrategy { override operator fun invoke(products: IntArray): Int { val n = products.size var ans = Int.MIN_VALUE for (i in products.indices) { for (j in i + 1 until n) { for (k in j + 1 until n) { ans = ans.coerceAtLeast(products[i] * products[j] * products[k]) } } } return ans } } /** * Time complexity : O(n log n). Sorting the nums array takes n\log n n log n time. * Space complexity : O(log n). Sorting takes O(\log n)O(log n) space. */ class MaximumProductSorting : AbstractMaximumProductStrategy { override operator fun invoke(products: IntArray): Int { products.sort() val n = products.size return (products.first() * products[1] * products.last()) .coerceAtLeast(products.last() * products[n - 2] * products[n - 3]) } } /** * Time complexity : O(n). Only one iteration over the nums array of length nn is required. * Space complexity : O(1). Constant extra space is used. */ class MaximumProductSingleScan : AbstractMaximumProductStrategy { override operator fun invoke(products: IntArray): Int { var max1 = Int.MIN_VALUE var max2 = Int.MIN_VALUE var max3 = Int.MIN_VALUE var min1 = Int.MAX_VALUE var min2 = Int.MAX_VALUE for (product in products) { when { product > max1 -> { max3 = max2 max2 = max1 max1 = product } product > max2 -> { max3 = max2 max2 = product } product > max3 -> { max3 = product } } if (product < min1) { min2 = min1 min1 = product } else if (product < min2) { min2 = product } } return (max1 * max2 * max3).coerceAtLeast(max1 * min1 * min2) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,120
kotlab
Apache License 2.0
src/day12/Day12.kt
quinlam
573,215,899
false
{"Kotlin": 31932}
package day12 import utils.ArrayMovement import utils.Day /** * Actual answers after submitting; * part1: 420 * part2: 414 */ class Day12 : Day<Int, Array<Array<Char>>>( testPart1Result = 31, testPart2Result = 29, ) { override fun part1Answer(input: Array<Array<Char>>): Int { val endNode = findE(input) return bfs(endNode, 'S', input) } override fun part2Answer(input: Array<Array<Char>>): Int { val endNode = findE(input) return bfs(endNode, 'a', input) } private fun bfs(fromNode: BFSNode, startNode: Char, input: Array<Array<Char>>): Int { val visited = HashSet<Pair<Int, Int>>() val queue = ArrayDeque<BFSNode>() queue.add(fromNode) visited.add(fromNode.location) while (!queue.isEmpty()) { val currentNode = queue.removeFirst() if (currentNode.letter == startNode) { return currentNode.steps } val newNodes = getNodes(currentNode, input, visited) queue.addAll(newNodes) } return Integer.MAX_VALUE } private fun findE(input: Array<Array<Char>>): BFSNode { input .forEachIndexed { i, arr -> arr.forEachIndexed { j, it -> if (it == 'E') { return BFSNode(Pair(i, j), 0, it) } } } throw RuntimeException("Can't find the end") } private fun getNodes(node: BFSNode, input: Array<Array<Char>>, visited: HashSet<Pair<Int, Int>>): List<BFSNode> { val row = node.location.first val col = node.location.second return ArrayMovement.values() .map { Pair(row + it.horizontal, col + it.vertical) } .filter { input.getOrNull(it.first)?.getOrNull(it.second) != null } .filter { canStep(node.letter, input[it.first][it.second]) } .filter { !visited.contains(it) } .map { BFSNode(it, node.steps + 1, input[it.first][it.second]) } .onEach { visited.add(it.location) } } private fun canStep(current: Char, next: Char): Boolean { return current.elevation() - next.elevation() <= 1 } private fun Char.elevation(): Int { return when (this) { 'S' -> 'a'.code 'E' -> 'z'.code else -> this.code } } override fun modifyInput(input: List<String>): Array<Array<Char>> { return input.map { it.toCharArray().toTypedArray() } .toTypedArray() } }
0
Kotlin
0
0
d304bff86dfecd0a99aed5536d4424e34973e7b1
2,613
advent-of-code-2022
Apache License 2.0
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day10/Day10.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day10 import eu.janvdb.aocutil.kotlin.readLines import kotlin.math.abs //const val FILENAME = "input10-test.txt" const val FILENAME = "input10.txt" const val WIDTH = 40 const val HEIGHT = 6 fun main() { val instructions = readLines(2022, FILENAME) .map(String::toInstruction) val computer = Computer(instructions) var sum = 0 for (i in 1..WIDTH * HEIGHT) { if (i % 40 == 20) sum += computer.x * i val x = (i - 1) % WIDTH val ch = if (abs(x - computer.x) <= 1) "##" else " " print(ch) if (i % 40 == 0) println() computer.step() } println(sum) } interface Instruction { val numberOfCycles: Int fun execute(computer: Computer) } class AddXInstruction(private val value: Int) : Instruction { override val numberOfCycles = 2 override fun execute(computer: Computer) { computer.x += value } override fun toString(): String = "addx $value" } class NoopInstruction : Instruction { override val numberOfCycles = 1 override fun execute(computer: Computer) {} override fun toString(): String = "noop" } fun String.toInstruction(): Instruction { val parts = this.split(" ") return when (parts[0]) { "addx" -> AddXInstruction(parts[1].toInt()) "noop" -> NoopInstruction() else -> throw IllegalArgumentException(this) } } class Computer(private val program: List<Instruction>) { private var pc = 0 private var currentInstruction: Instruction = program[0] private var cycleInInstruction = 0 var x = 1 fun step() { val complete = cycleInInstruction == currentInstruction.numberOfCycles - 1 if (complete) { currentInstruction.execute(this) pc = (pc + 1) % program.size currentInstruction = program[pc] cycleInInstruction = 0 } else { cycleInInstruction++ } } override fun toString(): String = "Computer(pc=$pc, x=$x)" }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,819
advent-of-code
Apache License 2.0
src/Day02.kt
Lonexera
573,177,106
false
null
fun main() { fun String.mapYourChoiceToRockPaperScissors(): RockPaperScissors { return when (this) { "X" -> RockPaperScissors.ROCK "Y" -> RockPaperScissors.PAPER "Z" -> RockPaperScissors.SCISSORS else -> error("This input is not allowed - $this!") } } fun String.mapOpponentsChoiceToRockPaperScissors(): RockPaperScissors { return when (this) { "A" -> RockPaperScissors.ROCK "B" -> RockPaperScissors.PAPER "C" -> RockPaperScissors.SCISSORS else -> error("This input is not allowed - $this!") } } fun getYourResultPoints( you: RockPaperScissors, opponent: RockPaperScissors ): Int { val choicePoints = when (you) { RockPaperScissors.ROCK -> 1 RockPaperScissors.PAPER -> 2 RockPaperScissors.SCISSORS -> 3 } val matchResultPoints = when { you == opponent -> 3 you == RockPaperScissors.PAPER && opponent == RockPaperScissors.ROCK -> 6 you == RockPaperScissors.SCISSORS && opponent == RockPaperScissors.PAPER -> 6 you == RockPaperScissors.ROCK && opponent == RockPaperScissors.SCISSORS -> 6 opponent == RockPaperScissors.PAPER && you == RockPaperScissors.ROCK -> 0 opponent == RockPaperScissors.SCISSORS && you == RockPaperScissors.PAPER -> 0 opponent == RockPaperScissors.ROCK && you == RockPaperScissors.SCISSORS -> 0 else -> error("Undefined match - $opponent vs $you!") } return choicePoints + matchResultPoints } fun part1(input: List<String>): Int { return input.sumOf { val (opponent, you) = it.split(" ") .zipWithNext() .first() getYourResultPoints( you = you.mapYourChoiceToRockPaperScissors(), opponent = opponent.mapOpponentsChoiceToRockPaperScissors() ) } } fun RockPaperScissors.winChoice(): RockPaperScissors { return when (this) { RockPaperScissors.ROCK -> RockPaperScissors.PAPER RockPaperScissors.PAPER -> RockPaperScissors.SCISSORS RockPaperScissors.SCISSORS -> RockPaperScissors.ROCK } } fun RockPaperScissors.loseChoice(): RockPaperScissors { return when (this) { RockPaperScissors.ROCK -> RockPaperScissors.SCISSORS RockPaperScissors.PAPER -> RockPaperScissors.ROCK RockPaperScissors.SCISSORS -> RockPaperScissors.PAPER } } fun String.getYourChoice( opponent: RockPaperScissors ): RockPaperScissors { return when (this) { "X" -> opponent.loseChoice() "Y" -> opponent "Z" -> opponent.winChoice() else -> error("Illegal input - $this") } } fun part2(input: List<String>): Int { return input.sumOf { val (opponent, you) = it.split(" ") .zipWithNext() .first() val opponentChoice = opponent.mapOpponentsChoiceToRockPaperScissors() getYourResultPoints( you = you.getYourChoice(opponentChoice), opponent = opponentChoice ) } } val input = readInput("Day02") println(part1(input)) println(part2(input)) } enum class RockPaperScissors { ROCK, PAPER, SCISSORS }
0
Kotlin
0
0
c06d394cd98818ec66ba9c0311c815f620fafccb
3,560
kotlin-advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch6/Problem64.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch6 import kotlin.math.sqrt import kotlin.math.truncate /** * Problem 64: Odd Period Square Roots * * https://projecteuler.net/problem=64 * * Goal: Count how many continued fraction representations of irrational square roots of * numbers <= N have an odd-length period (repeated sequence). * * Constraints: 10 <= N <= 3e4 * * Square Root: This can be expressed as an infinite continued fraction -> * * sqrt(N) = a_0 + 1/(a_1 + 1/(a_2 + 1/(...))) * * e.g. sqrt(3) = 1 + 1/(1 + 1/(2 + 1/(...))) == [1;(1,2)] * Note that (1,2) is not a reptend, but the values of a_i for each infinite iteration. * * e.g.: N = 10 * count = 3 * sqrt(2) = [1;(2)], sqrt(5) = [2;(4)], sqrt(10) = [3;(6)] */ class OddPeriodSquareRoots { /** * Solution is based on the expression of the square root of x: * * sqrt(x) = a + r/(a + sqrt(x)) * * where a is the floored root (integer part) of x and r is the remainder (fractional part). * * Initialisation of the expression shows: * * sqrt(x) = 0 + (x - 0)/1 , with remainder numerator (n) = 0 & denominator (d) = 1 * * if the floored root of x is substituted as a_0, the remainder can be found: * * n_k = d_{k-1} * a_{k-1} - n_{k-1} * d_k = floor((x - (n_k)^2)/d_{k-1}) * * thereby helping find the next a_1, which corresponds to the first period number, * * a_k = floor((a_0 + n_k)/d_k) * * These 3 values together will be unique unless the period has entered a new repeated sequence. * * N.B. A repeated loop will also be entered once a_k = 2 * a_0, which proves true in the * solution, & can replace the set of Triples loop break. */ fun oddSquareRoots(num: Int): Int { var count = 0 for (x in 2..num) { val root = sqrt(1.0 * x) val a0 = truncate(root).toInt() val fractional = root - a0 if (fractional == 0.0) continue // skip perfect squares var period = 0 var a = a0 var n = 0 var d = 1 val visited = mutableSetOf<Triple<Int, Int, Int>>() while (true) { n = d * a - n d = (x - n * n) / d a = (a0 + n) / d val expression = Triple(a, n ,d) if (expression in visited) break visited.add(expression) period++ } if (period % 2 == 1) count++ } return count } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,599
project-euler-kotlin
MIT License