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/Day01.kt
elliaoster
573,666,162
false
{"Kotlin": 14556}
fun main() { fun part1(input: List<String>): Int { var max = 0 var elfLine = 0 for (line in input) { if (line.isEmpty()) { elfLine = 0 } else { elfLine = elfLine + line.toInt() if (elfLine > max) { max = elfLine } } } return max } fun part2old(input: List<String>): Int { var max = 0 var max2 = 0 var max3 = 0 var elfLine = 0 for (line in input) { if (line.isEmpty()) { if (elfLine > max) { max3 = max2 max2 = max max = elfLine } else if (elfLine > max2) { max3 = max2 max2 = elfLine } else if (elfLine > max3) { max3 = elfLine } elfLine = 0 } else { elfLine = elfLine + line.toInt() } } if (elfLine > max) { max3 = max2 max2 = max max = elfLine } else if (elfLine > max2) { max3 = max2 max2 = elfLine } else if (elfLine > max3) { max3 = elfLine } return max + max2 + max3 } fun part2(input: List<String>): Int { var elves = arrayListOf<Int>() var elfLine = 0 for (i in 0..input.size - 1) { if (!input[i].isEmpty()) { elfLine = elfLine + input[i].toInt() } if (input[i].isEmpty()||i == input.size - 1) { elves.add(elfLine) elfLine = 0 } } var max = 0 var max2 = 0 var max3 = 0 for (elf in elves) { if (elf > max) { max3 = max2 max2 = max max = elf } else if (elf > max2) { max3 = max2 max2 = elf } else if (elf > max3) { max3 = elf } } return max + max2 + max3 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
27e774b133f9d5013be9a951d15cefa8cb01a984
2,470
advent-of-code-2022
Apache License 2.0
src/main/kotlin/us/jwf/aoc2021/Day12PassagePathing.kt
jasonwyatt
318,073,137
false
null
package us.jwf.aoc2021 import java.io.Reader import us.jwf.aoc.Day /** * AoC 2021 - Day 12 */ class Day12PassagePathing : Day<Int, Int> { override suspend fun executePart1(input: Reader): Int { val graph = Graph() input.readLines().forEach { graph.addEdge(it) } return graph.countPathsToEnd(Cave("start"), mutableSetOf(Cave("start"))) } override suspend fun executePart2(input: Reader): Int { val graph = Graph() input.readLines().forEach { graph.addEdge(it) } return graph.countPathsToEnd2(Cave("start"), mutableSetOf(Cave("start")), false) } class Graph { val neighbors = mutableMapOf<Cave, MutableSet<Cave>>() fun addEdge(line: String) { val (end1, end2) = line.split("-").map { Cave(it) } val end1Neighbors = neighbors[end1] ?: mutableSetOf() val end2Neighbors = neighbors[end2] ?: mutableSetOf() end1Neighbors.add(end2) end2Neighbors.add(end1) neighbors[end1] = end1Neighbors neighbors[end2] = end2Neighbors } fun countPathsToEnd(loc: Cave, visitedSmall: MutableSet<Cave>, soFar: List<Cave> = listOf(loc)): Int { if (loc.name == "end") { println(soFar) return 1 } val neighbors = neighbors[loc]!! return neighbors.sumOf { if (it.isSmall && it in visitedSmall) 0 else { if (it.isSmall) visitedSmall.add(it) val count = countPathsToEnd(it, visitedSmall, soFar + it) visitedSmall.remove(it) count } } } fun countPathsToEnd2( loc: Cave, visitedSmall: MutableSet<Cave>, visitedTwice: Boolean, soFar: List<Cave> = listOf(loc) ): Int { if (loc.name == "end") { println(soFar) return 1 } val neighbors = neighbors[loc]!! return neighbors.sumOf { if (it.isSmall) { if (it.name == "start") 0 else if (it in visitedSmall) { if (!visitedTwice) { // second time visiting it. only traverse if nothing else has been visited twice countPathsToEnd2(it, visitedSmall, true, soFar + it) } else { 0 } } else { // First time visiting it, no problem. visitedSmall.add(it) val ct = countPathsToEnd2(it, visitedSmall, visitedTwice, soFar + it) visitedSmall.remove(it) ct } } else { countPathsToEnd2(it, visitedSmall, visitedTwice, soFar + it) } } } } data class Cave(val name: String) { val isSmall: Boolean = name.none { it.isUpperCase() } override fun toString(): String { return name } } data class Edge(val endPoints: Pair<Cave, Cave>) }
0
Kotlin
0
0
0c92a62ba324aaa1f21d70b0f9f5d1a2c52e6868
2,766
AdventOfCode-Kotlin
Apache License 2.0
src/day2.kt
SerggioC
573,171,085
false
{"Kotlin": 8824}
fun main() { // A, X -> rock = 1 // B, Y -> paper = 2 // C, Z -> scissors = 3 val input: List<String> = readInput("day2") var total = 0 input.forEach { val game = it.split(" ") val player2 = game[0] when (game[1]) { "X" -> total += getGameScoreForX(player2) "Y" -> total += getGameScoreForY(player2) "Z" -> total += getGameScoreForZ(player2) } } println("total score of games = $total") // part 2 // X loose // y draw // z win total = 0 input.forEach { val game = it.split(" ") val player2 = game[0] when (game[1]) { "X" -> total += getScoreToLoose(player2) "Y" -> total += getScoreToDraw(player2) + 3 "Z" -> total += getScoreToWin(player2) + 6 } } println("total score of game 2 = $total") } fun getGameScoreForX(player2: String): Int { val score = when (player2) { "A" -> 3 "B" -> 0 "C" -> 6 else -> 0 } return score + 1 } fun getGameScoreForY(player2: String): Int { val score = when (player2) { "A" -> 6 "B" -> 3 "C" -> 0 else -> 0 } return score + 2 } fun getGameScoreForZ(player2: String): Int { val score = when (player2) { "A" -> 0 "B" -> 6 "C" -> 3 else -> 0 } return score + 3 } fun getScoreOfPlay(play: String): Int { if (play == "X") return 1 if (play == "Y") return 2 if (play == "Z") return 3 return 0 } fun getScoreToWin(player2: String): Int { if (player2 == "A") return getScoreOfPlay("Y") if (player2 == "B") return getScoreOfPlay("Z") if (player2 == "C") return getScoreOfPlay("X") return 0 } fun getScoreToDraw(player2: String): Int { if (player2 == "A") return getScoreOfPlay("X") if (player2 == "B") return getScoreOfPlay("Y") if (player2 == "C") return getScoreOfPlay("Z") return 0 } fun getScoreToLoose(player2: String): Int { if (player2 == "A") return getScoreOfPlay("Z") if (player2 == "B") return getScoreOfPlay("X") if (player2 == "C") return getScoreOfPlay("Y") return 0 }
0
Kotlin
0
0
d56fb119196e2617868c248ae48dcde315e5a0b3
2,216
aoc-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2019/Day10.kt
tginsberg
222,116,116
false
null
/* * Copyright (c) 2019 by <NAME> */ /** * Advent of Code 2019, Day 10 - Monitoring Station * Problem Description: http://adventofcode.com/2019/day/10 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day10/ */ package com.ginsberg.advent2019 class Day10(input: List<String>) { private val asteroids: List<Point2D> = parseInput(input) fun solvePart1(): Int = asteroids.map { it.countTargets() }.max()!! fun solvePart2(): Int = targetingOrder(asteroids.maxBy { it.countTargets() }!!).drop(199).first().run { (x * 100) + y } private fun Point2D.countTargets(): Int = asteroids.filterNot { it == this }.map { this.angleTo(it) }.distinct().size private fun parseInput(input: List<String>): List<Point2D> = input.withIndex().flatMap { (y, row) -> row.withIndex().filter { it.value == '#' }.map { Point2D(it.index, y) } } private fun targetingOrder(base: Point2D): List<Point2D> = asteroids .filterNot { it == base } .groupBy { base.angleTo(it) } .mapValues { it.value.sortedBy { target -> base.distanceTo(target) } } .toSortedMap() .values .flattenRoundRobin() }
0
Kotlin
2
23
a83e2ecdb6057af509d1704ebd9f86a8e4206a55
1,262
advent-2019-kotlin
Apache License 2.0
src/main/kotlin/advent/week1/Dijkstra.kt
reitzig
159,310,794
false
null
package advent.week1 import java.util.* /** * Implements a simple form of Dijkstra's algorithm. */ object Dijkstra : ShortestPathSolver { override fun shortestPath(maze: Labyrinth, source: Node, target: Node): List<Node> { require(maze.contains(source) && maze.contains(target)) // Set up auxiliary data structures val distances = HashMap<Node, Double>() val predecessors = Array(maze.rows) { Array<Node?>(maze.columns) { null } } // Plain queue, handles priority updates naively. Switch implementation if need be. val queue = PriorityQueue<Node>(kotlin.Comparator { u, v -> val distU = distances[u] ?: Double.MAX_VALUE val distV = distances[v] ?: Double.MAX_VALUE return@Comparator distU.compareTo(distV) }) /** * Utilize that node `v` can be reached source `source` via a path * through `via` of length `d`. */ fun relax(v: Node, d: Double, via: Node? = null) { assert(v == source || via != null) if (d < distances.getOrDefault(v, Double.MIN_VALUE)) { // the new path is better¹ if (queue.remove(v)) { // we haven't reached `v` yet² distances[v] = d queue.add(v) predecessors[v.row][v.column] = via } } // 1. Default applies target nodes we have already removed; // never do anything for those! // 2. Technically, the second check is redundant: // if the new distance is smaller, we _can't_ have removed `v` // yet. That's the invariant of Dijkstra's algorithm. } // Initialize with(maze.nodes) { forEach { distances[it] = Double.MAX_VALUE // --> make sure the first path to each node is definitely chosen } queue.addAll(this) } // Dijkstra! relax(source, 0.0) // --> start with `source` while (queue.isNotEmpty()) { val current = queue.poll() if (current == target) { break } maze.neighbours(current).forEach { relax(it, distances[current]!! + maze.cost(current, it), current) } } // Extract path by backtracking from the target node return sequence { var current: Node? = target while (current != null) { yield(current) // new inference! current = predecessors[current.row][current.column] } }.toList().reversed() } }
0
Kotlin
0
0
38911626f62bce3c59abe893afa8f15dc29dcbda
2,693
advent-of-kotlin-2018
MIT License
2019/task_13/src/main/kotlin/task_13/App.kt
romanthekat
52,710,492
false
{"Go": 90415, "Kotlin": 74230, "Python": 57300, "Nim": 22698, "Ruby": 7404, "Rust": 1516, "Crystal": 967}
package task_13 import java.io.File import java.lang.RuntimeException class App { fun solveFirst(input: String): Int { val tiles = HashMap<Point, Tile>() val computer = IntcodeComputer(input) while (!computer.isHalt) { val x = computer.run() val y = computer.run() val tileId = computer.run() tiles[Point(x.toInt(), y.toInt())] = Tile.of(tileId.toInt()) } return tiles.filterValues { it == Tile.BLOCK }.size } //TODO pretty bad code fun solveSecond(input: String): Long { val tiles = HashMap<Point, Tile>() val computer = IntcodeComputer(input) computer.state[0] = 2 //add coins var score = 0L while (!computer.isHalt) { val x = computer.run() val y = computer.run() val tileId = computer.run() if (isScoreOutput(x, y)) { score = tileId } else { tiles[Point(x.toInt(), y.toInt())] = Tile.of(tileId.toInt()) } val (paddleFound, paddlePos) = get(tiles, Tile.HORIZONTAL_PADDLE) val (ballFound, ballPos) = get(tiles, Tile.BALL) if (paddleFound && ballFound) { when { ballPos.x < paddlePos.x -> { setInput(computer, -1) } ballPos.x > paddlePos.x -> { setInput(computer, 1) } else -> { setInput(computer, 0) } } } } return score } private fun setInput(computer: IntcodeComputer, input: Int) { if (computer.inputValues.size < 1) { computer.addInput(input.toLong()) } else { computer.inputValues[0] = input.toLong() } } private fun get(tiles: HashMap<Point, Tile>, tileToFind: Tile): Pair<Boolean, Point> { for ((point, tile) in tiles) { if (tile == tileToFind) { return Pair(true, point) } } return Pair(false, Point(-1, -1)) } private fun printTiles(tiles: HashMap<Point, Tile>) { val minX = tiles.minBy { it.key.x }!!.key.x val maxX = tiles.maxBy { it.key.x }!!.key.x val minY = tiles.minBy { it.key.y }!!.key.y val maxY = tiles.maxBy { it.key.y }!!.key.y for (y in minY..maxY) { for (x in minX..maxX) { val tile = tiles[Point(x, y)] if (tile != null) { print(tile.symbol) } } println() } } private fun isScoreOutput(x: Long, y: Long) = x == -1L && y == 0L } enum class Tile(val symbol: Char) { EMPTY(' '), WALL('#'), BLOCK('█'), HORIZONTAL_PADDLE('P'), BALL('O'); companion object { fun of(id: Int): Tile { return when (id) { 0 -> EMPTY 1 -> WALL 2 -> BLOCK 3 -> HORIZONTAL_PADDLE 4 -> BALL else -> throw RuntimeException("unknown tile id $id") } } } } data class Point(val x: Int, val y: Int) class IntcodeComputer(input: String) { var isHalt = false var state = getStateByInput(input) private var ptr = 0 private var relativeBase = 0 private val extendedMemory = HashMap<Int, Long>() var inputValues = mutableListOf<Long>() private var outputValue = 0L fun addInput(vararg input: Long): IntcodeComputer { input.forEach { inputValues.add(it) } return this } fun run(stopAtOutput: Boolean = true): Long { var ptrInc = 0 while (true) { var finished = false isHalt = false val num = state[ptr] var opcode = num var firstOperandMode = Mode.POSITION var secondOperandMode = Mode.POSITION var thirdOperandMode = Mode.POSITION if (num.specifiesParamMode()) { val parameterModes = num.toString() opcode = parameterModes[parameterModes.length - 1].toString().toLong() firstOperandMode = getOperandMode(parameterModes, parameterModes.length - 3) secondOperandMode = getOperandMode(parameterModes, parameterModes.length - 4) thirdOperandMode = getOperandMode(parameterModes, parameterModes.length - 5) } when (opcode) { 1L -> { ptrInc = opcodeAdd(firstOperandMode, secondOperandMode, thirdOperandMode) } 2L -> { ptrInc = opcodeMult(firstOperandMode, secondOperandMode, thirdOperandMode) } 3L -> { ptrInc = opcodeSaveTo(firstOperandMode, getInput(inputValues)) } 4L -> { val result = opcodeGetFrom(firstOperandMode) outputValue = result.first ptrInc = result.second if (stopAtOutput) finished = true } 5L -> { ptr = opcodeJumpIfTrue(firstOperandMode, secondOperandMode) ptrInc = 0 } 6L -> { ptr = opcodeJumpIfFalse(firstOperandMode, secondOperandMode) ptrInc = 0 } 7L -> { ptrInc = opcodeLessThan(firstOperandMode, secondOperandMode, thirdOperandMode) } 8L -> { ptrInc = opcodeEquals(firstOperandMode, secondOperandMode, thirdOperandMode) } 9L -> { ptrInc = opcodeAdjustRelativeBase(firstOperandMode) } 99L -> { isHalt = true } else -> { println("unknown value of $num") } } ptr += ptrInc if (finished || isHalt) break } return outputValue } private fun getInput(inputValues: MutableList<Long>): Long { val result = inputValues[0] inputValues.removeAt(0) return result } private fun getOperandMode(parameterModes: String, index: Int): Mode { return if (index < 0) { Mode.POSITION } else { Mode.of(parameterModes[index]) } } fun Long.specifiesParamMode(): Boolean { return this > 99 } fun opcodeAdd(firstOperand: Mode, secondOperand: Mode, thirdOperandMode: Mode): Int { val first = get(firstOperand, ptr + 1) val second = get(secondOperand, ptr + 2) val resultPtr = getIndex(thirdOperandMode, ptr + 3) setByIndex(resultPtr, first + second) return 4 } fun opcodeMult(firstOperand: Mode, secondOperand: Mode, thirdOperandMode: Mode): Int { val first = get(firstOperand, ptr + 1) val second = get(secondOperand, ptr + 2) val resultPtr = getIndex(thirdOperandMode, ptr + 3) setByIndex(resultPtr, first * second) return 4 } fun opcodeSaveTo(firstOperand: Mode, input: Long): Int { val resultPtr = getIndex(firstOperand, ptr + 1) setByIndex(resultPtr, input) return 2 } fun opcodeGetFrom(firstOperandMode: Mode): Pair<Long, Int> { val result = get(firstOperandMode, ptr + 1) //getByIndex(relativeBase + getByIndex(index).toInt()) return Pair(result, 2) } fun opcodeJumpIfTrue(firstOperand: Mode, secondOperand: Mode): Int { val first = get(firstOperand, ptr + 1) val second = get(secondOperand, ptr + 2) return if (first != 0L) { second.toInt() } else { ptr + 3 } } fun opcodeJumpIfFalse(firstOperand: Mode, secondOperand: Mode): Int { val first = get(firstOperand, ptr + 1) val second = get(secondOperand, ptr + 2) return if (first == 0L) { second.toInt() } else { ptr + 3 } } fun opcodeLessThan(firstOperand: Mode, secondOperand: Mode, thirdOperandMode: Mode): Int { val first = get(firstOperand, ptr + 1) val second = get(secondOperand, ptr + 2) val resultPtr = getIndex(thirdOperandMode, ptr + 3) setByIndex(resultPtr, if (first < second) 1 else 0) return 4 } fun opcodeEquals(firstOperand: Mode, secondOperand: Mode, thirdOperandMode: Mode): Int { val first = get(firstOperand, ptr + 1) val second = get(secondOperand, ptr + 2) val resultPtr = getIndex(thirdOperandMode, ptr + 3) setByIndex(resultPtr, if (first == second) 1 else 0) return 4 } fun opcodeAdjustRelativeBase(firstOperand: Mode): Int { val first = get(firstOperand, ptr + 1) relativeBase += first.toInt() return 2 } private fun getStateByInput(input: String) = input.split(',').map { it.toLong() }.toMutableList() fun get(operand: Mode, ptr: Int): Long { return when (operand) { Mode.POSITION -> getPositionMode(ptr) Mode.IMMEDIATE -> getImmediateMode(ptr) Mode.RELATIVE -> getRelativeMode(ptr, relativeBase) } } fun getIndex(operand: Mode, ptr: Int): Int { return when (operand) { Mode.POSITION -> getByIndex(ptr).toInt() Mode.RELATIVE -> relativeBase + getByIndex(ptr).toInt() else -> throw RuntimeException("Can't use $operand to get address to write") } } fun getPositionMode(index: Int): Long = getByIndex(getByIndex(index).toInt()) fun getImmediateMode(index: Int): Long = getByIndex(index) fun getRelativeMode(index: Int, relativeBase: Int): Long = getByIndex(relativeBase + getByIndex(index).toInt()) fun getByIndex(index: Int): Long { if (index >= state.size) { return extendedMemory.getOrDefault(index, 0) } return state[index] } fun setByIndex(index: Int, value: Long) { if (index >= state.size) { extendedMemory[index] = value } else { state[index] = value } } enum class Mode { POSITION, IMMEDIATE, RELATIVE; companion object { fun of(value: Char): Mode { return when (value) { '0' -> POSITION '1' -> IMMEDIATE '2' -> RELATIVE else -> throw RuntimeException("Unknown mode value of $value") } } } } } fun main() { val app = App() val input = File("input.txt").readLines()[0] println(app.solveFirst(input)) println(app.solveSecond(input)) }
4
Go
0
0
f410f71c3ff3e1323f29898c1ab39ad6858589bb
11,033
advent_of_code
MIT License
src/main/kotlin/day20/Day20.kt
dustinconrad
572,737,903
false
{"Kotlin": 100547}
package day20 import readResourceAsBufferedReader fun main() { println("part 1: ${part1(readResourceAsBufferedReader("20_1.txt").readLines())}") //println("part 2: ${part2(readResourceAsBufferedReader("20_1.txt").readLines())}") } fun part1(input: List<String>): Int { val nums = input.map { it.toInt() } val encryptedFile = EncryptedFile(nums) val coords = encryptedFile.coordinates() return coords.sum() } fun part2(input: List<String>): Int { TODO() } class EncryptedFile(private val contents: List<Int>) { fun mix(steps: Int = contents.size): List<Int> { var initial = contents for (i in 0 until steps) { initial = step(i, initial) } return initial } fun step(step: Int, state: List<Int>): List<Int> { val selected = contents[step] val index = state.indexOf(selected) var newIndex = indexAfterOffset(index, selected) if (newIndex < index) { newIndex++ } val result = state.toMutableList() if (index != newIndex) { result.removeAt(index) result.add(newIndex, selected) } return result } private fun indexAfterOffset(start: Int, offset: Int): Int { var normalizedOffset = offset % contents.size if (normalizedOffset < 0) { normalizedOffset = contents.size + normalizedOffset - 1 } var newIndex = start + normalizedOffset if (newIndex >= contents.size) { newIndex = newIndex % contents.size } return newIndex } fun coordinates(): List<Int> { val file = mix() val zeroIndex = file.indexOf(0) return listOf(1000, 2000, 3000).map { indexAfterOffset(zeroIndex, it) } .map { file[it] } } }
0
Kotlin
0
0
1dae6d2790d7605ac3643356b207b36a34ad38be
1,828
aoc-2022
Apache License 2.0
src/day05/Day05.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
package day05 import readInput import java.util.regex.Pattern class CargoBay(arrangement: List<String>, newerCrane: Boolean = false) { val stacks = mutableListOf<ArrayDeque<Char>>() init { val it = arrangement.iterator() // Parse initial layout while (it.hasNext()) { val line = it.next().trimEnd() if (line.isEmpty()) break var i = 0 var stackIndex = 1 while (i < line.length) { if (stackIndex > stacks.size) { stacks.add(ArrayDeque()) } if (line[i] == '[') { stacks[stackIndex-1].addFirst(line[i+1]) } i += 4 stackIndex += 1 } } // Parse moves val pattern = Pattern.compile("""\p{Alpha}+ (\d+) \p{Alpha}+ (\d+) \p{Alpha}+ (\d+)""") while (it.hasNext()) { val line = it.next().trimEnd() if (! line.startsWith("move", true)) { break } val matcher = pattern.matcher(line) matcher.find() var count = matcher.group(1).toInt() val fromStack = matcher.group(2).toInt() - 1 val toStack = matcher.group(3).toInt() - 1 if (newerCrane) { val substack = stacks[fromStack].drop(stacks[fromStack].size-count) stacks[toStack].addAll(substack) while(count > 0) { stacks[fromStack].removeLast() count -= 1 } } else { while (count > 0) { stacks[toStack].addLast(stacks[fromStack].last()) stacks[fromStack].removeLast() count -= 1 } } } } } fun main() { fun part1(input: List<String>): String { var result = "" val bay = CargoBay(input) var stack = 0 while (stack < bay.stacks.size) { result += bay.stacks[stack].last() stack += 1 } return result } fun part2(input: List<String>): String { var result = "" val bay = CargoBay(input, true) var stack = 0 while (stack < bay.stacks.size) { result += bay.stacks[stack].last() stack += 1 } return result } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
2,637
AdventOfCode2022
Apache License 2.0
intstar-mcalculus/src/main/kotlin/intstar/mcalculus/Prelude.kt
vikaskushwaha9oct
276,676,290
false
null
package intstar.mcalculus import java.nio.ByteBuffer.wrap import java.util.* import kotlin.math.abs typealias InputStream = java.io.InputStream const val INFINITY = Double.POSITIVE_INFINITY const val NEG_INFINITY = Double.NEGATIVE_INFINITY fun <T> Iterable<T>.sumsToOne(valueFn: (T) -> Double): Boolean { return abs(sumByDouble(valueFn) - 1) < 0.00001 } fun Double.isDefined(): Boolean { return !isNaN() && (-0.0).compareTo(this) != 0 } fun <T> iteratorOf(vararg elements: T): Iterator<T> { return elements.iterator() } sealed class Interval { abstract fun compareStart(other: Interval): Int abstract fun intersectsWith(other: Interval): Boolean abstract fun anchors(): List<Double> } data class OpenInterval(val low: Double, val high: Double) : Interval() { init { require(low.isDefined() && high.isDefined()) { "Low and high should have a defined value" } require(high > low) { "High should be > low for open interval" } } override fun compareStart(other: Interval): Int { return when (other) { is OpenInterval -> low.compareTo(other.low) is PointInterval -> low.compareTo(other.value).let { if (it == 0) 1 else it } } } override fun intersectsWith(other: Interval): Boolean { return when (other) { is OpenInterval -> low >= other.low && low < other.high || other.low >= low && other.low < high is PointInterval -> other.value > low && other.value < high } } override fun anchors(): List<Double> { return listOf(low, high) } } data class PointInterval(val value: Double) : Interval() { init { require(value.isDefined() && value.isFinite()) { "Point interval value should be defined and finite" } } override fun compareStart(other: Interval): Int { return when (other) { is OpenInterval -> value.compareTo(other.low).let { if (it == 0) -1 else it } is PointInterval -> value.compareTo(other.value) } } override fun intersectsWith(other: Interval): Boolean { return when (other) { is OpenInterval -> value > other.low && value < other.high is PointInterval -> value == other.value } } override fun anchors(): List<Double> { return listOf(value) } } fun Iterable<Interval>.isSortedByStart(): Boolean { return zipWithNext { a, b -> a.compareStart(b) <= 0 }.all { it } } fun Iterable<Interval>.isDisjoint(allowConnected: Boolean = true): Boolean { val map = TreeMap<Double, MutableList<Interval>>() for (interval in this) { for (anchor in interval.anchors()) { val closestIntervals = mutableSetOf<Interval>() map.floorEntry(anchor)?.value?.let { closestIntervals.addAll(it) } map.ceilingEntry(anchor)?.value?.let { closestIntervals.addAll(it) } if (closestIntervals.any { interval.intersectsWith(it) }) { return false } } interval.anchors().forEach { map.getOrPut(it, { mutableListOf() }).add(interval) } } return allowConnected || map.values.none { it.size == 3 } } fun Iterable<Interval>.isDisconnected(): Boolean { return isDisjoint(false) } fun <T> Iterable<T>.isSortedByStart(intervalsFn: (T) -> Iterable<Interval>): Boolean { return map { intervalsFn(it).first() }.isSortedByStart() } fun <T> Iterable<T>.isDisjoint(intervalsFn: (T) -> Iterable<Interval>): Boolean { return flatMap { intervalsFn(it) }.isDisjoint() } class ByteString(bytes: ByteArray = EMPTY_BYTE_ARRAY) : Iterable<Byte> { private val bytes = if (bytes.isNotEmpty()) bytes.copyOf() else EMPTY_BYTE_ARRAY fun byteAt(index: Int): Byte { return bytes[index] } fun size(): Int { return bytes.size } fun toByteArray(): ByteArray { return bytes.copyOf() } fun asString(): String { return Charsets.UTF_8.newDecoder().decode(wrap(bytes)).toString() } override fun equals(other: Any?): Boolean { return this === other || (javaClass == other?.javaClass && bytes.contentEquals((other as ByteString).bytes)) } override fun hashCode(): Int { return bytes.contentHashCode() } override fun iterator(): ByteIterator { return bytes.iterator() } override fun toString(): String { return bytes.joinToString(" ") { "%02x".format(it) } } } private val EMPTY_BYTE_ARRAY = ByteArray(0)
0
Kotlin
0
5
27ee78077690f2de1712a2b9f2ca6e4738162b56
4,518
intstar
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MostPoints.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 2140. Solving Questions With Brainpower * @see <a href="https://leetcode.com/problems/solving-questions-with-brainpower/">Source</a> */ fun interface MostPoints { operator fun invoke(questions: Array<IntArray>): Long } class MostPointsDP : MostPoints { override operator fun invoke(questions: Array<IntArray>): Long { val n: Int = questions.size val dp = LongArray(n) dp[n - 1] = questions[n - 1][0].toLong() for (i in n - 2 downTo 0) { dp[i] = questions[i][0].toLong() val skip = questions[i][1] if (i + skip + 1 < n) { dp[i] += dp[i + skip + 1] } dp[i] = max(dp[i], dp[i + 1]) } return dp[0] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,413
kotlab
Apache License 2.0
Day2/src/IntState.kt
gautemo
225,219,298
false
null
import java.io.File fun main(){ val state = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText() val arr = toArr(state) part1(arr) part2(arr) } fun part1(start: List<Int>){ val arr = start.toMutableList() arr[1] = 12 arr[2] = 2 val output = outCode(arr) println("value at position 0 is $output") } fun part2(arr: List<Int>){ val answer = brute(arr) println(answer) } fun brute(start: List<Int>): Int{ val correct = 19690720 for(i in 0..99){ for(j in 0..99){ val arr = start.toMutableList() arr[1] = i arr[2] = j if(outCode(arr) == correct){ return 100 * i + j } } } return -1 } fun outCode(arr: List<Int>) = transform(arr)[0] fun transform(start: List<Int>): List<Int>{ val arr = start.toMutableList() loop@ for(i in arr.indices step 4){ when(arr[i]){ 1 -> arr[arr[i + 3]] = arr[arr[i + 1]] + arr[arr[i + 2]] 2 -> arr[arr[i + 3]] = arr[arr[i + 1]] * arr[arr[i + 2]] 99 -> break@loop else -> println("Should not happen!") } } return arr } fun toArr(line: String) = line.split(',').map { it.trim().toInt() }.toMutableList()
0
Kotlin
0
0
f8ac96e7b8af13202f9233bb5a736d72261c3a3b
1,304
AdventOfCode2019
MIT License
src/Main.kt
Arch-vile
162,448,942
false
null
import solutions.AreaSelection import utils.* fun main2(args: Array<String>) { val solution = deserialize() solution.sortedBy { routeLength(it) }.reversed() .take(50).takeLast(10) .forEachIndexed { index, route -> exportForGpsVizualizerTrack(index.toString(), route.stops) } } fun main(args: Array<String>) { println("Hello, Santa!") val input = readInput("resources/nicelist.txt") val solution = AreaSelection(input, 99.0, 1.20).solve() println("Route length: ${distanceForHumans(routeLength(solution))}") serialize(solution) writeOutput(solution) } fun maini(args: Array<String>) { println("Hello, Santa!") val range = km(1500) val locations = readInput("resources/nicelist.txt") val area = circularArea(locations, SOUTHAFRICA, range).toMutableList() area.addAll(circularArea(locations, WARSAW, km(500))) for(i in 0..100) { val targetFill = 50 + Math.random()*50 val tolerance = 1.0 + Math.random()*0.3 val solution3 = AreaSelection(area, targetFill, tolerance).solve() println("areaBuilding\tSA and Warsaw\t${doubleForHumans(targetFill)}\t${doubleForHumans(tolerance)}\t${area.size}\t" + "${solution3.size}\t${distanceForHumans(routeLength(solution3))}\t${averageCapacityPercent(solution3)}\n") // exportForGpsVizualizer(area) // // exportForGpsVizualizerTrack(solution3) } }
0
Kotlin
0
0
03160a5ea318082a0995b08ba1f70b8101215ed7
1,441
santasLittleHelper
Apache License 2.0
src/Day01.kt
pimts
573,091,164
false
{"Kotlin": 8145}
fun main() { fun part1(input: String): Int { return input.split("\n\n") .maxOf { elf -> elf.lines().sumOf { calories -> calories.toInt() } } } fun part2(input: String): Int { return input.split("\n\n") .map { elf -> elf.lines().sumOf { calories -> calories.toInt() } } .sorted() .takeLast(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInputText("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputText("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc7abb10538bf6ad9950a079bbea315b4fbd011b
812
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2016/2016-17.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2016 import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.component1 import com.github.ferinagy.adventOfCode.component2 import com.github.ferinagy.adventOfCode.md5toBytes import com.github.ferinagy.adventOfCode.searchGraph import com.github.ferinagy.adventOfCode.singleStep fun main() { println("Part1:") println(part1()) println() println("Part2:") println(part2("ihgpwlah")) println(part2("ulqzkmiv")) println(part2(input)) } private fun part1(): String { val start = Coord2D(0, 0) to "" var result = "no way" searchGraph( start = start, isDone = { (position, path) -> val done = position.isVault() if (done) result = path done }, nextSteps = { (position, path) -> openDoors(input, path, position).singleStep() } ) return result } private fun part2(input: String): Int { val start = Coord2D(0, 0) to "" var result = -1 searchGraph( start = start, isDone = { (position, path) -> val done = position.isVault() if (done) result = path.length false }, nextSteps = { (position, path) -> if (position.isVault()) emptySet() else openDoors(input, path, position).singleStep() } ) return result } private fun openDoors(input: String, path: String, position: Coord2D): Set<Pair<Coord2D, String>> { val (b1, b2) = (input + path).md5toBytes() val (u, d) = b1 val (l, r) = b2 val (lp, tp, rp, bp) = position.adjacent(includeDiagonals = false) return buildSet { if (lp.x in 0..3 && lp.y in 0..3 && 10 < l) this += lp to path + "L" if (rp.x in 0..3 && rp.y in 0..3 && 10 < r) this += rp to path + "R" if (tp.x in 0..3 && tp.y in 0..3 && 10 < u) this += tp to path + "U" if (bp.x in 0..3 && bp.y in 0..3 && 10 < d) this += bp to path + "D" } } private fun Coord2D.isVault() = x == 3 && y == 3 private const val input = """udskfozm"""
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,090
advent-of-code
MIT License
src/main/kotlin/com/polydus/aoc18/Day13.kt
Polydus
160,193,832
false
null
package com.polydus.aoc18 class Day13: Day(13){ //https://adventofcode.com/2018/day/13 val height = input.size val width = input.sortedBy { it.length }.last().length val map = Array(height) {CharArray(width){ ' '}} val carts = arrayListOf<Point>() init { var i = 0 input.forEach { val chars = it.toCharArray() //println(chars.size) for(c in 0 until chars.size){ map[i][c] = chars[c] if(chars[c] == '>'){ carts.add(Point(c, i, 1)) map[i][c] = '-' } else if(chars[c] == '<'){ carts.add(Point(c, i, 3)) map[i][c] = '-' } else if(chars[c] == '^'){ carts.add(Point(c, i, 0)) map[i][c] = '|' } else if(chars[c] == 'v'){ carts.add(Point(c, i, 2)) map[i][c] = '|' } } i++ //println(it) } //println("") //print() //partOne() partTwo() } fun partOne(){ var running = true var tick = 0 while (running){ carts.sortWith(compareBy({ it.y }, { it.x })) for(c in carts){ when(c.direction){ 0 -> c.y-- 1 -> c.x++ 2 -> c.y++ 3 -> c.x-- } setDirection(c) for(c2 in carts){ if(c != c2 && c.x == c2.x && c.y == c2.y){ running = false println("Collision at ${c.x},${c.y}! tick: $tick") break } } } tick++ carts.sortWith(compareBy({ it.y }, { it.x })) } for(c in carts.withIndex()){ println("Cart ${c.index} at ${c.value.x}x${c.value.y}y | ${c.value.direction}d") } //print() } fun partTwo(){ var running = true var tick = 0 while (running){ carts.sortWith(compareBy({ it.y }, { it.x })) for(c in carts){ if(c.alive){ when(c.direction){ 0 -> c.y-- 1 -> c.x++ 2 -> c.y++ 3 -> c.x-- } setDirection(c) for(c2 in carts){ if(c2.alive && c != c2 && c.x == c2.x && c.y == c2.y){ //running = false println("Collision at ${c.x},${c.y}! tick: $tick") c.alive = false c2.alive = false //break } } } } tick++ if(carts.filter { it.alive }.size == 1){ val c = carts.filter { it.alive }.first() println("last cart is ${c.x},${c.y}! tick: $tick") break } carts.sortWith(compareBy({ it.y }, { it.x })) } for(c in carts.withIndex()){ //println("Cart ${c.index} at ${c.value.x}x${c.value.y}y | ${c.value.direction}d") } } fun setDirection(c: Point){ when(map[c.y][c.x]){ '\\' -> { when(c.direction){ 0 -> c.direction = 3 1 -> c.direction = 2 2 -> c.direction = 1 3 -> c.direction = 0 } } '/' -> { when(c.direction){ 0 -> c.direction = 1 1 -> c.direction = 0 2 -> c.direction = 3 3 -> c.direction = 2 } } '+' -> { when(c.intersectionCount){ 0 -> { c.direction-- if(c.direction < 0) c.direction = 3 } 1 -> c.direction = c.direction 2 -> { c.direction++ if(c.direction > 3) c.direction = 0 } } c.intersectionCount++ if(c.intersectionCount == 3) c.intersectionCount = 0 } } } fun print(){ println("") for(y in 0 until height){ for(x in 0 until width){ var cart = false for(c in carts){ if(c.x == x && c.y == y){ when(c.direction){ 0 -> print('^') 1 -> print('>') 2 -> print('v') 3 -> print('<') } cart = true break } } if(!cart) print(map[y][x]) } print("\n") } } // 0 //3 1 // 2 class Point(var x: Int, var y: Int, var direction: Int){ var intersectionCount = 0 var alive = true override fun toString(): String { var result = "" if(x < 0){ result += "${x}x" } else { result += " ${x}x" } if(y < 0){ result += " ${y}y" } else { result += " ${y}y" } return result } } }
0
Kotlin
0
0
e510e4a9801c228057cb107e3e7463d4a946bdae
5,786
advent-of-code-2018
MIT License
src/main/kotlin/days/Solution02.kt
Verulean
725,878,707
false
{"Kotlin": 62395}
package days import adventOfCode.InputHandler import adventOfCode.Solution import adventOfCode.util.PairOf import kotlin.math.max object Solution02 : Solution<List<String>>(AOC_YEAR, 2) { enum class Color { RED, GREEN, BLUE } private val colorMap = mapOf("red" to Color.RED, "green" to Color.GREEN, "blue" to Color.BLUE) override fun getInput(handler: InputHandler) = handler.getInput(delimiter = "\n") private fun minimumCubes(game: String): Map<Color, Int> { val minCubes = Color.entries .associateWith { 0 } .toMutableMap() game.substringAfter(':') .split(';', ',') .map { it.trim().split(' ') } .forEach { minCubes.merge(colorMap.getValue(it.last()), it.first().toInt(), ::max) } return minCubes } override fun solve(input: List<String>): PairOf<Int> { var ans1 = 0 var ans2 = 0 input.map(::minimumCubes) .forEachIndexed { index, minCubes -> val (red, green, blue) = Color.entries.map(minCubes::getValue) if (red <= 12 && green <= 13 && blue <= 14) ans1 += index + 1 ans2 += red * green * blue } return ans1 to ans2 } }
0
Kotlin
0
1
99d95ec6810f5a8574afd4df64eee8d6bfe7c78b
1,258
Advent-of-Code-2023
MIT License
difficultycalculator-app/app/src/main/java/com/stehno/difficulty/CombatantStore.kt
cjstehno
143,009,387
false
null
package com.stehno.difficulty class CombatantStore(private val combatants: MutableList<Combatant> = mutableListOf()) { // FIXME: should this be stored in DB? - not really something needed beyond app use so prob not companion object { private val xpForCr = mapOf( Pair("0", 10), Pair("1/8", 25), Pair("1/4", 50), Pair("1/2", 100), Pair("1", 200), Pair("2", 450), Pair("3", 700), Pair("4", 1100), Pair("5", 1800), Pair("6", 2300), Pair("7", 2900), Pair("8", 3900), Pair("9", 5000), Pair("10", 5900), Pair("11", 7200), Pair("12", 8400), Pair("13", 10000), Pair("14", 11500), Pair("15", 11500), Pair("16", 15000), Pair("17", 18000), Pair("18", 20000), Pair("19", 22000), Pair("20", 25000), Pair("21", 33000), Pair("22", 41000), Pair("23", 50000), Pair("24", 62000), Pair("25", 75000), Pair("26", 90000), Pair("27", 105000), Pair("28", 120000), Pair("29", 135000), Pair("30", 155000) ) private var multipliers = mapOf( Pair(1, 1.0), Pair(2, 1.5), Pair(3, 2.0), Pair(4, 2.0), Pair(5, 2.0), Pair(6, 2.0), Pair(7, 2.5), Pair(8, 2.5), Pair(9, 2.5), Pair(10, 2.5), Pair(11, 3.0), Pair(12, 3.0), Pair(13, 3.0), Pair(14, 3.0), Pair(15, 4.0) ) } fun all() = combatants.toList() fun count() = combatants.size fun add(combatant: Combatant) { val index = combatants.indexOfFirst { c -> c.cr == combatant.cr } when { index >= 0 -> combatants[index] = Combatant(combatants[index].cr, combatants[index].count + combatant.count) else -> combatants.add(combatant) } } fun update(combatant: Combatant) { val index = combatants.indexOfFirst { c -> c.cr == combatant.cr } combatants[index] = combatant } fun remove(combatant: Combatant) { combatants.remove(combatant) } private fun calculateEffectiveXp(): Int { var totalXp = 0 combatants.forEach { c -> totalXp += (xpForCr[c.cr]!! * c.count) } val multiplier = multipliers[combatants.sumBy { it.count }] ?: 4.0 return (totalXp * multiplier).toInt() } fun difficulty(level: Int, xp: Int = calculateEffectiveXp()): Difficulty { val diffs = Difficulty.values().toMutableList() diffs.reverse() val dr = diffs.find { d -> d.xps[level - 1] < xp } return when (dr != null) { true -> dr!! else -> Difficulty.EASY } } operator fun get(index: Int) = combatants[index] } enum class Difficulty(val xps: List<Int>) { EASY(listOf(100, 200, 300, 500, 1000, 1200, 1400, 1800, 2200, 2400, 3200, 4000, 4400, 5000, 5600, 6400, 8000, 8400, 9600, 11200, 12000)), MEDIUM(listOf(200, 400, 600, 1000, 2000, 2400, 3000, 3600, 4400, 4800, 6400, 8000, 8800, 10000, 11200, 12800, 15600, 16800, 19600, 22800, 24000)), HARD(listOf(300, 636, 900, 1500, 3000, 3600, 4400, 5600, 6400, 7600, 9600, 12000, 13600, 15200, 17200, 19200, 23600, 25200, 29200, 34400, 36000)), DEADLY(listOf(400, 800, 1600, 2000, 4400, 5600, 6800, 8400, 9600, 11200, 14400, 18000, 20400, 22800, 25600, 28800, 35200, 38000, 43600, 50800, 54000)) }
1
Kotlin
0
1
5bfedc56ad901db11ac77a5a1a45a998ba979668
3,288
dmtools
The Unlicense
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions54.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import com.qiaoyuang.algorithm.round0.BinaryTreeNode fun test54() { printlnResult(testCase1(), 3) printlnResult(testCase1(), 1) printlnResult(testCase1(), 7) printlnResult(testCase1(), 4) } /** * Questions 54: Find the Kth smallest node in a Binary-search tree */ private infix fun <T : Comparable<T>> BinaryTreeNode<T>.findKNode(k: Int): BinaryTreeNode<T> = findKNode(k, 0).first ?: throw IllegalArgumentException("This binary-tree's size smaller than k") private fun <T : Comparable<T>> BinaryTreeNode<T>.findKNode(k: Int, count: Int): Pair<BinaryTreeNode<T>?, Int> { val pair = left?.findKNode(k, count)?.also { pair -> val (node, _) = pair node?.let { return pair } } val newCount = (pair?.second ?: count) + 1 if (k == newCount) return this to newCount return right?.findKNode(k, newCount) ?: (null to newCount) } private fun testCase1(): BinaryTreeNode<Int> = BinaryTreeNode( value = 5, left = BinaryTreeNode( value = 3, left = BinaryTreeNode(value = 2), right = BinaryTreeNode(value = 4), ), right = BinaryTreeNode( value = 7, left = BinaryTreeNode(value = 6), right = BinaryTreeNode(value = 8), ), ) private fun printlnResult(node: BinaryTreeNode<Int>, k: Int) = println("The ${k}th smallest node is: ${node.findKNode(k).value} in binary-search tree: ${node.inOrderList()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,484
Algorithm
Apache License 2.0
src/main/kotlin/days/Day8.kt
MaciejLipinski
317,582,924
true
{"Kotlin": 60261}
package days import days.Operation.ACC import days.Operation.JMP import days.Operation.NOP class Day8 : Day(8) { override fun partOne(): Any { val instructions = inputList.map { Instruction.from(it) } val alreadyVisited = instructions.map { false }.toMutableList() var i = 0 var accumulator = 0 while (i < instructions.size) { if (alreadyVisited[i]) { return accumulator } alreadyVisited[i] = true when (instructions[i].operation) { ACC -> { accumulator += instructions[i].argument i++ } JMP -> i += instructions[i].argument NOP -> i++ } } return -1 } override fun partTwo(): Any { possibleChangedInstructions() .forEach { instructions -> val alreadyVisited = instructions.map { false }.toMutableList() var i = 0 var accumulator = 0 while (i < instructions.size) { if (alreadyVisited[i]) { i = Int.MAX_VALUE continue } alreadyVisited[i] = true when (instructions[i].operation) { ACC -> { accumulator += instructions[i].argument i++ } JMP -> i += instructions[i].argument NOP -> i++ } if (i == instructions.size) { return accumulator } } } return -1 } private fun possibleChangedInstructions(): List<List<Instruction>> { val possibleChangedInstructions = mutableListOf<MutableList<Instruction>>() val actualInstructions = inputList.map { Instruction.from(it) } var j = 0 for (i in actualInstructions.indices) { if (actualInstructions[i].operation in listOf(JMP, NOP)) { possibleChangedInstructions.add(j, actualInstructions.toMutableList()) if (possibleChangedInstructions[j][i].operation == JMP) { possibleChangedInstructions[j][i] = Instruction(NOP, possibleChangedInstructions[j][i].argument) } else { possibleChangedInstructions[j][i] = Instruction(JMP, possibleChangedInstructions[j][i].argument) } j++ } } return possibleChangedInstructions } } data class Instruction(val operation: Operation, val argument: Int) { companion object { fun from(input: String): Instruction { val operation = Operation.valueOf(input.substring(0..2).toUpperCase()) val argument = input.substring(4, input.lastIndex + 1).removePrefix("+").toInt() return Instruction(operation, argument) } } } enum class Operation { ACC, JMP, NOP }
0
Kotlin
0
0
1c3881e602e2f8b11999fa12b82204bc5c7c5b51
3,214
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/ginsberg/advent2018/Day03.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 3 - No Matter How You Slice It * * Problem Description: http://adventofcode.com/2018/day/3 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day3/ */ package com.ginsberg.advent2018 class Day03(rawInput: List<String>) { private val claims = rawInput.map { Claim.parse(it) } fun solvePart1(): Int = claims .flatMap { it.area() } .groupingBy { it } .eachCount() .count { it.value > 1 } fun solvePart2(): Int { val cloth = mutableMapOf<Pair<Int, Int>, Int>() val uncovered = claims.map { it.id }.toMutableSet() claims.forEach { claim -> claim.area().forEach { spot -> val found = cloth.getOrPut(spot) { claim.id } if (found != claim.id) { uncovered.remove(found) uncovered.remove(claim.id) } } } return uncovered.first() } } data class Claim(val id: Int, val left: Int, val top: Int, val width: Int, val height: Int) { fun area(): List<Pair<Int, Int>> = (0 + left until width + left).flatMap { w -> (0 + top until height + top).map { h -> Pair(w, h) } } // This code parses a String into a Claim, using a Regular Expression companion object { private val pattern = """^#(\d+) @ (\d+),(\d+): (\d+)x(\d+)$""".toRegex() fun parse(input: String): Claim = pattern.find(input)?.let { val (id, left, top, w, h) = it.destructured Claim(id.toInt(), left.toInt(), top.toInt(), w.toInt(), h.toInt()) } ?: throw IllegalArgumentException("Cannot parse $input") } }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
1,831
advent-2018-kotlin
MIT License
packages/solutions/src/Day01.kt
ffluk3
576,832,574
false
{"Kotlin": 21246, "Shell": 85}
fun main() { fun getElfCapacities(input: List<String>): List<Int> { var allElfCapacities = mutableListOf<Int>() var currentElfCapacity: Int = 0 input.forEach { if (it.isEmpty()) { allElfCapacities.add(currentElfCapacity) currentElfCapacity = 0 } else { currentElfCapacity += it.toInt() } } allElfCapacities.add(currentElfCapacity) allElfCapacities.sortDescending() return allElfCapacities } fun part1(input: List<String>): Int { val allElfCapacities = getElfCapacities(input) return allElfCapacities[0] } fun part2(input: List<String>): Int { val allElfCapacities = getElfCapacities(input) println(allElfCapacities.subList(0, 3)) return allElfCapacities.subList(0, 3).reduce { s, t -> s + t } } runAdventOfCodeSuite("Day01", ::part1, 24000, ::part2, 45000) }
0
Kotlin
0
0
f9b68a8953a7452d804990e01175665dffc5ab6e
996
advent-of-code-2022
Apache License 2.0
src/main/kotlin/org/example/adventofcode/puzzle/Day01.kt
wcchristian
712,668,434
false
{"Kotlin": 5484}
package org.example.adventofcode.puzzle import org.example.adventofcode.util.FileLoader val numberMap = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9" ) object Day01 { fun part1(filePath: String): Int { val fileLines = FileLoader.loadFromFile<String>(filePath) return fileLines.sumOf { val matchIterator = Regex("(\\d)").findAll(it.lowercase()) (matchIterator.first().groupValues[0] + matchIterator.last().groupValues[0]).toInt() } } // Lessons learned in part 2. I had the solution working for the most part but ended up getting stuck. // Kotlins findAll doesn't handle overlapping tokens like threeight. It finds the three and finds nothing from ight that is left over. // Part 1 was my original solution that I tried to use for part 2 (expanding the regexp pattern to what I have on the firstMatch line below) // Took quite a bit of time to get this figured out, oof. Fun first day. // ¯\_(ツ)_/¯ fun part2(filePath: String): Int { val fileLines = FileLoader.loadFromFile<String>(filePath) return fileLines.sumOf { val firstMatch = Regex("(\\d|one|two|three|four|five|six|seven|eight|nine)").find(it.lowercase())!! val lastMatch = Regex("(\\d|eno|owt|eerht|ruof|evif|xis|neves|thgie|enin)").find(it.lowercase().reversed())!! val firstDigit = if(firstMatch.value.toIntOrNull() == null) numberMap[firstMatch.value] else firstMatch.value val lastDigit = if(lastMatch.value.toIntOrNull() == null) numberMap[lastMatch.value.reversed()] else lastMatch.value (firstDigit + lastDigit).toInt() } } } fun main() { println("Part 1 example solution is: ${Day01.part1("/day01_example.txt")}") println("Part 1 main solution is: ${Day01.part1("/day01.txt")}") println("Part 2 example solution is: ${Day01.part2("/day01p2_example.txt")}") println("Part 2 main solution is: ${Day01.part2("/day01.txt")}") }
0
Kotlin
0
0
8485b440dcd10b0399acbe9d6ae3ee9cf7f4d6ae
2,123
advent-of-code-2023
MIT License
src/main/kotlin/d21/d21.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d21 import readInput import java.lang.IllegalArgumentException import java.lang.IllegalStateException import java.lang.NullPointerException import java.util.Scanner open class Monkey { open fun res(): Long = 0 } val monkeys = mutableMapOf<String, Monkey>() data class MonkeyNumber(val nb: Long) : Monkey() { override fun res(): Long = nb } data class MonkeyMath(val nb1: String, val op: String, val nb2: String) : Monkey() { override fun res(): Long = when (op) { "+" -> monkeys[nb1]!!.res() + monkeys[nb2]!!.res() "*" -> monkeys[nb1]!!.res() * monkeys[nb2]!!.res() "/" -> monkeys[nb1]!!.res() / monkeys[nb2]!!.res() "-" -> monkeys[nb1]!!.res() - monkeys[nb2]!!.res() else -> throw IllegalArgumentException("unknown op $op") } } fun part1(input: List<String>): Long { for (ligne in input) { val scan = Scanner(ligne) scan.useDelimiter("[: ]+") val name = scan.next() if (scan.hasNextLong()) monkeys[name] = MonkeyNumber(scan.nextLong()) else { val name1 = scan.next() val op = scan.next() val name2 = scan.next() monkeys[name] = MonkeyMath(name1, op, name2) } } return monkeys["root"]!!.res() } fun part2(input: List<String>): Long { val unused = part1(input) val root = monkeys["root"] as MonkeyMath val left = monkeys[root.nb1]!! val right = monkeys[root.nb2]!! monkeys.remove("humn") try { val valueLeft = left.res() return findMath(root.nb2, valueLeft) } catch (_: NullPointerException) { val target = monkeys[root.nb2]!!.res() return findMath(root.nb1, target) } } fun findMath(name: String, target: Long): Long { if (name == "humn") return target if (monkeys[name] is MonkeyNumber) { throw IllegalStateException("Oops") } val monkey = monkeys[name] as MonkeyMath val left = monkeys[monkey.nb1] try { if (left == null) throw NullPointerException() val value = left.res() when (monkey.op) { "+" -> return findMath(monkey.nb2, target - value) //target = value + ? "-" -> return findMath(monkey.nb2, value - target) //target = value - ? "*" -> return findMath(monkey.nb2, target / value) //target = value * ? "/" -> return findMath(monkey.nb2, value / target) //target = value / ? else -> throw IllegalArgumentException("unk op ${monkey.op}") } } catch (_: NullPointerException) { val value = monkeys[monkey.nb2]!!.res() when (monkey.op) { "+" -> return findMath(monkey.nb1, target - value) //target = ? + value "-" -> return findMath(monkey.nb1, value + target) //target = ? - value "*" -> return findMath(monkey.nb1, target / value) //target = ? * value "/" -> return findMath(monkey.nb1, value * target) //target = ? / value else -> throw IllegalArgumentException("unk op ${monkey.op}") } } } fun main() { //val input = readInput("d21/test") val input = readInput("d21/input1") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
3,246
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/TrappingRainWater.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.datastructures.Stack fun interface RainWaterStrategy { operator fun invoke(arr: IntArray): Int } class RainWaterStraightForward : RainWaterStrategy { override operator fun invoke(arr: IntArray): Int { return arr.trapRainWater() } private fun IntArray.trapRainWater(): Int { if (this.isEmpty()) return 0 var low = 0 var high = size - 1 var maxLeft = 0 var maxRight = 0 var ans = 0 while (low <= high) { if (this[low] <= this[high]) { if (this[low] >= maxLeft) { maxLeft = this[low] } else { ans += maxLeft - this[low] } low++ } else { if (this[high] >= maxRight) maxRight = this[high] ans += maxRight - this[high] high-- } } return ans } } class RainWaterStack : RainWaterStrategy { override operator fun invoke(arr: IntArray): Int { return arr.trapRainWaterUsingStack() } private fun IntArray.trapRainWaterUsingStack(): Int { var ans = 0 var current = 0 val stack = Stack<Int>() while (current < this.size) { while (stack.isNotEmpty() && this[current] > this[stack.peek()]) { val top = stack.peek() stack.poll() if (stack.isEmpty()) break val distance = current - stack.peek() - 1 val boundedHeight = this[current].coerceAtMost(this[stack.peek()] - this[top]) ans += distance * boundedHeight } stack.push(current++) } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,394
kotlab
Apache License 2.0
net.akehurst.language/agl-processor/src/commonMain/kotlin/collections/binaryHeapFifo.kt
dhakehurst
197,245,665
false
{"Kotlin": 3541898, "ANTLR": 64742, "Rascal": 17698, "Java": 14313, "PEG.js": 6866, "JavaScript": 5287, "BASIC": 22}
/** * Copyright (C) 2021 Dr. <NAME> (http://dr.david.h.akehurst.net) * * 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 net.akehurst.language.agl.collections fun <K : Comparable<K>, V> binaryHeapFifoMin(): BinaryHeapFifo<K, V> = binaryHeapFifo { parent, child -> when { parent < child -> 1 parent > child -> -1 else -> 0 } } fun <K : Comparable<K>, V> binaryHeapFifoMax(): BinaryHeapFifo<K, V> = binaryHeapFifo { parent, child -> when { parent > child -> 1 parent < child -> -1 else -> 0 } } /** * comparator: parent,child -> when { * 1 -> move parent up * -1 -> move child up * 0 -> do nothing * } */ fun <K, V> binaryHeapFifo(comparator: Comparator<K>): BinaryHeapFifo<K, V> = BinaryHeapFifoComparable(comparator) interface BinaryHeapFifo<K, V> : Iterable<V> { val size: Int /** * the root of the tree - the (or one of the) element(s) with the minimum key * null if the BinaryHeap is empty */ val peekRoot: V? /** * the keys of the heap in the order the heap stores them */ val keys: List<K> /** * insert(key,value) */ operator fun set(key: K, value: V) /** * peek(key) * order is not predictable, but faster to return a list than a set */ operator fun get(key: K): List<V> fun isEmpty(): Boolean fun isNotEmpty(): Boolean fun insert(key: K, value: V) fun peek(key: K): V? fun peekAll(key: K): List<V> fun extractRoot(): V? fun clear() } class BinaryHeapFifoComparable<K, V>( val comparator: Comparator<K> //(parent: K, child: K) -> Boolean ) : BinaryHeapFifo<K, V> { private val _elements = mutableMapOf<K, FifoQueue<V>>() private val _keys = mutableListOf<K>() override val size: Int get() = this._elements.values.sumOf { it.size } override val peekRoot: V? get() = when (this._elements.size) { 0 -> null else -> this._elements[this._keys[0]!!]!!.back } override val keys: List<K> get() = _keys override operator fun set(key: K, value: V) = this.insert(key, value) override fun get(key: K): List<V> = this.peekAll(key) override fun isEmpty(): Boolean = 0 == this.size override fun isNotEmpty(): Boolean = 0 != this.size override fun insert(key: K, value: V) { when { this._elements.containsKey(key) -> { this._elements[key]!!.addFront(value) } else -> { this.addElement(key, value) this._keys.add(key) this.upHeap(this._elements.size - 1, key) } } } override fun extractRoot(): V? { return when(this._keys.size) { 0 -> null else -> { val rootKey = this._keys[0] val q = this._elements[rootKey]!! return when { 1 == q.size -> { this._elements.remove(rootKey) //TODO: might be faster not to delete the FifoQueue - just leave it empty? this.swap(0, this._keys.size - 1) this._keys.removeLastOrNull() this.downHeap(0) q.removeBack() } else -> { q.removeBack() } } } } } /* override fun extractRootAndThenInsert(key: K, value: V): V? { return when { 0 == this._keys.size -> { this.addElement(key, value) this._keys.add(key) null } key==this._keys[0] -> { val q = this._elements[key]!! q.addFront(value) q.removeBack() } TODO() else -> { this.addElement(key, value) this._keys.add(key) this.swap(0, this._elements.size - 1) val oldRoot = this._keys.removeLastOrNull() this.downHeap(0) this.removeElement(oldRoot) } } } override fun insertAndThenExtractRoot(key: K, value: V): V { return when { 0 == this._keys.size -> value 0 < this.comparator.compare(key, this._keys[0]) -> value key==this._keys[0] -> { val q = this._elements[key]!! q.addFront(value) q.removeBack() } TODO() else -> { this.addElement(key,value) val oldRoot = this._keys[0] this._keys[0] = key this.downHeap(0) this.removeElement(key) } } } */ override fun peek(key: K): V? = this._elements[key]?.back override fun peekAll(key: K): List<V> = this._elements[key]?.toList() ?: emptyList() override fun clear() { this._elements.clear() } private fun parentIndexOf(childIndex: Int) = (childIndex - 1) / 2 private fun leftChildIndexOf(parentIndex: Int) = (2 * parentIndex) + 1 private fun rightChildIndexOf(parentIndex: Int) = (2 * parentIndex) + 2 private fun addElement(key: K, value: V) { var q = this._elements[key] if (null==q) { q = FifoQueue() this._elements[key] = q } q.addFront(value) } // index - of the element to sort // elementKey - of the element to sort (saves fetching it) // return new index of element private fun upHeap(index: Int, elementKey: K): Int { var elementIndex = index var parentIndex = parentIndexOf(elementIndex) var parentKey = this._keys[parentIndex] while (0 > this.comparator.compare(parentKey, elementKey)) { swap(parentIndex, elementIndex) elementIndex = parentIndex parentIndex = parentIndexOf(elementIndex) parentKey = this._keys[parentIndex] } return elementIndex } // index - of the element to sort // elementKey - of the element to sort (saves fetching it) // return new index of element private fun downHeap(index: Int): Int { val leftChildIndex = leftChildIndexOf(index) val rightChildIndex = rightChildIndexOf(index) var smallest = index if (leftChildIndex < this._elements.size && 0 < this.comparator.compare(this._keys[leftChildIndex], this._keys[smallest])) { smallest = leftChildIndex } if (rightChildIndex < this._elements.size && 0 < this.comparator.compare(this._keys[rightChildIndex], this._keys[smallest])) { smallest = rightChildIndex } return if (smallest != index) { swap(index, smallest) downHeap(smallest) } else { index } } fun swap(i1: Int, i2: Int) { val t = this._keys[i1] this._keys[i1] = this._keys[i2] this._keys[i2] = t } // --- Iterable<V> --- override fun iterator(): Iterator<V> = object : Iterator<V> { private var _sortedQueues = this@BinaryHeapFifoComparable._elements.entries.sortedWith { a, b -> this@BinaryHeapFifoComparable.comparator.compare(b.key, a.key) } private var _sorted = _sortedQueues.flatMap { it.value.toList() } private var _nextIndex = 0 override fun hasNext(): Boolean = _nextIndex < _sorted.size override fun next(): V = _sorted[_nextIndex].also { _nextIndex++ } } override fun toString(): String = when (this.size) { 0 -> "{}" else -> this._keys.map { Pair(it,_elements[it]) }.joinToString(separator = "\n") { it.toString() } } }
3
Kotlin
7
45
177abcb60c51efcfc2432174f5d6620a7db89928
8,338
net.akehurst.language
Apache License 2.0
src/shreckye/coursera/algorithms/Course 3 Programming Assignment #4.kts
ShreckYe
205,871,625
false
{"Kotlin": 72136}
package shreckye.coursera.algorithms import java.io.File import kotlin.math.max import kotlin.random.Random import kotlin.system.measureNanoTime import kotlin.test.assertEquals data class Item(val value: Int, val weight: Int) fun File.readKnapsackData() = bufferedReader().use { val (knapsackSize, numItems) = it.readLine().splitToInts() val items = it.lineSequence().map { val lineInts = it.splitToInts() Item(lineInts[0], lineInts[1]) }.toList() Triple(knapsackSize, numItems, items) } fun knapsackIterativeWith2DimArray(items: List<Item>, n: Int, w: Int): Int { val mvs = Array(n + 1) { IntArray(w + 1) } for (i in 0..n) for (x in 0..w) mvs[i][x] = if (i == 0) 0 else { val iMinus1 = i - 1 val item = items[iMinus1] val xLeft = x - item.weight if (xLeft < 0) mvs[iMinus1][x] else max(mvs[iMinus1][x], mvs[iMinus1][xLeft] + item.value) } return mvs[n][w] } fun knapsackIterativeWithSingleArray(items: List<Item>, n: Int, w: Int): Int { val mvs = IntArray(w + 1) for (i in 0..n) for (x in w downTo 0) mvs[x] = if (i == 0) 0 else { val item = items[i - 1] val xLeft = x - item.weight if (xLeft < 0) mvs[x] else max(mvs[x], mvs[xLeft] + item.value) } return mvs[w] } val UNKNWON = Int.MIN_VALUE fun knapsackRecursive( items: List<Item>, n: Int, w: Int, mvs: SimpleMutableMap<IntPair, Int> ): Int { val nw = n to w var mvwn = mvs[nw] if (mvwn != UNKNWON) return mvwn mvwn = if (n == 0) 0 else { val nMinus1 = n - 1 val item = items[nMinus1] val wLeft = w - item.weight if (wLeft < 0) knapsackRecursive(items, nMinus1, w, mvs) else max(knapsackRecursive(items, nMinus1, w, mvs), knapsackRecursive(items, nMinus1, wLeft, mvs) + item.value) } mvs[nw] = mvwn return mvwn } fun knapsackRecursiveWithHashMapOfArrays(items: List<Item>, n: Int, w: Int): Int { val nSize = n + 1 return knapsackRecursive(items, n, w, object : SimpleMutableMap<IntPair, Int> { val mvs = HashMap<Int, IntArray>() @Suppress("NAME_SHADOWING") override fun get(key: IntPair): Int { val (n, w) = key val mvsw = mvs[w] return if (mvsw != null) mvsw[n] else UNKNWON } @Suppress("NAME_SHADOWING") override fun set(key: IntPair, value: Int) { val (n, w) = key var mvsw = mvs[w] if (mvsw == null) { mvsw = IntArray(nSize) { UNKNWON } mvs[w] = mvsw } mvsw[n] = value } }) } fun knapsackRecursiveWithHashMap(items: List<Item>, n: Int, w: Int): Int = knapsackRecursive(items, n, w, HashMap<IntPair, Int>().asSimpleMutableMap({ (ni, wi) -> ni in 0..n && wi in 0..w }, UNKNWON)) fun knapsackRecursiveWith2DimArray(items: List<Item>, n: Int, w: Int): Int = knapsackRecursive(items, n, w, Array(n + 1) { IntArray(w + 1) { UNKNWON } }.asSimpleMutableMap()) fun knapsackRecursiveOnNWithSingleArray(items: List<Item>, n: Int, w: Int): Int { val mvs = IntArray(w + 1) knapsackRecursiveOnNWithSingleArrayRecursiveProcess(items, n, intArrayOf(w), mvs) return mvs[w] } fun knapsackRecursiveOnNWithSingleArrayRecursiveProcess( items: List<Item>, n: Int, ws: IntArray, mvs: IntArray ) { if (n == 0) { for (w in ws) mvs[w] = 0 return } val (value, weight) = items[n - 1] //ws.assertSortedIncreasingWithNoDuplicates { "n = $n, ws = ${ws.contentToString()}" } knapsackRecursiveOnNWithSingleArrayRecursiveProcess( items, n - 1, mergeSortedDistinct( ws, ws.asSequence().map { it - weight }.filter { it >= 0 }.toList().toIntArray() ), mvs ) for (w in ws.reversed()) { val wLeft = w - weight mvs[w] = if (wLeft < 0) mvs[w] else max(mvs[w], mvs[wLeft] + value) } } data class Evaluation(val algorithmName: String, val result: Int, val nanoTime: Long) fun List<Evaluation>.getSingleResult() = map(Evaluation::result).assertAllEqualsAndGet() val KNAPSACK_ALGORITHMS = listOf( ::knapsackIterativeWith2DimArray, ::knapsackIterativeWithSingleArray, ::knapsackRecursiveWithHashMapOfArrays, ::knapsackRecursiveWithHashMap, ::knapsackRecursiveWith2DimArray, ::knapsackRecursiveOnNWithSingleArray ) fun evaluateKnapsackAlgorithms( items: List<Item>, n: Int, w: Int, knapsackAlgorithms: List<Pair<String, (List<Item>, Int, Int) -> Int>> = KNAPSACK_ALGORITHMS.map { it.name to it } ): List<Evaluation> = knapsackAlgorithms.map { var knapsack: Int = UNKNWON val knapsackTime = measureNanoTime { knapsack = it.second(items, n, w) } Evaluation(it.first, knapsack, knapsackTime) } // Question 1 val question1Filename = args[0] val (question1KnapsackSize, question1NumItems, question1Items) = File(question1Filename).readKnapsackData() val question1Evaluations = evaluateKnapsackAlgorithms(question1Items, question1NumItems, question1KnapsackSize) println(question1Evaluations) println("1. ${question1Evaluations.getSingleResult()}") println() // Question 2 val question2Filename = args[1] val (question2KnapsackSize, question2NumItems, question2Items) = File(question2Filename).readKnapsackData() val question2Evaluations = evaluateKnapsackAlgorithms( question2Items, question2NumItems, question2KnapsackSize, listOf( ::knapsackIterativeWithSingleArray, ::knapsackRecursiveWithHashMapOfArrays, ::knapsackRecursiveOnNWithSingleArray ).map { it.name to it } ) println(question2Evaluations) println("2. ${question2Evaluations.getSingleResult()}") println() // Test cases for (n in 0..16) { val items = List(n) { Item(Random.nextInt(0, 1024), Random.nextInt(0, 1024)) } val w = items.sumBy(Item::weight) / 2 val expected = items.subsets().filter { it.sumBy(Item::weight) <= w }.map { it.sumBy(Item::value) }.max() val evaluations = evaluateKnapsackAlgorithms(items, n, w) println("n = $n, evaluations = $evaluations") for (evaluation in evaluations) assertEquals( expected, evaluation.result, "n = $n, algorithmName = ${evaluation.algorithmName}, knapsackSize = $w, items = $items" ) }
0
Kotlin
1
2
1746af789d016a26f3442f9bf47dc5ab10f49611
6,672
coursera-stanford-algorithms-solutions-kotlin
MIT License
2022/src/main/kotlin/day17.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.Parser import utils.Solution import utils.Vec2i import utils.badInput fun main() { Day17.run() } object Day17 : Solution<String>() { override val name = "day17" override val parser = Parser { it.trim() } private val rocks = listOf( // #### listOf(Vec2i(0, 0), Vec2i(1, 0), Vec2i(2, 0), Vec2i(3, 0)), // .#. // ### // .#. listOf(Vec2i(0, 1), Vec2i(1, 1), Vec2i(2, 1), Vec2i(1, 0), Vec2i(1, 2)), // ..# // ..# // ### listOf(Vec2i(0, 0), Vec2i(1, 0), Vec2i(2, 0), Vec2i(2, 1), Vec2i(2, 2)), // # // # // # // # listOf(Vec2i(0, 0), Vec2i(0, 1), Vec2i(0, 2), Vec2i(0, 3)), // ## // ## listOf(Vec2i(0, 0), Vec2i(0, 1), Vec2i(1, 0), Vec2i(1, 1)), ) @Suppress("unused") private fun render(grid: IntGrid, height: Int, rock: Int, rockPos: Vec2i) { val rockCoords = rocks[rock].map { it + rockPos }.toSet() for (y in height downTo 0) { println(buildString { for (x in 0 until grid.width) { if (grid[x][y] == 1) { append("#") } else if (Vec2i(x, y) in rockCoords) { append("@") } else { append(".") } } }) } } override fun part1(input: String): Long { return solve(input, 2022) } override fun part2(input: String): Long { return solve(input, 1000000000000) } private fun solve(input: String, targetRocks: Long): Long { var repeatsAdded = false var simulatedHeight = 0L // input-specific repeat params, test: var repeatInjectionHeight = 44 var heightPerCycle = 53 var rocksPerCycle = 35 if (input.length > 50) { // not test repeatInjectionHeight = 330 heightPerCycle = 2759 rocksPerCycle = 1740 } val grid = IntGrid(7, 24000, 0).toMutable() var highest = 0 var rock = 0 var rockPos = Vec2i(2, 3) var inputPos = 0 var spawnedRocks = 1L while (spawnedRocks < targetRocks + 1) { // apply input val translate = when (input[inputPos]) { '>' -> Vec2i(1, 0) '<' -> Vec2i(-1, 0) else -> badInput() } inputPos = (inputPos + 1) % input.length if (rocks[rock].map { it + rockPos + translate }.all { it.x in 0..6 && grid[it] == 0 }) { rockPos += translate } val rockPts = rocks[rock].map { it + rockPos } // apply gravity if (rockPts.map { it + Vec2i(0, -1) }.any { it.y < 0 || grid[it] != 0 }) { // solidify, spawn new rockPts.forEach { grid[it] = 1 } highest = maxOf(highest, rockPts.maxOf { it.y } + 1) spawnedRocks++ rock = (rock + 1) % rocks.size rockPos = Vec2i(2, highest + 3) } else { // fall by one rockPos += Vec2i(0, -1) } // pt2 optimization, using hand-calculated repeat values if (!repeatsAdded && highest == repeatInjectionHeight) { // simulate X cycles out of band val cycles = (targetRocks - spawnedRocks) / rocksPerCycle spawnedRocks += cycles * rocksPerCycle simulatedHeight = cycles * heightPerCycle repeatsAdded = true } } return highest + simulatedHeight } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
3,262
aoc_kotlin
MIT License
src/main/kotlin/day09/Code.kt
fcolasuonno
317,324,330
false
null
package day09 import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" val size = if (isDebug()) 5 else 25 System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/main/kotlin/$dir/$name").readLines() val parsed = parse(input) val v1 = part1(parsed, size) part2(parsed, v1) } fun parse(input: List<String>) = input.map { it.toLong() }.requireNoNulls() fun part1(input: List<Long>, size: Int): Long { val res = input.withIndex().filter { (i, _) -> i >= size }.first { (i, num) -> isInvalid(num, input.subList(i - size, i)) }.value println("Part 1 = $res") return res } fun isInvalid(num: Long, subList: List<Long>) = subList.none { firstNum -> subList.filter { i -> i != firstNum }.any { secondNum -> firstNum + secondNum == num } } fun part2(input: List<Long>, v1: Long) { val res = (2..input.size).asSequence() .flatMap { input.windowed(it) } .first { it.sum() == v1 } .let { it.getMin() + it.getMax() } println("Part 2 = $res") } fun <T : Comparable<T>> Iterable<T>.getMin() = requireNotNull(minOrNull()) fun <T : Comparable<T>> Iterable<T>.getMax() = requireNotNull(maxOrNull())
0
Kotlin
0
0
e7408e9d513315ea3b48dbcd31209d3dc068462d
1,276
AOC2020
MIT License
src/aoc2017/kot/Day19.kt
Tandrial
47,354,790
false
null
package aoc2017.kot import java.io.File object Day19 { fun solve(input: List<CharArray>): Pair<String, Int> { var posX = input[0].indexOf('|') var posY = 0 var dx = 0 var dy = 1 var count = 0 val sb = StringBuilder() loop@ while (true) { val currChar = input[posY][posX] when (currChar) { in 'A'..'Z' -> sb.append(currChar) ' ' -> break@loop '+' -> { // We only need to check +-90° turns val (dxnew, dynew) = listOf(Pair(-dy, -dx), Pair(dy, dx)).first { (x, y) -> val (rx, ry) = Pair(posX + x, posY + y) if (ry in (0 until input.size) && rx in (0 until input[ry].size)) { //Make sure we don't run into a different line, y == 0 means we're moving horizontal ==> nextChar == '-' // ----+| Left is correct x == 0 means we're moving vertical ==> nextChar == '|' // || // ^| (y == 0 && input[ry][rx] == '-') || (x == 0 && input[ry][rx] == '|') } else { false } } dx = dxnew; dy = dynew } } posX += dx posY += dy count++ } return Pair(sb.toString(), count) } } fun main(args: Array<String>) { val input = File("./input/2017/Day19_input.txt").readLines().map { it.toCharArray() } val (partOne, partTwo) = Day19.solve(input) println("Part One = $partOne") println("Part Two = $partTwo") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,518
Advent_of_Code
MIT License
src/com/kingsleyadio/adventofcode/y2022/day08/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2022.day08 import com.kingsleyadio.adventofcode.util.readInput fun main() { val grid = buildGrid() part1(grid) part2(grid) } fun part1(grid: List<List<Int>>) { // We could also use a boolean array as a shadow grid and do the counting explicitly val visibleCells = hashSetOf<String>() for (i in 1 until grid.lastIndex) { val row = grid[i] var maxLeft = -1 for (left in row.indices) { if (row[left] > maxLeft) { visibleCells.add("$i-$left") maxLeft = row[left] } } var maxRight = -1 for (right in row.lastIndex downTo 0) { if (row[right] > maxRight) { visibleCells.add("$i-$right") maxRight = row[right] } } } for (i in 1 until grid[0].lastIndex) { var maxTop = -1 for (top in 0..grid.lastIndex) { if (grid[top][i] > maxTop) { visibleCells.add("$top-$i") maxTop = grid[top][i] } } var maxBottom = -1 for (bottom in grid.lastIndex downTo 0) { if (grid[bottom][i] > maxBottom) { visibleCells.add("$bottom-$i") maxBottom = grid[bottom][i] } } } val visibleCount = visibleCells.size + 4 println(visibleCount) } fun part2(grid: List<List<Int>>) { // We could do this more elegantly and with less code using a bruteforce approach // However, this approach is supposed to be slightly more optimal than the bruteforce val lefts = Array(grid.size) { IntArray(grid[0].size) { 0 } } val tops = Array(grid.size) { IntArray(grid[0].size) { 0 } } val rights = Array(grid.size) { IntArray(grid[0].size) { 0 } } val bottoms = Array(grid.size) { IntArray(grid[0].size) { 0 } } for (i in 1 until grid.lastIndex) { val row = grid[i] var maxIndex = 0 for (left in 1 until row.lastIndex) { lefts[i][left] = when { row[left] > row[maxIndex] -> left.also { maxIndex = left } row[left] == row[maxIndex] -> (left - maxIndex).also { maxIndex = left } else -> { var jumpIndex = left - 1 var value = 1 while (row[left] > row[jumpIndex]) { value += lefts[i][jumpIndex] jumpIndex -= lefts[i][jumpIndex] } value } } } maxIndex = row.lastIndex for (right in row.lastIndex - 1 downTo 1) { rights[i][right] = when { row[right] > row[maxIndex] -> (row.lastIndex - right).also { maxIndex = right } row[right] == row[maxIndex] -> (maxIndex - right).also { maxIndex = right } else -> { var jumpIndex = right + 1 var value = 1 while (row[right] > row[jumpIndex]) { value += rights[i][jumpIndex] jumpIndex += rights[i][jumpIndex] } value } } } } for (i in 1 until grid[0].lastIndex) { var maxIndex = 0 for (top in 1 until grid.lastIndex) { tops[top][i] = when { grid[top][i] > grid[maxIndex][i] -> top.also { maxIndex = top } grid[top][i] == grid[maxIndex][i] -> (top - maxIndex).also { maxIndex = top } else -> { var jumpIndex = top - 1 var value = 1 while (grid[top][i] > grid[jumpIndex][i]) { value += tops[jumpIndex][i] jumpIndex -= tops[jumpIndex][i] } value } } } maxIndex = grid.lastIndex for (bottom in grid.lastIndex - 1 downTo 1) { bottoms[bottom][i] = when { grid[bottom][i] > grid[maxIndex][i] -> (grid.lastIndex - bottom).also { maxIndex = bottom } grid[bottom][i] == grid[maxIndex][i] -> (maxIndex - bottom).also { maxIndex = bottom } else -> { var jumpIndex = bottom + 1 var value = 1 while (grid[bottom][i] > grid[jumpIndex][i]) { value += bottoms[jumpIndex][i] jumpIndex += bottoms[jumpIndex][i] } value } } } } var result = 0 for (i in grid.indices) { for (j in grid[i].indices) { result = maxOf(result, lefts[i][j] * rights[i][j] * tops[i][j] * bottoms[i][j]) } } println(result) } fun buildGrid(): List<List<Int>> = buildList { readInput(2022, 8).forEachLine { add(it.map(Char::digitToInt)) } }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
5,027
adventofcode
Apache License 2.0
src/Day13.kt
Aldas25
572,846,570
false
{"Kotlin": 106964}
fun main() { open class PacketList() { val list: MutableList<PacketList> = mutableListOf() override fun toString(): String { var res = "[" for (p in list) res += "$p," res += "]" return res } override fun equals(other: Any?): Boolean{ if (this === other) return true if (other?.javaClass != javaClass) return false other as PacketList return this.list == other.list } } class PacketNumber(val number: Int) : PacketList() { override fun toString(): String { return number.toString() } override fun equals(other: Any?): Boolean{ if (this === other) return true if (other?.javaClass != javaClass) return false other as PacketNumber return this.number == other.number } } fun comparePackets(left: PacketList, right: PacketList): Int { if (left == right) return 0 if (left is PacketNumber && right is PacketNumber) { val numLeft = (left as PacketNumber).number val numRight = (right as PacketNumber).number return if (numLeft < numRight) -1 else if (numLeft == numRight) 0 else 1 } if (left is PacketNumber) { val packet = PacketList() packet.list.add(left) return comparePackets(packet, right) } if (right is PacketNumber) { return comparePackets(right, left) * -1 } // both left and right are packet lists val szLeft = left.list.size val szRight = right.list.size val size = minOf(szLeft, szRight) for (i in 0 until size) { val res = comparePackets(left.list[i], right.list[i]) if (res == 0) continue return res } return if (szLeft < szRight) -1 else if (szLeft == szRight) 0 else 1 } fun part1(pairs: List<Pair<PacketList, PacketList>>): Int { var ans = 0 for (i in pairs.indices) { val pair = pairs[i] val res = comparePackets(pair.first, pair.second) // println(" comparing packets, res: $res") if (res < 1) ans += i+1 } return ans } fun parseLine(line: String): PacketList { if (line[0] == '[') { val packet = PacketList() val inside = line.substring(1, line.length-1) if (inside.isNotEmpty()) { var newLine: String = "" var dep = 0 for (c in inside) { if (c == ',' && dep == 0) { packet.list.add(parseLine(newLine)) newLine = "" continue } if (c == '[') dep++ else if (c == ']') dep-- newLine += c } packet.list.add(parseLine(newLine)) } return packet } return PacketNumber(line.toInt()) } fun part2(packets: MutableList<PacketList>): Int { val divider1 = parseLine("[[2]]") val divider2 = parseLine("[[6]]") packets.add(divider1) packets.add(divider2) for (i in packets.indices) { var ch = i for (j in (i+1) until packets.size) if (comparePackets(packets[j], packets[ch]) == -1) ch = j val tmp = packets[ch] packets[ch] = packets[i] packets[i] = tmp } var ans = 1 for (i in packets.indices) if (packets[i] == divider1 || packets[i] == divider2) ans *= (i+1) return ans } fun parsePair(line1: String, line2: String): Pair<PacketList, PacketList> { return Pair(parseLine(line1), parseLine(line2)) } fun parseInput(input: List<String>): List<Pair<PacketList, PacketList>> { var i = 0 var list: List<Pair<PacketList, PacketList>> = emptyList() while (i < input.size) { list += parsePair(input[i], input[i+1]) i += 3 } return list } fun pairsToList(pairs: List<Pair<PacketList, PacketList>>): List<PacketList> { var list: List<PacketList> = emptyList() for (pair in pairs) { list += pair.first list += pair.second } return list } val filename = // "inputs/day13_sample" "inputs/day13" val input = readInput(filename) val pairs: List<Pair<PacketList, PacketList>> = parseInput(input) val list = pairsToList(pairs) println("Part 1: ${part1(pairs)}") println("Part 2: ${part2(list.toMutableList())}") }
0
Kotlin
0
0
80785e323369b204c1057f49f5162b8017adb55a
4,905
Advent-of-Code-2022
Apache License 2.0
archive/673/solve.kt
daniellionel01
435,306,139
false
null
/* === #673 Beds and Desks - Project Euler === At Euler University, each of the $n$ students (numbered from 1 to $n$) occupies a bed in the dormitory and uses a desk in the classroom. Some of the beds are in private rooms which a student occupies alone, while the others are in double rooms occupied by two students as roommates. Similarly, each desk is either a single desk for the sole use of one student, or a twin desk at which two students sit together as desk partners. We represent the bed and desk sharing arrangements each by a list of pairs of student numbers. For example, with $n=4$, if $(2,3)$ represents the bed pairing and $(1,3)(2,4)$ the desk pairing, then students 2 and 3 are roommates while 1 and 4 have single rooms, and students 1 and 3 are desk partners, as are students 2 and 4. The new chancellor of the university decides to change the organisation of beds and desks: a permutation $\sigma$ of the numbers $1,2,\ldots,n$ will be chosen, and each student $k$ will be given both the bed and the desk formerly occupied by student number $\sigma(k)$. The students agree to this change, under the conditions that: Any two students currently sharing a room will still be roommates. Any two students currently sharing a desk will still be desk partners. In the example above, there are only two ways to satisfy these conditions: either take no action ($\sigma$ is the identity permutation), or reverse the order of the students. With $n=6$, for the bed pairing $(1,2)(3,4)(5,6)$ and the desk pairing $(3,6)(4,5)$, there are 8 permutations which satisfy the conditions. One example is the mapping $(1, 2, 3, 4, 5, 6) \mapsto (1, 2, 5, 6, 3, 4)$. With $n=36$, if we have bed pairing: $(2,13)(4,30)(5,27)(6,16)(10,18)(12,35)(14,19)(15,20)(17,26)(21,32)(22,33)(24,34)(25,28)$ and desk pairing $(1,35)(2,22)(3,36)(4,28)(5,25)(7,18)(9,23)(13,19)(14,33)(15,34)(20,24)(26,29)(27,30)$ then among the $36!$ possible permutations (including the identity permutation), 663552 of them satisfy the conditions stipulated by the students. The downloadable text files beds.txt and desks.txt contain pairings for $n=500$. Each pairing is written on its own line, with the student numbers of the two roommates (or desk partners) separated with a comma. For example, the desk pairing in the $n=4$ example above would be represented in this file format as: 1,3 2,4 With these pairings, find the number of permutations that satisfy the students' conditions. Give your answer modulo $999\,999\,937$. Difficulty rating: 35% */ fun solve(x: Int): Int { return x*2; } fun main() { val a = solve(10); println("solution: $a"); }
0
Kotlin
0
1
1ad6a549a0a420ac04906cfa86d99d8c612056f6
2,631
euler
MIT License
judge/src/main/kotlin/bluejam/hobby/gekitsui/judge/problem/floydalgorithmwarshall/solution.kt
blue-jam
234,080,324
false
null
package bluejam.hobby.gekitsui.judge.problem.floydalgorithmwarshall import bluejam.hobby.gekitsui.judge.tool.JudgeSuite import bluejam.hobby.gekitsui.judge.tool.validator.InStream import bluejam.hobby.gekitsui.judge.tool.validator.InvalidFormatException import org.springframework.stereotype.Component import java.util.* import kotlin.math.min private const val INF = 10000000 private fun warshallFloyd(d: Array<IntArray>) { for (k in d.indices) for (i in d.indices) for (j in d.indices) { d[i][j] = min(d[i][j], d[i][k] + d[k][j]) } } private fun warshallFloydIJK(d: Array<IntArray>) { for (i in d.indices) for (j in d.indices) for (k in d.indices) { d[i][j] = min(d[i][j], d[i][k] + d[k][j]) } } private fun warshallFloydIKJ(d: Array<IntArray>) { for (i in d.indices) for (k in d.indices) for (j in d.indices) { d[i][j] = min(d[i][j], d[i][k] + d[k][j]) } } private fun solve(scanner: Scanner, warshallFloyd: (Array<IntArray>) -> Unit): String { val N = scanner.nextInt() val M = scanner.nextInt() val d = Array(N) { i -> IntArray(N) { j -> if (i == j) 0 else INF } } for (i in 1..M) { val u = scanner.nextInt() val v = scanner.nextInt() val c = scanner.nextInt() d[u][v] = c d[v][u] = c } warshallFloyd(d) val S = scanner.nextInt() val T = scanner.nextInt() val ans = if (d[S][T] == INF) -1 else d[S][T] return "$ans\n" } private fun correctSolution(scanner: Scanner): String = solve(scanner, ::warshallFloyd) private fun wrongSolution1(scanner: Scanner): String = solve(scanner, ::warshallFloydIJK) private fun wrongSolution2(scanner: Scanner): String = solve(scanner, ::warshallFloydIKJ) private const val MAX_N = 10 private const val MIN_C = 1 private const val MAX_C = 100 private fun validate(input: InStream) { val N = input.readInt(2, MAX_N) input.readSpace() val M = input.readInt(1, MAX_N * (MAX_N - 1) / 2) input.readLineFeed() val used = Array(N) { BooleanArray(N) { false } } for (i in 1..M) { val u = input.readInt(0, N - 1) input.readSpace() val v = input.readInt(0, N - 1) input.readSpace() input.readInt(MIN_C, MAX_C) input.readLineFeed() if (u == v) { throw InvalidFormatException("Self loop is not allowed: ($u, $v)") } if (used[u][v]) { throw InvalidFormatException("Duplicated edges: ($u, $v)") } used[u][v] = true used[v][u] = true } input.readInt(0, N - 1) input.readSpace() input.readInt(0, N - 1) input.readLineFeed() input.expectEndOfInput() } @Component class FloydAlgorithmWarshallJudge: JudgeSuite( "floyd_algorithm_warshall", ::correctSolution, listOf(::wrongSolution1, ::wrongSolution2), ::validate )
14
Kotlin
0
0
36b446bbe2ea27bace0cb028ba76ede4fd0df00e
2,886
gekitsui-online-judge
Apache License 2.0
src/main/day6/Day06.kt
Derek52
572,850,008
false
{"Kotlin": 22102}
package main.day6 import main.readInput fun main() { val input = readInput("day6/day6") val firstHalf = false //testAlg(firstHalf) if (firstHalf) { println(part1(input)) } else { println(part2(input)) } } fun part1(input: List<String>) : Int { val message = input[0] for (i in 3 until message.length) { val letters = listOf(message[i], message[i-1], message[i-2], message[i-3]) if (areUnique(letters)) { println("${letters.forEach { it }} are unique") return i+1 } } return -1 } //TODO: Make this more efficient. Making the list on every loop is bad. fun part2(input: List<String>) : Int { val message = input[0] for (i in 13 until message.length) { val letters = mutableListOf<Char>() for (j in i downTo i-13){ letters.add(message[j]) } if (areUnique(letters)) { return i+1 } } return -1 } fun areUnique(letters: List<Char>): Boolean { val hashSet = HashSet<Char>() for (letter in letters) { if (hashSet.contains(letter)) { return false } else { hashSet.add(letter) } } return true } fun testAlg(firstHalf : Boolean) { val input = readInput("day6/day6_test") if (firstHalf) { println(part1(input)) } else { println(part2(input)) } }
0
Kotlin
0
0
c11d16f34589117f290e2b9e85f307665952ea76
1,423
2022AdventOfCodeKotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindKPairs.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.abs /** * 532. K-diff Pairs in an Array */ fun interface FindKPairs { operator fun invoke(nums: IntArray, k: Int): Int } sealed class FindKStrategy { /** * Approach 1: Brute Force */ object BruteForce : FindKStrategy(), FindKPairs { override operator fun invoke(nums: IntArray, k: Int): Int { nums.sort() var result = 0 for (i in nums.indices) { if (i > 0 && nums[i] == nums[i - 1]) continue for (j in i + 1 until nums.size) { if (j > i + 1 && nums[j] == nums[j - 1]) continue if (abs(nums[j] - nums[i]) == k) result++ } } return result } } /** * Approach 2: Two Pointers */ object TwoPointers : FindKStrategy(), FindKPairs { override operator fun invoke(nums: IntArray, k: Int): Int { nums.sort() var left = 0 var right = 1 var result = 0 while (left < nums.size && right < nums.size) { if (left == right || nums[right] - nums[left] < k) { // List item 1 in the text right++ } else if (nums[right] - nums[left] > k) { // List item 2 in the text left++ } else { // List item 3 in the text left++ result++ while (left < nums.size && nums[left] == nums[left - 1]) left++ } } return result } } /** * Approach 3: Hashmap */ object Hashmap : FindKStrategy(), FindKPairs { override operator fun invoke(nums: IntArray, k: Int): Int { var result = 0 val counter = HashMap<Int, Int>() for (n: Int in nums) { counter[n] = counter.getOrDefault(n, 0) + 1 } for (entry: Map.Entry<Int, Int> in counter.entries) { if (k > 0 && counter.containsKey(entry.key + k)) { result++ } else if (k == 0 && entry.value > 1) { result++ } } return result } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,967
kotlab
Apache License 2.0
src/main/kotlin/g2401_2500/s2440_create_components_with_same_value/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2440_create_components_with_same_value // #Hard #Array #Math #Depth_First_Search #Tree #Enumeration // #2023_07_05_Time_751_ms_(100.00%)_Space_60.1_MB_(100.00%) class Solution { private lateinit var nums: IntArray fun componentValue(nums: IntArray, edges: Array<IntArray>): Int { val n = nums.size this.nums = nums val graph: Array<MutableList<Int>> = Array(n) { ArrayList<Int>() } for (e in edges) { graph[e[0]].add(e[1]) graph[e[1]].add(e[0]) } var sum = 0 for (i in nums) { sum += i } for (k in n downTo 1) { if (sum % k != 0) { continue } val ans = helper(graph, 0, -1, sum / k) if (ans == 0) { return k - 1 } } return 0 } private fun helper(graph: Array<MutableList<Int>>, i: Int, prev: Int, target: Int): Int { if (graph[i].size == 1 && graph[i][0] == prev) { if (nums[i] > target) { return -1 } return if (nums[i] == target) { 0 } else nums[i] } var sum = nums[i] for (k in graph[i]) { if (k == prev) { continue } val ans = helper(graph, k, i, target) if (ans == -1) { return -1 } sum += ans } if (sum > target) { return -1 } return if (sum == target) { 0 } else sum } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,618
LeetCode-in-Kotlin
MIT License
src/Day17.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
import kotlin.math.absoluteValue private operator fun Set<Pair<Int, Int>>.times(point: Pair<Int, Int>): Set<Pair<Int, Int>> = map { Pair(it.first + point.first, it.second + point.second) }.toSet() abstract class Shape(var x: Long, var y: Long, val map: Set<Pair<Long, Long>>) { abstract val width: Long abstract fun cells(): Set<Pair<Long, Long>> fun left(): Boolean { x-- if (x < 0L || cells().any { it in map }) { x++ } return true } fun right(): Boolean { x++ if (x + width > 6L || cells().any { it in map }) { x-- } return true } fun down(): Boolean { y-- if (cells().any { it in map }) { y++ return false } return true } } fun Set<Pair<Int, Int>>.norm(): List<Int> = groupBy { it.first } .entries .sortedBy { it.key } .map { pointList -> pointList.value.minBy { point -> point.second } } .let { val to = minOf { stone -> stone.second } it.map { point -> to - point.second } } val shapes = listOf( setOf(Pair(0, 0), Pair(1, 0), Pair(2, 0), Pair(3, 0)), setOf( Pair(1, 0), Pair(0, -1), Pair(1, -1), Pair(2, -1), Pair(1, -2) ), setOf( Pair(0, 0), Pair(1, 0), Pair(2, 0), Pair(2, -1), Pair(2, -2) ), setOf(Pair(0, 0), Pair(0, -1), Pair(0, -2), Pair(0, -3)), setOf(Pair(0, 0), Pair(1, 0), Pair(0, -1), Pair(1, -1)) ) class HorizontalLine(x: Long, y: Long, map: Set<Pair<Long, Long>>) : Shape(x, y, map) { override val width: Long get() = 3 override fun cells(): Set<Pair<Long, Long>> = (0L..3L).map { Pair(x + it, y) }.toSet() } class Plus(x: Long, y: Long, map: Set<Pair<Long, Long>>) : Shape(x, y, map) { override val width: Long get() = 2L override fun cells(): Set<Pair<Long, Long>> = setOf(Pair(x + 1L, y), Pair(x, y + 1L), Pair(x + 1L, y + 1L), Pair(x + 2L, y + 1L), Pair(x + 1L, y + 2L)) } class ReversedL(x: Long, y: Long, map: Set<Pair<Long, Long>>) : Shape(x, y, map) { override val width: Long get() = 2L override fun cells(): Set<Pair<Long, Long>> = setOf(Pair(x, y), Pair(x + 1L, y), Pair(x + 2L, y), Pair(x + 2L, y + 1L), Pair(x + 2L, y + 2L)) } class VerticalLine(x: Long, y: Long, map: Set<Pair<Long, Long>>) : Shape(x, y, map) { override val width: Long get() = 0L override fun cells(): Set<Pair<Long, Long>> = (0L..3L).map { Pair(x, y + it) }.toSet() } class Square(x: Long, y: Long, map: Set<Pair<Long, Long>>) : Shape(x, y, map) { override val width: Long get() = 1L override fun cells(): Set<Pair<Long, Long>> = setOf(Pair(x, y), Pair(x + 1L, y), Pair(x, y + 1L), Pair(x + 1L, y + 1L)) } fun getFigure(index: Long, x: Long, y: Long, map: Set<Pair<Long, Long>>): Shape = when (index % 5) { 0L -> HorizontalLine(x, y, map) 1L -> Plus(x, y, map) 2L -> ReversedL(x, y, map) 3L -> VerticalLine(x, y, map) 4L -> Square(x, y, map) else -> error("Unexpected state") } fun symbolIndex(input: List<String>, index: Long) = index % input[0].length fun printMap(map: Set<Pair<Long, Long>>, maxY: Long) { for (y in maxY downTo 0L) { print('|') for (x in 0L..6L) { print(if (y == 0L) "-" else if (Pair(x, y) in map) "#" else ".") } print('|') println() } } fun main() { fun process(input: List<String>, size: Long): Long { var figures = 0L var symbolIndex = 0L var figureIndex = 0L val map = (0L..6L).map { Pair(it, 0L) }.toMutableSet() var maxY = 4L while (figures != size) { var index = 0L val figure = getFigure(figureIndex++, 2L, maxY, map) var checker = true while (checker) { checker = if (index++ % 2L == 1L) { figure.down() } else { if (input[0][symbolIndex(input, symbolIndex++).toInt()] == '<') figure.left() else figure.right() } } maxY = kotlin.math.max(maxY, figure.cells().maxOf { it.second + 4L }) figure.cells().forEach { map.add(it) } figures++ } return maxY - 4L } fun part1(input: List<String>): Long { return process(input, 2022L) } fun part2(input: List<String>): Long { val toCoordinates: List<Pair<Int, Int>> = input[0].map { if (it == '>') Pair(1, 0) else Pair(-1, 0) } val map: MutableSet<Pair<Int, Int>> = (0..6).map { Pair(it, 0) }.toMutableSet() val up: Pair<Int, Int> = Pair(0, -1) val down: Pair<Int, Int> = Pair(0, 1) var coordinatesCount = 0 var blocks = 0 val stones = 999999999999L val visited: MutableMap<Triple<List<Int>, Int, Int>, Pair<Int, Int>> = mutableMapOf() while (true) { var current = shapes[(blocks++) % shapes.size].map { Pair( it.first + 2, it.second + map.minOf { stone -> stone.second } - 4) }.toSet() do { val currentPhysical = current * toCoordinates[(coordinatesCount++) % toCoordinates.size] if (currentPhysical.all { it.first in (0..6) } && currentPhysical.intersect(map).isEmpty()) { current = currentPhysical } current = current * down } while (current.intersect(map).isEmpty()) map += (current * up) val combination = Triple(map.norm(), blocks % shapes.size, coordinatesCount % toCoordinates.size) if (combination in visited) { val start = visited.getValue(combination) val timed = blocks - 1L - start.first val total = (stones - start.first) / timed val remain = (stones - start.first) - (total * timed) val heightGainedSinceLoop = map.minOf { stone -> stone.second }.absoluteValue - start.second repeat(remain.toInt()) { var cur = shapes[(blocks++) % shapes.size].map { Pair( it.first + 2, it.second + map.minOf { stone -> stone.second } - 4) } .toSet() do { val curShape = cur * toCoordinates[(coordinatesCount++) % toCoordinates.size] if (curShape.all { it.first in (0..6) } && curShape.intersect(map).isEmpty()) { cur = curShape } cur = cur * down } while (cur.intersect(map).isEmpty()) map += (cur * up) } return map.minOf { stone -> stone.second }.absoluteValue + (heightGainedSinceLoop * (total - 1)) } visited[combination] = blocks - 1 to map.minOf { stone -> stone.second }.absoluteValue } } val input = readInput("Day17") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
7,380
Advent-of-code
Apache License 2.0
src/day15/Interval.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day15 data class Interval (val x0: Int, val x1: Int) { fun touches (other: Interval): Boolean { val (y0, y1) = other if (x0 <= y0 && x1 >= y1) { return true } if (x0 in y0 - 1 .. y1 + 1) { return true } if (x1 in y0 - 1 .. y1 + 1) { return true } return false } fun before (other: Interval): Boolean = x1 < other.x0 - 1 fun after (other: Interval): Boolean = x0 > other.x1 + 1 fun intersect (other: Interval): Interval { if (! touches (other)) { throw IllegalStateException () } val (y0, y1) = other return Interval (Math.min (x0, y0), Math.max (x1, y1)) } override fun toString (): String = "[$x0, $x1]" } class Intervals { private val intervals: MutableList<Interval> = mutableListOf () val segments: List<Interval> get () = intervals fun clip (min: Int, max: Int) { var i = 0 while (i < intervals.size) { val el = intervals[i] if (el.x1 < min || el.x0 > max) { intervals.removeAt (i) continue } if (el.x0 < min || el.x1 > max) { intervals[i] = Interval (Math.max (el.x0, min), Math.min (max, el.x1)) } i ++ } return } fun add (other: Interval) { if (intervals.isEmpty ()) { intervals.add (other) } else { var i = 0 var mutated = false outer@ while (i < intervals.size) { val el = intervals[i] if (other.before (el)) { intervals.add (i, other) return } if (el.touches (other)) { intervals[i] = el.intersect (other) while (i != intervals.size - 1 && intervals[i].touches (intervals[i + 1])) { val removed = intervals.removeAt (i + 1) intervals[i] = intervals[i].intersect (removed) } mutated = true break@outer } i ++ } if (! mutated) { intervals.add (other) } } return } override fun toString(): String { val buf = StringBuffer () intervals.forEach { i -> buf.append (i) } return buf.toString () } } fun main (args: Array<String>) { // test Interval val a = Interval (45, 55) val b = Interval (40, 50) val c = Interval (50,60) val d = Interval (40, 60) val e = Interval (10, 40) val f = Interval (60, 100) val g = Interval (43, 44) val h = Interval (56, 57) val compare = { i0: Interval, i1: Interval -> val check = i0.touches (i1) println ("$a and $b ${if (check) "TOUCH" else "DO NOT TOUCH"}") println (" before: ${a.before(b)}") println (" after: ${a.after(b)}") if (check) { println (" -> ${a.intersect(b)}") } } println ("===============") val i = Interval (10, 20) val j = Interval (30, 40) println ("$i after $j: ${i.after(j)}") println ("$i before $j: ${i.before(j)}") println ("$j after $i: ${j.after(i)}") println ("$j before $i: ${j.before(i)}") println ("===============") val list = listOf (a, b, c, d, e, f, g, h) list.forEach { el -> compare (a, el) } // test Intervals val pairs = listOf ( Pair(10, 20), Pair(30, 40), Pair(90, 100), Pair(70, 80), Pair(50, 60), Pair(8,9), Pair (21,22), Pair (48,49), Pair (61, 62), Pair (23, 29), Pair (41, 69), Pair (102, 103), Pair (105, 106), Pair (108, 109), Pair (111, 113), Pair (91, 200) ) val intervals = Intervals () println (intervals) pairs.forEach { pair -> val (x0, x1) = pair val i = Interval (x0, x1) intervals.add (i) println ("\n ADD $i") println (intervals) } intervals.clip (50, 150) println (intervals) return } // EOF
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
4,256
advent_of_code_2022
Apache License 2.0
src/main/kotlin/org/jetbrains/bio/statistics/Constraints.kt
karl-crl
208,228,814
true
{"Kotlin": 1021604}
package org.jetbrains.bio.statistics import com.google.common.primitives.Ints import java.util.* /** * A container for internal parameters used by pairwise comparison models. * * @author <NAME> * @author <NAME> * @since 16/08/14 */ class Constraints ( /** Mapping from (dimension, state) pairs to equivalence classes. */ val constraintMap: Array<IntArray>, /** * Mapping from (dimension, 1D state) to the corresponding * equivalence classes. */ val constraintMap1D: Array<IntArray>) { /** * Number of samples being compared. */ val numDimensions = constraintMap.size /** * Number of equivalence classes. Should be the same as the number of * different elements in [constraintMap]. */ val numClasses: Int /** * Number of [DifferenceType] states used by the model. Should be * a square of [numStates1D]. */ val numStates = constraintMap.first().size /** * Number of one dimensional states used by the model. E.g. for * `MethylationDifference2` the number of 1D states is `2`. */ val numStates1D = constraintMap1D.first().size init { require(constraintMap.isNotEmpty()) { "zero dimensions" } require(constraintMap1D.size == constraintMap.size) { "incompatible dimensions in constraint maps" } // Check that two constraint maps agree on the number of classes? numClasses = Arrays.stream(constraintMap).mapToInt { Ints.max(*it) }.max().asInt + 1 } } /** * A common interface for pairwise comparison enums. * * @author <NAME> * @since 27/08/14 */ interface DifferenceType<out State> { val isDifferent: Boolean fun component(index: Int) = when (index) { 0 -> first() 1 -> second() else -> throw IndexOutOfBoundsException() } fun first(): State fun second(): State }
0
Kotlin
0
0
469bed933860cc34960a61ced4599862acbea9bd
1,958
bioinf-commons
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day3.kt
clechasseur
567,968,171
false
{"Kotlin": 493887}
package io.github.clechasseur.adventofcode.y2022 import io.github.clechasseur.adventofcode.y2022.data.Day3Data object Day3 { private val input = Day3Data.input fun part1(): Int = input.lines().sumOf { it.toRucksack().commonType.priority } fun part2(): Int = input.lines().map { it.toRucksack() }.chunked(3).sumOf { it.commonType.priority } private data class Rucksack(val pouch1: String, val pouch2: String) { val allItems: String get() = pouch1 + pouch2 } private fun String.toRucksack(): Rucksack = Rucksack( substring(0, length / 2), substring(length / 2, length) ) private val Rucksack.commonType: Char get() = pouch1.toList().distinct().single { pouch2.contains(it) } private val List<Rucksack>.commonType: Char get() { require(size == 3) { "Invalid group size" } return this[0].allItems.toList().distinct().single { this[1].allItems.contains(it) && this[2].allItems.contains(it) } } private val Char.priority: Int get() = if (this in 'a'..'z') { this - 'a' + 1 } else { this - 'A' + 27 } }
0
Kotlin
0
0
7ead7db6491d6fba2479cd604f684f0f8c1e450f
1,205
adventofcode2022
MIT License
src/main/kotlin/days/aoc2021/Day18.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2021 import days.Day import kotlin.math.ceil class Day18 : Day(2021, 18) { override fun partOne(): Any { return calculateMagnitudeOfFinalSum(inputList) } override fun partTwo(): Any { return findLargestMagnitudeOfPairs(inputList) } fun findLargestMagnitudeOfPairs(inputList: List<String>): Int { val magnitudes = mutableListOf<Int>() for (i in 0 until inputList.lastIndex) { for (j in i+1..inputList.lastIndex) { magnitudes.add(parseSnailfishNumber(inputList[i]).plus(parseSnailfishNumber(inputList[j])).reduce().magnitude()) magnitudes.add(parseSnailfishNumber(inputList[j]).plus(parseSnailfishNumber(inputList[i])).reduce().magnitude()) } } return magnitudes.maxOf { it } } fun calculateMagnitudeOfFinalSum(inputList: List<String>): Int { return addSnailfishNumbersTogether(inputList).magnitude() } fun addSnailfishNumbersTogether(inputList: List<String>): SnailfishNumber { return inputList.map { line -> parseSnailfishNumber(line) }.reduce { acc, snailfishNumber -> acc.plus(snailfishNumber).reduce() } } fun parseSnailfishNumber(string: String): SnailfishNumber { var depth = 0 var current = string if (current.first() in '0'..'9') { return SnailfishNumber.Regular(current.first() - '0') } // we want to find the comma separating the left from the right of the outermost enclosing // snailfish number while (current.isNotEmpty()) { when (current.first()) { '[' -> { depth++ } ']' -> { depth-- } ',' -> { if (depth == 1) { break } } } current = current.drop(1) } val left = string.substring(1..string.length - current.length) val right = current.drop(1).dropLast(1) return SnailfishNumber.Pair(parseSnailfishNumber(left), parseSnailfishNumber(right)) } open class SnailfishNumber(var parent: Pair? = null) { data class Pair(var left: SnailfishNumber, var right: SnailfishNumber) : SnailfishNumber() { init { left.parent = this right.parent = this } } data class Regular(var value: Int) : SnailfishNumber() fun plus(other: SnailfishNumber): SnailfishNumber { return Pair(this, other) } fun explode(toExplode: SnailfishNumber) { val pair = toExplode as Pair var current: SnailfishNumber? = pair // find first left regular to add this left to while (current?.parent != null) { if (current?.parent?.left != current) { // found it, now we have to find the regular all the way to the right current = current?.parent?.left while (current is Pair && current?.right != null) { current = current.right } if (current != null && current is Regular) { current.value += (pair.left as Regular).value break } } else { current = current?.parent } } // find first right regular to add this right to current = pair while (current?.parent != null) { if (current?.parent?.right != current) { // found it, now we have to find the regular all the way to the left current = current?.parent?.right while (current is Pair && current?.left != null) { current = current.left } if (current != null && current is Regular) { current.value += (pair.right as Regular).value break } } else { current = current?.parent } } // now replace the value val replacement = Regular(0) replacement.parent = toExplode.parent if (toExplode.parent?.left === toExplode) { toExplode.parent?.left = replacement } else { toExplode.parent?.right = replacement } } private fun findFirstPairToExplode(number: SnailfishNumber, depth: Int): SnailfishNumber? { return if (number is Pair) { if (depth == 4) { number } else { findFirstPairToExplode(number.left, depth + 1) ?: findFirstPairToExplode(number.right, depth + 1) } } else { null } } private fun findFirstValueToSplit(number: SnailfishNumber): Regular? { if (number is Pair) { return findFirstValueToSplit(number.left) ?: findFirstValueToSplit(number.right) } else if (number is Regular) { if (number.value > 9) { return number } } return null } private fun split(number: Regular) { val newValue = Pair(Regular(number.value / 2), Regular(ceil(number.value / 2F).toInt())) newValue.parent = number.parent if (number.parent?.left == number) { number.parent?.left = newValue } else { number.parent?.right = newValue } } fun reduce(): SnailfishNumber { run breaker@ { do { run loop@{ findFirstPairToExplode(this, 0)?.let { explode(it) return@loop } findFirstValueToSplit(this)?.let { split(it) return@loop } ?: return@breaker } } while(true) } return this } fun magnitude(): Int { if (this is Pair) { return left.magnitude() * 3 + right.magnitude() * 2 } else if (this is Regular) { return value } throw IllegalStateException() } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
6,713
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/Dec7.kt
karlstjarne
572,529,215
false
{"Kotlin": 45095}
import java.util.* object Dec7 { private const val DISK_SPACE = 70_000_000 private const val REQUIRED_SPACE = 30_000_000 private val fileStructure = hashMapOf<String, Node>() fun a(): Int { setup() // Go through each node, find <= 100000 var totalSum = 0 fileStructure.forEach { val node = it.value if (node.type == Type.DIRECTORY && node.size <= 100_000) { totalSum += node.size } } return totalSum } fun b(): Int { setup() val usedSpace = fileStructure.asIterable().maxBy { it.value.size }.value.size val missingSpace = REQUIRED_SPACE - (DISK_SPACE - usedSpace) return fileStructure.asIterable() .filter { it.value.type == Type.DIRECTORY } .sortedBy { it.value.size } .first { it.value.size >= missingSpace } .value .size } private fun setup() { val input = readInput("dec7") var currentNode = Node(Type.DIRECTORY, "/", 0, "root-root", "") // Build file structure input.forEach { if (it.startsWith("\$ cd ..")) { currentNode = fileStructure[currentNode.parentId]!! } else if (it.startsWith("\$ cd ")) { val name = it.substring(5, it.length) val id = UUID.randomUUID().toString() currentNode = Node( Type.DIRECTORY, name, 0, id, currentNode.id ) fileStructure[id] = currentNode } else if (!it.startsWith("\$") && !it.startsWith("dir")) { val size = it.split(" ")[0].toInt() val name = it.split(" ")[1] val id = UUID.randomUUID().toString() fileStructure[id] = Node(Type.FILE, name, size, id, currentNode.id) currentNode.incSize(size) incrementParentRecursive(currentNode.parentId, size) } } } private fun incrementParentRecursive(parentId: String, size: Int) { if (parentId != "root-root") { val parent: Node = fileStructure[parentId]!! parent.incSize(size) incrementParentRecursive(parent.parentId, size) } } class Node(val type: Type, var name: String, var size: Int, val id: String, val parentId: String) { fun incSize(sizeToAdd: Int) { size += sizeToAdd } } enum class Type { DIRECTORY, FILE } }
0
Kotlin
0
0
9220750bf71f39f693d129d170679f3be4328576
2,639
AoC_2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FrogJump.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Arrays /** * 403. Frog Jump * @see <a href="https://leetcode.com/problems/frog-jump">Source</a> */ fun interface FrogJump { operator fun invoke(stones: IntArray): Boolean } private const val LIMIT = 2000 /** * Approach 1: Top-Down Dynamic Programming */ class FrogJumpTopDownDp : FrogJump { private val mark = HashMap<Int, Int>() private val dp = Array(LIMIT + 1) { IntArray(LIMIT + 1) } override operator fun invoke(stones: IntArray): Boolean { // Mark stones in the map to identify if such stone exists or not. for (i in stones.indices) { mark[stones[i]] = i } // Mark all states as -1 to denote they're not calculated. for (i in 0 until LIMIT) { Arrays.fill(dp[i], -1) } return solve(stones, stones.size, 0, 0) } private fun solve(stones: IntArray, n: Int, index: Int, prevJump: Int): Boolean { // If reached the last stone, return 1. if (index == n - 1) { return true } // If this sub-problem has already been calculated, return it. if (dp[index][prevJump] != -1) { return dp[index][prevJump] == 1 } var ans = false // Iterate over the three possibilities {k - 1, k, k + 1}. for (nextJump in prevJump - 1..prevJump + 1) { if (nextJump > 0 && mark.containsKey(stones[index] + nextJump)) { ans = ans || solve(stones, n, mark[stones[index] + nextJump]!!, nextJump) } } // Store the result to fetch later. dp[index][prevJump] = if (ans) 1 else 0 return ans } } /** * Approach 2: Bottom-up Dynamic Programming */ class FrogJumpBottomUpDp : FrogJump { private val mark = HashMap<Int, Int>() private val dp = Array(LIMIT + 1) { BooleanArray(LIMIT + 1) } override operator fun invoke(stones: IntArray): Boolean { val n = stones.size // Mark stones in the map to identify if such stone exists or not. for (i in 0 until n) { mark[stones[i]] = i } dp[0][0] = true for (index in 0 until n) { for (prevJump in 0..n) { // If stone exists, mark the value with position and jump as 1. if (dp[index][prevJump]) { if (mark.containsKey(stones[index] + prevJump)) { dp[mark[stones[index] + prevJump]!!][prevJump] = true } if (mark.containsKey(stones[index] + prevJump + 1)) { dp[mark[stones[index] + prevJump + 1]!!][prevJump + 1] = true } if (mark.containsKey(stones[index] + prevJump - 1)) { dp[mark[stones[index] + prevJump - 1]!!][prevJump - 1] = true } } } } // If any value with index as n - 1 is true, return true. for (index in 0..n) { if (dp[n - 1][index]) { return true } } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,759
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CreateBinaryTree.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 /** * 2196. Create Binary Tree From Descriptions * @see <a href="https://leetcode.com/problems/create-binary-tree-from-descriptions">Source</a> */ fun interface CreateBinaryTree { operator fun invoke(descriptions: Array<IntArray>): TreeNode? } class CreateBinaryTreeHashMap : CreateBinaryTree { override operator fun invoke(descriptions: Array<IntArray>): TreeNode? { val map = HashMap<Int, TreeNode?>() val children: MutableSet<Int> = HashSet() for (arr in descriptions) { val parent = arr[0] val child = arr[1] val isLeft = arr[2] children.add(child) val node = map.getOrDefault(parent, TreeNode(parent)) if (isLeft == 1) { node?.left = map.getOrDefault(child, TreeNode(child)) map[child] = node?.left } else { node?.right = map.getOrDefault(child, TreeNode(child)) map[child] = node?.right } map[parent] = node } var root = -1 for (arr in descriptions) { if (!children.contains(arr[0])) { root = arr[0] break } } return map.getOrDefault(root, null) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,908
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/Subsets.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.pow /** * 78. Subsets * @see <a href="https://leetcode.com/problems/subsets/">Source</a> */ fun interface Subsets { operator fun invoke(nums: IntArray): List<List<Int>> } /** * Approach 1: Cascading */ class CascadingSubsets : Subsets { override operator fun invoke(nums: IntArray): List<List<Int>> { val output: MutableList<List<Int>> = ArrayList() output.add(ArrayList()) for (num in nums) { val newSubsets: MutableList<List<Int>> = ArrayList() for (curr in output) { newSubsets.add( object : ArrayList<Int>(curr) { init { add(num) } }, ) } for (curr in newSubsets) { output.add(curr) } } return output } } /** * Approach 2: Backtracking */ class BacktrackingSubsets : Subsets { override operator fun invoke(nums: IntArray): List<List<Int>> { val result: MutableList<List<Int>> = ArrayList() backtrack(result, ArrayList(), nums, 0) return result } private fun backtrack(result: MutableList<List<Int>>, tempList: MutableList<Int>, nums: IntArray, start: Int) { if (nums.size == start) { result.add(ArrayList(tempList)) return } tempList.add(nums[start]) backtrack(result, tempList, nums, start + 1) tempList.removeAt(tempList.size - 1) backtrack(result, tempList, nums, start + 1) } } /** * Approach 3: Lexicographic (Binary Sorted) Subsets */ class LexicographicSubsets : Subsets { override operator fun invoke(nums: IntArray): List<List<Int>> { val output: MutableList<List<Int>> = ArrayList() val n: Int = nums.size for (i in 2.0.pow(n.toDouble()).toInt() until 2.0.pow((n + 1).toDouble()).toInt()) { // generate bitmask, from 0..00 to 1..11 val bitmask = Integer.toBinaryString(i).substring(1) // append subset corresponding to that bitmask val curr: MutableList<Int> = ArrayList() for (j in 0 until n) { if (bitmask[j] == '1') curr.add(nums[j]) } output.add(curr) } return output } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,005
kotlab
Apache License 2.0
src/P12HighlyDivisibleTriangularNumber.kt
rhavran
250,959,542
false
null
fun main(args: Array<String>) { println("Res: " + findSolution()) } /** The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? Res:76576500 Solution: σ0(N) https://en.wikipedia.org/wiki/Prime_omega_function */ private fun findSolution(): Long { val min = 10000 // 28 has 5 val nThTriangleNumber = Long.MAX_VALUE for (nTh in min..nThTriangleNumber) { val triangleNumber = nTh.sequenceSumStartingFrom(1) if (triangleNumber % 2 != 0L && triangleNumber % 5 != 0L) { println(triangleNumber) continue } val numberOfDividers = triangleNumber.dividers() if (numberOfDividers >= 500L) { return triangleNumber } } return -1 }
0
Kotlin
0
0
11156745ef0512ab8aee625ac98cb6b7d74c7e92
1,196
ProjectEuler
MIT License
src/main/kotlin/Day09.kt
robfletcher
724,814,488
false
{"Kotlin": 18682}
class Day09 : Puzzle { override fun test() { val input = """ 0 3 6 9 12 15 1 3 6 10 15 21 10 13 16 21 30 45""".trimIndent() assert(part1(input.lineSequence()) == 114) assert(part2(input.lineSequence()) == 2) } override fun part1(input: Sequence<String>) = input.sumOf { line -> line.split(' ').map(String::toInt).findNext() } override fun part2(input: Sequence<String>) = input.sumOf { line -> line.split(' ').map(String::toInt).findPrevious() } private fun Iterable<Int>.findNext(): Int = if (all { it == 0 }) { 0 } else { last() + windowed(2).map { (a, b) -> b - a }.findNext() } private fun Iterable<Int>.findPrevious(): Int = if (all { it == 0 }) { 0 } else { first() - windowed(2).map { (a, b) -> b - a }.findPrevious() } }
0
Kotlin
0
0
cf10b596c00322ea004712e34e6a0793ba1029ed
852
aoc2023
The Unlicense
src/main/kotlin/me/circuitrcay/euler/challenges/twentySixToFifty/Problem31.kt
adamint
134,989,381
false
null
package me.circuitrcay.euler.challenges.twentySixToFifty import me.circuitrcay.euler.Problem class Problem31 : Problem<String>() { override fun calculate(): Any { var sum = 0 (0..200).forEach { one -> (0..100).forEach { two -> (0..40).forEach { five -> (0..20).forEach { ten -> (0..10).forEach { twenty -> (0..4).forEach { fifty -> (0..2).forEach { hundred -> (0..1).forEach { twoHundred -> if (one * 1 + two * 2 + five * 5 + ten * 10 + twenty * 20 + fifty * 50 + hundred * 100 + twoHundred * 200 == 200) sum++ } } } } } } } } return sum } } enum class MonetaryValue(val value: Int) { ONE_P(1), TWO_P(2), FIVE_P(5), TEN_P(10), TWENTY_P(20), FIFTY_P(50), HUNDRED_P(100), TWO_HUNDRED_P(200) }
0
Kotlin
0
0
cebe96422207000718dbee46dce92fb332118665
1,165
project-euler-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinDeletions.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT /** * 1647. Minimum Deletions to Make Character Frequencies Unique * @see <a href="https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique">Source</a> */ fun interface MinDeletions { operator fun invoke(s: String): Int } class MinDeletionsGreedy : MinDeletions { override fun invoke(s: String): Int { val cnt = IntArray(ALPHABET_LETTERS_COUNT) var res = 0 val used: MutableSet<Int> = HashSet() for (element in s) { ++cnt[element - 'a'] } for (i in 0 until ALPHABET_LETTERS_COUNT) { while (cnt[i] > 0 && !used.add(cnt[i])) { --cnt[i] ++res } } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,431
kotlab
Apache License 2.0
src/main/kotlin/com/chimber/debtislav/util/Graph.kt
chimbersaw
441,295,823
false
{"Kotlin": 46382}
package com.chimber.debtislav.util data class Edge<T>(val a: T, val b: T, var weight: Int) class Graph<T>(edgesList: List<Edge<T>>) { val edges: MutableList<Edge<T>> private var start: T? = null init { val edgeMap = HashMap<Pair<T, T>, Int>() for (edge in edgesList) { edgeMap.compute(edge.a to edge.b) { _, v -> edge.weight + (v ?: 0) } } edges = edgeMap.map { Edge(it.key.first, it.key.second, it.value) }.toMutableList() } private fun dfs(v: T, g: Map<T, List<Edge<T>>>, used: MutableMap<T, Int>): MutableList<Edge<T>>? { used[v] = 1 val outEdges = g[v] ?: run { used[v] = 2 return null } for (edge in outEdges) { val x = edge.b if (used[x] == 0) { val cycle = dfs(x, g, used) cycle?.let { if (start == null) return it else if (start == v) start = null it.add(edge) return it } } else if (used[x] == 1) { start = x return mutableListOf(edge) } } used[v] = 2 return null } private fun findCycle(): List<Edge<T>> { val g = mutableMapOf<T, MutableList<Edge<T>>>() for (edge in edges) { if (!g.contains(edge.a)) { g[edge.a] = mutableListOf() } g[edge.a]?.add(edge) } val vertices = edges.map { listOf(it.a, it.b) }.flatten().distinct() val used = vertices.associateWith { 0 }.toMutableMap() start = null for (v in vertices) { if (used[v] == 0) { val cycle = dfs(v, g, used) if (cycle != null) { return cycle.reversed() } } } return emptyList() } private fun reduceCycle(): Boolean { val cycle = findCycle() val minWeight = cycle.minByOrNull { it.weight }?.weight ?: return false val edgesToRemove = mutableListOf<Edge<T>>() for (edge in cycle) { edge.weight -= minWeight if (edge.weight == 0) { edgesToRemove.add(edge) } } edges.removeAll(edgesToRemove) return true } fun reduceAllCycles() { var finished = false while (!finished) { finished = !reduceCycle() } } }
0
Kotlin
0
0
be2459710d4fb05a659be8d0a33388f48a4d97fd
2,512
debtislav
Apache License 2.0
src/Day04.kt
ChristianNavolskyi
573,154,881
false
{"Kotlin": 29804}
class Day04 : Challenge<Int> { override val name: String get() = "Day 04" override fun inputName(): String = "Day04" override fun testInputName(): String = "Day04_test" override fun testResult1(): Int = 2 override fun testResult2(): Int = 4 override fun part1(input: String): Int = input.split("\n").map { ElfPair(it) }.count { it.contained } override fun part2(input: String): Int = input.split("\n").map { ElfPair(it) }.count { it.overlaps } } class ElfPair(private val input: String) { val overlaps: Boolean get() { val bounds = input.bounds() return bounds.first.overlaps(bounds.second) || bounds.second.contains(bounds.first) } val contained: Boolean get() { val bounds = input.bounds() return bounds.first.contains(bounds.second) || bounds.second.contains(bounds.first) } private fun String.bounds(): Pair<List<Int>, List<Int>> { val ranges = split(",") val firstBounds = ranges[0].split("-").map { it.toInt() } val secondBounds = ranges[1].split("-").map { it.toInt() } return Pair(firstBounds, secondBounds) } private fun List<Int>.contains(other: List<Int>) = first() <= other.first() && last() >= other.last() private fun List<Int>.overlaps(other: List<Int>) = first() <= other.first() && other.first() <= last() || first() <= other.last() && other.last() <= last() }
0
Kotlin
0
0
222e25771039bdc5b447bf90583214bf26ced417
1,471
advent-of-code-2022
Apache License 2.0
src/year2022/14/Day14.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2022.`14` import readInput data class Point( val x: Int, val y: Int ) sealed class Cell { abstract val point: Point data class Sand( override val point: Point ) : Cell() data class SandGenerator( override val point: Point ) : Cell() data class Rock( override val point: Point ) : Cell() } fun parseLine(string: String): List<Point> { return string.split(" -> ") .map { it.split(",") } .map { Point(it.first().toInt(), it[1].toInt()) } } private fun createSet(paths: List<List<Point>>, generator: Cell.SandGenerator): Set<Cell> { val mutableSet = mutableSetOf<Cell>() paths.forEach { path -> var initial = path.first() path.drop(1) .forEach { newPoint -> when { initial.x == newPoint.x -> { val initMinY = minOf(initial.y, newPoint.y) val initMaxY = maxOf(initial.y, newPoint.y) (initMinY..initMaxY).forEach { newYPoint -> mutableSet.add(Cell.Rock(initial.copy(y = newYPoint))) } } initial.y == newPoint.y -> { val initMinX = minOf(initial.x, newPoint.x) val initMaxX = maxOf(initial.x, newPoint.x) (initMinX..initMaxX).forEach { newXPoint -> mutableSet.add(Cell.Rock(initial.copy(x = newXPoint))) } } else -> error("!! $initial $newPoint") } initial = newPoint } } mutableSet.add(generator) return mutableSet } private fun Set<Cell>.rect(): Pair<Point, Point> { val minX = minOf { it.point.x } val maxX = maxOf { it.point.x } val minY = minOf { it.point.y } val maxY = maxOf { it.point.y } return Point(minX, minY) to Point(maxX, maxY) } private fun Point.moveDown() = copy(x = x, y = y + 1) private fun Point.moveLeft() = copy(x = x - 1, y = y) private fun Point.moveRight() = copy(x = x + 1, y = y) /** * This could be improved by removing sealed class * (I'm sorry for this, but at least it's not O(N))) */ private fun Set<Cell>.findFor(point: Point): Cell? { val sand = Cell.Sand(point) val rock = Cell.Rock(point) val generator = Cell.SandGenerator(point) return when { contains(sand) -> sand contains(rock) -> rock contains(generator) -> generator else -> null } } private fun Set<Cell>.withDownLine(): Set<Cell> { val (leftTop, rightBottom) = rect() val yDelta = rightBottom.y - leftTop.y val newLeftX = leftTop.x - yDelta val newRightX = rightBottom.x + yDelta val points = (newLeftX..newRightX) .map { Point(it, rightBottom.y + 2) } .map { Cell.Rock(it) } return this + points } private fun Point.pointInRange( leftTop: Point, rightBottom: Point ): Boolean { return (x in leftTop.x..rightBottom.x) && (y in leftTop.y..rightBottom.y) } private fun moveSand( sandPoint: Point, cellSet: MutableSet<Cell>, leftTop: Point, rightBottom: Point ) { var isStill = true var currentPoint = sandPoint while (isStill) { isStill = currentPoint.pointInRange(leftTop, rightBottom) when (cellSet.findFor(currentPoint.moveDown())) { is Cell.Rock, is Cell.Sand -> { val leftPoint = currentPoint.moveLeft() when (cellSet.findFor(leftPoint.moveDown())) { is Cell.Rock, is Cell.Sand -> { val rightPoint = currentPoint.moveRight() when (cellSet.findFor(rightPoint.moveDown())) { is Cell.Rock, is Cell.Sand -> isStill = false is Cell.SandGenerator -> error("!!") null -> currentPoint = rightPoint } } is Cell.SandGenerator -> error("!!") null -> currentPoint = leftPoint.moveDown() } } is Cell.SandGenerator -> error("!!") null -> currentPoint = currentPoint.moveDown() } } if (currentPoint.pointInRange(leftTop, rightBottom)) { cellSet.add(Cell.Sand(currentPoint)) } } fun main() { fun part1(input: List<String>): Int { val sendGeneratorPoint = Point(500, 0) val sendGenerator = Cell.SandGenerator(sendGeneratorPoint) val set = createSet( paths = input.map { parseLine(it) }, generator = sendGenerator ) .toMutableSet() val (leftTop, rightBottom) = set.rect() var currentSetSize: Int do { currentSetSize = set.size moveSand(sendGeneratorPoint, set, leftTop, rightBottom) } while (currentSetSize != set.size) return set.count { it is Cell.Sand } } fun part2(input: List<String>): Int { val sendGeneratorPoint = Point(500, 0) val sendGenerator = Cell.SandGenerator(sendGeneratorPoint) val set = createSet( paths = input.map { parseLine(it) }, generator = sendGenerator ) .withDownLine() .toMutableSet() val (leftTop, rightBottom) = set.rect() do { moveSand(sendGeneratorPoint, set, leftTop, rightBottom) } while (!set.contains(Cell.Sand(sendGeneratorPoint))) return set.count { it is Cell.Sand } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") val part1Test = part1(testInput) val part2Test = part2(testInput) check(part1Test == 24) check(part2Test == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
6,000
KotlinAdventOfCode
Apache License 2.0
codeforces/src/main/kotlin/contest1911/F.kt
austin226
729,634,548
false
{"Kotlin": 23837}
// https://codeforces.com/contest/1911/problem/F private fun String.splitWhitespace() = split("\\s+".toRegex()) private fun <T> List<T>.counts(): Map<T, Int> = this.groupingBy { it }.eachCount() fun idealUniqueWeights(weights: List<Int>): Set<Int> { val uniqueWeights = mutableSetOf<Int>() for (weight in weights.sorted()) { if (weight > 1) { // First try to insert weight-1 if (!uniqueWeights.contains(weight - 1)) { uniqueWeights.add(weight - 1) continue } } // Next try to insert weight if (!uniqueWeights.contains(weight)) { uniqueWeights.add(weight) continue } // Finally try to insert weight+1 if (!uniqueWeights.contains(weight + 1)) { uniqueWeights.add(weight + 1) } } return uniqueWeights } fun main() { // n boxers. n in 1..=150_000 val n = readln().toInt() // weight of each boxer. // n ints, a_i where a_i in 1..150_000 val a = readln().splitWhitespace().map { it.toInt() } println(idealUniqueWeights(a).size) }
0
Kotlin
0
0
4377021827ffcf8e920343adf61a93c88c56d8aa
1,138
codeforces-kt
MIT License
kotlin/src/com/daily/algothrim/leetcode/medium/SortColors.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 75. 颜色分类 * * 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 * 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 */ class SortColors { companion object { @JvmStatic fun main(args: Array<String>) { val nums = intArrayOf(2, 0, 2, 1, 1, 0) SortColors().sortColors(nums) nums.forEach { println(it) } val nums1 = intArrayOf(2, 0, 2, 1, 1, 0) SortColors().sortColors2(nums1) nums1.forEach { println(it) } } } fun sortColors(nums: IntArray) { val bucket = IntArray(3) nums.forEach { bucket[it]++ } var start = 0 bucket.forEachIndexed { index, i -> nums.fill(index, start, start + i) start += i } } fun sortColors2(nums: IntArray) { var p0 = 0 var p1 = 0 for (i in 0 until nums.size) { if (nums[i] == 1) { val temp = nums[i] nums[i] = nums[p1] nums[p1] = temp p1++ } else if (nums[i] == 0) { var temp = nums[i] nums[i] = nums[p0] nums[p0] = temp if (p0 < p1) { temp = nums[i] nums[i] = nums[p1] nums[p1] = temp } p0++ p1++ } } } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,734
daily_algorithm
Apache License 2.0
src/main/kotlin/utils/Collections.kt
Arch-vile
317,641,541
false
null
package utils fun <T> subsets(collection: List<T>): List<List<T>> { val subsets = mutableListOf<List<T>>() val n: Int = collection.size for (i in 0 until (1 shl n)) { val subset = mutableListOf<T>() for (j in 0 until n) { if (i and (1 shl j) > 0) { subset.add(collection[j]) } } subsets.add(subset) } return subsets.filter { it.isNotEmpty() } } fun <T> rotateCW(matrix: List<List<T>>): List<List<T>> { return IntRange(0,matrix[0].size-1) .map {x -> ((matrix.size-1) downTo 0).map { y -> matrix[y][x] } } } // This seems to flip horizontally and then rotate CW 🤷‍♂️ // btw the nested list means that the first nested list is the first row of the matrix fun <T> transpose(matrix: List<List<T>>): List<List<T>> { return IntRange(0,matrix[0].size-1) .map { column -> matrix.map { it[column] } } } fun <T> intersect(data: List<List<T>>): List<T> { return data.reduce { acc, list -> acc.intersect(list).toList() } }
0
Kotlin
0
0
12070ef9156b25f725820fc327c2e768af1167c0
1,035
adventOfCode2020
Apache License 2.0
src/Day01.kt
guilherme
574,434,377
false
{"Kotlin": 7468}
fun main() { fun elfScores(input: List<String>): List<Int> = input .split { it.isBlank() } .map { it.sumOf { it.toInt() } } fun part1(input: List<String>): Int { return elfScores(input).max() } fun part2(input: List<String>): Int { return elfScores(input) .sorted() .takeLast(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) println("check 1 ok") check(part2(testInput) == 45000) println("check 2 ok") val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
3
dfc0cee1d023be895f265623bec130386ed12f05
651
advent-of-code
Apache License 2.0
kotlin/MaxBipartiteMatchingEV.kt
indy256
1,493,359
false
{"Java": 545116, "C++": 266009, "Python": 59511, "Kotlin": 28391, "Rust": 4682, "CMake": 571}
// https://en.wikipedia.org/wiki/Matching_(graph_theory)#In_unweighted_bipartite_graphs in O(V * E) fun maxMatching(graph: Array<out List<Int>>, n2: Int): Int { val n1 = graph.size val vis = BooleanArray(n1) val matching = IntArray(n2) { -1 } val findPath = DeepRecursiveFunction { u1 -> vis[u1] = true for (v in graph[u1]) { val u2 = matching[v] if (u2 == -1 || !vis[u2] && callRecursive(u2) == 1) { matching[v] = u1 return@DeepRecursiveFunction 1 } } 0 } return (0 until n1).sumOf { vis.fill(false); findPath(it) } } // Usage example fun main() { val g = (1..2).map { arrayListOf<Int>() }.toTypedArray() g[0].add(0) g[0].add(1) g[1].add(1) println(2 == maxMatching(g, 2)) }
97
Java
561
1,806
405552617ba1cd4a74010da38470d44f1c2e4ae3
823
codelibrary
The Unlicense
src/org/aoc2021/Day20.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day20 { private const val iterationsPart1 = 2 private const val iterationsPart2 = 50 data class Image( val lit: Set<Pair<Int, Int>>, val outOfBoundsLit: Boolean, ) private fun solve(lines: List<String>, iterations: Int): Int { val (algorithm, image) = parseInput(lines) val processed = (1..iterations).fold(image) { prevImage, _ -> processImage(algorithm, prevImage) } return processed.lit.size } private fun processImage(algorithm: String, image: Image): Image { val newImage = mutableSetOf<Pair<Int, Int>>() val minX = image.lit.minOf { it.first } val maxX = image.lit.maxOf { it.first } val minY = image.lit.minOf { it.second } val maxY = image.lit.maxOf { it.second } for (i in (minX - 1)..(maxX + 1)) { for (j in (minY - 1)..(maxY + 1)) { val algorithmIndex = computeAlgorithmIndex(image, i, j, minX, maxX, minY, maxY) if (algorithm[algorithmIndex] == '#') { newImage.add(i to j) } } } val newOutOfBoundsLit = if (image.outOfBoundsLit) (algorithm.last() == '#') else (algorithm.first() == '#') return Image(newImage.toSet(), newOutOfBoundsLit) } private fun computeAlgorithmIndex(image: Image, i: Int, j: Int, minX: Int, maxX: Int, minY: Int, maxY: Int): Int { var algorithmIndex = 0 for (dx in -1..1) { for (dy in -1..1) { algorithmIndex *= 2 if (image.lit.contains(i + dx to j + dy)) { algorithmIndex++ } else if (i + dx < minX || i + dx > maxX || j + dy < minY || j + dy > maxY) { if (image.outOfBoundsLit) { algorithmIndex++ } } } } return algorithmIndex } private fun parseInput(lines: List<String>): Pair<String, Image> { val algorithm = lines[0] val litPixels = lines.drop(2).flatMapIndexed { i, line -> line.mapIndexed { j, c -> if (c == '#') (i to j) else null }.filterNotNull() }.toSet() return algorithm to Image(litPixels, false) } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input20.txt"), Charsets.UTF_8) val solution1 = solve(lines, iterationsPart1) println(solution1) val solution2 = solve(lines, iterationsPart2) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
2,692
advent-of-code-2021
The Unlicense
src/commonMain/kotlin/com/github/d_costa/acacia/BinaryTree.kt
d-costa
603,519,207
false
null
package com.github.d_costa.acacia data class BNode<T>( val value: T, val left: BNode<T>? = null, val right: BNode<T>? = null ) /** * A Binary Tree * * Supports insertion, deletion, and iteration */ class BinaryTree<T : Comparable<T>>: Iterable<T> { var root: BNode<T>? = null fun insert(value: T) { root = internalInsert(root, value) } fun exists(value: T): Boolean = findNode(root, value) != null fun find(value: T): BNode<T>? = findNode(root, value) fun delete(value: T) { root = deleteNode(root, value) } override fun iterator(): Iterator<T> = BinaryTreeIterator(root) } class BinaryTreeIterator<T : Comparable<T>>(private val bt: BNode<T>?) : Iterator<T> { private val queue = ArrayDeque<BNode<T>>() init { var current = bt while(current != null) { queue.add(current) current = current.left } } override fun hasNext(): Boolean { return queue.isNotEmpty() } override fun next(): T { if (!hasNext()) throw RuntimeException() val current = queue.removeLast() var next = current.right if(next != null) { queue.add(next) next = next.left while(next != null) { queue.add(next) next = next.left } } return current.value } } private fun <T : Comparable<T>> internalInsert(tree: BNode<T>?, value: T): BNode<T> { return if (tree == null) { BNode(value) } else if (tree.value > value) { BNode(tree.value, internalInsert(tree.left, value), tree.right) } else if (tree.value < value) { BNode(tree.value, tree.left, internalInsert(tree.right, value)) } else { BNode(tree.value, tree.left, tree.right) } } private tailrec fun <T : Comparable<T>> findNode(tree: BNode<T>?, value: T): BNode<T>? { if (tree == null) { return null } return if (tree.value > value) { findNode(tree.left, value) } else if (tree.value < value) { findNode(tree.right, value) } else { tree } } private fun <T: Comparable<T>> deleteNode(tree: BNode<T>?, value: T): BNode<T>? { if (tree == null) { return tree } var newValue = tree.value var leftSubtree = tree.left var rightSubtree = tree.right if (tree.value > value) { leftSubtree = deleteNode(tree.left, value) } else if (tree.value < value) { rightSubtree = deleteNode(tree.right, value) } else { // Found it! if (tree.left == null && tree.right == null) return null if (tree.right != null) { newValue = findSmallest(tree.right) rightSubtree = deleteNode(tree.right, newValue) } else if (tree.left != null) { newValue = findLargest(tree.left) leftSubtree = deleteNode(tree.left, newValue) } } return BNode(newValue, leftSubtree, rightSubtree) } private tailrec fun <T: Comparable<T>> findLargest(tree: BNode<T>): T { return if (tree.right != null) { findLargest(tree.right) } else { tree.value } } private tailrec fun <T: Comparable<T>> findSmallest(tree: BNode<T>): T { return if (tree.left != null) { findSmallest(tree.left) } else { tree.value } }
0
Kotlin
0
0
35aa2f394cfdbbb66e9a5055940a6e672b301b73
3,382
acacia
The Unlicense
advent-of-code-2023/src/main/kotlin/Point.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import kotlin.math.abs data class Point(val x: Int, val y: Int) fun <T : Any> Map<Point, T>.lines( invertedY: Boolean = true, prefixFun: (Int) -> String = { "" }, func: Point.(T?) -> String = { "${it ?: " "}" } ): List<String> { val maxX = keys.maxOf { it.x } val minX = keys.minOf { it.x } val maxY = keys.maxOf { it.y } val minY = keys.minOf { it.y } return (minY..maxY) .let { if (invertedY) it.sorted() else it.sortedDescending() } .map { y -> (minX..maxX).joinToString( prefix = prefixFun(y), separator = "", transform = { x -> func(Point(x, y), this[Point(x, y)]) }) } } fun <T : Any> Map<Point, T>.print( invertedY: Boolean = true, prefixFun: (Int) -> String = { "" }, func: Point.(T?) -> String = { "${it ?: " "}" } ) { lines(invertedY, prefixFun, func).print() } fun List<String>.print() { forEach { println(it) } } fun parseMap(mapString: String): Map<Point, Char> { return mapString .lines() .mapIndexed { y, line -> line.mapIndexed { x, c -> Point(x, y) to c } } .flatten() .toMap() } operator fun Point.rangeTo(other: Point): List<Point> = when { x == other.x -> (y..other.y).map { Point(x, it) } y == other.y -> (x..other.x).map { Point(it, y) } else -> error("Cannot go from $this to $other") } fun Point.left(inc: Int = 1) = copy(x = x - inc) fun Point.right(inc: Int = 1) = copy(x = x + inc) fun Point.up(inc: Int = 1) = copy(y = y - inc) fun Point.down(inc: Int = 1) = copy(y = y + inc) operator fun Point.minus(other: Point) = Point(x - other.x, y - other.y) operator fun Point.plus(other: Point) = Point(x + other.x, y + other.y) fun Point.direction() = Point(x = x.compareTo(0), y = y.compareTo(0)) fun Point.manhattan(): Int = abs(x) + abs(y) fun Point.rotateCCW() = Point(x = -y, y = x) fun Point.rotateCW() = Point(x = y, y = -x)
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
1,923
advent-of-code
MIT License
src/main/kotlin/g1001_1100/s1036_escape_a_large_maze/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1001_1100.s1036_escape_a_large_maze // #Hard #Array #Hash_Table #Depth_First_Search #Breadth_First_Search // #2023_05_25_Time_387_ms_(100.00%)_Space_94.1_MB_(100.00%) class Solution { fun isEscapePossible(blocked: Array<IntArray>, source: IntArray, target: IntArray): Boolean { if (blocked.isEmpty()) { return true } val blocks: MutableSet<Int> = HashSet() for (b in blocked) { if (target[0] * 1000000 + target[1] != b[0] * 1000000 + b[1]) { blocks.add(b[0] * 1000000 + b[1]) } } return ( dfs(blocks, source, source[0], source[1], HashSet(), target) && dfs(blocks, target, target[0], target[1], HashSet(), source) ) } private fun dfs( blocks: Set<Int>, start: IntArray, i: Int, j: Int, visited: MutableSet<Int>, target: IntArray ): Boolean { if (i < 0 || j < 0 || i > 999999 || j > 999999 || blocks.contains(i * 1000000 + j) || visited.contains(i * 1000000 + j) ) { return false } if (i == target[0] && j == target[1]) { return true } visited.add(i * 1000000 + j) return if (visited.size > blocks.size * (blocks.size + 1)) { true } else dfs(blocks, start, i + 1, j, visited, target) || dfs(blocks, start, i - 1, j, visited, target) || dfs(blocks, start, i, j + 1, visited, target) || dfs(blocks, start, i, j - 1, visited, target) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,602
LeetCode-in-Kotlin
MIT License
src/Day01.kt
dmstocking
575,012,721
false
{"Kotlin": 40350}
fun main() { fun part1(input: List<String>): Int { val grouped = mutableListOf<MutableList<Int>>() grouped.add(mutableListOf()) input.forEach { if (it.isBlank()) { grouped.add(mutableListOf()) } else { grouped[grouped.size-1].add(it.toInt()) } } return grouped.maxOf { it.sum() } } fun part2(input: List<String>): Int { val grouped = mutableListOf<MutableList<Int>>() grouped.add(mutableListOf()) input.forEach { if (it.isBlank()) { grouped.add(mutableListOf()) } else { grouped[grouped.size-1].add(it.toInt()) } } return grouped.map { it.sum() }.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e49d9247340037e4e70f55b0c201b3a39edd0a0f
1,060
advent-of-code-kotlin-2022
Apache License 2.0
src/Day02.kt
cak
573,455,947
false
{"Kotlin": 8236}
enum class RockPaperScissors(val bonus: Int) { ROCK(1), PAPER(2), SCISSORS(3) } enum class End(val score: Int) { LOSE(0), DRAW(3), WIN(6) } fun main() { fun letterToRPS(item: String): RockPaperScissors? { return when (item) { "A", "X" -> RockPaperScissors.ROCK "B", "Y" -> RockPaperScissors.PAPER "C", "Z" -> RockPaperScissors.SCISSORS else -> null } } fun rpsGame(opponent: RockPaperScissors, you: RockPaperScissors): Int { val bonus = you.bonus val gamePoint = when (opponent to you) { (RockPaperScissors.PAPER to RockPaperScissors.SCISSORS) -> 6 (RockPaperScissors.PAPER to RockPaperScissors.PAPER) -> 3 (RockPaperScissors.PAPER to RockPaperScissors.ROCK) -> 0 (RockPaperScissors.ROCK to RockPaperScissors.PAPER) -> 6 (RockPaperScissors.ROCK to RockPaperScissors.ROCK) -> 3 (RockPaperScissors.ROCK to RockPaperScissors.SCISSORS) -> 0 (RockPaperScissors.SCISSORS to RockPaperScissors.ROCK) -> 6 (RockPaperScissors.SCISSORS to RockPaperScissors.SCISSORS) -> 3 (RockPaperScissors.SCISSORS to RockPaperScissors.PAPER) -> 0 else -> 0 } return bonus + gamePoint } fun letterToEnd(item: String): End? { return when (item) { "X" -> End.LOSE "Y" -> End.DRAW "Z" -> End.WIN else -> null } } fun rpsGameTwo(opponent: RockPaperScissors, end: End): Int { val outcome = end.score val bonus = when (opponent to end) { (RockPaperScissors.PAPER to End.LOSE) -> RockPaperScissors.ROCK.bonus (RockPaperScissors.PAPER to End.DRAW) -> RockPaperScissors.PAPER.bonus (RockPaperScissors.PAPER to End.WIN) -> RockPaperScissors.SCISSORS.bonus (RockPaperScissors.ROCK to End.LOSE) -> RockPaperScissors.SCISSORS.bonus (RockPaperScissors.ROCK to End.DRAW) -> RockPaperScissors.ROCK.bonus (RockPaperScissors.ROCK to End.WIN) -> RockPaperScissors.PAPER.bonus (RockPaperScissors.SCISSORS to End.LOSE) -> RockPaperScissors.PAPER.bonus (RockPaperScissors.SCISSORS to End.DRAW) -> RockPaperScissors.SCISSORS.bonus (RockPaperScissors.SCISSORS to End.WIN) -> RockPaperScissors.ROCK.bonus else -> 0 } return outcome + bonus } fun part1(input: List<String>): Int { val data = input.map { it.split(" ") }.map { Pair(letterToRPS(it.first()), letterToRPS(it.last())) } val total = data.sumOf { if (it.first == null || it.second == null) { 0 } else { rpsGame(it.first!!, it.second!!) } } return total } fun part2(input: List<String>): Int { val data = input.map { it.split(" ") }.map { Pair(letterToRPS(it.first()), letterToEnd(it.last())) } val total = data.sumOf { if (it.first == null || it.second == null) { 0 } else { rpsGameTwo(it.first!!, it.second!!) } } return total } val testInput = getTestInput() check(part1(testInput) == 15) check(part2(testInput) == 12) val input = getInput() println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
cab2dffae8c1b78405ec7d85e328c514a71b21f1
3,432
advent-of-code-2022
Apache License 2.0
Problem Solving/Algorithms/Basic - The Hurdle Race.kt
MechaArms
525,331,223
false
{"Kotlin": 30017}
/* A video player plays a game in which the character competes in a hurdle race. Hurdles are of varying heights, and the characters have a maximum height they can jump. There is a magic potion they can take that will increase their maximum jump height by 1 unit for each dose. How many doses of the potion must the character take to be able to jump all of the hurdles. If the character can already clear all of the hurdles, return 0. Example height = [1,2,3,3,2] k = 1 The character can jump 1 unit high initially and must take 3-1=2 doses of potion to be able to jump all of the hurdles. Function Description Complete the hurdleRace function in the editor below. hurdleRace has the following parameter(s): int k: the height the character can jump naturally int height[n]: the heights of each hurdle Returns int: the minimum number of doses required, always 0 or more Input Format The first line contains two space-separated integers n and k, the number of hurdles and the maximum height the character can jump naturally. The second line contains n space-separated integers height[i] where 0 <= i < n. Sample Input 0 5 4 1 6 3 5 2 Sample Output 0 2 Explanation 0 Dan's character can jump a maximum of k=4 units, but the tallest hurdle has a height of h1=6: To be able to jump all the hurdles, Dan must drink 6-4=2 doses. Sample Input 1 5 7 2 5 4 5 2 Sample Output 1 0 Explanation 1 Dan's character can jump a maximum of k=7 units, which is enough to cross all the hurdles: Because he can already jump all the hurdles, Dan needs to drink 0 doses. */ fun hurdleRace(k: Int, height: Array<Int>): Int { return if(height.max()!!-k < 0) 0 else height.max()!!-k } fun main(args: Array<String>) { val first_multiple_input = readLine()!!.trimEnd().split(" ") val n = first_multiple_input[0].toInt() val k = first_multiple_input[1].toInt() val height = readLine()!!.trimEnd().split(" ").map{ it.toInt() }.toTypedArray() val result = hurdleRace(k, height) println(result) }
0
Kotlin
0
1
eda7f92fca21518f6ee57413138a0dadf023f596
2,017
My-HackerRank-Solutions
MIT License
src/main/kotlin/at/doml/anc/lab1/MutableMatrix.kt
domagojlatecki
124,923,523
false
null
package at.doml.anc.lab1 import java.io.File import java.util.Arrays class MutableMatrix constructor(rows: Int, columns: Int) : Matrix { init { if (rows <= 0 || columns <= 0) { throw IllegalArgumentException("invalid matrix dimensions provided: [$rows, $columns]") } } private val elements: Array<DoubleArray> = Array(rows) { DoubleArray(columns) { 0.0 } } override val rows: Int = this.elements.size override val columns: Int = this.elements[0].size constructor(elements: Array<DoubleArray>) : this(elements.size, elements[0].size) { for (i in elements.indices) { if (elements[i].size != elements[0].size) { throw IllegalArgumentException( "provided array has inconsistent column dimensions;" + " expected dimension: ${elements[0].size}, actual dimension: ${elements[i].size}" + " at row with index: $i" ) } System.arraycopy(elements[i], 0, this.elements[i], 0, elements[0].size) } } override fun copy(): MutableMatrix = MutableMatrix(this.elements) override operator fun get(row: Int, column: Int): Double = this.elements[row][column] override operator fun get(row: Int): DoubleArray = this.elements[row].copyOf() override operator fun set(row: Int, column: Int, value: Double) { this.elements[row][column] = value } override fun newMatrix(rows: Int, columns: Int) = MutableMatrix(rows, columns) override fun toString(): String = this.elements.joinToString( separator = "\n", transform = { row -> row.joinToString( separator = " ", transform = Double::toString ) } ) override fun toPrettyString(): String { val stringMatrix = this.elements.map { row -> row.map { e -> e.toString() } } val longest = stringMatrix.map({ row -> row.map(String::length).max()!! }).max()!! val withPadding = stringMatrix.map { row -> row.map { e -> e.padStart(longest) } } val padding = "".padStart((longest + 1) * this.columns) val builder = StringBuilder("┌ ") .append(padding) .append("┐\n") for (i in 0 until this.rows) { builder.append("│ ") for (j in 0 until this.columns) { builder.append(withPadding[i][j]) builder.append(' ') } builder.append("│\n") } builder.append("└ ") .append(padding) .append('┘') return builder.toString() } override fun toArrayString(): String = this.elements.map { it.joinToString(prefix = "[", postfix = "]", separator = ",") }.joinToString(prefix = "[", postfix = "]", separator = ",") override fun equals(other: Any?): Boolean = when (other) { is Matrix -> this.equals(other) else -> false } override fun hashCode(): Int { var result = Arrays.hashCode(elements) result = 31 * result + rows result = 31 * result + columns return result } companion object { fun fromFile(file: File): MutableMatrix = this.parse(file.readLines()) fun parse(string: String): MutableMatrix = this.parse(string.split("\n")) fun parse(lines: List<String>): MutableMatrix = MutableMatrix( lines.map(String::trim) .filter(String::isNotEmpty) .map({ line -> line.split(Regex("\\s+")) .map(String::toDouble) .toDoubleArray() }).toTypedArray() ) } }
0
Kotlin
0
0
b483dda88bd9f2a6dc9f4928c7aa4e9a217eac8f
3,969
anc-lab
MIT License
solutions/src/solutions/y20/day 24.kt
Kroppeb
225,582,260
false
null
@file:Suppress("PackageDirectoryMismatch") package solutions.y20.d24 import collections.counter import grid.Clock import helpers.Lines import helpers.getLines import helpers.toP val xxxxx = Clock(6, 3); private fun part1(data: Data) { val points = data.map { line -> var i = 0 var p = 0 toP 0 println(line) while (i < line.length) { when (line[i]) { 'e' -> {p = p.east; i++ } 'w' -> {p = p.west; i++ } 's' -> {p = if (line[i+1] == 'e') p.south else p.south.west; i += 2 } 'n' -> {p = if (line[i+1] == 'w') p.north else p.north.east; i += 2 } } println(p) } p }.counter() val pp = points.counts.filter { (_,v) -> v % 2 == 1 } println(points.counts) println(pp.count()) } private fun part2(data: Data) { val points = data.map { line -> var i = 0 var p = 0 toP 0 println(line) while (i < line.length) { when (line[i]) { 'e' -> {p = p.east.east; i++ } 'w' -> {p = p.west.west; i++ } 's' -> {p = if (line[i+1] == 'e') p.south.east else p.south.west; i += 2 } 'n' -> {p = if (line[i+1] == 'w') p.north.west else p.north.east; i += 2 } } } p }.counter() var pp = points.counts.filter { (_,v) -> v % 2 == 1 }.keys.toSet() repeat(100){ //println(pp) //for(x in pp.minBy { it.x }!!.x..(pp.maxBy { it.x }!!.x)){ // for(y in pp.minBy { it.y }!!.y..(pp.maxBy { it.y }!!.y)){ // print(if(x toP y in pp) '#' else '.') // } // println() //} val ne = pp.flatMap { listOf(it.east.east, it.west.west, it.south.east, it.south.west, it.north.west, it.north.east) }.counter().counts //println(ne) val new = (pp.union(ne.keys)).toSet().filter{ if(it in pp){ ne[it] == 1 || ne[it] == 2 } else { ne[it] == 2 } }.toSet() pp = new println("$it: ${pp.size}") } println(pp.size) } private typealias Data = Lines fun main() { val data: Data = getLines(2020_24) part1(data) part2(data) } fun <T> T.log(): T = also { println(this) }
0
Kotlin
0
1
744b02b4acd5c6799654be998a98c9baeaa25a79
1,949
AdventOfCodeSolutions
MIT License
src/main/kotlin/d4_GiantSquid/GiantSquid.kt
aormsby
425,644,961
false
{"Kotlin": 68415}
package d4_GiantSquid import util.CollectionHelper import util.Input import util.Output var boardSize = 0 fun main() { Output.day(4, "Giant Squid") val startTime = Output.startTime() var bingoDrawings: List<Int> var bingoBoards = mutableListOf<BingoBoard>() // set up number call and board collections with(Input.parseLines("/input/d4_bingo_subsystem.txt")) { // get bingo drawings as Ints bingoDrawings = Input.parseToListOf<Int>(rawData = this[0], delimiter = ",") // get boards as 2d lists val tempBoards = with(this.drop(2).chunked(6)) { transformTo2D() } // flatten boards and their transposed forms tempBoards.forEach { board -> bingoBoards.add( BingoBoard(board, CollectionHelper.transposeList(board)) ) } // set board size boardSize = bingoBoards.first().rows.first().size } // to store board and called number data var firstWinBoard = BingoBoard(listOf(), listOf()) var firstWinNum = -1 var lastWinBoard = BingoBoard(listOf(), listOf()) var lastWinNum = -1 run end@{ // call numbers bingoDrawings.forEach { num -> // mark boards bingoBoards.forEach { mark(it, num) if (it.isWinner && firstWinBoard.rows.isEmpty()) { firstWinBoard = BingoBoard(it.rows, it.columns) firstWinNum = num } } if (bingoBoards.size == 1 && bingoBoards.first().isWinner) { lastWinBoard = bingoBoards.first() lastWinNum = num return@end } // remove winners from play bingoBoards = bingoBoards.filterNot { it.isWinner }.toMutableList() } } Output.part(1, "Winning Board Remainder Sum", firstWinBoard.rows.fold(0) { acc, list -> acc + list.filterNot { it == -1 }.sum() } * firstWinNum) Output.part(2, "Losing Board Remainder Sum", lastWinBoard.rows.fold(0) { acc, list -> acc + list.filterNot { it == -1 }.sum() } * lastWinNum) Output.executionTime(startTime) } fun mark(board: BingoBoard, num: Int) { var x = -1 var y = -1 // mark nums for (row in board.rows.indices) { val col = board.rows[row].indexOf(num) if (col != -1) { // num found x = row y = col board.rows[x][y] = -1 board.columns[y][x] = -1 break } } // check if winner if (x != -1) { board.isWinner = board.rows[x].all { it == -1 } || board.columns[y].all { it == -1 } } } fun List<List<String>>.transformTo2D() = this.map { board -> board.mapNotNull { line -> if (line.isBlank()) null else line.trim(' ') .replace(" ", " ") .split(" ") .map { it.toInt() } as MutableList } } data class BingoBoard( val rows: List<MutableList<Int>>, // rows from input val columns: List<MutableList<Int>>, // transposed rows var isWinner: Boolean = false // to mark for removal from game )
0
Kotlin
1
1
193d7b47085c3e84a1f24b11177206e82110bfad
3,193
advent-of-code-2021
MIT License
findPositionElementArrayInfiniteLength.kt
prashantsinghpaliwal
537,191,958
false
{"Kotlin": 9473}
// Question Link - https://www.geeksforgeeks.org/find-position-element-sorted-array-infinite-numbers/ /* In this problem, since the array is of infinite length, we dont know the length and hence wont make use of arr.length - We will reverse the binary search approach to find a window or range in which the target exists. - We start with start = 0 and end = 1 - We keep on increasing this window/range by 2 - E.g. [2,3,4,7,9,11,12,15,23,30,31,34,35,36] and target is 15 - Level 0 -> 2 to 3 - Level 1 -> 4 to 11 - Level 2 -> 12 to 36, in this range, the target exists, hence we'll apply binary search here. Notice we are increasing the window by 2 */ fun main() { val arr = arrayOf(2, 3, 4, 7, 9, 11, 12, 15, 23, 30, 31, 34, 35, 36) val target = 15 println(findRange(arr, target)) } /* This method finds the range or window in which target exists. After finding the range we can easily apply binary search to find the element's index. */ fun findRange(arr: Array<Int>, target: Int): Int { var start = 0 var end = 1 while (target > arr[end]) { val newStart = end + 1 // double the box value // end = prev end + sizeOfBox*2 end = end + (end - start + 1) * 2 start = newStart } if (target == arr[end]) return end return normalBinarySearch(arr, target, start, end) } fun normalBinarySearch( arr: Array<Int>, target: Int, s: Int, e: Int ): Int { var start = s var end = e while (start <= end) { val mid = start + (end - start) / 2 // for elements not existing in array, it will throw IndexOutOfBoundException // in case target element > last element in ascending order list and vice versa if (mid >= arr.size - 1) return -1 if (target < arr[mid]) { end = mid - 1 } else if (target > arr[mid]) { start = mid + 1 } else { return mid } } return -1 }
0
Kotlin
0
0
e66599817508beb4e90de43305939d200a9e3964
2,029
DsAlgo
Apache License 2.0
src/main/kotlin/com/thedevadventure/roverkata/RoverKata.kt
EduanPrinsloo
549,216,876
false
{"Kotlin": 12299}
package com.thedevadventure.roverkata import java.util.* fun main() { val scanner = Scanner(System.`in`) // Get and validate the plateau println("Please enter the dimensions of your plateau starting with the size of X?") val plateauDimensionsX = scanner.nextInt() println("And the size of Y?") val plateauDimensionsY = scanner.nextInt() val marsTerrain = Plateau(plateauDimensionsX, plateauDimensionsY) validatePlateau(marsTerrain) // Get and validate the locations of the rovers println("Please enter the first rovers coordinates, starting with X hitting enter and then Y...") val firstRoverLocation = Location(scanner.nextInt(), scanner.nextInt()) val firstRoverCommands = getRoverCommands(scanner) println("Please enter the second rovers coordinates, starting with X hitting enter and then Y...") val secondRoverLocation = Location(scanner.nextInt(), scanner.nextInt()) val secondRoverCommands = getRoverCommands(scanner) validateTheRoverHasLanded(marsTerrain, firstRoverLocation) validateTheRoverHasLanded(marsTerrain, secondRoverLocation) explore(marsTerrain, firstRoverLocation, firstRoverCommands) explore(marsTerrain, secondRoverLocation, secondRoverCommands) checkIntersections( explore(marsTerrain, firstRoverLocation, firstRoverCommands), explore(marsTerrain, secondRoverLocation, secondRoverCommands) ) } fun validatePlateau(plateauDimensions: Plateau): Boolean { if (plateauDimensions.X > 0 && plateauDimensions.Y > 0) { println("Thank you for passing a valid plateau...") return true } else { throw Exception("Invalid plateau passed both your inputs should be larger than 0!") } } fun validateTheRoverHasLanded(plateau: Plateau, location: Location): Boolean { if ((location.X > plateau.X || location.X < 0) || (location.Y > plateau.Y || location.Y < 0)) { throw Exception("Mission failed... The rover missed the target!") } else { println("Rover has been located on the plateau, good job!") return true } } fun validateRoverCommands(commands: String): Instructions { if (!commands.uppercase().all { it.isLetter().and(it == 'N' || it == 'S' || it == 'W' || it == 'E') }) { throw Exception("Computer says No!") } val roverCommands = Instructions(commands.uppercase()) println("Commands received: ${roverCommands.roverCommands}...") return roverCommands } fun getRoverCommands(scanner: Scanner): Instructions { println("Please enter the command sequence for the first rover... valid inputs are limited to N, E, W, and S! ") val roverCommands = scanner.next() return validateRoverCommands(roverCommands) } fun explore(plateau: Plateau, startingLocation: Location, roverInstructions: Instructions): MutableList<Location> { val instructions = roverInstructions.roverCommands.map { it } val pathPoints = mutableListOf<Location>() var currentLocation = startingLocation pathPoints.add(startingLocation) for (instruction in instructions) { val result = move(instruction, currentLocation) isValidRoverPosition(result, plateau) pathPoints.add(result) currentLocation = result } return pathPoints } fun move(input: Char, location: Location): Location { return when (input.uppercaseChar()) { 'N' -> increaseY(location) 'E' -> increaseX(location) 'S' -> decreaseY(location) 'W' -> decreaseX(location) else -> location } } fun isValidRoverPosition(currentLocation: Location, plateau: Plateau): Boolean { if ((currentLocation.X > plateau.X || currentLocation.X < 0) || (currentLocation.Y > plateau.Y || currentLocation.Y < 0)) { throw Exception("Mission failed... The rover was lost at $currentLocation...") } else return true } fun increaseX(location: Location): Location { return Location(location.X + 1, location.Y) } fun increaseY(location: Location): Location { return Location(location.X, location.Y + 1) } fun decreaseX(location: Location): Location { return Location(location.X - 1, location.Y) } fun decreaseY(location: Location): Location { return Location(location.X, location.Y - 1) } fun checkIntersections(pathPoints1: List<Location>, pathPoints2: List<Location>): MutableList<Location> { val intersections = pathPoints1.intersect(pathPoints2.toSet()).toMutableList() if (intersections.isEmpty()) { throw Exception("No Intersections found...") } else { println("Intersection point are: $intersections") } return intersections } data class Plateau(val X: Int, val Y: Int) data class Location(val X: Int, val Y: Int) data class Instructions(val roverCommands: String)
0
Kotlin
0
0
5ee857f548921b79f3184cff5f2f83956d8521b9
4,782
RoverKata
Apache License 2.0
day1/src/main/kotlin/com/nohex/aoc/day1/Solution.kt
mnohe
433,396,563
false
{"Kotlin": 105740}
package com.nohex.aoc.day1 import com.nohex.aoc.PuzzleInput fun main() { println("Day 1, part 1: " + Solution().count(getInput())) println("Day 1, part 2: " + Solution().countWindows(getInput())) } private fun getInput() = PuzzleInput("input.txt") .asSequence() .filter(String::isNotBlank) .map(String::toInt) internal class Solution { /** * Counts the number of consecutive increases in the provided [measurements]. */ fun count(measurements: Sequence<Int>): Int { val iterator = measurements.iterator() // If no elements, the count is 0. if (!iterator.hasNext()) return 0 // Holds the count of consecutive increases. var count = 0 // Get the first value. var previous = iterator.next() while (iterator.hasNext()) { // Get the next value in the sequence val current = iterator.next() // If the current value has increased since the last one, count it. if (current > previous) count++ previous = current } return count } /** * Counts the number of consecutive increases in the provided [measurements]. */ fun countWindows(measurements: Sequence<Int>): Int { val iterator = measurements.windowed(3).iterator() // If no elements, the count is 0. if (!iterator.hasNext()) return 0 // Holds the count of consecutive increases. var count = 0 // Get the first value. var previousWindowSum = iterator.next().sum() while (iterator.hasNext()) { // Get the next value in the sequence val currentWindowSum = iterator.next().sum() // If the current value has increased since the last one, count it. if (currentWindowSum > previousWindowSum) count++ previousWindowSum = currentWindowSum } return count } }
0
Kotlin
0
0
4d7363c00252b5668c7e3002bb5d75145af91c23
1,993
advent_of_code_2021
MIT License
src/leetcodeProblem/leetcode/editor/en/HammingDistance.kt
faniabdullah
382,893,751
false
null
//The Hamming distance between two integers is the number of positions at which //the corresponding bits are different. // // Given two integers x and y, return the Hamming distance between them. // // // Example 1: // // //Input: x = 1, y = 4 //Output: 2 //Explanation: //1 (0 0 0 1) //4 (0 1 0 0) // ↑ ↑ //The above arrows point to positions where the corresponding bits are //different. // // // Example 2: // // //Input: x = 3, y = 1 //Output: 1 // // // // Constraints: // // // 0 <= x, y <= 2³¹ - 1 // // Related Topics Bit Manipulation 👍 2642 👎 188 package leetcodeProblem.leetcode.editor.en class HammingDistance { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun oneLineHammingDistance(x: Int, y: Int): Int { return Integer.bitCount(x xor y) } fun hammingDistance(x: Int, y: Int): Int { if (x == y) return 0 var count = 0 var n = x xor y while (n > 0) { count += n and 1 n = n shr 1 } return count } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { HammingDistance.Solution().hammingDistance(11, 12) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,406
dsa-kotlin
MIT License
leetcode-75-kotlin/src/main/kotlin/DecodeString.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * Given an encoded string, return its decoded string. * * The encoding rule is: k[encoded_string], * where the encoded_string inside the square brackets is being repeated exactly k times. * Note that k is guaranteed to be a positive integer. * * You may assume that the input string is always valid; * there are no extra white spaces, square brackets are well-formed, etc. * Furthermore, * you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, * k. * For example, there will not be input like 3a or 2[4]. * * The test cases are generated so that the length of the output will never exceed 105. * * * * Example 1: * * Input: s = "3[a]2[bc]" * Output: "aaabcbc" * Example 2: * * Input: s = "3[a2[c]]" * Output: "accaccacc" * Example 3: * * Input: s = "2[abc]3[cd]ef" * Output: "abcabccdcdcdef" * * * Constraints: * * 1 <= s.length <= 30 * s consists of lowercase English letters, digits, and square brackets '[]'. * s is guaranteed to be a valid input. * All the integers in s are in the range [1, 300]. * @see <a href="https://leetcode.com/problems/decode-string/">LeetCode</a> */ fun decodeString(s: String): String { var frequency = 0 var currentString = mutableListOf<Char>() var currentNumber = mutableListOf<Char>() var stack = mutableListOf<Char>() s.forEach { char -> if (char == ']') { while (stack.last() != '[') { currentString.add(0, stack.removeLast()) } stack.removeLast() while (stack.isNotEmpty() && stack.last().isDigit()) { currentNumber.add(0, stack.removeLast()) } frequency = currentNumber.joinToString("").toInt() currentString.joinToString("").repeat(frequency).forEach { char -> stack.add(char) } currentString.clear() currentNumber.clear() } else { stack.add(char) } } return stack.joinToString("") }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
2,034
leetcode-75
Apache License 2.0
src/2021/Day04.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2021` import java.io.File import java.util.* fun main() { Day04().solve() } data class BingoResult(val turn: Int, val score: Int) class BingoBoard(s: Scanner) { data class BingoField(val number: Int, var isDrawn: Boolean = false) val numbers = List(25){BingoField(s.nextInt())} val numberMap: Map<Int, Int> var result: BingoResult? = null init { val m = mutableMapOf<Int, Int>() numbers.forEachIndexed{ix, it -> m.put(it.number, ix)} numberMap = m.toMap() } fun draw(turn: Int, n: Int): Boolean { if (result != null) { return true } val ix = numberMap.get(n) if (ix != null) { numbers[ix].isDrawn = true if (allDrawn(row(ix)) || allDrawn(column(ix))) { result = BingoResult(turn, score(ix)) return true } } return false } fun allDrawn(ixs: IntProgression): Boolean { for (i in ixs) { if (!numbers[i].isDrawn) { return false } } return true } fun row(ix: Int): IntProgression { val start = ix - ix % 5 return start..start+4 } fun column(ix: Int): IntProgression { val start = ix % 5 return start..20+start step 5 } fun score(ix: Int): Int { return numbers.filterNot { it.isDrawn }.map { it.number }.sum() * numbers[ix].number } } class Day04 { fun solve() { val f = File("src/2021/inputs/day04.in") val s = Scanner(f) val nums = s.nextLine().trim().split(",").map { it.toInt() } val boards = mutableListOf<BingoBoard>() while (s.hasNextInt()) { boards.add(BingoBoard(s)) } for (ix in nums.indices) { if (boards.map { it.draw(ix, nums[ix]) }.all{it}) { break } } val sortedBoards = boards.sortedBy { it.result!!.turn } println("${sortedBoards.first().result} ${sortedBoards.last().result}") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
2,070
advent-of-code
Apache License 2.0
src/main/day05/Day05.kt
rolf-rosenbaum
543,501,223
false
{"Kotlin": 17211}
package day05 import readInput fun part1(input: List<String>): Int { return input.first().process().length } fun part2(input: List<String>): Int { return ('a'..'z').map { c -> c to input.first().filterNot { c.lowercase() == it.lowercase() }.process().apply { println("'$c' done: $length") } }.minOf { it.second.length } } fun main() { val input = readInput("main/day05/Day05") println(part1(input)) println(part2(input)) } fun String.process(): String { return generateSequence(this to false) { it.first.processOnce() }.first { it.second }.first } fun String.processOnce(): Pair<String, Boolean> { val result = this.fold(mutableListOf<Char>()) { processed, c -> if (processed.lastOrNull() matches c) { processed.removeLast() } else { processed.add(c) } processed }.joinToString("") return result to (result == this) } infix fun Char?.matches(other: Char): Boolean = this != null && this.isLowerCase() != other.isLowerCase() && this.lowercase() == other.lowercase()
0
Kotlin
0
0
dfd7c57afa91dac42362683291c20e0c2784e38e
1,096
aoc-2018
Apache License 2.0
src/commonMain/kotlin/org/petitparser/core/parser/consumer/CharPredicate.kt
petitparser
541,100,427
false
{"Kotlin": 114391}
package org.petitparser.core.parser.consumer import org.petitparser.core.parser.action.map import org.petitparser.core.parser.combinator.or import org.petitparser.core.parser.combinator.seqMap import org.petitparser.core.parser.misc.end import org.petitparser.core.parser.parse import org.petitparser.core.parser.repeater.star /** Functional character predicate. */ fun interface CharPredicate { /** Tests if the character predicate is satisfied. */ fun test(char: Char): Boolean /** Negates this character predicate. */ fun not(): CharPredicate = object : CharPredicate { override fun test(char: Char) = !this@CharPredicate.test(char) override fun not(): CharPredicate = this@CharPredicate } companion object { /** A character predicate that matches any character. */ internal fun any(): CharPredicate = object : CharPredicate { override fun test(char: Char): Boolean = true override fun not(): CharPredicate = none() } /** A character predicate that matches all of the provided [chars]. */ internal fun anyOf(chars: String): CharPredicate = ranges(chars.asIterable().map { it..it }) /** A character predicate that matches no character. */ internal fun none(): CharPredicate = object : CharPredicate { override fun test(char: Char): Boolean = true override fun not(): CharPredicate = any() } /** A character predicate that matches none of the provided [chars]. */ internal fun noneOf(chars: String): CharPredicate = anyOf(chars).not() /** A character predicate that matches the [expected] char. */ internal fun char(expected: Char) = CharPredicate { char -> expected == char } /** A character predicate that matches a character [range]. */ internal fun range(range: CharRange) = CharPredicate { char -> char in range } /** A character predicate that matches any of the provides [ranges]. */ internal fun ranges(ranges: List<CharRange>): CharPredicate { // 1. sort the ranges val sortedRanges = ranges.sortedWith(CHAR_RANGE_COMPARATOR) // 2. merge adjacent or overlapping ranges val mergedRanges = mutableListOf<CharRange>() for (thisRange in sortedRanges) { if (mergedRanges.isEmpty()) { mergedRanges.add(thisRange) } else { val lastRange = mergedRanges.last() if (lastRange.last.code + 1 >= thisRange.first.code) { val characterRange = lastRange.first..thisRange.last mergedRanges[mergedRanges.size - 1] = characterRange } else { mergedRanges.add(thisRange) } } } // 3. build the best resulting predicates return if (mergedRanges.isEmpty()) { none() } else if (mergedRanges.size == 1) { val characterRange = mergedRanges.first() if (characterRange.first == characterRange.last) { char(characterRange.first()) } else { range(characterRange) } } else { val starts = mergedRanges.map(CharRange::first).toList() val stops = mergedRanges.map(CharRange::last).toList() ranges(starts, stops) } } private fun ranges(starts: List<Char>, stops: List<Char>) = CharPredicate { char -> val index = starts.binarySearch(char) index >= 0 || index < -1 && char <= stops[-index - 2] } /** A character predicate that matches the provided [pattern]. */ internal fun pattern(pattern: String) = PATTERN.parse(pattern).value } } private val CHAR_RANGE_COMPARATOR = compareBy<CharRange> { range -> range.first }.thenBy { range -> range.last } private val PATTERN_SIMPLE = any().map { value -> value..value } private val PATTERN_RANGE = seqMap(any(), char('-'), any()) { start, _, stop -> start..stop } private val PATTERN_POSITIVE = or(PATTERN_RANGE, PATTERN_SIMPLE).star().map { ranges -> CharPredicate.ranges(ranges) } private val PATTERN_NEGATIVE = seqMap(char('^'), PATTERN_POSITIVE) { _, predicate -> predicate.not() } private val PATTERN = or(PATTERN_NEGATIVE, PATTERN_POSITIVE).end()
1
Kotlin
1
5
349522c37813e7714f66af4ed27db0b5750dd6f0
4,089
kotlin-petitparser
MIT License
day21/kotlin/RJPlog/day2021_1_2.kts
smarkwart
317,009,367
true
{"Python": 528881, "Rust": 179510, "Kotlin": 92549, "Ruby": 59698, "TypeScript": 57721, "Groovy": 56394, "CSS": 38649, "Java": 36866, "JavaScript": 27433, "HTML": 5424, "Dockerfile": 3230, "C++": 2171, "Go": 1733, "Jupyter Notebook": 988, "Shell": 897, "Clojure": 567, "PHP": 68, "Tcl": 46, "Dart": 41, "Haskell": 37}
import java.io.File // tag::allergen_2[] fun allergen_2(): String { // tag::read_puzzle[] var food_ingredients = mutableMapOf<Int, List<String>>() var food_allergens = mutableMapOf<Int, List<String>>() var allergen_list = mutableMapOf<String, String>() var food: Int = 0 File("day2021_puzzle_input.txt").forEachLine { var instruction = it.replace(",", "").replace(")", "").split(" (contains ") food_ingredients.put(food, instruction[0].split(" ")) food_allergens.put(food, instruction[1].split(" ")) instruction[1].split(" ").forEach { allergen_list.put(it, "-") } food++ } // end::read_puzzle[] // tag::search[] var i: Int var temp_list1 = mutableListOf<String>() var temp_list2 = mutableListOf<String>() var new_list: String = "" for (m in 0..5) { allergen_list.forEach { if (it.value.equals("-")) { var allergen = it.key i = 0 while (!food_allergens.getValue(i).contains(allergen)) { i++ } temp_list1.clear() temp_list1.addAll(food_ingredients.getValue(i)) for (j in i + 1..food - 1) { temp_list2.clear() temp_list2.addAll(food_ingredients.getValue(j)) if (food_allergens.getValue(j).contains(allergen)) { temp_list1.retainAll(temp_list2) } } if (temp_list1.size == 1) { allergen_list.put(allergen, temp_list1[0]) food_ingredients.forEach { for (k in 0..it.value.size - 1) { if (it.value[k] != temp_list1[0]) { new_list = new_list + it.value[k] + " " } } food_ingredients.put(it.key, new_list.dropLast(1).split(" ")) new_list = "" } } } // end if } } // end::search[] // tag::order_result[] var result: String = "" val sorted = allergen_list.toSortedMap() sorted.forEach { result = result + it.value + "," } result = result.dropLast(1) // end::order_result[] return result } // end::allergen_2[] // tag::allergen[] fun allergen(): Int { // tag::read_puzzle[] var food_ingredients = mutableMapOf<Int, List<String>>() var food_allergens = mutableMapOf<Int, List<String>>() var allergen_list = mutableMapOf<String, String>() var food: Int = 0 File("day2021_puzzle_input.txt").forEachLine { var instruction = it.replace(",", "").replace(")", "").split(" (contains ") food_ingredients.put(food, instruction[0].split(" ")) food_allergens.put(food, instruction[1].split(" ")) instruction[1].split(" ").forEach { allergen_list.put(it, "-") } food++ } // end::read_puzzle[] // tag::search[] var i: Int var temp_list1 = mutableListOf<String>() var temp_list2 = mutableListOf<String>() var new_list: String = "" for (m in 0..5) { // better to replace with while loop and a proper exitcondition allergen_list.forEach { if (it.value.equals("-")) { var allergen = it.key i = 0 while (!food_allergens.getValue(i).contains(allergen)) { i++ } temp_list1.clear() temp_list1.addAll(food_ingredients.getValue(i)) for (j in i + 1..food - 1) { temp_list2.clear() temp_list2.addAll(food_ingredients.getValue(j)) if (food_allergens.getValue(j).contains(allergen)) { temp_list1.retainAll(temp_list2) } } if (temp_list1.size == 1) { allergen_list.put(allergen, temp_list1[0]) food_ingredients.forEach { for (k in 0..it.value.size - 1) { if (it.value[k] != temp_list1[0]) { new_list = new_list + it.value[k] + " " } } food_ingredients.put(it.key, new_list.dropLast(1).split(" ")) new_list = "" } } } } } // end::search[] // tag::count_result[] var result: Int = 0 food_ingredients.forEach { result = result + it.value.size } // end::count_result[] return result } // end::allergen[] //fun main(args: Array<String>) { // tag::part_1[] var t1 = System.currentTimeMillis() var solution1 = allergen() t1 = System.currentTimeMillis() - t1 println() println("part 1 solved in $t1 ms -> $solution1") // end::part_1[] // tag::part_2[] var t2 = System.currentTimeMillis() var solution2 = allergen_2() t2 = System.currentTimeMillis() - t2 println() println("part 2 solved in $t2 ms -> $solution2") // end::part_2[] // tag::output[] // print solution for part 1 println("***********************************") println("--- Day 21: Allergen Assessment ---") println("***********************************") println("Solution for part1") println(" $solution1 times do any of those ingredients appear") println() // print solution for part 2 println("****************************") println("Solution for part2") println(" $solution2 is your canonical dangerous ingredient list") println() // end::output[] //}
0
Python
0
0
b1f9e04177afaf7e7c15fdc7bf7bc76f27a029f6
4,687
aoc-2020
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-23.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2015, "23-input") val test1 = readInputLines(2015, "23-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { return solve(input, 0) } private fun solve(input: List<String>, a: Int): Int { var comp = Computer(a = a) val instructions = input.map { Instruction.parse(it) } while (comp.ip in instructions.indices) { comp = comp.doInstruction(instructions[comp.ip]) } return comp.b } private fun part2(input: List<String>): Int { return solve(input, 1) } private data class Computer(val a: Int = 0, val b: Int = 0, val ip: Int = 0) private fun Computer.doInstruction(instruction: Instruction): Computer { return when (instruction) { is Instruction.Half -> { if (instruction.register == "a") copy(a = a / 2, ip = ip + 1) else copy(b = b / 2, ip = ip + 1) } is Instruction.Inc -> { if (instruction.register == "a") copy(a = a + 1, ip = ip + 1) else copy(b = b + 1, ip = ip + 1) } is Instruction.Triple -> { if (instruction.register == "a") copy(a = a * 3, ip = ip + 1) else copy(b = b * 3, ip = ip + 1) } is Instruction.Jump -> { copy(ip = ip + instruction.offset) } is Instruction.Jie -> { if (instruction.register == "a") { if (a % 2 == 0) { copy(ip = ip + instruction.offset) } else { copy(ip = ip + 1) } } else { if (b % 2 == 0) { copy(ip = ip + instruction.offset) } else { copy(ip = ip + 1) } } } is Instruction.Jio -> { if (instruction.register == "a") { if (a == 1) { copy(ip = ip + instruction.offset) } else { copy(ip = ip + 1) } } else { if (b == 1) { copy(ip = ip + instruction.offset) } else { copy(ip = ip + 1) } } } } } private sealed class Instruction { data class Inc(val register: String) : Instruction() data class Half(val register: String) : Instruction() data class Triple(val register: String) : Instruction() data class Jump(val offset: Int) : Instruction() data class Jie(val register: String, val offset: Int) : Instruction() data class Jio(val register: String, val offset: Int) : Instruction() companion object { fun parse(line: String) = when { line.startsWith("inc") -> Inc(line.substring(4)) line.startsWith("hlf") -> Half(line.substring(4)) line.startsWith("tpl") -> Triple(line.substring(4)) line.startsWith("jmp") -> Jump(line.substring(4).toInt()) line.startsWith("jie") -> Jie(line.substring(4..4), line.substring(7).toInt()) line.startsWith("jio") -> Jio(line.substring(4..4), line.substring(7).toInt()) else -> error("Unknown: '$line'") } } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
3,498
advent-of-code
MIT License
src/main/kotlin/tr/emreone/kotlin_utils/extensions/Sequences.kt
EmRe-One
442,916,831
false
{"Kotlin": 173543}
import tr.emreone.kotlin_utils.extensions.minMaxOrNull import tr.emreone.kotlin_utils.extensions.safeTimes class InfiniteSequence<T>(base: Sequence<T>) : Sequence<T> by base fun <T> Iterable<T>.asInfiniteSequence() = InfiniteSequence(sequence { while (true) yieldAll(this@asInfiniteSequence) }) fun <T> Sequence<T>.repeatLastForever() = InfiniteSequence(sequence { val it = this@repeatLastForever.iterator() if (it.hasNext()) { var elem: T do { elem = it.next() yield(elem) } while (it.hasNext()) while (true) yield(elem) } }) @JvmName("intProduct") fun Sequence<Int>.product(): Long = fold(1L, Long::safeTimes) fun Sequence<Long>.product(): Long = reduce(Long::safeTimes) /** * Returns the smallest and largest element or `null` if there are no elements. */ fun <T : Comparable<T>> Sequence<T>.minMaxOrNull(): Pair<T, T>? = asIterable().minMaxOrNull() /** * Returns the smallest and largest element or throws [NoSuchElementException] if there are no elements. */ fun <T : Comparable<T>> Sequence<T>.minMax(): Pair<T, T> = minMaxOrNull() ?: throw NoSuchElementException() /** * Returns a sequence containing the runs of equal elements and their respective count as Pairs. */ fun <T> Sequence<T>.runs(): Sequence<Pair<T, Int>> = sequence { val iterator = iterator() if (iterator.hasNext()) { var current = iterator.next() var count = 1 while (iterator.hasNext()) { val next: T = iterator.next() if (next != current) { yield(current to count) current = next count = 0 } count++ } yield(current to count) } } fun <T> Sequence<T>.runsOf(e: T): Sequence<Int> = runs().filter { it.first == e }.map { it.second }
0
Kotlin
0
0
aee38364ca1827666949557acb15ae3ea21881a1
1,841
kotlin-utils
Apache License 2.0
2020/Day12/src/main/kotlin/main.kt
airstandley
225,475,112
false
{"Python": 104962, "Kotlin": 59337}
import java.io.File import kotlin.math.* fun getInput(filename: String): List<String> { return File(filename).readLines() } const val NORTH = 'N' const val SOUTH = 'S' const val EAST = 'E' const val WEST = 'W' const val TURN_LEFT = 'L' const val TURN_RIGHT = 'R' const val FORWARD = 'F' fun getManhattanDistance(endPosition: Pair<Int, Int>, startPosition: Pair<Int, Int> = Pair(0,0)): Int { val x = endPosition.first - startPosition.first val y = endPosition.second - startPosition.second return abs(x) + abs(y) } fun turn(currentDirection: Pair<Int, Int>, angleInDegrees: Int): Pair<Int, Int> { val angleInRadians = angleInDegrees * PI/180 val x = currentDirection.first * cos(angleInRadians) - currentDirection.second * sin(angleInRadians) val y = currentDirection.first * sin(angleInRadians) + currentDirection.second * cos(angleInRadians) return Pair(x.roundToInt(),y.roundToInt()) } fun executeCommand( input: String, currentShipPosition: Pair<Int, Int>, currentWayPointPosition: Pair<Int, Int> ): Pair<Pair<Int, Int>,Pair<Int, Int>> { // currentDirection is a unit vector val instruction = input[0] val magnitude = input.drop(1).toInt() var newWayPointPosition: Pair<Int, Int> = currentWayPointPosition var newShipPosition: Pair<Int, Int> = currentShipPosition when (instruction) { NORTH -> newWayPointPosition = Pair(currentWayPointPosition.first, currentWayPointPosition.second + magnitude) SOUTH -> newWayPointPosition = Pair(currentWayPointPosition.first, currentWayPointPosition.second - magnitude) EAST -> newWayPointPosition = Pair(currentWayPointPosition.first + magnitude, currentWayPointPosition.second) WEST -> newWayPointPosition = Pair(currentWayPointPosition.first - magnitude, currentWayPointPosition.second) TURN_LEFT -> newWayPointPosition = turn(currentWayPointPosition, magnitude) TURN_RIGHT -> newWayPointPosition = turn(currentWayPointPosition, 360-magnitude) FORWARD -> newShipPosition = Pair( currentShipPosition.first + currentWayPointPosition.first * magnitude, currentShipPosition.second + currentWayPointPosition.second * magnitude ) } return Pair(newShipPosition, newWayPointPosition) } fun main(args: Array<String>) { val input = getInput("Input") var currentPosition = Pair(0,0) // East var currentDirection = Pair(10, 1) // println("Initial: Position (${currentPosition.first}, ${currentPosition.second}), Direction: ${currentDirection.first}, ${currentDirection.second})") for (command in input) { val output = executeCommand(command, currentPosition, currentDirection) currentPosition = output.first currentDirection = output.second // println("Input: $command, Position (${currentPosition.first}, ${currentPosition.second}), Direction: ${currentDirection.first}, ${currentDirection.second})") } val distance = getManhattanDistance(currentPosition, Pair(0,0)) println("Second Solution: $distance") }
0
Python
0
0
86b7e289d67ba3ea31a78f4a4005253098f47254
3,068
AdventofCode
MIT License
Kotlin/problems/0049_unique_paths_iii.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
//Problem Statement // On a 2-dimensional grid, there are 4 types of squares: // // * 1 represents the starting square. There is exactly one starting square. // * 2 represents the ending square. There is exactly one ending square. // * 0 represents empty squares we can walk over. // * -1 represents obstacles that we cannot walk over. // // Return the number of 4-directional walks from the starting square to the ending // square, that walk over every non-obstacle square exactly once. class Solution { private val visited = mutableSetOf<Int>() private var result = 0 private var walkableSquares = 0 private val dir = intArrayOf(0,1,0,-1) fun uniquePathsIII(grid: Array<IntArray>): Int { var start_row = 0 var start_col = 0 for(i in 0 until grid.size){ for(j in 0 until grid[0].size){ if(grid[i][j]==0){ walkableSquares+=1 } if(grid[i][j]==1){ start_row = i start_col = j walkableSquares+=1 } } } dfs(grid,start_row,start_col) return result } private fun dfs(grid: Array<IntArray>, row: Int, col:Int){ val newKey = row*grid[0].size+col if(row<0 || col<0 || row>=grid.size || col>=grid[0].size || grid[row][col]==-1 || visited.contains(newKey)){ return } if(grid[row][col]==2){ if(walkableSquares==visited.size){ result+=1 } return } visited.add(newKey) for(i in 0 until 4){ dfs(grid,row+dir[i],col+dir[(i+1)%4]) } visited.remove(newKey) } } fun main(args: Array<String>) { val grid = arrayOf(intArrayOf(1,0,0,0),intArrayOf(0,0,0,0),intArrayOf(0,0,2,-1)) val sol = Solution println(sol.uniquePathsIII(grid)) }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
1,981
algorithms
MIT License
src/main/kotlin/machines/FSMMinimizer.kt
Niksen111
736,732,938
false
{"Kotlin": 16917}
package machines class FSMMinimizer { companion object { fun minimize(fsm: FiniteStateMachine): FiniteStateMachine { val achievableStates = findAchievableStates(fsm) val classes = extractKEquivalenceClasses(achievableStates, 0, fsm) val states = classes.map { it.joinToString(" ") } val endStates = classes.filter { t -> t.any { fsm.endStates.contains(it) } } .map { it.joinToString(" ") } val startStateClass = classes.first { it.contains(fsm.startState) } val startState = startStateClass.joinToString(" ") val map = HashMap<Rule, String>() classes.forEach { currClass -> val classRepresentative = currClass[0] val state = currClass.joinToString(" ") fsm.alphabet.forEach { c -> val rule = Rule(classRepresentative, c) fsm.getMap()[rule]?.let { val valueClass = findStateClass(it, classes).joinToString(" ") map[Rule(state, c)] = valueClass } } } return FiniteStateMachine(states, fsm.alphabet, map, startState, endStates) } fun minimizeSecondStep(baseFsm: FiniteStateMachine): FiniteStateMachine { val fsm = minimize(baseFsm) val classes = fsm.states.map { listOf(it) }.toMutableList() val representatives = fsm.states.toMutableList() for (i in fsm.startState.indices) { for (j in i+1..<fsm.states.size) { val firstState = fsm.states[i] val secondState = fsm.states[j] var isEquivalent = true for (c in fsm.alphabet) { val firstValue = fsm.getMap()[Rule(firstState, c)] val secondValue = fsm.getMap()[Rule(secondState, c)] val isEqual = firstValue == secondValue || firstValue == null || secondValue == null if (!isEqual) { isEquivalent = false break } } if (!isEquivalent) { continue } val firstStateClass = classes.find { it.contains(firstState) }.orEmpty().toMutableList() val secondStateClass = classes.find { it.contains(secondState) }.orEmpty().toMutableList() if (firstStateClass == secondStateClass) { continue } val secondStateClassIndex = classes.indexOf(secondStateClass) firstStateClass.add(secondState) secondStateClass.remove(secondState) if (secondStateClass.isNotEmpty()) { val representative = secondStateClass[0] representatives[secondStateClassIndex] = representative } else { representatives[secondStateClassIndex] = "" } } } classes.removeAll { it.isEmpty() } representatives.removeAll { it.isEmpty() } val states = classes.map { it.joinToString(" ") } val endStates = classes.filter { it.any { x -> fsm.endStates.contains(x) } } .map { it.joinToString(" ") } val startStateClass = classes.first { it.contains(fsm.startState) } val startState = startStateClass.joinToString(" ") val map = hashMapOf<Rule, String>() for (i in classes.indices) { val currClass = classes[i] val classRepresentative = representatives[i] val state = currClass.joinToString(" ") fsm.alphabet.forEach { c -> val rule = Rule(classRepresentative, c) fsm.getMap()[rule]?.let { value -> val valueClass = findStateClass(value, classes).joinToString(" ") map[Rule(state, c)] = valueClass } } } return FiniteStateMachine(states, fsm.alphabet, map, startState, endStates) } private fun extractKEquivalenceClasses( states: List<String>, k: Int, fsm: FiniteStateMachine ): List<List<String>> { val classes = divideIntoKEquivalenceClasses(states, k, fsm) val newK = k + 1 if (classes.size == 1) { return classes } val subclasses = mutableListOf<MutableList<String>>() classes.forEach { c -> val currClasses = extractKEquivalenceClasses(c.toList(), newK, fsm) subclasses.addAll(currClasses.map { it.toMutableList() }) } return subclasses } private fun divideIntoKEquivalenceClasses( states: List<String>, k: Int, fsm: FiniteStateMachine ): List<List<String>> { val equivalenceClasses = mutableListOf<MutableList<String>>() for (i in states.indices) { if (equivalenceClasses.any { it.contains(states[i]) }) { continue } equivalenceClasses.add(mutableListOf(states[i])) for (j in i+1..<states.size) { if (isStatesKEqual(states[i], states[j], k, fsm)) { equivalenceClasses.last().add(states[j]) } } } return equivalenceClasses } private fun isStates0Equal(firstState: String?, secondState: String?, fsm: FiniteStateMachine): Boolean { if (fsm.endStates.contains(firstState) && fsm.endStates.contains(secondState)) { return true } val notEndStates = fsm.states.minus(fsm.endStates.toSet()) return notEndStates.contains(firstState) && notEndStates.contains(secondState) } private fun isStatesKEqual(firstState: String?, secondState: String?, k: Int, fsm: FiniteStateMachine): Boolean { if (k == 0) { return isStates0Equal(firstState, secondState, fsm) } fsm.alphabet.forEach { c -> val firstValue = fsm.getMap()[Rule(firstState!!, c)] val secondValue = fsm.getMap()[Rule(secondState!!, c)] if (firstValue != secondValue && !isStatesKEqual(firstValue, secondValue, k - 1, fsm)) { return false } } return isStatesKEqual(firstState, secondState, k - 1, fsm) } private fun findAchievableStates(fsm: FiniteStateMachine): List<String> { val achievableStates = mutableListOf(fsm.startState) var newStates = listOf(fsm.startState) while (true) { val states = mutableListOf<String>() newStates.forEach { state -> val currStates = fsm.getMap().filter { it.key.state == state } .map { it.value }.minus(achievableStates.toSet()) states.addAll(currStates) } if (states.isEmpty()) { achievableStates.sort() return achievableStates.distinct() } achievableStates.addAll(states) newStates = states } } private fun findStateClass(state: String, classes: List<List<String>>): List<String> { return classes.first { it.contains(state) } } } }
0
Kotlin
0
1
7cb9dd0072fc2c4cc11b893de4d5f9d4092d9213
7,938
formalki-referat
Apache License 2.0
src/main/kotlin/days/Day3.kt
hughjdavey
317,575,435
false
null
package days class Day3 : Day(3) { private val trees = TreeGrid(inputList.map { it.trim() }) // 237 override fun partOne(): Any { return trees.path(3, 1).count { it == '#' } } // 2106818610 override fun partTwo(): Any { return listOf(1 to 1, 3 to 1, 5 to 1, 7 to 1, 1 to 2) .map { (right, down) -> trees.path(right, down).count { it == '#' } } .reduce { sum, i -> sum * i } } class TreeGrid(private val grid: List<String>) { private val maxX = grid.first().length fun get(x: Int, y: Int): Char { return grid[y][x % maxX] } fun path(right: Int, down: Int): List<Char> { return generateSequence(0 to 0) { (x, y) -> if (y + down >= grid.size) null else x + right to y + down } .map { (x, y) -> get(x, y) }.toList() } } }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
882
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day20.kt
butnotstupid
433,717,137
false
{"Kotlin": 55124}
package days class Day20 : Day(20) { private val padx = 250 private val pady = 250 override fun partOne(): Any { return extendImage(inputList, 2) } override fun partTwo(): Any { return extendImage(inputList, 50) } private fun extendImage(inputList: List<String>, stepsNumber: Int): Int { val extendMap = inputList[0].map { it != '.' }.toTypedArray() var canvas = Array(padx * 2 + 10) { Array(pady * 2 + 10) { false } } inputList.drop(2).forEachIndexed { x, s -> s.forEachIndexed { y, c -> if (c == '#') canvas[padx + x][pady + y] = true } } repeat(stepsNumber) { canvas = nextStep(canvas, extendMap) } return canvas.drop(100).dropLast(100).sumOf { it.drop(100).dropLast(100).count { it } } } private fun nextStep(canvas: Array<Array<Boolean>>, extendMap: Array<Boolean>): Array<Array<Boolean>> { val di = listOf(-1, -1, -1, 0, 0, 0, 1, 1, 1) val dj = listOf(-1, 0, 1, -1, 0, 1, -1, 0, 1) val next = Array(canvas.size) { Array(canvas.first().size) { false } } for (x in -padx + 2..padx - 2) { for (y in -pady + 2..pady - 2) { val (cx, cy) = x + padx to y + pady val decimal = generateSequence(1) { it * 2 }.take(9).toList().reversed().zip( di.zip(dj).map { (i, j) -> canvas[cx + i][cy + j] } ).sumOf { (pow2, digit) -> pow2 * if (digit) 1 else 0 } next[cx][cy] = extendMap[decimal] } } return next } }
0
Kotlin
0
0
a06eaaff7e7c33df58157d8f29236675f9aa7b64
1,633
aoc-2021
Creative Commons Zero v1.0 Universal
utility/src/main/java/org/oppia/android/util/math/ComparatorExtensions.kt
oppia
148,093,817
false
{"Kotlin": 12174721, "Starlark": 666467, "Java": 33231, "Shell": 12716}
package org.oppia.android.util.math import com.google.protobuf.MessageLite /** * Compares two [Iterable]s based on an item [Comparator] and returns the result. * * The two [Iterable]s are iterated in an order determined by [Comparator], and then compared * element-by-element. If any element is different, the difference of that item becomes the overall * difference. If the lists are different sizes (but otherwise match up to the boundary of one * list), then the longer list will be considered "greater". * * This means that two [Iterable]s are only equal if they have the same number of elements, and that * all of their items are equal per this [Comparator], including duplicates. */ fun <U> Comparator<U>.compareIterables(first: Iterable<U>, second: Iterable<U>): Int { return compareIterablesInternal(first, second, reverseItemSort = false) } /** * Compares two [Iterable]s based on an item [Comparator] and returns the result, in much the same * way as [compareIterables] except this reverses the result (that is, [first] will be considered * less than [second] if it's larger). * * This should be used in place of a standard 'reversed()' since it will properly reverse (both the * internal sorting and the comparison needs to be reversed in order for the reversal to be * correct). */ fun <U> Comparator<U>.compareIterablesReversed(first: Iterable<U>, second: Iterable<U>): Int { // Note that first & second are reversed here. return compareIterablesInternal(second, first, reverseItemSort = true) } private fun <U> Comparator<U>.compareIterablesInternal( first: Iterable<U>, second: Iterable<U>, reverseItemSort: Boolean ): Int { // Reference: https://stackoverflow.com/a/30107086. val itemComparator = if (reverseItemSort) reversed() else this val firstIter = first.sortedWith(itemComparator).iterator() val secondIter = second.sortedWith(itemComparator).iterator() while (firstIter.hasNext() && secondIter.hasNext()) { val comparison = this.compare(firstIter.next(), secondIter.next()).coerceIn(-1..1) if (comparison != 0) return comparison // Found a different item. } // Everything is equal up to here, see if the lists are different length. return when { firstIter.hasNext() -> 1 // The first list is longer, therefore "greater." secondIter.hasNext() -> -1 // Ditto, but for the second list. else -> 0 // Otherwise, they're the same length with all equal items (and are thus equal). } } /** * Compares two protos of type [T] ([left] and [right]) using this [Comparator] and returns the * result. * * This adds behavior above the standard ``compare`` function by short-circuiting if either proto is * equal to the default instance (in which case "defined" is always considered larger, and this * [Comparator] isn't used). This short-circuiting behavior can be useful when comparing recursively * infinite proto structures to avoid stack overflows.. */ fun <T : MessageLite> Comparator<T>.compareProtos(left: T, right: T): Int { val defaultValue = left.defaultInstanceForType val leftIsDefault = left == defaultValue val rightIsDefault = right == defaultValue return when { leftIsDefault && rightIsDefault -> 0 // Both are default, therefore equal. leftIsDefault -> -1 // right > left since it's initialized. rightIsDefault -> 1 // left > right since it's initialized. else -> compare(left, right) // Both are initialized; perform a deep-comparison. } }
508
Kotlin
491
285
4a07d8db69e395c9e076c342c0d1dc3521ff3051
3,475
oppia-android
Apache License 2.0
src/main/kotlin/leetcode/kotlin/dp/53. Maximum Subarray.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.dp /** 1. Optimal structure f(n) = MAX(f(n-1), f`(n-1) + arr[n], arr[n]) f`(i) = MAX(f`(i-1), 0) + arr[i] Legends: f(n) = max sum including and excluding index n f`(n) = max sum including index n arr[n] = element at index n in given array 2. sub-problems calls tree for f(4), depicting overlapping sub-problems f4 / \ f3 f`3 / \ \ f2 f`2 f`2 / \ \ \ f1 f`1 f`1 f`1 / \ \ \ \ f0 f`0 f`0 f`0 f`0 */ // top-down approach using memoization // StackOverflowError for big size array, but works for smaller array size private fun maxSubArray(arr: IntArray): Int { var dpi = IntArray(arr.size) { Int.MIN_VALUE } // function to return max sum ending at index i fun maxi(i: Int): Int { if (i == 0) return arr[0] if (dpi[i] > Int.MIN_VALUE) return dpi[i] var r = Math.max(maxi(i - 1), 0) + arr[i] dpi[i] = r return r } fun max(n: Int): Int { if (n == 0) return arr[0] var r = Math.max(max(n - 1), maxi(n - 1) + arr[n]) r = Math.max(r, arr[n]) return r } return max(arr.size - 1) } // bottom-up approach using tabulation // f(n) = MAX(f(n-1), f`(n-1) + arr[n], arr[n]) // f(n) is max_so_far // f`(n) is max_ending_here private fun maxSubArray2(arr: IntArray): Int { var max_so_far = arr[0] var max_ending_here = arr[0] for (i in 1..arr.lastIndex) { max_ending_here = maxOf(max_ending_here + arr[i], arr[i]) max_so_far = maxOf(max_so_far, max_ending_here) } return max_so_far }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
1,688
kotlinmaster
Apache License 2.0
src/main/aoc2018/Day16.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2018 import aoc2018.Day16.InstructionName.* class Day16(input: List<String>) { data class Example(val before: List<Int>, val after: List<Int>, val instruction: Instruction) data class Instruction(val opcode: Int, val a: Int, val b: Int, val output: Int) enum class InstructionName { ADDR, ADDI, MULR, MULI, BANR, BANI, BORR, BORI, SETR, SETI, GTIR, GTRI, GTRR, EQIR, EQRI, EQRR } private val registers = MutableList(4) { 0 } private val examples: List<Example> private val program: List<Instruction> init { var examplePart = true var i = 0 val ex = mutableListOf<Example>() val prog = mutableListOf<Instruction>() while (i < input.size) { if (input[i].isEmpty()) { examplePart = false i += 2 } if (examplePart) { val before = input[i++].substringAfter("[").substringBefore("]") .split(", ").map { it.toInt() } val instruction = input[i++].split(" ").map { it.toInt() } val after = input[i++].substringAfter("[").substringBefore("]") .split(", ").map { it.toInt() } i++ ex.add(Example(before, after, Instruction(instruction[0], instruction[1], instruction[2], instruction[3]))) } else { val instruction = input[i++].split(" ").map { it.toInt() } prog.add(Instruction(instruction[0], instruction[1], instruction[2], instruction[3])) } } examples = ex program = prog } private fun doInstruction(instruction: Instruction, getInstruction: (Int) -> InstructionName) { registers[instruction.output] = when (getInstruction(instruction.opcode)) { ADDR -> registers[instruction.a] + registers[instruction.b] ADDI -> registers[instruction.a] + instruction.b MULR -> registers[instruction.a] * registers[instruction.b] MULI -> registers[instruction.a] * instruction.b BANR -> registers[instruction.a] and registers[instruction.b] BANI -> registers[instruction.a] and instruction.b BORR -> registers[instruction.a] or registers[instruction.b] BORI -> registers[instruction.a] or instruction.b SETR -> registers[instruction.a] SETI -> instruction.a GTIR -> if (instruction.a > registers[instruction.b]) 1 else 0 GTRI -> if (registers[instruction.a] > instruction.b) 1 else 0 GTRR -> if (registers[instruction.a] > registers[instruction.b]) 1 else 0 EQIR -> if (instruction.a == registers[instruction.b]) 1 else 0 EQRI -> if (registers[instruction.a] == instruction.b) 1 else 0 EQRR -> if (registers[instruction.a] == registers[instruction.b]) 1 else 0 } } // Generate a list of opcode -> list of opcodes to instructions that are possible pairs based on example data private fun testExamples(): List<Pair<Int, List<InstructionName>>> { return examples.map { example -> val possible = mutableListOf<InstructionName>() entries.forEach { instruction -> for (i in 0 until registers.size) { registers[i] = example.before[i] } doInstruction(example.instruction) { instruction } if (registers == example.after) { possible.add(instruction) } } example.instruction.opcode to possible } } // Based on all the example data, generate a map from opcode to list of possible instructions for that opcode private fun opcodeToInstructions(): Map<Int, List<InstructionName>> { val ret = mutableMapOf<Int, List<InstructionName>>() val examples = testExamples() (0..15).forEach { opcode -> val possibleInstructions = examples.filter { it.first == opcode }.map { it.second } ret[opcode] = entries.toMutableList() .filter { instruction -> possibleInstructions.all { it.contains(instruction) } } } return ret } // Based on a opcode to list of possible instructions map recursively reduce the map // with known opcodes until all is known. private tailrec fun reduceInstructions(instructions: Map<Int, List<InstructionName>>): Map<Int, List<InstructionName>> { val ret = mutableMapOf<Int, List<InstructionName>>() val known = instructions.filter { it.value.size == 1 }.values.flatten() instructions.forEach { (key, value) -> if (value.size == 1) { ret[key] = value } else { val unknown = value.toMutableList() known.forEach { unknown.remove(it) } ret[key] = unknown } } return if (ret.any { it.value.size > 1 }) { reduceInstructions(ret) } else { ret } } private fun runProgram(instructions: Map<Int, List<InstructionName>>) { program.forEach { doInstruction(it) { instruction -> instructions.getValue(instruction).first() } } } fun solvePart1(): Int { return testExamples().count { it.second.size >= 3 } } fun solvePart2(): Int { val instructions = reduceInstructions(opcodeToInstructions()) (0 until registers.size).forEach { registers[it] = 0 } runProgram(instructions) return registers[0] } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
5,737
aoc
MIT License
src/main/kotlin/g1801_1900/s1802_maximum_value_at_a_given_index_in_a_bounded_array/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1802_maximum_value_at_a_given_index_in_a_bounded_array // #Medium #Greedy #Binary_Search #Binary_Search_II_Day_17 // #2023_06_19_Time_118_ms_(100.00%)_Space_33.8_MB_(13.82%) class Solution { private fun isPossible(n: Int, index: Int, maxSum: Int, value: Int): Boolean { val leftValue = (value - index).coerceAtLeast(0) val rightValue = (value - (n - 1 - index)).coerceAtLeast(0) val sumBefore = (value + leftValue).toLong() * (value - leftValue + 1) / 2 val sumAfter = (value + rightValue).toLong() * (value - rightValue + 1) / 2 return sumBefore + sumAfter - value <= maxSum } fun maxValue(n: Int, index: Int, maxSum: Int): Int { var left = 0 var right = maxSum - n while (left < right) { val middle = (left + right + 1) / 2 if (isPossible(n, index, maxSum - n, middle)) { left = middle } else { right = middle - 1 } } return left + 1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,039
LeetCode-in-Kotlin
MIT License
year2019/src/main/kotlin/net/olegg/aoc/year2019/day6/Day6.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2019.day6 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2019.DayOf2019 /** * See [Year 2019, Day 6](https://adventofcode.com/2019/day/6) */ object Day6 : DayOf2019(6) { override fun first(): Any? { val orbits = lines .mapTo(mutableListOf()) { line -> line.split(")").let { it.first() to it.last() } } val available = orbits.map { it.second }.toMutableSet() val counts = orbits.flatMap { it.toList() }.associateWithTo(mutableMapOf()) { 0 } while (available.isNotEmpty()) { val curr = available.first { planet -> orbits.none { it.first == planet } } val orbit = orbits.first { it.second == curr } counts[orbit.first] = counts.getOrDefault(orbit.first, 0) + counts.getOrDefault(orbit.second, 0) + 1 available.remove(curr) orbits.remove(orbit) } return counts.values.sum() } override fun second(): Any? { val orbits = lines.associate { line -> line.split(")").let { it.last() to it.first() } } val you = mutableListOf("YOU") while (you.last() in orbits) { you += orbits.getOrDefault(you.last(), "") } val san = mutableListOf("SAN") while (san.last() in orbits) { san += orbits.getOrDefault(san.last(), "") } return you.indexOfFirst { it in san } + san.indexOfFirst { it in you } - 2 } } fun main() = SomeDay.mainify(Day6)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,394
adventofcode
MIT License
src/day17/Day17.kt
spyroid
433,555,350
false
null
package day17 import kotlin.math.absoluteValue import kotlin.system.measureTimeMillis class Simulation(val x1: Int, val x2: Int, val y1: Int, val y2: Int) { data class Bullet(var dx: Int, var dy: Int, var x: Int = 0, var y: Int = 0) { var maxY = y fun step() { x += dx y += dy-- if (dx > 0) dx -= 1 else dx = 0 maxY = maxOf(maxY, y) } } private fun simulate(x: Int, y: Int): Bullet? { val b = Bullet(x, y) while (b.y >= y1 && b.x <= x2) { b.step() if (b.x in x1..x2 && b.y in y1..y2) return b } return null } fun find(): Pair<Int, Int> { var maxY = -1 var count = 0 for (x in 1..x2) { for (y in y1..y1.absoluteValue) { val res = simulate(x, y) if (res != null) { maxY = maxOf(maxY, res.maxY) count++ } } } return Pair(maxY, count) } } fun main() { var res = Simulation(20, 30, -10, -5).find() check(res.first == 45) { "Expected 45 but got ${res.first}" } check(res.second == 112) { "Expected 112 but got ${res.second}" } measureTimeMillis { res = Simulation(48, 70, -189, -148).find() }.also { time -> println("⭐️ Part1: ${res.first} in $time ms") println("⭐️ Part2: ${res.second} in $time ms") } }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
1,471
Advent-of-Code-2021
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day18/day18.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day18 import biz.koziolek.adventofcode.* import java.util.* import kotlin.math.ceil import kotlin.math.floor fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val numbers = parseSnailfishNumbers(lines) val sum = addAndReduceAll(numbers) println("Sum magnitude is: ${sum.magnitude}") val (_, _, maxMagnitude) = findMaxPossibleMagnitudeOfTwo(numbers) println("Max possible magnitude of sum of two numbers is: $maxMagnitude") } sealed interface SnailfishNumber { val level: Int val magnitude: Int fun asText(): String fun increaseLevel(): SnailfishNumber fun reduce(): SnailfishNumber fun reduceOnce(): SnailfishNumber fun explode(): SnailfishNumber fun split(): SnailfishNumber } data class SnailfishPair( val left: SnailfishNumber, val right: SnailfishNumber, override val level: Int ) : SnailfishNumber { override val magnitude by lazy { 3 * left.magnitude + 2 * right.magnitude } override fun asText() = "[${left.asText()},${right.asText()}]" override fun increaseLevel(): SnailfishPair = copy( left = left.increaseLevel(), right = right.increaseLevel(), level = level + 1 ) operator fun plus(other: SnailfishPair): SnailfishPair = SnailfishPair( left = this.increaseLevel(), right = other.increaseLevel(), level = 0 ) override fun reduce(): SnailfishPair { var prev: SnailfishNumber = this var next = reduceOnce() while (next != prev) { prev = next next = next.reduceOnce() } return next } override fun reduceOnce(): SnailfishPair { val newThis = this.explode() if (newThis != this) { return newThis } val newThis2 = this.split() if (newThis2 != this) { return newThis2 } return this } override fun explode(): SnailfishPair { return when (val explosionResult = explodeInternal(NoExplosion)) { is NoExplosion -> this is LeftAndRight -> throw IllegalStateException("Not consumed left nor right should never happen (I think?)") is OnlyLeft -> explosionResult.number is OnlyRight -> explosionResult.number as SnailfishPair is ExplosionComplete -> explosionResult.number as SnailfishPair } } private fun explodeInternal(result: ExplosionResult): ExplosionResult = when (result) { is NoExplosion -> { if (level >= 4 && left is SnailfishRegular && right is SnailfishRegular) { LeftAndRight(left.value, right.value, SnailfishRegular(value = 0, level = level)) } else { val leftResult = if (left is SnailfishPair) { left.explodeInternal(result) } else { NoExplosion } when (leftResult) { is NoExplosion -> { val rightResult = if (right is SnailfishPair) { right.explodeInternal(leftResult) } else { NoExplosion } when (rightResult) { is NoExplosion -> NoExplosion is LeftAndRight -> { val leftResult2 = when (left) { is SnailfishRegular -> OnlyRight(rightResult.right, left.copy(value = left.value + rightResult.left)) // BTW, this is impossible and won't work if called. // 1) Left cannot be a pair and not be exploded at the same time when right was exploded. // They are at the same level, so left or something inside it must have been exploded. // 2) Left receives LeftAndRight as argument, which is not supported by outer-most when. is SnailfishPair -> left.explodeInternal(rightResult) } when (leftResult2) { is NoExplosion -> throw IllegalStateException("Impossible") is ExplosionComplete -> throw IllegalStateException("Impossible") is LeftAndRight -> throw IllegalStateException("Impossible") is OnlyLeft -> throw IllegalStateException("Impossible") is OnlyRight -> OnlyRight(right = rightResult.right, number = copy( left = leftResult2.number, right = rightResult.number, )) } } is OnlyLeft -> { val leftResult2 = when (left) { is SnailfishRegular -> ExplosionComplete(left.copy(value = left.value + rightResult.left)) is SnailfishPair -> left.explodeInternal(rightResult) } when (leftResult2) { is NoExplosion -> throw IllegalStateException("Impossible") is ExplosionComplete -> ExplosionComplete(number = copy( left = leftResult2.number, right = rightResult.number, )) is LeftAndRight -> throw IllegalStateException("Impossible") is OnlyLeft -> throw IllegalStateException("Impossible") is OnlyRight -> throw IllegalStateException("Impossible") } } is OnlyRight -> rightResult.copy(number = copy( right = rightResult.number, )) is ExplosionComplete -> rightResult.copy(number = copy( right = rightResult.number, )) } } is LeftAndRight -> { val rightResult = when (right) { is SnailfishRegular -> ExplosionComplete(right.copy(value = right.value + leftResult.right)) is SnailfishPair -> right.explodeInternal(OnlyRight(right = leftResult.right, number = this)) } when (rightResult) { is NoExplosion -> throw IllegalStateException("Impossible") is ExplosionComplete -> OnlyLeft(left = leftResult.left, number = copy( left = leftResult.number, right = rightResult.number, )) is LeftAndRight -> throw IllegalStateException("Impossible") is OnlyLeft -> throw IllegalStateException("Impossible") is OnlyRight -> throw IllegalStateException("Impossible") } } is ExplosionComplete -> leftResult.copy(number = copy( left = leftResult.number, )) is OnlyLeft -> leftResult.copy(number = copy( left = leftResult.number, )) is OnlyRight -> { val rightResult = when (right) { is SnailfishRegular -> ExplosionComplete(right.copy(value = right.value + leftResult.right)) is SnailfishPair -> right.explodeInternal(leftResult) } when (rightResult) { is NoExplosion -> throw IllegalStateException("Impossible") is ExplosionComplete -> ExplosionComplete(copy( left = leftResult.number, right = rightResult.number, )) is LeftAndRight -> throw IllegalStateException("Impossible") is OnlyLeft -> throw IllegalStateException("Impossible") is OnlyRight -> throw IllegalStateException("Impossible") } } } } } is LeftAndRight -> throw IllegalStateException("Don't know what to do - please do not pass me that") is OnlyLeft -> { val rightResult = when (right) { is SnailfishRegular -> ExplosionComplete(right.copy(value = right.value + result.left)) is SnailfishPair -> right.explodeInternal(result) } when (rightResult) { is NoExplosion -> throw IllegalStateException("Impossible") is ExplosionComplete -> rightResult.copy(number = copy( right = rightResult.number, )) is LeftAndRight -> throw IllegalStateException("Impossible") is OnlyLeft -> throw IllegalStateException("Impossible") is OnlyRight -> throw IllegalStateException("Impossible") } } is OnlyRight -> { val leftResult = when (left) { is SnailfishRegular -> ExplosionComplete(left.copy(value = left.value + result.right)) is SnailfishPair -> left.explodeInternal(result) } when (leftResult) { is NoExplosion -> throw IllegalStateException("Impossible") is ExplosionComplete -> leftResult.copy(number = copy( left = leftResult.number, )) is LeftAndRight -> throw IllegalStateException("Impossible") is OnlyLeft -> throw IllegalStateException("Impossible") is OnlyRight -> throw IllegalStateException("Impossible") } } is ExplosionComplete -> throw IllegalStateException("Impossible") } override fun split(): SnailfishPair { val newLeft = left.split() if (newLeft != left) { return copy(left = newLeft) } val newRight = right.split() if (newRight != left) { return copy(right = newRight) } return this } private sealed interface ExplosionResult private object NoExplosion : ExplosionResult private data class LeftAndRight(val left: Int, val right: Int, val number: SnailfishNumber) : ExplosionResult private data class OnlyLeft(val left: Int, val number: SnailfishPair) : ExplosionResult private data class OnlyRight(val right: Int, val number: SnailfishNumber) : ExplosionResult private data class ExplosionComplete(val number: SnailfishNumber) : ExplosionResult } data class SnailfishRegular( val value: Int, override val level: Int ) : SnailfishNumber { override val magnitude = value override fun asText() = value.toString() override fun increaseLevel(): SnailfishRegular = copy(level = level + 1) override fun reduce() = reduceOnce() override fun reduceOnce() = split() override fun explode() = this override fun split(): SnailfishNumber = if (value < 10) { this } else { SnailfishPair( left = SnailfishRegular( value = floor(value / 2.0).toInt(), level = level + 1 ), right = SnailfishRegular( value = ceil(value / 2.0).toInt(), level = level + 1 ), level = level ) } } fun parseSnailfishNumbers(lines: Iterable<String>): List<SnailfishPair> = lines.map { parseSnailfishNumber(it) } fun parseSnailfishNumber(line: String): SnailfishPair { try { val stack: Deque<SnailfishNumber> = ArrayDeque() var currentLevel = 0 var readingRegular = false for (char in line) { when (char) { '[' -> { currentLevel++ } ']' -> { readingRegular = false currentLevel-- check(stack.size >= 2) { "Stack does not have at least 2 elements" } val right = stack.pop() val left = stack.pop() stack.push(SnailfishPair(left, right, currentLevel)) } ',' -> { readingRegular = false } else -> { val regular = if (readingRegular) { check(stack.peek() is SnailfishRegular) { "Stack does not have regular number at the top" } stack.pop() as SnailfishRegular } else { SnailfishRegular(0, currentLevel) } stack.push(SnailfishRegular(regular.value * 10 + char.digitToInt(), currentLevel)) readingRegular = true } } } check(stack.size == 1) { "Stack does not have exactly 1 element, but ${stack.size}" } check(stack.peek() is SnailfishPair) { "Stack does not have pair at the top" } return stack.first as SnailfishPair } catch (e: Exception) { throw IllegalArgumentException("Could not parse: $line", e) } } fun addAndReduceAll(numbers: Iterable<SnailfishPair>): SnailfishPair = numbers.reduce { a, b -> (a + b).reduce() } fun findMaxPossibleMagnitudeOfTwo(numbers: Iterable<SnailfishPair>): Triple<SnailfishPair, SnailfishPair, Int> = sequence { for (a in numbers) { for (b in numbers) { if (a != b) { yield(a to b) } } } } .map { (a, b) -> Triple(a, b, (a + b).reduce().magnitude) } .sortedByDescending { it.third } .first()
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
15,188
advent-of-code
MIT License
src/main/kotlin/ru/timakden/aoc/year2015/Day03.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2015 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 3: Perfectly Spherical Houses in a Vacuum](https://adventofcode.com/2015/day/3). */ object Day03 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2015/Day03").single() println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: String): Int { var x = 0 var y = 0 return input.map { when (it) { '^' -> y++ 'v' -> y-- '<' -> x-- '>' -> x++ } x to y }.plus(0 to 0).distinct().size } fun part2(input: String): Int { var santaX = 0 var santaY = 0 var robotX = 0 var robotY = 0 var counter = 0 return input.map { val isCounterEven = counter % 2 == 0 when (it) { '^' -> if (isCounterEven) santaY++ else robotY++ 'v' -> if (isCounterEven) santaY-- else robotY-- '<' -> if (isCounterEven) santaX-- else robotX-- '>' -> if (isCounterEven) santaX++ else robotX++ } counter++ if (isCounterEven) santaX to santaY else robotX to robotY }.plus(0 to 0).distinct().size } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
1,447
advent-of-code
MIT License
foundations/merge-sort-with-insertion/Main.kt
ivan-magda
102,283,964
false
null
import java.util.* fun insertionSort(array: Array<Int>) { insertionSort(array, 1, array.lastIndex) } fun insertionSort(array: Array<Int>, start: Int, end: Int) { val startIndex: Int = if (start >= 1) { start } else { 1 } for (i in startIndex..end) { val key = array[i] var j = i - 1 while (j >= 0 && array[j] > key) { array[j + 1] = array[j--] } array[j + 1] = key } } fun mergeSort(array: Array<Int>) { if (!array.isEmpty()) { val threshold = (array.size / 4) + 1 mergeSort(array, Array(array.size, { 0 }), 0, array.lastIndex, threshold) } } fun mergeSort(array: Array<Int>, buffer: Array<Int>, start: Int, end: Int, thresholdForInsertionSort: Int) { if (end - start <= thresholdForInsertionSort) { insertionSort(array, start, end) } else if (start < end) { val middle = start + (end - start) / 2 mergeSort(array, buffer, start, middle, thresholdForInsertionSort) mergeSort(array, buffer, middle + 1, end, thresholdForInsertionSort) merge(array, buffer, start, middle, end) } } fun merge(array: Array<Int>, buffer: Array<Int>, start: Int, middle: Int, end: Int) { val size = end - start + 1 var left = start var right = middle + 1 var copy = start while (left <= middle && right <= end) { if (array[left] <= array[right]) { buffer[copy++] = array[left++] } else { buffer[copy++] = array[right++] } } System.arraycopy(array, left, buffer, copy, middle - left + 1) System.arraycopy(array, right, buffer, copy, end - right + 1) System.arraycopy(buffer, start, array, start, size) } fun main(args: Array<String>) { val array = arrayOf(8, 2, 5, 9, 21, 2, 3, 9, 8, 7, 6, 5, 4, 3, 2, 1, 10, 45, 20, 13, 25, 75, 1) println("Unsorted: ${Arrays.toString(array)}") mergeSort(array) println("Sorted: ${Arrays.toString(array)}") }
0
Kotlin
0
2
da06ec75cbd06c8e158aec86ca813e72bd22a2dc
2,000
introduction-algorithms
MIT License
grind-75-kotlin/src/main/kotlin/ValidPalindrome.kt
Codextor
484,602,390
false
{"Kotlin": 27206}
/** * A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, * it reads the same forward and backward. Alphanumeric characters include letters and numbers. * * Given a string s, return true if it is a palindrome, or false otherwise. * * * * Example 1: * * Input: s = "A man, a plan, a canal: Panama" * Output: true * Explanation: "amanaplanacanalpanama" is a palindrome. * Example 2: * * Input: s = "race a car" * Output: false * Explanation: "raceacar" is not a palindrome. * Example 3: * * Input: s = " " * Output: true * Explanation: s is an empty string "" after removing non-alphanumeric characters. * Since an empty string reads the same forward and backward, it is a palindrome. * * * Constraints: * * 1 <= s.length <= 2 * 105 * s consists only of printable ASCII characters. * @see <a href="https://leetcode.com/problems/valid-palindrome/">LeetCode</a> */ fun isPalindrome(s: String): Boolean { val cleanedString = s.filter { it.isLetterOrDigit() }.lowercase() if (cleanedString.length <= 1) { return true } var startIndex = 0 var endIndex = cleanedString.length - 1 while (startIndex <= endIndex) { if (cleanedString[startIndex] == cleanedString[endIndex]) { startIndex++ endIndex-- } else { return false } } return true }
0
Kotlin
0
0
87aa60c2bf5f6a672de5a9e6800452321172b289
1,445
grind-75
Apache License 2.0
src/questions/GenerateParentheses.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.assertIterableSameInAnyOrder /** * Given `n` pairs of parentheses, write a function to generate all combinations of well-formed parentheses. * * [Source](https://leetcode.com/problems/generate-parentheses/) */ @UseCommentAsDocumentation private fun generateParenthesis(n: Int): List<String> { if (n == 1) return listOf(VALID_PAREN) val result = mutableSetOf<String>() result.add(VALID_PAREN) _generateParens(n, 0, result) return result // contains intermediate values from different iterations .filter { it.length == 2 * n } // remove the intermediate values (these are of length < 2*n) .toList() } private fun _generateParens(n: Int, currentIteration: Int, result: MutableSet<String>) { if (currentIteration > n) { return } HashSet(result) // clone .forEach { result.add(VALID_PAREN + it) // add parens at start result.add(it + VALID_PAREN) // add parens at end for (i in 0..it.length / 2) { val newValue = addPairAfterStartParensAt(it, i) // add parens in the middle result.add(newValue) } } _generateParens(n, currentIteration + 1, result) } private fun addPairAfterStartParensAt(str: String, startIndexOffset: Int): String { val occurrenceOfStartParen = str.indexOf('(', startIndex = startIndexOffset) return str.substring(0, occurrenceOfStartParen + 1) .plus(VALID_PAREN) .plus(str.substring(occurrenceOfStartParen + 1)) } private const val VALID_PAREN = "()" fun main() { assertIterableSameInAnyOrder( listOf("((()))", "(()())", "(())()", "()(())", "()()()"), generateParenthesis(3), ) assertIterableSameInAnyOrder( listOf("()()", "(())"), generateParenthesis(2), ) assertIterableSameInAnyOrder( actual = generateParenthesis(1), expected = listOf("()") ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,065
algorithms
MIT License
src/main/kotlin/day9/Day9.kt
stoerti
726,442,865
false
{"Kotlin": 19680}
package io.github.stoerti.aoc.day9 import io.github.stoerti.aoc.IOUtils import io.github.stoerti.aoc.MathUtils import io.github.stoerti.aoc.StringExt.longValues import kotlin.math.abs fun main(args: Array<String>) { val lines = IOUtils.readInput("day_9_input").map { it.longValues() } val result1 = lines.sumOf { part1(it) } val result2 = lines.sumOf { part2(it) } println("Result1: $result1") println("Result2: $result2") } fun part1(numbers: List<Long>): Long { val lines = mutableListOf(numbers) while (!lines.last().onlyZeros()) { lines.last().let { line -> lines.add(line.mapIndexedNotNull { i, it -> if (i >= line.size - 1) null else (line[i + 1] - it) }) } } return lines.sumOf { it.last() } } fun part2(numbers: List<Long>): Long { val lines = mutableListOf(numbers) while (!lines.last().onlyZeros()) { lines.last().let { line -> lines.add(line.mapIndexedNotNull { i, it -> if (i >= line.size - 1) null else (line[i + 1] - it) }) } } var result = 0L lines.reversed().forEach { result = it.first() - result } return result } fun List<Long>.onlyZeros(): Boolean = this.none { it != 0L }
0
Kotlin
0
0
05668206293c4c51138bfa61ac64073de174e1b0
1,212
advent-of-code
Apache License 2.0
src/main/kotlin/days/aoc2021/Day1.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2021 import days.Day class Day1 : Day(2021, 1) { override fun partOne(): Any { return countIncreasingPairs(inputList.map { it.toInt() }) } fun countIncreasingPairs(list: List<Int>): Int { return pairs(list) .filter { pair -> pair.first < pair.second } .count() } override fun partTwo(): Any { return countIncreasingTriples(inputList.map { it.toInt() }) } fun countIncreasingTriples(list: List<Int>): Int { val sums = triples(list) .map { it.first + it.second + it.third } return countIncreasingPairs(sums.toList()) } private fun pairs(list: List<Int>): Sequence<Pair<Int,Int>> = sequence { for (i in list.indices) if (i < list.size - 1) yield(Pair(list[i], list[i+1])) } private fun triples(list: List<Int>): Sequence<Triple<Int,Int,Int>> = sequence { for (i in list.indices) if (i < list.size - 2) yield(Triple(list[i], list[i+1], list[i+2])) } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
1,067
Advent-Of-Code
Creative Commons Zero v1.0 Universal
leetcode/src/offer/Offer012.kt
zhangweizhe
387,808,774
false
null
package offer fun main() { // https://leetcode-cn.com/problems/tvdfij/ // 剑指 Offer II 012. 左右两边子数组的和相等 println(pivotIndex1(intArrayOf(1,7,3,6,5,6))) } private fun pivotIndex(nums: IntArray): Int { val leftSums = IntArray(nums.size) val rightSums = IntArray(nums.size) leftSums[0] = nums[0] rightSums[nums.size - 1] = nums[nums.size - 1] for (i in 1 until nums.size) { leftSums[i] = leftSums[i-1] + nums[i] rightSums[nums.size - i - 1] = rightSums[nums.size - i] + nums[nums.size - i - 1] } for (i in nums.indices) { if (leftSums[i] == rightSums[i]) { return i } } return -1 } private fun pivotIndex1(nums: IntArray): Int { val total = nums.sum() var sum = 0 for (i in nums.indices) { if (2 * sum + nums[i] == total) { return i } sum += nums[i] } return -1 }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
944
kotlin-study
MIT License
src/main/kotlin/day01/Day01.kt
dustinconrad
572,737,903
false
{"Kotlin": 100547}
package day01 import byEmptyLines import readResourceAsBufferedReader import java.util.PriorityQueue fun main() { println("part 1: ${part1(readResourceAsBufferedReader("1_1.txt").readLines())}") println("part 2: ${part2(readResourceAsBufferedReader("1_1.txt").readLines())}") } fun parseElf(elf: String): Elf { return Elf(elf.lines().map { it.toInt() }) } fun part1(input: List<String>): Int { return input.byEmptyLines() .map { parseElf(it) } .topN(1, Comparator.comparing { it.calories }) .sumOf { it.calories } } fun part2(input: List<String>): Int { return input.byEmptyLines() .map { parseElf(it) } .topN(3, Comparator.comparing { it.calories }) .sumOf { it.calories } } fun <T> Collection<T>.topN(n: Int, comp: Comparator<T>): Collection<T> { check(n > 0) { "$n must be greater than 0" } val minHeap = PriorityQueue(comp) for (item in this) { if (minHeap.size < n) { minHeap.add(item) } else { val min = minHeap.peek()!! if (comp.compare(item, min) > 0) { minHeap.remove() minHeap.offer(item) } } } return minHeap } data class Elf( val food: List<Int> ) { val calories = food.sum() }
0
Kotlin
0
0
1dae6d2790d7605ac3643356b207b36a34ad38be
1,298
aoc-2022
Apache License 2.0
src/main/kotlin/day09/Day09.kt
vitalir2
572,865,549
false
{"Kotlin": 89962}
package day09 import Challenge import utils.Coordinates import kotlin.math.absoluteValue import kotlin.math.sign object Day09 : Challenge(9) { override fun part1(input: List<String>): Any { return modelRopeMovement(input, ROPE_LENGTH_PART_1) } override fun part2(input: List<String>): Any { return modelRopeMovement(input, ROPE_LENGTH_PART_2) } private fun modelRopeMovement(input: List<String>, ropeLength: Int): Int { val rope = List(ropeLength - 1) { Coordinates(0, 0) }.toMutableList() // last - tail var headCoordinates = rope.first() val tailCoordinatesHistory = mutableSetOf(rope.last()) for (command in input) { val splitCommand = command.split(" ") val direction = splitCommand[0].toCharArray().first() val steps = splitCommand[1].toInt() repeat(steps) { when (direction) { 'R' -> headCoordinates = headCoordinates.moveRight() 'D' -> headCoordinates = headCoordinates.moveDown() 'L' -> headCoordinates = headCoordinates.moveLeft() 'U' -> headCoordinates = headCoordinates.moveUp() } for (ropePartIndex in rope.indices) { var ropePart = rope[ropePartIndex] val previousRopePart = rope.getOrElse(ropePartIndex-1) { headCoordinates } ropePart = ropePart moveToTouch previousRopePart if (ropePartIndex == rope.lastIndex) { tailCoordinatesHistory.add(ropePart) } rope[ropePartIndex] = ropePart } } } return tailCoordinatesHistory.count() } private infix fun Coordinates.moveToTouch(other: Coordinates): Coordinates { return when { this == other || this adjacentTo other -> this else -> { val coordinatesDiff = other - this // not adjacent => on the same row or column when (coordinatesDiff.x.absoluteValue + coordinatesDiff.y.absoluteValue) { 2 -> this.copy(x = x + coordinatesDiff.x / 2, y = y + coordinatesDiff.y / 2) else -> this.copy(x = x + coordinatesDiff.x.sign, y = y + coordinatesDiff.y.sign) } } } } private const val ROPE_LENGTH_PART_1 = 2 private const val ROPE_LENGTH_PART_2 = 10 }
0
Kotlin
0
0
ceffb6d4488d3a0e82a45cab3cbc559a2060d8e6
2,517
AdventOfCode2022
Apache License 2.0
src/y2022/Day09.kt
Yg0R2
433,731,745
false
null
package y2022 import DayX import y2022.Day09.Direction.D import y2022.Day09.Direction.L import y2022.Day09.Direction.R import y2022.Day09.Direction.U import kotlin.math.abs class Day09 : DayX<Int>(listOf(13), listOf(1, 36)) { override fun part1(input: List<String>): Int { val rope = Rope(2) input.initSteps() .forEach { rope.move(it.first, it.second) } return rope.tailCoordinates.size } override fun part2(input: List<String>): Int { val rope = Rope(10) input.initSteps() .forEach { rope.move(it.first, it.second) } return rope.tailCoordinates.size } companion object { private fun List<String>.initSteps(): List<Pair<Direction, Int>> = map { Direction.valueOf(it[0].toString()) to it.substring(2).toInt() } } private data class Knot( val x: Int, val y: Int ) private enum class Direction { L, R, U, D } private class Rope( length: Int ) { private val knots: MutableList<Knot> = MutableList(length) { Knot(0, 0) } val tailCoordinates: MutableSet<Knot> = mutableSetOf<Knot>() .also { it.add(knots[knots.size - 1]) } fun move(direction: Direction, amount: Int) { IntRange(1, amount).forEach { _ -> moveHead(direction) moveTail() tailCoordinates.add(knots[knots.size - 1]) } } private fun getTailDirection(diff: Int) = if (diff == 0) { 0 } else if (diff < 0) { 1 } else { -1 } private fun moveHead(direction: Direction) { knots[0] = with(knots[0]) { when (direction) { L -> { copy(x = x - 1) } R -> { copy(x = x + 1) } U -> { copy(y = y - 1) } D -> { copy(y = y + 1) } } } } private fun moveTail() { IntRange(1, knots.size - 1).forEach { if (tailHasToMove(it)) { knots[it] = with(knots[it]) { copy( x = x + getTailDirection(x - knots[it - 1].x), y = y + getTailDirection(y - knots[it - 1].y) ) } } } } private fun tailHasToMove(currentIndex: Int): Boolean = (abs(knots[currentIndex].x - knots[currentIndex - 1].x) == 2) || (abs(knots[currentIndex].y - knots[currentIndex - 1].y) == 2) } }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
2,914
advent-of-code
Apache License 2.0