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/Day06.kt
mddanishansari
576,622,315
false
{"Kotlin": 11861}
fun main() { fun String.containsDuplicate(): Boolean { val duplicates = mutableListOf<Char>() forEach { if (duplicates.contains(it)) { return true } duplicates.add(it) } return false } fun String.solution(distinctCharacters:Int): Int { var marker = distinctCharacters for (s in windowed(distinctCharacters, 1)) { if (s.containsDuplicate()) { marker++ } else { break } } return marker } fun part1(input: List<String>): Int { return input.first().solution(4) } fun part2(input: List<String>): Int { return input.first().solution(14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") part1(input).println() part2(input).println() }
0
Kotlin
0
0
e032e14b57f5e6c2321e2b02b2e09d256a27b2e2
1,045
advent-of-code-2022
Apache License 2.0
src/main/kotlin/tools/math/Modulo.kt
wrabot
739,807,905
false
{"Kotlin": 19706}
package tools.math fun Long.times(multiplier: Long, modulo: Long): Long { if (this < 0) error("negative multiplicand") if (multiplier < 0) error("negative multiplier") if (modulo < 0) error("negative modulo") var res = 0L var a = this % modulo var b = multiplier % modulo while (true) { if (b and 1L > 0L) res = (res + a) % modulo b = b shr 1 if (b == 0L) return res a = a shl 1 if (a < 0) error("overflow") a %= modulo } } fun Long.inv(modulo: Long): Long = inverse(this, modulo, 1, 0).let { if (it < 0) it + modulo else it } private tailrec fun inverse(v: Long, n: Long, s: Long, t: Long): Long = if (v == 1L) s else inverse(n % v, v, t - n / v * s, s) fun chineseRemainder(input: List<Pair<Long, Long>>): Long { val np = input.fold(1L) { acc, i -> acc * i.second } return input.fold(0L) { acc, (v, n) -> (np / n).let { (acc + v.times(it.inv(n), np).times(it, np)).mod(np) } } }
0
Kotlin
0
0
fd2da26c0259349fbc9719e694d58549e7f040a0
976
competitive-tools
Apache License 2.0
src/day19/Day19.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
package day19 import readInput import java.util.* import java.util.regex.Pattern import kotlin.time.measureTime import kotlin.time.Duration import kotlin.time.ExperimentalTime enum class Material { ORE, CLAY, OBSIDIAN, GEODE } data class BuildCost(val ore: Int, val clay: Int, val obsidian: Int) class Blueprint(description: String) { val id: Int val buildCosts = EnumMap<Material, BuildCost>(Material::class.java) val maxMaterialNeeded = EnumMap<Material, Int>(Material::class.java) init { val pattern = Pattern.compile( """Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""") val matcher = pattern.matcher(description) if (matcher.find()) { var matchGroup = 1 id = matcher.group(matchGroup++).toInt() buildCosts[Material.ORE] = BuildCost(matcher.group(matchGroup++).toInt(), 0, 0) buildCosts[Material.CLAY] = BuildCost(matcher.group(matchGroup++).toInt(), 0, 0) buildCosts[Material.OBSIDIAN] = BuildCost(matcher.group(matchGroup++).toInt(), matcher.group(matchGroup++).toInt(), 0) buildCosts[Material.GEODE] = BuildCost(matcher.group(matchGroup++).toInt(), 0, matcher.group(matchGroup).toInt()) print("Blueprint $id max materials: ") maxMaterialNeeded[Material.ORE] = buildCosts.maxOf{ it.value.ore } print("ORE: ${maxMaterialNeeded[Material.ORE]} ") maxMaterialNeeded[Material.CLAY] = buildCosts.maxOf{ it.value.clay } print("CLAY: ${maxMaterialNeeded[Material.CLAY]} ") maxMaterialNeeded[Material.OBSIDIAN] = buildCosts.maxOf{ it.value.obsidian } println("OBS: ${maxMaterialNeeded[Material.OBSIDIAN]}") maxMaterialNeeded[Material.GEODE] = Int.MAX_VALUE } else { throw Exception("Blueprint description not in expected format.") } } } data class ProductionState(val blueprint: Blueprint, var stepsRemaining: Int, var robots: EnumMap<Material, Int>, var materials: EnumMap<Material, Int> ) { fun fingerprint(): String { // Fingerprint ID is of this form: // <steps><robot counts><material quantities> var id = "$stepsRemaining|" for (m in Material.values()) { id += "%d|".format(robots[m] ?: 0) } for (m in Material.values()) { id += "%d|".format(materials[m] ?: 0) } return id } fun collectMaterials() { for (m in Material.values()) { materials[m] = (materials[m] ?: 0) + (robots[m] ?: 0) } } fun canBuildRobot(robotType: Material): Boolean = (materials[Material.ORE] ?: 0) >= (blueprint.buildCosts[robotType]?.ore ?: 0) && (materials[Material.CLAY] ?: 0) >= (blueprint.buildCosts[robotType]?.clay ?: 0) && (materials[Material.OBSIDIAN] ?: 0) >= (blueprint.buildCosts[robotType]?.obsidian ?: 0) fun shouldBuildRobot(robotType: Material): Boolean = when(robotType) { Material.ORE -> (robots[Material.ORE] ?: 0) < blueprint.maxMaterialNeeded[Material.ORE]!! * 2 Material.CLAY -> (robots[Material.CLAY] ?: 0) < blueprint.maxMaterialNeeded[Material.CLAY]!! Material.OBSIDIAN -> (robots[Material.OBSIDIAN] ?: 0) < blueprint.maxMaterialNeeded[Material.OBSIDIAN]!! Material.GEODE -> true } fun buildRobot(robotType: Material): Boolean { if (canBuildRobot(robotType)) { materials[Material.ORE] = (materials[Material.ORE] ?: 0) - (blueprint.buildCosts[robotType]?.ore ?: 0) materials[Material.CLAY] = (materials[Material.CLAY] ?: 0) - (blueprint.buildCosts[robotType]?.clay ?: 0) materials[Material.OBSIDIAN] = (materials[Material.OBSIDIAN] ?: 0) - (blueprint.buildCosts[robotType]?.obsidian ?: 0) robots[robotType] = (robots[robotType] ?: 0) + 1 return true } return false } } fun computeMaxGeodeProduction(blueprint: Blueprint, steps: Int): Int { val states = mutableListOf(ProductionState(blueprint, steps, EnumMap<Material, Int>(Material::class.java), EnumMap<Material, Int>(Material::class.java))) val alreadyComputedStates = mutableSetOf<String>() var maxGeodes = 0 states.last().robots[Material.ORE] = 1 while(states.isNotEmpty()) { val state = states.last() states.removeLast() if (state.stepsRemaining == 0) { if (state.materials.containsKey(Material.GEODE) && state.materials[Material.GEODE]!! > maxGeodes) { maxGeodes = state.materials[Material.GEODE]!! } continue } for (robot in Material.values()) { if (state.canBuildRobot(robot)) { if (state.shouldBuildRobot(robot)) { val newState = state.copy( stepsRemaining = state.stepsRemaining - 1, robots = state.robots.clone(), materials = state.materials.clone() ) newState.collectMaterials() newState.buildRobot(robot) val fingerprint = newState.fingerprint() if (!alreadyComputedStates.contains(fingerprint)) { states.add(newState) alreadyComputedStates.add(fingerprint) } } } } val newState = state.copy(stepsRemaining = state.stepsRemaining - 1, robots = state.robots.clone(), materials = state.materials.clone()) newState.collectMaterials() val fingerprint = newState.fingerprint() if (! alreadyComputedStates.contains(fingerprint)) { states.add(newState) alreadyComputedStates.add(fingerprint) } } return maxGeodes } fun parseBlueprints(input: List<String>): List<Blueprint> { val blueprints = mutableListOf<Blueprint>() for (description in input) { blueprints.add(Blueprint(description.trim())) } return blueprints } @OptIn(ExperimentalTime::class) fun main() { fun part1(input: List<String>): Int { var qualitySum = 0 val blueprints = parseBlueprints(input) for (blueprint in blueprints) { var maxGeodes = 0 val elapsedTime: Duration = measureTime { maxGeodes = computeMaxGeodeProduction(blueprint, 24) } println("Blueprint ${blueprint.id} can produce ${maxGeodes}; computation time: ${elapsedTime.toIsoString()}") qualitySum += maxGeodes * blueprint.id } println("Sum of all blueprint qualities: ${qualitySum}") return qualitySum } fun part2(input: List<String>): Int = 0 val testInput = readInput("Day19_test") check(part1(testInput) == 33) check(part2(testInput) == 0) val input = readInput("Day19") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
7,231
AdventOfCode2022
Apache License 2.0
src/main/kotlin/aoc2022/Day17.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2022 import utils.Coordinates import utils.InputUtils import java.lang.Integer.max typealias Rock = List<String> fun Rock.width() = get(0).length class Room(val jets: Iterator<Char>, val rockSupply: Iterator<Rock>) { val rows : MutableList<CharArray> = arrayListOf() var highest = -1 fun isCollision(topLeft:Coordinates, rock:Rock) : Boolean { if (topLeft.x + rock.width() > 7 || topLeft.x<0) return true if (topLeft.y - rock.size < -1) return true for(y in rock.indices) for (x in rock[y].indices) if (rock[y][x] == '#' && at(topLeft.x + x, topLeft.y - y) == '#') return true return false } fun ensureRows(size: Int) { if (size > rows.size) repeat(size-rows.size) { rows.add(CharArray(7) { '.' })} } fun at(x: Int, y: Int): Char { ensureRows(y+1) return rows[y][x] } fun setRock(x: Int, y:Int) { ensureRows(y+1) rows[y][x] = '#' } fun startingLocation(rock: Rock): Coordinates = Coordinates(2, highest + rock.size + 3) fun stop(topLeft: Coordinates, rock: Rock) { //println("Stopping at $topLeft") for(y in rock.indices) for (x in rock[y].indices) if (rock[y][x] == '#') setRock(topLeft.x + x, topLeft.y - y) highest = max(topLeft.y, highest) } fun render(size: Int): String { return (highest downTo max(0, highest - size)).asSequence().map { '|' + rows[it].concatToString() + '|' }.joinToString("\n") + "\n+-------+\n" } fun addRocks(n: Int) = repeat(n) { addRock() } fun addRock() = addRock(rockSupply.next()) fun addRock(rock: Rock) { var pos = startingLocation(rock) do { val jet = jets.next() var nextPos = pos.dX(if (jet == '<') -1 else 1) if (!isCollision(nextPos, rock)) pos = nextPos nextPos = pos.dY(-1) if (!isCollision(nextPos, rock)) { pos = nextPos } else { break; } } while (true) stop(pos, rock) } } fun main() { val testInput = """>>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>""".split("\n") val rocks = listOf( listOf("####"), listOf( ".#.", "###", ".#.", ), listOf( "..#", "..#", "###", ), listOf( "#", "#", "#", "#", ), listOf( "##", "##", ) ) fun supplyRocks(jetString: String, count: Int): Room { val rockSupply = rocks.asSequence().repeatForever().iterator() val jets = jetString.asSequence().repeatForever().iterator() val room = Room(jets, rockSupply) repeat(count) { room.addRock() } return room } fun part1(input: List<String>): Int { val room = supplyRocks(input[0], 2022) return room.highest + 1 } fun part2(input: List<String>): Int { println(rocks.size) val jetString = input[0] println(jetString.length) val supplyLoop = rocks.size * jetString.length val room = supplyRocks(jetString, supplyLoop) sequence { while(true) { yield(room.highest) room.addRocks(supplyLoop) } }.zipWithNext { a,b -> b-a}.take(100).forEach { println(it) } return -1; } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 3068) val puzzleInput = InputUtils.downloadAndGetLines(2022, 17).toList() println(part1(puzzleInput)) println(part2(testInput)) println(part2(puzzleInput)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
3,929
aoc-2022-kotlin
Apache License 2.0
src/year_2022/day_23/Day23.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2022.day_23 import readInput import util.* enum class Direction { NORTH, SOUTH, WEST, EAST, ; companion object { fun byOrder(order: Int): Direction { return when(order) { 1 -> NORTH 2 -> SOUTH 3 -> WEST 0 -> EAST else -> throw IllegalArgumentException() } } } } class Day23(text: List<String>) { private val originalElfPositions = parseText(text) fun solutionOne(debug: Boolean = false): Int { val currentPoints = originalElfPositions.toMutableList() for (round in 1..10) { val proposals = currentPoints.map { point -> val proposedPosition = proposeLocation( point = point, priorityDirection = Direction.byOrder(round % 4), currentPoints = currentPoints ) point to proposedPosition } val approvedProposals = proposals .groupBy { it.second } .filter { it.value.size == 1 } .map { it.key } proposals .filter { (_, proposed) -> proposed in approvedProposals } .forEach { (current, approved) -> currentPoints.remove(current) currentPoints.add(approved) } if (debug) { println("== End of Round $round ==") val minX = currentPoints.minOfOrNull { it.first }!! val maxX = currentPoints.maxOfOrNull { it.first }!! val minY = currentPoints.minOfOrNull { it.second }!! val maxY = currentPoints.maxOfOrNull { it.second }!! for (row in minY..maxY) { for (col in minX .. maxX) { if (col to row in currentPoints) { print("#") } else { print(".") } } println() } } } val minX = currentPoints.minOfOrNull { it.first }!! val maxX = currentPoints.maxOfOrNull { it.first }!! val minY = currentPoints.minOfOrNull { it.second }!! val maxY = currentPoints.maxOfOrNull { it.second }!! var totalEmpty = 0 for (row in minY..maxY) { for (col in minX .. maxX) { if (col to row !in currentPoints) { totalEmpty += 1 } } } return totalEmpty } fun solutionTwo(debug: Boolean = false): Int { val currentPoints = originalElfPositions.toMutableList() var round = 1 println("Total elves: ${currentPoints.size}") while (true) { val proposals = currentPoints.map { point -> val proposedPosition = proposeLocation( point = point, priorityDirection = Direction.byOrder(round % 4), currentPoints = currentPoints ) point to proposedPosition } // if no one needs to move then we alllll good if (debug) { println("Round $round - moving ${proposals.count { it.first != it.second }} elves.") } if (proposals.all { it.first == it.second }) { break } val approvedProposals = proposals .groupBy { it.second } .filter { it.value.size == 1 } .map { it.key } proposals .filter { (_, proposed) -> proposed in approvedProposals } .forEach { (current, approved) -> currentPoints.remove(current) currentPoints.add(approved) } if (debug) { println("== End of Round $round ==") val minX = currentPoints.minOfOrNull { it.first }!! val maxX = currentPoints.maxOfOrNull { it.first }!! val minY = currentPoints.minOfOrNull { it.second }!! val maxY = currentPoints.maxOfOrNull { it.second }!! for (row in minY..maxY) { for (col in minX .. maxX) { if (col to row in currentPoints) { print("#") } else { print(".") } } println() } } round += 1 } return round } private fun parseText(text: List<String>): List<Point> { return text.flatMapIndexed { row, rowString -> rowString.mapIndexedNotNull { col, letter -> if (letter == '#') { Point(col, row) } else { null } } } } private fun proposeLocation(point: Point, priorityDirection: Direction, currentPoints: List<Point>): Point { if (evaluateAlone(point, currentPoints)) { return point } return when (priorityDirection) { Direction.NORTH -> { if (evaluateNorth(point, currentPoints)) { point.up() } else if (evaluateSouth(point, currentPoints)) { point.down() } else if (evaluateWest(point, currentPoints)) { point.left() } else if (evaluateEast(point, currentPoints)) { point.right() } else { point } } Direction.SOUTH -> { if (evaluateSouth(point, currentPoints)) { point.down() } else if (evaluateWest(point, currentPoints)) { point.left() } else if (evaluateEast(point, currentPoints)) { point.right() } else if (evaluateNorth(point, currentPoints)) { point.up() } else { point } } Direction.WEST -> { if (evaluateWest(point, currentPoints)) { point.left() } else if (evaluateEast(point, currentPoints)) { point.right() } else if (evaluateNorth(point, currentPoints)) { point.up() } else if (evaluateSouth(point, currentPoints)) { point.down() } else { point } } Direction.EAST -> { if (evaluateEast(point, currentPoints)) { point.right() } else if (evaluateNorth(point, currentPoints)) { point.up() } else if (evaluateSouth(point, currentPoints)) { point.down() } else if (evaluateWest(point, currentPoints)) { point.left() } else { point } } } } private fun evaluateAlone(point: Point, currentPoints: List<Point>): Boolean { return point.upLeft() !in currentPoints && point.up() !in currentPoints && point.upRight() !in currentPoints && point.right() !in currentPoints && point.downRight() !in currentPoints && point.down() !in currentPoints && point.downLeft() !in currentPoints && point.left() !in currentPoints } private fun evaluateNorth(point: Point, currentPoints: List<Point>): Boolean { return point.upLeft() !in currentPoints && point.up() !in currentPoints && point.upRight() !in currentPoints } private fun evaluateSouth(point: Point, currentPoints: List<Point>): Boolean { return point.downLeft() !in currentPoints && point.down() !in currentPoints && point.downRight() !in currentPoints } private fun evaluateEast(point: Point, currentPoints: List<Point>): Boolean { return point.upRight() !in currentPoints && point.right() !in currentPoints && point.downRight() !in currentPoints } private fun evaluateWest(point: Point, currentPoints: List<Point>): Boolean { return point.upLeft() !in currentPoints && point.left() !in currentPoints && point.downLeft() !in currentPoints } } fun main() { val inputText = readInput("year_2022/day_23/Day23.txt") val day = Day23(text = inputText) println("Solution 1: ${day.solutionOne()}") println("Solution 2: ${day.solutionTwo()}") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
9,055
advent_of_code
Apache License 2.0
src/Day02.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
fun main() { fun part1(input: List<String>): Int { return input.size } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: // shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) val input = readInput("day2_input") var totalScore = 0 input.forEach { val opponent = it.split(" ")[0] val myself = it.split(" ")[1] // println("opponent $opponent myself $myself") totalScore += getGameScore2(opponent, myself) } println(totalScore) } private fun getGameScore2(opponent: String, myself: String): Int { var shapeScore = 0 val gameScore = when (myself) { "X" -> { shapeScore = getLoseScore(opponent) 0 } "Y" -> { shapeScore = getDrawScore(opponent) 3 } else -> { shapeScore = getWinScore(opponent) 6 } } return shapeScore + gameScore } //shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) private fun getLoseScore(letter: String): Int { return when(letter) { "A" -> 3 "B" -> 1 "C" -> 2 else -> -1000000 } } //shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) private fun getDrawScore(letter: String): Int { return when(letter) { "A" -> 1 "B" -> 2 "C" -> 3 else -> -1000000 } } //shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) private fun getWinScore(letter: String): Int { return when(letter) { "A" -> 2 "B" -> 3 "C" -> 1 else -> -1000000 } } private fun getShapeScore2(letter: String): Int { return when(letter) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> -1000000 } } // A for Rock, B for Paper, and C for Scissors // X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. // outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won). private fun getGameScore(opponent: String, myself: String): Int { return if ((opponent == "A" && myself == "X") || (opponent == "B" && myself == "Y") || (opponent == "C" && myself == "Z")) { 3 //draw } else if ((opponent == "A" && myself == "Y") || (opponent == "B" && myself == "Z") || (opponent == "C" && myself == "X") ){ 6 } else { 0 } } private fun getShapeScore(letter: String): Int { return when(letter) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> -1000000 } }
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
2,684
advent22
Apache License 2.0
src/Day12.kt
felldo
572,233,925
false
{"Kotlin": 76496}
import java.lang.Integer.min fun main() { fun buildMinMountain(mountain: Array<Array<Int>>, ey: Int, ex: Int): Array<Array<Int>> { val minMountain = Array(mountain.size) { Array(mountain[0].size) { Int.MAX_VALUE - 10 } } minMountain[ey][ex] = 0 var changed = true while (changed) { changed = false for (y in mountain.indices) { for (x in mountain[y].indices) { // UP if (y > 0 && mountain[y-1][x] <= mountain[y][x] + 1 && minMountain[y-1][x] + 1 < minMountain[y][x]) { minMountain[y][x] = minMountain[y-1][x] + 1 changed = true } // DOWN if (y < mountain.size - 1 && mountain[y+1][x] <= mountain[y][x] + 1 && minMountain[y+1][x] + 1 < minMountain[y][x]) { minMountain[y][x] = minMountain[y+1][x] + 1 changed = true } // LEFT if (x > 0 && mountain[y][x-1] <= mountain[y][x] + 1 && minMountain[y][x-1] + 1 < minMountain[y][x]) { minMountain[y][x] = minMountain[y][x-1] + 1 changed = true } // RIGHT if (x < mountain[0].size - 1 && mountain[y][x+1] <= mountain[y][x] + 1 && minMountain[y][x+1] + 1 < minMountain[y][x]) { minMountain[y][x] = minMountain[y][x+1] + 1 changed = true } } } } return minMountain } fun part1(input: List<String>): Int { val mountain = Array<Array<Int>>(input.size) { Array(input[0].length) { 0 } } var sy = 0 var sx = 0 var ey = 0 var ex = 0 for (y in input.indices) { for (x in 0 until input[y].length) { if (input[y][x] == 'S') { sy = y sx = x mountain[y][x] = 0 } else if (input[y][x] == 'E') { ey = y ex = x mountain[y][x] = 25 } else { mountain[y][x] = input[y][x] - 'a' } } } val minMountain = buildMinMountain(mountain, ey, ex) return minMountain[sy][sx] } fun part2(input: List<String>): Int { val mountain = Array<Array<Int>>(input.size) { Array(input[0].length) { 0 } } var ey = 0 var ex = 0 for (y in input.indices) { for (x in 0 until input[y].length) { if (input[y][x] == 'S') { mountain[y][x] = 0 } else if (input[y][x] == 'E') { ey = y ex = x mountain[y][x] = 25 } else { mountain[y][x] = input[y][x] - 'a' } } } val minMountain = buildMinMountain(mountain, ey, ex) var minPath = Int.MAX_VALUE for (y in input.indices) { for (x in 0 until input[y].length) { if (input[y][x] == 'a' || input[y][x] == 'S') { minPath = min(minPath, minMountain[y][x]) } } } return minPath } val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
3,529
advent-of-code-kotlin-2022
Apache License 2.0
src/day13/a/day13a.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day13.a import readInputLines import shouldBe fun main() { val msg = read() var r = 0 var i = 0 for (p in msg) { i++ val (m0, m1) = p if (m0 < m1) r += i } shouldBe(6187, r) } data class Message( val list : List<*> ) : Comparable<Message> { constructor(v: Int): this(listOf(v)) override fun toString(): String { return list.toString() } override operator fun compareTo(other: Message): Int { val it0 = this.list.iterator() val it1 = other.list.iterator() while (it0.hasNext() && it1.hasNext()) { var v0 = it0.next() var v1 = it1.next() var d : Int if (v0 is Int && v1 is Int) { d = v0 - v1 } else { if (v0 is Int) v0 = Message(v0) if (v1 is Int) v1 = Message(v1) v0 as Message v1 as Message d = v0.compareTo(v1) } if (d != 0) return d } if (it0.hasNext()) return 1 if (it1.hasNext()) return -1 return 0 } } fun read(): ArrayList<Pair<Message, Message>> { val r = ArrayList<Pair<Message, Message>>() val lines = readInputLines(13) val it = lines.iterator() while(it.hasNext()) { val s0 = it.next() val s1 = it.next() val m0 = parse(s0, 0) val m1 = parse(s1, 0) r.add(Pair(m0.second,m1.second)) if (it.hasNext()) it.next() } return r } fun parse(s: String, start: Int): Pair<Int, Message> { val l = ArrayList<Any>() var i = start + 1 while (true) { when (s[i]) { '[' -> { val p = parse(s, i) i = p.first + 1 l.add(p.second) } ']' -> return Pair(i, Message(l)) ',' -> i++ else -> { val j = i while (s[i] in '0'..'9') i++ val v = s.substring(j, i).toInt() l.add(v) } } } }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
2,089
advent-of-code-2022
Apache License 2.0
kotlin/src/test/kotlin/be/swsb/aoc2023/day9/Solve.kt
Sch3lp
724,797,927
false
{"Kotlin": 44815, "Rust": 14075}
package be.swsb.aoc2023.day9 import be.swsb.aoc2023.readFile import io.kotest.matchers.equals.shouldBeEqual import org.junit.jupiter.api.Test class Solve { private val exampleInput = "2023/day9/exampleInput.txt" private val actualInput = "2023/day9/input.txt" private fun parse(input: String) = input.lines().map { line -> line.split(" ").map { it.toLong() } } @Test fun `solve - part 1 - example input`() { val sequences: List<List<Long>> = parse(readFile(exampleInput)) val actual = sequences.sumOf { sequence -> predict(sequence) } actual shouldBeEqual 114 } @Test fun `solve - part 1 - actual`() { val sequences: List<List<Long>> = parse(readFile(actualInput)) val actual = sequences.sumOf { sequence -> predict(sequence) } actual shouldBeEqual 1757008019 } @Test fun `solve - part 2 - example input`() { val sequences: List<List<Long>> = parse(readFile(exampleInput)) val actual = sequences.sumOf { sequence -> predict(sequence, true) } actual shouldBeEqual 2 } @Test fun `solve - part 2 - actual`() { val sequences: List<List<Long>> = parse(readFile(actualInput)) val actual = sequences.sumOf { sequence -> predict(sequence, true) } actual shouldBeEqual 995 } @Test fun `generateNextSequence - generates sequence based on the differences between the numbers`() { val sequence1 = listOf(0L, 3L, 6L, 9L, 12L, 15L) generateNextSequenceFrom(sequence1) shouldBeEqual listOf(3L, 3L, 3L, 3L, 3L) } @Test fun `predict - uses generated sequences to predict next value`() { predict(listOf(0L, 3L, 6L, 9L, 12L, 15L)) shouldBeEqual 18L predict(listOf(1L, 3L, 6L, 10L, 15L, 21L)) shouldBeEqual 28L predict(listOf(10L, 13L, 16L, 21L, 30L, 45L)) shouldBeEqual 68L } @Test fun `predictBackwards - uses generated sequences to predict next value backwards`() { predict(listOf(0L, 3L, 6L, 9L, 12L, 15L), true) shouldBeEqual -3L predict(listOf(1L, 3L, 6L, 10L, 15L, 21L), true) shouldBeEqual 0L predict(listOf(10L, 13L, 16L, 21L, 30L, 45L), true) shouldBeEqual 5L } }
0
Kotlin
0
1
dec9331d3c0976b4de09ce16fb8f3462e6f54f6e
2,222
Advent-of-Code-2023
MIT License
src/main/kotlin/_2018/Day7.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2018 import aocRun import java.util.regex.Pattern import kotlin.math.min private val pattern = Pattern.compile("Step (?<step1>.) must be finished before step (?<step2>.) can begin") fun main() { aocRun(puzzleInput) { input -> val steps = processSteps(input) //println("Steps:\n$steps") val allSteps = allSteps(steps) //println("All steps:\n$allSteps") val groupedSteps = steps.groupByTo(mutableMapOf(), { it.second }, { it.first }) val stepOrder = StringBuilder() val stepsWithoutRequirements = allSteps.filter { !groupedSteps.keys.contains(it) }.sorted().toMutableList() do { //println("\nSteps grouped:\n$groupedSteps") println("Steps without requirements:\n$stepsWithoutRequirements") val next = stepsWithoutRequirements[0] println("Adding next step: $next") stepOrder.append(next) groupedSteps.remove(next) stepsWithoutRequirements.remove(next) groupedSteps.forEach { (step, req) -> if (req.remove(next)) println("Removed requirement $next from step $step") if (req.isEmpty() && !stepsWithoutRequirements.contains(step)) stepsWithoutRequirements += step } stepsWithoutRequirements.sort() } while (stepsWithoutRequirements.isNotEmpty()) return@aocRun stepOrder.toString() } aocRun(puzzleInput) { input -> val steps = processSteps(input) println("Steps:\n$steps") val allSteps = allSteps(steps) val durations = allSteps.associateWith { it.toInt() - 4 } println(durations) val groupedSteps = steps.groupByTo(mutableMapOf(), { it.second }, { it.first }) val stepOrder = StringBuilder() val stepsProcessing = mutableMapOf<Char, Int>() val stepsWithoutRequirements = allSteps.filter { !groupedSteps.keys.contains(it) }.sorted().toMutableList() val numWorkers = 5 var curTime = 0 do { println("\nTime: $curTime") println("Processing:\n$stepsProcessing") // Update steps being processed val finished = mutableListOf<Char>() val processingIter = stepsProcessing.iterator() while (processingIter.hasNext()) { val entry = processingIter.next() entry.setValue(entry.value - 1) if (entry.value <= 0) { val c = entry.key println("Step $c finished") finished += c processingIter.remove() groupedSteps.remove(c) groupedSteps.forEach { (step, req) -> if (req.remove(c)) { println("Removed requirement $c from step $step") if (req.isEmpty() && !stepsWithoutRequirements.contains(step)) stepsWithoutRequirements += step } } } } // Add finished steps to stepOrder if (finished.isNotEmpty()) { finished.sort() finished.forEach { stepOrder.append(it) } } // Try give workers more steps to process stepsWithoutRequirements.sort() val numWorking = stepsProcessing.size if (numWorking < numWorkers) { repeat(min(numWorkers - numWorking, stepsWithoutRequirements.size)) { println("Steps without requirements: $stepsWithoutRequirements") val next = stepsWithoutRequirements[0] println("Adding next step: $next") stepsProcessing[next] = durations.getValue(next) stepsWithoutRequirements.remove(next) } } curTime++ } while (stepsWithoutRequirements.isNotEmpty() || stepsProcessing.isNotEmpty()) println("\nOrder: $stepOrder") return@aocRun curTime - 1 } } private fun processSteps(input: String): List<Pair<Char, Char>> = input.split("\n").map { val matcher = pattern.matcher(it) if (!matcher.find()) throw RuntimeException("Not a valid input! -> '$it'") return@map Pair(matcher.group("step1")[0], matcher.group("step2")[0]) } private fun allSteps(input: List<Pair<Char, Char>>): MutableList<Char> { val all = mutableListOf<Char>() input.forEach { if (!all.contains(it.first)) all += it.first if (!all.contains(it.second)) all += it.second } all.sort() return all } private val testInput = """ Step C must be finished before step A can begin. Step C must be finished before step F can begin. Step A must be finished before step B can begin. Step A must be finished before step D can begin. Step B must be finished before step E can begin. Step D must be finished before step E can begin. Step F must be finished before step E can begin. """.trimIndent() private val puzzleInput = """ Step I must be finished before step G can begin. Step J must be finished before step A can begin. Step L must be finished before step D can begin. Step V must be finished before step S can begin. Step U must be finished before step T can begin. Step F must be finished before step Z can begin. Step D must be finished before step A can begin. Step E must be finished before step Z can begin. Step C must be finished before step Q can begin. Step H must be finished before step X can begin. Step A must be finished before step Z can begin. Step Z must be finished before step M can begin. Step P must be finished before step Y can begin. Step N must be finished before step K can begin. Step R must be finished before step W can begin. Step K must be finished before step O can begin. Step W must be finished before step S can begin. Step G must be finished before step Q can begin. Step Q must be finished before step B can begin. Step S must be finished before step T can begin. Step B must be finished before step M can begin. Step T must be finished before step Y can begin. Step M must be finished before step O can begin. Step X must be finished before step O can begin. Step O must be finished before step Y can begin. Step C must be finished before step O can begin. Step B must be finished before step O can begin. Step T must be finished before step O can begin. Step S must be finished before step X can begin. Step E must be finished before step K can begin. Step Q must be finished before step M can begin. Step E must be finished before step P can begin. Step Q must be finished before step S can begin. Step E must be finished before step O can begin. Step D must be finished before step P can begin. Step X must be finished before step Y can begin. Step I must be finished before step U can begin. Step B must be finished before step X can begin. Step F must be finished before step T can begin. Step B must be finished before step T can begin. Step V must be finished before step R can begin. Step I must be finished before step Q can begin. Step I must be finished before step A can begin. Step M must be finished before step X can begin. Step Z must be finished before step S can begin. Step C must be finished before step S can begin. Step T must be finished before step M can begin. Step K must be finished before step X can begin. Step Z must be finished before step P can begin. Step V must be finished before step H can begin. Step Z must be finished before step B can begin. Step M must be finished before step Y can begin. Step C must be finished before step K can begin. Step W must be finished before step Y can begin. Step J must be finished before step Z can begin. Step Q must be finished before step O can begin. Step T must be finished before step X can begin. Step P must be finished before step Q can begin. Step P must be finished before step K can begin. Step D must be finished before step M can begin. Step P must be finished before step N can begin. Step S must be finished before step B can begin. Step H must be finished before step Y can begin. Step R must be finished before step K can begin. Step G must be finished before step S can begin. Step P must be finished before step S can begin. Step C must be finished before step Z can begin. Step Q must be finished before step Y can begin. Step F must be finished before step R can begin. Step N must be finished before step B can begin. Step G must be finished before step M can begin. Step E must be finished before step X can begin. Step D must be finished before step E can begin. Step D must be finished before step C can begin. Step U must be finished before step O can begin. Step H must be finished before step Z can begin. Step L must be finished before step C can begin. Step L must be finished before step F can begin. Step V must be finished before step D can begin. Step F must be finished before step X can begin. Step V must be finished before step W can begin. Step S must be finished before step Y can begin. Step K must be finished before step T can begin. Step D must be finished before step Z can begin. Step C must be finished before step W can begin. Step V must be finished before step M can begin. Step F must be finished before step H can begin. Step A must be finished before step M can begin. Step G must be finished before step Y can begin. Step H must be finished before step M can begin. Step N must be finished before step W can begin. Step J must be finished before step K can begin. Step C must be finished before step B can begin. Step Z must be finished before step Y can begin. Step L must be finished before step E can begin. Step G must be finished before step B can begin. Step Q must be finished before step T can begin. Step D must be finished before step W can begin. Step H must be finished before step G can begin. Step L must be finished before step O can begin. Step N must be finished before step O can begin. """.trimIndent()
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
10,139
AdventOfCode
Creative Commons Zero v1.0 Universal
year2022/src/cz/veleto/aoc/year2022/Day23.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay import cz.veleto.aoc.core.Pos import cz.veleto.aoc.core.plus import cz.veleto.aoc.core.rotateBy class Day23(config: Config) : AocDay(config) { override fun part1(): String { var elves = parseElves() for (round in 1..10) { elves = moveElves(round, elves) } val minX = elves.minOf { (x, _) -> x } val maxX = elves.maxOf { (x, _) -> x } val minY = elves.minOf { (_, y) -> y } val maxY = elves.maxOf { (_, y) -> y } val rectSize = (maxX - minX + 1) * (maxY - minY + 1) return (rectSize - elves.size).toString() } override fun part2(): String { var elves = parseElves() var round = 0 var anyElvesMoved = true while (anyElvesMoved) { round++ val newElves = moveElves(round, elves) anyElvesMoved = newElves != elves if (config.log) println("Round $round, movedElves ${(newElves - elves).size}") elves = newElves } return round.toString() } private fun parseElves(): Set<Pair<Int, Int>> = input.flatMapIndexed { x: Int, line: String -> line.mapIndexedNotNull { y, c -> if (c == '#') x to y else null } }.toSet() private fun moveElves(round: Int, elves: Set<Pos>): Set<Pos> { // first half val directions = Direction.entries.map { it.rotateBy(round - 1) } val proposedMoves = mutableMapOf<Pos, List<Pos>>() // proposed pos, to proposing elves val surroundedElves = mutableSetOf<Pos>() for (elf in elves) { val emptyDirections: List<Direction> = directions.filter { direction -> direction.neighborFov.all { (elf + it) !in elves } } if (emptyDirections.isEmpty() || emptyDirections.size == Direction.entries.size) { surroundedElves += elf } else { val proposedMove = elf + emptyDirections.first().neighborFov[1] val oldProposingElves = proposedMoves[proposedMove] ?: emptyList() proposedMoves[proposedMove] = oldProposingElves + elf } } // second half val collidingElves = mutableSetOf<Pos>() val movedElves = mutableSetOf<Pos>() for ((proposedMove, proposingElves) in proposedMoves) { if (proposingElves.size == 1) { movedElves += proposedMove } else { collidingElves += proposingElves } } val newElves = surroundedElves + collidingElves + movedElves check(newElves.size == elves.size) return newElves } private enum class Direction(val neighborFov: List<Pos>) { North(listOf(-1 to -1, -1 to 0, -1 to 1)), South(listOf(1 to -1, 1 to 0, 1 to 1)), West(listOf(-1 to -1, 0 to -1, 1 to -1)), East(listOf(-1 to 1, 0 to 1, 1 to 1)), } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
3,006
advent-of-pavel
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CarPooling.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import java.util.TreeMap /** * 1094. Car Pooling * @see <a href="https://leetcode.com/problems/car-pooling/">Source</a> */ fun interface CarPooling { operator fun invoke(trips: Array<IntArray>, capacity: Int): Boolean } class ThousandOneStops : CarPooling { companion object { private const val STOPS = 1001 } override operator fun invoke(trips: Array<IntArray>, capacity: Int): Boolean { val nums = IntArray(STOPS) for (trip in trips) { if (trip.isEmpty()) return false for (i in trip[1] until trip[2]) { // put load in index range [getUpStop, getOffStop) nums[i] += trip[0] } } for (num in nums) { if (num > capacity) return false } return true } } class CarPoolingMeetingRoom : CarPooling { override operator fun invoke(trips: Array<IntArray>, capacity: Int): Boolean { var c = capacity val m: MutableMap<Int, Int> = TreeMap() for (t in trips) { if (t.isEmpty()) return false m[t[1]] = (m[t[1]] ?: 0) + t[0] m[t[2]] = (m[t[2]] ?: 0) - t[0] } for (v in m.values) { c -= v if (c < 0) { return false } } return true } } class CarPoolingInterval : CarPooling { override operator fun invoke(trips: Array<IntArray>, capacity: Int): Boolean { if (trips.isEmpty() || capacity == 0) return false trips.sortWith(compareBy({ it[1] }, { it[2] })) val pq = PriorityQueue<IntArray>(compareBy({ it.first() }, { it.last() })).apply { trips.forEach { offer(intArrayOf(it[2], -it[0])) offer(intArrayOf(it[1], it[0])) } } var maxCount = 0 while (pq.isNotEmpty()) { maxCount += pq.poll().last() if (maxCount > capacity) return false } return true } } class CarPoolingStream : CarPooling { companion object { private const val STOPS = 1001 } override operator fun invoke(trips: Array<IntArray>, capacity: Int): Boolean { val count = IntArray(STOPS) for (t in trips) { if (t.isEmpty()) return false for (i in t[1] until t[2]) { count[i] += t[0] } } return count.max() <= capacity } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,101
kotlab
Apache License 2.0
11/part_two.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File const val LAST_DAY = 100 fun readInput() : Octopuses { val inputLines = File("input.txt") .readLines() .map { line -> line.split("") .filter { it.isNotEmpty() } .map{ it.toInt() }} return Octopuses(inputLines.map { it.toMutableList() }.toMutableList()) } class Octopuses(inputLines : MutableList<MutableList<Int>>) { companion object { const val ENERGY_TO_FLASH = 10 } var energy = inputLines var daysPassed = 0 var flashes = 0 private val rows = energy.size private val cols = energy[0].size fun passDay() { daysPassed++ updateEnergy() } private fun updateEnergy() { increaseEnergyLevel() startChainFlashes() resetFlashedEnergy() } private fun increaseEnergyLevel() { for (row in 0 until rows) { for (col in 0 until cols) { energy[row][col]++ } } } private fun startChainFlashes() { val queue = ArrayDeque<Pair<Int, Int>>() val flashedThisDay = mutableSetOf<Pair<Int, Int>>() for (row in 0 until rows) { for (col in 0 until cols) { if (energy[row][col] >= ENERGY_TO_FLASH) { flashedThisDay.add(Pair(row, col)) queue.add(Pair(row, col)) } } } while (queue.isNotEmpty()) { val (row, col) = queue.first() queue.removeFirst() val neighbors = getNeighbors(row, col) for (neighbor in neighbors) { energy[neighbor.first][neighbor.second]++ if (energy[neighbor.first][neighbor.second] >= ENERGY_TO_FLASH && neighbor !in flashedThisDay) { flashedThisDay.add(neighbor) queue.add(neighbor) } } } } private fun getNeighbors(row : Int, col : Int) : MutableList<Pair<Int, Int>> { val result = mutableListOf<Pair<Int, Int>>() for (i in -1..1) { for (j in -1.. 1) { if (isIn(row + i, col + j)) { result.add(Pair(row + i, col + j)) } } } return result } private fun isIn(row : Int, col : Int) : Boolean { return row in 0 until rows && col in 0 until cols } private fun resetFlashedEnergy() { for (row in 0 until rows) { for (col in 0 until cols) { if (energy[row][col] >= ENERGY_TO_FLASH) { flashes++ energy[row][col] = 0 } } } } } fun solve(octopuses : Octopuses) : Int { for (day in 1..LAST_DAY) { octopuses.passDay() } return octopuses.flashes } fun main() { val octopuses = readInput() val ans = solve(octopuses) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
3,004
advent-of-code-2021
MIT License
src/Day07.kt
Reivax47
572,984,467
false
{"Kotlin": 32685}
fun main() { fun part1(input: List<String>): Int { var monArbre = directory(arbre = input, parentname = "", "/", -1) directory.index = 1 monArbre.ComputeMyPart(input) var somme = 0 monArbre.getLespetits().forEach { it -> somme += it.totalSize() } return somme } fun part2(input: List<String>): Int { var monArbre = directory(arbre = input, parentname = "", "/", -1) directory.index = 1 monArbre.ComputeMyPart(input) val totaloccupe = monArbre.totalSize() val totallibre = 70000000 - totaloccupe val objectif = 30000000 - totallibre var reponse = monArbre.getlespretendants(objectif) reponse.sortedWith(compareBy { it.total_size }) return reponse[reponse.size - 1].total_size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) } class directory( val arbre: List<String>, val parentname: String, val name: String, val parentId: Int ) { companion object { var compteur_id = 0 var index = 1 } var id = 0 var directSize: Int = 0 val mesEnfants = mutableListOf<directory>() var lestoutepetits = mutableSetOf<directory>() var pretendant = mutableListOf<directory>() var total_size = 0 init { this.id = compteur_id++ } fun getLespetits(): MutableSet<directory> { var reponse = mutableSetOf<directory>() mesEnfants.forEach { it -> reponse.addAll(it.getLespetits()) if (it.totalSize() < 100000) { reponse.add(it) } } lestoutepetits.addAll(reponse) return lestoutepetits } fun getlespretendants(barriere: Int): MutableList<directory> { mesEnfants.forEach { it -> if (it.totalSize() >= barriere) { this.pretendant.add(it) } this.pretendant.addAll(it.getlespretendants(barriere)) } return this.pretendant } fun ComputeMyPart(arbo: List<String>) { while (arbo[index].substring(0, 4) == "$ ls") { index++ } while (index < arbo.size && arbo[index].substring(0, 4) != "$ cd") { if (arbo[index].substring(0, 3) == "dir") { this.mesEnfants.add(directory(arbo, this.name, arbo[index].substring(4), this.id)) } else { this.directSize += arbo[index].split(" ")[0].toInt() } index++ } while (index < arbo.size && arbo[index] != "$ cd ..") { val nom_enfant = arbo[index].substring(5) val enfant = mesEnfants.find { it.name == nom_enfant } if (enfant != null) { index++ enfant.ComputeMyPart(arbo) } } index++ } fun totalSize(): Int { var reponse = this.directSize mesEnfants.forEach { it -> reponse += it.totalSize() } this.total_size = reponse return reponse } }
0
Kotlin
0
0
0affd02997046d72f15d493a148f99f58f3b2fb9
3,300
AD2022-01
Apache License 2.0
src/leetcode_problems/medium/AddTwoNumbers.kt
MhmoudAlim
451,633,139
false
{"Kotlin": 31257, "Java": 586}
package leetcode_problems.medium /* https://leetcode.com/problems/add-two-numbers/ */ /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } * Example 1: * Input: l1 = [2,4,3], l2 = [5,6,4] * Output: [7,0,8] * Explanation: 342 + 465 = 807. * * Example 2: * Input: l1 = [0], l2 = [0] * Output: [0] * * Example 3: * Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] * Output: [8,9,9,9,0,0,0,1] */ /// 3(4(5)) class ListNode(var value: List<Int>) fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode { val ls1 = StringBuilder() val ls2 = StringBuilder() val resultNode = mutableListOf<Int>() (l1?.value?.reversed() ?: listOf()).forEach { i -> ls1.append(i) } for (i in l2?.value?.reversed() ?: listOf()) { ls2.append(i) } val result = ls1.toString().toInt() + ls2.toString().toInt() result.toString().forEach { resultNode.add(it.digitToInt()) } return ListNode(resultNode.reversed()) } fun main() { val ans = addTwoNumbers(l1 = ListNode(listOf(9,9,9,9,9,9,9)), l2 = ListNode(listOf(9,9,9,9))) println(ans.value) }
0
Kotlin
0
0
31f0b84ebb6e3947e971285c8c641173c2a60b68
1,225
Coding-challanges
MIT License
src/Day04.kt
robinpokorny
572,434,148
false
{"Kotlin": 38009}
private typealias Assignment = Pair<IntRange, IntRange> private fun parse(input: List<String>): List<Assignment> = input .map(fun(line): List<IntRange> { return line .split(",") .map { it.split("-").map(String::toInt) } .map { (first, second) -> first..second } }) .map { (first, second) -> first to second } private fun countFullyContaining(assignments: List<Assignment>): Int = assignments .count { (left, right) -> left.minus(right).isEmpty() or right.minus(left).isEmpty() } private fun countOverlapping(assignments: List<Assignment>): Int = assignments .count { (left, right) -> left.intersect(right).isNotEmpty() } fun main() { val input = parse(readDayInput(4)) val testInput = parse(rawTestInput) // PART 1 assertEquals(countFullyContaining(testInput), 2) println("Part1: ${countFullyContaining(input)}") // PART 2 assertEquals(countOverlapping(testInput), 4) println("Part2: ${countOverlapping(input)}") } private val rawTestInput = """ 2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8 """.trimIndent().lines()
0
Kotlin
0
2
56a108aaf90b98030a7d7165d55d74d2aff22ecc
1,133
advent-of-code-2022
MIT License
Jump_Game_II_v1.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
import kotlin.math.min class Solution { fun jump(nums: IntArray): Int { if (nums.isEmpty() || nums.size == 1) return 0 val minimumNumberOfJumps = IntArray(nums.size) { 0xffffff } minimumNumberOfJumps[0] = 0 var longest = 0 for ((i, j) in nums.withIndex()) { if (i + j <= longest) continue longest = i + j if (longest >= nums.lastIndex) return minimumNumberOfJumps[i] + 1 for (k in 1..j) { if (i + k >= nums.size) break minimumNumberOfJumps[i + k] = min(minimumNumberOfJumps[i + k], minimumNumberOfJumps[i] + 1) } } return minimumNumberOfJumps.last() } } fun main() { val solution = Solution() // 2 2 0 2 val testCases = arrayOf(intArrayOf(2, 3, 1, 1, 4), intArrayOf(2, 3, 0, 1, 4), intArrayOf(1), intArrayOf(7, 0, 9, 6, 9, 6, 1, 7, 9, 0, 1, 2, 9, 0, 3)) for (case in testCases) { println(solution.jump(case)) } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
999
leetcode
MIT License
src/main/kotlin/day2/Day2.kt
cyril265
433,772,262
false
{"Kotlin": 39445, "Java": 4273}
package day2 import readToList private val input = readToList("day2") fun main() { println(part1()) println(part2()) } private fun part1(): Int { val (horizontal, vertical) = splitInput() .partition { (direction, _) -> direction == "forward" } return horizontal.sumOf { (_, amount) -> amount } * vertical.sumOf { (direction, amount) -> if (direction == "down") amount else -amount } } private fun part2(): Int { var aim = 0 var position = 0 var depth = 0 splitInput().forEach { (direction, x) -> when (direction) { "forward" -> { position += x depth += aim * x } "down" -> { aim += x } else -> { aim -= x } } } return depth * position } private fun splitInput() = input.map { val (direction, amount) = it.split(" ") direction to amount.toInt() }
0
Kotlin
0
0
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
998
aoc2021
Apache License 2.0
src/Day20.kt
frungl
573,598,286
false
{"Kotlin": 86423}
import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { val list = MutableList (input.size) { i -> input[i].toInt() to i } val orig = list.toList() for ((i, index) in orig) { val pos = list.indexOf(i to index) var next = 0 if (i < 0) { if(pos >= -i) { next = pos + i } else { next = (list.size - 1) - abs(i + pos) % (list.size - 1) } } else { if(i <= (list.size - pos - 1)) { next = pos + i } else { next = (i - (list.size - pos - 1)) % (list.size - 1) } } list.removeAt(pos) list.add(next, i to index) } val n = list.indexOfFirst { it.first == 0 } return list[(n + 1000) % list.size].first + list[(n + 2000) % list.size].first + list[(n + 3000) % list.size].first } fun part2(input: List<String>): Long { val list = MutableList (input.size) { i -> input[i].toLong() * 811589153L to i } val orig = list.toList() repeat(10) { for ((i, index) in orig) { val pos = list.indexOf(i to index) var next = 0L if (i < 0) { if(pos >= -i) { next = pos + i } else { next = (list.size - 1L) - abs(i + pos) % (list.size - 1L) } } else { if(i <= (list.size - pos - 1)) { next = pos + i } else { next = (i - (list.size - pos - 1L)) % (list.size - 1L) } } list.removeAt(pos) list.add(next.toInt(), i to index) } } val n = list.indexOfFirst { it.first == 0L } return list[(n + 1000) % list.size].first + list[(n + 2000) % list.size].first + list[(n + 3000) % list.size].first } val testInput = readInput("Day20_test") check(part1(testInput) == 3) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
2,314
aoc2022
Apache License 2.0
src/Day09.kt
hottendo
572,708,982
false
{"Kotlin": 41152}
import kotlin.math.absoluteValue import kotlin.math.max private data class Knot(var x: Int = 0, var y: Int = 0) { fun getXY(): Pair<Int, Int> { return Pair(x, y) } fun step(direction: String) { when (direction) { "R" -> x++ "U" -> y-- "D" -> y++ "L" -> x-- "UR" -> { y-- x++ } "RD" -> { x++ y++ } "DL" -> { y++ x-- } "LU" -> { x-- y-- } else -> { println("ERROR: operator $direction is invalid!") } } } } private class Rope(val noOfTailKnots: Int = 1) { var head = Knot() val tailKnots = Array<Knot>(noOfTailKnots){Knot()} val tailPositions = mutableSetOf(Pair<Int, Int>(tailKnots.last().x, tailKnots.last().y)) fun moveNext(x: Int, y: Int, knot: Knot): Pair<Int, Int> { val distance = max((x - knot.x).absoluteValue, (y - knot.y).absoluteValue) if (distance > 1) { val tailDirection = calcTailStep(x, y, knot.x, knot.y) knot.step(tailDirection) } return Pair(knot.x, knot.y) } fun move(direction: String, steps: Int) { println("Dir: $direction\tSteps: $steps") for (i in 0 until steps) { head.step(direction) var (x, y) = head.getXY() for (j in 0 until noOfTailKnots) { with(moveNext(x, y, tailKnots[j])) { x = first; y = second } } tailPositions.add(Pair(x, y)) // println("Tail step: $tailDirection 1") } } fun calcTailStep(x1: Int, y1: Int, x2: Int, y2: Int): String { var direction = "" val dy = y1 - y2 val dx = x1 - x2 if (dy < 0) { direction = "U" if (dx < 0) { direction = "LU" } if (dx > 0) { direction = "UR" } } if (dy > 0) { direction = "D" if (dx > 0) { direction = "RD" } if (dx < 0) { direction = "DL" } } if (dy == 0) { if (dx < 0) { direction = "L" } if (dx > 0) { direction = "R" } } return direction } } fun main() { fun check(): Int { return 0 } fun part1(input: List<String>): Int { val score: Int val rope = Rope(1) for (cmd in input) { val tokens = cmd.split(' ') val dir = tokens.first() val steps = tokens.last().toInt() rope.move(dir, steps) // calculate tail move } score = rope.tailPositions.size return score } fun part2(input: List<String>): Int { val score: Int val rope = Rope(9) for (cmd in input) { val tokens = cmd.split(' ') val dir = tokens.first() val steps = tokens.last().toInt() rope.move(dir, steps) // calculate tail move } score = rope.tailPositions.size return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) println("Part 1 (Test): ${part1(testInput)}") check(part2(testInput) == 1) println("Part 2.1 (Test): ${part2(testInput)}") val testInput2 = readInput("Day09_2_test") check(part2(testInput2) == 36) println("Part 2.1 (Test): ${part2(testInput2)}") val input = readInput("Day09") println("Part 1 : ${part1(input)}") println("Part 2 : ${part2(input)}") }
0
Kotlin
0
0
a166014be8bf379dcb4012e1904e25610617c550
3,935
advent-of-code-2022
Apache License 2.0
2023/src/main/kotlin/sh/weller/aoc/Day04.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.aoc object Day04 : SomeDay<Pair<List<Int>, List<Int>>, Int> { override fun partOne(input: List<Pair<List<Int>, List<Int>>>): Int = input .map { (winningNumbers, havingNumbers) -> val numberOfWinningNumbers = havingNumbers .filter { it in winningNumbers } .size if (numberOfWinningNumbers > 0) { var result = 1 repeat(numberOfWinningNumbers - 1) { result *= 2 } return@map result } return@map 0 } .sum() override fun partTwo(input: List<Pair<List<Int>, List<Int>>>): Int { val cards = input .map { (winningNumbers, havingNumbers) -> Triple(1, winningNumbers, havingNumbers) } .toMutableList() for (i in 0..<cards.size) { val (numberOfCopies, winningNumbers, havingNumbers) = cards[i] val numberOfMatches = getNumberOfMatches(winningNumbers, havingNumbers) for (j in i + 1..i + numberOfMatches) { val card = cards .getOrNull(j) ?: break cards[j] = card.copy(first = card.first + numberOfCopies) } } return cards .sumOf { it.first } } private fun getNumberOfMatches(winningNumbers: List<Int>, havingNumbers: List<Int>): Int = havingNumbers .filter { it in winningNumbers } .size }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
1,571
AdventOfCode
MIT License
src/main/java/challenges/cracking_coding_interview/trees_graphs/build_order/edge_removal/Question.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.trees_graphs.build_order.edge_removal object Question { private fun buildOrderWrapper( projects: Array<String>, dependencies: Array<Array<String>> ): Array<String?> { val buildOrder = findBuildOrder(projects, dependencies) ?: return emptyArray() return convertToStringList(buildOrder) } private fun findBuildOrder(projects: Array<String>, dependencies: Array<Array<String>>): Array<Project?>? { val graph = buildGraph(projects, dependencies) return orderProjects(graph.nodes) } /* * Build the graph, adding the edge (a, b) if b is dependent on a. * Assumes a pair is listed in “build order”. The pair (a, b) in * dependencies indicates that b depends on a and a must be built * before b. * */ private fun buildGraph(projects: Array<String>, dependencies: Array<Array<String>>): Graph { val graph = Graph() for (project in projects) { graph.getOrCreateNode(project) } for (dependency in dependencies) { val first = dependency[0] val second = dependency[1] graph.addEdge(first, second) } return graph } private fun orderProjects(projects: List<Project>): Array<Project?>? { val order = arrayOfNulls<Project>(projects.size) /* Add “roots” to the build order first.*/ var endOfList = addNonDependent(order, projects, 0) var toBeProcessed = 0 while (toBeProcessed < order.size) { /* We have a circular dependency since there are no remaining * projects with zero dependencies. */ val current = order[toBeProcessed] ?: return null /* Remove myself as a dependency. */ val children = current.children for (child in children) { child.decrementDependencies() } /* Add children that have no one depending on them. */ endOfList = addNonDependent(order, children, endOfList) toBeProcessed++ } return order } /* A helper function to insert projects with zero dependencies * into the order array, starting at index offset. * */ private fun addNonDependent(order: Array<Project?>, projects: List<Project>, _offset: Int): Int { var offset = _offset for (project in projects) { if (project.numberDependencies == 0) { order[offset] = project offset++ } } return offset } private fun convertToStringList(projects: Array<Project?>): Array<String?> { val buildOrder = arrayOfNulls<String>(projects.size) for (i in projects.indices) { buildOrder[i] = projects[i]!!.name } return buildOrder } @JvmStatic fun main(args: Array<String>) { val projects = arrayOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") val dependencies = arrayOf( arrayOf("a", "b"), arrayOf("b", "c"), arrayOf("a", "c"), arrayOf("d", "e"), arrayOf("b", "d"), arrayOf("e", "f"), arrayOf("a", "f"), arrayOf("h", "i"), arrayOf("h", "j"), arrayOf("i", "j"), arrayOf("g", "j") ) val buildOrder = buildOrderWrapper(projects, dependencies) if (buildOrder.isEmpty()) { println("Circular Dependency.") } else { for (s in buildOrder) { println(s) } } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,690
CodingChallenges
Apache License 2.0
dsalgo/src/commonMain/kotlin/com/nalin/datastructurealgorithm/ds/AVLTree.kt
nalinchhajer1
534,780,196
false
{"Kotlin": 86359, "Ruby": 1605}
package com.nalin.datastructurealgorithm.ds import kotlin.math.abs import kotlin.math.max /** * AVL Tree: * Creates a self balancing Binary tree * Left is smaller than parent and right is greater than or equal to parent */ class AVLTree<T : Comparable<T>> : BSTTree<T> { private var rootNode: BSTNode<T>? = null private var count = 0 override fun root(): BSTNode<T>? { return rootNode } /** * Insert given value on BST */ override fun insert(value: T) { this.rootNode = _insertInBST(this.rootNode, value); } /** * Count */ fun size(): Int { return count } private fun _insertInBST(node: BSTNode<T>?, value: T): BSTNode<T> { if (node == null) { count++; return BSTNode(value) } if (node.value == value) { node.count++ count++ return node } if (node.value < value) { node.rightNode = _insertInBST(node.rightNode, value) } else { node.leftNode = _insertInBST(node.leftNode, value) } node.height = node.maxChildHeight() + 1 // Balancing if (abs(node.balancingFactor()) > 1) { return this._rotate(node, value) } return node } private fun _rotate(node: BSTNode<T>, value: T): BSTNode<T> { val balance = node.balancingFactor() if (balance > 1 && node.leftNode != null) { if (node.leftNode!!.value > value) { // left left return _rightRotate(node) } else { // left right node.leftNode = _leftRotate(node.leftNode!!) return _rightRotate(node) } } else if (balance < 1 && node.rightNode != null) { if (node.rightNode!!.value < value) { // right right return _leftRotate(node) } else { // right left node.rightNode = this._rightRotate(node.rightNode!!) return _leftRotate(node) } } return node; } // [c] -> [b,x] -> [a,y] // [b] -> [a,c] -> [y,x] private fun _rightRotate(parent: BSTNode<T>): BSTNode<T> { val child = parent.leftNode!! parent.leftNode = child.rightNode child.rightNode = parent parent.height = parent.maxChildHeight() + 1 child.height = child.maxChildHeight() + 1 return child } private fun _leftRotate(parent: BSTNode<T>): BSTNode<T> { val child = parent.rightNode!! parent.rightNode = child.leftNode child.leftNode = parent parent.height = parent.maxChildHeight() + 1 child.height = child.maxChildHeight() + 1 return child // child becomes parent } } fun <T : Comparable<T>> AVLTree<T>.height(): Int { return (root() as BSTNode).height } /** * AVL Tree node */ class BSTNode<T>( var value: T, var leftNode: BSTNode<T>? = null, var rightNode: BSTNode<T>? = null ) : BTreeNode<T> { var height: Int = 1 var count: Int = 1 // To manage duplicates inline fun balancingFactor(): Int { return (this.leftNode?.height ?: 0) - (this.rightNode?.height ?: 0) } inline fun maxChildHeight(): Int { return max(this.leftNode?.height ?: 0, this.rightNode?.height ?: 0) } override fun value(): T { return value } override fun leftNode(): BTreeNode<T>? { return leftNode } override fun rightNode(): BTreeNode<T>? { return rightNode } }
0
Kotlin
0
0
eca60301dab981d0139788f61149d091c2c557fd
3,644
kotlin-ds-algo
MIT License
src/day10/Day10.kt
pnavais
574,712,395
false
{"Kotlin": 54079}
package day10 import readInput import kotlin.text.StringBuilder class CycleRegister(private val frequency: Int = 20, private val step: Int = 40) { private var registerX: Int = 1 private val signalStrengths = mutableListOf<Int>() private var cycleNum = 0 private val rows = mutableListOf<String>() private val currentRow = StringBuilder() fun registerCycle(numCycles: Int, value: Int) { for (i in 1 .. numCycles) { cycleNum++ processSignal() } registerX+=value } fun getTotal(): Int { return signalStrengths.sum() } fun draw(): String { val builder = StringBuilder() for (row in rows) { builder.append(row) builder.append("\n") } return builder.toString() } private fun processSignal() { drawPixel() if ((cycleNum == frequency) || (cycleNum % step == frequency)) { signalStrengths.add(cycleNum * registerX) } if (currentRow.length % step == 0) { rows.add(currentRow.toString()) currentRow.clear() } } private fun drawPixel() { // Check if sprite overlaps current pos (i.e. currentRow length) var c = "." if ((registerX-1..registerX+1).contains(currentRow.length)) { c = "#" } currentRow.append(c) } } private fun processInput(input: List<String>): CycleRegister { val cycleRegister = CycleRegister() for (inst in input) { if (inst == "noop") { cycleRegister.registerCycle(1, 0) } else { val (_, data) = inst.split(" ") cycleRegister.registerCycle(2, data.toInt()) } } return cycleRegister } fun part1(input: List<String>): Int { return processInput(input).getTotal() } fun part2(input: List<String>): String { val cycleRegister = processInput(input) return cycleRegister.draw() } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day10/Day10_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
ed5f521ef2124f84327d3f6c64fdfa0d35872095
2,266
advent-of-code-2k2
Apache License 2.0
src/main/kotlin/adventofcode/year2015/Day13KnightsOfTheDinnerTable.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2015 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.permutations class Day13KnightsOfTheDinnerTable(customInput: PuzzleInput? = null) : Puzzle(customInput) { override val name = "Knights of the Dinner Table" private val happiness by lazy { input .lines() .associate { val (a, gainOrLose, amount, b) = INPUT_REGEX.find(it)!!.destructured Pair(a, b) to amount.toInt() * if (gainOrLose == "lose") -1 else 1 } } private val guests by lazy { input.lines().map { INPUT_REGEX.find(it)!!.destructured.component1() }.toSet() } override fun partOne() = guests.findOptimalSeatingArrangement(happiness) override fun partTwo() = (guests + "me").findOptimalSeatingArrangement(happiness) companion object { private val INPUT_REGEX = """(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+).""".toRegex() private fun List<String>.neighbors(guest: String) = when (val position = indexOf(guest)) { 0 -> listOf(last(), this[1]) size - 1 -> listOf(this[size - 2], first()) else -> listOf(this[position - 1], this[position + 1]) } private fun Set<String>.findOptimalSeatingArrangement(happiness: Map<Pair<String, String>, Int>) = this .permutations() .map { arrangement -> arrangement.map { guest -> Pair(guest, arrangement.neighbors(guest)) } } .map { it.map { guest -> guest.second.sumOf { neighbor -> happiness[guest.first to neighbor] ?: 0 } } } .maxOfOrNull { it.sum() } ?: 0 } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,678
AdventOfCode
MIT License
src/problemOfTheDay/problemEight/universalTree.kt
cunrein
159,861,371
false
null
package problemOfTheDay.problemEight import problemOfTheDay.problemThree.node // A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. // // Given the root to a binary tree, count the number of unival subtrees. // // For example, the following tree has 5 unival subtrees: // // 0 // / \ // 1 0 // / \ // 1 0 // / \ // 1 1 // Original -- wrong fun <T> node.Companion.universalTrees(n: node<T>?): Int { return if (n == null) { 0 } else if (n.rightNode == null && n.leftNode == null) { 1 } else if (n.leftNode != null && n.rightNode != null) { // test to see if universal val lnode = n.leftNode val rnode = n.rightNode return if (n.value == lnode?.value && n.value == rnode?.value) { 1 + universalTrees(lnode) + universalTrees(rnode) } else { universalTrees(lnode) + universalTrees(rnode) } } else { 0 } } fun <T> node.Companion.countUniversalTrees(n: node<T>): Int { val cnt = Count(0) countUniversalTrees(n, cnt) return cnt.cnt } private data class Count(var cnt: Int) private fun <T> node.Companion.countUniversalTrees(n: node<T>?, cnt: Count): Boolean { if (n == null) return true val ln = n.leftNode val rn = n.rightNode // Recursively count in left and right subtrees also val left = countUniversalTrees(ln, cnt) val right = countUniversalTrees(rn, cnt) // If any of the subtrees is not universal, then this // cannot be universal. if (!left || !right) return false // If left subtree is singly and non-empty, but data // doesn't match if (n.leftNode != null && n.value !== ln?.value) return false // Same for right subtree if (n.rightNode != null && n.value !== rn?.value) return false // If none of the above conditions is true, then // tree rooted under root is single valued, increment // count and return true. cnt.cnt++ return true }
0
Kotlin
0
0
3488ccb200f993a84f1e9302eca3fe3977dbfcd9
2,059
ProblemOfTheDay
Apache License 2.0
src/main/kotlin/pl/mrugacz95/aoc/day15/day15.kt
mrugacz95
317,354,321
false
null
package pl.mrugacz95.aoc.day15 fun findSpokenNumber(turns: List<Int>, toFind: Int): Int { var lastFound: Int? = null for (i in turns.indices.reversed()) { val turn = turns[i] if (turn == toFind) { if (lastFound != null) { return lastFound - i } else { lastFound = i } } } return 0 } fun part1(numbers: List<Int>): Int { val turns = numbers.toMutableList() var lastNum = numbers.last() for (i in 0 until 2020 - numbers.size) { val spelledNum = findSpokenNumber(turns, lastNum) turns.add(spelledNum) lastNum = spelledNum } return lastNum } fun part2(numbers: List<Int>): Int { val lastOccurrences = numbers .withIndex() .associateBy({ it.value }, { it.index }) .toMutableMap() var nextNum = 0 for (turn in numbers.size until 30000000 - 1) { val lastOccur = lastOccurrences[nextNum] val spelledNum = if (lastOccur != null) turn - lastOccur else 0 lastOccurrences[nextNum] = turn nextNum = spelledNum } return nextNum } fun main() { val numbers = {}::class.java.getResource("/day15.in") .readText() .split(",") .map { it.toInt() } println("Answer part 1: ${part1(numbers)}") println("Answer part 2: ${part2(numbers)}") }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
1,385
advent-of-code-2020
Do What The F*ck You Want To Public License
year2019/src/main/kotlin/net/olegg/aoc/year2019/day3/Day3.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2019.day3 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.year2019.DayOf2019 /** * See [Year 2019, Day 3](https://adventofcode.com/2019/day/3) */ object Day3 : DayOf2019(3) { override fun first(): Any? { val (wire1, wire2) = lines .map { line -> line.split(",").map { Directions.valueOf(it.take(1)) to it.drop(1).toInt() } } .map { wire -> wire.fold(listOf(Vector2D())) { acc, (dir, length) -> val start = acc.last() return@fold acc + (1..length).map { start + dir.step * it } } } .map { it.toSet() - Vector2D() } return (wire1.intersect(wire2)).minOf { it.manhattan() } } override fun second(): Any? { val (wire1, wire2) = lines .map { line -> line.split(",").map { Directions.valueOf(it.take(1)) to it.drop(1).toInt() } } .map { wire -> wire.fold(listOf(Vector2D() to 0)) { acc, (dir, length) -> val start = acc.last() return@fold acc + (1..length).map { start.first + dir.step * it to start.second + it } } } .map { it.drop(1) } .map { wire -> wire .groupBy(keySelector = { it.first }, valueTransform = { it.second }) .mapValues { (_, points) -> points.min() } } return wire1 .mapValues { (point, distance) -> distance + (wire2[point] ?: 1_000_000) } .minOf { it.value } } } fun main() = SomeDay.mainify(Day3)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,527
adventofcode
MIT License
csp-scheduling/src/main/kotlin/com/tsovedenski/csp/scheduling/Scheduling.kt
RedShuhart
152,120,429
false
null
package com.tsovedenski.csp.scheduling import com.tsovedenski.csp.* import com.tsovedenski.csp.scheduling.TimeRange.Companion.fromString import java.io.File import kotlin.random.Random class Scheduling(val classesSchedules: Map<String, List<TimeRange>>) : Solvable<String, TimeRange> { private val classes = classesSchedules.keys.toList() private val constraints: List<Constraint<String, TimeRange>> = listOf(AllConstraint(classes, ::areNotOverlapping)) override fun toProblem() = Problem(classes, constraints, classesSchedules::getValue) } fun generateClass(name: String, day: DayOfWeek, start: String, end: String) = name to TimeRange(Boundary(day, start), Boundary(day, end)) fun generateTimeRange(day: DayOfWeek, start: String, end: String) = TimeRange(Boundary(day, start), Boundary(day, end)) fun createSampleOfRanges(day: DayOfWeek, hour: Int) = listOf<TimeRange>( generateTimeRange(day, "$hour:15", "${hour + 1}:15"), generateTimeRange(day, "$hour:15", "${hour + 1}:30"), generateTimeRange(day, "$hour:30", "${hour + 1}:30"), generateTimeRange(day, "$hour:30", "${hour + 1}:45"), generateTimeRange(day, "$hour:00", "${hour + 1}:00"), generateTimeRange(day, "$hour:00", "${hour + 1}:30"), generateTimeRange(day, "$hour:45", "${hour + 1}:45") ) fun generateListOfClasses() = (0..6).map { day -> (6..22).map { hour -> createSampleOfRanges(DayOfWeek.fromInt(day), hour) }.flatten() } .flatten().reduceList() fun List<TimeRange>.reduceList(): List<TimeRange> { val first = Random.nextInt(size / 2) val second = Random.nextInt(size / 2) + first return subList(first, second) } fun List<TimeRange>.toText(): String = joinToString(";") { it.print() } fun printSchedule(solution: Solved<String, TimeRange>) { val classes = solution.assignment.toList() classes.forEach { println("${it.first} ${it.second.print()}") } } fun writeClassesToFile(classesSchedules: Map<String, List<TimeRange>>, filePath: String) { File(filePath).printWriter().use { out -> classesSchedules .toList() .map { "${it.first}_${it.second.toText()}" } .forEach {out.println(it)} } } //Algebra_Tuesday 8:30-Tuesday 9:30;Tuesday 8:30-Tuesday 9:45; fun textToSchedule(text: String): List<TimeRange> = text.split(";").map { TimeRange.fromString(it) } fun toClassSchedulePair(text: String): Pair<String, List<TimeRange>> { val split = text.split("_") return Pair(split[0], textToSchedule(split[1])) } fun readFileToSchedules(filePath: String) = File(filePath) .bufferedReader() .readLines() .map { toClassSchedulePair(it) } .associateBy({it.first}, {it.second})
0
Kotlin
1
4
29d59ec7ff4f0893c0d1ec895118f961dd221c7f
2,756
csp-framework
MIT License
ceria/08/src/main/kotlin/Solution.kt
VisionistInc
572,963,504
false
null
import java.io.File; fun main(args : Array<String>) { var input = mutableListOf<List<Int>>() File(args.first()).readLines().forEach { var row = it.toList().map{ it.digitToInt() } input.add(row) } println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input: List<List<Int>>) :Int { // left and right columns are input.size var visibleCount = input.size * 2 // top and bottom rows are intput.get(0) and input.get(input.size - 1) // minus the corners (so minus 4) visibleCount += ((input.get(0).size * 2) - 4) // skip iterating the top and bottom edges for (y in 1..input.size - 2) { var row = input.get(y) // skip iterating the outside left and right edges for (x in 1..row.size - 2) { var tree = row.get(x) // inspect the trees looking up var upVisible = input.subList(0, y).map{ it.get(x) }.filter{ it > tree - 1 }.isEmpty() // inspect the trees looking down var downVisible = input.subList(y+1, input.size).map{ it.get(x) }.filter{ it > tree - 1}.isEmpty() // inspect the trees looking left var leftVisible = row.subList(0, x).filter{ it > tree - 1 }.isEmpty() // inspect the trees looking right var rightVisible = row.subList(x+1, row.size).filter{ it > tree - 1 }.isEmpty() if (upVisible || downVisible || leftVisible || rightVisible) { visibleCount++ } } } return visibleCount } private fun solution2(input: List<List<Int>>) :Int { var scenicScore = 0 for (y in 0..input.size - 1) { var row = input.get(y) for (x in 0..row.size - 1) { var tree = row.get(x) // inspect the trees looking up var upScenicScore = 0 val lookingUp = input.subList(0, y).map{ it.get(x) } for (up in lookingUp.size - 1 downTo 0) { upScenicScore++ if (lookingUp.get(up) >= tree) { break } } // inspect the trees looking down var downScenicScore = 0 val lookingDown = input.subList(y + 1, input.size).map{ it.get(x) } for (down in 0..lookingDown.size - 1) { downScenicScore++ if (lookingDown.get(down) >= tree) { break } } // inspect the trees looking left var leftScenicScore = 0 val lookingLeft = row.subList(0, x) for (left in lookingLeft.size - 1 downTo 0) { leftScenicScore++ if (lookingLeft.get(left) >= tree) { break } } // inspect the trees looking right var rightScenicScore = 0 val lookingRight = row.subList(x+1, row.size) for (right in 0..lookingRight.size - 1) { rightScenicScore++ if (lookingRight.get(right) >= tree) { break } } val newScenicScore = upScenicScore * downScenicScore * leftScenicScore * rightScenicScore if (newScenicScore > scenicScore) { scenicScore = newScenicScore } } } return scenicScore }
0
Rust
0
0
90b348d9c8060a8e967fe1605516e9c126fc7a56
3,088
advent-of-code-2022
MIT License
src/day19/Day19.kt
idle-code
572,642,410
false
{"Kotlin": 79612}
package day19 import logEnabled import logln import readInput import java.util.PriorityQueue import kotlin.math.ceil import kotlin.math.min import kotlin.math.roundToInt private const val DAY_NUMBER = 19 val blueprintRegex = """Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""".toRegex() data class Resources(val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0) { operator fun plus(other: Resources): Resources { return Resources(ore + other.ore, clay + other.clay, obsidian + other.obsidian, geode + other.geode) } operator fun minus(other: Resources): Resources { return Resources(ore - other.ore, clay - other.clay, obsidian - other.obsidian, geode - other.geode) } } infix fun Resources.canBuy(robot: RobotBlueprint): Boolean { return ore >= robot.cost.ore && clay >= robot.cost.clay && obsidian >= robot.cost.obsidian && geode >= robot.cost.geode } data class RobotBlueprint(val name: String, val cost: Resources, val yield: Resources) { override fun toString(): String = "$name robot" } data class SimulationState(val resources: Resources, val yield: Resources, val minutesLeft: Int) : Comparable<SimulationState> { override fun compareTo(other: SimulationState): Int { return minutesLeft.compareTo(other.minutesLeft) } } data class FactoryBlueprint( val id: Int, val oreRobotBlueprint: RobotBlueprint, val clayRobotBlueprint: RobotBlueprint, val obsidianRobotBlueprint: RobotBlueprint, val geodeRobotBlueprint: RobotBlueprint ) { val maxYield: Resources init { val robots = listOf(oreRobotBlueprint, clayRobotBlueprint, obsidianRobotBlueprint, geodeRobotBlueprint) val maxOreYield = robots.maxOf { it.cost.ore } val maxClayYield = robots.maxOf { it.cost.clay } val maxObsidianYield = robots.maxOf { it.cost.obsidian } maxYield = Resources(maxOreYield, maxClayYield, maxObsidianYield) } } fun parseFactoryBlueprint(line: String): FactoryBlueprint { val (id, oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, obsidianRobotClayCost, geodeRobotOreCost, geodeRobotObsidianCost) = blueprintRegex.matchEntire(line)?.destructured ?: throw IllegalArgumentException("Invalid input line") return FactoryBlueprint( id.toInt(), RobotBlueprint( "Ore", cost = Resources(ore = oreRobotOreCost.toInt()), yield = Resources(ore = 1) ), RobotBlueprint( "Clay", cost = Resources(ore = clayRobotOreCost.toInt()), yield = Resources(clay = 1) ), RobotBlueprint( "Obsidian", cost = Resources(ore = obsidianRobotOreCost.toInt(), clay = obsidianRobotClayCost.toInt()), yield = Resources(obsidian = 1) ), RobotBlueprint( "Geode", cost = Resources(ore = geodeRobotOreCost.toInt(), obsidian = geodeRobotObsidianCost.toInt()), yield = Resources(geode = 1) ) ) } private const val MINUTES = 24 fun simulate(factoryBlueprint: FactoryBlueprint): SimulationState { val startState = SimulationState(Resources(), Resources(ore = 1), MINUTES) //val queue = ArrayDeque<SimulationState>().apply { add(startState) } val queue = PriorityQueue<SimulationState>().apply { add(startState) } var bestState = startState while (queue.isNotEmpty()) { //val state = queue.removeFirst() val state = queue.remove() if (state.minutesLeft == 0) { if (bestState.resources.geode < state.resources.geode) { logln("Found better state with ${state.resources.geode} output") bestState = state } } else queue.addAll(possibleStatesFrom(factoryBlueprint, state)) } return bestState } fun possibleStatesFrom(factoryBlueprint: FactoryBlueprint, simulationState: SimulationState): List<SimulationState> { if (simulationState.minutesLeft <= 0) return listOf() // No more time to simulate val possibleStates = mutableListOf(simulationState) // Do not buy anything if (simulationState.resources canBuy factoryBlueprint.geodeRobotBlueprint) { possibleStates.clear() possibleStates.add(buyRobot(simulationState, factoryBlueprint.geodeRobotBlueprint)) } else { if (simulationState.resources canBuy factoryBlueprint.obsidianRobotBlueprint && simulationState.yield.obsidian < factoryBlueprint.maxYield.obsidian) possibleStates.add(buyRobot(simulationState, factoryBlueprint.obsidianRobotBlueprint)) if (simulationState.resources canBuy factoryBlueprint.clayRobotBlueprint && simulationState.yield.clay < factoryBlueprint.maxYield.clay) possibleStates.add(buyRobot(simulationState, factoryBlueprint.clayRobotBlueprint)) if (simulationState.resources canBuy factoryBlueprint.oreRobotBlueprint && simulationState.yield.ore < factoryBlueprint.maxYield.ore) possibleStates.add(buyRobot(simulationState, factoryBlueprint.oreRobotBlueprint)) } return possibleStates.map { state -> SimulationState(state.resources + simulationState.yield, state.yield, simulationState.minutesLeft - 1) } } fun buyRobot(simulationState: SimulationState, robotToBuy: RobotBlueprint): SimulationState { return SimulationState(simulationState.resources - robotToBuy.cost, simulationState.yield + robotToBuy.yield, simulationState.minutesLeft) } fun main() { fun part1(rawInput: List<String>): Int { var totalQuality = 0 for (blueprint in rawInput.map { parseFactoryBlueprint(it) }) { val bestState = simulate(blueprint) val blueprintQuality = blueprint.id * bestState.resources.geode if (blueprint.id == 1) check(blueprintQuality == 9) else if (blueprint.id == 2) check(blueprintQuality == 2 * 12) totalQuality += blueprintQuality } return totalQuality } fun part2(rawInput: List<String>): Int { return 0 } val sampleInput = readInput("sample_data", DAY_NUMBER) val mainInput = readInput("main_data", DAY_NUMBER) logEnabled = true val part1SampleResult = part1(sampleInput) println(part1SampleResult) check(part1SampleResult == 33) // val part1MainResult = part1(mainInput) // println(part1MainResult) // check(part1MainResult == 0) // val part2SampleResult = part2(sampleInput) // println(part2SampleResult) // check(part2SampleResult == 0) // val part2MainResult = part2(mainInput) // println(part2MainResult) // check(part2MainResult == 0) }
0
Kotlin
0
0
1b261c399a0a84c333cf16f1031b4b1f18b651c7
6,872
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/davio/aoc/y2023/Day8.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2023 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.getInputAsList import com.github.davio.aoc.general.lcm /** * See [Advent of Code 2023 Day 8](https://adventofcode.com/2023/day/8#part2]) */ class Day8(exampleNumber: Int? = null) : Day(exampleNumber) { private val input = getInputAsList() private val directions = input[0].map { it == 'L' } private var elementsMap = mutableMapOf<String, Element>() private val elements: List<Element> init { input.drop(2).forEach { val id = it.substringBefore(" = ") val myElement = elementsMap.getOrPut(id) { Element(id) } val (leftId, rightId) = it.substringAfter(" = ").trim('(', ')').split(", ") val leftElement = elementsMap.getOrPut(leftId) { Element(leftId) } val rightElement = elementsMap.getOrPut(rightId) { Element(rightId) } myElement.left = leftElement myElement.right = rightElement } elements = elementsMap.values.filterNot { it == it.left && it.left == it.right }.toList() } override fun part1(): Int { var steps = 0 var currentElement = elements.first { it.id == ("AAA") } directions.forEach { direction -> steps++ currentElement = if (direction) currentElement.left else currentElement.right if (currentElement.id == "ZZZ") { return steps } } return -1 } override fun part2(): Long { return elements.filter { it.isStartElement }.map { getCycleLength(it) }.reduce { acc, l -> lcm(acc, l) } } private fun getCycleLength(element: Element): Long { var stepsToEnd = 0L var currentElement = element while (!currentElement.isEndElement) { stepsToEnd += directions.size currentElement = directions.fold(currentElement) { acc, d -> if (d) acc.left else acc.right } } return stepsToEnd } private data class Element(val id: String) { val isStartElement = id.endsWith('A') val isEndElement = id.endsWith('Z') lateinit var left: Element lateinit var right: Element override fun toString(): String = id } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
2,372
advent-of-code
MIT License
src/Day13.kt
underwindfall
573,471,357
false
{"Kotlin": 42718}
fun main() { val dayId = "13" val input = readInput("Day${dayId}") fun parse(s: String): Any { var i = 0 fun next(): Any { if (s[i] == '[') { i++ val res = ArrayList<Any>() while(true) { if (s[i] == ']') { i++ return res } res.add(next()) if (s[i] == ']') { i++ return res } check(s[i] == ',') i++ } } check(s[i] in '0'..'9') var num = 0 while (s[i] in '0'..'9') { num = num * 10 + (s[i] - '0') i++ } return num } val res = next() check(i == s.length) return res } fun cmp(a: Any, b: Any): Int { if (a is Int && b is Int) return a.compareTo(b) if (a is List<*> && b is List<*>) { var i = 0 while (i < a.size && i < b.size) { val c = cmp(a[i]!!, b[i]!!) if (c != 0) return c i++ } return a.size.compareTo(b.size) } if (a is Int) return cmp(listOf(a), b) if (b is Int) return cmp(a, listOf(b)) error("!!!") } val d1 = parse("[[2]]") val d2 = parse("[[6]]") val list = (input.mapNotNull { s -> if (s != "") parse(s) else null } + listOf(d1, d2)).sortedWith { a, b -> cmp(a, b) } val i1 = list.indexOf(d1) + 1 val i2 = list.indexOf(d2) + 1 println(i1 * i2) }
0
Kotlin
0
0
0e7caf00319ce99c6772add017c6dd3c933b96f0
1,728
aoc-2022
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day22.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2020 class Day22(private val input: String) { fun solvePart1(): Int { return playCombat(false) } fun solvePart2(): Int { return playCombat(true) } private fun playCombat(recursive: Boolean): Int { val (deck1, deck2) = input.split("\n\n").map { it.split("\n").drop(1).map(String::toInt).toMutableList() } val (_, deck) = playCombat(deck1, deck2, recursive) return deck.reversed().reduceIndexed { index, sum, n -> sum + (index + 1) * n } } private fun playCombat(startDeck1: List<Int>, startDeck2: List<Int>, recursive: Boolean): Pair<Int, List<Int>> { val deck1 = startDeck1.toMutableList() val deck2 = startDeck2.toMutableList() val history = mutableSetOf<Pair<List<Int>, List<Int>>>() while (deck1.isNotEmpty() && deck2.isNotEmpty()) { if (recursive && !history.add(deck1 to deck2)) { return 1 to deck1 } val card1 = deck1.removeFirst() val card2 = deck2.removeFirst() val winner = when { recursive && deck1.size >= card1 && deck2.size >= card2 -> { playCombat(deck1.take(card1), deck2.take(card2), true).first } card1 > card2 -> 1 else -> 2 } if (winner == 1) { deck1 += card1 deck1 += card2 } else { deck2 += card2 deck2 += card1 } } return if (deck1.isNotEmpty()) { 1 to deck1 } else { 2 to deck2 } } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
1,683
advent-of-code
Apache License 2.0
src/main/kotlin/day20/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day20 import util.readTestInput // Wrapper class to capture the original index of each number. // The original index can be used to find the current index of number to be shifted private data class ShiftingNumber(val originalIndex: Int, val value: Long) // Decryption key is used in part 2. In part 1 it's 1. private fun parseNumbers(inputLines: List<String>, decryptionKey: Long) = inputLines .mapIndexed { index, valueStr -> ShiftingNumber(index, decryptionKey * valueStr.toLong()) } .toMutableList() private fun shift(index: Int, numberList: MutableList<ShiftingNumber>) { // Numbers should be moved in the order they originally appear. // Find the current position based on the original position: val currentIndex = numberList.indexOfFirst { it.originalIndex == index } // Remove the number val shiftingNumber = numberList.removeAt(currentIndex) // Resolve the new index (wrapping around when necessary): // Note: Unlike %, the mod-function always returns a positivive number. // This was the hardest part of the puzzle. val newIndex = (currentIndex + shiftingNumber.value).mod(numberList.size) // Add the number back numberList.add(newIndex, shiftingNumber) } private fun shiftAll(numberList: MutableList<ShiftingNumber>) { for (index in 0 until numberList.size) { shift(index, numberList) } } private fun getGroveCoordinates(numberList: List<ShiftingNumber>): List<Long> { val indexOfZero = numberList.indexOfFirst { it.value == 0L } return listOf(1000, 2000, 3000).map { numberList[(indexOfZero + it) % numberList.size].value } } fun part1(inputLines: List<String>): Long { val numberList = parseNumbers(inputLines, 1) shiftAll(numberList) return getGroveCoordinates(numberList).sum() } fun part2(inputLines: List<String>): Long { val numberList = parseNumbers(inputLines, 811589153) repeat(10) { shiftAll(numberList) } return getGroveCoordinates(numberList).sum() } fun main() { val inputLines = readTestInput("day20") println(part1(inputLines)) println(part2(inputLines)) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
2,150
advent-of-code-2022
MIT License
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day18/Cube.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day18 data class Cube(val x: Int, val y: Int, val z: Int) { fun getSides(): Sequence<Side> { return sequenceOf( Side(x + 0, x + 0, y + 0, y + 1, z + 0, z + 1), Side(x + 1, x + 1, y + 0, y + 1, z + 0, z + 1), Side(x + 0, x + 1, y + 0, y + 0, z + 0, z + 1), Side(x + 0, x + 1, y + 1, y + 1, z + 0, z + 1), Side(x + 0, x + 1, y + 0, y + 1, z + 0, z + 0), Side(x + 0, x + 1, y + 0, y + 1, z + 1, z + 1), ) } } data class Side(val xFrom: Int, val xTo: Int, val yFrom: Int, val yTo: Int, val zFrom: Int, val zTo: Int) fun String.toCube(): Cube { val parts = split(",") return Cube(parts[0].toInt(), parts[1].toInt(), parts[2].toInt()) } fun Iterable<Cube>.min(f: (Cube) -> Int) = f(minBy(f)) fun Iterable<Cube>.max(f: (Cube) -> Int) = f(maxBy(f)) fun Iterable<Cube>.rangeOver(f: (Cube) -> Int) = IntRange(min(f) + 1, max(f) - 1)
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
879
advent-of-code
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions77.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import com.qiaoyuang.algorithm.round1.SingleDirectionNode import com.qiaoyuang.algorithm.round1.printlnLinkedList fun test77() { val head = SingleDirectionNode(element = 3, next = SingleDirectionNode(element = 5, next = SingleDirectionNode(element = 1, next = SingleDirectionNode(element = 4, next = SingleDirectionNode(element = 2, next = SingleDirectionNode(element = 6)))))) printlnResult(head) } /** * Questions 77: Input a head node of a linked list, please sort this linked list */ private fun SingleDirectionNode<Int>.sort(): SingleDirectionNode<Int> { if (next == null) return this val head1 = this val head2 = split() return merge(head1.sort(), head2.sort()) } private fun SingleDirectionNode<Int>.split(): SingleDirectionNode<Int> { var pointer1: SingleDirectionNode<Int>? = this var pointer2: SingleDirectionNode<Int>? = this while (true) { val nextPointer2 = pointer2?.next?.next if (nextPointer2 != null) { pointer1 = pointer1!!.next pointer2 = nextPointer2 } else break } val result = pointer1!!.next!! pointer1.next = null return result } fun <T : Comparable<T>> merge(head1: SingleDirectionNode<T>, head2: SingleDirectionNode<T>): SingleDirectionNode<T> { var pointer1: SingleDirectionNode<T>? = head1 var pointer2: SingleDirectionNode<T>? = head2 val head = if (head1.element < head2.element) { pointer1 = pointer1!!.next head1 } else { pointer2 = pointer2!!.next head2 } var pointer = head while (pointer1 != null || pointer2 != null) { when { pointer1 != null && pointer2 == null -> { pointer.next = pointer1 break } pointer1 == null && pointer2 != null -> { pointer.next = pointer2 break } pointer1 != null && pointer2 != null -> { pointer.next = if (pointer1.element < pointer2.element) { val temp = pointer1 pointer1 = pointer1.next temp } else { val temp = pointer2 pointer2 = pointer2.next temp } pointer = pointer.next!! } } } return head } private fun printlnResult(head: SingleDirectionNode<Int>) { print("Input lined list: ") printlnLinkedList(head) print("Sort it, we can get: ") printlnLinkedList(head.sort()) }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,629
Algorithm
Apache License 2.0
src/commonMain/kotlin/de/voize/semver4k/Requirement.kt
voize-gmbh
369,655,654
true
{"Kotlin": 125030}
package de.voize.semver4k import de.voize.semver4k.Tokenizer.tokenize import de.voize.semver4k.Semver.SemverType import de.voize.semver4k.Range.RangeOperator /** * A requirement will provide an easy way to check if a version is satisfying. * There are 2 types of requirements: * - Strict: checks if a version is equivalent to another * - NPM: follows the rules of NPM */ class Requirement /** * Builds a requirement. (private use only) * * A requirement has to be a range or a combination of an operator and 2 other requirements. * * @param range the range that will be used for the requirement (optional if all other params are provided) * @param req1 the requirement used as a left operand (requires the `op` and `req2` params to be provided) * @param op the operator used between the requirements (requires the `req1` and `req2` params to be provided) * @param req2 the requirement used as a right operand (requires the `req1` and `op` params to be provided) */ constructor(val range: Range?, val req1: Requirement?, val op: RequirementOperator?, val req2: Requirement?) { /** * @see .isSatisfiedBy * @param version the version that will be checked * * @return true if the version satisfies the requirement */ fun isSatisfiedBy(version: String?): Boolean { return if (range != null) { this.isSatisfiedBy(Semver(version!!, range.version.type)) } else { this.isSatisfiedBy(Semver(version!!)) } } /** * Checks if the requirement is satisfied by a version. * * @param version the version that will be checked * * @return true if the version satisfies the requirement */ fun isSatisfiedBy(version: Semver): Boolean { if (range != null) { return range.isSatisfiedBy(version) } when (op) { RequirementOperator.AND -> try { val set = getAllRanges(this, ArrayList()) for (range in set) { if (!range!!.isSatisfiedBy(version)) { return false } } if (version.suffixTokens?.isNotEmpty() == true) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (range in set) { if (range!!.version == null) { continue } if (range.version.suffixTokens?.isNotEmpty() == true) { val allowed = range.version if (version.major == allowed.major && version.minor == allowed.minor && version.patch == allowed.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } catch (e: Exception) { // Could be that we have a OR in AND - fallback to default test return req1!!.isSatisfiedBy(version) && req2!!.isSatisfiedBy(version) } RequirementOperator.OR -> return req1!!.isSatisfiedBy(version) || req2!!.isSatisfiedBy(version) else -> throw RuntimeException("Code error. Unknown RequirementOperator: " + op) // Should never happen } } fun minVersion(): Semver? { var minver: Semver? = Semver("0.0.0") if (minver != null && this.isSatisfiedBy(minver)) { return minver } minver = Semver("0.0.0-0") if (this.isSatisfiedBy(minver)) { return minver } minver = null val ranges = mutableListOf<Range?>() this.getAllGreaterOrEqualRanges(this, ranges) for (range in ranges) { if (range == null) { continue; } var compver = range.version; if (range.op.equals(RangeOperator.GT)) { compver = compver.nextIncrement(); } // Pick this new version if it's smaller than the one we already have and still satisfies the requirements if ((range.op.equals(RangeOperator.GT) || range.op.equals(RangeOperator.GTE) || range.op.equals(RangeOperator.EQ)) && (minver == null || minver.compareTo(compver) > 0) && this.isSatisfiedBy(compver) ) { minver = compver } } if (minver != null && this.isSatisfiedBy(minver)) { return minver } return null } private fun getAllGreaterOrEqualRanges(requirement: Requirement?, res: MutableList<Range?>): List<Range?> { if (requirement!!.range != null) { if (requirement.range!!.op.equals(RangeOperator.GT) || requirement.range.op.equals(RangeOperator.GTE) || requirement.range.op.equals(RangeOperator.EQ) ) { res.add(requirement.range) } } else { getAllGreaterOrEqualRanges(requirement.req1, res) getAllGreaterOrEqualRanges(requirement.req2, res) } return res } private fun getAllRanges(requirement: Requirement?, res: MutableList<Range?>): List<Range?> { if (requirement!!.range != null) { res.add(requirement.range) } else if (requirement.op == RequirementOperator.AND) { getAllRanges(requirement.req1, res) getAllRanges(requirement.req2, res) } else { throw RuntimeException("OR in AND not allowed") } return res } override fun equals(o: Any?): Boolean { if (this === o) return true if (o !is Requirement) return false val that = o return range == that.range && req1 == that.req1 && op == that.op && req2 == that.req2 } override fun hashCode(): Int { return "$range$req1$op$req2".hashCode() } override fun toString(): String { return if (range != null) { range.toString() } else req1.toString() + " " + (if (op == RequirementOperator.OR) op.asString() + " " else "") + req2 } /** * The operators that can be used in a requirement. */ enum class RequirementOperator(private val s: String) { AND(""), OR("||"); fun asString(): String { return s } } companion object { private val IVY_DYNAMIC_PATCH_PATTERN = Regex("(\\d+)\\.(\\d+)\\.\\+") private val IVY_DYNAMIC_MINOR_PATTERN = Regex("(\\d+)\\.\\+") private val IVY_LATEST_PATTERN = Regex("latest\\.\\w+") private val IVY_MATH_BOUNDED_PATTERN = Regex( "(\\[|\\])" + // 1ST GROUP: a square bracket "([\\d\\.]+)" + // 2ND GROUP: a version "," + // a comma separator "([\\d\\.]+)" + // 3RD GROUP: a version "(\\[|\\])" // 4TH GROUP: a square bracket ) private val IVY_MATH_LOWER_UNBOUNDED_PATTERN = Regex( "\\(," + // a parenthesis and a comma separator "([\\d\\.]+)" + // 1ST GROUP: a version "(\\[|\\])" // 2ND GROUP: a square bracket ) private val IVY_MATH_UPPER_UNBOUNDED_PATTERN = Regex( "(\\[|\\])" + // 1ST GROUP: a square bracket "([\\d\\.]+)" + // 2ND GROUP: a version ",\\)" // a comma separator and a parenthesis ) /** * Builds a requirement (will test that the version is equivalent to the requirement) * * @param requirement the version of the requirement * * @return the generated requirement */ fun build(requirement: Semver?): Requirement { return Requirement(Range(requirement!!, RangeOperator.EQ), null, null, null) } /** * Builds a strict requirement (will test that the version is equivalent to the requirement) * * @param requirement the version of the requirement * * @return the generated requirement */ fun buildStrict(requirement: String?): Requirement { return build(Semver(requirement!!, SemverType.STRICT)) } /** * Builds a loose requirement (will test that the version is equivalent to the requirement) * * @param requirement the version of the requirement * * @return the generated requirement */ fun buildLoose(requirement: String?): Requirement { return build(Semver(requirement!!, SemverType.LOOSE)) } /** * Builds a requirement following the rules of NPM. * * @param requirement the requirement as a string * * @return the generated requirement */ fun buildNPM(requirement: String): Requirement { var requirement = requirement if (requirement.isEmpty()) { requirement = "*" } return buildWithTokenizer(requirement, SemverType.NPM) } /** * Builds a requirement following the rules of Cocoapods. * * @param requirement the requirement as a string * * @return the generated requirement */ fun buildCocoapods(requirement: String): Requirement { return buildWithTokenizer(requirement, SemverType.COCOAPODS) } private fun buildWithTokenizer(requirement: String, type: SemverType): Requirement { // Tokenize the string var tokens = tokenize(requirement, type) tokens = removeFalsePositiveVersionRanges(tokens) tokens = addParentheses(tokens) // Tranform the tokens list to a reverse polish notation list val rpn = toReversePolishNotation(tokens) // Create the requirement tree by evaluating the rpn list return evaluateReversePolishNotation(rpn.iterator(), type) } /** * Builds a requirement following the rules of Ivy. * * @param requirement the requirement as a string * * @return the generated requirement */ fun buildIvy(requirement: String): Requirement { try { return buildLoose(requirement) } catch (ignored: SemverException) { } val matchPath = IVY_DYNAMIC_PATCH_PATTERN.find(requirement) if (matchPath != null) { val major = matchPath.groupValues[1].toInt() val minor = matchPath.groupValues[2].toInt() val lower = Requirement(Range("$major.$minor.0", RangeOperator.GTE), null, null, null) val upper = Requirement(Range(major.toString() + "." + (minor + 1) + ".0", RangeOperator.LT), null, null, null) return Requirement(null, lower, RequirementOperator.AND, upper) } val matchMinor = IVY_DYNAMIC_MINOR_PATTERN.find(requirement) if (matchMinor != null) { val major = matchMinor.groupValues[1].toInt() val lower = Requirement(Range("$major.0.0", RangeOperator.GTE), null, null, null) val upper = Requirement(Range((major + 1).toString() + ".0.0", RangeOperator.LT), null, null, null) return Requirement(null, lower, RequirementOperator.AND, upper) } val matchLatest = IVY_LATEST_PATTERN.find(requirement) if (matchLatest != null) { return Requirement(Range("0.0.0", RangeOperator.GTE), null, null, null) } val matchBounded = IVY_MATH_BOUNDED_PATTERN.find(requirement) if (matchBounded != null) { val lowerOp = if ("[" == matchBounded.groupValues[1]) RangeOperator.GTE else RangeOperator.GT val lowerVersion = Semver(matchBounded.groupValues[2], SemverType.LOOSE) val upperVersion = Semver(matchBounded.groupValues[3], SemverType.LOOSE) val upperOp = if ("]" == matchBounded.groupValues[4]) RangeOperator.LTE else RangeOperator.LT val lower = Requirement(Range(extrapolateVersion(lowerVersion), lowerOp), null, null, null) val upper = Requirement(Range(extrapolateVersion(upperVersion), upperOp), null, null, null) return Requirement(null, lower, RequirementOperator.AND, upper) } val matchLowerUnbounded = IVY_MATH_LOWER_UNBOUNDED_PATTERN.find(requirement) if (matchLowerUnbounded != null) { val version = Semver(matchLowerUnbounded.groupValues[1], SemverType.LOOSE) val op = if ("]" == matchLowerUnbounded.groupValues[2]) RangeOperator.LTE else RangeOperator.LT return Requirement(Range(extrapolateVersion(version), op), null, null, null) } val matchUpperUnbounded = IVY_MATH_UPPER_UNBOUNDED_PATTERN.find(requirement) if (matchUpperUnbounded != null) { val op = if ("[" == matchUpperUnbounded.groupValues[1]) RangeOperator.GTE else RangeOperator.GT val version = Semver(matchUpperUnbounded.groupValues[2], SemverType.LOOSE) return Requirement(Range(extrapolateVersion(version), op), null, null, null) } throw SemverException("Invalid requirement") } /** * Return parenthesized expression, giving lowest priority to OR operator * * @param tokens the tokens contained in the requirement string * * @return the tokens with parenthesis */ private fun addParentheses(tokens: List<Tokenizer.Token?>): List<Tokenizer.Token?> { val result: MutableList<Tokenizer.Token?> = ArrayList() result.add(Tokenizer.Token(Tokenizer.TokenType.OPENING, "(")) for (token in tokens) { if (token!!.type === Tokenizer.TokenType.OR) { result.add(Tokenizer.Token(Tokenizer.TokenType.CLOSING, ")")) result.add(token) result.add(Tokenizer.Token(Tokenizer.TokenType.OPENING, "(")) } else { result.add(token) } } result.add(Tokenizer.Token(Tokenizer.TokenType.CLOSING, ")")) return result } /** * Some requirements may contain versions that look like version ranges. For example ' 0.0.1-SNASHOT ' could be * interpreted incorrectly as a version range from 0.0.1 to SNAPSHOT. This method parses all tokens and looks for * groups of three tokens that are respectively of type [VERSION, HYPHEN, VERSION] and validates that the token * after the hyphen is a valid version string. If it isn't the, three tokens are merged into one (thus creating a * single version token, in which the third token is the build information). * * @param tokens the tokens contained in the requirement string * * @return the tokens with any false positive version ranges replaced with version strings */ private fun removeFalsePositiveVersionRanges(tokens: List<Tokenizer.Token?>): List<Tokenizer.Token?> { val result: MutableList<Tokenizer.Token?> = ArrayList() var i = 0 while (i < tokens.size) { var token = tokens[i] if (thereIsFalsePositiveVersionRange(tokens, i)) { token = Tokenizer.Token(Tokenizer.TokenType.VERSION, token!!.value + '-' + tokens[i + 2]!!.value) i += 2 } result.add(token) i++ } return result } private fun thereIsFalsePositiveVersionRange(tokens: List<Tokenizer.Token?>, i: Int): Boolean { if (i + 2 >= tokens.size) { return false } val suspiciousTokens = arrayOf(tokens[i], tokens[i + 1], tokens[i + 2]) if (suspiciousTokens[0]!!.type != Tokenizer.TokenType.VERSION) { return false } if (suspiciousTokens[2]!!.type != Tokenizer.TokenType.VERSION) { return false } return if (suspiciousTokens[1]!!.type != Tokenizer.TokenType.HYPHEN) { false } else attemptToParse(suspiciousTokens[2]!!.value) == null } private fun attemptToParse(value: String?): Semver? { try { return Semver(value!!, SemverType.NPM) } catch (e: SemverException) { // Ignore. } return null } /** * Adaptation of the shutting yard algorithm */ private fun toReversePolishNotation(tokens: List<Tokenizer.Token?>): List<Tokenizer.Token?> { val queue = mutableListOf<Tokenizer.Token?>() val stack = mutableListOf<Tokenizer.Token?>() var i = 0 while (i < tokens.size) { val token = tokens[i] when (token!!.type) { Tokenizer.TokenType.VERSION -> queue.add(0, token) Tokenizer.TokenType.CLOSING -> { while (stack[0]!!.type !== Tokenizer.TokenType.OPENING) { queue.add(0, stack.removeAt(0)) } stack.removeAt(0) if (stack.size > 0 && stack[0]!!.type.isUnary) { queue.add(0, stack.removeAt(0)) } } else -> if (token.type.isUnary) { // Push the operand first i++ queue.add(0, tokens[i]) // Then the operator queue.add(0, token) } else { stack.add(0, token) } } i++ } while (stack.isNotEmpty()) { queue.add(0, stack.removeAt(0)) } return queue } /** * Evaluates a reverse polish notation token list */ private fun evaluateReversePolishNotation(iterator: Iterator<Tokenizer.Token?>, type: SemverType): Requirement { return try { val token = iterator.next() if (token!!.type === Tokenizer.TokenType.VERSION) { if ("*" == token!!.value || type === SemverType.NPM && "latest" == token.value) { // Special case for "*" and "latest" in NPM return Requirement(Range("0.0.0", RangeOperator.GTE), null, null, null) } val version = Semver(token.value!!, type) if (version.minor != null && version.patch != null) { val range = Range(version, RangeOperator.EQ) Requirement(range, null, null, null) } else { // If we have a version with a wildcard char (like 1.2.x, 1.2.* or 1.2), we need a tilde requirement tildeRequirement(version.value, type) } } else if (token!!.type === Tokenizer.TokenType.HYPHEN) { val token3 = iterator.next() // Note that token3 is before token2! val token2 = iterator.next() hyphenRequirement(token2!!.value, token3!!.value, type) } else if (token!!.type.isUnary) { val token2 = iterator.next() val rangeOp: RangeOperator rangeOp = when (token.type) { Tokenizer.TokenType.EQ -> RangeOperator.EQ Tokenizer.TokenType.LT -> RangeOperator.LT Tokenizer.TokenType.LTE -> RangeOperator.LTE Tokenizer.TokenType.GT -> RangeOperator.GT Tokenizer.TokenType.GTE -> RangeOperator.GTE Tokenizer.TokenType.TILDE -> return tildeRequirement(token2!!.value, type) Tokenizer.TokenType.CARET -> return caretRequirement(token2!!.value, type) else -> throw SemverException("Invalid requirement") } val range = Range(token2!!.value, rangeOp) Requirement(range, null, null, null) } else { // They don't call it "reverse" for nothing val req2 = evaluateReversePolishNotation(iterator, type) val req1 = evaluateReversePolishNotation(iterator, type) val requirementOp: RequirementOperator requirementOp = when (token.type) { Tokenizer.TokenType.OR -> RequirementOperator.OR Tokenizer.TokenType.AND -> RequirementOperator.AND else -> throw SemverException("Invalid requirement") } Requirement(null, req1, requirementOp, req2) } } catch (e: NoSuchElementException) { throw SemverException("Invalid requirement") } } /** * Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * * @param version the version of the requirement * @param type the version system used for this requirement * * @return the generated requirement */ fun tildeRequirement(version: String?, type: SemverType): Requirement { if (type !== SemverType.NPM && type !== SemverType.COCOAPODS) { throw SemverException("The tilde requirements are only compatible with NPM and Cocoapods.") } val semver = Semver(version!!, type) val req1 = Requirement(Range(extrapolateVersion(semver), RangeOperator.GTE), null, null, null) val next: String next = when (type) { SemverType.COCOAPODS -> { if (semver.patch != null) { semver.major.toString() + "." + (semver.minor!! + 1) + ".0" } else if (semver.minor != null) { (semver.major!! + 1).toString() + ".0.0" } else { return req1 } } SemverType.NPM -> { if (semver.minor != null) { semver.major.toString() + "." + (semver.minor!! + 1) + ".0" } else { (semver.major!! + 1).toString() + ".0.0" } } else -> throw SemverException("The tilde requirements are only compatible with NPM and Cocoapods.") } val req2 = Requirement(Range(next, RangeOperator.LT), null, null, null) return Requirement(null, req1, RequirementOperator.AND, req2) } /** * Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple. * * @param version the version of the requirement * @param type the version system used for this requirement * * @return the generated requirement */ fun caretRequirement(version: String?, type: SemverType): Requirement { if (type !== SemverType.NPM) { throw SemverException("The caret requirements are only compatible with NPM.") } val semver = Semver(version!!, type) val req1 = Requirement(Range(extrapolateVersion(semver), RangeOperator.GTE), null, null, null) val next: String next = if (semver.major == 0) { if (semver.minor == null) { "1.0.0" } else if (semver.minor == 0) { if (semver.patch == null) { "0.1.0" } else { "0.0." + (semver.patch!! + 1) } } else { "0." + (semver.minor!! + 1) + ".0" } } else { (semver.major!! + 1).toString() + ".0.0" } val req2 = Requirement(Range(next, RangeOperator.LT), null, null, null) return Requirement(null, req1, RequirementOperator.AND, req2) } /** * Creates a requirement that satisfies "x1.y1.z1 - x2.y2.z2". * * @param lowerVersion the version of the lower bound of the requirement * @param upperVersion the version of the upper bound of the requirement * @param type the version system used for this requirement * * @return the generated requirement */ fun hyphenRequirement(lowerVersion: String?, upperVersion: String?, type: SemverType): Requirement { if (type !== SemverType.NPM) { throw SemverException("The hyphen requirements are only compatible with NPM.") } val lower = extrapolateVersion(Semver(lowerVersion!!, type)) var upper = Semver(upperVersion!!, type) var upperOperator = RangeOperator.LTE if (upper.minor == null || upper.patch == null) { upperOperator = RangeOperator.LT upper = if (upper.minor == null) { extrapolateVersion(upper).withIncMajor() } else { extrapolateVersion(upper).withIncMinor() } } val req1 = Requirement(Range(lower, RangeOperator.GTE), null, null, null) val req2 = Requirement(Range(upper, upperOperator), null, null, null) return Requirement(null, req1, RequirementOperator.AND, req2) } /** * Extrapolates the optional minor and patch numbers. * - 1 = 1.0.0 * - 1.2 = 1.2.0 * - 1.2.3 = 1.2.3 * * @param semver the original semver * * @return a semver with the extrapolated minor and patch numbers */ private fun extrapolateVersion(semver: Semver): Semver { val sb = StringBuilder() .append(semver.major) .append(".") .append(if (semver.minor == null) 0 else semver.minor) .append(".") .append(if (semver.patch == null) 0 else semver.patch) var first = true for (i in 0 until (semver.suffixTokens?.size ?: 0)) { if (first) { sb.append("-") first = false } else { sb.append(".") } sb.append(semver.suffixTokens!![i]) } if (semver.build != null) { sb.append("+").append(semver.build) } return Semver(sb.toString(), semver.type) } } }
0
Kotlin
1
2
fb9a7623e181b3246ad894b439dff6cb1353dfbc
28,055
semver4k
MIT License
advent2022/src/main/kotlin/year2022/Day09.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay import kotlin.math.sign class Day09 : AdventDay(2022, 9) { sealed class RopeMove(val amount: Int) { companion object { fun from(input: String) = input.split(" ").let { (a, b) -> when (a) { "L" -> Left(b.toInt()) "R" -> Right(b.toInt()) "U" -> Up(b.toInt()) "D" -> Down(b.toInt()) else -> error("could not parse") } } } } class Up(amount: Int) : RopeMove(amount) class Down(amount: Int) : RopeMove(amount) class Left(amount: Int) : RopeMove(amount) class Right(amount: Int) : RopeMove(amount) private infix fun Pair<Int, Int>.adjacent(other: Pair<Int, Int>): Boolean = (first - other.first) in (-1 .. 1) && (second - other.second) in (-1 .. 1) private infix fun Pair<Int, Int>.moveOnce(move: RopeMove): Pair<Int, Int> = when (move) { is Up -> first + 1 to second is Down -> first - 1 to second is Right -> first to second + 1 is Left -> first to second - 1 } private infix fun Pair<Int, Int>.follow(head: Pair<Int, Int>): Pair<Int, Int> = this.first + (head.first - this.first).sign to this.second + (head.second - this.second).sign private fun simulate(inst: List<RopeMove>, knots: MutableList<Pair<Int, Int>>): Int = inst.fold(mutableSetOf(0 to 0)) { visited, m -> repeat(m.amount) { knots[0] = knots[0] moveOnce m knots.drop(1).indices.forEach { index -> val head = knots[index] val tail = knots[index + 1] if (!(head adjacent tail)) { knots[index + 1] = tail follow head visited += knots.last() } } } visited }.size override fun part1(input: List<String>): Int = simulate( input.map { RopeMove.from(it) }, MutableList(2) { 0 to 0} ) override fun part2(input: List<String>): Int = simulate( input.map { RopeMove.from(it) }, MutableList(10) { 0 to 0} ) } fun main() = Day09().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
2,322
advent-of-code
Apache License 2.0
src/main/kotlin/aoc2022/Day07.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.* import aoc.parser.* class Day07() { sealed interface Node { val size: Int val subNodes: List<Node> } data class FileNode(override val size: Int, val name: String) : Node { override val subNodes: List<Node> get() = emptyList() } data class DirNode(val name: String, override val subNodes: List<Node> = emptyList()) : Node { override val size: Int get() = subNodes.sumOf { it.size } } val fileEntry = seq(number() followedBy " ", regex("[a-zA-Z./]+") followedBy "\n", ::FileNode) val dirEntry = "dir " followedBy regex("[a-zA-Z./]+") followedBy "\n" asValue null val fileDirEntry = dirEntry or fileEntry val entry: Parser<Node?> = ref(::dirListing) or fileDirEntry val entries = oneOrMore(entry) map { it.filterNotNull() } val dirListing = seq( "\$ cd " followedBy regex("[a-zA-Z/]+"), "\n\$ ls\n" followedBy entries, ::DirNode) followedBy (eoF() or literal("\$ cd ..\n")) fun part1(input: String): Int { val tree = dirListing.parse(input) val r = foldTree(tree, Node::subNodes, 0) { acc, node -> acc + if (node is DirNode && node.size < 100000) node.size else 0 } return r } fun part2(input: String): Int { val minimum = 30000000 - 21618835 val tree = dirListing.parse(input) val r = foldTree(tree, Node::subNodes, null) { acc: Node?, node: Node -> if (node is DirNode && node.size >= minimum && node.size < (acc?.size ?: Int.MAX_VALUE)) node else acc } return r?.size ?: 0 } }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
1,649
aoc-kotlin
Apache License 2.0
src/Day07.kt
SeanDijk
575,314,390
false
{"Kotlin": 29164}
// Not the most efficient code, but it works interface FileSystemObject { fun size(): Int } sealed interface Command { data class Cd(val dir: String) : Command data class Ls(val output: List<String>) : Command } fun main() { fun parseCommands(input: String): List<Command> { return input // Split into strings of a command with outputs. // To achieve this, look at a new line (\n) followed by the start of a command ($). // Then because we do not want to 'delete' this 'separator', use a zero-width positive lookahead: https://stackoverflow.com/questions/4416425/how-to-split-string-with-some-separator-but-without-removing-that-separator-in-j .splitToSequence(Regex("(?=\\n\\\$)")) // Map to the typed command .map { commandWithOutput -> val trimmed = commandWithOutput.trim() when { trimmed.startsWith("$ cd") -> Command.Cd(commandWithOutput.split(' ').last()) trimmed.startsWith("$ ls") -> { // Now ls commands with their outputs are still a single string. Split it in lines. // Also remove what would be the first line, since we only want the output. Command.Ls(trimmed.removePrefix("$ ls\n").split('\n')) } else -> throw IllegalStateException("Unknown command: $commandWithOutput") } } .toList() } data class Dir( val name: String, val parent: Dir?, val fileSystemObjects: MutableMap<String, FileSystemObject> = HashMap(), ) : FileSystemObject { override fun size() = fileSystemObjects.values.sumOf { it.size() } override fun toString() = "$fileSystemObjects" } data class File(val name: String, val size: Int) : FileSystemObject { override fun size() = size } fun handleCd(command: Command.Cd, root: Dir, currentDir: Dir): Dir { return when (command.dir) { "/" -> root ".." -> currentDir.parent ?: throw IllegalStateException() else -> { // If the dir already exists return it, otherwise create a new one (currentDir.fileSystemObjects.computeIfAbsent(command.dir) { Dir(command.dir, currentDir) } as Dir) // Trust the advent of code input is good, and assume we do not have dirs and files with the same name. // Add it to the objects of the currentDir. If we overwrite it with itself it is not a big deal. .also { currentDir.fileSystemObjects[command.dir] = it } } } } fun handleLs(command: Command.Ls, currentDir: Dir) { command.output // We honestly could not care less about dirs that are listed and not traversed, so we ignore them. .filter { !it.startsWith("dir ") } .forEach { fileDescriptor -> val (size, name) = fileDescriptor.split(' ') currentDir.fileSystemObjects[name] = File(name, size.toInt()) } } fun traverseDir(root: Dir, handle: (Dir) -> Unit) { val toTraverse = ArrayDeque<Dir>() toTraverse.addFirst(root) while (toTraverse.isNotEmpty()) { val current = toTraverse.removeLast() toTraverse.addAll(current.fileSystemObjects.values.filterIsInstance<Dir>()) handle(current) } } fun constructFileSystem(commands: List<Command>): Dir { val root = Dir("/", null) var currentDir = root commands.forEach { command -> when (command) { is Command.Cd -> currentDir = handleCd(command, root, currentDir) is Command.Ls -> handleLs(command, currentDir) } } return root } fun part1(input: String): Int { val commands = parseCommands(input) val root = constructFileSystem(commands) val dirsWithSizeLessThan100000 = mutableListOf<Dir>() traverseDir(root) { if (it.size() <= 100_000) { dirsWithSizeLessThan100000.add(it) } } return dirsWithSizeLessThan100000.sumOf { it.size() } } fun part2(input: String): Int { val diskSize = 70_000_000 val neededRequired = 30_000_000 val commands = parseCommands(input) val root = constructFileSystem(commands) val spaceToFree = neededRequired - (diskSize - root.size()) val dirs = ArrayList<Dir>() traverseDir(root) { dirs.add(it) } return dirs.asSequence() .map { it.size() } .filter { it >= spaceToFree } .min() } val test = """ $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent() println(part1(test)) println(part1(readInputAsString("Day07"))) println(part2(test)) println(part2(readInputAsString("Day07"))) }
0
Kotlin
0
0
363747c25efb002fe118e362fb0c7fecb02e3708
5,359
advent-of-code-2022
Apache License 2.0
puzzles/src/main/kotlin/com/kotlinground/puzzles/search/binarysearch/findpeakelement/findPeakElement.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.puzzles.search.binarysearch.findpeakelement /** * Finds a peak element's index in the provided list of integers * * Algorithm: * - Initializes left as the start index of the list and right as the end index of the list (len(nums)- 1). * - Perform binary search until left becomes equal to right. * - Calculate the middle index mid using the formula mid = left + (right - left) // 2. or mid = (left + right) >> 1 * - Compare nums[mid] with nums[mid + 1] to determine if the peak is on the left side or the right side of mid. * - If nums[mid] is greater than nums[mid + 1], move the right index to mid, indicating that the peak is on the * left side. * - Otherwise, move the left index to mid + 1, indicating that the peak is on the right side. * - Repeat steps 3-4 until left becomes equal to right. * - Return the value of peak_index, which represents the index of the peak element. * * Complexity: * * - Time complexity O(log n): Where n is the number of elements in the nums vector. * - Space Complexity O(1): Since it uses a constant amount of extra space. * * @param nums [IntArray] list of integers with duplicate peaks * @return [Int] index of a peak element(i.e. element that is greater than its adjacent neighbours) */ fun findPeakElement(nums: IntArray): Int { var left = 0 var right = nums.size - 1 var peakIndex = -1 while (left <= right) { val mid = (left + right).shr(1) val potentialPeak = nums[mid] if (mid == nums.size - 1 || potentialPeak > nums[mid + 1]) { peakIndex = mid right = mid - 1 } else { left = mid + 1 } } return peakIndex }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
1,716
KotlinGround
MIT License
src/main/kotlin/dp/MetaPal.kt
yx-z
106,589,674
false
null
package dp import util.OneArray import util.get import util.toOneArray // a metapalindrome is a decomposition of string into palindromes, // such that the sequence of palindrome lengths itself is a palindrome fun main(args: Array<String>) { val str = "BUBBLESSEESABANANA".toCharArray().toList().toOneArray() println(str.metaPal()) // BUB B L E S SEES A B A N ANA -> [3, 1, 1, 1, 1, 4, 1, 1, 1, 1, 3].size == 11 } // given S[1..n], find the minimum length of the sequence obtained by metapalindrome fun OneArray<Char>.metaPal(): Int { val S = this // S.prettyPrintln() val n = S.size // isPal[i, j]: if S[i..j] is palindromic // imported from SplitInPal // time complexity: O(n^2) // space complexity: O(n^2) val isPal = isPal() // dp(i): min len of metapal of S[i..n - i + 1] val lM = (n + 1) / 2 val rM = n - lM + 1 // memoization structure: 1d array dp[1..lM] : dp[i] = dp(i) val dp = OneArray(lM) { 0 } // space complexity: O(n) // base case: // dp(lM) = 1 if S[lM..rM] is palindromic (lM = rM in the case of odd n) // = 2 o/w dp[lM] = if (isPal[lM, rM]) 1 else 2 // recursive case: // dp(i) = 1 if S[i..j] is palindromic // min{ dp(k + 1) + 2 } : i <= k < lM, // S[i..k] and S[s..j] are both palindromic // where lM - i = j - rM and k - i = j - s // dependency: dp(i) depends on dp(k) : k > i, that is entries to the right // evaluation order: outer loop for i from lM - 1 down to 1 (right to left) for (i in lM - 1 downTo 1) { // lM - i = j - rM -> j = lM - i + rM val j = lM - i + rM dp[i] = if (isPal[i, j]) { 1 } else { (i until lM) .filter { k -> // k - i = j - s -> s = j - (k - i) = j - k + i val s = j - k + i isPal[i, k] && isPal[s, j] } .map { k -> dp[k + 1] + 2 } .min()!! } } // time complexity: O(n^2) // dp.prettyPrintln() // we want dp(1) return dp[1] // overall space complexity: O(n^2) // overall time complexity: O(n^2) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,971
AlgoKt
MIT License
src/Day09.kt
marosseleng
573,498,695
false
{"Kotlin": 32754}
fun main() { fun part1(input: List<String>): Int { return countVisitedByTail(input) } fun part2(input: List<String>): Int { return countVisitedByTail2(input) } val testInput = readInput("Day09_test") check(part1(testInput) == 13) val testInput2 = readInput("Day09_test_2") check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) } fun countVisitedByTail(instructions: List<String>): Int { var headX = 0 var headY = 0 var tailX = 0 var tailY = 0 val visitedByTail = mutableSetOf(tailX to tailY) fun needsTailUpdate(): Boolean { val candidates = listOf( headX-1 to headY+1, headX to headY+1, headX+1 to headY+1, headX-1 to headY, headX to headY, headX+1 to headY, headX-1 to headY-1, headX to headY-1, headX+1 to headY-1, ) return (tailX to tailY) !in candidates } fun moveTail(direction: Char) { if (!needsTailUpdate()) { return } val tailPosition = when (direction) { 'L' -> (headX+1) to headY 'R' -> (headX-1) to headY 'U' -> headX to (headY-1) else -> headX to (headY+1) } tailX = tailPosition.first tailY = tailPosition.second visitedByTail.add(tailPosition) } fun moveHead(direction: Char, count: Int, headPositions: MutableList<Pair<Int, Int>>, tailPositions: MutableList<Pair<Int, Int>>) { repeat(count) { when (direction) { 'L' -> headX -= 1 'R' -> headX += 1 'U' -> headY += 1 'D' -> headY -= 1 } moveTail(direction) headPositions.add(headX to headY) tailPositions.add(tailX to tailY) } } instructions.forEach { val headPositions = mutableListOf<Pair<Int, Int>>() val tailPositions = mutableListOf<Pair<Int, Int>>() val match = """(\w) (\d+)""".toRegex().matchEntire(it)?.groupValues.orEmpty() moveHead(match[1].first(), match[2].toInt(), headPositions, tailPositions) } return visitedByTail.size } fun countVisitedByTail2(instructions: List<String>, knotCount: Int = 10): Int { val positions = mutableMapOf<Int, Pair<Int, Int>>() repeat(knotCount) { positions[it] = 0 to 0 } val visitedByTail = mutableSetOf(0 to 0) fun needsTailUpdate(index: Int): Boolean { val (headX, headY) = positions[index - 1] ?: return false val (tailX, tailY) = positions[index] ?: return false val candidates = listOf( headX-1 to headY+1, headX to headY+1, headX+1 to headY+1, headX-1 to headY, headX to headY, headX+1 to headY, headX-1 to headY-1, headX to headY-1, headX+1 to headY-1, ) return (tailX to tailY) !in candidates } fun moveTail(index: Int, verbosely: Boolean) { if (!needsTailUpdate(index)) { return } val (headX, headY) = positions[index - 1] ?: return val (tailX, tailY) = positions[index] ?: return val distanceX = headX - tailX val distanceY = headY - tailY var newTailX: Int var newTailY: Int when { distanceX == 2 -> { newTailX = tailX + 1 newTailY = when (distanceY) { 1, -1 -> headY 2 -> headY - 1 -2 -> headY + 1 // 0 else -> tailY } } distanceX == -2 -> { newTailX = tailX - 1 newTailY = when (distanceY) { 1, -1 -> headY 2 -> headY - 1 -2 -> headY + 1 // 0 else -> tailY } } distanceY == 2 -> { newTailX = when (distanceX) { 1, -1 -> headX // 0 else -> tailX } newTailY = tailY + 1 } else -> { // distanceY == -2 newTailX = when (distanceX) { // WRONG 1, -1 -> headX else -> tailX } newTailY = tailY - 1 } } positions[index] = newTailX to newTailY if (verbosely) { println("Moving [$index] from [$tailX;$tailY] to [$newTailX;$newTailY] because head is on [$headX;$headY]") } moveTail(index + 1, verbosely) if (index == knotCount - 1) { visitedByTail.add(positions[index] ?: return) } } fun moveHead(direction: Char, count: Int, verbosely: Boolean) { repeat(count) { val currentHead = positions[0] ?: return@repeat when (direction) { 'L' -> positions[0] = currentHead.copy(first = currentHead.first - 1) 'R' -> positions[0] = currentHead.copy(first = currentHead.first + 1) 'U' -> positions[0] = currentHead.copy(second = currentHead.second + 1) 'D' -> positions[0] = currentHead.copy(second = currentHead.second - 1) } if (verbosely) { println("Moving [0] from [${currentHead.first};${currentHead.second}] to [${positions[0]?.first};${positions[0]?.second}].") } moveTail(index = 1, verbosely = verbosely) } } instructions.forEachIndexed { index, str -> val verbosely = false if (verbosely) { println("[$index]=>$str") } val match = """(\w) (\d+)""".toRegex().matchEntire(str)?.groupValues.orEmpty() moveHead(match[1].first(), match[2].toInt(), verbosely = verbosely) if (verbosely) { positions.forEach { (index, pos) -> println("[$index]~>[${pos.first};${pos.second}]") } } } return visitedByTail.size }
0
Kotlin
0
0
f13773d349b65ae2305029017490405ed5111814
6,300
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2023/Day02.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2023 import se.saidaspen.aoc.util.* fun main() = Day02.run() object Day02 : Day(2023, 2) { override fun part1() : Any { var possible = 0 for (line in input.lines()) { val gameID = words(line)[1].replace(":", "").toInt() val game = line.split(":")[1] val reds = words(game).windowed(2).filter { it[1].startsWith("red") }.maxOf { it[0].toInt() } val greens = words(game).windowed(2).filter { it[1].startsWith("green") }.maxOf { it[0].toInt() } val blues = words(game).windowed(2).filter { it[1].startsWith("blue") }.maxOf { it[0].toInt() } if (reds <= 12 && greens <= 13 && blues <= 14) possible += gameID } return possible } override fun part2() : Any { var sum = 0 for (line in input.lines()) { val game = line.split(":")[1] val reds = words(game).windowed(2).filter { it[1].startsWith("red") }.maxOf { it[0].toInt() } val greens = words(game).windowed(2).filter { it[1].startsWith("green") }.maxOf { it[0].toInt() } val blues = words(game).windowed(2).filter { it[1].startsWith("blue") }.maxOf { it[0].toInt() } sum += reds * greens * blues } return sum } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,323
adventofkotlin
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year15/Day22.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year15 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.drain import com.grappenmaker.aoc.hasDuplicateBy import com.grappenmaker.aoc.splitInts import java.util.* fun PuzzleSet.day22() = puzzle(day = 22) { val (initialBossHP, bossDMG) = input.splitInts() // Horrible code but it was the first idea I had please forgive meee val spells = listOf( Spell(53) { it.copy(bossHP = it.bossHP - 4) }, Spell(73) { it.copy(bossHP = it.bossHP - 2, playerHP = it.playerHP + 2) }, Spell(113) { it.copy( effects = it.effects + Effect(6, 0, remove = { s -> s.copy(playerDef = s.playerDef - 7) }), playerDef = it.playerDef + 7 ) }, Spell(173) { it.copy(effects = it.effects + Effect(6, 1, step = { s -> s.copy(bossHP = s.bossHP - 3) })) }, Spell(229) { it.copy(effects = it.effects + Effect(5, 2, step = { s -> s.copy(mana = s.mana + 101) })) } ) val initialState = GameState(initialBossHP) fun solve(hardMode: Boolean): Int { val seen = hashSetOf(initialState) val queue = PriorityQueue<Pair<GameState, Int>>(compareBy { (_, c) -> c }).also { it.add(initialState to 0) } queue.drain { (current, currentCost) -> if (current.bossHP <= 0) return currentCost if (current.playerHP <= 0) return@drain val step1 = current.effects.fold(current) { acc, curr -> curr.step(acc).let { if (curr.timer == 1) curr.remove(it) else it } } val step2 = step1.copy(effects = step1.effects.mapNotNull { val newTimer = it.timer - 1 if (newTimer == 0) null else it.copy(timer = newTimer) }) if (!current.playerTurn) { val actualDamage = (bossDMG - step2.playerDef).coerceAtLeast(1) val bossUpdated = step2.copy( playerHP = step2.playerHP - actualDamage - if (hardMode) 1 else 0, playerTurn = true ) if (seen.add(bossUpdated)) queue.offer(bossUpdated to currentCost) } else { spells.filter { it.mana <= step2.mana }.forEach { cast -> val appliedSpell = cast.apply(step2) if (appliedSpell.effects.hasDuplicateBy { it.type }) return@forEach val new = appliedSpell.copy(mana = step2.mana - cast.mana, playerTurn = false) if (seen.add(new)) queue.offer(new to currentCost + cast.mana) } } } error("Not found") } partOne = solve(false).s() partTwo = solve(true).s() } data class Spell(val mana: Int, val apply: (GameState) -> GameState) data class Effect( val timer: Int, val type: Int, val step: (GameState) -> GameState = { it }, val remove: (GameState) -> GameState = { it } ) data class GameState( val bossHP: Int, val effects: List<Effect> = emptyList(), val playerHP: Int = 50, val mana: Int = 500, val playerDef: Int = 0, val playerTurn: Boolean = true )
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
3,168
advent-of-code
The Unlicense
kotlin/src/com/s13g/aoc/aoc2023/Day12.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.resultFrom /** * --- Day 12: Hot Springs --- * https://adventofcode.com/2023/day/12 */ class Day12 : Solver { private val cache = mutableMapOf<String, Long>() override fun solve(lines: List<String>): Result { val newLines = lines.map { expandLine(it) } val partA = lines.sumOf { countSolutionsNew(it) } val partB = newLines.sumOf { countSolutionsNew(it) } return resultFrom(partA, partB) } private fun countSolutionsNew(str: String): Long { cache.clear() val (part1, part2) = str.split(" ") val nums = part2.split(",").map { it.toInt() } val length = part1.length val positions = mutableMapOf<Char, Set<Int>>() val empties = mutableSetOf<Int>() str.forEachIndexed { i, c -> if (c == '.') empties.add(i) } val hashes = mutableSetOf<Int>() str.forEachIndexed { i, c -> if (c == '#') hashes.add(i) } val placeholders = mutableSetOf<Int>() str.forEachIndexed { i, c -> if (c == '?') placeholders.add(i) } positions['.'] = empties positions['#'] = hashes positions['?'] = placeholders // Place every number in their first possible location. return countSolutionsNew(0, nums, length, positions) } private fun countSolutionsNew( placeOnOrAfter: Int, toPlace: List<Int>, length: Int, setup: Map<Char, Set<Int>> ): Long { if (toPlace.isEmpty()) { // Ensure there is not hash piece later than this. return if ((placeOnOrAfter until length).count { it in setup['#']!! } > 0) 0 else 1 } val cacheKey = "$placeOnOrAfter-${toPlace.size}" if (cacheKey in cache) return cache[cacheKey]!! val nextToPlace = toPlace.first() val newToPlace = toPlace.drop(1) var count = 0L for (start in placeOnOrAfter..(length - nextToPlace)) { // We cannot skip already placed pieces if ((start - 1) in setup['#']!!) break; // Check that the location just following is not a '# as it would not // properly separate this range. var valid = (start + nextToPlace) !in setup['#']!! if (start > 0 && (start - 1) in setup['#']!!) valid = false // Check that there is no confirmed dot within the range, prohibiting this // placement. if (valid) { for (n in start until start + nextToPlace) { if (n in setup['.']!!) { valid = false break } } } if (valid) { count += countSolutionsNew( start + nextToPlace + 1, newToPlace, length, setup ) } } cache[cacheKey] = count return count } private fun expandLine(str: String): String { val (part1, part2) = str.split(" ") val newPart1 = (1..5).map { part1 }.joinToString("?") val newPart2 = (1..5).map { part2 }.joinToString(",") return "$newPart1 $newPart2" } private data class Range(val from: Int, val to: Int) }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
3,018
euler
Apache License 2.0
src/year_2021/day_11/Day11.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2021.day_11 import readInput import util.neighbors import java.awt.font.ImageGraphicAttribute enum class FlashAttemptResult { IGNORED, INCREASED, FLASHED, ; } data class Octopus( var charge: Int ) { var hasFlashedThisRound: Boolean = false private set fun attemptFlash(): FlashAttemptResult { if (hasFlashedThisRound) { return FlashAttemptResult.IGNORED } charge += 1 if (charge > 9) { hasFlashedThisRound = true charge = 0 return FlashAttemptResult.FLASHED } return FlashAttemptResult.INCREASED } fun resetFlash() { hasFlashedThisRound = false } } object Day11 { /** * @return */ fun solutionOne(text: List<String>): Int { val map = parseText(text) var flashCount = 0 for (round in 1..100) { val toEvaluate = map.keys.toMutableList() map.values.forEach { it.resetFlash() } while (toEvaluate.isNotEmpty()) { val position = toEvaluate.removeFirst() if (map[position]?.attemptFlash() == FlashAttemptResult.FLASHED) { toEvaluate.addAll(position.neighbors(includeDiagonals = true)) } } val numFlashes = map.values.count { it.hasFlashedThisRound } flashCount += numFlashes } return flashCount } /** * @return */ fun solutionTwo(text: List<String>): Int { val map = parseText(text) var round = 1 while(true) { val toEvaluate = map.keys.toMutableList() map.values.forEach { it.resetFlash() } while (toEvaluate.isNotEmpty()) { val position = toEvaluate.removeFirst() if (map[position]?.attemptFlash() == FlashAttemptResult.FLASHED) { toEvaluate.addAll(position.neighbors(includeDiagonals = true)) } } if (map.values.all { it.hasFlashedThisRound }) { return round } round += 1 } } private fun parseText(text: List<String>): Map<Pair<Int, Int>, Octopus> { val map = mutableMapOf<Pair<Int, Int>, Octopus>() text.forEachIndexed { y, row -> row.forEachIndexed { x, num -> map[x to y] = Octopus(Integer.parseInt("$num")) } } return map } } fun main() { val inputText = readInput("year_2021/day_11/Day11.txt") val solutionOne = Day11.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day11.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
2,770
advent_of_code
Apache License 2.0
src/main/kotlin/kr/co/programmers/P42861.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://github.com/antop-dev/algorithm/issues/530 class P42861 { fun solution(n: Int, costs: Array<IntArray>): Int { // 건설 비용이 낮은 순으로 정렬 costs.sortBy { (_, _, cost) -> cost } // Union-Find val root = IntArray(n) { it } var ans = 0 var count = 0 for ((from, to, cost) in costs) { // 두 정점의 부모 정점이 같다면 패스 (루프) if (root.find(from) == root.find(to)) continue // 비용 누적 ans += cost // 부모를 합쳐준다. root.union(from, to) // 간선은 (N-1)개가 만들어진다. if (count++ >= n) break } return ans } private fun IntArray.find(x: Int): Int = if (this[x] == x) x else find(this[x]) private fun IntArray.union(x: Int, y: Int) { this[find(y)] = find(x) } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
951
algorithm
MIT License
src/main/java/io/github/lunarwatcher/aoc/day6/Day6.kt
LunarWatcher
160,042,659
false
null
package io.github.lunarwatcher.aoc.day6 import io.github.lunarwatcher.aoc.commons.readFile import kotlin.math.absoluteValue const val INFINITE_AREA = -1 data class Area (val center: Pair<Int, Int>, val points: MutableList<Pair<Int, Int>> = mutableListOf()){ val area: Int get() = points.size fun won(x: Int, y: Int){ points.add(x to y) } } fun day6part1processor(coords: List<Pair<Int, Int>>) : Int{ val areas = getAreas(coords) val filteredAreas = areas.filter { it.points.none { it.first == 0 || it.second == 0 } // it's safe to assume if x or y == 0, the area is infinite. } return filteredAreas.maxBy { it.area }!!.area } fun day6part2processor(points: List<Pair<Int, Int>>) : Int { val areas = getAreas(points) val manhattenPoints = areas.map { it.points}.flatten() val maxDist = 10000 val accepted = mutableListOf<Int>() for((x, y) in manhattenPoints){ var totalDist = 0; for(area in areas){ totalDist += calculateManhatten(x, y, area.center) } if(totalDist < maxDist) accepted.add(totalDist) } return accepted.size } fun calculateManhatten(x: Int, y: Int, center: Pair<Int, Int>) : Int{ return (center.first - x).absoluteValue + (y - center.second).absoluteValue } fun getAreas(coords: List<Pair<Int, Int>>) : List<Area> { val areas = coords.map { Area(it) } val max = coords.maxBy { it.first }!!.first to coords.maxBy { it.second }!!.second val grid = mutableMapOf<Int, Pair<Int, Int>>() for (x in 0..(max.first)){ for(y in 0..(max.second)){ var highestManhatten: Int = Int.MAX_VALUE var currArea: Area? = null for(area in areas){ val center = area.center val manhatten = calculateManhatten(x, y, center) if(manhatten < highestManhatten){ highestManhatten = manhatten currArea = area } else if(manhatten == highestManhatten){ // The point is equally far from two points; skip it. continue; } } currArea!!.won(x, y) } } return areas; } fun day6(part: Boolean = false){ val points = readFile("day6.txt", Int::class.java, Int::class.java) val res = if(!part) day6part1processor(points) else day6part2processor(points) println(res) }
0
Kotlin
0
1
99f9b05521b270366c2f5ace2e28aa4d263594e4
2,486
AoC-2018
MIT License
src/aoc2022/Day14.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import utils.* import kotlin.math.max private const val ROCK = -1 private const val AIR = 0 private const val SAND = 1 //private val SAND_START_POINT = 0 to 500 private val SAND_START_POINT = Vertex(500, 0) fun main() { // parts execution val testInput = readInput("Day14_test") val input = readInput("Day14") Day14.part1(testInput).checkEquals(24) Day14.part1(input) .checkEquals(979) // .sendAnswer(part = 1, day = "14", year = 2022) Day14.part2(testInput).checkEquals(93) Day14.part2(input) .checkEquals(29044) // .sendAnswer(part = 2, day = "14", year = 2022) } object Day14 { val input get() = readInput("Day14") fun part1(input: List<String>): Int { var highestY = -1 val cave2D = input.scanCave { maxY, _ -> highestY = maxY } return cave2D.startSandFlowThenCount(highestY) } fun part2(input: List<String>): Int { var highestY = -1 val cave2D = input.scanCave(afterScanTransform = { maxY, cave -> highestY = maxY cave[highestY + 2] = cave[highestY + 2].map { ROCK }.toIntArray() }) return cave2D.startSandFlowThenCount(highestY + 2) } } private typealias Cave2D = Array<IntArray> private fun List<String>.scanCave(afterScanTransform: (highestY: Int, cave: Cave2D) -> Unit): Cave2D { // y lies in 200 row, x lies in 1000 col val cave2D = Array(200) { IntArray(1000) { AIR } } var highestY = -1 for (line in this) for ((from, to) in line.split(" -> ").windowed(2)) { val fromVertx = from.split(',').let(Vertex.Companion::ofDestructuringStrings) val toVertx = to.split(',').let(Vertex.Companion::ofDestructuringStrings) when { fromVertx isHorizontallyEquals toVertx -> { val directionRange = if (fromVertx.y < toVertx.y) (fromVertx.y..toVertx.y) else (toVertx.y..fromVertx.y) for (i in directionRange) cave2D[i][fromVertx.x] = ROCK } fromVertx isVerticallyEquals toVertx -> { val directionRange = if (fromVertx.x < toVertx.x) (fromVertx.x..toVertx.x) else (toVertx.x..fromVertx.x) for (i in directionRange) cave2D[fromVertx.y][i] = ROCK } else -> error("not accepted input") } max(fromVertx.y, toVertx.y).let { if (it > highestY) highestY = it } } afterScanTransform(highestY, cave2D) return cave2D } private fun Cave2D.startSandFlowThenCount(maxHeight: Int): Int { val cave2D = this var score = 0 var fallingSandVertex = SAND_START_POINT //(500 - 400) sandFlow@ while (fallingSandVertex.y < maxHeight) when { cave2D canGoDownFrom fallingSandVertex -> fallingSandVertex = fallingSandVertex.down() cave2D canGoDownLeftFrom fallingSandVertex -> fallingSandVertex = fallingSandVertex.downLeft() cave2D canGoDownRightFrom fallingSandVertex -> fallingSandVertex = fallingSandVertex.downRight() else -> { score++ cave2D[fallingSandVertex] = SAND fallingSandVertex = SAND_START_POINT if (cave2D.getOrDefault(fallingSandVertex.downLeft(), defaultValue = SAND) == SAND && cave2D[fallingSandVertex] == SAND && cave2D.getOrDefault(fallingSandVertex.downRight(), defaultValue = SAND) == SAND ) { cave2D[fallingSandVertex] = SAND break@sandFlow } } } return score } private infix fun Cave2D.canGoDownFrom(ver: Vertex) = this[ver.down()] == AIR private infix fun Cave2D.canGoDownLeftFrom(ver: Vertex) = this.getOrDefault(ver.downLeft(), ROCK) == AIR private infix fun Cave2D.canGoDownRightFrom(ver: Vertex) = this.getOrDefault(ver.downRight(), ROCK) == AIR
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
4,063
Kotlin-AOC-2023
Apache License 2.0
src/Day21.kt
mrugacz95
572,881,300
false
{"Kotlin": 102751}
import java.math.BigInteger private const val DEBUG = true private sealed class TreeNode(open val name: String?) private data class Terminal( val value: BigInteger, override val name: String? ) : TreeNode(name) { override fun toString(): String { return "$value" } } private data class Production( var lhs: TreeNode, var rhs: TreeNode, var symbol: Char, override val name: String? ) : TreeNode(name) { override fun toString(): String { return "($lhs $symbol $rhs)" } } private data class Human( override val name: String ) : TreeNode(name) { override fun toString(): String { return "x" } } private const val ROOT = "root" private const val HUMAN = "humn" private fun oppositeSymbol(symbol: Char) = when (symbol) { '+' -> '-' '-' -> '+' '*' -> '/' '/' -> '*' else -> error("Unknown symbol") } fun main() { fun List<String>.parse(replaceHuman: Boolean = false): TreeNode { val tree = this.associate { val key = it.slice(0..3) val value = it.slice(6 until it.length) key to value } fun parseSubTree(nodeName: String): TreeNode { if (replaceHuman && nodeName == HUMAN) { return Human(HUMAN) } val value = tree[nodeName] ?: error("Node not found") return if (!value.first().isDigit()) { val lhsNodeName = value.slice(0..3) val rhsNodeName = value.slice(7..10) val lhs = parseSubTree(lhsNodeName) val rhs = parseSubTree(rhsNodeName) val symbol = if (replaceHuman && nodeName == ROOT) { '=' } else { value[5] } Production(lhs, rhs, symbol, nodeName) } else { Terminal(value.toBigInteger(), nodeName) } } return parseSubTree(ROOT) } fun evaluateNode(tree: TreeNode): BigInteger { when (tree) { is Terminal -> return tree.value is Production -> { val operation: (BigInteger, BigInteger) -> BigInteger = when (tree.symbol) { '+' -> { a, b -> a + b } '*' -> { a, b -> a * b } '/' -> { a, b -> a / b } '-' -> { a, b -> a - b } '=' -> { if (tree.lhs is Human) { return evaluateNode(tree.rhs) } else { return evaluateNode(tree.lhs) } } else -> error("Unknown operation") } val ev1 = evaluateNode(tree.lhs) val ev2 = evaluateNode(tree.rhs) return operation(ev1, ev2) } is Human -> error("Unknown value of $HUMAN") else -> { error("Unknown type") } } } fun TreeNode.hasUnknown(): Boolean { return when (this) { is Human -> true is Production -> lhs.hasUnknown() || rhs.hasUnknown() is Terminal -> false } } fun TreeNode.simplify(): TreeNode { return if (hasUnknown()) { this } else { when (this) { is Production -> Terminal(value = evaluateNode(this), name = null) is Terminal -> this is Human -> error("this node is unknown") } } } fun part1(input: List<String>): BigInteger { val tree = input.parse() return evaluateNode(tree) } fun part2(input: List<String>, debug : Boolean = false): BigInteger { val tree = input.parse(replaceHuman = true) as? Production ?: error("Root is not production") if (debug) println(tree) tree.lhs = tree.lhs.simplify() tree.rhs = tree.rhs.simplify() if (tree.rhs.hasUnknown()) { tree.lhs = tree.rhs.also { tree.rhs = tree.lhs } } if (debug) println(tree) while (tree.lhs !is Human) { val rhsTree = tree.rhs val lhsTree = tree.lhs as? Production ?: error("lhs is not production") val subLeft = (tree.lhs as Production).lhs val subRight = (tree.lhs as Production).rhs if (lhsTree.symbol in listOf('-', '/') && subRight.hasUnknown()) { // handle sub and div with swap tree.lhs = subRight tree.rhs = Production(subLeft, rhsTree, lhsTree.symbol, name = null) } else { if (subLeft.hasUnknown()) { tree.lhs = subLeft tree.rhs = Production(rhsTree, subRight, oppositeSymbol(lhsTree.symbol), name = null) } else { tree.lhs = subRight tree.rhs = Production(rhsTree, subLeft, oppositeSymbol(lhsTree.symbol), name = null) } } tree.rhs = tree.rhs.simplify() if (debug) println(tree) } return evaluateNode(tree) } val testInput = readInput("Day21_test") val input = readInput("Day21") assert(part1(testInput).toInt(), 152) println(part1(input)) assert(part2(testInput, debug = DEBUG).toInt(), 301) println(part2(input)) } // Part 1 time: 01:20 // Part 2 time: 01:50
0
Kotlin
0
0
29aa4f978f6507b182cb6697a0a2896292c83584
5,504
advent-of-code-2022
Apache License 2.0
Edit_Distance.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
import kotlin.math.max import kotlin.math.min class Solution { fun minDistance(word1: String, word2: String): Int { val maxLen = max(word1.length, word2.length) if (word1.isEmpty() || word2.isEmpty()) return maxLen val dp = Array(word1.length + 1) { Array(word2.length + 1) { 0 } } for (i in 0..word1.length) dp[i][0] = i for (i in 0..word2.length) dp[0][i] = i for (i in 1..word1.length) { for (j in 1..word2.length) { if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] } else dp[i][j] = min(dp[i - 1][j], min(dp[i][j - 1], dp[i - 1][j - 1])) + 1 } } return dp[word1.length][word2.length] } } fun main() { val solution = Solution() val testCases = arrayOf(arrayOf("acaeda", "abdaf"), arrayOf("abcde", "ace"), arrayOf("abc", "def"), arrayOf("horse", "ros"), arrayOf("intention", "execution")) for (case in testCases) println(solution.minDistance(case[0], case[1])) }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,049
leetcode
MIT License
Problems/Algorithms/695. Max Area of Island/MaxArea.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun closedIsland(grid: Array<IntArray>): Int { val n = grid.size val m = grid[0].size val visited = Array(n) { IntArray(m) { 0 } } var ans = 0 for (r in 0..n-1) { for (c in 0..m-1) { val curr = dfs(grid, visited, n, m, r, c) if (curr > 0) { ans++ } } } return ans } private fun isValid(n: Int, m: Int, r: Int, c: Int): Boolean { return r >= 0 && r < n && c >= 0 && c < m } private fun isCorner(n: Int, m: Int, r: Int, c: Int): Boolean { return r == 0 || c == 0 || r == n-1 || c == m-1 } private fun dfs(grid: Array<IntArray>, visited: Array<IntArray>, n: Int, m: Int, r: Int, c: Int): Int { if (!isValid(n, m, r, c) || visited[r][c] == 1 || grid[r][c] == 1) return 0 if (isCorner(n, m, r, c)) return -1000 visited[r][c] = 1 return 1 + dfs(grid, visited, n, m, r+1, c) + dfs(grid, visited, n, m, r-1, c) + dfs(grid, visited, n, m, r, c+1) + dfs(grid, visited, n, m, r, c-1) } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,166
leet-code
MIT License
src/Day02.kt
JCofman
576,062,635
false
{"Kotlin": 6297}
object PointConstants { const val DRAW_SCORE = 3; const val LOOSE_SCORE = 0; const val WIN_SCORE = 6; } fun main() { fun solvePart1(input: List<String>): Int { var points = 0; input.forEach { when (it) { "A X" -> points += 1 + PointConstants.DRAW_SCORE "A Y" -> points += 2 + PointConstants.WIN_SCORE "A Z" -> points += 3 + PointConstants.LOOSE_SCORE "B X" -> points += 1 + PointConstants.LOOSE_SCORE "B Y" -> points += 2 + PointConstants.DRAW_SCORE "B Z" -> points += 3 + PointConstants.WIN_SCORE "C X" -> points += 1 + PointConstants.WIN_SCORE "C Y" -> points += 2 + PointConstants.LOOSE_SCORE "C Z" -> points += 3 + PointConstants.DRAW_SCORE } } return points } fun solvePart2(input: List<String>): Int { var points = 0; input.forEach { when (it) { "A X" -> points += 3 + PointConstants.LOOSE_SCORE "A Y" -> points += 1 + PointConstants.DRAW_SCORE "A Z" -> points += 2 + PointConstants.WIN_SCORE "B X" -> points += 1 + PointConstants.LOOSE_SCORE "B Y" -> points += 2 + PointConstants.DRAW_SCORE "B Z" -> points += 3 + PointConstants.WIN_SCORE "C X" -> points += 2 + PointConstants.LOOSE_SCORE "C Y" -> points += 3 + PointConstants.DRAW_SCORE "C Z" -> points += 1 + PointConstants.WIN_SCORE } } return points } fun part1(input: List<String>): Int { return solvePart1(input) } fun part2(input: List<String>): Int { return solvePart2(input) } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
c25a54b03df77c1be46827642b6adc7644825c8c
1,899
aoc-2022-in-kotlin
Apache License 2.0
leetcode-75-kotlin/src/main/kotlin/AsteroidCollision.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
import kotlin.math.absoluteValue /** * We are given an array asteroids of integers representing asteroids in a row. * * For each asteroid, the absolute value represents its size, * and the sign represents its direction (positive meaning right, negative meaning left). * Each asteroid moves at the same speed. * * Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. * If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. * * * * Example 1: * * Input: asteroids = [5,10,-5] * Output: [5,10] * Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. * Example 2: * * Input: asteroids = [8,-8] * Output: [] * Explanation: The 8 and -8 collide exploding each other. * Example 3: * * Input: asteroids = [10,2,-5] * Output: [10] * Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. * * * Constraints: * * 2 <= asteroids.length <= 10^4 * -1000 <= asteroids[i] <= 1000 * asteroids[i] != 0 * @see <a href="https://leetcode.com/problems/asteroid-collision/">LeetCode</a> */ fun asteroidCollision(asteroids: IntArray): IntArray { val asteroidStack = mutableListOf<Int>() var index = 0 while (index < asteroids.size) { asteroids[index].let { currentAsteroid -> if (asteroidStack.isEmpty() || currentAsteroid > 0 || asteroidStack.last() < 0) { asteroidStack.add(currentAsteroid) index++ } else { val currentAsteroidSize = currentAsteroid.absoluteValue val lastAsteroidSize = asteroidStack.last() when { currentAsteroidSize < lastAsteroidSize -> { index++ } currentAsteroidSize > lastAsteroidSize -> { asteroidStack.removeLast() } else -> { asteroidStack.removeLast() index++ } } } } } return asteroidStack.toIntArray() }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
2,202
leetcode-75
Apache License 2.0
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day22Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith private fun solution1(input: String) = parse(input).let { (map, path) -> val width = map[0].size val height = map.size var row = 0 var col = map[0].indexOfFirst { it != ' ' } var facing = Facing.RIGHT path.forEach { instr -> when (instr) { is Instr.Move -> { val (dr, dc) = when (facing) { Facing.RIGHT -> 0 to 1 Facing.DOWN -> 1 to 0 Facing.LEFT -> 0 to -1 Facing.UP -> -1 to 0 } val (newR, newC) = generateSequence(row to col) { (r, c) -> (r + dr + height) % height to (c + dc + width) % width } .filter { (r, c) -> map[r][c] != ' ' } .take(instr.steps + 1) .takeWhile { (r, c) -> map[r][c] != '#' } .onEach { (r, c) -> map[r][c] = facing.char } .last() row = newR col = newC } is Instr.Turn -> { facing = when (instr.direction) { "R" -> facing.rotateRight() "L" -> facing.rotateLeft() else -> throw IllegalStateException() } } } } (row + 1) * 1000 + (col + 1) * 4 + facing.value } private fun solution2(input: String): Long = 0L private fun parse(input: String) = input.split("\n\n").let { (map, path) -> val mapLines = map.lines() val mapWidth = mapLines.maxOf { it.length } val parsedMap = mapLines .map { line -> Array(mapWidth) { line.getOrElse(it) { ' ' } } } .toTypedArray<Array<Char>>() val parsedPath = "\\d+|[RL]".toRegex().findAll(path) .map { it.value } .map { if (it[0].isDigit()) Instr.Move(it.toInt()) else Instr.Turn(it) } parsedMap to parsedPath } private sealed interface Instr { class Move(val steps: Int) : Instr class Turn(val direction: String) : Instr } private enum class Facing(val char: Char, val value: Int) { RIGHT('>', 0) { override fun rotateLeft() = UP override fun rotateRight() = DOWN }, DOWN('v', 1) { override fun rotateLeft() = RIGHT override fun rotateRight() = LEFT }, LEFT('<', 2) { override fun rotateLeft() = DOWN override fun rotateRight() = UP }, UP('^', 3) { override fun rotateLeft() = LEFT override fun rotateRight() = RIGHT }; abstract fun rotateLeft(): Facing abstract fun rotateRight(): Facing } private fun printMap(map: Array<Array<Char>>) { map.forEach { row -> row.forEach { print(it) } println() } } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 22 class Day22Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 6032 } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 88226 } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 5031 } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 0L } }) private val exampleInput = """ ...# .#.. #... .... ...#.......# ........#... ..#....#.... ..........#. ...#.... .....#.. .#...... ......#. 10R5L5R10L4R5L5 """.trimIndent()
0
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
3,788
adventofcode-kotlin
MIT License
Chapter10/src/main/kotlin/com/programming/kotlin/chapter10/MapsCollection.kt
PacktPublishing
78,835,440
false
null
package com.programming.kotlin.chapter10 import java.util.* fun maps() { val carsMap: Map<String, String> = mapOf("a" to "<NAME>", "b" to "bmw", "m" to "mercedes", "f" to "ferrari") println("cars[${carsMap.javaClass.canonicalName}:$carsMap]") println("car maker starting with 'f':${carsMap.get("f")}") //ferrari println("car maker starting with 'X':${carsMap.get("X")}") //null val customers: java.util.HashMap<Int, Customer> = hashMapOf( 1 to Customer("Dina", "Kreps", 1), 2 to Customer("Andy", "Smith", 2) ) val linkedHashMap: java.util.LinkedHashMap<String, String> = linkedMapOf( "red" to "#FF0000", "azure" to "#F0FFFF", "white" to "#FFFFFF" ) val states: MutableMap<String, String> = mutableMapOf("AL" to "Alabama", "AK" to "Alaska", "AZ" to "Arizona") states += ("CA" to "California") println("States [${states.javaClass.canonicalName}:$states") println("States keys:${states.keys}") println("States values:${states.values}") val sortedMap: SortedMap<Int, String> = sortedMapOf(4 to "d", 1 to "a", 3 to "c", 2 to "b") println("Sorted map[${sortedMap.javaClass.canonicalName}]:${sortedMap}") CollectionsJ.dangerousCallMap(carsMap.toList().toMap()) println("Cars:$carsMap") //a=<NAME>, b=bmw, m=mercedes, f=ferrari, newKey!=newValue! customers.mapKeys { it.toString() } // "1" = Customer("Dina","Kreps",1),... customers.map { it.key * 10 to it.value.id } // 10= 1, 20 =2 customers.mapValues { it.value.lastName } // 1=Kreps, 2="Smith customers.flatMap { (it.value.firstName + it.value.lastName).toSet() }.toSet() //D, i, n, a, K, r, e, p, s, A, d, y, S, m, t, h] linkedHashMap.filterKeys { it.contains("r") } //red=#FF0000,.. states.filterNot { it.value.startsWith("C") } //AL=Alabama, AK=Alaska, AZ=Arizona } data class Customer(val firstName: String, val lastName: String, val id: Int)
5
Kotlin
41
75
4502b55d4086795df3f76ef65517679ad6c8cd55
1,988
Programming-Kotlin
MIT License
src/main/kotlin/year_2022/Day01.kt
krllus
572,617,904
false
{"Kotlin": 97314}
package year_2022 import utils.readInput fun main() { fun part1(input: List<String>): Int { val caloriesCountByElf = arrayListOf<Int>() var currentElfCaloriesCount = 0 for(index in input.indices){ val element = input[index] if(element.isEmpty()){ caloriesCountByElf.add(currentElfCaloriesCount) currentElfCaloriesCount = 0 continue } currentElfCaloriesCount += element.toInt() if(index == input.size -1){ caloriesCountByElf.add(currentElfCaloriesCount) } } return caloriesCountByElf.maxBy { it } } fun part2(input: List<String>): Int { val caloriesCountByElf = arrayListOf<Int>() var currentElfCaloriesCount = 0 for(index in input.indices){ val element = input[index] if(element.isEmpty()){ caloriesCountByElf.add(currentElfCaloriesCount) currentElfCaloriesCount = 0 continue } currentElfCaloriesCount += element.toInt() if(index == input.size -1){ caloriesCountByElf.add(currentElfCaloriesCount) } } caloriesCountByElf.sortBy { it } return caloriesCountByElf.takeLast(3).sumOf { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b5280f3592ba3a0fbe04da72d4b77fcc9754597e
1,655
advent-of-code
Apache License 2.0
src/main/kotlin/days/day25/Day25.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day25 import days.Day class Day25 : Day() { override fun partOne(): Any { val vertices = mutableSetOf<String>() val edges = mutableListOf<Pair<String, String>>() readInput().forEach { val firstComponent = it.substringBefore(": ") vertices.add(firstComponent) it.substringAfter(": ").split(" ").forEach { secondComponent -> vertices.add(secondComponent) val edge = firstComponent to secondComponent val reversedEdge = secondComponent to firstComponent if (edge !in edges && reversedEdge !in edges) edges.add(edge) } } var groups:MutableList<MutableList<String>> do { groups = vertices.map { mutableListOf(it) }.toMutableList() while (groups.size > 2) { val random = edges.random() val subset1 = groups.first { it.contains(random.first) } val subset2 = groups.first { it.contains(random.second) } if (subset1 == subset2) continue groups.remove(subset2) subset1.addAll(subset2) } } while (countCuts(groups.toList(), edges) != 3) return groups.fold(1) { acc, s -> acc * s.size } } private fun countCuts(subsets: List<List<String>>, edges:List<Pair<String,String>>): Int { var cuts = 0 edges.forEach { edge -> val subset1 = subsets.first { it.contains(edge.first) } val subset2 = subsets.first { it.contains(edge.second) } if (subset1 != subset2) cuts++ } return cuts } override fun partTwo(): Any { return "day 25 part 2 not Implemented" } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
1,772
advent-of-code_2023
The Unlicense
core/src/main/kotlin/moe/sdl/yac/sources/ValueSource.kt
Colerar
481,849,090
false
{"Kotlin": 188073}
package moe.sdl.yac.sources import moe.sdl.yac.core.Context import moe.sdl.yac.parameters.options.Option import moe.sdl.yac.parameters.options.longestName import moe.sdl.yac.parameters.options.splitOptionPrefix interface ValueSource { data class Invocation(val values: List<String>) { companion object { /** Create a list of a single Invocation with a single value */ fun just(value: Any?): List<Invocation> = listOf(value(value)) /** Create an Invocation with a single value */ fun value(value: Any?): Invocation = Invocation(listOf(value.toString())) } } fun getValues(context: Context, option: Option): List<Invocation> companion object { /** * Get a name for an option that can be useful as a key for a value source. * * The returned value is the longest option name with its prefix removed * * ## Examples * * ``` * name(option("-h", "--help")) == "help" * name(option("/INPUT")) == "INPUT" * name(option("--new-name", "--name")) == "new-name * ``` */ fun name(option: Option): String { val longestName = option.longestName() requireNotNull(longestName) { "Option must have a name" } return splitOptionPrefix(longestName).second } /** * Create a function that will return string keys for options. * * By default, keys will be equal to the value returned by [name]. * * @param prefix A static string prepended to all keys * @param joinSubcommands If null, keys will not include names of subcommands. If given, * this string be used will join subcommand names to the beginning of keys. For options * that are in a root command, this has no effect. For option in subcommands, the * subcommand name will joined. The root command name is never included. * @param uppercase If true, returned keys will be entirely uppercase. * @param replaceDashes `-` characters in option names will be replaced with this character. */ fun getKey( prefix: String = "", joinSubcommands: String? = null, uppercase: Boolean = false, replaceDashes: String = "-", ): (Context, Option) -> String = { context, option -> var k = name(option).replace("-", replaceDashes) if (joinSubcommands != null) { k = (context.commandNameWithParents().drop(1) + k).joinToString(joinSubcommands) } k = k.replace("-", replaceDashes) if (uppercase) k = k.uppercase() prefix + k } } }
0
Kotlin
0
2
40194f93904bedb1d25bf325fa7a2ebde33f58f1
2,531
Yac
Apache License 2.0
src/main/kotlin/com/hjk/advent22/Day13.kt
h-j-k
572,485,447
false
{"Kotlin": 26661, "Racket": 3822}
package com.hjk.advent22 import com.fasterxml.jackson.databind.ObjectMapper object Day13 { fun part1(input: List<String>): Int = input.chunkedByEmptyLine().foldIndexed(0) { index, acc, (a, b) -> acc + (if (isRightOrder(a.convert(), b.convert()) == true) index + 1 else 0) } fun part2(input: List<String>): Int = listOf(listOf(listOf(2)), listOf(listOf(6))).let { dividerPackets -> (input.filter { it.isNotEmpty() }.map { it.convert() } + dividerPackets) .sortedWith { a, b -> isRightOrder(a, b)?.let { if (it) -1 else 1 } ?: 0 } .let { sorted -> dividerPackets.fold(1) { acc, packet -> acc * (1 + sorted.indexOf(packet)) } } } private fun isRightOrder(aList: List<*>, bList: List<*>): Boolean? { for (index in 0..maxOf(aList.lastIndex, bList.lastIndex)) { val (a, b) = listOf(aList, bList).map { it.getOrNull(index) } val result = when { a == null -> true b == null -> false a is Int && b is Int -> a.takeUnless { it == b }?.let { it < b } a is List<*> && b is List<*> -> isRightOrder(a, b) a is Int && b is List<*> -> isRightOrder(listOf(a), b) a is List<*> && b is Int -> isRightOrder(a, listOf(b)) else -> null } if (result != null) return result } return null } private fun String.convert(): List<*> = ObjectMapper().readValue(this, List::class.java) }
0
Kotlin
0
0
20d94964181b15faf56ff743b8646d02142c9961
1,515
advent22
Apache License 2.0
src/main/kotlin/adventofcode/day16/Valve.kt
jwcarman
573,183,719
false
{"Kotlin": 183494}
/* * Copyright (c) 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 adventofcode.day16 import adventofcode.util.graph.Graph import adventofcode.util.graph.SparseGraph import adventofcode.util.removeAll fun Graph<Valve, Unit>.flowValves() = vertices().filter { it.flowRate > 0 } data class Valve(val label: String, val flowRate: Int) { companion object { fun start() = Valve("AA", 0) fun parseGraph(input: String): Graph<Valve, Unit> { val graph = SparseGraph<Valve, Unit>() val valvesMap = mutableMapOf<String, Valve>() val successorsMap = mutableMapOf<Valve, List<String>>() input.removeAll("Valve ", "has flow rate=", "; tunnels lead to valves", "; tunnel leads to valve") .replace(", ", ",") .lines() .forEach { line -> val splits = line.split(' ') val label = splits[0] val flowRate = splits[1].toInt() val successorLabels = splits[2].split(',').toList() if (flowRate > 0) { val passThrough = Valve(label, 0) valvesMap[label] = passThrough graph.addVertex(passThrough) successorsMap[passThrough] = successorLabels val openValve = Valve(label, flowRate) successorsMap[openValve] = successorLabels graph.addVertex(openValve) graph.addEdge(passThrough, openValve, Unit, 1.0) } else { val valve = Valve(label, 0) valvesMap[label] = valve successorsMap[valve] = successorLabels graph.addVertex(valve) } } successorsMap.forEach { (valve, successorLabels) -> successorLabels.forEach { successorLabel -> val successor = valvesMap[successorLabel]!! graph.addEdge(valve, successor, Unit, 1.0) } } return graph } } } fun List<Valve>.removeFlowValves(vararg valves: Valve): List<Valve> { return valves.filter { it.flowRate > 0 }.fold(this) { list, v -> list - v } }
0
Kotlin
0
0
d6be890aa20c4b9478a23fced3bcbabbc60c32e0
2,890
adventofcode2022
Apache License 2.0
src/main/kotlin/github/walkmansit/aoc2020/Day16.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 class Day16(val input: String) : DayAoc<Int, Long> { private class TicketScanner private constructor( val fieldValidators: LinkedHashMap<String, Array<IntRange>>, val myTicket: Array<Int>, val nearbyTickets: Array<Array<Int>> ) { fun getScanningErrorRate(): Int { /*fun getInvalidNumbersInTicket(ticket:Array<Int>) : List<Int> { val allRanges = fieldValidators.values.flatMap { it.toList() } return ticket.filter { num -> allRanges.all { range -> !range.contains(num) } } }*/ val allRanges = fieldValidators.values.flatMap { it.toList() } return nearbyTickets.flatMap { t -> t.toList() } .filter { num -> allRanges.all { range -> !range.contains(num) } }.sum() } fun getDepartmentValuesMult(): Long { val validTickets: MutableList<Array<Int>> = mutableListOf() val allRanges = fieldValidators.values.flatMap { it.toList() } validTickets.add(myTicket) validTickets.addAll(nearbyTickets.filter { nums -> nums.all { num -> allRanges.any { it.contains(num) } } }) fun getColumnBy(col: Int): Array<Int> { val result = Array(validTickets.size) { 0 } for (i in validTickets.indices) result[i] = validTickets[i][col] return result } fun numsValidForField(nums: Array<Int>, column: String): Boolean { return nums.all { num -> fieldValidators[column]!!.any { r -> r.contains(num) } } } val n = fieldValidators.size val mt = Array(n) { -1 } val g = Array(n) { mutableListOf<Int>() } val used = mutableListOf<Int>() for ((i, key) in fieldValidators.keys.withIndex()) { for (col in myTicket.indices) { if (numsValidForField(getColumnBy(col), key)) { g[i].add(col) } } } fun tryKuhn(v: Int): Boolean { if (used.contains(v)) return false used.add(v) for (i in g[v].indices) { val to = g[v][i] if (mt[to] == -1 || tryKuhn(mt[to])) { mt[to] = v return true } } return false } for (i in g.indices) { used.clear() tryKuhn(i) } var mult = 1L for ((i, v) in mt.withIndex()) { if (v < 6 && i != -1) { mult *= myTicket[i] } } return mult } companion object { private val FIELD_REGEX = Regex("([a-z ]+): (\\d+)-(\\d+) or (\\d+)-(\\d+)") fun fromInput(inp: String): TicketScanner { val parts = inp.split("\n\n") val fields: LinkedHashMap<String, Array<IntRange>> = linkedMapOf() for (field in parts[0].split("\n")) { val fieldMatch = FIELD_REGEX.matchEntire(field)!! fields[fieldMatch.groupValues[1]] = arrayOf( fieldMatch.groupValues[2].toInt()..fieldMatch.groupValues[3].toInt(), fieldMatch.groupValues[4].toInt()..fieldMatch.groupValues[5].toInt() ) } val myTicket = parts[1].split("\n")[1].split(",").map { it.toInt() }.toTypedArray() val nearbyLines = parts[2].split("\n") val height = nearbyLines.size - 1 val width = nearbyLines[1].split(",").size val massive = Array(height) { Array(width) { 0 } } for (i in 0 until height) { val line = nearbyLines[i + 1].split(",").map { it.toInt() } for (j in 0 until width) { massive[i][j] = line[j] } } return TicketScanner(fields, myTicket, massive) } } } override fun getResultPartOne(): Int { return TicketScanner.fromInput(input).getScanningErrorRate() } override fun getResultPartTwo(): Long { return TicketScanner.fromInput(input).getDepartmentValuesMult() } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
4,503
AdventOfCode2020
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions88.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import kotlin.math.min fun test88() { printlnResult(1, 100, 1, 1, 100, 1) } /** * Questions 88: Minimum cost for climbing stairs */ private fun minCost(vararg costs: Int): Int { require(costs.size >= 2) { "The size of costs must greater or equal than 2" } return minCost(costs, costs.lastIndex) } private fun minCost(costs: IntArray, index: Int): Int = when { index < 2 -> costs[index] else -> min(minCost(costs, index - 1), minCost(costs, index - 2)) + costs[index] } private fun minCostInLoop(vararg costs: Int): Int { if (costs.size == 2) return costs.last() require(costs.size > 2) { "The size of costs must greater or equal than 2" } val cache = intArrayOf(costs[0], costs[1]) for (i in 2 ..< costs.size) { val currentCost = min(cache.first(), cache.last()) + costs[i] cache[0] = cache.last() cache[1] = currentCost } return cache.last() } private fun printlnResult(vararg costs: Int) { val result = minCostInLoop(*costs) println("The minimum cost in ${costs.toList()} is ${result}, is ${result == minCost(*costs)}") }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,155
Algorithm
Apache License 2.0
app/src/main/java/online/vapcom/codewars/math/ScreenLockingPatterns.kt
vapcomm
503,057,535
false
{"Kotlin": 142486}
package online.vapcom.codewars.math /* * A B C 0 1 2 * D E F -> 3 4 5 * G H I 6 7 8 */ private val DIRECT_POINTS = arrayOf( intArrayOf(1, 5, 4, 7, 3), // 0 intArrayOf(2, 5, 8, 4, 6, 3, 0), // 1 intArrayOf(5, 7, 4, 3, 1), // 2 intArrayOf(0, 1, 2, 4, 8, 7, 6), // 3 intArrayOf(1, 2, 5, 8, 7, 6, 3, 0), // 4 intArrayOf(2, 8, 7, 6, 4, 0, 1), // 5 intArrayOf(3, 1, 4, 5, 7), // 6 intArrayOf(4, 2, 5, 8, 6, 3, 0), // 7 intArrayOf(5, 7, 3, 4, 1), // 8 ) private val INDIRECT_POINTS = arrayOf( // used -> indirect point arrayOf(Pair(1, 2), Pair(4, 8), Pair(3, 6)), // 0 arrayOf(Pair(4, 7)), // 1 arrayOf(Pair(5, 8), Pair(4, 6), Pair(1, 0)), // 2 arrayOf(Pair(4, 5)), // 3 arrayOf(), // 4 arrayOf(Pair(4, 3)), // 5 arrayOf(Pair(3, 0), Pair(4, 2), Pair(7, 8)), // 6 arrayOf(Pair(4, 1)), // 7 arrayOf(Pair(5, 2), Pair(7, 6), Pair(4, 0)) // 8 ) private class UsedPoints( val used: BooleanArray = BooleanArray(9), var usedNumber: Int = 0 ) { fun use(point: Int) { used[point] = true usedNumber++ } fun isAllUsed(): Boolean = usedNumber >= used.size fun isNotUsed(point: Int): Boolean = !used[point] fun newUsedPoints(point: Int): UsedPoints { val newUsed = UsedPoints(used.clone(), usedNumber) newUsed.use(point) return newUsed } override fun toString(): String { val result = mutableListOf<Int>() used.forEachIndexed { i, b -> if (b) result.add(i) } return result.joinToString() } } /** * Screen Locking Patterns * * https://www.codewars.com/kata/585894545a8a07255e0002f1/train/kotlin * * @return the number of possible patterns starting from a given first point, that have a given length. */ fun countPatternsFrom(firstPoint: String, length: Int): Int { if (firstPoint.isBlank() || firstPoint.first() < 'A' || firstPoint.first() > 'I') return 0 if (length < 2) return length // use letters indexes to simplify work with them val first = firstPoint.first().code - 'A'.code val startLines = DIRECT_POINTS[first] // println("== first: '$first', length: $length, startLines: ${startLines.joinToString { it.toString() }}") var waysCount = 0 val firstUsed = UsedPoints() firstUsed.use(first) startLines.forEach { next -> waysCount += lineTo(next, firstUsed.newUsedPoints(next), length - 1) } return waysCount } private fun lineTo(pointTo: Int, used: UsedPoints, length: Int): Int { // println("${"-".repeat(length)} lineTo: '$pointTo', length: $length, used: '$used'") if (used.isAllUsed()) { // println("${"-".repeat(length)} all used, STOP") return if (length <= 1) 1 else 0 } if (length <= 1) { // println("${"-".repeat(length)} reached length, STOP") return 1 } var ways = 0 val nextPoints = DIRECT_POINTS[pointTo] nextPoints.forEach { next -> if(used.isNotUsed(next)) { // println("${"-".repeat(length)} direct $pointTo->$next ") ways += lineTo(next, used.newUsedPoints(next), length - 1) } else { // println("${"-".repeat(length)} try indirect $pointTo via $next") val indirectPoint = INDIRECT_POINTS[pointTo].find { it.first == next } if (indirectPoint != null && used.isNotUsed(indirectPoint.second)) { // println("${"-".repeat(length)} indirect $pointTo->$next->${indirectPoint.second}") ways += lineTo(indirectPoint.second, used.newUsedPoints(indirectPoint.second), length - 1) } } } // println("${"-".repeat(length)} pointTo: $pointTo, ways: $ways") return ways }
0
Kotlin
0
0
97b50e8e25211f43ccd49bcee2395c4bc942a37a
3,957
codewars
MIT License
year2020/day18/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day18/part1/Year2020Day18Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 18: Operation Order --- As you look out the window and notice a heavily-forested continent slowly appear over the horizon, you are interrupted by the child sitting next to you. They're curious if you could help them with their math homework. Unfortunately, it seems like this "math" follows different rules than you remember. The homework (your puzzle input) consists of a series of expressions that consist of addition (+), multiplication (*), and parentheses ((...)). Just like normal math, parentheses indicate that the expression inside must be evaluated before it can be used by the surrounding expression. Addition still finds the sum of the numbers on both sides of the operator, and multiplication still finds the product. However, the rules of operator precedence have changed. Rather than evaluating multiplication before addition, the operators have the same precedence, and are evaluated left-to-right regardless of the order in which they appear. For example, the steps to evaluate the expression 1 + 2 * 3 + 4 * 5 + 6 are as follows: 1 + 2 * 3 + 4 * 5 + 6 3 * 3 + 4 * 5 + 6 9 + 4 * 5 + 6 13 * 5 + 6 65 + 6 71 Parentheses can override this order; for example, here is what happens if parentheses are added to form 1 + (2 * 3) + (4 * (5 + 6)): 1 + (2 * 3) + (4 * (5 + 6)) 1 + 6 + (4 * (5 + 6)) 7 + (4 * (5 + 6)) 7 + (4 * 11 ) 7 + 44 51 Here are a few more examples: 2 * 3 + (4 * 5) becomes 26. 5 + (8 * 3 + 9 + 3 * 4 * 3) becomes 437. 5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4)) becomes 12240. ((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2 becomes 13632. Before you can help with the homework, you need to understand it yourself. Evaluate the expression on each line of the homework; what is the sum of the resulting values? */ package com.curtislb.adventofcode.year2020.day18.part1 import com.curtislb.adventofcode.year2020.day18.expression.evaluate import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 18, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long { val file = inputPath.toFile() var total = 0L file.forEachLine { total += evaluate(it) } return total } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,422
AdventOfCode
MIT License
src/main/kotlin/07.kts
reitzig
318,492,753
false
null
import java.io.File typealias Color = String data class BagRule private constructor(val color: Color, val canContain: Map<Color, Int>) { companion object { val bagAmountPattern = Regex("(\\d+) ([a-z ]+) bags?") val rulePattern = Regex("^([a-z ]+) bags contain ([0-9a-z, ]+)\\.$") operator fun invoke(englishRule: String): BagRule { val match = rulePattern.matchEntire(englishRule) ?: throw IllegalArgumentException("Invalid rule: '$englishRule'") val color = match.groupValues[1] val contains = if (match.groupValues[2] == "no other bags") { mapOf() } else { match.groupValues[2] .split(", ") .map { bagAmountPattern.matchEntire(it) ?: throw IllegalArgumentException("Invalid bag amount: '$it'") } .map { it.groupValues.drop(1) } .map { Pair(it.last(), it.first().toInt()) } .toMap() } return BagRule(color, contains) } } override fun toString(): String { val included = if (canContain.isEmpty()) { "no other bags" } else { canContain.map { if (it.value > 1) { "${it.value} ${it.key} bags" } else { "${it.value} ${it.key} bag" } }.joinToString(", ") } return "$color bags contain $included." } } data class BagRules(val rules: Set<BagRule>) { fun holdersOf(color: Color): List<Color> { fun directHoldersOf(color: Color): Set<BagRule> = rules.filter { it.canContain.containsKey(color) }.toSet() // Fixpoint "iteration" fun allHoldersOf(someHolders: Set<BagRule>): Set<BagRule> { val directHolders = someHolders.flatMap { directHoldersOf(it.color) }.toSet() val moreHolders = someHolders.union(directHolders) return if (someHolders == moreHolders) { someHolders } else { allHoldersOf(moreHolders) } } return allHoldersOf(directHoldersOf(color)).map { it.color } } fun numberOfBagsIn(color: Color): Int? = numberOfBagsInAll()[color] fun numberOfBagsInAll(): Map<Color, Int?> { val numbers = rules .filter { it.canContain.isEmpty() } .map { Pair(it.color, 0) } .toMap<Color, Int?>().toMutableMap() fun computedNumbers(): Int = numbers.values.count { it != null } // Fixpoint iteration do { val alreadyComputedNumbers = computedNumbers() rules.filter { numbers[it.color] == null } .map { Pair(it.color, it.canContain.map { colorAndCount -> numbers[colorAndCount.key] // the already computed number of bags _in_ a bag of that color ?.plus(1) // the bag of that color itself ?.times(colorAndCount.value) // the number bags of that color this one contains }) } .filter { pair -> pair.second.all { count -> count != null } } .forEach { pair -> numbers[pair.first] = pair.second.requireNoNulls().sum() } } while (alreadyComputedNumbers < computedNumbers()) return numbers } } val bagRules = BagRules(File(args[0]).readLines().map { BagRule(it) }.toSet()) // For checking the parsing: // println(bagRules.rules.map { it.toString() }.joinToString("\n")) // Part 1: println(bagRules.holdersOf("shiny gold").size) // Part 2: println(bagRules.numberOfBagsIn("shiny gold"))
0
Kotlin
0
0
f17184fe55dfe06ac8897c2ecfe329a1efbf6a09
4,016
advent-of-code-2020
The Unlicense
library/src/main/kotlin/io/github/tomplum/libs/algorithm/DijkstrasAlgorithm.kt
TomPlum
317,517,927
false
{"Kotlin": 161096}
package io.github.tomplum.libs.algorithm import java.util.* /** * A single node in a graph traversed by Dijkstra's algorithm. * * @param value The value of the node. Usually contains cartesian positional information. * @param distance The distance to this node from the starting point. */ data class Node<T>(val value: T, val distance: Int): Comparable<Node<T>> { override fun compareTo(other: Node<T>): Int { return distance.compareTo(other.distance) } } /** * Calculates the shortest distance to all nodes in a weighted-graph from the given [startingPositions] * and terminates based on the given [terminates] predicate. * * @param startingPositions A collection of nodes to start from. * @param evaluateAdjacency A function that is passed an instance of the current node and should return a collection of all adjacent nodes or "neighbours" that should be evaluated as part of the pathfinding. * @param processNode An optional function that is applied after the adjacency evaluation for each neighbouring node. Can be used to mutate the state of the node before evaluation. * @param terminates A boolean predicate used to determine when the destination node has been reached. When it evaluates as true, the algorithm is terminated and the shortest path for the current node is returned. * @return The shortest path from the starting nodes to the node that produces true when passed into the [terminates] predicate. */ fun <N> dijkstraShortestPath( startingPositions: Collection<N>, evaluateAdjacency: (currentNode: Node<N>) -> Collection<Node<N>>, processNode: (currentNode: Node<N>, adjacentNode: Node<N>) -> Node<N>, terminates: (currentNode: Node<N>) -> Boolean ): Int { // A map of nodes and the shortest distance from the given starting positions to it val distance = mutableMapOf<N, Int>() // Unsettled nodes that are yet to be evaluated. Prioritised by their distance from the start val next = PriorityQueue<Node<N>>() // Settled nodes whose shortest path has been calculated and need not be evaluated again val settled = mutableSetOf<N>() startingPositions.forEach { startingPosition -> next.offer(Node(startingPosition, 0)) } while(next.isNotEmpty()) { // Take the next node from the queue, ready for evaluation val currentNode = next.poll() // Considered the current node settled now settled.add(currentNode.value) // If the terminal condition has been met // (I.e. the current node is the location we want to find the shortest path to) // then we stop and return the current known shortest distance to it if (terminates(currentNode)) { return currentNode.distance } // Find all the adjacent nodes to the current one (as per the given predicate) // and evaluate each one evaluateAdjacency(currentNode).forEach { adjacentNode -> // Perform any additional processing on the adjacent node before evaluation val evaluationNode = processNode(currentNode, adjacentNode) if (!settled.contains(evaluationNode.value)) { // The new shortest path to the adjacent node is the current nodes distance // plus the weight of the node being evaluated val updatedDistance = currentNode.distance + evaluationNode.distance // If the distance of this new path is shorter than the shortest path we're // already aware of, then we can update it since we've found a shorter one if (updatedDistance < distance.getOrDefault(evaluationNode.value, Int.MAX_VALUE)) { // Track the new shortest path distance[evaluationNode.value] = updatedDistance // Queue up the adjacent node to continue down that path next.add(Node(evaluationNode.value, updatedDistance)) } } } } val message = "Could not find a path from the given starting positions to the node indicated by the terminates predicate." throw IllegalStateException(message) }
2
Kotlin
0
0
c026ab7ae982c34db4f5fbebf3f79b0b8c717ee5
4,182
advent-of-code-libs
Apache License 2.0
src/main/kotlin/days/Day1.kt
jgrgt
433,952,606
false
{"Kotlin": 113705}
package days class Day1 : Day(1) { override fun partOne(): Any { val depths = inputList.map { it.toInt() } val increases = DepthIncreaseCounter.count(depths) println("Increases: $increases") return increases } override fun partTwo(): Any { val depths = inputList.map { it.toInt() } val increases = DepthIncreaseCounter.count(smoother(depths)) println("Increases: $increases") return increases } } fun smoother(depths: List<Int>): List<Int> { return depths.windowed(3, 1, false).map { it.sum() } } data class DepthIncreaseCounter(val count: Int = 0, val previous: Int) { companion object { fun count(depths: List<Int>): Int { if (depths.isEmpty() || depths.size == 1) { return 0 } val start = DepthIncreaseCounter(0, depths[0]) val acc = depths.drop(1).fold(start) { acc, d -> acc.add(d) } return acc.count } } private fun add(depth: Int): DepthIncreaseCounter { return if (depth > previous) { copy(count = count + 1, previous = depth) } else { copy(count = count, previous = depth) } } }
0
Kotlin
0
0
6231e2092314ece3f993d5acf862965ba67db44f
1,264
aoc2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/sortingandsearching/MedianOfTwoSortedArrays.kt
e-freiman
471,473,372
false
{"Kotlin": 78010}
package sortingandsearching // O(log(min(m, n))) fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { val a = if (nums1.size < nums2.size) nums1 else nums2 val b = if (nums1.size < nums2.size) nums2 else nums1 var l = 0 var r = a.size var i: Int var j: Int var found: Boolean do { i = (l + r) / 2 j = (a.size + b.size) / 2 - i found = true if (i > 0 && i <= a.size && j >= 0 && j < b.size && a[i - 1] > b[j]) { r = i - 1 found = false } if (i >= 0 && i < a.size && j > 0 && j <= b.size && b[j - 1] > a[i]) { l = i + 1 found = false } } while (!found) val left = maxOf( if (i > 0 && i <= a.size) a[i - 1] else Int.MIN_VALUE, if (j > 0 && j <= b.size) b[j - 1] else Int.MIN_VALUE) val right = minOf( if (i >= 0 && i < a.size) a[i] else Int.MAX_VALUE, if (j >= 0 && j < b.size) b[j] else Int.MAX_VALUE) return if ((a.size + b.size) % 2 == 0) (left + right) / 2.0 else right / 1.0 } fun main() { println(findMedianSortedArrays(intArrayOf(2,3,4,5,6,7), intArrayOf(1))) }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
1,202
LeetcodeGoogleInterview
Apache License 2.0
dcp_kotlin/src/main/kotlin/dcp/day257/day257.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day257 // day257.kt // By <NAME>, 2019. fun <T: Comparable<T>> smallestWindowBruteForce(list: List<T>): Pair<Int, Int>? { if (list.isEmpty()) return null val sorted = list.sorted() val left = list.zip(sorted).indexOfFirst { it.first != it.second } val right = list.zip(sorted).indexOfLast { it.first != it.second } return if (left == right) null else Pair(left, right) } fun <T: Comparable<T>> smallestWindow(list: List<T>): Pair<Int, Int>? { if (list.isEmpty()) return null // Traverse from left to right, finding the element less than the max seen so far. // This has to be part of the sorting window. // The pair holds the max so far and the index of the element mentioned above. val right = list.foldIndexed(Pair(list.min(), 0)) { idx, acc, value -> val (maxSeen, right) = acc val newMaxSeen = maxOf(maxSeen!!, value) Pair(newMaxSeen, if (value < newMaxSeen) idx else right) }.second // Traverse from right to left, finding the element greater than the min seen so far. // This has to be part of the sorting window. // The pair holds the min so far and the index of the element mentioned above. val left = list.foldRightIndexed(Pair(list.max(), 0)) { idx, value, acc -> val (minSeen, leftN) = acc val newMinSeen = minOf(minSeen!!, value) Pair(newMinSeen, if (value > newMinSeen) idx else leftN) }.second return if (left == right) null else Pair(left, right) }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
1,515
daily-coding-problem
MIT License
src/Day04.kt
ChAoSUnItY
572,814,842
false
{"Kotlin": 19036}
fun main() { fun part1(data: List<List<IntRange>>): Int = data.sumOf { val (l, r) = it.take(2) val intersectedSize = l.intersect(r).size if (intersectedSize == l.count() || intersectedSize == r.count()) 1.toInt() else 0 } fun part2(data: List<List<IntRange>>): Int = data.sumOf { val (l, r) = it.take(2) if (l.intersect(r).isNotEmpty()) 1.toInt() else 0 } fun processData(data: List<String>): List<List<IntRange>> = data.map { it.split(',') .map { range -> range.split('-') .map { n -> n.toInt() } } .map { range -> range[0]..range[1] } } val input = readInput("Day04") val processedInput = processData(input) println(part1(processedInput)) println(part2(processedInput)) }
0
Kotlin
0
3
4fae89104aba1428820821dbf050822750a736bb
954
advent-of-code-2022-kt
Apache License 2.0
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day03/Day03.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * 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 com.pietromaggi.aoc2021.day03 import com.pietromaggi.aoc2021.readInput import java.lang.Integer.parseInt data class DigitsCount(var zeros: Int, var ones: Int) fun digitsCounts(input: List<String>): MutableList<DigitsCount> { val counts: MutableList<DigitsCount> = mutableListOf() input.forEach { line -> line.forEachIndexed() { idx, digit -> if (counts.size <= idx) counts.add(idx, DigitsCount(0, 0)) if ('0' == digit) { counts[idx].zeros++ } else counts[idx].ones++ } } return counts } fun part1(input: List<String>): Int { var gamma = "" var epsilon = "" val counts: MutableList<DigitsCount> = digitsCounts(input) counts.iterator().forEach { digit -> if (digit.zeros > digit.ones) { gamma += "0" epsilon += "1" } else { gamma += "1" epsilon += "0" } } return parseInt(gamma, 2) * parseInt(epsilon, 2) } fun part2(input: List<String>): Int { val co2Scrubber: Int val oxygenGenerator : Int var counts: MutableList<DigitsCount> = digitsCounts(input) var numbers: MutableList<String> = input.toMutableList() while (numbers.size > 1) { counts.forEachIndexed { idx, _ -> counts = digitsCounts(numbers) for (line_idx in numbers.lastIndex downTo 0) { val line = numbers[line_idx] if (counts[idx].zeros > counts[idx].ones) { if ('1' == line[idx]) { numbers.removeAt(line_idx) } } else { if ('0' == line[idx]) { numbers.removeAt(line_idx) } } } if (numbers.size == 1) return@forEachIndexed } } oxygenGenerator = parseInt(numbers[0], 2) counts = digitsCounts(input) numbers = input.toMutableList() while (numbers.size > 1) { counts.forEachIndexed { idx, _ -> if (numbers.size == 1) return@forEachIndexed counts = digitsCounts(numbers) for (line_idx in numbers.lastIndex downTo 0) { val line = numbers[line_idx] if (counts[idx].zeros > counts[idx].ones) { if ('0' == line[idx]) { numbers.removeAt(line_idx) } } else { if ('1' == line[idx]) { numbers.removeAt(line_idx) } } } } } co2Scrubber = parseInt(numbers[0], 2) return oxygenGenerator * co2Scrubber } fun main() { val input = readInput("Day03") println("What is the power consumption of the submarine?") println("My puzzle answer is: ${part1(input)}") println("What is the life support rating of the submarine?") println("My puzzle answer is: ${part2(input)}") }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
3,594
AdventOfCode
Apache License 2.0
src/main/kotlin/days/Day12.kt
MaciejLipinski
317,582,924
true
{"Kotlin": 60261}
package days import days.InstructionType.E import days.InstructionType.F import days.InstructionType.L import days.InstructionType.N import days.InstructionType.R import days.InstructionType.S import days.InstructionType.W class Day12 : Day(12) { override fun partOne(): Any = interpretInstructions(Ferry1()) override fun partTwo(): Any = interpretInstructions(Ferry2(Waypoint(10, -1))) private fun interpretInstructions(ferry: Ferry): Int = inputList .map { FerryInstruction.from(it) } .forEach { ferry.execute(it) } .let { ferry.calculateDistance() } } open class Waypoint(open var posX: Int, open var posY: Int) { fun moveForward(direction: Direction, units: Int) { when (direction) { Direction.N -> posY -= units Direction.S -> posY += units Direction.E -> posX += units Direction.W -> posX -= units else -> throw UnsupportedOperationException() } } open fun rotateLeft(degrees: Int) { rotateRight(360 - degrees) } open fun rotateRight(degrees: Int) { val full90s = degrees / 90 val directions = listOf(Direction.N, Direction.E, Direction.S, Direction.W) when (full90s % directions.size){ 0 -> return 1 -> { val tmp = posX; posX = -posY; posY = tmp } 2 -> { posX = -posX; posY = -posY } 3 -> { val tmp = posX; posX = posY; posY = -tmp } } } } abstract class Ferry( override var posX: Int = 0, override var posY: Int = 0, var facing: Direction = Direction.E ) : Waypoint(posX, posY) { abstract fun execute(instruction: FerryInstruction) fun calculateDistance(): Int = posX + posY } class Ferry1 : Ferry() { override fun execute(instruction: FerryInstruction) { when (instruction.type) { N, S, E, W -> moveForward(Direction.valueOf(instruction.type.toString()), instruction.units) L -> rotateLeft(instruction.units) R -> rotateRight(instruction.units) F -> moveForward(facing, instruction.units) } } override fun rotateLeft(degrees: Int) { rotateRight(360 - degrees) } override fun rotateRight(degrees: Int) { val full90s = degrees / 90 val directions = listOf(Direction.N, Direction.E, Direction.S, Direction.W) val startingIndex = directions.indexOf(facing) facing = directions[(startingIndex + full90s) % directions.size] } } class Ferry2(var waypoint: Waypoint) : Ferry() { override fun execute(instruction: FerryInstruction) { when (instruction.type) { N, S, E, W -> waypoint.moveForward(Direction.valueOf(instruction.type.toString()), instruction.units) L -> waypoint.rotateLeft(instruction.units) R -> waypoint.rotateRight(instruction.units) F -> moveTowardWaypoint(instruction.units) } } private fun moveTowardWaypoint(times: Int) { posX += times * waypoint.posX posY += times * waypoint.posY } } class FerryInstruction(val type: InstructionType, val units: Int) { companion object { fun from(input: String): FerryInstruction { return FerryInstruction( InstructionType.valueOf(input.substring(0, 1)), input.substring(1, input.lastIndex + 1).toInt() ) } } } enum class InstructionType { N, S, E, W, L, R, F }
0
Kotlin
0
0
1c3881e602e2f8b11999fa12b82204bc5c7c5b51
3,556
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/solairerove/algs4/leprosorium/binary_search_tree/CountOfSmallerNumbersAfterSelf.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.binary_search_tree import java.util.* fun main() { println(countSmallerNaiveSquared(intArrayOf(5, 2, 6, 1))) // [2, 1, 1, 0] println(countSmallerBST(listOf(5, 2, 6, 1))) // [2, 1, 1, 0] println(countSmaller(intArrayOf(5, 2, 6, 1))) // [2, 1, 1, 0] } private data class ValueWithIdx(val value: Int, val originalIdx: Int) // O(log(n)) time | O(n) space private fun countSmaller(nums: IntArray): List<Int> { if (nums.isEmpty()) return emptyList() val n = nums.size val arr = Array(n) { ValueWithIdx(0, 0) } for (i in 0 until n) arr[i] = ValueWithIdx(nums[i], i) val res = IntArray(n) mergeSortAndCount(arr, res, 0, n - 1) return res.toList() } private fun mergeSortAndCount(arr: Array<ValueWithIdx>, aux: IntArray, low: Int, high: Int) { if (low >= high) return val mid = low + (high - low) / 2 mergeSortAndCount(arr, aux, low, mid) mergeSortAndCount(arr, aux, mid + 1, high) mergeAndCount(arr, aux, low, mid, high) } private fun mergeAndCount(arr: Array<ValueWithIdx>, aux: IntArray, low: Int, mid: Int, high: Int) { var i = low var j = mid + 1 val merged = LinkedList<ValueWithIdx>() var numElementRightArrayLessThanLeftArray = 0 while (i < mid + 1 && j <= high) { if (arr[i].value > arr[j].value) { ++numElementRightArrayLessThanLeftArray merged.add(arr[j]) ++j } else { aux[arr[i].originalIdx] += numElementRightArrayLessThanLeftArray merged.add(arr[i]) ++i } } while (i < mid + 1) { aux[arr[i].originalIdx] += numElementRightArrayLessThanLeftArray merged.add(arr[i]) ++i } while (j <= high) { merged.add(arr[j]) ++j } var pos = low for (m in merged) { arr[pos] = m ++pos } } // O(nˆ2) time | O(n) space private fun countSmallerNaiveSquared(arr: IntArray): List<Int> { val counts = mutableListOf<Int>() for (i in arr.indices) { var counter = 0 for (j in i + 1 until arr.size) { if (arr[j] < arr[i]) counter++ } counts.add(counter) } return counts } // O(log(n)) time | O(n) space // O(nˆ2) time | O(n) space worst private fun countSmallerBST(arr: List<Int>): List<Int> { if (arr.isEmpty()) return listOf() val counts = arr.toMutableList() val bst = BST() for (i in arr.size - 1 downTo 0) { bst.put(arr[i], counts, i, 0) } return counts } private class BST { private var root: Node? = null inner class Node(var value: Int) { var right: Node? = null var left: Node? = null var segmentLeftCount = 0 } fun put(value: Int, arr: MutableList<Int>, idx: Int, preSum: Int) { root = put(root, value, arr, idx, preSum) } private fun put(root: Node?, value: Int, arr: MutableList<Int>, idx: Int, preSum: Int): Node { var x = root if (x == null) { arr[idx] = preSum x = Node(value = value) } else if (value >= x.value) { val newPreSum = preSum + x.segmentLeftCount + if (value > x.value) 1 else 0 x.right = put(x.right, value, arr, idx, newPreSum) } else { x.segmentLeftCount++ x.left = put(x.left, value, arr, idx, preSum) } return x } }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
3,438
algs4-leprosorium
MIT License
src/main/kotlin/_2023/Day18.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2023 import Coordinate import Day import InputReader import java.math.BigInteger import java.util.* import kotlin.collections.LinkedHashSet import kotlin.math.abs import kotlin.math.absoluteValue import kotlin.time.measureTime class Day18 : Day(2023, 18) { override val firstTestAnswer = 62 override val secondTestAnswer = 952408144115 val directionMap = mapOf( "U" to TOP, "D" to BOTTOM, "L" to LEFT, "R" to RIGHT ) override fun first(input: InputReader): Int { val unparsedDirection = input.asLines().map { val (direction, steps) = it.split(" ") Pair(direction, steps.toInt()) } val map = mutableMapOf<Int, MutableMap<Int, Coordinate>>() var currentCoordinate = Coordinate(0, 0) unparsedDirection.forEach { d -> val (directionChar, steps) = d val direction = directionMap[directionChar]!! repeat(steps) { map.getOrPut(currentCoordinate.x) { mutableMapOf() }[currentCoordinate.y] = direction currentCoordinate += direction } } val minRow = map.minOf { it.key } val maxRow = map.maxOf { it.key } val minColumn = map.minOf { it.value.minOf { row -> row.key } } val maxColumn = map.maxOf { it.value.maxOf { row -> row.key } } val firstInside = Coordinate(minRow - 1, minColumn) val queue: Queue<Coordinate> = LinkedList<Coordinate>().apply { add(firstInside) } val visited = mutableSetOf<Coordinate>() while (queue.isNotEmpty()) { val coordinate = queue.poll() if (!visited.add(coordinate)) { continue } directions.forEach { direction -> val nextCoordinate = coordinate + direction if (nextCoordinate.x in minRow - 1..maxRow + 1 && nextCoordinate.y in minColumn - 1..maxColumn + 1) { if (map.getOrDefault(nextCoordinate.x, mutableMapOf())[nextCoordinate.y] == null) { queue.add(nextCoordinate) } } } } return (((maxRow + 2) - (minRow - 1)) * ((maxColumn + 2) - (minColumn - 1))) - visited.size } override fun second(input: InputReader): Long { val unparsedDirection = input.asLines().map { val hex = it.split(" ").last().drop(2).dropLast(1) val steps = hex.dropLast(1).toLong(radix = 16) val direction = when (hex.last()) { '0' -> RIGHT '1' -> BOTTOM '2' -> LEFT '3' -> TOP else -> error("") } Pair(direction, steps.toInt()) } var perimeter = 0L var currentCoordinate = Coordinate(0, 0) val vertexes = mutableListOf<Coordinate>().apply { add(currentCoordinate) } println(measureTime { unparsedDirection.forEach { d -> val (direction, steps) = d currentCoordinate += Coordinate(direction.x * steps, direction.y * steps) vertexes.add(currentCoordinate) perimeter+=steps } }) // https://en.wikipedia.org/wiki/Shoelace_formula // https://en.wikipedia.org/wiki/Pick%27s_theorem val numbers = vertexes.zipWithNext { first, second -> first.y.toLong() * second.x - first.x.toLong() * second.y } val area = numbers.sum() / 2 return area + perimeter / 2 + 1 } } fun main() { Day18().solve() }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
3,619
advent-of-code
Apache License 2.0
src/main/kotlin/g2101_2200/s2151_maximum_good_people_based_on_statements/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2151_maximum_good_people_based_on_statements // #Hard #Array #Bit_Manipulation #Backtracking #Enumeration // #2023_06_26_Time_308_ms_(100.00%)_Space_46.3_MB_(100.00%) class Solution { fun maximumGood(statements: Array<IntArray>): Int { val known = IntArray(statements.size) known.fill(2) return max(statements, known, 0) } private fun max(statements: Array<IntArray>, known: IntArray, position: Int): Int { return if (position == statements.size) { known.asSequence().filter { a: Int -> a == 1 }.count() } else when (known[position]) { 0 -> assumeBad(statements, known, position) 1 -> assumeGood(statements, known, position) else -> Math.max( assumeBad(statements, known, position), assumeGood(statements, known, position) ) } } private fun assumeBad(statements: Array<IntArray>, known: IntArray, position: Int): Int { val updatedKnown = known.clone() updatedKnown[position] = 0 return max(statements, updatedKnown, position + 1) } private fun assumeGood(statements: Array<IntArray>, known: IntArray, position: Int): Int { val updatedKnown = known.clone() var conflictDetected = false updatedKnown[position] = 1 for (i in statements[position].indices) { val answer = statements[position][i] if (answer != 2) { if (known[i] != 2 && answer != known[i]) { conflictDetected = true break } updatedKnown[i] = answer } } return if (conflictDetected) 0 else max(statements, updatedKnown, position + 1) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,791
LeetCode-in-Kotlin
MIT License
Array/zhangjunwei/6.28-7.4/numOfSubarrays.kt
JessonYue
268,215,243
false
null
package com.lanfairy.md.july class Solution628 { /**https://leetcode-cn.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/solution/ci-ti-zui-you-jie-hua-dong-chuang-kou-jia-dong-tai/ * 思路: step1 : 取出前k个数求和,然后减去k*threshold ,如果结果大于0,说明符合要求。 step2 : 指针后移一位,用后移一位的值减去移动之前的第一位的值,再加上上次减法的结果,如果大于0,说明符合要求 整体思路没有除法,只有增量的加减,而且加减数值非常小。 */ fun numOfSubarrays(arr: IntArray, k: Int, threshold: Int): Int { var count = 0 var i = 0 var sum = 0 while (i < k) { sum += arr[i] i++ } var t = sum - k * threshold if (t >= 0) count++ var len = arr.size - k var pos = k i = 0 while (i < len) { t = arr[pos] - arr[i] + t if (t >= 0) count++ pos++ i++ } return count } } fun main() { var arr = intArrayOf(2, 2, 2, 2, 5, 5, 5, 8) var count = Solution628().numOfSubarrays(arr, 3, 4) print(count) }
0
C
19
39
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
1,283
LeetCodeLearning
MIT License
leetcode2/src/leetcode/generate-parentheses.kt
hewking
68,515,222
false
null
package leetcode /** * 22. 括号生成 * https://leetcode-cn.com/problems/generate-parentheses/ * * 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n = 3,生成结果为: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/generate-parentheses 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object GenerateParentheses { class Solution { fun generateParenthesis(n: Int): List<String> { val ans = mutableListOf<String>() generateAll(CharArray(2 * n),0,ans) return ans } fun generateAll(charArr : CharArray,pos: Int,ans: MutableList<String>) { if (pos == charArr.size - 1) { if (isValid(charArr)) { ans.add(String(charArr)) } } else { charArr[pos] = '(' generateAll(charArr,pos + 1,ans) charArr[pos] = ')' generateAll(charArr,pos + 1, ans) } } fun isValid(charArr: CharArray) : Boolean{ var balance = 0 for (ch in charArr) { if (ch == '(') { balance ++ } else { balance -- } // 确保 ( 号在左边 if (balance < 0) { return false } } return balance == 0 } } } fun main() { println(GenerateParentheses.Solution().generateParenthesis(2)); }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,752
leetcode
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-06.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.BooleanGrid import com.github.ferinagy.adventOfCode.IntGrid import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2015, "06-input") val test1 = readInputLines(2015, "06-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val grid = BooleanGrid(1000, 1000, false) val regex = """(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)""".toRegex() input.forEach { val (command, x1, y1, x2, y2) = regex.matchEntire(it)!!.destructured for (x in x1.toInt() .. x2.toInt()) { for (y in y1.toInt() .. y2.toInt()) { when (command) { "turn off" -> { grid[x, y] = false } "turn on" -> { grid[x, y] = true } "toggle" -> { grid[x, y] = !grid[x, y] } } } } } return grid.count() } private fun part2(input: List<String>): Int { val grid = IntGrid(1000, 1000, 0) val regex = """(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)""".toRegex() input.forEach { val (command, x1, y1, x2, y2) = regex.matchEntire(it)!!.destructured for (i in x1.toInt() .. x2.toInt()) { for (j in y1.toInt() .. y2.toInt()) { when (command) { "turn off" -> { grid[i,j] = (grid[i,j] - 1).coerceAtLeast(0) } "turn on" -> { grid[i,j]++ } "toggle" -> { grid[i,j] += 2 } } } } } return grid.sum() }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,855
advent-of-code
MIT License
src/main/kotlin/com/github/solairerove/algs4/leprosorium/binary_search_tree/SameBSTs.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.binary_search_tree fun main() { println(sameBsts(listOf(1, 2, 3), listOf(1, 2, 3))) // true println(sameBsts(listOf(1, 2, 3), listOf(1, 3, 2))) // false } // O(nˆ2) time | O(d) space // n is number of nodes // d is depth fun sameBsts( arrOne: List<Int>, arrTwo: List<Int>, idxOne: Int = 0, idxTwo: Int = 0, min: Int = Int.MIN_VALUE, max: Int = Int.MAX_VALUE ): Boolean { if (idxOne == -1 || idxTwo == -1) return idxOne == idxTwo if (arrOne[idxOne] != arrTwo[idxTwo]) return false val smallOne = getSmall(arrOne, idxOne, min) val smallTwo = getSmall(arrTwo, idxTwo, min) val bigOne = getBig(arrOne, idxOne, max) val bigTwo = getBig(arrTwo, idxTwo, max) val curr = arrOne[idxOne] val left = sameBsts(arrOne, arrTwo, smallOne, smallTwo, min, curr) val right = sameBsts(arrOne, arrTwo, bigOne, bigTwo, curr, max) return left && right } fun getSmall(arr: List<Int>, idx: Int, min: Int): Int { for (i in idx + 1 until arr.size) { if (arr[i] < arr[idx] && arr[i] >= min) { return i } } return -1 } fun getBig(arr: List<Int>, idx: Int, max: Int): Int { for (i in idx + 1 until arr.size) { if (arr[i] >= arr[idx] && arr[i] < max) { return i } } return -1 }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,381
algs4-leprosorium
MIT License
src/main/kotlin/Main.kt
MisterVitoPro
538,020,117
false
{"Kotlin": 17186}
import mu.KotlinLogging import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt private val logger = KotlinLogging.logger {} fun main() { print("Set Number of Players (2-5): ") val numOfPlayer = Integer.valueOf(readLine()) println("Number of Players set to: $numOfPlayer") print("Human Playing (y/n): ") val humanPlaying: Boolean = readLine().equals("y") val numOfGames = if (!humanPlaying) { print("Set Number of Games to Simulate: ") Integer.valueOf(readLine()) } else { 1 } println("Number of Games set to: $numOfGames") val aggregated: MutableList<Results> = mutableListOf<Results>() (0 until numOfGames).forEach { i -> val r = Game(numOfPlayer, humanPlaying, i.toString()).run() aggregated.add(r) } val averageTurns = aggregated.map { it.turns }.average() val averageSpaces = aggregated.map { it.playerMoves.average() }.average() val playerWins = aggregated.groupingBy { it.winningPlayer.id }.eachCount().toSortedMap() val winsWithHopCards = aggregated.map { it.winningPlayerHopCardsPlayed }.average() logger.info { "--------------- SIMULATION COMPLETE ---------------" } logger.info { "Games Played: ${aggregated.size}" } if (!humanPlaying) { for (w in playerWins) { logger.info { "${w.key} (${w.value} wins) - ${(aggregated[0].players.first { it.id == w.key } as AIPlayer).aiDifficulty}" } } } logger.info { "Average Spaces Moved: ${String.format("%.2f", averageSpaces)}" } logger.info { "Average Number of Turns: ${String.format("%.2f", averageTurns)}" } logger.info { "Average Number of Hop Cards Played by Winner: ${String.format("%.2f", winsWithHopCards)}" } val shortestGame = aggregated.minWith(Comparator.comparingInt { it.turns }) logger.info { "Shortest Game: ${shortestGame.turns} (Game:${shortestGame.gameName})" } // logger.info { "Shortest Game: ${aggregated.map { it.turns }.minByOrNull { it }}" } val longestGame = aggregated.maxWith(Comparator.comparingInt { it.turns }) logger.info { "Longest Game: ${longestGame.turns} (Game:${longestGame.gameName})" } // logger.info { "Longest Game: ${aggregated.map { it.turns }.maxByOrNull { it }}" } logger.info { "Average Game Time: ${String.format("%.2f", (averageTurns * 18 / 60))} minutes." } winPercentageLikelihoodWhenPlayHopCard(aggregated) } fun winPercentageLikelihoodWhenPlayHopCard(aggregated: MutableList<Results>) { val winsWithHopCardPlayed = aggregated.map { it.winningPlayerHopCardsPlayed }.groupingBy { it }.eachCount().toSortedMap() val lossesWithHopCardPlayed = aggregated.map { r -> r.players.filter { it != r.winningPlayer }.map { it.hopCardsPlayed } }.flatten() .groupingBy { it }.eachCount().toSortedMap() for (n in winsWithHopCardPlayed) { if (lossesWithHopCardPlayed[n.key] != null) { logger.info { "Playing ${n.key} Hop Cards: ${ String.format( "%.2f", min((n.value.toDouble() / lossesWithHopCardPlayed[n.key]!!) * 100.00, 100.00) ) }% you are likely to win." } } } }
0
Kotlin
0
0
0ef653d232d6abef8da4c0f39fbf2fbf6d3bd1e4
3,281
Alphabet-crossing-Simulator
Apache License 2.0
y2021/src/main/kotlin/adventofcode/y2021/Day05.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution import adventofcode.util.vector.Vec2 import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.sign object Day05 : AdventSolution(2021, 5, "Hydrothermal Venture") { override fun solvePartOne(input: String) = parseInput(input).filterNot(Line::isDiagonal).countOverlap() override fun solvePartTwo(input: String) = parseInput(input).countOverlap() private fun Sequence<Line>.countOverlap() = flatMap(Line::toPointSequence).groupingBy { it }.eachCount().count { it.value > 1 } private data class Line(private val a: Vec2, private val b: Vec2) { fun isDiagonal() = a.x != b.x && a.y != b.y fun toPointSequence(): Sequence<Vec2> { val delta = (b - a) val step = Vec2(delta.x.sign, delta.y.sign) val length = max(delta.x.absoluteValue, delta.y.absoluteValue) + 1 return generateSequence(a, step::plus).take(length) } } private fun parseInput(input: String): Sequence<Line> { val regex = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex() return input.lineSequence() .map { regex.matchEntire(it)!!.destructured } .map { (x1, y1, x2, y2) -> Line(Vec2(x1.toInt(), y1.toInt()), Vec2(x2.toInt(), y2.toInt())) } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,359
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestObstacleCourse.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 /** * 1964. Find the Longest Valid Obstacle Course at Each Position * @see <a href="https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position"> * Source</a> */ fun interface LongestObstacleCourse { operator fun invoke(obstacles: IntArray): IntArray } class LongestObstacleCourseGreedyBS : LongestObstacleCourse { override operator fun invoke(obstacles: IntArray): IntArray { val n = obstacles.size var lisLength = 0 // lis[i] records the lowest increasing sequence of length i + 1. val answer = IntArray(n) val lis = IntArray(n) for (i in 0 until n) { val height = obstacles[i] // Find the rightmost insertion position idx. val idx = bisectRight(lis, height, lisLength) if (idx == lisLength) lisLength++ lis[idx] = height answer[i] = idx + 1 } return answer } var answer: List<Int>? = null // Find the rightmost insertion position. We use a fixed-length array and a changeable right boundary // to represent an arraylist of dynamic size. private fun bisectRight(a: IntArray, target: Int, right: Int): Int { var r = right if (r == 0) return 0 var left = 0 while (left < r) { val mid = left + (r - left) / 2 if (a[mid] <= target) left = mid + 1 else r = mid } return left } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,096
kotlab
Apache License 2.0
2022/Day14/problems.kt
moozzyk
317,429,068
false
{"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794}
import java.io.File import kotlin.math.max fun main(args: Array<String>) { val lines = File(args[0]).readLines() println(problem1(lines)) println(problem2(lines)) } fun problem1(lines: List<String>): Int { val cave = buildCave(lines, addFloor = false) var numGrains = 0 while (!dropSand(cave)) { numGrains++ } return numGrains } fun problem2(lines: List<String>): Int { val cave = buildCave(lines, addFloor = true) var numGrains = 0 while (!dropSand(cave)) { numGrains++ } return numGrains } fun buildCave(lines: List<String>, addFloor: Boolean): Array<Array<Char>> { var cave = Array<Array<Char>>(200) { Array<Char>(1000) { ' ' } } var maxDepth = 0 lines.forEach { it.split(" -> ").windowed(2).forEach { var (fromCol, fromRow) = it[0].split(",").map { it.toInt() } val (toCol, toRow) = it[1].split(",").map { it.toInt() } maxDepth = max(max(maxDepth, fromRow), toRow) while (fromCol != toCol || fromRow != toRow) { cave[fromRow][fromCol] = '#' if (fromCol < toCol) { fromCol++ } else if (fromCol > toCol) { fromCol-- } else if (fromRow < toRow) { fromRow++ } else if (fromRow > toRow) { fromRow-- } } cave[fromRow][fromCol] = '#' } } if (addFloor) { cave[maxDepth + 2].fill('#') } return cave } fun dropSand(cave: Array<Array<Char>>): Boolean { var row = 0 var col = 500 if (cave[row][col] != ' ') { return true } while (row < cave.size - 1) { if (cave[row + 1][col] == ' ') { row++ } else if (cave[row + 1][col - 1] == ' ') { row++ col-- } else if (cave[row + 1][col + 1] == ' ') { row++ col++ } else { cave[row][col] = 'o' return false } } cave[row][col] = 'o' return true }
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
2,118
AdventOfCode
MIT License
src/problems/1006-clumsy.kt
w1374720640
352,006,409
false
null
package problems /** * 1006.笨阶乘 https://leetcode-cn.com/problems/clumsy-factorial/ * * 解:以N=10为例,clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1 * = (10 * 9 / 8) + (7) + (-6 * 5 / 4) + (3) + (-2 * 1) * 以每个括号内的值为单位,不停累加即可得出最终值 */ fun clumsy(N: Int): Int { require(N >= 0) var result = 0 var i = 0 while (i < N) { val pair = getValue(N, i) result += pair.first // 需要在这里更新索引 i = pair.second } return result } private fun getValue(N: Int, i: Int): Pair<Int, Int> { require(i >= 0) var value = N - i if (i % 4 == 3) return value to i + 1 check(i % 4 == 0) if (i < N - 1) { value *= N - i - 1 if (i < N - 2) { value /= N - i - 2 } } return if (i == 0) { // 只有i==0时返回正数,其他都返回负数 value to 3 } else { value * -1 to i + 3 } } fun main() { check(clumsy(0) == 0) check(clumsy(1) == 1) check(clumsy(2) == 2) check(clumsy(3) == 6) check(clumsy(4) == 7) check(clumsy(10) == 12) println("check succeed.") }
0
Kotlin
0
0
21c96a75d13030009943474e2495f1fc5a7716ad
1,222
LeetCode
MIT License
src/main/kotlin/nl/tiemenschut/aoc/y2023/day15.kt
tschut
723,391,380
false
{"Kotlin": 61206}
package nl.tiemenschut.aoc.y2023 import nl.tiemenschut.aoc.lib.dsl.aoc import nl.tiemenschut.aoc.lib.dsl.day typealias Box = LinkedHashMap<String, Int> fun main() { aoc { puzzle { 2023 day 15 } fun String.christmasHash() = this.fold(0) { acc, c -> (17 * (acc + c.code)).and(0b11111111) } part1 { input -> input.split(",").sumOf { it.christmasHash() } } part2 { input -> val boxes: List<Box> = List(256) { Box() } val operationRegex = "([a-z]*)([-|=])([1-9]?)".toRegex() input.split(",").forEach { it -> val (_, label, operator, f) = operationRegex.find(it)!!.groupValues val box = boxes[label.christmasHash()] when (operator) { "-" -> box.remove(label) else -> if (label in box) box[label] = f.toInt() else box.putLast(label, f.toInt()) } } boxes.mapIndexed { index, box -> var power = 0 var slot = 1 box.forEach { (_, f) -> power += (1 + index) * slot++ * f } power }.sum() } } }
0
Kotlin
0
1
a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3
1,236
aoc-2023
The Unlicense
src/main/kotlin/d14_ExtendedPolymerization/ExtendedPolymerization.kt
aormsby
425,644,961
false
{"Kotlin": 68415}
package d14_ExtendedPolymerization import util.Input import util.Output fun main() { Output.day(14, "Extended Polymerization") val startTime = Output.startTime() // sort input val input = Input.parseLines(filename = "/input/d14_polymer_pairs_insertion_rules.txt") val polymer = input[0].split("").mapNotNull { if (it.isNotBlank()) it else null } as MutableList val instructions = input.drop(2).associateBy( keySelector = { it.slice(0..1) }, valueTransform = { it.takeLast(1) } ) // create 2 maps -- one to count single chars, one to keep track of existing pairs in polymer chain val polySingles = polymer.toSet().associateBy({ it }) { polymer.count { c -> c == it }.toLong() } as MutableMap val polyPairs = polymer.windowed(2).associateBy( keySelector = { it.joinToString("") }, valueTransform = { v -> polymer.windowed(2).count { c -> c == v }.toLong() }) as MutableMap // for part 1 var countStep10 = 0L for (step in 1..40) { // for each polymer chain pair.. polyPairs.filterNot { it.value < 1 }.forEach { pair -> instructions[pair.key]?.also { insert -> // add newly formed pairs from insertion polyPairs.merge(pair.key[0] + insert, pair.value) { a, b -> a + b } polyPairs.merge(insert + pair.key[1], pair.value) { a, b -> a + b } // subtract pair that was split up polyPairs.merge(pair.key, pair.value * -1) { a, b -> a + b } // add inserted letter count to singles map polySingles.merge(insert, pair.value) { a, b -> a + b } } } // store step 10 data for part answer if (step == 10) countStep10 = polySingles.values.maxOf { it } - polySingles.values.minOf { it } } Output.part(1, "10 Steps", countStep10) Output.part(2, "40 Steps", polySingles.maxOf { it.value } - polySingles.minOf { it.value }) Output.executionTime(startTime) }
0
Kotlin
1
1
193d7b47085c3e84a1f24b11177206e82110bfad
2,022
advent-of-code-2021
MIT License
src/Day02.kt
KliminV
573,758,839
false
{"Kotlin": 19586}
fun main() { fun part1(input: List<String>): Int { if (input.isEmpty()) return 0; var totalPoints = 0; for (line in input) { val split = line.split(" "); val playerOneChoice = decrypt(split.get(0)[0]) val playerTwoChoice = decrypt(split.get(1)[0]) totalPoints += playerTwoChoice.points + roundPoints(playerOneChoice, playerTwoChoice) } return totalPoints } fun part2(input: List<String>): Int { if (input.isEmpty()) return 0; var totalPoints = 0; for (line in input) { val split = line.split(" "); val playerOneChoice = decrypt(split.get(0)[0]) val playerTwoGoal = gameResult(split.get(1)[0]) totalPoints += playerTwoGoal + decryptReverse(playerTwoGoal, playerOneChoice) } return totalPoints } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } enum class GameChoice(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3), UNKNOWN(0); } fun decrypt(input: Char): GameChoice { return when (input) { 'A', 'X' -> GameChoice.ROCK 'B', 'Y' -> GameChoice.PAPER 'C', 'Z' -> GameChoice.SCISSORS else -> GameChoice.UNKNOWN } } fun decryptReverse(points: Int, opponentChoice: GameChoice): Int { if (points == 3) return opponentChoice.points return when (opponentChoice) { GameChoice.ROCK -> when (points) { 0 -> GameChoice.SCISSORS.points 6 -> GameChoice.PAPER.points else -> -1 } GameChoice.PAPER -> when (points) { 0 -> GameChoice.ROCK.points 6 -> GameChoice.SCISSORS.points else -> -1 } GameChoice.SCISSORS -> when (points) { 0 -> GameChoice.PAPER.points 6 -> GameChoice.ROCK.points else -> -1 } else -> -1 } } fun gameResult(input: Char): Int { return when (input) { 'X' -> 0 'Y' -> 3 'Z' -> 6 else -> -1 } } fun roundPoints(gameChoice1: GameChoice, gameChoice2: GameChoice): Int { if (gameChoice1 == gameChoice2) return 3 return when (gameChoice1) { GameChoice.ROCK -> if (gameChoice2 == GameChoice.PAPER) 6 else 0 GameChoice.SCISSORS -> if (gameChoice2 == GameChoice.ROCK) 6 else 0 GameChoice.PAPER -> if (gameChoice2 == GameChoice.SCISSORS) 6 else 0 else -> 0 } }
0
Kotlin
0
0
542991741cf37481515900894480304d52a989ae
2,782
AOC-2022-in-kotlin
Apache License 2.0
src/main/kotlin/g1301_1400/s1395_count_number_of_teams/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1395_count_number_of_teams // #Medium #Array #Dynamic_Programming #Binary_Indexed_Tree // #2023_06_06_Time_192_ms_(100.00%)_Space_38.4_MB_(33.33%) @Suppress("NAME_SHADOWING") class Solution { fun numTeams(rating: IntArray): Int { val cp = rating.clone() cp.sort() // count i, j such that i<j and rating[i]<rating[j] val count = Array(cp.size) { IntArray(2) } val bit = IntArray(cp.size) for (i in rating.indices) { count[i][0] = count(bs(cp, rating[i] - 1), bit) count[i][1] = i - count[i][0] add(bs(cp, rating[i]), bit) } // reverse count from right to left, that i<j and rating[i]>rating[j] val reverseCount = Array(cp.size) { IntArray(2) } val reverseBit = IntArray(cp.size) for (i in cp.indices.reversed()) { reverseCount[i][0] = count(bs(cp, rating[i] - 1), reverseBit) reverseCount[i][1] = cp.size - 1 - i - reverseCount[i][0] add(bs(cp, rating[i]), reverseBit) } var result = 0 for (i in rating.indices) { result += count[i][0] * reverseCount[i][1] + count[i][1] * reverseCount[i][0] } return result } private fun count(idx: Int, bit: IntArray): Int { var idx = idx var sum = 0 while (idx >= 0) { sum += bit[idx] idx = (idx and idx + 1) - 1 } return sum } private fun add(idx: Int, bit: IntArray) { var idx = idx if (idx < 0) { return } while (idx < bit.size) { bit[idx] += 1 idx = idx or idx + 1 } } private fun bs(arr: IntArray, `val`: Int): Int { var l = 0 var r = arr.size - 1 while (l < r) { val m = l + (r - l) / 2 if (arr[m] == `val`) { return m } else if (arr[m] < `val`) { l = m + 1 } else { r = m - 1 } } return if (arr[l] > `val`) l - 1 else l } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,123
LeetCode-in-Kotlin
MIT License
src/Day10.kt
proggler23
573,129,757
false
{"Kotlin": 27990}
import kotlin.math.abs fun main() { fun part1(input: List<String>): Long { val cycles = input.cycles() val checkMarks = listOf(IndexedValue(19, cycles[19])) + cycles.asSequence().withIndex().drop(20).take(200).windowed(size = 40, step = 40).map { it.last() } return checkMarks.sumOf { v -> (1 + v.index) * v.value } } fun part2(input: List<String>) { val cycles = input.cycles() repeat(6) {y -> repeat(40) { x-> if (abs(cycles[y*40+x] - x) <= 1) print('#') else print('.') } println() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140L) println() val input = readInput("Day10") println(part1(input)) println(part2(input)) } fun List<String>.cycles(): List<Long> { return flatMap { if (it == "noop") listOf(0L) else listOf(0, it.substringAfter("addx ").toLong()) }.runningFold(1L) { acc, register -> acc + register } }
0
Kotlin
0
0
584fa4d73f8589bc17ef56c8e1864d64a23483c8
1,178
advent-of-code-2022
Apache License 2.0
kotlin/2018/src/main/kotlin/2018/Lib07.kt
nathanjent
48,783,324
false
{"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966}
package aoc.kt.y2018; /** * Day 7. */ data class Node(val id: Char) data class Edge(val before: Char, val after: Char) /** Part 1 */ fun processSteps1(input: String): String { val stepMatch = " [A-Z] ".toRegex() val nodes = mutableSetOf<Node>() val edges = mutableSetOf<Edge>() input.lines().forEach { val (before, after) = stepMatch.findAll(it) .map { it.value.trim().toCharArray() } .filter { it.size == 1 } .map { it.single() } .toList() nodes.add(Node(before)) nodes.add(Node(after)) edges.add(Edge(before, after)) } // Find first step var current: Node? = nodes.find { node -> !edges.map { it.after }.any { it == node.id } } // Find remaining steps val visited = mutableListOf<Char>() while (current != null) { val currentId = current.id visited.add(currentId) val nextList = edges .filter { it.before == currentId } .sortedBy { it.after } .map { it.after } if (!nextList.isEmpty()) { current = nodes.find { it.id == nextList.first() } } else { current = null } } return visited .toString() } /** Part 2 */ fun processSteps2(input: String): String { return "42" }
0
Rust
0
0
7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf
1,341
adventofcode
MIT License
src/Day01.kt
emanguy
573,113,840
false
{"Kotlin": 17921}
fun main() { fun part1(input: List<String>): Int { var maxSum = 0 var currentSum = 0 for (calorieCount in input) { if (calorieCount.isBlank()) { if (currentSum > maxSum) maxSum = currentSum currentSum = 0 continue } currentSum += calorieCount.toInt() } if (currentSum != 0 && maxSum < currentSum) maxSum = currentSum return maxSum } fun addSumToQueue(listToModify: MutableList<Int>, newValue: Int) { listToModify += newValue listToModify.sort() if (listToModify.size > 3) listToModify.removeFirst() } fun part2(input: List<String>): Int { val topSums = mutableListOf<Int>() var currentSum = 0 for (calorieCount in input) { if (calorieCount.isBlank()) { addSumToQueue(topSums, currentSum) currentSum = 0 continue } currentSum += calorieCount.toInt() } if (currentSum != 0) addSumToQueue(topSums, currentSum) println("Part 2 top sums: $topSums") return topSums.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
211e213ec306acc0978f5490524e8abafbd739f3
1,477
advent-of-code-2022
Apache License 2.0
src/Day02.kt
wedrychowiczbarbara
573,185,235
false
null
fun main() { data class Rule(val move: String, val reward: Int) val gameRules = mutableListOf<Rule>( Rule("A X", 4), Rule("A Y", 8), Rule("A Z", 3), Rule("B X", 1), Rule("B Y", 5), Rule("B Z", 9), Rule("C X", 7), Rule("C Y", 2), Rule("C Z", 6), ) fun part1(input: List<String>): Int { var suma=0 input.forEach{ val s = it suma += gameRules.find {it.move == s}?.reward ?: 0 } return suma } val gameRules2 = mutableListOf<Rule>( Rule("A X", 3), Rule("A Y", 4), Rule("A Z", 8), Rule("B X", 1), Rule("B Y", 5), Rule("B Z", 9), Rule("C X", 2), Rule("C Y", 6), Rule("C Z", 7), ) fun part2(input: List<String>): Int { var suma=0 input.forEach{ val s = it suma += gameRules2.find {it.move == s}?.reward ?: 0 } return suma } val input = readInput("input2") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
04abc035c51649dffe1dde8a115d98640552a99d
1,104
AOC_2022_Kotlin
Apache License 2.0
capitulo5/src/main/kotlin/5.30(Adivinhe o número).kt
Cursos-Livros
667,537,024
false
{"Kotlin": 104564}
import kotlin.random.Random //5.30 (Adivinhe o número) Escreva um aplicativo que reproduza “adivinhe o número” da seguinte maneira: //programa escolhe o número a ser adivinhado selecionando um número inteiro aleatório no intervalo de 1 a 1000. //O aplicativo exibe o prompt Adivinhe um número entre 1 e 1000. O jogador insere um primeiro //adivinhar. Se o palpite do jogador estiver incorreto, seu programa deve exibir Muito alto. Tente novamente. ou também //baixo. Tente novamente. para ajudar o jogador a "zerar" a resposta correta. O programa deve solicitar ao //usuário para o próximo palpite. Quando o usuário insere a resposta correta, exibe Parabéns. Você adivinhou o número! e permite que o usuário escolha se quer jogar novamente. //[Nota: A técnica de adivinhação empregada neste problema é semelhante a uma pesquisa binária, que é discutida no Capítulo 19, //Pesquisando, Classificando e Big O.] fun main() { val numeroSorteado = sorteiaNumero() println(numeroSorteado) var palpite = lePalpite() var status = verificaAcerto(numeroSorteado, palpite) while (!status) { verificaErro(numeroSorteado, palpite) println("Você errou digite novamente") palpite = lePalpite() status = verificaAcerto(numeroSorteado, palpite) } } fun sorteiaNumero(): Int { val valorRandom = Random.nextInt(1000) return valorRandom } fun lePalpite(): Int { val input = readLine() ?: "0" return input.toInt() } fun verificaAcerto(numeroSorteado: Int, palpite: Int): Boolean { if (numeroSorteado == palpite) { println("Você acertou") } return numeroSorteado == palpite } fun verificaErro(numeroSorteado: Int, palpite: Int) { if (palpite > numeroSorteado) { println("O numero é maior") } else { println("O numero é menor") } }
0
Kotlin
0
0
f2e005135a62b15360c2a26fb6bc2cbad18812dd
1,866
Kotlin-Como-Programar
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year17/Day10.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year17 import com.grappenmaker.aoc.* fun PuzzleSet.day10() = puzzle(day = 10) { val (a, b) = knotHash(input.split(",").map(String::toInt)).data partOne = (a * b).s() partTwo = totalKnotHash(input.deepen().map { it.code }).display() } private val primeLengths = listOf(17, 31, 73, 47, 23) fun totalKnotHash(data: List<Int>): KnotHashResult { val fullData = data + primeLengths return generateSequence(KnotHashResult()) { knotHash(fullData, it.data, it.curr, it.skip) }.nth(64) } data class KnotHashResult(val data: List<Int> = (0..0xFF).toList(), val curr: Int = 0, val skip: Int = 0) fun KnotHashResult.dense() = data.windowed(16, 16) { it.reduce { acc, curr -> acc xor curr } } fun KnotHashResult.display() = dense().joinToString("") { "%02x".format(it) } fun knotHash( lengths: List<Int>, toHash: List<Int> = (0..0xFF).toList(), initialCurr: Int = 0, initialSkip: Int = 0 ): KnotHashResult { val nums = toHash.toMutableList() var curr = initialCurr var skip = initialSkip var totalRot = 0 for (length in lengths) { if (curr + length >= nums.size) { val rot = -(nums.size - curr - length) totalRot += rot nums.rotateInPlace(-rot) curr = (curr - rot).mod(nums.size) } nums.addAll(curr, nums.removeNAt(length, curr).asReversed()) curr = (curr + length + skip) % nums.size skip++ } nums.rotateInPlace(totalRot) return KnotHashResult(nums, (curr + totalRot) % nums.size, skip) }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,569
advent-of-code
The Unlicense
day05/kotlin/RJPlog/day2305_1_2.kt
mr-kaffee
720,687,812
false
{"Rust": 223627, "Kotlin": 46100, "Python": 39390, "Shell": 3369, "Haskell": 3122, "Dockerfile": 2236, "Gnuplot": 1678, "C++": 980, "HTML": 592, "CMake": 314}
import java.io.File import kotlin.math.* fun fertilizer(): Long { var locationList = mutableListOf<Long>() var newLocationList = mutableListOf<Long>() File("day2305_puzzle_input.txt").forEachLine { if (it.contains("seeds: ")) { locationList = it.substringAfter("seeds: ").split(" ").map { it.toLong() }.toMutableList() newLocationList = it.substringAfter("seeds: ").split(" ").map { it.toLong() }.toMutableList() } if (it.length != 0 && it.first().isDigit()) { var convertInstruction = it.split(" ") var range = LongRange( convertInstruction[1].toLong(), convertInstruction[1].toLong() + convertInstruction[2].toLong() - 1 ) for (i in 0..locationList.size - 1) { if (range.contains(locationList[i])) { newLocationList[i] = locationList[i] - convertInstruction[1].toLong() + convertInstruction[0].toLong() } } } if (it.length == 0) { locationList.clear() locationList.addAll(newLocationList) //println (newLocationList) } } return newLocationList.min()!! } fun main() { var t1 = System.currentTimeMillis() var solution1 = fertilizer() // part 2 brutal force - takes 2 days var solution2: Long = -1 var instruction = File("day2305_puzzle_input.txt").readLines() var seeds = instruction[0] var seedRanges = seeds.substringAfter("seeds: ").split(" ").map { it.toLong() }.toList() seedRanges.chunked(2).forEach { var i: Long = 0 while (i < it.last()) { var location: Long = it.first() + i var newLocation: Long = location instruction.forEach { if (it.length != 0 && it.first().isDigit()) { var convertInstruction = it.split(" ") var range = LongRange( convertInstruction[1].toLong(), convertInstruction[1].toLong() + convertInstruction[2].toLong() - 1 ) if (range.contains(location)) { newLocation = location - convertInstruction[1].toLong() + convertInstruction[0].toLong() } } if (it.length == 0) { location = newLocation } } var x = newLocation if (x < solution2 || solution2 < 0) solution2 = x i += 1 } } // print solution for part 1 println("*******************************") println("--- Day 5: If You Give A Seed A Fertilizer ---") println("*******************************") println("Solution for part1") println(" $solution1 is the lowest location number that corresponds to any of the initial seed numbers") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 is the lowest location number that corresponds to any of the initial seed numbers") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
0
Rust
2
0
5cbd13d6bdcb2c8439879818a33867a99d58b02f
2,740
aoc-2023
MIT License
src/Day02.kt
gojoel
573,543,233
false
{"Kotlin": 28426}
enum class Option { // *** elf options *** A, // rock B, // paper C, // scissors // *** player options *** X, // rock, lose Y, // paper, draw Z; // scissors, win fun value(): Int { return when (this) { X -> 1 Y -> 2 Z -> 3 else -> 0 } } } data class Round(val opponent: Option , val player: Option) { fun isWin() : Boolean { return player == winOption() } fun isDraw() : Boolean { return player == drawOption() } fun winOption(): Option { return when (opponent) { Option.A -> Option.Y Option.B -> Option.Z Option.C -> Option.X else -> throw IllegalArgumentException("Unexpected opponent option $opponent") } } fun loseOption(): Option { return when (opponent) { Option.A -> Option.Z Option.B -> Option.X Option.C -> Option.Y else -> throw IllegalArgumentException("Unexpected opponent option $opponent") } } fun drawOption(): Option { return when (opponent) { Option.A -> Option.X Option.B -> Option.Y Option.C -> Option.Z else -> throw IllegalArgumentException("Unexpected opponent option $opponent") } } } fun main() { val input = readInput("02") // val input = readInput("02_test") fun part1(input: List<String>) : Int { return input.map { line -> Round( Option.valueOf(line.substringBefore(" ")), Option.valueOf(line.substringAfter(" "))) }.sumOf { round -> round.player.value() + if (round.isWin()) { 6 } else if (round.isDraw()) { 3 } else { 0 } } } fun part2(input: List<String>) : Int { return input.map { line -> Round( Option.valueOf(line.substringBefore(" ")), Option.valueOf(line.substringAfter(" "))) }.sumOf { when (it.player) { Option.X -> 0 + it.loseOption().value() Option.Y -> 3 + it.drawOption().value() Option.Z -> 6 + it.winOption().value() else -> 0 } } } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0690030de456dad6dcfdcd9d6d2bd9300cc23d4a
2,495
aoc-kotlin-22
Apache License 2.0
src/Day11/Day11.kt
G-lalonde
574,649,075
false
{"Kotlin": 39626}
package Day11 import readInput import java.math.BigInteger import java.time.LocalDateTime fun main() { fun extractInstructions(input: String): Instruction { val regex = """Monkey (\d+):\s+Starting items: (\d+(?:, \d+)*)\s+Operation: new = old ([+,-,\\,\*]) (old|\d+)\s+Test: divisible by (\d+)\s+If true: throw to monkey (\d+)\s+If false: throw to monkey (\d+)""".toRegex() val groups = regex.find(input)?.groupValues!! val startingItems = Queue<BigInteger>() groups[2] .split(", ") .toList() .map { it.toBigInteger() } .forEach { startingItems.enqueue(it) } return Instruction( monkey = groups[1].toInt(), items = startingItems, operation = groups[3].first(), operationValue = { value -> if (groups[4] == "old") value else groups[4].toBigInteger() }, divisibleBy = groups[5].toInt(), throwToIf = { bool -> if (bool) groups[6].toInt() else groups[7].toInt() } ) } fun operate(firstValue: BigInteger, operator: Char, secondValue: BigInteger): BigInteger { return when (operator) { '*' -> firstValue * secondValue '/' -> firstValue / secondValue '+' -> firstValue + secondValue '-' -> firstValue - secondValue else -> BigInteger("0") } } fun isDivisible(dividend: BigInteger, divisor: BigInteger): Boolean { return (dividend % divisor) == BigInteger("0") } fun part1(input: List<String>): Int { val filteredList = input .filter { it.isNotEmpty() } val monkeys = mutableListOf<Instruction>() for (i in filteredList.indices step 6) { monkeys.add( extractInstructions( filteredList .subList(i, i + 6) .joinToString("") ) ) } val itemInspected = MutableList(monkeys.size) { 0 } for (round in 1..20) { for (instruction in monkeys) { while (!instruction.items.isEmpty()) { val item = instruction.items.dequeue()!! val worryLevel = operate( item, instruction.operation, instruction.operationValue(item) ) / BigInteger("3") val throwTo = instruction.throwToIf( isDivisible( worryLevel, instruction.divisibleBy.toBigInteger() ) ) val monkeyThrownTo = monkeys.first { it.monkey == throwTo } monkeyThrownTo.items.enqueue(worryLevel) itemInspected[instruction.monkey] += 1 } } } val (one, two) = itemInspected.sortedDescending().toList().take(2) return one * two } fun part2(input: List<String>): Long { val filteredList = input .filter { it.isNotEmpty() } val monkeys = mutableListOf<Instruction>() for (i in filteredList.indices step 6) { monkeys.add( extractInstructions( filteredList .subList(i, i + 6) .joinToString("") ) ) } val itemInspected = MutableList(monkeys.size) { 0 } for (round in 1..10000) { for (instruction in monkeys) { while (!instruction.items.isEmpty()) { val item = instruction.items.dequeue()!! val worryLevel = operate(item, instruction.operation, instruction.operationValue(item)) val throwTo = instruction.throwToIf( isDivisible( worryLevel, instruction.divisibleBy.toBigInteger() ) ) val monkeyThrownTo = monkeys.first { it.monkey == throwTo } monkeyThrownTo.items.enqueue(worryLevel) itemInspected[instruction.monkey] += 1 } } if (round in arrayOf(1, 20, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 10000)) { print("[${LocalDateTime.now()}] Round ") println(round) // for (monkey in monkeys.indices) { // println("Monkey $monkey inspected items ${itemInspected[monkey]} times.") // } } } val (one, two) = itemInspected.sortedDescending().toList().take(2) return one.toLong() * two.toLong() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11/Day11_test") // check(part1(testInput) == 10605) { "Got instead : ${part1(testInput)}" } // check(part2(testInput) == 2713310158) { "Got instead : ${part2(testInput)}" } val input = readInput("Day11/Day11") // println("Answer for part 1 : ${part1(input)}") println("Answer for part 2 : ${part2(input)}") } class Instruction( val monkey: Int, val items: Queue<BigInteger>, val operation: Char, val operationValue: (BigInteger) -> BigInteger, val divisibleBy: Int, val throwToIf: (Boolean) -> Int, ) class Queue<T> { private val list = mutableListOf<T>() fun enqueue(item: T) = list.add(item) fun dequeue(): T? { return if (list.isNotEmpty()) list.removeAt(0) else null } fun peek(): T? = list.firstOrNull() fun isEmpty(): Boolean = list.isEmpty() fun size(): Int = list.size fun print() = println(this.list) }
0
Kotlin
0
0
3463c3228471e7fc08dbe6f89af33199da1ceac9
6,009
aoc-2022
Apache License 2.0