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/Day10.kt
lmoustak
573,003,221
false
{"Kotlin": 25890}
fun main() { val addPattern = Regex("""addx (-?\d+)""") fun part1(input: List<String>): Int { val targetCycles = mutableListOf(20, 60, 100, 140, 180, 220) var registerTotal = 0 var register = 1 var cycle = 1 for (line in input) { if (cycle > targetCycles[0]) targetCycles.removeAt(0) if (targetCycles.isEmpty()) return registerTotal val target = targetCycles[0] var value = 0 if (addPattern.matches(line)) { value = addPattern.find(line)!!.groupValues[1].toInt() cycle++ } if (cycle >= target) { registerTotal += register * target } cycle++ register += value } return registerTotal } fun part2(input: List<String>): String { var cycle = 0 var register = 1 val screen = Array(6) { Array(40) { '.' } } for (line in input) { if (cycle < 240) { var move = 0 do { val x = cycle % 40 val y = cycle / 40 if (x in register - 1..register + 1) screen[y][x] = '#' register += move move = if (move == 0) { addPattern.find(line)?.groupValues?.get(1)?.toInt() ?: 0 } else { 0 } cycle++ } while (move != 0) } } return screen.joinToString("\n") { it.joinToString("") } } val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bd259af405b557ab7e6c27e55d3c419c54d9d867
1,729
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/dayfour/DayFour.kt
pauliancu97
619,525,509
false
null
package dayfour import getLines private val REGEX = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex() private data class Interval( val start: Int, val end: Int ) { fun isContaining(other: Interval): Boolean = this.start <= other.start && this.end >= other.end fun isOverlapping(other: Interval): Boolean = !(this.end < other.start || this.start > other.end) } private data class ElvesPair( val first: Interval, val second: Interval ) private fun isInefficientPair(elvesPair: ElvesPair): Boolean = elvesPair.first.isContaining(elvesPair.second) || elvesPair.second.isContaining(elvesPair.first) private fun isReallyInefficientPair(elvesPair: ElvesPair) = elvesPair.first.isOverlapping(elvesPair.second) private fun String.toElvesPair(): ElvesPair? { val match = REGEX.matchEntire(this) ?: return null val firstStart = match.groupValues.getOrNull(1)?.toIntOrNull() ?: return null val firstEnd = match.groupValues.getOrNull(2)?.toIntOrNull() ?: return null val secondStart = match.groupValues.getOrNull(3)?.toIntOrNull() ?: return null val secondEnd = match.groupValues.getOrNull(4)?.toIntOrNull() ?: return null return ElvesPair( first = Interval(firstStart, firstEnd), second = Interval(secondStart, secondEnd) ) } private fun getElvesPairs(path: String): List<ElvesPair> = getLines(path).mapNotNull { it.toElvesPair() } private fun getNumInefficientPairs(elvesPairs: List<ElvesPair>): Int = elvesPairs.count { isInefficientPair(it) } private fun getNumReallyInefficientPairs(elvesPairs: List<ElvesPair>): Int = elvesPairs.count { isReallyInefficientPair(it) } private fun solvePartOne() { val elvesPair = getElvesPairs("day_4.txt") println(getNumInefficientPairs(elvesPair)) } private fun solvePartTwo() { val elvesPair = getElvesPairs("day_4.txt") println(getNumReallyInefficientPairs(elvesPair)) } fun main() { //solvePartOne() solvePartTwo() }
0
Kotlin
0
0
78af929252f094a34fe7989984a30724fdb81498
1,990
advent-of-code-2022
MIT License
2021/kotlin/src/main/kotlin/aoc/days/Day5.kt
tupini07
76,610,908
false
{"Haskell": 35857, "Elixir": 22701, "Clojure": 20266, "Kotlin": 12288, "F#": 4426, "HTML": 4256, "CSS": 4163, "Dockerfile": 1374, "Shell": 963, "C#": 489, "TypeScript": 320, "Emacs Lisp": 299, "Makefile": 182}
package aoc.days import aoc.entities.Vector2d typealias Day5Input = List<Pair<Vector2d, Vector2d>> class Day5 : BaseDay<Day5Input>(5) { override fun prepareData(data: String): Day5Input = data.split("\n").filter { it.isNotEmpty() }.map { instruction -> val (pos1, pos2) = instruction.split(" -> ").map { singlePos -> val (x, y) = singlePos.split(",").map(Integer::parseInt) Vector2d(x, y) } Pair(pos1, pos2) } private fun walkInstruction(start: Vector2d, end: Vector2d): List<Vector2d> { var currentPos = start val result = mutableListOf(currentPos) while (currentPos != end) { val direction = (end - currentPos).sign() currentPos += direction result.add(currentPos) } return result } private fun countPositions(positions: List<Vector2d>): Map<Vector2d, Int> = positions.fold(mutableMapOf<Vector2d, Int>()) { acc, pos -> acc[pos] = acc.getOrDefault(pos, 0) + 1 acc } override fun part1(data: Day5Input): Number { // only consider horizontal or vertical movements val validInstructions = data.filter { val (start, end) = it start.x == end.x || start.y == end.y } // get visited points for every instruction val positionsVisited = validInstructions .map { val (start, end) = it walkInstruction(start, end) } .flatten() return countPositions(positionsVisited).values.filter { it >= 2 }.size } override fun part2(data: Day5Input): Number { // same as part1 but we're considering every instruction val positionsVisited = data .map { val (start, end) = it walkInstruction(start, end) } .flatten() return countPositions(positionsVisited).values.filter { it >= 2 }.size } }
0
Haskell
0
0
4aee7ef03880e3cec9467347dc817b1db8a5fc0f
2,159
advent-of-code
MIT License
src/day11/Day11.kt
diesieben07
572,879,498
false
{"Kotlin": 44432}
package day11 import streamInput private val file = "Day11" //private val file = "Day11Example" sealed interface ItemOperationInput { fun getValue(oldValue: Long): Long object Old : ItemOperationInput { override fun getValue(oldValue: Long): Long { return oldValue } } data class Constant(val value: Long): ItemOperationInput { override fun getValue(oldValue: Long): Long { return value } } companion object { fun parse(input: String): ItemOperationInput { return when (input) { "old" -> Old else -> Constant(input.toLong()) } } } } typealias Operator = Long.(Long) -> Long val operators = mapOf<String, Operator>("+" to Long::plus, "*" to Long::times) data class Operation(val lhs: ItemOperationInput, val rhs: ItemOperationInput, val operator: Operator) { fun getNewValue(oldValue: Long): Long { return this.operator(this.lhs.getValue(oldValue), this.rhs.getValue(oldValue)) } companion object { private val regex = Regex("""new = (old|\d+) (\+|\*) (old|\d+)$""") fun parse(line: String): Operation { val (lhs, op, rhs) = checkNotNull(regex.find(line)).destructured return Operation(ItemOperationInput.parse(lhs), ItemOperationInput.parse(rhs), checkNotNull(operators[op])) } } } class Test(val divisibleBy: Long) { fun matches(value: Long): Boolean { return (value % divisibleBy) == 0L } companion object { private val regex = Regex("""divisible by (\d+)$""") fun parse(line: String): Test { val (d) = checkNotNull(regex.find(line)).destructured return Test(d.toLong()) } } } data class TestResult(val targetMonkey: Int) { companion object { private val regex = Regex("""throw to monkey (\d+)$""") fun parse(line: String): TestResult { val (d) = checkNotNull(regex.find(line)).destructured return TestResult(d.toInt()) } } } data class MonkeyState(val index: Int, val items: MutableList<Long>, val operation: Operation, val test: Test, val resultTrue: TestResult, val resultFalse: TestResult) { companion object { private val indexRegex = Regex("""Monkey (\d+):$""") private val itemsRegex = Regex("""Starting items: ((?:\d+(?:, )?)+)$""") fun parse(input: Iterator<String>): MonkeyState? { if (!input.hasNext()) { return null } val (index) = checkNotNull(indexRegex.find(input.next())).destructured val itemsLine = input.next() val (items) = checkNotNull(itemsRegex.find(itemsLine)).destructured val operation = Operation.parse(input.next()) val test = Test.parse(input.next()) val trueResult: TestResult val falseResult: TestResult val l = input.next() if (l.contains("If true")) { trueResult = TestResult.parse(l) falseResult = TestResult.parse(input.next()) } else { falseResult = TestResult.parse(l) trueResult = TestResult.parse(input.next()) } if (input.hasNext()) input.next() // skip blank line return MonkeyState( index.toInt(), items.split(", ").mapTo(ArrayList()) { it.toLong() }, operation, test, trueResult, falseResult ) } } } fun runSimulation(divisionBy: Long, rounds: Int, monkeys: List<MonkeyState>): List<Long> { val inspectionCounts = MutableList(monkeys.size) { 0L } val moduloBy = monkeys.fold(1L) { acc, monkey -> acc * monkey.test.divisibleBy } repeat(rounds) { for (monkey in monkeys) { val listIt = monkey.items.listIterator() for (item in listIt) { inspectionCounts[monkey.index]++ val newLevel = (monkey.operation.getNewValue(item) / divisionBy) % moduloBy val action = if (monkey.test.matches(newLevel)) monkey.resultTrue else monkey.resultFalse listIt.remove() monkeys[action.targetMonkey].items.add(newLevel) } } } return inspectionCounts } private fun part(divisionBy: Long, rounds: Int) { streamInput(file) { input -> val it = input.iterator() val monkeys = generateSequence { MonkeyState.parse(it) }.toList() val inspectionCounts = runSimulation(divisionBy, rounds, monkeys) val monkeyBusiness = inspectionCounts.sortedDescending().subList(0, 2).reduce(Long::times) println(monkeyBusiness) } } private fun part1() { part(3, 20) } private fun part2() { part(1, 10000) } fun main() { part1() part2() }
0
Kotlin
0
0
0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6
4,911
aoc-2022
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2020/Day3.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.mul /** * --- Day 3: Toboggan Trajectory --- * https://adventofcode.com/2020/day/3 */ class Day3 : Solver { override fun solve(lines: List<String>): Result { val slopesB = listOf(Slope(1, 1), Slope(3, 1), Slope(5, 1), Slope(7, 1), Slope(1, 2)) return Result("${solve(listOf(Slope(3, 1)), lines)}", "${solve(slopesB, lines)}") } private fun solve(slopes: List<Slope>, level: List<String>): Int { val numTrees = mutableListOf<Int>() for (slope in slopes) { var x = slope.dX var y = slope.dY var num = 0 while (y < level.size) { if (level.isTree(x, y)) num++ x += slope.dX y += slope.dY } numTrees.add(num) } return numTrees.mul() } private fun List<String>.isTree(x: Int, y: Int) = this[y][x % this[y].length] == '#' private data class Slope(val dX: Int, val dY: Int) }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
976
euler
Apache License 2.0
src/main/kotlin/com/colinodell/advent2016/Day04.kt
colinodell
495,627,767
false
{"Kotlin": 80872}
package com.colinodell.advent2016 class Day04(val input: List<String>) { fun solvePart1(): Int { return input.map { Room.fromString(it) } .filter { it.isReal } .sumOf { it.sectorId } } fun solvePart2(): Int { return input.map { Room.fromString(it) } .filter { it.isReal } .first { it.realName.contains("north") } .sectorId } class Room(val name: String, val sectorId: Int, val checksum: String) { // Static constructor companion object { fun fromString(input: String): Room { val regex = Regex("""([a-z\-]+)-(\d+)\[(\w+)\]""") val matchResult = regex.matchEntire(input) ?: throw IllegalArgumentException("Invalid input: $input") val name = matchResult.groupValues[1] val sectorId = matchResult.groupValues[2].toInt() val checksum = matchResult.groupValues[3] return Room(name, sectorId, checksum) } } val realChecksum: String get() { return name.replace("-", "") .groupingBy { it } .eachCount() .toList() .sortedWith(compareByDescending<Pair<Char, Int>> { it.second }.thenBy { it.first }) .take(5) .map { it.first } .joinToString("") } val realName: String get() { // Shift cipher val shiftedName = name.map { c -> if (c == '-') { ' ' } else { ('a' + (c - 'a' + sectorId) % 26) } } return shiftedName.joinToString("") } val isReal: Boolean get() { return realChecksum == checksum } } }
0
Kotlin
0
0
8a387ddc60025a74ace8d4bc874310f4fbee1b65
1,979
advent-2016
Apache License 2.0
src/day14/Day14.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day14 import readInput import readTestInput private data class Coordinate(val x: Int, val y: Int) private val Set<Coordinate>.minX get() = minOf { coordinate -> coordinate.x } private val Set<Coordinate>.minY get() = minOf { coordinate -> coordinate.y } private val Set<Coordinate>.maxX get() = maxOf { coordinate -> coordinate.x } private val Set<Coordinate>.maxY get() = maxOf { coordinate -> coordinate.y } private fun List<String>.parseRockCoordinates(): Set<Coordinate> { return this.flatMap { rockFormation -> rockFormation .split(" -> ") .map { rawCoordinate -> val (x, y) = rawCoordinate.split(",") Coordinate(x.toInt(), y.toInt()) } .windowed(size = 2, step = 1, partialWindows = false) { val (start, end) = it if (start.x == end.x) { (minOf(start.y, end.y)..maxOf(start.y, end.y)).map { y -> Coordinate(start.x, y) } } else { (minOf(start.x, end.x)..maxOf(start.x, end.x)).map { x -> Coordinate(x, start.y) } } } .flatten() }.toSet() } private fun leftUnderOf(coordinate: Coordinate): Coordinate = Coordinate(x = coordinate.x - 1, y = coordinate.y + 1) private fun underOf(coordinate: Coordinate): Coordinate = Coordinate(x = coordinate.x, y = coordinate.y + 1) private fun rightUnderOf(coordinate: Coordinate): Coordinate = Coordinate(x = coordinate.x + 1, y = coordinate.y + 1) private enum class CaveParticle { AIR, ROCK, RESTING_SAND } private typealias CaveMap = Map<Coordinate, CaveParticle> private fun Set<Coordinate>.toCaveMap(): CaveMap { val rockCoordinates = this return buildMap { val minY = rockCoordinates.minY.coerceAtMost(0) for (x in rockCoordinates.minX..rockCoordinates.maxX) { for (y in minY..rockCoordinates.maxY) { val coordinate = Coordinate(x = x, y = y) val particle = if (coordinate in rockCoordinates) CaveParticle.ROCK else CaveParticle.AIR put(coordinate, particle) } } } } private val CaveMap.minX get() = this.keys.minX private val CaveMap.minY get() = this.keys.minY private val CaveMap.maxX get() = this.keys.maxX private val CaveMap.maxY get() = this.keys.maxY private fun CaveMap.with(coordinate: Coordinate, particle: CaveParticle): CaveMap = buildMap { putAll(this@with) put(coordinate, particle) } private fun CaveMap.withSandInserted(startCoordinate: Coordinate, floorAt: Int?): Pair<CaveMap, Coordinate?> { val caveMap = this val defaultOrNull: (key: Coordinate) -> CaveParticle? = if (floorAt == null) { _ -> null } else { coordinate -> if (coordinate.y == floorAt) CaveParticle.ROCK else CaveParticle.AIR } var x = startCoordinate.x var y = startCoordinate.y while (true) { val coordinate = Coordinate(x = x, y = y) val particleAtCoordinate = caveMap[coordinate] ?: defaultOrNull(coordinate) val positionUnder = underOf(coordinate) val particleUnder = caveMap[positionUnder] ?: defaultOrNull(positionUnder) val positionLeftUnder = leftUnderOf(coordinate) val particleLeftUnder = caveMap[positionLeftUnder] ?: defaultOrNull(positionLeftUnder) val positionRightUnder = rightUnderOf(coordinate) val particleRightUnder = caveMap[positionRightUnder] ?: defaultOrNull(positionRightUnder) when { particleAtCoordinate in setOf(CaveParticle.RESTING_SAND, CaveParticle.ROCK) -> return caveMap to null particleUnder == null -> return caveMap to null particleUnder == CaveParticle.AIR -> { y += 1 } particleLeftUnder == null -> return caveMap to null particleLeftUnder == CaveParticle.AIR -> { x -= 1 y += 1 } particleRightUnder == null -> return caveMap to null particleRightUnder == CaveParticle.AIR -> { x += 1 y += 1 } else -> return caveMap.with(coordinate, CaveParticle.RESTING_SAND) to coordinate } } } private fun CaveMap.asPrintout(): String { val caveMap = this return buildString { for (y in minY..maxY) { for (x in minX..maxX) { val particle = when (caveMap[Coordinate(x, y)] ?: CaveParticle.AIR) { CaveParticle.AIR -> '.' CaveParticle.ROCK -> '#' CaveParticle.RESTING_SAND -> 'o' } append(particle) } appendLine() } } } private fun CaveMap.fillWithSandFrom(coordinate: Coordinate, floorAt: Int? = null): Int { var computedCaveMap: CaveMap = this var insertions = 0 while (true) { val result = computedCaveMap.withSandInserted(coordinate, floorAt) val targetPosition = result.second computedCaveMap = result.first if (targetPosition == null) break insertions += 1 } return insertions } private val fillCoordinate = Coordinate(x = 500, y = 0) private fun part1(input: List<String>): Int { val rockPositions = input.parseRockCoordinates() val caveMap: CaveMap = rockPositions.toCaveMap() return caveMap.fillWithSandFrom(coordinate = fillCoordinate) } private fun part2(input: List<String>): Int { val rockPositions = input.parseRockCoordinates() val caveMap: CaveMap = rockPositions.toCaveMap() return caveMap.fillWithSandFrom(coordinate = fillCoordinate, floorAt = rockPositions.maxY + 2) } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day14") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
6,117
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/g0301_0400/s0312_burst_balloons/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0301_0400.s0312_burst_balloons // #Hard #Array #Dynamic_Programming #2022_11_09_Time_210_ms_(100.00%)_Space_35.2_MB_(100.00%) class Solution { fun maxCoins(nums: IntArray): Int { if (nums.size == 0) { return 0 } val dp = Array(nums.size) { IntArray(nums.size) } return balloonBurstDp(nums, dp) } private fun balloonBurstDp(nums: IntArray, dp: Array<IntArray>): Int { for (gap in nums.indices) { var si = 0 var ei = gap while (ei < nums.size) { val l = if (si - 1 == -1) 1 else nums[si - 1] val r = if (ei + 1 == nums.size) 1 else nums[ei + 1] var maxAns = -1e7.toInt() for (cut in si..ei) { val leftAns = if (si == cut) 0 else dp[si][cut - 1] val rightAns = if (ei == cut) 0 else dp[cut + 1][ei] val myAns = leftAns + l * nums[cut] * r + rightAns maxAns = Math.max(maxAns, myAns) } dp[si][ei] = maxAns si++ ei++ } } return dp[0][nums.size - 1] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,200
LeetCode-in-Kotlin
MIT License
2019/06 - Universal Orbit Map/kotlin/src/app.kt
Adriel-M
225,250,242
false
null
import java.io.File import java.util.* fun main() { val edges = generateEdges("../input") println("===== Part 1 =====") println(runPart1(edges)) println("===== Part 2 =====") println(runPart2(edges)) } fun runPart1(edges: Map<String, Set<String>>): Int { val queue: Deque<Pair<String, Int>> = ArrayDeque() queue.addLast(Pair("COM", 0)) val queuedNodes = mutableSetOf("COM") var numberOfOrbits = 0 while (queue.size > 0) { val (currPlanet, currNumberOfOrbits) = queue.removeFirst() numberOfOrbits += currNumberOfOrbits edges[currPlanet]?.forEach { if (!queuedNodes.contains(it)) { queue.addLast(Pair(it, currNumberOfOrbits + 1)) queuedNodes.add(it) } } } return numberOfOrbits } fun runPart2(edges: Map<String, Set<String>>): Int { return calculateMinimumOrbitalTransfers(edges, "YOU", "SAN") } fun calculateMinimumOrbitalTransfers(edges: Map<String, Set<String>>, source: String, destination: String): Int { val queue: Deque<String> = ArrayDeque() queue.addLast(source) val queuedNodes = mutableSetOf(source) var numberOfOrbitalTransfers = -2 while (queue.size > 0) { for (i in 0 until queue.size) { val currentPlanet = queue.removeFirst() if (currentPlanet == destination) { return numberOfOrbitalTransfers } edges[currentPlanet]?.forEach { if (!queuedNodes.contains(it)) { queue.addLast(it) queuedNodes.add(it) } } } numberOfOrbitalTransfers += 1 } return -1 } fun generateEdges(path: String): Map<String, Set<String>> { val edges: MutableMap<String, MutableSet<String>> = mutableMapOf() File(path).forEachLine { val (node1, node2) = extractEdge(it) if (!edges.contains(node1)) { edges[node1] = mutableSetOf() } edges[node1]?.add(node2) if (!edges.contains(node2)) { edges[node2] = mutableSetOf() } edges[node2]?.add(node1) } return edges } fun extractEdge(line: String): Pair<String, String> { val splitLine = line.split(")") return Pair(splitLine[0], splitLine[1]) }
0
Kotlin
0
0
ceb1f27013835f13d99dd44b1cd8d073eade8d67
2,327
advent-of-code
MIT License
src/main/kotlin/g0701_0800/s0778_swim_in_rising_water/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0701_0800.s0778_swim_in_rising_water // #Hard #Array #Depth_First_Search #Breadth_First_Search #Binary_Search #Matrix // #Heap_Priority_Queue #Union_Find #2023_03_11_Time_190_ms_(100.00%)_Space_37_MB_(89.47%) import java.util.LinkedList import java.util.Queue class Solution { private val dir = intArrayOf(-1, 0, 1, 0, -1) fun swimInWater(grid: Array<IntArray>): Int { var max = 0 // find the maximum value in the matrix for (ints in grid) { for (j in grid[0].indices) { max = max.coerceAtLeast(ints[j]) } } var l = 0 var r = max var res = 0 // perform binary search while (l <= r) { // find test water level val mid = (l + r) / 2 // if you can reach destination with current water level, store it as an answer and try // lowering water level if (bfs(grid, mid)) { res = mid r = mid - 1 } else { // otherwise increase water level and try again l = mid + 1 } } return res } private fun bfs(grid: Array<IntArray>, limit: Int): Boolean { // use queue to process cells starting from top left corner val que: Queue<IntArray> = LinkedList() // boolean array to keep track of visited cells val visited = Array(grid.size) { BooleanArray( grid[0].size ) } // we start from top left corner que.add(intArrayOf(0, 0)) visited[0][0] = true while (que.isNotEmpty()) { // get current cell val cur = que.poll() val x = cur[0] val y = cur[1] // if value of current cell is greater than limit return false if (grid[x][y] > limit) { return false } // if we reached the destination return true if (x == grid.size - 1 && y == grid[0].size - 1) { return true } // check cells in all 4 directions for (i in 0 until dir.size - 1) { val dx = x + dir[i] val dy = y + dir[i + 1] // if neighboring cell is in bounds, and hasn't been visited yet, // and its value is less than current water level, add it to visited array and to // the queue if (dx >= 0 && dy >= 0 && dx < grid.size && dy < grid[0].size && !visited[dx][dy] && grid[dx][dy] <= limit ) { visited[dx][dy] = true que.add(intArrayOf(dx, dy)) } } } return false } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,812
LeetCode-in-Kotlin
MIT License
aoc-2021/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentyone/Day06.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwentyone import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day06 : Day<Long> { companion object { private const val MIN_DAY = 0L private const val MAX_DAY = 8L private const val RESET_DAY = 6L } private data class State(val fishCountByDay: Map<Long, Long>) { val totalFishCount: Long by lazy { fishCountByDay.values.sum() } } private val initialMap: Map<Long, Long> = (MIN_DAY..MAX_DAY).associateWith { 0L } private val initialState = readDayInput() .split(',') .map { fish -> fish.toLong() } .fold(initialMap) { acc, fish -> acc + (fish to acc.getValue(fish) + 1) } .let { State(fishCountByDay = it) } private fun State.reduce(): State = copy( fishCountByDay = fishCountByDay.mapValues { (day, _) -> when (day) { RESET_DAY -> fishCountByDay.getValue(day + 1) + fishCountByDay.getValue(MIN_DAY) MAX_DAY -> fishCountByDay.getValue(MIN_DAY) else -> fishCountByDay.getValue(day + 1) } } ) private fun State.reduceUntil(day: Long): State { return (0 until day).fold(this) { acc, _ -> acc.reduce() } } override fun step1() = initialState.reduceUntil(day = 80).totalFishCount override fun step2() = initialState.reduceUntil(day = 256).totalFishCount override val expectedStep1 = 380_612L override val expectedStep2 = 1_710_166_656_900L }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
1,523
adventofcode
Apache License 2.0
src/main/kotlin/Day08.kt
nmx
572,850,616
false
{"Kotlin": 18806}
fun main(args: Array<String>) { class Tree(val height: Int) { var visited = false var viewScore = 0 override fun toString(): String { return "$height${if (visited) '*' else ' '} " } } fun countRows(input: List<String>): Int { return input.size } fun countCols(input: List<String>): Int { return input[0].length } fun visit(tree: Tree, maxHeight: Int): Int { return if (tree.height > maxHeight) { tree.visited = true tree.height } else { maxHeight } } fun countFromTop(grid: Array<Array<Tree>>) { for (col in 0 until grid[0].size) { var maxHeight = -1 for (row in 0 until grid.size) { maxHeight = visit(grid[row][col], maxHeight) } } } fun countFromRight(grid: Array<Array<Tree>>) { for (row in 0 until grid.size) { var maxHeight = -1 for (col in grid.size - 1 downTo 0) { maxHeight = visit(grid[row][col], maxHeight) } } } fun countFromBottom(grid: Array<Array<Tree>>) { for (col in 0 until grid[0].size) { var maxHeight = -1 for (row in grid.size - 1 downTo 0) { maxHeight = visit(grid[row][col], maxHeight) } } } fun countFromLeft(grid: Array<Array<Tree>>) { for (row in 0 until grid.size) { var maxHeight = -1 for (col in 0 until grid.size) { maxHeight = visit(grid[row][col], maxHeight) } } } fun part1(grid: Array<Array<Tree>>) { countFromTop(grid) countFromRight(grid) countFromBottom(grid) countFromLeft(grid) grid.forEach{ it.forEach { it2 -> print(it2)} println() } val visibleCount = grid.sumOf { it.filter { tree -> tree.visited }.size } println("Visible: $visibleCount") } fun viewScoreUp(grid: Array<Array<Tree>>, treeRow: Int, treeCol: Int): Int { val height = grid[treeRow][treeCol].height var score = 0 for (row in treeRow - 1 downTo 0) { score++ if (grid[row][treeCol].height >= height) { break } } return score } fun viewScoreRight(grid: Array<Array<Tree>>, treeRow: Int, treeCol: Int): Int { val height = grid[treeRow][treeCol].height var score = 0 for (col in treeCol + 1 until grid[treeRow].size) { score++ if (grid[treeRow][col].height >= height) { break } } return score } fun viewScoreDown(grid: Array<Array<Tree>>, treeRow: Int, treeCol: Int): Int { val height = grid[treeRow][treeCol].height var score = 0 for (row in treeRow + 1 until grid.size) { score++ if (grid[row][treeCol].height >= height) { break } } return score } fun viewScoreLeft(grid: Array<Array<Tree>>, treeRow: Int, treeCol: Int): Int { val height = grid[treeRow][treeCol].height var score = 0 for (col in treeCol - 1 downTo 0) { score++ if (grid[treeRow][col].height >= height) { break } } return score } fun calcViewScore(grid: Array<Array<Tree>>, row: Int, col: Int) { grid[row][col].viewScore = viewScoreUp(grid, row, col) if (grid[row][col].viewScore == 0) return grid[row][col].viewScore *= viewScoreRight(grid, row, col) if (grid[row][col].viewScore == 0) return grid[row][col].viewScore *= viewScoreDown(grid, row, col) if (grid[row][col].viewScore == 0) return grid[row][col].viewScore *= viewScoreLeft(grid, row, col) } fun part2(grid: Array<Array<Tree>>) { for (row in 0 until grid.size) { for (col in 0 until grid[row].size) { calcViewScore(grid, row, col) } } grid.forEach{ it.forEach { it2 -> print("${it2.viewScore} ") } println() } val bestViewScore = grid.maxOf { it -> it.maxOf { tree -> tree.viewScore }} println("Best view score: $bestViewScore") } val input = object {}.javaClass.getResource("Day08.txt").readText().trim().split("\n") val rows = countRows(input) val cols = countCols(input) val protoGrid: Array<Array<Tree?>> = Array(rows) { arrayOfNulls(cols) } input.forEachIndexed { rowIdx, row -> row.forEachIndexed { colIdx, height -> protoGrid[rowIdx][colIdx] = Tree(height.digitToInt()) } } val grid = protoGrid as Array<Array<Tree>> part1(grid) part2(grid) }
0
Kotlin
0
0
33da2136649d08c32728fa7583ecb82cb1a39049
4,898
aoc2022
MIT License
2015/src/main/kotlin/de/skyrising/aoc2015/day7/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2015.day7 import de.skyrising.aoc.* private fun parse(input: PuzzleInput): MutableMap<String, List<String>> { val map = mutableMapOf<String, List<String>>() for (line in input.lines) { val parts = line.split(' ') val name = parts[parts.lastIndex] map[name] = parts.subList(0, parts.size - 2) } return map } private fun eval(map: MutableMap<String, List<String>>, name: String): UShort { val parts = map[name] ?: return name.toUShort() if (parts.size == 1) { return try { parts[0].toUShort() } catch (e: NumberFormatException) { eval(map, parts[0]).also { map[name] = listOf(it.toString()) } } } if (parts[0] == "NOT") { return eval(map, parts[1]).inv().also { map[name] = listOf(it.toString()) } } val x = parts[0] val y = parts[2] return when(parts[1]) { "AND" -> (eval(map, x) and eval(map, y)).also { map[name] = listOf(it.toString()) } "OR" -> (eval(map, x) or eval(map, y)).also { map[name] = listOf(it.toString()) } "LSHIFT" -> (eval(map, x).toInt() shl eval(map, y).toInt()).toUShort().also { map[name] = listOf(it.toString()) } "RSHIFT" -> (eval(map, x).toInt() shr eval(map, y).toInt()).toUShort().also { map[name] = listOf(it.toString()) } else -> throw IllegalArgumentException(parts[1]) } } val test = TestInput(""" 123 -> x 456 -> y x AND y -> d x OR y -> e x LSHIFT 2 -> f y RSHIFT 2 -> g NOT x -> h NOT y -> i """) @PuzzleName("Some Assembly Required") fun PuzzleInput.part1() = eval(parse(this), "a") fun PuzzleInput.part2(): Any { val map = parse(this) val map2 = HashMap(map) map2["b"] = listOf(eval(map, "a").toString()) return eval(map2, "a") }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
1,814
aoc
MIT License
src/main/java/org/billthefarmer/solver/Solver.kt
billthefarmer
453,687,125
false
{"Java": 29517, "Kotlin": 3366, "HTML": 1565}
package org.billthefarmer.solver class Solver(private var g: List<String>, var y1: List<String>, var y2: List<String>, var y3: List<String>, private var gray: String) { // g green: is correct and in the correct position // y yellow: is in answer but not in the right position // gray: is not in the answer at all fun solve(): List<List<String>> { if (g.joinToString("").trim().isEmpty()) g = listOf() if (y1.joinToString("").trim().isEmpty()) y1 = listOf() if (y2.joinToString("").trim().isEmpty()) y2 = listOf() if (y3.joinToString("").trim().isEmpty()) y3 = listOf() gray = gray.trim() var words = getAllDicWords().toList() if (g.isNotEmpty()) { words = words.filter { w -> (w[0] == g[0] || g[0] == "") && (w[1] == g[1] || g[1] == "") && (w[2] == g[2] || g[2] == "") && (w[3] == g[3] || g[3] == "") && (w[4] == g[4] || g[4] == "") } } if (y1.isNotEmpty()) { words = filterOutYellow(y1, words) } if (y2.isNotEmpty()) { words = filterOutYellow(y2, words) } if (y3.isNotEmpty()) { words = filterOutYellow(y3, words) } // letters remove from gray @Suppress("UNUSED_VARIABLE") var removeWs = mutableListOf<String>().apply { addAll(g) addAll(y1) addAll(y2) addAll(y3) forEach { gray = gray.replace(it, "") } } if (gray.isNotEmpty()) { words = words.filter { w -> w.none { gray.contains(it) } } } return words } fun filterOutYellow(y: List<String>, words: List<List<String>>) = run { words.filter { w -> ((w[0] != y[0]) && (w[1] != y[1]) && (w[2] != y[2]) && (w[3] != y[3]) && (w[4] != y[4])) }.filter { w -> val wordSt: String = w.joinToString("") y.all { wordSt.contains(it) } } } companion object { private var dicWords: List<List<String>> = listOf() private fun getAllDicWords(): List<List<String>> { if (dicWords.isEmpty()) { var tempDicWords = mutableListOf<List<String>>() var tempWords = mutableListOf<String>() tempWords.addAll(Words.getWords()) tempWords.sort() tempWords.forEach { val w = it.split("").toMutableList() w.removeFirst() w.removeLast() tempDicWords.add(w) } dicWords = tempDicWords.toList() } return dicWords } fun emptyDicWords() { dicWords = listOf() } } } fun joinListColumns(words: List<List<String>>, numOfColumn: Int): String { var sb: StringBuffer = StringBuffer() var counter = 1 words.forEach { sb.append(it.joinToString("") + " ") if (counter++ % numOfColumn == 0) sb.append("\n") } return sb.toString() }
0
Java
3
12
6e2b9a3a138e835516c283e14161ff2a37f3ad2c
3,366
wordlesolver
Apache License 2.0
src/main/kotlin/day19/part1/Part1.kt
bagguley
329,976,670
false
null
package day19.part1 import day19.data val ruleMap: MutableMap<Int, Rule> = mutableMapOf() fun main() { val rules = parseRules(data[0].split("\n")) val input = parseInput(data[1].split("\n")) for (rule in rules) { ruleMap[rule.index] = rule } val valid = rules[0].validStrings(ruleMap) var count = 0 for (str in input) { if (str in valid) count++ } println(count) } fun parseInput(input: List<String>): List<String> { return input.filter { it.isNotEmpty() } } fun parseRules(input: List<String>): List<Rule> { return input.filter { it.isNotEmpty() }.map{parseRule(it)}.sortedBy { it.index } } fun parseRule(input: String): Rule { val split = input.split(": ") val index = split[0].toInt() val rule = split[1] return parseRuleString(index, rule) } fun parseRuleString(index: Int, rule: String): Rule { return if (rule.contains("\"")) { StringRule(index, rule.substring(1, rule.length-1)) } else { if (rule.contains("|")) { val leftRule = rule.split(" | ")[0] val rightRule = rule.split(" | ")[1] OrRule(index, leftRule, rightRule) } else { PairRule(index, rule) } } }
0
Kotlin
0
0
6afa1b890924e9459f37c604b4b67a8f2e95c6f2
1,242
adventofcode2020
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/New21Game.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 /** * 837. New 21 Game * @see <a href="https://leetcode.com/problems/new-21-game/">Source</a> */ fun interface New21Game { operator fun invoke(n: Int, k: Int, maxPts: Int): Double } class New21GameDP : New21Game { override operator fun invoke(n: Int, k: Int, maxPts: Int): Double { val p1 = 1.0 / maxPts.toDouble() val cache = Array(n + 1) { -1.0 } // f(x) = (f(x+1) + f(x+2)+..+f(x + maxPts))*p1 // f(x + 1) = (f(x+2) + f(x+3) +...+f(x + maxPts)*p1 + f(x + 1 + maxPts))*p1 // f(x) - f(x + 1) = f(x+1)*p1 - f(x+1+maxPts)*p1 // f(x) = f(x+1) + (f(x+1) - f(x+1+maxPts))*p1 fun dfs(currSum: Int): Double { if (currSum == k - 1) return minOf(1.0, (n - k + 1) * p1) // corner case if (currSum >= k) return if (currSum <= n) 1.0 else 0.0 if (cache[currSum] != -1.0) return cache[currSum] val res = dfs(currSum + 1) + (dfs(currSum + 1) - dfs(currSum + 1 + maxPts)) * p1 cache[currSum] = res return res } return dfs(0) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,718
kotlab
Apache License 2.0
solver/src/commonMain/kotlin/org/hildan/sudoku/solver/techniques/NFish.kt
joffrey-bion
9,559,943
false
{"Kotlin": 51198, "HTML": 187}
package org.hildan.sudoku.solver.techniques import org.hildan.sudoku.model.* object XWing : NFish("X-Wing", dimension = 2) object Swordfish : NFish("Swordfish", dimension = 3) object Jellyfish : NFish("Jellyfish", dimension = 4) object Squirmbag : NFish("Squirmbag", dimension = 5) open class NFish( private val techniqueName: String, private val dimension: Int, ) : Technique { /** * Possible groups of [dimension] indices in a line. */ private val cellIndicesSets = (0 until Grid.SIZE).toSet().allTuplesOfSize(dimension) override fun attemptOn(grid: Grid): List<FishStep> = buildList { ALL_DIGITS.forEach { digit -> addAll(findFishes(digit, grid.rows, grid.cols)) addAll(findFishes(digit, grid.cols, grid.rows)) } } private fun findFishes( digit: Int, definingUnits: List<GridUnit>, secondaryUnits: List<GridUnit>, ): List<FishStep> { val fishes = mutableListOf<FishStep>() val groups = definingUnits.groupUnitsByIndicesOfOccurrenceOf(digit = digit) groups.forEach { (indices, definingSet) -> if (definingSet.size == dimension) { val secondarySet = secondaryUnits.slice(indices) val removals = candidateRemovalActions( digit = digit, definingSet = definingSet, secondarySet = secondarySet, ) if (removals.isNotEmpty()) { fishes.add( FishStep( techniqueName = techniqueName, digit = digit, cells = indices, definingSet = definingSet, secondarySet = secondarySet.toSet(), actions = removals, ) ) } } } return fishes } private fun candidateRemovalActions( digit: Int, definingSet: Set<GridUnit>, secondarySet: List<GridUnit>, ): List<Action.RemoveCandidate> { val definingCells = definingSet.flatMapTo(HashSet()) { it.cells } return secondarySet.flatMap { secondaryUnit -> secondaryUnit.cells.filter { it.isEmpty && digit in it.candidates && it !in definingCells }.map { Action.RemoveCandidate(digit, it.index) } } } private fun List<GridUnit>.groupUnitsByIndicesOfOccurrenceOf(digit: Digit): Map<Set<Int>, Set<GridUnit>> { return cellIndicesSets.associateWith { cellsTuple -> // we consider all units who have candidates for the given digit only in the current set of cells filterTo(HashSet()) { unit -> val digitIndices = unit.indicesWithDigit(digit) digitIndices.isNotEmpty() && cellsTuple.containsAll(digitIndices) } } } private fun GridUnit.indicesWithDigit(digit: Digit): Set<Int> { return (0 until Grid.SIZE).filterTo(HashSet()) { cells[it].isEmpty && digit in cells[it].candidates } } } /** X-Wing, Swordfish, Jellyfish, Squirmbag */ data class FishStep( override val techniqueName: String, val digit: Int, val cells: Set<CellIndex>, val definingSet: Set<GridUnit>, val secondarySet: Set<GridUnit>, override val actions: List<Action.RemoveCandidate>, ): Step { override val description: String get() = "Within ${definingSet}, the digit $digit only appears in the same positions $secondarySet. " + "We know there must be ${definingSet.size} in those" }
0
Kotlin
0
0
441fbb345afe89b28df9fe589944f40dbaccaec5
3,697
sudoku-solver
MIT License
src/shreckye/coursera/algorithms/Course 3 Programming Assignment #1 Question 3.kts
ShreckYe
205,871,625
false
{"Kotlin": 72136}
package shreckye.coursera.algorithms import java.util.* val filename = args[0] val INDEX_LABEL_OFFSET = 1 val (numVertices, _, verticesEdges) = readUndirectedGraphVerticesArrayListSimplifiedEdgesFromEdges( filename, INDEX_LABEL_OFFSET ) data class VertexCost(val vertex: Int, val cost: Int) fun mstOverallCost(verticesEdges: VerticesArrayListSimplifiedEdges, numVertices: Int, initialVertex: Int): Int { var mstOverallCost = 0 val vertexCostHeap = CustomPriorityQueue(numVertices, compareBy(VertexCost::cost)) val vertexCostHeapHolders = arrayOfNulls<CustomPriorityQueue.Holder<VertexCost>>(numVertices) val spanned = BitSet(numVertices) val INITIAL_COST = Int.MAX_VALUE val minCosts = IntArray(numVertices) { INITIAL_COST } minCosts[initialVertex] = Int.MIN_VALUE vertexCostHeapHolders[initialVertex] = vertexCostHeap.offerAndGetHolder(VertexCost(initialVertex, 0)) repeat(numVertices) { val (vertex, cost) = vertexCostHeap.poll() vertexCostHeapHolders[vertex] = null spanned[vertex] = true mstOverallCost += cost for ((head, headCost) in verticesEdges[vertex]) { /* Must check whether it's spanned already, because minCosts at a spanned vertex stores a min cost from previously spanned vertex sets to this vertex, thus might be greater than current cost. This is different from the implementation of Dijkstra's algorithm where we can ignore checking. */ if (!spanned[head]) { //println("$vertex $head $headCost ${minCosts[head]}") if (minCosts[head] == INITIAL_COST) { minCosts[head] = headCost vertexCostHeapHolders[head] = vertexCostHeap.offerAndGetHolder(VertexCost(head, headCost)) } else if (headCost < minCosts[head]) { minCosts[head] = headCost vertexCostHeapHolders[head] = vertexCostHeap.replaceByHolder(vertexCostHeapHolders[head]!!, VertexCost(head, headCost)) } } } } assert(vertexCostHeap.isEmpty()) { "size = ${vertexCostHeap.size}" } return mstOverallCost } println(mstOverallCost(verticesEdges, numVertices, 1 - INDEX_LABEL_OFFSET)) // Test cases (0 until numVertices).map { mstOverallCost(verticesEdges, numVertices, it) }.assertAllEqualsAndGet()
0
Kotlin
1
2
1746af789d016a26f3442f9bf47dc5ab10f49611
2,419
coursera-stanford-algorithms-solutions-kotlin
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem207/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem207 /** * LeetCode page: [207. Course Schedule](https://leetcode.com/problems/course-schedule/); */ class Solution { /* Complexity: * Time O(V+E) and Space O(V+E) where V equals numCourses and E is the size of prerequisites; */ fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean { val visited = BooleanArray(numCourses) val adjacencyList = adjacencyList(prerequisites) // entry = (course, its prerequisites) fun hasCyclicPrerequisites(course: Int, currentPath: MutableSet<Int>): Boolean { if (visited[course]) { return currentPath.contains(course) } visited[course] = true currentPath.add(course) for (prerequisite in (adjacencyList[course] ?: emptyList())) { if (hasCyclicPrerequisites(prerequisite, currentPath)) { return true } } currentPath.remove(course) return false } val courses = 0 until numCourses return courses.none { hasCyclicPrerequisites(it, hashSetOf()) } } private fun adjacencyList(prerequisites: Array<IntArray>): Map<Int, List<Int>> { val result = hashMapOf<Int, MutableList<Int>>() for ((course, prerequisite) in prerequisites) { result .computeIfAbsent(course) { mutableListOf() } .add(prerequisite) } return result } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,525
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/days/Day10.kt
MisterJack49
574,081,723
false
{"Kotlin": 35586}
package days class Day10 : Day(10) { override fun partOne(): Any { val cpu = CPU() inputList.map { it.split(" ") } .map { Command.valueOf(it.first()) to if (it.first() == "addx") it.last().toInt() else 0 } .forEach { cpu.runCommand(it.first, it.second) } println("CPU signal strength logs: ${cpu.signalStrengthLog}") return cpu.signalStrengthLog.sumOf { it.first * it.second } } override fun partTwo(): Any { val cpu = CPU() inputList.map { it.split(" ") } .map { Command.valueOf(it.first()) to if (it.first() == "addx") it.last().toInt() else 0 } .forEach { cpu.runCommand(it.first, it.second) } val crt = CRT(List(6) { mutableListOf<Char>() }) crt.buildImage(cpu.registerLog) println("CRT image:") crt.screen.forEach { println(it.joinToString("")) } return crt.screen } } data class CPU(var register: Int = 1, var cycles: Int = 1) { val signalStrengthLog = mutableListOf<Pair<Int, Int>>() val registerLog = mutableListOf<Int>() fun runCommand(command: Command, value: Int = 0) { for (i in 0 until command.cycles) { logSignalStrength() logRegister() cycles += 1 } if (command == Command.addx) { register += value } } private fun logSignalStrength() = if (cycles == 20 || (signalStrengthLog.isNotEmpty() && cycles == signalStrengthLog.last().first + 40)) signalStrengthLog.add(cycles to register) else false private fun logRegister() = registerLog.add(register) } data class CRT(val screen: List<MutableList<Char>>) { private var spritePosition = 0..2 fun buildImage(cpuRegisterLog: List<Int>) { cpuRegisterLog.chunked(40) .forEachIndexed(::buildRow) } private fun buildRow(row: Int, cpuRegisterLog: List<Int>) { cpuRegisterLog.forEachIndexed { index, register -> updateSpritePosition(register) screen[row].add(if (index in spritePosition) '#' else '.') } } private fun updateSpritePosition(register: Int) { spritePosition = register - 1..register + 1 } } enum class Command(val cycles: Int) { noop(1), addx(2) }
0
Kotlin
0
0
e82699a06156e560bded5465dc39596de67ea007
2,331
AoC-2022
Creative Commons Zero v1.0 Universal
archive/src/main/kotlin/com/grappenmaker/aoc/year15/Day19.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year15 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.asPair import com.grappenmaker.aoc.splitAt fun PuzzleSet.day19() = puzzle(day = 19) { val (rulesPart, molecule) = input.split("\n\n") val rules = rulesPart.lines().map { it.split(" => ").asPair() } fun Pair<String, String>.replacements(on: String) = on.indices.mapNotNull { idx -> if (on.regionMatches(idx, first, 0, first.length)) { val (before, after) = on.toList().splitAt(idx) (before + second + after.drop(first.length)).joinToString("") } else null } partOne = rules.fold(setOf<String>()) { acc, curr -> acc + curr.replacements(molecule) }.size.s() fun Pair<String, String>.replaceOnce(on: String) = if (first !in on) null else on.replaceFirst(first, second) val reverseRules = rules.map { (a, b) -> b to a } // When the random "hillclimbing" works :facepalm: // This is probably not garaunteed to work all the time, but it worked for my input // (and it is blazingly fast) // Other attempts include: // - naive BFS // - dijkstra with levenshtein distance // - dijkstra with memoized levenshtein distance // - greedy algorithm trying the biggest replacement (invalid) // - greedy backtracking // If this were to check all permutations, since there are 43 rules in my case, 43! = big (panic) // But since this is random, we could technically say this runs O(1)... lol // Proper solution: CYK, but no experience with it fun solvePartTwo(): String { val r = reverseRules.toMutableList() while (true) { r.shuffle() var curr = molecule var result = 0 while (true) { var updated = curr r.forEach { while (true) { updated = it.replaceOnce(updated) ?: break result++ } } if (curr == updated) break curr = updated } if (curr == "e") return result.s() } } partTwo = solvePartTwo() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,184
advent-of-code
The Unlicense
src/main/kotlin/g0301_0400/s0399_evaluate_division/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0301_0400.s0399_evaluate_division // #Medium #Array #Depth_First_Search #Breadth_First_Search #Graph #Union_Find #Shortest_Path // #2022_11_29_Time_183_ms_(91.49%)_Space_34.6_MB_(95.74%) @Suppress("kotlin:S6518") class Solution { private var root: MutableMap<String?, String?>? = null private var rate: MutableMap<String?, Double>? = null fun calcEquation( equations: List<List<String?>>, values: DoubleArray, queries: List<List<String?>> ): DoubleArray { root = HashMap() rate = HashMap() val n = equations.size for (equation in equations) { val x = equation[0] val y = equation[1] (root as HashMap<String?, String?>)[x] = x (root as HashMap<String?, String?>)[y] = y (rate as HashMap<String?, Double>)[x] = 1.0 (rate as HashMap<String?, Double>)[y] = 1.0 } for (i in 0 until n) { val x = equations[i][0] val y = equations[i][1] union(x, y, values[i]) } val result = DoubleArray(queries.size) for (i in queries.indices) { val x = queries[i][0] val y = queries[i][1] if (!(root as HashMap<String?, String?>).containsKey(x) || !(root as HashMap<String?, String?>).containsKey(y) ) { result[i] = -1.0 continue } val rootX = findRoot(x, x, 1.0) val rootY = findRoot(y, y, 1.0) result[i] = if (rootX == rootY) (rate as HashMap<String?, Double>).get(x)!! / (rate as HashMap<String?, Double>).get(y)!! else -1.0 } return result } private fun union(x: String?, y: String?, v: Double) { val rootX = findRoot(x, x, 1.0) val rootY = findRoot(y, y, 1.0) root!![rootX] = rootY val r1 = rate!![x]!! val r2 = rate!![y]!! rate!![rootX] = v * r2 / r1 } private fun findRoot(originalX: String?, x: String?, r: Double): String? { if (root!![x] == x) { root!![originalX] = x rate!![originalX] = r * rate!![x]!! return x } return findRoot(originalX, root!![x], r * rate!![x]!!) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,300
LeetCode-in-Kotlin
MIT License
src/main/kotlin/de/tek/adventofcode/y2022/day08/TreeTopTreeHouse.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.day08 import de.tek.adventofcode.y2022.util.math.Direction import de.tek.adventofcode.y2022.util.math.Grid import de.tek.adventofcode.y2022.util.math.Point import de.tek.adventofcode.y2022.util.math.isIn import de.tek.adventofcode.y2022.util.readInputLines class TreeGrid(treeSizes: Array<Array<Int>>) : Grid<Int, Tree>(treeSizes, { _, size -> Tree(size) }) { private val trees = grid fun getNumberOfVisibleTrees(): Int { setBorderVisibleFromOutside() gridCells() .filter { (_, tree) -> tree.isVisible() == null } .forEach { (position, tree) -> checkNeighbours(position, tree) } return allTrees().count { it.isVisible() == true } } private fun setBorderVisibleFromOutside() { for (tree in trees[0]) { tree.setVisible(Direction.UP) } for (tree in trees[maxRow]) { tree.setVisible(Direction.DOWN) } for (row in 0..maxRow) { trees[row][0].setVisible(Direction.LEFT) trees[row][maxColumn].setVisible(Direction.RIGHT) } } private fun gridCells(): Sequence<Pair<GridPosition, Tree>> = IntRange(0, maxRow).flatMap { row -> IntRange(0, maxColumn).map { column -> GridPosition(row, column) }.map { position -> position to at(position)!! } }.asSequence() private fun at(gridPosition: GridPosition) = super.at(gridPosition.toPoint()) inner class GridPosition(private val row: Int, private val column: Int) { private val grid = this@TreeGrid fun toPoint() = Point(column, row) infix fun isIn(grid: TreeGrid) = toPoint() isIn grid fun distancesToBorder(grid: TreeGrid) = mapOf( Direction.UP to row, Direction.LEFT to column, Direction.DOWN to grid.maxRow - row, Direction.RIGHT to grid.maxColumn - column ) operator fun plus(direction: Direction) = GridPosition(row + direction.deltaY, column + direction.deltaX) /** * Returns an iterator along the grid in the given direction. The first element returned by {@link Iterator#next()} * is the next position next to this position in the given direction. */ fun iterator(direction: Direction) = object : Iterator<GridPosition> { private var currentPosition = this@GridPosition override fun hasNext() = (currentPosition + direction) isIn grid override fun next(): GridPosition { currentPosition += direction return currentPosition } } } private fun checkNeighbours(position: GridPosition, tree: Tree) { val directionsSortedByDistanceToBorder = position.distancesToBorder(this).entries.sortedBy { it.value }.map { it.key } for (direction in directionsSortedByDistanceToBorder) { if (checkNeighbour(position, direction, tree)) return } } private fun checkNeighbour( position: GridPosition, direction: Direction, tree: Tree ): Boolean { val neighbouringTree = getNeighbouringTree(position, direction) ?: return true if (neighbouringTree.size >= tree.size) { tree.setInvisible(direction) return false } val neighbouringTreeVisible = neighbouringTree.isVisible(direction) ?: checkNextNeighbour( position, direction, neighbouringTree ) return if (neighbouringTreeVisible) { tree.setVisible(direction) true } else { checkNextNeighbour(position, direction, tree) } } private fun getNeighbouringTree(position: GridPosition, direction: Direction): Tree? { val neighbourCell = position + direction return if (neighbourCell isIn this) { at(neighbourCell) } else { null } } private fun checkNextNeighbour( position: GridPosition, direction: Direction, neighbouringTree: Tree ): Boolean { return checkNeighbour(position + direction, direction, neighbouringTree) } private fun allTrees(): Sequence<Tree> = this.iterator().asSequence() fun getHighestScenicScore(): Int { for ((position, tree) in gridCells()) { for (direction in Direction.values()) { computeVisibilities(position, direction, tree) } } return allTrees().map { it.getScenicScore() }.max() } private fun computeVisibilities( position: GridPosition, direction: Direction, pointOfView: Tree ) { val treesInLine = mutableListOf<Tree>() position.iterator(direction).asSequence() .map { at(it)!! } .takeWhile { neighbouringTree -> pointOfView.addVisibleTree(direction, neighbouringTree) } .takeWhile { neighbouringTree -> pointOfView.isBiggerThan(neighbouringTree) } .forEach { neighbouringTree -> treesInLine.removeIf { otherTree -> !otherTree.addVisibleTree( direction, neighbouringTree ) || !otherTree.isBiggerThan(neighbouringTree) } treesInLine.add(neighbouringTree) } } } fun main() { val input = readInputLines(TreeGrid::class) val treeSizes = input.map { it.map { char -> char.digitToInt() }.toTypedArray() }.toTypedArray() val treeGrid = TreeGrid(treeSizes) fun part1() = treeGrid.getNumberOfVisibleTrees() fun part2() = treeGrid.getHighestScenicScore() println("The number of visible trees in the grid is ${part1()}.") println("The highest scenic score is ${part2()}.") }
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
5,955
advent-of-code-2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/InsertionSortList.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 147. 对链表进行插入排序 * * 插入排序算法: * * 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。 * 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。 * 重复直到所有输入数据插入完为止。 * * 示例 1: * * 输入: 4->2->1->3 * 输出: 1->2->3->4 * 示例 2: * * 输入: -1->5->3->4->0 * 输出: -1->0->3->4->5 * */ class InsertionSortList { companion object { @JvmStatic fun main(args: Array<String>) { InsertionSortList().solution(ListNode(4).apply { next = ListNode(2).apply { next = ListNode(1).apply { next = ListNode(3) } } })?.printAll() println() InsertionSortList().solution2(ListNode(4).apply { next = ListNode(2).apply { next = ListNode(1).apply { next = ListNode(3) } } })?.printAll() } } // 4->2->1->3 2->4->1->3 // 4->2 // 1->2->3->4 // 反转 fun solution(head: ListNode?): ListNode? { var reversal: ListNode? = null var p = head var cur: ListNode? while (p != null) { cur = p p = cur.next var q = reversal var pre: ListNode? = null while (q != null) { if (cur.`val` < q.`val`) { pre = q q = q.next } else { break } } if (pre != null) { pre.next = cur cur.next = q } else { cur.next = reversal reversal = cur } } var pre: ListNode? = null while (reversal != null) { val curr = reversal reversal = reversal.next curr.next = pre pre = curr } return pre } // 从前往后查找插入点 fun solution2(head: ListNode?): ListNode? { var result: ListNode? = null var p = head while (p != null) { val cur = p p = p.next var q = result var pre: ListNode? = null while (q != null) { if (cur.`val` < q.`val`) { break } pre = q q = q.next } if (pre == null) { cur.next = result result = cur } else { pre.next = cur cur.next = q } } return result } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,931
daily_algorithm
Apache License 2.0
src/main/kotlin/org/example/adventofcode/puzzle/Day02.kt
nikos-ds
573,046,617
false
null
package org.example.adventofcode.puzzle import org.apache.commons.lang3.StringUtils.isBlank import org.example.adventofcode.puzzle.RockPaperScissors.PAPER import org.example.adventofcode.puzzle.RockPaperScissors.ROCK import org.example.adventofcode.puzzle.RockPaperScissors.SCISSORS import org.example.adventofcode.util.FileLoader private const val FILE_PATH = "/day-02-input.txt" private val MAPPINGS: Map<String, RockPaperScissors> = mapOf("A" to ROCK, "B" to PAPER, "C" to SCISSORS) enum class RockPaperScissors { ROCK { override val superior: RockPaperScissors get() = PAPER override val inferior: RockPaperScissors get() = SCISSORS override val score = 1 }, PAPER { override val superior: RockPaperScissors get() = SCISSORS override val inferior: RockPaperScissors get() = ROCK override val score = 2 }, SCISSORS { override val superior: RockPaperScissors get() = ROCK override val inferior: RockPaperScissors get() = PAPER override val score = 3 }; abstract val superior: RockPaperScissors abstract val inferior: RockPaperScissors abstract val score: Int fun scoreAgainst(other: RockPaperScissors) = when (other) { superior -> 0 inferior -> +6 else -> +3 } } object Day02 { fun printSolution() { println("- part 1: ${getTotalScore(Day02::part1Selector)}") println("- part 2: ${getTotalScore(Day02::part2Selector)}") } private fun getTotalScore(playerSelector: (String, RockPaperScissors) -> RockPaperScissors): Int { val allLines = FileLoader.loadFromFile<String>(FILE_PATH) var totalScore = 0 for (line in allLines) { if (isBlank(line)) { continue } val opponent: RockPaperScissors = MAPPINGS[line[0].toString()]!! val player: RockPaperScissors = playerSelector(line[2].toString(), opponent) totalScore += player.score totalScore += player.scoreAgainst(opponent) } return totalScore } private fun part1Selector(encodedSelection: String, opponent: RockPaperScissors): RockPaperScissors { return when (encodedSelection) { "X" -> ROCK "Y" -> PAPER else -> SCISSORS } } private fun part2Selector(encodedSelection: String, opponent: RockPaperScissors): RockPaperScissors { return when (encodedSelection) { "X" -> loseAgainst(opponent) "Y" -> opponent // draw else -> winAgainst(opponent) } } private fun loseAgainst(opponent: RockPaperScissors): RockPaperScissors { return when (opponent) { ROCK -> SCISSORS PAPER -> ROCK else -> PAPER } } private fun winAgainst(opponent: RockPaperScissors): RockPaperScissors { return when (opponent) { ROCK -> PAPER PAPER -> SCISSORS else -> ROCK } } }
0
Kotlin
0
0
3f97096ebcd19f971653762fe29ddec1e379d09a
3,046
advent-of-code-2022-kotlin
MIT License
src/Day01.kt
inssein
573,116,957
false
{"Kotlin": 47333}
import java.util.PriorityQueue fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 input.forEach { if (it.isEmpty()) { if (current > max) { max = current } current = 0 } else { current += it.toInt() } } return max } fun part2(input: List<String>): Int { val top3 = input.fold(0 to PriorityQueue<Int>()) { (sum, acc), it -> if (it.isEmpty()) { acc.add(sum) if (acc.size > 3) { acc.poll() } 0 to acc } else { sum + it.toInt() to acc } }.second return top3.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") check(part2(input) == 200116) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
095d8f8e06230ab713d9ffba4cd13b87469f5cd5
1,113
advent-of-code-2022
Apache License 2.0
src/main/kotlin/adventofcode/year2020/Day08HandheldHalting.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2020 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.year2020.Day08HandheldHalting.Companion.Operation.ACC import adventofcode.year2020.Day08HandheldHalting.Companion.Operation.JMP import adventofcode.year2020.Day08HandheldHalting.Companion.Operation.NOP class Day08HandheldHalting(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val instructions by lazy { input.lines().map(::Instruction) } override fun partOne() = instructions.execute().acc override fun partTwo() = (instructions.indices) .mapNotNull { val before = instructions.take(it) val after = instructions.takeLast(instructions.size - it - 1) when (instructions[it].operation) { ACC -> null JMP -> before + Instruction(NOP, instructions[it].argument) + after NOP -> before + Instruction(JMP, instructions[it].argument) + after } } .map { it.execute() } .first { it.terminatedNormally } .acc companion object { private data class Instruction( val operation: Operation, val argument: Int ) { constructor(input: String) : this(Operation(input.split(" ").first()), input.split(" ").last().toInt()) } private fun List<Instruction>.execute(): ExecutionResult { var acc = 0 var index = 0 val visitedInstructions = mutableListOf<Int>() while (index < size && !visitedInstructions.contains(index)) { visitedInstructions.add(index) when (this[index].operation) { ACC -> { acc += this[index].argument index++ } JMP -> index += this[index].argument NOP -> index++ } } return ExecutionResult(acc, index == size) } private data class ExecutionResult( val acc: Int, val terminatedNormally: Boolean ) private enum class Operation(val type: String) { ACC("acc"), JMP("jmp"), NOP("nop"); companion object { operator fun invoke(type: String) = entries.associateBy(Operation::type)[type]!! } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,437
AdventOfCode
MIT License
src/main/kotlin/com/github/dangerground/aoc2020/Day12.kt
dangerground
317,439,198
false
null
package com.github.dangerground.aoc2020 import com.github.dangerground.aoc2020.util.DayInput import kotlin.math.absoluteValue fun main() { val process = Day12(DayInput.asStringList(12)) println("result part 1: ${process.part1()}") println("result part 2: ${process.part2()}") } class Day12(val input: List<String>) { val directions = listOf('E', 'S', 'W', 'N') fun part1(): Int { var north = 0 var east = 0 var currentDirection = 'E' input.forEach { val diff = it.substring(1).toInt() var command = it[0] if (command == 'F') { command = currentDirection } when (command) { 'N' -> north += diff 'S' -> north -= diff 'E' -> east += diff 'W' -> east -= diff 'L' -> currentDirection = getCurrent(currentDirection, 0-diff) 'R' -> currentDirection = getCurrent(currentDirection, diff) } println("$it -> $east, $north ($currentDirection)") } return north.absoluteValue+east.absoluteValue } private fun getCurrent(currentDirection: Char, diff: Int): Char { val indexDiff = diff / 90 val currentIndex = directions.indexOf(currentDirection) var nextIndex = currentIndex + indexDiff while (nextIndex < 0) { nextIndex += 4 } return directions[nextIndex % 4] } var shipNorth = 0 var shipEast = 0 var wpNorth = 1 var wpEast = 10 var currentDirection = 'E' fun part2(): Int { input.forEach { val diff = it.substring(1).toInt() var command = it[0] when (command) { 'N' -> wpNorth += diff 'S' -> wpNorth -= diff 'E' -> wpEast += diff 'W' -> wpEast -= diff 'F' -> { shipEast += diff * wpEast shipNorth += diff * wpNorth } 'L' -> rotateLeft(diff) 'R' -> rotateRight(diff) } println("$it -> ($shipEast, $shipNorth) ($wpEast, $wpNorth)") } return shipNorth.absoluteValue+shipEast.absoluteValue } private fun rotateLeft(diff: Int) { if (diff == 180) { wpEast *= -1 wpNorth *= -1 } else if (diff == 90) { val tmp1 = wpEast val tmp2 = wpNorth wpEast = tmp2 * -1 wpNorth = tmp1 } else if (diff == 270) { val tmp1 = wpEast val tmp2 = wpNorth wpEast = tmp2 wpNorth = tmp1 * -1 } } private fun rotateRight(diff: Int) { if (diff == 180) { wpEast *= -1 wpNorth *= -1 } else if (diff == 90) { val tmp1 = wpEast val tmp2 = wpNorth wpEast = tmp2 wpNorth = tmp1 * -1 } else if (diff == 270) { val tmp1 = wpEast val tmp2 = wpNorth wpEast = tmp2 * -1 wpNorth = tmp1 } } }
0
Kotlin
0
0
c3667a2a8126d903d09176848b0e1d511d90fa79
3,188
adventofcode-2020
MIT License
algorithms/src/main/kotlin/com/kotlinground/algorithms/backtracking/permutations/generatePermutations.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.algorithms.backtracking.permutations import java.util.stream.Collectors /** * Generates permutations of the given letters and returns a list of all permutations. * Time Complexity * We have n letters to choose in the first level, n - 1 choices in the second level and so on therefore the number * of strings we generate is n * (n - 1) * (n - 2) * ... * 1, or O(n!). Since each string has length n, generating * all the strings requires O(n * n!) time. * Space Complexity * The total space complexity is given by the amount of space required by the strings we're constructing. Like the * time complexity, the space complexity is also O(n * n!). * @param letters [String] letters to find permutations for * @return [List] of [String] with all the permutations of the letters */ fun generatePermutations(letters: String): List<String> { fun dfs(startIndex: Int, path: ArrayList<Char>, used: BooleanArray, result: ArrayList<String>) { if (startIndex == used.size) { // make a deep copy, otherwise we'd be appending the same list over and over result.add(path.stream().map { it.toString() }.collect(Collectors.joining())) return } for (i in used.indices) { // skip used letters if (used[i]) { continue } // add letter to permutation, mark letter as used path.add(letters[i]) used[i] = true dfs(startIndex + 1, path, used, result) // remove letter from permutation path.removeAt(path.size - 1) used[i] = false } } val result = arrayListOf<String>() val usedLetters = BooleanArray(letters.length) val start = 0 val pathTaken = arrayListOf<Char>() dfs(start, pathTaken, usedLetters, result) return result }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
1,896
KotlinGround
MIT License
src/main/kotlin/PassagePathing_12.kt
Flame239
433,046,232
false
{"Kotlin": 64209}
val caveGraph: HashMap<String, MutableList<String>> by lazy { val paths = readFile("PassagePathing").split("\n").map { it.split("-").zipWithNext()[0] } val graph: HashMap<String, MutableList<String>> = HashMap() paths.forEach { graph.getOrPut(it.first) { mutableListOf() }.add(it.second) graph.getOrPut(it.second) { mutableListOf() }.add(it.first) } graph } fun countPaths(): Int { return dfs(caveGraph, hashSetOf("start"), "start") } fun countPathsWIthDoubleVisit(): Int { return dfsWithDoubleVisit(caveGraph, hashSetOf(), null, "start") } fun dfs(graph: HashMap<String, MutableList<String>>, visited: HashSet<String>, vertex: String): Int { var totalPaths = 0 if (isSmallCave(vertex)) { visited.add(vertex) } for (adjacent in graph[vertex]!!) { if (visited.contains(adjacent)) { continue } if (adjacent == "end") { totalPaths++ } else { totalPaths += dfs(graph, visited, adjacent) } } visited.remove(vertex) return totalPaths } fun dfsWithDoubleVisit( graph: HashMap<String, MutableList<String>>, visited: HashSet<String>, doubleVisited: String?, vertex: String ): Int { var curDoubleVisited = doubleVisited if (visited.contains(vertex)) { if (doubleVisited == null && vertex != "start") { curDoubleVisited = vertex } else { return 0 } } println(curDoubleVisited) var totalPaths = 0 if (isSmallCave(vertex)) { visited.add(vertex) } for (adjacent in graph[vertex]!!) { if (adjacent == "start") { continue } if (adjacent == "end") { totalPaths++ } else { totalPaths += dfsWithDoubleVisit(graph, visited, curDoubleVisited, adjacent) } } if (vertex != curDoubleVisited) { visited.remove(vertex) } return totalPaths } fun isSmallCave(name: String) = Character.isLowerCase(name[0]) fun main() { println(countPaths()) println(countPathsWIthDoubleVisit()) }
0
Kotlin
0
0
ef4b05d39d70a204be2433d203e11c7ebed04cec
2,131
advent-of-code-2021
Apache License 2.0
Maximal_Rectangle.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 /** * height[i] record the current number of countinous '1' in column i; * left[i] record the left most index j which satisfies that for any index k from j to i, height[k] >= height[i]; * right[i] record the right most index j which satifies that for any index k from i to j, height[k] >= height[i]; */ class Solution { fun maximalRectangle(matrix: Array<CharArray>): Int { if (matrix.isEmpty() || matrix[0].isEmpty()) return 0 val m = matrix.size val n = matrix[0].size // we know initially, height array contains all 0, so according to the definition of left and right array, // left array should contains all 0, and right array should contain all n - 1 val height = IntArray(n) val right = IntArray(n) { n } val left = IntArray(n) var result = 0 for (i in 0 until m) { for (j in 0 until n) { height[j] = if (matrix[i][j] == '1') height[j] + 1 else 0 } var leftBound = 0 for (j in 0 until n) { // this means the current bound should satisfy two conditions: // within the boundry of the previous height array, and within the boundry of the current row... if (matrix[i][j] == '1') left[j] = max(left[j], leftBound) else { // since all height in between 0 - j satisfies the condition of height[k] >= height[j]; left[j] = 0 leftBound = j + 1 } } var rightBound = n for (j in n - 1 downTo 0) { if (matrix[i][j] == '1') right[j] = min(right[j], rightBound) else { right[j] = n rightBound = j } } for (j in 0 until n) { result = max(result, (right[j] - left[j]) * height[j]) } // println(i) // println(height.joinToString(" ")) // println(left.joinToString(" ")) // println(right.joinToString(" ")) } return result } } fun main() { val solution = Solution() val testCases = arrayOf(arrayOf( charArrayOf('1', '0', '1', '0', '0'), charArrayOf('1', '0', '1', '1', '1'), charArrayOf('1', '1', '1', '1', '1'), charArrayOf('1', '0', '0', '1', '0')), arrayOf(charArrayOf()), arrayOf(charArrayOf('0')), arrayOf(charArrayOf('1')), arrayOf(charArrayOf('0', '1', '0'), charArrayOf('1', '1', '1')), arrayOf(charArrayOf('1', '0', '0', '0', '0', '1', '0', '1', '1', '0'), charArrayOf('0', '1', '1', '1', '1', '1', '1', '0', '1', '0'), charArrayOf('0', '0', '1', '1', '1', '1', '1', '1', '1', '0'))) for (case in testCases) { println(solution.maximalRectangle(case)) // println() } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
2,957
leetcode
MIT License
src/Day06/Day06.kt
Nathan-Molby
572,771,729
false
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
package Day06 import readInput import java.util.* fun firstUniqueIndex(input: String, sizeOfmarker: Int): Int { var elementsQueue = LinkedList<Char>() var elementsDictionary = mutableMapOf<Char, Int>() var duplicateElementsCount = 0 var index = 0 for (char in input) { elementsQueue.add(char) var newCharsInDict = (elementsDictionary[char] ?: 0) + 1 elementsDictionary[char] = newCharsInDict if(newCharsInDict == 2) { duplicateElementsCount += 1 } if (index >= sizeOfmarker) { val elementToRemove = elementsQueue.remove() val newElementCount = elementsDictionary[elementToRemove]!! - 1 if(newElementCount == 1) { duplicateElementsCount -= 1 if (duplicateElementsCount == 0) { return index + 1 } } elementsDictionary[elementToRemove] = newElementCount } index++ } return -1 } fun main() { fun part1(input: List<String>): Int { return firstUniqueIndex(input[0], 4) } fun part2(input: List<String>): Int { return firstUniqueIndex(input[0], 14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06","Day06_test") println(part1(testInput)) check(part1(testInput) == 11) println(part2(testInput)) check(part2(testInput) == 26) val input = readInput("Day06","Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
750bde9b51b425cda232d99d11ce3d6a9dd8f801
1,573
advent-of-code-2022
Apache License 2.0
src/Day01.kt
hubikz
573,170,763
false
{"Kotlin": 8506}
fun main() { fun carriedCaloriesByTopElves(input: List<String>, elvesNbr: Int): Int { var elves = mutableListOf<MutableList<Int>>() var tmp = mutableListOf<Int>() for (caloric in input) { if (caloric.isNotEmpty()) { tmp.add(caloric.toInt()) } else { elves.add(tmp) tmp = mutableListOf() } } elves.add(tmp) return elves.map { it.sum() }.sortedDescending().slice(IntRange(0, elvesNbr-1)).sum() } fun part1(input: List<String>): Int { return carriedCaloriesByTopElves(input, 1) } fun part2(input: List<String>): Int { return carriedCaloriesByTopElves(input, 3) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println("Part 1: ${part1(input)}") check(part2(testInput) == 45000) println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
902c6c3e664ad947c38c8edcb7ffd612b10e58fe
1,045
AoC2022
Apache License 2.0
aoc21/day_17/main.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
import java.io.File import kotlin.math.max data class Pos(val x: Int, val y: Int) data class Range(val min: Int, val max: Int) { fun contains(v: Int): Boolean = v >= min && v <= max } fun hit(x: Int, y: Int, xTarget: Range, yTarget: Range): Boolean { var pos = Pos(0, 0) var vel = Pos(x, y) while (true) { pos = Pos(pos.x + vel.x, pos.y + vel.y) vel = Pos(max(0, vel.x - 1), vel.y - 1) if (xTarget.contains(pos.x) && yTarget.contains(pos.y)) return true else if (pos.y < yTarget.min) { return false } } } fun main() { val re = "target area: x=(-?\\d+)..(-?\\d+), y=(-?\\d+)..(-?\\d+)".toRegex() val match = re.find(File("input").readText())!!.groupValues val xTarget = Range(match.get(1).toInt(), match.get(2).toInt()) val yTarget = Range(match.get(3).toInt(), match.get(4).toInt()) val yMax = -yTarget.min - 1 println("First: ${(yMax * yMax + yMax) / 2}") val second = (1..xTarget.max) .flatMap { x -> (yTarget.min..yMax).map { y -> Pos(x, y) } } .count { p -> hit(p.x, p.y, xTarget, yTarget) } println("Second: $second") }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
1,163
advent-of-code
MIT License
src/main/kotlin/com/colinodell/advent2022/Day21.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 class Day21(input: List<String>) { private val monkeys = input .map { line -> val parts = line.split(":? ".toRegex()) if (parts.size == 2) { NumberMonkey(parts[0], parts[1].toLong()) } else { JobMonkey(parts[0], parts[1], parts[3], parts[2]) } } .associateBy { it.name } .apply { values.forEach { m -> if (m is JobMonkey) { m.associate(this) } } } private val root = monkeys["root"]!! as JobMonkey fun solvePart1() = root.yell() fun solvePart2(): Long { val targetName = "humn" val pathToTarget = mutableListOf<Monkey>().also { root.find(targetName, it) } return when { (root.left in pathToTarget) -> (root.left as JobMonkey).findNumberGiving(root.right.yell(), targetName, pathToTarget) (root.right in pathToTarget) -> (root.right as JobMonkey).findNumberGiving(root.left.yell(), targetName, pathToTarget) else -> error("No path to human") } } abstract class Monkey { open lateinit var name: String abstract fun yell(): Long fun find(name: String, path: MutableList<Monkey>): Monkey? { if (this.name == name) { path.add(this) return this } if (this is JobMonkey) { left.find(name, path)?.let { path.add(this); return it } right.find(name, path)?.let { path.add(this); return it } } return null } fun findNumberGiving(result: Long, targetName: String, pathToTarget: List<Monkey>): Long { if (name == targetName) { return result } this as JobMonkey return when { left in pathToTarget -> left.findNumberGiving(invertLeft(right.yell(), result), targetName, pathToTarget) right in pathToTarget -> right.findNumberGiving(invertRight(left.yell(), result), targetName, pathToTarget) else -> throw IllegalStateException("Couldn't find $targetName in $left or $right") } } } private class NumberMonkey( override var name: String, private val value: Long ) : Monkey() { override fun yell() = value } private class JobMonkey( override var name: String, private val leftName: String, private val rightName: String, private val operator: String ) : Monkey() { lateinit var left: Monkey lateinit var right: Monkey fun associate(monkeys: Map<String, Monkey>) { left = monkeys[leftName]!! right = monkeys[rightName]!! } override fun yell() = when (operator) { "+" -> left.yell() + right.yell() "-" -> left.yell() - right.yell() "*" -> left.yell() * right.yell() "/" -> left.yell() / right.yell() else -> throw IllegalArgumentException("Unknown operator: $operator") } fun invertLeft(right: Long, result: Long) = when (operator) { "+" -> result - right "-" -> result + right "*" -> result / right "/" -> result * right else -> throw IllegalArgumentException("Unknown operator: $operator") } fun invertRight(left: Long, result: Long) = when (operator) { "+" -> result - left "-" -> left - result "*" -> result / left "/" -> left / result else -> throw IllegalArgumentException("Unknown operator: $operator") } } }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
3,799
advent-2022
MIT License
year2021/day14/part1/src/main/kotlin/com/curtislb/adventofcode/year2021/day14/part1/Year2021Day14Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 14: Extended Polymerization --- The incredible pressures at this depth are starting to put a strain on your submarine. The submarine has polymerization equipment that would produce suitable materials to reinforce the submarine, and the nearby volcanically-active caves should even have the necessary input elements in sufficient quantities. The submarine manual contains instructions for finding the optimal polymer formula; specifically, it offers a polymer template and a list of pair insertion rules (your puzzle input). You just need to work out what polymer would result after repeating the pair insertion process a few times. For example: ``` NNCB CH -> B HH -> N CB -> H NH -> C HB -> C HC -> B HN -> C NN -> C BH -> H NC -> B NB -> B BN -> B BB -> N BC -> B CC -> N CN -> C ``` The first line is the polymer template - this is the starting point of the process. The following section defines the pair insertion rules. A rule like `AB -> C` means that when elements `A` and `B` are immediately adjacent, element `C` should be inserted between them. These insertions all happen simultaneously. So, starting with the polymer template `NNCB`, the first step simultaneously considers all three pairs: - The first pair (`NN`) matches the rule `NN -> C`, so element `C` is inserted between the first `N` and the second `N`. - The second pair (`NC`) matches the rule `NC -> B`, so element `B` is inserted between the `N` and the `C`. - The third pair (`CB`) matches the rule `CB -> H`, so element `H` is inserted between the `C` and the `B`. Note that these pairs overlap: the second element of one pair is the first element of the next pair. Also, because all pairs are considered simultaneously, inserted elements are not considered to be part of a pair until the next step. After the first step of this process, the polymer becomes `NCNBCHB`. Here are the results of a few steps using the above rules: ``` Template: NNCB After step 1: NCNBCHB After step 2: NBCCNBBBCBHCB After step 3: NBBBCNCCNBBNBNBBCHBHHBCHB After step 4: NBBNBNBBCCNBCNCCNBBNBBNBBBNBBNBBCBHCBHHNHCBBCBHCB ``` This polymer grows quickly. After step 5, it has length 97; After step 10, it has length 3073. After step 10, `B` occurs 1749 times, `C` occurs 298 times, `H` occurs 161 times, and `N` occurs 865 times; taking the quantity of the most common element (`B`, 1749) and subtracting the quantity of the least common element (`H`, 161) produces 1749 - 161 = 1588. Apply 10 steps of pair insertion to the polymer template and find the most and least common elements in the result. What do you get if you take the quantity of the most common element and subtract the quantity of the least common element? */ package com.curtislb.adventofcode.year2021.day14.part1 import com.curtislb.adventofcode.year2021.day14.polymer.PolymerizationProcess import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2021, day 14, part 1. * * @param inputPath The path to the input file for this puzzle. * @param stepCount The number of pair insertion steps to apply to the polymer template. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt"), stepCount: Int = 10): Long { val polymerization = PolymerizationProcess.fromFile(inputPath.toFile()) polymerization.applyPairInsertions(stepCount) return polymerization.maxElementCountDifference() } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
3,450
AdventOfCode
MIT License
src/main/kotlin/g0701_0800/s0712_minimum_ascii_delete_sum_for_two_strings/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0701_0800.s0712_minimum_ascii_delete_sum_for_two_strings // #Medium #String #Dynamic_Programming #2023_02_25_Time_176_ms_(100.00%)_Space_36.9_MB_(58.33%) class Solution { fun minimumDeleteSum(s1: String, s2: String): Int { val len1 = s1.length val len2 = s2.length val dp = Array(len1 + 1) { IntArray(len2 + 1) } var c1: Char var c2: Char for (i in 1 until len1 + 1) { dp[i][0] = dp[i - 1][0] + s1[i - 1].code } for (j in 1 until len2 + 1) { dp[0][j] = dp[0][j - 1] + s2[j - 1].code } for (i in 1 until len1 + 1) { c1 = s1[i - 1] for (j in 1 until len2 + 1) { c2 = s2[j - 1] if (c1 == c2) { dp[i][j] = dp[i - 1][j - 1] } else { dp[i][j] = (dp[i - 1][j] + c1.code).coerceAtMost(dp[i][j - 1] + c2.code) } } } return dp[len1][len2] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,012
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/chriswk/aoc/advent2022/Day2.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2022 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report class Day2 : AdventDay(2022, 2) { companion object { @JvmStatic fun main(args: Array<String>): Unit { val day = Day2() report { day.part1() } report { day.part2() } } } enum class Play(val score: Int) { Rock(1), Paper(2), Scissors(3); fun win(): Play { return when(this) { Rock -> Scissors Paper -> Rock Scissors -> Paper } } fun lose(): Play { return when(this) { Rock -> Paper Paper -> Scissors Scissors -> Rock } } } data class Round(val opponent: Play, val player: Play) { private val outcomeValue: Int = if (opponent == player) { 3 } else if (player.win() == opponent) { 6 } else { 0 } val score: Int = player.score + outcomeValue companion object { fun fromLine(line: String): Round { val (opponentChoice, playerChoice) = line.split(" ") val opponent = when (opponentChoice) { "A" -> Play.Rock "B" -> Play.Paper "C" -> Play.Scissors else -> throw IllegalStateException("Don't know how to interpret opponent state") } val player = when (playerChoice) { "Y" -> Play.Paper "X" -> Play.Rock "Z" -> Play.Scissors else -> throw IllegalStateException("Don't know how to interpret player state") } return Round(opponent, player) } fun fromLinePart2(line: String): Round { val (opponentChoice, playerChoice) = line.split(" ") val opponent = when (opponentChoice) { "A" -> Play.Rock "B" -> Play.Paper "C" -> Play.Scissors else -> throw IllegalStateException("Don't know how to interpret opponent state") } val player = when (playerChoice) { "Y" -> opponent "X" -> opponent.win() "Z" -> opponent.lose() else -> throw IllegalStateException("Don't know how to interpret player state") } return Round(opponent, player) } } } fun parseInput(input: List<String>): List<Round> { return input.map(Round::fromLine) } fun parseInputPart2(input: List<String>): List<Round> { return input.map(Round::fromLinePart2) } fun part1(): Int { return parseInput(inputAsLines).sumOf { it.score } } fun part2(): Int { return parseInputPart2(inputAsLines).sumOf { it.score } } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
3,064
adventofcode
MIT License
src/test/kotlin/solutions/TaxCalculatorValidator.kt
daniel-rusu
669,564,782
false
{"Kotlin": 70755}
package solutions import dataModel.base.Money import dataModel.base.Money.Companion.dollars import dataModel.base.TaxBracket import dataModel.base.TaxCalculator import solutions.linear.LinearTaxCalculator import strikt.api.Assertion import strikt.api.expectThat import kotlin.random.Random private const val NUM_SAMPLES_PER_BRACKET = 10 object TaxCalculatorValidator { fun ensureProducesSameResultsAsLinearTaxCalculator( taxCalculator: TaxCalculator, taxBrackets: List<TaxBracket>, random: Random, ) { val linearTaxCalculator = LinearTaxCalculator(taxBrackets) for (taxBracket in taxBrackets) { // Test the start of the bracket expectThat(taxCalculator) .producesSameTax(asCalculator = linearTaxCalculator, forIncome = taxBracket.from) validateRandomIncomesInBracket(taxBracket, random, taxCalculator, linearTaxCalculator) if (taxBracket.to == null) continue // Test the highest income that lies within this bracket val highestIncomeInBracket = taxBracket.to!! - Money.ofCents(1) expectThat(taxCalculator) .producesSameTax(asCalculator = linearTaxCalculator, forIncome = highestIncomeInBracket) } } } private fun validateRandomIncomesInBracket( taxBracket: TaxBracket, random: Random, taxCalculator: TaxCalculator, linearTaxCalculator: LinearTaxCalculator ) { val numValidations = when (taxBracket.to) { null -> NUM_SAMPLES_PER_BRACKET else -> NUM_SAMPLES_PER_BRACKET.coerceAtMost((taxBracket.to!! - taxBracket.from).cents.toInt()) } val upperBound = when { taxBracket.to != null -> taxBracket.to!! taxBracket.from.cents == 0L -> 100.dollars else -> taxBracket.from * 2 } repeat(numValidations) { // Test a random value that lies within this bracket val amount = random.nextLong(from = taxBracket.from.cents, until = upperBound.cents) expectThat(taxCalculator) .producesSameTax(asCalculator = linearTaxCalculator, forIncome = Money.ofCents(amount)) } } private fun Assertion.Builder<TaxCalculator>.producesSameTax( asCalculator: TaxCalculator, forIncome: Money ): Assertion.Builder<TaxCalculator> { return assert(description = "produces same tax for income $forIncome") { when (val tax = subject.computeTax(forIncome)) { asCalculator.computeTax(forIncome) -> pass() else -> fail(actual = tax) } } }
0
Kotlin
0
1
166d8bc05c355929ffc5b216755702a77bb05c54
2,559
tax-calculator
MIT License
src/main/kotlin/com.gjosquin.partyoptimizer/definitions/Constraints.kt
Oduig
197,274,049
true
{"Kotlin": 9737}
package com.gjosquin.partyoptimizer.definitions object Constraints { val groupHasATank: Constraint = { specs -> specs.any { it.canTank } } val groupHasAHealer: Constraint = { specs -> specs.any { it.canHeal } } val groupHasAHealerWhoIsNotTheOnlyTank: Constraint = { specs -> specs.any { val tanks = specs.filter { it.canTank } tanks.isNotEmpty() && it.canHeal && (tanks.size > 1 || it != tanks.first()) } } val differentGearRequirementsBelow40: Constraint = { specs -> val specsByArmorClass = specs.groupBy { it.wowClass.armorClassUntil40 } specsByArmorClass.none { it.value.size > 1 && hasOverlappingStatPriorities(it.value) } } val differentGearRequirementsAfter40: Constraint = { specs -> val specsByArmorClass = specs.groupBy { it.wowClass.armorClassAfter40 } specsByArmorClass.none { it.value.size > 1 && hasOverlappingStatPriorities(it.value) } } fun isFaction(faction: Faction): Constraint = { specs -> specs.all { it.wowClass.faction == Faction.BOTH || it.wowClass.faction == faction } } fun groupHasA(wowClass: WowClass, specCondition: (ClassSpec) -> Boolean = { true }): Constraint = { specs -> specs.any { it.wowClass == wowClass && specCondition(it) } } private fun hasOverlappingStatPriorities(specs: List<ClassSpec>): Boolean { return GearStats.all.filter {gearStat -> specs.count { it.statPriority.take(2).contains(gearStat) } > 1 }.any() } }
0
Kotlin
0
0
7be0ebefc97994b1420a22f674d364e378122965
1,567
party-optimizer
Apache License 2.0
Kotlin/problems/0023_redundant_connection.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
//Problem Statement // // In this problem, a tree is an undirected graph that is connected and has no cycles. // The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), // with one additional edge added. The added edge has two different vertices chosen // from 1 to N, and was not an edge that already existed. // // The resulting graph is given as a 2D-array of edges. Each element of edges is // a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v. // // Return an edge that can be removed so that the resulting graph is a tree of // N nodes. If there are multiple answers, return the answer that occurs last in // the given 2D-array. The answer edge [u, v] should be in the same format, with u < v. // Input: [[1,2], [1,3], [2,3]] // Output: [2,3] class Solution { private lateinit var parent: IntArray private fun find(x : Int): Int{ if(parent[x]==x){ return x } return find(parent[x]) } private fun Union(x: Int, y: Int) : Boolean{ val xparent = find(x) val yparent = find(y) return if(xparent!=yparent){ parent[yparent] = xparent true }else{ false } } fun findRedundantConnection(edges: Array<IntArray>): IntArray { parent = IntArray(edges.size+1) for(i in 0 until parent.size){ parent[i] = i } var result: IntArray = intArrayOf() for(edge in edges){ if(!Union(edge[0],edge[1])){ result = edge } } return result; } } fun main(args: Array<String>) { val edges = arrayOf(intArrayOf(1,2),intArrayOf(2,3),intArrayOf(3,4),intArrayOf(1,4),intArrayOf(1,5)) val sol = Solution() println(sol.findRedundantConnection(edges).joinToString()) }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
1,901
algorithms
MIT License
src/main/kotlin/d3/D3_2.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d3 import input.Input fun findGears(lines: List<String>): List<Pair<Int, Int>> { val gears = mutableListOf<Pair<Int, Int>>() for (i in lines.indices) { for (j in lines[i].indices) { val c = lines[i][j] if (c != '*') continue gears.add(Pair(i, j)) } } return gears } fun findAdjacentNumbers(lines: List<String>, gear: Pair<Int, Int>): List<Int> { val numbers = mutableListOf<Int>() val line = lines[gear.first] if (gear.first > 0 && !lines[gear.first - 1][gear.second].isDigit()) { val previousLine = lines[gear.first - 1] numbers.addAll(getNumbersNextToLoc(previousLine, gear.second)) } else { val previousLine = lines[gear.first - 1] if (previousLine[gear.second].isDigit()) { numbers.add(getNumberAt(previousLine, gear.second)) } } numbers.addAll(getNumbersNextToLoc(line, gear.second)) if (gear.first < lines.size - 1 && !lines[gear.first + 1][gear.second].isDigit()) { val nextLine = lines[gear.first + 1] numbers.addAll(getNumbersNextToLoc(nextLine, gear.second)) } else { val nextLine = lines[gear.first + 1] if (nextLine[gear.second].isDigit()) { numbers.add(getNumberAt(nextLine, gear.second)) } } return numbers } fun getNumbersNextToLoc(line: String, col: Int): List<Int> { val numbers = mutableListOf<Int>() if ( col > 0 && line[col - 1].isDigit() ) { numbers.add(getNumberAt(line, col - 1)) } if ( col < line.length - 1 && line[col + 1].isDigit() ) { numbers.add(getNumberAt(line, col + 1)) } return numbers } fun getNumberAt(line: String, i: Int): Int { var start = i - 1 while (start >= 0 && line[start].isDigit()) start-- start++ var end = i + 1 while (end < line.length && line[end].isDigit()) end++ end-- return line.substring(start, end + 1).toInt() } fun main() { val lines = Input.read("input.txt") val gears = findGears(lines) var gearRatiosSum = 0 for (gear in gears) { val numbers = findAdjacentNumbers(lines, gear) if (numbers.size != 2) continue gearRatiosSum += numbers[0] * numbers[1] } println(gearRatiosSum) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
2,343
aoc2023-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountKDifference.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 kotlin.math.abs /** * 2006. Count Number of Pairs With Absolute Difference K * @see <a href="https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/">Source</a> */ fun interface CountKDifference { operator fun invoke(nums: IntArray, k: Int): Int } class CountKDifferenceBruteForce : CountKDifference { override operator fun invoke(nums: IntArray, k: Int): Int { var count = 0 for (i in nums.indices) { for (j in i + 1 until nums.size) { val curr = nums[i] val next = nums[j] if (abs(curr - next) == k) { count++ } } } return count } } class CountKDifferenceMap : CountKDifference { override operator fun invoke(nums: IntArray, k: Int): Int { val map: MutableMap<Int, Int> = HashMap() var res = 0 for (i in nums.indices) { val el = nums[i] if (map.containsKey(el - k)) { res += map[el - k] ?: 0 } if (map.containsKey(el + k)) { res += map[el + k] ?: 0 } map[el] = (map[el] ?: 0) + 1 } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,882
kotlab
Apache License 2.0
src/aoc2022/Day05.kt
nguyen-anthony
572,781,123
false
null
package aoc2022 import utils.readInputAsList fun main() { fun part1(input: List<String>) : String { val split = input.indexOf("") val stacks = input.slice(0 until split) val instructionsList = input.slice(split+1 until input.size) val allStacks = mutableListOf<ArrayDeque<String>>() for(stack in stacks) { val crates = stack.chunked(1) allStacks.add(ArrayDeque(crates)) } for(line in instructionsList) { val instructions = line.split(" ") var numMoves = instructions[1].toInt() val fromStack = instructions[3].toInt() val toStack = instructions[5].toInt() while(numMoves > 0){ allStacks[toStack-1].add(allStacks[fromStack-1].removeLast()) numMoves-- } } var topOfAllStacks = "" for(stack in allStacks){ topOfAllStacks += stack.last() } return topOfAllStacks } fun part2(input : List<String>) : String { val split = input.indexOf("") val stacks = input.slice(0 until split) val instructionsList = input.slice(split+1 until input.size) val allStacks = mutableListOf<ArrayDeque<String>>() for(stack in stacks) { val crates = stack.chunked(1) allStacks.add(ArrayDeque(crates)) } for(line in instructionsList) { val instructions = line.split(" ") var numBoxes = instructions[1].toInt() val fromStack = instructions[3].toInt() val toStack = instructions[5].toInt() val fromStackList = allStacks[fromStack-1] val cratesToMove = fromStackList.slice((fromStackList.size - numBoxes) until fromStackList.size) allStacks[toStack-1].addAll(cratesToMove) while(numBoxes > 0){ allStacks[fromStack-1].removeLast() numBoxes-- } } var topOfAllStacks = "" for(stack in allStacks){ topOfAllStacks += stack.last() } return topOfAllStacks } val input = readInputAsList("Day05", "2022") println(part1(input)) println(part2(input)) // test if implementation meets criteria from the description, like: val testInput = readInputAsList("Day05_test", "2022") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") }
0
Kotlin
0
0
9336088f904e92d801d95abeb53396a2ff01166f
2,468
AOC-2022-Kotlin
Apache License 2.0
packages/solutions/src/Day02.kt
ffluk3
576,832,574
false
{"Kotlin": 21246, "Shell": 85}
import java.lang.Error enum class OpponentMove(val str: String) { A("rock"), B("paper"), C("scissors") } enum class PlayerMove(val str: String) { X("rock"), Y("paper"), Z("scissors") } enum class EndResult(val str: String) { X("lose"), Y("draw"), Z("win") } fun main() { fun getMoveScore(str: String): Int { when (str) { "rock" -> return 1 "paper" -> return 2 "scissors" -> return 3 else -> { println("oop") } } return 0 } fun getWinningPlayerMove(opponentMove: OpponentMove): PlayerMove { val move = when (opponentMove.str) { "rock" -> PlayerMove.Y "paper" -> PlayerMove.Z "scissors" -> PlayerMove.X else -> throw Error("invalid move") } return move } fun getLosingPlayerMove(opponentMove: OpponentMove): PlayerMove { val move = when (opponentMove.str) { "rock" -> PlayerMove.Z "paper" -> PlayerMove.X "scissors" -> PlayerMove.Y else -> throw Error("invalid move") } return move } fun getDrawPlayerMove(opponentMove: OpponentMove): PlayerMove { val move = when (opponentMove.str) { "rock" -> PlayerMove.X "paper" -> PlayerMove.Y "scissors" -> PlayerMove.Z else -> throw Error("invalid move") } return move } fun playerWonRound(opponentMove: OpponentMove, playerMove: PlayerMove): Boolean { return (opponentMove.str === "rock" && playerMove.str === "paper") || (opponentMove.str === "paper" && playerMove.str === "scissors") || (opponentMove.str === "scissors" && playerMove.str === "rock") } fun roundWasADraw(opponentMove: OpponentMove, playerMove: PlayerMove): Boolean { return playerMove.str == opponentMove.str } fun part1(input: List<String>): Int { var playerScore = 0 input.forEach { val parts = it.split(" ") val opponentMove = enumValueOf<OpponentMove>(parts[0]) val playerMove = enumValueOf<PlayerMove>(parts[1]) playerScore += getMoveScore(playerMove.str) if(roundWasADraw(opponentMove,playerMove)) { playerScore += 3 } else if(playerWonRound(enumValueOf(parts[0]), enumValueOf(parts[1]))) { playerScore += 6 } } return playerScore } fun part2(input: List<String>): Int { var playerScore = 0 input.forEach { val parts = it.split(" ") val opponentMove = enumValueOf<OpponentMove>(parts[0]) val endResult = enumValueOf<EndResult>(parts[1]) if(endResult.str == "lose") { playerScore += getMoveScore(getLosingPlayerMove(opponentMove).str) } else if(endResult.str == "draw") { playerScore += 3 playerScore += getMoveScore(getDrawPlayerMove(opponentMove).str) } else if(endResult.str == "win") { playerScore += 6 playerScore += getMoveScore(getWinningPlayerMove(opponentMove).str) } } return playerScore } val input = readInput("Day02") part1(input).println() part2(input).println() }
0
Kotlin
0
0
f9b68a8953a7452d804990e01175665dffc5ab6e
3,449
advent-of-code-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day11.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.e fun main() = Day11.run() object Day11 : Day(2015, 11) { override fun part1() = nextValid(input) override fun part2() = nextValid(nextValid(input)) private fun nextValid(current: String): String { var pwd = increment(current) while (!isValid(pwd)) pwd = increment(pwd) return pwd } private fun isValid(pwd: String): Boolean { return hasIncreasing(pwd) && !pwd.contains("[iol]".toRegex()) && getPairs(pwd) >= 2 } private fun getPairs(pwd: String): Int { var pairs = 0 var i = 0 while (i < pwd.length -1) { if (pwd[i] == pwd[i + 1]) { pairs += 1 i++ } i++ } return pairs } private fun hasIncreasing(pwd: String) = pwd.e().windowed(3).any { val (a, b, c) = it.toCharArray() a.code + 1 == b.code && b.code + 1 == c.code } private fun increment(inp: String): String { val chars = inp.toCharArray().toMutableList() var i = inp.length - 1 while (i != -1) { if (chars[i] == 'z') { chars[i] = 'a' i-- } else { chars[i] = inp[i] + 1 break } } norm(chars) return chars.joinToString("") } private fun norm(chars: MutableList<Char>) { val idx = chars.indexOfFirst { it == 'i' || it == 'l' || it == 'o' } if (idx != -1) { chars[idx] = chars[idx] + 1 for (i in idx + 1 until chars.size) chars[i] = 'a' } } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,709
adventofkotlin
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[109]有序链表转换二叉搜索树.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 // // 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 // // 示例: // // 给定的有序链表: [-10, -3, 0, 5, 9], // //一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: // // 0 // / \ // -3 9 // / / // -10 5 // // Related Topics 树 二叉搜索树 链表 分治 二叉树 // 👍 612 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { var currNode : ListNode? = null fun sortedListToBST(head: ListNode?): TreeNode? { //递归 中序遍历 时间复杂度 O(n) //先计算链表长度 然后递归构造, 二分查找 中间值二根节点 左边为左子树 右边为右子树 if (head == null) return null var len = 0 currNode = head var temp = head while(temp != null){ len++ temp = temp.next } return buildBTS(0,len-1) } private fun buildBTS(left: Int, right: Int): TreeNode? { //递归结束条件 if(left>right) return null //逻辑处理 进入下层循环 //寻找中间值 var mid = left + (right-left)/2 var leftNode = buildBTS(left,mid-1) val root = TreeNode(0) root.left = leftNode root.`val` = currNode?.`val`!! currNode = currNode?.next root.right = buildBTS(mid+1,right) //数据reverse return root } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,120
MyLeetCode
Apache License 2.0
src/Day03/Day03.kt
thmsbdr
574,632,643
false
{"Kotlin": 6603}
package Day03 import readInput fun main() { fun part1(input: List<String>): Int { var total = 0 input.forEach { s -> val compOne = s.substring(0, s.length / 2).toSet() run findFirst@{ s.substring(s.length / 2).toCharArray().forEach { if (compOne.contains(it)) { val intValue = it.toInt() total += if (intValue < 92) { intValue - 38 } else { intValue - 96 } return@findFirst } } } } return total } fun part2(input: List<String>): Int { var total = 0 input.chunked(3).forEach { val badge = it.first().toSet().intersect(it[1].toSet()).intersect(it[2].toSet()).first().toInt() total += if (badge < 92) { badge - 38 } else { badge - 96 } } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03/Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03/Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b9ac3ed8b52a95dcc542f4de79fb24163f3929a4
1,390
AoC-2022
Apache License 2.0
hashcode/y2018/qual/Main.kt
winger
151,886,986
true
{"Java": 19887, "Python": 17946, "C++": 10397, "JavaScript": 2402, "Kotlin": 2355, "Lua": 711}
import java.io.File import java.io.PrintWriter import java.util.* //val filename = "a_example" //val filename = "b_should_be_easy" //val filename = "c_no_hurry" val filename = "d_metropolis" //val filename = "e_high_bonus" fun main(args: Array<String>) { val sc = Scanner(File("data/$filename.in")) val (_, _, V, R) = Array(4) { sc.nextInt() } B = sc.nextInt() val T = sc.nextInt() val rides = Array(R) { sc.nextRide(it) } val cars = Array(V) { Car(Point(0, 0), 0) } println("Max score: " + rides.sumBy { it.duration + B }) rides.sortBy { it.end - it.duration } for (ride in rides) { cars.maxBy { it.canScore(ride) }?.take(ride) } println(cars.totalScore) printSolution(cars) } val Array<Car>.totalScore get() = fold(0) { acc, state -> acc + state.score } var B = 0 class Car(var point: Point, var time: Int, val schedule: MutableList<Ride> = mutableListOf(), var score: Int = 0) { fun willFinishAt(ride: Ride) = possibleArrival(ride) + ride.duration fun possibleArrival(ride: Ride) = Math.max(time + (ride.start - point), ride.begin) fun waitTime(ride: Ride) = Math.max(possibleArrival(ride) - time, 0) fun canScore(ride: Ride): Int { return if (willFinishAt(ride) <= ride.end) { ride.duration + if (possibleArrival(ride) <= ride.begin) B else 0 } else 0 } fun take(ride: Ride) { score += canScore(ride) schedule += ride time = willFinishAt(ride) point = ride.finish } } fun printSolution(solution: Array<Car>) { PrintWriter("$filename-${solution.totalScore}.out").use { pr -> solution.forEach { pr.print(it.schedule.size) it.schedule.forEach { pr.print(" ${it.num}") } pr.println() } } } operator fun Point.minus(o: Point) = Math.abs(x - o.x) + Math.abs(y - o.y) data class Point(val x: Int, val y: Int) data class Ride(val num: Int, val start: Point, val finish: Point, val begin: Int, val end: Int) { val duration get() = finish - start } val Ride.longRide get() = finish.x > 5000 || finish.y > 5000 fun Scanner.nextPoint() = Point(nextInt(), nextInt()) fun Scanner.nextRide(num: Int) = Ride(num, nextPoint(), nextPoint(), nextInt(), nextInt())
0
Java
2
1
df24b920181ddcee443764e956191ffc097f581f
2,355
team-competitions
The Unlicense
kotlin/src/Day10.kt
ekureina
433,709,362
false
{"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386}
import java.lang.IllegalStateException import java.lang.Integer.parseInt import java.util.* fun main() { val illegalCharMap = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137 ) fun part1(input: List<String>): Int { return input.sumOf { line -> val stack = Stack<Char>() for (char in line) { if (char !in illegalCharMap.keys) { stack.push(char) } else { when (stack.peek()) { '(' -> { if (char == ')') { stack.pop() } else { return@sumOf illegalCharMap[char] ?: 0 } } '{' -> { if (char == '}') { stack.pop() } else { return@sumOf illegalCharMap[char] ?: 0 } } '[' -> { if (char == ']') { stack.pop() } else { return@sumOf illegalCharMap[char] ?: 0 } } '<' -> { if (char == '>') { stack.pop() } else { return@sumOf illegalCharMap[char] ?: 0 } } } } } 0 } } fun part2(input: List<String>): Long { val scores = input.map { line -> val stack = Stack<Char>() var score = 0L for (char in line) { if (char !in illegalCharMap.keys) { stack.push(char) } else { when (stack.peek()) { '(' -> { if (char == ')') { stack.pop() } else { return@map -1L } } '{' -> { if (char == '}') { stack.pop() } else { return@map -1L } } '[' -> { if (char == ']') { stack.pop() } else { return@map -1L } } '<' -> { if (char == '>') { stack.pop() } else { return@map -1L } } } } } while (stack.isNotEmpty()) { score *= 5 when (stack.pop()) { '(' -> { score += 1 } '[' -> { score += 2 } '{' -> { score += 3 } '<' -> { score += 4 } } } score }.filter { it != -1L }.sorted() return scores[scores.size / 2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 26397) { "${part1(testInput)}" } check(part2(testInput) == 288957L) { "${part2(testInput)}" } val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
391d0017ba9c2494092d27d22d5fd9f73d0c8ded
4,135
aoc-2021
MIT License
src/main/kotlin/com/chriswk/aoc/advent2021/Day18.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report import java.lang.Math.round import kotlin.math.roundToInt class Day18 : AdventDay(2021, 18) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day18() report { day.part1() } report { day.part2() } } } fun findMagnitude(list: List<String>): Int { return list.map { parseFish(it) }.reduce { acc, fish -> acc + fish }.magnitude() } fun part1(): Int { return findMagnitude(inputAsLines) } fun part2(): Int { return findBiggestMagnitude(inputAsLines) } private fun findBiggestMagnitude(inputAsLines: List<String>): Int { return inputAsLines.flatMap { l1 -> inputAsLines.mapNotNull { l2 -> if (l1 != l2) { (parseFish(l1) + parseFish(l2)).magnitude() } else { null } } }.maxOrNull()!! } fun parseFish(input: String): Fish { if (!input.startsWith("[")) { return FishNumber(input.toInt()) } val contents = input.removeSurrounding("[", "]") var nesting = 0 val index = contents.indexOfFirst { if (it == '[') { nesting++ } else if (it == ']') { nesting-- } else if (it == ',' && nesting == 0) return@indexOfFirst true false } return FishPair(parseFish(contents.substring(0, index)), parseFish(contents.substring(index + 1))) } sealed class Fish { abstract fun magnitude(): Int abstract fun split(): Fish abstract fun shouldSplit(): FishNumber? abstract fun shouldExplode(level: Int = 0): FishPair? abstract fun flatten(): List<Fish> abstract fun replace(replacement: Pair<Fish, Fish>): Fish operator fun plus(fish: Fish): Fish { val fishPair = FishPair(this, fish) return fishPair.reduce() } fun reduce(): Fish { var reduced = this while (true) { val exploding = reduced.shouldExplode() if (exploding != null) { val flattened = reduced.flatten() val index = flattened.indexOf(exploding) reduced = reduced.replace(exploding to FishNumber(0)) val numberToLeft = flattened.take(index).filterIsInstance<FishNumber>().lastOrNull() if (numberToLeft != null) { reduced = reduced.replace(numberToLeft to FishNumber(numberToLeft.value + (exploding.left as FishNumber).value)) } val numberToRight = flattened.drop(index + 1).filterIsInstance<FishNumber>().drop(2).firstOrNull() if (numberToRight != null) { reduced = reduced.replace(numberToRight to FishNumber(numberToRight.value + (exploding.right as FishNumber).value)) } continue } val splitting = reduced.shouldSplit() if (splitting != null) { val pair = FishPair( FishNumber(splitting.value / 2), FishNumber(((splitting.value + 0.5) / 2.0).roundToInt()) ) reduced = reduced.replace(splitting to pair) continue } break } return reduced } } class FishNumber(val value: Int) : Fish() { override fun magnitude(): Int = value override fun split(): Fish = when { value > 9 -> FishPair(FishNumber(value.floorDiv(2)), FishNumber(round(value.toDouble() / 2.0).toInt())) else -> this } override fun shouldSplit(): FishNumber? { return if (value > 9) { this } else { null } } override fun shouldExplode(level: Int): FishPair? = null override fun flatten(): List<Fish> = emptyList() override fun replace(replacement: Pair<Fish, Fish>): Fish { return if (this === replacement.first) { replacement.second } else { this } } override fun toString(): String { return "$value" } } class FishPair(val left: Fish, val right: Fish) : Fish() { override fun magnitude(): Int { return left.magnitude() * 3 + right.magnitude() * 2 } override fun split(): Fish { return FishPair(left.split(), right.split()) } override fun shouldSplit(): FishNumber? { return left.shouldSplit() ?: right.shouldSplit() } override fun shouldExplode(level: Int): FishPair? { return when (level) { 4 -> this else -> left.shouldExplode(level + 1) ?: right.shouldExplode(level + 1) } } override fun flatten(): List<Fish> { return listOf(listOf(left), left.flatten(), listOf(right), right.flatten()).flatten() } override fun replace(replacement: Pair<Fish, Fish>): Fish { return if (this === replacement.first) { replacement.second } else { FishPair(left.replace(replacement), right.replace(replacement)) } } override fun toString(): String { return "[$left,$right]" } } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
5,852
adventofcode
MIT License
aoc-day12/src/Day12.kt
rnicoll
438,043,402
false
{"Kotlin": 90620, "Rust": 1313}
import java.nio.file.Files import java.nio.file.Path fun main() { val vertices = Files.readAllLines(Path.of("input")) .filter { it.isNotBlank() } .map { Vertex.parse(it) } val graph = Graph.build(vertices) val paths = part2(graph.start, setOf(graph.start), null) paths.forEach { path -> println(path.joinToString(",") { node -> node.id }) } println(paths.toSet().size) } fun part1(from: Node, visited: Set<Node>): List<List<Node>> { if (from.id == "end") { return listOf(listOf(from)) } val paths = mutableListOf<List<Node>>() from.exits().forEach { next -> if (!visited.contains(next)) { if (next.isSmall()) { paths.addAll(part1(next, visited + next).map { listOf(from) + it }) } else { paths.addAll(part1(next, visited).map { listOf(from) + it }) } } } return paths } fun part2(from: Node, visitedOnce: Set<Node>, visitedTwice: Node?): List<List<Node>> { if (from.id == "end") { return listOf(listOf(from)) } val paths = mutableListOf<List<Node>>() from.exits().forEach { next -> if (!visitedOnce.contains(next)) { if (next.isSmall()) { paths.addAll(part2(next, visitedOnce + next, visitedTwice).map { listOf(from) + it }) } else { paths.addAll(part2(next, visitedOnce, visitedTwice).map { listOf(from) + it }) } } if (visitedTwice == null) { if (next.isSmall()) { paths.addAll(part2(next, visitedOnce + next, from).map { listOf(from) + it }) } else { paths.addAll(part2(next, visitedOnce, from).map { listOf(from) + it }) } } } return paths }
0
Kotlin
0
0
8c3aa2a97cb7b71d76542f5aa7f81eedd4015661
1,812
adventofcode2021
MIT License
src/com/hlq/leetcode/array/Question26.kt
HLQ-Struggle
310,978,308
false
null
package com.hlq.leetcode.array /** * @author HLQ_Struggle * @date 2020/11/30 * @desc LeetCode 26. 删除排序数组中的重复项 https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/ */ fun main() { val nums = intArrayOf(0,0,1,1,1,2,2,3,3,4) println("----> ${removeDuplicates(nums)}") } /** * 双指针解法 */ fun removeDuplicates(nums: IntArray): Int { if(nums.isEmpty()){ return 0 } var resultCount = 0 for(i in nums.indices){ if(nums[i] != nums[resultCount]){ nums[++resultCount] = nums[i] } } return ++resultCount } /** * LeetCode 执行用时范例 */ fun removeDuplicates1(nums: IntArray): Int { if (nums.isEmpty()) return 0 var i = 0 for (j in 1 until nums.size) { if (nums[j] != nums[i]) { i++ nums[i] = nums[j] } } return i + 1 } /** * LeetCode 执行消耗内存范例 */ fun removeDuplicates2(nums: IntArray): Int { if(nums == null){ return 0 } if(nums.size == 1){ return 1 } var i = 0 for(j in 1 until nums.size){ if(nums[i] != nums[j]){ i++ nums[i] = nums[j] } } return i+1 }
0
Kotlin
0
2
76922f46432783218ddd34e74dbbf3b9f3c68f25
1,242
LeetCodePro
Apache License 2.0
app/src/main/kotlin/day10/Day10.kt
W3D3
433,748,408
false
{"Kotlin": 72893}
package day10 import common.InputRepo import common.readSessionCookie import common.solve import java.util.* val openToClosed = mapOf( '(' to ')', '[' to ']', '{' to '}', '<' to '>', ) fun main(args: Array<String>) { val day = 10 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay10Part1, ::solveDay10Part2) } fun solveDay10Part1(input: List<String>): Int { val pointsLookup = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137, ) fun lineToScore(line: String): Int { val expect = Stack<Char>() for (c in line.toCharArray()) { if (openToClosed[c] != null) { expect.push(openToClosed[c]) } else if (expect.peek() == c) { expect.pop() } else { return pointsLookup[c]!! } } return 0 } return input.map(::lineToScore).sum() } fun solveDay10Part2(input: List<String>): Long { val scoreLookup = mapOf( ')' to 1, ']' to 2, '}' to 3, '>' to 4, ) fun lineToScore(line: String): Long { val expect = Stack<Char>() var score: Long = 0 var valid = true for (char in line) { if (openToClosed[char] != null) { expect.push(openToClosed[char]) } else { valid = expect.pop() == char if (!valid) break } } if (expect.isNotEmpty() and valid) { repeat(expect.size) { score = score * 5 + scoreLookup[expect.pop()]!! } } return score } val sortedScores = input .map(::lineToScore) .filter { score -> score > 0 } .sorted() return sortedScores[(sortedScores.size - 1) / 2] }
0
Kotlin
0
0
df4f21cd99838150e703bcd0ffa4f8b5532c7b8c
1,852
AdventOfCode2021
Apache License 2.0
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2015/day13/Day13.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.aoc2015.day13 import nl.sanderp.aoc.common.permutations val preferences = mapOf( "Alice" to mapOf( "Bob" to 54, "Carol" to -81, "David" to -42, "Eric" to 89, "Frank" to -89, "George" to 97, "Mallory" to -94, ), "Bob" to mapOf( "Alice" to 3, "Carol" to -70, "David" to -31, "Eric" to 72, "Frank" to -25, "George" to -95, "Mallory" to 11, ), "Carol" to mapOf( "Alice" to -83, "Bob" to 8, "David" to 35, "Eric" to 10, "Frank" to 61, "George" to 10, "Mallory" to 29, ), "David" to mapOf( "Alice" to 67, "Bob" to 25, "Carol" to 48, "Eric" to -65, "Frank" to 8, "George" to 84, "Mallory" to 9, ), "Eric" to mapOf( "Alice" to -51, "Bob" to -39, "Carol" to 84, "David" to -98, "Frank" to -20, "George" to -6, "Mallory" to 60 ), "Frank" to mapOf( "Alice" to 51, "Bob" to 79, "Carol" to 88, "David" to 33, "Eric" to 43, "George" to 77, "Mallory" to -3 ), "George" to mapOf( "Alice" to -14, "Bob" to -12, "Carol" to -52, "David" to 14, "Eric" to -62, "Frank" to -18, "Mallory" to -17, ), "Mallory" to mapOf( "Alice" to -36, "Bob" to 76, "Carol" to -34, "David" to 37, "Eric" to 40, "Frank" to 18, "George" to 7, ) ) fun happiness(name: String, nextTo: String) = preferences[name]?.get(nextTo) ?: 0 fun happiness(seating: List<String>) = seating .withIndex() .sumOf { (index, name) -> val left = if (index == 0) seating.last() else seating[index - 1] val right = if (index == seating.lastIndex) seating.first() else seating[index + 1] happiness(name, left) + happiness(name, right) } fun main() { println("Part one: ${preferences.keys.toList().permutations().maxOf { happiness(it) }}") println("Part two: ${preferences.keys.toList().plus("Sander").permutations().maxOf { happiness(it) }}") }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
2,292
advent-of-code
MIT License
src/main/java/hes/nonogram/RecursiveSolver.kt
Hes-Siemelink
689,215,071
false
{"Kotlin": 32733}
package hes.nonogram import hes.nonogram.State.EMPTY import hes.nonogram.State.FILLED class RecursiveSolver : PuzzleSolver { override fun solve(puzzle: Puzzle): Puzzle? { if (puzzle.isSolved()) { return puzzle } for (r in puzzle.rows.indices) { for (c in puzzle.rows[r].cells.indices) { if (puzzle.rows[r].cells[c].state != State.UNKNOWN) continue val candidate = puzzle.copy() candidate.rows[r].cells[c].state = FILLED if (!candidate.isValid()) { puzzle.rows[r].cells[c].state = EMPTY continue } println("Checking with ($r, $c):\n$candidate\n") val solution = solve(candidate) if (solution != null) { return solution } puzzle.rows[r].cells[c].state = EMPTY } } return null } } fun Puzzle.isValid(): Boolean = rows.all { it.isValid() } && columns.all { it.isValid() } fun Line.isValid(): Boolean { // Special case: hint is 0 and all cells are empty if (hints == listOf(0) && cells.all(EMPTY)) { return true; } // Not valid if there are more cells filled in than the total of the hints if (cells.count(FILLED) > hints.total()) { return false } // Check if the cells that are filled in from the left (or top) until the first unknown cell are // consistent with the first hints if (!knownCellsFromLeftConsistentWithHints()) { return false } // Check the segment that each hint can logically be in for (i in hints.indices) { val hint = hints[i] var left = hints.subList(0, i).minimumLength() + emptyLeft() val right = hints.subList(i + 1, hints.size).minimumLength() + emptyRight() // Hack to detect cases like .*. with [1, 1] if (left > 0 && cells[left - 1].state == FILLED) { left += 1 } if (left > cells.size - right) { return false } try { val segment = LineSegment(cells.subList(left, cells.size - right), hint) // Check if segment where this hint should lie is valid if (!segment.isValid()) { return false } } catch (e: IllegalArgumentException) { println("Segment: $this with hints $hints. Left: $left; right: $right") throw e } } return true } private fun List<Cell>.count(state: State): Int = this.count { it.state == state } private fun List<Cell>.all(state: State): Boolean = this.all { it.state == state } private fun Line.knownCellsFromLeftConsistentWithHints(): Boolean { val filled = splitFilled() if (filled.size <= hints.size) { return (filled == hints.subList(0, filled.size)) } return false } private fun Line.splitFilled(): List<Int> { val filled = mutableListOf<Int>() var count = 0 for (cell in cells) { if (cell.state == EMPTY) { if (count > 0) { filled.add(count) } count = 0 } if (cell.state == FILLED) { count++ } if (cell.state == State.UNKNOWN) { return filled } } if (count > 0) { filled.add(count) } return filled } private fun Line.emptyLeft(): Int { var total = 0 for (cell in cells) { if (cell.state != EMPTY) { return total } total++ } return total } private fun Line.emptyRight(): Int { var total = 0 for (cell in cells.reversed()) { if (cell.state != EMPTY) { return total } total++ } return total } fun Hints.total(): Int = this.sumOf { it } fun Hints.minimumLength(): Int { var total = 0 for (hint in this) { total += hint + 1 } return total } class LineSegment(val cells: List<Cell>, val hint: Int) { constructor(cells: String, hint: Int) : this(Cell.from(cells), hint) fun isValid(): Boolean { for (i in 0..cells.size - hint) { if (isValidAt(i)) { return true } } return false } private fun isValidAt(position: Int): Boolean { for (i in position until position + hint) { if (cells[i].state == EMPTY) { return false } } if (position > 0 && cells[position - 1].state == FILLED) { return false } // ..* position 1 hint 1 if (position + hint < cells.size && cells[position + hint].state == FILLED) { return false } return true } override fun toString(): String { return "${cells.asString()} ($hint)" } }
0
Kotlin
0
0
7b96e50eb2973e4e2a906cf20af743909f0ebc8d
4,897
Nonogram
MIT License
src/main/kotlin/me/peckb/aoc/_2018/calendar/day18/Day18.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2018.calendar.day18 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory class Day18 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).read { input -> var forest = input.map { it.toList() }.toList() repeat(TIME) { forest = forest.evolve() } forest.woodCount() } fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input -> var forest = input.map { it.toList() }.toList() // our pattern starts its repeat on step 574 repeat(PATTERN_START_TIME) { forest = forest.evolve() } // our pattern is 28 steps long before we hit the first value again val pattern = (0 until PATTERN_LENGTH).map { forest = forest.evolve() forest.woodCount() } // find out how far into the pattern "FOREVER" will be // then remove one to get our pattern index val indexInPattern = ((FOREVER - PATTERN_START_TIME) % PATTERN_LENGTH) - 1 pattern[indexInPattern] } private fun List<List<Char>>.evolve(): List<List<Char>> { val forest = this return buildList { forest.forEachIndexed { y, row -> val newRow = buildList { row.forEachIndexed { x, self -> val (adjacentTrees, adjacentLumber) = forest.findNeighbors(y, x) when (self) { OPEN -> if (adjacentTrees >= 3) add(TREES) else add(OPEN) TREES -> if (adjacentLumber >= 3) add(LUMBER) else add(TREES) LUMBER -> if (adjacentTrees == 0 || adjacentLumber == 0) add(OPEN) else add(LUMBER) } } } add(newRow) } } } private fun List<List<Char>>.findNeighbors(myY: Int, myX: Int): Pair<Int, Int> { var adjacentTrees = 0 var adjacentLumber = 0 (myY - 1..myY + 1).forEach { y -> (myX - 1..myX + 1).forEach { x -> if (x != myX || y != myY) { if (y in indices) { if (x in 0 until this[y].size) { val adjacent = this[y][x] if (adjacent == TREES) { adjacentTrees++ } else if (adjacent == LUMBER) { adjacentLumber++ } } } } } } return adjacentTrees to adjacentLumber } private fun List<List<Char>>.woodCount(): Int { var treesCount = 0 var lumberCount = 0 forEach { row -> row.forEach { c -> if (c == TREES) { treesCount++ } else if (c == LUMBER) { lumberCount++ } } } return treesCount * lumberCount } companion object { const val OPEN = '.' const val TREES = '|' const val LUMBER = '#' const val TIME = 10 const val FOREVER = 1000000000 const val PATTERN_START_TIME = 573 const val PATTERN_LENGTH = 28 } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,922
advent-of-code
MIT License
kotlin/src/main/kotlin/dev/egonr/leetcode/02_AddTwoNumbers.kt
egon-r
575,970,173
false
null
package dev.egonr.leetcode /* Medium You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. 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] Constraints: The number of nodes in each linked list is in the range [1, 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros. */ class AddTwoNumbers { class ListNode(var `val`: Int) { companion object { fun fromList(list: List<Int>): ListNode { val root = ListNode(list.first()) var nextNode = root list.forEachIndexed { i, it -> if (i > 0) { val newNode = ListNode(it) nextNode.next = newNode nextNode = newNode } } return root } } var next: ListNode? = null override fun toString(): String { var res = this.`val`.toString() var next: ListNode? = next while (next != null) { res += next.`val`.toString() next = next.next } return res } } fun test() { var n1 = ListNode.fromList(arrayListOf(2, 4, 3)) var n2 = ListNode.fromList(arrayListOf(5, 6, 4)) println("$n1 + $n2 = ${addTwoNumbers(n1, n2)}") n1 = ListNode.fromList(arrayListOf(5, 5)) n2 = ListNode.fromList(arrayListOf(5, 5)) println("$n1 + $n2 = ${addTwoNumbers(n1, n2)}") n1 = ListNode.fromList(arrayListOf(9, 9, 9, 9)) n2 = ListNode.fromList(arrayListOf(9, 9, 9, 9, 9, 9, 9)) println("$n1 + $n2 = ${addTwoNumbers(n1, n2)}") } fun ListNode.depth(): Int { var depth = 0 var next: ListNode? = this.next while (next != null) { depth++ next = next.next } return depth } fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { if (l1 == null || l2 == null) { return null } var carry = false val l1depth = l1.depth() val l2depth = l2.depth() val minDepth = Math.min(l1depth, l2depth) val maxDepth = Math.max(l1depth, l2depth) var nextLong = l1 var nextShort = l2 if (l1depth < l2depth) { nextLong = l2 nextShort = l1 } var resultRoot: ListNode? = null var resultNext: ListNode? = null var loopDepth = 0 while (nextLong != null) { var sum = nextLong!!.`val` if (loopDepth <= minDepth) { sum += nextShort!!.`val` nextShort = nextShort?.next } if (carry) { sum += 1 carry = false } if (sum >= 10) { sum -= 10 carry = true } nextLong = nextLong?.next loopDepth++ if (resultRoot == null) { resultRoot = ListNode(sum) resultNext = resultRoot } else { resultNext?.next = ListNode(sum) resultNext = resultNext?.next } } if (carry) { resultNext?.next = ListNode(1) } return resultRoot } }
0
Kotlin
0
0
b9c59e54ca2d1399d34d1ee844e03c16a580cbcb
3,834
leetcode
The Unlicense
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-10.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.CharGrid import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.contains import com.github.ferinagy.adventOfCode.get import com.github.ferinagy.adventOfCode.positionOfFirst import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import com.github.ferinagy.adventOfCode.set import com.github.ferinagy.adventOfCode.toCharGrid fun main() { val input = readInputLines(2023, "10-input") val test1 = readInputLines(2023, "10-test1") val test2 = readInputLines(2023, "10-test2") val test3 = readInputLines(2023, "10-test3") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test2).println() part2(test3).println() part2(input).println() } private fun part1(input: List<String>): Int { val grid = input.toCharGrid() val loop = getLoop(grid) return loop.size / 2 } private fun part2(input: List<String>): Int { val grid = input.toCharGrid() val loop = getLoop(grid) grid.replaceStart() return grid.yRange.sumOf { y -> var inside = false grid.xRange.count { x -> val pos = Coord2D(x, y) when { pos !in loop && inside -> true pos in loop && grid[pos] in "|F7'" -> { inside = !inside false } else -> false } } } } private fun getLoop(grid: CharGrid): MutableList<Coord2D> { val start = grid.positionOfFirst { it == 'S' } var current = start var previous = start val loop = mutableListOf(start) do { val adjacent = current.adjacent(includeDiagonals = false) - previous previous = current current = adjacent.first { grid.isConnected(current, it) } loop += current } while (current != start) return loop } private fun CharGrid.replaceStart() { val start = positionOfFirst { it == 'S' } val options = "|-F7JL" options.forEach { candidate -> set(start, candidate) if (start.adjacent(includeDiagonals = false).filter { this.isConnected(start, it) }.size == 2) return } } private fun CharGrid.isConnected(current: Coord2D, other: Coord2D): Boolean { if (other !in this) return false val pipe = this[current] val otherPipe = this[other] val right = current.x < other.x && current.y == other.y && otherPipe in "-J7S" val left = current.x > other.x && current.y == other.y && otherPipe in "-LFS" val top = current.x == other.x && current.y > other.y && otherPipe in "|F7S" val bottom = current.x == other.x && current.y < other.y && otherPipe in "|LJS" return when (pipe) { '|' -> top || bottom '-' -> left || right 'L' -> top || right 'J' -> top || left '7' -> bottom || left 'F' -> bottom || right '.' -> false 'S' -> top || bottom || left || right else -> error("unexpected '$pipe' vs '$otherPipe'") } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
3,158
advent-of-code
MIT License
kotlin/src/katas/kotlin/leetcode/clone_graph/CloneGraph.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.clone_graph import datsok.shouldEqual import org.junit.Test class CloneGraphTests { @Test fun `clone single node`() { GraphNode(1).cloneGraph() shouldEqual GraphNode(1) } @Test fun `clone two nodes`() { UndirectedGraph.parse("1-2").nodes.first().cloneGraph().toMap() shouldEqual mapOf( 1 to setOf(2), 2 to setOf(1) ) } @Test fun `clone three nodes in sequence`() { UndirectedGraph.parse("1-2,2-3").nodes.first().cloneGraph().toMap() shouldEqual mapOf( 1 to setOf(2), 2 to setOf(1, 3), 3 to setOf(2) ) } @Test fun `clone three nodes loop`() { UndirectedGraph.parse("1-2,2-3,3-1").nodes.first().cloneGraph().toMap() shouldEqual mapOf( 1 to setOf(2, 3), 2 to setOf(1, 3), 3 to setOf(2, 1) ) } @Test fun `clone four nodes square`() { UndirectedGraph.parse("1-2,2-3,3-4,4-1").nodes.first().cloneGraph().toMap() shouldEqual mapOf( 1 to setOf(2, 4), 2 to setOf(1, 3), 3 to setOf(2, 4), 4 to setOf(1, 3) ) } } private fun GraphNode.cloneGraph(): GraphNode { val nodeClones = HashMap<Int, GraphNode>() fun depthFirstTraversal(node: GraphNode, prevNode: GraphNode? = null) { val visited = nodeClones.containsKey(node.value) val nodeClone = nodeClones.getOrPut(node.value, { GraphNode(node.value) }) if (prevNode != null) nodeClones[prevNode.value]!!.neighbors.add(nodeClone) if (!visited) node.neighbors.forEach { depthFirstTraversal(it, node) } } depthFirstTraversal(this) return nodeClones[value]!! } class GraphNodeTests { @Test fun `convert to map`() { GraphNode(1).toMap() shouldEqual mapOf(1 to emptySet()) UndirectedGraph().connect(1, 2).nodes.first().toMap() shouldEqual mapOf( 1 to setOf(2), 2 to setOf(1) ) UndirectedGraph().connect(1, 2).connect(2, 3).nodes.first().toMap() shouldEqual mapOf( 1 to setOf(2), 2 to setOf(1, 3), 3 to setOf(2) ) UndirectedGraph().connect(1, 2).connect(2, 3).connect(3, 1).nodes.first().toMap() shouldEqual mapOf( 1 to setOf(2, 3), 2 to setOf(1, 3), 3 to setOf(1, 2) ) } @Test fun `create graph from string`() { UndirectedGraph.parse("1-2").nodes.first().toMap() shouldEqual mapOf( 1 to setOf(2), 2 to setOf(1) ) } } private fun GraphNode.toMap(result: HashMap<Int, Set<Int>> = HashMap()): Map<Int, Set<Int>> { if (result.containsKey(value)) return result result[value] = neighbors.map { it.value }.toSet() neighbors.forEach { it.toMap(result) } return result } data class GraphNode(var value: Int, var neighbors: MutableList<GraphNode> = ArrayList()) data class UndirectedGraph(val nodes: MutableSet<GraphNode> = LinkedHashSet()) { fun connect(value1: Int, value2: Int): UndirectedGraph { val node1 = nodes.find { it.value == value1 } ?: GraphNode(value1).also { nodes.add(it) } val node2 = nodes.find { it.value == value2 } ?: GraphNode(value2).also { nodes.add(it) } node1.neighbors.add(node2) node2.neighbors.add(node1) return this } companion object { fun parse(s: String): UndirectedGraph { val graph = UndirectedGraph() s.split(",").forEach { token -> val list = token.split("-") graph.connect(list[0].toInt(), list[1].toInt()) } return graph } } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
3,718
katas
The Unlicense
Kotlin/structures/seg_tree.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
class SegTree(val array: IntArray){ private var treeArray:MutableList<Int> private var arrSize: Int init{ treeArray = MutableList<Int>(4*array.size){0} initSegTree(array,0,0,array.size-1) arrSize = array.size println(treeArray) } private fun initSegTree(array: IntArray, treeIndex:Int, start:Int, end:Int) : Int { if(start == end){ treeArray[treeIndex] = array[start] }else{ val mid:Int = start + (end - start)/2 treeArray[treeIndex] = initSegTree(array,2*treeIndex+1,start,mid) + initSegTree(array,2*treeIndex+2,mid+1,end) } return treeArray[treeIndex] } private fun queryHelper(treeIndex:Int, currStart:Int, currEnd:Int, start:Int, end:Int) : Int{ return if(currStart > end || currEnd < start){ return 0 }else if(currStart == currEnd){ treeArray[treeIndex] }else if(currStart >= start && currEnd <= end){ treeArray[treeIndex] }else{ val mid = currStart+ (currEnd - currStart)/2 queryHelper(2*treeIndex+1,currStart,mid,start,end) + queryHelper(2*treeIndex+2,mid+1,currEnd,start,end) } } private fun updateHelper(treeIndex:Int, currStart:Int, currEnd:Int, start:Int, end:Int, value: Int) : Int{ if(currStart>end || currEnd < start){ return treeArray[treeIndex] } if(currStart == currEnd){ treeArray[treeIndex]+=value }else{ val mid:Int = currStart + (currEnd - currStart)/2 treeArray[treeIndex] = updateHelper(2*treeIndex+1,currStart,mid,start,end,value) + updateHelper(2*treeIndex+2,mid+1,currEnd,start,end,value) } return treeArray[treeIndex] } fun queryInterval(start: Int, end: Int) : Int { return queryHelper(0,0,arrSize-1,start,end) } fun updateInterval(start: Int, end: Int, value : Int){ updateHelper(0,0,arrSize-1,start,end,value) } fun printSegTree(){ println(treeArray) } } fun main(args: Array<String>) { val input = intArrayOf(1,2,3,1,3,5,6,4,1,2) val segTree = SegTree(input) println(segTree.queryInterval(3,7)) segTree.updateInterval(0,3,2) segTree.printSegTree() }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
2,322
algorithms
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinReplacement.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 /** * 2366. Minimum Replacements to Sort the Array * @see <a href="https://leetcode.com/problems/minimum-replacements-to-sort-the-array">Source</a> */ fun interface MinReplacement { operator fun invoke(nums: IntArray): Long } class MinReplacementGreedy : MinReplacement { override operator fun invoke(nums: IntArray): Long { var answer: Long = 0 val n: Int = nums.size // Start from the second last element, as the last one is always sorted. for (i in n - 2 downTo 0) { // No need to break if they are already in order. if (nums[i] <= nums[i + 1]) { continue } // Count how many elements are made from breaking nums[i]. val numElements = (nums[i] + nums[i + 1] - 1).toLong() / nums[i + 1].toLong() // It requires numElements - 1 replacement operations. answer += numElements - 1 // Maximize nums[i] after replacement. nums[i] = nums[i] / numElements.toInt() } return answer } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,713
kotlab
Apache License 2.0
src/Lesson8Leader/EquiLeader.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
/** * 100/100 * @param A * @return */ fun solution(A: IntArray): Int { val N = A.size var count = 1 var candidate = A[0] // 1. Find a candidate, note: if there is a leader it will for sure be candidate for (i in 1 until N) { if (count == 0) candidate = A[i] if (A[i] == candidate) { count++ } else { count-- } } // 2. Check if candidate is a leader? count = 0 // Count how many times a candidate appears for (i in 0 until N) { if (candidate == A[i]) count++ } // If it appears less than half there is no solution, return 0 if (count < N / 2) return 0 // 3. Count EquiLeaders var countLeft = 0 var countRight = count var equiLeaders = 0 for (i in 0 until N) { if (A[i] == candidate) { countLeft++ countRight-- } if (countLeft > (i + 1) / 2 && countRight > (N - i - 1) / 2 ) { equiLeaders++ } } return equiLeaders } /** * A non-empty array A consisting of N integers is given. * * The leader of this array is the value that occurs in more than half of the elements of A. * * An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value. * * For example, given array A such that: * * A[0] = 4 * A[1] = 3 * A[2] = 4 * A[3] = 4 * A[4] = 4 * A[5] = 2 * we can find two equi leaders: * * 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4. * 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4. * The goal is to count the number of equi leaders. * * Write a function: * * class Solution { public int solution(int[] A); } * * that, given a non-empty array A consisting of N integers, returns the number of equi leaders. * * For example, given: * * A[0] = 4 * A[1] = 3 * A[2] = 4 * A[3] = 4 * A[4] = 4 * A[5] = 2 * the function should return 2, as explained above. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [1..100,000]; * each element of array A is an integer within the range [−1,000,000,000..1,000,000,000]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
2,368
Codility-Kotlin
Apache License 2.0
src/main/kotlin/aoc22/Day12.kt
asmundh
573,096,020
false
{"Kotlin": 56155}
package aoc22 import datastructures.Coordinate import getEntryAboveOrNull import getEntryBelowOrNull import getEntryLeftOrNull import getEntryRightOrNull import readInput import toAocCode import java.util.PriorityQueue import kotlin.math.abs data class Vertex( val position: Coordinate, val fScore: Int, ) data class Grid( val startPosition: Coordinate, val endPosition: Coordinate, val grid: List<List<Int>>, val lowValues: List<Coordinate> ) fun List<String>.toGrid(): Grid { var startPosition = Coordinate(0, 0) var endPosition = Coordinate(0, 0) val lowValues = mutableListOf<Coordinate>() val grid = this.mapIndexed { idxY, row -> row.mapIndexed inner@{ idxX, it -> if (it == 'S') { startPosition = Coordinate(idxX, idxY) lowValues.add(startPosition) return@inner 'a'.toAocCode() } if (it == 'E') { endPosition = Coordinate(idxX, idxY) return@inner 'z'.toAocCode() } if (it == 'a') lowValues.add(Coordinate(idxX, idxY)) it.toAocCode() }.toMutableList() } return Grid(startPosition, endPosition, grid, lowValues) } fun reconstructPath(cameFrom: MutableMap<Coordinate, Vertex>, current: Vertex): Int { var total = 0 var current2 = current while (cameFrom.keys.contains(current2.position)) { current2 = cameFrom[current2.position]!! total += 1 } return total } fun Coordinate.heuristic(other: Coordinate) = abs(this.x - other.x) + abs(this.y - other.y) fun Int.isConnected(other: Int) = other - this < 2 fun List<List<Int>>.getNeighbors(x: Int, y: Int): List<Pair<Int, Coordinate>> { val left = this.getEntryLeftOrNull(x, y) val right = this.getEntryRightOrNull(x, y) val below = this.getEntryBelowOrNull(x, y) val above = this.getEntryAboveOrNull(x, y) return listOfNotNull( left?.let { it to Coordinate(x - 1, y) }, right?.let { it to Coordinate(x + 1, y) }, below?.let { it to Coordinate(x, y + 1) }, above?.let { it to Coordinate(x, y - 1) }, ).filter { this[y][x].isConnected(it.first) } } fun List<List<Int>>.aStar(start: Coordinate, goal: Coordinate): Int { val openSet = PriorityQueue<Vertex> { a, b -> a.fScore - b.fScore } openSet.add(Vertex(start, 0)) val cameFrom = mutableMapOf<Coordinate, Vertex>() val gScore: MutableMap<Coordinate, Int> = mutableMapOf(start to 0) val fScore: MutableMap<Coordinate, Int> = mutableMapOf(start to start.heuristic(goal)) while (openSet.isNotEmpty()) { val current = openSet.poll() if (current.position == goal) return reconstructPath(cameFrom, current) openSet.remove(current) val neighbors = this.getNeighbors(current.position.x, current.position.y) // .filter { it.second != cameFrom[current.position]?.position } for (neighbor in neighbors) { val neighborPosition = neighbor.second val currentG = gScore[current.position] val edgeWeight = 1 val tentativeScoreG = currentG!!.plus(edgeWeight) val neighborScoreG = gScore[neighborPosition] ?: Int.MAX_VALUE if (tentativeScoreG < (neighborScoreG)) { cameFrom[neighborPosition] = current gScore[neighborPosition] = tentativeScoreG fScore[neighborPosition] = tentativeScoreG + neighborPosition.heuristic(goal) val neighborVertex = Vertex(neighborPosition, fScore[neighborPosition]!!) if (!openSet.contains(neighborVertex)) openSet.add(neighborVertex) } } } return Int.MAX_VALUE } fun day12part1(input: List<String>): Int { val grid = input.toGrid() return grid.grid.aStar(grid.startPosition, grid.endPosition) } fun day12part2(input: List<String>): Int { val grid = input.toGrid() val attempts = mutableListOf<Int>() println(grid.lowValues) for (startPosition in grid.lowValues) { val cost = grid.grid.aStar(startPosition, grid.endPosition) attempts.add(cost) } return attempts.min() } fun main() { val input = readInput("Day12") println(day12part1(input)) println(day12part2(input)) }
0
Kotlin
0
0
7d0803d9b1d6b92212ee4cecb7b824514f597d09
4,361
advent-of-code
Apache License 2.0
src/main/kotlin/adventofcode/day13.kt
Kvest
163,103,813
false
null
package adventofcode import java.io.File fun main(args: Array<String>) { first13(File("./data/day13_1.txt").readLines()) second13(File("./data/day13_2.txt").readLines()) } fun first13(data: List<String>) { val carts = mutableListOf<Cart>() data.forEachIndexed { i, row -> row.forEachIndexed { j, ch -> when (ch) { '>' -> carts.add(Cart(i, j, Direction.RIGHT)) '<' -> carts.add(Cart(i, j, Direction.LEFT)) 'v' -> carts.add(Cart(i, j, Direction.DOWN)) '^' -> carts.add(Cart(i, j, Direction.UP)) } } } var noCrash = true while (noCrash) { val sorted = carts.sortedWith(compareBy(Cart::i, Cart::j)) sorted.forEach { cart -> cart.move(adjastChar(data[cart.i][cart.j])) //find collision carts.filter { cart != it && cart.i == it.i && cart.j == it.j }.forEach { noCrash = false println("${it.j},${it.i}") } } } } private fun second13(data: List<String>) { val carts = mutableListOf<Cart>() data.forEachIndexed { i, row -> row.forEachIndexed { j, ch -> when (ch) { '>' -> carts.add(Cart(i, j, Direction.RIGHT)) '<' -> carts.add(Cart(i, j, Direction.LEFT)) 'v' -> carts.add(Cart(i, j, Direction.DOWN)) '^' -> carts.add(Cart(i, j, Direction.UP)) } } } while (carts.size > 1) { val crashed = mutableSetOf<Cart>() val sorted = carts.sortedWith(compareBy(Cart::i, Cart::j)) sorted.forEach { cart -> if (!crashed.contains(cart)) { cart.move(adjastChar(data[cart.i][cart.j])) //find collision carts.filter { cart != it && cart.i == it.i && cart.j == it.j }.forEach { crashed.add(it) crashed.add(cart) } } } carts.removeAll(crashed) } with(carts.first()) { println("$j,$i") } } private fun adjastChar(ch: Char) = when (ch) { '>' -> '-' '<' -> '-' 'v' -> '|' '^' -> '|' else -> ch } private enum class Direction { LEFT, RIGHT, UP, DOWN } private class Cart(var i: Int, var j: Int, var dir: Direction, var nextTurn: Direction = Direction.LEFT) { fun move(ch: Char) { when (ch) { '|' -> { if (dir == Direction.UP) { --i } else { ++i } } '-' -> { if (dir == Direction.LEFT) { --j } else { ++j } } '/' -> { when (dir) { Direction.LEFT -> { ++i dir = Direction.DOWN } Direction.RIGHT -> { --i dir = Direction.UP } Direction.UP -> { ++j dir = Direction.RIGHT } Direction.DOWN -> { --j dir = Direction.LEFT } } } '\\' -> { when (dir) { Direction.LEFT -> { --i dir = Direction.UP } Direction.RIGHT -> { ++i dir = Direction.DOWN } Direction.UP -> { --j dir = Direction.LEFT } Direction.DOWN -> { ++j dir = Direction.RIGHT } } } '+' -> turn() } } private fun turn() { when (dir) { Direction.LEFT -> { when (nextTurn) { Direction.LEFT -> { ++i dir = Direction.DOWN nextTurn = Direction.UP } Direction.UP -> { --j dir = Direction.LEFT nextTurn = Direction.RIGHT } Direction.RIGHT -> { --i dir = Direction.UP nextTurn = Direction.LEFT } } } Direction.RIGHT -> { when (nextTurn) { Direction.LEFT -> { --i dir = Direction.UP nextTurn = Direction.UP } Direction.UP -> { ++j dir = Direction.RIGHT nextTurn = Direction.RIGHT } Direction.RIGHT -> { ++i dir = Direction.DOWN nextTurn = Direction.LEFT } } } Direction.UP -> { when (nextTurn) { Direction.LEFT -> { --j dir = Direction.LEFT nextTurn = Direction.UP } Direction.UP -> { --i dir = Direction.UP nextTurn = Direction.RIGHT } Direction.RIGHT -> { ++j dir = Direction.RIGHT nextTurn = Direction.LEFT } } } Direction.DOWN -> { when (nextTurn) { Direction.LEFT -> { ++j dir = Direction.RIGHT nextTurn = Direction.UP } Direction.UP -> { ++i dir = Direction.DOWN nextTurn = Direction.RIGHT } Direction.RIGHT -> { --j dir = Direction.LEFT nextTurn = Direction.LEFT } } } } } }
0
Kotlin
0
0
d94b725575a8a5784b53e0f7eee6b7519ac59deb
6,868
aoc2018
Apache License 2.0
solutions/aockt/y2015/Y2015D22.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2015 import aockt.y2015.Y2015D22.Spell.* import io.github.jadarma.aockt.core.Solution object Y2015D22 : Solution { /** Parses the input and returns the initial [GameState] to simulate. */ private fun parseInput(input: List<String>) = GameState( playerHealth = 50, playerMana = 500, enemyHealth = input[0].substringAfter(": ").toInt(), enemyDamage = input[1].substringAfter(": ").toInt(), ) /** Describes the properties (but not the effects) of a spell. */ private enum class Spell(val cost: Int, val turns: Int = 0) { MagicMissile(cost = 53), Drain(cost = 73), Shield(cost = 113, turns = 6), Poison(cost = 173, turns = 6), Recharge(cost = 229, turns = 5); } /** Describes the state of the game in any point during the battle simulation. */ private data class GameState( val playerHealth: Int, val playerMana: Int, val enemyHealth: Int, val enemyDamage: Int, private val spellList: List<Spell> = emptyList(), private val shieldTimer: Int = 0, private val poisonTimer: Int = 0, private val rechargeTimer: Int = 0, private val hardMode: Boolean = false, ) { /** Returns the total mana cost of spells cast until this point. */ val totalCost by lazy { spellList.sumOf { it.cost } } /** Filters the spells that can be cast by the player in the current state. */ val availableSpells: Set<Spell> by lazy { mutableListOf(MagicMissile, Drain).apply { if (shieldTimer <= 1) add(Shield) if (poisonTimer <= 1) add(Poison) if (rechargeTimer <= 1) add(Recharge) }.filter { it.cost <= playerMana }.toSet() } /** Cast the selected [spell] and adjust the cooldown of passive ones. */ private fun playerTurn(spell: Spell) = when (spell) { MagicMissile -> copy(enemyHealth = enemyHealth - 4) Drain -> copy(playerHealth = playerHealth + 2, enemyHealth = enemyHealth - 2) Shield -> copy(shieldTimer = spell.turns) Poison -> copy(poisonTimer = spell.turns) Recharge -> copy(rechargeTimer = spell.turns) }.copy(playerMana = playerMana - spell.cost, spellList = spellList + spell) /** If the enemy is alive, attack the player. */ private fun enemyTurn() = when { enemyHealth <= 0 -> this else -> copy(playerHealth = playerHealth - maxOf(1, enemyDamage - if (shieldTimer > 0) 7 else 0)) } /** Apply the effects of all passive spells. */ private fun applyEffects() = copy( playerMana = if (rechargeTimer > 0) playerMana + 101 else playerMana, enemyHealth = if (poisonTimer > 0) enemyHealth - 3 else enemyHealth, shieldTimer = maxOf(0, shieldTimer - 1), poisonTimer = maxOf(0, poisonTimer - 1), rechargeTimer = maxOf(0, rechargeTimer - 1), ) /** Calculates the next [GameState] after the player and enemy turns if the player selected this [spell]. */ fun playRound(spell: Spell): GameState { require(spell in availableSpells) { "You cannot cast this!" } if (hardMode && playerHealth == 1) return copy(playerHealth = 0) val hardModeAdjusted = if (hardMode) copy(playerHealth = playerHealth - 1) else this return hardModeAdjusted .playerTurn(spell) .applyEffects() .enemyTurn() .applyEffects() } } /** Checks for winning conditions: enemy is dead. */ private fun GameState.playerWon() = enemyHealth <= 0 /** Checks for losing conditions: either dead or out of spells to cast. */ private fun GameState.playerLost() = playerHealth <= 0 || availableSpells.isEmpty() /** Picks the state with the lowest mana cost. */ private fun minByManaCost(a: GameState?, b: GameState?) = minOf(a, b, nullsLast(compareBy { it.totalCost })) /** * Recursively simulates the battle by picking spells searching for the optimal strategy. * * @param state The state to search from. * @param currentBest If another winning state is already known, optimises the search from this [state] by * pruning out all paths that would have a greater total cost, even if winning. * @return The most optimal [GameState] that wins the match, or `null` if impossible to win from this [state]. */ private fun trySpells(state: GameState, currentBest: GameState? = null): GameState? = when { state.playerLost() -> null state.playerWon() -> minByManaCost(state, currentBest) else -> state.availableSpells.fold(currentBest) { best, spell -> when { best != null && state.totalCost + spell.cost > best.totalCost -> best else -> minByManaCost(best, trySpells(state.playRound(spell), best)) } } } override fun partOne(input: String) = parseInput(input.lines()) .let(this::trySpells)!! .totalCost override fun partTwo(input: String) = parseInput(input.lines()) .copy(hardMode = true) .let(this::trySpells)!! .totalCost }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
5,444
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/com/digitalreasoning/langpredict/util/NGramGenerator.kt
MJMalone
118,636,650
true
{"Kotlin": 44995, "Groovy": 29696}
package com.digitalreasoning.langpredict.util const val NGRAM_SIZE = 3 class NGramGenerator { fun generate(text: String): List<String> = text .map { CharacterNormalizer.normalize(it) } .joinToString("") .split(' ') .filter { it.length < 3 || it.any { !it.isUpperCase() } } .flatMap { getGrams(it) } private fun getGrams(word: String): List<String> = when (word.length) { 0 -> emptyList() 1 -> listOf(word, " $word", "$word ", " $word ") 2 -> listOf(word.substring(0,1), word.substring(1,2), " ${word[0]}", "${word[1]} ", word, " $word", "$word ") 3 -> listOf( word.substring(0,1), word.substring(1,2), word.substring(2,3), // 3 unigrams (a,b,c) " ${word[0]}", word.substring(0,2), word.substring(1,3), "${word[2]} ", // 4 bigrams (" a", "ab", "bc", "c ") " ${word.substring(0,2)}", word, "${word.substring(1,3)} " // 3 trigrams (" ab", "abc", "bc " ) else -> getInnerGrams(word) + " ${word[0]}" + " ${word[0]}${word[1]}" + // 2 leading grams (" a", " ab") "${word[word.length-1]} " + "${word[word.length-2]}${word[word.length-1]} " // 2 trailing grams ("z ", "yz ") } // Only called on words of length > 3 private fun getInnerGrams(word: String): List<String> = (3..word.length) .flatMap { end -> listOf( word.substring(end - 1, end), word.substring(end - 2, end), word.substring(end - 3, end)) } + word.substring(0,1) + word.substring(1,2) + word.substring(0,2) } internal class OLD_NGram { private var grams: StringBuffer = StringBuffer(" ") private var capitalword: Boolean = false /** * Append a character into ngram buffer. * @param ch */ fun addChar(ch: Char) { val normCh = CharacterNormalizer.normalize(ch) val lastchar = grams.last() if (lastchar == ' ') { grams = StringBuffer(" ") capitalword = false if (normCh == ' ') return } else if (grams.length >= NGRAM_SIZE) { grams.deleteCharAt(0) } grams.append(normCh) if (Character.isUpperCase(normCh)) { if (Character.isUpperCase(lastchar)) capitalword = true } else { capitalword = false } } /** * Get n-Gram * @param n length of n-gram * @return n-Gram String (null if it is invalid) */ operator fun get(n: Int): String? { if (capitalword) return null val len = grams.length if (n < 1 || n > 3 || len < n) return null if (n == 1) { val ch = grams[len - 1] return if (ch == ' ') null else Character.toString(ch) } else { return grams.substring(len - n, len) } } }
0
Kotlin
0
0
be5badebb71586a770cbda52cb223b1278537406
3,079
lang-predict
Apache License 2.0
Desafios/Kotlin/Primeiros passos em Kotlin/Carrefour Android Developer/Figurinhas/figurinhas.kt
shyoutarou
394,972,098
false
null
/* Ricardo e Vicente são aficionados por figurinhas. Nas horas vagas, eles arrumam um jeito de jogar um “bafo” ou algum outro jogo que envolva tais figurinhas. Ambos também têm o hábito de trocarem as figuras repetidas com seus amigos e certo dia pensaram em uma brincadeira diferente. Chamaram todos os amigos e propuseram o seguinte: com as figurinhas em mãos, cada um tentava fazer uma troca com o amigo que estava mais perto seguindo a seguinte regra: cada um contava quantas figurinhas tinha. Em seguida, eles tinham que dividir as figurinhas de cada um em pilhas do mesmo tamanho, no maior tamanho que fosse possível para ambos. Então, cada um escolhia uma das pilhas de figurinhas do amigo para receber. Por exemplo, se Ricardo e Vicente fossem trocar as figurinhas e tivessem respectivamente 8 e 12 figuras, ambos dividiam todas as suas figuras em pilhas de 4 figuras (Ricardo teria 2 pilhas e Vicente teria 3 pilhas) e ambos escolhiam uma pilha do amigo para receber. Entrada A primeira linha da entrada contém um único inteiro N (1 ≤ N ≤ 3000), indicando o número de casos de teste. Cada caso de teste contém 2 inteiros F1 (1 ≤ F1 ≤ 1000) e F2 (1 ≤ F2 ≤ 1000) indicando, respectivamente, a quantidade de figurinhas que Ricardo e Vicente têm para trocar. Saída Para cada caso de teste de entrada haverá um valor na saída, representando o tamanho máximo da pilha de figurinhas que poderia ser trocada entre dois jogadores. */ fun main(args: Array<String>) { val lista = mutableListOf<Int>() for (i in 1..readLine()!!.toInt()) { val input = readLine()!!.split(" ").map { it.toInt() } input.forEach { number -> lista.add(number) } println(mdc(lista[0], lista[1])) lista.clear() } } fun mdc(n1: Int, n2: Int): Int { return if (n2 == 0) { n1 } else { mdc(n2, (n1 % n2)) } }
0
Java
50
184
b312f8f5e860802d558ad3a78c53850066c880f0
1,934
desafios-DIO
MIT License
src/Day01.kt
LtTempletonPeck
572,896,842
false
{"Kotlin": 1817}
fun main() { fun part1(input: List<String>): Int { return input .splitListByBlank() .maxOf { it.sum() } } fun part2(input: List<String>): Int { val sum = input .splitListByBlank() .map { it.sum() } .sortedDescending() .take(3) .sum() return sum } // test if implementation meets criteria from the description, like: val testInput1 = readInput("Day01_test") check(part1(testInput1) == 24000) // test if implementation meets criteria from the description, like: val testInput2 = readInput("Day01_test") check(part2(testInput2) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) } fun List<String>.splitListByBlank(): MutableList<MutableList<Int>> { val elves: MutableList<MutableList<Int>> = mutableListOf() var food: MutableList<Int> = mutableListOf() forEach { if (it.isBlank()) { elves.add(food) food = mutableListOf() } else { food.add(it.toInt()) } } elves.add(food) return elves }
0
Kotlin
0
0
72ce7365f5543e6a45c76a5db46009a43510c398
1,169
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day12/Day12.kt
vitalir2
572,865,549
false
{"Kotlin": 89962}
package day12 import Challenge import java.util.PriorityQueue import utils.Coordinates private data class Heightmap( val startPoint: Point, val endPoint: Point, val points: List<Point>, ) { fun printPath(path: List<Point>) { val maxX = points.maxOf { it.coordinates.x } val maxY = points.maxOf { it.coordinates.y } data class DrawPoint(val coordinates: Coordinates, val symbol: Char) val drawingSet = mutableSetOf<DrawPoint>() var first = true for (points in path.windowed(size = 2, partialWindows = true)) { val point = points.first() val nextPoint = points.getOrNull(1) val drawnChar = when { first -> 'S'.also { first = false } point.coordinates == endPoint.coordinates -> 'E' nextPoint == null -> 'e' point.coordinates.moveDown() == nextPoint.coordinates -> '↓' point.coordinates.moveUp() == nextPoint.coordinates -> '↑' point.coordinates.moveLeft() == nextPoint.coordinates -> '←' point.coordinates.moveRight() == nextPoint.coordinates -> '→' else -> '.' } drawingSet.add(DrawPoint(point.coordinates, drawnChar)) } val result = StringBuilder() for (j in 0.. maxY) { for (i in 0.. maxX) { val coordinates = Coordinates(i, j) val char = drawingSet.firstOrNull { it.coordinates == coordinates }?.symbol ?: '.' result.append(char) } result.appendLine() } println(result) } fun reachablePoints(from: Point): List<Point> { return points.filter { from.coordinates adjacentCross it.coordinates && it.height - from.height <= 1 } } data class Point( val coordinates: Coordinates, val height: Char, ) } object Day12 : Challenge(12) { // Dijkstra's algo override fun part1(input: List<String>): Any { val heightmap = parseInput(input) val path = dijkstra(heightmap, heightmap.startPoint) heightmap.printPath(path.reversed()) return path.size - 1 } override fun part2(input: List<String>): Any { val heightmap = parseInput(input) val startingPoints = heightmap.points.filter { it.height == 'a' } val paths = startingPoints .map { dijkstra(heightmap, it) } .filter { it.size > 1 } val minPath = paths.minBy(List<Heightmap.Point>::size) heightmap.printPath(minPath.reversed()) return minPath.size - 1 } private fun parseInput(input: List<String>): Heightmap { lateinit var startPoint: Heightmap.Point lateinit var endPoint: Heightmap.Point val points = buildList { input.forEachIndexed { rowIndex, line -> line.forEachIndexed { colIndex, char -> val coordinates = Coordinates(x = colIndex, y = rowIndex) val point = when (char) { 'S' -> Heightmap.Point(coordinates, height = 'a').also { startPoint = it } 'E' -> Heightmap.Point(coordinates, height = 'z').also { endPoint = it } else -> Heightmap.Point(coordinates, height = char) } add(point) } } } return Heightmap( startPoint = startPoint, endPoint = endPoint, points = points, ) } private fun dijkstra(heightmap: Heightmap, startPoint: Heightmap.Point): List<Heightmap.Point> { val visitedPoints = mutableSetOf<Heightmap.Point>() val pointToDistance = mutableMapOf<Heightmap.Point, Int>() val pointToPrev = mutableMapOf<Heightmap.Point, Heightmap.Point>() val queue = PriorityQueue<Heightmap.Point> { first, second -> val firstDistance = pointToDistance[first] val secondDistance = pointToDistance[second] when { firstDistance == null && secondDistance == null -> 0 firstDistance == null -> -1 secondDistance == null -> 1 else -> firstDistance.compareTo(secondDistance) } } pointToDistance[startPoint] = 0 queue.offer(startPoint) while (queue.isNotEmpty()) { val point = queue.poll() val distance = pointToDistance[point]!! val reachablePoints = heightmap.reachablePoints(from = point) for (reachablePoint in reachablePoints) { if (reachablePoint !in visitedPoints && reachablePoint !in queue) { val distanceToReachablePoint = pointToDistance[reachablePoint] if (distanceToReachablePoint == null || distance + 1 < distanceToReachablePoint) { pointToDistance[reachablePoint] = distance + 1 pointToPrev[reachablePoint] = point } queue.offer(reachablePoint) } } visitedPoints.add(point) } return buildList { var currentPoint: Heightmap.Point? = heightmap.endPoint while (currentPoint != null) { add(currentPoint) currentPoint = pointToPrev[currentPoint] } } } }
0
Kotlin
0
0
ceffb6d4488d3a0e82a45cab3cbc559a2060d8e6
5,476
AdventOfCode2022
Apache License 2.0
src/main/kotlin/day17/part1/Part1.kt
bagguley
329,976,670
false
null
package day17.part1 import day17.data const val active = '#' var worldMap:MutableMap<String, Boolean> = mutableMapOf() fun main() { val input = data initWorld(input) advanceWorld() advanceWorld() advanceWorld() advanceWorld() advanceWorld() advanceWorld() println(worldMap.values.filter { it }.count()) } fun initWorld(input: List<String>) { var y = 0 val z = 0 for(line in input) { var x = 0 for (c in line) { worldMap["$x,$y,$z"] = (c == active) x++ } y++ } } fun advanceWorld() { val newWorldMap: MutableMap<String, Boolean> = mutableMapOf() val newCells = advanceExisting(newWorldMap) advanceEdges(newWorldMap, newCells) worldMap = newWorldMap } fun advanceExisting(newWorldMap: MutableMap<String, Boolean>): MutableSet<String> { val newCells: MutableSet<String> = mutableSetOf() for (worldEntry in worldMap) { if (worldEntry.value) newWorldMap[worldEntry.key] = (neighbourCount(worldEntry.key, newCells) in 2..3) else newWorldMap[worldEntry.key] = (neighbourCount(worldEntry.key, newCells) == 3) } return newCells } fun advanceEdges(newWorldMap: MutableMap<String, Boolean>, newCells: MutableSet<String>) { for (newCell in newCells) { if (neighbourCount(newCell) == 3) newWorldMap[newCell] = true } } fun neighbourCount(input: String, newCells: MutableSet<String>): Int { val coords = input.split(",").map{it.toInt()} return neighbourCount(coords[0], coords[1], coords[2], newCells) } fun neighbourCount(x: Int, y: Int, z: Int, newCells: MutableSet<String>): Int { var count = 0 for(xx in x-1..x+1) { for(yy in y-1..y+1) for( zz in z-1..z+1) { if (xx == x && yy == y && zz == z) continue val cell: Boolean? = worldMap["$xx,$yy,$zz"] if (cell != null && cell == true) count++ else newCells.add("$xx,$yy,$zz") } } return count } fun neighbourCount(input: String): Int { val coords = input.split(",").map{it.toInt()} return neighbourCount(coords[0], coords[1], coords[2]) } fun neighbourCount(x: Int, y: Int, z: Int): Int { var count = 0 for(xx in x-1..x+1) { for(yy in y-1..y+1) for( zz in z-1..z+1) { if (xx == x && yy == y && zz == z) continue val cell = worldMap.getOrDefault("$xx,$yy,$zz", false) if (cell) count++ } } return count }
0
Kotlin
0
0
6afa1b890924e9459f37c604b4b67a8f2e95c6f2
2,552
adventofcode2020
MIT License
src/nativeMain/kotlin/Day8.kt
rubengees
576,436,006
false
{"Kotlin": 67428}
class Day8 : Day { private class Matrix(size: Int) { private val data: Array<Array<Int>> = (0 until size).map { arrayOfZeros(size) }.toTypedArray() operator fun set(x: Int, y: Int, value: Int) { this.data[x][y] = value } operator fun get(x: Int, y: Int): Int { return this.data[x][y] } fun isVisible(x: Int, y: Int): Boolean { val value = get(x, y) if ((0 until x).all { i -> value > get(i, y) }) return true // Check left edge. if ((x + 1 until data.size).all { i -> value > get(i, y) }) return true // Check right edge. if ((0 until y).all { i -> value > get(x, i) }) return true // Check top edge. if ((y + 1 until data.size).all { i -> value > get(x, i) }) return true // Check bottom edge. return false } fun scenicScore(x: Int, y: Int): Int { val value = get(x, y) val blockingLeft = (x - 1 downTo 0).find { i -> value <= get(i, y) } val blockingRight = (x + 1 until data.size).find { i -> value <= get(i, y) } val blockingTop = (y - 1 downTo 0).find { i -> value <= get(x, i) } val blockingBottom = (y + 1 until data.size).find { i -> value <= get(x, i) } val scoreLeft = x - (blockingLeft ?: 0) val scoreRight = (blockingRight ?: (data.size - 1)) - x val scoreTop = y - (blockingTop ?: 0) val scoreBottom = (blockingBottom ?: (data.size - 1)) - y return scoreLeft * scoreRight * scoreTop * scoreBottom } fun positions(): Sequence<Pair<Int, Int>> { return sequence { data.forEachIndexed { x, rows -> rows.forEachIndexed { y, _ -> yield(x to y) } } } } private fun arrayOfZeros(size: Int): Array<Int> { return arrayOf(*(0 until size).map { 0 }.toTypedArray()) } } private fun parse(input: String): Matrix { val result = Matrix(input.lines().first().length) input.lines().forEachIndexed { x, line -> line.forEachIndexed { y, char -> result[x, y] = char.digitToInt() } } return result } override suspend fun part1(input: String): String { val matrix = parse(input) return matrix.positions().count { (x, y) -> matrix.isVisible(x, y) }.toString() } override suspend fun part2(input: String): String { val matrix = parse(input) return matrix.positions().maxOf { (x, y) -> matrix.scenicScore(x, y) }.toString() } }
0
Kotlin
0
0
21f03a1c70d4273739d001dd5434f68e2cc2e6e6
2,677
advent-of-code-2022
MIT License
src/main/kotlin/com/groundsfam/advent/y2022/d24/Day24.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2022.d24 import com.groundsfam.advent.* import com.groundsfam.advent.points.Point import kotlin.io.path.div import kotlin.io.path.useLines class Solver(grid: List<String>) { private val width = grid[0].length private val height = grid.size var time = 0 private set private var blizzards = mutableMapOf<Point, List<Direction>>().apply { grid.forEachIndexed { y, line -> line.forEachIndexed { x, c -> c.toDirection()?.also { dir -> this[Point(x, y)] = (this[Point(x, y)] ?: emptyList()) + listOf(dir) } } } } private fun timeIncrement() { blizzards = mutableMapOf<Point, List<Direction>>().apply { blizzards.forEach { (position, dirs) -> dirs.forEach { dir -> val nextPosition = (position + dir.asPoint()) .let { (x, y) -> Point(x.mod(width), y.mod(height)) // new blizzard forms by opposite wall } this[nextPosition] = (this[nextPosition] ?: emptyList()) + listOf(dir) } } } time++ } // reversed = true indicates we're going from the end to the start fun goToGoal(reversed: Boolean) { val start = if (reversed) Point(width - 1, height) else Point(0, -1) val goal = if (reversed) Point(0, 0) else Point(width - 1, height - 1) var possiblePositions = setOf(start) // (width - 1, height - 1) is one move away from the goal while (goal !in possiblePositions) { timeIncrement() possiblePositions = mutableSetOf<Point>().apply { possiblePositions.forEach { position -> // one option is to wait where we are if (position !in blizzards) { add(position) } // other options are to move up, down, left or right Direction.entries.forEach { dir -> val nextPosition = position + dir.asPoint() if ( nextPosition.x in 0 until width && nextPosition.y in 0 until height && nextPosition !in blizzards ) { add(nextPosition) } } } } } // simulate final move to the goal timeIncrement() } } fun main() = timed { val solver = (DATAPATH / "2022/day24.txt").useLines { it.toList() } .let { it.subList(1, it.size - 1) } // remove first and last lines .map { line -> line.substring(1..line.length - 2) // remove first and last chars of each line } .let(::Solver) solver.goToGoal(false) println("Part one: ${solver.time}") solver.goToGoal(true) solver.goToGoal(false) println("Part two: ${solver.time}") }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
3,107
advent-of-code
MIT License
src/adventofcode/blueschu/y2017/day03/solution.kt
blueschu
112,979,855
false
null
package adventofcode.blueschu.y2017.day03 import kotlin.test.assertEquals fun input(): Int = 289326 fun main(args: Array<String>) { assertEquals(0, part1(1)) assertEquals(3, part1(12)) assertEquals(2, part1(23)) assertEquals(31, part1(1024)) println("Part 1: ${part1(input())}") assertEquals(23, part2(20)) println("Part 2: ${part2(input())}") } fun part1(input: Int): Int { if (input == 1) return 0 // 1 maps to 0 if (input < 1) return -1 // ignore invalid cell numbers // Distance along perpendicular from origin; may be vertical or horizontal. // Also equal to the distance from a ring corner to a ring center. val perpendicularDistance = (Math.ceil(Math.sqrt(input.toDouble())) / 2).toInt() // "index" of the ring containing the memory cell. // The square of this value is the cell number in the bottom right corner // of the ring. val ringIndex = (perpendicularDistance * 2) + 1 // Distance "walked" around ring clockwise from ring index to input. // e.g. 49 -> 48 -> 47 ... -> 26 val distanceAroundRing = (ringIndex * ringIndex) - input // Distance from the center of the ring (at the end of a perpendicular // distance) to the memory cell. val offsetDistance = Math.abs(distanceAroundRing % (ringIndex - 1) - perpendicularDistance) return perpendicularDistance + offsetDistance } enum class Direction { NORTH, EAST, SOUTH, WEST; fun turnedLeft(): Direction = if (this == NORTH) WEST else values()[ordinal - 1] fun turnedRight(): Direction = values()[(ordinal + 1) % values().size] } // for part 2, very messy but functional class CellGrid(radius: Int) { private inner class Walker(var xPos: Int, var yPos: Int) { var facing: Direction = Direction.EAST fun advance(): Int { // advance one cell when (facing) { Direction.NORTH -> yPos++ Direction.EAST -> xPos++ Direction.SOUTH -> yPos-- Direction.WEST -> xPos-- } // check if cell to the left is open, if so turn if (0 == when (facing) { Direction.NORTH -> this@CellGrid[xPos - 1, yPos] Direction.EAST -> this@CellGrid[xPos, yPos + 1] Direction.SOUTH -> this@CellGrid[xPos + 1, yPos] Direction.WEST -> this@CellGrid[xPos, yPos - 1] }) facing = facing.turnedLeft() return loadCurrentCell() } private fun loadCurrentCell(): Int { val cellValue = this@CellGrid[xPos + 1, yPos] + this@CellGrid[xPos + 1, yPos + 1] + this@CellGrid[xPos, yPos + 1] + this@CellGrid[xPos - 1, yPos + 1] + this@CellGrid[xPos - 1, yPos] + this@CellGrid[xPos - 1, yPos - 1] + this@CellGrid[xPos, yPos - 1] + this@CellGrid[xPos + 1, yPos - 1] this@CellGrid[xPos, yPos] = cellValue return cellValue } } // walker starts at the origin private val gridWalker: Walker = Walker(radius + 1, radius + 1) private val width: Int = (radius * 2) + 1 private val grid = Array<Int>(width * width, { _ -> 0 }) private operator fun get(i: Int, j: Int) = try { grid[i * width + j] } catch (e: IndexOutOfBoundsException) { 0 } private operator fun set(i: Int, j: Int, value: Int) { // println("Adding $value @ [$i, $j]") grid[i * width + j] = value } fun nextCell(): Int = gridWalker.advance() init { this[radius + 1, radius + 1] = 1 } } fun cellGridFor(cellNumber: Int) = CellGrid((Math.ceil(Math.sqrt(cellNumber.toDouble())) / 2).toInt()) fun part2(input: Int): Int { val cellGrid = cellGridFor(input) while (true) { val cell = cellGrid.nextCell() if (cell > input) { return cell } } }
0
Kotlin
0
0
9f2031b91cce4fe290d86d557ebef5a6efe109ed
4,004
Advent-Of-Code
MIT License
src/day10/Day10.kt
MaxBeauchemin
573,094,480
false
{"Kotlin": 60619}
package day10 import readInput import java.lang.Math.abs enum class CMDType { NOOP, ADDX } data class CMD(val type: CMDType, val arg: Int? = null) fun List<Boolean>.render() { this.chunked(40).forEach { row -> row.map { bool -> if (bool) "#" else "." }.also { println(it.joinToString("")) } } } fun main() { fun parseInput(input: List<String>): List<CMD> { return input.map { str -> str.split(" ").let { tokens -> if (tokens[0] == "noop") CMD(CMDType.NOOP) else CMD(CMDType.ADDX, tokens[1].toInt()) } } } fun part1(input: List<String>): Int { var clock = 1 var xReg = 1 var prevStop = -20 var signalSum = 0 val commands = parseInput(input).toMutableList() var addInProg = false var addNext = 0 while (commands.any() || addInProg) { if (prevStop + 40 == clock) { prevStop = clock signalSum += (xReg * clock) } if (addInProg) { xReg += addNext addInProg = false } else { val cmd = commands.first() commands.removeAt(0) if (cmd.type == CMDType.ADDX) { addInProg = true addNext = cmd.arg!! } } clock++ } return signalSum } fun part2(input: List<String>): List<Boolean> { var clock = 1 var xReg = 1 val commands = parseInput(input).toMutableList() val pixels = mutableListOf<Boolean>() val xHistory = mutableListOf<Int>() var addInProg = false var addNext = 0 while (commands.any() || addInProg) { xHistory.add(xReg) val pixelLit = abs(xReg - (clock - 1)) <= 1 pixels.add(pixelLit) if (addInProg) { xReg += addNext addInProg = false } else { val cmd = commands.first() commands.removeAt(0) if (cmd.type == CMDType.ADDX) { addInProg = true addNext = cmd.arg!! } } if (clock == 40) { clock = 1 } else clock++ } return pixels } val testInput = readInput("Day10_test") val input = readInput("Day10") println("Part 1 [Test] : ${part1(testInput)}") check(part1(testInput) == 13140) println("Part 1 [Real] : ${part1(input)}") println("Part 2 [Test]") part2(testInput).render() println() println("Part 2 [Real]") part2(input).render() }
0
Kotlin
0
0
38018d252183bd6b64095a8c9f2920e900863a79
2,794
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CanPartitionKSubsets.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 /** * 698. Partition to K Equal Sum Subsets * @see <a href="https://leetcode.com/problems/partition-to-k-equal-sum-subsets/">Source</a> */ fun interface CanPartitionKSubsets { operator fun invoke(nums: IntArray, k: Int): Boolean } class CanPartitionKSubsetsDP : CanPartitionKSubsets { override operator fun invoke(nums: IntArray, k: Int): Boolean { if (nums.isEmpty()) return false val n: Int = nums.size // result array val dp = BooleanArray(1 shl n) val total = IntArray(1 shl n) dp[0] = true var sum = 0 for (num in nums) { sum += num } nums.sort() if (sum % k != 0) return false sum /= k if (nums[n - 1] > sum) return false // Loop over power set for (i in 0 until (1 shl n)) { if (dp[i]) { // Loop over each element to find subset for (j in 0 until n) { // set the jth bit val temp = i or (1 shl j) if (temp != i) { // if total sum is less than target store in dp and total array if (nums[j] <= sum - total[i] % sum) { dp[temp] = true total[temp] = nums[j] + total[i] } else { break } } } } } return dp[(1 shl n) - 1] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,168
kotlab
Apache License 2.0
day08/main.kt
LOZORD
441,007,912
false
{"Kotlin": 29367, "Python": 963}
import java.util.Scanner fun main(args: Array<String>) { val digitsToWires: Array<Set<Char>> = arrayOf( // 0 setOf('a', 'b', 'c', 'e', 'f', 'g'), // 1 setOf('c', 'f'), // 2 setOf('a', 'c', 'd', 'e', 'g'), // 3 setOf('a', 'c', 'd', 'f', 'g'), // 4 setOf('b', 'c', 'd', 'f'), // 5 setOf('a', 'b', 'd', 'f', 'g'), // 6 setOf('a', 'b', 'd', 'e', 'f', 'g'), // 7 setOf('a', 'c', 'f'), // 8 setOf('a', 'b', 'c', 'd', 'e', 'f', 'g'), // 9 setOf('a', 'b', 'c', 'd', 'f', 'g'), ) // Map of length => Index(index=digit, value=character set). val uniqueDigitLengthsMap = digitsToWires .withIndex() .toList() .groupBy { it.value.size } .filterValues { it.size == 1 } .mapValues { it.value.get(0) } val uniqueLengthsSet = uniqueDigitLengthsMap.keys.toSet() if (args.contains("--part1")) { var count = 0 val input = Scanner(System.`in`) while (input.hasNextLine()) { val scanned = input.nextLine() val signalsAndOutputs = scanned.split('|') check(signalsAndOutputs.size == 2) val split = signalsAndOutputs[1].split(Regex("\\s+")) count += split .filter { uniqueLengthsSet.contains(it.length) } .size } println("COUNT: $count") } fun getOnlyElement(s: Set<Char>): Char { check(s.size == 1) { "expected $s to have only one element" } return s.first() } fun findMissing(signals: Set<Set<Char>>, allButOne: Set<Char>): Char { val s = signals.find { (it.size == allButOne.size + 1) && (it.containsAll(allButOne)) } // println("found missing signal: $s from argument=$allButOne") val signal = s!! val diff = signal.subtract(allButOne) // println("diff is $diff") return getOnlyElement(diff) } fun unscrambleWires(signals: Set<Set<Char>>): Map<Char, Char> { val solved = HashMap<Char, Char>(7) val digits = HashMap<Int, Set<Char>>(10) val all = digitsToWires[8] // Place all of the unique length digits in the digits map. signals .filter { uniqueLengthsSet.contains(it.size) } .forEach { val digit = uniqueDigitLengthsMap.get(it.size)!!.index digits.set(digit, it) } // Find `a`: `7` - `1`. solved.put('a', getOnlyElement(digits.get(7)!!.subtract(digits.get(1)!!))) // Find `g`: `9` - (`4` U `a`). solved.put('g', findMissing(signals, digits.get(4)!!.union(setOf(solved.get('a')!!)))) // Find `d`: `3` - (`7` U `g`). solved.put('d', findMissing(signals, digits.get(7)!!.union(setOf(solved.get('g')!!)))) // Find `e`: `8` - `9` = `8` - (`4` U `a` U `g`) solved.put('e', getOnlyElement( all.subtract(digits.get(4)!!.union(setOf(solved.get('a')!!, solved.get('g')!!))))) // Find `b`: `8` - (`3` U `e`) = `8` - (`7` U `d` U `g` U `e`). solved.put('b', getOnlyElement( all.subtract(digits.get(7)!!.union(setOf( solved.get('d')!!, solved.get('g')!!, solved.get('e')!!, ))))) // Find `f`: find the signal is just one wire larger than the // translation of `abde[f=?]g` (based on what we know). solved.put('f', findMissing(signals, setOf( solved.get('a')!!, solved.get('b')!!, solved.get('d')!!, solved.get('e')!!, solved.get('g')!!, ))) // Find `c`: the remaining wire. solved.put('c', getOnlyElement(all.filter{!solved.containsValue(it)}.toSet())) return solved } var sum = 0 val input = Scanner(System.`in`) while (input.hasNextLine()) { val scanned = input.nextLine() val signalsAndOutputs = scanned.split('|') check(signalsAndOutputs.size == 2) val signals = signalsAndOutputs[0].trim().split(' ').map { it.toCharArray().toSet() }.toSet() val output = signalsAndOutputs[1].trim().split(' ').map { it.toCharArray().toSet() } val wireMapping = unscrambleWires(signals) // println(wireMapping) // for (entry in wireMapping) { // println("UNSCRAMBLED %c <=> SCRAMBLED %c".format(entry.key, entry.value)) // } // var outputNumber = output // .map { wires: Set<Char> -> wires.map { wireMapping.get(it)!! }.toSet() } // .map { digitsToWires.indexOf(it) } // .reversed() // .reduceIndexed { i, cur, acc -> acc + (i * 10 * cur) } // println(wireMapping) // println(output) // https://stackoverflow.com/a/45380326 var reversed = wireMapping.entries.associateBy({ it.value }) { it.key } fun getDigit(wires: Iterable<Char>): Int { val n = digitsToWires.indexOf(wires.toSet()) check(n >= 0) return n } var outputNumber = 0 for ((i, scrambled) in output.reversed().withIndex()) { var digit = getDigit(scrambled.map { reversed.get(it)!! }) outputNumber += digit * Math.pow(10.0, i.toDouble()).toInt() } // println(outputNumber) sum += outputNumber } print("SUM: $sum") }
0
Kotlin
0
0
17dd266787acd492d92b5ed0d178ac2840fe4d57
5,626
aoc2021
MIT License
src/twentytwentythree/day05/Day05.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentythree.day05 import readInput fun main() { fun findMatchKey(map: Map<Pair<Long, Long>, Pair<Long, Long>>, seed: Long): Long { val entryMatch = map.entries.firstOrNull { it.key.first <= seed && it.key.second >= seed } return if (entryMatch != null) { val diff = seed - entryMatch.key.first return entryMatch.value.first + diff } else { seed } } fun part1(input: List<String>): Long { val seedToSoil = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val soilToFertilizer = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val fertilizerToWater = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val waterToLight = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val lightToTemperature = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val temperatureToHumidity = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val humidityToLocation = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val seeds = mutableSetOf<Long>() var currentMap = seedToSoil input.forEach { line -> val title = line.split(":")[0] if (title == "seeds") { seeds.addAll(line.split(":")[1].split(" ").mapNotNull { it.toLongOrNull() }) } else if (title.contains("map")) { val mapType = title.split(" ")[0] currentMap = when (mapType) { "seed-to-soil" -> seedToSoil "soil-to-fertilizer" -> soilToFertilizer "fertilizer-to-water" -> fertilizerToWater "water-to-light" -> waterToLight "light-to-temperature" -> lightToTemperature "temperature-to-humidity" -> temperatureToHumidity "humidity-to-location" -> humidityToLocation else -> throw Exception("Unknown map type") } } else if (line.isNotBlank()) { val nums = line.split(" ").mapNotNull { it.toLongOrNull() } val destStart = nums[0] val sourceStart = nums[1] val range = nums[2] currentMap[Pair(sourceStart, sourceStart + range)] = Pair(destStart, destStart + range) } } return seeds.minOf { seed -> // println("Next seed:") // println(seed) val soil = findMatchKey(seedToSoil, seed) // println(soil) val fertilizer = findMatchKey(soilToFertilizer, soil) // println(fertilizer) val water = findMatchKey(fertilizerToWater, fertilizer) // println(water) val light = findMatchKey(waterToLight, water) // println(water) val temperature = findMatchKey(lightToTemperature, light) // println(temperature) val humidity = findMatchKey(temperatureToHumidity, temperature) // println(humidity) val location = findMatchKey(humidityToLocation, humidity) // println(location) location } } fun part2(input: List<String>): Long { val seedToSoil = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val soilToFertilizer = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val fertilizerToWater = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val waterToLight = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val lightToTemperature = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val temperatureToHumidity = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val humidityToLocation = mutableMapOf<Pair<Long, Long>, Pair<Long, Long>>() val seedRanges = mutableSetOf<Pair<Long, Long>>() var currentMap = seedToSoil input.forEach { line -> val title = line.split(":")[0] if (title == "seeds") { seedRanges.addAll( line.split(":")[1].split(" ").mapNotNull { it.toLongOrNull() }.chunked(2).map { val start = it[0] val range = it[1] Pair(start, start + range) }) } else if (title.contains("map")) { val mapType = title.split(" ")[0] currentMap = when (mapType) { "seed-to-soil" -> seedToSoil "soil-to-fertilizer" -> soilToFertilizer "fertilizer-to-water" -> fertilizerToWater "water-to-light" -> waterToLight "light-to-temperature" -> lightToTemperature "temperature-to-humidity" -> temperatureToHumidity "humidity-to-location" -> humidityToLocation else -> throw Exception("Unknown map type") } } else if (line.isNotBlank()) { val nums = line.split(" ").mapNotNull { it.toLongOrNull() } val destStart = nums[0] val sourceStart = nums[1] val range = nums[2] currentMap[Pair(sourceStart, sourceStart + range)] = Pair(destStart, destStart + range) } } return seedRanges.minOf { seedRange -> val seeds = seedRange.first..seedRange.second seeds.minOf { seed -> val soil = findMatchKey(seedToSoil, seed) val fertilizer = findMatchKey(soilToFertilizer, soil) val water = findMatchKey(fertilizerToWater, fertilizer) val light = findMatchKey(waterToLight, water) val temperature = findMatchKey(lightToTemperature, light) val humidity = findMatchKey(temperatureToHumidity, temperature) val location = findMatchKey(humidityToLocation, humidity) location } } } val input = readInput("twentytwentythree/day05", "Day05_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
5,373
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindSpecialInt.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 /** * 1287. Element Appearing More Than 25% In Sorted Array * @see <a href="https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array">Source</a> */ fun interface FindSpecialInt { operator fun invoke(arr: IntArray): Int } class FindSpecialIntHashMap : FindSpecialInt { override fun invoke(arr: IntArray): Int { val counts: MutableMap<Int, Int> = HashMap() val target: Int = arr.size / 4 for (num in arr) { val value = counts.getOrDefault(num, 0) counts[num] = value + 1 if (value > target) { return num } } return -1 } } class FindSpecialIntCheckElement : FindSpecialInt { override fun invoke(arr: IntArray): Int { val size: Int = arr.size / 4 for (i in 0 until arr.size - size) { if (arr[i] == arr[i + size]) { return arr[i] } } return -1 } } class FindSpecialIntBS : FindSpecialInt { override fun invoke(arr: IntArray): Int { val n: Int = arr.size val candidates = intArrayOf(arr[n / 4], arr[n / 2], arr[3 * n / 4]) val target = n / 4 for (candidate in candidates) { val left: Int = lowerBound(arr, candidate) val right: Int = upperBound(arr, candidate) - 1 if (right - left + 1 > target) { return candidate } } return -1 } private fun upperBound(arr: IntArray, target: Int): Int { var left = 0 var right = arr.size while (left < right) { val mid = left + (right - left) / 2 if (arr[mid] > target) { right = mid } else { left = mid + 1 } } return left } private fun lowerBound(arr: IntArray, target: Int): Int { var left = 0 var right = arr.size while (left < right) { val mid = left + (right - left) / 2 if (arr[mid] >= target) { right = mid } else { left = mid + 1 } } return left } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,836
kotlab
Apache License 2.0
src/Day04.kt
Sasikuttan2163
647,296,570
false
null
fun main() { val input = readInput("Day04") val part1 = input.count { l -> val list = splitInTwo(l) (list[0][0] <= list[1][0] && list[0][1] >= list[1][1]) || (list[0][0] >= list[1][0] && list[0][1] <= list[1][1]) } val part2 = input.count { l -> val list = splitInTwo(l) (list[0][0]..list[0][1]).intersect(list[1][0]..list[1][1]).isNotEmpty() } part1.println() part2.println() } fun splitInTwo(line: String): List<List<Int>> { line.split(",").let { it -> val first = it[0].trim().split("-").map { it.toInt() }.toList() val second = it[1].trim().split("-").map { it.toInt() }.toList() return listOf(first, second) } }
0
Kotlin
0
0
fb2ade48707c2df7b0ace27250d5ee240b01a4d6
708
AoC-2022-Solutions-In-Kotlin
MIT License
2022/Day08/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 data class Position(val row: Int, val col: Int) {} fun main(args: Array<String>) { val lines = File(args[0]).readLines() val forest = lines.map { it.toCharArray().map { it.code - '0'.code } } println(problem1(forest)) println(problem2(forest)) // println(computeScenicScore(forest, 1, 2)) // println(computeScenicScore(forest, 3, 2)) } fun problem1(forest: List<List<Int>>): Int { var numVisible = 0 for (row in 0..forest[0].size - 1) { for (col in 0..forest[0].size - 1) { if (isVisible(forest, row, col)) numVisible++ } } return numVisible } fun isVisible(forest: List<List<Int>>, row: Int, col: Int): Boolean { val pos = Position(row, col) return isVisibleFromRight(forest, pos) || isVisibleFromLeft(forest, pos) || isVisibleFromTop(forest, pos) || isVisibleFromBottom(forest, pos) } fun isVisibleFromRight(forest: List<List<Int>>, pos: Position): Boolean { for (col in 0..pos.col - 1) { if (forest[pos.row][pos.col] <= forest[pos.row][col]) return false } return true } fun isVisibleFromLeft(forest: List<List<Int>>, pos: Position): Boolean { for (col in forest[0].size - 1 downTo pos.col + 1) { if (forest[pos.row][pos.col] <= forest[pos.row][col]) return false } return true } fun isVisibleFromTop(forest: List<List<Int>>, pos: Position): Boolean { for (row in 0..pos.row - 1) { if (forest[pos.row][pos.col] <= forest[row][pos.col]) return false } return true } fun isVisibleFromBottom(forest: List<List<Int>>, pos: Position): Boolean { for (row in forest.size - 1 downTo pos.row + 1) { if (forest[pos.row][pos.col] <= forest[row][pos.col]) return false } return true } fun problem2(forest: List<List<Int>>): Int { var maxScore = 0 for (row in 0..forest[0].size - 1) { for (col in 0..forest[0].size - 1) { val scenicScore = computeScenicScore(forest, row, col) maxScore = max(maxScore, scenicScore) } } return maxScore } fun computeScenicScore(forest: List<List<Int>>, row: Int, col: Int): Int { val pos = Position(row, col) // println( // "(up)${numVisibleUp(forest, pos)} " + // "(left)${numVisibleLeft(forest, pos)} " + // "(down)${numVisibleDown(forest, pos)} " + // "(right)${numVisibleRight(forest, pos)} " // ) return numVisibleUp(forest, pos) * numVisibleLeft(forest, pos) * numVisibleDown(forest, pos) * numVisibleRight(forest, pos) } fun numVisibleLeft(forest: List<List<Int>>, pos: Position): Int { for (col in pos.col - 1 downTo 0) { if (forest[pos.row][pos.col] <= forest[pos.row][col]) return pos.col - col } return pos.col } fun numVisibleRight(forest: List<List<Int>>, pos: Position): Int { for (col in pos.col + 1 until forest[0].size) { if (forest[pos.row][pos.col] <= forest[pos.row][col]) return col - pos.col } return forest[0].size - pos.col - 1 } fun numVisibleUp(forest: List<List<Int>>, pos: Position): Int { for (row in pos.row - 1 downTo 0) { if (forest[pos.row][pos.col] <= forest[row][pos.col]) return pos.row - row } return pos.row } fun numVisibleDown(forest: List<List<Int>>, pos: Position): Int { for (row in pos.row + 1 until forest.size) { if (forest[pos.row][pos.col] <= forest[row][pos.col]) return row - pos.row } return forest.size - pos.row - 1 }
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
3,604
AdventOfCode
MIT License
2020/day3/day3.kt
Deph0
225,142,801
false
null
// data class Position(var x: Int = 1, var y: Int = 1) class day3 { fun part1(input: List<String>): Int { // first fumbeling attempt on grasping the task.. /*var treeMap: MutableList<String> = input.map { it.repeat(input.size+1) }.toMutableList() var pos = Position() for (y in 0..input.size-1) { // 3 right, 1 down // println(treeMap[y]) for (x in 0..treeMap[y].length-1) { var xChar = treeMap[y][x] if (x+pos.x == pos.x+3) { val objectType = when (treeMap[y][x]) { '.' -> 'O' '#' -> 'X' else -> treeMap[y][x] } val charsList = treeMap[y].toMutableList() charsList[x] = objectType treeMap[y] = charsList.joinToString(separator = "") // println("objectType: $objectType") pos.x += 3 // println("Char: $xChar, X: $x, Y: $y") // println(pos) } } pos.y += 1 // when pos is # then set X else O }*/ var treeMap: MutableList<String> = input.toMutableList() var treeCount = 0 var idx = 0 var down = 1 var right = 3 for (y in 0..treeMap.size-1 step down) { var xChar = treeMap[y].toMutableList() var xCharValue = xChar[idx] // var xCharString = treeMap[y].toString() // debug for breakpoint treeCount += if (xCharValue == '#') 1 else 0 idx += right // go 3 steps to the right idx -= if (idx >= xChar.size) xChar.size else 0 // we traveled above length, take reminder of idx } // println(treeCount) // treeMap.forEach(::println) return treeCount // count amount of X in treeMap } fun part2(input: List<String>, slopes: List<Pair<Int, Int>>): Long { fun calcSlope(right: Int, down: Int): Int { var treeMap: MutableList<String> = input.toMutableList() var treeCount = 0 var idx = 0 for (y in 0..treeMap.size-1 step down) { var xChar = treeMap[y].toMutableList() var xCharValue = xChar[idx] treeCount += if (xCharValue == '#') 1 else 0 idx += right idx -= if (idx >= xChar.size) xChar.size else 0 // remove if we went over length } return treeCount } return slopes.map { val (a, b) = it // deconstuct to (right, down) val slope = calcSlope(a, b) // println("Slope: $slope") slope.toLong() // 64bit Int, to avoid overflow }.reduce(Long::times) } init { val slopes = listOf( Pair(1, 1), Pair(3, 1), Pair(5, 1), Pair(7, 1), Pair(1, 2) ) val exampleinput = listOf( "..##.......", "#...#...#..", ".#....#..#.", "..#.#...#.#", ".#...##..#.", "..#.##.....", ".#.#.#....#", ".#........#", "#.##...#...", "#...##....#", ".#..#...#.#" ) println("day3-pt1-example: " + part1(exampleinput)) // 7 println("day3-pt2-example: " + part2(exampleinput, slopes)) // 336 val input = listOf( ".....#.##......#..##..........#", "##.#.##..#............##....#..", "......###...#..............#.##", ".....#..##.#..#......#.#.#..#..", "..#.......###..#..........#.#..", "..#..#.##.......##.....#....#..", ".##....##....##.###.....###..#.", "..##....#...##..#....#.#.#.....", ".....##..###.##...............#", "#.....#..#....#.##...####..#...", "#......#.#....#..#.##....#..#.#", "##.#...#.#............#......#.", ".#####.......#..#.#....#......#", "..#.#....#.#.##...#.##...##....", ".....#.#...#..####.##..#.......", "#....#...##.#.#.##.#..##.....#.", "##.##...#....#...#......#..##..", "....##...#..#.#...#.#.#.....##.", "..#....##......##....#.#....#..", "#..#....#....###..#.##....#.#.#", "..#.#####..##....#....#.....##.", ".#...##.......#...#....#.#...##", "#.#.#.##.......#.....#.#.#....#", ".#.#.....#.......#.......##....", ".#......#....#....#.......##...", "#......#.....#......#..#..#....", "#.#...#...#....##....#.#...#..#", "....#.....##...#...#..#.#......", "..#......#..........#...#.#....", "..#..#......####..##...###.....", ".#.....#...##...#.##........###", "#.#....#..#....#..#.....#.#..#.", "...##.##.#.#.##...#.....#......", "##....#.#.#...####.#.#.#.#.....", ".##.........#..#..###..........", "..##.###.#..#..#....##.....#...", "##........#..###....#.#..#..#..", "....#.#.......##..#.#.#.#......", "....##.....#.........##.......#", "..#........##.#.........###..##", "....#..................##..#...", "#...#.#..###..#.....#..#..#...#", "..#..#.##..#..#.......#.......#", ".....#..##..#....##...........#", "..##...#........#...#.#.......#", ".........#.#..#.#..#.##.#.###..", "....#...#..#..#......##....#.#.", "..#..#.#....#....#..#.####..##.", "##....#.....#......##.###.#..#.", "#..#..##..###......#.#.#.#...#.", ".......#..##..##...#...#..#....", "..#.###.#...#....#.##.#.....##.", ".#.#.......##...##...##....#...", "#...#.#.#...#.####..#..##......", "###..#.##..#..........#...#....", "##.#.........#..##......####...", "..##.#..#....#.##..............", "...#....#.......###............", "...#.....##....#.#.#.#.......##", "###.###...#...#...###.##...##..", "#.#....#.##..#.....#.....##.#..", "...#....#....#.........#....#.#", "##.#....#........#..#..##.#....", ".#.#..#.......#...##.......#...", ".##...##........#....#.#..#....", "....#..#.##.###.....#.#........", ".#.#...#.#..#.....#.........#..", ".......#.#.#..##....#.........#", ".##...#....#..#...#........#..#", "....#....#..#.#..#.#.#....##.##", "..##....#.....##..#.#...#...#..", "#.##.........#.....#.......#.##", "...#...##.#.#..........#......#", "###...#.....#..#.......#####..#", "#.####...##.#.#..#...#.........", ".##.....#.....##..#...##.##....", ".........###...#......##....###", ".#....##...###.#..#...##..#.#.#", ".......#.......#.#...##.#......", ".....#.#........#..##.....##...", "....#.#.........##.#...##..#.#.", "#..#..#.##..#.##.##.....##.###.", "..##.........###...#....#....#.", ".###...#..#.##...........#.....", "#..##..........#..........#....", ".....#.#....#..##..#...#.#....#", "..#.....#.#....#...##.##.......", "##.....##........#....#..##....", ".#..#.#.........#..#..#........", ".............##....#....#..#...", "....##....#..#.#.##....###.##.#", ".###..#.....#..#..##..#..##..#.", "...#..###.......#.#....#..###..", "#.#..#.....#...#......#........", "#..#..............###.#......#.", "..#....##.#....#.##.#.#...#....", ".........##..#...#.#.......#...", "........#...#.#....#.....##..#.", "...#.##..#..#..###..#..#......#", ".....####......#...#....#...#.#", "...###.#.#......#....#.......#.", "#...##.#....#....##....##.###..", ".......##...##.....#.##.#..#..#", ".....#.#............##...#.####", ".##..#.#.#.#..#.#.#.....#.##...", ".#..####...#.#....#.....#..#...", "....##..#.#...#..#....#.#......", "...#......###..#..###..#.....#.", ".#.#.#..##....#...##..#.....#..", "###....#....#...##.....#...#...", "#.##....#......#...###.........", ".#..#.#...#..#....#....#....#..", "...............##...####..#..#.", "#.#...........####..#...##.....", "##.#....#........#......#...##.", "......#...#...#....#....#.....#", "#......#.............#....###..", ".#...#...##.....#...##.##..#...", "..#.#......#.#........#........", ".......#..#.#...##..#.#.#......", "..##...#.##........#....#.#...#", ".....#..#..#........#.#......##", "....#.#...##............##....#", ".#.#....#.#.#...#...#.##.....#.", "#.#.##...#....#.#.#..#.##..#.#.", ".........####..#...#...#.......", "#..#..####......#..##..#...#...", ".........##..................#.", ".....##.#..##.#.#...#......##..", "...#....#....#.#.....#...#..#.#", "#...##.#...##...........#..#...", "#..........#.#..#..#.##..#..#.#", ".#...#.##...#.#.#..#.......##..", ".........#...........#..#..#...", ".##...##....#.#......#........#", "#.#...........#....#.......#...", "##.#.#.......#...###......##..#", "...###..#.##..##.#.#.......#...", ".#...#..##.#...#........#.....#", "...#.......#..#..........#.#...", "..#.#.#.#.....#.#.......#..#..#", "#.##.....#..##...#..###.#....#.", ".......#...........#...#....###", ".......#..#...#.............#..", "#.....###.......#...#........#.", ".#..#..#..#...........#........", "....#.#...#.#.##.#.#....#.##..#", ".......#..##...##...#...#......", "...#.....##.###...#.#...##....#", "#..#....#...##......#....##....", "#.#.......#....#.###.##..#..#..", "..##...........#...#....#......", ".#........#.....#..#..#...#..##", ".....#.#.#..#.......#....#.....", "#..#.#......#......##....#.....", "##.....................##......", ".##........###..#.........#...#", "........#.........#..#.........", ".#.##....#.....#...#.........##", "....##......#.........#........", "...#.#..#...##.##.#.#..####....", "..##...........##.#.#....#.....", ".#.....#.#...#..#.......#....#.", "....#...#......##...#...##.#..#", "....#..##....#..#.........##.#.", "..##...##.##....#....##.###...#", "..#....##..##.#.#.#...#......#.", "##...#.........#...........#...", ".##....##.#.....#...#.......#..", "..........##.###.##....###....#", "..........#..##..#....#.#.##.##", "........##.#...#.#.#.#...###.#.", ".#......#.#.#...###.#.#.#......", ".........#......#......#...#..#", "......#.....#.##....##.#####..#", "..#..##...###.#..........#.#.#.", ".#..#....###.#...#..#....#...##", "...................#..........#", "....###.....#...##......#.....#", "#.....#..##.....#.#..........#.", "..#.......##.#....#..#.##.#...#", "........##.#..###..#......##...", "#...........##.#...###..#....#.", "....#...........#.....#.#...#..", ".##..#.#...#...#.##...#..#.....", "#........#.#.#.#.#.#...........", "#..#.....#..#..#.##....#....#.#", "..#............##....#.#.##...#", ".....###.#....#.#......#.###...", "...#.....#.#.................#.", "..#...##..#.#...#...#...#.....#", ".##.#........#..#....##..#..##.", ".#..........#...#.#..#..#.#....", "#.......##.........#.##..#.####", ".#..............#.......##.....", "#......#.##..........#..#......", "..##...#...#.#...#............#", ".##.##..##..##........##.....#.", ".....#..#.....##...............", ".#..#...##...#...#.....#.......", "#......#...#.......#..##.###.##", "###..##......##......###....#..", "....#..........#...#.##.#.....#", ".........#....#..#..#.#..##....", ".....#.....#...........#......#", ".#.......#...#....##...#.##...#", "..##.#..............#..#...#.#.", ".#..####.#.........#....#....#.", "..###.#...#..#......#.......###", ".#.#..##...###...#...#.#...#.#.", "...#..##..###.#..#.....#.##....", "#...###.#...##.....####.....#..", ".#.##...#..#.#..##.....#.......", "...#.##.....##.....#....#......", ".#...##.....#..###..#..........", "..........#...#.....#....##.#..", ".......#...#...#...#........#..", "#....##..#...#..##.#.#.....#...", ".#.#..............#..#....#....", ".####.#.#.###......#...#.#....#", ".#...#...##.#...............#.#", "...#.......##...#...#....##....", "#..........###.##..........##.#", ".......#...#....#.#..#.#....#..", "....#.##.#...###..#..##.##.....", "..#.#.#......#.#.......###.....", "#..................#.##....#...", "#.....#..#.#.#..#...#.........#", "..#..#...#.#.##........#.......", "#..#.#..#..........###...#.#...", ".......#.##....#........##.#...", ".####.#.#...#.#...##.##.....###", "........#.#...#.#..##...##.....", "....##.##......#.##.........#..", ".#..#...#.#...........#........", ".......#..........#....#...#...", "..###.#.###..#..#.....#..##....", ".#..........#.......##...#.....", ".#.....#...#........#...#.##..#", ".#..#.......#..#.......#.#.#...", "....#..##.#...##...#.#....#....", ".....#.........#..#..#....#....", "..#.#..##....#..#..##.#.#.....#", "........#.#...###....#.#.#.....", ".#.....#.......#..###.#........", ".......#...#.#...#...##........", "##.............#.#.....#.#..#..", ".#....#.......#.#.......#..##..", "#.....#........#..##..##.......", "...........#.........###......#", "....#.##...#.#...#...#....#..##", "......#..##......#......#.##.#.", "......##....####...###...#.....", "#....#..........#.#.##.....#..#", "....#.#...........#.#.#.#.#...#", "....####.....##...#..##..#...#.", "#....#.###..###.....#..###.....", "..##.........#......#...##.#...", "..#.....#.#...#.##.#...#..###.#", "..#.##..##........#.......#.###", ".....#..........#.....#....#...", ".......##..##..###.......#####.", "..###......#.#....###....##...#", "#..##.....#..###...#.....##.##.", "#..#..##.##.###.####.##.#......", ".#.#......#.##......#..#......#", "..###.....#.#......#.#.####....", "#..............#..#.#...#.###..", "...#..#.##..........##.#...#.##", ".#.#.#.........#....#.#..#.....", "..#.##..#...#..#...#......#....", ".......#...#.##.#.#..#...##..#.", "..........#.####...#........#.#", "....#...#....##.#.........#.#..", "##.#..#.......###....#..#..#.#.", "..##.....#..#.#.#.####......#..", ".#.....#..........#..#..#.#....", "......#.#.......#.#...#..#..#..", "...#...............#....#...#..", "##.......#.........#.......#...", "...#.......###...#.#...#.......", "#...###....#....##....#....#...", "...#....##..#.#.............##.", ".....#.#.#..#......#...#.#..#..", ".##....#..##..#####..##.....##.", "....##.#.#..#.....#.#...#......", "...#.....##.#.#..##..#.#.......", ".......#..#..#..........#......", ".......#...#..#.........#.##...", "..#..#..#...##..#.#....#......#", "..#....#...#.#......#........#.", ".#...#..#...#.#..........#.....", "#..#...####..#......##.##.#.#..", ".#...#.#...#.#.....#..##.#.....", "..#.##.#......#.........##...#.", "###..............#.............", "...#...###....#..#.............", ".##....#......#..#.....#..#..#.", ".#..........#.....##...#..#....", "....##..#.#......###.##......#.", ".#..##.#.##.#...##.#......###.#", "#..###.#...###..#........#.#...", "#..#.#.#..#...###.##.##..#..#..", "#.#..#....#.........##......#..", "....###.....###....#...........", "....#..##.##....##..#.....#....", ".#.....#....####...#..##.#..###", ".........##..#......#.#...##...", ".##.......#.....#.###.#..#.#..#", ".....#.#...###.....#......####.", "##.#...#......#.#.#..#.####...#", ".#.##.....#..#..#.............#", ".#..###..#..#......#..##......#", ".......#.#........##.....#.#...", "#....#...#..###..#.#.....#.##..", ".##.....#.#....###..#.....##...", "...##....#....#...#....#.#.#...", "#####..#...........###....#...#", ".#.......##.##.....#....#......", ".#..#.#...#..#......#...#..#.#.", "....#.....##...#####..#...#...#", "###.##...#.#............#....#.", ".....#...#........##.........#." ) println("day3-pt1: " + part1(input)) // 276 println("day3-pt2: " + part2(input, slopes)) // 7812180000 } }
0
Kotlin
0
0
42a4fce4526182737d9661fae66c011f0948e481
16,395
adventofcode
MIT License
src/chapter3/section3/ex5&6.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter3.section3 import chapter1.section4.factorial import chapter2.sleep import chapter3.section2.fullArray import edu.princeton.cs.algs4.StdDraw import extensions.formatDouble /** * 3.3.5: 右图显示了N=1到6之间大小为N的所有不同的2-3树(无先后次序) * 请画出N=7、8、9和10的大小为N的所有不同的2-3树 * 3.3.6: 计算用N个随机键构造练习3.3.5中每棵2-3树的概率 * * 解:参考练习3.2.9、3.2.26 */ fun ex5(N: Int, delay: Long) { val allBSTArray = createAllComparableRedBlackBST(N) val countBST = RedBlackBST<ComparableRedBlackBST<Int, Int>, Int>() allBSTArray.forEach { tree -> val count = countBST.get(tree) if (count == null) { countBST.put(tree, 1) } else { countBST.put(tree, count + 1) } } val total = allBSTArray.size println("N=$N factorial(N)=$total diffTreeNum=${countBST.size()}") countBST.keys().forEach { tree -> drawRedBlackBST(tree) val count = countBST.get(tree) ?: 1 StdDraw.setPenColor() StdDraw.textLeft(0.3, 0.98, "N=$N probabilities=${count}/${total}=${formatDouble(count.toDouble() / total * 100, 2)}%") sleep(delay) } } fun createAllComparableRedBlackBST(N: Int): Array<ComparableRedBlackBST<Int, Int>> { val array = Array(N) { it + 1 } val list = ArrayList<Array<Int>>() fullArray(array, 0, list) check(list.size == factorial(N).toInt()) return Array(list.size) { index -> ComparableRedBlackBST<Int, Int>().apply { list[index].forEach { key -> put(key, 0) } } } } /** * 可比较大小的红黑树 */ class ComparableRedBlackBST<K : Comparable<K>, V : Any> : RedBlackBST<K, V>(), Comparable<ComparableRedBlackBST<K, V>> { override fun compareTo(other: ComparableRedBlackBST<K, V>): Int { return compare(this.root, other.root) } fun compare(node1: Node<K, V>?, node2: Node<K, V>?): Int { if (node1 == null && node2 == null) return 0 if (node1 == null) return -1 if (node2 == null) return 1 val result1 = node1.key.compareTo(node2.key) if (result1 != 0) return result1 val result2 = compare(node1.left, node2.left) if (result2 != 0) return result2 return compare(node1.right, node2.right) } } fun main() { var N = 1 val delay = 1000L repeat(10) { ex5(N, delay) N++ } }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,498
Algorithms-4th-Edition-in-Kotlin
MIT License
aoc_2023/src/main/kotlin/problems/day3/Gondola.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day3 class Gondola(val symbolNumbers: List<SymbolNumbers>) { companion object { val symbolRegex = Regex("""[^\d.]""") fun fromLines(lines: List<String>): Gondola { val symbolNumbers = mutableListOf<SymbolNumbers>() for (i in lines.indices) { val line = lines[i] for (j in line.indices) { val char = line[j] if (symbolRegex.matches(char.toString())) { val numbersArooundCoordinate = numbersAroundCoordinate(lines, i, j) symbolNumbers.add(SymbolNumbers(char, numbersArooundCoordinate)) } } } return Gondola(symbolNumbers) } private fun numbersAroundCoordinate(lines: List<String>, i: Int, j: Int): List<Int> { val listNumbers: MutableList<Int> = mutableListOf() var jContinue: Int for (i2 in i - 1..<i + 2) { jContinue = -1 for (j2 in j - 1..<j + 2) { if (i2 == i && j2 == j) continue if (jContinue >= j2) continue val line = lines[i2] val char = line[j2] if (char.isDigit()) { val digitsBefore: MutableList<Char> = mutableListOf() for (x1 in j2 - 1 downTo 0) { if (line[x1].isDigit()) { digitsBefore.add(0, line[x1]) } else { break } } val digitsAfter: MutableList<Char> = mutableListOf() for (x2 in j2 + 1 until line.length) { if (line[x2].isDigit()) { digitsAfter.add(line[x2]) } else { break } } val numString = digitsBefore.joinToString("") + char + digitsAfter.joinToString("") listNumbers.add(numString.toInt()) jContinue = j2 + digitsAfter.count() } } } return listNumbers } } fun sumValues(): Int { return this.symbolNumbers.fold(0) { acc, symbolNumbers -> acc + symbolNumbers.numbers.sum() } } fun gearRatio(): Int { return this.symbolNumbers.filter { it.symbol == '*' && it.numbers.count() == 2 }.fold(0) { acc, symbolNumbers -> acc + symbolNumbers.numbers.reduce { acc2, value -> acc2 * value } } } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
2,826
advent-of-code-2023
MIT License
src/main/kotlin/leetcode/kotlin/Important Code Snippets.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin import java.util.concurrent.TimeUnit // using comparator private fun sortArray(twoDArray: Array<IntArray>) { // 1 twoDArray.sortWith(kotlin.Comparator { t1, t2 -> t1[1] - t2[1] }) // 2 twoDArray.sortWith(object : Comparator<IntArray> { override fun compare(p0: IntArray?, p1: IntArray?): Int { return p0!![1] - p1!![1] } }) } fun main() { arrayOverFlow() // var r = Range(1, Int.MAX_VALUE) // r // IntStream.range(0,20).parallel().forEach(i->{ // ... do something here // }); } private fun arrayOverFlow() { var list = mutableListOf<Int>() var start = System.currentTimeMillis() var k = 0 for (i in 1..Int.MAX_VALUE) { k++ list.add(k) } println(k) var milliseconds = System.currentTimeMillis() - start val minutes: Long = TimeUnit.MILLISECONDS.toMinutes(milliseconds) val seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) println("time taken milliseconds=" + milliseconds) println("time taken minutes=" + minutes) println("time taken seconds=" + seconds) println("its okay till here") } private fun findMode() { val count = hashMapOf<Int, Int>() /** * sort map with max value frequency and return IntArray of keys. */ // 1. val maxVal = count.map { it.value }.max() ?: 0 var arr: IntArray = count.filter { it.value >= maxVal }.map { it.key }.toIntArray() // 2. arr = count.filter { it.value >= count.maxBy { it.value }!!.value }.map { it.key }.toIntArray() } // using pair and tripple private fun PairExample() { var p = Pair("sandeep", 1) println(p.first) println(p.second) } // using pair and tripple private fun TrippleExample() { var p = Triple("sandeep", 1, 4.9) println(p.first) println(p.second) println(p.third) } // find min index of smallest abs value in array private fun minIndex() { var arr = intArrayOf(3, 2, -1, 6, 9, 0) println(arr.indexOf(arr.minBy { i -> (i) }!!)) val index = arr.minBy { (it) }?.let { arr.indexOf(it) } println(index) val i = arr.withIndex().minBy { (_, f) -> f }?.index println(i) println(arr.indexOf(arr.min()!!)) println(arr.indices.minBy { arr[it] }) } private fun sortingExamples() { var sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e") sortedValues.sortBy { it.second } println(sortedValues) var a = mutableListOf(3, 2, 1, 4) a.sortBy { it % 2 } println(a) val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim") val ageComparator = compareBy<Pair<Int, String?>> { it.first } val ageAndNameComparator = ageComparator.thenByDescending { it.second } println(students.sortedWith(ageAndNameComparator)) var arr = intArrayOf(3, 2, 1, 4) var arr1 = arr.sortedBy { it % 2 } println(arr1.toList()) }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
2,953
kotlinmaster
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/remove_duplicates_from_array/RemoveDuplicatesFromSortedArray.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.remove_duplicates_from_array import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/problems/remove-duplicates-from-sorted-array/ */ class RemoveDuplicatesFromSortedArrayTests { @Test fun `remove the duplicates in-place such that each element appear only once`() { intArrayOf().removeDuplicatesToList() shouldEqual emptyList() intArrayOf(1).removeDuplicatesToList() shouldEqual listOf(1) intArrayOf(1).removeDuplicatesToList() shouldEqual listOf(1) intArrayOf(1, 1).removeDuplicatesToList() shouldEqual listOf(1) intArrayOf(1, 1, 1).removeDuplicatesToList() shouldEqual listOf(1) intArrayOf(1, 2).removeDuplicatesToList() shouldEqual listOf(1, 2) intArrayOf(1, 1, 2).removeDuplicatesToList() shouldEqual listOf(1, 2) intArrayOf(1, 2, 2).removeDuplicatesToList() shouldEqual listOf(1, 2) intArrayOf(1, 2, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(1, 1, 2, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(1, 2, 2, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(1, 2, 3, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(1, 1, 2, 2, 3, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4).removeDuplicatesToList() shouldEqual listOf(0, 1, 2, 3, 4) } } private fun IntArray.removeDuplicatesToList(): List<Int> { val newSize = removeDuplicates() return toList().take(newSize) } private fun IntArray.removeDuplicates(): Int { if (size <= 1) return size var i = 0 var j = 1 while (j < size) { if (this[i] != this[j]) { if (i + 1 != j) this[i + 1] = this[j] i++ } j++ } return i + 1 }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,863
katas
The Unlicense
src/day21/Day21.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
package day21 import readInput import java.util.regex.Pattern enum class Operation { ADD, SUBTRACT, MULTIPLY, DIVIDE, COMPARE } fun translateOp(op: String): Operation = when(op) { "+" -> Operation.ADD "-" -> Operation.SUBTRACT "/" -> Operation.DIVIDE "*" -> Operation.MULTIPLY "=" -> Operation.COMPARE else -> throw Exception("Unexpected operation") } data class Job(val lhs: String, val op: Operation, val rhs: String) fun parseMonkeyJobs(input: List<String>, resolvedMonkeys: MutableMap<String, Long>, unresolvedMonkeys: MutableMap<String, Job>) { val pattern = Pattern.compile( """([a-z]+) ([+\-*/]) ([a-z]+)""") for (entry in input) { val dataPair = entry.split(":") val name = dataPair[0] val job = dataPair[1].trim() val matcher = pattern.matcher(job) if (matcher.find()) { var matchGroup = 1 unresolvedMonkeys[name] = Job( matcher.group(matchGroup++), translateOp(matcher.group(matchGroup++)), matcher.group(matchGroup) ) } else { resolvedMonkeys[name] = job.toLong() } } } fun resolve(monkey: String, resolvedMonkeys: MutableMap<String, Long>, unresolvedMonkeys: MutableMap<String, Job>): Long { while(unresolvedMonkeys.containsKey(monkey)) { for (entry in unresolvedMonkeys) { val lhs = entry.value.lhs val rhs = entry.value.rhs if (resolvedMonkeys.containsKey(lhs) && resolvedMonkeys.containsKey(rhs)) { val resolvedValue = when(entry.value.op) { Operation.ADD -> resolvedMonkeys[lhs]!! + resolvedMonkeys[rhs]!! Operation.DIVIDE -> resolvedMonkeys[lhs]!! / resolvedMonkeys[rhs]!! Operation.MULTIPLY -> resolvedMonkeys[lhs]!! * resolvedMonkeys[rhs]!! Operation.SUBTRACT -> resolvedMonkeys[lhs]!! - resolvedMonkeys[rhs]!! else -> throw Exception("Unexpected operation") } unresolvedMonkeys.remove(entry.key) resolvedMonkeys[entry.key] = resolvedValue break } } } return resolvedMonkeys[monkey]!! } abstract class TreeNode(val name: String) { abstract fun dependsOn(provider: String): Boolean abstract fun value(): Long abstract fun reverseResolve(unknownValue: String, targetValue: Long): Long } class InternalNode(name: String, val op: Operation): TreeNode(name) { lateinit var lhs: TreeNode lateinit var rhs: TreeNode override fun dependsOn(provider: String): Boolean = lhs.dependsOn(provider) || rhs.dependsOn(provider) override fun value(): Long = when (op) { Operation.ADD -> lhs.value() + rhs.value() Operation.DIVIDE -> lhs.value() / rhs.value() Operation.MULTIPLY -> lhs.value() * rhs.value() Operation.SUBTRACT -> lhs.value() - rhs.value() else -> throw Exception("Unexpected operation") } override fun reverseResolve(unknownValue: String, targetValue: Long): Long { if (lhs.dependsOn(unknownValue)) { return when(op) { Operation.ADD -> lhs.reverseResolve(unknownValue, targetValue - rhs.value()) Operation.SUBTRACT -> lhs.reverseResolve(unknownValue, targetValue + rhs.value()) Operation.MULTIPLY -> lhs.reverseResolve(unknownValue, targetValue / rhs.value()) Operation.DIVIDE -> lhs.reverseResolve(unknownValue, targetValue * rhs.value()) else -> throw Exception("Unexpected operation") } } else { return when(op) { Operation.ADD -> rhs.reverseResolve(unknownValue, targetValue - lhs.value()) Operation.SUBTRACT -> rhs.reverseResolve(unknownValue, lhs.value() - targetValue) Operation.MULTIPLY -> rhs.reverseResolve(unknownValue, targetValue / lhs.value()) Operation.DIVIDE -> rhs.reverseResolve(unknownValue, lhs.value() / targetValue) else -> throw Exception("Unexpected operation") } } } } class TerminalNode(name: String, val value: Long): TreeNode(name) { override fun dependsOn(provider: String): Boolean = name == provider override fun value(): Long = value override fun reverseResolve(unknownValue: String, targetValue: Long): Long { if (name == unknownValue) { return targetValue } return value } } fun buildSubTree(rootNode: InternalNode, resolvedMonkeys: MutableMap<String, Long>, unresolvedMonkeys: MutableMap<String, Job>) { val rootEntry = unresolvedMonkeys[rootNode.name]!! if (resolvedMonkeys.containsKey(rootEntry.rhs)) { rootNode.rhs = TerminalNode(rootEntry.rhs, resolvedMonkeys[rootEntry.rhs]!!) } else { rootNode.rhs = InternalNode(rootEntry.rhs, unresolvedMonkeys[rootEntry.rhs]!!.op) buildSubTree(rootNode.rhs as InternalNode, resolvedMonkeys, unresolvedMonkeys) } if (resolvedMonkeys.containsKey(rootEntry.lhs)) { rootNode.lhs = TerminalNode(rootEntry.lhs, resolvedMonkeys[rootEntry.lhs]!!) } else { rootNode.lhs = InternalNode(rootEntry.lhs, unresolvedMonkeys[rootEntry.lhs]!!.op) buildSubTree(rootNode.lhs as InternalNode, resolvedMonkeys, unresolvedMonkeys) } } fun buildTree(resolvedMonkeys: MutableMap<String, Long>, unresolvedMonkeys: MutableMap<String, Job>): InternalNode { val root = InternalNode("root", Operation.ADD) buildSubTree(root, resolvedMonkeys, unresolvedMonkeys) return root } fun main() { fun part1(input: List<String>): Long { val resolvedMonkeys = mutableMapOf<String, Long>() val unresolvedMonkeys = mutableMapOf<String, Job>() parseMonkeyJobs(input, resolvedMonkeys, unresolvedMonkeys) val rootYell = resolve("root", resolvedMonkeys, unresolvedMonkeys) println("Root monkey yells $rootYell") return rootYell } fun part2(input: List<String>): Long { var humanSays: Long = 0 val resolvedMonkeys = mutableMapOf<String, Long>() val unresolvedMonkeys = mutableMapOf<String, Job>() parseMonkeyJobs(input, resolvedMonkeys, unresolvedMonkeys) val dependencyTree = buildTree(resolvedMonkeys, unresolvedMonkeys) val humanName = "humn" if (dependencyTree.rhs.dependsOn(humanName)) { val targetVal = resolve(dependencyTree.lhs.name, resolvedMonkeys, unresolvedMonkeys) humanSays = dependencyTree.rhs.reverseResolve(humanName, targetVal) } else { val targetVal = resolve(dependencyTree.rhs.name, resolvedMonkeys, unresolvedMonkeys) humanSays = dependencyTree.lhs.reverseResolve(humanName, targetVal) } println("Human says $humanSays") return humanSays } val testInput = readInput("Day21_test") check(part1(testInput) == 152.toLong()) check(part2(testInput) == 301.toLong()) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
7,210
AdventOfCode2022
Apache License 2.0
repository/src/main/kotlin/org/goodmath/polytope/repository/agents/text/lcs.kt
MarkChuCarroll
608,827,232
false
null
/* * 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 org.goodmath.polytope.repository.agents.text data class CrossVersionLineMapping( val lineNumberInLeft: Int, val lineNumberInRight: Int) fun<T> List<T>.prepend(x: T): List<T> = listOf(x) + this /** * An implementation of the dynamic programming algorithm for the longest common subsequence. * * if last(left) == last(right): the result is lcs(left[:-1], right[:-1]) + last(left) * * if last(left) != last(right): lcs is the longer of lcs(left[0:-1], right) and * lcs(left, right[]0:-1]). * * Instead of doing the classic dynamic programming table, I think * it's clearer to just use memoization. Same thing in the end. * * This returns an indexed representation of the LCS, where each element * of the result is a pair containing the position of the * line in the left and right inputs. */ fun indexedLcs(left: List<String>, right: List<String>): List<CrossVersionLineMapping> = computeMemoized(left, left.size, right, right.size, HashMap()) fun computeMemoized( left: List<String>, leftLength: Int, right: List<String>, rightLength: Int, memoTable: MutableMap<Pair<Int, Int>, List<CrossVersionLineMapping>>): List<CrossVersionLineMapping> { val memoizedResult = memoTable[Pair(leftLength, rightLength)] return if (memoizedResult == null) { val newResult = computeLcs( left, leftLength, right, rightLength, memoTable) memoTable[Pair(leftLength, rightLength)] = newResult newResult } else { memoizedResult } } private fun computeLcs( left: List<String>, leftLength: Int, right: List<String>, rightLength: Int, memoTable: MutableMap<Pair<Int, Int>, List<CrossVersionLineMapping>>): List<CrossVersionLineMapping> { if (leftLength == 0 || rightLength == 0) { return emptyList() } return if (left[leftLength - 1] == right[rightLength - 1]) { val subSolution: List<CrossVersionLineMapping> = computeMemoized(left, leftLength - 1, right, rightLength - 1, memoTable) subSolution.prepend(CrossVersionLineMapping(leftLength - 1, rightLength - 1)) } else { val rightBiased = computeMemoized(left, leftLength - 1, right, rightLength, memoTable) val leftBiased = computeMemoized(left, leftLength, right, rightLength - 1, memoTable) if (rightBiased.size > leftBiased.size) { rightBiased } else { leftBiased } } }
0
Kotlin
0
0
e33a10b8bb604355e724d724ac27499d4cef826e
3,083
k-polytope
Apache License 2.0
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day17/Day17.kt
jntakpe
433,584,164
false
{"Kotlin": 64657, "Rust": 51491}
package com.github.jntakpe.aoc2021.days.day17 import com.github.jntakpe.aoc2021.shared.Day import com.github.jntakpe.aoc2021.shared.readInput object Day17 : Day { override val input = readInput(17) override fun part1() = Launcher(TargetArea.from(input)).calibrate().maxOrNull()!! override fun part2() = Launcher(TargetArea.from(input)).calibrate().count() class Launcher(private val target: TargetArea) { fun calibrate() = (0..target.x.last).flatMap { x -> (target.y.first..200).mapNotNull { launch(Velocity(x, it)) } } private fun launch(velocity: Velocity): Int? { var probe = Probe(velocity, Position.START, target) var max = 0 while (probe.hasNext()) { if (probe.position.y > max) { max = probe.position.y } probe = probe.next() } return max.takeIf { probe.target.contains(probe.position) } } } data class Probe(val velocity: Velocity, val position: Position, val target: TargetArea) : Iterator<Probe> { override fun hasNext() = !target.missed(position) && !target.contains(position) override fun next() = copy(position = position.next(velocity), velocity = velocity.next()) } data class TargetArea(val x: IntRange, val y: IntRange) { companion object { fun from(raw: String) = TargetArea(range(raw, 'x'), range(raw, 'y')) private fun range(raw: String, axis: Char): IntRange { return raw.substringAfter("$axis=").substringBefore(",").split("..").map { it.toInt() } .let { IntRange(it.minOrNull()!!, it.maxOrNull()!!) } } } fun contains(position: Position) = x.contains(position.x) && y.contains(position.y) fun missed(position: Position) = position.x > x.last || position.y < y.first } data class Position(val x: Int, val y: Int) { companion object { val START = Position(0, 0) } fun next(velocity: Velocity) = Position(x + velocity.x, y + velocity.y) } data class Velocity(val x: Int, val y: Int) { fun next() = copy(x = if (x > 0) x - 1 else 0, y = y - 1) } }
0
Kotlin
1
5
230b957cd18e44719fd581c7e380b5bcd46ea615
2,257
aoc2021
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxConcatenationOfSubsequence.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2024 <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 kotlin.math.max /** * 1239. Maximum Length of a Concatenated String with Unique Characters * @see <a href="https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters">Source * </a> */ fun interface MaxConcatenationOfSubsequence { operator fun invoke(arr: List<String>): Int } class MaxConcatenationOfSubsequenceSet : MaxConcatenationOfSubsequence { override fun invoke(arr: List<String>): Int { val dp: MutableList<Int> = ArrayList() dp.add(0) var res = 0 for (str in arr) { var a = 0 var dup = 0 for (c in str.toCharArray()) { dup = dup or (a and (1 shl (c.code - 'a'.code))) a = a or (1 shl (c.code - 'a'.code)) } if (dup > 0) continue for (i in dp.indices.reversed()) { if ((dp[i] and a) > 0) continue dp.add(dp[i] or a) res = max(res.toDouble(), Integer.bitCount(dp[i] or a).toDouble()).toInt() } } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,731
kotlab
Apache License 2.0
src/Day08.kt
kkaptur
573,511,972
false
{"Kotlin": 14524}
import java.io.File import java.util.Collections.max class Position( val topElements: MutableList<Int>, val bottomElements: MutableList<Int>, val leftElements: MutableList<Int>, val rightElements: MutableList<Int> ) { companion object { fun of( currentColumnElements: MutableList<Int>, currentRowElements: MutableList<Int>, rowIndex: Int, elementIndex: Int, listSize: Int, rowSize: Int ): Position { return Position( topElements = currentColumnElements.subList(0, rowIndex), bottomElements = currentColumnElements.subList(rowIndex + 1, listSize), leftElements = currentRowElements.subList(0, elementIndex), rightElements = currentRowElements.subList(elementIndex + 1, rowSize) ) } } fun allElements(): MutableList<Int> { val fullList = mutableListOf<Int>() fullList.addAll(topElements) fullList.addAll(bottomElements) fullList.addAll(leftElements) fullList.addAll(rightElements) return fullList } } fun main() { val input = File("src", "Day08.txt").readLines() val inputTest = File("src", "Day08_test.txt").readLines() fun getPopulatedTable(input: List<String>): MutableList<MutableList<Int>> { val lists = mutableListOf<MutableList<Int>>() input.map { row -> lists.add(mutableListOf<Int>().apply { addAll(row.map { it.digitToInt() }) }) } return lists } fun part1(input: List<String>): Int { val lists = getPopulatedTable(input) var visibleTreesNumber = 0 //trees on the edges visibleTreesNumber += 2 * lists.size + (lists[0].size - 2) * 2 //trees in the interior lists.forEachIndexed { rowIndex, elementsList -> if (rowIndex == 0 || rowIndex == lists.size - 1) return@forEachIndexed elementsList.forEachIndexed { elementIndex, element -> if (elementIndex != 0 && elementIndex != elementsList.size - 1) { val currentColumn = mutableListOf<Int>() lists.forEach { list -> currentColumn.add(list[elementIndex]) } val elementPosition = Position.of( currentColumn, elementsList, rowIndex, elementIndex, lists.size, elementsList.size ) if (max(elementPosition.topElements) < element || max(elementPosition.bottomElements) < element || max(elementPosition.leftElements) < element || max(elementPosition.rightElements) < element ) visibleTreesNumber += 1 } } } return visibleTreesNumber } fun part2(input: List<String>): Int { val lists = getPopulatedTable(input) var visibleTreesNumber = 0 val scenicScores = mutableListOf<Int>() //trees on the edges visibleTreesNumber += 2 * lists.size + (lists[0].size - 2) * 2 //trees in the interior lists.forEachIndexed { rowIndex, elementsList -> if (rowIndex == 0 || rowIndex == lists.size - 1) return@forEachIndexed elementsList.forEachIndexed { elementIndex, element -> if (elementIndex != 0 && elementIndex != elementsList.size - 1) { var scoreTop = 0 var scoreBottom = 0 var scoreLeft = 0 var scoreRight = 0 val currentColumn = mutableListOf<Int>() lists.forEach { list -> currentColumn.add(list[elementIndex]) } val elementPosition = Position.of( currentColumn, elementsList, rowIndex, elementIndex, lists.size, elementsList.size ) for (e in elementPosition.topElements.reversed()) { scoreTop += 1;if (e >= element) break } for (e in elementPosition.bottomElements) { scoreBottom += 1; if (e >= element) break } for (e in elementPosition.leftElements.reversed()) { scoreLeft += 1; if (e >= element) break } for (e in elementPosition.rightElements) { scoreRight += 1; if (e >= element) break } scenicScores.add(scoreTop * scoreBottom * scoreLeft * scoreRight) } } } return scenicScores.max() } check(part1(inputTest) == 21) check(part2(inputTest) == 8) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
055073b7c073c8c1daabbfd293139fecf412632a
5,169
AdventOfCode2022Kotlin
Apache License 2.0
src/main/kotlin/leetcode/Problem2115.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/ */ class Problem2115 { fun findAllRecipes(recipes: Array<String>, ingredients: List<List<String>>, supplies: Array<String>): List<String> { val recipeToIngredients = mutableMapOf<String, List<String>>() for ((index, recipe) in recipes.withIndex()) { recipeToIngredients[recipe] = ingredients[index] } val answer = mutableListOf<String>() val memo = mutableMapOf<String, Boolean>() val visited = mutableSetOf<String>() val supplySet = supplies.toSet() for (recipe in recipes) { if (findAllRecipes(recipeToIngredients, supplySet, recipe, visited, memo)) { answer += recipe } } return answer } private fun findAllRecipes(recipeToIngredients: MutableMap<String, List<String>>, supplies: Set<String>, recipe: String, visited: MutableSet<String>, memo: MutableMap<String, Boolean>): Boolean { if (memo[recipe] != null) { return memo[recipe]!! } if (recipe in visited) { return false } visited += recipe var found = true for (ingredient in recipeToIngredients[recipe] ?: listOf()) { found = if (ingredient in recipeToIngredients) { found && findAllRecipes(recipeToIngredients, supplies, ingredient, visited, memo) } else { found && ingredient in supplies } } memo[recipe] = found return found } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,738
leetcode
MIT License
src/main/kotlin/days/Day21.kt
butnotstupid
433,717,137
false
{"Kotlin": 55124}
package days class Day21 : Day(21) { private val circleSize = 10 override fun partOne(): Any { val maxScore = 1000 val (startFirst, startSecond) = inputList.map { Regex("""Player \d+ starting position: (\d+)""").find(it)!!.groupValues[1].toInt() } val players = generateSequence(0) { 1 - it } val turns = generateSequence(1) { it + 1 }.chunked(3).zip(players) val endGame = turns.scan(Position(startFirst) to Position(startSecond)) { positions, turn -> val (first, second) = positions val (steps, player) = turn when (player) { 0 -> Position(first.pos.step(steps), first.score + first.pos.step(steps), steps.last().toLong()) to second 1 -> first to Position(second.pos.step(steps), second.score + second.pos.step(steps), steps.last().toLong()) else -> throw IllegalArgumentException("Player $player unexpected") } }.first { it.first.score >= maxScore || it.second.score >= maxScore } return listOf(endGame.first, endGame.second).let { it.minOf { it.score } * it.maxOf { it.lastRolled } } } private fun Int.step(steps: List<Int>): Int { return 1 + (this + steps.sum() - 1) % circleSize } data class Position(val pos: Int, val score: Long = 0, val lastRolled: Long = 0) override fun partTwo(): Any { TODO() } }
0
Kotlin
0
0
a06eaaff7e7c33df58157d8f29236675f9aa7b64
1,417
aoc-2021
Creative Commons Zero v1.0 Universal
calendar/day03/Day3.kt
divgup92
726,169,029
false
{"Kotlin": 16931}
package day03 import Day import Lines import kotlin.math.max import kotlin.math.min class Day3 : Day() { private var numberList = mutableListOf<Map<Int, MutableList<Pair<Int, Int>>>>() private var specialCharList = mutableListOf<List<Int>>() private var starCharList = mutableListOf<List<Int>>() override fun part1(input: Lines): Any { var sum = 0.0 buildLists(input) for ((i, numberLine) in numberList.withIndex()) { val lineList = specialCharList.subList(max(0, i - 1), min(specialCharList.size, i + 2)) for (number in numberLine) { for (pos in number.value) { if (isPartNumber(pos, lineList, input[0].length - 1)) { sum += number.key } } } } return sum } private fun buildLists(input: Lines) { for (line in input) { var start = -1 var num = 0 val numberMap = mutableMapOf<Int, MutableList<Pair<Int, Int>>>() val specialCharLine = mutableListOf<Int>() val starCharLine = mutableListOf<Int>() for (i in line.indices) { if (line[i].isDigit() && start >= 0) { num = num * 10 + line[i].digitToInt() } else if (line[i].isDigit()) { start = i num = line[i].digitToInt() } else if (start >= 0) { val listPos = numberMap.getOrDefault(num, mutableListOf()) listPos.add(Pair(start, i - 1)) numberMap[num] = listPos start = -1 num = 0 } if (!line[i].isDigit() && line[i] != '.') { specialCharLine.add(i) } if (line[i] == '*') { starCharLine.add(i) } } if (start > 0) { val listPos = numberMap.getOrDefault(num, mutableListOf()) listPos.add(Pair(start, line.length - 1)) numberMap[num] = listPos } numberList.add(numberMap) specialCharList.add(specialCharLine) starCharList.add(starCharLine) } } private fun isPartNumber(startEndNumber: Pair<Int, Int>, lines: List<List<Int>>, lastIndex: Int): Boolean { val start = max(0, startEndNumber.first - 1) val end = min(startEndNumber.second + 1, lastIndex) for (line in lines) { for (specialCharPos in line) { if (specialCharPos in start..end) { return true } } } return false } override fun part2(input: Lines): Any { buildLists(input) var sum = 0 for ((i, starLine) in starCharList.withIndex()) { val lineList = numberList.subList(max(0, i - 1), min(specialCharList.size, i + 2)) for (star in starLine) { sum += getGearProduct(star, lineList, input[0].length) } } return sum } private fun getGearProduct(starPos: Int, lines: List<Map<Int, MutableList<Pair<Int, Int>>>>, lastIndex: Int): Int { val adjNumbers = mutableListOf<Int>() for (line in lines) { for (num in line) { for (numPos in num.value) { val start = max(numPos.first - 1, 0) val end = min(numPos.second + 1, lastIndex) if (starPos in start..end) { adjNumbers.add(num.key) } } } } if (adjNumbers.size == 2) { return adjNumbers.reduce(Int::times) } return 0 } }
0
Kotlin
0
0
38dbf3b6eceea8d5b0eeab82b384acdd0c205852
3,859
advent-of-code-2023
Apache License 2.0
src/main/java/com/barneyb/aoc/aoc2022/day02/RockPaperScissors.kt
barneyb
553,291,150
false
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
package com.barneyb.aoc.aoc2022.day02 import com.barneyb.aoc.util.Solver fun main() { Solver.execute( ::parse, partOne, partTwo, ) } internal fun parse(input: String) = input.trim() .lines() private val tableOne: Map<String, Int> = mapOf( "A X" to 4, "B X" to 1, "C X" to 7, "A Y" to 8, "B Y" to 5, "C Y" to 2, "A Z" to 3, "B Z" to 9, "C Z" to 6, ) private val tableTwo: Map<String, Int> = mapOf( "A X" to 3, "B X" to 1, "C X" to 2, "A Y" to 4, "B Y" to 5, "C Y" to 6, "A Z" to 8, "B Z" to 9, "C Z" to 7, ) internal fun part(table: Map<String, Int>) = fun(rounds: List<String>) = rounds.sumOf(table::getValue) internal val partOne = part(tableOne) internal val partTwo = part(tableTwo)
0
Kotlin
0
0
8b5956164ff0be79a27f68ef09a9e7171cc91995
822
aoc-2022
MIT License
src/main/kotlin/adventofcode/year2022/Day02RockPaperScissors.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2022 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day02RockPaperScissors(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val strategies by lazy { input.lines().map { it.split(" ") }.map { it.first() to it.last() } } override fun partOne() = strategies .map { (opponent, me) -> when { opponent == "A" && me == "X" -> 1 + 3 opponent == "A" && me == "Y" -> 2 + 6 opponent == "A" && me == "Z" -> 3 + 0 opponent == "B" && me == "X" -> 1 + 0 opponent == "B" && me == "Y" -> 2 + 3 opponent == "B" && me == "Z" -> 3 + 6 opponent == "C" && me == "X" -> 1 + 6 opponent == "C" && me == "Y" -> 2 + 0 opponent == "C" && me == "Z" -> 3 + 3 else -> throw IllegalArgumentException("'$opponent $me' is not a valid strategy") } } .sum() override fun partTwo() = strategies .map { (opponent, outcome) -> when { opponent == "A" && outcome == "X" -> 3 + 0 opponent == "A" && outcome == "Y" -> 1 + 3 opponent == "A" && outcome == "Z" -> 2 + 6 opponent == "B" && outcome == "X" -> 1 + 0 opponent == "B" && outcome == "Y" -> 2 + 3 opponent == "B" && outcome == "Z" -> 3 + 6 opponent == "C" && outcome == "X" -> 2 + 0 opponent == "C" && outcome == "Y" -> 3 + 3 opponent == "C" && outcome == "Z" -> 1 + 6 else -> throw IllegalArgumentException("'$opponent $outcome' is not a valid strategy") } } .sum() }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,774
AdventOfCode
MIT License
src/aoc2022/Day16.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
package aoc2022 import utils.* import java.util.* import kotlin.math.max private const val STARTING_ROOM = "AA" private class Day16(val lines: List<String>) { var roomMap: Map<String, Room> val sparseEdges: Map<String, List<Edge>> val cache = mutableMapOf<State, Long>() init { val denseEdges = mutableMapOf<String, List<Edge>>() val denseRooms = lines.map { l -> val (a, b) = l.split(";") val name = a.split(" ")[1] val flow = a.split("=")[1].toLong() denseEdges[name] = b.split("valve")[1] .removePrefix("s") .removePrefix(" ") .split(", ") .map { Edge(it, 1) } Room(name, flow) } roomMap = denseRooms .filter { it.rate >= 0 || it.name == STARTING_ROOM } .associateBy { it.name } // Make shortest paths from every room to every other room sparseEdges = denseRooms.associate { r -> val shortestPath = computeSparseEdges(r, denseEdges) r.name to shortestPath .filter { r.name != it.key } .filter { roomMap[it.key]!!.rate > 0 } .map { Edge(it.key, it.value) } } } /** Create min spanning tree for this room. */ private fun computeSparseEdges(r: Room, denseEdges: Map<String, List<Edge>>): Map<String, Int> { val shortestPaths = mutableMapOf<String, Int>() val pq = PriorityQueue<Pair<String, Int>>(compareBy { it.second }) // PQ pq.add(r.name to 0) while (pq.isNotEmpty()) { val (name, distance) = pq.poll() // check if (shortestPaths.containsKey(name) && shortestPaths[name]!! <= distance) { continue } shortestPaths[name] = distance pq.addAll(denseEdges[name]!!.map { it.dest to distance + 1 }) } return shortestPaths } data class Room(val name: String, val rate: Long) data class Edge(val dest: String, val weight: Int) data class Actor(val minute: Int, val location: String) data class State( val actors: List<Actor>, val openValves: Set<String>, val isEle: Boolean = false, val isPt2: Boolean = false ) { constructor(actor: Actor, openValves: Set<String>, isEle: Boolean = false, isPt2: Boolean = false) : this(listOf(actor), openValves, isEle, isPt2) fun leadActor(): Actor { return actors[0] } } fun part1(): Long { cache.clear() val state = State(Actor(0, STARTING_ROOM), setOf()) val result = sparseEdges[state.leadActor().location]!!.maxOfOrNull { goto(it, state, 30) }!! cache.clear() return result } fun part2(): Long { cache.clear() val me = Actor(0, STARTING_ROOM) val elephant = Actor(0, STARTING_ROOM) val state = State(listOf(me, elephant), setOf()) val result = sparseEdges[state.leadActor().location]!!.maxOfOrNull { goto(it, state, 26) }!! cache.clear() return result } /** * Traverse the edge taking n minutes. If there is time, turn the valve and score those points. * * Return the max pressure you can release after this state. This only includes valves opened after this state. * The total pressure released for a volve is counted on the round it is open. */ private fun goto(edge: Edge, prevState: State, totalMinutes: Int): Long { // Move to the new location val loc = roomMap.get(edge.dest)!! // Put us on turn + traversal time + 1 turn to turn on the valve. // We can check the turn to change the valve now because if we don't have time to turn it, we can't score // any more points. val currentMinute = prevState.leadActor().minute + edge.weight + 1 // Turn on the valve val openValves = buildSet { addAll(prevState.openValves); add(loc.name) } val pressureReleasedThisTurn = loc.rate * (totalMinutes - currentMinute) val actors = mutableListOf<Actor>() actors.addAll(prevState.actors.drop(1)) actors.add(Actor(currentMinute, loc.name)) actors.sortedWith(compareBy<Actor> { it.minute }.thenBy { it.location }) val newState = prevState.copy(actors = actors, openValves=openValves) if (newState.actors.any { it.minute >= totalMinutes }) { return 0L } if (cache.containsKey(newState)) { return cache[newState]!! } val maxPressureReleasedAfterThisTurn = sparseEdges[newState.leadActor().location]!! .filter { !newState.openValves.contains(it.dest) } .map { goto(it, newState, totalMinutes) } .maxOrNull() ?: 0L // If we have more than one actor, consider the case where the leader goes solo. var maxPressureReleasedAfterThisTurnSolo = 0L if (actors.size > 1) { val soloState = newState.copy(actors = actors.take(1)) maxPressureReleasedAfterThisTurnSolo = sparseEdges[soloState.leadActor().location]!! .filter { !soloState.openValves.contains(it.dest) } .map { goto(it, soloState, totalMinutes) } .maxOrNull() ?: 0L } val maxPressureReleased = max(maxPressureReleasedAfterThisTurnSolo, maxPressureReleasedAfterThisTurn) + pressureReleasedThisTurn cache[newState] = maxPressureReleased return maxPressureReleased } } fun main() { val day = "16".toInt() val todayTest = Day16(readInput(day, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 1651L) val today = Day16(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1") execute(todayTest::part2, "Day[Test] $day: pt 2", 1707L) execute(today::part2, "Day $day: pt 2", 2838L) }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
5,461
aoc2022
Apache License 2.0
archive/2022/Day16_submission.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
/** * Pretty terrible code hacked together during submission. * I missed that lots of valves are not useful to open (flow = 0) and tried a walking-time solution * optimized to limit to the 500K top states at every minute */ private const val EXPECTED_1 = 1651 private const val EXPECTED_2 = 1707 private val edges = mutableMapOf<String, List<String>>() private val flow = mutableMapOf<String, Int>() private val num = mutableMapOf<String, Int>() class Day16_submission(isTest: Boolean) : Solver(isTest) { data class State(val open: Long, val loc: String) { fun calcflow() = flow.entries.sumOf { if (open and (1L shl num[it.key]!!) != 0L ) flow[it.key]!! else 0 } } data class State2(val open: Long, val loc: String, val loc2: String) { fun calcflow() = flow.entries.sumOf { if (open and (1L shl num[it.key]!!) != 0L ) flow[it.key]!! else 0 } } fun part1(): Any { var index = 0 edges.clear() flow.clear() num.clear() readAsLines().forEach{ line -> val parts = line.split(" ") val key = parts[1] flow[key] = parts[4].removeSurrounding("rate=", ";").toInt() val parts2 = line.split(", ") edges[key] = parts2.map { it.substringAfterLast(' ', it) } num[key] = index++ } var states = mapOf(State(0, "AA") to 0) repeat(30) { var newStates = mutableMapOf<State, Int>() for ((state, cflow) in states.entries) { val locNum = num[state.loc]!! val newflow = cflow + state.calcflow() if ((state.open and (1L shl locNum)) == 0L) { newStates.compute(state.copy(open = state.open or (1L shl locNum))) { key, prev -> if (prev != null) maxOf(prev, newflow) else newflow } } for (dest in edges[state.loc]!!) { newStates.compute(state.copy(loc = dest)) { key, prev -> if (prev != null) maxOf(prev, newflow) else newflow } } } states = newStates.entries.sortedByDescending { it.value }.take(500_000).associate { it.key to it.value } //println("${states.size} ${states.entries.maxOf { it.value }}") } return states.maxOf { state -> state.value } } fun part2(): Any { var index = 0 edges.clear() flow.clear() num.clear() readAsLines().forEach{ line -> val parts = line.split(" ") val key = parts[1] flow[key] = parts[4].removeSurrounding("rate=", ";").toInt() val parts2 = line.split(", ") edges[key] = parts2.map { it.substringAfterLast(' ', it) } num[key] = index++ } var states = mapOf(State2(0, "AA", "AA") to 0) repeat(26) { var newStates = mutableMapOf<State2, Int>() for ((state, cflow) in states.entries) { val locNum = num[state.loc]!! val locNum2 = num[state.loc2]!! val newflow = cflow + state.calcflow() //if (newflow < currentMin) continue val newstate1 = mutableSetOf<State2>() if ((state.open and (1L shl locNum)) == 0L) { newstate1.add(state.copy(open = state.open or (1L shl locNum))) } for (dest in edges[state.loc]!!) { newstate1.add(state.copy(loc = dest)) } //println("new1 ${newstate1.size}") val newstate2 = mutableSetOf<State2>() for (state in newstate1) { if ((state.open and (1L shl locNum2)) == 0L) { newstate2.add(state.copy(open = state.open or (1L shl locNum2))) } for (dest in edges[state.loc2]!!) { newstate2.add(state.copy(loc2 = dest)) } } for (state in newstate2) { if (state.loc > state.loc2) { newStates.compute(state.copy(loc=state.loc2, loc2=state.loc)) { key, prev -> if (prev != null) maxOf(prev, newflow) else newflow } } else newStates.compute(state) { key, prev -> if (prev != null) maxOf(prev, newflow) else newflow } } } states = newStates.entries.sortedByDescending { it.value }.take(500_000).associate { it.key to it.value } println("${states.size} ${states.entries.maxOf { it.value }}") } return states.maxOf { state -> state.value } } } fun main() { val testInstance = Day16_submission(true) val instance = Day16_submission(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
5,399
advent-of-code-2022
Apache License 2.0
src/Day01.kt
raigol
573,133,877
false
{"Kotlin": 1657}
fun main() { fun getElfCalories(input: List<String>): List<Int> { var sum = 0 val elfTotals = mutableListOf<Int>() for (i in input) { if(i.isNotBlank()) { sum += i.toInt() } else { elfTotals.add(sum) sum=0 } } elfTotals.add(sum) return elfTotals } fun sumOfNBiggestElfCalories(input: List<String>, n: Int): Int { val elfTotals = getElfCalories(input) return elfTotals.sortedDescending() .take(n) .sum() } val testInput = readInput("Day01_test") val input = readInput("Day01") check(sumOfNBiggestElfCalories(testInput, 1) == 24000) println("Biggest calories test: " +sumOfNBiggestElfCalories(testInput, 1)) println("Biggest calories: " + sumOfNBiggestElfCalories(input, 1)) println("3 Biggest calories total: "+ sumOfNBiggestElfCalories(input, 3)) }
0
Kotlin
0
0
bfc7d520693456fa3a2f539c4a611b6fb74aa53d
1,010
aoc-in-kotlin-2022
Apache License 2.0
src/main/kotlin/g1401_1500/s1489_find_critical_and_pseudo_critical_edges_in_minimum_spanning_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1489_find_critical_and_pseudo_critical_edges_in_minimum_spanning_tree // #Hard #Sorting #Graph #Union_Find #Minimum_Spanning_Tree #Strongly_Connected_Component // #2023_06_13_Time_342_ms_(100.00%)_Space_39.1_MB_(100.00%) import java.util.Arrays import java.util.LinkedList class Solution { fun findCriticalAndPseudoCriticalEdges(n: Int, edges: Array<IntArray>): List<List<Int>> { // {w, ind} val g = Array(n) { Array(n) { IntArray(2) } } for (i in edges.indices) { val e = edges[i] val f = e[0] val t = e[1] val w = e[2] g[f][t][0] = w g[t][f][0] = w g[f][t][1] = i g[t][f][1] = i } val mst: Array<MutableList<Int>?> = arrayOfNulls(n) for (i in 0 until n) { mst[i] = LinkedList() } val mstSet = BooleanArray(edges.size) Arrays.sort(edges) { a: IntArray, b: IntArray -> Integer.compare( a[2], b[2] ) } buildMST(n, edges, mstSet, mst, g) val ans: MutableList<List<Int>> = ArrayList(2) val pce: MutableSet<Int> = HashSet() val ce: MutableList<Int> = LinkedList() // pseudo critical edges for (edge in edges) { val f = edge[0] val t = edge[1] val w = edge[2] val ind = g[f][t][1] if (!mstSet[ind]) { val cur: MutableSet<Int> = HashSet() val p = path(f, t, w, -1, mst, g, cur) if (p && cur.isNotEmpty()) { pce.addAll(cur) pce.add(ind) } if (!p) { println("Should not reach here") } } } // critical edges for (edge in edges) { val f = edge[0] val t = edge[1] val ind = g[f][t][1] if (mstSet[ind] && !pce.contains(ind)) { ce.add(ind) } } ans.add(ce) ans.add(LinkedList(pce)) return ans } private fun path( f: Int, t: Int, w: Int, p: Int, mst: Array<MutableList<Int>?>, g: Array<Array<IntArray>>, ind: MutableSet<Int> ): Boolean { if (f == t) { return true } for (nbr in mst[f]!!) { if (p != nbr && path(nbr, t, w, f, mst, g, ind)) { if (g[f][nbr][0] == w) { ind.add(g[f][nbr][1]) } return true } } return false } private fun buildMST( n: Int, edges: Array<IntArray>, mste: BooleanArray, mstg: Array<MutableList<Int>?>, g: Array<Array<IntArray>> ) { val ds = DisjointSet(n) for (ints in edges) { if (ds.union(ints[0], ints[1])) { mstg[ints[0]]?.add(ints[1]) mstg[ints[1]]?.add(ints[0]) mste[g[ints[0]][ints[1]][1]] = true } } } private class DisjointSet(n: Int) { var parent: IntArray init { parent = IntArray(n) for (i in 0 until n) { parent[i] = i } } fun find(i: Int): Int { if (i == parent[i]) { return i } parent[i] = find(parent[i]) return parent[i] } fun union(u: Int, v: Int): Boolean { val pu = find(u) val pv = find(v) if (pu == pv) { return false } parent[pu] = pv return true } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,787
LeetCode-in-Kotlin
MIT License