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/com/github/ferinagy/adventOfCode/aoc2021/2021-03.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2021, "03-input") val test1 = readInputLines(2021, "03-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val gamma = getGammaRate(input) val epsilon = gamma.map { if (it == '0') '1' else '0' }.joinToString(separator = "") return gamma.toInt(2) * epsilon.toInt(2) } private fun part2(input: List<String>): Int { val o2 = getByCriteria(input, true).toInt(2) val co2 = getByCriteria(input, false).toInt(2) return o2 * co2 } private fun getGammaRate(input: List<String>): String { val report = input.map { line -> line.map { it.digitToInt() } } val size = report.first().size return buildString { repeat(size) { digit -> val count = report.count { it[digit] == 1 } append(if (count > report.size / 2) '1' else '0') } } } private fun getByCriteria(input: List<String>, mostCommon: Boolean): String { var report = input var position = 0 while (1 < report.size) { val sum = report.count { it[position] == '1' } report = if (mostCommon && sum >= report.size / 2f || !mostCommon && sum < report.size / 2f) { report.filter { it[position] == '1' } } else { report.filter { it[position] == '0' } } position++ } return report.first() }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,673
advent-of-code
MIT License
src/day14/Day14.kt
PoisonedYouth
571,927,632
false
{"Kotlin": 27144}
package day14 import readInput import kotlin.math.max import kotlin.math.min private data class Point(val x: Int, val y: Int) private val sandSource = Point(500, 0) fun main() { fun Point.to(other: Point) = if (x == other.x) { (min(y, other.y)..max(y, other.y)).map { Point(x, it) } } else { (min(x, other.x)..max(x, other.x)).map { Point(it, y) } } fun Point.next(points: MutableMap<Point, Char>): Point = listOf(0, -1, 1).firstNotNullOfOrNull { dx -> Point(x + dx, y + 1).let { if (it !in points) it else null } } ?: this fun List<Point>.toCaveMap() = associate { it to '#' }.toMutableMap() fun createPoints(input: List<String>): List<Point> { val points = input.flatMap { line -> line .split(" -> ") .map { element -> element .split(",") .map { it.toInt() } .let { Point(it[0], it[1]) } } .windowed(2) .map { it[0].to(it[1]) } .flatten() } return points } fun dropSand(path: MutableList<Point>, map: MutableMap<Point, Char>, newMax: Int) { var proceed = true while (proceed) { var curr = path.removeLast() while (true) { val next = curr.next(map) when { next.y >= newMax -> { proceed = false break } next == curr -> { map[curr] = 'o' proceed = path.isNotEmpty() break } else -> { path.add(curr) curr = next } } } } } fun part1(input: List<String>): Int { val points = createPoints(input).toCaveMap() val yMax = points.keys.maxOf { it.y } val path = mutableListOf(sandSource) dropSand(path, points, yMax) return points.values.count { it == 'o' } } fun part2(input: List<String>): Int { val points = createPoints(input) val yMax = points.maxOf { it.y } val floor = Point(sandSource.x - yMax - 3, yMax + 2).to(Point(sandSource.x + yMax + 3, yMax + 2)) val map = (points + floor).toCaveMap() val newMax = map.keys.maxOf { it.y } val path = mutableListOf(sandSource) dropSand(path, map, newMax) return map.values.count { it == 'o' } } val lines = readInput("day14/Day14") println(part1(lines)) println(part2(lines)) }
0
Kotlin
1
0
dbcb627e693339170ba344847b610f32429f93d1
2,751
advent-of-code-kotlin-2022
Apache License 2.0
src/Day13.kt
makohn
571,699,522
false
{"Kotlin": 35992}
fun main() { val day = "13" fun eval(str: MutableList<Char>): List<Any> { val list = mutableListOf<Any>() var cs = "" while (str.isNotEmpty()) { when (val c = str.removeFirst()) { in '0'..'9' -> cs+=c '[' -> list.add(eval(str)) ']' -> { if (cs.isNotEmpty()) list.add(cs.toInt()) return list } ',' -> { if (cs.isNotEmpty()) list.add(cs.toInt()) cs = "" } else -> error("Unexpected!") } } return list } fun compare(a: Any, b: Any): Int { if (a is Int && b is Int) { return a.compareTo(b) } val l = if (a is List<*>) a else listOf(a) val r = if (b is List<*>) b else listOf(b) for (i in l.indices) { if (i !in r.indices) return 1 val res = compare(l[i]!!, r[i]!!) if (res != 0) return res } return l.size.compareTo(r.size) } fun part1(input: List<String>): Int { val numRightOrder = input .asSequence() .filter { it.isNotEmpty() } .chunked(2) .map { val (a, b) = it eval(a.toMutableList())[0] as List<*> to eval(b.toMutableList())[0] as List<*> } .map { (a, b) -> compare(a, b) } .foldIndexed(0) { idx, acc, b -> if (b < 0) acc + idx + 1 else acc } return numRightOrder } fun part2(input: List<String>): Int { val list = input .filter { it.isNotEmpty() } .map { eval(it.toMutableList())[0] as List<*> } .toMutableList() println(list) val da = listOf(listOf(2)) val db = listOf(listOf(6)) list.add(da) list.add(db) list.sortWith(::compare) val a = list.indexOf(da) + 1 val b = list.indexOf(db) + 1 return a * b } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2734d9ea429b0099b32c8a4ce3343599b522b321
2,352
aoc-2022
Apache License 2.0
src/main/kotlin/day2.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package day2 import aoc.utils.decode import aoc.utils.getLooping import aoc.utils.readInput // S = scissors // R = rock // P = paper // wins suite before it on list and loses to suite after it // loop if out of bounds val suites = listOf("R", "P", "S") val opponent = listOf("A", "B", "C") val us = listOf("X", "Y", "Z") fun part1(): Int { return readInput("day2-part1.txt") .map { it.split(" ") } .map { Pair( suites.decode(it[0], opponent), suites.decode(it[1], us), ) } .sumOf { calculateScore(it) } } fun part2(): Int { return readInput("day2-part1.txt") .map { it.split(" ") } .map { Pair( suites.decode(it[0], opponent), it[1], ) } .map { Pair( it.first, when (it.second) { "Z" -> suites.getLooping(suites.indexOf(it.first)+1) "X" -> suites.getLooping(suites.indexOf(it.first)-1) else -> it.first } ) } .sumOf { calculateScore(it) } } fun calculateScore(it: Pair<String, String>): Int { val shapeScore = suites.indexOf(it.second) + 1 val wasDraw = it.first == it.second val ourSelection = suites.indexOf(it.second) val wasWin = !wasDraw && suites.getLooping(ourSelection - 1) == it.first return shapeScore + if (wasWin) 6 else if (wasDraw) 3 else 0; }
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
1,531
adventOfCode2022
Apache License 2.0
src/main/kotlin/de/p58i/utils/tableoptimizer/solver/evolutionary/DefaultFunctions.kt
mspoeri
529,728,917
false
{"Kotlin": 30057}
package de.p58i.utils.tableoptimizer.solver.evolutionary import de.p58i.utils.tableoptimizer.model.Group import de.p58i.utils.tableoptimizer.model.Pairing import de.p58i.utils.tableoptimizer.model.Problem import de.p58i.utils.tableoptimizer.model.Solution import de.p58i.utils.tableoptimizer.model.Table import de.p58i.utils.tableoptimizer.model.TableAffinity import kotlin.math.abs import kotlin.math.min import kotlin.random.Random object DefaultConstants { const val mutationProbability = 0.20 } fun defaultMutation(solution: Solution): Solution { if (Random.nextDouble() <= DefaultConstants.mutationProbability) { swapRandomGroup(solution) } return solution } fun randomSolution(problem: Problem): Solution { val groupsToSeat = problem.groups.shuffled().toMutableList() val tablesToSeat = problem.tables.map { it.copy(groups = HashSet()) }.toSet() groupsToSeat.forEach { group -> val matchingTable = tablesToSeat.shuffled().find { it.freeSeats() >= group.count().toInt() } matchingTable?.groups?.add(group) } groupsToSeat.removeAll(tablesToSeat.flatMap { it.groups }) groupsToSeat.forEach { group -> tablesToSeat.shuffled().first().groups.add(group) } return Solution(tablesToSeat) } fun defaultPairingFunction(solutionA: Solution, solutionB: Solution): Solution { val pivotCount = min(solutionA.tables.size, solutionB.tables.size) / 2 val childTableSet = HashSet(solutionA.tables.shuffled().take(pivotCount).map { it.copy(groups = HashSet(it.groups)) }) childTableSet.addAll(solutionB.tables.filter { bTable -> !childTableSet.contains(bTable) }.map { it.copy(groups = HashSet(it.groups)) }) removeDoubleGroups(childTableSet) addMissingGroups(childTableSet, solutionA.tables.flatMap { it.groups }) return Solution(childTableSet) } fun defaultFitnessFunction(problem: Problem, solution: Solution): Double { val overPlacement = solution.tables.sumOf { min(it.freeSeats(), 0) } val pairingScore = problem.pairings.filter { it.applies(solution) }.sumOf { pairing -> pairing.score } val tableScore = problem.tableAffinities.filter { it.applies(solution) }.sumOf { affinity -> affinity.score } return (100 * overPlacement) + pairingScore + tableScore } fun removeDoubleGroups(tables: Set<Table>) { tables.forEach { table -> table.groups.forEach { group -> tables.filter { it != table }.forEach { it.groups.remove(group) } } } } fun addMissingGroups(tables: Collection<Table>, allGroups: Collection<Group>){ val placedGroups = tables.flatMap { it.groups } val missingGroups = allGroups.filter { !placedGroups.contains(it) } missingGroups.forEach { tables.place(it) } } private fun Collection<Table>.place(group: Group) { this.filter { !it.isEmpty() }.maxByOrNull { it.freeSeats() }?.groups?.add(group) ?: this.maxBy { it.freeSeats() }.groups.add(group) } private fun Pairing.applies(solution: Solution): Boolean { return solution.tables.map { this.applies(it) }.find { it } ?: false } private fun Pairing.applies(table: Table): Boolean { return table.groups.flatMap { it.people }.containsAll(listOf(this.personA, this.personB)) } private fun TableAffinity.applies(solution: Solution): Boolean { return solution.tables.map { this.applies(it) }.find { it } ?: false } private fun TableAffinity.applies(table: Table): Boolean { return table.name == this.tableName && table.groups.map { it.name }.contains(this.groupName) } private fun swapRandomGroup(solution: Solution) { val randomTable = solution.tables.filter { table -> !table.isEmpty() }.shuffled().first() val randomGroup = randomTable.groups.shuffled().first() randomTable.groups.remove(randomGroup) val fittingTable = solution.tables.filter { it != randomTable }.firstOrNull { it.freeSeats() >= randomGroup.count().toInt() } if (fittingTable != null) { fittingTable.groups.add(randomGroup) return } val swapTable = solution.tables.firstOrNull { table -> table.groups.filter { it.count() >= randomGroup.count() } .find { it.count().toInt() <= randomTable.freeSeats() } != null } ?: solution.tables.shuffled().first() val swapGroup = swapTable.groups.minBy { abs((it.count().toInt() - randomGroup.count().toInt())) } swapTwoGroups(randomTable, randomGroup, swapTable, swapGroup) } fun swapTwoGroups(tableA: Table, groupA: Group, tableB: Table, groupB: Group) { tableA.groups.remove(groupA) tableB.groups.remove(groupB) tableA.groups.add(groupB) tableB.groups.add(groupA) }
4
Kotlin
0
2
7e8765be47352e79b45f6ff0f8e6396e3da9abc9
4,644
table-optimizer
MIT License
src/Day20.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
fun main() { val day = 20 fun decrypt(data: List<Pair<Int, Long>>): List<Pair<Int, Long>> { val nums = data.toMutableList() debug(data) nums.indices .forEach { idx -> val offset = nums.indexOfFirst { it.first == idx } val s = nums[offset] val (_, d) = s if (d != 0L) { nums.removeAt(offset) val move = (offset.toLong() + d).mod(nums.size) nums.add(move, s) } } return nums } fun doIt(nums: List<Long>, r: Int = 1, m: Long = 1): Long { var data = nums.mapIndexed { i, v -> i to v * m } repeat (r) { data = decrypt(data) debug("After ${it + 1} round:\n${data.map { it.second }}") } val nums = data.map { it.second } val zeroIdx = nums.indexOf(0) return listOf(1000, 2000, 3000) .sumOf { nums[(zeroIdx + it).mod(nums.size)] } } fun parseInput(input: List<String>) = input.map { it.toLong() } fun part1(input: List<String>) = doIt(parseInput(input)) fun part2(input: List<String>) = doIt(parseInput(input), 10, 811589153) // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day.pad(2)}_test") checkTest(3) { part1(testInput) } checkTest(1623178306) { part2(testInput) } val input = readInput("Day${day.pad(2)}") solution { part1(input) } solution { part2(input) } }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
1,589
aoc22
Apache License 2.0
src/Day09.kt
andydenk
573,909,669
false
{"Kotlin": 24096}
import java.lang.IllegalStateException import kotlin.math.abs fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val largerTestInput = readInput("Day09_test_larger") val input = readInput("Day09") val part1Test = part1(testInput) val part2Test = part2(testInput) val part2TestLarger = part2(largerTestInput) check(part1Test == 13) check(part2Test == 1) check(part2TestLarger == 36) val part1Result = part1(input) val part2Result = part2(input) println("Part 1: $part1Result") println("Part 2: $part2Result") } private fun part1(input: List<String>): Int { return Rope.fromInput(input, 2).getVisitedPlaces() } private fun part2(input: List<String>): Int { return Rope.fromInput(input, 10).getVisitedPlaces() } private class Rope(val moves: List<Move>, val ropeLength: Int) { val nodes: ArrayDeque<Node> = ArrayDeque((0 until ropeLength).map { 0 to 0 }) val visited = mutableSetOf<Node>() fun getVisitedPlaces(): Int { visited.add(nodes.first().first to nodes.first().second) //Visualization(nodes, visited).printState() moves.forEach { move -> repeat(move.steps) { moveHead(move) (1 until ropeLength).forEach { nodeNumber -> moveTail(nodeNumber) } } } Visualization(nodes, visited).printState(endState = true) return visited.size } private fun moveHead(move: Move) { nodes[0] = nodes[0].first + move.direction.xModifier to nodes[0].second + move.direction.yModifier } private fun moveTail(nodeNumber: Int) { val (leadingX, leadingY) = nodes[nodeNumber - 1] val (x, y) = nodes[nodeNumber] val xModifier = leadingX - x val yModifier = leadingY - y if (abs(xModifier) < 2 && abs(yModifier) < 2) { return } val updatedNode = x + xModifier.toMoveAmount() to y + yModifier.toMoveAmount() nodes[nodeNumber] = updatedNode if (nodeNumber == ropeLength - 1) { visited.add(updatedNode) } } private fun Int.toMoveAmount(): Int = coerceAtMost(1).coerceAtLeast(-1) companion object { fun fromInput(input: List<String>, ropeLength: Int): Rope { return Rope(input.map { Move.fromLine(it) }, ropeLength) } } } private class Visualization(val nodes: ArrayDeque<Node>, val visited: Set<Node>) { fun printState(endState: Boolean = false) { val yGridRange = (233 downTo -19) val xGridRange = (-12..304) yGridRange.forEach { y -> println(xGridRange.map { x -> getCharacter(x, y, endState) }.toCharArray()) } println() } private fun getCharacter(x: Int, y: Int, endState: Boolean): Char { return if (nodes[0].first == x && nodes[0].second == y) { 'H' } else if (nodes.drop(1).contains(Node(x, y))) { nodes.indexOf(Node(x, y)).toString()[0] } else if (x == 0 && y == 0 * -1) { 's' } else if (visited.contains(x to y)) { '#'.takeIf { endState } ?: '.' } else { '.' } } } typealias Node = Pair<Int, Int> private data class Move(val direction: Direction, val steps: Int) { companion object { fun fromLine(line: String): Move { return Move(Direction.forInput(line[0]), line.drop(2).toInt()) } } } private enum class Direction(val xModifier: Int, val yModifier: Int) { RIGHT(1, 0), LEFT(-1, 0), UP(0, 1), DOWN(0, -1); companion object { fun forInput(input: Char): Direction { return when (input) { 'R' -> RIGHT 'L' -> LEFT 'U' -> UP 'D' -> DOWN else -> throw IllegalStateException("Unsupported Direction") } } } }
0
Kotlin
0
0
1b547d59b1dc55d515fe8ca8e88df05ea4c4ded1
4,047
advent-of-code-2022
Apache License 2.0
src/Day05.kt
ShuffleZZZ
572,630,279
false
{"Kotlin": 29686}
import java.util.* private fun stackPeeks(input: List<List<String>>, move: (List<Stack<Char>>, Int, Int, Int) -> Unit): String { val (towers, instructions) = input val stacksSize = towers.last().split("\\s+".toRegex()).last().toInt() val stacks = List(stacksSize) { Stack<Char>() } for (i in (0 until towers.size - 1).reversed()) { for (j in 1 until towers[i].length step 4) { if (towers[i][j] != ' ') { stacks[j / 4].push(towers[i][j]) } } } for (instruction in instructions) { val (amount, from, to) = "move (\\d+) from (\\d+) to (\\d+)".toRegex().find(instruction)!!.destructured move(stacks, amount.toInt(), from.toInt(), to.toInt()) } return stacks.map { it.peek() }.joinToString("") } fun main() { fun part1(input: List<List<String>>) = stackPeeks(input) { stacks: List<Stack<Char>>, amount: Int, from: Int, to: Int -> repeat(amount) { stacks[to - 1].push(stacks[from - 1].pop()) } } fun part2(input: List<List<String>>) = stackPeeks(input) { stacks: List<Stack<Char>>, amount: Int, from: Int, to: Int -> stacks[to - 1].addAll(stacks[from - 1].takeLast(amount)) repeat(amount) { stacks[from - 1].pop() } } // test if implementation meets criteria from the description, like: val testInput = readBlocks("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readBlocks("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e
1,582
advent-of-code-kotlin
Apache License 2.0
src/Day07.kt
AleksanderBrzozowski
574,061,559
false
null
import Day07.Back import Day07.ChangeDirectory import Day07.Directory import Day07.File import Day07.Instruction import Day07.ListFiles class Day07 { sealed interface Instruction object Back : Instruction data class ChangeDirectory(val toDir: String) : Instruction object ListFiles : Instruction data class File(val name: String, val size: Int) : Instruction data class Directory(val name: String) : Instruction } fun main() { data class DirectoryDepth(val name: String, val depth: Int, val number: Int) fun String.toInstruction(): Instruction = when { this == "$ cd .." -> Back this.startsWith("$ cd") -> ChangeDirectory(toDir = this.substringAfter("$ cd ")) this == "$ ls" -> ListFiles this.startsWith("dir") -> Directory(name = this.substringAfter("dir ")) else -> { val (size, name) = this.split(" ") File(name = name, size = size.toInt()) } } class DirectoriesStructure( val directoriesTree: Map<DirectoryDepth, List<DirectoryDepth>>, val directoriesFiles: Map<DirectoryDepth, List<File>> ) { fun allDirectories(): List<DirectoryDepth> = directoriesTree.flatMap { (parentDir, dirs) -> dirs + parentDir }.distinct() .apply { println(this.size) } fun part1Result(): Int = allDirectories() .map { dir -> dir to dir.size() } .filter { (dir, size) -> size <= 100_000 && dir.name != "/" } .onEach { println("size: " + it.second) } .sumOf { (_, size) -> size } fun totalSize(): Int = allDirectories().sumOf { it.size() } fun dirsBySizes(): List<Pair<DirectoryDepth, Int>> = allDirectories().map { it to it.size() } private fun DirectoryDepth.size(): Int { val filesSize = directoriesFiles[this]?.sumOf { it.size } ?: 0 val directories = directoriesTree[this] ?: emptyList() if (directories.isEmpty()) { return filesSize } val directoriesSize = directories.sumOf { it.size() } return filesSize + directoriesSize } } fun List<Instruction>.toDirectoriesStructure(): DirectoriesStructure { val directoriesTree = mutableMapOf<DirectoryDepth, List<DirectoryDepth>>() val directoriesFiles = mutableMapOf<DirectoryDepth, List<File>>() val directoriesStack = ArrayDeque<DirectoryDepth>() val visitedDirsOccurrences = mutableMapOf<Pair<String, Int>, Int>() fun number(name: String, depth: Int): Int = (visitedDirsOccurrences[name to depth] ?: 0) this.forEach { instruction -> when (instruction) { is Directory -> { visitedDirsOccurrences.merge( instruction.name to directoriesStack.size + 1, 1 ) { o1, o2 -> o1 + o2 } directoriesTree.merge( directoriesStack.last(), listOf( DirectoryDepth( name = instruction.name, depth = directoriesStack.size + 1, number = number(instruction.name, directoriesStack.size + 1) ) ) ) { d1, d2 -> d1 + d2 } } is File -> { directoriesFiles directoriesFiles.merge(directoriesStack.last(), listOf(instruction)) { f1, f2 -> f1 + f2 } } is Back -> { directoriesStack.removeLast() } is ChangeDirectory -> { directoriesStack.addLast( DirectoryDepth( name = instruction.toDir, depth = directoriesStack.size + 1, number = number(instruction.toDir, directoriesStack.size + 1) ) ) } is ListFiles -> {} } } return DirectoriesStructure(directoriesTree = directoriesTree, directoriesFiles = directoriesFiles) } val (_, occurrences) = readInput("Day07_test") .filter { it.startsWith("$ cd") } .fold(0 to emptyList<Int>()) { (depth, occurrences), cd -> when (cd) { "$ cd .." -> depth - 1 to occurrences "$ cd gqlg" -> depth + 1 to occurrences + (depth + 1) else -> depth + 1 to occurrences } } println(occurrences) val part1DirectoriesStructure = readInput("Day07_test") .map { it.toInstruction() } .toDirectoriesStructure() val part1Result = part1DirectoriesStructure .part1Result() println(part1Result) check(part1Result == 1749646) val totalDiskSpace = 70_000_000 val neededForUpdate = 30_000_000 // 221035442 // 41412830 val usedDiskSpace = part1DirectoriesStructure.totalSize() // 1498966 val atLeastToDelete = neededForUpdate - (totalDiskSpace - usedDiskSpace) check(totalDiskSpace > usedDiskSpace) part1DirectoriesStructure.dirsBySizes() .filter { (_, size) -> size >= atLeastToDelete } .minBy { (_, size) -> size } .apply { println("2nd part: $this") } }
0
Kotlin
0
0
161c36e3bccdcbee6291c8d8bacf860cd9a96bee
5,491
kotlin-advent-of-code-2022
Apache License 2.0
day16/src/main/kotlin/App.kt
ascheja
317,918,055
false
null
package net.sinceat.aoc2020.day16 import kotlin.properties.Delegates fun main() { run { val parseResult = parseInput("testinput.txt") println(parseResult.calculateScanningErrorRate()) } run { val parseResult = parseInput("input.txt") println(parseResult.calculateScanningErrorRate()) } run { val parseResult = parseInput("testinput2.txt").filterCompletelyInvalid() val assignedFields = parseResult.assignFields() println(assignedFields) } run { val parseResult = parseInput("input.txt").filterCompletelyInvalid() val assignedFields = parseResult.assignFields() println(assignedFields) val departureFields = assignedFields.filterKeys { it.startsWith("departure") } println(departureFields.values.map { index -> parseResult.myTicket[index].toLong() }.reduce { acc, i -> acc * i }) } } fun ParseResult.filterCompletelyInvalid(): ParseResult { return ParseResult( rules, myTicket, nearbyTickets.filter { ticket -> ticket.all { value -> rules.values.any { rule -> value in rule } } } ) } fun ParseResult.assignFields(): Map<String, Int> { val ticketColumns = myTicket.indices.map { index -> nearbyTickets.map { ticket -> ticket[index] } } val candidates = ticketColumns.map { columnValues -> rules.filter { (_, rule) -> columnValues.all { it in rule } }.map { it.key } } val alreadyUsed = mutableSetOf<String>() return candidates.withIndex().sortedBy { it.value.size }.associate { (index, values) -> val remaining = values.filterNot { it in alreadyUsed }.single() alreadyUsed.add(remaining) Pair(remaining, index) } } fun ParseResult.calculateScanningErrorRate(): Int { return nearbyTickets.map { ticket -> ticket.filterNot { value -> rules.values.any { rule -> value in rule } }.sum() }.sum() } data class Rule(val range1: IntRange, val range2: IntRange) { operator fun contains(value: Int) = value in range1 || value in range2 } data class ParseResult(val rules: Map<String, Rule>, val myTicket: List<Int>, val nearbyTickets: List<List<Int>>) private enum class FileSection { RULES, MY_TICKET, OTHER_TICKETS } fun parseInput(fileName: String): ParseResult { return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines -> var section = FileSection.RULES val rules = mutableMapOf<String, Rule>() var myTicket by Delegates.notNull<List<Int>>() val nearbyTickets = mutableListOf<List<Int>>() lines.filter(String::isNotBlank).forEach { line -> when (line) { "your ticket:" -> section = FileSection.MY_TICKET "nearby tickets:" -> section = FileSection.OTHER_TICKETS else -> if (section == FileSection.RULES) { val (fieldName, ruleRangesString) = line.split(":").map(String::trim) val rule = ruleRangesString.split(" or ") .map { ruleRangeString -> ruleRangeString.split("-") .map(String::toInt) .let { (start, endInclusive) -> start..endInclusive } }.let { (range1, range2) -> Rule(range1, range2) } rules[fieldName] = rule } else { val ticket = line.split(",").map(String::toInt) if (section == FileSection.MY_TICKET) { myTicket = ticket } else { nearbyTickets.add(ticket) } } } } ParseResult(rules, myTicket, nearbyTickets) } }
0
Kotlin
0
0
f115063875d4d79da32cbdd44ff688f9b418d25e
3,857
aoc2020
MIT License
src/Day05.kt
mvmlisb
572,859,923
false
{"Kotlin": 14994}
fun main() { val part1 = solve(false) val part2 = solve(true) println(part1) println(part2) } private fun solve(reverseFirstCrates: Boolean): String { val input = readInput("Day05_test") val lineIndexWithCrateStackNumbers = input.indexOfFirst { it.matches("^[\\s,1-9]*\$".toRegex()) } val stacks = createStacks(input, lineIndexWithCrateStackNumbers) input.drop(lineIndexWithCrateStackNumbers + 2).forEach { line -> val split = line.split(" ") val count = split[1].toInt() val from = split[3].toInt() val to = split[5].toInt() val targetStack = stacks[to - 1] repeat(count) { targetStack.addFirst(stacks[from - 1].removeFirst()) } if (reverseFirstCrates) targetStack.reverseFirst(count) } return stacks.joinToString("") { it.first().trim('[', ']') } } private fun createStacks(input: List<String>, lineIndexWithCrateStackNumbers: Int): List<ArrayDeque<String>> { val stackCrateCount = input[lineIndexWithCrateStackNumbers].split(" ").size val stacks = (0 until stackCrateCount).map { ArrayDeque<String>() } input.take(lineIndexWithCrateStackNumbers).forEach { line -> val crates = line.chunked(4).map(String::trim) (0 until stackCrateCount).forEach { stackIndex -> val crate = crates.getOrNull(stackIndex) if (!crate.isNullOrBlank()) stacks[stackIndex].addLast(crate) } } return stacks } private fun ArrayDeque<String>.reverseFirst(count: Int) { var startIndex = 0 while (startIndex < count / 2) { val temp = this[startIndex] this[startIndex] = this[count - startIndex - 1] this[count - startIndex - 1] = temp startIndex++ } }
0
Kotlin
0
0
648d594ec0d3b2e41a435b4473b6e6eb26e81833
1,797
advent_of_code_2022
Apache License 2.0
src/Day09.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import kotlin.math.abs fun main() { val direction = mapOf( "D" to (-1 to 0), "U" to (1 to 0), "L" to (0 to -1), "R" to (0 to 1) ) fun stepCloser(head: Int, tail: Int): Int = when { head > tail -> tail + 1 head < tail -> tail - 1 else -> tail } fun moveTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> { val (hx, hy) = head val (tx, ty) = tail if (abs(hx - tx) <= 1 && abs(hy - ty) <= 1) return tail // tail already touches head return stepCloser(hx, tx) to stepCloser(hy, ty) } fun part1(input: List<String>): Int { var head = 0 to 0 var tail = head val positions = mutableSetOf<Pair<Int, Int>>() positions += tail for (line in input) { val (c, dist) = line.split(" ") val dir = direction[c] ?: (0 to 0) for (i in 0 until dist.toInt()) { head = head.first + dir.first to head.second + dir.second tail = moveTail(head, tail) positions += tail } } return positions.size } fun part2(input: List<String>): Int { val knots = Array(10) { 0 to 0 } val positions = mutableSetOf<Pair<Int, Int>>() positions += knots for (line in input) { val (c, dist) = line.split(" ") val dir = direction[c] ?: (0 to 0) for (i in 0 until dist.toInt()) { knots[0] = knots[0].first + dir.first to knots[0].second + dir.second for (j in 1 until knots.size) { knots[j] = moveTail(knots[j - 1], knots[j]) } positions += knots.last() } } return positions.size } val test = readInput("Day09_test") println(part1(test)) println(part2(test)) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
1,994
Advent-Of-Code-2022
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2023/d08/Day08.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2023.d08 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.lcm import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.readLines data class State(val node: String, val i: Int) data class EndCondition(val solutions: Set<Int>, val modulo: Int, val minSolution: Int) class Solution(private val directions: String, private val network: Map<String, Pair<String, String>>) { fun State.next() = State( nextNode(node, i.toLong()), (i + 1) % directions.length ) private fun nextNode(node: String, i: Long): String = network[node]?.let { (l, r) -> if (directions[(i % directions.length).toInt()] == 'L') l else r } ?: throw RuntimeException("Node $node not found in network!") fun partOne(): Long { var node = "AAA" return generateSequence(0L) { it + 1 }.first { i -> node = nextNode(node, i) node == "ZZZ" } + 1 } private fun findEndCondition(start: String): EndCondition { // track first end node found var firstEndSteps: Int? = null var stepsTaken = 0 // r1 and r2 will intersect somewhere in the loop var r1 = State(start, 0).next() var r2 = State(start, 0).next().next() stepsTaken++ if (r1.node.endsWith('Z')) { firstEndSteps = stepsTaken } while (r1 != r2) { r1 = r1.next() r2 = r2.next().next() stepsTaken++ if (firstEndSteps == null && r1.node.endsWith('Z')) { firstEndSteps = stepsTaken } } // r1 and r2 will intersect at beginning of the loop // stepsToLoop is equal to length of path from start to beginning of loop var stepsToLoop = 0 r2 = State(start, 0) while (r1 != r2) { r1 = r1.next() r2 = r2.next() stepsToLoop++ stepsTaken++ if (firstEndSteps == null && r1.node.endsWith('Z')) { firstEndSteps = stepsTaken } } val loopStart = r1 // traverse through loop again to find its length // and find locations of end nodes val ends = mutableSetOf<Int>() var loopLength = 0 do { if (r1.node.endsWith('Z')) { ends.add(loopLength) } r1 = r1.next() loopLength++ } while (r1 != loopStart) return EndCondition( ends.mapTo(mutableSetOf()) { (it + stepsToLoop) % loopLength }, loopLength, firstEndSteps ?: throw RuntimeException("No end node found!") ) } fun partTwo(): Long { val conditions = network.keys .filter { it.endsWith('A') } .map(::findEndCondition) // observe all of them have single solution at exactly `modulo` steps... return conditions.map { it.modulo.toLong() }.lcm() } } fun main() = timed { val lines = (DATAPATH / "2023/day08.txt").readLines() val directions = lines.first() val network = mutableMapOf<String, Pair<String, String>>() lines.subList(2, lines.size).forEach { line -> network[line.substring(0..2)] = Pair(line.substring(7..9), line.substring(12..14)) } val solution = Solution(directions, network) println("Part one: ${solution.partOne()}") println("Part two: ${solution.partTwo()}") }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
3,513
advent-of-code
MIT License
src/Day15.kt
er453r
572,440,270
false
{"Kotlin": 69456}
import kotlin.math.max import kotlin.math.min fun main() { fun parseData(input: List<String>): List<Triple<Vector2d, Vector2d, Int>> = input.map { line -> line.ints().let { val sensor = Vector2d(it[0], it[1]) val beacon = Vector2d(it[2], it[3]) val range = (sensor - beacon).manhattan() Triple(sensor, beacon, range) } } fun part1(input: List<String>): Long { val coverage = mutableSetOf<Vector2d>() val data = parseData(input) val xMin = data.minOf { (sensor, _, range) -> sensor.x - range } val xMax = data.maxOf { (sensor, _, range) -> sensor.x + range } val targetY = if (input.size < 15) 10 else 2000000 for (x in xMin..xMax) { for ((sensor, _, range) in data) { val candidate = Vector2d(x, targetY) if ((sensor - candidate).manhattan() <= range) coverage += candidate } } coverage -= data.map { (_, beacon, _) -> beacon }.toSet() coverage -= data.map { (sensor, _, _) -> sensor }.toSet() return coverage.size.toLong() } fun part2(input: List<String>): Long { val data = parseData(input) val bounds = mutableSetOf<Vector2d>() val maxBound = 4000000 for ((sensor, _, range) in data) { val boundRange = range + 1 var dx = 0 for (y in max(sensor.y - boundRange, 0)..min(sensor.y, maxBound)) { if (sensor.x + dx <= maxBound) bounds += Vector2d(sensor.x + dx, y) if (sensor.x - dx >= 0) bounds += Vector2d(sensor.x - dx, y) dx++ } dx-- for (y in max(sensor.y + 1, 0)..min(sensor.y + boundRange, maxBound)) { if (sensor.x + dx <= maxBound) bounds += Vector2d(sensor.x + dx, y) if (sensor.x - dx >= 0) bounds += Vector2d(sensor.x - dx, y) dx++ } } for (bound in bounds.filter { it.x in (0..maxBound) && it.y in (0..maxBound) }) { if (data.count { (sensor, _, range) -> (sensor - bound).manhattan() <= range } == 0) { return bound.x * 4000000L + bound.y } } return -1 } test( day = 15, testTarget1 = 26, testTarget2 = 56000011, part1 = ::part1, part2 = ::part2, ) }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
2,538
aoc2022
Apache License 2.0
src/day16/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day16 import day02.cartesian import day06.main import readInput fun main() { val format = """Valve ([A-Z]+) has flow rate=(\d+); tunnels? leads? to valves? ([A-Z, ]+)""".toRegex() data class Valve(val id: String, val flow: Int, val conn: List<String>) fun parse(input: List<String>) = input.map { format.matchEntire(it)!!.destructured.let { (valve, flow, conn) -> Valve( valve, flow.toInt(), conn.split(", ") ) } }.associateBy { it.id } fun movementCostMap(input: Map<String, Valve>, movementCost: Int = 1) = buildMap<Pair<String, String>, Int> { input.values.forEach { from -> from.conn.forEach { to -> this[from.id to to] = movementCost } } val explore = input.keys.cartesian().toMutableSet() explore.removeIf { it.first == it.second } while (explore.isNotEmpty()) { entries.forEach { (tunnel, currentCost) -> val (from, to) = tunnel input.getValue(to).conn.forEach { val existing = this[(from to it)] val costToReach = currentCost + movementCost if (existing == null || existing > costToReach) { this[(from to it)] = costToReach } } } explore.removeAll(this.keys) } } fun part1(input: Map<String, Valve>) = movementCostMap(input).let { cost -> val actionableValves = input.values.filter { it.flow > 0 }.map { it.id } val activationCost = actionableValves.let { it.cartesian().filter { it.first != it.second }.associateWith { cost[it]!! + 1 } .plus(it.associate { ("AA" to it) to cost["AA" to it]!! + 1 }) } data class EscapePlan( val valveToCheck: List<String> = actionableValves, val current: String = "AA", val releasedPressure: Int = 0, val time: Int = 0 ) : Iterable<EscapePlan> { override fun iterator() = iterator { yield(this@EscapePlan) valveToCheck.takeIf { it.isNotEmpty() }?.map { valve -> val act = activationCost[current to valve]!! val newTime = time + act copy( valveToCheck = valveToCheck - valve, current = valve, releasedPressure = releasedPressure + (30 - newTime) * input[valve]!!.flow, time = newTime ) }?.filter { it.time < 31 }?.forEach { yieldAll(it) } } } EscapePlan().asSequence().filter { it.time < 30 }.map { it.releasedPressure }.max() } fun part2(input: Map<String, Valve>): Any { val actionableValves = input.values.filter { it.flow > 0 }.map { it.id }.toSet() val cost = movementCostMap(input) val activationCost = actionableValves.let { it.cartesian().filter { it.first != it.second }.associateWith { cost[it]!! + 1 } .plus(it.associate { ("AA" to it) to cost["AA" to it]!! + 1 }) } val minMap = mutableMapOf<Set<String>, Int>().withDefault { Int.MAX_VALUE } data class NewEscapePlan( val valveToCheck: Set<String> = actionableValves, val current: String = "AA", val elephantCurrent: String = "AA", val releasedPressure: Int = 0, val time: Int = 0, val elephantTime: Int = 0 ) : Iterable<NewEscapePlan> { override fun iterator() = iterator { yield(this@NewEscapePlan) valveToCheck.takeIf { it.isNotEmpty() }?.flatMap { valve -> val newValveToCheck = valveToCheck - valve listOfNotNull( copy( valveToCheck = newValveToCheck, current = valve, elephantCurrent = elephantCurrent, releasedPressure = releasedPressure + (26 - (time + activationCost[current to valve]!!)) * input[valve]!!.flow, time = time + activationCost[current to valve]!!, elephantTime = elephantTime ).takeIf { maxOf(it.time, it.elephantTime) <= minMap.getValue(newValveToCheck) } ?.also { minMap[newValveToCheck] = maxOf(it.time, it.elephantTime) }, copy( valveToCheck = newValveToCheck, current = current, elephantCurrent = valve, releasedPressure = releasedPressure + (26 - (elephantTime + activationCost[elephantCurrent to valve]!!)) * input[valve]!!.flow, time = time, elephantTime = elephantTime + activationCost[elephantCurrent to valve]!! ).takeIf { maxOf(it.time, it.elephantTime) <= minMap.getValue(newValveToCheck) } ?.also { minMap[newValveToCheck] = maxOf(it.time, it.elephantTime) } ) }?.filter { it.time < 26 && it.elephantTime < 26 }?.sortedByDescending { it.releasedPressure } ?.forEach { yieldAll(it) } } } return NewEscapePlan().asSequence().map { it.releasedPressure }.max() } val input = parse(readInput(::main.javaClass.packageName)) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
5,768
AOC2022
Apache License 2.0
src/main/kotlin/g2801_2900/s2812_find_the_safest_path_in_a_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2801_2900.s2812_find_the_safest_path_in_a_grid // #Medium #Array #Breadth_First_Search #Binary_Search #Matrix #Union_Find // #2023_12_06_Time_902_ms_(100.00%)_Space_89.4_MB_(100.00%) import java.util.LinkedList import java.util.Queue import kotlin.math.min class Solution { fun maximumSafenessFactor(grid: List<List<Int>>): Int { val n = grid.size if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return 0 val cost = Array(n) { IntArray(n) } for (v in cost) v.fill(Int.MAX_VALUE) bfs(cost, grid, n) var l = 1 var r = n * n var ans = 0 while (l <= r) { val mid = (r - l) / 2 + l if (possible(0, 0, cost, mid, n, Array(n) { BooleanArray(n) })) { ans = mid l = mid + 1 } else { r = mid - 1 } } return ans } private fun possible( i: Int, j: Int, cost: Array<IntArray>, mid: Int, n: Int, visited: Array<BooleanArray> ): Boolean { if (i < 0 || j < 0 || i >= n || j >= n) return false if (cost[i][j] == Int.MAX_VALUE || cost[i][j] < mid) return false if (i == n - 1 && j == n - 1) return true if (visited[i][j]) return false visited[i][j] = true val dir = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1)) var ans = false for (v in dir) { val ii = i + v[0] val jj = j + v[1] ans = ans or possible(ii, jj, cost, mid, n, visited) if (ans) return true } return ans } private fun bfs(cost: Array<IntArray>, grid: List<List<Int>>, n: Int) { val q: Queue<IntArray> = LinkedList() val visited = Array(n) { BooleanArray(n) } for (i in grid.indices) { for (j in grid.indices) { if (grid[i][j] == 1) { q.add(intArrayOf(i, j)) visited[i][j] = true } } } var level = 1 val dir = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1)) while (q.isNotEmpty()) { val len = q.size for (i in 0 until len) { val v = q.poll() for (`val` in dir) { val ii = v[0] + `val`[0] val jj = v[1] + `val`[1] if (isValid(ii, jj, n) && !visited[ii][jj]) { q.add(intArrayOf(ii, jj)) cost[ii][jj] = min(cost[ii][jj].toDouble(), level.toDouble()).toInt() visited[ii][jj] = true } } } level++ } } private fun isValid(i: Int, j: Int, n: Int): Boolean { return i >= 0 && j >= 0 && i < n && j < n } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,939
LeetCode-in-Kotlin
MIT License
src/main/kotlin/days/Day13.kt
VictorWinberg
433,748,855
false
{"Kotlin": 26228}
package days class Day13 : Day(13) { private fun parseInput(): Pair<List<Pair<Int, Int>>, List<Pair<String, Int>>> { var input = inputString.split("\n\n")[0].split("\n").map { Pair(it.split(",")[0].toInt(), it.split(",")[1].toInt()) } val instructions = inputString.split("\n\n")[1].split("\n").map { Pair(it.split("=")[0], it.split("=")[1].toInt()) } return Pair(input, instructions) } override fun partOne(): Any { val (input, instructions) = parseInput() val output = foldPaper(input, instructions[0]) return output.size } override fun partTwo(): Any { val (input, instructions) = parseInput() var output: List<Pair<Int, Int>> = input instructions.forEach { instruction -> output = foldPaper(output, instruction) } var size = Pair(output.maxOfOrNull { it.first }!!, output.maxOfOrNull { it.second }!!) return "\n" + (0..size.second).joinToString("\n") { y -> (0..size.first).joinToString("") { x -> if (output.contains(Pair(x, y))) "#" else "." } } } private fun foldPaper( input: List<Pair<Int, Int>>, instruction: Pair<String, Int> ) = input.fold<Pair<Int, Int>, List<Pair<Int, Int>>>(listOf()) { acc, (x, y) -> when (instruction.first) { "fold along x" -> if (instruction.second == x) acc else acc + Pair( if (x > instruction.second) 2 * instruction.second - x else x, y ) "fold along y" -> if (instruction.second == y) acc else acc + Pair( x, if (y > instruction.second) 2 * instruction.second - y else y ) else -> throw Error("Missing instruction") } }.toSet().toList() }
0
Kotlin
0
0
d61c76eb431fa7b7b66be5b8549d4685a8dd86da
1,857
advent-of-code-kotlin
Creative Commons Zero v1.0 Universal
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions45.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import com.qiaoyuang.algorithm.round0.exchange fun test45() { printlnResult(intArrayOf(3, 32, 321)) printlnResult(intArrayOf(111, 123, 321)) } /** * Questions 45: Give an IntArray, append all integer and find the smallest number that appended */ private fun findSmallestNumber(array: IntArray): String { require(array.isNotEmpty()) { "The array can't be empty" } array.quickSortByQuestions45() return buildString { array.forEach { append(it) } } } private object MyComparator : Comparator<Int> { override fun compare(a: Int, b: Int): Int { val aStr = a.toString() val bStr = b.toString() var aIndex = 0 var bIndex = 0 do { val aCurrent = aStr[aIndex++].digitToInt() val bCurrent = bStr[bIndex++].digitToInt() if (aCurrent == bCurrent) { if (aIndex == aStr.length && bIndex != bStr.length) aIndex = 0 if (aIndex != aStr.length && bIndex == bStr.length) bIndex = 0 continue } else return aCurrent - bCurrent } while (aIndex < aStr.length && bIndex < bStr.length) return 0 } } private fun IntArray.quickSortByQuestions45() { quickSort(0, this.size - 1, MyComparator) } private fun IntArray.quickSort(low: Int, height: Int, comparator: Comparator<Int>) { if (height <= low) return val mid = partition(low, height, comparator) quickSort(low, mid - 1, comparator) quickSort(mid + 1, height, comparator) } private fun IntArray.partition(low: Int, height: Int, comparator: Comparator<Int>): Int { var i = low var j = height + 1 while (true) { while (comparator.compare(this[++i], this[low]) < 0) if (i == height) break while (comparator.compare(this[low], this[--j]) < 0) if (j == low) break if (i >= j) break exchange(i, j) } exchange(low, j) return j } private fun printlnResult(array: IntArray) = println("Give the Array: ${array.toList()}, appended all of the integers, the smallest number is: ${findSmallestNumber(array)}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,242
Algorithm
Apache License 2.0
src/day04/Day04.kt
tobihein
569,448,315
false
{"Kotlin": 58721}
package day04 import readInput class Day04 { fun part1(): Int { val readInput = readInput("day04/input") return part1(readInput) } fun part2(): Int { val readInput = readInput("day04/input") return part2(readInput) } fun part1(input: List<String>): Int = input.map { parse(it) }.filter { overlappedComplete(it) }.count() fun part2(input: List<String>): Int = input.map { parse(it) }.filter { overlapped(it) }.count() private fun parse(input: String): Pair<Pair<Int, Int>, Pair<Int, Int>> { val tokens = input.split(",", "-") return Pair(Pair(tokens[0].toInt(), tokens[1].toInt()), Pair(tokens[2].toInt(), tokens[3].toInt())) } private fun overlappedComplete(input: Pair<Pair<Int, Int>, Pair<Int, Int>>): Boolean { val first = input.first val second = input.second return isIn(first, second) || isIn(second, first) } private fun overlapped(input: Pair<Pair<Int, Int>, Pair<Int, Int>>): Boolean { val first = input.first val second = input.second return (between(second.first, first) || between(second.second, first) || (between( first.first, second ) || between(first.second, second))) } private fun between(number: Int, range: Pair<Int, Int>): Boolean { return (number in range.first..range.second) } private fun isIn(first: Pair<Int, Int>, second: Pair<Int, Int>): Boolean { return first.first <= second.first && first.second >= second.second } }
0
Kotlin
0
0
af8d851702e633eb8ff4020011f762156bfc136b
1,582
adventofcode-2022
Apache License 2.0
src/main/kotlin/pl/mrugacz95/aoc/day24/day24.kt
mrugacz95
317,354,321
false
null
package pl.mrugacz95.aoc.day24 import pl.mrugacz95.aoc.day19.first operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> { return Pair(first + other.first, second + other.second) } enum class Direction(val delta: Pair<Int, Int>) { E(Pair(+1, 0)), SE(Pair(0, 1)), SW(Pair(-1, 1)), W(Pair(-1, 0)), NW(Pair(0, -1)), NE(Pair(1, -1)); companion object { fun fromString(direction: String): Direction { return when (direction) { "e" -> E "se" -> SE "sw" -> SW "w" -> W "nw" -> NW "ne" -> NE else -> throw RuntimeException("Unknown direction : $direction") } } } } fun getInitialState(paths: List<List<Direction>>): Set<Pair<Int, Int>> { val floor = mutableSetOf<Pair<Int, Int>>() // only black tiles for (path in paths) { var tile = Pair(0, 0) for (dir in path) { tile += dir.delta } if (tile in floor) { floor.remove(tile) } else { floor.add(tile) } } return floor } fun part1(paths: List<List<Direction>>): Int { return getInitialState(paths).size } fun countNeighbours(pos: Pair<Int, Int>, floor: Set<Pair<Int, Int>>): Int { var counter = 0 for (n in Direction.values()) { if (pos + n.delta in floor) { counter += 1 } } return counter } fun getBounds(floor: Set<Pair<Int, Int>>): Sequence<Pair<Int, Int>> = sequence { val qValues = floor.map { it.first } val minQ = qValues.minOrNull()!! val maxQ = qValues.maxOrNull()!! val rValues = floor.map { it.second } val minR = rValues.minOrNull()!! val maxR = rValues.maxOrNull()!! for (q in minQ - 1..maxQ + 1) { for (r in minR - 1..maxR + 1) { yield(Pair(q, r)) } } } fun part2(paths: List<List<Direction>>): Int { var state = getInitialState(paths) for (day in 1..100) { val newState = mutableSetOf<Pair<Int, Int>>() for (tile in getBounds(state)) { val isBlack = tile in state when (countNeighbours(tile, state)) { 1 -> if(isBlack) newState.add(tile) 2 -> newState.add(tile) else -> { } } } state = newState } return state.size } fun main() { val paths = {}::class.java.getResource("/day24.in") .readText() .split("\n") .map { path -> "e|se|sw|w|nw|ne".toRegex() .findAll(path) .map { it.groupValues[0] } .map { Direction.fromString(it) } .toList() } println("Answer part 1: ${part1(paths)}") println("Answer part 2: ${part2(paths)}") }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
2,862
advent-of-code-2020
Do What The F*ck You Want To Public License
src/main/kotlin/biz/koziolek/adventofcode/year2021/day03/day3.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day03 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val gammaRate = calculateGammaRate(lines) val epsilonRate = calculateEpsilonRate(lines) println("Gamma rate: $gammaRate (${gammaRate.toString(2)})") println("Epsilon rate: $epsilonRate (${epsilonRate.toString(2)})") println("Power consumption: ${calculatePowerConsumption(lines)}") println() val oxygenGeneratorRating = calculateOxygenGeneratorRating(lines) val co2ScrubberRating = calculateCO2ScrubberRating(lines) println("Oxygen generator rating: $oxygenGeneratorRating (${oxygenGeneratorRating.toString(2)})") println("CO2 scrubber rating: $co2ScrubberRating (${co2ScrubberRating.toString(2)})") println("Life support rating: ${calculateLifeSupportRating(lines)}") } fun calculatePowerConsumption(lines: List<String>): Int { val epsilonRate = calculateEpsilonRate(lines) val gammaRate = calculateGammaRate(lines) return epsilonRate * gammaRate } fun calculateGammaRate(lines: List<String>): Int { val mostCommonBits = getMostCommonBits(lines) return mostCommonBits.toInt(2) } fun calculateEpsilonRate(lines: List<String>): Int { val leastCommonBits = getLeastCommonBits(lines) return leastCommonBits.toInt(2) } fun calculateLifeSupportRating(lines: List<String>): Int { val oxygenGeneratorRating = calculateOxygenGeneratorRating(lines) val co2ScrubberRating = calculateCO2ScrubberRating(lines) return oxygenGeneratorRating * co2ScrubberRating } fun calculateOxygenGeneratorRating(lines: List<String>): Int { val theLine = findLine(lines, ::getMostCommonBits) return theLine.toInt(2) } fun calculateCO2ScrubberRating(lines: List<String>): Int { val theLine = findLine(lines, ::getLeastCommonBits) return theLine.toInt(2) } private fun findLine(lines: List<String>, bitCriteria: (List<String>) -> String): String { var currentIndex = 0 var currentLines = lines val bitCount = getBitCount(lines) while (currentLines.size > 1) { check(currentIndex < bitCount) { "No more bits to check" } val mostCommonBits = bitCriteria(currentLines) currentLines = currentLines.filter { it[currentIndex] == mostCommonBits[currentIndex] } currentIndex++ } check(currentLines.isNotEmpty()) { "No lines left" } return currentLines[0] } private fun getMostCommonBits(lines: List<String>): String { val bitCount = getBitCount(lines) val initialAcc = MutableList(bitCount) { 0 } val oneCounts = lines .fold(initialAcc) { acc, line -> for ((i, c) in line.withIndex()) { if (c == '1') { acc[i] = acc[i].inc() } } acc } val totalCount = lines.size return oneCounts.fold("") { acc, oneCount -> val zeroCount = totalCount - oneCount acc + if (oneCount >= zeroCount) "1" else "0" } } private fun getLeastCommonBits(lines: List<String>): String { val mostCommonBits = getMostCommonBits(lines) return mostCommonBits.fold("") { acc, c -> acc + if (c == '1') "0" else "1" } } private fun getBitCount(lines: List<String>) = lines[0].length
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
3,373
advent-of-code
MIT License
src/Day09.kt
buongarzoni
572,991,996
false
{"Kotlin": 26251}
import java.awt.Point import kotlin.math.sign fun solveDay09() { val input = readInput("Day09") val part1 = solve(input, (1 .. 2).map { Point(1, 1) }) println("Part 1 : $part1") val part2 = solve(input, (1 .. 10).map { Point(1, 1) }) println("Part 2 : $part2") } private fun solve(input: List<String>, points: List<Point>): Int { val visitedPositions = mutableSetOf<Pair<Int, Int>>() input.forEach { line -> val (direction, moves) = line.split(" ") for (move in 0 until moves.toInt()) { points.moveHead(direction) points.forEachIndexed { index, point -> if (index != 0) { val leading = points[index - 1] point.follow(leading) if (index == points.lastIndex) { visitedPositions.add(point.toPair()) } } } } } return visitedPositions.size } private fun List<Point>.moveHead(direction: String) { when (direction) { "R" -> first().moveRight() "L" -> first().moveLeft() "U" -> first().moveUp() "D" -> first().moveDown() } } private fun Point.follow(other: Point) { if (distance(other) >= 2) { translate((other.x - x).sign, (other.y - y).sign) } } private fun Point.moveRight() = translate(1, 0) private fun Point.moveLeft() = translate(-1, 0) private fun Point.moveUp() = translate(0, 1) private fun Point.moveDown() = translate(0, -1) private fun Point.toPair() = x to y
0
Kotlin
0
0
96aadef37d79bcd9880dbc540e36984fb0f83ce0
1,557
AoC-2022
Apache License 2.0
src/day15/Day15.kt
palpfiction
572,688,778
false
{"Kotlin": 38770}
package day15 import readInput import kotlin.math.abs data class Coordinate(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } infix fun Coordinate.distanceTo(other: Coordinate) = abs(this.x - other.x) + abs(this.y - other.y) sealed class Object(val coordinate: Coordinate) { infix fun distanceTo(other: Object) = this.coordinate distanceTo other.coordinate override fun toString() = coordinate.toString() } class Sensor(coordinate: Coordinate, private val closestBeacon: Beacon) : Object(coordinate) { fun covers(coordinate: Coordinate) = this.coordinate distanceTo coordinate <= this distanceTo this.closestBeacon fun minColumnCovered(row: Int) = this.coordinate.x - abs(this.distanceTo(this.closestBeacon) - abs(row - coordinate.y)) fun maxColumnCovered(row: Int) = this.coordinate.x + abs(this.distanceTo(this.closestBeacon) - abs(row - coordinate.y)) } class Beacon(coordinate: Coordinate) : Object(coordinate) typealias Grid = Map<Int, List<Object>> fun emptyGrid() = mapOf<Int, List<Object>>() fun main() { val itemRegex = """.* x=(.+), y=(.+)""".toRegex() fun parseCoordinates(input: String): Coordinate { assert(itemRegex.matches(input)) val (_, x, y) = itemRegex.matchEntire(input)!!.groupValues return Coordinate(x.toInt(), y.toInt()) } fun parseSensor(input: String, closestBeacon: Beacon) = Sensor(parseCoordinates(input), closestBeacon) fun parseBeacon(input: String) = Beacon(parseCoordinates(input)) fun parseLine(input: String): Pair<Sensor, Beacon> { val (sensorFragment, beaconFragment) = input.split(":") val beacon = parseBeacon(beaconFragment) return parseSensor(sensorFragment, beacon) to beacon } operator fun Grid.plus(obj: Object): Grid = this.plus( obj.coordinate.y to (this[obj.coordinate.y]?.plus(obj) ?: listOf(obj)) ) fun parseGrid(input: List<String>) = input .map { parseLine(it) } .fold(emptyGrid()) { grid, (sensor, beacon) -> grid.plus(sensor).plus(beacon) } fun Coordinate.isCoveredBySensor(sensors: List<Sensor>) = sensors.find { it.covers(this) } fun part1(input: List<String>): Int { val row = 2000000 val grid = parseGrid(input) val sensors = grid .map { it.value } .flatten() .filterIsInstance<Sensor>() val beacons = grid .map { it.value } .flatten() .filterIsInstance<Beacon>() val minX = sensors.minOf { it.minColumnCovered(row) } val maxX = sensors.maxOf { it.maxColumnCovered(row) } var count = 0 for (x in minX..maxX) { val coordinate = Coordinate(x, row) if (coordinate.isCoveredBySensor(sensors) != null && sensors.find { it.coordinate == coordinate } == null && beacons.find { it.coordinate == coordinate } == null ) { count++ } } return count } fun part2(input: List<String>): Long { val max = 4_000_000 val grid = parseGrid(input) val sensors = grid .map { it.value } .flatten() .filterIsInstance<Sensor>() for (row in 0..max) { var column = 0 while (column <= max) { val coordinate = Coordinate(column, row) val sensor = coordinate.isCoveredBySensor(sensors) ?: return coordinate.x.toLong() * 4_000_000 + coordinate.y.toLong() // we skip until the coordinate that sensor no longer covers (rest is covered) column = sensor.maxColumnCovered(row) + 1 } } throw Error() } val testInput = readInput("/day15/Day15_test") // println(part1(testInput)) //println(part2(testInput)) //check(part1(testInput) == 2) //check(part2(testInput) == 4) val input = readInput("/day15/Day15") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7
4,110
advent-of-code
Apache License 2.0
src/main/java/challenges/cracking_coding_interview/arrays_strings/PalindromePermutation.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.arrays_strings /* Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. EXAMPLE Input: Tact Coa Output: True (permutations: "taco cat", "atco eta", etc.) */ /* Given a string, determine if a permutation of the string could form a palindrome. For example, "code" -> False, "aab" -> True, "carerac" -> True. Reference: https://github.com/cherryljr/LeetCode/blob/master/Palindrome%20Permutation.java */ /** * If a string with an even length is a palindrome, every character in the string must always occur an even number of times. * If the string with an odd length is a palindrome, every character except one of the characters must always occur an even number of times. * Thus, in case of a palindrome, the number of characters with odd number of occurrences can't exceed 1 * (1 in case of odd length and 0 in case of even length). */ /** * Approach 1: HashMap * Algorithm: * From the discussion above, we know that to solve the given problem, * we need to count the number of characters with odd number of occurrences in the given string s. * To do so, we can also make use of a hashmap. This map takes the form (character_i, number of occurrences of character_i). * * We traverse over the given string s. * For every new character found in s, we create a new entry in the map for this character with the number of occurrences as 1. * Whenever we find the same character again, we update the number of occurrences appropriately. * * At the end, we traverse over the map created and find the number of characters with odd number of occurrences. * If this count happens to exceed 1 at any step, we conclude that a palindromic permutation isn't possible for the string s. * But, if we can reach the end of the string with count lesser than 2, we conclude that a palindromic permutation is possible for s. * * Complexity Analysis * Time complexity : O(n). * We traverse over the given string s with n characters once. * We also traverse over the map which can grow up to a size of n in case all characters in s are distinct. * Space complexity : O(n). The hashmap can grow up to a size of n, in case all the characters in s are distinct. */ private object Solution1 { fun solve(s: String): Boolean { val map = hashMapOf<Char, Int>() for (i in s.indices) { map[s[i]] = map.getOrDefault(s[i], 0) + 1 } var count = 0 for (key in map.keys) { count += map[key]!! % 2 } return count <= 1 } @JvmStatic fun main(args: Array<String>) { println(solve("eye")) // true println(solve("carerac")) // true println(solve("taco cat")) // false println(solve("atco eta")) // false println(solve("atco cta")) // false println(solve("taco cate")) // false println(solve("code")) // false } } /** * Approach 2: HashSet * Algorithm * A modification of the last approach could be by making use of a set for keeping track of * the number of elements with odd number of occurrences in s. * For doing this, we traverse over the characters of the string s. * Whenever the number of occurrences of a character becomes odd, we put its entry in the set. * Later on, if we find the same element again, lead to its number of occurrences as even, * we remove its entry from the set. * Thus, if the element occurs again(indicating an odd number of occurrences), its entry won't exist in the set. * * Based on this idea, when we find a character in the string s that isn't present in the set * (indicating an odd number of occurrences currently for this character), we put its corresponding entry in the set. * If we find a character that is already present in the set * (indicating an even number of occurrences currently for this character), we remove its corresponding entry from the set. * * At the end, the size of set indicates the number of elements with odd number of occurrences in s. * If it is lesser than 2, a palindromic permutation of the string s is possible, otherwise not. * * Complexity Analysis * Time complexity : O(n). We traverse over the string s of length n once only. * Space complexity : O(n). The set can grow upto a maximum size of n in case of all distinct elements. */ private object Solution2 { fun solve(s: String): Boolean { val set: MutableSet<Char> = HashSet() for (i in s.indices) { if (!set.add(s[i])) set.remove(s[i]) } return set.size <= 1 } @JvmStatic fun main(args: Array<String>) { println(solve("eye")) // true println(solve("carerac")) // true println(solve("taco cat")) // false println(solve("atco eta")) // false println(solve("atco cta")) // false println(solve("taco cate")) // false println(solve("code")) // false } } /** * Approach 3: Using Array instead of Set * Algorithm * We traverse over s and update the number of occurrences of the character just encountered in the map (an array). * But, whenever we update any entry in map, we also check if its value becomes even or odd. * We start of with a count value of 0. * If the value of the entry just updated in map happens to be odd, * we increment the value of count to indicate that one more character with odd number of occurrences has been found. * But, if this entry happens to be even, * we decrement the value of count to indicate that the number of characters with odd number of occurrences has reduced by one. * * But, in this case, we need to traverse till the end of the string to determine the final result, * because, even if the number of elements with odd number of occurrences may seem very large at the current moment, * but their occurrences could turn out to be even when we traverse further in the string s. * At the end, we again check if the value of count is lesser than 2 to conclude that a palindromic permutation is possible for the string s. * * Complexity Analysis * Time complexity : O(n). We traverse over the string s of length n once only. * Space complexity : O(1). An array of constant size(128) is used. */ private object Solution3 { fun solve(s: String): Boolean { val array = IntArray(128) var count = 0 for (i in s.indices) { array[s[i].toInt()]++ if (array[s[i].toInt()] % 2 == 0) { count-- continue } count++ } return count <= 1 } @JvmStatic fun main(args: Array<String>) { println(solve("eye")) // true println(solve("carerac")) // true println(solve("taco cat")) // false println(solve("atco eta")) // false println(solve("atco cta")) // false println(solve("taco cate")) // false println(solve("code")) // false } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
7,207
CodingChallenges
Apache License 2.0
src/Day03.kt
a2xchip
573,197,744
false
{"Kotlin": 37206}
private fun String.toSetOfItemsInside() = this.toCharArray().toSet() private fun List<Set<Char>>.findCommonItem() = this.fold(this.first()) { acc, chars -> acc.intersect(chars) }.first() private fun Char.calculatePriority() = if (this.isUpperCase()) { this - 'A' + 27 } else { this - 'a' + 1 } fun main() { fun part1(input: List<String>): Int { // The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the // items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. // The only item type that appears in both compartments is lowercase p. // The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. // The only item type that appears in both compartments is uppercase L. // The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; // the only common item type is uppercase P. // The fourth rucksack's compartments only share item type v. // The fifth rucksack's compartments only share item type t. // The sixth rucksack's compartments only share item type s. return input.sumOf { line -> val itemsInCompartments = line.chunked(line.length / 2).map { it.toSetOfItemsInside() } itemsInCompartments.findCommonItem().calculatePriority() } } fun part2(input: List<String>): Int { return input.map { it.toSetOfItemsInside() }.chunked(3).sumOf { triplet -> triplet.findCommonItem().calculatePriority() } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) println("Test ${part1(testInput)}") val input = readInput("Day03") println("Part 1 - ${part1(input)}") println("Part 2 - ${part2(input)}") check(part1(input) == 7446) check(part2(input) == 2646) }
0
Kotlin
0
2
19a97260db00f9e0c87cd06af515cb872d92f50b
1,889
kotlin-advent-of-code-22
Apache License 2.0
2022/Day24/problems.kt
moozzyk
317,429,068
false
{"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794}
import java.io.File import java.util.ArrayDeque import kotlin.math.* val EMPTY = 0 val WALL = 1 val UP = 2 val DOWN = 4 val LEFT = 8 val RIGHT = 16 data class State(val row: Int, val col: Int, val ticks: Int) fun main(args: Array<String>) { val lines = File(args[0]).readLines() println(problem1(lines)) println(problem2(lines)) } fun problem1(lines: List<String>): Int { var areas = mutableListOf(createArea(lines)) return findPath(areas, Pair(0, 1), Pair(lines.size - 1, lines[0].length - 2)) } fun problem2(lines: List<String>): Int { var areas = mutableListOf(createArea(lines)) val trip1 = findPath(areas, Pair(0, 1), Pair(lines.size - 1, lines[0].length - 2)) areas = mutableListOf(areas[trip1]) val trip2 = findPath(areas, Pair(lines.size - 1, lines[0].length - 2), Pair(0, 1)) areas = mutableListOf(areas[trip2]) val trip3 = findPath(areas, Pair(0, 1), Pair(lines.size - 1, lines[0].length - 2)) return trip1 + trip2 + trip3 } fun findPath( areas: MutableList<List<MutableList<Int>>>, start: Pair<Int, Int>, end: Pair<Int, Int> ): Int { var q = ArrayDeque<State>() q.add(State(start.first, start.second, 0)) var visited = mutableSetOf(q.first()) while (!q.isEmpty()) { var (row, col, ticks) = q.removeFirst() if (row == end.first && col == end.second) { return ticks - 1 } if (areas.size == ticks) { areas.add(tick(areas.last())) } val area = areas[ticks] for (newPos in listOf( Pair(row, col), Pair(row - 1, col), Pair(row + 1, col), Pair(row, col - 1), Pair(row, col + 1) )) { val (r, c) = newPos if (r >= 0 && r < area.size && area[r][c] == EMPTY) { val newState = State(r, c, ticks + 1) if (!visited.contains(newState)) { visited.add(newState) q.addLast(newState) } } } } throw Exception("No solutions found") } fun createArea(lines: List<String>): List<MutableList<Int>> { return lines.map { it.toCharArray() .map { when (it) { '.' -> EMPTY '#' -> WALL '^' -> UP 'v' -> DOWN '<' -> LEFT '>' -> RIGHT else -> throw Exception("Unexpected input") } } .toMutableList() } } fun tick(area: List<MutableList<Int>>): List<MutableList<Int>> { var newArea = area.map { it.map { if (it == WALL) WALL else EMPTY }.toMutableList() }.toList() for (row in 0 until area.size) { for (col in 0 until area[row].size) { if ((area[row][col] and RIGHT) != 0) { val c = if (area[row][col + 1] == WALL) 1 else col + 1 newArea[row][c] = newArea[row][c] or RIGHT } if ((area[row][col] and LEFT) != 0) { val c = if (area[row][col - 1] == WALL) area[row].size - 2 else col - 1 newArea[row][c] = newArea[row][c] or LEFT } if ((area[row][col] and UP) != 0) { val r = if (area[row - 1][col] == WALL) area.size - 2 else row - 1 newArea[r][col] = newArea[r][col] or UP } if ((area[row][col] and DOWN) != 0) { val r = if (area[row + 1][col] == WALL) 1 else row + 1 newArea[r][col] = newArea[r][col] or DOWN } } } return newArea } fun printArea(area: List<MutableList<Int>>) { for (row in area) { for (loc in row) { print( when (loc) { EMPTY -> ' ' WALL -> '#' UP -> '^' DOWN -> 'v' RIGHT -> '>' LEFT -> '<' else -> '*' } ) } println() } println() }
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
4,295
AdventOfCode
MIT License
src/Day13.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
data class Line(var s: String) { var pos = 0 val c: Char get() = s[pos] fun isDigit() = c.isDigit() fun closed() = pos == s.length operator fun inc(): Line { pos++ return this } fun addList() { var end = pos do { end++ } while (s[end].isDigit()) s = s.substring(0, pos) + "[" + s.substring(pos, end) + "]" + s.substring(end) //pos++ } fun nextInt(): Int { var end = pos do { end++ } while (s[end].isDigit()) return s.substring(pos, end).toInt().also { pos = end } } } fun smaller(s1: String, s2: String): Boolean { var (a, b) = listOf(Line(s1), Line(s2)) while (true) { if (a.closed()) return true else if (b.closed()) return false if (a.c == ']' && b.c != ']') return true else if (b.c == ']' && a.c != ']') return false else if (a.c == ']' && b.c == ']') { a++ b++ continue } if (a.c == '[' && b.isDigit()) b.addList() if (b.c == '[' && a.isDigit()) a.addList() if (a.c == ',' && b.c != ',' || a.c != ',' && b.c == ',') error("bad tokens ${a.c} ${b.c}") if (a.c == ',' && b.c == ',') { a++ b++ continue } if (a.c == '[' && b.c == '[') { a++ b++ continue } if (!a.isDigit() || !b.isDigit()) error("not digit ${a.c} ${b.c}") val (a1, b1) = listOf(a.nextInt(), b.nextInt()) if (a1 < b1) return true else if (a1 > b1) return false } } fun main() { fun part1(input: List<String>): Int { var sum = 0 // var test = Line("asf123,") // test++ // test++ // test++ // println(test.pos) // test.addList() // println(test.s) // println(test.pos) // test++ // println(test.nextInt()) // println(test.pos) input.chunked(3).forEachIndexed { index, strings -> if (smaller(strings[0], strings[1])) sum += index + 1 // else println(strings[0] + "-" + strings[1]) } return sum } fun part2(input: List<String>): Int { val myComparator = Comparator<String> { a, b -> if (smaller(a, b)) -1 else 1 } val list = input.filter { it.isNotBlank() }.toMutableList() list.add("[[2]]") list.add("[[6]]") val sorted = list.sortedWith(myComparator) val pos2 = sorted.indexOf("[[2]]") + 1 val pos6 = sorted.indexOf("[[6]]") + 1 return pos2 * pos6 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") println(part1(testInput)) check(part1(testInput) == 13) println(part2(testInput)) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
3,013
AoC-2022
Apache License 2.0
2017-kotlin/src/main/kotlin/com/morninghacks/aoc2017/Day03.kt
whaley
116,508,747
false
null
package com.morninghacks.aoc2017 import kotlin.math.roundToInt import kotlin.math.sqrt // let x be the target number // let y next highest perfect square derived from multiplying odd numbers after and including x // // let max distance = (square root of y) - 1 // let f(x) = max - ((y - x) % max) <--- this fails for numbers like 10, 27, or 33 // if f(x) >= min then f(x) max - f(x) fun manhattan(x: Int): Int { val y = nextOddPerfectSquareInclusive(x) val max = sqrt(y.toDouble()).roundToInt() - 1 val min = max / 2 val f = if (max == 0) 0 else max - ((y - x) % max) //for 33, f is 2, needs to be 4 return if (f < min) max - f else f } fun nextOddPerfectSquareInclusive(x: Int): Int { for (i in 1..x step 2) { val iSquared = Math.pow(i.toDouble(), 2.toDouble()).roundToInt() val nextSquared = Math.pow((i + 2).toDouble(), 2.toDouble()).roundToInt() if (x == iSquared) return x else if (x > iSquared && x < nextSquared) return nextSquared else continue } throw IllegalStateException() } fun main(args: Array<String>) { println(manhattan(325489)) println(createGridUntil(325489).values.max() ?: 0) } data class Point(val x: Int, val y: Int) fun createGridUntil(target: Int) : Map<Point,Int>{ val initial = Point(0, 0) val knownPointsAndScores = hashMapOf(initial to 1) var direction = Direction.RIGHT var currentPoint = initial var steps = 1 var stepsRemainingBeforeTurn = steps while ((knownPointsAndScores[currentPoint] ?: 0) < target) { if (stepsRemainingBeforeTurn == 0 && (direction == Direction.UP || direction == Direction.DOWN)) { direction = direction.nextDirection() steps++ stepsRemainingBeforeTurn = steps - 1 } else if (stepsRemainingBeforeTurn == 0) { direction = direction.nextDirection() stepsRemainingBeforeTurn = steps - 1 } else { stepsRemainingBeforeTurn-- } currentPoint = direction.nextPoint(currentPoint) val score: Int = knownPointsAndScores.keys.intersect(adjacentPoints(currentPoint)).sumBy { knownPointsAndScores[it] ?: 0 } knownPointsAndScores[currentPoint] = score } return knownPointsAndScores } enum class Direction { UP { override fun nextDirection(): Direction = LEFT override fun nextPoint(point: Point) = Point(point.x, point.y + 1) }, DOWN { override fun nextDirection(): Direction = RIGHT override fun nextPoint(point: Point) = Point(point.x, point.y - 1) }, LEFT { override fun nextDirection(): Direction = DOWN override fun nextPoint(point: Point) = Point(point.x - 1, point.y) }, RIGHT { override fun nextDirection(): Direction = UP override fun nextPoint(point: Point) = Point(point.x + 1, point.y) }; abstract fun nextDirection(): Direction abstract fun nextPoint(point: Point): Point } fun adjacentPoints(point: Point): Set<Point> { val adjacentPoints = hashSetOf<Point>() for (x in -1..1) { for (y in -1..1) { adjacentPoints.add(Point(point.x + x, point.y + y)) } } return adjacentPoints }
0
Kotlin
0
0
16ce3c9d6310b5faec06ff580bccabc7270c53a8
3,258
advent-of-code
MIT License
src/Day09.kt
jorander
571,715,475
false
{"Kotlin": 28471}
import kotlin.math.abs typealias Knot = Position2D private fun Knot.isCloseTo(other: Knot) = (this - other).run { abs(dx) <= 1 && abs(dy) <= 1 } fun main() { val day = "Day09" data class Simulation( val numberOfExtraKnots: Int = 0, val head: Knot = Knot(0, 0), val knots: List<Knot> = List(numberOfExtraKnots) { _ -> head }, val tail: Knot = head, val placesVisitedByTail: Set<Knot> = setOf(tail) ) { fun moveHead(direction: String): Simulation { val newHeadPosition = calculateNewHeadPosition(direction) val newKnotPositions = calculateKnotPositions(newHeadPosition) val newTailPosition = tail.calculateNewPosition(if (numberOfExtraKnots > 0) newKnotPositions.last() else newHeadPosition) return this.copy( head = newHeadPosition, knots = newKnotPositions, tail = newTailPosition, placesVisitedByTail = placesVisitedByTail + newTailPosition ) } private fun calculateNewHeadPosition(direction: String) = head + when (direction) { "U" -> Movement2D(0, 1) "L" -> Movement2D(-1, 0) "D" -> Movement2D(0, -1) "R" -> Movement2D(1, 0) else -> { throw IllegalArgumentException("Unknown input: $direction") } } private fun calculateKnotPositions(head: Knot) = knots.runningFold(head) { prev, tail -> tail.calculateNewPosition(prev) }.drop(1) private fun Knot.calculateNewPosition(head: Knot): Knot { val tail = this return if (tail.isCloseTo(head)) { tail } else { tail + Movement2D((head.x - tail.x).coerceIn(-1, 1), (head.y - tail.y).coerceIn(-1, 1)) } } } fun List<String>.simulate(simulation: Simulation) = this.flatMap { val (direction, steps) = it.split(" ") List(steps.toInt()) { _ -> direction } }.fold(simulation) { runningSimulation, direction -> runningSimulation.moveHead(direction) } fun part1(input: List<String>): Int { return input.simulate(Simulation()) .placesVisitedByTail.size } fun part2(input: List<String>): Int { return input.simulate(Simulation(numberOfExtraKnots = 8)) .placesVisitedByTail.size } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val testInput2 = readInput("${day}_test2") val input = readInput(day) check(part1(testInput) == 13) val result1 = part1(input) println(result1) check(result1 == 6090) check(part2(testInput) == 1) check(part2(testInput2) == 36) val result2 = part2(input) println(result2) check(result2 == 2566) }
0
Kotlin
0
0
1681218293cce611b2c0467924e4c0207f47e00c
2,963
advent-of-code-2022
Apache License 2.0
src/Day03.kt
Kaaveh
572,838,356
false
{"Kotlin": 13188}
val Char.priority get(): Int = when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("Wrong input! $this") } inline infix fun String.singleIntersect(other: String) = (toSet() intersect other.toSet()).single() inline infix fun Char.singleIntersect(other: String) = (setOf(this) intersect other.toSet()).single() private fun part1(input: List<String>): Int = input.sumOf { items -> val first = items.substring(0 until items.length / 2) val second = items.substring(items.length / 2) val common = first singleIntersect second common.priority } private fun part2(input: List<String>): Int = input.chunked(3).sumOf { elfGroup -> val (first, second, third) = elfGroup val common = first singleIntersect second singleIntersect third common.priority } fun main() { val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
9022f1a275e9c058655898b64c196f7a0a494b48
1,059
advent-of-code-kotlin-2022
Apache License 2.0
src/day24/Day24.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day24 import Coordinate import bfs import readInput import java.util.* const val day = "24" data class Board(val board: List<List<List<Char>>>) { val height = board.size val width = board.first().size fun print(location: Coordinate) { board.forEachIndexed { y, line -> line.forEachIndexed { x, chars -> when { x == location.x && y == location.y -> print("E") chars.isEmpty() -> print(".") chars.size == 1 -> print(chars.first()) else -> print(chars.size) } } println() } println() } fun Int.wrappedX(): Int { return when (this) { 0 -> width - 2 width - 1 -> 1 else -> this } } fun Int.wrappedY(): Int { return when (this) { 0 -> height - 2 height - 1 -> 1 else -> this } } fun isFree(coordinate: Coordinate): Boolean = coordinate.isIn(width, height) && board[coordinate.y][coordinate.x].isEmpty() } class BoardCache(initial: Board) { private val boardCache = mutableMapOf(0 to initial) fun getBoard(step: Int): Board { return boardCache.getOrPut(step) { getBoard(step - 1).run { val newBoard = List(height) { List(width) { mutableListOf<Char>() } } board.forEachIndexed { y, line -> line.forEachIndexed { x, chars -> chars.forEach { c -> when (c) { '^' -> newBoard[(y - 1).wrappedY()][x].add('^') '>' -> newBoard[y][(x + 1).wrappedX()].add('>') 'v' -> newBoard[(y + 1).wrappedY()][x].add('v') '<' -> newBoard[y][(x - 1).wrappedX()].add('<') '#' -> newBoard[y][x].add('#') } } } } Board(newBoard) } } } } val positionOffsets = listOf( Coordinate(0, 0), Coordinate(1, 0), Coordinate(-1, 0), Coordinate(0, 1), Coordinate(0, -1), ) data class State(val position: Coordinate, val stepCounter: Int) { fun nextPossibleStates(boardCache: BoardCache): List<State> { val nextBoard = boardCache.getBoard(stepCounter + 1) return positionOffsets .map { position + it } .filter { nextBoard.isFree(it) } .map { State(it, stepCounter + 1) } } fun print(boardCache: BoardCache) { boardCache.getBoard(stepCounter + 1).print(position) } } fun main() { fun findPath(boardCache: BoardCache, startState: State, targetLocation: Coordinate): State? { return bfs(startState, { position == targetLocation }) { nextPossibleStates(boardCache) } } fun List<String>.parseBoard(): Triple<Board, Coordinate, Coordinate> { val board = map { it.toCharArray().map { char -> listOf(char).filter { c -> c != '.' } } } val start = Coordinate(board.first().indexOfFirst { it.isEmpty() }, 0) val end = Coordinate(board.last().indexOfFirst { it.isEmpty() }, board.size - 1) return Triple(Board(board), start, end) } fun calculatePart1Score(input: List<String>): Int { val (initialBoard, start, end) = input.parseBoard() val boardCache = BoardCache(initialBoard) val startState = State(start, 0) return findPath(boardCache, startState, end)?.stepCounter ?: 0 } fun calculatePart2Score(input: List<String>): Int { val (initialBoard, start, end) = input.parseBoard() val boardCache = BoardCache(initialBoard) val path1 = findPath(boardCache, State(start, 0), end) ?: error("path 1 failed") val path2 = findPath(boardCache, path1, start) ?: error("path 2 failed") val path3 = findPath(boardCache, path2, end) ?: error("path 3 failed") return path3.stepCounter } // test if implementation meets criteria from the description, like: val testInput = readInput("/day$day/Day${day}_test") val input = readInput("/day$day/Day${day}") val part1TestPoints = calculatePart1Score(testInput) println("Part1 test points: $part1TestPoints") check(part1TestPoints == 18) val part1points = calculatePart1Score(input) println("Part1 points: $part1points") val part2TestPoints = calculatePart2Score(testInput) println("Part2 test points: $part2TestPoints") check(part2TestPoints == 54) val part2points = calculatePart2Score(input) println("Part2 points: $part2points") }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
4,790
advent-of-code-22-kotlin
Apache License 2.0
src/Day10.kt
cornz
572,867,092
false
{"Kotlin": 35639}
fun main() { fun runInstruction(cycleRegister: Triple<String, Int, Int>): Triple<String, Int, Int> { var input = cycleRegister.first return if (input == "noop") { cycleRegister.copy("", cycleRegister.second + 1, cycleRegister.third) } else if (input.startsWith("addx ")) { input = input.replace("addx", "add") cycleRegister.copy(input, cycleRegister.second + 1, cycleRegister.third) } else { val toAddToRegister = input.split(" ")[1].toInt() cycleRegister.copy("", cycleRegister.second + 1, cycleRegister.third + toAddToRegister) } } fun part1(input: List<String>): Int { var cycle = 0 var register = 1 val solution = mutableListOf<Int>() for (line in input) { var newInst: String var inst = Triple(line, cycle, register) var ret = runInstruction(inst) newInst = ret.first if (newInst.startsWith("add ")) { cycle = ret.second register = ret.third if ((cycle - 20).mod(40) == 0) { solution.add(register * cycle) } inst = Triple(newInst, cycle, register) ret = runInstruction(inst) } cycle = ret.second if ((cycle - 20).mod(40) == 0) { solution.add(register * cycle) } register = ret.third } return solution.sum() } fun part2(input: List<String>): Int { var cycle = 0 var register = 1 var solution = CharArray(40) { '.' } val solutions = mutableListOf<String>() var spritePosition = listOf(0, 1, 2) for (line in input) { if (spritePosition.contains(cycle)) { solution[cycle] = '#' } var newInst: String var inst = Triple(line, cycle, register) var ret = runInstruction(inst) newInst = ret.first if (newInst.startsWith("add ")) { cycle = ret.second register = ret.third spritePosition = listOf(register - 1, register, register + 1) if (cycle.mod(40) == 0) { solutions.add(String(solution)) solution = CharArray(40) { '.' } cycle = 0 } if (spritePosition.contains(cycle)) { solution[cycle] = '#' } inst = Triple(newInst, cycle, register) ret = runInstruction(inst) } cycle = ret.second register = ret.third spritePosition = listOf(register - 1, register, register + 1) if (cycle.mod(40) == 0) { solutions.add(String(solution)) solution = CharArray(40) { '.' } cycle = 0 } } for (solution in solutions) { System.out.println(solution) } return solution.size } // test if implementation meets criteria from the description, like: val testInput = readInput("input/Day10_test") check(part1(testInput) == 13140) //check(part2(testInput) == 1) val input = readInput("input/Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2800416ddccabc45ba8940fbff998ec777168551
3,413
aoc2022
Apache License 2.0
src/Year2022Day12.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
fun main() { data class Node( val i: Int, val j: Int, val char: Char, var distanceToEnd: Int = Int.MAX_VALUE, ) { val value = when (char) { 'S' -> 0 'E' -> 'z' - 'a' else -> char - 'a' } fun isCanMoveTo(other: Node) = other.value - value == 1 || value >= other.value } val directions = arrayOf( Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1), ) fun solve(lines: List<String>): List<List<Node>> { val G = lines.mapIndexed{ i, row -> row.mapIndexed { j, char -> Node(i, j, char) } } val queue = ArrayDeque<Pair<Node, Int>>() val end = G.asSequence().flatten().first { it.char == 'E' } end.distanceToEnd = 0 // BFS from end queue.addLast(Pair(end, 0)) while (queue.isNotEmpty()) { val (now, distanceToEnd) = queue.removeFirst() if (now.distanceToEnd != distanceToEnd) continue for ((di, dj) in directions) { G.getOrNull(now.i + di)?.getOrNull(now.j + dj)?.let { next -> if (next.isCanMoveTo(now) && next.distanceToEnd > now.distanceToEnd + 1) { next.distanceToEnd = now.distanceToEnd + 1 queue.addLast(Pair(next, next.distanceToEnd)) } } } } return G } fun part1(lines: List<String>): Int { return solve(lines).asSequence().flatten().first { it.char == 'S' }.distanceToEnd } fun part2(lines: List<String>): Int { return solve(lines).asSequence().flatten().filter { it.value == 0 }.minOf { it.distanceToEnd } } val testLines = readLines(true) assertEquals(31, part1(testLines)) assertEquals(29, part2(testLines)) val lines = readLines() println(part1(lines)) println(part2(lines)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
1,994
aoc-2022-in-kotlin
Apache License 2.0
2k23/aoc2k23/src/main/kotlin/09.kt
papey
225,420,936
false
{"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117}
package d09 import input.read fun main() { println("Part 1: ${part1(read("09.txt"))}") println("Part 2: ${part2(read("09.txt"))}") } fun part1(input: List<String>): Int = input .map { line -> line.split(" ") .map { it.toInt() } } .map { numbers -> val history: List<List<Int>> = mutableListOf(numbers.toMutableList()) // predict while (!history.last().all { it == 0 }) { val next = history.last().zip(history.last().subList(1, history.last().size)).map { it.second - it.first } history.addLast(next.toMutableList()) } // extrapolate: add 0 to list of 0 history.last().addLast(0) history.indices.reversed().drop(1).forEach { history[it].addLast(history[it + 1].last() + history[it].last()) } history }.sumOf { it.first().last() } fun part2(input: List<String>): Int = input .map { line -> line.split(" ") .map { it.toInt() } } .map { numbers -> val history: List<List<Int>> = mutableListOf(numbers.toMutableList()) // predict while (!history.last().all { it == 0 }) { val next = history.last().reversed().zip(history.last().reversed().subList(1, history.last().size)) .map { it.first - it.second } history.addLast(next.reversed().toMutableList()) } // extrapolate: add 0 to list of 0 history.last().addFirst(0) history.indices.reversed().drop(1).forEach { history[it].addFirst(history[it].first() - history[it + 1].first()) } history }.sumOf { it.first().first() }
0
Rust
0
3
cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5
1,722
aoc
The Unlicense
src/day12/Day12.kt
palpfiction
572,688,778
false
{"Kotlin": 38770}
package day12 import readInput import java.lang.IllegalArgumentException typealias Matrix<T> = MutableList<MutableList<T>> fun emptyMatrix(x: Int, y: Int) = MutableList(x) { MutableList<Square>(y) { Start } } fun <T> Matrix<T>.dimensions() = this.size to this[0].size fun <T> Matrix<T>.print() { val (rows, columns) = this.dimensions() for (j in 0 until columns) { for (i in 0 until rows) { print(this[i][j]) } println() } } data class Coordinate(val x: Int, val y: Int) sealed class Square(val height: Int) object Start : Square(1) { override fun toString(): String = "S" } object Destination : Square(26) { override fun toString(): String = "E" } class RegularSquare(height: Int) : Square(height) { override fun toString(): String = Char(height + 96).toString() } fun main() { fun dimensions(input: List<String>): Pair<Int, Int> = input[0].toCharArray().size to input.size fun parseMap(input: List<String>): Matrix<Square> { val (rows, columns) = dimensions(input) val map = emptyMatrix(rows, columns) input .forEachIndexed { y, line -> line.toCharArray() .forEachIndexed { x, height -> map[x][y] = when (height) { 'S' -> Start 'E' -> Destination else -> RegularSquare(height.code - 96) } } } return map } fun possibleSteps(current: Coordinate, map: Matrix<Square>): List<Coordinate> { return listOf( current.copy(x = current.x + 1), current.copy(x = current.x - 1), current.copy(y = current.y + 1), current.copy(y = current.y - 1) ) .filter { it.x in map.indices && it.y in map[0].indices } .filter { map[current.x][current.y].height <= map[it.x][it.y].height + 1 } } fun exploreSquare(coordinate: Coordinate, map: Matrix<Square>, paths: MutableMap<Coordinate, Int>): Coordinate { val possibleSteps = possibleSteps(coordinate, map) for (step in possibleSteps) { val currentDistance = paths.getOrDefault(step, Int.MAX_VALUE) val newDistance = paths.getOrDefault(coordinate, 0) + 1 if (newDistance < currentDistance) { paths[step] = newDistance } } paths.remove(coordinate) return paths.minBy { it.value }.key } fun getDestination(map: Matrix<Square>): Coordinate { for (i in map.indices) { for (j in map[0].indices) { if (map[i][j] is Destination) return Coordinate(i, j) } } throw IllegalArgumentException() } fun findShortest(start: Coordinate, map: Matrix<Square>, shouldStop: (Square) -> Boolean = { false }): Int { val paths = mutableMapOf<Coordinate, Int>() var current = start while (!shouldStop(map[current.x][current.y])) { current = exploreSquare(current, map, paths) } return paths.getValue(current) } fun part1(input: List<String>): Int = with(parseMap(input)) { findShortest(getDestination(this), this, shouldStop = { it is Start }) } fun part2(input: List<String>): Int = with(parseMap(input)) { findShortest(getDestination(this), this, shouldStop = { it.height == 1 }) } val testInput = readInput("/day12/Day12_test") println(part1(testInput)) println(part2(testInput)) //check(part1(testInput) == 2) //check(part2(testInput) == 4) val input = readInput("/day12/Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7
3,899
advent-of-code
Apache License 2.0
facebook/y2020/round2/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2020.round2 import java.util.* private fun solve(MOD: Int = 1_000_000_007, maxWeight: Int = 1_000_000_000): Int { val (n, m, events, k) = readInts() val edges = n * m + n val (x, y, ids, weights) = listOf(m to n, m to n, edges to events, maxWeight to events).map { (modulo, length) -> val array = readInts().toIntArray() + IntArray(length - k) { 0 } val (a, b, c) = readInts() for (i in k until length) { array[i] = ((a.toLong() * array[i - 2] + b.toLong() * array[i - 1] + c) % modulo).toInt() } array } val (short, long) = List(2) { List(n) { TreeSet<Long>() } } val main = TreeSet<Long>() val alter = LongArray(n) { -1L } val selected = LongArray(n) { -1L } fun isShort(cycle: Int, j: Int): Boolean { return x[cycle] <= j && j < y[cycle] } for (cycle in x.indices) { val (min, max) = listOf(x[cycle], y[cycle]).sorted() x[cycle] = min; y[cycle] = max for (j in 0 until m) { val id = cycle * m + j if (isShort(cycle, j)) { short[cycle].add(1L * edges + id) } else { long[cycle].add(1L * edges + id) } } if (short[cycle].isNotEmpty()) { alter[cycle] = short[cycle].last() main.add(alter[cycle]) } selected[cycle] = long[cycle].last() main.add(1L * edges + n * m + cycle) } var ans = 1 val w = IntArray(edges) { 1 } var sum = edges.toLong() var removed = (n + 1).toLong() for (event in ids.indices) { val id = ids[event] val oldWeight = w[id] val newWeight = weights[event] removed -= main.last() / edges if (id < n * m) { val cycle = id / m val j = id % m val set = if (isShort(cycle, j)) short[cycle] else long[cycle] if (!set.remove(oldWeight.toLong() * edges + id)) error("") set.add(newWeight.toLong() * edges + id) val alt = alter[cycle] val sel = selected[cycle] removed -= sel / edges if (alt != -1L) { if (!main.remove(alt)) error("") val a1 = short[cycle].last() val a2 = long[cycle].last() alter[cycle] = minOf(a1, a2) main.add(alter[cycle]) selected[cycle] = maxOf(a1, a2) } else { selected[cycle] = long[cycle].last() } removed += selected[cycle] / edges } else { main.remove(oldWeight.toLong() * edges + id) main.add(newWeight.toLong() * edges + id) } removed += main.last() / edges sum += newWeight - oldWeight w[id] = newWeight ans = ((ans * ((sum - removed) % MOD)) % MOD).toInt() } return ans } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,660
competitions
The Unlicense
src/day19.kt
miiila
725,271,087
false
{"Kotlin": 77215}
import java.io.File import kotlin.system.exitProcess private const val DAY = 19 fun main() { if (!File("./day${DAY}_input").exists()) { downloadInput(DAY) println("Input downloaded") exitProcess(0) } val transformer = { x: String -> x } val input = parseWorkflowsAndParts(loadInput(DAY, false, transformer)) val graph = parseWorkflowsIntoGraph(loadInput(DAY, false, transformer)) // println(input) println(solvePart1(input)) println(solvePart2(graph)) } // Part 1 private fun solvePart1(input: Pair<Map<String, List<(part: Part) -> String?>>, List<Part>>): Int { val (workflows, parts) = input val state = solveState(workflows, parts) return state["A"]!!.sumOf { it.sum() } } // Part 2 private fun solvePart2(graph: List<Pair<String, List<Pair<String, String?>>>>): Long { val graph = graph.toMap() val ranges = mutableMapOf( 'x' to (1..4000).toSet(), 'm' to (1..4000).toSet(), 'a' to (1..4000).toSet(), 's' to (1..4000).toSet() ) val q = mutableListOf(Pair("in", ranges)) val res = mutableListOf<Map<Char, Set<Int>>>() while (q.isNotEmpty()) { val (node, ranges) = q.removeFirst() val conds = graph[node]!! for ((target, cond) in conds) { if (target == "A") { if (cond.isNullOrBlank()) { res.add(ranges) continue } val (c, condRange) = parseCondToRange(cond) val newRanges = ranges.toMutableMap() newRanges[c] = newRanges[c]!!.intersect(condRange) res.add(newRanges) ranges[c] = ranges[c]!!.minus(condRange) continue } if (target == "R") { if (cond.isNullOrBlank()) { continue } val (c, condRange) = parseCondToRange(cond) ranges[c] = ranges[c]!!.minus(condRange) continue } if (cond.isNullOrBlank()) { q.add(Pair(target, ranges)) continue } val (c, condRange) = parseCondToRange(cond) val newRanges = ranges.toMutableMap() newRanges[c] = newRanges[c]!!.intersect(condRange) q.add(Pair(target, newRanges)) ranges[c] = ranges[c]!!.minus(condRange) } } return res.sumOf { it.values.fold(1L) { acc, ints -> acc * ints.count().toLong() } } } fun parseCondToRange(cond: String): Pair<Char, IntProgression> { return when (cond[1]) { '>' -> Pair(cond[0], (cond.drop(2).toInt() + 1..4000)) '<' -> Pair(cond[0], (1..<cond.drop(2).toInt())) else -> error("BOOM") } } fun solveState( workflows: Map<String, List<(part: Part) -> String?>>, parts: List<Part> ): Map<String, List<Part>> { var state = mutableMapOf(Pair("in", parts.toMutableList())) while ((state["A"]?.count() ?: 0) + (state["R"]?.count() ?: 0) != parts.count()) { val newState = mutableMapOf<String, MutableList<Part>>() for ((wf, ps) in state) { if (wf == "A" || wf == "R") { newState[wf] = newState[wf] ?: mutableListOf() newState[wf]!!.addAll(ps) continue } while (ps.isNotEmpty()) { val p = ps.removeFirst() val r = workflows[wf]!!.firstNotNullOf { it(p) } newState[r] = newState[r] ?: mutableListOf() newState[r]!!.add(p) } } state = newState } return state } fun parseWorkflowsAndParts(input: List<String>): Pair<Map<String, List<(part: Part) -> String?>>, List<Part>> { val split = input.indexOfFirst { it.isEmpty() } val workflows = input.slice(0..<split).map(::parseWorkflow).toMap() val parts = input.slice(split + 1..<input.count()).map(::parsePart) return Pair(workflows, parts) } fun parseWorkflowsIntoGraph(input: List<String>): List<Pair<String, List<Pair<String, String?>>>> { val split = input.indexOfFirst { it.isEmpty() } val workflows = input.slice(0..<split).map(::parseWorkflowIntoGraph) return workflows } data class Part(val x: Int, val m: Int, val a: Int, val s: Int) { fun sum(): Int { return x + m + a + s } fun get(prop: Char): Int { return when (prop) { 'x' -> this.x 'm' -> this.m 'a' -> this.a 's' -> this.s else -> error("BOOM") } } } fun parseWorkflowIntoGraph( workflow: String, ): Pair<String, List<Pair<String, String?>>> { val workflow = workflow.split('{') val source = workflow[0] val targets = workflow[1].let { x -> x.split(',').map { x -> x.split(':').let { x -> if (x.count() == 2) { Pair(x[1], x[0]) } else { Pair(x[0].dropLast(1), null) } } } } return Pair(source, targets) } fun parseWorkflow(workflow: String): Pair<String, List<(part: Part) -> String?>> { val workflow = workflow.split('{') val name = workflow[0] return Pair(name, workflow[1].let { x -> x.split(',').map { x -> when (x[1]) { '>' -> isGreater( x[0], x.drop(2).takeWhile { it != ':' }.toInt(), x.reversed().takeWhile { it != ':' }.reversed() ) '<' -> isLess( x[0], x.drop(2).takeWhile { it != ':' }.run(String::toInt), x.reversed().takeWhile { it != ':' }.reversed() ) else -> send(x.dropLast(1)) } } }) } fun isGreater(prop: Char, limit: Int, ret: String): (part: Part) -> String? { return { part: Part -> if (part.get(prop) > limit) ret else null } } fun isLess(prop: Char, limit: Int, ret: String): (part: Part) -> String? { return { part: Part -> if (part.get(prop) < limit) ret else null } } fun send(ret: String): (part: Part) -> String? { return { ret } } fun parsePart(part: String): Part { val part = part.slice(1..<part.count() - 1) part.let { x -> val p = x.split(",") return Part(p[0].drop(2).toInt(), p[1].drop(2).toInt(), p[2].drop(2).toInt(), p[3].drop(2).toInt()) } }
0
Kotlin
0
1
1cd45c2ce0822e60982c2c71cb4d8c75e37364a1
6,505
aoc2023
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2023/day07/day7.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day07 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val bids = parseCamelBids(inputFile.bufferedReader().readLines()) println("Total winnings are: ${getTotalWinnings(bids)}") } data class CamelBid(val hand: CamelHand, val bid: Int) data class CamelHand(var cards: List<CamelCard>) : Comparable<CamelHand> { val type: CamelHandType get() { return if (cards.contains(CamelCard.JOKER)) { findBestHand(cards).type } else { CamelHandType.fromCards(cards) } } companion object { fun fromString(str: String, jacksAreJokers: Boolean = false): CamelHand = CamelHand(cards = str.map { CamelCard.fromChar(it, jacksAreJokers) }) } override fun compareTo(other: CamelHand): Int { val typeComparison = this.type.compareTo(other.type) if (typeComparison != 0) { return -typeComparison } for ((thisCard, otherCard) in cards.zip(other.cards)) { val cardComparison = thisCard.compareTo(otherCard) if (cardComparison != 0) { return -cardComparison } } return 0 } } enum class CamelCard(val symbol: Char) { ACE('A'), KING('K'), QUEEN('Q'), JACK('J'), TEN('T'), NINE('9'), EIGHT('8'), SEVEN('7'), SIX('6'), FIVE('5'), FOUR('4'), THREE('3'), TWO('2'), JOKER('*'); companion object { fun fromChar(symbol: Char, jacksAreJokers: Boolean = false): CamelCard = entries.single { it.symbol == symbol } .let { card -> if (jacksAreJokers && card == JACK) { JOKER } else { card } } } } enum class CamelHandType(private val expectedCounts: List<Int>) { FIVE_OF_A_KIND(listOf(5)), FOUR_OF_A_KIND(listOf(4)), FULL_HOUSE(listOf(3, 2)), THREE_OF_A_KIND(listOf(3)), TWO_PAIR(listOf(2, 2)), ONE_PAIR(listOf(2)), HIGH_CARD(listOf(1, 1, 1, 1, 1)); companion object { fun fromCards(cards: List<CamelCard>): CamelHandType = entries.filter { it.matches(cards) }.minOf { it } } fun matches(cards: List<CamelCard>): Boolean { if (cards.size != 5) { throw IllegalArgumentException("Got ${cards.size} instead of 5") } val countCounts = cards .groupingBy { it } .eachCount() .values .groupingBy { it } .eachCount() val expected = expectedCounts .groupingBy { it } .eachCount() return expected.all { countCounts[it.key] == it.value } } } private fun findBestHand(cards: List<CamelCard>): CamelHand { val jokerCount = cards.count { it == CamelCard.JOKER } val nonJokerCards = cards.filter { it != CamelCard.JOKER } val nonJokerCounts = nonJokerCards .groupingBy { it } .eachCount() val mostCommonCard = nonJokerCounts.entries.maxByOrNull { it.value } return CamelHand( cards = nonJokerCards + List(jokerCount) { _ -> mostCommonCard?.key ?: CamelCard.ACE } ) } fun parseCamelBids(lines: Iterable<String>, jacksAreJokers: Boolean = false): List<CamelBid> = lines.map { line -> val (cardsStr, bidValue) = line.split(" ") CamelBid( hand = CamelHand( cards = cardsStr.map { CamelCard.fromChar(it, jacksAreJokers) }, ), bid = bidValue.toInt(), ) } fun getTotalWinnings(bids: List<CamelBid>): Int = bids .sortedBy { it.hand } .foldIndexed(0) { index, acc, bid -> acc + bid.bid * (index + 1) }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
3,890
advent-of-code
MIT License
day2/src/main/kotlin/day2/Diving.kt
snv
434,384,799
false
{"Kotlin": 99328}
package day2 fun main() { val commands = input.lines() .map(::parseCommand) val lastPosition1 = commands .fold(Position(), Position::execute) println(""" first part: Last position is $lastPosition1 Quizanswer is ${lastPosition1.horizontal * lastPosition1.depth} """.trimIndent()) val lastPosition2 = commands .fold(ComplexPosition(), ComplexPosition::execute) println(""" second part: Last position is $lastPosition2 Quizanswer is ${lastPosition2.horizontal * lastPosition2.depth} """.trimIndent()) } data class Position(val horizontal: Int = 0, val depth: Int = 0): Divable<Position>(){ override fun forward(x:Int) = copy(horizontal = horizontal+x) override fun down(x:Int) = copy(depth = depth + x) override fun up(x: Int) = copy(depth = depth - x) } data class ComplexPosition(val horizontal: Int = 0, val depth: Int = 0, val aim: Int = 0): Divable<ComplexPosition>(){ override fun forward(x:Int) = copy(horizontal = horizontal + x, depth = depth + aim*x) override fun down(x:Int) = copy(aim = aim + x) override fun up(x: Int) = copy(aim = aim - x) } abstract class Divable<T> { abstract fun forward(x:Int) : T abstract fun down(x:Int) : T abstract fun up(x:Int) : T fun execute(command: Command) = when (command.direction) { Direction.FORWARD -> forward(command.distance) Direction.DOWN -> down(command.distance) Direction.UP -> up(command.distance) } } enum class Direction{ FORWARD, UP, DOWN } data class Command(val direction: Direction, val distance: Int) fun parseCommand(s: String) = s.uppercase() .split(' ') .let { Command( Direction.valueOf(it[0]), it[1].toInt() ) }
0
Kotlin
0
0
0a2d94f278defa13b52f37a938a156666314cd13
1,823
adventOfCode21
The Unlicense
src/main/kotlin/days/model/CamelCards.kt
errob37
726,532,024
false
{"Kotlin": 29748, "Shell": 408}
package days.model enum class GameMode { NORMAL, WITH_JOKERS } class CamelCards(private val input: List<String>, private val gameMode: GameMode) { fun totalWinnings() = createHands() .sorted() .mapIndexed { index, hand -> (index + 1) * hand.bid } .sum() private fun createHands() = input.map { val (cards, bid) = it.split(" ") Hand(cards.trim(), bid.trim().toLong(), gameMode) } } data class Hand( val cards: String, val bid: Long, val gameMode: GameMode, ) : Comparable<Hand> { private val type: HandType get() { return if (gameMode == GameMode.NORMAL) { getTypeForNormalGameMode() } else { getTypeForWithJokerGameMode() } } private fun getTypeForNormalGameMode(): HandType { val byCardValue = cards.asSequence().groupBy { it } return when (byCardValue.size) { 1 -> HandType.FIVE_OF_KIND 2 -> handleTwoSets(byCardValue) 3 -> handleThreeSets(byCardValue) 4 -> HandType.ONE_PAIR else -> HandType.HIGH_CARD } } private fun getTypeForWithJokerGameMode(): HandType { val type = getTypeForNormalGameMode() return when (cards.jokerCount) { 0, 5 -> type 4 -> HandType.FIVE_OF_KIND 3 -> if (type == HandType.FULL_HOUSE) HandType.FIVE_OF_KIND else HandType.FOUR_OF_KIND 2 -> if (type == HandType.TWO_PAIR) HandType.FOUR_OF_KIND else HandType.THREE_OF_KIND 1 -> when (type) { HandType.FOUR_OF_KIND -> HandType.FIVE_OF_KIND HandType.THREE_OF_KIND -> HandType.FOUR_OF_KIND HandType.TWO_PAIR -> HandType.FULL_HOUSE HandType.ONE_PAIR -> HandType.THREE_OF_KIND else -> HandType.ONE_PAIR } else -> HandType.ONE_PAIR } } private fun getOrderHexa() = cards.map { when (it) { 'A' -> 'E' 'K' -> 'D' 'Q' -> 'C' 'J' -> if (gameMode == GameMode.NORMAL) 'B' else '1' 'T' -> 'A' else -> it } } .joinToString("") .toInt(16) private fun handleTwoSets(byCardValue: Map<Char, List<Char>>) = if (byCardValue.any { it.value.size == 4 }) HandType.FOUR_OF_KIND else HandType.FULL_HOUSE private fun handleThreeSets(byCardValue: Map<Char, List<Char>>) = if (byCardValue.values.any { it.size == 3 }) HandType.THREE_OF_KIND else HandType.TWO_PAIR override fun compareTo(other: Hand) = if (other.type != type) type.ordinal - other.type.ordinal else getOrderHexa() - other.getOrderHexa() } enum class HandType { HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_KIND, FULL_HOUSE, FOUR_OF_KIND, FIVE_OF_KIND } private var String.jokerCount: Int get() = this.count { 'J' == it } private set(_) {}
0
Kotlin
0
0
79db6f0f56d207b68fb89425ad6c91667a84d60f
3,113
adventofcode-2023
Apache License 2.0
src/Day12.kt
6234456
572,616,769
false
{"Kotlin": 39979}
import java.util.Queue fun main() { fun part1(input: List<String>): Int { val rows = input.size val cols = input.first().length val points = Array<IntArray>(rows){ IntArray(cols){0} } val ans = Array<IntArray>(rows){ IntArray(cols){Int.MAX_VALUE} } var start: Pair<Int, Int> = Pair(0,0) var end: Pair<Int, Int> = Pair(0,0) (0 until rows).forEach { x -> val arr = input[x].toCharArray() (0 until cols).forEach { y-> when(arr[y]){ 'S' -> { start = x to y points[x][y] = 0 } 'E' -> { end = x to y points[x][y] = 25 } else -> points[x][y] = arr[y] - 'a' } } } val queue: Queue<Pair<Int, Int>> = java.util.LinkedList<Pair<Int, Int>>().apply { add(start) } val visited: MutableSet<Pair<Int, Int>> = mutableSetOf(start,) ans[start.first][start.second] = 0 fun shortest():Int{ while (queue.isNotEmpty()) { val (x0, y0) = queue.poll() if (x0 == end.first && y0 == end.second) return ans[end.first][end.second] listOf(x0 to y0 + 1, x0 + 1 to y0, x0 to y0 - 1, x0 - 1 to y0).forEach { val x = it.first val y = it.second if (!(x >= rows || y >= cols || x < 0 || y < 0 || (x to y) in visited || points[x][y] - points[x0][y0] > 1)) { ans[x][y] = ans[x0][y0] + 1 queue.add(x to y) visited.add(x to y) } } } return -1 } return shortest() } fun part2(input: List<String>): Int{ val rows = input.size val cols = input.first().length val points = Array<IntArray>(rows){ IntArray(cols){0} } val ans = Array<IntArray>(rows){ IntArray(cols){Int.MAX_VALUE} } var start: Pair<Int, Int> = Pair(0,0) var end: Pair<Int, Int> = Pair(0,0) (0 until rows).forEach { x -> val arr = input[x].toCharArray() (0 until cols).forEach { y-> when(arr[y]){ 'S' -> { start = x to y points[x][y] = 0 } 'E' -> { end = x to y points[x][y] = 25 } else -> points[x][y] = arr[y] - 'a' } } } val queue: Queue<Pair<Int, Int>> = java.util.LinkedList<Pair<Int, Int>>().apply { add(end) } val visited: MutableSet<Pair<Int, Int>> = mutableSetOf(end) ans[end.first][end.second] = 0 fun shortest():Int{ while (queue.isNotEmpty()) { val (x0, y0) = queue.poll() if (points[x0][y0] == 0) return ans[x0][y0] listOf(x0 to y0 + 1, x0 + 1 to y0, x0 to y0 - 1, x0 - 1 to y0).forEach { val x = it.first val y = it.second if (!(x >= rows || y >= cols || x < 0 || y < 0 || (x to y) in visited || points[x0][y0] - points[x][y] > 1)) { ans[x][y] = ans[x0][y0] + 1 queue.add(x to y) visited.add(x to y) } } } return -1 } return shortest() } var input = readInput("Test12") println(part1(input)) println(part2(input)) input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b6d683e0900ab2136537089e2392b96905652c4e
4,031
advent-of-code-kotlin-2022
Apache License 2.0
src/Day08.kt
Aldas25
572,846,570
false
{"Kotlin": 106964}
fun main() { fun part1(r: Int, c: Int, grid: Array<IntArray>): Int { val visible = Array(r) { BooleanArray(c) { false } } for (row in 0 until r) { var highest = -1 for (col in 0 until c) { if (grid[row][col] > highest) { visible[row][col] = true highest = grid[row][col] } } highest = -1 for (col in (c-1) downTo 0) { if (grid[row][col] > highest) { visible[row][col] = true highest = grid[row][col] } } } for (col in 0 until c) { var highest = -1 for (row in 0 until r) { if (grid[row][col] > highest) { visible[row][col] = true highest = grid[row][col] } } highest = -1 for (row in (r-1) downTo 0) { if (grid[row][col] > highest) { visible[row][col] = true highest = grid[row][col] } } } return visible.sumOf { row -> row.count { it } } } fun calcVisible(x: Int, y: Int, dx: Int, dy: Int, r: Int, c: Int, grid: Array<IntArray>): Int { var ans = 0 var i = x + dx var j = y + dy while ((i in 0 until r) && (j in 0 until c)) { ans++ if (grid[i][j] >= grid[x][y]) break i += dx j += dy } return ans } fun scenicScore(x: Int, y: Int, r: Int, c: Int, grid: Array<IntArray>): Int { var ans = 1 for (dir in listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1))) { ans *= calcVisible(x, y, dir.first, dir.second, r, c, grid) } return ans } fun part2(r: Int, c: Int, grid: Array<IntArray>): Int { var ans = 0 for (i in 0 until r) for (j in 0 until c) ans = maxOf(ans, scenicScore(i, j, r, c, grid)) return ans } val filename = // "inputs/day08_sample" "inputs/day08" val input = readInput(filename) val grid = Array(input.size) { IntArray(input[0].length) } val r = grid.size val c = grid[0].size for (i in input.indices) { for (j in input[0].indices) { grid[i][j] = input[i][j].code } } println("Part 1: ${part1(r, c, grid)}") println("Part 2: ${part2(r, c, grid)}") }
0
Kotlin
0
0
80785e323369b204c1057f49f5162b8017adb55a
2,564
Advent-of-Code-2022
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2021/day10/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day10 import com.kingsleyadio.adventofcode.util.readInput fun main() { println(part1()) println(part2()) } fun part1(): Int { fun findInvalidChar(line: String): Char { val stack = StringBuilder() for (char in line) { val complement = when (char) { ']' -> '[' '}' -> '{' ')' -> '(' '>' -> '<' else -> { stack.append(char); continue } } if (stack.isEmpty() || stack.last() != complement) return char stack.deleteCharAt(stack.lastIndex) } return ' ' // Ignore } readInput(2021, 10).useLines { lines -> val scoresMap = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) return lines.map { findInvalidChar(it) }.sumOf { scoresMap[it] ?: 0 } } } fun part2(): Long { fun evaluateCompletionString(line: String): String? { val stack = StringBuilder() for (char in line) { val complement = when (char) { ']' -> '[' '}' -> '{' ')' -> '(' '>' -> '<' else -> { stack.append(char); continue } } if (stack.isEmpty() || stack.last() != complement) return null stack.deleteCharAt(stack.lastIndex) } return stack.reverse().toString() } readInput(2021, 10).useLines { lines -> val scoresMap = mapOf('(' to 1, '[' to 2, '{' to 3, '<' to 4) val points = lines .mapNotNull { evaluateCompletionString(it) } .map { it.fold(0L) { acc, c -> acc * 5 + scoresMap.getValue(c) } } .toList() .sorted() return points[points.size shr 1] } }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,808
adventofcode
Apache License 2.0
src/day11/b/day11b.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day11.b import readInputLines import shouldBe fun main() { val monkeys = readInput() fun doMonkey(m: Monkey) { val it = m.items.iterator() while(it.hasNext()) { val item = it.next(); it.remove() m.activity++ item.rem = m.operation(item.rem) if (item.rem[m.divTest] == 0) { monkeys[m.ifTrue].items.add(item) } else { monkeys[m.ifFalse].items.add(item) } } } for (round in 1..10000) monkeys.forEach { doMonkey(it) } val r = monkeys.map { it.activity }.sorted().reversed() val wl = 1L*r[0]*r[1] shouldBe(14508081294, wl) } data class Remainders( val m: HashMap<Int, Int> = HashMap() ) { constructor(other: Remainders) : this(HashMap(other.m)) constructor(value: Int) : this() { for (div in listOf(2,3,5,7,11,13,17,19)) { this[div] = value % div } } operator fun plus(that: Remainders): Remainders { val r = Remainders(this) that.m.forEach { (k, v) -> r[k] = (r[k] + v) % k } return r } operator fun times(that: Remainders): Remainders { val r = Remainders() m.forEach { (k, v) -> r[k] = (that[k] * v) % k } return r } operator fun get(div: Int) : Int { return m[div]?:0 } operator fun set(div: Int, rem: Int) { if (rem == 0) m.remove(div) else m[div] = rem } } data class Item( var rem: Remainders = Remainders() ) data class Monkey( val items : ArrayList<Item>, val operation : (Remainders) -> Remainders, val divTest : Int, val ifTrue : Int, val ifFalse : Int, ) { var activity: Int = 0 } fun readInput(): ArrayList<Monkey> { val r = ArrayList<Monkey>() val it = readInputLines(11).iterator() while (it.hasNext()) { it.next() // skip Monkey var s = it.next() val items = ArrayList(s.substring(18).split(", ").map { i -> Item(Remainders(i.toInt())) }) s = it.next() val op = s.substring(23, 24) val w = s.substring(25) val oper: (Remainders, Remainders)->Remainders = when(op) { "*" -> { a,b -> a*b } "+" -> { a,b -> a+b } else -> throw RuntimeException() } val oper2: (Remainders)->Remainders = if (w == "old") { {old:Remainders->oper(old, old)} } else { {old:Remainders->oper(old, Remainders(w.toInt()))} } s = it.next() val divTest = s.substring(21).toInt() s = it.next() val ifTrue = s.substring(29).toInt() s = it.next() val ifFalse = s.substring(30).toInt() if (it.hasNext()) it.next() // empty line val m = Monkey(items, oper2, divTest, ifTrue, ifFalse) r.add(m) } return r }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
2,858
advent-of-code-2022
Apache License 2.0
src/Day16.kt
jinie
572,223,871
false
{"Kotlin": 76283}
import java.util.* data class Valve(val name: String, val flowRate: Int, val neighbours: MutableList<Valve>, var open: Boolean) { companion object { fun of(name: String, flowRate: Int): Valve { return Valve(name, flowRate, mutableListOf(), false) } } override fun toString(): String { return "$name: flowRate=$flowRate open=$open" } override fun hashCode(): Int { return name.hashCode() } } data class Node(val valve: Valve, var distance: Int) : Comparable<Node> { override fun compareTo(other: Node): Int { return this.distance.compareTo(other.distance) } } class Day16 { private fun relax(u: Node, v: Node, weight: Int = 1): Boolean { if (v.distance > u.distance + weight) { v.distance = u.distance + weight return true } return false } /** * Computes distances between all pair of nodes in the graph. We compute that with running Dijsktra algorithm for every node in the graph. */ private fun computeAllPairDistances(valves: Map<String, Valve>): Map<Valve, List<Node>> { val distances = mutableMapOf<Valve, List<Node>>() valves.values.filter { it.flowRate > 0 || it.name == "AA" }.map { valve -> val nodes = valves.values.map { Node(it, Int.MAX_VALUE) } nodes.first { it.valve == valve }.distance = 0 val visitedNodes = mutableListOf<Node>() val unvisitedNodes = PriorityQueue<Node>() unvisitedNodes.addAll(nodes) while (unvisitedNodes.isEmpty().not()) { val node = unvisitedNodes.poll() visitedNodes.add(node) node.valve.neighbours.map { neighbourValve -> val neighbour = nodes.first { it.valve == neighbourValve } if (relax(node, neighbour)) { unvisitedNodes.remove(neighbour) unvisitedNodes.add(neighbour) } } } // We are only interested in the nodes with positive flow rate visitedNodes.filter { it.valve.flowRate > 0 }.run { distances[valve] = this } } return distances } private fun findBestPath(valve: Valve, time: Int, allPairDistances: Map<Valve, List<Node>>): Int { return allPairDistances[valve]!! .filter { !it.valve.open && time - (it.distance + 1) > 0 } .maxOfOrNull { val remainingTime = time - (it.distance + 1) it.valve.open = true val releasedPressure = remainingTime * it.valve.flowRate + findBestPath(it.valve, remainingTime, allPairDistances) it.valve.open = false releasedPressure } ?: 0 } private fun findBestPathWithElephant( valveElf: Valve, valveElephant: Valve, timeElf: Int, timeElephant: Int, allPairDistances: Map<Valve, List<Node>> ): Int { return allPairDistances[valveElf]!!.filter { !it.valve.open && timeElf - (it.distance + 1) > 0 } .maxOfOrNull { currentElfValve -> val remainingTimeElf = timeElf - (currentElfValve.distance + 1) currentElfValve.valve.open = true val releasedPressure = allPairDistances[valveElephant]!! .filter { !it.valve.open && timeElephant - (it.distance + 1) > 0 } .maxOfOrNull { currentElephantValve -> val remainingTimeElephant = timeElephant - (currentElephantValve.distance + 1) currentElephantValve.valve.open = true val releasedPressure = findBestPathWithElephant( currentElfValve.valve, currentElephantValve.valve, remainingTimeElf, remainingTimeElephant, allPairDistances ) currentElephantValve.valve.open = false remainingTimeElephant * currentElephantValve.valve.flowRate + releasedPressure } ?: 0 currentElfValve.valve.open = false remainingTimeElf * currentElfValve.valve.flowRate + releasedPressure } ?: 0 } fun part1(input: List<String>): Int { val valves = parseInput(input) val allPairDistances = computeAllPairDistances(valves) val startValve = valves["AA"]!! return findBestPath(startValve, 30, allPairDistances) } fun part2(input: List<String>): Int { val valves = parseInput(input) val allPairDistances = computeAllPairDistances(valves) val startValve = valves["AA"]!! return findBestPathWithElephant(startValve, startValve, 26, 26, allPairDistances) } private fun parseInput(input: List<String>): MutableMap<String, Valve> { val valves = mutableMapOf<String, Valve>() input.map { it.replace(Regex("[,;=]"), " ") } .map { it.split(" ").filter { it.isNotEmpty() } } .use { valves[it[1]] = Valve.of(it[1], it[5].toInt()) } .map { val index = if (it.indexOf("valves") == -1) it.size - 1 else it.indexOf("valves") + 1 it.subList(index, it.size).map { valve -> valves[it[1]]?.neighbours?.add(valves[valve]!!) } } return valves } } fun <T, R> List<T>.use(transform: (T) -> R): List<T> { return this.map { transform(it) it } } fun main() { val testInput = readInput("Day16_test") check(Day16().part1(testInput) == 1651) measureTimeMillisPrint { val input = readInput("Day16") println(Day16().part1(input)) println(Day16().part2(input)) } }
0
Kotlin
0
0
4b994515004705505ac63152835249b4bc7b601a
5,930
aoc-22-kotlin
Apache License 2.0
kotlin/structures/MosAlgorithm.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package structures // https://www.hackerearth.com/notes/mos-algorithm/ // Solution of http://www.spoj.com/problems/DQUERY/en/ object MosAlgorithm { fun add(a: IntArray, cnt: IntArray, i: Int): Int { return if (++cnt[a[i]] == 1) 1 else 0 } fun remove(a: IntArray, cnt: IntArray, i: Int): Int { return if (--cnt[a[i]] == 0) -1 else 0 } fun processQueries(a: IntArray, queries: Array<Query>): IntArray { for (i in queries.indices) queries[i].index = i val sqrtn = Math.sqrt(a.size) as Int Arrays.sort( queries, Comparator.< Query > comparingInt < structures . MosAlgorithm . Query ? > { q -> q.a / sqrtn }.thenComparingInt { q -> q.b }) val cnt = IntArray(1000002) val res = IntArray(queries.size) var L = 1 var R = 0 var cur = 0 for (query in queries) { while (L < query.a) cur += remove(a, cnt, L++) while (L > query.a) cur += add(a, cnt, --L) while (R < query.b) cur += add(a, cnt, ++R) while (R > query.b) cur += remove(a, cnt, R--) res[query.index] = cur } return res } fun main(args: Array<String?>?) { val a = intArrayOf(1, 3, 3, 4) val queries = arrayOf(Query(0, 3), Query(1, 3), Query(2, 3), Query(3, 3)) val res = processQueries(a, queries) System.out.println(Arrays.toString(res)) } class Query(var a: Int, var b: Int) { var index = 0 } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,520
codelibrary
The Unlicense
src/main/kotlin/io/dmitrijs/aoc2022/Day15.kt
lakiboy
578,268,213
false
{"Kotlin": 76651}
package io.dmitrijs.aoc2022 import kotlin.math.max class Day15(input: List<String>) { private val pairs = input.map { """x=(-?\d+), y=(-?\d+)""".toRegex() .findAll(it) .toList() .let { (match1, match2) -> Signal(match1.toPoint(), match2.toPoint()) } } fun puzzle1(row: Int) = takenRanges(row) .sortedBy { it.first } .reduce { acc, next -> acc merge next } .let { (a, b) -> b - a } fun puzzle2(limit: Int): Long { for (row in 0..limit) { val ranges = takenRanges(row) .sortedBy { it.first } .map { (a, b) -> a.coerceIn(0, limit) to b.coerceIn(0, limit) } var fullRange = ranges.first() for (i in 1 until ranges.size) { val col = fullRange.second + 1 // Lookup for gap if (col < ranges[i].first) { return 4_000_000L * col + row } fullRange = fullRange merge ranges[i] } } return -1 } private fun MatchResult.toPoint() = Point( groupValues[1].toInt(), groupValues[2].toInt(), ) private infix fun Pair<Int, Int>.merge(other: Pair<Int, Int>) = first to max(second, other.second) private fun takenRanges(row: Int) = buildList { pairs.forEach { signal -> val radius = signal.rowRadius(row) if (radius > 0) { this += (signal.sensor.x - radius) to (signal.sensor.x + radius) } } } private data class Signal(val sensor: Point, val beacon: Point) { private val distance get() = sensor.distanceTo(beacon) fun rowRadius(row: Int) = if (sensor.y < row) { sensor.y + distance - row } else { row - (sensor.y - distance) } } }
0
Kotlin
0
1
bfce0f4cb924834d44b3aae14686d1c834621456
1,883
advent-of-code-2022-kotlin
Apache License 2.0
src/Day14.kt
robinpokorny
572,434,148
false
{"Kotlin": 38009}
import kotlin.math.max import kotlin.math.min private fun line(from: Point, to: Point): List<Point> = if (from.x == to.x) (min(from.y, to.y)..max(from.y, to.y)).map { Point(to.x, it) } else if (from.y == to.y) (min(from.x, to.x)..max(from.x, to.x)).map { Point(it, to.y) } else error("No support for diagonals.") private fun parse(input: List<String>) = input.flatMap { line -> line .split(" -> ") .map { val (x, y) = it.split(",") Point(x.toInt(), y.toInt()) } .windowed(2) .flatMap { (from, to) -> line(from, to) } } private tailrec fun moveGrain( from: Point, isFinished: (Point) -> Boolean, taken: HashSet<Point>, floor: Int = Int.MAX_VALUE ): Boolean { if (isFinished(from)) return true listOf(0, -1, 1) .map { Point(from.x + it, from.y + 1) } .find { !taken.contains(it) && it.y < floor } ?.let { return moveGrain(it, isFinished, taken, floor) } taken.add(from) return false } private fun part1(cave: List<Point>): Int { val taken = cave.toHashSet() val source = Point(500, 0) val voidStart = cave.maxOf { it.y } var sandGrains = -1 var finished = false while (!finished) { sandGrains++ finished = moveGrain(source, { it.y >= voidStart }, taken) } return sandGrains } private fun part2(cave: List<Point>): Int { val taken = cave.toHashSet() val source = Point(500, 0) val floor = cave.maxOf { it.y } + 2 var sandGrains = -1 var finished = false while (!finished) { sandGrains++ finished = moveGrain(source, { _ -> taken.contains(source) }, taken, floor) } return sandGrains } fun main() { val input = parse(readDayInput(14)) val testInput = parse(rawTestInput) // PART 1 assertEquals(part1(testInput), 24) println("Part1: ${part1(input)}") // PART 2 assertEquals(part2(testInput), 93) println("Part2: ${part2(input)}") } private val rawTestInput = """ 498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9 """.trimIndent().lines()
0
Kotlin
0
2
56a108aaf90b98030a7d7165d55d74d2aff22ecc
2,150
advent-of-code-2022
MIT License
src/day18/Day18.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day18 import java.io.File fun main() { val data = parse("src/day18/Day18.txt") println("🎄 Day 18 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } enum class Direction { U, D, L, R } private data class Instruction( val direction: Direction, val distance: Int, ) private fun parse(path: String): List<String> = File(path).readLines() private fun solve(data: List<Instruction>): Long { val x = mutableListOf<Long>() val y = mutableListOf<Long>() var px = 0L var py = 0L for ((direction, meters) in data) { when (direction) { Direction.D -> py += meters Direction.U -> py -= meters Direction.L -> px -= meters Direction.R -> px += meters } x += px y += py } val area = (x.indices).sumOf { i -> val prev = if (i - 1 < 0) x.lastIndex else i - 1 val next = if (i + 1 > x.lastIndex) 0 else i + 1 x[i] * (y[next] - y[prev]) } / 2 val exterior = data.sumOf { it.distance } val interior = (area - (exterior / 2) + 1) return interior + exterior } private fun part1(data: List<String>): Long = solve(data.map { line -> val (directionPart, distancePart, _) = line.split(" ") val direction = when (directionPart) { "R" -> Direction.R "D" -> Direction.D "L" -> Direction.L "U" -> Direction.U else -> error("Invalid direction!") } val distance = distancePart.toInt() Instruction(direction, distance) }) private fun part2(data: List<String>): Long = solve(data.map { line -> val (_, _, colorPart) = line.split(" ") val color = colorPart.trim('(', ')', '#') val distance = color .substring(0, 5) .toInt(radix = 16) val direction = when (color.last()) { '0' -> Direction.R '1' -> Direction.D '2' -> Direction.L '3' -> Direction.U else -> error("Invalid direction!") } Instruction(direction, distance) })
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
2,347
advent-of-code-2023
MIT License
src/main/kotlin/days/y2023/day03/Day03.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day03 import util.InputReader private class Day03(puzzleInput: String) { val grid = puzzleInput.lines().filter { it.isNotEmpty() }.map { line -> line.toCharArray().toList() }.toList() fun partOne(): Int { val foundNumbers = mutableListOf<Int>() val digits = mutableListOf<Char>() val positions = mutableListOf<Pair<Int, Int>>() grid.forEachIndexed { y, line -> line.forEachIndexed { x, char -> if (char.isDigit()) { digits.add(char) positions.add(Pair(x, y)) } if (!char.isDigit() || line.lastX == x) { val hasSpecialNeighbor = positions.any { position -> grid.adjacentTo(position).any { it.isSpecial() } } if (hasSpecialNeighbor) { foundNumbers.add(digits.joinToString("").toInt()) } digits.clear() positions.clear() } } } println("Found numbers: $foundNumbers") return foundNumbers.sum() } fun partTwo(): Int { val foundNumbers = mutableMapOf<Set<Pair<Int, Int>>, Int>() val digits = mutableListOf<Char>() val positions = mutableListOf<Pair<Int, Int>>() grid.forEachIndexed { y, line -> line.forEachIndexed { x, char -> if (char.isDigit()) { digits.add(char) positions.add(Pair(x, y)) } if (!char.isDigit() || line.lastX == x) { if (positions.isNotEmpty()) { foundNumbers[positions.toSet()] = digits.joinToString("").toInt() } digits.clear() positions.clear() } } } val gearRatios = mutableListOf<Pair<Int, Int>>() grid.forEachIndexed { y, line -> line.forEachIndexed { x, char -> if (char.isSpecial('*')) { val adjacent = grid.adjacentToCoords(Pair(x, y)) val numbersAdjacentToIt = foundNumbers.filter { (positions, _) -> positions.intersect(adjacent).isNotEmpty() }.values.toList() if (numbersAdjacentToIt.size == 2) { val (first, second) = numbersAdjacentToIt gearRatios.add(Pair(first, second)) } } } } return gearRatios.sumOf { it.first * it.second } } } private fun Char.isSpecial(c: Char? = null): Boolean = if (c != null) this == c else this != ' ' && this != '.' && !isDigit() private fun <E> List<List<E>>.adjacentTo(position: Pair<Int, Int>): Set<E> { val coords = adjacentToCoords(position) return coords.map { (x, y) -> this[y][x] }.toSet() } private fun <E> List<List<E>>.adjacentToCoords(position: Pair<Int, Int>): Set<Pair<Int, Int>> { val (x, y) = position val validPositions = mutableListOf<Pair<Int, Int>>() for (dy in -1..1) { for (dx in -1..1) { if (dx == 0 && dy == 0) continue val newX = x + dx val newY = y + dy if (newX < 0 || newY < 0) continue if (newY >= size || newX >= this[newY].size) continue validPositions.add(Pair(newX, newY)) } } return validPositions.toSet() } private val <E> List<E>.lastX: Int get() = this.size - 1 fun main() { println("Example 1: ${Day03(InputReader.getExample(2023, 3)).partOne()}") println("Part 1: ${Day03(InputReader.getPuzzle(2023, 3)).partOne()}") println("Example 2: ${Day03(InputReader.getExample(2023, 3)).partTwo()}") println("Part 2: ${Day03(InputReader.getPuzzle(2023, 3)).partTwo()}") }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
3,943
AdventOfCode
Creative Commons Zero v1.0 Universal
src/day03/Day03.kt
mherda64
512,106,270
false
{"Kotlin": 10058}
package day03 import readInput fun main() { fun part1(input: List<String>): Int { val epsilonRate = buildString { for (column in input[0].indices) { val (zeroes, ones) = input.countBitsInColumn(column) append(if (zeroes > ones) '0' else '1') } } val gammaRate = epsilonRate.invertBinaryString() return epsilonRate.toInt(2) * gammaRate.toInt(2) } fun part2(input: List<String>): Int { fun rating(type: RatingType): Int { val columns = input[0].indices var candidates = input for (column in columns) { val (zeroes, ones) = candidates.countBitsInColumn(column) val mostCommon = if (zeroes > ones) '0' else '1' candidates = candidates.filter { when (type) { RatingType.OXYGEN -> it[column] == mostCommon RatingType.CO2 -> it[column] != mostCommon } } if (candidates.size == 1) break } return candidates.single().toInt(2) } return rating(RatingType.OXYGEN) * rating(RatingType.CO2) } val testInput = readInput("Day03_test") check(part1(testInput) == 198) check(part2(testInput) == 230) val input = readInput("Day03") println(part1(input)) println(part2(input)) } private enum class RatingType { OXYGEN, CO2 } private fun String.invertBinaryString(): String = this .asIterable() .joinToString("") { if (it == '0') "1" else "0" } private fun List<String>.countBitsInColumn(column: Int): BitCount { var zeroes = 0 var ones = 0 for (line in this) { if (line[column] == '0') zeroes++ else ones++ } return BitCount(zeroes, ones) } private data class BitCount(val zeroes: Int, val ones: Int)
0
Kotlin
0
0
d04e179f30ad6468b489d2f094d6973b3556de1d
1,927
AoC2021_kotlin
Apache License 2.0
src/main/kotlin/Solution.kt
tucuxi
391,628,300
false
{"Kotlin": 50486}
class Solution { fun largestIsland(grid: Array<IntArray>): Int { val n = grid.size val firstLabel = 2 val sizes = mutableMapOf<Int, Int>() fun label(row: Int, col: Int): Int = if (row !in 0 until n || col !in 0 until n) 0 else grid[row][col] fun conquerIsland(label: Int, row: Int, col: Int): Int { val queue = mutableListOf<Pair<Int, Int>>() var size = 0 grid[row][col] = label queue.add(Pair(row, col)) while (queue.isNotEmpty()) { val (r, c) = queue.removeAt(0) size++ for (step in steps) { val nextR = r + step.first val nextC = c + step.second if (label(nextR, nextC) == 1) { grid[nextR][nextC] = label queue.add(Pair(nextR, nextC)) } } } return size } fun discoverIslands() { var k = firstLabel for (row in 0 until n) { for (col in 0 until n) { if (grid[row][col] == 1) { val size = conquerIsland(k, row, col) sizes[k] = size k++ } } } } fun largestCombinedIsland(): Int { var maxSize = sizes.getOrDefault(firstLabel, 0) for (row in 0 until n) { for (col in 0 until n) { if (grid[row][col] == 0) { val neighbors = steps.map { (dr, dc) -> label(row + dr, col + dc) }.toSet() val combinedSize = neighbors.sumOf { label -> sizes.getOrDefault(label, 0) } maxSize = maxOf(combinedSize + 1, maxSize) } } } return maxSize } discoverIslands() return largestCombinedIsland() } companion object { private val steps = arrayOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1)) } }
0
Kotlin
0
0
b44a1d37c84711d98f497e557b5244152041eada
2,161
leetcode-make-a-large-island
MIT License
2017/src/main/kotlin/Day07.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import utils.splitCommas import utils.splitNewlines import java.util.regex.Pattern object Day07 { private val PATTERN = Pattern.compile("(\\w+) \\((\\d+)\\)( -> (.*))?") data class Program(val name: String, val weight: Int, val holding: List<String>) data class BalanceInfo(val totalWeight: Int, val imbalanceNodeNewWeight: Int = 0) fun part1(input: String): String { val programs = parse(input) return findRoot(programs).name } fun part2(input: String): Int { val programs = parse(input) val root = findRoot(programs) val balance = balance(programs, root) return balance.imbalanceNodeNewWeight } private fun parse(input: String): Map<String, Program> { return input.splitNewlines().map { line -> val matcher = PATTERN.matcher(line) matcher.matches() val name = matcher.group(1) val weight = matcher.group(2).toInt() val holding = if (matcher.group(3) != null) { matcher.group(4).splitCommas() } else { emptyList() } return@map Program(name, weight, holding) } .associateBy { it.name } } private fun findRoot(programs: Map<String, Program>): Program { var filteredPrograms = programs while (filteredPrograms.size > 1) { filteredPrograms = filteredPrograms.filterValues { program -> program.holding.any { it in filteredPrograms } } } return filteredPrograms.values.first() } private fun balance(programs: Map<String, Program>, node: Program): BalanceInfo { if (node.holding.isEmpty()) { return BalanceInfo(node.weight) } // Recurse through all the children val children = node.holding.map { programs[it]!! } val balances = children.associate { child -> child to balance(programs, child) } // If we already found the imbalance, fall through val imbalanceFound = balances.values.firstOrNull { it.imbalanceNodeNewWeight != 0 } imbalanceFound?.let { return it } // Figure out if it's unbalanced val weights = balances.values.map { it.totalWeight } val weightMap = balances.values.groupingBy { it.totalWeight }.eachCount() if (weightMap.size == 1) { return BalanceInfo(weights.sum() + node.weight) } // We've found the unbalanced thing, figure out what to do val imbalancedWeight = weightMap.filterValues { it == 1 }.keys.first() val balancedWeight = weightMap.filterValues { it != 1 }.keys.first() val diff = balancedWeight - imbalancedWeight val imbalancedNode = balances.filterValues { it.totalWeight == imbalancedWeight }.keys.first() return BalanceInfo(0, imbalancedNode.weight + diff) } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
2,672
advent-of-code
MIT License
src/main/kotlin/dev/bogwalk/batch4/Problem47.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch4 import dev.bogwalk.util.maths.isPrime import dev.bogwalk.util.maths.primeFactors /** * Problem 47: Distinct Primes Factors * * https://projecteuler.net/problem=47 * * Goal: Find the 1st integers (must be <= N) of K consecutive integers, that have exactly K * distinct prime factors. * * Constraints: 20 <= N <= 2e6, 2 <= K <= 4 * * Distinct Prime Factors: The 1st 2 consecutive integers to have 2 distinct prime factors are: * 14 -> 2 * 7, 15 -> 3 * 5. * * The 1st 3 consecutive integers to have 3 distinct prime factors are: * 644 -> 2^2 * 7, 645 -> 3 * 5 * 43, 646 -> 2 * 17 * 19. * * e.g.: N = 20, K = 2 * result = {14, 20} * N = 644, K = 3 * result = {644} */ class DistinctPrimesFactors { /** * Solution could be integrated with the helper function below, countPrimeFactors(), by looping * only once through the range [0, [n] + [k]) and performing both functions' tasks in an 'if' * block, branched based on whether the list element == [k]. */ fun consecutiveDistinctPrimes(n: Int, k: Int): List<Int> { val firstConsecutive = mutableListOf<Int>() var count = 0 // extend k-above limit to account for k-consecutive runs val factorCounts = countPrimeFactors(n + k) for (composite in 14 until n + k) { if (factorCounts[composite] != k) { count = 0 continue } count++ if (count >= k) { firstConsecutive.add(composite - k + 1) } } return firstConsecutive } /** * Modified primeFactors() helper method. * * @return IntArray of amount of distinct prime factors for every N, where N = index. */ private fun countPrimeFactors(n: Int): IntArray { val count = IntArray(n + 1) for (i in 2..n) { if (count[i] == 0) { for (j in i..n step i) { count[j] += 1 } } } return count } /** * Project Euler specific implementation that returns the 1st integer of the 1st 4 * consecutive numbers that have 4 distinct prime factors. * * The minimum representation with 4 distinct prime factors is: * * 2 * 3 * 5 * 7 = 210 */ fun first4DistinctPrimes(): Int { val k = 4 var composite = 210 nextC@while (true) { composite++ if ( composite.isPrime() || primeFactors(composite.toLong()).size != k ) continue@nextC for (i in 1 until k) { val adjacent = composite + i if ( adjacent.isPrime() || primeFactors(adjacent.toLong()).size != k ) continue@nextC } // only reachable if composite with 3 valid adjacents found break@nextC } return composite } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,021
project-euler-kotlin
MIT License
src/aoc2022/Day10.kt
Playacem
573,606,418
false
{"Kotlin": 44779}
package aoc2022 import utils.readInput import kotlin.math.abs private sealed class Instruction { object Noop : Instruction() class Add(val modifier: Int): Instruction() } private fun createInstruction(input: String): Instruction { return if (input == "noop") { Instruction.Noop } else { Instruction.Add(input.split(' ')[1].toInt(10)) } } private fun List<Int>.signalStrengthAt(index: Int): Int { return index * this[index] } private fun List<Int>.signalStrengthAt(indexes: List<Int>): Int { return indexes.sumOf { this.signalStrengthAt(it) } } private fun List<Int>.renderAsSingleString(): String { return this.mapIndexed { cycle, spritePos -> if (abs(spritePos - (cycle % 40)) <= 1) { "#" } else { "." } }.joinToString(separator = "") } fun main() { val (year, day) = 2022 to "Day10" fun cycleData(input: List<String>): List<Int> { var current = 1 val data = mutableListOf(current) input.map(::createInstruction).forEach { when(it) { is Instruction.Noop -> { data.add(current) } is Instruction.Add -> { data.add(current) data.add(current) current += it.modifier } } } data.add(current) return data } fun part1(input: List<String>): Int { return cycleData(input).signalStrengthAt(listOf(20, 60, 100, 140, 180, 220)) } fun part2(input: List<String>): List<String> { val renderedString = cycleData(input).drop(1).renderAsSingleString() return renderedString.chunked(40).dropLast(1) } val testInput = readInput(year, "${day}_test") val input = readInput(year, day) // test if implementation meets criteria from the description, like: check(part1(testInput) == 13140) println(part1(input)) val testPart2Result = part2(testInput) check(testPart2Result.size == 6) { "not exactly 6 rows, instead we got ${testPart2Result.size} rows" } check(testPart2Result.all { it.length == 40 }) { "not every row has 40 pixels" } testPart2Result.forEach { println(it) } println("====") part2(input).forEach { println(it) } }
0
Kotlin
0
0
4ec3831b3d4f576e905076ff80aca035307ed522
2,332
advent-of-code-2022
Apache License 2.0
src/Day18.kt
catcutecat
572,816,768
false
{"Kotlin": 53001}
import kotlin.system.measureTimeMillis fun main() { measureTimeMillis { Day18.run { solve1(64) // 4192 solve2(58) // 2520 } }.let { println("Total: $it ms") } } object Day18 : Day.LineInput<Day18.Data, Int>("18") { class Data(val cubes: Array<Array<BooleanArray>>, val positions: List<List<Int>>) override fun parse(input: List<String>): Data { val positions = input.map { it.split(",").map { it.toInt() + 1 } } val (maxX, maxY, maxZ) = (0..2).map { i -> positions.maxOf { it[i] } } val cubes = Array(maxX + 2) { Array(maxY + 2) { BooleanArray(maxZ + 2) } } for ((x, y, z) in positions) { cubes[x][y][z] = true } return Data(cubes, positions) } private val directions = arrayOf( intArrayOf(1, 0, 0), intArrayOf(-1, 0, 0), intArrayOf(0, 1, 0), intArrayOf(0, -1, 0), intArrayOf(0, 0, 1), intArrayOf(0, 0, -1) ) override fun part1(data: Data) = data.run { positions.sumOf { (x, y, z) -> directions.count { (dx, dy, dz) -> !cubes[x + dx][y + dy][z + dz] } } } override fun part2(data: Data) = data.run { var res = 0 val visited = Array(cubes.size) { x -> Array(cubes[x].size) { y -> BooleanArray(cubes[x][y].size) } } var next = listOf(intArrayOf(0, 0, 0)) while (next.isNotEmpty()) { val newNext = mutableListOf<IntArray>() for ((x, y, z) in next) for ((dx, dy, dz) in directions) { val (nx, ny, nz) = intArrayOf(x + dx, y + dy, z + dz) if (nx in visited.indices && ny in visited[nx].indices && nz in visited[nx][ny].indices) { if (cubes[nx][ny][nz]) { ++res } else if (!visited[nx][ny][nz]) { visited[nx][ny][nz] = true newNext.add(intArrayOf(nx, ny, nz)) } } } next = newNext } res } }
0
Kotlin
0
2
fd771ff0fddeb9dcd1f04611559c7f87ac048721
2,063
AdventOfCode2022
Apache License 2.0
2020/src/year2020/day13/Day13.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2020.day12 import util.readAllLines private fun findFirstBus(filename: String) { val input = readAllLines(filename) val timestamp = input[0].toInt() val buses = input[1].split(",").mapNotNull { it.toIntOrNull() } var bestId = -1 var bestArrival = Int.MAX_VALUE buses .forEach { id -> val nextArrival = timestamp + id - (timestamp % id) println("Next arrival for bus $id --> $nextArrival") if (nextArrival < bestArrival) { bestId = id bestArrival = nextArrival } } println("First bus $filename: ts = $timestamp, id = $bestId, nextArrival = $bestArrival --> ${bestId * (bestArrival - timestamp)}") } private fun findSequentialBuses( start: Long, increment: Int, allBuses: List<Int>, filteredBuses: List<Int> ): Long { if (filteredBuses.isEmpty()) { return start } var timestamp = start var result = 0L while (result == 0L) { // println("Testing $timestamp with buses ${filteredBuses.joinToString()}") val currentBusId = filteredBuses[0] val currentBusIndex = allBuses.indexOf(currentBusId).toLong() // println(" testing id = $currentBusId, index = $currentBusIndex, mod = ${(timestamp + currentBusIndex) % currentBusId}") val mod = (timestamp + currentBusIndex) % currentBusId if (mod != 0L) { // println(" bail") result = 0L break } else { // println(" found, recurse with increment ${filteredBuses[0]}, list [${filteredBuses.subList(1, filteredBuses.size).joinToString()}]") result = findSequentialBuses(timestamp, increment, allBuses, filteredBuses.subList(1, filteredBuses.size)) } timestamp += increment } // println(" exit with ts $result") return result } private fun findSequentialBuses(filename: String) { val buses = readAllLines(filename)[1].split(",").map { if (it == "x") 0 else it.toInt() } val filteredBuses = buses.filter { it > 0 }.sortedDescending() val maxBus = checkNotNull(filteredBuses.maxOrNull()) val timestamp = findSequentialBuses((maxBus - buses.indexOf(maxBus)).toLong(), maxBus, buses, filteredBuses) println("Sequential $filename: $timestamp") } fun main() { // findFirstBus("test.txt") // findFirstBus("input.txt") findSequentialBuses("test.txt") findSequentialBuses("input.txt") }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
2,497
adventofcode
MIT License
src/main/kotlin/day23/Day23.kt
daniilsjb
572,664,294
false
{"Kotlin": 69004}
package day23 import java.io.File fun main() { val data = parse("src/main/kotlin/day23/Day23.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 23 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } typealias Point = Pair<Int, Int> @Suppress("SameParameterValue") private fun parse(path: String): Set<Point> { val elves = mutableSetOf<Pair<Int, Int>>() val lines = File(path).readLines() for ((y, row) in lines.withIndex()) { for ((x, col) in row.withIndex()) { if (col == '#') { elves += x to y } } } return elves } private fun Point.neighbors(): List<Point> { val (x, y) = this return listOf( x - 1 to y - 1, x + 0 to y - 1, x + 1 to y - 1, x - 1 to y + 0, x + 1 to y + 0, x - 1 to y + 1, x + 0 to y + 1, x + 1 to y + 1, ) } private val directions = listOf( (+0 to -1) to listOf(-1 to -1, +0 to -1, +1 to -1), // North (+0 to +1) to listOf(-1 to +1, +0 to +1, +1 to +1), // South (-1 to +0) to listOf(-1 to -1, -1 to +0, -1 to +1), // West (+1 to +0) to listOf(+1 to -1, +1 to +0, +1 to +1), // East ) private data class State( val elves: Set<Point>, val firstDirection: Int = 0, ) private fun State.next(): State { val movements = mutableMapOf<Point, List<Point>>() for ((x, y) in elves) { if ((x to y).neighbors().all { it !in elves }) { continue } search@for (i in 0..3) { val (proposal, offsets) = directions[(firstDirection + i) % 4] if (offsets.all { (dx, dy) -> (x + dx) to (y + dy) !in elves }) { val (px, py) = proposal val (nx, ny) = (x + px) to (y + py) movements.merge(nx to ny, listOf(x to y)) { a, b -> a + b } break@search } } } val newElves = elves.toMutableSet() for ((position, candidates) in movements) { if (candidates.size == 1) { newElves -= candidates.first() newElves += position } } val newFirstDirection = (firstDirection + 1) % 4 return State(newElves, newFirstDirection) } private fun part1(data: Set<Point>): Int = generateSequence(State(data), State::next) .drop(10) .first() .let { (elves, _) -> val minX = elves.minOf { (x, _) -> x } val maxX = elves.maxOf { (x, _) -> x } val minY = elves.minOf { (_, y) -> y } val maxY = elves.maxOf { (_, y) -> y } (minY..maxY).sumOf { y -> (minX..maxX).sumOf { x -> (if (x to y !in elves) 1 else 0).toInt() } } } private fun part2(data: Set<Point>): Int = generateSequence(State(data), State::next) .zipWithNext() .withIndex() .dropWhile { (_, states) -> states.let { (s0, s1) -> s0.elves != s1.elves } } .first() .let { (idx, _) -> idx + 1 }
0
Kotlin
0
0
6f0d373bdbbcf6536608464a17a34363ea343036
3,169
advent-of-code-2022
MIT License
dcp_kotlin/src/main/kotlin/dcp/day291/day291.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day291 // day291.kt // By <NAME>, 2020. /** * We want to know how many boats of given capacity it requires to carry people of weights given to safety, * with a maximum of two people per boat. * * Strategy: sort the weights by nondecreasing order and proceed recursively. * If the heaviest person remaining and the lightest person remaining fit in a boat, then pair them together. * If they don't, send the heaviest remaining person alone. * * We do not need to do any more than pair people like this: if there was some violation of this strategy * that didn't work - say we had weights [x y z w] in order - our strategy would pair - if possible - w with x and * y with z. * * We examine the possible violations to prove that this strategy works: * 1. If w + x > capacity, then w + y and w + z are also > capacity, so w cannot be paired with anyone else. * 2. Assume w + x < capacity but y + z > capacity, i.e. maybe we could have used less boats by not pairing w * with the smallest element. * If we pair w with y, then since w > z and y + z > capacity, w + y > capacity, so this pairing doesn't work. * Similarly, w with z, then since w > y and y + z > capacity, w + z > capacity, so this pairing doesn't work. * * Note that to achieve O(n log n), we have to use an array instead of a linked list, so that the lookups * are in constant time and / or we don't have to change the collection's size: using a linked list would give us * time O(n log n + n^3) = O(n^3), since each boat requires O(n^2) (one pass to get the current lower bound, and one * to get the current upper bound) and there are O(n) boats. */ fun findBoats(capacity: Int, weights: Array<Int>): Int { // Nobody can be stranded. require(weights.all { it <= capacity }) val sortedWeights: Array<Int> = weights.sortedArray() tailrec fun aux(boats: Int = 0, lowerBound: Int = 0, upperBound: Int = weights.size - 1): Int = when { upperBound < lowerBound -> boats lowerBound == upperBound -> boats + 1 sortedWeights[upperBound] + sortedWeights[lowerBound] <= capacity -> aux(boats + 1, lowerBound + 1, upperBound - 1) else -> aux(boats + 1, lowerBound, upperBound - 1) } return aux() }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
2,290
daily-coding-problem
MIT License
src/day02/Solve02.kt
NKorchagin
572,397,799
false
{"Kotlin": 9272}
package day02 import utils.* import kotlin.time.ExperimentalTime import kotlin.time.measureTimedValue import day02.RPS.* enum class RPS(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3) } fun RPS.customCompare(other: RPS): Int = when { this == ROCK && other == SCISSORS -> 1 this == SCISSORS && other == ROCK -> -1 else -> score.compareTo(other.score) } infix fun RPS.beats(other: RPS) = this.customCompare(other) > 0 infix fun RPS.loses(other: RPS) = this.customCompare(other) < 0 infix fun RPS.ties(other: RPS) = this.customCompare(other) == 0 fun Char.toRPS(): RPS = when (this) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> error("Unknown $this") } @ExperimentalTime fun main() { fun roundOutcome(opponent: RPS, your: RPS): Int = when { your beats opponent -> 6 your loses opponent -> 0 your ties opponent -> 3 else -> error("Unexpected round outcome") } fun totalRoundScore(opponent: RPS, your: RPS): Int = roundOutcome(opponent, your) + your.score fun smartChoice(opponent: RPS, strategy: Char): RPS = when (strategy) { 'X' -> RPS.values().first { it loses opponent } // lose strategy 'Y' -> opponent // tie strategy 'Z' -> RPS.values().first { it beats opponent } // win strategy else -> error("Unknown $strategy") } fun totalSmartRoundScore(opponent: RPS, strategy: Char): Int = totalRoundScore(opponent, smartChoice(opponent, strategy)) fun solveA(fileName: String): Long { val input = readInput(fileName) return input .sumOf { totalRoundScore(it.first().toRPS(), it.last().toRPS()) } .toLong() } fun solveB(fileName: String): Long { val input = readInput(fileName) return input .sumOf { totalSmartRoundScore(it.first().toRPS(), it.last()) } .toLong() } check(solveA("day02/Example") == 15L) check(solveB("day02/Example") == 12L) val input = "day02/Input.ignore" val (part1, time1) = measureTimedValue { solveA(input) } println("Part1: $part1 takes: ${time1.inWholeMilliseconds}ms") val (part2, time2) = measureTimedValue { solveB(input) } println("Part2: $part2 takes: ${time2.inWholeMilliseconds}ms") // Alternative solution fun solveAMath(fileName: String): Long { return readInput(fileName) .map { it[0] - 'A' to it[2] - 'X' } .sumOf { it.second + 1 + listOf(3, 6, 0)[(it.second - it.first + 3) % 3] } .toLong() } fun solveBMath(fileName: String): Long { return readInput(fileName) .map { it[0] - 'A' to it[2] - 'X' } .sumOf { it.second * 3 + (it.first + it.second + 2) % 3 + 1 } .toLong() } check(solveAMath("day02/Example") == 15L) check(solveBMath("day02/Example") == 12L) val (part1Math, time1Math) = measureTimedValue { solveAMath(input) } println("Part1_math: $part1Math takes: ${time1Math.inWholeMilliseconds}ms") val (part2Math, time2Math) = measureTimedValue { solveAMath(input) } println("Part2_math: $part2Math takes: ${time2Math.inWholeMilliseconds}ms") }
0
Kotlin
0
0
ed401ab4de38b83cecbc4e3ac823e4d22a332885
3,208
AOC-2022-Kotlin
Apache License 2.0
src/day21/Day21.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day21 import readInput const val day = "21" fun calculate(monkey: String, monkeyOperationsMap: Map<String, String>): Long { val operation = monkeyOperationsMap.getValue(monkey) val operationInt = operation.toLongOrNull() if (operationInt != null) { return operationInt } val (operand1, operand, operand2) = operation.split(" ") return when (operand) { "+" -> calculate(operand1, monkeyOperationsMap) + calculate(operand2, monkeyOperationsMap) "-" -> calculate(operand1, monkeyOperationsMap) - calculate(operand2, monkeyOperationsMap) "*" -> calculate(operand1, monkeyOperationsMap) * calculate(operand2, monkeyOperationsMap) "/" -> calculate(operand1, monkeyOperationsMap) / calculate(operand2, monkeyOperationsMap) else -> error("unknown operation $operation") } } fun main() { fun calculatePart1Score(input: List<String>): Long { val monkeyOperationsMap = input.associate { val split = it.split(": ") split[0] to split[1] } return calculate("root", monkeyOperationsMap) } fun calculatePart2Score(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("/day$day/Day${day}_test") val input = readInput("/day$day/Day${day}") val part1TestPoints = calculatePart1Score(testInput) println("Part1 test points: $part1TestPoints") check(part1TestPoints == 152L) val part1points = calculatePart1Score(input) println("Part1 points: $part1points") val part2TestPoints = calculatePart2Score(testInput) println("Part2 test points: $part2TestPoints") check(part2TestPoints == 1707) val part2points = calculatePart2Score(input) println("Part2 points: $part2points") }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
1,862
advent-of-code-22-kotlin
Apache License 2.0
src/Day04.kt
Pixselve
572,907,486
false
{"Kotlin": 7404}
class SectionRange(range: String) { private val start: Int private val end: Int init { val split = range.split("-") this.start = split[0].toInt() this.end = split[1].toInt() } fun contains(value: SectionRange): Boolean { return value.start >= start && value.end <= end } fun overlaps(value: SectionRange): Boolean { return value.start <= end && value.end >= start } override fun toString(): String { return "SectionRange(start=$start, end=$end)" } } fun parseSectionRanges(input: List<String>): List<Pair<SectionRange, SectionRange>> { return input.map { val (firstPart, secondPart) = it.split(",") val first = SectionRange(firstPart) val second = SectionRange(secondPart) first to second } } fun main() { fun part1(input: List<Pair<SectionRange, SectionRange>>): Int { return input.map { it.first.contains(it.second) || it.second.contains(it.first) }.count { it } } fun part2(input: List<Pair<SectionRange, SectionRange>>): Int { return input.map { it.first.overlaps(it.second) || it.second.overlaps(it.first) }.count { it } } val testInput = readInput("Day04_test") val parsedTestInput = parseSectionRanges(testInput) check(part1(parsedTestInput) == 2) check(part2(parsedTestInput) == 4) val input = readInput("Day04") val parsedInput = parseSectionRanges(input) println(part1(parsedInput)) println(part2(parsedInput)) }
0
Kotlin
0
0
10e14393b8b6ee3f98dfd4c37e32ad81f9952533
1,530
advent-of-code-2022-kotlin
Apache License 2.0
src/commonMain/kotlin/advent2020/day18/Day18Puzzle.kt
jakubgwozdz
312,526,719
false
null
package advent2020.day18 fun part1(input: String): String { val lines = input.trim().lineSequence() // priority: parenthesis, rest val result = lines .map { shuntingYard(parse(it).toList()) { prev, _ -> prev != OpenParenthesis } } .map { rpn(it) } .sum() return result.toString() } fun part2(input: String): String { val lines = input.trim().lineSequence() // priority: parenthesis, plus, times val result = lines .map { shuntingYard(parse(it).toList()) { prev, current -> current == TimesOp && prev == TimesOp || prev == PlusOp } } .map { rpn(it) } .sum() return result.toString() } sealed class Token object TimesOp : Token() object PlusOp : Token() object OpenParenthesis : Token() object CloseParenthesis : Token() data class Digits(val v: Long) : Token() private fun parse(line: String) = sequence { var i = 0 while (i < line.length) { when (line[i]) { in '0'..'9' -> { var j = i + 1 while (j < line.length && line[j] in ('0'..'9')) j++ yield(Digits(line.substring(i, j).toLong())) i = j - 1 } '*' -> yield(TimesOp) '+' -> yield(PlusOp) '(' -> yield(OpenParenthesis) ')' -> yield(CloseParenthesis) else -> error("unknown `${line[i]}` @ $i") } i++ while (i < line.length && line[i] == ' ') i++ // skip spaces } } private fun shuntingYard(tokens: List<Token>, priorityOp: (Token, Token) -> Boolean): List<Token> { val rpn = mutableListOf<Token>() val opStack = mutableListOf<Token>() // shunting-yard tokens.forEach { token -> when (token) { PlusOp, TimesOp -> { while (opStack.isNotEmpty() && priorityOp(opStack.last(), token)) rpn.add(opStack.removeLast()) opStack.add(token) } OpenParenthesis -> opStack.add(token) CloseParenthesis -> { while (opStack.last() != OpenParenthesis) rpn.add(opStack.removeLast()) opStack.removeLast() } else -> rpn.add(token) } } while (opStack.isNotEmpty()) rpn.add(opStack.removeLast()) return rpn.toList() } private fun rpn(rpn: List<Token>): Long { val result = mutableListOf<Long>() rpn.forEach { when (it) { is Digits -> result.add(it.v) is PlusOp -> result.add(result.removeLast() + result.removeLast()) is TimesOp -> result.add(result.removeLast() * result.removeLast()) else -> error("invalid token $it") } } return result.single() }
0
Kotlin
0
2
e233824109515fc4a667ad03e32de630d936838e
2,724
advent-of-code-2020
MIT License
src/main/kotlin/day15/Day15.kt
dustinconrad
572,737,903
false
{"Kotlin": 100547}
package day15 import geometry.Coord import geometry.combine import geometry.fullyContains import geometry.mdist import geometry.overlaps import geometry.x import geometry.y import readResourceAsBufferedReader import kotlin.math.absoluteValue import kotlin.time.ExperimentalTime import kotlin.time.measureTime @OptIn(ExperimentalTime::class) fun main() { println("part 1: ${part1(readResourceAsBufferedReader("15_1.txt").readLines())}") var result: Long val time = measureTime { result = part2(readResourceAsBufferedReader("15_1.txt").readLines()); } println("part 2(${time}): $result") } fun part1(input: List<String>, y: Int = 2000000): Int { val sensors = input.map { Sensor.parse(it) } val overlaps = overlapsOnY(sensors, y) var overlapCount = overlaps.sumOf { it.count() } val beacons = sensors.map { it.closestBeacon } .filter { it.y() == y } .toSet() beacons.forEach { beacon -> if (overlaps.any { it.contains(beacon.x()) }) { overlapCount-- } } return overlapCount } fun overlapsOnY(sensors: List<Sensor>, y: Int): Set<IntRange> { val overlaps = sensors.foldRight(mutableSetOf<IntRange>()) { sensor, acc -> val sensorOverlap = sensor.yOverlap(y) val overlaps = acc.filter { it.overlaps(sensorOverlap) }.toSet() if (overlaps.isEmpty()) { acc.add(sensorOverlap) acc } else { acc.removeAll(overlaps) val combined = overlaps.fold(sensorOverlap) { l, r -> l.combine(r) } acc.add(combined) acc } } return overlaps } fun part2(input: List<String>, tl: Coord = 0 to 0, br: Coord = 4000000 to 4000000): Long { val sensors = input.map { Sensor.parse(it) } val xRange = (tl.x()..br.x()) for (y in tl.y()..br.y()) { val coord = emptyOnY(sensors, y, xRange) if (coord != null) { return coord.x().toLong() * 4000000 + coord.y() } } throw IllegalArgumentException() } fun emptyOnY(sensors: List<Sensor>, y: Int, xRange: IntRange): Coord? { val overlapsOnY = overlapsOnY(sensors, y) val spots = overlapsOnY.filter { it.fullyContains(xRange) } return if (spots.isEmpty()) { val sorted = overlapsOnY.sortedBy { it.first } val (l, r) = sorted if (r.first - l.last != 2) { throw IllegalArgumentException() } else { y to (r.first - 1) } } else { null } } data class Sensor(val pos: Coord, val closestBeacon: Coord) { val manhattanDistance = pos.mdist(closestBeacon) fun yOverlap(y: Int): IntRange { val yDist = (pos.y() - y).absoluteValue return if (yDist > manhattanDistance) { IntRange.EMPTY } else { val xOffset = (manhattanDistance - yDist).absoluteValue val left = pos.x() - xOffset val right = pos.x() + xOffset return (left .. right) } } companion object { val xy: Regex = Regex("""x=(-?\d+), y=(-?\d+)""") fun parse(line: String): Sensor { val (sensor, beacon) = xy.findAll(line).toList() .map { val (x, y) = it.destructured y.toInt() to x.toInt() } return Sensor(sensor, beacon) } } }
0
Kotlin
0
0
1dae6d2790d7605ac3643356b207b36a34ad38be
3,406
aoc-2022
Apache License 2.0
src/main/kotlin/dp/SPS.kt
yx-z
106,589,674
false
null
package dp import util.* // Shortest Palindromic Supersequence // given a String S[1..n], find the shortest palindromic superseuqnce of S fun main(args: Array<String>) { val arr = "TWENTYONE".toCharArray().toList().toOneArray() println(arr.sps()) // TWENToYOtNEwt -> 13 (inserted characters are lowercased) } fun OneArray<Char>.sps(): Int { // follow the naming convention val S = this val n = size // dp(i, j): len of SPS of S[i..j] // memoization structure: 2d array dp[1..n, 1..n] : dp[i, j] = dp(i, j) val dp = OneArray(n + 1) { OneArray(n) { 0 } } // space complexity: O(n^2) // base case: // dp(i, j) = 0 if j < i or i, j !in 1..n // = 1 if i = j (single character string is already palindromic) for (i in 1..n) { dp[i, i] = 1 } // recursive case: // dp(i, j) = dp(i + 1, j - 1) + 2 if S[i] == S[j] // since we need to wrap S[i] and S[j] as the first and the last // character in the sps // = util.min{ dp(i + 1, j), dp(i, j - 1) } + 2 // find the minimum and either wrap two S[i] around SPS or two S[j] // dependency: dp(i, j) depends on dp(i + 1, j - 1), dp(i + 1, j ), // and dp(i, j - 1) // that is entries below, to the left, and to the lower-left // evaluation order: outer loop for i from n to 1 (bottom up) for (i in n downTo 1) { // inner loop for j from i + 1 to n (left to right) for (j in i + 1..n) { dp[i, j] = if (S[i] == S[j]) { dp[i + 1, j - 1] + 2 } else { min(dp[i, j - 1], dp[i + 1, j]) + 2 } } } // time complexity: O(n^2) dp.prettyPrintTable() // we want len of SPS of S[1..n], which is dp[1, n] return dp[1, n] }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,679
AlgoKt
MIT License
Kotlin/QuickSort.kt
manan025
412,155,744
false
null
import java.util.* /* Sample Input & Output : --------------------- The first line of the input contains an integer 'n' denoting the size of the array The second line of the input contains 'n' no integers SAMPLE INPUT & OUTPUT 1 INPUT : 4 98 76 54 32 OUTPUT : 32 54 76 98 SAMPLE INPUT & OUTPUT 2 INPUT : 5 45 45 23 65 12 OUTPUT: 12 23 45 45 65 ------------------------ Time Complexity : Best Case Complexity - O(n*logn) Worst Case Complexity - O(n2) ------------------------ Space Complexity : The space complexity of quicksort is O(n*logn) */ class QuickSort(private val array: IntArray) { private fun partition(start: Int, end: Int): Int { val pivot: Int = array[end] // pivot is the last element var i = start - 1; /** * At start of each iteration, array will satisfy following * elements less than or equal to pivot are between start index and ith index * elements greater than pivot are between (i + 1)th index and (j - 1)th index */ for (j in start until end) { if (array[j] <= pivot) { i += 1 swap(i, j) } } swap(i + 1, end); // After this swap pivot will get to its sorted position return i + 1; } private fun swap(index1: Int, index2: Int) { array[index1] = array[index2].also { array[index2] = array[index1] } } fun sort(start: Int, end: Int) { if (start < end) { val partitionIndex = partition(start, end); sort(start, partitionIndex - 1) sort(partitionIndex + 1, end) } } fun printElements() { println(array.joinToString(" ")) } } fun main() { val scanner = Scanner(System.`in`) val noOfElements = scanner.nextInt() val array = IntArray(noOfElements) readInputArray(array, scanner) val quickSort = QuickSort(array) quickSort.sort(0, array.size - 1) quickSort.printElements() } fun readInputArray(array: IntArray, scanner: Scanner) { for (i in array.indices) { array[i] = scanner.nextInt() } }
115
Java
89
26
c185dcedc449c7e4f6aa5e0d8989589ef60b9565
2,105
DS-Algo-Zone
MIT License
src/main/kotlin/aoc2015/Day13.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2015 import AoCDay import aoc2015.Day13.Subject.Guest import aoc2015.Day13.Subject.Me import util.illegalInput import util.match import util.permutations // https://adventofcode.com/2015/day/13 object Day13 : AoCDay<Int>( title = "Knights of the Dinner Table", part1ExampleAnswer = 330, part1Answer = 733, part2Answer = 725, ) { private sealed interface Subject { data class Guest(val name: String) : Subject object Me : Subject } private class HappinessList(private val map: Map<Guest, Map<Guest, Int>>) { val subjects = map.keys.toList() operator fun get(subject: Subject, neighbor: Subject) = if (subject == Me || neighbor == Me) 0 else map[subject]!![neighbor]!! } private val HAPPINESS_REGEX = Regex("""(\w+) would (lose|gain) (\d+) happiness units by sitting next to (\w+)\.""") private fun parseHappinessList(list: String): HappinessList { data class Happiness(val subject: Guest, val neighbor: Guest, val amount: Int) return list .lineSequence() .map { line -> HAPPINESS_REGEX.match(line) } .map { (subject, type, amount, neighbor) -> when (type) { "lose" -> Happiness(Guest(subject), Guest(neighbor), -amount.toInt()) "gain" -> Happiness(Guest(subject), Guest(neighbor), +amount.toInt()) else -> illegalInput(type) } } .groupingBy { it.subject } .fold(initialValue = emptyMap<Guest, Int>()) { map, (_, neighbor, amount) -> map + (neighbor to amount) } .let(::HappinessList) } private fun totalChangeInHappinessForOptimalArrangement(input: String, includingMe: Boolean): Int { val happinessList = parseHappinessList(input) val subjects = if (includingMe) happinessList.subjects + Me else happinessList.subjects return subjects .permutations() .maxOf { arrangement -> val first = arrangement.first() val last = arrangement.last() arrangement .zipWithNext { a, b -> happinessList[a, b] + happinessList[b, a] }.sum() + happinessList[first, last] + happinessList[last, first] } } override fun part1(input: String) = totalChangeInHappinessForOptimalArrangement(input, includingMe = false) override fun part2(input: String) = totalChangeInHappinessForOptimalArrangement(input, includingMe = true) }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
2,564
advent-of-code-kotlin
MIT License
src/Day02.kt
paul-matthews
433,857,586
false
{"Kotlin": 18652}
typealias Command = Pair<String, Int> typealias DiveState = Triple< /* Horizontal */Int, /* Depth */ Int, /* Aim */ Int> fun List<String>.toCommands() = map { with(it.split(" ")) { Command(first(), this[1].toInt()) } } fun DiveState.add(firstAdd: Int = 0, secondAdd: Int = 0, thirdAdd: Int = 0) = copy(first + firstAdd, second + secondAdd, third + thirdAdd) fun DiveState.total() = first * second fun main() { fun part1(input: List<String>): Int = input.toCommands().fold(DiveState(0, 0, 0)) {state, (cmd, distance) -> when(cmd) { "forward" -> state.add(firstAdd = distance) "backward" -> state.add(firstAdd = -distance) "up" -> state.add(secondAdd = -distance) "down" -> state.add(secondAdd = distance) else -> state } }.total() fun part2(input: List<String>): Int = input.toCommands().fold(DiveState(0, 0, 0)) {state, (cmd, distance) -> when(cmd) { "forward" -> state.add(firstAdd = distance, secondAdd = (distance * state.third)) "backward" -> state.add(firstAdd = -distance) "up" -> state.add(thirdAdd = -distance) "down" -> state.add(thirdAdd = distance) else -> state } }.total() // test if implementation meets criteria from the description, like: val testInput = readFileContents("Day02_test") val part1Result = part1(testInput) check(part1Result == 150, {"Expected: 150 but found $part1Result"}) val part2Result = part2(testInput) check(part2Result == 900, { "Expected 900 but is: $part2Result"}) val input = readFileContents("Day02") println("Part1: " + part1(input)) println("Part2: " + part2(input)) }
0
Kotlin
0
0
2f90856b9b03294bc279db81c00b4801cce08e0e
1,814
advent-of-code-kotlin-template
Apache License 2.0
2021/src/main/kotlin/com/github/afranken/aoc/Day202108.kt
afranken
434,026,010
false
{"Kotlin": 28937}
package com.github.afranken.aoc object Day202108 { fun part1(inputs: Array<String>): Int { val input = convert(inputs) var count = 0 input.forEach { it.second.forEach { when (it.length) { 2 -> count++ // 1 4 -> count++ // 4 3 -> count++ // 7 7 -> count++ // 8 } } } return count } fun part2(inputs: Array<String>): Int { val input = convert(inputs) return input.sumOf { (input, output) -> randomConfig(input, output) } } /** * Took this from Sebastian's solution after many tries of implementing this myself. * Kudos! * * https://github.com/SebastianAigner */ private val segmentsToDigits = mapOf( setOf(0, 1, 2, 4, 5, 6) to 0, setOf(2, 5) to 1, setOf(0, 2, 3, 4, 6) to 2, setOf(0, 2, 3, 5, 6) to 3, setOf(1, 2, 3, 5) to 4, setOf(0, 1, 3, 5, 6) to 5, setOf(0, 1, 3, 4, 5, 6) to 6, setOf(0, 2, 5) to 7, setOf(0, 1, 2, 3, 4, 5, 6) to 8, setOf(0, 1, 2, 3, 5, 6) to 9 ) private fun randomConfig(words: List<String>, expectedNumbers: List<String>): Int { val inputCables = 0..6 val inputChars = 'a'..'g' fun getMapping(): Map<Char, Int> { permute@ while (true) { val perm = inputChars.zip(inputCables.shuffled()).toMap() for (word in words) { val mapped = word.map { perm[it]!! }.toSet() val isValidDigit = segmentsToDigits.containsKey(mapped) if (!isValidDigit) continue@permute } return perm } } val mapping = getMapping() val num = expectedNumbers.joinToString("") { digit -> val segments = digit.map { mapping[it]!! }.toSet() val dig = segmentsToDigits[segments]!! "$dig" } return num.toInt() } private fun convert(inputs: Array<String>): List<Pair<List<String>, List<String>>> { return inputs.map{ val (part1, part2) = it.split(" | ") val signals = part1.split(" ") val digits = part2.split(" ") Pair(signals, digits) } } }
0
Kotlin
0
0
0140f68e60fa7b37eb7060ade689bb6634ba722b
2,409
advent-of-code-kotlin
Apache License 2.0
src/aoc2022/Day01.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 private fun part1(input: List<String>): Int { var maxRecordedCalorie = 0 var currentElvesCalorieSum = 0 for (line in input) { when (val calorie = line.toIntOrNull()) { null -> currentElvesCalorieSum = 0 else -> currentElvesCalorieSum += calorie } maxRecordedCalorie = maxOf(maxRecordedCalorie, currentElvesCalorieSum) } return maxRecordedCalorie } private fun part2(input: List<String>): Int = buildList { var currentElvesCalorieSum = 0 for (lineIndex in input.indices) { val calorie = input[lineIndex].toIntOrNull() when { calorie == null -> { add(currentElvesCalorieSum) currentElvesCalorieSum = 0 } // to not miss adding last number in file lineIndex == input.lastIndex -> add(currentElvesCalorieSum + calorie) else -> currentElvesCalorieSum += calorie } } }.sortedDescending().take(3).sum() fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test")//.plus("\n") check(part1(testInput).also(::println) == 24000) check(part2(testInput).also(::println) == 45000) val input = readInput("Day01").plus("\n") println("part1: ${part1(input)}") println("part2: ${part2(input)}") }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
1,396
Kotlin-AOC-2023
Apache License 2.0
src/main/kotlin/io/dmitrijs/aoc2022/Day11.kt
lakiboy
578,268,213
false
{"Kotlin": 76651}
package io.dmitrijs.aoc2022 class Day11(input: String) { private val monkeys = createMonkeys(input) fun puzzle1() = solve(20) { it / 3L } fun puzzle2(): Long { val maxLevel = monkeys.fold(1L) { acc, monkey -> acc * monkey.divisor } return solve(10_000) { it % maxLevel } } private fun solve(rounds: Int, reduce: (Long) -> Long): Long { val inspections = MutableList(monkeys.size) { 0 } val monkeyItems = monkeys.map { it.startingItems.toMutableList() } repeat(rounds) { monkeys.forEach { monkey -> with(monkey) { val currentItems = monkeyItems[id] currentItems.forEach { level -> val newLevel = reduce(expression(level)) val monkeyId = if (newLevel % divisor == 0L) trueId else falseId monkeyItems[monkeyId].add(newLevel) } inspections[id] += currentItems.size currentItems.clear() } } } return inspections .sortedDescending() .take(2) .zipWithNext { a, b -> a.toLong() * b } .single() } private fun String.toExpression() = expressionFactory(substringAfter(" = ")) private fun String.toDivisor() = substringAfter(" by ").toLong() private data class Monkey( val id: Int, val startingItems: List<Long>, val trueId: Int, val falseId: Int, val expression: (Long) -> Long, val divisor: Long, ) private fun expressionFactory(expr: String) = { value: Long -> val (a, op, b) = expr.replace("old", value.toString()).split(" ") when (op) { "*" -> a.toLong() * b.toLong() "+" -> a.toLong() + b.toLong() "-" -> a.toLong() - b.toLong() else -> error("Unknown expression operator.") } } private fun createMonkeys(input: String) = input.split("\n\n").mapIndexed { index, commands -> val (itemsCmd, operationCmd, testCmd, trueOutcomeCmd, falseOutcomeCmd) = commands .split("\n") .drop(1) .map { it.trim() } val items = itemsCmd .substringAfter(": ") .split(", ") .map { it.toLong() } Monkey( id = index, startingItems = items, trueId = trueOutcomeCmd.substringAfter("monkey ").toInt(), falseId = falseOutcomeCmd.substringAfter("monkey ").toInt(), expression = operationCmd.toExpression(), divisor = testCmd.toDivisor() ) } }
0
Kotlin
0
1
bfce0f4cb924834d44b3aae14686d1c834621456
2,706
advent-of-code-2022-kotlin
Apache License 2.0
src/Day18.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
private fun neighbors(rock: Triple<Int, Int, Int>) = listOf( rock.copy(first = rock.first + 1), rock.copy(first = rock.first - 1), rock.copy(second = rock.second + 1), rock.copy(second = rock.second - 1), rock.copy(third = rock.third + 1), rock.copy(third = rock.third - 1), ) fun main() { val rocks = readInput("Day18") .parseAllInts() .map { (x, y, z) -> Triple(x, y, z) } .toSet() println(rocks.sumOf { rock -> neighbors(rock).count { neighbor -> neighbor !in rocks } }) val minX = rocks.minOf { it.first } - 1 val maxX = rocks.maxOf { it.first } + 1 val xRange = minX..maxX val minY = rocks.minOf { it.second } - 1 val maxY = rocks.maxOf { it.second } + 1 val yRange = minY..maxY val minZ = rocks.minOf { it.third } - 1 val maxZ = rocks.maxOf { it.third } + 1 val zRange = minZ..maxZ val start = Triple(minX, minY, minZ) val steam = mutableSetOf(start) val frontier = ArrayDeque(listOf(start)) while (frontier.isNotEmpty()) { val cube = frontier.removeFirst() neighbors(cube).forEach { neighbor -> if (neighbor.first in xRange && neighbor.second in yRange && neighbor.third in zRange && neighbor !in steam && neighbor !in rocks ) { steam.add(neighbor) frontier.add(neighbor) } } } println(rocks.sumOf { rock -> neighbors(rock).count { neighbor -> neighbor in steam } }) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
1,554
advent-of-code-2022
Apache License 2.0
src/Day03.kt
nguyendanv
573,066,311
false
{"Kotlin": 18026}
fun main() { fun part1(input: List<String>): Int { return input .flatMap { val first = it.subSequence(0, it.length / 2).toSet() val second = it.subSequence(it.length / 2, it.length).toSet() first.intersect(second).toList() } .map { if (it in 'a'..'z') it - 0x60 else it - 0x26 } .sumOf { it.code } } fun part2(input: List<String>): Int { return input.windowed(3, 3) .flatMap { (first, second, third) -> first.toSet() .intersect(second.toSet()) .intersect(third.toSet()) .toList() } .map { if (it in 'a'..'z') it - 0x60 else it - 0x26 } .sumOf { it.code } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput)==157) check(part2(testInput)==70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
376512583af723b4035b170db1fa890eb32f2f0f
1,084
advent2022
Apache License 2.0
src/Day08.kt
papichulo
572,669,466
false
{"Kotlin": 16864}
fun main() { fun isVisible(x: Int, y: Int, matrix: List<String>): Boolean { if (x == 0 || x == matrix[0].lastIndex || y == 0 || y == matrix.lastIndex) return true val tree = matrix[x][y] val yArray = matrix.map { it[x] } return (0 until x).none { matrix[y][it] >= tree } || (x + 1 until matrix[0].length).none { matrix[y][it] >= tree } || (0 until y).none { yArray[it] >= tree } || (y + 1 until matrix.size).none { yArray[it] >= tree } } fun part1(input: List<String>): Int { return input.mapIndexed { y, row -> row.filterIndexed { x, _ -> isVisible(x, y, input) } }.sumOf { it.length } } fun part2(input: List<String>): Int { return 2 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) //check(part2(testInput) == 45000) val input = readInput("Day08") println(part1(input)) //println(part2(input)) }
0
Kotlin
0
0
e277ee5bca823ce3693e88df0700c021e9081948
1,092
aoc-2022-in-kotlin
Apache License 2.0
src/Day16/Day16.kt
Nathan-Molby
572,771,729
false
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
package Day16 import readInput import java.util.Dictionary import java.util.PriorityQueue import kotlin.math.* class Valve (val id: String, val flowRate: Int) { var connectedValves = mutableListOf<Valve>() fun addConnectedValves(vararg valves: Valve) { connectedValves.addAll(valves) } } class Node (val valve: Valve): Comparable<Node> { var distance = Int.MAX_VALUE - 1 var prev: Node? = null override fun compareTo(other: Node) = compareValuesBy(this, other, {it.distance}, {it.distance}) } class ValveSimulator { var shortestDistanceBetweenPointedVales: HashMap<Valve, List<Pair<Int, Valve>>> = hashMapOf() var allValves = hashMapOf<String, Valve>() fun readInput(input: List<String>) { for (row in input) { val rowSplit = row.split(" ") val id = rowSplit[1] val flowRateString = rowSplit[4] val flowRate = flowRateString .split("=")[1] .trimEnd(';') .toInt() allValves[id] = Valve(id, flowRate) } for (row in input) { val rowSplit = row.split(" ") val id = rowSplit[1] for (i in 9 until rowSplit.size) { allValves[id]?.addConnectedValves(allValves[rowSplit[i].trimEnd(',')]!!) } } } fun preprocessValves() { val filteredValves = allValves .filter { it.value.flowRate > 0 || it.value.id == "AA" } for (valve in filteredValves) { shortestDistanceBetweenPointedVales[valve.value] = runDjikstras(valve.value) } } fun getOptimalRoute(): Int { val result = getOptimalRoute(allValves["AA"]!!, arrayListOf(allValves["AA"]!!),0, 30) return result.second } fun getOptimalRouteWithElephant(): Int { val result = getOptimalRoute(allValves["AA"]!!, allValves["AA"]!!, arrayListOf(allValves["AA"]!!), 0, 26, 26) return result.second } private fun getOptimalRoute(currentValve: Valve, visitedValves: ArrayList<Valve>, currentScore: Int, turnsRemaining: Int): Pair<ArrayList<Valve>, Int> { val possibleOtherValves = shortestDistanceBetweenPointedVales[currentValve]!! .filter { !visitedValves.contains(it.second) && it.first < turnsRemaining } var maxScore = currentScore var bestRoute = visitedValves for (distance_otherValve in possibleOtherValves) { val newSet = ArrayList(visitedValves) newSet.add(distance_otherValve.second) val turnsRemainingAfterMove = turnsRemaining - distance_otherValve.first - 1 val newScore = currentScore + turnsRemainingAfterMove * distance_otherValve.second.flowRate val optimalRouteResult = getOptimalRoute(distance_otherValve.second, newSet, newScore, turnsRemainingAfterMove) if (optimalRouteResult.second > maxScore) { bestRoute = optimalRouteResult.first maxScore = optimalRouteResult.second } } return Pair(bestRoute, maxScore) } private fun getOptimalRoute(personCurrentValve: Valve, elephantCurrentValve: Valve, visitedValves: ArrayList<Valve>, currentScore: Int, personTurnsRemaining: Int, elephantTurnsRemaining: Int): Pair<ArrayList<Valve>, Int> { var maxScore = currentScore var bestRoute = visitedValves //process human first val possiblePersonValves = shortestDistanceBetweenPointedVales[personCurrentValve]!! .filter { !visitedValves.contains(it.second) && it.first < personTurnsRemaining } possiblePersonValves.stream().parallel().forEach { person_distance_otherValve -> val newSet = ArrayList(visitedValves) newSet.add(person_distance_otherValve.second) val personTurnsRemainingAfterMove = personTurnsRemaining - person_distance_otherValve.first - 1 val newScore = currentScore + personTurnsRemainingAfterMove * person_distance_otherValve.second.flowRate val possibleElephantValves = shortestDistanceBetweenPointedVales[elephantCurrentValve]!! .filter { !newSet.contains(it.second) && it.first < elephantTurnsRemaining } //process each elephant move for each human move possibleElephantValves.stream().parallel().forEach {elephant_distance_otherValue -> val newCombinedSet = ArrayList(newSet) newCombinedSet.add(elephant_distance_otherValue.second) val elephantTurnsRemainingAfterMove = elephantTurnsRemaining - elephant_distance_otherValue.first - 1 val combinedNewScore = newScore + elephantTurnsRemainingAfterMove * elephant_distance_otherValue.second.flowRate val optimalRouteResult = getOptimalRoute(person_distance_otherValve.second, elephant_distance_otherValue.second, newCombinedSet, combinedNewScore, personTurnsRemainingAfterMove, elephantTurnsRemainingAfterMove) if (optimalRouteResult.second > maxScore) { bestRoute = optimalRouteResult.first maxScore = optimalRouteResult.second } } //deal with case where only the person moves if (possibleElephantValves.isEmpty()) { val optimalRouteResult = getOptimalRoute(person_distance_otherValve.second, elephantCurrentValve, newSet, newScore, personTurnsRemainingAfterMove, elephantTurnsRemaining) if (optimalRouteResult.second > maxScore) { bestRoute = optimalRouteResult.first maxScore = optimalRouteResult.second } } } //process elephant first val possibleElephantValves = shortestDistanceBetweenPointedVales[elephantCurrentValve]!! .filter { !visitedValves.contains(it.second) && it.first < elephantTurnsRemaining } possibleElephantValves.stream().parallel() .forEach {elephant_distance_otherValve -> val elephantNewSet = ArrayList(visitedValves) elephantNewSet.add(elephant_distance_otherValve.second) val elephantTurnsRemainingAfterMove = elephantTurnsRemaining - elephant_distance_otherValve.first - 1 val newScore = currentScore + elephantTurnsRemainingAfterMove * elephant_distance_otherValve.second.flowRate val myPossiblePersonValves = shortestDistanceBetweenPointedVales[personCurrentValve]!! .filter { !elephantNewSet.contains(it.second) && it.first < personTurnsRemaining } //process each elephant move for each human move myPossiblePersonValves.stream().parallel() .forEach {person_distance_otherValue -> val newCombinedSet = ArrayList(elephantNewSet) newCombinedSet.add(person_distance_otherValue.second) val personTurnsRemainingAfterMove = personTurnsRemaining - person_distance_otherValue.first - 1 val combinedNewScore = newScore + personTurnsRemainingAfterMove * person_distance_otherValue.second.flowRate val optimalRouteResult = getOptimalRoute(person_distance_otherValue.second, elephant_distance_otherValve.second, newCombinedSet, combinedNewScore, personTurnsRemainingAfterMove, elephantTurnsRemainingAfterMove) if (optimalRouteResult.second > maxScore) { bestRoute = optimalRouteResult.first maxScore = optimalRouteResult.second } } //deal with case where only the elephant moves if (myPossiblePersonValves.isEmpty()) { val optimalRouteResult = getOptimalRoute(personCurrentValve, elephant_distance_otherValve.second, elephantNewSet, newScore, personTurnsRemaining, elephantTurnsRemainingAfterMove) if (optimalRouteResult.second > maxScore) { bestRoute = optimalRouteResult.first maxScore = optimalRouteResult.second } } } return Pair(bestRoute, maxScore) } fun runDjikstras(valve: Valve): List<Pair<Int, Valve>> { var nodesPriorityQueue = PriorityQueue<Node>() var allNodes = allValves .map { it.key to Node(it.value) } .toMap() nodesPriorityQueue.add(allNodes[valve.id]) allNodes[valve.id]!!.distance = 0 while (nodesPriorityQueue.isNotEmpty()) { val node = nodesPriorityQueue.remove() for (neighbor in node.valve.connectedValves) { val dist = node.distance + 1 val neighborNode = allNodes[neighbor.id]!! if(dist < neighborNode.distance) { neighborNode.distance = dist neighborNode.prev = node nodesPriorityQueue.remove(neighborNode) nodesPriorityQueue.add(neighborNode) } } } return allNodes .filter { it.value.valve.flowRate > 0 } .map { Pair(it.value.distance, it.value.valve) } } } fun main() { fun part1(input: List<String>): Int { val valveSimulator = ValveSimulator() valveSimulator.readInput(input) valveSimulator.preprocessValves() return valveSimulator.getOptimalRoute() } fun part2(input: List<String>): Int { val valveSimulator = ValveSimulator() valveSimulator.readInput(input) valveSimulator.preprocessValves() return valveSimulator.getOptimalRouteWithElephant() } val testInput = readInput("Day16","Day16_test") println(part1(testInput)) check(part1(testInput) == 1651) println(part2(testInput)) check(part2(testInput) == 1707) // val input = readInput("Day16","Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
750bde9b51b425cda232d99d11ce3d6a9dd8f801
9,964
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day01.kt
rgawrys
572,698,359
false
{"Kotlin": 20855}
import utils.chunkedBy import utils.readInput fun main() { fun part1(input: List<String>): Int = maxCaloriesOfElves(input) fun part2(input: List<String>): Int = sumCaloriesOfTopElves(input, 3) // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") part1(testInput).let { check(it == 24000) { "Part 1: Incorrect result. Is `$it`, but should be `24000`" } } part2(testInput).let { check(it == 45000) { "Part 2: Incorrect result. Is `$it`, but should be `45000`" } } val input = readInput("Day01") println(part1(input)) println(part2(input)) } private fun sumCaloriesOfTopElves(input: List<String>, top: Int): Int = input .toCaloriesByElves() .sortedByDescending { it } .take(top) .sum() private fun maxCaloriesOfElves(input: List<String>): Int = input .toSnacksByElves() .maxOf(List<Int>::sum) private fun List<String>.toCaloriesByElves(): List<Int> = this.toSnacksByElves().map { it.sum() } private fun List<String>.toSnacksByElves(): List<List<Int>> = this.chunkedBy(String::isBlank) { it.toInt() }
0
Kotlin
0
0
5102fab140d7194bc73701a6090702f2d46da5b4
1,184
advent-of-code-2022
Apache License 2.0
2021/src/day22/Day22.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day22 import readInput import java.lang.IllegalStateException enum class InstructionType { ON, OFF } data class Bound(val min: Int, val max:Int) { fun isSmall() = min >= -50 && max <= 50 } data class Instruction(val type: InstructionType, val xBound: Bound, val yBound: Bound, val zBound: Bound) { fun toArea() = Area(xBound, yBound, zBound) } data class Point(val x: Int, val y: Int, val z: Int) data class Area(val xBound: Bound, val yBound: Bound, val zBound: Bound) { fun isEmpty() = size() == 0L override fun toString() = "([${xBound.min},${xBound.max}], [${yBound.min},${yBound.max}], [${zBound.min},${zBound.max}])" fun size(): Long = maxOf((xBound.max - xBound.min) + 1L,0L) * maxOf((yBound.max - yBound.min) + 1L,0L) * maxOf((zBound.max - zBound.min) + 1L,0L) } fun List<String>.toInstructions() : List<Instruction> = map { val spaces = it.split(" ") val type = when (spaces[0]) { "on" -> InstructionType.ON "off" -> InstructionType.OFF else -> throw IllegalStateException("Unknown instruction: ${spaces[0]}") } val commas = spaces[1].split(",") val xBounds = commas[0].substringAfter("x=") val yBounds = commas[1].substringAfter("y=") val zBounds = commas[2].substringAfter("z=") Instruction(type, Bound(xBounds.split("..")[0].toInt(), xBounds.split("..")[1].toInt()), Bound(yBounds.split("..")[0].toInt(), yBounds.split("..")[1].toInt()), Bound(zBounds.split("..")[0].toInt(), zBounds.split("..")[1].toInt()), ) } fun part1(lines: List<String>): Int { val instructions = lines.toInstructions() val turnedOn = mutableSetOf<Point>() for (inst in instructions) { if (!inst.xBound.isSmall() || !inst.yBound.isSmall() || !inst.zBound.isSmall()) { continue } for (x in inst.xBound.min..inst.xBound.max) { for (y in inst.yBound.min..inst.yBound.max) { for (z in inst.zBound.min..inst.zBound.max) { when (inst.type) { InstructionType.ON -> turnedOn.add(Point(x, y, z)) InstructionType.OFF -> turnedOn.remove(Point(x, y, z)) } } } } } return turnedOn.size } /** * Returns an Area that represents the intersection with the given Area * If there are no intersection, Area.isEmpty() will return true */ fun Area.intersection(other: Area): Area { return Area( Bound(maxOf(xBound.min, other.xBound.min), minOf(xBound.max, other.xBound.max)), Bound(maxOf(yBound.min, other.yBound.min), minOf(yBound.max, other.yBound.max)), Bound(maxOf(zBound.min, other.zBound.min), minOf(zBound.max, other.zBound.max)) ) } /** * Given a sub-area (other), returns a list of area that represents the current Area *Without* * the given sub-area. * Thanks to this guy for helping me visualize: https://www.youtube.com/watch?v=OatnI5y6KQw&t=856 */ fun Area.sub(other: Area): List<Area> { // left & right val a = Area(Bound(xBound.min, other.xBound.min - 1), yBound, zBound) val b = Area(Bound(other.xBound.max + 1, xBound.max), yBound, zBound) // top & bottom val c = Area(other.xBound, Bound(other.yBound.max + 1, yBound.max), zBound) val d = Area(other.xBound, Bound(yBound.min, other.yBound.min - 1), zBound) // depth val e = Area(other.xBound, other.yBound, Bound(zBound.min, other.zBound.min - 1)) val f = Area(other.xBound, other.yBound, Bound(other.zBound.max + 1, zBound.max)) return listOf(a, b, c, d, e, f).filter { !it.isEmpty() } // return areas that have a non empty volume } fun part2(lines: List<String>): Long { val instructions = lines.toInstructions() val areas = mutableListOf<Area>() for (ins in instructions) { val newArea = ins.toArea() val splitedAreas = mutableListOf<Area>() if (ins.type == InstructionType.ON) splitedAreas.add(newArea) for (a in areas) { val inter = a.intersection(newArea) // we cut the bigger cube into smaller remaining pieces // we remove the original area & add the smaller remaining pieces if (!inter.isEmpty()) { splitedAreas.addAll(a.sub(inter)) } else { splitedAreas.add(a) } } areas.clear() areas.addAll(splitedAreas) } return areas.sumOf { it.size() } } fun main() { val simple = readInput("day22/simple") println("part1(simple) => " + part1(simple)) println("part2(simple) => " + part2(simple)) val larger = readInput("day22/larger") println("part1(larger) => " + part1(larger)) println("part2(larger) => " + part2(larger)) val input = readInput("day22/input") println("part1(input) => " + part1(input)) println("part2(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
4,938
advent-of-code
Apache License 2.0
src/Day03.kt
handrodev
577,884,162
false
{"Kotlin": 7670}
fun main() { // Map each char to its priority (index 0-based) val prioMap = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun part1(input: List<String>): Int { var prioScore = 0 for (line in input) { val halfLength: Int = line.length / 2 // Divide input into two equally sized compartments val firstSet = line.substring(0, halfLength).toSet() val secondSet = line.substring(halfLength).toSet() // Get common object val common = firstSet.intersect(secondSet) if (common.isNotEmpty()) { // Accumulate priority of common object prioScore += prioMap.indexOf(common.first()) + 1 // +1 because prioMap is 0-based } } return prioScore } fun part2(input: List<String>): Int { var prioScore = 0 val groups: Int = input.size / 3 // Number of groups of 3 elves for (g in 0 until groups) { val elf1 = input[g * 3].toSet() val elf2 = input[g * 3 + 1].toSet() val elf3 = input[g * 3 + 2].toSet() // Get the object common to all 3 elves val common = elf1.intersect(elf2.intersect(elf3)) if (common.isNotEmpty()) { // Accumulate priority of common object prioScore += prioMap.indexOf(common.first()) + 1 // +1 because prioMap is 0-based } } return prioScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") part1(input).println() part2(input).println() }
0
Kotlin
0
0
d95aeb85b4baf46821981bb0ebbcdf959c506b44
1,750
aoc-2022-in-kotlin
Apache License 2.0
2021/src/main/kotlin/day12_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.mapItems fun main() { Day12Func.run() } object Day12Func : Solution<Map<String, List<String>>>() { override val name = "day12" override val parser = Parser.lines.mapItems { val (start, end) = it.split('-', limit = 2) start to end }.map { it.flatMap { (start, end) -> listOf(start to end, end to start) } .groupBy({ (start, _) -> start }) { (_, end) -> end } } val String.isBig get() = toCharArray().all(Char::isUpperCase) fun countPaths(graph: Map<String, List<String>>, visited: Set<String>, doubleVisit: String?, vertex: String): Int { if (vertex == "end") { return 1 } val novisit = graph[vertex]!!.filter { it.isBig || it !in visited }.sumOf { countPaths(graph, visited + it, doubleVisit, it) } val doublevisit = if (doubleVisit == null) { graph[vertex]!!.filter { !it.isBig && it in visited && it !in setOf("start", "end") }.sumOf { countPaths(graph, visited, it, it) } } else { 0 } return novisit + doublevisit } override fun part1(input: Map<String, List<String>>): Int { return countPaths(input, setOf("start"), "start", "start") } override fun part2(input: Map<String, List<String>>): Int { return countPaths(input, setOf("start"), null, "start") } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,366
aoc_kotlin
MIT License
src/Day01.kt
halirutan
575,809,118
false
{"Kotlin": 24802}
fun main() { fun transformInputList(input: List<String>): List<List<Int>> { val result = mutableListOf<List<Int>>() var container = mutableListOf<Int>() for (item in input) { if (item.isEmpty()) { result.add(container) container = mutableListOf() } else { val num = item.toInt() container.add(num) } } result.add(container) return result } fun part1(input: List<String>): Int { var currentMax = 0 input .map { if (it.isNotBlank()) it.toInt() else 0 } .reduce { acc, i -> val sum = acc + i if (sum > currentMax) { currentMax = sum } if (i == 0) { 0 } else { acc + i } } return currentMax } fun part2(input: List<String>): Int { val sortedSums = transformInputList(input) .map { it.sum() } .sortedDescending() return sortedSums[0] + sortedSums[1] + sortedSums[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(transformInputList(testInput).size == 5) println(part2(testInput)) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
09de80723028f5f113e86351a5461c2634173168
1,551
AoC2022
Apache License 2.0
src/main/kotlin/days/Day8Data.kt
yigitozgumus
572,855,908
false
{"Kotlin": 26037}
package days import utils.SolutionData fun main() = with(Day8Data()) { solvePart1() solvePart2() } class Day8Data : SolutionData(inputFile = "inputs/day8.txt") { val grid = rawData.map { line -> line.map { it.toString().toInt() } } val borders = rawData.first().length * 2 + (rawData.size - 2) * 2 fun processGrid(from: Int, to: Int, action: (row: Int, col: Int) -> Unit) { (from..to).forEach { row -> (from..to).forEach { column -> action(row, column) } } } fun getScenicScore(target: Int, path: List<Int>): Int { var score = 0 run lit@{ path.forEach { score += 1 if (it >= target) return@lit } } return score.coerceAtLeast(1) } } fun Day8Data.solvePart1() { var visibleTrees = 0 processGrid(from = 1, to = grid.size - 2) { row, column -> val tree = grid[row][column] val treeCol = grid[row].indices.map { grid[it][column] } if ( grid[row].subList(0, column).max() < tree || grid[row].subList(column + 1, grid.size).max() < tree || treeCol.subList(0, row).max() < tree || treeCol.subList(row + 1, grid.size).max() < tree ) { visibleTrees += 1 } } println(visibleTrees + borders) } fun Day8Data.solvePart2() { val scenicScoreList = mutableListOf<Int>() processGrid(from = 1, to = grid.size - 2) { row, column -> val tree = grid[row][column] val treeCol = grid[row].indices.map { grid[it][column] } scenicScoreList.add( getScenicScore(tree, grid[row].subList(0, column).reversed()) * getScenicScore(tree, grid[row].subList(column + 1, grid.size)) * getScenicScore(tree, treeCol.subList(0, row).reversed()) * getScenicScore(tree, treeCol.subList(row + 1, grid.size)) ) } println(scenicScoreList.maxOrNull()) }
0
Kotlin
0
0
9a3654b6d1d455aed49d018d9aa02d37c57c8946
1,703
AdventOfCode2022
MIT License
src/Day03.kt
mandoway
573,027,658
false
{"Kotlin": 22353}
fun main() { fun String.partitionRucksack(): Pair<String, String> { return substring(0, length / 2) to substring(length / 2) } fun intersectRucksack(first: String, second: String): Set<Char> { return first.toSet() intersect second.toSet() } fun Char.toPriority() = if (isLowerCase()) { code - 'a'.code + 1 } else { code - 'A'.code + 27 } fun part1(input: List<String>): Int { return input .map { it.partitionRucksack() } .map { (first, second) -> intersectRucksack(first, second).first() } .sumOf { it.toPriority() } } fun part2(input: List<String>): Int { return input .asSequence() .map { it.toSet() } .chunked(3) .map { it.reduce(Set<Char>::intersect).first() } .sumOf { it.toPriority() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0393a4a25ae4bbdb3a2e968e2b1a13795a31bfe2
1,163
advent-of-code-22
Apache License 2.0
src/Day04.kt
rosyish
573,297,490
false
{"Kotlin": 51693}
fun fullyContains(x: IntRange, y: IntRange): Boolean { return (x.first <= y.first && x.last >= y.last) || (y.first <= x.first && y.last >= x.last) // alternative below inefficient // return x.all { y.contains(it) } || y.all { x.contains(it) } } fun overlaps(x: IntRange, y: IntRange): Boolean { return x.contains(y.first) || y.contains(x.first) // alternative below inefficient // return x.intersect(y).isNotEmpty() } fun main() { // Alternative mapToRanges fun mapToRangesUseRegexCaptures(str : String) : List<IntRange> { return Regex("(\\d+)-(\\d+),(\\d+)-(\\d+)") .matchEntire(str)!! .groupValues .drop(1) .chunked(2) .map { (start, end) -> start.toInt().rangeTo(end.toInt()) } } fun mapToRanges(str: String): List<IntRange> { return str.split(",") .map { interval -> interval.split("-").let { it[0].toInt().rangeTo(it[1].toInt()) } } } val input = readInput("Day04_input") val part1Result = input .asSequence() .map { mapToRanges(it) } .count { (range1, range2) -> fullyContains(range1, range2) } val part2Result = input .asSequence() .map { mapToRanges(it) } .count { (range1, range2) -> overlaps(range1, range2) } println(part1Result) println(part2Result) }
0
Kotlin
0
2
43560f3e6a814bfd52ebadb939594290cd43549f
1,409
aoc-2022
Apache License 2.0
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D19.kt
PsHegger
325,498,299
false
null
package io.github.pshegger.aoc.y2020 import io.github.pshegger.aoc.common.BaseSolver class Y2020D19 : BaseSolver() { override val year = 2020 override val day = 19 override fun part1(): Int { val (rules, messages) = parseInput() val validRegex = "^${calculateRule(rules, false)}$".toRegex() return messages.count { validRegex.matches(it) } } override fun part2(): Int { val (rules, messages) = parseInput() val validRegex = "^${calculateRule(rules, true)}$".toRegex() return messages.count { validRegex.matches(it) } } private fun calculateRule(rules: Map<Int, List<RuleMatch>>, p2: Boolean): String { fun Int.regex(depth: Int = 0): String = when { p2 && this == 8 -> "(?:${42.regex()})+" p2 && this == 11 && depth > 10 -> "" p2 && this == 11 -> "(?:${42.regex()}${11.regex(depth + 1)}?${31.regex()})" else -> (rules[this] ?: error("Missing rule $this")) .joinToString("|", prefix = "(?:", postfix = ")") { when (it) { is RuleMatch.Data -> it.str is RuleMatch.OtherRules -> it.ruleIds.joinToString("") { id -> id.regex() } } } } return 0.regex() } private fun parseInput() = readInput { val lines = readLines() val ruleLines = lines.takeWhile { it.isNotBlank() } val messages = lines.dropWhile { it.isNotBlank() }.drop(1) Pair(parseRules(ruleLines), messages) } private fun parseRules(lines: List<String>): Map<Int, List<RuleMatch>> = lines.associate { line -> val (idStr, matchersStr) = line.split(":", limit = 2) val matchers = matchersStr .split("|") .map { matcher -> val dataMatch = "\"(.+)\"".toRegex().matchEntire(matcher.trim()) if (dataMatch != null) { RuleMatch.Data(dataMatch.groupValues[1]) } else { RuleMatch.OtherRules( matcher.trim().split(" ").map { it.toInt() } ) } } val id = idStr.toInt() Pair(id, matchers) } private sealed class RuleMatch { data class OtherRules(val ruleIds: List<Int>) : RuleMatch() data class Data(val str: String) : RuleMatch() } }
0
Kotlin
0
0
346a8994246775023686c10f3bde90642d681474
2,514
advent-of-code
MIT License
src/Day14.kt
ShuffleZZZ
572,630,279
false
{"Kotlin": 29686}
private data class CurrentUnit(var pile: Int = 500, var height: Int = 0) { fun diagonalMove(piles: Map<Int, Set<Int>>): Boolean { if (piles[pile - 1] == null || !piles[pile - 1]!!.contains(height + 1)) { pile-- height++ return true } if (piles[pile + 1] == null || !piles[pile + 1]!!.contains(height + 1)) { pile++ height++ return true } return false } fun reset(): Boolean { if (pile == 500 && height == 0) return false pile = 500 height = 0 return true } } private fun getPoints(input: List<String>) = input.map { line -> line.split(" -> ") .map { it.split(',').map(String::toInt) } .map { (first, second) -> first to second } } private fun getPiles(points: List<List<Pair<Int, Int>>>): MutableMap<Int, MutableSet<Int>> { val piles = mutableMapOf<Int, MutableSet<Int>>() points.forEach { line -> line.zipWithNext().forEach { (start, end) -> val (minPoint, maxPoint) = if (start < end) start to end else end to start val (x, y) = maxPoint - minPoint for (i in 0..x) { for (j in 0..y) { piles.computeIfAbsent(minPoint.first + i) { mutableSetOf() }.add(minPoint.second + j) } } } } return piles } private fun Set<Int>.fallUnitOrNull(height: Int) = this.filter { it > height }.minOrNull() fun main() { fun part1(input: List<String>): Int { val piles = getPiles(getPoints(input)) var cnt = 0 val point = CurrentUnit() while (true) { val pile = piles[point.pile] point.height = pile?.fallUnitOrNull(point.height) ?: return cnt point.height-- if (point.diagonalMove(piles)) continue pile.add(point.height) cnt++ point.reset() } } fun part2(input: List<String>): Int { val piles = getPiles(getPoints(input)) val floor = piles.values.maxOf { it.max() } + 2 var cnt = 0 val point = CurrentUnit() while (true) { val pile = piles.computeIfAbsent(point.pile) { mutableSetOf(floor) } point.height = pile.fallUnitOrNull(point.height) ?: floor point.height-- if (point.height != floor - 1 && point.diagonalMove(piles)) continue pile.add(point.height) cnt++ if (!point.reset()) return cnt } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e
2,862
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day08.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day class Day08 : Day("321", "1028926") { private data class Entry(val signalPatterns: List<String>, val outputPatterns: List<String>) private val entries = input .lines() .map { it.split(" | ") } .map { Entry(it[0].split(" "), it[1].split(" ")) } private val segmentIndicesByDigit = mapOf( 0 to listOf(0, 1, 2, 4, 5, 6), 1 to listOf(2, 5), 2 to listOf(0, 2, 3, 4, 6), 3 to listOf(0, 2, 3, 5, 6), 4 to listOf(1, 2, 3, 5), 5 to listOf(0, 1, 3, 5, 6), 6 to listOf(0, 1, 3, 4, 5, 6), 7 to listOf(0, 2, 5), 8 to listOf(0, 1, 2, 3, 4, 5, 6), 9 to listOf(0, 1, 2, 3, 5, 6) ) override fun solvePartOne(): Any { return entries .flatMap { it.outputPatterns } .map { it.length } .count { it == 2 || it == 4 || it == 3 || it == 7 } } override fun solvePartTwo(): Any { val segmentsPermutations = generateSegmentsPermutations() return entries.sumOf { entry -> val segments = segmentsPermutations.find { segments -> entry.signalPatterns.all { patternToDigit(it, segments) != null } }!! (0 until 4) .map { patternToDigit(entry.outputPatterns[it], segments) } .joinToString("") .toInt() } } private fun generateSegmentsPermutations( prefix: String = "abcdefg", suffix: String = "", generatedPermutations: MutableList<String> = mutableListOf() ): List<String> { if (prefix.isEmpty()) { generatedPermutations.add(suffix) } else { for (i in prefix.indices) { generateSegmentsPermutations( prefix.substring(0, i) + prefix.substring(i + 1), suffix + prefix[i], generatedPermutations ) } } return generatedPermutations } private fun patternToDigit(pattern: String, segments: String): Int? { outer@ for ((digit, segmentIndices) in segmentIndicesByDigit) { if (pattern.length != segmentIndices.size) { continue } for (index in segmentIndices) { if (segments[index] !in pattern) { continue@outer } } return digit } return null } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
2,515
advent-of-code-2021
MIT License
src/main/kotlin/adventofcode2017/Day24ElectromagneticMoat.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2017 class Day24ElectromagneticMoat data class Port(val sideA: Int, val sideB: Int) { val strength: Int get() = sideA + sideB } class Bridge(val ports: List<Port> = listOf()) { fun totalStrength(): Int = ports.sumOf { it.strength } val totalLength: Int = ports.size override fun toString(): String { return buildString { append("[Strength: ${totalStrength()}]: ") ports.forEach { append("[") append(it.sideA) append("/") append(it.sideB) append("]") append(" - ") } } } } class BridgeBuilder(input: List<String>) { val constructedBridges = mutableSetOf<Bridge>() val ports: List<Port> val strongestBridge: Int get() { return if (constructedBridges.isNotEmpty()) { constructedBridges.maxOf { it.totalStrength() } } else 0 } fun longestStrongestBridge(): Int { val maxLength = constructedBridges.maxOf { bridge -> bridge.totalLength } return constructedBridges.filter { bridge -> bridge.totalLength == maxLength }.maxOf { it.totalStrength() } } init { ports = input.map { portConfiguration -> val parts = portConfiguration.split("/") Port(parts[0].toInt(), parts[1].toInt()) } } fun buildBridge( usedPorts: List<Port> = mutableListOf(), currentEnding: Int = 0, remainingPorts: List<Port> = ports ) { val eligiblePorts = findMatchingPorts(currentEnding, remainingPorts) if (eligiblePorts.isNotEmpty()) { eligiblePorts.forEach { eligible -> val otherPorts = remainingPorts.filter { it != eligible } val otherEnd = if (eligible.sideA == currentEnding) eligible.sideB else eligible.sideA constructedBridges.add(Bridge(usedPorts + eligible)) buildBridge(usedPorts + eligible, otherEnd, otherPorts) } } else { constructedBridges.add(Bridge(usedPorts)) } } private fun findMatchingPorts(pins: Int, ports: List<Port>): List<Port> { return ports.filter { port -> port.sideA == pins || port.sideB == pins } } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
2,342
kotlin-coding-challenges
MIT License
archive/2022/Day23.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 110 private const val EXPECTED_2 = 20 private class Day23(isTest: Boolean) : Solver(isTest) { val dirs = listOf(0 to -1, 1 to -1, 1 to 0, 1 to 1, 0 to 1, -1 to 1, -1 to 0, -1 to -1) val startCoords = readAsLines().withIndex().flatMap { (y, line) -> line.withIndex().filter { it.value == '#' }.map { (x, value) -> x to y } }.toSet() fun surroundDirs(index: Int) = listOf(dirs[(index - 1).mod(dirs.size)], dirs[index], dirs[(index + 1).mod(dirs.size)]) operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>) = first + other.first to second + other.second fun draw(c: Set<Pair<Int, Int>>) { val field = Array<Array<Boolean>>(12) { Array<Boolean>(12) { false } } for ((x, y) in c) { field[y + 2][x + 2] = true } for (y in 0 until field.size) { println(field[y].joinToString("") { if (it) "#" else "." }) } println() } fun part1(): Any { val dirIndex = mutableListOf(0, 4, 6, 2) var coords = startCoords // draw(coords) repeat(10) { coords = simulate(coords, dirIndex) dirIndex.add(dirIndex.removeFirst()) } return (coords.maxOf { it.first } - coords.minOf { it.first } + 1) * (coords.maxOf { it.second } - coords.minOf { it.second } + 1) - coords.size } private fun simulate(coords: Set<Pair<Int, Int>>, dirIndex: MutableList<Int>): Set<Pair<Int, Int>> { var proposedCoords = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() for (elf in coords) { val allEmpty = dirs.all { (elf + it) !in coords } if (!allEmpty) { var ok = false for (index in dirIndex) { if (surroundDirs(index).none { (elf + it) in coords }) { proposedCoords[elf] = elf + dirs[index] ok = true break } } if (!ok) { proposedCoords[elf] = elf } } else { proposedCoords[elf] = elf } } val coordCount = proposedCoords.values.groupBy { it } return proposedCoords.map { (key, value) -> if (coordCount[value]!!.size == 1) { value } else key }.toSet() } fun part2(): Any { var dirIndex = mutableListOf(0, 4, 6, 2) var coords = startCoords repeat(Int.MAX_VALUE) { round -> coords = simulate(coords, dirIndex).also { if (it == coords) { return round + 1 } } dirIndex.add(dirIndex.removeFirst()) } error("") } } fun main() { val testInstance = Day23(true) val instance = Day23(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
3,196
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/lucaszeta/adventofcode2020/day13/day13.kt
LucasZeta
317,600,635
false
null
package com.lucaszeta.adventofcode2020.day13 import com.lucaszeta.adventofcode2020.ext.getResourceAsText import java.lang.IllegalArgumentException fun main() { val input = getResourceAsText("/day13/notes.txt") .split("\n") .filter { it.isNotEmpty() } val (earliestTimestamp, buses) = parseBusData(input) val nearestBus = calculateNearestBusArrival(buses, earliestTimestamp) println("Bus #${nearestBus.first} is going to arrive in ${nearestBus.second} minutes") println("Multiplication: ${nearestBus.first * nearestBus.second}") val sequentialBusDeparture = calculateSequentialBusDepartures(buses) println("Earliest sequential bus departure: $sequentialBusDeparture") } fun calculateSequentialBusDepartures(buses: List<Bus>): Long { var earliestTimestamp = 0L var accumulator = buses.first().id for (index in 0 until buses.size - 1) { var multiplier = 1 val nextBus = buses[index + 1] while (true) { val timestamp = earliestTimestamp + accumulator * multiplier if ((timestamp + nextBus.offset).rem(nextBus.id) == 0L) { earliestTimestamp = timestamp if (index < buses.size - 2) { accumulator = buses .slice(0..(index + 1)) .map { it.id } .reduce(::leastCommonMultiplier) } break } multiplier++ } } return earliestTimestamp } fun calculateNearestBusArrival(buses: List<Bus>, earliestTimestamp: Int) = buses .map { bus -> bus.id to bus.id - earliestTimestamp.rem(bus.id) } .minByOrNull { it.second } ?: throw IllegalArgumentException("Invalid input") fun parseBusData(input: List<String>) = input.run { val timestamp = first().toInt() val buses = last() .split(",") .mapIndexed { index, stringValue -> if (stringValue != "x") { Bus(stringValue.toLong(), index) } else { null } } .filterNotNull() Pair(timestamp, buses) } private fun leastCommonMultiplier(number1: Long, number2: Long): Long { var a = number1 var b = number2 while (a != b) { if (a > b) { a -= b } else { b -= a } } return number1 * number2 / a }
0
Kotlin
0
1
9c19513814da34e623f2bec63024af8324388025
2,419
advent-of-code-2020
MIT License
src/main/kotlin/com/lucaszeta/adventofcode2020/day01/day01.kt
LucasZeta
317,600,635
false
null
package com.lucaszeta.adventofcode2020.day01 import com.lucaszeta.adventofcode2020.ext.getResourceAsText fun findPair( input: List<Int>, sumGoal: Int ): Pair<Int, Int> { val numbers = input.sorted() for (index in 0 until numbers.size - 1) { search@ for (secondIndex in (index + 1) until numbers.size) { val operand1 = numbers[index] val operand2 = numbers[secondIndex] val sum = operand1 + operand2 when { sum == sumGoal -> return operand1 to operand2 sum > sumGoal -> break@search } } } throw IllegalArgumentException("There are no elements in this input that sum to %d".format(sumGoal)) } fun findTriple( input: List<Int>, sumGoal: Int ): Triple<Int, Int, Int> { val numbers = input.sorted() for (index in 0 until numbers.size - 2) { for (secondIndex in (index + 1) until numbers.size - 1) { search@ for (thirdIndex in (secondIndex + 1) until numbers.size) { val operand1 = numbers[index] val operand2 = numbers[secondIndex] val operand3 = numbers[thirdIndex] val sum = operand1 + operand2 + operand3 when { sum == sumGoal -> return Triple(operand1, operand2, operand3) sum > sumGoal -> break@search } } } } throw IllegalArgumentException("There are no elements in this input that sum to %d".format(sumGoal)) } fun main() { val input = getResourceAsText("/day01/expense-report.txt") .split("\n") .filter { it.isNotEmpty() } .map { it.toInt() } val pair = findPair(input, 2020) val triple = findTriple(input, 2020) println("Day 1 part 1: %d".format(pair.first * pair.second)) println("Day 1 part 2: %d".format(triple.first * triple.second * triple.third)) }
0
Kotlin
0
1
9c19513814da34e623f2bec63024af8324388025
1,947
advent-of-code-2020
MIT License
src/main/kotlin/g1901_2000/s1977_number_of_ways_to_separate_numbers/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1977_number_of_ways_to_separate_numbers // #Hard #String #Dynamic_Programming #Suffix_Array // #2023_06_21_Time_199_ms_(100.00%)_Space_37.6_MB_(100.00%) class Solution { fun numberOfCombinations(str: String): Int { if (str[0] == '1' && str[str.length - 1] == '1' && str.length > 2000) return 755568658 val num = str.toCharArray() val n = num.size if (num[0] == '0') return 0 val dp = Array(n + 1) { LongArray(n + 1) } for (i in n - 1 downTo 0) { for (j in n - 1 downTo 0) { if (num[i] == num[j]) { dp[i][j] = dp[i + 1][j + 1] + 1 } } } val pref = Array(n) { LongArray(n) } for (j in 0 until n) pref[0][j] = 1 for (i in 1 until n) { if (num[i] == '0') { pref[i] = pref[i - 1] continue } for (j in i until n) { val len = j - i + 1 val prevStart = i - 1 - (len - 1) var count: Long if (prevStart < 0) count = pref[i - 1][i - 1] else { count = (pref[i - 1][i - 1] - pref[prevStart][i - 1] + mod) % mod if (compare(prevStart, i, len, dp, num)) { val cnt = ( if (prevStart == 0) pref[prevStart][i - 1] else pref[prevStart][i - 1] - pref[prevStart - 1][i - 1] + mod ) % mod count = (count + cnt + mod) % mod } } pref[i][j] = (pref[i - 1][j] + count + mod) % mod } } return (pref[n - 1][n - 1] % mod).toInt() % mod } private fun compare(i: Int, j: Int, len: Int, dp: Array<LongArray>, s: CharArray): Boolean { val common = dp[i][j].toInt() if (common >= len) return true return s[i + common] < s[j + common] } companion object { var mod = 1000000007 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,110
LeetCode-in-Kotlin
MIT License
facebook/y2019/round1/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2019.round1 private fun solve(): Int { val (n, h, v) = readInts() val (x, y) = List(2) { val (x1, x2, ax, bx, cx, dx) = readInts() val x = IntArray(n) x[0] = x1 x[1] = x2 for (i in 2 until n) { x[i] = ((ax * 1L * x[i - 2] + bx * 1L * x[i - 1] + cx) % dx + 1).toInt() } x } val sorted = listOf(x to y, y to x).map { (x, y) -> val longs = List(n) { (x[it].toLong() shl 32) + y[it].toLong() }.sorted() longs.map { (it shr 32).toInt() } to longs.map { it.toInt() } } return if (h + v < n) -1 else List(2) { t -> solveVertical(sorted[t].second, sorted[t].first, sorted[1 - t].first, listOf(h, v)[t]) }.minOrNull()!! } fun solveVertical(x: List<Int>, y: List<Int>, xSorted: List<Int>, v: Int): Int { val n = x.size var ans = y.last() + if (v < n) xSorted.last() else 0 val xAffordable = xSorted.getOrElse(n - v - 1) { 0 } var xMaxAbove = 0 var xMax = 0 for (i in n - 1 downTo 0) { xMax = maxOf(xMax, x[i]) if (i > 0 && y[i] == y[i - 1]) continue if (xMaxAbove <= xMax) { ans = minOf(ans, y[i] + maxOf(xAffordable, xMaxAbove)) xMaxAbove = xMax } if (i < v) break xMax = 0 } return ans } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private operator fun <T> List<T>.component6(): T { return get(5) } private val isOnlineJudge = System.getProperty("ONLINE_JUDGE") == "true" @Suppress("unused") private val stdStreams = (false to false).apply { if (!isOnlineJudge) { if (!first) System.setIn(java.io.File("input.txt").inputStream()) if (!second) System.setOut(java.io.PrintStream("output.txt")) }} private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,781
competitions
The Unlicense
src/Day08.kt
RichardLiba
572,867,612
false
{"Kotlin": 16347}
fun main() { fun readGrid(input: List<String>): List<List<Int>> { return input.map { it.map { s -> s.digitToInt() } } } fun visibleTrees(grid: List<List<Int>>): Int { val n = grid.size val m = grid[0].size val visible = Array(n) { BooleanArray(m) } for (i in grid.indices) { var heighest = -1 var heighestOtherDir = -1 for (j in 0 until m) { if (grid[i][j] > heighest) { heighest = grid[i][j] visible[i][j] = true } if (grid[i][m - 1 - j] > heighestOtherDir) { heighestOtherDir = grid[i][m - 1 - j] visible[i][m - 1 - j] = true } } } for (j in grid[0].indices) { var heighest = -1 var heighestOtherDir = -1 for (i in 0 until n) { if (grid[i][j] > heighest) { heighest = grid[i][j] visible[i][j] = true } if (grid[n - 1 - i][j] > heighestOtherDir) { heighestOtherDir = grid[n - 1 - i][j] visible[n - 1 - i][j] = true } } } return visible.sumOf { it.count { it } } } fun part1(input: List<String>): Int { val grid = readGrid(input) val visibleTrees = visibleTrees(grid) return visibleTrees } fun part2(input: List<String>): Int { return 1 } val input = readInput("Day08") println(part1(input)) val inputTEst = readInput("Day08_test") println(part1(inputTEst)) println(part2(input)) }
0
Kotlin
0
0
6a0b6b91b5fb25b8ae9309b8e819320ac70616ed
1,746
aoc-2022-in-kotlin
Apache License 2.0
src/Day16.kt
TinusHeystek
574,474,118
false
{"Kotlin": 53071}
import kotlin.math.ceil class Day16 : Day(16) { data class Node(val key: String, val rate: Int) { val valves = mutableListOf<String>() } data class Snapshot(val keys: List<String>, val estimate: Int, val opened: Set<String>, val time: Int) private fun parse(input: List<String>): Map<String, Node> { val pattern = """Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? (.+)""".toRegex() return buildMap { input.forEach { line -> pattern.find(line)!!.groupValues.let { (_, key, rate, valves) -> val valveKeys = valves.split(", ") put(key, Node(key, rate.toInt()).apply { this.valves.addAll(valveKeys) } ) } } } } private fun estimate(maps: Map<String, Node>, playerNum: Int = 1, round: Int = 30): Map<List<String>, Int> { val start = (1..playerNum).map { "AA" } val estimates = mutableMapOf(start to 0) val queue = ArrayDeque(listOf(Snapshot(start, 0, emptySet(), round * playerNum))) val bucket = mutableSetOf<Snapshot>() fun addToBucket(snap: Snapshot) { if (snap.keys !in estimates || snap.keys.filter { it !in snap.opened }.distinct().sumOf { maps.getValue(it).rate }.let { it * (snap.time - 1) } + snap.estimate >= estimates.getValue(snap.keys) ) { bucket.add(snap) } } while (queue.isNotEmpty() || bucket.isNotEmpty()) { if (queue.isEmpty()) { queue.addAll(bucket) bucket.clear() } val (current, est, opened, rem) = queue.removeFirst() val index = rem % playerNum val nodes = current.map(maps::getValue) val time = ceil(rem.toFloat() / playerNum).toInt() when { rem <= 0 -> continue // finish // no value to open nodes[index].rate == 0 -> Unit // already opened current[index] in opened -> Unit est + nodes[index].rate * (time - 1) > estimates.getOrDefault(current, 0) -> { val v = est + nodes[index].rate * (time - 1) estimates[current] = v addToBucket(Snapshot(current, v, opened + current[index], rem - 1)) } else -> Unit } nodes[index].valves.forEach { val next = current.toMutableList().apply { this[index] = it } addToBucket(Snapshot(next, est, opened, rem - 1)) } } return estimates } // --- Part 1 --- override fun part1ToInt(input: String): Int { val maps = parse(input.lines()) val estimates = estimate(maps) return estimates.values.max() } // --- Part 2 --- override fun part2ToInt(input: String): Int { val maps = parse(input.lines()) val estimates = estimate(maps, 2, 26) return estimates.values.max() } } fun main() { Day16().printToIntResults(1651, 1707) }
0
Kotlin
0
0
80b9ea6b25869a8267432c3a6f794fcaed2cf28b
3,291
aoc-2022-in-kotlin
Apache License 2.0
kotlin/zebra-puzzle/src/main/kotlin/ZebraPuzzle.kt
ErikSchierboom
27,632,754
false
{"C++": 14523188, "C": 1712536, "C#": 843402, "JavaScript": 766003, "Java": 570202, "F#": 559855, "Elixir": 504471, "Haskell": 499200, "Shell": 393291, "TypeScript": 381035, "Kotlin": 326721, "Scala": 321830, "Clojure": 303772, "Nim": 283613, "Ruby": 233410, "Elm": 157678, "Crystal": 155384, "Go": 152557, "Gleam": 150059, "Zig": 139897, "Python": 115799, "Makefile": 105638, "COBOL": 86064, "Prolog": 80765, "D": 66683, "CoffeeScript": 66377, "Scheme": 63956, "CMake": 62581, "Visual Basic .NET": 57136, "Rust": 54763, "Julia": 49727, "R": 43757, "Swift": 42546, "WebAssembly": 29203, "Wren": 27102, "Ballerina": 26773, "Fortran": 10325, "PowerShell": 4747, "OCaml": 4629, "Awk": 4125, "Tcl": 2927, "PLSQL": 2402, "Roff": 2089, "Lua": 1038, "Common Lisp": 915, "Assembly": 753, "Reason": 215, "jq": 37, "JSONiq": 16}
import kotlin.math.absoluteValue enum class Color { Red, Green, Ivory, Yellow, Blue } enum class Resident { Englishman, Spaniard, Ukrainian, Norwegian, Japanese } enum class Pet { Dog, Snails, Fox, Horse, Zebra } enum class Drink { Coffee, Tea, Milk, OrangeJuice, Water } enum class Smoke { OldGold, Kools, Chesterfields, LuckyStrike, Parliaments } data class Solution( val colors: List<Color>, val residents: List<Resident>, val pets: List<Pet>, val drinks: List<Drink>, val smokes: List<Smoke> ) class ZebraPuzzle { fun drinksWater() = solution.residents[solution.drinks.indexOf(Drink.Water)].name fun ownsZebra() = solution.residents[solution.pets.indexOf(Pet.Zebra)].name private val solution = calculateSolution() private fun calculateSolution(): Solution { for (colors in permutations<Color>().filter { it.matchesColorRules() }) { for (residents in permutations<Resident>().filter { it.matchesResidentRules(colors) }) { for (pets in permutations<Pet>().filter { it.matchesPetRules(residents) }) { for (drinks in permutations<Drink>().filter { it.matchesDrinkRules(colors, residents) }) { for (smokes in permutations<Smoke>().filter { it.matchesSmokeRules(colors, residents, drinks, pets) }) { return Solution(colors, residents, pets, drinks, smokes) } } } } } throw Exception("No solution could be found") } private fun List<Color>.matchesColorRules() = indexOf(Color.Green) == indexOf(Color.Ivory) + 1 private fun List<Resident>.matchesResidentRules(colors: List<Color>) = indexOf(Resident.Norwegian) == 0 && indexOf(Resident.Englishman) == colors.indexOf(Color.Red) && (indexOf(Resident.Norwegian) - colors.indexOf(Color.Blue)).absoluteValue == 1 private fun List<Pet>.matchesPetRules(residents: List<Resident>) = indexOf(Pet.Dog) == residents.indexOf(Resident.Spaniard) private fun List<Drink>.matchesDrinkRules(colors: List<Color>, residents: List<Resident>) = indexOf(Drink.Coffee) == colors.indexOf(Color.Green) && indexOf(Drink.Tea) == residents.indexOf(Resident.Ukrainian) && indexOf(Drink.Milk) == 2 private fun List<Smoke>.matchesSmokeRules( colors: List<Color>, residents: List<Resident>, drinks: List<Drink>, pets: List<Pet> ) = indexOf(Smoke.OldGold) == pets.indexOf(Pet.Snails) && indexOf(Smoke.Kools) == colors.indexOf(Color.Yellow) && (indexOf(Smoke.Chesterfields) - pets.indexOf(Pet.Fox)).absoluteValue == 1 && (indexOf(Smoke.Kools) - pets.indexOf(Pet.Horse)).absoluteValue == 1 && indexOf(Smoke.LuckyStrike) == drinks.indexOf(Drink.OrangeJuice) && indexOf(Smoke.Parliaments) == residents.indexOf(Resident.Japanese) } private inline fun <reified T : Enum<T>> permutations() = enumValues<T>().toList().permutations() private fun <T> List<T>.permutations(): Sequence<List<T>> = if (size <= 1) sequenceOf(this) else asSequence().flatMap { seq -> (this - seq).permutations().map { listOf(seq) + it } }
0
C++
10
29
d84c9d48a2d3adb0c37d7bd93c9a759d172bdd8e
3,318
exercism
Apache License 2.0
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day23/Day23.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day23 import eu.janvdb.aocutil.kotlin.point2d.Direction import eu.janvdb.aocutil.kotlin.point2d.Point2D import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input23-test1.txt" //const val FILENAME = "input23-test2.txt" const val FILENAME = "input23.txt" fun main() { val elves = readLines(2022, FILENAME).toElves() part1(elves) part2(elves) } fun part1(elves: Elves) { var current = elves repeat(10) { current = current.step() } println(current.emptyGrounds()) } fun part2(elves: Elves) { var current = elves var rounds = 0 while (true) { val next = current.step() rounds++ if (current == next) break current = next } println("$rounds rounds") } class Elves(val elves: Set<Point2D>, val directions: List<Direction>) { val minY = elves.minOf { it.y } val maxY = elves.maxOf { it.y } val minX = elves.minOf { it.x } val maxX = elves.maxOf { it.x } fun step(): Elves { fun tryMoveElf(position: Point2D, position1: Point2D, position2: Point2D): Point2D? { return if (elves.contains(position) || elves.contains(position1) || elves.contains(position2)) null else position } fun tryMoveElf(position: Point2D): Point2D? { val up = position.up() val down = position.down() val left = position.left() val right = position.right() val upLeft = up.left() val upRight = up.right() val downLeft = down.left() val downRight = down.right() if (!elves.contains(up) && !elves.contains(down) && !elves.contains(left) && !elves.contains(right) && !elves.contains(upLeft) && !elves.contains(upRight) && !elves.contains(downLeft) && !elves.contains(downRight) ) return position return directions.asSequence().map { direction -> when (direction) { Direction.N -> tryMoveElf(up, upLeft, upRight) Direction.S -> tryMoveElf(down, downLeft, downRight) Direction.W -> tryMoveElf(left, upLeft, downLeft) Direction.E -> tryMoveElf(right, upRight, downRight) } }.firstOrNull { it != null } } val moves = elves.asSequence().map { Pair(it, tryMoveElf(it)) } .filter { it.second != null } .map { Pair(it.first, it.second!!) } .toMap() val doubleLocations = moves.values.groupingBy { it }.eachCount().filter { it.value >= 2 }.keys val newElves = elves.asSequence().map { val move = moves[it] if (move != null && !doubleLocations.contains(move)) move else it }.toSet() val newDirections = directions.toMutableList() newDirections.add(newDirections.removeAt(0)) return Elves(newElves, newDirections) } fun emptyGrounds(): Int { return (minY..maxY).map { y -> (minX..maxX).count { x -> !elves.contains(Point2D(x, y)) } }.sum() } override fun toString(): String { val builder = StringBuilder() for (y in minY..maxY) { for (x in minX..maxX) { val ch = if (elves.contains(Point2D(x, y))) '#' else '.' builder.append(ch) } builder.append('\n') } return builder.toString() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Elves if (elves != other.elves) return false return true } override fun hashCode(): Int { return elves.hashCode() } } fun List<String>.toElves(): Elves { val elves = this.flatMapIndexed { y, line -> line .mapIndexed { x, ch -> Pair(Point2D(x, y), ch) } .filter { it.second == '#' } .map { it.first } }.toSet() return Elves(elves, listOf(Direction.N, Direction.S, Direction.W, Direction.E)) }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
4,168
advent-of-code
Apache License 2.0
src/Day03.kt
RickShaa
572,623,247
false
{"Kotlin": 34294}
fun main() { val fileName = "day03.txt" val testFileName = "day03_test.txt" val input:List<String> = FileUtil.getListOfLines(fileName); //Helper function for mapping chars to priority numbers fun createPriorityMap(letters:List<Char>):Map<Char, Int>{ var map = mutableMapOf<Char, Int>() letters.forEachIndexed{index, element -> map[element] = index+1 } return map } //Generate alphabet from a...zA...Z val lowerCaseLetters = AlphabetUtil.createLetters(97,122) val upperCaseLetters = AlphabetUtil.createLetters(65,90) val letters = ListUtil.concat(lowerCaseLetters,upperCaseLetters) //prioritize each letter val priorityMap = createPriorityMap(letters) //PART 1 fun String.splitInHalf():List<String>{ val midIndex = this.length /2; return listOf(this.substring(0, midIndex), this.substring(midIndex)) } //Find common char in a tuple fun List<String>.commonChars():List<Char>{ val first = this[0].toCharArray() val second = this[1].toCharArray(); return first.map{element -> second.find { it == element }}.filterNotNull() } //sum priorities up val sum = input.map{ it.splitInHalf() }.map { rucksack -> priorityMap[rucksack.commonChars().first()]!! }.sumOf { s -> s } println(sum) //PART 2 //group by three val groups = input.chunked(3) // find common char in Triple - utilizing commonChars() method from part 1 fun List<String>.commonCharTriple():Char{ val firstTuple = this.toMutableList().take(2) val third = this[2] val commonChars = firstTuple.commonChars() return commonChars.firstNotNullOf { element -> third.find { it == element } } } //get sum val badgeSum = groups.map { rucksacks -> priorityMap[rucksacks.commonCharTriple()]!!}.sumOf { s -> s } println(badgeSum) }
0
Kotlin
0
1
76257b971649e656c1be6436f8cb70b80d5c992b
1,902
aoc
Apache License 2.0
src/y2022/Day14.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.Direction import util.Pos import util.readInput object Day14 { private fun parse(input: List<String>): Set<Pos> { return input.map { lineToCoordinates(it) }.flatten().toSet() } private fun lineToCoordinates(line: String): List<Pos> { 1..5 return line.split(Regex(" -> |,")) .asSequence() .map { it.toInt() } .chunked(2) .map { (x, y) -> x to y } .windowed(2, 1) .map { (p1, p2) -> (p1..p2) } .flatten() .toList() } operator fun Pos.rangeTo(other: Pos): List<Pos> { return if (first == other.first) { if (second < other.second) { (second..other.second).map { first to it } } else { (second downTo other.second).map { first to it } } } else { if (first < other.first) { (first..other.first).map { it to second } } else { (first downTo other.first).map { it to second } } } } fun part1(input: List<String>): Int { val blocked = parse(input).toMutableSet() val maxY = blocked.maxBy { it.second }.second val start = 500 to 0 val blocks = blocked.size outer@ while (true) { var currentSand = start while (true) { val next = oneSandStep(currentSand, blocked)!! if (next == currentSand) { blocked.add(currentSand) break } currentSand = next if (currentSand.second > maxY) { break@outer } } } return blocked.size - blocks } private fun oneSandStep(start: Pos, blocks: Set<Pos>): Pos? { val down = Direction.UP.move(start) val downLeft = Direction.LEFT.move(down) val downRight = Direction.RIGHT.move(down) return listOf(down, downLeft, downRight, start).firstOrNull { it !in blocks } } fun part2(input: List<String>): Int { val blocked = parse(input).toMutableSet() val maxY = blocked.maxBy { it.second }.second + 2 blocked.addAll((500 - 2 * maxY to maxY)..(500 + 2 * maxY to maxY)) val start = 500 to 0 val blocks = blocked.size outer@ while (true) { var currentSand = start while (true) { val next = oneSandStep(currentSand, blocked) ?: break@outer if (next == currentSand) { blocked.add(currentSand) break } currentSand = next } } return blocked.size - blocks } } fun main() { val testInput = """ 498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9 """.trimIndent().split("\n") println("------Tests------") println(Day14.part1(testInput)) println(Day14.part2(testInput)) println("------Real------") val input = readInput("resources/2022/day14") println(Day14.part1(input)) println(Day14.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
3,201
advent-of-code
Apache License 2.0
src/Day03.kt
purdyk
572,817,231
false
{"Kotlin": 19066}
fun main() { val lOffset = 'a'.code - 1 val uOffset = 'A'.code - 1 fun prio(c: Char): Int { return if (c.isUpperCase()) { (c.code - uOffset) + 26 } else { c.code - lOffset } } fun part1(input: List<String>): String { val sacks = input.map { sack -> (sack.length / 2).let { mid -> sack.subSequence(0, mid) to sack.subSequence(mid, sack.length) } } val common = sacks.map { sack -> sack.first.first { it in sack.second } } // println(common) val ints = common.map { prio(it) } // println(ints) return ints.sum().toString() } fun part2(input: List<String>): String { val groups = input.chunked(3) val common = groups.map { sacks -> sacks.reduce { acc, sack -> acc.filter { it in sack } }[0] } println(common) return common.map { prio(it) }.sum().toString() } val day = "03" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test").split("\n") check(part1(testInput) == "157") check(part2(testInput) == "70") println("Test: ") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day${day}").split("\n") println("\nProblem: ") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
02ac9118326b1deec7dcfbcc59db8c268d9df096
1,485
aoc2022
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2023/Day04.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2023 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part4A : PartSolution() { internal lateinit var cards: List<Card> override fun parseInput(text: String) { val cards = mutableListOf<Card>() val pattern = "Card +\\d+: +((?:\\d+ *)+) \\| +((?:\\d+ *)+)".toRegex() for (line in text.split("\n")) { val match = pattern.find(line) as MatchResult val winningNumbers = match.groupValues[1].split(" +".toRegex()).map { it.toInt() } val numbers = match.groupValues[2].split(" +".toRegex()).map { it.toInt() } cards.add(Card(winningNumbers, numbers)) } this.cards = cards } override fun getExampleAnswer() = 13 override fun compute(): Int { return cards.sumOf { it.points } } internal data class Card(val winningNumbers: List<Int>, val numbers: List<Int>) { val matches get() = winningNumbers.intersect(numbers.toSet()).size val points: Int get() { val matches = this.matches if (matches == 0) { return 0 } return 1 shl (matches - 1) } } } class Part4B : Part4A() { override fun getExampleAnswer() = 30 override fun compute(): Int { val copies = MutableList(cards.size) { 1 } for (i in cards.indices) { for (j in i + 1..i + cards[i].matches) { copies[j] += copies[i] } } return copies.sum() } } fun main() { Day(2023, 4, Part4A(), Part4B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
1,660
advent-of-code-kotlin
MIT License