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/Day03.kt
kpilyugin
572,573,503
false
{"Kotlin": 60569}
import java.lang.IllegalArgumentException fun main() { fun Char.priority(): Int = when (this) { in 'A'..'Z' -> this - 'A' + 27 in 'a'..'z' -> this - 'a' + 1 else -> throw IllegalArgumentException() } fun part1(input: List<String>): Int { return input.sumOf { bag -> val (l, r) = bag.chunked(bag.length / 2).map { it.toSet() } val common = l intersect r common.sumOf { it.priority() } } } fun part2(input: List<String>): Int { return input.chunked(3) .sumOf { group -> val (a, b, c) = group.map { it.toSet() } val common = a intersect b intersect c common.sumOf { it.priority() } } } val testInput = readInputLines("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInputLines("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7f0cfc410c76b834a15275a7f6a164d887b2c316
980
Advent-of-Code-2022
Apache License 2.0
src/Day10.kt
zhiqiyu
573,221,845
false
{"Kotlin": 20644}
val cyclesToLook = arrayOf(20, 60, 100, 140, 180, 220) class Machine(var width: Int, var height: Int) { var spritePos: Int var cycle: Int var signalStrength: Int var screen: Array<Array<Char>> init { spritePos = 1 cycle = 0 signalStrength = 0 screen = Array(height) { Array(width) { '.' }} } private fun maybeRecordSignalStrength(cycle: Int) { if (cyclesToLook.contains(cycle)) { signalStrength += cycle * spritePos } } private fun cycleToPixel(): Pair<Int, Int> { return Pair((cycle-1) / width, (cycle-1).mod(width)) } private fun drawPixel() { var (i, j) = cycleToPixel() if (arrayOf(spritePos-1, spritePos, spritePos+1).contains(j)) { screen.get(i).set(j, '#') } } fun execute(command: List<String>) { if (command.size == 1) { // noop maybeRecordSignalStrength(++cycle) drawPixel() } else if (command.size == 2) { for (i in 0..1) { maybeRecordSignalStrength(++cycle) drawPixel() } spritePos += command.get(1).toInt() } else { throw Error("wrong command") } } fun printScreen() { screen.forEach { line -> println(line.joinToString("")) } } } fun main() { fun part1(input: List<String>): Int { var machine = Machine(40, 6) input.map { it -> it.split(" ") }.forEach { command -> machine.execute(command) } return machine.signalStrength } fun part2(input: List<String>) { var machine = Machine(40, 6) input.map { it -> it.split(" ")}.forEach { command -> machine.execute(command) } machine.printScreen() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) // check(part2(testInput) == ) val input = readInput("Day10") println("----------") println(part1(input)) part2(input) }
0
Kotlin
0
0
d3aa03b2ba2a8def927b94c2b7731663041ffd1d
2,183
aoc-2022
Apache License 2.0
src/main/kotlin/me/astynax/aoc2023kt/Day04.kt
astynax
726,011,031
false
{"Kotlin": 9743}
package me.astynax.aoc2023kt import kotlin.math.pow import kotlin.math.roundToInt object Day04 { data class Game(val id: Int, val points: Int) { companion object { private val space = Regex("\\s+") private val pipe = Regex(" \\| ") fun fromString(s: String): Game { val halves = s.split(pipe) val left = halves.first().split(space).drop(1) val right = halves.last().split(space) val ws = left.drop(1).toSet() return Game( id = left.first().dropLast(1).toInt(), points = right.count { it in ws } ) } } } fun step1(games: List<Game>): Int = games.sumOf { if (it.points > 0) 2.0.pow(it.points.dec()).roundToInt() else 0 } fun step2(games: List<Game>): Int { val points = games.associate { it.id to it.points } val ids = games.map { it.id }.toIntArray() val counts = ids.associateWith { 1 }.toMutableMap() for ((idx, id) in ids.withIndex()) { val n = counts[id]!! val m = points[id]!! for (k in ids.slice(idx + 1 .. idx + m)) { counts.replace(k, counts[k]!! + n) } } return counts.values.sum() } val input = lazy { Input.linesFrom("/Day04.input").map(Game::fromString) } }
0
Kotlin
0
0
9771b5ccde4c591c7edb413578c5a8dadf3736e0
1,247
aoc2023kt
MIT License
Advent-of-Code-2023/src/Day10.kt
Radnar9
726,180,837
false
{"Kotlin": 93593}
private const val AOC_DAY = "Day10" private const val PART1_TEST_FILE = "${AOC_DAY}_test_part1" private const val PART2_TEST_FILE = "${AOC_DAY}_test_part2" private const val INPUT_FILE = AOC_DAY private data class Point(val x: Int, val y: Int) private data class Path(val prev: Point, val next: Point) private val pipes = mapOf( // | is a vertical pipe connecting north and south. '|' to listOf(Path(Point(0, -1), Point(0, 1)), Path(Point(0, 1), Point(0, -1))), // - is a horizontal pipe connecting east and west. '-' to listOf(Path(Point(-1, 0), Point(1, 0)), Path(Point(1, 0), Point(-1, 0))), // L is a 90-degree bend connecting north and east. 'L' to listOf(Path(Point(0, -1), Point(1, 0)), Path(Point(1, 0), Point(0, -1))), // J is a 90-degree bend connecting north and west. 'J' to listOf(Path(Point(0, -1), Point(-1, 0)), Path(Point(-1, 0), Point(0, -1))), // 7 is a 90-degree bend connecting south and west. '7' to listOf(Path(Point(-1, 0), Point(0, 1)), Path(Point(0, 1), Point(-1, 0))), // F is a 90-degree bend connecting south and east. 'F' to listOf(Path(Point(0, 1), Point(1, 0)), Path(Point(1, 0), Point(0, 1))), ) private const val GROUND = '.' // . is ground; there is no pipe in this tile. private const val START = 'S' // S is the starting position of the animal; there is a pipe on this tile. private val possibleDirections = listOf(Point(0, 1), Point(1, 0), Point(-1, 0), Point(0, -1)) private fun getPipeAtPoint(point: Point, diagram: List<CharArray>): Char { return diagram[point.y][point.x] } private fun Point.isStart(diagram: List<CharArray>): Boolean { return getPipeAtPoint(this, diagram) == START } private fun Point.isGround(diagram: List<CharArray>): Boolean { return getPipeAtPoint(this, diagram) == GROUND } private fun Point.sum(other: Point): Point { return Point(x + other.x, y + other.y) } private fun Point.minus(other: Point): Point { return Point(x - other.x, y - other.y) } private fun Point.isValid(diagram: List<CharArray>): Boolean { return x >= 0 && y >= 0 && y < diagram.size && x < diagram[y].size } private fun Point.isValidPath(diagram: List<CharArray>): Boolean { return isValid(diagram) && !isGround(diagram) } private fun tryPath(point: Point, startingPoint: Point, diagram: List<CharArray>): List<Point> { val path = mutableListOf(startingPoint) var currentPoint = point var prevPoint = startingPoint while (!currentPoint.isStart(diagram)) { val nextPoint = pipes[getPipeAtPoint(currentPoint, diagram)]!!.find { val prev = currentPoint.sum(it.prev) val next = currentPoint.sum(it.next) prev == prevPoint && next.isValidPath(diagram) }?.let { currentPoint.sum(it.next) } ?: return emptyList() path.add(currentPoint) prevPoint = currentPoint currentPoint = nextPoint } return path } private fun tryPathBFS(queue: ArrayDeque<Path>, startingPoint: Point, diagram: List<CharArray>): List<Point> { val path = mutableSetOf(startingPoint) do { val currentPath = queue.removeFirst() val nextPoint = pipes[getPipeAtPoint(currentPath.next, diagram)]!!.find { val prev = currentPath.next.sum(it.prev) val next = currentPath.next.sum(it.next) prev == currentPath.prev && next.isValid(diagram) && !next.isGround(diagram) /*(next == startingPoint || currentPath.next.isValidPath(prev, diagram))*/ }?.let { currentPath.next.sum(it.next) } ?: continue if (path.contains(nextPoint)) continue path.add(currentPath.next) queue.add(Path(currentPath.next, nextPoint)) } while (queue.isNotEmpty()) return path.toList() } /** * Counts the steps along the loop until the starting point is reached again. * @return the steps needed to get to the farthest point from the starting point */ private fun part1(input: List<String>): Int { val diagram = input.map { it.toCharArray() } val startingPoint: Point = diagram.find { it.contains(START) }?.let { Point(it.indexOf(START), diagram.indexOf(it)) } ?: throw Exception("No starting point found") for (direction in possibleDirections) { val nextPoint = startingPoint.sum(direction) if (!nextPoint.isValidPath(diagram)) continue val path = tryPath(nextPoint, startingPoint, diagram) if (path.isNotEmpty()) return path.size / 2 } return -1 } /** * Breadth-first search version, i.e., don't start by verifying the full path, but rather by verifying the first step in * all possible directions, then the second step in all possible directions, etc. */ private fun part1BFS(input: List<String>): Int { val diagram = input.map { it.toCharArray() } val startingPoint: Point = diagram.find { it.contains(START) }?.let { Point(it.indexOf(START), diagram.indexOf(it)) } ?: throw Exception("No starting point found") val queue = ArrayDeque<Path>() for (direction in possibleDirections) { val nextPoint = startingPoint.sum(direction) if (!nextPoint.isValidPath(diagram)) continue queue.add(Path(startingPoint, nextPoint)) } val path = tryPathBFS(queue, startingPoint, diagram) return (path.size + 1) / 2 } /** * Finds the loop, then replaces the starting point with the corresponding pipe, and finally counts the number of tiles * enclosed by the loop. */ private fun part2(input: List<String>): Int { val diagram = input.map { it.toCharArray() } val startingPoint: Point = diagram.find { it.contains(START) }?.let { Point(it.indexOf(START), diagram.indexOf(it)) } ?: throw Exception("No starting point found") var path = listOf<Point>() for (direction in possibleDirections) { val nextPoint = startingPoint.sum(direction) if (!nextPoint.isValidPath(diagram)) continue path = tryPath(nextPoint, startingPoint, diagram) if (path.isNotEmpty()) break } // Find the starting pipe and clear the diagram val point1 = path[1].minus(startingPoint) val point2 = path.last().minus(startingPoint) val pipePaths = listOf(Path(point2, point1), Path(point1, point2)) val startingPipe = pipes.filter { it.value.all { path -> pipePaths.contains(path) } }.keys.first() val cleanedDiagram = diagram.mapIndexed { yIdx, yLine -> yLine.mapIndexed { xIdx, c -> if (c == START) startingPipe else if (path.contains(Point(xIdx, yIdx))) c else GROUND } } val outside = mutableSetOf<Point>() cleanedDiagram.forEachIndexed { yIdx, yLine -> var within = false var up = false yLine.forEachIndexed { xIdx, c -> when (c) { '|' -> within = !within '-' -> assert(!up) 'L', 'F' -> up = (c == 'L') '7', 'J' -> { if (c != (if (up) 'J' else '7')) within = !within up = false } '.' -> "" else -> throw Exception("Unexpected character $c") } if (!within) outside.add(Point(xIdx, yIdx)) } } return diagram.size * diagram[0].size - (outside.size + path.count { !outside.contains(it) }) } fun main() { createTestFiles(AOC_DAY) var testInput = readInputToList(PART1_TEST_FILE) val part1ExpectedRes = 8 println("---| TEST INPUT |---") println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes") println("* PART 1: ${part1BFS(testInput)}\t== $part1ExpectedRes (BFS)") testInput = readInputToList(PART2_TEST_FILE) val part2ExpectedRes = 10 println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n") val input = readInputToList(INPUT_FILE) val improving = true println("---| FINAL INPUT |---") println("* PART 1: ${part1(input)}${if (improving) "\t== 7102" else ""}") println("* PART 1: ${part1BFS(input)}${if (improving) "\t== 7102" else ""} (BFS)") println("* PART 2: ${part2(input)}${if (improving) "\t== 363" else ""}") }
0
Kotlin
0
0
e6b1caa25bcab4cb5eded12c35231c7c795c5506
8,125
Advent-of-Code-2023
Apache License 2.0
2021/src/test/kotlin/Day11.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.test.Test import kotlin.test.assertEquals class Day11 { data class Coord(val x: Int, val y: Int) data class Octopus(val coord: Coord, var energy: Int) private val flashArea = listOf( Coord(-1, -1), Coord(0, -1), Coord(1, -1), Coord(-1, 0), Coord(0, 0), Coord(1, 0), Coord(-1, 1), Coord(0, 1), Coord(1, 1) ) @Test fun `run part 01`() { val grid = getGrid() val flashes = (1..100).sumOf { runDay(grid) } assertEquals(1601, flashes) } @Test fun `run part 02`() { val grid = getGrid() val day = generateSequence(1) { if (runDay(grid) != grid.count()) it.inc() else null } .last() assertEquals(368, day) } private fun runDay(grid: List<Octopus>) = grid .onEach { it.energy++ } .also { it.processFlashing() } .filter { it.energy > 9 } .onEach { it.energy = 0 } .count() private fun List<Octopus>.processFlashing() { while (true) { this.firstOrNull { it.energy == 10 } ?.let { flashArea.forEach { coord -> this .firstOrNull { adjacent -> adjacent.coord.x == it.coord.x + coord.x && adjacent.coord.y == it.coord.y + coord.y } ?.let { octopus -> octopus.energy = if (octopus == it) 11 else if (octopus.energy == 10) 10 else octopus.energy.inc() } } } ?: return } } private fun getGrid() = Util.getInputAsListOfString("day11-input.txt") .map { it.map { c -> c.digitToInt() } } .let { it .first() .indices .flatMap { x -> List(it.size) { y -> Octopus(Coord(x, y), it[y][x]) } } } }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,083
adventofcode
MIT License
src/Day05.kt
stevefranchak
573,628,312
false
{"Kotlin": 34220}
class CrateStacks { companion object { private val EXTRACT_CRATE_ID_REGEX = Regex("""[A-Z]""") } private val stacks: MutableMap<Int, ArrayDeque<Char>> = mutableMapOf() fun addToStartingStacks(inputLine: String) { inputLine.chunked(4).asSequence() .map { crate -> EXTRACT_CRATE_ID_REGEX.find(crate)?.value?.get(0) } .forEachIndexed { index, crateId -> // Do this instead of filterNotNull'ing the sequence to retain the index if (crateId == null) return@forEachIndexed val key = index + 1 stacks.computeIfAbsent(key) { ArrayDeque() }.add(crateId) } } fun executeMoveInstruction(craneSimulator: CraneSimulator, moveInstruction: MoveInstruction) { craneSimulator.moveCrates( moveInstruction.numCratesToMove, stacks[moveInstruction.fromStackIndex]!!, stacks[moveInstruction.toStackIndex]!! ) } fun getMessage() = stacks.entries.sortedBy { it.key }.map { it.value.first() }.joinToString("") } class MoveInstruction(val numCratesToMove: Int, val fromStackIndex: Int, val toStackIndex: Int) { companion object { private val MOVE_INSTRUCTION_REGEX = Regex("""move (\d+) from (\d+) to (\d+)""") fun extractMoveInstruction(inputLine: String) = MOVE_INSTRUCTION_REGEX.find(inputLine)?.groupValues?.mapNotNull { it.toIntOrNull() }?.let { MoveInstruction(it[0], it[1], it[2]) } } } interface CraneSimulator { fun moveCrates(numCratesToMove: Int, fromStack: ArrayDeque<Char>, toStack: ArrayDeque<Char>) /** * A mutable `take`. */ fun <E> ArrayDeque<E>.steal(n: Int) = require(n >= 1) { "n must be greater than or equal to 1" }.run { (1..n).map { removeFirst() }.toList() } } class CrateMover9000Simulator : CraneSimulator { override fun moveCrates(numCratesToMove: Int, fromStack: ArrayDeque<Char>, toStack: ArrayDeque<Char>) { fromStack.steal(numCratesToMove).forEach { toStack.addFirst(it) } } } class CrateMover9001Simulator : CraneSimulator { override fun moveCrates(numCratesToMove: Int, fromStack: ArrayDeque<Char>, toStack: ArrayDeque<Char>) { fromStack.steal(numCratesToMove).reversed().forEach { toStack.addFirst(it) } } } fun main() { fun processPart(input: List<String>, craneSimulator: CraneSimulator) = CrateStacks().apply { input.asSequence() // Also skip the "crate index" line - it's not needed with this approach .filter { it.isNotBlank() && !it.startsWith(" 1") } .forEach { inputLine -> MoveInstruction.extractMoveInstruction(inputLine)?.let { executeMoveInstruction(craneSimulator, it) } ?: addToStartingStacks(inputLine) } }.getMessage() fun part1(input: List<String>) = processPart(input, CrateMover9000Simulator()) fun part2(input: List<String>) = processPart(input, CrateMover9001Simulator()) // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") val part1TestOutput = part1(testInput) val part1ExpectedOutput = "CMZ" check(part1TestOutput == part1ExpectedOutput) { "$part1TestOutput != $part1ExpectedOutput" } val part2TestOutput = part2(testInput) val part2ExpectedOutput = "MCD" check(part2TestOutput == part2ExpectedOutput) { "$part2TestOutput != $part2ExpectedOutput" } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
22a0b0544773a6c84285d381d6c21b4b1efe6b8d
3,629
advent-of-code-2022
Apache License 2.0
marathons/icpcchallenge/y2020_huaweiGraphMining/a.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package marathons.icpcchallenge.y2020_huaweiGraphMining import java.io.BufferedReader import java.io.FileReader import java.io.PrintWriter import java.util.* import kotlin.math.pow import kotlin.random.asJavaRandom fun solve(fileName: String, nei: List<IntArray>) { val outputFile = "$fileName.out" val auxFile = "$fileName.aux" val n = nei.size val edges = nei.sumOf { it.size } / 2 val r = kotlin.random.Random(566) println("$fileName $n ${2.0 * edges / n}") fun eval(color: IntArray): Double { val map = mutableMapOf<Int, Int>() for (c in color) if (c !in map) map[c] = map.size val parts = map.size val eIn = IntArray(parts) val eOut = IntArray(parts) val size = IntArray(parts) val sumDeg = IntArray(parts) for (u in nei.indices) { val cu = map[color[u]]!! size[cu]++ sumDeg[cu] += nei[u].size for (v in nei[u]) { if (map[color[v]] == cu) eIn[cu]++ else eOut[cu]++ } } val modularity = eIn.indices.sumOf { eIn[it] * 0.5 / edges - (sumDeg[it] * 0.5 / edges).pow(2) } val regularization = 0.5 * (eIn.indices.sumOf { if (size[it] == 1) 1.0 else eIn[it].toDouble() / (size[it] * (size[it] - 1)) } / parts - parts.toDouble() / n) // println("$modularity $regularization $res") return (1 + modularity + regularization) * 1e5 } fun randomCenters(parts: Int) = nei.indices.shuffled(r).take(parts).toIntArray() fun byCenters(centers: IntArray): IntArray { val inf = n + 1 val queue = IntArray(n) val dist = IntArray(n) { inf } val which = IntArray(n) { inf } // val size = IntArray(n) { 0 } var low = 0; var high = 0 for (c in centers) { dist[c] = 0 which[c] = c // size[c] = 1 queue[high++] = c } while (low < high) { val u = queue[low++] for (v in nei[u]) { if (dist[v] < inf) continue dist[v] = dist[u] + 1 which[v] = which[u] // size[which[v]]++ queue[high++] = v } } return which } @Suppress("unused") fun bestParts(): Int { return (10000..60000 step 1000).maxByOrNull { parts -> val q = List(8) { eval(byCenters(randomCenters(parts))) }.maxOrNull()!! println("$parts $q") q }!! } val bestParts = mapOf("a1" to 21000, "a2" to 29000, "a3" to 29000) val parts = bestParts[fileName] ?: error("") // val centers = randomCenters(parts) val centers = BufferedReader(FileReader(auxFile)).readLine().split(" ").map { it.toInt() }.toIntArray() var answer = byCenters(centers) var best = eval(answer) fun improve1() { val index = r.nextInt(centers.size) val oldValue = centers[index] val centersSet = centers.toMutableSet() centersSet.remove(oldValue) while (true) { centers[index] = r.nextInt(n) if (centers[index] in centersSet) continue centersSet.add(centers[index]) break } val new = byCenters(centers) val score = eval(new) print("$best -> $score") if (score > best) { best = score answer = new print(" YES") } else { centersSet.remove(centers[index]) centers[index] = oldValue centersSet.add(oldValue) } println() } fun improve2() { val old = centers.clone() val level = 256 for (i in centers.indices) { if (r.nextInt(level) == 0) centers[i] = -1 } val set = centers.toMutableSet() for (i in centers.indices) { if (centers[i] != -1) continue while (true) { centers[i] = r.nextInt(n) if (centers[i] in set) continue set.add(centers[i]) break } } val new = byCenters(centers) val score = eval(new) print("$best -> $score") if (score > best) { best = score answer = new print(" YES") } else { for (i in centers.indices) centers[i] = old[i] } print(" $level") println() } class Centers(val a: IntArray) { private val energy: Double = eval(byCenters(a)) fun energy(): Double = energy fun randomInstance(random: Random): Centers { val list = ArrayList<Int>() for (i in 0 until n) { list.add(i) } list.shuffle(random) for (i in 0 until parts) { a[i] = list[i] } return Centers(a) } fun vary(): Centers { val new: IntArray = a.clone() val level = 256 for (i in new.indices) { if (r.nextInt(level) == 0) new[i] = -1 } val set = new.toMutableSet() for (i in new.indices) { if (new[i] != -1) continue while (true) { new[i] = r.nextInt(n) if (new[i] in set) continue set.add(new[i]) break } } return Centers(new) } } class Settings constructor(var globalIterations: Int = 1024, var iterations: Int = 8192, var probStartWithPrevious: Double = 1 - 1.0 / 16, var recessionLimit: Int = Int.MAX_VALUE, var desiredEnergy: Double = -Double.MAX_VALUE, var temp0: Double = 1.0) repeat(10) { improve1() improve2() } fun simulatedAnnealing(item: Centers, settings: Settings, r1: Random): Centers? { var item = item var energy = item!!.energy() var answerEnergy = Double.MAX_VALUE var answer: Centers? = null for (glob in 0 until settings.globalIterations) { if (glob > 0 && r1.nextDouble() >= settings.probStartWithPrevious) { item = item!!.randomInstance(r1) energy = item.energy() } var end = settings.iterations var iter = 1 var recession = 0 while (true) { if (energy < answerEnergy) { answerEnergy = energy answer = item println(answerEnergy) if (answerEnergy <= settings.desiredEnergy) { return answer } end = Math.max(end, iter + settings.iterations) } if (iter > end) { break } var nextEnergy: Double var next: Centers? = null next = item!!.vary()!! nextEnergy = next.energy() val dEnergy = nextEnergy - energy var accept: Boolean if (dEnergy < 0) { accept = true recession = 0 } else { recession++ if (recession == settings.recessionLimit) { break } val barrier = Math.exp(-1.0 * dEnergy * iter / settings.temp0) accept = r1.nextDouble() < barrier } if (accept) { assert(next != null) item = next!! energy = nextEnergy } else { } iter++ } } return answer } val settings = Settings() val item = Centers(centers) val q: Centers = simulatedAnnealing(item, settings, r.asJavaRandom()) as Centers for (i in centers.indices) centers[i] = q.a[i] val output = PrintWriter(outputFile) val aux = PrintWriter(auxFile) answer.indices.groupBy { answer[it] }.values.sortedBy { it.size }.forEach { output.println(it.joinToString(" ")) } aux.println(centers.joinToString(" ")) output.close() aux.close() } fun main() { for (test in 1..3) { val fileName = "a$test" val input = BufferedReader(FileReader("${fileName}.in")) val edges = generateSequence { input.readLine()?.split(" ")?.map { it.toInt() } }.toList() val n = edges.flatten().maxOrNull()!! + 1 val nei = List(n) { mutableListOf<Int>() } for ((u, v) in edges) { nei[u].add(v); nei[v].add(u) } solve(fileName, nei.map { it.toIntArray() }) } }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
6,902
competitions
The Unlicense
src/main/kotlin/Day1.kt
maldoinc
726,264,110
false
{"Kotlin": 14472}
import java.io.File fun getFirstAndLastDigitsFromString(input: String): Pair<Int, Int>? { val digits = input.filter { it.isDigit() }.map { it.digitToInt() } return if (digits.isNotEmpty()) { digits.first() to digits.last() } else { null } } fun getFirstAndLastDigitsFromStringWithWords(input: String): Pair<Int, Int>? { var first: Int? = null var last: Int? = null val numWords = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") input.fold(0) { index, char -> if (char.isDigit()) { first = first ?: char.digitToInt() last = char.digitToInt() } else { numWords .withIndex() .firstOrNull { it.value.startsWith(char) && index + it.value.length <= input.length && input.substring(index, index + it.value.length) == it.value } ?.let { first = first ?: it.index last = it.index } } index + 1 } return first?.let { f -> last?.let { l -> f to l } } } fun main(args: Array<String>) { val sum = File(args[0]) .readLines() .mapNotNull { getFirstAndLastDigitsFromStringWithWords(it) } .sumOf { 10 * it.first + it.second } println(sum) }
0
Kotlin
0
1
47a1ab8185eb6cf16bc012f20af28a4a3fef2f47
1,502
advent-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/UniqueOccurrences.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1207. Unique Number of Occurrences * @see <a href="https://leetcode.com/problems/unique-number-of-occurrences">Source</a> */ fun interface UniqueOccurrences { operator fun invoke(arr: IntArray): Boolean } class UniqueOccurrencesMap : UniqueOccurrences { override fun invoke(arr: IntArray): Boolean { val count: MutableMap<Int, Int> = HashMap() for (num in arr) { count[num] = 1 + count.getOrDefault(num, 0) } return count.size == count.values.toHashSet().size } } class UniqueOccurrencesSort : UniqueOccurrences { override fun invoke(arr: IntArray): Boolean { arr.sort() val ans = mutableListOf<Int>() var i = 0 while (i < arr.size) { var count = 1 var j = i + 1 while (j < arr.size && arr[i] == arr[j]) { count++ j++ } ans.add(count) i += count } ans.sort() for (j in 0 until ans.size - 1) { if (ans[j] == ans[j + 1]) { return false } } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,787
kotlab
Apache License 2.0
kotest-property/src/commonMain/kotlin/io/kotest/property/exhaustive/strings.kt
kotest
47,071,082
false
{"Kotlin": 4460715, "CSS": 352, "Java": 145}
package io.kotest.property.exhaustive import io.kotest.property.Exhaustive import io.kotest.property.RandomSource fun Exhaustive.Companion.azstring(range: IntRange): Exhaustive<String> { fun az() = ('a'..'z').map { it.toString() } val values = range.toList().flatMap { size -> List(size) { az() }.reduce { acc, seq -> acc.zip(seq).map { (a, b) -> a + b } } } return values.exhaustive() } fun Exhaustive.Companion.upperLowerCase(s: String): Exhaustive<String> { val caseSensitiveChars = s.filter(::isCaseSensitive).length if (caseSensitiveChars > 20) { println( "[WARN] Generating exhaustive permutations for $s, which has $caseSensitiveChars case-sensitive characters. " + "This will generate 2**$caseSensitiveChars permutations, which may take a while to run." ) } return Exhaustive.of(*s.upperLowerCases(RandomSource.default()).toList().toTypedArray()) } internal fun String.upperLowerCases(rs: RandomSource): Sequence<String> = when { isEmpty() -> sequenceOf("") else -> first().let { c -> val upper = c.uppercaseChar() val lower = c.lowercaseChar() val rest = substring(1).upperLowerCases(rs) sequence { if (upper == lower) rest.forEach { yield(buildString { append(c); append(it) }) } else rest.forEach { substringCasing -> // Otherwise we will guarantee to start with all upper, or all lower val (first, second) = if (rs.random.nextBoolean()) upper to lower else lower to upper yield(buildString { append(first); append(substringCasing) }) yield(buildString { append(second); append(substringCasing) }) } } } } private fun isCaseSensitive(c: Char) = c.uppercaseChar() != c.lowercaseChar()
102
Kotlin
615
4,198
7fee2503fbbdc24df3c594ac6b240c11b265d03e
1,781
kotest
Apache License 2.0
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day6/OrbitMap.kt
jrhenderson1988
289,786,400
false
{"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37}
package com.github.jrhenderson1988.adventofcode2019.day6 import java.util.* class OrbitMap(items: List<String>) { private val rootNode = buildNodeTree(items) fun calculateChecksum(): Int { var checksum = 0 val stack = Stack<Node>() stack.push(rootNode) while (stack.isNotEmpty()) { val node = stack.pop() checksum += totalDescendantsOfNode(node) for (child in node.children) { stack.push(child) } } return checksum } fun calculateMinimumOrbitalTransfersBetween(a: String, b: String) = calculateMinimumOrbitalTransfersBetween( findNode(a).parent ?: error("Node with identifier [$a] does not have a parent"), findNode(b).parent ?: error("Node with identifier [$b] does not have a parent") ) private fun calculateMinimumOrbitalTransfersBetween(a: Node, b: Node): Int { val aAncestors = ancestorsWithDistances(a) val bAncestors = ancestorsWithDistances(b) return aAncestors.keys.intersect(bAncestors.keys) .map { distanceTo(it, aAncestors) + distanceTo(it, bAncestors) } .min() ?: error("There are no common ancestors between $a and $b") } private fun distanceTo(node: Node, distances: Map<Node, Int>) = distances[node] ?: error("Could not find distance to [$node]") private fun totalDescendantsOfNode(item: Node): Int { var total = 0 val stack = Stack<Node>() stack.add(item) while (stack.isNotEmpty()) { val node = stack.pop() total += node.children.size stack.addAll(node.children) } return total } private fun findNode(identifier: String): Node { val stack = Stack<Node>() stack.add(rootNode) while (stack.isNotEmpty()) { val node = stack.pop() if (node.identifier == identifier) { return node } stack.addAll(node.children) } error("Could not find node identified by [$identifier].") } private fun ancestorsWithDistances(node: Node): Map<Node, Int> { val ascendants = mutableMapOf<Node, Int>() var n = node var distance = 1 while (n.parent != null) { n = n.parent!! ascendants[n] = distance++ } return ascendants } companion object { fun buildNodeTree(orbits: List<String>): Node { val dependencies = mutableMapOf<String, MutableSet<String>>() val nodes = mutableMapOf<String, Node>() orbits.forEach { val (parent, child) = it.trim().toUpperCase().split(')') if (dependencies.containsKey(parent)) { dependencies[parent]!!.add(child) } else { dependencies[parent] = mutableSetOf(child) } nodes.putIfAbsent(parent, Node(null, parent)) nodes.putIfAbsent(child, Node(null, child)) } dependencies.forEach { (parentId, childIds) -> val parent = nodes[parentId] childIds.forEach { childId -> val child = nodes[childId] parent!!.addChild(child!!) } } return nodes.values.find { it.parent == null }!! } } }
0
Kotlin
0
0
7b56f99deccc3790c6c15a6fe98a57892bff9e51
3,473
advent-of-code
Apache License 2.0
src/main/kotlin/year2022/Day09.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2022 import utils.Direction import utils.Point2D import kotlin.math.abs import kotlin.math.sign class Day09 { private fun solution(input: String, len: Int): Int { val positions = mutableSetOf<Point2D>() val parts = MutableList(len) { Point2D(0, 0) } positions.add(parts.last()) input.lines().forEach { line -> val steps = line.substringAfter(" ").toInt() val (dx, dy) = Direction.byFirstLetter(line.substringBefore(" ")[0]) repeat(steps) { parts[0] = parts[0].move(dx, dy) parts.indices.windowed(2, partialWindows = false).forEach { (i1, i2) -> val part1 = parts[i1] val part2 = parts[i2] if (abs(part1.y - part2.y) >= 2 || abs(part1.x - part2.x) >= 2) { parts[i2] = if (part1.x != part2.x && part1.y != part2.y) { part2.move((part1.x - part2.x).sign, (part1.y - part2.y).sign) } else if (abs(part1.x - part2.x) == 2) part2.move((part1.x - part2.x).sign, 0) else part2.move(0, (part1.y - part2.y).sign) } } positions.add(parts.last()) } } return positions.size } fun part2(input: String) = solution(input, 10) fun part1(input: String) = solution(input, 2) }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
1,432
aoc-2022
Apache License 2.0
kotlin/ConvexHull.kt
indy256
1,493,359
false
{"Java": 545116, "C++": 266009, "Python": 59511, "Kotlin": 28391, "Rust": 4682, "CMake": 571}
data class Point(val x: Int, val y: Int) // Convex hull in O(n*log(n)) fun convexHull(points: Array<Point>): Array<Point> { fun isNotRightTurn(p3: List<Point>): Boolean { val (a, b, c) = p3 val cross = (a.x - b.x).toLong() * (c.y - b.y) - (a.y - b.y).toLong() * (c.x - b.x) val dot = (a.x - b.x).toLong() * (c.x - b.x) + (a.y - b.y).toLong() * (c.y - b.y) return cross < 0 || cross == 0L && dot <= 0 } val sortedPoints = points.sortedArrayWith(compareBy({ it.x }, { it.y })) val n = sortedPoints.size val hull = arrayListOf<Point>() for (i in 0 until 2 * n) { val j = if (i < n) i else 2 * n - 1 - i while (hull.size >= 2 && isNotRightTurn(hull.takeLast(2) + sortedPoints[j])) hull.removeAt(hull.size - 1) hull.add(sortedPoints[j]) } return hull.subList(0, hull.size - 1).toTypedArray() } // Usage example fun main() { val points = arrayOf(Point(0, 0), Point(2, 2), Point(1, 1), Point(0, 1), Point(1, 0), Point(0, 0)) val hull = convexHull(points) println(hull.contentToString()) }
97
Java
561
1,806
405552617ba1cd4a74010da38470d44f1c2e4ae3
1,098
codelibrary
The Unlicense
src/main/kotlin/algorithms/ShortestSuperstring.kt
jimandreas
377,843,697
false
null
@file:Suppress("MemberVisibilityCanBePrivate") package algorithms /** * See also: * http://rosalind.info/problems/long/ * Introduction to Genome Sequencing * * Problem Problem For a collection of strings, a larger string containing every one of the smaller strings as a substring is called a superstring. By the assumption of parsimony, a shortest possible superstring over a collection of reads serves as a candidate chromosome. Given: At most 50 DNA strings of approximately equal length, not exceeding 1 kbp, in FASTA format (which represent reads deriving from the same strand of a single linear chromosome). The dataset is guaranteed to satisfy the following condition: there exists a unique way to reconstruct the entire chromosome from these reads by gluing together pairs of reads that overlap by more than half their length. Return: A shortest superstring containing all the given strings (thus corresponding to a reconstructed chromosome). */ /** * Algorithm: * Leverage the FindSharedMotif class to find the longest shared motif * comparing all pairs of strings. * Then merge the two winning strings. Repeat until no strings are left. * * Optimize: Hash the common string analysis as a cache. */ class ShortestSuperstring { val fsm = FindSharedMotif() fun shortestSuperstring(stringList: MutableList<String>): String { // use a hash map as it can be modified in the loop val hashStringList: HashMap<Int, String> = hashMapOf() for (i in 0 until stringList.size) { hashStringList[i] = stringList[i] } val hashMotif: HashMap<String, String> = hashMapOf() var maxKey = Pair(-1, -1) var merged = 0 var result = "" while (merged < stringList.size - 1) { var maxLen = Int.MIN_VALUE for (i in 0 until stringList.size) { for (j in i + 1 until stringList.size) { if (hashStringList[i] == "" || hashStringList[j] == "") { continue } if (maxLen > (hashStringList[i]!!.length + hashStringList[j]!!.length)) { continue } //println("i $i j $j") val keysb = StringBuilder().append(hashStringList[i]) keysb.append(hashStringList[j]) val key = keysb.toString() if (hashMotif.containsKey(key)) { //println("Found Key in cache $key") if (hashMotif[key]!!.length > maxLen) { maxLen = hashMotif[key]!!.length maxKey = Pair(i, j) //println("from cache i $i j $j New max $maxLen with ${hashMotif[key]}") } } else { val sharedMotif = fsm.findMostLikelyCommonAncestor( listOf(hashStringList[i]!!, hashStringList[j]!!) ) //println("i $i j $j of ${stringList.size} $sharedMotif") hashMotif[key] = sharedMotif if (sharedMotif.length > maxLen) { maxLen = sharedMotif.length //println("i $i j $j key $key New max $maxLen with $sharedMotif") maxKey = Pair(i, j) } } } } // now merge the two key strings as given by i, j val i = maxKey.first val s1 = hashStringList[i] val j = maxKey.second val s2 = hashStringList[j] //println("strings s1 $s1 s2 and $s2 BEFORE") val keysb = StringBuilder() keysb.append(s1) keysb.append(s2) val key = keysb.toString() val motif = hashMotif[key] val mlen = motif!!.length val str = StringBuilder() when { // motif located at start of string S1 and end of S2 s1!!.substring(0, mlen) == motif && s2!!.substring(s2.length - mlen, s2.length) == motif -> { str.append(s2) str.append(s1.substring(motif.length, s1.length)) } // motif located at start of string S2 and end of S1 s2!!.substring(0, mlen) == motif && s1.substring(s1.length - mlen, s1.length) == motif -> { str.append(s1) str.append(s2.substring(motif.length, s2.length)) } // motif located at end of string s1 and start of 2 s1.substring(s1.length - mlen, s1.length) == motif && s2.substring(0, mlen) == motif -> { val idx = s2.indexOf(motif) str.append(s1) str.append(s2.substring(idx + motif.length, s2.length)) } // motif located at end of string s2 and start of s1 s2.substring(s2.length - mlen, s2.length) == motif && s1.substring(0, mlen) == motif -> { val idx = s1.indexOf(motif) str.append(s2) str.append(s1.substring(idx + motif.length, s1.length)) } else -> { println("****************************************") println("ERROR s1 $s1 and s2 $s2 for motif $motif CONCATENATING") println("****************************************") str.append(s1) str.append(s2) } } result = str.toString() // println("strings s1 $s1 s2 and $s2 AFTER") // println("********* merging i $i j $j key $key") // println("strings $s1 and $s2 with motif $motif result $str") hashStringList[i] = result hashStringList[j] = "" merged++ } return result } }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
6,104
stepikBioinformaticsCourse
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem2130/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2130 import com.hj.leetcode.kotlin.common.model.ListNode /** * LeetCode page: [2130. Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the size of head; */ fun pairSum(head: ListNode?): Int { // Collect all values in the linkedList then compute all twin sums and return the maximum return maxTwinSum(head.values()) } private fun ListNode?.values(): List<Int> { val result = mutableListOf<Int>() linearTraversal { node -> result.add(node.`val`) } return result } private fun ListNode?.linearTraversal(onEachNode: (node: ListNode) -> Unit) { var currentNode = this while (currentNode != null) { onEachNode(currentNode) currentNode = currentNode.next } } private fun maxTwinSum(values: List<Int>): Int { require(values.isNotEmpty()) require(values.size.isEven()) // Compute all twin sums and return the maximum var maxTwinSum = values[0] + values[values.lastIndex] for (index in 0 until (values.size / 2)) { val value = values[index] val twinValue = values[values.lastIndex - index] val twinSum = value + twinValue if (twinSum > maxTwinSum) { maxTwinSum = twinSum } } return maxTwinSum } private fun Int.isEven(): Boolean = this and 1 == 0 }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,582
hj-leetcode-kotlin
Apache License 2.0
kotlin/13.kt
NeonMika
433,743,141
false
{"Kotlin": 68645}
class Day13 : Day<Day13.PaperFolding>("13") { data class FoldInstruction(val axis: Char, val line: Int) infix fun Char.foldBy(amount: Int) = FoldInstruction(this, amount) data class PaperFolding(val dots: TwoDimensionalArray<Boolean>, val folds: List<FoldInstruction>) { val nextFold get() = folds.first() val nextFoldAxis get() = nextFold.axis fun fold(): PaperFolding { val mergeRows = (0 until dots.rows).associateBy { it }.toMutableMap() val mergeCols = (0 until dots.cols).associateBy { it }.toMutableMap() if (nextFoldAxis == 'y') { (folds[0].line + 1 until dots.rows).forEachIndexed { i, r -> mergeRows[folds[0].line - 1 - i] = r } } else { (folds[0].line + 1 until dots.cols).forEachIndexed { i, c -> mergeCols[folds[0].line - 1 - i] = c } } val rows = if (nextFoldAxis == 'y') folds[0].line else dots.rows val cols = if (nextFoldAxis == 'y') dots.cols else folds[0].line return PaperFolding(TwoDimensionalArray(rows, cols) { row, col -> dots[row, col] or dots[mergeRows[row]!!, mergeCols[col]!!] }, folds.drop(1)) } override fun toString() = buildString { for (row in 0 until dots.rows) { for (col in 0 until dots.cols) { append(if (dots[row, col]) "#" else ".") } appendLine() } } } override fun dataStar1(lines: List<String>): PaperFolding { val foldPattern = """fold along (.)=(\d+)""".toRegex() val positions = lines.takeWhile { !foldPattern.matches(it) } .map { it.ints(",").run { get(1) to get(0) } }.toSet() val foldInstructions = lines.dropWhile { !foldPattern.matches(it) } .map { foldPattern.find(it)!!.groupValues.run { get(1)[0] foldBy get(2).toInt() } } return PaperFolding( TwoDimensionalArray(positions.maxOf { it.first } + 1, positions.maxOf { it.second } + 1) { row, col -> row to col in positions }, foldInstructions ) } override fun dataStar2(lines: List<String>) = dataStar1(lines) override fun star1(data: PaperFolding): Number { return data.fold().apply { println(this) }.dots.count { it } } override fun star2(data: PaperFolding): PaperFolding { var cur = data while (cur.folds.isNotEmpty()) { cur = cur.fold() } return cur } } fun main() { Day13()() }
0
Kotlin
0
0
c625d684147395fc2b347f5bc82476668da98b31
2,618
advent-of-code-2021
MIT License
src/main/kotlin/com/chriswk/aoc/advent2020/Day19.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2020 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report class Day19 : AdventDay(2020, 19) { companion object { @JvmStatic fun main(args: Array<String>): Unit { val day = Day19() report { day.part1() } report { day.part2() } } } fun parseRules(rules: List<String>): MutableMap<Int, List<List<Rule>>> { return rules.takeWhile { it.isNotBlank() }.map { ruleLine -> val (id, rhs) = ruleLine.split(": ") val sides = rhs.split(" | ") id.toInt() to sides.map { side -> side.split(' ').map { part -> if (part.startsWith('"')) { Atom(part[1]) } else { Reference(part.toInt()) } } } }.toMap().toMutableMap() } fun validMessages(messages: List<String>, ruleSet: MutableMap<Int, List<List<Rule>>>): Int { return messages.count { message -> message.validForRule(0, 0, ruleSet).any { it == message.length }} } fun part1(): Int { val rules = parseRules(inputAsLines) val messages = inputAsLines.dropWhile { it.isNotBlank() }.drop(1) return validMessages(messages, rules) } fun part2(): Int { val rules = parseRules(inputAsLines) rules[8] = listOf( listOf(Reference(42)), listOf(Reference(42), Reference(8)) ) rules[11] = listOf( listOf(Reference(42), Reference(31)), listOf(Reference(42), Reference(11), Reference(31)) ) return validMessages(inputAsLines.dropWhile { it.isNotBlank() }.drop(1), rules) } } sealed class Rule { } data class Reference(val id: Int): Rule() data class Atom(val symbol: Char): Rule() fun String.validForRule(ruleId: Int, position: Int = 0, ruleMap: Map<Int, List<List<Rule>>>): List<Int> { return ruleMap.getValue(ruleId).flatMap { rules -> var validPositions = listOf(position) rules.forEach { rule -> validPositions = validPositions.mapNotNull { idx -> when { rule is Atom && getOrNull(idx) == rule.symbol -> listOf(idx+1) rule is Reference -> validForRule(rule.id, idx, ruleMap) else -> null } }.flatten() } validPositions } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,612
adventofcode
MIT License
src/Day03.kt
saikatsgupta
572,824,837
false
{"Kotlin": 2709}
fun main() { fun Char.getPriority(): Int { return when { isUpperCase() -> code - 'A'.code + 27 else -> code - 'a'.code + 1 } } fun part1(input: List<String>): Int { return input.sumOf { val compartment1 = it.take(it.length / 2) val compartment2 = it.takeLast(it.length / 2) (compartment1.toSet() intersect compartment2.toSet()).single().getPriority() } } fun part2(input: List<String>): Int { return (input.indices step 3) .map { listOf(input[it].toSet(), input[it + 1].toSet(), input[it + 2].toSet()) } .sumOf { ((it[0] intersect it[1]) intersect it[2]).single().getPriority() } } }
0
Kotlin
0
1
2c491a9e5ddc7c08fbeacccce29f574510cd0288
736
aoc-2022-in-kotlin
Apache License 2.0
src/Day05.kt
Kanialdo
573,165,497
false
{"Kotlin": 15615}
fun main() { val moveRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex() fun part1(input: String): String { val (stack, moves) = input.split("\n\n").map { it.lines() } val size = stack.last().trim().last().digitToInt() val data = List<ArrayDeque<Char>>(size) { ArrayDeque() } stack.dropLast(1).forEach { row -> row.chunked(4).forEachIndexed { index, value -> value[1].takeIf { it != ' ' }?.let { data[index].addFirst(it) } } } moves.forEach { move -> val (count, from, to) = moveRegex.find(move)?.groupValues?.drop(1)?.map { it.toInt() } ?: error("Not found") repeat(count) { data[to - 1].addLast(data[from - 1].removeLast()) } } return data.map { it.last() }.joinToString(separator = "") } fun part2(input: String): String { val (stack, moves) = input.split("\n\n").map { it.lines() } val size = stack.last().trim().last().digitToInt() val data = List<ArrayDeque<Char>>(size) { ArrayDeque() } stack.dropLast(1).forEach { row -> row.chunked(4).forEachIndexed { index, value -> value[1].takeIf { it != ' ' }?.let { data[index].addFirst(it) } } } moves.forEach { move -> val (count, from, to) = moveRegex.find(move)?.groupValues?.drop(1)?.map { it.toInt() } ?: error("Not found") val buffer = ArrayDeque<Char>() repeat(count) { buffer.addFirst(data[from - 1].removeLast()) } data[to - 1].addAll(buffer) } return data.map { it.last() }.joinToString(separator = "") } val testInput = readInputAsText("Day05_test") check(part1(testInput), "CMZ") check(part2(testInput), "MCD") val input = readInputAsText("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
10a8550a0a85bd0a928970f8c7c5aafca2321a4b
1,947
advent-of-code-2022
Apache License 2.0
src/day_4/kotlin/Day4.kt
Nxllpointer
573,051,992
false
{"Kotlin": 41751}
// AOC Day 4 fun part1(pairs: List<Pair<IntRange, IntRange>>) { val containingCount = pairs.count { it.first.containsAll(it.second) || it.second.containsAll(it.first) } println("Part 1: In $containingCount assignment pairs one fully contains the others assignment") } fun part2(pairs: List<Pair<IntRange, IntRange>>) { val overlappingCount = pairs.count { it.first.containsAny(it.second) || it.second.containsAny(it.first) } println("Part 1: In $overlappingCount assignment pairs the assignments are overlapping") } fun main() { val pairs = getAOCInput { rawInput: String -> rawInput .trim() .split("\n") .map { it.split(',', '-').mapToInt() } .map { IntRange(it[0], it[1]) to IntRange(it[2], it[3]) } } part1(pairs) part2(pairs) }
0
Kotlin
0
0
b6d7ef06de41ad01a8d64ef19ca7ca2610754151
826
AdventOfCode2022
MIT License
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/UnboundedKnapsack.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* Use this technique to select elements that give maximum profit from a given set with a limitation on capacity and that each element can be picked multiple times. */ //1. Rod Cutting fun maxRodCuttingProfit(lengths: IntArray, prices: IntArray, rodLength: Int): Int { val n = lengths.size // Create a 1D array to store the maximum profit for each length val dp = IntArray(rodLength + 1) // Populate the array using the Unbounded Knapsack approach for (i in 1..rodLength) { for (j in 0 until n) { if (lengths[j] <= i) { dp[i] = maxOf(dp[i], dp[i - lengths[j]] + prices[j]) } } } return dp[rodLength] } fun main() { // Example usage val lengths = intArrayOf(1, 2, 3, 4, 5) val prices = intArrayOf(2, 5, 9, 6, 8) val rodLength = 5 val result = maxRodCuttingProfit(lengths, prices, rodLength) println("Maximum Rod Cutting Profit: $result") } //2. Coin Change fun minCoinsToMakeChange(coins: IntArray, amount: Int): Int { val n = coins.size // Create a 1D array to store the minimum number of coins for each amount val dp = IntArray(amount + 1) { Int.MAX_VALUE } // Initialization: Zero coins needed to make change for amount 0 dp[0] = 0 // Populate the array using the Unbounded Knapsack approach for (i in 1..amount) { for (j in 0 until n) { if (coins[j] <= i && dp[i - coins[j]] != Int.MAX_VALUE) { dp[i] = minOf(dp[i], dp[i - coins[j]] + 1) } } } return if (dp[amount] == Int.MAX_VALUE) -1 else dp[amount] } fun main() { // Example usage val coins = intArrayOf(1, 2, 5) val amount = 11 val result = minCoinsToMakeChange(coins, amount) println("Minimum Coins to Make Change: $result") } /* Rod Cutting: The maxRodCuttingProfit function calculates the maximum profit that can be obtained by cutting a rod of a given length into pieces of different lengths, each with its corresponding price. It uses a 1D array to store the maximum profit for each possible rod length. Coin Change: The minCoinsToMakeChange function calculates the minimum number of coins needed to make change for a given amount using a set of coin denominations. It uses a 1D array to store the minimum number of coins for each possible amount. */
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
2,353
Kotlin-Data-Structures-Algorithms
Apache License 2.0
shared/src/commonMain/kotlin/com/joetr/sync/sphere/ui/results/AvailabilityCalculator.kt
j-roskopf
712,951,839
false
{"Kotlin": 1486933, "Ruby": 3083, "Shell": 1352, "Swift": 588}
package com.joetr.sync.sphere.ui.results import com.joetr.sync.sphere.data.model.People import com.joetr.sync.sphere.ui.results.data.ALL_DAY import com.joetr.sync.sphere.ui.results.data.NONE import com.joetr.sync.sphere.ui.results.data.Time import com.joetr.sync.sphere.ui.results.data.TimeRange import com.joetr.sync.sphere.ui.time.DayTime class AvailabilityCalculator { fun findOverlappingTime(people: List<People>): Map<String, List<Pair<String, DayTime>>> { // Flatten and map each availability to a comparable time range) val availabilities = people.flatMap { person -> person.availability.mapNotNull { availability -> when (availability.time) { is DayTime.AllDay -> Pair(availability.display, ALL_DAY) is DayTime.NotSelected -> Pair(availability.display, NONE) is DayTime.Range -> Pair( availability.display, TimeRange( startTime = Time( availability.time.startTimeHour, availability.time.startTimeMinute, ), endTime = Time( availability.time.endTimeHour, availability.time.endTimeMinute, ), ), ) } } } // Group by day val groupedByDay = availabilities.groupBy { it.first } // Find overlapping times for each day return groupedByDay.mapValues { (_, availabilities) -> val accumulatedAvailabilities = availabilities.fold(availabilities) { acc, range -> acc.map { val intersection = it.intersect(range) intersection ?: Pair(it.first, NONE) } }.map { val dayTime = when (it.second) { ALL_DAY -> DayTime.AllDay NONE -> DayTime.NotSelected else -> { DayTime.Range( it.second.startTime.hour, it.second.startTime.minute, it.second.endTime.hour, it.second.endTime.minute, ) } } as DayTime Pair(it.first, dayTime) } if (accumulatedAvailabilities.size != people.size) { // no shared availability for all people listOf( Pair( accumulatedAvailabilities.first().first, DayTime.NotSelected, ), ) } else { accumulatedAvailabilities } } } private fun Pair<String, TimeRange>.intersect(other: Pair<String, TimeRange>): Pair<String, TimeRange>? { if (this.second == ALL_DAY && other.second == ALL_DAY) return Pair(this.first, ALL_DAY) val maxStart = maxOf(this.second.startTime, other.second.startTime) val minEnd = minOf(this.second.endTime, other.second.endTime) return if (maxStart < minEnd) Pair(this.first, TimeRange(maxStart, minEnd)) else null } private fun minOf(a: Time, b: Time): Time { return if (a >= b) { b } else { a } } private fun maxOf(a: Time, b: Time): Time { return if (a >= b) { a } else { b } } }
0
Kotlin
0
1
39a74df18fc0c00515027cd7f52e9539214b0085
3,673
SyncSphere
MIT License
puzzles/kotlin/src/mayan-calc/mayan-calc.kt
charlesfranciscodev
179,561,845
false
{"Python": 141140, "Java": 34848, "Kotlin": 33981, "C++": 27526, "TypeScript": 22844, "C#": 22075, "Go": 12617, "JavaScript": 11282, "Ruby": 6255, "Swift": 3911, "Shell": 3090, "Haskell": 1375, "PHP": 1126, "Perl": 667, "C": 493}
import java.util.Scanner const val BASE = 20 val input = Scanner(System.`in`) fun main(args : Array<String>) { val width = input.nextInt() val height = input.nextInt() val numerals = ArrayList<String>() // mayan numerals val numeralMap = HashMap<String, Long>() // mayan numeral -> base 20 number for (i in 0 until height) { val row = input.next() numerals.add(row) } // Store the mayan numerals in a map for (i in 0 until BASE) { val numeral = StringBuilder() val column = i * width for (row in numerals) { for (j in column until column + width) { numeral.append(row[j]) } numeral.append('\n') } numeralMap[numeral.toString()] = i.toLong() } // Read the first and second number val numArray1 = readNum(numeralMap, height) val numArray2 = readNum(numeralMap, height) val num1 = convertBase20To10(numArray1) val num2 = convertBase20To10(numArray2) val operation = input.next() // Calculate the result of the operation in base 10 val result = when (operation) { "+" -> num1 + num2 "-" -> num1 - num2 "*" -> num1 * num2 else -> num1 / num2 } // Convert the result back to the original base val numArray = convertBase10To20(result) for (number in numArray) { for ((numeral, n) in numeralMap) { if (n == number) { print(numeral) } } } } fun readNum(numeralMap: HashMap<String, Long>, height: Int): List<Long> { var numeral = StringBuilder() val numArray = ArrayList<Long>() val nbLines = input.nextInt() for (i in 0 until nbLines) { val numLine = input.next() numeral.append(numLine) numeral.append('\n') if (i % height == height - 1) { // last column val number = numeralMap.getOrDefault(numeral.toString(), 0L) numArray.add(number) numeral = StringBuilder() // reset } } return numArray.reversed() } fun convertBase20To10(numArray: List<Long>): Long { return numArray.mapIndexed { i, num -> num * Math.pow(BASE.toDouble(), i.toDouble()).toLong() }.sum() } fun convertBase10To20(num: Long): List<Long> { var number = num val numArray = ArrayList<Long>() // avoid division by 0 if (number == 0L) { numArray.add(0L) return numArray } while (number != 0L) { numArray.add(number % BASE) number /= BASE } return numArray.reversed() }
0
Python
19
45
3ec80602e58572a0b7baf3a2829a97e24ca3460c
2,376
codingame
MIT License
src/y2022/Day04.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.readInput object Day04 { fun part1(input: List<String>): Int { return input.count { fullyContains(it) } } private fun inputToRanges(input: String): Pair<IntRange, IntRange> { val (p1, p2) = input.split(",") .map { it.split("-") .map { x -> x.toInt() } } return (p1[0]..p1[1]) to (p2[0]..p2[1]) } private fun fullyContains(input: String): Boolean { val (range1, range2) = inputToRanges(input) return (range1.first in range2 && range1.last in range2) || (range2.first in range1 && range2.last in range1) } fun part2(input: List<String>): Int { return input.count { partlyContains(it) } } private fun partlyContains(input: String): Boolean { val (range1, range2) = inputToRanges(input) return listOf( range1.first in range2, range1.last in range2, range2.first in range1 ).any { it } } } fun main() { val input = readInput("resources/2022/day04") println(Day04.part1(input)) println(Day04.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,154
advent-of-code
Apache License 2.0
src/main/kotlin/g0601_0700/s0632_smallest_range_covering_elements_from_k_lists/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0632_smallest_range_covering_elements_from_k_lists // #Hard #Array #Hash_Table #Sorting #Greedy #Heap_Priority_Queue #Sliding_Window // #2023_02_09_Time_399_ms_(83.33%)_Space_59.2_MB_(66.67%) import java.util.Objects import java.util.PriorityQueue class Solution { internal class Triplet(var value: Int, var row: Int, var idx: Int) : Comparable<Triplet?> { override operator fun compareTo(other: Triplet?): Int { return value - other!!.value } } fun smallestRange(nums: List<List<Int>>): IntArray { val pq = PriorityQueue<Triplet>() var maxInPq = Int.MIN_VALUE for (i in nums.indices) { pq.add(Triplet(nums[i][0], i, 0)) if (maxInPq < nums[i][0]) { maxInPq = nums[i][0] } } var rangeSize = maxInPq - Objects.requireNonNull(pq.peek()).value + 1 var rangeLeft = Objects.requireNonNull(pq.peek()).value var rangeRight = maxInPq while (true) { val nextNumber = pq.remove() if (nextNumber.idx + 1 < nums[nextNumber.row].size) { val `val` = nums[nextNumber.row][nextNumber.idx + 1] if (`val` > maxInPq) { maxInPq = `val` } pq.add(Triplet(`val`, nextNumber.row, nextNumber.idx + 1)) if (maxInPq - Objects.requireNonNull(pq.peek()).value + 1 < rangeSize) { rangeSize = maxInPq - pq.peek().value + 1 rangeLeft = maxInPq rangeRight = pq.peek().value } } else { break } } val answer = IntArray(2) answer[0] = rangeLeft answer[1] = rangeRight return answer } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,813
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/colinodell/advent2023/Search.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 import java.util.PriorityQueue data class Seen<State>(val cost: Int, val prev: State?) private data class Scored<State>(val state: State, val cost: Int, private val heuristic: Int) : Comparable<Scored<State>> { override fun compareTo(other: Scored<State>): Int = (cost + heuristic).compareTo(other.cost + other.heuristic) } fun <State> aStar( start: State, reachedEnd: (State) -> Boolean, nextStates: (State) -> Iterable<State>, cost: (State, State) -> Int, heuristic: (State) -> Int, ): SearchResult<State> { val seen: MutableMap<State, Seen<State>> = mutableMapOf(start to Seen(0, null)) val next = PriorityQueue(listOf(Scored(start, 0, heuristic(start)))) while (next.isNotEmpty()) { val (state, score) = next.remove() if (reachedEnd(state)) { return SearchResult(state, seen) } nextStates(state) .filter { it !in seen } .map { n -> Scored(n, score + cost(state, n), heuristic(n)) } .forEach { n -> next.add(n) seen[n.state] = Seen(n.cost, state) } } return SearchResult(null, seen) } class SearchResult<State>(private val end: State?, private val seen: Map<State, Seen<State>>) { fun end(): State = end ?: throw IllegalStateException("Failed to find a path") fun score(): Int = seen[end()]!!.cost fun path(): List<State> { val path = mutableListOf<State>() var current: State? = end() while (current != null) { path.add(current) current = seen[current]!!.prev } return path.reversed() } }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
1,682
advent-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ContainsDuplicate2.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.TreeSet import kotlin.math.max /** * Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array * such that nums of i = nums of j and the absolute difference between i and j is at most k. */ fun interface ContainsDuplicate2 { operator fun invoke(nums: IntArray, k: Int): Boolean } /** * Approach #1: Naive Linear Search. * Time complexity : O(n * min(k,n)). * Space complexity : O(1). */ class ContainsDuplicateLinear : ContainsDuplicate2 { override operator fun invoke(nums: IntArray, k: Int): Boolean { for (i in nums.indices) { for (j in max(i - k, 0) until i) { if (nums[i] == nums[j]) return true } } return false } } /** * Approach #2: Binary Search Tree. * Time complexity : O(nlog(min(k,n))). * Space complexity : O(min(n,k)). */ class ContainsDuplicateBinarySearchTree : ContainsDuplicate2 by ContainsDuplicateBehavior(TreeSet()) /** * Approach #3: Hash Table. * */ class ContainsDuplicateHash : ContainsDuplicate2 by ContainsDuplicateBehavior(HashSet()) class ContainsDuplicateBehavior(private val set: MutableSet<Int>) : ContainsDuplicate2 { override operator fun invoke(nums: IntArray, k: Int): Boolean { for (i in nums.indices) { if (set.contains(nums[i])) return true set.add(nums[i]) if (set.size > k) { set.remove(nums[i - k]) } } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,169
kotlab
Apache License 2.0
src/main/kotlin/adventofcode/y2021/Day08.kt
Tasaio
433,879,637
false
{"Kotlin": 117806}
import adventofcode.allPermutations fun main() { val testInput = """ be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce """.trimIndent() val test = Day08(testInput) println("TEST: " + test.part1()) test.reset() println("TEST: " + test.part2()) val day = Day08() val t1 = System.currentTimeMillis() println("${day.part1()} (${System.currentTimeMillis() - t1}ms)") day.reset() val t2 = System.currentTimeMillis() println("${day.part2()} (${System.currentTimeMillis() - t2}ms)") } class Day08(staticInput: String? = null) : Y2021Day(8, staticInput) { private val input = fetchInput().map { it.split('|').map { it.split(' ').filter { it.isNotBlank() }.map { it.trim() } } } private val displayDigits = hashMapOf<Int, Set<Char>>( Pair(0, hashSetOf('a', 'b', 'c', 'e', 'f', 'g')), Pair(1, hashSetOf('c', 'f')), Pair(2, hashSetOf('a', 'c', 'd', 'e', 'g')), Pair(3, hashSetOf('a', 'c', 'd', 'f', 'g')), Pair(4, hashSetOf('b', 'c', 'd', 'f')), Pair(5, hashSetOf('a', 'b', 'd', 'f', 'g')), Pair(6, hashSetOf('a', 'b', 'd', 'e', 'f', 'g')), Pair(7, hashSetOf('a', 'c', 'f')), Pair(8, hashSetOf('a', 'b', 'c', 'd', 'e', 'f', 'g')), Pair(9, hashSetOf('a', 'b', 'c', 'd', 'f', 'g')), ) override fun reset() { super.reset() } override fun part1(): Number? { val targetLength = hashSetOf(2, 3, 5, 7) input.forEach { it[1].forEach { if (targetLength.contains(it.length)) { sum++ } } } return sum } override fun part2(): Number? { val permutations = displayDigits[8]!!.allPermutations() return input.sumOf { line -> val matchingDic = permutations.firstNotNullOf { permutation -> val dic = hashMapOf<Char, Char>() for (i in 0..6) { dic['a' + i] = permutation[i] } val match = line[0].all { displayDigits.containsValue( it.map { dic[it] }.toSet() ) } if (match) dic else null } var res = "" for (word in line[1]) { val translated = word.map { matchingDic[it] }.toSet() val digit = displayDigits.entries.filter { it.value == translated }.map { it.key }.single() res += digit.toString() } res.toInt() } } }
0
Kotlin
0
0
cc72684e862a782fad78b8ef0d1929b21300ced8
3,390
adventofcode2021
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/ConstructQuadTree.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 427. Construct Quad Tree * @see <a href="https://leetcode.com/problems/construct-quad-tree/">Source</a> */ fun interface ConstructQuadTree { fun construct(grid: Array<IntArray>): QuadTreeNode? } class ConstructQuadTreeRecursive : ConstructQuadTree { override fun construct(grid: Array<IntArray>): QuadTreeNode? { return if (grid.isEmpty()) null else helper(grid, 0, 0, grid.size) } fun helper(grid: Array<IntArray>, x: Int, y: Int, len: Int): QuadTreeNode { val newNode = QuadTreeNode(grid[x][y] != 0, true) val half = len / 2 if (len == 1) return newNode val topL = helper(grid, x, y, half) val topR = helper(grid, x, y + half, half) val bottomL = helper(grid, x + half, y, half) val bottomR = helper(grid, x + half, y + half, half) val c1 = topL.isLeaf.not().or(topR.isLeaf.not()).or(bottomL.isLeaf.not()).or(bottomR.isLeaf.not()) val c2 = (topL.value != topR.value).or(topR.value != bottomL.value).or(bottomL.value != bottomR.value) if (c1 || c2) { newNode.apply { topLeft = topL topRight = topR bottomLeft = bottomL bottomRight = bottomR isLeaf = false } } return newNode } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,961
kotlab
Apache License 2.0
src/Day01.kt
Inn0
573,532,249
false
{"Kotlin": 16938}
fun main() { fun getElvesList(input: List<String>): MutableList<MutableList<Int>> { val elvesList: MutableList<MutableList<Int>> = mutableListOf() var elf: MutableList<Int> = mutableListOf() input.forEach { if (it == ""){ elvesList.add(elf) elf = mutableListOf() } else { elf.add(it.toInt()) } } elvesList.add(elf) return elvesList } fun getTotalCalories(elf: List<Int>): Int { var total = 0 elf.forEach { total += it } return total } fun part1(input: List<String>): Int { val elvesList = getElvesList(input) var highest = 0 elvesList.forEach { val current = getTotalCalories(it) if (current > highest){ highest = current } } return highest } fun part2(input: List<String>): Int { val elves = getElvesList(input) var totalsList: MutableList<Int> = mutableListOf() elves.forEach { totalsList.add(getTotalCalories(it)) } totalsList = totalsList.sortedDescending().toMutableList() totalsList = totalsList.take(3).toMutableList() var total = 0 totalsList.forEach { total += it } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
f35b9caba5f0c76e6e32bc30196a2b462a70dbbe
1,710
aoc-2022
Apache License 2.0
src/day03/Day03.kt
Xlebo
572,928,568
false
{"Kotlin": 10125}
package day03 import getOrFetchInputData import readInput fun main() { fun getValueOfItem(item: Char): Int { return if (item.isLowerCase()) { item.code - 96 } else { item.code - 38 } } fun part1(input: List<String>): Int { return input.map { Pair(it.substring(0, it.length / 2), it.substring(it.length / 2, it.length)) } .map { pair -> pair.first.first { pair.second.contains(it) } } .sumOf { getValueOfItem(it) } } fun part2(input: List<String>): Int { return input.chunked(3) .map { group -> group[0].first { group[1].contains(it) && group[2].contains(it) } } .sumOf { getValueOfItem(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test", "day03") val result1 = part1(testInput) val result2 = part2(testInput) check(result1 == 157) { "Got: $result1" } check(result2 == 70) { "Got: $result2" } val input = getOrFetchInputData(3) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
cd718c2c7cb59528080d2aef599bd93e0919d2d9
1,190
aoc2022
Apache License 2.0
test/leetcode/AssignCookies.kt
andrej-dyck
340,964,799
false
null
package leetcode import lib.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.* import org.junit.jupiter.params.converter.* import org.junit.jupiter.params.provider.* /** * https://leetcode.com/problems/assign-cookies/ * * 455. Assign Cookies * [Easy] * * Assume you are an awesome parent and want to give your children some cookies. * But, you should give each child at most one cookie. * * Each child i has a greed factor g[i], which is the minimum size of a cookie that the child * will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign * the cookie j to the child i, and the child i will be content. Your goal is to maximize * the number of your content children and output the maximum number. * * Constraints: * - 1 <= g.length <= 3 * 10^4 * - 0 <= s.length <= 3 * 10^4 * - 1 <= g[i], s[j] <= 2^31 - 1 */ fun findContentChildren(childrenGreeds: Array<Int>, cookieSizes: Array<Int>) = childrenGreeds.asSequence().sorted() .zipIf(cookieSizes.asSequence().sorted()) { g, s -> s >= g } .count() /** * zipIf - integrates sequence with only those items from the other sequence which * satisfy the predicate */ fun <T, R> Sequence<T>.zipIf( other: Sequence<R>, predicate: (T, R) -> Boolean ): Sequence<Pair<T, R>> { tailrec fun recZipIf( s1: Sequence<T>, s2: Sequence<R>, pairs: Sequence<Pair<T, R>> = emptySequence() ): Sequence<Pair<T, R>> { val (f1, rs1) = s1.headTails() val (f2, rs2) = s2.dropWhile { f1 != null && !predicate(f1, it) }.headTails() return when { f1 == null || f2 == null -> pairs else -> recZipIf(rs1, rs2, pairs + (f1 to f2)) } } return recZipIf(this, other) } //fun <T, R> Sequence<T>.zipIf(other: Sequence<R>, predicate: (T, R) -> Boolean): Sequence<Pair<T, R>> { // val thisIterator = iterator() // val otherIterator = other.iterator() // // return sequence { // while (thisIterator.hasNext()) { // val thisNext = thisIterator.next() // // while (otherIterator.hasNext()) { // val otherNext = otherIterator.next() // // if (predicate(thisNext, otherNext)) { // yield(thisNext to otherNext) // break // } // } // } // } //} /** * Unit tests */ class AssignCookiesTest { @ParameterizedTest @CsvSource( "[1,2,3]; [1,1]; 1", "[1,2]; [1,2,3]; 2", "[4,1,3,2,1,1,2,2]; [1,1,1,1]; 3", "[4,1,3,2,1,1,2,2]; [2,2,2,2]; 4", "[1,2,3,3]; [1,1,1,1,3,3,3]; 4", "[2,2,2,5]; [1,1,1,4]; 1", delimiter = ';' ) fun `maximize the number of your content children`( @ConvertWith(IntArrayArg::class) childrenGreed: Array<Int>, @ConvertWith(IntArrayArg::class) cookieSizes: Array<Int>, expectedNumberOfContentChildren: Int ) { assertThat( findContentChildren(childrenGreed, cookieSizes) ).isEqualTo( expectedNumberOfContentChildren ) } }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
3,151
coding-challenges
MIT License
src/main/kotlin/days/Day6.kt
MaciejLipinski
317,582,924
true
{"Kotlin": 60261}
package days class Day6 : Day(6) { override fun partOne(): Any { return splitIntoGroups(inputString) .map { FormGroup.from(it) } .map { it.distinctAnswers() } .map { it.count() } .sum() } override fun partTwo(): Any { return splitIntoGroups(inputString) .map { FormGroup.from(it) } .map { it.commonAnswers() } .map { it.count() } .sum() } private fun splitIntoGroups(input: String): List<String> { val groups = mutableListOf<String>() val groupLines = mutableListOf<String>() for (i in inputList.indices) { if (inputList[i].isBlank()) { groups.add(groupLines.reduce { acc, s -> "$acc $s" }) groupLines.clear() continue } groupLines.add(inputList[i]) } groups.add(groupLines.reduce { acc, s -> "$acc $s" }) return groups } } data class FormGroup(val forms: List<Form>) { fun distinctAnswers(): List<Char> = forms.flatMap { it.answers }.distinct() fun commonAnswers(): List<Char> = distinctAnswers().filter { forms.all { form -> form.answers.contains(it) } } companion object { fun from(input: String): FormGroup = FormGroup(input.split(" ").map { Form(it.toCharArray().toList()) }) } } data class Form(val answers: List<Char>)
0
Kotlin
0
0
1c3881e602e2f8b11999fa12b82204bc5c7c5b51
1,471
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/dangerground/aoc2020/Day14.kt
dangerground
317,439,198
false
null
package com.github.dangerground.aoc2020 import com.github.dangerground.aoc2020.util.DayInput import kotlin.math.pow fun main() { val process = Day14(DayInput.asStringList(14)) println("result part 1: ${process.part1()}") println("result part 2: ${process.part2()}") } class Day14(val input: List<String>) { var mask = "X".repeat(36) var mem = mutableMapOf<Long, Long>() val regex = Regex("mem\\[(\\d+)] = (\\d+)") fun part1(): Long { input.forEach { if (it.startsWith("mask")) { mask = it.substring(7).reversed() //println("mask $mask") } else { val groups = regex.matchEntire(it)!! val memPos = groups.groupValues[1] val memVal = groups.groupValues[2] val numToBitArray = numToBitArray(memVal.toLong()) val applyMask = applyMask(numToBitArray) val bitsToLong = bitsToLong(applyMask) println("value: ${numToBitArray.contentToString()} (decimal $memVal)") println("mask: ${mask}") println("result: ${applyMask.contentToString()} (decimal $bitsToLong)") mem[memPos.toLong()] = bitsToLong } } return mem.map { it.value }.sum() } private fun bitsToLong(applyMask: LongArray): Long { var result = 0L applyMask.forEachIndexed { index, i -> if (i == 1L) { result += 2.0.pow(index).toLong() } } return result } fun numToBitArray(num: Long): IntArray { val result = IntArray(36) var remaining = num for (i in 35 downTo 0) { val test = 2.0.pow(i) if (remaining >= test) { remaining -= test.toLong() result[i] = 1 } } return result } fun applyMask(x: IntArray): LongArray { val y = x.toList().map {it.toLong()}.toLongArray() mask.forEachIndexed { index, c -> if (c != 'X') { y[index] = c.toString().toLong() } } return y } fun part2(): Long { mem.clear() input.forEach { if (it.startsWith("mask")) { mask = it.substring(7).reversed() //println("mask $mask") } else { val groups = regex.matchEntire(it)!! val memPos = groups.groupValues[1] val memVal = groups.groupValues[2] val numToBitArray = numToBitArray(memPos.toLong()) val applyMask = applyMask2(numToBitArray) val expandFloating = expandFloating(applyMask) expandFloating.forEach { val pos = bitsToLong(it.map { it.toLong() }.toTypedArray().toLongArray()) mem[pos] = memVal.toLong() } //println("$expandFloating") //val bitsToLong = bitsToLong(applyMask) //println("value: ${numToBitArray.contentToString()} (decimal $memVal)") //println("mask: ${mask}") //println("result: ${applyMask} (decimal bitsToLong)") // mem[memPos.toInt()] = bitsToLong } } return mem.map { it.value }.sum() } private fun expandFloating(applyMask: List<String>): List<List<String>> { val toProcess = mutableListOf(applyMask) val results = mutableListOf<List<String>>() while (toProcess.size > 0) { val current = toProcess.removeAt(0) if (!current.contains("X")) { results.add(current) } else { //println("current $current") val pos = current.indexOf("X") val first = current.toMutableList() first[pos] = "1" toProcess.add(first) val second = current.toMutableList() second[pos] = "0" toProcess.add(second) } } return results } fun applyMask2(x: IntArray): List<String> { val y = x.map { it.toString() }.toMutableList() mask.forEachIndexed { index, c -> if (c != '0') { y[index] = c.toString() } } return y } }
0
Kotlin
0
0
c3667a2a8126d903d09176848b0e1d511d90fa79
4,418
adventofcode-2020
MIT License
src/day8/Day08.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day8 import readInput private var counter: Int = 0 private fun part1(input: List<String>): Int { val grid: Array<IntArray> = Array(input.size) { IntArray(input[0].length) } val added: Array<BooleanArray> = Array(input.size) { BooleanArray(input[0].length) } for (row in input.indices) { for (col in 0 until input[row].length) { grid[row][col] = input[row][col].digitToInt() } } counter = 2 * grid[0].size + 2 * (grid.size - 2) for (row in 1 until grid.size - 1) { helperHorizontalLeft(row, 1, grid, grid[row][0], added) helperHorizontalRight(row, grid[0].size - 2, grid, grid[row][grid[0].size - 1], added) } for (col in 1 until grid[0].size - 1) { helperVerticalUp(1, col, grid, grid[0][col], added) helperVerticalDown(grid.size - 2, col, grid, grid[grid.size - 1][col], added) } return counter } private fun helperHorizontalLeft(row: Int, col: Int, grid: Array<IntArray>, max: Int, added: Array<BooleanArray>) { checkPartOne(row, col, grid, max, added) { helperHorizontalLeft(row, col + 1, grid, it, added) } } private fun helperHorizontalRight(row: Int, col: Int, grid: Array<IntArray>, max: Int, added: Array<BooleanArray>) { checkPartOne(row, col, grid, max, added) { helperHorizontalRight(row, col - 1, grid, it, added) } } private fun helperVerticalDown(row: Int, col: Int, grid: Array<IntArray>, max: Int, added: Array<BooleanArray>) { checkPartOne(row, col, grid, max, added) { helperVerticalDown(row - 1, col, grid, it, added) } } private fun helperVerticalUp(row: Int, col: Int, grid: Array<IntArray>, max: Int, added: Array<BooleanArray>) { checkPartOne(row, col, grid, max, added) { helperVerticalUp(row + 1, col, grid, it, added) } } private fun checkPartOne( row: Int, col: Int, grid: Array<IntArray>, max: Int, added: Array<BooleanArray>, nextCall: (max: Int) -> Unit ) { if (row <= 0 || col <= 0 || row >= grid.size - 1 || col >= grid[0].size - 1) return val current = grid[row][col] if (current > max && !added[row][col]) { counter++ added[row][col] = true } val nextMax = Math.max(max, current) nextCall(nextMax) } private fun part2(input: List<String>): Int { val grid: Array<IntArray> = Array(input.size) { IntArray(input[0].length) } for (row in input.indices) { for (col in 0 until input[row].length) { grid[row][col] = input[row][col].digitToInt() } } var max = 0 for (row in 1 until grid.size - 1) { for (col in 1 until grid[0].size - 1) { max = max.coerceAtLeast(helperPartTwo(row, col, grid)) } } return max } private fun helperPartTwo(row: Int, col: Int, grid: Array<IntArray>): Int { val current = grid[row][col] val left = helperLeft(row, col - 1, grid, current) val right = helperRight(row, col + 1, grid, current) val top = helperUp(row + 1, col, grid, current) val bottom = helperDown(row - 1, col, grid, current) return left * top * right * bottom } private fun helperLeft(row: Int, col: Int, grid: Array<IntArray>, max: Int): Int { if (row < 0 || col < 0 || row > grid.size - 1 || col > grid[0].size - 1) return 0 if (grid[row][col] >= max) return 1 return 1 + helperLeft(row, col - 1, grid, max) } private fun helperRight(row: Int, col: Int, grid: Array<IntArray>, max: Int): Int { if (row < 0 || col < 0 || row > grid.size - 1 || col > grid[0].size - 1) return 0 if (grid[row][col] >= max) return 1 return 1 + helperRight(row, col + 1, grid, max) } private fun helperDown(row: Int, col: Int, grid: Array<IntArray>, max: Int): Int { if (row < 0 || col < 0 || row > grid.size - 1 || col > grid[0].size - 1) return 0 if (grid[row][col] >= max) return 1 return 1 + helperDown(row - 1, col, grid, max) } private fun helperUp(row: Int, col: Int, grid: Array<IntArray>, max: Int): Int { if (row < 0 || col < 0 || row > grid.size - 1 || col > grid[0].size - 1) return 0 if (grid[row][col] >= max) return 1 return 1 + helperUp(row + 1, col, grid, max) } fun main() { val input = readInput("day8/input") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
4,306
aoc-2022
Apache License 2.0
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/common/Collections.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.common import java.util.* /** * Generates all permutations of a list. * @see <a href="https://rosettacode.org/wiki/Permutations#Kotlin">Source on RosettaCode</a> */ fun <T> List<T>.permutations(): List<List<T>> { if (this.size == 1) return listOf(this) val perms = mutableListOf<List<T>>() val toInsert = this[0] for (perm in this.drop(1).permutations()) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) perms.add(newPerm) } } return perms } /** * Generates all combinations of a list of size m. * @see <a href="https://rosettacode.org/wiki/Combinations#Kotlin">Source on RosettaCode</a> */ inline fun <reified T> List<T>.combinations(m: Int): Sequence<List<T>> { val items = this return sequence { val result = MutableList(m) { items[0] } val stack = LinkedList<Int>() stack.push(0) while (stack.isNotEmpty()) { var resIndex = stack.size - 1 var arrIndex = stack.pop() while (arrIndex < size) { result[resIndex++] = items[arrIndex++] stack.push(arrIndex) if (resIndex == m) { yield(result.toList()) break } } } } } fun <T, U> allPairs(first: Iterable<T>, second: Iterable<U>) = sequence { for (a in first) { for (b in second) { yield(Pair(a, b)) } } } fun <T, U, V> allTriples(first: Iterable<T>, second: Iterable<U>, third: Iterable<V>) = sequence { for (a in first) { for (b in second) { for (c in third) { yield(Triple(a, b, c)) } } } } fun <T> Iterable<T>.allPairs() = allPairs(this, this) fun <T> Iterable<T>.allTriples() = allTriples(this, this, this) fun <T> MutableMap<T, Int>.increaseBy(key: T, value: Int) = merge(key, value) { a, b -> a + b } fun <T> MutableMap<T, Long>.increaseBy(key: T, value: Long) = merge(key, value) { a, b -> a + b }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
2,111
advent-of-code
MIT License
leetcode/kotlin/insert-interval.kt
PaiZuZe
629,690,446
false
null
import kotlin.math.max class Solution { fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { val newIntervals = mutableListOf<IntArray>() var newIserted = false if (intervals.size == 0 || intervals[0][0] >= newInterval[0]) { newIntervals.add(newInterval) newIserted = true } else { newIntervals.add(intervals[0]) } var lastInterval = newIntervals.last() var i = 0 while (i < intervals.size) { val interval = intervals[i] if (!newIserted && newInterval[0] <= lastInterval[1]) { lastInterval[1] = max(lastInterval[1], newInterval[1]) newIserted = true continue } if (interval[0] <= lastInterval[1]) { lastInterval[1] = max(lastInterval[1], interval[1]) i++ continue } if (!newIserted && newInterval[0] <= interval[0]) { newIntervals.add(newInterval) lastInterval = newInterval newIserted = true continue } lastInterval = interval newIntervals.add(interval) i++ } if (!newIserted && newInterval[0] <= lastInterval[1]) { lastInterval[1] = max(lastInterval[1], newInterval[1]) newIserted = true } else if (!newIserted) { newIntervals.add(newInterval) } return newIntervals.toTypedArray() } } // private fun joinIntervals(intervals: Array<IntArray>, start: Int, end: Int): Array<IntArray> { // val newIntervals = mutableList<IntArray>() // for (i in 0 until start) { // newInterval.add(intervals[i]) // } // newInterval.add() // } // private fun intervalBinSearchEnd(arr: Array<IntArray>, target: Int, start: Int, end: Int): Int { // if (end <= start) { // return end // } // val middle = ((end - start) / 2) + start // if (target >= arr[middle][0] && target <= arr[middle][1]) { // return middle // } // if (target < arr[middle][1]) { // return intervalBinSearch(arr, target, start, middle) // } else { // return intervalBinSearch(arr, target, middle + 1, end) // } // } fun main () { val sol = Solution() val arr = arrayOf<IntArray> ( intArrayOf(1,2), intArrayOf(3,5), intArrayOf(6,7), intArrayOf(8,10), intArrayOf(12,16) ) var target = 0 println(sol.intervalBinSearch(arr, target, 0, arr.size)) target = 1 println(sol.intervalBinSearch(arr, target, 0, arr.size)) target = 5 println(sol.intervalBinSearch(arr, target, 0, arr.size)) target = 11 println(sol.intervalBinSearch(arr, target, 0, arr.size)) target = 18 println(sol.intervalBinSearch(arr, target, 0, arr.size)) }
0
Kotlin
0
0
175a5cd88959a34bcb4703d8dfe4d895e37463f0
2,957
interprep
MIT License
src/main/kotlin/day23/Day23.kt
Arch-vile
317,641,541
false
null
package day23 class Cup(val label: Int, var previous: Cup?, var next: Cup?) { fun joinWith(joinWith: Cup) { next = joinWith joinWith.previous = this } override fun toString() = label.toString() } fun main(args: Array<String>) { val maxCupLabel = 1000000 val cupSetting = "253149867".windowed(1) .map { it.toInt() } .plus(IntRange(10,maxCupLabel).toList()) var firstCup = buildLinkedList(cupSetting) val lookupTable = buildLookupTable(firstCup) IntRange(1, 10000000).forEach { val firstMoved = firstCup.next!! val middleMoved = firstMoved.next!! val lastMoved = middleMoved.next!! // Fix the references to fill the gap firstCup.joinWith(lastMoved.next!!) var targetCupLabel = targetCupLabel(firstCup, firstMoved.label, middleMoved.label, lastMoved.label, maxCupLabel) lastMoved.joinWith(lookupTable[targetCupLabel]!!.next!!) lookupTable[targetCupLabel]!!.joinWith(firstMoved) firstCup = firstCup.next!! } var cup1 = lookupTable[1]!!.next!!.label var cup2 = lookupTable[1]!!.next!!.next!!.label println(cup1) println(cup2) println(cup1.toLong()*cup2) } fun targetCupLabel(indexCup: Cup, first: Int, middle: Int, last: Int, max: Int): Int { val cupLabel = indexCup.label val movedValues = listOf(first, middle, last) var target = cupLabel do { target-- }while (movedValues.contains(target)) if(target > 0) return target target = max while(movedValues.contains(target)){ target-- } return target } fun buildLookupTable(firstCup: Cup): Map<Int, Cup> { val map = mutableMapOf<Int, Cup>() var currentCup = firstCup do { map[currentCup.label] = currentCup currentCup = currentCup.next!! } while (currentCup != firstCup) return map } fun buildLinkedList(cupSetting: List<Int>): Cup { var first = Cup(cupSetting.first(), null, null) var previous = first for (cupLabel in cupSetting.drop(1)) { val latest = Cup(cupLabel, previous, null) previous.next = latest previous = latest } first.previous = previous previous.next = first return first }
0
Kotlin
0
0
12070ef9156b25f725820fc327c2e768af1167c0
2,113
adventOfCode2020
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindDuplicate.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * Find Duplicate File in System * @see <a href="https://leetcode.com/problems/find-duplicate-file-in-system/">Source</a> */ fun interface FindDuplicate { operator fun invoke(paths: Array<String>): List<List<String>> } /** * Approach #1 Brute Force * Time complexity : O(n*x + f^2*s). * Space complexity : O(n*x). */ class FindDuplicateBruteForce : FindDuplicate { override operator fun invoke(paths: Array<String>): List<List<String>> { val list: MutableList<Array<String>> = ArrayList() for (path in paths) { val values = path.split(" ".toRegex()).toTypedArray() for (i in 1 until values.size) { val nameCont = values[i].split("\\(".toRegex()).toTypedArray() nameCont[1] = nameCont[1].replace(")", "") list.add( arrayOf( values[0] + "/" + nameCont[0], nameCont[1], ), ) } } val visited = BooleanArray(list.size) val res: MutableList<List<String>> = ArrayList() for (i in 0 until list.size - 1) { if (visited[i]) continue val l: MutableList<String> = ArrayList() for (j in i + 1 until list.size) { if (list[i][1] == list[j][1]) { l.add(list[j][0]) visited[j] = true } } if (l.isNotEmpty()) { l.add(list[i][0]) res.add(l) } } return res } } /** * Approach #2 Using HashMap */ class FindDuplicateHashMap : FindDuplicate { override operator fun invoke(paths: Array<String>): List<List<String>> { val map = HashMap<String, MutableList<String>>() for (path in paths) { val values = path.split(" ".toRegex()).toTypedArray() for (i in 1 until values.size) { val nameCont = values[i].split("\\(".toRegex()).toTypedArray() nameCont[1] = nameCont[1].replace(")", "") val list = map.getOrDefault(nameCont[1], ArrayList()) list.add(values[0] + "/" + nameCont[0]) map[nameCont[1]] = list } } val res: MutableList<List<String>> = ArrayList() for (key in map.keys) { if (map[key]!!.size > 1) res.add(map[key]!!) } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,103
kotlab
Apache License 2.0
src/Day01.kt
esp-er
573,196,902
false
{"Kotlin": 29675}
package patriker.day01 import patriker.utils.* fun main() { // test if implementation meets criteria from the description, like: val testInput = readInputText("Day01_test") check(solvePart1(testInput) == 24000) check(solvePart2(testInput) == listOf(24000, 11000, 10000)) val input = readInputText("Day01_input") println(solvePart1(input)) println(solvePart2(input).sum()) } fun caloriesPerElf(input: String): List<Int>{ val calories = input.split("\n\n").map {cals -> cals.lines().filter(String::isNotBlank).map{ it.toInt() }.sum() } return calories } fun solvePart1(input: String): Int{ val elfCalorieList = caloriesPerElf(input) return elfCalorieList.max() } fun solvePart2(input: String): List<Int>{ val elfCalorieList = caloriesPerElf(input) return elfCalorieList.sortedDescending().take(3) }
0
Kotlin
0
0
f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362
892
aoc2022
Apache License 2.0
src/Day11.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { val multiply = 0 val add = 1 data class Data( val items: ArrayDeque<Long>, val operation: Int, val operand: Long, val divisor: Long, val passTrue: Int, val passFalse: Int ) fun parseInput(input: List<String>): List<Data> { var i = 0 val items = mutableListOf<Data>() while (i < input.size) { i++ val line2 = input[i].substringAfter(": ") i++ val line3 = input[i].substringAfter(" = old ") val operand = line3.substringAfter(' ') i++ val divisor = input[i].substringAfter("Test: divisible by ").toLong() i++ val passTrue = input[i].substringAfter("If true: throw to monkey ").toInt() i++ val passFalse = input[i].substringAfter("If false: throw to monkey ").toInt() i += 2 items.add( Data( items = ArrayDeque(line2.split(", ").map { it.toLong() }), operation = if (line3[0] == '*') multiply else add, operand = if (operand != "old") operand.toLong() else 0, divisor = divisor, passTrue = passTrue, passFalse = passFalse, ) ) } return items } fun part1(input: List<String>): Int { val data = parseInput(input) val inspectionCount = MutableList(data.size) { 0 } for (round in 0 until 20) { for ((index, value) in data.withIndex()) { while (value.items.isNotEmpty()) { val first = value.items.removeFirst() val calculated = if (value.operation == multiply) { var operand = value.operand if (operand == 0.toLong()) { operand = first } first * operand } else { first + value.operand } / 3 inspectionCount[index]++ val pass = if (calculated % value.divisor == 0.toLong()) { value.passTrue } else { value.passFalse } data[pass].items.add(calculated) } } } var answer = inspectionCount.max() inspectionCount.remove(answer) answer *= inspectionCount.max() return answer } fun part2(input: List<String>): Long { val data = parseInput(input) val inspectionCount = MutableList<Long>(data.size) { 0 } var lcm = 1.toLong() for (it in data) { lcm *= it.divisor } for (round in 0 until 10000) { for ((index, value) in data.withIndex()) { while (value.items.isNotEmpty()) { val first = value.items.removeFirst() val calculated = if (value.operation == multiply) { var operand = value.operand if (operand == 0.toLong()) { operand = first } first * operand } else { first + value.operand } % lcm inspectionCount[index]++ val pass = if (calculated % value.divisor == 0.toLong()) { value.passTrue } else { value.passFalse } data[pass].items.add(calculated) } } } var answer = inspectionCount.max() inspectionCount.remove(answer) answer *= inspectionCount.max() return answer } val testInput = readInput("Day11_test") check(part1(testInput) == 10605) check(part2(testInput) == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
4,161
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day24.kt
mstar95
317,305,289
false
null
package days import arrow.core.mapOf import days.Direction.E import days.Direction.NE import days.Direction.NW import days.Direction.SE import days.Direction.SW import days.Direction.W import days.HexColor.* class Day24 : Day(24) { override fun partOne(): Any { val input = parseInput(inputList) println(run(listOf(E, SE, NE, E))) val result = input.fold(mapOf(), this::run) return result.filter { it.value == BLACK }.size } override fun partTwo(): Any { val input = parseInput(inputList) val floor = input.fold(mapOf(), this::run) val result = (1..100).fold(floor) {acc, it -> day(acc)} return result.filter { it.value == BLACK }.size } fun day(fields: Map<Field, HexColor>): Map<Field, HexColor> { val blacks = fields.filter { it.value == BLACK } val blacksWithNeighbours: List<Pair<Map.Entry<Field, HexColor>, List<Pair<Field, HexColor>>>> = blacks.map { black -> black to black.key.neighbours().map { it to (fields.get(it) ?: WHITE) } } val blacksToWhite = blacksWithNeighbours.filter { black -> shouldMutateBlack(black.second) } .map { it.first }.map { it.key} val whiteToBlacks = blacksWithNeighbours.toList().map { black -> black.second.filter { it.second == WHITE } }.flatten() .groupBy { it }.filter { shouldMutateWhite(it) }.keys.map { it.first } return fields + whiteToBlacks.map { it to BLACK }.toMap() + blacksToWhite.map { it to WHITE }.toMap() } fun shouldMutateBlack(neighbours: List<Pair<Field, HexColor>>): Boolean { val size = neighbours.filter { it.second == BLACK }.size return size == 0 || size > 2 } fun shouldMutateWhite(entry: Map.Entry<Pair<Field, HexColor>, List<Pair<Field, HexColor>>>): Boolean { val size = entry.value.size return size == 2 } fun run(fields: Map<Field, HexColor>, directions: List<Direction>): Map<Field, HexColor> { val f = run(directions) if (fields.get(f) ?: WHITE == WHITE) { return fields + (f to BLACK) } else { return fields + (f to WHITE) } } fun run(directions: List<Direction>): Field { return directions.fold(Field(0, 0, 0)) { acc, dir -> acc + dir } } fun parseInput(input: List<String>): List<List<Direction>> { return input.map { row -> row.fold(emptyList<Direction>() to null, this::parseChar).first } } fun parseChar(acc: Pair<List<Direction>, Char?>, char: Char): Pair<List<Direction>, Char?> { val (list, lastChar) = acc if (lastChar == 's') { return when (char) { 'e' -> (list + listOf(SE)) to null 'w' -> (list + listOf(SW)) to null else -> error("Bad char $char") } } if (lastChar == 'n') { return when (char) { 'e' -> (list + listOf(NE)) to null 'w' -> (list + listOf(NW)) to null else -> error("Bad char $char") } } assert(lastChar == null) { "Bad char $char" } return when (char) { 'e' -> (list + listOf(E)) to null 'w' -> (list + listOf(W)) to null 's', 'n' -> list to char else -> error("Bad char $char") } } } enum class HexColor { WHITE, BLACK } enum class Direction(val x: Int, val y: Int, val z: Int) { E(1, -1, 0), SE(0, -1, 1), SW(-1, 0, 1), W(-1, 1, 0), NW(0, 1, -1), NE(1, 0, -1) } data class Field(val x: Int, val y: Int, val z: Int) { operator fun plus(direction: Direction): Field { return Field(x + direction.x, y + direction.y, z + direction.z) } fun neighbours(): List<Field> { return Direction.values().map { this + it } } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
3,910
aoc-2020
Creative Commons Zero v1.0 Universal
src/Day10.kt
mr-cell
575,589,839
false
{"Kotlin": 17585}
import kotlin.math.absoluteValue fun main() { fun part1(input: List<String>): Int { val signals = parseInput(input).runningReduce(Int::plus) return signals.sampleSignals().sum() } fun part2(input: List<String>) { val signals = parseInput(input).runningReduce(Int::plus) signals.screen().print() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) } private fun parseInput(input: List<String>): List<Int> { return buildList { add(1) input.forEach { line -> add(0) if (line.startsWith("addx")) { add(line.substringAfter(" ").toInt()) } } } } private fun List<Int>.sampleSignals(): List<Int> = (60.. size step 40).map { cycle -> cycle * this[cycle - 1] } + this[19] * 20 private fun List<Int>.screen(): List<Boolean> = this.mapIndexed { pixel, signal -> (signal - (pixel % 40)).absoluteValue <= 1 } private fun List<Boolean>.print() { this.windowed(40, 40, false).forEach { row -> row.forEach { pixel -> print(if(pixel) '#' else ' ') } println() } }
0
Kotlin
0
0
2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9
1,366
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1380/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1380 /** * LeetCode page: [1380. Lucky Numbers in a Matrix](https://leetcode.com/problems/lucky-numbers-in-a-matrix/); */ class Solution { /* Complexity: * Time O(MN) and Space O(1) where M and N are mat.length and mat[0].length; */ fun luckyNumbers(matrix: Array<IntArray>): List<Int> { val maxRowMin = getMaxOfRowMinimums(matrix) val minColumnMax = getMinOfColumnMaximums(matrix) return if (maxRowMin == minColumnMax) listOf(maxRowMin) else listOf() } private fun getMaxOfRowMinimums(matrix: Array<IntArray>): Int { var maxRowMin = checkNotNull(matrix[0].min()) for (row in 1..matrix.lastIndex) { val rowMin = checkNotNull(matrix[row].min()) if (maxRowMin < rowMin) maxRowMin = rowMin } return maxRowMin } private fun getMinOfColumnMaximums(matrix: Array<IntArray>): Int { var minColumnMax = getMaximumOfColumn(0, matrix) for (column in 1..matrix[0].lastIndex) { val columnMax = getMaximumOfColumn(column, matrix) if (minColumnMax > columnMax) minColumnMax = columnMax } return minColumnMax } private fun getMaximumOfColumn(column: Int, matrix: Array<IntArray>): Int { var columnMax = matrix[0][column] for (row in 1..matrix.lastIndex) { val num = matrix[row][column] if (columnMax < num) columnMax = num } return columnMax } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,511
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day07/day7.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day07 import biz.koziolek.adventofcode.findInput import kotlin.math.abs fun main() { val inputFile = findInput(object {}) val line = inputFile.bufferedReader().readLines().first() val (position, cost) = findCheapestPosition(line, ::calculateLinearCost) println("Cheapest position is $position with linear cost: $cost") val (position2, cost2) = findCheapestPosition(line, ::calculateNonLinearCost) println("Cheapest position is $position2 with non-linear cost: $cost2") } fun findCheapestPosition(line: String, costFunction: (Int, Int) -> Int): Pair<Int, Int> { val initialPositions = line.split(',') .map { it.toInt() } return (0..initialPositions.maxOf { it }) .map { dst -> Pair(dst, initialPositions.sumOf { src -> costFunction(src, dst) }) } .minByOrNull { it.second } ?: throw IllegalArgumentException("Could not find cheapest position") } fun calculateLinearCost(source: Int, destination: Int): Int = abs(source - destination) fun calculateNonLinearCost(source: Int, destination: Int): Int { val n = abs(source - destination) return ((1 + n) / 2.0 * n).toInt() }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
1,216
advent-of-code
MIT License
src/main/kotlin/com/chriswk/aoc/advent2018/Day2.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2018 object Day2 { fun partOne(input: List<String>): Int { val (twos, threes) = input.asSequence().map { line -> val charCount = line.groupBy { c -> c }.mapValues { it.value.size } val hasTwoChars = charCount.entries.any { it.value == 2 } val hasThreeChars = charCount.entries.any { it.value == 3 } (hasTwoChars to hasThreeChars) }.fold((0 to 0)) { (twos, threes), (hasTwoChars, hasThreeChars) -> when(hasTwoChars) { true -> when(hasThreeChars) { true -> (twos+1 to threes+1) false -> (twos + 1 to threes) } false -> when(hasThreeChars) { true -> (twos to threes + 1) false -> (twos to threes) } } } return twos * threes } fun partTwo(input: List<String>): String { return input.asSequence().mapIndexedNotNull { i, checksum -> input.subList(i, input.size).map { candidate -> candidate.filterIndexed { i, c -> c == checksum[i]} }.firstOrNull { candidate -> candidate.length == checksum.length - 1 } }.first() } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
1,311
adventofcode
MIT License
src/Day07.kt
tristanrothman
572,898,348
false
null
data class Directory( val path: String, ) { fun back(): Directory { return Directory(path.substringBeforeLast('/')) } } data class FileSystem( var pwd: Directory, val sizes: MutableMap<Directory, Int> = mutableMapOf(pwd to 0) ) { fun cd(dir: String) { pwd = when (dir) { ".." -> pwd.back() else -> Directory("${pwd.path}/$dir") } } } fun main() { fun List<String>.isCd() = this.component2() == "cd" fun List<String>.hasSize() = this.component1().all { it.isDigit() } fun List<String>.getSize() = this.component1().toInt() val root = Directory("") val testInput = readInput("Day07_test") val input = readInput("Day07") fun List<String>.fileSystem() = this.drop(1).fold(FileSystem(root)) { fileSystem, item -> val command = item.split(' ') if (command.isCd()) { fileSystem.cd(command.component3()) } else if (command.hasSize()) { fileSystem.pwd.path.split('/').fold(fileSystem.pwd) { dir, _ -> fileSystem.sizes[dir] = fileSystem.sizes.getOrElse(dir) { 0 } + command.getSize() dir.back() } } fileSystem } fun FileSystem.part1() = this.sizes.values.filter { it <= 100000 }.sum() fun FileSystem.part2() = this.sizes.values.filter { 70000000 - (this.sizes.getValue(root) - it) >= 30000000 }.min() check(testInput.fileSystem().part1() == 95437) check(testInput.fileSystem().part2() == 24933642) println(input.fileSystem().part1()) println(input.fileSystem().part2()) }
0
Kotlin
0
0
e794ab7e0d50f22d250c65b20e13d9b5aeba23e2
1,624
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinSubsequence.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Collections import java.util.PriorityQueue fun interface MinSubsequenceStrategy { operator fun invoke(arr: IntArray): List<Int> } /** * Counting sort since the values are in [1, 100] * O(n) time * O(n) space */ class MinSubsequenceCountingSort : MinSubsequenceStrategy { override operator fun invoke(arr: IntArray): List<Int> { val count = IntArray(ARR_SIZE) var totalSum = 0 for (current in arr) { totalSum += current count[current]++ } val currentSubsequence = mutableListOf<Int>() var currSum = 0 var i = count.size - 1 while (i >= 0) { while (count[i] > 0) { currentSubsequence.add(i) currSum += i count[i]-- if (currSum > totalSum - currSum) { i = -1 break } } --i } return currentSubsequence } companion object { private const val ARR_SIZE = 101 } } class MinSubsequencePriorityQueue : MinSubsequenceStrategy { override operator fun invoke(arr: IntArray): List<Int> { return if (arr.isEmpty()) return listOf() else arr.solve() } private fun IntArray.solve(): List<Int> { val res = mutableListOf<Int>() val pq = PriorityQueue<Int>(Collections.reverseOrder()) var subSum = 0 var totalSum = 0 for (num in this) { pq.offer(num) totalSum += num } while (subSum <= totalSum / 2) { res.add(pq.peek()) subSum += pq.poll() } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,339
kotlab
Apache License 2.0
app/src/main/java/com/alqoview/data/source/LeetCode_1-5.kt
alonsd
581,167,011
false
{"Kotlin": 64432}
package com.alqoview.data.source import com.alqoview.model.AlgorithmicProblem val leetcode1 = AlgorithmicProblem( problemId = 1, questionNumber = 1, title = "Two Sum", problemDescription = "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\n" + "\n" + "You may assume that each input would have exactly one solution, and you may not use the same element twice.\n" + "\n" + "You can return the answer in any order.", solution = AlgorithmicProblem.Solution( solutionCode = "fun twoSum(numbers: IntArray, target: Int): IntArray? { \n" + " val map = hashMapOf<Int, Int>() \n" + " numbers.forEachIndexed { index, value -> \n" + " val complement = target - value \n" + " if (map.containsKey(complement)) \n" + " return intArrayOf(map[complement]!!, index) \n" + " map[value] = index \n" + " } \n" + " return null \n" + " }", explanation = AlgorithmicProblem.Solution.Explanation( bestApproach = "One-pass Hash Table", explanationDescription = "We can iterate through the array while inserting at each iteration the value(of the current iteration) to the index of the current iteration." + "At each iteration, before we are inserting elements into the hash table, we also look back to check if current element's complement already exists in the hash table." + "If it exists, we have found a solution and return the indices immediately. ", coreConcepts = listOf( AlgorithmicProblem.Solution.Explanation.CoreConcept( "Compliment", "Compliment, from the word 'completion' is the number that we" + " are missing in each iteration in order to find the desired target number." ) ), timeComplexity = "O(n).\nWe traverse the list containing n elements only once. Each lookup in the table costs only O(1) time.", spaceComplexity = "O(n).\nThe extra space required depends on the number of items stored in the hash table, which stores at most n elements." ) ), examples = listOf( AlgorithmicProblem.Example( input = "nums = [2,7,11,15], target = 9", output = "[0,1]", explanation = "Because nums[0] + nums[1] == 9, we return [0, 1]." ), AlgorithmicProblem.Example( input = "nums = [2,7,11,15], target = 9", output = "[0,1]" ), AlgorithmicProblem.Example( input = "nums = [3,3], target = 6", output = "[0,1]" ), ), source = AlgorithmicProblem.Source.LEETCODE, difficulty = AlgorithmicProblem.Difficulty.EASY ) val leetcode2 = AlgorithmicProblem( problemId = 2, questionNumber = 2, title = "Add Two Numbers", problemDescription = "You are given two non-empty linked lists representing two non-negative integers." + " The digits are stored in reverse order, and each of their nodes contains a single digit." + " Add the two numbers and return the sum as a linked list. \n" + "\n" + "You may assume the two numbers do not contain any leading zero, except the number 0 itself.", solution = AlgorithmicProblem.Solution( solutionCode = "class ListNode(var `val`: Int) { \n" + " var next: ListNode? = null \n" + "} \n\n" + "fun addTwoNumbers(list1: ListNode?, list2: ListNode?): ListNode? { \n" + " var l1 = list1 \n" + " var l2 = list2 \n" + " val head = ListNode(0) \n" + " var current = head \n" + " var carry = 0 \n" + " while (l1 != null || l2 != null || carry != 0) { \n" + " val x = l1?.`val` ?: 0 \n" + " val y = l2?.`val` ?: 0 \n" + " val sum = carry + x + y \n" + " carry = sum / 10 \n" + " current.next = ListNode(sum % 10) \n" + " current = current.next!! \n" + " if (l1 != null) { \n" + " l1 = l1.next \n" + " } \n" + " if (l2 != null) { \n" + " l2 = l2.next \n" + " } \n" + " } \n" + " return head.next \n" + "}", explanation = AlgorithmicProblem.Solution.Explanation( bestApproach = "Elementary Math", coreConcepts = listOf( AlgorithmicProblem.Solution.Explanation.CoreConcept( "Least Significant Digit", "When combining 2 numbers, we start from right to left of each number. Each time, we all the most right digit of the first number to the " + "most right number of the second number. For each iteration of doing that, we are combining digits that are considered the " + "least significant ones, because their numbers effect the least compared to their left digits which will come next.\n" + "For example: 24 + 73 = 97. We are starting by adding 4 and 3 which are the least significant digits, then we continue to add 2 and 7. " + "Things will get complicated when a least significant digits sums at each iteration will pass 10, making us need to use a carry." ), AlgorithmicProblem.Solution.Explanation.CoreConcept( "Carry", "What happens in the previous concept when we need to sum the following numbers - 27 + 78 = 105 ? This is where we need to use a carry." + "Carry is the remainder of a calculation for each iteration, therefore it can only be 0 or 1. Why? " + "because the maximum calculation we do for each least significant digit is 9+9 which is 18, or we can get a result that is less than 10, which means our carry is 0." ), AlgorithmicProblem.Solution.Explanation.CoreConcept( "Head/Tail Swapping", "When building a new LinkedList 'head' that will represents our result in an iterative way, we need to update heads 'next' value each iteration." + " In order to achieve such behavior, we create a new tail node called 'current' that will initially take the same pointer of 'head' but will be the one responsible " + "for assigning new values to it's 'next' value instead of 'head' variable, allowing us to return 'head' at the end of the algorithm with all of the 'next' values that " + "we have calculated." ), ), explanationDescription = "Just like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits, which is the heads of l1 and l2." + " Since each digit is in the range of 0 to 9, summing two digits may \"overflow\" as we explained in the first core concept." + " For example 5 + 7 = 12 - in this case, we set the current digit to 2 and bring over the carry with a value of 1 to the next iteration.", timeComplexity = "O(max(m,n))\nAssume that m and n represents the length of l1 and l2 respectively, the algorithm above iterates at most max(m,n) times.", spaceComplexity = "O(max(m,n)).\nThe length of the new list is at most max(m,n)+1." ) ), examples = listOf( AlgorithmicProblem.Example( input = "l1 = [2,4,3], l2 = [5,6,4]", output = "[7,0,8]", explanation = "342 + 465 = 807." ), AlgorithmicProblem.Example( input = "l1 = [0], l2 = [0]", output = "[0]" ), AlgorithmicProblem.Example( input = "l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]", output = "[8,9,9,9,0,0,0,1]" ), ), source = AlgorithmicProblem.Source.LEETCODE, difficulty = AlgorithmicProblem.Difficulty.MEDIUM ) val leetcode3 = AlgorithmicProblem( problemId = 3, questionNumber = 3, title = "Longest Substring Without Repeating Characters", problemDescription = "Given a string s, find the length of the longest \n" + "substring\n" + " without repeating characters. A substring is a contiguous non-empty sequence of characters within a string.", solution = AlgorithmicProblem.Solution( solutionCode = "fun lengthOfLongestSubstring(string: String): Int {\n" + " val charToWindowRightSideMap = hashMapOf<Char, Int>()\n" + " var result = 0\n" + " //Window starts from 0,1 because window represents the length of our result\n" + " var slidingWindowLeftSide = 0\n" + " var slidingWindowRightSide = 1\n" + " string.forEach { char ->\n" + " if (charToWindowRightSideMap.containsKey(char)) {\n" + " // Since we are iterating and constantly updating the left window side, the\n" + " // correct answer could be either one of the index of the current char already\n" + " // visited or the current position of the sliding window left side.\n" + " slidingWindowLeftSide = max(charToWindowRightSideMap[char]!!, slidingWindowLeftSide)\n" + " }\n" + " val currentWindow = slidingWindowRightSide - slidingWindowLeftSide\n" + " // Same as before - iterating while updating. The current window is not guaranteed to be\n" + " // bigger than the last result saved\n" + " result = max(result, currentWindow)\n" + " charToWindowRightSideMap[char] = slidingWindowRightSide\n" + " slidingWindowRightSide++\n" + " }\n" + " return result\n" + " }", explanation = AlgorithmicProblem.Solution.Explanation( bestApproach = "Optimized Sliding Window", coreConcepts = listOf( AlgorithmicProblem.Solution.Explanation.CoreConcept( "Substring", "A substring is a contiguous non-empty sequence of characters within a string.\n" + "For example, given a string \"fast car\" the word \"fast\" is a substring. Note that for this specific " + "problem, we are looking for a substring without repeating characters, therefore the result for the string \"abcabcab\" " + "for this problem will be 3 - \"abc\"." ), AlgorithmicProblem.Solution.Explanation.CoreConcept( "Iterating and changing values via max() function", "We are using the max() function 2 times in this solution. The concept is to update the needed value firstly by" + " a new value than it's initial 0, and from there going on we are not sure that the new value that we got will be bigger than " + "what we already recorded." ), AlgorithmicProblem.Solution.Explanation.CoreConcept( "Sliding Window", "Sliding window is a method used to solve array or lists related problems. Iterating from left to right, we " + "\"open\" the window to the right side and \"close\" the window to the left side when needed, giving us the solution we need." ), ), explanationDescription = "Since we are looking for a substring without repeating characters, we can iterate through the string and " + "record a map of char : position. Each time we see a char that we have already recorded in our map, we update 2 values:\n" + "1 - The window's left side as the max between the current window left side value and the index of the same char\n" + "2 - The problem's result to be the max value between the current result and the current window, which is the right - left", timeComplexity = "O(n)\n We iterate through the entire string and in the worst case fill the map with all of the chars.", spaceComplexity = "O(min(n,m))\n We iterate through the entire string, filling the map entirely in the worst case - meaning" + "a complexity of O(n). We also need to consider the charset/alphabet we are using, meaning another complexity of" + "O(m). Therefor, we chose the minimum between n and m." ) ), examples = listOf( AlgorithmicProblem.Example( input = "s = \"abcabcbb\"", output = "3", explanation = "The answer is \"abc\", with the length of 3." ), AlgorithmicProblem.Example( input = "s = \"bbbbb\"", output = "1", explanation = "The answer is \"b\", with the length of 1." ), AlgorithmicProblem.Example( input = "s = \"pwwkew\"", output = "3", explanation = "The answer is \"wke\", with the length of 3.\n" + "Notice that the answer must be a substring, \"pwke\" is a subsequence and not a substring." ), ), source = AlgorithmicProblem.Source.LEETCODE, difficulty = AlgorithmicProblem.Difficulty.MEDIUM ) val leetcode4 = AlgorithmicProblem( problemId = 4, questionNumber = 4, title = "Median of Two Sorted Arrays", problemDescription = "Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays." + "The overall run time complexity should be O(log (m+n)).", solution = AlgorithmicProblem.Solution( solutionCode = "", explanation = AlgorithmicProblem.Solution.Explanation( bestApproach = "", coreConcepts = listOf( AlgorithmicProblem.Solution.Explanation.CoreConcept( "", "" ), ), explanationDescription = "", spaceComplexity = "", timeComplexity = "" ) ), examples = listOf( AlgorithmicProblem.Example( input = "nums1 = [1,3], nums2 = [2]", output = "2.00000", explanation = "merged array = [1,2,3] and median is 2." ), AlgorithmicProblem.Example( input = "nums1 = [1,2], nums2 = [3,4]", output = "2.50000", explanation = "merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. " ), ), source = AlgorithmicProblem.Source.LEETCODE, difficulty = AlgorithmicProblem.Difficulty.HARD )
0
Kotlin
0
0
c43f3f20c169fff1511391452b3a7a21f1913276
15,633
AlqoView
Apache License 2.0
codeforces/deltix2021summer/f.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.deltix2021summer fun main() { readLn() val strengths = readInts().map { it.toModular() } val n = strengths.size val probWin = Array(n) { i -> Array(n) { j -> strengths[i] / (strengths[i] + strengths[j]) } } val masks = 1 shl n val pScc = Array(masks) { 1.toModular() } var ans = 0.toModular() for (mask in 1 until masks) { if (mask.countOneBits() == 1) continue var top = (mask - 1) and mask var rest = 1L while (top > 0) { var thisTop = pScc[top] for (i in 0 until n) { if (!top.hasBit(i)) continue for (j in 0 until n) { if (top.hasBit(j) || !mask.hasBit(j)) continue thisTop *= probWin[i][j] } } if (mask == masks - 1) ans += top.countOneBits() * thisTop rest -= thisTop.x top = (top - 1) and mask } pScc[mask] = rest.toModular() } println(ans + n * pScc.last()) } private fun Int.toModular() = Modular(this)//toDouble() private fun Long.toModular() = Modular(this) private class Modular { companion object { const val M = 1_000_000_007 } val x: Int @Suppress("ConvertSecondaryConstructorToPrimary") constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } } @Suppress("ConvertSecondaryConstructorToPrimary") constructor(value: Long) { x = (value % M).toInt().let { if (it < 0) it + M else it } } operator fun plus(that: Modular) = Modular((x + that.x) % M) operator fun minus(that: Modular) = Modular((x + M - that.x) % M) operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular() private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt()) operator fun div(that: Modular) = times(that.modInverse()) override fun toString() = x.toString() } private operator fun Int.plus(that: Modular) = Modular(this) + that private operator fun Int.minus(that: Modular) = Modular(this) - that private operator fun Int.times(that: Modular) = Modular(this) * that private operator fun Int.div(that: Modular) = Modular(this) / that private fun Int.bit(index: Int) = shr(index) and 1 private fun Int.hasBit(index: Int) = bit(index) != 0 private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,238
competitions
The Unlicense
src/Day09.kt
a2xchip
573,197,744
false
{"Kotlin": 37206}
import kotlin.math.abs import kotlin.math.sign class RopeAction(val direction: Direction, val stepsCount: Int) { companion object { fun fromString(s: String): RopeAction { val (d, c) = s.split(" ") return RopeAction(Direction.valueOf(d), c.toInt()) } } } enum class Direction() { R, L, U, D } class RopeLog { private val headLog = mutableListOf<Pair<Int, Int>>() private val tailLog = mutableListOf<Pair<Int, Int>>() fun tailUniquePositionsCount(): Int { return tailLog.toSet().size } fun recordHead(head: Head) { headLog.add(head.x to head.y) } fun recordTail(tail: Tail) { tailLog.add(tail.x to tail.y) } } open class Knot(var x: Int, var y: Int) { fun move(direction: Direction) { when (direction) { Direction.U -> y += 1 Direction.D -> y -= 1 Direction.R -> x += 1 Direction.L -> x -= 1 } } fun move(position: Pair<Int, Int>) { x = position.first y = position.second } } class Head(x: Int, y: Int) : Knot(x, y) {} class Tail(x: Int, y: Int) : Knot(x, y) { fun followHead(head: Head) { if (listOf(abs(head.x - x), abs(head.y - y)).max() < 2) return // distance is 1 or less if (head.x == x) y += (head.y - y).sign // follow vertically else if (head.y == y) x += (head.x - x).sign // follow horizontally else { // diagonal adjustment x += (head.x - x).sign y += (head.y - y).sign } } } class KnotInteraction { private val head: Head = Head(0, 0) private val tail: Tail = Tail(0, 0) private val ropeLog: RopeLog = RopeLog() init { ropeLog.recordHead(head) ropeLog.recordTail(tail) } fun moveHead(action: RopeAction) { head.move(action.direction) ropeLog.recordHead(head) tail.followHead(head) ropeLog.recordTail(tail) } fun moveHead(position: Pair<Int, Int>) { head.move(position) ropeLog.recordHead(head) tail.followHead(head) ropeLog.recordTail(tail) } fun countTailsUniquePositions(): Int { return ropeLog.tailUniquePositionsCount() } fun tailPosition(): Pair<Int, Int> { return tail.x to tail.y } } fun main() { fun part1(input: List<String>): Int { val knotInteraction = KnotInteraction() for (m in input) { val action = RopeAction.fromString(m) repeat(action.stepsCount) { knotInteraction.moveHead(action) } } return knotInteraction.countTailsUniquePositions() } fun part2(input: List<String>): Int { val numberOfKnots = 9 val knotInteractions = List(numberOfKnots) { KnotInteraction() } for (m in input) { val action = RopeAction.fromString(m) repeat(action.stepsCount) { for ((i, interaction) in knotInteractions.withIndex()) { if (i == 0) { interaction.moveHead(action) } else { val position = knotInteractions[i - 1].tailPosition() interaction.moveHead(position) } } } } return knotInteractions.last().countTailsUniquePositions() } val input = readInput("Day09") println("Part 1 - ${part1(input)}") println("Part 2 - ${part2(input)}") check(part1(input) == 6339) check(part2(input) == 2541) }
0
Kotlin
0
2
19a97260db00f9e0c87cd06af515cb872d92f50b
3,609
kotlin-advent-of-code-22
Apache License 2.0
src/main/kotlin/io/array/MinimumWindowSubstring.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.array import io.utils.runTests // https://leetcode.com/problems/minimum-window-substring/ class MinimumWindowSubstring { fun execute(input: String, chars: String): String { if (chars.isEmpty() || input.isEmpty() || chars.length > input.length) return "" val charsSet = chars.fold(mutableMapOf<Char, Int>()) { acc, value -> acc.apply { this[value] = this.getOrDefault(value, 0) + 1 } } val info = input.fold(mutableMapOf<Char, Int>()) { acc, value -> acc.apply { if (charsSet.containsKey(value)) this[value] = this.getOrDefault(value, 0) + 1 } } if (!info.keys.containsAll(charsSet.keys) || charsSet.any { (key, value) -> value > info.getValue(key) }) return "" var start = 0 var end = 1 val content = mutableMapOf(input[start] to mutableSetOf(start)) var result = input while (end <= input.length && start <= (input.length - chars.length)) { if (content.keys.containsAll(charsSet.keys) && charsSet.all { (key, value) -> content.getValue(key).size >= value }) { if (result.length > end - start) result = input.substring(start until end) val key = input[start] val listOfIndices = content.getValue(key) listOfIndices.remove(start) if (listOfIndices.isEmpty()) content.remove(key) start++ while (start < input.length && !charsSet.contains(input[start])) { start++ } } else { if (end < input.length) { val key = input[end] if (charsSet.contains(key)) content.getOrPut(key) { mutableSetOf() }.add(end) } end++ } } return result } } fun main() { runTests(listOf( Triple("ADOBECODEBANC", "ABC", "BANC"), Triple("a", "aa", ""), Triple("ab", "b", "b"), Triple("aa", "aa", "aa"), Triple("babb", "baba", "") )) { (input, chars, value) -> value to MinimumWindowSubstring().execute(input, chars) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,943
coding
MIT License
src/main/kotlin/Day03.kt
ripla
573,901,460
false
{"Kotlin": 19599}
object Day3 { private val characterRanges = CharRange('a', 'z') + CharRange('A', 'Z') private fun characterPriority(char: Char): Int = characterRanges.indexOf(char) + 1 fun part1(input: List<String>): Int { return input.map { Pair(it.take(it.length / 2), it.takeLast(it.length / 2)) } .map { it.first.toSet().intersect((it.second.toSet())) } .map { it.first() } .sumOf { characterPriority(it) } } fun part2(input: List<String>): Int { return input.chunked(3) .map { group -> group.map { it.toSet() } } .map { group -> group.reduce{ left, right -> left.intersect(right)} } .map { it.first() } .sumOf { characterPriority(it) } } }
0
Kotlin
0
0
e5e6c0bc7a9c6eaee1a69abca051601ccd0257c8
757
advent-of-code-2022-kotlin
Apache License 2.0
src/Day14.kt
JIghtuse
572,807,913
false
{"Kotlin": 46764}
package day14 import readText data class Position(val x: Int, val y: Int) val SandSource = Position(500, 0) fun String.toPosition(): Position { val parts = this.split(",") return Position(parts[0].toInt(), parts[1].toInt()) } fun String.toPositionList() = this .split(" -> ") .map(String::toPosition) .toList() fun toLinePositions(a: Position, b: Position): Set<Position> { return when { a.x == b.x -> { val yRange = (minOf(a.y, b.y)..maxOf(a.y, b.y)) yRange .map { Position(a.x, it) } .toSet() } a.y == b.y -> { val xRange = (minOf(a.x, b.x)..maxOf(a.x, b.x)) xRange .map { Position(it, a.y) } .toSet() } else -> setOf() } } fun toLinesPositions(positions: List<List<Position>>): MutableSet<Position> { return positions.flatMap { it.windowed(2) .flatMap { (start, end) -> toLinePositions(start, end) } .toSet() }.toMutableSet() } fun display( xs: Pair<Int, Int>, ys: Pair<Int, Int>, walls: Set<Position>, sand: Set<Position>) { for (y in ys.first .. ys.second) { for (x in xs.first .. xs.second) { val p = Position(x, y) when { sand.contains(p) -> print("o") p == SandSource -> print("+") walls.contains(p) -> print("#") else -> print(".") } } println() } } fun simulateSand(walls: Set<Position>, hasFloor: Boolean): Int { val sand = mutableSetOf<Position>() val xMin = walls.minBy { it.x }.x val xMax = walls.maxBy { it.x }.x val yMax = walls.maxBy { it.y }.y val abyssLine = yMax + 1 fun display() = display(xMin to xMax, 0 to yMax + 3, walls, sand) fun isFinalPosition(p: Position) = hasFloor && p == SandSource || p.y == abyssLine fun busy(p: Position) = sand.contains(p) || walls.contains(p) fun nextPosition(grain: Position) = when { !busy(grain.copy(y = grain.y + 1)) -> { grain.copy(y = grain.y + 1) } !busy(Position(grain.x - 1, grain.y + 1)) -> { Position(grain.x - 1, grain.y + 1) } !busy(Position(grain.x + 1, grain.y + 1)) -> { Position(grain.x + 1, grain.y + 1) } else -> grain } fun dropGrain(): Position? { var grain = SandSource var nextPos = nextPosition(grain) while (nextPos != grain) { grain = nextPos nextPos = nextPosition(grain) if (isFinalPosition(grain)) return null } return grain } // display() while (true) { val grain = dropGrain() ?: break sand.add(grain) if (isFinalPosition(grain)) break // display() } display() return sand.size } fun main() { fun part1(inputText: String): Int { val wallSections = inputText .split("\n") .map(String::toPositionList) val walls = toLinesPositions(wallSections) return simulateSand(walls, hasFloor = false) } fun part2(inputText: String): Int { val wallSections = inputText .split("\n") .map(String::toPositionList) val walls = toLinesPositions(wallSections) val floorLevel = walls.maxBy { it.y }.y + 2 val floor = ((SandSource.x - (floorLevel + 1))..(SandSource.x + floorLevel + 1)) .map { Position(it, floorLevel) } walls.addAll(floor) return simulateSand(walls, hasFloor = true) } // test if implementation meets criteria from the description, like: val testInput = readText("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) println("tests done") val input = readText("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8f33c74e14f30d476267ab3b046b5788a91c642b
4,007
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/ru/itmo/ctlab/gmwcs/solver/TreeSolver.kt
ctlab
290,164,889
false
{"Java": 250115, "Kotlin": 21543}
package ru.itmo.ctlab.gmwcs.solver import ru.itmo.ctlab.gmwcs.solver.preprocessing.preprocess import ru.itmo.ctlab.virgo.gmwcs.graph.Edge import ru.itmo.ctlab.virgo.gmwcs.graph.Elem import ru.itmo.ctlab.virgo.gmwcs.graph.Graph import ru.itmo.ctlab.virgo.gmwcs.graph.Node import ru.itmo.ctlab.virgo.gmwcs.solver.MSTSolver import java.util.* import java.util.stream.IntStream import kotlin.math.exp /** * Created by <NAME> on 18/01/2018. */ data class D(val root: Node?, val best: Set<Elem>, val withRoot: Set<Elem>, val bestD: Double, val withRootD: Double ) fun solve(g: Graph, root: Node, parent: Node?): D { val children = if (parent == null) g.neighborListOf(root) else g.neighborListOf(root).minus(parent) val withRoot = mutableSetOf<Elem>(root) val solutions = mutableSetOf<D>() var withRootD = root.weight val emptySol = D(root, emptySet(), withRoot.toSet(), 0.0, root.weight) if (children.isEmpty()) { return if (root.weight < 0) emptySol else D(root, withRoot, withRoot, root.weight, root.weight) } for (e in g.edgesOf(root)) { val opp = g.opposite(root, e) if (parent != null && opp == parent) continue assert(opp != root) val sub = solve(g, opp, root) if (sub.bestD > 0) { solutions.add(sub) } if (sub.withRootD + e.weight >= 0) { withRoot.addAll(sub.withRoot) withRoot.add(e) withRootD += sub.withRootD + e.weight } } solutions.add(emptySol) val bestSub = solutions.maxBy { it.bestD }!! val bestSol = if (bestSub.bestD > withRootD) bestSub.best else withRoot return D(root, bestSol, withRoot, maxOf(bestSub.bestD, withRootD), withRootD) } fun mergeEdges(g: Graph) { for (u in g.vertexSet()) { for (v in g.neighborListOf(u)) { if (u == v) { g.removeEdge(g.getEdge(u, v)) continue } if (u.num > v.num) continue val e = g.getAllEdges(u, v).maxBy { it.weight } g.getAllEdges(u, v).forEach { g.removeEdge(it) } g.addEdge(u, v, e) } } } fun mapWeight(w: Double): Double { return 1.0 / (1 + exp(w)) } fun solveComponents(g: Graph): Set<Elem> { preprocess(g) val components = g.connectedSets() val gs = components.map { g.subgraph(it) } return gs.map { solve(it) } .maxBy { it.sumByDouble { it.weight } } .orEmpty() } fun solve(g: Graph): Set<Elem> { val random = Random(1337) mergeEdges(g) val weights = g.edgeSet().associateWith { val u: Node = g.getEdgeSource(it) val v: Node = g.getEdgeTarget(it) val weight = u.weight / g.edgesOf(u).size + +v.weight / g.edgesOf(v).size + it.weight mapWeight(weight) } val r = g.vertexSet().toList()[random.nextInt(g.vertexSet().size)] val mst = MSTSolver(g, weights, r) mst.solve() val res = solve(g.subgraph(g.vertexSet(), mst.edges.toSet()), r, null) return g.subgraph( res.best.filterIsInstanceTo(mutableSetOf()), res.best.filterIsInstanceTo(mutableSetOf())).elemSet() } fun main(args: Array<String>) { val g = Graph() val nodes = arrayOf(Node(1, -5.0), Node(2, -1.0), Node(3, -2.0)) val edges = arrayOf(Edge(1, 1.0), Edge(2, -1.0)) nodes.forEach { g.addVertex(it) } edges.forEach { g.addEdge(nodes[it.num - 1], nodes[it.num], it) } print(solve(g, nodes[1], null).withRootD) }
0
Java
0
3
f561bdce02f43b7c58cd5334896c2aec513bda15
3,616
virgo-solver
Apache License 2.0
src/main/kotlin/com/hopkins/aoc/day10/main.kt
edenrox
726,934,488
false
{"Kotlin": 88215}
package com.hopkins.aoc.day10 import java.io.File const val debug = false const val part = 2 /** Advent of Code 2023: Day 10 */ fun main() { val inputFile = File("input/input10.txt") val lines: List<String> = inputFile.readLines() var start = Point(-1, -1) val pieceTypeLookup = PieceType.values().associateBy { it.symbol } val pieces: List<Piece> = lines.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == 'S') { start = Point(x, y) null } else { val type = pieceTypeLookup.get(c) if (type == null) { null } else { Piece(type, Point(x, y)) } } }} if (debug) { println("Start: $start") println("Num Pieces: ${pieces.size}") } val pieceMap = pieces.associateBy { it.position } if (debug) { println("Map:") val origin = Point(start.x - 2, start.y - 2) for (y in 0 until 10) { for (x in 0 until 10) { val pos = origin.add(x, y) if (start == pos) { print("S") } else if (pieceMap.containsKey(pos)) { print(pieceMap.getValue(pos).type.symbol) } else { print(".") } } println() } } for (startPieceType in PieceType.values()) { //val startPieceType = PieceType.DOWN_RIGHT val distance = walkMap(Piece(startPieceType, start), pieceMap) if (part == 1 && distance != -1) { println("Start Piece: $startPieceType, distance=$distance") // 6725 } } } fun printDistanceMap(origin: Point, width: Int, map: Map<Point, Int>) { println("Distance Map: ") for (y in 0 until width) { for (x in 0 until width) { val point = origin.add(x, y) print(map[point] ?: ".") } println() } } fun walkMap(start: Piece, pieceMap: Map<Point, Piece>): Int { val distanceMap: MutableMap<Point, Int> = mutableMapOf(start.position to 0) var distance = 0 var currentPieces: List<Piece> = listOf(start, start) var nextPoints: List<Point> while (true) { if (debug) { println("Iteration $distance") printDistanceMap(Point(0, 0), 6, distanceMap) } nextPoints = if (distance == 0) { start.type.positions.map { start.position.add(it) } } else { // Next point is not where we just came from (distance - 1) currentPieces.flatMap { piece -> piece.getConnected().filter { distanceMap[it] != distance - 1 }} } require(nextPoints.size == 2) if (debug) { println("Next points: $nextPoints") } val nextPieces = nextPoints.mapNotNull { pieceMap[it] } distance++ if (nextPieces.size < 2) { println("Ground at $nextPoints, distance=$distance") return -1 } for (i in 0..1) { val nextPiece = nextPieces[i]!! val connected = nextPiece.getConnected() if (!connected.contains(currentPieces[i].position)) { println("Unconnected piece at ${nextPiece.position}") return -1 } } nextPieces.map { distanceMap[it.position] = distance } if (nextPieces[0] == nextPieces[1]) { if (part == 2) { val max = 140 val insideSet = mutableSetOf<Point>() for (y in 0..max) { for (x in 0..max) { val point = Point(x, y) if (distanceMap[point] == null) { var lastCornerPiece: Piece? = null var crossings = 0 for (dx in x..max) { val testPoint = Point(dx, y) if (distanceMap[testPoint] != null) { val piece = pieceMap[testPoint] ?: start when (piece.type) { PieceType.VERTICAL -> crossings++ PieceType.HORIZONTAL -> 0 // noop else -> if (lastCornerPiece == null) { lastCornerPiece = piece } else { if (lastCornerPiece.type.getVertical() != piece.type.getVertical()) { crossings++ } lastCornerPiece = null } } } } if (crossings % 2 == 1) { if (debug) { println("Point: $point crossings: $crossings") } insideSet.add(point) } } } } println("Inside: ${insideSet.size}") } return distance } currentPieces = nextPieces.filterNotNull() } } enum class PieceType(val symbol: Char, val positions: List<Point>) { VERTICAL('|', listOf(Point(0, -1), Point(0, 1))), HORIZONTAL('-', listOf(Point(-1, 0), Point(1, 0))), DOWN_RIGHT('F', listOf(Point(0, 1), Point(1, 0))), DOWN_LEFT('7', listOf(Point(0, 1), Point(-1, 0))), UP_RIGHT('L', listOf(Point(0, -1), Point(1, 0))), UP_LEFT('J', listOf(Point(0, -1), Point(-1, 0))); fun getVertical(): Boolean { require(this != VERTICAL && this != HORIZONTAL) return this == UP_RIGHT || this == UP_LEFT } } data class Piece(val type: PieceType, val position: Point) { fun getConnected(): List<Point> = type.positions.map { position.add(it) } } data class Point(val x: Int, val y: Int) { fun add(dx: Int, dy: Int) = Point(x + dx, y + dy) fun add(other: Point): Point = add(other.x, other.y) }
0
Kotlin
0
0
45dce3d76bf3bf140d7336c4767e74971e827c35
6,509
aoc2023
MIT License
day15/src/main/kotlin/Battle.kt
rstockbridge
159,586,951
false
null
class Battle(private val rawMap: List<String>) { data class Result(val rounds: Int, val remainingHp: Int) data class ShortestPathResult(val start: GridPoint2d, val distance: Int) data class ClosestLocationResult(val closestLocation: GridPoint2d, val firstStep: GridPoint2d) companion object { fun findFoes(warrior: Warrior, candidates: List<Warrior>): List<Warrior> { return candidates.filter { other -> other.isFoeOf(warrior) } } fun findAttackLocations( foeLocations: List<GridPoint2d>, liveWarriorLocations: List<GridPoint2d>, cavern: List<String> ): List<GridPoint2d> { return foeLocations .flatMap { it.adjacentPoints() } .toSet() .filterNot { location -> cavern[location.y][location.x] == '█' } .filterNot { location -> location in liveWarriorLocations } .sortedWith(compareBy(GridPoint2d::y).thenBy(GridPoint2d::x)) } fun findFoeToAttack(warriorLocation: GridPoint2d, foes: List<Warrior>): Warrior? { val adjacentLocations = warriorLocation.adjacentPoints() return foes .filter { foe -> foe.location in adjacentLocations } .sortedWith(compareBy(Warrior::hp).thenBy { it.location.y }.thenBy { it.location.x }) .firstOrNull() } fun shortestPathBetween( start: GridPoint2d, end: GridPoint2d, liveWarriorLocations: List<GridPoint2d>, cavern: List<String> ): ShortestPathResult? { val firstNode = Node(start) val targetNode = Node(end) val nodesToEvaluate = mutableSetOf<Node>().apply { this += firstNode } val evaluatedNodes = mutableSetOf<Node>() val cameFrom = mutableMapOf<Node, Node>() val gScores = mutableMapOf(firstNode to 0) fun heuristic(current: Node): Int { return current.inputPoint.l1DistanceTo(targetNode.inputPoint) } val fScores = mutableMapOf(firstNode to heuristic(firstNode)) while (nodesToEvaluate.isNotEmpty()) { val currentNode = nodesToEvaluate.minBy { fScores[it]!! }!! if (currentNode == targetNode) { val distance = fScores[currentNode]!! return ShortestPathResult(start, distance) } nodesToEvaluate.remove(currentNode) evaluatedNodes.add(currentNode) for ((node, distance) in currentNode.validNeighborCosts(liveWarriorLocations, cavern)) { if (node in evaluatedNodes) continue val tentativeGScore = gScores[currentNode]!! + distance if (node !in nodesToEvaluate) { nodesToEvaluate += node } else if (tentativeGScore >= gScores[node]!!) { continue } cameFrom[node] = currentNode gScores[node] = tentativeGScore fScores[node] = gScores[node]!! + heuristic(node) } } return null } fun shortestPathBetweenWarriorAndTarget( warriorLocation: GridPoint2d, targetLocation: GridPoint2d, liveWarriorLocations: List<GridPoint2d>, cavern: List<String> ): ShortestPathResult? { var shortestPathResult: ShortestPathResult? = null val validNeighbors = warriorLocation .adjacentPoints() .filterNot { neighbor -> cavern[neighbor.y][neighbor.x] == '█' } .filterNot { neighbor -> neighbor in liveWarriorLocations } if (validNeighbors.isNotEmpty()) { val neighborShortestPathResults: List<ShortestPathResult?> = validNeighbors .mapNotNull { adjacentPoint -> shortestPathBetween(adjacentPoint, targetLocation, liveWarriorLocations, cavern) } if (neighborShortestPathResults.isNotEmpty()) { shortestPathResult = neighborShortestPathResults .sortedWith(compareBy({ it!!.distance }, { it!!.start.y }, { it!!.start.x })) .firstOrNull() } } return shortestPathResult } fun closestLocationResult( warrior: Warrior, locations: Collection<GridPoint2d>, liveWarriorLocations: List<GridPoint2d>, cavern: List<String> ): ClosestLocationResult? { val storedShortestPathResults = mutableMapOf<GridPoint2d, ShortestPathResult>() locations.forEach { location -> val shortestPathResult = shortestPathBetweenWarriorAndTarget( warrior.location, location, liveWarriorLocations, cavern) if (shortestPathResult != null) { storedShortestPathResults[location] = shortestPathResult } } if (storedShortestPathResults.isEmpty()) { return null } val sortedLocations = storedShortestPathResults .keys .sortedWith(compareBy({ storedShortestPathResults[it]!!.distance }, { it.y }, { it.x })) return ClosestLocationResult(sortedLocations.first(), storedShortestPathResults[sortedLocations.first()]!!.start) } } private val cavern: List<String> by lazy { return@lazy rawMap.map { row -> row.replace("[GE]".toRegex(), ".") } } private fun getInitialWarriors(): List<Warrior> { var id = 0 return rawMap .withIndex() .flatMap { (y, row) -> //@formatter:off row.withIndex() .mapNotNull { (x, char) -> Warrior.from(char, id = id++, location = GridPoint2d(x, y)) } } } fun executePartI(debug: Boolean = false): Result { var round = 0 var roundWarriors = getInitialWarriors() if (debug) { println("Initially:") print(roundWarriors, cavern) } while (true) { if (debug) println("After ${round + 1} rounds:") roundWarriors = roundWarriors .filter(Warrior::isAlive) .sortedWith(compareBy<Warrior> { it.location.y }.thenBy { it.location.x }) for (warrior in roundWarriors) { val turnWarriors = roundWarriors.filter(Warrior::isAlive) if (warrior !in turnWarriors) continue val foes = findFoes(warrior, candidates = turnWarriors - warrior) if (foes.isEmpty()) { return Result(round, remainingHp = turnWarriors.sumBy(Warrior::hp)) } val foeToAttack = findFoeToAttack(warrior.location, foes) if (foeToAttack != null) { warrior.attack(foeToAttack) continue } val attackLocations = findAttackLocations( foeLocations = foes.map(Warrior::location), liveWarriorLocations = turnWarriors.map(Warrior::location), cavern = cavern ) val closestLocation = closestLocationResult( warrior, locations = attackLocations, liveWarriorLocations = turnWarriors.map(Warrior::location), cavern = cavern) ?: continue warrior.location = closestLocation.firstStep findFoeToAttack(warrior.location, foes)?.let { newFoeToAttack -> warrior.attack(newFoeToAttack) } } if (debug) print(roundWarriors, cavern) round++ } } fun executePartII(debug: Boolean = false): Result { var elfAttackPower = 4 attackPowerLoop@ while (true) { var round = 0 var roundWarriors = getInitialWarriors() roundWarriors.forEach { warrior -> if (warrior is Warrior.Elf) { warrior.attackPower = elfAttackPower } } if (debug) { println("attack power: $elfAttackPower") println("Initially:") print(roundWarriors, cavern) } while (true) { if (debug) println("After ${round + 1} rounds:") roundWarriors = roundWarriors .filter(Warrior::isAlive) .sortedWith(compareBy<Warrior> { it.location.y }.thenBy { it.location.x }) for (warrior in roundWarriors) { val turnWarriors = roundWarriors.filter(Warrior::isAlive) if (warrior !in turnWarriors) continue val foes = findFoes(warrior, candidates = turnWarriors - warrior) if (foes.isEmpty()) { return Result(round, remainingHp = turnWarriors.sumBy(Warrior::hp)) } val foeToAttack = findFoeToAttack(warrior.location, foes) if (foeToAttack != null) { warrior.attack(foeToAttack) if (foeToAttack is Warrior.Elf && !foeToAttack.isAlive) { elfAttackPower++ continue@attackPowerLoop } continue } val attackLocations = findAttackLocations( foeLocations = foes.map(Warrior::location), liveWarriorLocations = turnWarriors.map(Warrior::location), cavern = cavern ) val closestLocation = closestLocationResult( warrior, locations = attackLocations, liveWarriorLocations = turnWarriors.map(Warrior::location), cavern = cavern) ?: continue warrior.location = closestLocation.firstStep findFoeToAttack(warrior.location, foes)?.let { newFoeToAttack -> warrior.attack(newFoeToAttack) } } if (debug) print(roundWarriors, cavern) round++ } } } private fun print(liveWarriors: List<Warrior>, cavern: List<String>) { for (y in 0 until cavern.size) { var hitPointsString = " " for (x in 0 until cavern[0].length) { var printedWarrior = false liveWarriors.forEach { warrior -> if (warrior.location == GridPoint2d(x, y)) { print(warrior) printedWarrior = true hitPointsString += "$warrior(${warrior.hp}), " } } if (!printedWarrior) { print(cavern[y][x]) } } print(hitPointsString) println() } println() } data class Node(val inputPoint: GridPoint2d) { override fun equals(other: Any?): Boolean { if (other !is Node) return false if (other.inputPoint != inputPoint) return false return true } override fun hashCode(): Int { return 0 } fun validNeighborCosts(liveWarriorLocations: List<GridPoint2d>, cavern: List<String>): Map<Node, Int> { val result = mutableMapOf<Node, Int>() val validNeighbors = inputPoint .adjacentPoints() .filterNot { neighbor -> cavern[neighbor.y][neighbor.x] == '█' } .filterNot { neighbor -> neighbor in liveWarriorLocations } validNeighbors.forEach { neighbor -> result[Node(neighbor)] = 1 } return result } override fun toString(): String { return "(${inputPoint.x}, ${inputPoint.y})" } } }
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
13,027
AdventOfCode2018
MIT License
src/Day01.kt
toninau
729,811,683
false
{"Kotlin": 8423}
fun main() { val spelledToDigit = mapOf( "one" to '1', "two" to '2', "three" to '3', "four" to '4', "five" to '5', "six" to '6', "seven" to '7', "eight" to '8', "nine" to '9', ) fun String.firstDigit(): Char { var string = "" for (char in this) { string += char for (digit in spelledToDigit) { if (string.contains(digit.value) || string.contains(digit.key)) { return digit.value } } } throw Exception("no digit found in string $string") } fun String.lastDigit(): Char { var string = "" for (char in this.reversed()) { string = "$char$string" for (digit in spelledToDigit) { if (string.contains(digit.value) || string.contains(digit.key)) { return digit.value } } } throw Exception("no digit found in string $string") } fun part1(input: List<String>): Int { return input.sumOf { line -> val firstDigit = line.first { it.isDigit() } val lastDigit = line.last { it.isDigit() } "${firstDigit}${lastDigit}".toInt() } } fun part2(input: List<String>): Int { return input.sumOf { line -> "${line.firstDigit()}${line.lastDigit()}".toInt() } } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b3ce2cf2b4184beb2342dd62233b54351646722b
1,541
advent-of-code-2023
Apache License 2.0
src/main/kotlin/g0101_0200/s0153_find_minimum_in_rotated_sorted_array/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0101_0200.s0153_find_minimum_in_rotated_sorted_array // #Medium #Top_100_Liked_Questions #Array #Binary_Search #Algorithm_II_Day_2_Binary_Search // #Binary_Search_I_Day_12 #Udemy_Binary_Search #Big_O_Time_O(log_N)_Space_O(log_N) // #2022_09_06_Time_262_ms_(60.96%)_Space_35.4_MB_(86.45%) class Solution { private fun findMinUtil(nums: IntArray, l: Int, r: Int): Int { if (l == r) { return nums[l] } val mid = (l + r) / 2 if (mid == l && nums[mid] < nums[r]) { return nums[l] } if (mid - 1 >= 0 && nums[mid - 1] > nums[mid]) { return nums[mid] } if (nums[mid] < nums[l]) { return findMinUtil(nums, l, mid - 1) } else if (nums[mid] > nums[r]) { return findMinUtil(nums, mid + 1, r) } return findMinUtil(nums, l, mid - 1) } fun findMin(nums: IntArray): Int { val l = 0 val r = nums.size - 1 return findMinUtil(nums, l, r) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,023
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/nibado/projects/advent/y2021/Day13.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2021 import com.nibado.projects.advent.* object Day13 : Day { private val input = resourceStrings(2021, 13).let { (first, second) -> first.split("\n").map(Point::parse) to second.split("\n") } private val instructions = input.second.map { it.matchGroups("fold along ([x|y])=([0-9]+)".toRegex()).let { (_, a, b) -> a to b.toInt() } } private fun solve(onlyFirst: Boolean): Set<Point> { val grid = input.first.toMutableSet() instructions.take(if(onlyFirst) 1 else instructions.size).forEach { (xy, value) -> val reflect = if(xy == "x") grid.filter { it.x > value } .map { it to Point(value - (it.x - value), it.y) } else grid.filter { it.y > value } .map { it to Point(it.x, value - (it.y - value)) } grid -= reflect.map { it.first }.toSet() grid += reflect.map { it.second } } return grid } private fun gridToString(grid: Set<Point>) : String { val width = grid.maxX()!! + 1 val points = (0 until grid.maxY()!! + 1).flatMap { y -> (0 until width).map { x -> Point(x, y) } } return points.map { if(grid.contains(it)) '#' else '.' } .chunked(width).joinToString("\n") { it.joinToString("") } } override fun part1(): Int = solve(true).size override fun part2() = gridToString(solve(false)) }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,437
adventofcode
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions61.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import com.qiaoyuang.algorithm.round0.PriorityQueue import kotlin.math.min fun test61() { printlnResult(intArrayOf(1, 5, 13, 21), intArrayOf(2, 4, 9, 15), 3) } /** * Questions 61: Given two increased IntArrays, find the k integers pair that sum is minimum */ private fun minPairs(a: IntArray, b: IntArray, k: Int): List<Pair<Int, Int>> { val queue = PriorityQueue<IntArrayComparable>() for (i in 0 ..< min(k, a.size)) { queue.enqueue(IntArrayComparable(intArrayOf(i, 0), a, b)) } var count = k return buildList { while (count-- > 0 && !queue.isEmpty) { val (i, j) = queue.dequeue().intArray add(a[i] to b[j]) if (j < b.lastIndex) queue.enqueue(IntArrayComparable(intArrayOf(i, j + 1), a, b)) } } } class IntArrayComparable( val intArray: IntArray, val a: IntArray, val b: IntArray, ) : Comparable<IntArrayComparable> { override fun compareTo(other: IntArrayComparable): Int = a[other.intArray.first()] + b[other.intArray.last()] - a[intArray.first()] - b[intArray.last()] } private fun printlnResult(a: IntArray, b: IntArray, k: Int) = println("The minimum number pairs are: ${minPairs(a, b, k)}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,276
Algorithm
Apache License 2.0
src/main/kotlin/Day05.kt
SimonMarquis
570,868,366
false
{"Kotlin": 50263}
import java.lang.System.lineSeparator class Day05(input: String) { private val stacks: List<ArrayDeque<Char>> private val moves: List<Move> init { val (crates, procedure) = input.split(lineSeparator() * 2) stacks = crates.lines().asReversed().drop(1).foldInPlace( initial = List(size = crates.lines().last().split(" ").last().toInt()) { ArrayDeque() } ) { line: String -> line.chunked(4).forEachIndexed { index, crate /*[?]*/ -> get(index).addFirst(crate[1].takeIf(Char::isLetter) ?: return@forEachIndexed) } } moves = procedure.lines().map { it.split(" ") .mapNotNull(String::toIntOrNull) .let { (amount, start, end) -> Move(amount, start.dec(), end.dec()) } } } fun part1(): String = moves.foldInPlace(stacks) { (amount, start, end) -> repeat(amount) { val pick = get(start).removeFirst() get(end).addFirst(pick) } }.top() fun part2() = moves.foldInPlace(stacks) { (amount, start, end) -> val picks = get(start).takeAndRemove(amount) get(end).addAll(0, picks) }.top() data class Move(val amount: Int, val start: Int, val end: Int) private fun List<ArrayDeque<Char>>.top() = joinToString("") { it.first().toString() } private fun ArrayDeque<Char>.takeAndRemove(n: Int) = take(n).also { repeat(n) { removeFirst() } } }
0
Kotlin
0
0
a2129cc558c610dfe338594d9f05df6501dff5e6
1,475
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/alturkovic/robots/txt/RuleMatchingStrategy.kt
alturkovic
636,725,117
false
null
package com.github.alturkovic.robots.txt interface RuleMatchingStrategy { fun matches(rule: Rule, path: String): Boolean } object WildcardRuleMatchingStrategy : RuleMatchingStrategy { override fun matches(rule: Rule, path: String): Boolean { return matches(rule.pattern, path) } // taken from Google // https://github.com/google/robotstxt-java/blob/master/src/main/java/com/google/search/robotstxt/RobotsLongestMatchStrategy.java private fun matches(pattern: String, path: String): Boolean { // "Prefixes" array stores "path" prefixes that match specific prefix of "pattern". // Prefixes of "pattern" are iterated over in ascending order in the loop below. // Each prefix is represented by its end index (exclusive), the array stores them in ascending order. val prefixes = IntArray(path.length + 1) prefixes[0] = 0 var prefixesCount = 1 for (i in pattern.indices) { val ch = pattern[i] // '$' in the end of pattern indicates its termination. if (ch == '$' && i + 1 == pattern.length) return prefixes[prefixesCount - 1] == path.length // In case of '*' occurrence all path prefixes starting from the shortest one may be matched. if (ch == '*') { prefixesCount = path.length - prefixes[0] + 1 for (j in 1 until prefixesCount) prefixes[j] = prefixes[j - 1] + 1 } else { // Iterate over each previous prefix and try to extend by one character. var newPrefixesCount = 0 for (j in 0 until prefixesCount) { if (prefixes[j] < path.length && path[prefixes[j]] == ch) { prefixes[newPrefixesCount++] = prefixes[j] + 1 } } if (newPrefixesCount == 0) return false prefixesCount = newPrefixesCount } } return true } }
0
Kotlin
0
1
a70632010f74029f5e6414aaaa464975ba51b481
1,994
robots-txt
MIT License
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day24/BugPlanet.kt
jrhenderson1988
289,786,400
false
{"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37}
package com.github.jrhenderson1988.adventofcode2019.day24 import com.github.jrhenderson1988.adventofcode2019.common.Direction import com.github.jrhenderson1988.adventofcode2019.common.powerOf class BugPlanet(private val grid: Map<Pair<Int, Int>, Char>) { private val maxY = grid.keys.map { it.second }.max()!! private val maxX = grid.keys.map { it.first }.max()!! private val center = Pair(maxX / 2, maxY / 2) fun biodiversityRatingOfFirstRepetition(): Long { var g = grid.toMap() val biodiversityRatings = mutableSetOf(biodiversityRating(g)) while (true) { g = mutateGrid(g) val bdr = biodiversityRating(g) if (biodiversityRatings.contains(bdr)) { return bdr } else { biodiversityRatings.add(bdr) } } } fun calculateTotalBugsInRecursiveUniverseAfterMinutes(minutes: Int) = countBugs((0 until minutes).fold(mapOf(0 to grid)) { u, _ -> mutateUniverse(u) }) private fun mutateUniverse(u: Map<Int, Map<Pair<Int, Int>, Char>>): Map<Int, Map<Pair<Int, Int>, Char>> { val minLevel = u.keys.min()!! val maxLevel = u.keys.max()!! val mutated = mutableMapOf<Int, Map<Pair<Int, Int>, Char>>() (minLevel - 1..maxLevel + 1).forEach { level -> val grid = mutableMapOf<Pair<Int, Int>, Char>() (0..maxY).forEach { y -> (0..maxX).forEach { x -> grid[Pair(x, y)] = mutateTile( tile(x, y, level, u), neighboursOf(x, y, level).map { tile(it.first, it.second, it.third, u) } ) } } mutated[level] = grid } return mutated } fun neighboursOf(x: Int, y: Int, level: Int): Set<Triple<Int, Int, Int>> { val neighbours = Direction.neighboursOf(Pair(x, y)) .filter { it.first in 0..maxX && it.second in 0..maxY } .map { Triple(it.first, it.second, level) } .toMutableSet() val mid = Triple(center.first, center.second, level) if (neighbours.contains(mid)) { neighbours.remove(mid) neighbours.addAll(when { x == mid.first && y == mid.second - 1 -> (0..maxX).map { _x -> Triple(_x, 0, level + 1) } x == mid.first && y == mid.second + 1 -> (0..maxX).map { _x -> Triple(_x, maxY, level + 1) } x == mid.first - 1 && y == mid.second -> (0..maxY).map { _y -> Triple(0, _y, level + 1) } x == mid.first + 1 && y == mid.second -> (0..maxY).map { _y -> Triple(maxX, _y, level + 1) } else -> emptyList() }) } mapOf( Triple(-1, 0, -1) to (x == 0), Triple(0, -1, -1) to (y == 0), Triple(1, 0, -1) to (x == maxX), Triple(0, 1, -1) to (y == maxY) ).filter { it.value }.forEach { (delta, _) -> neighbours.add(Triple(mid.first + delta.first, mid.second + delta.second, mid.third + delta.third)) } return neighbours } private fun tile(x: Int, y: Int, level: Int, u: Map<Int, Map<Pair<Int, Int>, Char>>) = if (Pair(x, y) == center) { '.' } else { (u[level] ?: mapOf())[Pair(x, y)] ?: '.' } private fun countBugs(u: Map<Int, Map<Pair<Int, Int>, Char>>) = u.map { level -> level.value.filter { grid -> grid.key != center && grid.value == '#' }.size }.sum() private fun mutateGrid(g: Map<Pair<Int, Int>, Char>) = g.map { it.key to mutateTile(it.value, Direction.neighboursOf(it.key).map { pt -> g[pt] ?: '.' }) }.toMap() private fun mutateTile(ch: Char, neighbours: List<Char>) = when (ch) { '#' -> if (neighbours.filter { tile -> tile == '#' }.size == 1) '#' else '.' '.' -> if (neighbours.filter { tile -> tile == '#' }.size in setOf(1, 2)) '#' else '.' else -> error("Invalid tile '$ch'.") } private fun biodiversityRating(g: Map<Pair<Int, Int>, Char>) = (0..maxY).map { y -> (0..maxX).map { x -> g[Pair(x, y)] } } .flatten() .mapIndexed { i, ch -> if (ch == '#') powerOf(2L, i.toLong()) else 0 } .sum() companion object { fun parse(input: String): BugPlanet { val grid = mutableMapOf<Pair<Int, Int>, Char>() input.lines().forEachIndexed { y, line -> line.forEachIndexed { x, ch -> grid[Pair(x, y)] = ch } } return BugPlanet(grid) } } }
0
Kotlin
0
0
7b56f99deccc3790c6c15a6fe98a57892bff9e51
4,677
advent-of-code
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/ReorderList.kt
faniabdullah
382,893,751
false
null
//You are given the head of a singly linked-list. The list can be represented //as: // // //L0 → L1 → … → Ln - 1 → Ln // // // Reorder the list to be on the following form: // // //L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … // // // You may not modify the values in the list's nodes. Only nodes themselves may //be changed. // // // Example 1: // // //Input: head = [1,2,3,4] //Output: [1,4,2,3] // // // Example 2: // // //Input: head = [1,2,3,4,5] //Output: [1,5,2,4,3] // // // // Constraints: // // // The number of nodes in the list is in the range [1, 5 * 10⁴]. // 1 <= Node.val <= 1000 // // Related Topics Linked List Two Pointers Stack Recursion 👍 4025 👎 170 package leetcodeProblem.leetcode.editor.en import leetcode_study_badge.data_structure.ListNode class ReorderList { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { tailrec fun midPoint(slow: ListNode?, fast: ListNode? = slow): ListNode? = if (fast?.next == null) slow else midPoint(slow?.next, fast.next?.next) tailrec fun reverse(node: ListNode?, reversed: ListNode? = null): ListNode? = if (node == null) reversed else reverse(node.next.also { node.next = reversed }, node) tailrec fun merge(left: ListNode?, right: ListNode?) { if(left != right) { val nextRight = right?.next.also { right?.next = left?.next } val nextLeft = left?.next.also { left?.next = right } if (right != null) merge(nextLeft, nextRight) } } fun reorderList(head: ListNode?) = merge(head, reverse(midPoint(head))) } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,107
dsa-kotlin
MIT License
src/Day05.kt
yeung66
574,904,673
false
{"Kotlin": 8143}
fun main() { fun initStacks() = listOf(ArrayDeque(), ArrayDeque("DBJV".toList()), ArrayDeque("PVBWRDF".toList()), ArrayDeque("RGFLDCWQ".toList()), ArrayDeque("WJPMLNDB".toList()), ArrayDeque("HNBPCSQ".toList()), ArrayDeque("RDBSNG".toList()), ArrayDeque("ZBPMQFSH".toList()), ArrayDeque("WLF".toList()), ArrayDeque("SVFMR".toList())) fun parse(input: String): List<List<Int>> { return input.lines().map { line -> val parts = line.split(" ") listOf(parts[1], parts[3], parts[5]).map { it.toInt() } }.toList() } fun part1(input: List<List<Int>>): String { val stacks = initStacks() input.forEach {op -> (1..op[0]).forEach { stacks[op[2]].addLast(stacks[op[1]].removeLast()) } } return stacks.filter { it.isNotEmpty() }.map { it.last() }.joinToString(separator = "") } fun part2(input: List<List<Int>>): String { val stacks = initStacks() input.forEach {op -> val temp = mutableListOf<Char>() (1..op[0]).forEach { temp.add(stacks[op[1]].removeLast()) } stacks[op[2]].addAll(temp.reversed()) } return stacks.filter { it.isNotEmpty() }.map { it.last() }.joinToString(separator = "") } val input = parse(readInput("5")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
554217f83e81021229759bccc8b616a6b270902c
1,423
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/io/dmitrijs/aoc2022/Day21.kt
lakiboy
578,268,213
false
{"Kotlin": 76651}
package io.dmitrijs.aoc2022 import io.dmitrijs.aoc2022.Day21.Operation.DIV import io.dmitrijs.aoc2022.Day21.Operation.MINUS import io.dmitrijs.aoc2022.Day21.Operation.PLUS import io.dmitrijs.aoc2022.Day21.Operation.TIMES class Day21(input: List<String>) { private val env = buildEnv(input) fun puzzle1(): Long { val (vars, _) = resolveEnvUntil(env) { resolvedVars -> ROOT !in resolvedVars } return vars.getValue(ROOT) } fun puzzle2(): Long { val modifiedEnv = env.removeVar(HUMAN) val (vars, expr) = resolveEnvUntil(modifiedEnv) { resolvedVars -> resolvedVars.isNotEmpty() } val rootExpr = expr.getValue(ROOT) var (lookup, result) = if (rootExpr.operand1 in vars) { rootExpr.operand2 to vars.getValue(rootExpr.operand1) } else { rootExpr.operand1 to vars.getValue(rootExpr.operand2) } // Solve all expressions backwards until HUMAN is found. do { expr.getValue(lookup).solve(vars, result).apply { lookup = first result = second } } while (lookup != HUMAN) return result } private fun resolveEnvUntil(env: Environment, predicate: (Map<String, Long>) -> Boolean): Environment { val vars = env.vars.toMutableMap() val expr = env.expr.toMutableMap() do { val resolvedVars = expr .filterValues { it.operand1 in vars && it.operand2 in vars } .mapValues { (_, op) -> op.eval(vars) } .also { vars.putAll(it) } // Cleanup expressions. resolvedVars.keys.forEach { name -> expr.remove(name) } } while (predicate(resolvedVars)) return Environment(vars, expr) } private fun buildEnv(commands: List<String>): Environment { val vars = hashMapOf<String, Long>() val expr = hashMapOf<String, Expr>() commands.forEach { command -> val (name, op) = command.split(": ") op.toLongOrNull() ?.let { vars[name] = it } ?: run { expr[name] = op.toExpr() } } return Environment(vars, expr) } private data class Environment(val vars: Map<String, Long>, val expr: Map<String, Expr>) { fun removeVar(name: String) = copy( vars = vars.toMutableMap().apply { remove(name) }, expr = expr, ) } private fun String.toExpr(): Expr { val (operand1, op, operand2) = split(" ") return Expr(operand1, operand2, Operation.of(op)) } private data class Expr( val operand1: String, val operand2: String, private val op: Operation, ) { fun eval(vars: Map<String, Long>) = when (op) { PLUS -> vars.getValue(operand1) + vars.getValue(operand2) MINUS -> vars.getValue(operand1) - vars.getValue(operand2) TIMES -> vars.getValue(operand1) * vars.getValue(operand2) DIV -> vars.getValue(operand1) / vars.getValue(operand2) } fun solve(vars: Map<String, Long>, result: Long): Pair<String, Long> { val known = when { operand1 in vars -> vars.getValue(operand1) operand2 in vars -> vars.getValue(operand2) else -> error("Can not solve expression: $this.") } return if (operand1 in vars) { operand2 to when (op) { PLUS -> result - known MINUS -> result * -1 + known TIMES -> result / known DIV -> known / result } } else { operand1 to when (op) { PLUS -> result - known MINUS -> result + known TIMES -> result / known DIV -> result * known } } } } private enum class Operation { PLUS, MINUS, TIMES, DIV; companion object { fun of(op: String) = when (op) { "+" -> PLUS "-" -> MINUS "*" -> TIMES "/" -> DIV else -> error("Unsupported operation: $op.") } } } companion object { private const val ROOT = "root" private const val HUMAN = "humn" } }
0
Kotlin
0
1
bfce0f4cb924834d44b3aae14686d1c834621456
4,465
advent-of-code-2022-kotlin
Apache License 2.0
src/Java/LeetcodeSolutions/src/main/java/leetcode/solutions/concrete/kotlin/Solution_807_Max_Increase_to_Keep_City_Skyline.kt
v43d3rm4k4r
515,553,024
false
{"Kotlin": 40113, "Java": 25728}
package leetcode.solutions.concrete.kotlin import leetcode.solutions.* import leetcode.solutions.ProblemDifficulty.* import leetcode.solutions.validation.SolutionValidator.* import leetcode.solutions.annotations.ProblemInputData import leetcode.solutions.annotations.ProblemSolution /** * __Problem:__ There is a city composed of `n x n` blocks, where each block contains a single building * shaped like a vertical square prism. You are given a __0-indexed__ `n x n` integer matrix `grid` * where `grid[r][c]` represents the __height__ of the building located in the block at row `r` and column `c`. * * A city's __skyline__ is the outer contour formed by all the building when viewing * the side of the city from a distance. The __skyline__ from each cardinal direction * north, east, south, and west may be different. * * We are allowed to increase the height of __any number of buildings by any amount__ (the amount can be * different per building). The height of a `0`-height building can also be increased. However, * increasing the height of a building should __not__ affect the city's __skyline__ from any cardinal direction. * * Return _the __maximum total sum__ that the height of the buildings can be increased by __without__ changing * the city's __skyline__ from any cardinal direction_. * * __Constraints:__ * - `n == grid.length` * - `n == grid[r].length` * - `2 <= n <= 50` * - `0 <= grid[r][c] <= 100` * * __Solution:__ Each of the "buildings" can be increased by a value equal to the minimum value of the * two maximum values on each axis. To find these values for each cell, you first need to do two actions: * 1. Find the maximum values for each row and column * 2. Find the minimum of them for each cell, and subtract the initial height of the cell from it * * __Time:__ O(N^2) * * __Space:__ O(N) * * @author <NAME> */ class Solution_807_Max_Increase_to_Keep_City_Skyline : LeetcodeSolution(MEDIUM) { @ProblemSolution(timeComplexity = "O(N^2)", spaceComplexity = "O(N)") fun maxIncreaseKeepingSkyline(grid: Array<IntArray>): Int { val rowMaxes = Array(grid.size) { 0 } val colMaxes = Array(grid.size) { 0 } var result = 0 for (row in grid.indices) { for (col in grid.indices) { rowMaxes[row] = grid[row][col].coerceAtLeast(rowMaxes[row]) colMaxes[col] = grid[row][col].coerceAtLeast(colMaxes[col]) } } for (row in grid.indices) { for (col in grid.indices) { result += rowMaxes[row].coerceAtMost(colMaxes[col]) - grid[row][col] } } return result } @ProblemInputData override fun run() { val input = arrayOf( intArrayOf(3, 0, 8, 4), intArrayOf(2, 4, 5, 7), intArrayOf(9, 2, 6, 3), intArrayOf(0, 3, 1, 0), ) ASSERT_EQ(35, maxIncreaseKeepingSkyline(input)) val input1 = arrayOf( intArrayOf(0, 0, 0), intArrayOf(0, 0, 0), intArrayOf(0, 0, 0), ) ASSERT_EQ(0, maxIncreaseKeepingSkyline(input1)) } }
0
Kotlin
0
1
c5a7e389c943c85a90594315ff99e4aef87bff65
3,178
LeetcodeSolutions
Apache License 2.0
src/Day01.kt
monsterbrain
572,819,542
false
{"Kotlin": 42040}
fun main() { fun part1MostCalories(input: List<String>): Int { var currentElfIndex = 0 var maxElfCalories = 0 var elfCalorieCount = 0 input.forEach { if (it.isEmpty()) { if (elfCalorieCount > maxElfCalories) { // println("elfCalorieCount $elfCalorieCount") maxElfCalories = elfCalorieCount } // iterate next with calorie count reset currentElfIndex += 1 elfCalorieCount = 0 } else { elfCalorieCount += it.toInt() } } return maxElfCalories } fun part2SumOfTop3CalorieElves(input: List<String>): Int { val calorieSumList = ArrayList<Int>() var elfCalorieCount = 0 input.forEach { if (it.isEmpty()) { calorieSumList.add(elfCalorieCount) elfCalorieCount = 0 } else { elfCalorieCount += it.toInt() } } println(calorieSumList) return calorieSumList.sortedDescending().take(3).sum() } val input = readInput("Day01") println(part1MostCalories(input)) println(part2SumOfTop3CalorieElves(input)) }
0
Kotlin
0
0
3a1e8615453dd54ca7c4312417afaa45379ecf6b
1,273
advent-of-code-kotlin-2022-Solutions
Apache License 2.0
neuro_router_core/src/main/java/com/victor/neuro/router/core/Nucleus.kt
Victor2018
538,359,659
false
{"Kotlin": 69455}
package com.victor.neuro.router.core import com.victor.neuro.router.core.data.Chosen import java.util.* /* * ----------------------------------------------------------------- * Copyright (C) 2018-2028, by Victor, All rights reserved. * ----------------------------------------------------------------- * File: Nucleus * Author: Victor * Date: 2022/9/19 12:19 * Description: * ----------------------------------------------------------------- */ sealed class Nucleus(val id: String) : Comparable<Nucleus> { // pattern to expression, sort descending from the longest pattern private val schemePatterns: List<Pair<Regex, String>> by lazy { schemes.map { val lowerCase = it.toLowerCase(Locale.ROOT) // make it lowercase lowerCase.toPattern() to lowerCase }.sortedByDescending { it.first }.map { Regex(it.first) to it.second } } // pattern to expression, sort descending from the longest pattern private val hostPatterns: List<Pair<Regex, String>> by lazy { hosts.map { val lowerCase = it.toLowerCase(Locale.ROOT) // make it lowercase lowerCase.toPattern() to lowerCase }.sortedByDescending { it.first }.map { Regex(it.first) to it.second } } // only return boolen internal fun isMatch( scheme: String?, host: String?, port: Int ): Boolean { val hostMatch = hostPatterns.isEmpty() || hostPatterns.any { it.first.matches(host ?: "") } if (!hostMatch) return false val schemeMatch = schemePatterns.isEmpty() || schemePatterns.any { it.first.matches(scheme ?: "") } if (!schemeMatch) return false val portMatch = ports.isEmpty() || ports.contains(port) if (!portMatch) return false // all passed, means all is match return true } // return matched nucleus internal fun nominate( scheme: String?, host: String?, port: Int ): Chosen? { val chosenHost = if (hostPatterns.isEmpty()) null else hostPatterns.find { it.first.matches(host ?: "") }?.second val chosenScheme = if (schemePatterns.isEmpty()) null else schemePatterns.find { it.first.matches(scheme ?: "") }?.second val chosenPort = if (ports.isEmpty()) null else port // all passed, means all is match return Chosen(this, chosenScheme, chosenHost, chosenPort) } internal val memberCount: Int by lazy { val schemeSize = if (schemes.isEmpty()) 1 else schemes.size val hostSize = if (hosts.isEmpty()) 1 else hosts.size val portSize = if (ports.isEmpty()) 1 else ports.size schemeSize * hostSize * portSize } /** * Priorities: * #1 lowest priority number * #2 highest member count * #3 alphabetically by id */ final override fun compareTo(other: Nucleus): Int { val priority1 = priority val priority2 = other.priority return if (priority1 == priority2) { val memberCount1 = memberCount val memberCount2 = other.memberCount if (memberCount1 == memberCount2) { val id1 = id val id2 = other.id id1.compareTo(id2) } else memberCount2 - memberCount1 } else priority1 - priority2 } // empty means may be included or not open val schemes: List<String> = emptyList() // empty means may be included or not open val hosts: List<String> = emptyList() // empty means may be included or not open val ports: List<Int> = emptyList() open val priority: Int = DEFAULT_PRIORITY final override fun toString(): String = id final override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is Nucleus) return false return id == other.id } final override fun hashCode(): Int = 31 * id.hashCode() companion object { const val DEFAULT_PRIORITY = 100 } }
0
Kotlin
0
0
76abc8151196ca7f4ab0665b0a314a6c98007b5c
4,128
NRouter
Apache License 2.0
day08/Kotlin/day08.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* fun print_day_8() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 8" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Seven Segment Search -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_8() Day8().part_1() Day8().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day8 { private val lines = File("../Input/day8.txt").readLines().map { it.split("|")[0].trim() to it.split("|")[1].trim() } fun part_1() { val uniqueLengths = listOf(2, 3, 4, 7) var totalUnique = 0 for((_, output) in lines) { output.split(" ").forEach { if(it.length in uniqueLengths) totalUnique++ } } println("Puzzle 1: " + totalUnique) } fun part_2() { var total = 0 for((input, output) in lines) { val displays = mutableMapOf<String, Int>() val inputs = input.split(" ").map{ it.sortChars() } val one = inputs.first { it.length == 2 } val four = inputs.first { it.length == 4 } val seven = inputs.first { it.length == 3 } val eight = inputs.first { it.length == 7 } val nine = inputs.first { it.length == 6 && it.containsAll(four) } displays[one] = 1 displays[four] = 4 displays[seven] = 7 displays[eight] = 8 displays[nine] = 9 displays[inputs.first { it.length == 6 && it.containsAll(seven) && !it.containsAll(four) }] = 0 displays[inputs.first { it.length == 6 && !it.containsAll(one) }] = 6 displays[inputs.first { it.length == 5 && it.containsAll(one) }] = 3 displays[inputs.first { it.length == 5 && !it.containsAll(one) && nine.containsAll(it) }] = 5 displays[inputs.first { it.length == 5 && !it.containsAll(one) && !nine.containsAll(it) }] = 2 total += output.split(" ").fold("") { number, outputVal -> number + displays[outputVal.sortChars()].toString() }.toInt() } println("Puzzle 2: " + total) } private fun String.sortChars() = this.toCharArray().sorted().joinToString("") private fun String.containsAll(chars: String) = this.toList().containsAll(chars.toList()) }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
2,662
AOC2021
Apache License 2.0
kotlin/problems/src/solution/BitProblems.kt
lunabox
86,097,633
false
{"Kotlin": 146671, "Python": 38767, "JavaScript": 19188, "Java": 13966}
package solution import kotlin.math.max class BitProblems { /** * https://leetcode-cn.com/problems/single-number-iii/ */ fun singleNumber(nums: IntArray): IntArray { var mask = 0 nums.forEach { mask = mask.xor(it) } val last = mask.and(-mask) var x = 0 nums.forEach { if (it.and(last) != 0) { x = x.xor(it) } } return intArrayOf(x, mask.xor(x)) } /** * https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits/ */ fun sortByBits(arr: IntArray): IntArray { return arr.sortedWith(Comparator<Int> { o1, o2 -> val b1 = Integer.bitCount(o1) val b2 = Integer.bitCount(o2) if (b1 == b2) { o1 - o2 } else { b1 - b2 } }).toIntArray() } /** * https://leetcode-cn.com/problems/insert-into-bits-lcci/ */ fun insertBits(N: Int, M: Int, i: Int, j: Int): Int { var mask = 1 repeat(j - i) { mask = mask.shl(1).or(0x1) } mask = mask.shl(i).inv() return N.and(mask).or(M.shl(i)) } /** * https://leetcode-cn.com/problems/binary-gap/ */ fun binaryGap(N: Int): Int { val bin = ArrayList<Int>(12) var n = N while (n > 0) { bin.add(n % 2) n /= 2 } var left = -1 var maxDis = 0 bin.forEachIndexed { index, i -> if (i == 1) { if (left != -1) { maxDis = max(maxDis, index - left) } left = index } } return maxDis } }
0
Kotlin
0
0
cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9
1,762
leetcode
Apache License 2.0
src/Day11.kt
BurgundyDev
572,937,542
false
{"Kotlin": 11050}
fun main() { val testInput = readInput("../inputs/Day11_test") val input = readInput("../inputs/Day11") // println(part1(testInput)) // println(part1(input)) println(part2(testInput)) println(part2(input)) } enum class OperationType { ADD, MUL, ADDOLD, MULOLD } class Monkey(var items: MutableList<Long>, val operator: Long, val operation: OperationType, val test: Long, val true_target: Int, val false_target: Int, var monkeyBusiness: Long) { public fun testItems(targets: MutableList<Monkey>) { val iterate = items.listIterator() while(iterate.hasNext()) { var currItem = iterate.next() when(operation) { OperationType.ADD -> currItem += operator OperationType.MUL -> currItem *= operator OperationType.ADDOLD -> currItem += currItem OperationType.MULOLD -> currItem *= currItem } currItem = currItem.floorDiv(3L); if (currItem % test == 0L) { targets[true_target].items.add(currItem) } else { targets[false_target].items.add(currItem) } monkeyBusiness++ } items = mutableListOf() } public fun testItems2(targets: MutableList<Monkey>, modulo: Long) { val iterate = items.listIterator() while(iterate.hasNext()) { var currItem = iterate.next() when(operation) { OperationType.ADD -> currItem += operator OperationType.MUL -> currItem *= operator OperationType.ADDOLD -> currItem += currItem OperationType.MULOLD -> currItem *= currItem } currItem %= modulo if (currItem % test == 0L) { targets[true_target].items.add(currItem) } else { targets[false_target].items.add(currItem) } monkeyBusiness++ } items = mutableListOf() } } private fun part1(input: List<String>): Long { var monkeyList = mutableListOf<Monkey>() val iterate = input.listIterator() for (i in 0..input.size step 7) { iterate.next() val tItems = iterate.next().removePrefix(" Starting items: ").split(", ").map { it.toLong() }.toMutableList() val tOperatorString = iterate.next().removePrefix(" Operation: new = old ").split(" ").toList() var tOperator = 0.toLong() var tOperation = OperationType.ADD if (tOperatorString[1] == "old") { tOperator = 0.toLong() tOperation = if (tOperatorString[0] == "+") { OperationType.ADDOLD } else { OperationType.MULOLD } } else { tOperator = tOperatorString[1].toLong() tOperation = if (tOperatorString[0] == "+") { OperationType.ADD } else { OperationType.MUL } } val tTest = iterate.next().removePrefix(" Test: divisible by ").toLong() val tTrueTarget = iterate.next().removePrefix(" If true: throw to monkey ").toInt() val tFalseTarget = iterate.next().removePrefix(" If false: throw to monkey ").toInt() if (iterate.hasNext()) { iterate.next() } var monkey = Monkey(tItems, tOperator, tOperation, tTest, tTrueTarget, tFalseTarget, 0.toLong()) monkeyList.add(monkey) } for (i in 1..20) { for (monkey in monkeyList) { monkey.testItems(monkeyList) } } var sumMonkeyBusiness = mutableListOf<Long>() for (monkey in monkeyList) { sumMonkeyBusiness.add(monkey.monkeyBusiness) } sumMonkeyBusiness.sort() sumMonkeyBusiness.reverse() return (sumMonkeyBusiness[0] * sumMonkeyBusiness[1]) } private fun part2(input: List<String>): Long { var monkeyList = mutableListOf<Monkey>() val iterate = input.listIterator() for (i in 0..input.size step 7) { iterate.next() val tItems = iterate.next().removePrefix(" Starting items: ").split(", ").map { it.toLong() }.toMutableList() val tOperatorString = iterate.next().removePrefix(" Operation: new = old ").split(" ").toList() var tOperator = 0.toLong() var tOperation = OperationType.ADD if (tOperatorString[1] == "old") { tOperator = 0.toLong() tOperation = if (tOperatorString[0] == "+") { OperationType.ADDOLD } else { OperationType.MULOLD } } else { tOperator = tOperatorString[1].toLong() tOperation = if (tOperatorString[0] == "+") { OperationType.ADD } else { OperationType.MUL } } val tTest = iterate.next().removePrefix(" Test: divisible by ").toLong() val tTrueTarget = iterate.next().removePrefix(" If true: throw to monkey ").toInt() val tFalseTarget = iterate.next().removePrefix(" If false: throw to monkey ").toInt() if (iterate.hasNext()) { iterate.next() } var monkey = Monkey(tItems, tOperator, tOperation, tTest, tTrueTarget, tFalseTarget, 0.toLong()) monkeyList.add(monkey) } var accuracy = 1L for (monkey in monkeyList) { accuracy *= monkey.test } for (i in 1..10000) { for (monkey in monkeyList) { monkey.testItems2(monkeyList, accuracy) } } var sumMonkeyBusiness = mutableListOf<Long>() for (monkey in monkeyList) { sumMonkeyBusiness.add(monkey.monkeyBusiness) } sumMonkeyBusiness.sort() sumMonkeyBusiness.reverse() return (sumMonkeyBusiness[0] * sumMonkeyBusiness[1]) }
0
Kotlin
0
0
dd931604fa35f75599ef778fc3f0f8bc82b2fce0
5,845
aoc2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CloseStrings.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT /** * 1657. Determine if Two Strings Are Close * @see <a href="https://leetcode.com/problems/determine-if-two-strings-are-close/">Source</a> */ fun interface CloseStrings { operator fun invoke(word1: String, word2: String): Boolean } class CloseStringsMap : CloseStrings { override operator fun invoke(word1: String, word2: String): Boolean { if (word1.length != word2.length) { return false } val wf = IntArray(ALPHABET_LETTERS_COUNT) val wf2 = IntArray(ALPHABET_LETTERS_COUNT) for (i in word1.indices) { wf[word1[i] - 'a'] += 1 wf2[word2[i] - 'a'] += 1 } for (i in 0 until ALPHABET_LETTERS_COUNT) { if (wf[i] == 0 && wf2[i] != 0) return false } val map1: HashMap<Int, Int> = HashMap() val map2: HashMap<Int, Int> = HashMap() for (i in 0 until ALPHABET_LETTERS_COUNT) { map1[wf[i]] = map1.getOrDefault(wf[i], 0) + 1 map2[wf2[i]] = map2.getOrDefault(wf2[i], 0) + 1 } return map1 == map2 } } class CloseStringsBitwise : CloseStrings { override operator fun invoke(word1: String, word2: String): Boolean { if (word1.length != word2.length) { return false } val v1 = IntArray(ALPHABET_LETTERS_COUNT) val v2 = IntArray(ALPHABET_LETTERS_COUNT) var k1 = 0 var k2 = 0 for (b in word1.toByteArray()) { val i = b - 'a'.code.toByte() v1[i]++ k1 = k1 or (1 shl i) } for (b in word2.toByteArray()) { val i = b - 'a'.code.toByte() v2[i]++ k2 = k2 or (1 shl i) } // Ensure the same characters are used if (k1 != k2) { return false } // Test that occurrence counts match v1.sort() v2.sort() return v1.contentEquals(v2) } } class CloseStringsSort : CloseStrings { override operator fun invoke(word1: String, word2: String): Boolean { val freq1 = IntArray(ALPHABET_LETTERS_COUNT) val freq2 = IntArray(ALPHABET_LETTERS_COUNT) for (element in word1) { freq1[element - 'a']++ } for (element in word2) { freq2[element - 'a']++ } for (i in 0 until ALPHABET_LETTERS_COUNT) { if (freq1[i] == 0 && freq2[i] != 0 || freq1[i] != 0 && freq2[i] == 0) { return false } } freq1.sort() freq2.sort() for (i in 0 until ALPHABET_LETTERS_COUNT) { if (freq1[i] != freq2[i]) { return false } } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,427
kotlab
Apache License 2.0
src/main/kotlin/day14/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day14 import day14.Direction.* import util.readTestInput import kotlin.math.max private enum class Direction(val dx: Int, val dy: Int) { LEFT( -1, 0), RIGHT( 1, 0), UP( 0, -1), DOWN( 0, 1) } private data class Move(val direction: Direction, val amount: Int = 1) private data class Vector(val start: Coord, val end: Coord) { fun getAllCoords(): List<Coord> { val direction = when { end.x > start.x -> RIGHT end.x < start.x -> LEFT end.y < start.y -> UP else -> DOWN } val coords = mutableListOf(start) do { coords.add(coords.last().move(direction)) } while (coords.last() != end) return coords } } private data class Coord(val x: Int, val y: Int) { fun move(direction: Direction) = Coord(x + direction.dx, y + direction.dy) fun move(move: Move) = Coord(x + move.amount * move.direction.dx, y + move.amount * move.direction.dy) } private typealias Path = List<Coord> private class Cave(rockPaths: List<Path>, private val hasFloor: Boolean = false) { val sandPourCoord = Coord(500,0) var rockCoords = rockPaths .flatMap { path -> path.windowed(2).flatMap {coords -> Vector(coords[0], coords[1]).getAllCoords()} } val sandCoords = mutableListOf<Coord>() var width = rockCoords.maxOf { it.x } + 1 val height = rockCoords.maxOf { it.y } + 1 + (if (hasFloor) 2 else 0) fun isFLoor(coord: Coord) = coord.y == height - 1 fun isBlocked(coord: Coord) = sandCoords.contains(coord) || rockCoords.contains(coord) || coord == sandPourCoord || (hasFloor && isFLoor(coord)) fun findNewSandPos(fromPos: Coord = sandPourCoord): Coord? { for (i in 1 until height - fromPos.y) { val pos = fromPos.move(Move(DOWN, i)) if (isBlocked(pos)) { // when the pos is blocked, we check if we can move down left or right. val newPos = when { !isBlocked(pos.move(LEFT)) -> findNewSandPos(pos.move(LEFT)) !isBlocked(pos.move(RIGHT)) -> findNewSandPos(pos.move(RIGHT)) else -> pos.move(UP) } return if (newPos == sandPourCoord) null else newPos } } // dropping to void return null } fun play() { do { val newSandPos = findNewSandPos() sandCoords.add(newSandPos!!) if (sandCoords.size % 500 == 0) println("Round ${sandCoords.size} dropped to ${sandCoords.last()}") } while (findNewSandPos() != null) } fun drawMap() { val dynamicWidth = if (hasFloor) max(width, sandCoords.maxOf { it.x } + 1) else width for (y in 0 until height) { for (x in 0 until dynamicWidth) { if (x < 450) continue when { sandPourCoord == Coord(x, y) -> print('+') hasFloor && y == height -1 -> print('#') rockCoords.contains(Coord(x, y)) -> print('#') sandCoords.contains(Coord(x, y)) -> print('o') else -> print('.') } } println() } } } private fun part1(rockPaths: List<Path>): Int { val cave = Cave(rockPaths) cave.play() cave.drawMap() return cave.sandCoords.size } private fun part2(rockPaths: List<Path>): Int { val cave = Cave(rockPaths, hasFloor = true) cave.play() cave.drawMap() return cave.sandCoords.size + 1 // add one because the source of sand is full of sand too } private fun parsePath(line: String): Path = line.split(" -> ") .map { it.split(",").let { parts -> Coord(parts[0].toInt(), parts[1].toInt()) } } fun main() { val rockPaths = readTestInput("day14").map { parsePath(it) } println(part1(rockPaths)) println(part2(rockPaths)) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
3,929
advent-of-code-2022
MIT License
src/Day06.kt
3n3a-archive
573,389,832
false
{"Kotlin": 41221, "Shell": 534}
fun Day06() { fun getXUniqueLetters(input: String, uniqueAmount: Int): Int { val inputAsChars = input.toCharArray() val processedChars = mutableListOf<Char>() for ((index, char) in inputAsChars.withIndex()) { processedChars.add(char) if (index >= uniqueAmount) { val lastXLetters = processedChars.takeLast(uniqueAmount) if (lastXLetters.distinct().size == lastXLetters.size) { return index + 1 } } } return -1 } fun part1(input: String): Int { return getXUniqueLetters(input, 4) } fun part2(input: String): Int { return getXUniqueLetters(input, 14) } // test if implementation meets criteria from the description, like: val testInput = readInputToText("Day06_test") check(part1(testInput) == 10) check(part2(testInput) == 29) val input = readInputToText("Day06") println("1: " + (part1(input) == 1034)) println("2: " + (part2(input) == 2472)) }
0
Kotlin
0
0
fd25137d2d2df0aa629e56981f18de52b25a2d28
1,066
aoc_kt
Apache License 2.0
src/main/kotlin/day8.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
fun day8 (lines: List<String>) { val map = parseDesertMap(lines) val steps = countSteps(lines[0], map) println("Day 8 part 1: $steps") val ghostSteps = countGhostSteps(lines[0], map) var lcm = ghostSteps[0] for (i in ghostSteps.indices) { if (i == 0) { continue } lcm = lcm(lcm, ghostSteps[i]) } println("Day 8 part 2: $lcm") println() } fun lcm(number1: Long, number2: Long): Long { val high = number1.coerceAtLeast(number2) val low = number1.coerceAtMost(number2) var lcm = high while (lcm % low != 0L) { lcm += high } return lcm } fun countGhostSteps(order: String, map: Map<String, LeftRightInstruction>): List<Long> { var steps = 0L val currentNodes = map.keys.filter { it.endsWith("A") }.toTypedArray() val stepsList = mutableListOf<Long>() while (true) { for (i in order.indices) { steps++ for (j in currentNodes.indices) { val nextNode = map[currentNodes[j]]!! currentNodes[j] = if (order[i] == 'R') { nextNode.right } else { nextNode.left } if (currentNodes[j].endsWith("Z")) { stepsList.add(steps) } if (stepsList.size == currentNodes.size) { return stepsList } } } } } fun countSteps(order: String, map: Map<String, LeftRightInstruction>): Long { var steps = 0L var currentNode = "AAA" while (currentNode != "ZZZ") { for (i in order.indices) { val nextNode = map[currentNode]!! currentNode = if (order[i] == 'R') { nextNode.right } else { nextNode.left } steps++ } } return steps } fun parseDesertMap(lines: List<String>): Map<String, LeftRightInstruction> { val instructions = mutableMapOf<String, LeftRightInstruction>() for (i in lines.indices) { if (i < 2) { continue } val key = lines[i].split(" = ")[0] val value = lines[i].split(" = ")[1].trim('(').trim(')') val left = value.split(", ")[0] val right = value.split(", ")[1] instructions[key] = LeftRightInstruction(left, right) } return instructions } data class LeftRightInstruction(val left: String, val right: String)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
2,629
advent_of_code_2023
MIT License
src/2021/Day5_2.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File import kotlin.collections.HashMap import kotlin.collections.ArrayList class Point(val x: Int, val y: Int) class Line(val start: Point, val end: Point) { fun extrapolatePoints(): ArrayList<Point> { val extrapolated = ArrayList<Point>() if (start.y == end.y) { if (start.x < end.x) for (x in start.x..end.x) { extrapolated.add(Point(x, start.y)) } else for (x in end.x..start.x) { extrapolated.add(Point(x, start.y)) } } else if (start.x == end.x) { if (start.y < end.y) for (y in start.y..end.y) { extrapolated.add(Point(start.x, y)) } else for (y in end.y..start.y) { extrapolated.add(Point(start.x, y)) } } return extrapolated } } fun String.asPoint(): Point = Point(split(",")[0].toInt(),split(",")[1].toInt()) val lines = ArrayList<Line>() File("input/2021/day5").forEachLine { line -> val (start, end) = line.split(" -> ").map { it.asPoint() } lines.add(Line(start, end)) } val hits = HashMap<String, Int>() lines.forEach { it.extrapolatePoints().forEach { var hitsAtPoint = hits.getOrElse(it.toString()) { 0 } hits.put(it.toString(), ++hitsAtPoint) } } println(hits.filterValues { it > 1 }.size)
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
1,344
adventofcode
MIT License
src/main/kotlin/days/Day9.kt
vovarova
726,012,901
false
{"Kotlin": 48551}
package days import util.DayInput class Day9 : Day("9") { override fun partOne(dayInput: DayInput): Any { val map = dayInput.inputList().map { val findDiffs = findDiff(it.split(" ").map { it.toInt() }) val reversed = findDiffs.reversed() var currentValue = reversed.first().last() for (i in 1..reversed.size - 1) { currentValue = reversed[i].last() + currentValue } currentValue } return map.sum() } override fun partTwo(dayInput: DayInput): Any { val map = dayInput.inputList().map { val findDiffs = findDiff(it.split(" ").map { it.toInt() }) val reversed = findDiffs.reversed() var currentValue = reversed.first().first() for (i in 1..reversed.size - 1) { currentValue = reversed[i].first() - currentValue } currentValue } return map.sum() } fun findDiff(list: List<Int>): List<List<Int>> { val resultDifs = mutableListOf<List<Int>>() var currentList = list while (!currentList.all { it == 0 }) { resultDifs.add(currentList) currentList = currentList.windowed(2).map { twoElements -> twoElements[1] - twoElements[0] } } return resultDifs } } fun main() { Day9().run() }
0
Kotlin
0
0
77df1de2a663def33b6f261c87238c17bbf0c1c3
1,484
adventofcode_2023
Creative Commons Zero v1.0 Universal
y2017/src/main/kotlin/adventofcode/y2017/Day06.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution import adventofcode.util.collections.takeWhileDistinct fun main() = Day06.solve() object Day06 : AdventSolution(2017, 6, "Memory Reallocation") { override fun solvePartOne(input: String) = generateSequence(parse(input), ::redistribute) .takeWhileDistinct() .count() override fun solvePartTwo(input: String): Int { val seen = generateSequence(parse(input), ::redistribute) .takeWhileDistinct() .last() return generateSequence(seen, ::redistribute).drop(1).indexOf(seen) + 1 } private fun redistribute(state: List<Int>): List<Int> { val max = state.maxOrNull()!! val i = state.indexOf(max) val newState = state.map { it }.toMutableList() newState[i] = 0 ((i + 1)..i + max).forEach { newState[it % newState.size]++ } return newState } private fun parse(input: String) = input.split("\t").map(String::toInt) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,045
advent-of-code
MIT License
src/Day04.kt
adamgaafar
572,629,287
false
{"Kotlin": 12429}
import java.util.regex.Pattern fun main(){ fun part1(input: List<String>): Int { var score = 0 for (line in input){ val (first,second) = line.split(",") val (start1,end1) = first.split("-") val (start2,end2) = second.split("-") val assign1low = start1.toInt() val assign1high = end1.toInt() val assign2low = start2.toInt() val assign2high = end2.toInt() if (assign1low <= assign2low && assign1high >= assign2high){ score++ }else if (assign1low >= assign2low && assign1high <= assign2high){ score++ } } return score } fun part2(input: List<String>): Int { var score = 0 var noOverlapCount = 0 var total = 0 for (line in input){ val (first,second) = line.split(",") val (start1,end1) = first.split("-") val (start2,end2) = second.split("-") val assign1low = start1.toInt() val assign1high = end1.toInt() val assign2low = start2.toInt() val assign2high = end2.toInt() if (assign1low <= assign2low && assign1high >= assign2high){ score++ }else if (assign1low >= assign2low && assign1high <= assign2high){ score++ } if(assign1low > assign2high){ noOverlapCount++ }else if(assign2low > assign1high){ noOverlapCount++ } total++ } return total - noOverlapCount } // test if implementation meets criteria from the description, like: /* val testInput = readInput("Day01_test") check(part1(testInput) == 1)*/ val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5c7c9a2e819618b7f87c5d2c7bb6e6ce415ee41e
1,881
AOCK
Apache License 2.0
gcj/y2020/qual/e.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2020.qual private fun solve(possible: String = "POSSIBLE", impossible: String = "IMPOSSIBLE"): String { // for (n in 2..50) { solveDiagonal(n, 0, 0); solveDiagonal(n, 1, 1); solveDiagonal(n, 1, 2) } val (n, trace) = readInts() for (i in 1..n) for (j in 1..n) for (k in 1..n) { if ((i == j) xor (i == k) || (n - 2) * i + j + k != trace) continue val d0 = setOf(i, j).size - 1 val d1 = setOf(i, j, k).size - 1 val a = solveDiagonal(n, d0, d1) ?: continue val switch = IntArray(n) { -1 } switch[0] = i switch[d0] = j switch[d1] = k for (x in a.indices) if (switch[x] == -1) switch[x] = (1..n).first { it !in switch } return possible + "\n" + a.joinToString("\n") { row -> row.joinToString(" ") { switch[it].toString() } } } return impossible } private val memo = mutableMapOf<String, List<IntArray>?>() private fun solveDiagonal(n: Int, d0: Int, d1: Int): List<IntArray>? { val code = "$n $d0 $d1" if (code in memo) return memo[code] val a = List(n) { IntArray(n) { -1 } } a.indices.forEach { i -> a[i][i] = 0 } a[0][0] = d0 a[1][1] = d1 memo[code] = if (d1 >= n) null else search(a) return memo[code] } private fun search(a: List<IntArray>, magic: Int = 3): List<IntArray>? { val n = a.size for (x in magic until n) for (y in magic until n) a[x][y] = (y - x + n) % n for (x in magic until n - magic) { a[0][x] = x - 1 a[x][0] = n + 1 - x a[x][1] = n + 2 - x a[x][2] = n - x } val p = List(n) { LongArray(n) { -1L } } while (true) { for (i in a.indices) for (j in a.indices) { val v = a[i][j] if (v == -1) continue for (x in a.indices) { if (x != i) p[x][j] = p[x][j] and (1L shl v).inv() if (x != j) p[i][x] = p[i][x] and (1L shl v).inv() if (x != v) p[i][j] = p[i][j] and (1L shl x).inv() } } var improved = false for (x in a.indices) { for (y in a.indices) { var f = a.indices.filter { ((p[x][it] shr y) and 1) > 0 } if (f.isEmpty()) return null if (f.size == 1 && a[x][f.first()] == -1) { a[x][f.first()] = y improved = true } f = a.indices.filter { ((p[it][x] shr y) and 1) > 0 } if (f.isEmpty()) return null if (f.size == 1 && a[f.first()][x] == -1) { a[f.first()][x] = y improved = true } f = a.indices.filter { ((p[x][y] shr it) and 1) > 0 } if (f.isEmpty()) return null if (f.size == 1 && a[x][y] == -1) { a[x][y] = f.first() improved = true } } } if (!improved) break } for (i in a.indices) for (j in a.indices) { if (a[i][j] >= 0) continue for (v in a.indices) { if (((p[i][j] shr v) and 1) == 0L) continue val b = a.map { it.clone() } b[i][j] = v val res = search(b) if (res != null) return res } return null } return a } 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
3,002
competitions
The Unlicense
src/main/kotlin/sschr15/aocsolutions/Day14.kt
sschr15
317,887,086
false
{"Kotlin": 184127, "TeX": 2614, "Python": 446}
package sschr15.aocsolutions import sschr15.aocsolutions.util.* import sschr15.aocsolutions.util.watched.sumOf /** * AOC 2023 [Day 14](https://adventofcode.com/2023/day/14) * Challenge: TODO (based on the day's description) */ object Day14 : Challenge { @ReflectivelyUsed override fun solve() = challenge(2023, 14) { // test() fun move(direction: Direction, grid: Grid<Char>): Grid<Char> { val newGrid = grid.toGrid() // new grid when (direction) { Direction.North -> { for (y in 1..<newGrid.height) for (x in 0..<newGrid.width) { var point = Point(x, y) val char = newGrid[point] if (char == 'O') { while (newGrid[point.up()] == '.') { newGrid[point] = '.' point = point.up() if (point.y == 0) break } newGrid[point] = 'O' } } } Direction.South -> { for (y in newGrid.height - 2 downTo 0) for (x in 0..<newGrid.width) { var point = Point(x, y) val char = newGrid[point] if (char == 'O') { while (newGrid[point.down()] == '.') { newGrid[point] = '.' point = point.down() if (point.y == newGrid.height - 1) break } newGrid[point] = 'O' } } } Direction.East -> { for (y in 0..<newGrid.height) for (x in newGrid.width - 2 downTo 0) { var point = Point(x, y) val char = newGrid[point] if (char == 'O') { while (newGrid[point.right()] == '.') { newGrid[point] = '.' point = point.right() if (point.x == newGrid.width - 1) break } newGrid[point] = 'O' } } } Direction.West -> { for (y in 0..<newGrid.height) for (x in 1..<newGrid.width) { var point = Point(x, y) val char = newGrid[point] if (char == 'O') { while (newGrid[point.left()] == '.') { newGrid[point] = '.' point = point.left() if (point.x == 0) break } newGrid[point] = 'O' } } } } return newGrid } fun Grid<Char>.getPoints() = toPointMap().filterValues { it == 'O' }.keys part1 { val input = inputLines.chars().toGrid() val grid = move(Direction.North, input) grid.rows().mapIndexed { i, row -> grid.height - i to row.count { it == 'O' } }.sumOf { it.first.w * it.second } } part2 { var grid = inputLines.chars().toGrid() val gridSet = mutableSetOf<Set<Point>>() val previousGrids = mutableListOf(grid) var previousSet = grid.getPoints() while (gridSet.add(previousSet)) { grid = move(Direction.North, grid) grid = move(Direction.West, grid) grid = move(Direction.South, grid) grid = move(Direction.East, grid) previousGrids.add(grid) previousSet = grid.getPoints() } val lookup = previousGrids.dropWhile { it.getPoints() != previousSet } val billionth = lookup[(1_000_000_000 - gridSet.size) % (lookup.size - 1)] billionth.rows().mapIndexed { i, row -> billionth.height - i to row.count { it == 'O' } }.sumOf { it.first.w * it.second } } } @JvmStatic fun main(args: Array<String>) = println("Time: ${solve()}") }
0
Kotlin
0
0
e483b02037ae5f025fc34367cb477fabe54a6578
4,447
advent-of-code
MIT License
src/aoc2022/Day24.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
package aoc2022 import utils.* private class Day24(val lines: List<String>) { fun parseInput(): Triple<Coord, Coord, List<Blizz>> { val start = Coord.xy(lines[0].indexOfFirst { it == '.' }, 0) val end = Coord.xy(lines.last().indexOfFirst { it == '.' }, lines.size - 1) val blizzards = mutableListOf<Blizz>() for (y in lines.indices) { for (x in lines[y].indices) { if (lines[y][x] == '>') { blizzards.add(Blizz(Coord.xy(x, y), Coord.RIGHT)) } else if (lines[y][x] == '<') { blizzards.add(Blizz(Coord.xy(x, y), Coord.LEFT)) } else if (lines[y][x] == '^') { blizzards.add(Blizz(Coord.xy(x, y), Coord.DOWN)) } else if (lines[y][x] == 'v') { blizzards.add(Blizz(Coord.xy(x, y), Coord.UP)) } } } return Triple(start, end, blizzards) } data class Blizz(val loc: Coord, val dir: Coord) fun part1(): Long { println() val (start, end, blizzards) = parseInput() val endAdjacent = (end + Coord.DOWN) val topLeft = Coord.xy(1, 1) val bottomRight = Coord.xy(lines[0].length - 2, lines.size - 2) val gridBounds = (topLeft..bottomRight) var currentPositions = setOf(start) var currentBlizzards = blizzards var roundCount = 0 while (true) { // Update the grid to where it will be val newBlizzards = currentBlizzards.map { updateBlizzardLocation(it, gridBounds) } val newBlizzardLocations = newBlizzards.map { it.loc }.toSet() if (endAdjacent in currentPositions) { return roundCount + 1.toLong() } // for each spot, add all the spots that we could potentially move val newPossibleLocations = currentPositions.flatMap { buildList { add(it) addAll(it.neighborsBounded(gridBounds.xRange, gridBounds.yRange, "+")) }.filter { it !in newBlizzardLocations } }.toSet() currentBlizzards = newBlizzards currentPositions = newPossibleLocations roundCount++ } } private fun updateBlizzardLocation(it: Blizz, gridBounds: CoordRange): Blizz { var newLoc = it.loc + it.dir if (newLoc !in gridBounds) { if (newLoc.x < gridBounds.xRange.first) { newLoc = Coord.xy(gridBounds.xRange.last, newLoc.y) } else if (newLoc.x > gridBounds.xRange.last) { newLoc = Coord.xy(gridBounds.xRange.first, newLoc.y) } else if (newLoc.y < gridBounds.yRange.first) { newLoc = Coord.xy(newLoc.x, gridBounds.yRange.last) } else if (newLoc.y > gridBounds.yRange.last) { newLoc = Coord.xy(newLoc.x, gridBounds.yRange.first) } } return Blizz(newLoc, it.dir) } fun part2(): Long { println() val (start, end, blizzards) = parseInput() val endAdjacent = (end + Coord.DOWN) val startAdjacent = (start + Coord.UP) val topLeft = Coord.xy(1, 1) val bottomRight = Coord.xy(lines[0].length - 2, lines.size - 2) val gridBounds = (topLeft..bottomRight) var currentPositions = setOf(start) var currentBlizzard = blizzards var traversals = 0 var roundCount = 0 while (true) { // Update the grid to where it will be val newBlizzards = currentBlizzard.map { updateBlizzardLocation(it, gridBounds) } val newBlizzardLocations = newBlizzards.map { it.loc }.toSet() // Going toward the end if (endAdjacent in currentPositions && traversals % 2 == 0) { currentPositions = setOf(end) if (traversals == 2) { return roundCount + 1.toLong() } traversals++ // Going back toward the start } else if (startAdjacent in currentPositions && traversals % 2 == 1) { currentPositions = setOf(start) traversals++ } else { val newPossibleLocations = currentPositions.flatMap { buildList { add(it) addAll(it.neighborsBounded(gridBounds.xRange, gridBounds.yRange, "+")) }.filter { it !in newBlizzardLocations } }.toMutableSet() currentPositions = newPossibleLocations } currentBlizzard = newBlizzards roundCount++ } } } fun main() { val day = "24".toInt() val todayTest = Day24(readInput(day, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 18L) val today = Day24(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1", 299L) execute(todayTest::part2, "Day[Test] $day: pt 2", 54L) execute(today::part2, "Day $day: pt 2", 899L) }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
4,511
aoc2022
Apache License 2.0
src/main/kotlin/com/dr206/2022/Day01.kt
dr206
572,377,838
false
{"Kotlin": 9200}
fun main() { fun getCounts(input: List<String>): List<Int> = input .split { calorie -> calorie.isBlank() } .map { elfCalorieList -> elfCalorieList.sumOf { calorie -> calorie.toInt() } } fun part1(input: List<String>): Int { return getCounts(input).max() } fun part2(input: List<String>): Int { return getCounts(input) .sortedDescending() .also { println(it) } .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println("Part 1 ${part1(input)}") println("Part 2 ${part2(input)}") }
0
Kotlin
0
0
57b2e7227d992de87a51094a971e952b3774fd11
787
advent-of-code-in-kotlin
Apache License 2.0
src/Day02.kt
jpereyrol
573,074,843
false
{"Kotlin": 9016}
fun main() { fun part1(input: List<String>): Int { val rounds = input.map { line -> line.filterNot { it.isWhitespace() } } val scoreResults = rounds.map { it.processRound() } return scoreResults.sum() } fun part2(input: List<String>): Int { val rounds = input.map { line -> line.filterNot { it.isWhitespace() } } val scoreResults = rounds.map { it.processRoundDecrypted() } return scoreResults.sum() } val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun String.processRound(): Int { return this.last().getRockPaperScissorValue() + if (this == "AX" || this == "BY" || this == "CZ") { Values.DRAW_SCORE } else if (this == "CX" || this == "AY" || this == "BZ") { Values.WIN_SCORE } else { Values.LOSS_SCORE } } fun String.processRoundDecrypted(): Int { if (this.last() == 'X') { // loss return Values.LOSS_SCORE + this.first().getValueForLoss() } else if (this.last() == 'Y') { //DRAW return Values.DRAW_SCORE + this.first().getValueForDraw() } else { //WIN return Values.WIN_SCORE + this.first().getValueForWin() } } fun Char.getValueForLoss(): Int { return when(this) { 'A' -> 3 'B' -> 1 else -> 2 } } fun Char.getValueForWin(): Int { return when(this) { 'A' -> 2 'B' -> 3 else -> 1 } } fun Char.getValueForDraw(): Int { return when(this) { 'A' -> 1 'B' -> 2 else -> 3 } } fun Char.getRockPaperScissorValue(): Int { return when(this) { 'X' -> Values.ROCK_SCORE 'Y' -> Values.PAPER_SCORE 'Z' -> Values.SCISSOR_SCORE else -> 0 } } object Values { const val ROCK_SCORE = 1 const val PAPER_SCORE = 2 const val SCISSOR_SCORE = 3 const val DRAW_SCORE = 3 const val WIN_SCORE = 6 const val LOSS_SCORE = 0 }
0
Kotlin
0
0
e17165afe973392a0cbbac227eb31d215bc8e07c
1,980
advent-of-code
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2023/Day14.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2023 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.XY import com.s13g.aoc.resultFrom /** * --- Day 14: Parabolic Reflector Dish --- * https://adventofcode.com/2023/day/14 */ class Day14 : Solver { override fun solve(lines: List<String>): Result { val grid = Grid(lines) return resultFrom(moveRocks(grid), spin(grid)) } private fun spin(g: Grid): Int { val targetSpinNum = 1_000_000_000 val history = mutableMapOf<Int, Int>() var cycle = 1 while (cycle <= targetSpinNum) { Dir.values().forEach { dir -> moveRocks(g, dir) } // Find Loop if (g.hashCode() in history) { val loopLength = cycle - history[g.hashCode()]!! val numLoops = (targetSpinNum - cycle) / loopLength cycle += (numLoops * loopLength) } history[g.hashCode()] = cycle cycle++ } return g.load() } private fun moveRocks(g: Grid, dir: Dir = Dir.N): Int { var rocksMoved: Int do { rocksMoved = 0 for (y in g.yRange(dir)) { for (x in g.xRange(dir)) { if (g[x, y] == 1 && g[x + dir.d.x, y + dir.d.y] == 0) { g[x + dir.d.x, y + dir.d.y] = 1 g[x, y] = 0 rocksMoved++ } } } } while (rocksMoved > 0) return g.load() } private fun Grid(lines: List<String>): Grid { val intMap = mapOf('.' to 0, 'O' to 1, '#' to 2) val w = lines[0].length val h = lines.size // Speeds Day 14 up 2x by using IntArray instead of a list. val data = IntArray(w * h) { 0 } for ((y, line) in lines.withIndex()) { for ((x, ch) in line.withIndex()) { data[y * w + x] = intMap[ch]!! } } return Grid(data, h, w) } private data class Grid(val data: IntArray, val h: Int, val w: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Grid return data.contentEquals(other.data) } override fun hashCode() = data.contentHashCode() } private fun Grid.xRange(dir: Dir) = when (dir) { Dir.N, Dir.S -> 0 until w Dir.W -> 1 until w Dir.E -> w - 2 downTo 0 } private fun Grid.yRange(dir: Dir) = when (dir) { Dir.N -> 1 until h Dir.W, Dir.E -> 0 until h Dir.S -> h - 2 downTo 0 } private operator fun Grid.get(x: Int, y: Int) = data[idx(x, y)] private operator fun Grid.set(x: Int, y: Int, ch: Int) { data[idx(x, y)] = ch } private fun Grid.idx(x: Int, y: Int) = y * w + x private fun Grid.load() = (0 until h).sumOf { x -> (0 until w).filter { y -> this[x, y] == 1 }.sumOf { h - it } } private enum class Dir(val d: XY) { N(XY(0, -1)), W(XY(-1, 0)), S(XY(0, 1)), E(XY(1, 0)) } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,824
euler
Apache License 2.0
src/Day06.kt
fmborghino
573,233,162
false
{"Kotlin": 60805}
// four characters that are all different fun main() { fun log(message: Any?) { // println(message) } fun part1(input: String): Int { // whoaa TIL indexOfFirst() // windowedSequence or not... need to benchmark really, not obvious return input.windowedSequence(4).indexOfFirst { it.toSet().size == 4 } + 4 // first try // log(input) // val match = input // .windowed(4, 1).map{ it.toSet() }.first { it.size == 4 }.joinToString("") // log(match) // return input.indexOf(match) + 4 // more noodling (based on youtube) // for((index, window) in input.windowedSequence(4).withIndex()) { // if (window.toSet().size == 4) return index + 4 // } // return 0 } fun part2(input: String): Int { val match = input .windowed(14, 1).map{ it.toSet() }.first { it.size == 14 }.joinToString("") log(match) return input.indexOf(match) + 14 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test.txt").first() check(part1(testInput) == 7) // check(part2(testInput) == 999) val input = readInput("Day06.txt").first() println(part1(input)) check(part1(input) == 1651) println(part2(input)) check(part2(input) == 3837) }
0
Kotlin
0
0
893cab0651ca0bb3bc8108ec31974654600d2bf1
1,357
aoc2022
Apache License 2.0
leetcode/src/daily/Interview1709.kt
zhangweizhe
387,808,774
false
null
package daily import kotlin.math.min fun main() { // 面试题 17.09. 第 k 个数 // https://leetcode.cn/problems/get-kth-magic-number-lcci/ // 题解 // https://leetcode.cn/problems/get-kth-magic-number-lcci/solution/di-k-ge-shu-jiu-shi-xiang-bu-tong-wei-he-san-zhi-z/ println(getKthMagicNumber(5)) } fun getKthMagicNumber(k: Int): Int { // dp 数组,dp[i] 表示第 i 个数,所以要求第 k 个数,就是返回 dp[k] val dp = IntArray(k+1) dp[1] = 1 // 三个指针 var p3 = 1 var p5 = 1 var p7 = 1 var dpIndex = 1 while (dpIndex < k) { val tmp3 = dp[p3] * 3 val tmp5 = dp[p5] * 5 val tmp7 = dp[p7] * 7 val min = min(min(tmp3, tmp5), tmp7) if (min == tmp3) { p3++ } if (min == tmp5) { p5++ } if (min == tmp7) { p7++ } dpIndex++ dp[dpIndex] = min } return dp[k] } fun getKthMagicNumber1(k: Int): Int { // uglys 数组,uglys[i] 表示第 i 个数,所以要求第 k 个数,就是返回 uglys[k] val uglys = IntArray(k+1) var p3 = 1 var p5 = 1 var p7 = 1 uglys[1] = 1 var uglyIndex = 1 while (uglyIndex < k) { val tmp3 = uglys[p3] * 3 val tmp5 = uglys[p5] * 5 val tmp7 = uglys[p7] * 7 val min = min(tmp3, min(tmp5, tmp7)) if (tmp3 == min) { p3++ } if (tmp5 == min) { p5++ } if (tmp7 == min) { p7++ } uglyIndex++ uglys[uglyIndex] = min } return uglys[uglyIndex] }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,647
kotlin-study
MIT License
src/Day03.kt
kmakma
574,238,598
false
null
fun main() { fun Char.priority(): Int { return this.code - if (this.isLowerCase()) 96 else 38 } fun part1(input: List<String>): Int { var prioSum = 0 input.forEach { line -> val chunked = line.chunked(line.length / 2) val duplicate = chunked[0].toSet().intersect(chunked[1].toSet()).first() prioSum += duplicate.priority() } return prioSum } fun part2(input: List<String>): Int { return input.asSequence() .map { it.toSet() } .chunked(3) .map { it.reduce { intersection, prev -> intersection.intersect(prev) } } .map { it.first().priority() } .sum() } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
950ffbce2149df9a7df3aac9289c9a5b38e29135
817
advent-of-kotlin-2022
Apache License 2.0
src/Day10.kt
jordan-thirus
573,476,470
false
{"Kotlin": 41711}
fun main() { fun processCommand(command: String, registerX: Int, processCycle: () -> Unit): Int { return when (command) { "noop" -> { processCycle() registerX } else -> { //addx val v = command.split(" ")[1].toInt() processCycle() processCycle() registerX + v } } } fun part1(input: List<String>): Int { var registerX = 1 var cycle = 1 var signalStrength = 0 input.forEach { registerX = processCommand(it, registerX) { val calculateStrength = (cycle-20)%40 == 0 if(calculateStrength){ signalStrength += registerX * cycle } cycle++ } } return signalStrength } fun part2(input: List<String>) { var registerX = 1 var position = 0 val crtWidth = 40 val crt = mutableListOf<Char>() input.forEach { line -> registerX = processCommand(line, registerX) { if (position in registerX - 1..registerX + 1) { crt.add('#') } else { crt.add('.') } position++ if (position == crtWidth) { position = 0 } } } crt.chunked(crtWidth) .map { it.joinToString(separator = "") } .forEach { println(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) //part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e
1,847
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day10.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2021 class Day10(private val input: List<String>) { fun solvePart1(): Int { val bracketPoints = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) return solve().filterIsInstance<LineResult.Corrupt>().sumOf { result -> bracketPoints.getValue(result.bracket) } } fun solvePart2(): Long { val bracketPoints = mapOf(')' to 1L, ']' to 2L, '}' to 3L, '>' to 4L) val scores = solve().filterIsInstance<LineResult.Incomplete>().map { result -> result.missingBrackets.fold(0L) { acc, c -> acc * 5L + bracketPoints.getValue(c) } } return scores.sorted()[scores.size / 2] } private fun solve(): List<LineResult> { val brackets = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') return input.map { line -> val stack = mutableListOf<Char>() for (c in line) { if (brackets.containsKey(c)) { stack.add(brackets.getValue(c)) } else if (stack.removeLast() != c) { return@map LineResult.Corrupt(c) } } LineResult.Incomplete(stack.reversed()) } } private sealed class LineResult { class Corrupt(val bracket: Char) : LineResult() class Incomplete(val missingBrackets: List<Char>) : LineResult() } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
1,415
advent-of-code
Apache License 2.0
src/main/kotlin/Day13.kt
joostbaas
573,096,671
false
{"Kotlin": 45397}
import Packet.Companion.parsePacket import kotlin.math.max sealed interface Packet : Comparable<Packet> { companion object { fun String.parsePacket(): Packet { val firstPacketListContent = mutableListOf<Packet>() val stack: MutableList<PacketList> = mutableListOf(PacketList(firstPacketListContent)) var remainder = this while (remainder.isNotEmpty()) { val numberConsumed: Int = when (remainder[0]) { in ('0'..'9') -> { val number = remainder.takeWhile { it.isDigit() } stack.last().add(SinglePacket(number.toInt())) number.length } '[' -> { stack.add(PacketList(mutableListOf())) 1 } ']' -> { val finishedPacketList = stack.removeLast() stack.last().add(finishedPacketList) 1 } ',' -> 1 else -> throw IllegalArgumentException("should only be numbers, commas and brackets, but found \"${remainder[0]}\"") } remainder = remainder.drop(numberConsumed) } return stack.first().content.first() } } override fun compareTo(other: Packet): Int = when (this.shouldBeBefore(other)) { true -> -1 null -> 0 false -> 1 } fun shouldBeBefore(other: Packet): Boolean? { return when { this is SinglePacket && other is SinglePacket -> when { this.content < other.content -> true this.content == other.content -> null else -> false } this is PacketList && other is PacketList -> { for (i in (0..max(this.content.size, other.content.size))) { val thisChild = content.getOrNull(i) val otherChild = other.content.getOrNull(i) when { thisChild == null && otherChild != null -> return true thisChild == null && otherChild == null -> return null otherChild == null -> return false else -> { if (thisChild!!.shouldBeBefore(otherChild) == true) return true if (thisChild.shouldBeBefore(otherChild) == false) return false } } } null } this is SinglePacket && other is PacketList -> return PacketList(mutableListOf(this)).shouldBeBefore(other) this is PacketList && other is SinglePacket -> return this.shouldBeBefore(PacketList(mutableListOf(other))) else -> throw IllegalArgumentException() } } } data class SinglePacket(val content: Int) : Packet { override fun toString(): String { return content.toString() } } data class PacketList(val content: MutableList<Packet>) : Packet { fun add(packet: Packet) { this.content.add(packet) } override fun toString(): String { return content.joinToString(separator = ",", prefix = "[", postfix = "]") } } fun day13Part1(input: List<String>): Int = input.asSequence().chunked(3).mapIndexed { i, lines -> val (first, second) = lines i to first.parsePacket().shouldBeBefore(second.parsePacket()) }.filter { it.second == true } .map { it.first + 1 } .sum() fun day13Part2(input: List<String>): Int { val decoderPacket1 = "[[2]]".parsePacket() val decoderPacket2 = "[[6]]".parsePacket() val allPacketsSorted = input.filterNot { it.isEmpty() } .map { it.parsePacket() } .plus(listOf(decoderPacket1, decoderPacket2)) .sorted() val indexOfdecoderPacket1 = allPacketsSorted.indexOf("[[2]]".parsePacket()) + 1 val indexOfdecoderPacket2 = allPacketsSorted.indexOf("[[6]]".parsePacket()) + 1 return indexOfdecoderPacket1 * indexOfdecoderPacket2 }
0
Kotlin
0
0
8d4e3c87f6f2e34002b6dbc89c377f5a0860f571
4,240
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day6.kt
hughjdavey
225,440,374
false
null
package days class Day6 : Day(6) { override fun partOne(): Any { return numberOfOrbits(inputList) } override fun partTwo(): Any { return numberOfOrbits(inputList, "YOU", "SAN") } fun numberOfOrbits(map: List<String>): Int { val orbits = orbits(map) return orbits.keys.map { count(it, orbits) }.sum() } fun numberOfOrbits(map: List<String>, start: String, dest: String): Int { val orbits = orbits(map) val (startChain, destChain) = backChain(start, orbits) to backChain(dest, orbits) val firstIntersection = startChain.first { planet -> destChain.contains(planet) } return startChain.indexOf(firstIntersection) + destChain.indexOf(firstIntersection) } private fun orbits(map: List<String>): Map<String, String> { return map.map { orbit -> val (orbitee, orbiter) = orbit.split(')') orbiter to orbitee }.toMap() } private fun count(planet: String, planets: Map<String, String>): Int { val orbitee = planets[planet] return if (orbitee == null) 0 else { 1 + count(orbitee, planets) } } private fun backChain(planet: String, planets: Map<String, String>): List<String> { val orbitee = planets[planet] return if (orbitee == null) emptyList() else { listOf(orbitee).plus(backChain(orbitee, planets)) } } }
0
Kotlin
0
1
84db818b023668c2bf701cebe7c07f30bc08def0
1,438
aoc-2019
Creative Commons Zero v1.0 Universal
src/main/kotlin/unam/ciencias/heuristicas/algorithm/Graph.kt
angelgladin
203,038,278
false
{"TSQL": 7853771, "Kotlin": 28077, "TeX": 21759}
package unam.ciencias.heuristicas.algorithm import java.util.* /** * Weighted undirected graph. * * @param T The identifier of the node. * @param E The data it's going to store each node in it. */ class Graph<T, E> { private val nodes = hashMapOf<T, Node<T, E>>() val edges = PriorityQueue<Edge<T>>(Comparator { o1, o2 -> o2.weight.compareTo(o1.weight) }) fun addNode(a: T, info: E) { nodes[a] = Node(a, info, null) } fun getNodes() = nodes.keys fun getNodeInfo(a: T): E? = if (a in nodes) nodes[a]!!.info else null fun addEdge(a: T, b: T, weight: Double) { if (a in nodes && b in nodes) { if (nodes[a]!!.neighbors == null) nodes[a]!!.neighbors = hashMapOf() if (nodes[b]!!.neighbors == null) nodes[b]!!.neighbors = hashMapOf() nodes[a]!!.neighbors!![b] = weight nodes[b]!!.neighbors!![a] = weight edges.add(Edge(a, b, weight)) } else { throw IllegalArgumentException("Tha graph doesn't contain such nodes") } } fun size(): Int = nodes.size fun hasEdge(a: T, b: T): Boolean = a in nodes && nodes[a]!!.neighbors != null && b in nodes[a]!!.neighbors!! fun edgeWeight(a: T, b: T): Double? = if (hasEdge(a, b)) nodes[a]!!.neighbors!![b] else null fun inducedGraph(verticesSubSet: Collection<T>): Graph<T, E> { val graph = Graph<T, E>() verticesSubSet.forEach { graph.addNode(it, nodes[it]!!.info) } for (edge in edges) { if (edge.a in graph.nodes && edge.b in graph.nodes) graph.addEdge(edge.a, edge.b, edge.weight) } return graph } private data class Node<T, E>( val id: T, val info: E, var neighbors: HashMap<T, Double>? ) data class Edge<T>( val a: T, val b: T, val weight: Double ) }
0
TSQL
0
0
b8f3288ebc17f1a1468da4631cbf8af58f4fd28b
1,950
TSP-Threshold-Accepting
MIT License
DijkstraAlgorithm/src/main/java/com/muramsyah/dijkstraalgorithm/dijkstra/Dijkstra.kt
ramdhanjr11
493,106,469
false
{"Kotlin": 68652}
/* * Copyright (c) 2022. * Created By <NAME> on 16-05-2022 * Github : https://github.com/ramdhanjr11 * LinkedIn : https://www.linkedin.com/in/ramdhanjr11 * Instagram : ramdhan.official */ fun <T> dijkstra(graph: Graph<T>, start: T): Map<T, T?> { val S: MutableSet<T> = mutableSetOf() // subset dari simpul yang kita ketahui jarak sebenarnya, contoh [A, B, C, D, E] /* * variable delta mewakili jumlah dari banyaknya jalur terpendek * Isi pertama adalah infinity dengan Int.MAX_VALUE untuk nanti dibandingkan */ val delta = graph.vertices.map { it to Double.MAX_VALUE }.toMap().toMutableMap() delta[start] = 0.0 /* previous adalah variable untuk menampung path yang telah dikunjungi * inisialiasasi awal semua isi menjadi null */ val previous: MutableMap<T, T?> = graph.vertices.map { it to null }.toMap().toMutableMap() // Melakukan perulangan jika S != subset simpul, contoh [A, B] != [A, B, C, D] while (S != graph.vertices) { // v adalah simpul terdekat yang belum dikunjungi val v: T = delta .filter { !S.contains(it.key) } .minByOrNull { it.value }!! .key graph.edges.getValue(v).minus(S).forEach { neighbor -> val newPath = delta.getValue(v) + graph.weights.getValue(Pair(v, neighbor)) if (newPath < delta.getValue(neighbor)) { delta[neighbor] = newPath previous[neighbor] = v } } S.add(v) } return previous.toMap() } // fungsi untuk menampilkan shortest path dari fungsi dijkstra yang mengembalikan nilai previous path fun <T> shortestPath(shortestPathTree: Map<T, T?>, start: T, end: T): List<T> { fun pathTo(start: T, end: T): List<T> { if (shortestPathTree[end] == null) return listOf(end) return listOf(pathTo(start, shortestPathTree[end]!!), listOf(end)).flatten() } return pathTo(start, end) }
0
Kotlin
0
2
7f4782354a578030728cb2c64aed768095e38c32
1,973
Sea-Kidul-App
Apache License 2.0
src/day07/Day07.kt
Longtainbin
573,466,419
false
{"Kotlin": 22711}
package day07 import Reference import readInput import kotlin.math.min fun main() { val input = readInput("inputDay07") val root = generateTree(input) calculateDirectorySize(root) fun part1(root: Node): Long { return helperForPart1(root) } fun part2(root: Node): Long { return helperForPart2(root) } println(part1(root)) println(part2(root)) } /** * For part_1 */ fun helperForPart1(root: Node): Long { val limit = 100000L val result = Reference<Long>(0L) dfsForPart1(root, result, limit) return result.value } fun dfsForPart1(root: Node, result: Reference<Long>, limit: Long) { // println("${root.name} \t ### ${root.size}") if (root.size <= limit) { result.value += root.size } root.dirChildren?.let { it.forEach { node -> dfsForPart1(node, result, limit) } } } /** * For part_2 **/ fun helperForPart2(root: Node): Long { val totalSize = 70000000 val needSize = 30000000 val currentSize = root.size val minDeleteSize = needSize - (totalSize - currentSize) if (minDeleteSize <= 0) { return 0 } val result = Reference<Long>(currentSize) dfsForPart2(root, result, minDeleteSize) return result.value } fun dfsForPart2(root: Node, result: Reference<Long>, minDeleteSize: Long) { if (root.size >= minDeleteSize) { result.value = min(result.value, root.size) } root.dirChildren?.let { it.forEach { node -> dfsForPart2(node, result, minDeleteSize) } } }
0
Kotlin
0
0
48ef88b2e131ba2a5b17ab80a0bf6a641e46891b
1,543
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/colinodell/advent2016/Day10.kt
colinodell
495,627,767
false
{"Kotlin": 80872}
package com.colinodell.advent2016 class Day10(private val input: List<String>) { fun solvePart1() = Factory(input).runUntilBotHas(listOf(61, 17)) fun solvePart2(): Int { val f = Factory(input) f.runAll() return f.containers .filterKeys { listOf("output 0", "output 1", "output 2").contains(it) } .values .map { it.chips.first() } .reduce(Int::times) } private class Container(private val name: String) { val chips = mutableListOf<Int>() fun take(chip: Int) { chips.add(chip) } fun giveLow(container: Container) { container.take(chips.minOrNull()!!) } fun giveHigh(container: Container) { container.take(chips.maxOrNull()!!) } fun canProceed() = name.contains("output") || chips.size == 2 } private class Factory(input: List<String>) { val containers = mutableMapOf<String, Container>() fun getContainer(name: String) = containers.getOrPut(name) { Container(name) } val instructions: MutableList<Instruction> init { instructions = input.map { line -> if (line.contains("goes to")) { val (value, destination) = Regex("value (\\d+) goes to (.+)").find(line)!!.groupValues.drop(1) ValueAssignmentInstruction(destination, value.toInt()) } else { val (giver, lowDest, highDest) = Regex("(bot \\d+) gives low to (.+) and high to (.+)").find(line)!!.groupValues.drop(1) OutputInstruction(giver, lowDest, highDest) } }.toMutableList() } fun step(): Boolean { if (instructions.isEmpty()) { return false } val i = instructions.indexOfFirst { it.execute(this) } instructions.removeAt(i) return true } fun runAll() { while (step()) {} } fun runUntilBotHas(values: List<Int>): String { while (true) { step() val bot = containers.toList().firstOrNull { it.second.chips.containsAll(values) } if (bot !== null) { return bot.first } } } } private interface Instruction { fun execute(factory: Factory): Boolean } private class ValueAssignmentInstruction(val bot: String, val value: Int) : Instruction { override fun execute(factory: Factory): Boolean { factory.getContainer(bot).take(value) return true } } private class OutputInstruction(val bot: String, val lowTarget: String, val highTarget: String) : Instruction { override fun execute(factory: Factory): Boolean { val container = factory.getContainer(bot) if (!container.canProceed()) { return false } container.giveLow(factory.getContainer(lowTarget)) container.giveHigh(factory.getContainer(highTarget)) return true } } }
0
Kotlin
0
0
8a387ddc60025a74ace8d4bc874310f4fbee1b65
3,189
advent-2016
Apache License 2.0
src/day21.kt
miiila
725,271,087
false
{"Kotlin": 77215}
import java.io.File import kotlin.system.exitProcess private const val DAY = 21 fun main() { if (!File("./day${DAY}_input").exists()) { downloadInput(DAY) println("Input downloaded") exitProcess(0) } val transformer = { x: String -> x.toList() } val input = loadInput(DAY, false, transformer) println(input) println(solvePart1(input)) println(solvePart2(input)) } fun findStart(grid: List<List<Char>>): Pos { for ((r, row) in grid.withIndex()) { for ((c, char) in row.withIndex()) { if (char == 'S') { return Pos(r, c) } } } error("Start not found") } // Part 1 private fun solvePart1(input: List<List<Char>>): Int { val start = findStart(input) var currents = mutableListOf(start) val mem = mutableMapOf<Pos, Set<Pos>>() var res = 0 for (i in (1..64)) { val nexts = mutableSetOf<Pos>() while (currents.isNotEmpty()) { val current = currents.removeFirst() if (current !in mem) { mem[current] = getNextVisits(input, current) } nexts.addAll(mem[current]!!) } currents = nexts.toMutableList() res = nexts.count() } return res } fun getNextVisits(grid: List<List<Char>>, pos: Pos): Set<Pos> { val nexts = mutableSetOf<Pos>() for (next in getNext(pos)) { val nextPos = Pos(next.row `%` grid.count(), next.col `%` grid[0].count()) if (grid[nextPos.row][nextPos.col] == '#') { continue } nexts.add(nextPos) } return nexts } fun getNextVisitsInf(grid: List<List<Char>>, pos: Pos, visited: Set<Pos>?): Set<Pos> { val nexts = mutableSetOf<Pos>() for (next in getNext(pos)) { if (grid[next.row `%` grid.count()][next.col `%` grid[0].count()] == '#') { continue } if (visited != null && next in visited) { continue } nexts.add(next) } return nexts } infix fun Int.`%`(divisor: Int): Int { return ((this % divisor) + divisor) % divisor } // Part 2 private fun solvePart2Slow(input: List<List<Char>>): Int { val start = findStart(input) var currents = mutableListOf(start) var counts = mutableMapOf<Int, Int>() val visited = mutableSetOf<Pos>() for (i in (1..1000)) { val nexts = mutableSetOf<Pos>() while (currents.isNotEmpty()) { val current = currents.removeFirst() visited.add(current) for (next in getNextVisitsInf(input, current, null)) { if (next !in visited) { nexts.add(next) } } } currents = nexts.toMutableList() counts[i] = nexts.count() } val isEven = counts.keys.last() % 2 == 0 var res = if (isEven) 1 else 0 res += if (isEven) { counts.filter { (k, v) -> k % 2 == 0 }.values.sum() } else { counts.filter { (k, v) -> k % 2 == 1 }.values.sum() } return res } private fun solvePart2WIP(input: List<List<Char>>): Int { val start = findStart(input) var currents = setOf(start) val visited = mutableSetOf<Pos>() val mem = mutableMapOf<Set<Pos>, Int>() val mem2 = mutableMapOf<Set<Pos>, Set<Pos>>() var res = 0 for (i in (1..1000)) { val nexts = mutableSetOf<Pos>() println("Is seen? ${currents in mem}") // if (currents !in mem) { val iters = currents.toMutableList() while (iters.isNotEmpty()) { val current = iters.removeFirst() visited.add(current) for (next in getNextVisits(input, current)) { // val nextMod = Pair(next.first `%` input.count(), next.second `%` input[0].count()) nexts.add(next) } } mem[currents.toSet()] = nexts.count() // mem2[currents.toSet()] = nexts res = nexts.count() // } else { res = nexts.count() // } currents = nexts } return res } private fun solvePart2(input: List<List<Char>>): Int { val start = findStart(input) val mem: MutableMap<Set<Pos>, Set<Pos>> = mutableMapOf() val visited = mutableSetOf<Pos>() var q = mutableListOf<Pos>(start) for (i in 0..26501365) { if (i % 1000 == 0) { println(i) } val newQ: MutableSet<Pos> = mutableSetOf() while (q.isNotEmpty()) { val current = q.removeFirst() visited.add(current) newQ.addAll(getNextVisitsInf(input, current, visited)) } q = newQ.toMutableList() } return 0 } fun getNextState(grid: List<List<Char>>, reach: Set<Pos>): Set<Pos> { val nexts = mutableSetOf<Pos>() for (current in reach) { for (next in getNextVisits(grid, current)) { nexts.add(next) } } return nexts }
0
Kotlin
0
1
1cd45c2ce0822e60982c2c71cb4d8c75e37364a1
4,957
aoc2023
MIT License
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day02.kt
MichalChomo
572,214,942
false
{"Kotlin": 56758}
package eu.michalchomo.adventofcode.year2022 fun main() { val letterPairToScore = mapOf( "A X" to 3 + 1, "A Y" to 6 + 2, "A Z" to 0 + 3, "B X" to 0 + 1, "B Y" to 3 + 2, "B Z" to 6 + 3, "C X" to 6 + 1, "C Y" to 0 + 2, "C Z" to 3 + 3, ) val letterPairToScorePart2 = mapOf( "A X" to 0 + 3, "A Y" to 3 + 1, "A Z" to 6 + 2, "B X" to 0 + 1, "B Y" to 3 + 2, "B Z" to 6 + 3, "C X" to 0 + 2, "C Y" to 3 + 3, "C Z" to 6 + 1, ) fun part1(input: List<String>): Int = input.sumOf { letterPairToScore[it.trim()]!! } fun part2(input: List<String>) = input.sumOf { letterPairToScorePart2[it.trim()]!! } val testInput = readInputLines("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInputLines("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a95d478aee72034321fdf37930722c23b246dd6b
997
advent-of-code
Apache License 2.0