path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/g2801_2900/s2866_beautiful_towers_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2801_2900.s2866_beautiful_towers_ii // #Medium #Array #Stack #Monotonic_Stack #2023_12_21_Time_676_ms_(85.71%)_Space_70.9_MB_(71.43%) import java.util.Deque import java.util.LinkedList import kotlin.math.max class Solution { fun maximumSumOfHeights(mH: List<Int>): Long { val n = mH.size val st: Deque<Int> = LinkedList() val prevSmaller = IntArray(n + 1) for (i in 0 until n) { while (st.isNotEmpty() && mH[st.peek()] >= mH[i]) { st.pop() } if (st.isEmpty()) { prevSmaller[i] = -1 } else { prevSmaller[i] = st.peek() } st.push(i) } st.clear() val nextSmaller = IntArray(n + 1) for (i in n - 1 downTo 0) { while (st.isNotEmpty() && mH[st.peek()] >= mH[i]) { st.pop() } if (st.isEmpty()) { nextSmaller[i] = n } else { nextSmaller[i] = st.peek() } st.push(i) } val leftSum = LongArray(n) leftSum[0] = mH[0].toLong() for (i in 1 until n) { val prevSmallerIdx = prevSmaller[i] val equalCount = i - prevSmallerIdx leftSum[i] = (equalCount.toLong() * mH[i]) if (prevSmallerIdx != -1) { leftSum[i] += leftSum[prevSmallerIdx] } } val rightSum = LongArray(n) rightSum[n - 1] = mH[n - 1].toLong() for (i in n - 2 downTo 0) { val nextSmallerIdx = nextSmaller[i] val equalCount = nextSmallerIdx - i rightSum[i] = (equalCount.toLong() * mH[i]) if (nextSmallerIdx != n) { rightSum[i] += rightSum[nextSmallerIdx] } } var ans: Long = 0 for (i in 0 until n) { val totalSum = leftSum[i] + rightSum[i] - mH[i] ans = max(ans, totalSum) } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,037
LeetCode-in-Kotlin
MIT License
dcp_kotlin/src/main/kotlin/dcp/day255/day255.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day255 // day255.kt // By <NAME>, 2020. typealias Vertex = Int typealias AdjacencyList = Set<Vertex> typealias AdjacencyGraph = Map<Vertex, AdjacencyList> typealias AdjacencyMatrix = List<List<Vertex>> /** * Convert an adjacency graph into an adjacency matrix. */ fun adjacencyGraphToMatrix(adjacencyGraph: AdjacencyGraph): AdjacencyMatrix { if (adjacencyGraph.isEmpty()) return emptyList() // We want the vertices to be {0, ..., n-1}. val vertices = (adjacencyGraph.keys + adjacencyGraph.values.flatten()).toList().sorted() require(vertices == vertices.indices.toList()) fun row(vertex: Vertex): List<Vertex> { val adjacencyList: AdjacencyList = adjacencyGraph[vertex] ?: emptySet() return vertices.map { if (it in adjacencyList) 1 else 0 } } return vertices.map(::row) } /** * Given an adjacency matrix, find its transitive closure, represented again by an adjacency matrix. */ fun findTransitiveClosures(adjacencyMatrix: AdjacencyMatrix): AdjacencyMatrix { if (adjacencyMatrix.isEmpty()) return emptyList() // We'll use the Floyd Warshall Algorithm for this, which lends itself poorly to functional programming and // immutable data structures, unfortunately, so start by making a mutable copy of adjacencyMatrix. val matrix: MutableList<MutableList<Vertex>> = adjacencyMatrix.map{ it.toMutableList() }.toMutableList() val n: Int = matrix.size (0 until n).forEach { k -> (0 until n).forEach { i -> (0 until n).forEach { j -> if (matrix[i][k] == 1 && matrix[k][j] == 1) matrix[i][j] = 1 } } } return matrix }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
1,696
daily-coding-problem
MIT License
src/main/kotlin/com/groundsfam/advent/y2022/d04/Day04.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2022.d04 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines fun redundantPair(pair: List<Int>): Boolean = (pair[0] <= pair[2] && pair[1] >= pair[3]) || (pair[2] <= pair[0] && pair[3] >= pair[1]) fun overlappingPair(pair: List<Int>): Boolean = (pair[1] >= pair[2] && pair[0] <= pair[3]) || (pair[3] >= pair[0] && pair[2] <= pair[1]) fun main() = timed { // Pairs is a list of lists of ints. Each pair is a list of precisely four ints val pairs = (DATAPATH / "2022/day04.txt").useLines { lines -> lines.toList().map { line -> val (first, second) = line.split(',') first.split('-').map { it.toInt() } + second.split('-').map { it.toInt() } } } pairs.count(::redundantPair) .also { println("Redundant pairs: $it") } pairs.count(::overlappingPair) .also { println("Overlapping pairs: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
990
advent-of-code
MIT License
src/main/java/com/carson/commands/Chain.kt
Mee42
152,824,065
false
null
package com.carson.commands import com.carson.core.Main import java.lang.StringBuilder import java.util.* class Chain{ private val map :MutableMap<String,MutableList<String>> = mutableMapOf() /** feeds another message into the chain */ fun feed(input: String) { if(input.startsWith("!"))return if(input.startsWith(Main.PREFIX))return if(input.contains(START) || input.contains(END))return if(input.isBlank())return val list :List<String> = ("$START $input $END").split(" ").filter { it.isNotBlank() } for(i in 1 until list.size){ if(!map.containsKey(list[i-1])) map[list[i-1]] = mutableListOf() map[list[i-1]]!!+=list[i] } } fun generateSentenceChecked() :String{ var str :String var i = 0//forever blocking calls won't block forever do{ i++ str = generateSentence() }while(i < 100 && !isSentenceValid(str)) return str } private fun generateSentence() :String{ val str = mutableListOf<String>() str+= START while(!str.isEmpty() && str.last() != END){ val mapPos = str.last() if(map[mapPos] == null){ str+= END break } //hopefully makes longer sentences str+= (if(str.size <= 2) map[mapPos]!!.filter { it != END } else map[mapPos]!!).random() ?: END } str.removeIf { it == END || it == START } return str.fold("") {fold,one -> "$fold $one"}.trim() } override fun toString(): String { val b = StringBuilder() map.forEach { s,l -> b.append('[').append(s).append("] : ").append(Arrays.toString(l.toTypedArray())).append('\n') } return b.toString() } /** * This returns a copy of the map and is therefore extremely slow. * Use only if needed */ fun getMap(): Map<String, List<String>> { val map :MutableMap<String,List<String>> = mutableMapOf() map.putAll(this.map.map { Pair(it.key,it.value.map { w -> w }) }) return map.toMap() } } fun <T> List<T>.random() :T? = if(size == 0) null else this[(Math.random()*size).toInt()] const val VALID = "!VALID!" fun isSentenceValid(str :String):Boolean = isSentenceValidString(str) == VALID fun isSentenceValidString(str :String) :String{ val split = str.split(" ").map { it.trim() } // var i = 0 // split.forEach { println("${i++} : \"${it.replace("\n","\\n")}\"") } if(str.toCharArray().count { it == ' '} < 2) return "Too little words" if(split.distinct().size <= split.size / 2) return "Too many duplicates" //if more then half the words are duplicates if(split.count { it[0] == ':' && it[it.length - 1] == ':' } > split.size - 2) return "Too many emojis" //if less than two words are real words if(split.count { it.length == 1 } > split.size - 2) return "Too many one-letter words" //if the count of single-letter words makes up length-2 of the sentence if(str.contains("`"))return "Can't include backticks" return VALID }
0
Kotlin
0
0
f68dcf2091edf6429b70c89fa537eef526d83939
3,147
community-bot
The Unlicense
src/Day03.kt
mvmlisb
572,859,923
false
{"Kotlin": 14994}
private val Priorities = (('a'.code..'z'.code) + ('A'.code..'Z'.code)) .mapIndexed { charIndex, charCode -> charCode to charIndex + 1 }.toMap() private fun findCommonChar(strings: List<String>) = strings.first().first { char -> strings.drop(1).all { string -> string.contains(char) } } fun main() { val input = readInput("Day03_test") val part1 = input.sumOf { Priorities[findCommonChar(it.chunked(it.length / 2)).code] ?: 0 } val part2 = input.chunked(3).sumOf { Priorities[findCommonChar(it).code] ?: 0 } println(part1) println(part2) }
0
Kotlin
0
0
648d594ec0d3b2e41a435b4473b6e6eb26e81833
596
advent_of_code_2022
Apache License 2.0
src/main/kotlin/g1401_1500/s1494_parallel_courses_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1494_parallel_courses_ii // #Hard #Dynamic_Programming #Bit_Manipulation #Graph #Bitmask // #2023_06_13_Time_381_ms_(100.00%)_Space_37_MB_(100.00%) class Solution { fun minNumberOfSemesters(n: Int, relations: Array<IntArray>, k: Int): Int { val pres = IntArray(n) for (r in relations) { val prev = r[0] - 1 val next = r[1] - 1 pres[next] = pres[next] or (1 shl prev) } val dp = IntArray(1 shl n) dp.fill(n) dp[0] = 0 for (mask in dp.indices) { var canTake = 0 for (i in 0 until n) { // already taken if (mask and (1 shl i) != 0) { continue } // satisfy all pres if (mask and pres[i] == pres[i]) { canTake = canTake or (1 shl i) } } // loop each sub-masks var take = canTake while (take > 0) { if (Integer.bitCount(take) > k) { take = take - 1 and canTake continue } dp[take or mask] = Math.min(dp[take or mask], dp[mask] + 1) take = take - 1 and canTake } } return dp[(1 shl n) - 1] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,349
LeetCode-in-Kotlin
MIT License
2022/src/main/kotlin/sh/weller/aoc/Day04.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.aoc object Day04 : SomeDay<String, Int> { override fun partOne(input: List<String>): Int = input .map { inputString -> val sections = inputString.split(",") val firstValues = sections.first().split("-").map { it.toInt() } val secondValues = sections.last().split("-").map { it.toInt() } firstValues to secondValues } .map { (firstValues, secondValues) -> firstValues.first() <= secondValues.first() && firstValues.last() >= secondValues.last() || secondValues.first() <= firstValues.first() && secondValues.last() >= firstValues.last() } .count { it } override fun partTwo(input: List<String>): Int = input .map { inputString -> val sections = inputString.split(",") val firstValues = sections.first().split("-").map { it.toInt() } val secondValues = sections.last().split("-").map { it.toInt() } firstValues to secondValues } .map { (firstValues, secondValues) -> val firstRange = IntRange(firstValues.first(), firstValues.last()).toSet() val secondRange = IntRange(secondValues.first(), secondValues.last()).toSet() firstRange.intersect(secondRange).isNotEmpty() } .count { it } }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
1,463
AdventOfCode
MIT License
src/Day04.kt
spaikmos
573,196,976
false
{"Kotlin": 83036}
fun main() { fun part1(input: List<String>): Int { var num = 0 for (i in input) { var parts = i.split(",", "-").map{it.toInt()}.toTypedArray() if ((parts[0] <= parts[2]) && (parts[1] >= parts[3])) { num++ } else if ((parts[2] <= parts[0]) && (parts[3] >= parts[1])) { num++ } } return num } fun part2(input: List<String>): Int { var num = 0 for (i in input) { var parts = i.split(",", "-").map{it.toInt()}.toTypedArray() if ((parts[0] <= parts[3]) && (parts[1] >= parts[2])) { num++ } } return num } val input = readInput("../input/Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6fee01bbab667f004c86024164c2acbb11566460
812
aoc-2022
Apache License 2.0
src/main/kotlin/ru/byprogminer/compmath/lab4/math/LagrangeMethod.kt
ProgMiner
242,443,008
false
null
package ru.byprogminer.compmath.lab4.math import ru.byprogminer.compmath.lab4.expression.Expression import ru.byprogminer.compmath.lab4.expression.InvalidExpression import ru.byprogminer.compmath.lab5.util.toPlainString object LagrangeMethod: InterpolationMethod { override fun interpolate(expression: Expression, points: Set<Double>): Expression { if (expression.variables.size != 1 || points.size < 2) { return InvalidExpression("") } val pointList = points.toList() val variable = expression.variables.first() val values = pointList.map { x -> expression.evaluate(mapOf(variable to x)) } return LagrangePolynomial(pointList, values, variable) } override fun interpolate(points: Map<Double, Double>, variable: String): Expression { val pointList = points.keys.toList() val values = pointList.map(points::getValue) return LagrangePolynomial(pointList, values, variable) } private class LagrangePolynomial( private val points: List<Double>, private val values: List<Double>, variable: String ): Expression { override val isValid = true override val variables = setOf(variable) private val view by lazy { val f = values.map { it.toPlainString() } val x = points.map { it.toPlainString() } return@lazy f.indices.joinToString(" + ") { i -> "${f[i]} * " + x.indices .filter { j -> j != i }.joinToString(" * ") { j -> "(x - ${x[j]}) / (${x[i]} - ${x[j]})" } } } private val denominators: List<Double> init { denominators = this.values.indices.map { i -> points.indices.filter { j -> j != i } .map { j -> points[i] - points[j] } .reduce { a, b -> a * b } } } override fun evaluate(values: Map<String, Double>): Double { val x = values.getValue(variables.first()) return this.values.mapIndexed { i, f -> f * points.indices .filter { j -> j != i }.map { j -> (x - points[j]) } .reduce { a, b -> a * b } / denominators[i] }.sum() } override fun toString() = view } }
0
Kotlin
0
1
201b562e7e07961c695ed4d09ad0b381281f6d10
2,366
Lab_CompMath
MIT License
advent10/src/main/kotlin/Main.kt
thastreet
574,294,123
false
{"Kotlin": 29380}
import java.io.File import java.lang.IllegalArgumentException import java.util.Stack sealed interface Instruction { val cycles: Int } object Noop : Instruction { override val cycles = 1 } data class Add(val value: Int) : Instruction { override val cycles = 2 } fun main(args: Array<String>) { val lines = File("input.txt").readLines() val instructions = parseInstructions(lines) val part1Answer = part1(instructions) println("part1Answer: $part1Answer") val part2Answer = part2(instructions) println("part2Answer: $part2Answer") } fun parseInstructions(lines: List<String>): List<Instruction> = lines.map { line -> val parts = line.split(" ") when (parts[0]) { "noop" -> Noop "addx" -> Add(parts[1].toInt()) else -> throw IllegalArgumentException("Unknown instruction: ${parts[0]}") } } fun part1(instructions: List<Instruction>): Int { val positions = getPositions(instructions) val strengthCycles = listOf(20, 60, 100, 140, 180, 220) return strengthCycles.sumOf { it * positions[it - 1] } } fun part2(instructions: List<Instruction>): String { val positions = getPositions(instructions) positions.forEachIndexed { index, x -> if (index % 40 in x - 1..x + 1) { print("#") } else { print(".") } if ((index + 1) % 40 == 0) { println() } } return "ECZUZALR" } fun getPositions(instructions: List<Instruction>): List<Int> { val stack = Stack<Instruction>() instructions.reversed().forEach { stack.push(it) } var x = 1 val positions = mutableListOf<Int>() var instructionCycle = 1 var ended = false var executionBlock: (() -> Unit)? = null var executeAt = 1 do { if (instructionCycle == executeAt && stack.isNotEmpty()) { val instruction = stack.pop() executeAt = instructionCycle + instruction.cycles when (instruction) { is Add -> { executionBlock = { x += instruction.value } } else -> { executionBlock = null } } } if (instructionCycle == executeAt && stack.isEmpty()) { ended = true } else { positions.add(x) } ++instructionCycle if (instructionCycle == executeAt && executionBlock != null) { executionBlock() } } while (!ended) return positions }
0
Kotlin
0
0
e296de7db91dba0b44453601fa2b1696af9dbb15
2,585
advent-of-code-2022
Apache License 2.0
src/test/kotlin/ch/ranil/aoc/aoc2023/Day13.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day13 : AbstractDay() { @Test fun part1Test() { assertEquals(405, compute1(testInput)) } @Test fun part1Test2() { assertEquals( 1400, compute1( """ #....#.## ...##.#.# ###..#... #....#.## ######... ..##.##.. ..#...#.# ..#...#.# ..##.##.. ######... #....#.## ###..#... ...##.#.# #...##.## #...##.## """.trimIndent().lines(), ), ) } @Test fun part1Puzzle() { assertEquals(37381, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(0, compute2(testInput)) } @Test fun part2Puzzle() { assertEquals(0, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { return splitPatterns(input) .sumOf { pattern -> val reflectionPoint = pattern.findReflectionPoint() reflectionPoint } } private fun Pattern.findReflectionPoint(): Int { fun isReflectionPointCorrect(reflectionPoint: Int, lines: List<String>): Boolean { // check outwards to see if everything reflects var i = 1 while (reflectionPoint - i >= 0 && reflectionPoint + i + 1 < lines.size) { val q1 = lines[reflectionPoint - i] val q2 = lines[reflectionPoint + i + 1] if (q1 != q2) return false // not a perfect reflection i++ } return true } fun scan(lines: List<String>): Int { var reflectionPoint = 0 while (reflectionPoint + 1 < lines.size) { val p1 = lines[reflectionPoint] val p2 = lines[reflectionPoint + 1] if (p1 == p2) { if (isReflectionPointCorrect(reflectionPoint, lines)) { return reflectionPoint + 1 } } reflectionPoint++ } return 0 } // scan horizontally val horizontalReflection = scan(this) if (horizontalReflection > 0) return horizontalReflection * 100 val verticalReflection = scan(this.columns()) if (verticalReflection > 0) return verticalReflection println("No reflection found in pattern:\n${this.joinToString("\n")}") return 0 } fun compute2(input: List<String>): Long { TODO() } private fun splitPatterns(input: List<String>): List<Pattern> { val patterns = mutableListOf<List<String>>() var i = 0 while (i < input.size) { val pattern = input .drop(i) .takeWhile { it.isNotBlank() } patterns += pattern i += pattern.size + 1 } return patterns } } private typealias Pattern = List<String> private fun Pattern.columns(): List<String> { val columns = mutableListOf<String>() for (i in this.first().indices) { columns += this.joinToString("") { it[i].toString() } } return columns }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
3,425
aoc
Apache License 2.0
src/Day02.kt
monsterbrain
572,819,542
false
{"Kotlin": 42040}
enum class SHAPE(val score: Int, val oppCode: Char, val ourCode:Char) { ROCK(1, 'A', 'X'), PAPER(2, 'B', 'Y'), SCISSORS(3, 'C', 'Z'); companion object { fun getOppShape(code: Char): SHAPE { return when (code) { ROCK.oppCode -> ROCK PAPER.oppCode -> PAPER SCISSORS.oppCode -> SCISSORS else -> TODO() } } fun getOurShape(code: Char): SHAPE { return when (code) { ROCK.ourCode -> ROCK PAPER.ourCode -> PAPER SCISSORS.ourCode -> SCISSORS else -> TODO() } } } } enum class GAMESTATE(val score: Int) { LOSE(0), DRAW(3), WIN(6) } val endStateMap = mapOf( 'X' to GAMESTATE.LOSE, 'Y' to GAMESTATE.DRAW, 'Z' to GAMESTATE.WIN ) fun main() { fun getGameState(oppShape: SHAPE, ourShape: SHAPE): GAMESTATE { return when (oppShape) { SHAPE.ROCK -> when (ourShape) { SHAPE.ROCK -> GAMESTATE.DRAW SHAPE.PAPER -> GAMESTATE.WIN SHAPE.SCISSORS -> GAMESTATE.LOSE } SHAPE.PAPER -> when (ourShape) { SHAPE.ROCK -> GAMESTATE.LOSE SHAPE.PAPER -> GAMESTATE.DRAW SHAPE.SCISSORS -> GAMESTATE.WIN } SHAPE.SCISSORS -> when (ourShape) { SHAPE.ROCK -> GAMESTATE.WIN SHAPE.PAPER -> GAMESTATE.LOSE SHAPE.SCISSORS -> GAMESTATE.DRAW } } } fun part1(input: List<String>): Int { var totalScore = 0 input.forEach { val oppShape = it[0] val ourShape = it[2] val gameState = getGameState(SHAPE.getOppShape(oppShape), SHAPE.getOurShape(ourShape)) totalScore += gameState.score + SHAPE.getOurShape(ourShape).score } return totalScore } fun getOurShapeForState(oppShape: SHAPE, endState: GAMESTATE): SHAPE { return when (endState) { GAMESTATE.LOSE -> when (oppShape) { SHAPE.ROCK -> SHAPE.SCISSORS SHAPE.PAPER -> SHAPE.ROCK SHAPE.SCISSORS -> SHAPE.PAPER } GAMESTATE.DRAW -> when (oppShape) { SHAPE.ROCK -> SHAPE.ROCK SHAPE.PAPER -> SHAPE.PAPER SHAPE.SCISSORS -> SHAPE.SCISSORS } GAMESTATE.WIN -> when (oppShape) { SHAPE.ROCK -> SHAPE.PAPER SHAPE.PAPER -> SHAPE.SCISSORS SHAPE.SCISSORS -> SHAPE.ROCK } } } fun part2(input: List<String>): Int { var totalScore = 0 input.forEach { val oppShape = it[0] val gameEndStatusCode = it[2] val endState = endStateMap[gameEndStatusCode] ?: TODO() totalScore += endState.score val getOurShapeForState = getOurShapeForState(SHAPE.getOppShape(oppShape), endState) totalScore += getOurShapeForState.score } return totalScore } // test if implementation meets criteria from the description, like: /*val testInput = readInput("Day01_test") check(part1MostCalories(testInput) == 1)*/ val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3a1e8615453dd54ca7c4312417afaa45379ecf6b
3,418
advent-of-code-kotlin-2022-Solutions
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2021/day25/Seafloor.kt
michaelbull
433,565,311
false
{"Kotlin": 162839}
package com.github.michaelbull.advent2021.day25 import com.github.michaelbull.advent2021.math.Vector2 fun Sequence<String>.toSeafloor(): Seafloor { val cells = buildMap { for ((y, line) in this@toSeafloor.withIndex()) { for ((x, char) in line.withIndex()) { this[Vector2(x, y)] = char.toSeaCucumber() } } } return Seafloor(cells) } data class Seafloor( val cells: Map<Vector2, SeaCucumber> ) { private val xMin = cells.keys.minOf(Vector2::x) private val xMax = cells.keys.maxOf(Vector2::x) private val yMin = cells.keys.minOf(Vector2::y) private val yMax = cells.keys.maxOf(Vector2::y) private val start = Vector2(xMin, yMin) private val endInclusive = Vector2(xMax, yMax) private val range = start..endInclusive fun step(): Seafloor? { var result = cells var moved = false for ((cucumber, offset) in MOVEMENTS) { val next = result.toMutableMap() for (position in range) { val nextPosition = (position + offset) % range if (result[position] == cucumber && result[nextPosition] == SeaCucumber.Empty) { next[position] = SeaCucumber.Empty next[nextPosition] = cucumber moved = true } } result = next } return if (moved) { copy(cells = result) } else { null } } fun stepSequence(): Sequence<Seafloor> { return generateSequence(this, Seafloor::step) } private companion object { private val MOVEMENTS = listOf( Movement(SeaCucumber.East, Vector2(x = 1)), Movement(SeaCucumber.South, Vector2(y = 1)), ) } }
0
Kotlin
0
4
7cec2ac03705da007f227306ceb0e87f302e2e54
1,824
advent-2021
ISC License
day03/Kotlin/day03.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* fun print_day_3() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 3" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Binary Diagnostic -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_3() Day3().part_1() Day3().part_2() println("\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day3 { val lines = File("../Input/day3.txt").readLines() fun part_1() { val matrix = lines.map { s -> s.toCharArray().map { c -> c.digitToInt() } } var gamma = "" var epsilon = "" for(idx in matrix[0].indices) { val res = matrix.partition { it[idx] == 1 } gamma += if (res.first.count() > res.second.count()) "1" else "0" epsilon += if (res.first.count() > res.second.count()) "0" else "1" } val answer = gamma.toInt(2) * epsilon.toInt(2) println("Puzzle 1: " + answer) } fun part_2() { fun splitAndRecurse(list: List<List<Int>>, index: Int, max: Boolean) : List<Int> { if (list.size == 1) return list[0] val res = list.partition { it[index] == 1 } val keep = if (res.first.count() >= res.second.count()) if (max) res.first else res.second else if (max) res.second else res.first return splitAndRecurse(keep, index+1, max) } val matrix = lines.map { s -> s.toCharArray().map { c -> c.digitToInt() } } val oxygen = splitAndRecurse(matrix, 0, true) val co2 = splitAndRecurse(matrix, 0, false) val oxygenDecimal = oxygen.joinToString("").toInt(2) val co2Decimal = co2.joinToString("").toInt(2) println("Puzzle 2: " + oxygenDecimal * co2Decimal +"\n") } }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
2,138
AOC2021
Apache License 2.0
src/main/kotlin/g1001_1100/s1012_numbers_with_repeated_digits/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1001_1100.s1012_numbers_with_repeated_digits // #Hard #Dynamic_Programming #Math #2023_05_16_Time_123_ms_(100.00%)_Space_34_MB_(33.33%) import kotlin.math.pow class Solution { private var noRepeatCount = 0 fun numDupDigitsAtMostN(n: Int): Int { val nStrLength = n.toString().length val allNineLength: Int = if (n < 0 || nStrLength < 2) { return 0 } else if (10.0.pow(nStrLength.toDouble()) - 1 == n.toDouble()) { nStrLength } else { nStrLength - 1 } for (numberOfDigits in 1..allNineLength) { noRepeatCount += calcNumberOfNoRepeat(numberOfDigits) } if (10.0.pow(nStrLength.toDouble()) - 1 > n) { val mutations = 10 val hs: HashSet<Int> = HashSet() for (index1 in 0 until nStrLength) { var noRepeatCountLocal = 0 hs.clear() for (index2 in 0 until nStrLength) { val index2Digit = ( n / 10.0.pow(n.toString().length - (index2 + 1.0)) % 10 ).toInt() if (index2 < index1) { if (hs.contains(index2Digit)) { noRepeatCountLocal = 0 break } else { hs.add(index2Digit) } } else if (index2 == index1) { noRepeatCountLocal = if (index2 == 0) { index2Digit - 1 } else { var inIndex2Range = 0 for (j in hs) { if (index2 < nStrLength - 1 && j <= index2Digit - 1 || index2 == nStrLength - 1 && j <= index2Digit ) { inIndex2Range++ } } if (index2 == nStrLength - 1) { index2Digit + 1 - inIndex2Range } else { index2Digit - inIndex2Range } } } else { noRepeatCountLocal *= mutations - index2 } } if (noRepeatCountLocal > 0) { noRepeatCount += noRepeatCountLocal } } } return n - noRepeatCount } private fun calcNumberOfNoRepeat(numberOfDigits: Int): Int { var repeatCount = 0 var mutations = 9 for (i in 0 until numberOfDigits) { if (i == 0) { repeatCount = mutations } else { repeatCount *= mutations-- } } return repeatCount } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,030
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/ikueb/advent18/Day15.kt
h-j-k
159,901,179
false
null
package com.ikueb.advent18 import com.ikueb.advent18.model.* import java.util.* object Day15 { fun getBattleOutcome(input: List<String>) = battle(input) fun getModifiedBattleOutcome(input: List<String>) = generateSequence(4) { it + 1 } .map { elfPowerUp -> battle(input, elfPowerUp) { players -> players.any { !it.isActive() && it.role == Role.ELF } } }.first { it > 0 } private fun battle(input: List<String>, elfPowerUp: Int? = null, isEarlyTermination: (Players) -> Boolean = { false }): Int { val state: Cave = input.asInputMap(getPlayers(), getCaveMap()) val players = state.getTokens() elfPowerUp?.let { powerUp -> players.filter { it.role == Role.ELF }.forEach { it.attack = powerUp } } var completedRounds = 0 while (players.gameContinues()) { if (isEarlyTermination(players)) { return 0 } var isCompleteRound = true for (player in players.activeAndSorted()) { if (!players.gameContinues()) { isCompleteRound = false break } var target = players.getAttackTarget(player) if (target == null) { player.move(state, players.openingsFor(player, state)) .firstOrNull()?.let { player.point = it } target = players.getAttackTarget(player) } target?.let { player.attack(it) } } if (isCompleteRound) completedRounds++ } return completedRounds * players.active().sumBy { it.hit } } } private typealias Cave = List<InputLine<Player>> private fun Cave.isOpen(point: Point) = at(point) == '.' && getTokens().active().none { it.point == point } private fun Point.orderedOpenCardinals(state: Cave) = orderedCardinal.filter(state::isOpen) private typealias Players = InputTokens<Player> private fun Players.gameContinues() = active().groupBy { it.role }.size != 1 private fun Players.getAttackTarget(player: Player) = filter(player::isAttackTarget) .sortedWith(compareBy({ it.hit }, { it.point })) .firstOrNull() private fun Players.openingsFor(player: Player, state: Cave) = filter(player::isTarget) .flatMap { it.point.orderedOpenCardinals(state) } .toSet() private fun getPlayers(): (Int, String) -> Set<Player> = { row, input -> mutableSetOf<Player>().apply { input.forEachIndexed { i, position -> when (position) { 'E' -> add(Player(Point(i, row), Role.ELF)) 'G' -> add(Player(Point(i, row), Role.GOBLIN)) } } }.toSet() } private fun getCaveMap(): (String) -> String = { input -> input.replace("[EG]".toRegex(), ".") } private data class Player(override var point: Point, val role: Role, var attack: Int = 3, var hit: Int = 200) : InputToken(point) { override fun isActive() = hit > 0 fun isTarget(other: Player) = isActive() && other.isActive() && role != other.role fun isAttackTarget(other: Player) = isTarget(other) && point.manhattanDistance(other.point) == 1 fun attack(other: Player) { if (isAttackTarget(other)) other.attacked(attack) } private fun attacked(hit: Int) { this.hit -= hit } fun move(state: Cave, openings: Set<Point>): List<Point> { if (!isActive()) return emptyList() val seen = mutableSetOf(point) with(ArrayDeque<List<Point>>().apply { point.orderedOpenCardinals(state).forEach { add(listOf(it)) } }) { while (isNotEmpty()) { val path = removeFirst() val end = path.last() when { end in openings -> return path seen.add(end) -> end.orderedOpenCardinals(state) .filterNot { it in seen } .forEach { add(path + it) } } } } return emptyList() } } private enum class Role { ELF, GOBLIN; }
0
Kotlin
0
0
f1d5c58777968e37e81e61a8ed972dc24b30ac76
4,419
advent18
Apache License 2.0
app/src/main/java/com/canerkorkmaz/cicek/jobdistribution/solver/IPSolver.kt
nberktumer
173,110,988
false
{"Kotlin": 47340}
package com.canerkorkmaz.cicek.jobdistribution.solver import com.canerkorkmaz.cicek.jobdistribution.model.InputDataFormatted import com.canerkorkmaz.cicek.jobdistribution.model.JobData import com.canerkorkmaz.cicek.jobdistribution.model.Solution import com.canerkorkmaz.cicek.jobdistribution.model.SolutionPack import com.canerkorkmaz.cicek.jobdistribution.model.StoreData import com.canerkorkmaz.cicek.jobdistribution.model.distanceSqr import org.ojalgo.optimisation.ExpressionsBasedModel import org.ojalgo.optimisation.Variable import java.util.UUID /** * We have created the integer programming model for the given problem and using a library that can solve integer * programming optimisation problems in pure java, * this class can solve the problem for any given job/store input pairs in a reasonable time */ class IPSolver(data: InputDataFormatted) : SolverBase(data) { override fun solve(): SolutionPack { val model = ExpressionsBasedModel() val variables = data.storeList.map { store -> data.jobList.map { job -> Variable.makeBinary(nameOf(store, job)) .weight(store.distanceSqr(job)) } } variables.forEach { model.addVariables(it) } for (j in 0 until data.jobList.size) { val exp = model.addExpression(UUID.randomUUID().toString()) .lower(1.0).upper(1.0) for (i in 0 until data.storeList.size) { exp.setLinearFactor(variables[i][j], 1) } } for (i in 0 until data.storeList.size) { val exp = model.addExpression(UUID.randomUUID().toString()) .lower(data.storeList[i].min).upper(data.storeList[i].max) for (j in 0 until data.jobList.size) { exp.setLinearFactor(variables[i][j], 1) } } val result = model.minimise() val resultVars = data.storeList.mapIndexed { i, _ -> data.jobList.mapIndexed { j, _ -> result.get(model.indexOf(variables[i][j]).toLong()) } } return SolutionPack( resultVars.mapIndexed { i, lst -> i to lst.mapIndexed { j, res -> j to (res.toInt() == 1) }.filter { it.second }.map { data.jobList[it.first] }.toSet() }.map { data.storeList[it.first] to it.second }.associateBy({ it.first.name }) { Solution(store = it.first, jobs = it.second) }, data ) } } private fun nameOf(store: StoreData, job: JobData): String = "x_${store.name}_${job.id}"
0
Kotlin
0
0
bd3356d1dcd0da1fa4a4ed5967205ea488724d3a
2,670
CicekSepeti-Hackathon
Apache License 2.0
Kotlin for Java Developers. Week 3/Taxi Park/Task/src/taxipark/TaxiParkTask.kt
tinglu
248,072,283
false
null
package taxipark /* * Task #1. Find all the drivers who performed no trips. */ fun TaxiPark.findFakeDrivers(): Set<Driver> = allDrivers.subtract(trips.map { it.driver }) fun TaxiPark.findFakeDrivers2(): Set<Driver> = allDrivers.minus(trips.map { it.driver }) fun TaxiPark.findFakeDrivers3(): Set<Driver> = allDrivers.filter { d -> trips.none { it.driver == d } }.toSet() /* * Task #2. Find all the clients who completed at least the given number of trips. */ fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> { if (minTrips == 0) { return allPassengers } else { return trips .flatMap { it.passengers } .groupingBy { it } .eachCount() .filter { it.value >= minTrips } .keys } } // Better solution: (don't need to handle minTrips == 0) fun TaxiPark.findFaithfulPassengers2(minTrips: Int): Set<Passenger> = allPassengers .filter { p -> trips.count { p in it.passengers } >= minTrips } .toSet() /* * Task #3. Find all the passengers, who were taken by a given driver more than once. */ fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> = trips .filter { it.driver.name == driver.name } .flatMap { it.passengers } .groupingBy { it } .eachCount() .filter { it.value > 1 } // more than once .keys // Similar to mine fun TaxiPark.findFrequentPassengers2(driver: Driver): Set<Passenger> = trips .filter { it.driver == driver } .flatMap { it.passengers } .groupBy { p -> p } .filterValues { group -> group.size > 1 } // use filterValues here .keys fun TaxiPark.findFrequentPassengers3(driver: Driver): Set<Passenger> = allPassengers .filter { p -> trips.count { it.driver == driver && p in it.passengers } > 1 } .toSet() /* * Task #4. Find the passengers who had a discount for majority of their trips. */ fun TaxiPark.findSmartPassengers(): Set<Passenger> { val passengerTrips = trips.flatMap { it.passengers } .groupingBy { it } .eachCount() val passengerSmartTrips = trips.filter { it.discount != null && it.discount > 0.0 } .flatMap { it.passengers } .groupingBy { it } .eachCount() return passengerSmartTrips .filter { it.value * 2 > passengerTrips.getOrDefault(it.key, 0) } .keys } // Better solution: fun TaxiPark.findSmartPassengers2(): Set<Passenger> { val (tripsWithDiscount, tripsWithoutDiscout) = trips.partition { it.discount != null } return allPassengers .filter { passenger -> tripsWithDiscount.count { passenger in it.passengers } > tripsWithoutDiscout.count { passenger in it.passengers } } .toSet() } // I don't like this solution: fun TaxiPark.findSmartPassengers3(): Set<Passenger> = allPassengers .associate { p -> p to trips.filter { t -> p in t.passengers } } .filterValues { val (withDiscount, withoutDiscount) = it.partition { it.discount != null } withDiscount.size > withoutDiscount.size } .keys // Maybe: fun TaxiPark.findSmartPassengers4(): Set<Passenger> = allPassengers.filter { p -> val withDiscount = trips.count { t -> p in t.passengers && t.discount != null } val withoutDiscount = trips.count { t -> p in t.passengers && t.discount == null } withDiscount > withoutDiscount }.toSet() /* * Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on. * Return any period if many are the most frequent, return `null` if there're no trips. */ fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? { val intervalToOccurrence = trips.map { it.duration - it.duration % 10 } // map to it's closest left (start) of its range .groupingBy { it } .eachCount() .toList() .sortedByDescending { (_, counting) -> counting } if (trips.isEmpty()) { return null } else { val start = intervalToOccurrence.first().first val end = start + 9 return start..end } } // Similar to mine but cleaner fun TaxiPark.findTheMostFrequentTripDurationPeriod2(): IntRange? { return trips .groupBy { val start = it.duration / 10 * 10 val end = start + 9 start..end } // .toList() // .maxBy { (_, group) -> group.size } // ?.first .maxBy { (_, group) -> group.size } // can call maxBy on a map directly ?.key } /* * Task #6. * Check whether 20% of the drivers contribute 80% of the income. */ fun TaxiPark.checkParetoPrinciple(): Boolean { val totalIncome = trips.sumByDouble { it.cost } val incomeThreshold = totalIncome * 0.8 val groupByDriver = trips.groupingBy { it.driver } .fold(0.0) { total, trip -> total + trip.cost } .toList() .sortedByDescending { (_, value) -> value } var runningTotal = 0.0 var count = 0 for (driverEarnings: Pair<Driver, Double> in groupByDriver) { runningTotal += driverEarnings.second count++ if (runningTotal >= incomeThreshold) { break } } return trips.isNotEmpty() && count <= allDrivers.size * 0.2 } // Similar but better solution: fun TaxiPark.checkParetoPrinciple2(): Boolean { if (trips.isEmpty()) return false val totalIncome = trips.sumByDouble { it.cost } val sortedDriversIncome: List<Double> = trips .groupBy { it.driver } .map { (_, tripsByDriver) -> tripsByDriver.sumByDouble { it.cost } } .sortedDescending() val numberOfTopDrivers = (0.2 * allDrivers.size).toInt() val incomeByTopDrivers = sortedDriversIncome .take(numberOfTopDrivers) .sum() return incomeByTopDrivers >= 0.8 * totalIncome }
0
Kotlin
0
0
7a2e9034e6e51c6ffb619a525c1b1c932b265b0c
6,109
learn-kotlin
BSD with attribution
src/day_04/Day04.kt
BrumelisMartins
572,847,918
false
{"Kotlin": 32376}
package day_04 import readInput fun main() { fun doAllTasksOverlap(group: Group): Boolean { val intersectedList = group.firstAssignmentList.intersect(group.secondAssignmentList.toSet()) val containsInFirstList = intersectedList.containsAll(group.firstAssignmentList) val containsInSecondList = intersectedList.containsAll(group.secondAssignmentList) return containsInFirstList || containsInSecondList } fun doesAnyTaskOverlap(group: Group) = group.firstAssignmentList.intersect(group.secondAssignmentList.toSet()) .isNotEmpty() fun getSumOfOverlappingTasks(listOfGroups: List<Group>, areTasksOverlapping: (input: Group) -> Boolean) = listOfGroups.sumOf { if (areTasksOverlapping(it)) 1.toInt() else 0 } fun part1(input: List<String>) = getSumOfOverlappingTasks(input.toListOfGroups(), ::doAllTasksOverlap) fun part2(input: List<String>) = getSumOfOverlappingTasks(input.toListOfGroups(), ::doesAnyTaskOverlap) // test if implementation meets criteria from the description, like: val testInput = readInput("day_04/Day04_test") val input = readInput("day_04/Day04") println(part1(input)) println(part2(input)) println(part1(testInput)) }
0
Kotlin
0
0
3391b6df8f61d72272f07b89819c5b1c21d7806f
1,268
aoc-2022
Apache License 2.0
Lah_numbers/Kotlin/src/LahNumbers.kt
ncoe
108,064,933
false
{"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409}
import java.math.BigInteger fun factorial(n: BigInteger): BigInteger { if (n == BigInteger.ZERO) return BigInteger.ONE if (n == BigInteger.ONE) return BigInteger.ONE var prod = BigInteger.ONE var num = n while (num > BigInteger.ONE) { prod *= num num-- } return prod } fun lah(n: BigInteger, k: BigInteger): BigInteger { if (k == BigInteger.ONE) return factorial(n) if (k == n) return BigInteger.ONE if (k > n) return BigInteger.ZERO if (k < BigInteger.ONE || n < BigInteger.ONE) return BigInteger.ZERO return (factorial(n) * factorial(n - BigInteger.ONE)) / (factorial(k) * factorial(k - BigInteger.ONE)) / factorial(n - k) } fun main() { println("Unsigned Lah numbers: L(n, k):") print("n/k ") for (i in 0..12) { print("%10d ".format(i)) } println() for (row in 0..12) { print("%-3d".format(row)) for (i in 0..row) { val l = lah(BigInteger.valueOf(row.toLong()), BigInteger.valueOf(i.toLong())) print("%11d".format(l)) } println() } println("\nMaximum value from the L(100, *) row:") println((0..100).map { lah(BigInteger.valueOf(100.toLong()), BigInteger.valueOf(it.toLong())) }.max()) }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
1,258
rosetta
MIT License
src/Day05.kt
vitind
578,020,578
false
{"Kotlin": 60987}
fun main() { fun getOriginalCrateStack(): Array<ArrayList<Char>> { return arrayOf( arrayListOf('G', 'T', 'R', 'W'), // 1 arrayListOf('G', 'C', 'H', 'P', 'M', 'S', 'V', 'W'), // 2 arrayListOf('C', 'L', 'T', 'S', 'G', 'M'), // 3 arrayListOf('J', 'H', 'D', 'M', 'W', 'R', 'F'), // 4 arrayListOf('P', 'Q', 'L', 'H', 'S', 'W', 'F', 'J'), // 5 arrayListOf('P', 'J', 'D', 'N', 'F', 'M', 'S'), // 6 arrayListOf('Z', 'B', 'D', 'F', 'G', 'C', 'S', 'J'), // 7 arrayListOf('R', 'T', 'B'), // 8 arrayListOf('H', 'N', 'W', 'L', 'C') // 9 ) } fun moveCrates(crateStacks: Array<ArrayList<Char>>, cratesToMove: Int, fromStackPos: Int, toStackPos: Int) { for (i in 0 until cratesToMove) { val fromStack = crateStacks[fromStackPos - 1] val toStack = crateStacks[toStackPos - 1] toStack += fromStack.removeLast() } } fun moveCrateStacks(crateStacks: Array<ArrayList<Char>>, cratesToMove: Int, fromStackPos: Int, toStackPos: Int) { val fromStack = crateStacks[fromStackPos - 1] val toStack = crateStacks[toStackPos - 1] toStack += fromStack.takeLast(cratesToMove) for (i in 0 until cratesToMove) { fromStack.removeLast() } } val CRATES_TO_MOVE_ARG = 1 val FROM_STACK_ARG = 3 val TO_STACK_ARG = 5 fun part1(input: List<String>): String { val crateStack = getOriginalCrateStack() input.forEach { val args = it.split(' ') moveCrates(crateStack, args[CRATES_TO_MOVE_ARG].toInt(), args[FROM_STACK_ARG].toInt(), args[TO_STACK_ARG].toInt()) } return crateStack.map { it.last() }.joinToString("") } fun part2(input: List<String>): String { val crateStack = getOriginalCrateStack() input.forEach { val args = it.split(' ') moveCrateStacks(crateStack, args[CRATES_TO_MOVE_ARG].toInt(), args[FROM_STACK_ARG].toInt(), args[TO_STACK_ARG].toInt()) } return crateStack.map { it.last() }.joinToString("") } val input = readInput("Day05") part1(input).println() part2(input).println() }
0
Kotlin
0
0
2698c65af0acd1fce51525737ab50f225d6502d1
2,368
aoc2022
Apache License 2.0
src/Day01.kt
wlghdu97
573,333,153
false
{"Kotlin": 50633}
fun main() { fun part1(input: List<String>): Int { var max = 0 var inc = 0 input.forEach { if (it.isBlank()) { if (inc > max) { max = inc } inc = 0 } else { inc += it.toInt() } } return max } fun part2(input: List<String>): Int { var max = 0 var secondMax = 0 var thirdMax = 0 var inc = 0 input.forEach { if (it.isBlank()) { when { (inc > max) -> { thirdMax = secondMax secondMax = max max = inc } (inc > secondMax) -> { thirdMax = secondMax secondMax = inc } (inc > thirdMax) -> { thirdMax = inc } } inc = 0 } else { inc += it.toInt() } } return (max + secondMax + thirdMax) } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") // check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2b95aaaa9075986fa5023d1bf0331db23cf2822b
1,421
aoc-2022
Apache License 2.0
src/year2022/day22/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day22 import arrow.core.Either import arrow.core.left import arrow.core.right import arrow.optics.optics import io.kotest.matchers.shouldBe import utils.Direction import utils.Point import utils.cyclical import utils.readInput import utils.y fun main() { val (testMaze, testRoute) = readInput("22", "test_input").parse() val (realMaze, realRoute) = readInput("22", "input").parse() testMaze.runMazeRoute(testRoute) .computePassword() .also(::println) shouldBe 6032 realMaze.runMazeRoute(realRoute) .computePassword() .let(::println) val testCube = readInput("22", "test_input_converted_part_2").parseCube(4) val realCube = realMaze.parseCube(50) // testCube.runCubeRoute(testRoute) // .computePassword() // .also(::println) shouldBe 5031 // // realCube.runCubeRoute(testRoute) // .computePassword() // .let(::println) } private fun List<String>.parse(): Pair<List<String>, List<Either<Int, TurnDirection>>> { return takeWhile { it.isNotBlank() } to last().split(splittingRouteRegex).map { when (it) { "R" -> TurnDirection.CLOCKWISE.right() "L" -> TurnDirection.ANTI_CLOCKWISE.right() else -> it.toInt().left() } } } private val splittingRouteRegex = "(?<=\\d)(?=[RL])|(?<=[RL])(?=\\d)".toRegex() private enum class TurnDirection { CLOCKWISE, ANTI_CLOCKWISE } @optics data class Position( val coordinates: Point, val direction: Direction, ) { companion object } private fun List<String>.runMazeRoute(route: List<Either<Int, TurnDirection>>): Position { val startPosition = Position( coordinates = Point(first().indexOfFirst { it != ' ' }, 0), Direction.Right, ) return route.fold(startPosition, ::executeDirective) } private fun List<String>.executeDirective(position: Position, directive: Either<Int, TurnDirection>): Position { return when (directive) { is Either.Left -> Position.coordinates.modify(position) { currentPosition -> when (position.direction) { Direction.Right -> this[currentPosition.y].asSequence() .withIndex() .getStopCoordinate(currentPosition.x, directive.value) .let { Point(it, currentPosition.y) } Direction.Left -> this[currentPosition.y] .withIndex() .reversed() .asSequence() .getStopCoordinate( this[currentPosition.y].length - currentPosition.x - 1, directive.value ) .let { Point(it, currentPosition.y) } Direction.Down -> asSequence() .map { it.getOrElse(currentPosition.x) { ' ' } } .withIndex() .getStopCoordinate(currentPosition.y, directive.value) .let { Point(currentPosition.x, it) } Direction.Up -> asSequence() .map { it.getOrElse(currentPosition.x) { ' ' } } .withIndex() .toList() .reversed() .asSequence() .getStopCoordinate(size - currentPosition.y - 1, directive.value) .let { Point(currentPosition.x, it) } } } is Either.Right -> Position.direction.modify( position, if (directive.value == TurnDirection.CLOCKWISE) Direction::rotateClockwise else Direction::rotateAntiClockwise ) } } private fun Sequence<IndexedValue<Char>>.getStopCoordinate(startCoordinate: Int, movementLength: Int): Int { return cyclical() .drop(startCoordinate) .getStop(movementLength) .index } private fun Sequence<IndexedValue<Char>>.getStop(movementLength: Int): IndexedValue<Char> { return filterNot { it.value == ' ' } .take(movementLength + 1) .takeWhile { it.value != '#' } .last() } private fun Position.computePassword() = 1000 * (coordinates.y + 1) + 4 * (coordinates.x + 1) + when (direction) { Direction.Right -> 0 Direction.Down -> 1 Direction.Left -> 2 Direction.Up -> 3 } private fun List<String>.parseCube(size: Int): Map<Int, Map<Direction, List<String>>> { return TODO() // return mapOf( // 1 to asSequence() // .take(size) // .mapTo(mutableListOf()) { it.substring(size until 2 * size) } // .run { // generateSequence(Direction.Up to this) { // // } // .take(4) // .toMap() // }, // 2 to asSequence() // .take(size) // .mapTo(mutableListOf()) { it.substring(2 * size) }, // 3 to asSequence() // .drop(size) // .take(size) // .mapTo(mutableListOf()) { it.substring(size) }, // 4 to asSequence() // .drop(2 * size) // .take(size) // .mapTo(mutableListOf()) { it.take(size) }, // 5 to asSequence() // .drop(2 * size) // .take(size) // .mapTo(mutableListOf()) { it.substring(size) }, // 6 to drop(3 * size), // ) } private fun Map<Int, List<String>>.runCubeRoute(route: List<Either<Int, TurnDirection>>): CubePosition { val startPosition = Position( coordinates = Point(0, 0), Direction.Right, ) return route.fold(CubePosition(1, startPosition), ::executeDirective) } @optics data class CubePosition( val face: Int, val position: Position, ) { companion object } private fun Map<Int, List<String>>.executeDirective( position: CubePosition, directive: Either<Int, TurnDirection>, ): CubePosition = when (directive) { is Either.Left -> when (position.face) { 1 -> when (position.position.direction) { Direction.Left -> { getValue(1).asSequence() TODO() } Direction.Right -> { getValue(1)[position.position.coordinates.y] .asSequence() .withIndex() .map { (x, content) -> CubePosition(1, Position(Point(x, position.position.coordinates.y), Direction.Right)) to content } .plus( getValue(2)[position.position.coordinates.y] .asSequence() .withIndex() .map { (x, content) -> CubePosition(2, Position(Point(x, position.position.coordinates.y), Direction.Right)) to content } ) .plus( getValue(5).run { val realY = size - position.position.coordinates.y this[realY] .withIndex() .reversed() .asSequence() .map { (x, content) -> CubePosition(5, Position(Point(x, realY), Direction.Left)) to content } } ) .plus( getValue(4).run { val realY = size - position.position.coordinates.y this[realY] .withIndex() .reversed() .asSequence() .map { (x, content) -> CubePosition(4, Position(Point(x, realY), Direction.Left)) to content } } ) .cyclical() .drop(position.position.coordinates.x) .filterNot { it.second == ' ' } .take(directive.value + 1) .takeWhile { it.second != '#' } .last() .first } Direction.Down -> TODO() Direction.Up -> TODO() } 2 -> { TODO() } 3 -> { TODO() } 4 -> { TODO() } 5 -> { TODO() } else -> { TODO() } } is Either.Right -> CubePosition.position.direction.modify( position, if (directive.value == TurnDirection.CLOCKWISE) Direction::rotateClockwise else Direction::rotateAntiClockwise ) } private fun Map<Int, List<String>>.movementSequence( face: Int, faceOrientation: Direction, position: Position, direction: Direction, ): Sequence<CubePosition> { val faceMaze = getValue(face) val (flatPosition, flatDirection) = when (faceOrientation) { Direction.Up -> position to direction Direction.Down -> Position.coordinates.y.modify(position) { faceMaze.size - it } to if (direction is Direction.Vertical) direction.opposite() else direction Direction.Left -> TODO() Direction.Right -> TODO() } return TODO() } private fun CubePosition.computePassword(): Int { return TODO() }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
9,390
Advent-of-Code
Apache License 2.0
Coding Challenges/Advent of Code/2021/Day 7/part2.kt
Alphabeater
435,048,407
false
{"Kotlin": 69566, "Python": 5974}
import java.io.File import java.util.Scanner import kotlin.math.abs var crabPositions = listOf<Int>() var minVal = 0 var maxVal = 0 var value = -1 //used to return the last value of the recursive function. fun getMinFuel(minPos: Int, maxPos: Int): Int { val midPos = (maxPos + minPos) / 2 if (getFuel(minPos + 1) == getFuel(maxPos - 1)) { value = minOf(getFuel(minPos), getFuel(maxPos), getFuel(midPos)) //update the global value to return on the return value } val lowerMidPos = (minPos + midPos) / 2 val upperMidPos = (midPos + maxPos) / 2 if (getFuel(lowerMidPos) < getFuel(upperMidPos)) { //choose lower half of array getMinFuel(minPos, midPos) } else { //choose upper half of array getMinFuel(midPos, maxPos) } return value } fun getFuel(pos: Int): Int { var fuel = 0 for (crab in crabPositions) { fuel += abs(crab - pos) } return fuel } fun main() { val file = File("src/input.txt") crabPositions = Scanner(file).nextLine().split(',').map{ it.toInt() } minVal = crabPositions.minOrNull()!! maxVal = crabPositions.maxOrNull()!! println(getMinFuel(minVal, maxVal)) }
0
Kotlin
0
0
05c8d4614e025ed2f26fef2e5b1581630201adf0
1,193
Archive
MIT License
src/main/kotlin/dayEleven/DayEleven.kt
janreppien
573,041,132
false
{"Kotlin": 26432}
package dayEleven import AocSolution class DayEleven : AocSolution(11) { override fun solvePartOne(): String { val monkeys = createRealMonkeys() for (i in 0 until 20) { for (monkey in monkeys) { monkey.items.map { monkey.operation(it) / 3 }.forEach { monkeys[if (it % monkey.testNumber == 0L) monkey.ifTrue else monkey.ifFalse].items.add(it) monkey.inspectedItem++ } monkey.items.clear() } } return monkeys.sortedByDescending { it.inspectedItem }.toMutableList().subList(0, 2).map { it.inspectedItem } .reduce(Long::times).toString() } override fun solvePartTwo(): String { val monkeys = createRealMonkeys() val field = monkeys.map { it.testNumber }.reduce { acc, i -> acc * i } for (i in 0 until 10000) { for (monkey in monkeys) { monkey.items.map { monkey.operation(it) % field}.forEach { monkeys[if (it % monkey.testNumber == 0L) monkey.ifTrue else monkey.ifFalse].items.add(it) monkey.inspectedItem++ } monkey.items.clear() } } return monkeys.sortedByDescending { it.inspectedItem }.toMutableList().subList(0, 2).map { it.inspectedItem } .reduce(Long::times).toString() } private fun createTestMonkeys(): MutableList<Monkey> { val testMonkeys = mutableListOf<Monkey>() testMonkeys.add(Monkey(0, mutableListOf(79, 98), 23, { it * 19 }, 2, 3, 0)) testMonkeys.add(Monkey(1, mutableListOf(54, 65, 75, 74), 19, { it + 6 }, 2, 0, 0)) testMonkeys.add(Monkey(2, mutableListOf(79, 60, 97), 13, { it * it }, 1, 3, 0)) testMonkeys.add(Monkey(3, mutableListOf(74), 17, { it + 3 }, 0, 1, 0)) return testMonkeys } private fun createRealMonkeys(): MutableList<Monkey> { val monkeys = mutableListOf<Monkey>() monkeys.add(Monkey(0, mutableListOf(72, 64, 51, 57, 93, 97, 68), 17, {it * 19}, 4,7,0)) monkeys.add(Monkey(1, mutableListOf(62), 3, {it * 11}, 3,2,0)) monkeys.add(Monkey(2, mutableListOf(57, 94, 69, 79, 72), 19, {it + 6}, 0,4,0)) monkeys.add(Monkey(3, mutableListOf(80, 64, 92, 93, 64, 56), 7, {it + 5}, 2,0,0)) monkeys.add(Monkey(4, mutableListOf(70, 88, 95, 99, 78, 72, 65, 94), 2, {it + 7}, 7,5,0)) monkeys.add(Monkey(5, mutableListOf(57, 95, 81, 61), 5, {it * it}, 1,6,0)) monkeys.add(Monkey(6, mutableListOf(79, 99), 11, {it + 2}, 3,1,0)) monkeys.add(Monkey(7, mutableListOf(68, 98, 62), 13, {it + 3}, 5,6,0)) return monkeys } data class Monkey( val id: Int, var items: MutableList<Long>, val testNumber: Int, val operation: (i: Long) -> Long, val ifTrue: Int, val ifFalse: Int, var inspectedItem: Long ) }
0
Kotlin
0
0
b53f6c253966536a3edc8897d1420a5ceed59aa9
2,925
aoc2022
MIT License
atcoder/arc128/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package atcoder.arc128 fun main() { readLn() val a = readInts() val cumSum = mutableListOf(0.toModular()) fun sum(from: Int, to: Int) = cumSum[maxOf(to, from)] - cumSum[from] var same = 0 var diff = 0 var ans = 1.toModular() for (i in a.indices) { if (i < 2 || a[i] != a[i - 2]) diff = i if (i < 1 || a[i] == a[i - 1]) { same = i } else { ans = sum(same, i) - sum(maxOf(diff - 1, same), i - 2) } cumSum.add(cumSum.last() + ans) } println(ans) } private fun Int.toModular() = Modular(this) private class Modular { companion object { const val M = 998244353 } val x: Int @Suppress("ConvertSecondaryConstructorToPrimary") constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } } operator fun plus(that: Modular) = Modular((x + that.x) % M) operator fun minus(that: Modular) = Modular((x + M - that.x) % M) operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular() private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt()) operator fun div(that: Modular) = times(that.modInverse()) override fun toString() = x.toString() } private operator fun Int.plus(that: Modular) = Modular(this) + that private operator fun Int.minus(that: Modular) = Modular(this) - that private operator fun Int.times(that: Modular) = Modular(this) * that private operator fun Int.div(that: Modular) = Modular(this) / that private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,554
competitions
The Unlicense
src/Day05.kt
YunxiangHuang
572,333,905
false
{"Kotlin": 20157}
import java.util.Scanner import kotlin.collections.ArrayList import kotlin.collections.HashMap fun main() { val input = readInput("Day05") var matrix = HashMap<Int, ArrayList<Char>>(10) var rawMatrix = ArrayList<ArrayList<Char>>(10) // parse var actionBegin = 0 for ((i, line) in input.withIndex()) { if (line.isEmpty()) { actionBegin = i + 1 break } val num = (line.length + 1) / 4 var chars = ArrayList<Char>(num) for (j in 0..num) { val idx = 4 * j + 1 if (idx >= line.length) { break } chars.add(line[j * 4 + 1]) } rawMatrix.add(chars) } // build matrix rawMatrix = rawMatrix.reversed() as ArrayList<ArrayList<Char>> // line 0: id for (id in rawMatrix[0]) { matrix[Integer.valueOf(id.toString())] = ArrayList(rawMatrix.size) } for (line in rawMatrix.subList(1, rawMatrix.size)) { for ((id, c) in line.withIndex()) { if (!c.isLetter()) { continue } matrix[id + 1]!!.add(c) } } fun move(from: Int, to: Int) { matrix[to]!!.add(matrix[from]!!.removeLast()) } fun moves(count: Int, from: Int, to: Int) { var tmp = ArrayList<Char>(count) for (i in 0 until count) { tmp.add( matrix[from]!!.removeLast() )} matrix[to]!!.addAll(tmp.reversed()) } // Go action for (line in input.subList(actionBegin, input.size)) { var scanner = Scanner(line) var count = scanner.skip("move").nextInt() var from = scanner.skip(" from ").nextInt() var to = scanner.skip(" to ").nextInt() // while (count > 0) { // move(from, to); count-- // } moves(count, from, to) } print("Part II: ") for (i in 1 .. matrix.size) { print("${matrix[i]!!.last()}") } println() }
0
Kotlin
0
0
f62cc39dd4881f4fcf3d7493f23d4d65a7eb6d66
2,001
AoC_2022
Apache License 2.0
src/main/kotlin/leetcode/Problem1914.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/cyclically-rotating-a-grid/ */ class Problem1914 { fun rotateGrid(grid: Array<IntArray>, k: Int): Array<IntArray> { val maxRows: Int = grid.size val maxCols: Int = if (grid.isNotEmpty()) grid[0].size else 0 var row = 0 var col = 0 var length = 0 var height = maxRows var width = maxCols while (height >= 2 && width >= 2) { val perimeter = 2 * (height + width) rotateGrid(grid, maxRows, maxCols, length++, row++, col++, k % (perimeter - 4)) height -= 2 width -= 2 } return grid } private fun rotateGrid(grid: Array<IntArray>, maxRows: Int, maxCols: Int, length: Int, row: Int, col: Int, k: Int) { var elements = mutableListOf<Int>() iterate(maxRows, maxCols, length, row, col) { r, c -> elements.add(grid[r][c]) } var index = 0 var start = false var n = 0 for (i in 0 until elements.size + k) { iterate(maxRows, maxCols, length, row, col) { r, c -> if (n++ == k) { start = true } if (start && index < elements.size) { grid[r][c] = elements[index++] } } } } private fun iterate(maxRows: Int, maxCols: Int, length: Int, row: Int, col: Int, f: (Int, Int) -> Unit) { // Go down. var r = row var c = col while (r < maxRows - length) { f(r, c) r++ } // Go left. r-- c++ while (c < maxCols - length) { f(r, c) c++ } // Go up. r-- c-- while (r >= length) { f(r, c) r-- } // Go right. c-- r++ while (c >= length + 1) { f(r, c) c-- } } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
2,048
leetcode
MIT License
src/Day12.kt
underwindfall
573,471,357
false
{"Kotlin": 42718}
fun main() { val dayId = "12" val a = readInput("Day${dayId}").map { it.toCharArray() } val n = a.size val m = a[0].size data class P(val i: Int, val j: Int) var e: P? = null var s: P? = null for (i in 0 until n) for (j in 0 until m) { when (a[i][j]) { 'E' -> e = P(i, j) 'S' -> s = P(i, j) } } check(e != null) check(s != null) val q = ArrayDeque<P>() val v = HashMap<P, Int>() fun enq(i: Int, j: Int, d: Int) { val p = P(i, j) if (p in v) return v[p] = d q += p } fun el(h: Char): Int = when(h) { 'S' -> 0 'E' -> 'z' - 'a' else -> h - 'a' } fun go(i: Int, j: Int, d: Int, h: Int) { if (i !in 0 until n || j !in 0 until m) return val t = el(a[i][j]) if (h <= t + 1) enq(i, j, d) } enq(e.i, e.j, 0) while (q.isNotEmpty()) { val p = q.removeFirst() val d = v[p]!! + 1 val h = el(a[p.i][p.j]) go(p.i - 1, p.j, d, h) go(p.i + 1, p.j, d, h) go(p.i, p.j - 1, d, h) go(p.i, p.j + 1, d, h) } var ans = Int.MAX_VALUE for (i in 0 until n) for (j in 0 until m) { if (a[i][j] == 'a') { val d = v[P(i, j)] if (d != null) ans = minOf(ans, d) } } println(ans) }
0
Kotlin
0
0
0e7caf00319ce99c6772add017c6dd3c933b96f0
1,368
aoc-2022
Apache License 2.0
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day17Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith import java.lang.Integer.max private fun solution1(input: String) = Tower(input.toJetPattern()).simulate(2022) private fun solution2(input: String) = Tower(input.toJetPattern()).simulate(1000000000000) private fun String.toJetPattern() = map { if (it == '<') -1 else 1 } private class Tower(private val jetPattern: List<Int>) { private val tiles = mutableListOf<Int>() private var jetIndex = 0 private var height = 0 private val heightIncreases = mutableListOf<Int>() private val hasRepeatingPatternOnTop get() = repeatingPatternHeight != 0 private var repeatingPatternHeight = 0 private var repeatingPatternLength = 0 fun simulate(numberOfRocks: Long): Long { var currentShape = 0 fun iterate() { drop(shapes[currentShape]) currentShape = (currentShape + 1) % shapes.size } val iterations = generateSequence { if (hasRepeatingPatternOnTop) null else iterate() }.count() val nonRepeatingBottomIterations = iterations % repeatingPatternLength val nonRepeatingTopIterations = (numberOfRocks - nonRepeatingBottomIterations) % repeatingPatternLength repeat(nonRepeatingTopIterations.toInt()) { iterate() } val nonRepeatingBottomHeight = heightIncreases.take(nonRepeatingBottomIterations).sum() val nonRepeatingTopHeight = heightIncreases.takeLast(nonRepeatingTopIterations.toInt()).sum() val repeatingPatternIterations = numberOfRocks - nonRepeatingBottomIterations - nonRepeatingTopIterations val repetitionHeight = repeatingPatternIterations / repeatingPatternLength * repeatingPatternHeight return nonRepeatingBottomHeight + repetitionHeight + nonRepeatingTopHeight } fun drop(shape: IntArray) { repeat(height + 3 + shape.size) { tiles.add(0b0000000) } val rock = shape.copyOf() val rockHeight = generateSequence(height + 3) { currentHeight -> val direction = nextJet() val hasMoved = rock.tryMove(direction) if (hasMoved && overlapsWithTiles(rock, currentHeight)) rock.tryMove(-direction) if (currentHeight == 0 || overlapsWithTiles(rock, currentHeight - 1)) null else currentHeight - 1 }.last() rock.forEachIndexed { index, i -> tiles[rockHeight + index] = tiles[rockHeight + index] or i } val newHeight = max(height, rockHeight + shape.size) if (newHeight > height) heightIncreases.add(newHeight - height) else heightIncreases.add(0) height = newHeight if (!hasRepeatingPatternOnTop) { val hi = heightIncreases.joinToString("") for (i in hi.length / 2 downTo 10) { val s1 = hi.substring(hi.length - i) if (hi.endsWith(s1 + s1)) { repeatingPatternLength = s1.length repeatingPatternHeight = heightIncreases.takeLast(s1.length).sum() break } } } } private fun nextJet() = jetPattern[jetIndex].also { jetIndex = (jetIndex + 1) % jetPattern.size } private fun overlapsWithTiles(shape: IntArray, y: Int) = shape.foldIndexed(false) { index, acc, i -> acc || tiles[y + index] or i != tiles[y + index] xor i } override fun toString() = (height - 1 downTo 0).joinToString("\n") { y -> ("|" + tiles[y].toString(2).padStart(7, '0') + "|").replace('0', '.').replace('1', '#') } + "\n+-------+" } private fun IntArray.tryMove(dir: Int): Boolean { if (dir > 0) { if (any { it and 0b0000001 == 0b0000001 }) return false indices.forEach { this[it] = this[it] shr 1 } } else { if (any { it and 0b1000000 == 0b1000000 }) return false indices.forEach { this[it] = this[it] shl 1 } } return true } private val shapes = arrayOf( intArrayOf(0b0011110), intArrayOf(0b0001000, 0b0011100, 0b0001000), intArrayOf(0b0011100, 0b0000100, 0b0000100), intArrayOf(0b0010000, 0b0010000, 0b0010000, 0b0010000), intArrayOf(0b0011000, 0b0011000) ) //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 17 class Day17Test : StringSpec({ "drop 10 rocks and check the result" { val tower = Tower(exampleInput.toJetPattern()) generateSequence(0) { (it + 1) % shapes.size } .take(10) .forEach { tower.drop(shapes[it]) } println(tower) tower.toString() shouldBe """ |....#..| |....#..| |....##.| |##..##.| |######.| |.###...| |..#....| |.####..| |....##.| |....##.| |....#..| |..#.#..| |..#.#..| |#####..| |..###..| |...#...| |..####.| +-------+ """.trimIndent() } "example part 1" { ::solution1 invokedWith exampleInput shouldBe 3068 } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 3117 } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 1514285714288 } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 1553314121019 } }) private val exampleInput = """ >>><<><>><<<>><>>><<<>>><<<><<<>><>><<>> """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
5,662
adventofcode-kotlin
MIT License
src/main/kotlin/com/nibado/projects/advent/y2021/Day09.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2021 import com.nibado.projects.advent.* object Day09 : Day { private val values = resourceLines(2021, 9).map { it.toCharArray().map { it.digitToInt() } } private val points = values.indices.flatMap { y -> values[0].indices.map { x -> Point(x, y) } } override fun part1() = points.map { it to values[it.y][it.x] }.filter { val neighbors = it.first.neighborsHv().filter { it.inBound(values[0].size - 1, values.size - 1) } neighbors.all { n -> values[n.y][n.x] > it.second } }.sumOf { it.second + 1 } override fun part2() : Int { val consider = points.filterNot { (x, y) -> values[y][x] == 9 }.toMutableSet() val sizes = mutableListOf<Int>() while(consider.isNotEmpty()) { var area = 0 var frontier = setOf(consider.first()) while(frontier.isNotEmpty()) { area += frontier.size consider -= frontier frontier = frontier.flatMap { it.neighborsHv() }.filter { consider.contains(it) }.toSet() } sizes += area } return sizes.sorted().takeLast(3).let { (a,b,c) -> a * b * c } } }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,202
adventofcode
MIT License
src/Day02.kt
zfz7
573,100,794
false
{"Kotlin": 53499}
fun main() { println(day2A(readFile("Day02"))) println(day2B(readFile("Day02"))) } fun day2A(input: String): Int = input.trim().split("\n").sumOf { playedValue(it[2]) + winner(it[0], it[2]) } fun day2B(input: String): Int = input.trim().split("\n").sumOf { outcome(it[2]) + playedValue(it[0], it[2]) } fun playedValue(input: Char): Int = when (input) { 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> throw Exception("help") } fun winner(them: Char, you: Char): Int = when (Pair(them, you)) { Pair('A', 'X'), Pair('B', 'Y'), Pair('C', 'Z') -> 3 Pair('A', 'Y'), Pair('B', 'Z'), Pair('C', 'X') -> 6 Pair('A', 'Z'), Pair('B', 'X'), Pair('C', 'Y') -> 0 else -> throw Exception("help") } fun outcome(input: Char): Int = when (input) { 'X' -> 0 'Y' -> 3 'Z' -> 6 else -> throw Exception("help") } fun playedValue(them: Char, you: Char): Int = when (Pair(them, you)) { Pair('A', 'Y'), Pair('B', 'X'), Pair('C', 'Z') -> 1//Rock Pair('A', 'Z'), Pair('B', 'Y'), Pair('C', 'X') -> 2//Paper Pair('A', 'X'), Pair('B', 'Z'), Pair('C', 'Y') -> 3//Scissor else -> throw Exception("help") }
0
Kotlin
0
0
c50a12b52127eba3f5706de775a350b1568127ae
1,233
AdventOfCode22
Apache License 2.0
src/Day04.kt
rromanowski-figure
573,003,468
false
{"Kotlin": 35951}
object Day04 : Runner<Int, Int>(4, 2, 4) { override fun part1(input: List<String>): Int { return input.count { val ranges = it.split(",") val section1 = ranges[0].toSection() val section2 = ranges[1].toSection() (section1.first >= section2.first && section1.last <= section2.last) || (section2.first >= section1.first && section2.last <= section1.last) } } override fun part2(input: List<String>): Int { return input.count { val ranges = it.split(",") val section1 = ranges[0].toSection() val section2 = ranges[1].toSection() section1.intersect(section2).isNotEmpty() } } private fun String.toSection(): IntRange { val bounds = split("-") return bounds[0].toInt()..bounds[1].toInt() } }
0
Kotlin
0
0
6ca5f70872f1185429c04dcb8bc3f3651e3c2a84
875
advent-of-code-2022-kotlin
Apache License 2.0
alchemist/alchemist-cognitive-agents/src/main/kotlin/it/unibo/alchemist/model/implementations/actions/steeringstrategies/Weighted.kt
cric96
390,057,153
true
{"Java": 1915234, "Kotlin": 1101587, "Scala": 43027, "HTML": 6547, "ANTLR": 4034, "CSS": 1075, "JavaScript": 998}
package it.unibo.alchemist.model.implementations.actions.steeringstrategies import it.unibo.alchemist.model.implementations.positions.Euclidean2DPosition import it.unibo.alchemist.model.interfaces.GroupSteeringAction import it.unibo.alchemist.model.interfaces.Node import it.unibo.alchemist.model.interfaces.SteeringAction import it.unibo.alchemist.model.interfaces.SteeringActionWithTarget import it.unibo.alchemist.model.interfaces.SteeringStrategy import it.unibo.alchemist.model.interfaces.environments.Euclidean2DEnvironment /** * A [SteeringStrategy] performing a weighted sum of steering actions (see [computeNextPosition]). * * @param environment * the environment in which the node moves. * @param node * the owner of the steering actions combined by this strategy. * @param weight * lambda used to assign a weight to each steering action: the higher the weight, the greater the * importance of the action. */ open class Weighted<T>( private val environment: Euclidean2DEnvironment<T>, private val node: Node<T>, private val weight: SteeringAction<T, Euclidean2DPosition>.() -> Double ) : SteeringStrategy<T, Euclidean2DPosition> { /** * [actions] are partitioned in group steering actions and non-group steering actions. The overall next position * for each of these two sets of actions is computed via weighted sum. The resulting vectors are then summed * together (with unitary weight). */ override fun computeNextPosition(actions: List<SteeringAction<T, Euclidean2DPosition>>): Euclidean2DPosition = actions.partition { it is GroupSteeringAction<T, Euclidean2DPosition> }.let { (groupActions, steerActions) -> groupActions.calculatePosition() + steerActions.calculatePosition() } /** * If there's no [SteeringActionWithTarget] among the provided [actions], a zero vector is returned. Otherwise, * the closest target is picked. */ override fun computeTarget(actions: List<SteeringAction<T, Euclidean2DPosition>>): Euclidean2DPosition = environment.getPosition(node).let { currPos -> actions.filterIsInstance<SteeringActionWithTarget<T, out Euclidean2DPosition>>() .map { it.target() } .minByOrNull { it.distanceTo(currPos) } ?: currPos } private fun List<SteeringAction<T, Euclidean2DPosition>>.calculatePosition(): Euclidean2DPosition = if (size > 1) { map { it.nextPosition() to it.weight() }.run { val totalWeight = map { it.second }.sum() map { it.first * (it.second / totalWeight) }.reduce { acc, pos -> acc + pos } } } else firstOrNull()?.nextPosition() ?: environment.origin }
0
Java
0
0
cbc75fbf8ac1b11ab0ef658f3ee1537ae39764fa
2,790
Alchemist
Creative Commons Attribution 3.0 Unported
src/main/kotlin/day1.kt
sviams
726,160,356
false
{"Kotlin": 9233}
object day1 { val digitMap = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9" ) fun firstAndLast(input: String): String { val onlyDigits = input.toCharArray().filter { it.isDigit() } val res = "" + onlyDigits.first() + onlyDigits.last() return res } fun replaceSpelledOutDigits(input: String): String { val res = input.fold("") { acc, c -> val next = acc + c if (digitMap.keys.any { next.contains(it) }) { digitMap.entries.fold(next) { acc2, (spelledOut, asDigit) -> acc2.replace(spelledOut, asDigit) } + c } else next } return res } fun pt1(input: List<String>): Int = input.map { firstAndLast(it).toInt() }.sum() fun pt2(input: List<String>): Int = input.map { firstAndLast(replaceSpelledOutDigits(it)).toInt() }.sum() }
0
Kotlin
0
0
4914a54b21e8aac77ce7bbea3abc88ac04037d50
1,059
aoc23
Apache License 2.0
advent/src/test/kotlin/org/elwaxoro/advent/y2015/Dec06.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2015 import org.elwaxoro.advent.Coord import org.elwaxoro.advent.PuzzleDayTester import kotlin.math.max /** * https://adventofcode.com/2015/day/6 * Part 1: 569999 * Part 2: 17836115 */ class Dec06 : PuzzleDayTester(6, 2015) { override fun part1(): Any = doTheThing(::cmdPuzzle1) override fun part2(): Any = doTheThing(::cmdPuzzle2) private enum class CMD(val parse: String) { ON("turn on "), OFF("turn off "), TOGGLE("toggle ") } private fun doTheThing(mod: (initial: Int, cmd: CMD) -> Int): Int = // make the 1000x1000 grid MutableList(1000) { MutableList(1000) { 0 } }.also { grid -> load().map { line -> // parse the command and the coords val cmd = CMD.values().single { line.startsWith(it.parse) } val coords = line.replace("through ", "").replace(cmd.parse, "").split(" ").map { Coord.parse(it) } // build the list of all impacted coords, then run the command on that pixel coords[0].enumerateRectangle(coords[1]).map { grid[it.y][it.x] = mod(grid[it.y][it.x], cmd) } } }.sumOf{ it.sum() } private fun cmdPuzzle1(initial: Int, cmd: CMD): Int = when (cmd) { CMD.ON -> 1 CMD.OFF -> 0 CMD.TOGGLE -> (initial + 1) % 2 } private fun cmdPuzzle2(initial: Int, cmd: CMD): Int = when (cmd) { CMD.ON -> initial + 1 CMD.OFF -> max(0, initial - 1) CMD.TOGGLE -> initial + 2 } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
1,633
advent-of-code
MIT License
src/days/day14/Day14.kt
Riven-Spell
113,698,657
false
{"Kotlin": 25729}
package days.day14 import days.day10.binaryKnotHash import days.day3.plus fun day14p1(s: String): String = (0..127).map { "$s-$it" }.map { binaryKnotHash(it).toCharArray() }.map { it.filter { it == '1' }.size }.sum().toString() fun day14p2(s: String): String { (0..127).map { "$s-$it" }.map { binaryKnotHash(it).toCharArray() }.map{ it.withIndex().filter { it.value == '1' } }.withIndex().forEach { val y = it.index it.value.forEach { val x = it.index groups[Pair(x,y)] = 0 } } var gnums = 0 groups.keys.forEach { if(propGroups(it,gnums + 1)) gnums++ } return gnums.toString() } var groups: HashMap<Pair<Int,Int>, Int> = HashMap() val outerpos = listOf(Pair(0,1),Pair(0,-1),Pair(1,0), Pair(-1,0)) fun propGroups(pos: Pair<Int,Int>, gn: Int): Boolean { groups[pos] ?: return false if (groups[pos] != 0) return false groups[pos] = gn outerpos.map { it + pos }.forEach { propGroups(it,gn) } return true }
0
Kotlin
0
1
dbbdb390a0addee98c7876647106af208c3d9bc7
1,001
Kotlin-AdventOfCode-2017
MIT License
src/main/kotlin/Day16.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List public object Day16 { enum class Direction { UP, DOWN, LEFT, RIGHT } public fun part1(input: List<String>): String { val startCoordinate = Day10.Coordinate(0, 0) val startDirection = Direction.RIGHT return energizeCount(startCoordinate, startDirection, input).toString() } private fun energizeCount(startCoordinate: Day10.Coordinate, startDirection: Direction, grid: List<String>): Int { val seenCoordinates = mutableSetOf<Pair<Day10.Coordinate, Direction>>() val queue = ArrayDeque<Pair<Day10.Coordinate, Direction>>() queue.add(startCoordinate to startDirection) while (queue.isNotEmpty()) { val (currentCoordinate, currentDirection) = queue.removeFirst() if (currentCoordinate.x < 0 || currentCoordinate.y < 0 || currentCoordinate.y >= grid.size || currentCoordinate.x >= grid[currentCoordinate.y].length) { continue } if (seenCoordinates.contains(currentCoordinate to currentDirection)) { continue } seenCoordinates.add(currentCoordinate to currentDirection) val nextCoordinates = next(currentCoordinate, currentDirection, grid) queue.addAll(nextCoordinates) } return seenCoordinates.map { (coordinate, _) -> coordinate }.distinct().count() } private fun next( currentCoordinate: Day10.Coordinate, direction: Direction, grid: List<String> ): List<Pair<Day10.Coordinate, Direction>> { val currentMarker = grid[currentCoordinate.y][currentCoordinate.x] when (currentMarker) { '|' -> { if (direction == Direction.UP || direction == Direction.DOWN) { val nextCoordinate = when (direction) { Direction.UP -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1) Direction.DOWN -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1) else -> throw IllegalStateException("Should not happen") } // Keep going the same direction return listOf(nextCoordinate to direction) } else { return listOf( Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1) to Direction.UP, Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1) to Direction.DOWN ) } } '-' -> { if (direction == Direction.LEFT || direction == Direction.RIGHT) { val nextCoordinate = when (direction) { Direction.LEFT -> Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y) Direction.RIGHT -> Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y) else -> throw IllegalStateException("Should not happen") } // Keep going the same direction return listOf(nextCoordinate to direction) } else { return listOf( Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y) to Direction.LEFT, Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y) to Direction.RIGHT ) } } '\\' -> { val (nextCoordinate, nextDirection) = when (direction) { Direction.RIGHT -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1) to Direction.DOWN Direction.LEFT -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1) to Direction.UP Direction.UP -> Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y) to Direction.LEFT Direction.DOWN -> Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y) to Direction.RIGHT } return listOf(nextCoordinate to nextDirection) } '/' -> { val (nextCoordinate, nextDirection) = when (direction) { Direction.LEFT -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1) to Direction.DOWN Direction.RIGHT -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1) to Direction.UP Direction.DOWN -> Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y) to Direction.LEFT Direction.UP -> Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y) to Direction.RIGHT } return listOf(nextCoordinate to nextDirection) } '.' -> { val nextCoordinate = when (direction) { Direction.UP -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y - 1) Direction.DOWN -> Day10.Coordinate(currentCoordinate.x, currentCoordinate.y + 1) Direction.LEFT -> Day10.Coordinate(currentCoordinate.x - 1, currentCoordinate.y) Direction.RIGHT -> Day10.Coordinate(currentCoordinate.x + 1, currentCoordinate.y) } return listOf(nextCoordinate to direction) } else -> throw IllegalStateException("Should not happen") } } public fun part2(input: List<String>): String { val leftStarts = (0 until input.size).map { y -> Day10.Coordinate(0, y) to Direction.RIGHT } val rightStarts = (0 until input.size).map { y -> Day10.Coordinate(input[y].length - 1, y) to Direction.LEFT } val topStarts = (0 until input[0].length).map { x -> Day10.Coordinate(x, 0) to Direction.DOWN } val bottomStarts = (0 until input[0].length).map { x -> Day10.Coordinate(x, input.size - 1) to Direction.UP } val allStarts = leftStarts + rightStarts + topStarts + bottomStarts return allStarts.maxOf { (coordinate, direction) -> energizeCount(coordinate, direction, input) }.toString() } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
6,354
kotlin-kringle
Apache License 2.0
src/Day01.kt
fouksf
572,530,146
false
{"Kotlin": 43124}
fun main() { fun readCalories(input: List<String>): List<Int> { val calories = ArrayList<Int>() var current = 0 for (cal in input) { if (cal.isBlank()) { calories.add(current) current = 0 } else { current += cal.toInt() } } if (current != 0) { calories.add(current) } return calories } fun part1(input: List<String>): Int { val calories = readCalories(input) return calories.max() } fun part2(input: List<String>): Int { val calories = readCalories(input) return calories.sorted().takeLast(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") val input = readInput("Day01") // println(part1(testInput)) println(part2(testInput)) // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
701bae4d350353e2c49845adcd5087f8f5409307
984
advent-of-code-2022
Apache License 2.0
src/Day03.kt
m0r0
576,999,741
false
null
import kotlin.properties.Delegates fun main() { fun part1(input: List<String>): Int { return input.map { Rucksack(it) }.sumOf { it.calculatePriorityOfSharedItem() } } fun part2(input: List<String>): Int { val rucksacks = mutableListOf<String>() val rucksackGroups = mutableListOf<RucksackGroup>() input.forEachIndexed { index, s -> rucksacks.add(s) if ((index + 1) % 3 == 0) { rucksackGroups.add(RucksackGroup(rucksacks)) rucksacks.clear() } } rucksackGroups.forEach { it.calculateBadge() println(it.badgePriority) } return rucksackGroups.sumOf { it.badgePriority } } val input = readInput("Day03") part1(input).println() part2(input).println() } class Rucksack(input: String) { // These are two compartments private val firstC: Set<Char> = input.take(input.length / 2).toSortedSet() private val secondC: Set<Char> = input.takeLast(input.length / 2).toSortedSet() private var sharedItem by Delegates.notNull<Char>() private var sharedItemPriority by Delegates.notNull<Int>() init { firstC.forEach { if (secondC.contains(it)) sharedItem = it } sharedItemPriority = getPriority(sharedItem) } fun calculatePriorityOfSharedItem(): Int { return sharedItemPriority } override fun toString(): String { return "1 = $firstC, 2 = $secondC, sh = $sharedItem, p = $sharedItemPriority" } } class RucksackGroup(input: List<String>) { val line1 = input[0].toSet() val line2 = input[1].toSet().toMutableSet() val line3 = input[2].toSet().toMutableSet() private var badge by Delegates.notNull<Char>() var badgePriority by Delegates.notNull<Int>() private set fun calculateBadge(): Char { line1.forEach { if (!line2.add(it) && !line3.add(it)) badge = it } badgePriority = getPriority(badge) return badge } } fun getPriority(badge: Char): Int { return badge.code - if (badge.isLowerCase()) SMALL_LETTER_OFFSET else CAPITAL_LETTER_OFFSET } const val CAPITAL_LETTER_OFFSET = 38 const val SMALL_LETTER_OFFSET = 96
0
Kotlin
0
0
b6f3c5229ad758f61f219040f8db61f654d7fc00
2,247
kotlin-AoC-2022
Apache License 2.0
ceria/11/src/main/kotlin/Solution.kt
VisionistInc
317,503,410
false
null
import java.io.File; import java.util.LinkedList; val floor = '.' val seat = 'L' val occupied = '#' fun main(args : Array<String>) { val input = File(args.first()).readLines() println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input :List<String>) :Int { var openSeats = mutableListOf<Pair<Int, Int>>() var occupiedSeats = mutableListOf<Pair<Int, Int>>() var floorSpace = mutableListOf<Pair<Int, Int>>() val xMax = input.first().length var yMax = input.size input.forEachIndexed { y, line -> for (x in line.indices) { when (line[x]) { seat -> { openSeats.add(Pair(x, y)) } floor -> { floorSpace.add(Pair(x, y)) } } } } var openToOccupied = mutableListOf<Pair<Int, Int>>() var occupiedToOpen = mutableListOf<Pair<Int, Int>>() while (true) { for (seat in openSeats) { val adjacentSeats = checkAdjacentSeats(seat).filter { it.first > -1 && it.second > -1 && it.first < xMax && it.second < yMax } if (openSeats.union(floorSpace).containsAll(adjacentSeats)) { openToOccupied.add(seat) } } for (seat in occupiedSeats) { val adjacentSeats = checkAdjacentSeats(seat) if (occupiedSeats.intersect(adjacentSeats).size >= 4 ) { occupiedToOpen.add(seat) } } if (openToOccupied.isEmpty() && occupiedToOpen.isEmpty()) { break } openSeats.removeAll(openToOccupied) occupiedSeats.addAll(openToOccupied) openToOccupied.clear() occupiedSeats.removeAll(occupiedToOpen) openSeats.addAll(occupiedToOpen) occupiedToOpen.clear() } return occupiedSeats.size } private fun solution2(input :List<String>) :Int { var openSeats = mutableListOf<Pair<Int, Int>>() var occupiedSeats = mutableListOf<Pair<Int, Int>>() var floorSpace = mutableListOf<Pair<Int, Int>>() val xMax = input.first().length val yMax = input.size input.forEachIndexed { y, line -> for (x in line.indices) { when (line[x]) { seat -> { openSeats.add(Pair(x, y)) } floor -> { floorSpace.add(Pair(x, y)) } } } } var openToOccupied = mutableListOf<Pair<Int, Int>>() var occupiedToOpen = mutableListOf<Pair<Int, Int>>() // println() // debug(floorSpace, openSeats, occupiedSeats, xMax, yMax) // println() while (true) { for (seat in openSeats) { val visibleSeats = checkSeatsCanSee(seat, floorSpace, xMax, yMax).filter { it.first > -1 && it.second > -1 && it.first < xMax && it.second < yMax } if (openSeats.containsAll(visibleSeats)) { openToOccupied.add(seat) } } for (seat in occupiedSeats) { val visibleSeats = checkSeatsCanSee(seat, floorSpace, xMax, yMax).toMutableList() if (occupiedSeats.intersect( visibleSeats).size >= 5 ) { occupiedToOpen.add(seat) } } if (openToOccupied.isEmpty() && occupiedToOpen.isEmpty()) { break } openSeats.removeAll(openToOccupied) occupiedSeats.addAll(openToOccupied) openToOccupied.clear() occupiedSeats.removeAll(occupiedToOpen) openSeats.addAll(occupiedToOpen) occupiedToOpen.clear() // println() // debug(floorSpace, openSeats, occupiedSeats, xMax, yMax) // println() } return occupiedSeats.size } private fun checkAdjacentSeats(seat :Pair<Int, Int>) :List<Pair<Int, Int>> { return listOf( Pair(seat.first + 1, seat.second + 1), Pair(seat.first + 1, seat.second - 1), Pair(seat.first - 1, seat.second + 1), Pair(seat.first - 1, seat.second - 1), Pair(seat.first - 1, seat.second), Pair(seat.first + 1, seat.second), Pair(seat.first, seat.second + 1), Pair(seat.first, seat.second - 1 ), ) } private fun checkSeatsCanSee(seat :Pair<Int, Int>, floorSpace :List<Pair<Int, Int>>, xMax :Int, yMax :Int) :List<Pair<Int, Int>> { var canSee = mutableListOf<Pair<Int, Int>>() var brDiagFound = false var trDiagFound = false var rightFound = false var blDiagFound = false var tlDiagFound = false var leftFound = false for (x in 1 until xMax) { if (Pair(seat.first + x, seat.second + x) !in floorSpace && !brDiagFound) { canSee.add(Pair(seat.first + x, seat.second + x)) brDiagFound = true } if (Pair(seat.first + x, seat.second - x) !in floorSpace && !trDiagFound) { canSee.add(Pair(seat.first + x, seat.second - x)) trDiagFound = true } if (Pair(seat.first + x, seat.second) !in floorSpace && !rightFound) { canSee.add(Pair(seat.first + x, seat.second)) rightFound = true } if (Pair(seat.first - x, seat.second + x) !in floorSpace && !blDiagFound) { canSee.add(Pair(seat.first - x, seat.second + x)) blDiagFound = true } if (Pair(seat.first - x, seat.second - x) !in floorSpace && !tlDiagFound) { canSee.add(Pair(seat.first - x, seat.second - x)) tlDiagFound = true } if (Pair(seat.first - x, seat.second) !in floorSpace && !leftFound) { canSee.add(Pair(seat.first - x, seat.second)) leftFound = true } if (brDiagFound && trDiagFound && rightFound && blDiagFound && tlDiagFound && leftFound) { break } } var bottomFound = false var topFound = false for (y in 1 until yMax) { if (Pair(seat.first, seat.second + y) !in floorSpace && !bottomFound) { canSee.add(Pair(seat.first, seat.second + y)) bottomFound = true } if (Pair(seat.first, seat.second - y) !in floorSpace && !topFound) { canSee.add(Pair(seat.first, seat.second - y)) topFound = true } if (bottomFound && topFound) { break } } return canSee } private fun debug(floorSpace :List<Pair<Int, Int>>, openSeats :List<Pair<Int, Int>>, occupiedSeats :List<Pair<Int, Int>>, xMax :Int, yMax :Int) { for ( y in 0 until yMax ) { for (x in 0 until xMax ) { if (floorSpace.contains(Pair(x,y))) { print('.') } else if (openSeats.contains(Pair(x, y))) { print('L') } else if (occupiedSeats.contains(Pair(x, y))) { print('#') } } println() } }
0
Rust
0
0
002734670384aa02ca122086035f45dfb2ea9949
6,842
advent-of-code-2020
MIT License
src/AoC17.kt
Pi143
317,631,443
false
null
import java.io.File fun main() { println("Starting Day 17 A Test 1") calculateDay17PartA("Input/2020_Day17_A_Test1") println("Starting Day 17 A Real") calculateDay17PartA("Input/2020_Day17_A") println("Starting Day 17 B Test 1") calculateDay17PartB("Input/2020_Day17_A_Test1") println("Starting Day 17 B Real") calculateDay17PartB("Input/2020_Day17_A") } fun calculateDay17PartA(file: String): Int { var activeCubes = readDay17Data(file) val cycles = 6 for (i in 0 until cycles) { var newActiveCubes = mutableSetOf<Cube>() val generatedMesh = generateMesh(activeCubes) for (cube in generatedMesh) { val amountNeighbors = countNeighbors(cube, activeCubes) if (cube in activeCubes && amountNeighbors in 2 until 4) { newActiveCubes.add(cube) } if (cube !in activeCubes && amountNeighbors == 3) { newActiveCubes.add(cube) } } activeCubes = newActiveCubes } println("amount of actives cubes is ${activeCubes.size}") return activeCubes.size } fun countNeighbors(cube: Cube, activeCubes: Set<Cube>): Int { var amountNeighbors = 0 val x = cube.x val y = cube.y val z = cube.z for (xAdd in -1 until 2) { for (yAdd in -1 until 2) { for (zAdd in -1 until 2) { if (!(xAdd == 0 && yAdd == 0 && zAdd == 0) && activeCubes.contains(Cube(x + xAdd, y + yAdd, z + zAdd))) { amountNeighbors++ } } } } return amountNeighbors } fun countNeighbors4(cube: Cube4, activeCubes: Set<Cube4>): Int { var amountNeighbors = 0 val x = cube.x val y = cube.y val z = cube.z val w = cube.w for (xAdd in -1 until 2) { for (yAdd in -1 until 2) { for (zAdd in -1 until 2) { for (wAdd in -1 until 2) { if (!(xAdd == 0 && yAdd == 0 && zAdd == 0 && wAdd==0) && activeCubes.contains(Cube4(x + xAdd, y + yAdd, z + zAdd,w +wAdd))) { amountNeighbors++ } } } } } return amountNeighbors } fun generateMesh(activeCubes: Set<Cube>): MutableSet<Cube> { var cubeMesh = activeCubes.toMutableSet() for (cube in activeCubes) { val x = cube.x val y = cube.y val z = cube.z for (xAdd in -1 until 2) { for (yAdd in -1 until 2) { for (zAdd in -1 until 2) { cubeMesh.add(Cube(x + xAdd, y + yAdd, z + zAdd)) } } } } return cubeMesh } fun generateMesh4(activeCubes: Set<Cube4>): MutableSet<Cube4> { var cubeMesh = activeCubes.toMutableSet() for (cube in activeCubes) { val x = cube.x val y = cube.y val z = cube.z val w = cube.w for (xAdd in -1 until 2) { for (yAdd in -1 until 2) { for (zAdd in -1 until 2) { for (wAdd in -1 until 2) { cubeMesh.add(Cube4(x + xAdd, y + yAdd, z + zAdd, w+wAdd)) } } } } } return cubeMesh } fun calculateDay17PartB(file: String): Int { var activeCubes = readDay17Data4(file) val cycles = 6 for (i in 0 until cycles) { var newActiveCubes = mutableSetOf<Cube4>() val generatedMesh = generateMesh4(activeCubes) for (cube in generatedMesh) { val amountNeighbors = countNeighbors4(cube, activeCubes) if (cube in activeCubes && amountNeighbors in 2 until 4) { newActiveCubes.add(cube) } if (cube !in activeCubes && amountNeighbors == 3) { newActiveCubes.add(cube) } } activeCubes = newActiveCubes } println("amount of actives cubes is ${activeCubes.size}") return activeCubes.size } fun readDay17Data(input: String): Set<Cube> { var activeCubes = mutableSetOf<Cube>() val readLines = File(localdir + input).readLines() for (lineIndex in readLines.indices) { val line = readLines[lineIndex] for (charIndex in line.indices) if (line[charIndex] == '#') { activeCubes.add(Cube(charIndex, lineIndex, 0)) } } return activeCubes } fun readDay17Data4(input: String): Set<Cube4> { var activeCubes = mutableSetOf<Cube4>() val readLines = File(localdir + input).readLines() for (lineIndex in readLines.indices) { val line = readLines[lineIndex] for (charIndex in line.indices) if (line[charIndex] == '#') { activeCubes.add(Cube4(charIndex, lineIndex, 0,0)) } } return activeCubes } class Cube(x: Int, y: Int, z: Int) { val x = x val y = y val z = z override fun equals(other: Any?): Boolean { if (other == null || other !is Cube) return false return x == other.x && y == other.y && z == other.z } override fun hashCode(): Int { var result = x result = 31 * result + y result = 71 * result + z return result } } class Cube4(x: Int, y: Int, z: Int, w:Int) { val x = x val y = y val z = z val w = w override fun equals(other: Any?): Boolean { if (other == null || other !is Cube4) return false return x == other.x && y == other.y && z == other.z && w == other.w } override fun hashCode(): Int { var result = x result = 31 * result + y result = 31 * result + z result = 31 * result + w return result } }
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
5,734
AdventOfCode2020
MIT License
Rat Maze Problem/RatMaze.kt
ReciHub
150,083,876
false
{"C++": 2125921, "Java": 329701, "Python": 261837, "C#": 119510, "C": 86966, "JavaScript": 69795, "Jupyter Notebook": 48962, "HTML": 35203, "Kotlin": 20787, "Go": 15812, "CSS": 12510, "TeX": 12253, "TypeScript": 10773, "PHP": 8809, "Swift": 7787, "Scala": 6724, "Rust": 6297, "Shell": 5562, "Ruby": 5488, "Haskell": 4927, "SCSS": 4721, "Brainfuck": 1919, "Dart": 1879, "Elixir": 1592, "MATLAB": 734, "Visual Basic .NET": 679, "R": 617, "Assembly": 616, "LOLCODE": 243, "PowerShell": 15, "Batchfile": 5}
/** * @created October 2, 2019 * Kotlin Program that solves Rat in a maze problem using backtracking. */ class RatMaze { // Size of the maze. private var n: Int = 0 // Just in case. Primitive types cannot be lateinit. private lateinit var solution: Array<IntArray> private lateinit var maze: Array<IntArray> /** * This function solves the Maze problem using * Backtracking. It mainly uses solveMazeUtil() * to solve the problem. It returns false if no * path is possible, otherwise return true and * prints the path in the form of 1s. Please note * that there may be more than one solutions, this * function prints one of the feasible solutions. */ fun solve(maze: Array<IntArray>): Boolean { n = maze.size this.maze = maze solution = Array(n) { IntArray(n) } if (!solveMazeUtil(0, 0)) { println("Solution does not exist.") return false } printSolution() return true } /** * A recursive utility function to solve Maze problem. */ private fun solveMazeUtil(row: Int, column: Int): Boolean { // if (row ; column) is the goal then return true if (row == n - 1 && column == n - 1) { solution[row][column] = 1 return true } // Check if maze[row][column] is valid. if (isSafe(row, column)) { solution[row][column] = 1 // Move horizontally if (solveMazeUtil(row, column + 1)) { return true } // Move vertically if (solveMazeUtil(row + 1, column)) { return true } // If none of the above movements works then // BACKTRACK: remove mark on row, column as part of solution path solution[row][column] = 0 return false } return false } /** * Checks that the coordinates "row" and "column" are valid. */ private fun isSafe(row: Int, column: Int): Boolean { return row in 0..(n - 1) && column in 0..(n - 1) && maze[row][column] == 1 } /** * A utility function to print solution matrix. * solution[n][n] */ private fun printSolution() { (0..(n - 1)).forEach { row -> (0..(n - 1)).forEach { column -> print(" ${solution[row][column]}") } println() } } } fun main() { // Valid Maze val maze01 = arrayOf( intArrayOf(1, 0, 0, 0), intArrayOf(1, 1, 0, 1), intArrayOf(0, 1, 0, 0), intArrayOf(1, 1, 1, 1) ) // Valid Maze val maze02 = arrayOf( intArrayOf(1, 0, 0), intArrayOf(1, 1, 0), intArrayOf(0, 1, 1) ) // Invalid Maze val maze03 = arrayOf( intArrayOf(1, 0, 0), intArrayOf(0, 0, 0), intArrayOf(0, 0, 1) ) val mazes = arrayListOf<Array<IntArray>>() mazes.add(maze01) mazes.add(maze02) mazes.add(maze03) val ratMaze = RatMaze() for (i in 0 until mazes.size) { println("Solving Maze ${i + 1}") println() ratMaze.solve(mazes[i]) println() } }
121
C++
750
361
24518dd47bd998548e3e840c27968598396d30ee
3,279
FunnyAlgorithms
Creative Commons Zero v1.0 Universal
src/main/kotlin/net/danlew/wordle/wordleLogic.kt
dlew
446,149,485
false
{"Kotlin": 14254}
package net.danlew.wordle fun filterValidHardModeGuesses(wordList: List<String>, lastGuess: GuessResult): List<String> { return wordList.filter { guess -> validHardModeGuess(guess, lastGuess) } } fun validHardModeGuess(guess: String, lastGuess: GuessResult): Boolean { require(guess.length == lastGuess.guess.length) val unusedGuessLetters = mutableListOf<Char>() // Verify all correct letters are still present for (index in guess.indices) { if (lastGuess.hints[index] == Hint.CORRECT) { if (guess[index] != lastGuess.guess[index]) { return false } } else { unusedGuessLetters.add(guess[index]) } } // Verify misplaced letters are somewhere else val misplacedLetters = lastGuess.hints.mapIndexedNotNull { index, hint -> if (hint == Hint.MISPLACED) lastGuess.guess[index] else null } if (!unusedGuessLetters.containsAll(misplacedLetters)) { return false } return true } fun evaluateGuess(guess: String, target: String): List<Hint> { require(guess.length == target.length) { "guess and target are different lengths" } val length = guess.length val result = MutableList(length) { Hint.UNUSED } val unusedTargetLetters = target.toMutableList() // Find all correct letters first for (index in 0 until length) { val letter = guess[index] if (letter == target[index]) { result[index] = Hint.CORRECT unusedTargetLetters.remove(letter) } } // Find all letters in the wrong place for (index in 0 until length) { if (result[index] == Hint.CORRECT) continue val letter = guess[index] if (letter in unusedTargetLetters) { result[index] = Hint.MISPLACED unusedTargetLetters.remove(letter) } } return result } val List<Hint>.solved: Boolean get() = all { it == Hint.CORRECT }
0
Kotlin
1
12
73f46bf70178ab9aba6cdb6c2d7aadadf6ef7fa0
1,827
wordle-solver
MIT License
src/main/kotlin/kr/co/programmers/P1138.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers import kotlin.math.abs // https://leetcode.com/problems/alphabet-board-path/ class P1138 { fun alphabetBoardPath(target: String): String { var moves = "" var p = intArrayOf(0, 0) for (s in target) { // 아스키 코드의 특성을 이용한다. val t = (s - 97).toInt().run { intArrayOf(div(5), rem(5)) } // Z에서 다른 곳으로 이동하는 경우라면 미리 위로 한칸 간다. if (p[0] == 5 && p[0] - t[0] > 0) { moves += 'U' p = intArrayOf(p[0] - 1, p[1]) } // 왼쪽 또는 오른쪽으로 이동 if (t[1] - p[1] != 0) { val c = if (t[1] > p[1]) 'R' else 'L' repeat(abs(p[1] - t[1])) { moves += c } } // 위 또는 아래로 이동 if (t[0] - p[0] != 0) { val c = if (t[0] > p[0]) 'D' else 'U' repeat(abs(p[0] - t[0])) { moves += c } } // adds the character moves += "!" p = t } return moves } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,224
algorithm
MIT License
src/Day01.kt
ekgame
573,100,811
false
{"Kotlin": 20661}
fun main() { fun part1(input: List<String>): Int { return input .fold(mutableListOf<MutableList<Int>>(mutableListOf())) { acc, s -> if (s.isBlank()) { acc.add(mutableListOf()) } else { acc.last().add(s.toInt()) } acc } .maxOfOrNull { it.sum() } ?: 0 } fun part2(input: List<String>): Int { return input .fold(mutableListOf<MutableList<Int>>(mutableListOf())) { acc, s -> if (s.isBlank()) { acc.add(mutableListOf()) } else { acc.last().add(s.toInt()) } acc } .map { it.sum() } .sortedDescending() .take(3) .sum() } val testInput = readInput("01.test") check(part1(testInput) == 24000) val input = readInput("01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
0c2a68cedfa5a0579292248aba8c73ad779430cd
1,029
advent-of-code-2022
Apache License 2.0
src/main/kotlin/graph/EvaluateDivision.kt
ghonix
88,671,637
false
null
/** * https://leetcode.com/problems/evaluate-division/ */ package graph import java.util.* import kotlin.collections.HashMap import kotlin.collections.HashSet import kotlin.collections.LinkedHashSet class EvaluateDivision { data class Edge(val division: Double, val to: String) fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray { if (equations.size != values.size) { return doubleArrayOf(-1.0) } val graph = HashMap<String, MutableSet<Edge>>() // construct the division graph for (i in equations.indices) { if (equations[i].size < 2) { return doubleArrayOf(-1.0) } val first = equations[i][0] val second = equations[i][1] val division = values[i] graph.putIfAbsent(first, LinkedHashSet()) graph.putIfAbsent(second, LinkedHashSet()) graph[first]?.add(Edge(division, second)) graph[second]?.add(Edge(1/division, first)) } val output = Vector<Double>() for (query in queries) { output.add(calculate(graph, query[0], query[1])) } return output.toDoubleArray() } data class PathData(val node: String, val cost: Double) private fun calculate(graph: HashMap<String, MutableSet<Edge>>, src: String, dst: String): Double? { if (!graph.containsKey(src)) { return -1.0 } val visited = HashSet<String>() val queue: Queue<PathData> = LinkedList() queue.add(PathData(src, 1.0)) while(queue.isNotEmpty()) { val current = queue.poll() if (current.node == dst) { return current.cost } if (visited.contains(current.node)) { continue } visited.add(current.node) val neighbors = graph[current.node] if (neighbors != null) { for(neighbor in neighbors) { queue.add(PathData(neighbor.to, neighbor.division * current.cost)) } } } return -1.0 } }
0
Kotlin
0
2
25d4ba029e4223ad88a2c353a56c966316dd577e
2,300
Problems
Apache License 2.0
src/main/kotlin/days/aoc2023/Day1.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2023 import days.Day class Day1: Day(2023, 1) { override fun partOne(): Any { return calculatePartOne(inputList) } override fun partTwo(): Any { return calculatePartTwo(inputList) } fun calculatePartOne(input: List<String>): Int { return input.sumOf { line -> line.firstDigit() * 10 + line.lastDigit() } } fun calculatePartTwo(input: List<String>): Int { return input.sumOf { line -> line.firstDigit(true) * 10 + line.lastDigit(true) } } } fun String.firstDigit(includeSpelledOut: Boolean = false): Int { return getDigit(includeSpelledOut) } fun String.lastDigit(includeSpelledOut: Boolean = false): Int { return getDigit(includeSpelledOut, true) } fun String.getDigit(includeSpelledOut: Boolean, fromEnd: Boolean = false): Int { val numbers = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") if (includeSpelledOut) { for (i in (if (fromEnd) indices.reversed() else indices)) { if (this[i].isDigit()) { return this[i].digitToInt() } else { numbers.forEachIndexed { index, number -> if (i + number.length - 1 in indices) { if (substring(i, i + number.length) == number) { return index + 1 } } } } } } else { return if (fromEnd) last { it.isDigit() }.digitToInt() else first { it.isDigit() }.digitToInt() } throw IllegalStateException("That shouldn't happen") }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
1,670
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day17/Day17Puzzle1.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day17 import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver import kotlin.math.max class Day17Puzzle1 : PuzzleSolver { override fun solve(inputLines: Sequence<String>) = bruteForceHighestYPosition(inputLines.first()).toString() private fun bruteForceHighestYPosition(targetArea: String): Int { val targetAreaCoordinates = targetArea.removePrefix("target area: ").split(", ") val xTarget = targetAreaCoordinates[0].removePrefix("x=").toTargetRange() val yTarget = targetAreaCoordinates[1].removePrefix("y=").toTargetRange() var maxY = Int.MIN_VALUE for (startVelocityX in -1000..1000) { for (startVelocityY in -1000..1000) { var xPosition = 0 var yPosition = 0 var maxYForThisStartVelocities = 0 // We start at 0 for (step in 0..1000) { xPosition += max(0, startVelocityX - step) yPosition += startVelocityY - step if (yPosition > maxYForThisStartVelocities) maxYForThisStartVelocities = yPosition if (xPosition in xTarget && yPosition in yTarget && maxYForThisStartVelocities > maxY) { maxY = maxYForThisStartVelocities } if (xPosition > xTarget.last || yPosition < yTarget.first) break // beyond target, cannot hit it anymore } } } return maxY } private fun String.toTargetRange() = split("..").map { it.toInt() }.let { it[0]..it[1] } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
1,684
AdventOfCode2021
Apache License 2.0
src/day2/Code.kt
fcolasuonno
221,697,249
false
null
package day2 import java.io.File fun main() { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } fun parse(input: List<String>) = input.map { it.toList() }.requireNoNulls() val keypad = mapOf( 1 to Pair(-1, 1), 2 to Pair(0, 1), 3 to Pair(1, 1), 4 to Pair(-1, 0), 5 to Pair(0, 0), 6 to Pair(1, 0), 7 to Pair(-1, -1), 8 to Pair(0, -1), 9 to Pair(1, -1) ) val reverseKeypad = keypad.map { it.value to it.key }.toMap() class MultiNullMap<K> : HashMap<K, MultiNullMap.ValueMap<K>>(), MutableMap<K, MultiNullMap.ValueMap<K>> { class ValueMap<K> : HashMap<K, K?>(), MutableMap<K, K?> { override fun get(key: K) = super.get(key) } override fun get(key: K) = super.get(key) ?: ValueMap<K>().also { put(key, it) } } val crossPad = MultiNullMap<Char>().apply { this['5']['R'] = '6' this['2']['R'] = '3' this['2']['D'] = '6' this['6']['R'] = '7' this['6']['D'] = 'A' this['6']['L'] = '5' this['6']['U'] = '2' this['A']['R'] = 'B' this['A']['U'] = '6' this['1']['D'] = '3' this['3']['R'] = '4' this['3']['D'] = '7' this['3']['L'] = '2' this['3']['U'] = '1' this['7']['R'] = '8' this['7']['D'] = 'B' this['7']['L'] = '6' this['7']['U'] = '3' this['B']['R'] = 'C' this['B']['D'] = 'D' this['B']['L'] = 'A' this['B']['U'] = '7' this['D']['U'] = 'B' this['4']['D'] = '8' this['4']['L'] = '3' this['8']['R'] = '9' this['8']['D'] = 'C' this['8']['L'] = '7' this['8']['U'] = '4' this['C']['U'] = '8' this['C']['L'] = 'B' this['9']['L'] = '8' } fun part1(input: List<List<Char>>): Any? = input.fold(mutableListOf(5)) { combination, next -> combination.apply { val last = last() add(reverseKeypad.getValue(next.fold(keypad.getValue(last)) { pos, dir -> when (dir) { 'L' -> (pos.first - 1).coerceIn(-1, 1) to pos.second 'R' -> (pos.first + 1).coerceIn(-1, 1) to pos.second 'U' -> pos.first to (pos.second + 1).coerceIn(-1, 1) else -> pos.first to (pos.second - 1).coerceIn(-1, 1) } })) } }.drop(1).joinToString(separator = "") fun part2(input: List<List<Char>>): Any? = input.fold(mutableListOf('5')) { combination, next -> combination.apply { val last = last() add(next.fold(last) { pos, dir -> crossPad[pos][dir] ?: pos }) } }.drop(1).joinToString(separator = "")
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
2,736
AOC2016
MIT License
src/main/kotlin/net/voldrich/aoc2021/Day19.kt
MavoCz
434,703,997
false
{"Kotlin": 119158}
package net.voldrich.aoc2021 import net.voldrich.BaseDay import kotlin.math.abs import kotlin.math.max // link to task fun main() { Day19().run() } typealias ScFn = (Day19.ScannerPoint) -> Day19.ScannerPoint class Day19 : BaseDay() { override fun task1() : Int { return ScannerAnalyzer().findTotalPoints() } override fun task2() : Int { return ScannerAnalyzer().findMaxManhattanDistance() } inner class ScannerAnalyzer() { val scanners = parseScannerPoints() val transformationList : List<ScannerTransformation> init { val trList = ArrayList<ScannerTransformation>() for (i in scanners) { for (j in scanners) { if (i !== j) { val transformation = findTransformation(i, j) if (transformation != null) { trList.add(transformation) } } } } trList.forEach { println("${it.from.index} ${it.to.index}") } transformationList = trList } fun findTotalPoints() : Int { val resultPointSet = HashSet<ScannerPoint>() val targetScanner = scanners[0] resultPointSet.addAll(scanners[0].points) for (i in (1 until scanners.size)) { val from = scanners[i] val transformations = findTransitiveTransformationChain(from, targetScanner) println("scanner $i") val transformedTo0 = transformations.fold(from) { scanner, tr -> println("${tr.from.index} ${tr.to.index}") scanner.applyTransformation(tr.scfnWithShift) } resultPointSet.addAll(transformedTo0.points) } return resultPointSet.size } fun findMaxManhattanDistance() : Int { val scannerCenterPoints = ArrayList<ScannerPoint>() val targetScanner = scanners[0] scannerCenterPoints.add(ScannerPoint(0,0,0)) for (i in (1 until scanners.size)) { val from = scanners[i] val transformations = findTransitiveTransformationChain(from, targetScanner) val center = transformations[0].delta val centerTransformedTo0 = transformations.drop(1).fold(center) { point, tr -> tr.scfnWithShift.invoke(point) } scannerCenterPoints.add(centerTransformedTo0) } var max = Int.MIN_VALUE for (i in scannerCenterPoints.indices) { for (j in scannerCenterPoints.indices) { if (i > j) { max = max(max, scannerCenterPoints[i].distanceTo(scannerCenterPoints[j])) } } } return max } fun findTransitiveTransformationChain(from : Scanner, to : Scanner) : List<ScannerTransformation> { return findTransitiveTransformationChain(from, to, emptySet()) ?: throw Exception("Transformation chain not found to ${to.index}") } fun findTransitiveTransformationChain(from : Scanner, to : Scanner, visited : Set<Scanner>) : List<ScannerTransformation>? { transformationList.filter { it.from === from && !visited.contains(it.to) }.forEach { tr -> if (tr.to === to) { return listOf(tr) } else { val transitive = findTransitiveTransformationChain(tr.to, to, visited + setOf(from)) if (transitive != null) { return listOf(tr) + transitive } } } return null } fun findTransformation(from : Scanner, to: Scanner) : ScannerTransformation? { allTransformationOptions.forEach { scfn -> val s2Tr = from.applyTransformation(scfn) val deltaList = to.points.flatMap { s1point -> s2Tr.points.map { s2point -> s1point.delta(s2point) } }.toList() // group the points by their delta val deltaMap = HashMap<ScannerPoint, MutableList<Delta>>() deltaList.forEach { val list = deltaMap.computeIfAbsent(it.delta) { ArrayList() } list.add(it) } // if transformation is correct, 12 points should match val match = deltaMap.values.filter { it.size >= 12 }.toList() if (match.size == 1) { return ScannerTransformation(from, to, match[0], scfn) } } return null } fun parseScannerPoints() : ArrayList<Scanner> { val iterator = input.lines().iterator() val scannerList = ArrayList<Scanner>() while (iterator.hasNext()) { val scannerName = iterator.next() val pointList = ArrayList<ScannerPoint>() while (iterator.hasNext()) { val line = iterator.next() if (line.isBlank()) { break } val points = line.split(",").map { it.toInt() } pointList.add(ScannerPoint(points[0], points[1], points[2])) } scannerList.add(Scanner(scannerName, scannerList.size, pointList.toList())) pointList.clear() } return scannerList } } val trAxis = listOf<ScFn>( { point -> ScannerPoint(point.x, point.y, point.z) }, { point -> ScannerPoint(point.x, point.z, point.y) }, { point -> ScannerPoint(point.y, point.x, point.z) }, { point -> ScannerPoint(point.y, point.z, point.x) }, { point -> ScannerPoint(point.z, point.x, point.y) }, { point -> ScannerPoint(point.z, point.y, point.x) }, ) val trOrientation = listOf<ScFn>( { point -> ScannerPoint(point.x, point.y, point.z) }, { point -> ScannerPoint(-point.x, point.y, point.z) }, { point -> ScannerPoint(point.x, -point.y, point.z) }, { point -> ScannerPoint(point.x, point.y, -point.z) }, { point -> ScannerPoint(-point.x, -point.y, point.z) }, { point -> ScannerPoint(-point.x, point.y, -point.z) }, { point -> ScannerPoint(point.x, -point.y, -point.z) }, { point -> ScannerPoint(-point.x, -point.y, -point.z) }, ) val allTransformationOptions : List<ScFn> init { allTransformationOptions = trAxis.flatMap { axisFn -> trOrientation.map { orientFn -> { point : ScannerPoint -> axisFn.invoke(orientFn.invoke(point)) } } } .toList() } class Scanner(val name: String, val index : Int, val points: List<ScannerPoint>) { override fun toString(): String { return "$name \n${points.joinToString("\n")})\n" } fun applyTransformation(scfn: ScFn): Scanner { return Scanner(name, index, points.map(scfn).toList()) } } data class ScannerPoint(val x : Int, val y : Int, val z: Int) { override fun toString(): String { return "$x,$y,$z" } fun delta(other: ScannerPoint) : Delta { return Delta(ScannerPoint(this.x - other.x, this.y - other.y, this.z - other.z), this, other) } fun distanceTo(other: ScannerPoint): Int { return abs(x - other.x) + abs(y - other.y) + abs(z - other.z) } } data class Delta(val delta : ScannerPoint, val p1 : ScannerPoint, val p2 : ScannerPoint) data class ScannerTransformation(val from: Scanner, val to: Scanner, val points : List<Delta>, val scfn: ScFn) { val delta = points[0].delta val scfnWithShift = { point : ScannerPoint -> val fn = scfn.invoke(point) ScannerPoint(fn.x + delta.x, fn.y + delta.y, fn.z + delta.z) } } }
0
Kotlin
0
0
0cedad1d393d9040c4cc9b50b120647884ea99d9
8,267
advent-of-code
Apache License 2.0
src/main/kotlin/day10/Solution.kt
TestaDiRapa
573,066,811
false
{"Kotlin": 50405}
package day10 import java.io.File data class RegisterHistory( val history: Map<Int, Int> = mapOf(0 to 1) ) { fun addNoOp(): RegisterHistory { val lastClock = history.keys.last() val lastRegister = history.values.last() return this.copy(history = history + (lastClock+1 to lastRegister)) } fun addAddxOp(amount: Int): RegisterHistory { val lastClock = history.keys.last() val lastRegister = history.values.last() return this.copy(history = history + (lastClock + 2 to lastRegister + amount)) } fun getRegisterValueAtClock(clock: Int) = history.keys.last { it < clock }.let { history[it] } ?: 0 } data class CrtRender( val crt: List<Char> = emptyList() ) { fun renderSprite(spriteCenter: Int): CrtRender = if (crt.size < 240) { val adjustedSprite = spriteCenter + (crt.size/40) * 40 if (crt.size >= adjustedSprite-1 && crt.size <= adjustedSprite+1) this.copy(crt = crt + listOf('#')) else this.copy(crt = crt + listOf('.')) } else this fun printRendered() { crt.chunked(40).onEach { println(String(it.toCharArray())) } } } fun parseInputFile() = File("src/main/kotlin/day10/input.txt") .readLines() .fold(RegisterHistory()) { acc, cmd -> if(cmd == "noop") acc.addNoOp() else { val (_, amount) = cmd.split(" ") acc.addAddxOp(amount.toInt()) } } fun findSignalLevelAtClocks() = parseInputFile() .let { registerHistory -> List(6){ it*40+20 }.fold(0) { sum, it -> sum + registerHistory.getRegisterValueAtClock(it)*it } } fun renderCrt() = parseInputFile() .let { (1 .. 240).fold(CrtRender()) { crt, clock -> crt.renderSprite(it.getRegisterValueAtClock(clock)) }.printRendered() } fun main() { println("The sum of the signal strengths during the 20th, 60th, 100th, 140th, 180th, and 220th cycles is: ${findSignalLevelAtClocks()}") println("The final CRT render is:") renderCrt() }
0
Kotlin
0
0
b5b7ebff71cf55fcc26192628738862b6918c879
2,178
advent-of-code-2022
MIT License
LeetCode/Kotlin/TopKFrequent.kt
vale-c
177,558,551
false
null
/** * 347. Top K Frequent Elements * https://leetcode.com/problems/top-k-frequent-elements/ */ class Solution { fun topKFrequent(nums: IntArray, k: Int): List<Int> { val frequencyMap = mutableMapOf<Int, Int>() var maxCount = 0 nums.forEach { val currentFrequency = frequencyMap.computeIfAbsent(it) {0} + 1 maxCount = Math.max(maxCount, currentFrequency) frequencyMap.put(it, currentFrequency) } val groupedFrequencies = mutableMapOf<Int, MutableList<Int>>() frequencyMap.forEach { number, frequency -> groupedFrequencies.computeIfAbsent(frequency) {mutableListOf()} .add(number) } val topK = mutableListOf<Int>() var count = 0 while (count < k) { if (groupedFrequencies.contains(maxCount)) { val numbers = groupedFrequencies[maxCount]!! while (!numbers.isEmpty()) { topK.add(numbers.get(numbers.size-1)) numbers.removeAt(numbers.size-1) count++ } } maxCount-- } return topK } }
0
Java
5
9
977e232fa334a3f065b0122f94bd44f18a152078
1,095
CodingInterviewProblems
MIT License
src/main/kotlin/kr/co/programmers/P86052.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://github.com/antop-dev/algorithm/issues/409 class P86052 { companion object { const val UP = 0 const val RIGHT = 1 const val DOWN = 2 const val LEFT = 3 } fun solution(grid: Array<String>): IntArray { // 각 격자에서 네방향으로 이동한 기록 val memo = Array(grid.size) { Array(grid[0].length) { intArrayOf(0, 0, 0, 0) } } val steps = mutableListOf<Int>() for (i in memo.indices) { for (j in memo[i].indices) { for (k in 0 until 4) { // 4방향으로 빛을 쏜다. var y = i var x = j var d = k var step = 0 while (memo[y][x][d] == 0) { memo[y][x][d] = 1 step++ // 다음 격자로 이동 했다. y += when (d) { UP -> -1 DOWN -> 1 else -> 0 } if (y < 0) y = memo.lastIndex if (y > memo.lastIndex) y = 0 x += when (d) { RIGHT -> 1 LEFT -> -1 else -> 0 } if (x < 0) x = memo[0].lastIndex if (x > memo[0].lastIndex) x = 0 // 이동한 격자에서 이동할 방향을 구한다. when (grid[y][x]) { 'L' -> { d-- if (d < 0) d = LEFT } 'R' -> { d++ if (d > 3) d = UP } } } if (step > 0) steps += step } } } return steps.sorted().toIntArray() } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
2,184
algorithm
MIT License
src/main/kotlin/Day3_2.kt
vincent-mercier
726,287,758
false
{"Kotlin": 37963}
import java.io.File import java.io.InputStream import kotlin.streams.asSequence fun getGearRatios(input: List<Pair<List<MatchResult>, Sequence<Int>>>): List<Int> = input.flatMapIndexed { index: Int, pair: Pair<List<MatchResult>, Sequence<Int>> -> when (index) { 0 -> { pair.second.map { val nbs = (validInts(index, it, input[index].first) + validInts(index + 1, it, input[index + 1].first)) if (nbs.size == 2) { nbs[0].second * nbs[1].second } else { 0 } } } input.size - 1 -> { pair.second.map { val nbs = (validInts(index - 1, it, input[index - 1].first) + validInts(index, it, input[index].first)) if (nbs.size == 2) { nbs[0].second * nbs[1].second } else { 0 } } } else -> { pair.second.map { val nbs = (validInts(index - 1, it, input[index - 1].first) + validInts(index, it, input[index].first) + validInts(index + 1, it, input[index + 1].first)) if (nbs.size == 2) { nbs[0].second * nbs[1].second } else { 0 } } } }.toList() } fun main() { val inputStream: InputStream = File("./src/main/resources/day3.txt").inputStream() val intRegex = "(\\d+)".toRegex() val input = inputStream.bufferedReader().lines() .asSequence() .map { c -> val intMatches = intRegex.findAll(c).toList() val potentialGearIndices = c.asSequence() .mapIndexed { i2, c2 -> i2 to (c2 == '*') } .filter { it.second } .map { it.first } intMatches to potentialGearIndices } .toList() println( getGearRatios(input).sum() ) }
0
Kotlin
0
0
53b5d0a0bb65a77deb5153c8a912d292c628e048
2,236
advent-of-code-2023
MIT License
core/src/main/kotlin/com/bsse2018/salavatov/flt/algorithms/Hellings.kt
vsalavatov
241,599,920
false
{"Kotlin": 149462, "ANTLR": 1960}
package com.bsse2018.salavatov.flt.algorithms import com.bsse2018.salavatov.flt.grammars.ContextFreeGrammar import com.bsse2018.salavatov.flt.utils.Graph import java.util.* import kotlin.collections.MutableSet fun HellingsQuery(graph: Graph, wcnf: ContextFreeGrammar): MutableSet<Pair<Int, Int>> { val dp = List(graph.size) { List(graph.size) { mutableSetOf<String>() } } val queue = ArrayDeque<Triple<String, Int, Int>>() val epsilonRules = wcnf.rules.filter { it.isEpsilon() } val symRules = wcnf.rules.filter { it.isTerminal() } graph.forEachIndexed { u, edges -> epsilonRules.forEach { rule -> if (!dp[u][u].contains(rule.from)) { dp[u][u].add(rule.from) queue.add(Triple(rule.from, u, u)) } } edges.forEach { edge -> val v = edge.second symRules.filter { edge.first == it.to[0] } .forEach { rule -> if (!dp[u][v].contains(rule.from)) { dp[u][v].add(rule.from) queue.add(Triple(rule.from, u, v)) } } } } while (queue.isNotEmpty()) { val (nonTerm, u, v) = queue.pop() for (ufrom in dp.indices) { val postponedAdd = mutableSetOf<String>() dp[ufrom][u].forEach { nonTermBefore -> wcnf.rules .filter { it.to == listOf(nonTermBefore, nonTerm) } .forEach { rule -> if (!dp[ufrom][v].contains(rule.from) && !postponedAdd.contains(rule.from)) { postponedAdd.add(rule.from) queue.add(Triple(rule.from, ufrom, v)) } } } dp[ufrom][v].addAll(postponedAdd) } for (vto in dp.indices) { val postponedAdd = mutableSetOf<String>() dp[v][vto].forEach { nonTermAfter -> wcnf.rules .filter { it.to == listOf(nonTerm, nonTermAfter) } .forEach { rule -> if (!dp[u][vto].contains(rule.from) && !postponedAdd.contains(rule.from)) { postponedAdd.add(rule.from) queue.add(Triple(rule.from, u, vto)) } } } dp[u][vto].addAll(postponedAdd) } } val result = mutableSetOf<Pair<Int, Int>>() for (u in dp.indices) { for (v in dp.indices) { if (dp[u][v].contains(wcnf.start)) result.add(Pair(u, v)) } } return result }
0
Kotlin
0
1
c1c229c113546ef8080fc9d3568c5024a22b80a5
2,713
bsse-2020-flt
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-02.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2021, "02-input") val test1 = readInputLines(2021, "02-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 { var dist = 0 var depth = 0 val regex = """(\w+) (\d+)""".toRegex() input.forEach { val (command, size) = regex.matchEntire(it)!!.destructured when (command) { "forward" -> { dist += size.toInt() } "down" -> { depth += size.toInt() } "up" -> { depth -= size.toInt() } } } return dist * depth } private fun part2(input: List<String>): Int { var dist = 0 var depth = 0 var aim = 0 val regex = """(\w+) (\d+)""".toRegex() input.forEach { val (command, size) = regex.matchEntire(it)!!.destructured when (command) { "forward" -> { dist += size.toInt() depth += aim * size.toInt() } "down" -> { aim += size.toInt() } "up" -> { aim -= size.toInt() } } } return dist * depth }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,371
advent-of-code
MIT License
src/main/kotlin/g2601_2700/s2603_collect_coins_in_a_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2601_2700.s2603_collect_coins_in_a_tree // #Hard #Array #Tree #Graph #Topological_Sort // #2023_07_13_Time_986_ms_(100.00%)_Space_67.7_MB_(100.00%) class Solution { private lateinit var coins: IntArray private var n = 0 private lateinit var graph: Array<ArrayList<Int>?> private var sum = 0 private var ret = 0 fun collectTheCoins(coins: IntArray, edges: Array<IntArray>): Int { n = coins.size this.coins = coins graph = arrayOfNulls(n) for (i in 0 until n) { graph[i] = ArrayList() } for (edge in edges) { graph[edge[0]]!!.add(edge[1]) graph[edge[1]]!!.add(edge[0]) } for (coin in coins) { sum += coin } dfs(0, -1) return (2 * (ret - 1)).coerceAtLeast(0) } private fun dfs(node: Int, pre: Int): Int { var cnt = 0 var s = 0 for (nn in graph[node]!!) { if (nn != pre) { val r = dfs(nn, node) if (r - coins[nn] > 0) cnt++ s += r } } if (pre != -1 && sum - s - coins[node] - coins[pre] > 0) { cnt++ } if (cnt >= 2) { ret++ } return s + coins[node] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,302
LeetCode-in-Kotlin
MIT License
backend/src/main/kotlin/com/example/tictactoe/model/Winner.kt
ezhaka
140,628,510
false
{"JavaScript": 112184, "Kotlin": 56312, "HTML": 2377, "SCSS": 1686, "Procfile": 83}
package com.example.tictactoe.model import kotlin.ranges.IntProgression.Companion.fromClosedRange data class Winner( val userId: String, val ranges: List<CoordinateRange> ) data class CoordinateRange( val from: Coordinates, val to: Coordinates ) class WinnerCalculator(private val movesMap: Map<Coordinates, Move>, private val lastMove: Move) { private val coordinates = lastMove.coordinates fun get(): Winner? { val rightUpSequence = diagonalSequence(descendingRange(coordinates.row), ascendingRange(coordinates.column)) val leftDownSequence = diagonalSequence(ascendingRange(coordinates.row), descendingRange(coordinates.column)) val leftUpSequence = diagonalSequence(descendingRange(coordinates.row), descendingRange(coordinates.column)) val rightDownSequence = diagonalSequence(ascendingRange(coordinates.row), ascendingRange(coordinates.column)) val leftSequence = movesSequence(expandRow(descendingRange(coordinates.column))) val rightSequence = movesSequence(expandRow(ascendingRange(coordinates.column))) val upSequence = movesSequence(expandColumn(descendingRange(coordinates.row))) val downSequence = movesSequence(expandColumn(ascendingRange(coordinates.row))) val winningRanges = sequenceOf( Pair(leftDownSequence, rightUpSequence), Pair(leftUpSequence, rightDownSequence), Pair(leftSequence, rightSequence), Pair(upSequence, downSequence) ) .map { (from, to) -> CoordinateRange(expand(from).coordinates, expand(to).coordinates) } .filter { (from, to) -> val length = Integer.max(to.row - from.row, to.column - from.column) + 1 length >= K_PARAM } .toList() return if (winningRanges.isEmpty()) null else Winner(lastMove.userId, winningRanges) } private fun expandColumn(range: Sequence<Int>) = range.map { row -> Coordinates(row, coordinates.column) } private fun expandRow(range: Sequence<Int>) = range.map { column -> Coordinates(coordinates.row, column) } private fun movesSequence(pairs: Sequence<Coordinates>): Sequence<Move?> { return pairs .filter { (row, column) -> row in 0..(BOARD_SIZE - 1) && column in 0..(BOARD_SIZE - 1) } .map { (row, column) -> Coordinates(row, column) } .map { movesMap[it] } } private fun diagonalSequence(rowRange: Sequence<Int>, columnRange: Sequence<Int>): Sequence<Move?> { return movesSequence(rowRange.zip(columnRange).map { (row, column) -> Coordinates(row, column) }) } private fun expand(sequence: Sequence<Move?>): Move { return sequence .takeWhile { move: Move? -> move != null && move.userId == lastMove.userId } .last()!! } private fun ascendingRange(coordinate: Int): Sequence<Int> { return fromClosedRange(coordinate, coordinate + (K_PARAM - 1), 1).asSequence() } private fun descendingRange(coordinate: Int): Sequence<Int> { return fromClosedRange(coordinate, coordinate - (K_PARAM - 1), -1).asSequence() } }
0
JavaScript
0
1
359d6ee3251505e41223583e11bdc58c8e7de2fa
3,221
tic-tac-toe
MIT License
src/day06/Day06.kt
pnavais
574,712,395
false
{"Kotlin": 54079}
package day06 import readInput private fun readPackets(input: List<String>, maxLength: Int): List<Pair<String, Long>> { return input.map { s -> var idx = 0L val charSet = HashSet<Char>() var packetMarker = mutableListOf<Char>() for (c in s.toCharArray()) { idx++ if (charSet.contains(c)) { packetMarker = packetMarker.subList(packetMarker.indexOf(c)+1, packetMarker.size) charSet.clear() packetMarker.forEach(charSet::add) } packetMarker.add(c) charSet.add(c) if (packetMarker.size == maxLength) { break } } s to idx }.toList() } fun part1(input: List<String>): List<Pair<String, Long>> { return readPackets(input, 4) } fun part2(input: List<String>): List<Pair<String, Long>> { return readPackets(input, 14) } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day06/Day06_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
ed5f521ef2124f84327d3f6c64fdfa0d35872095
1,167
advent-of-code-2k2
Apache License 2.0
src/main/kotlin/Day09.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.time.LocalDateTime import java.time.ZoneOffset fun main() { fun part1(input: List<String>): Int { return input.sumOf { line -> var ints = line.split(" ").map { it.toInt() } var sum = 0 while (ints.any { it != 0 }) { sum += ints.last val zipped = ints.zipWithNext { a: Int, b: Int -> b - a } ints = zipped } sum } } fun part2(input: List<String>): Int { return input.sumOf { line -> var ints = line.split(" ").map { it.toInt() } val firsts = mutableListOf<Int>() while (ints.any { it != 0 }) { firsts.add(ints.first) val zipped = ints.zipWithNext { a: Int, b: Int -> b - a } ints = zipped } firsts.reversed().fold(0) { acc, i -> i - acc } as Int } } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val input = readLines("day09-input.txt") val result1 = part1(input) "Result1: $result1".println() val result2 = part2(input) "Result2: $result2".println() println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms") }
0
Kotlin
0
0
41f376bd71a8449e05bbd5b9dd03b3019bde040b
1,310
aoc-2023-in-kotlin
Apache License 2.0
year2022/src/main/kotlin/net/olegg/aoc/year2022/day11/Day11.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2022.day11 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.parseLongs import net.olegg.aoc.year2022.DayOf2022 /** * See [Year 2022, Day 11](https://adventofcode.com/2022/day/11) */ object Day11 : DayOf2022(11) { override fun first(): Any? { val monkeys = parseMonkeys() val inspected = MutableList(monkeys.size) { 0 } repeat(20) { monkeys.forEachIndexed { index, monkey -> inspected[index] += monkey.items.size while (monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() val newItem = monkey.op.apply(item) / 3 val target = if (newItem % monkey.test == 0L) monkey.targets.first else monkey.targets.second monkeys[target].items += newItem } } } return inspected .sortedDescending() .take(2) .reduce(Int::times) } override fun second(): Any? { val monkeys = parseMonkeys() val modulo = monkeys.map { it.test }.reduce(Long::times) val inspected = MutableList(monkeys.size) { 0L } repeat(10000) { monkeys.forEachIndexed { index, monkey -> inspected[index] += monkey.items.size.toLong() while (monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() val newItem = monkey.op.apply(item) % modulo val target = if (newItem % monkey.test == 0L) monkey.targets.first else monkey.targets.second monkeys[target].items += newItem } } } return inspected .sortedDescending() .take(2) .reduce(Long::times) } private fun parseMonkeys(): List<Monkey> { return data.split("\n\n") .map { monkeyData -> val lines = monkeyData.lines() val number = lines[0].split(" ").last().dropLast(1).toInt() val items = lines[1].substringAfter(": ").parseLongs(", ") val (rawOp, value) = lines[2].split(" ").takeLast(2) val op = when (rawOp) { "+" -> Op.Add(value.toLongOrNull()?.let { Arg.Val(it) } ?: Arg.Self) "*" -> Op.Mult(value.toLongOrNull()?.let { Arg.Val(it) } ?: Arg.Self) else -> error("Unable to parse $rawOp") } val test = lines[3].split(" ").last().toLong() val ifTrue = lines[4].split(" ").last().toInt() val ifFalse = lines[5].split(" ").last().toInt() Monkey( number = number, items = ArrayDeque(items), op = op, test = test, targets = ifTrue to ifFalse, ) } } data class Monkey( val number: Int, val items: ArrayDeque<Long>, val op: Op, val test: Long, val targets: Pair<Int, Int>, ) sealed interface Op { fun apply(to: Long): Long data class Add( val value: Arg, ) : Op { override fun apply(to: Long): Long = to + value.apply(to) } data class Mult( val value: Arg, ) : Op { override fun apply(to: Long): Long = to * value.apply(to) } } sealed interface Arg { fun apply(to: Long): Long data class Val( val value: Long, ) : Arg { override fun apply(to: Long): Long = value } object Self : Arg { override fun apply(to: Long): Long = to } } } fun main() = SomeDay.mainify(Day11)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
3,301
adventofcode
MIT License
advent-of-code-2019/src/test/java/Day10MonitoringStation.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import org.assertj.core.api.AbstractFloatAssert import org.assertj.core.api.Assertions.assertThat import org.assertj.core.data.Percentage import org.junit.Test import kotlin.math.PI import kotlin.math.atan2 import kotlin.math.sqrt class Day10MonitoringStation { data class Asteroid(val x: Int, val y: Int) { override fun toString(): String = "($x, $y)" } private fun parseInput(input: String): List<Asteroid> { return input .lines() .mapIndexed { y, line -> line to y } .flatMap { (line, y): Pair<String, Int> -> line.mapIndexedNotNull { x, char: Char -> when (char) { '#' -> Asteroid(x, y) else -> null } } } } private fun Asteroid.angleTo(center: Asteroid): Float { // mind the inverted y axle return atan2(-(y - center.y).toDouble(), (x - center.x).toDouble()).toFloat() } private fun mostVisibleAsteroids(input: String): Pair<Asteroid, Int> { val asteroids: List<Asteroid> = parseInput(input) val asteroidToDistinctAngles = asteroids.map { center -> val distinctAngles = asteroids.minus(center) .map { asteroid -> asteroid.angleTo(center) } .distinct() .size center to distinctAngles } return asteroidToDistinctAngles.maxBy { (asteroid, distinctAngles) -> distinctAngles }!! } @Test fun atan() { fun AbstractFloatAssert<*>.isCloseTo(other: Double) { isCloseTo(other.toFloat(), Percentage.withPercentage(10.0)) } assertThat(Asteroid(0, -10).angleTo(Asteroid(0, 0))).isCloseTo(PI / 2) assertThat(Asteroid(10, 0).angleTo(Asteroid(0, 0))).isCloseTo(0.0) assertThat(Asteroid(-10, 0).angleTo(Asteroid(0, 0))).isCloseTo(-PI) assertThat(Asteroid(-10, 1).angleTo(Asteroid(0, 0))).isCloseTo(-PI) assertThat(Asteroid(0, 10).angleTo(Asteroid(0, 0))).isCloseTo(-PI / 2) } @Test fun goldStar() { val vaporised = vaporisations(parseInput(testInput), Asteroid(27, 19)) assertThat(vaporised[-1 + 200]).isEqualTo(Asteroid(15, 13)) assertThat(vaporised[-1 + 200].x * 100 + vaporised[-1 + 200].y).isEqualTo(1513) } fun vaporisations(asteroids: List<Asteroid>, center: Asteroid): List<Asteroid> { fun Asteroid.degAngle(): Float { val rad = atan2(/* inverted Y axle */-(y - center.y).toDouble(), (x - center.x).toDouble()) val grad = Math.toDegrees(rad) return (-grad + 360 + 90).toFloat() % 360 } /** Angle in parts of PI */ fun Asteroid.piAngle(): Float { val rad = atan2(/* inverted Y axle */-(y - center.y).toDouble(), (x - center.x).toDouble()) val pgrad = rad / PI return (-pgrad + 2.5f).toFloat() % 2 } fun Asteroid.distance(): Double { return sqrt(((x - center.x).square() + (y - center.y).square())) } val shootings = asteroids .minus(center) .sortedBy { it.piAngle() } .groupBy { it.piAngle() } .mapValues { (key, value) -> value.sortedBy { it.distance() } } shootings.forEach { // println(it) } val bingo = generateSequence(0 to emptyList<Asteroid>()) { (index, _) -> index + 1 to shootings.values.mapNotNull { it.getOrNull(index) } } .take(10) .flatMap { (index, seq) -> seq.asSequence() } .take(333) .toList() bingo.forEachIndexed { index, it -> val (x, y) = it // println("$index grad: ${it.piAngle()} (${x - center.x}, ${y - center.y}), ($x, $y)") } return bingo } @Test fun verifyGoldStar() { val vaporised = vaporisations( parseInput( """ .#..##.###...####### ##.############..##. .#.######.########.# .###.#######.####.#. #####.##.#.##.###.## ..#####..#.######### #################### #.####....###.#.#.## ##.################# #####.##.###..####.. ..######..##.####### ####.##.####...##..# .#####..#.######.### ##...#.##########... #.##########.####### .####.#.###.###.#.## ....##.##.###..##### .#.#.###########.### #.#.#.#####.####.### ###.##.####.##.#..## """.trimIndent() ), Asteroid(11, 13) ) assertThat(vaporised[-1 + 1]).isEqualTo(Asteroid(11, 12)) assertThat(vaporised[-1 + 2]).isEqualTo(Asteroid(12, 1)) assertThat(vaporised[-1 + 3]).isEqualTo(Asteroid(12, 2)) assertThat(vaporised[-1 + 10]).isEqualTo(Asteroid(12, 8)) assertThat(vaporised[-1 + 20]).isEqualTo(Asteroid(16, 0)) assertThat(vaporised[-1 + 50]).isEqualTo(Asteroid(16, 9)) assertThat(vaporised[-1 + 100]).isEqualTo(Asteroid(10, 16)) assertThat(vaporised[-1 + 199]).isEqualTo(Asteroid(9, 6)) assertThat(vaporised[-1 + 200]).isEqualTo(Asteroid(8, 2)) assertThat(vaporised[-1 + 201]).isEqualTo(Asteroid(10, 9)) // assertThat(shooted[-1 + 299]).isEqualTo(Asteroid(11, 1)) } @Test fun verifySilverStar1() { assertThat( mostVisibleAsteroids( """ .#..# ..... ##### ....# ...## """.trimIndent() ) ).isEqualTo(Asteroid(3, 4) to 8) } @Test fun verifSilverStar2() { assertThat( mostVisibleAsteroids( """ ......#.#. #..#.#.... ..#######. .#.#.###.. .#..#..... ..#....#.# #..#....#. .##.#..### ##...#..#. .#....#### """.trimIndent() ) ).isEqualTo(Asteroid(5, 8) to 33) } @Test fun verifySilverStar3() { assertThat( mostVisibleAsteroids( """ #.#...#.#. .###....#. .#....#... ##.#.#.#.# ....#.#.#. .##..###.# ..#...##.. ..##....## ......#... .####.###. """.trimIndent() ) ).isEqualTo(Asteroid(1, 2) to 35) } @Test fun verifySilverStar4() { assertThat( mostVisibleAsteroids( """ .#..#..### ####.###.# ....###.#. ..###.##.# ##.##.#.#. ....###..# ..#.#..#.# #..#.#.### .##...##.# .....#.#.. """.trimIndent() ) ).isEqualTo(Asteroid(6, 3) to 41) } @Test fun verifySilverStar5() { assertThat( mostVisibleAsteroids( """ .#..##.###...####### ##.############..##. .#.######.########.# .###.#######.####.#. #####.##.#.##.###.## ..#####..#.######### #################### #.####....###.#.#.## ##.################# #####.##.###..####.. ..######..##.####### ####.##.####...##..# .#####..#.######.### ##...#.##########... #.##########.####### .####.#.###.###.#.## ....##.##.###..##### .#.#.###########.### #.#.#.#####.####.### ###.##.####.##.#..## """.trimIndent() ) ).isEqualTo(Asteroid(11, 13) to 210) } @Test fun silverStar() { assertThat(mostVisibleAsteroids(testInput)).isEqualTo(Asteroid(27, 19) to 314) } private val testInput = """ ..#..###....#####....###........# .##.##...#.#.......#......##....# #..#..##.#..###...##....#......## ..####...#..##...####.#.......#.# ...#.#.....##...#.####.#.###.#..# #..#..##.#.#.####.#.###.#.##..... #.##...##.....##.#......#.....##. .#..##.##.#..#....#...#...#...##. .#..#.....###.#..##.###.##....... .##...#..#####.#.#......####..... ..##.#.#.#.###..#...#.#..##.#.... .....#....#....##.####....#...... .#..##.#.........#..#......###..# #.##....#.#..#.#....#.###...#.... .##...##..#.#.#...###..#.#.#..### .#..##..##...##...#.#.#...#..#.#. .#..#..##.##...###.##.#......#... ...#.....###.....#....#..#....#.. .#...###..#......#.##.#...#.####. ....#.##...##.#...#........#.#... ..#.##....#..#.......##.##.....#. .#.#....###.#.#.#.#.#............ #....####.##....#..###.##.#.#..#. ......##....#.#.#...#...#..#..... ...#.#..####.##.#.........###..## .......#....#.##.......#.#.###... ...#..#.#.........#...###......#. .#.##.#.#.#.#........#.#.##..#... .......#.##.#...........#..#.#... .####....##..#..##.#.##.##..##... .#.#..###.#..#...#....#.###.#..#. ............#...#...#.......#.#.. .........###.#.....#..##..#.##... """.trimIndent() } private fun Int.square() = (this * this).toDouble()
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
8,638
advent-of-code
MIT License
src/adventofcode/day01/Day01.kt
bstoney
574,187,310
false
{"Kotlin": 27851}
package adventofcode.day01 import adventofcode.AdventOfCodeSolution import adventofcode.split fun main() { Solution.solve() } object Solution : AdventOfCodeSolution<Int>() { override fun solve() { solve(1, 24000, 45000) } override fun part1(input: List<String>): Int { return getMaxCarriedCalories(input) } override fun part2(input: List<String>): Int { return getTotalTopCarriedCalories(input, 3) } private fun getMaxCarriedCalories(input: List<String>): Int { return getElvesCalories(input).max() } private fun getTotalTopCarriedCalories(input: List<String>, limit: Int): Int { return getElvesCalories(input).sorted().reversed().take(limit).sum() } private fun getElvesCalories(input: List<String>) = getElvesItemCalories(input).map { it.sum() } private fun getElvesItemCalories(input: List<String>): List<List<Int>> { return input.split { it.isEmpty() } .map { it.map(String::toInt).toList() } .toList() } }
0
Kotlin
0
0
81ac98b533f5057fdf59f08940add73c8d5df190
1,048
fantastic-chainsaw
Apache License 2.0
2020/day18/day18.kt
flwyd
426,866,266
false
{"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398}
/* * Copyright 2021 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package day18 import kotlin.time.ExperimentalTime import kotlin.time.TimeSource import kotlin.time.measureTimedValue /* Input: Lines of infix expressions with only +, *, parentheses, and integers. Output: sum of expression value of each line. */ sealed class Token { interface Operator { fun op(a: Long, b: Long): Long } data class Number(val value: Long) : Token() object OpenParen : Token() object CloseParen : Token() object Plus : Token(), Operator { override fun op(a: Long, b: Long) = a + b } object Times : Token(), Operator { override fun op(a: Long, b: Long) = a * b } } val tokenPattern = Regex("""(\d+|[+*()])""") fun parse(line: String): List<Token> = tokenPattern.findAll(line).map { when (val str = it.groupValues.first()) { "+" -> Token.Plus "*" -> Token.Times "(" -> Token.OpenParen ")" -> Token.CloseParen else -> Token.Number(str.toLong()) } }.toList() /* Parenthesized expressions first, but no precedence difference between + and *. */ object Part1 { private fun evaluate(tokens: Iterator<Token>): Long { var result = 0L var operator: Token.Operator = Token.Plus while (tokens.hasNext()) { when (val token = tokens.next()) { is Token.Number -> result = operator.op(result, token.value) is Token.Plus -> operator = token is Token.Times -> operator = token is Token.OpenParen -> result = operator.op(result, evaluate(tokens)) is Token.CloseParen -> return result } } return result } fun solve(input: Sequence<String>): String { return input.map(::parse).map { evaluate(it.iterator()) }.sum().toString() } } /* Parenthesized expressions first, + has higher precedence than *. */ object Part2 { private fun evaluate(tokens: Iterator<Token>): Long { val operators = ArrayDeque<Token.Operator>() val numbers = ArrayDeque<Long>() operators.addLast(Token.Plus) numbers.addLast(0L) fun accumulate(value: Long) { when (operators.lastOrNull()) { is Token.Plus -> numbers.addLast(operators.removeLast().op(numbers.removeLast(), value)) is Token.Times -> numbers.addLast(value) else -> error("Accumulating $value on operator stack $operators") } } fun calculate(): Long { while (!operators.isEmpty()) { numbers.addLast(operators.removeLast().op(numbers.removeLast(), numbers.removeLast())) } check(numbers.size == 1) { "Expecting just one number, got $numbers" } return numbers.removeLast() } for (token in tokens) { when (token) { is Token.Number -> accumulate(token.value) is Token.Plus -> operators.addLast(token) is Token.Times -> operators.addLast(token) is Token.OpenParen -> accumulate(evaluate(tokens)) is Token.CloseParen -> return calculate() } } return calculate() } fun solve(input: Sequence<String>): String { return input.map(::parse).map { evaluate(it.iterator()) }.sum().toString() } } @ExperimentalTime @Suppress("UNUSED_PARAMETER") fun main(args: Array<String>) { val lines = generateSequence(::readLine).toList() print("part1: ") TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } print("part2: ") TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } }
0
Julia
1
5
f2d6dbb67d41f8f2898dbbc6a98477d05473888f
3,722
adventofcode
MIT License
src/shmulik/klein/day01/Day01.kt
shmulik-klein
573,426,488
false
{"Kotlin": 9136}
fun main() { fun getCaloriesList(input: List<String>): List<Int> { val result: MutableList<Int> = mutableListOf() var current = 0 for (row in input) { if (row.isEmpty()) { result.add(current) current = 0 continue } current += Integer.valueOf(row) } result.add(current) return result.toList() } fun part1(input: List<String>): Int { val max: List<Int> = getCaloriesList(input) return max.max() } fun part2(input: List<String>): Int { val descendCaloriesList: List<Int> = getCaloriesList(input).sortedDescending() var sum = 0 for (i in 0..2) { sum += descendCaloriesList[i] } return sum } val input = readInput("shmulik/klein/day01/Day01_test") val result1 = part1(input) println(result1) val result2 = part2(input) println(result2) }
0
Kotlin
0
0
4d7b945e966dad8514ec784a4837b63a942882e9
980
advent-of-code-2022
Apache License 2.0
src/main/kotlin/expressions/Expression.kt
rinatisk
355,830,207
false
null
package expressions import exceptions.ParseException import exceptions.TypeException import expressions.bool.* import expressions.num.* import kotlin.math.max interface Expression open class BinaryExpression(open val leftPart: Expression, open val rightPart: Expression, open val type: String) : Expression open class NumberBinaryExpression(override val leftPart: Expression, override val rightPart: Expression, override val type: String) : BinaryExpression(leftPart, rightPart, type) { override fun toString(): String = "($leftPart$type$rightPart)" } class PolynomialImplementation(val coefficientList: MutableList<Int>) { val degree get() = coefficientList.size - 1 fun equals(toCheck: PolynomialImplementation): Boolean { val result = true if (degree != toCheck.degree) return false for (i in 0..degree) result.and(coefficientList[i] == toCheck.coefficientList[i]) return result } fun plus(toPlus: PolynomialImplementation): PolynomialImplementation { val newCoefficientList = mutableListOf<Int>() for (i in 0..max(degree, toPlus.degree)) { newCoefficientList.add(0) } val sum = PolynomialImplementation(coefficientList = newCoefficientList) for (i in 0..degree) { sum.coefficientList[i] += coefficientList[i] } for (i in 0..toPlus.degree) { sum.coefficientList[i] += toPlus.coefficientList[i] } return sum } fun minus(toMinus: PolynomialImplementation): PolynomialImplementation { val newCoefficientsList = mutableListOf<Int>() for (i in 0..max(degree, toMinus.degree)) { newCoefficientsList.add(0) } val result = PolynomialImplementation(coefficientList = newCoefficientsList) for (i in 0..degree) { result.coefficientList[i] += this.coefficientList[i] } for (i in 0..toMinus.degree) { result.coefficientList[i] -= toMinus.coefficientList[i] } return result } fun times(toTimes: PolynomialImplementation): PolynomialImplementation { val newCoefficientsList = mutableListOf<Int>() for (i in 0..(degree + toTimes.degree)) { newCoefficientsList.add(0) } val result = PolynomialImplementation(newCoefficientsList) for (i in 0..degree) { for (j in 0..toTimes.degree) { result.coefficientList[i + j] += coefficientList[i] * toTimes.coefficientList[j] } } return result } override fun toString(): String { // because indexOfLast return -1 when no non-zero element in list if (degree == -1) return "0" var resultString = "" for (i in coefficientList.indices) { if (coefficientList[i] != 0) { resultString += when { i == 0 -> "${coefficientList[i]}" coefficientList[i] == 1 -> "element" + "*element".repeat(i - 1) else -> "(${coefficientList[i]}" + "*element".repeat(i) + ")" } if (i !=coefficientList.lastIndex) resultString += "+" } } return resultString } } fun newOperator(sign: String, leftExpression: Expression, rightExpression: Expression): BinaryExpression { if (leftExpression is Numeric && rightExpression is Numeric) { return when (sign) { "=" -> Equals(leftExpression, rightExpression) "+" -> Plus(leftExpression, rightExpression) "-" -> Minus(leftExpression, rightExpression) "<" -> Less(leftExpression, rightExpression) "*" -> Times(leftExpression, rightExpression) ">" -> Greater(leftExpression, rightExpression) else -> throw TypeException() } } else if (leftExpression is Bool && rightExpression is Bool) { return when (sign) { "|" -> Or(leftExpression, rightExpression) "&" -> And(leftExpression, rightExpression) else -> throw ParseException() } } else throw ParseException() } fun Expression.composition(toCompose: Expression): Expression = when (this) { is Numeric.Element -> toCompose is BinaryExpression -> { val leftPartCompos = leftPart.composition(toCompose) val rightPartCompos = rightPart.composition(toCompose) newOperator(type, leftPartCompos, rightPartCompos) } else -> this }
0
Kotlin
0
0
e622fdb1f6487d7dfb3aaa531587801308493d25
4,566
call-chain-converter
Apache License 2.0
src/main/kotlin/adventofcode2018/Day22ModeMaze.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2018 class Day22ModeMaze class MazeCalculator(val depth: Int, val targetX: Int, val targetY: Int) { val regions: List<MutableList<Int>> val errosionLevels: List<MutableList<Int>> = List(targetY + 1) { MutableList(targetX + 1) { 0 } } val riskLevel: Int get() = regions.map { line -> line.sum() }.sum() init { regions = (0..targetY).map { y -> (0..targetX).map { x -> 0 }.toMutableList() } calculateErosionLevels() } private fun calculateErosionLevels() { (0..targetY).forEach { y -> (0..targetX).forEach { x -> regions[y][x] = getRegionType(y, x) } } } private fun getRegionType(y: Int, x: Int): Int { val erosionLevel = getErosionLevel(y, x) return erosionLevel % 3 } private fun getErosionLevel(y: Int, x: Int): Int { val geologicalIndex = getGeologicalIndex(y, x) val errosionLevel = (geologicalIndex + depth) % 20183 errosionLevels[y][x] = errosionLevel return errosionLevel } private fun getGeologicalIndex(y: Int, x: Int): Int { if (y == 0 && x == 0) return 0 if (y == targetY && x == targetX) return 0 if (y == 0) { return x * 16807 } if (x == 0) { return y * 48271 } return errosionLevels[y - 1][x] * errosionLevels[y][x - 1] } fun printMaze() { regions.forEach { line -> line.forEach { region -> when (region) { 0 -> print(".") 1 -> print("=") else -> print("|") } } println() } } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
1,780
kotlin-coding-challenges
MIT License
src/main/kotlin/g0601_0700/s0698_partition_to_k_equal_sum_subsets/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0698_partition_to_k_equal_sum_subsets // #Medium #Array #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask #Memoization // #2023_02_22_Time_191_ms_(100.00%)_Space_45.5_MB_(50.00%) class Solution { fun canPartitionKSubsets(nums: IntArray, k: Int): Boolean { if (nums.isEmpty()) { return false } val n = nums.size var sum = 0 for (num in nums) { sum += num } if (sum % k != 0) { return false } // sum of each subset = sum / k sum /= k val dp = IntArray(1 shl n) dp.fill(-1) dp[0] = 0 for (i in 0 until (1 shl n)) { if (dp[i] == -1) { continue } val rem = sum - dp[i] % sum for (j in 0 until n) { // bitmask val tmp = i or (1 shl j) // skip if the bit is already taken if (tmp != i) { // num too big for current subset if (nums[j] > rem) { break } // cumulative sum dp[tmp] = dp[i] + nums[j] } } } // true if total sum of all nums is the same return dp[(1 shl n) - 1] == k * sum } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,373
LeetCode-in-Kotlin
MIT License
src/day01/Day01.kt
zypus
573,178,215
false
{"Kotlin": 33417, "Shell": 3190}
package day01 import AoCTask // https://adventofcode.com/2022/day/1 fun part1(input: List<String>): Int { val elvesRations = getTotalRationsPerElf(input) return elvesRations.max() } fun part2(input: List<String>): Int { val elvesRations = getTotalRationsPerElf(input) return elvesRations.sortedDescending().take(3).sum() } private fun getTotalRationsPerElf(input: List<String>): List<Int> { val elves = input.joinToString("\n") .split("\n\n").map { elfRations -> elfRations.split("\n").sumOf { it.toInt() } } return elves } fun main() = AoCTask("day01").run { // test if implementation meets criteria from the description, like: check(part1(testInput) == 24000) check(part2(testInput) == 45000) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f37ed8e9ff028e736e4c205aef5ddace4dc73bfc
824
aoc-2022
Apache License 2.0
Retos/Reto #1 - EL LENGUAJE HACKER [Fácil]/kotlin/icedrek.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
/* * Escribe un programa que reciba un texto y transforme lenguaje natural a * "lenguaje hacker" (conocido realmente como "leet" o "1337"). Este lenguaje * se caracteriza por sustituir caracteres alfanuméricos. * - Utiliza esta tabla (https://www.gamehouse.com/blog/leet-speak-cheat-sheet/) * con el alfabeto y los números en "leet". * (Usa la primera opción de cada transformación. Por ejemplo "4" para la "a") */ fun main() { val inputList = listOf( "<NAME>", "MoureDev", "El cielo esta enladrillado" ) inputList.forEach { input -> println("$input - ${input.toLeet()}") } } fun String.toLeet(): String { val leetMap = mapOf( 'a' to "4", 'b' to "13", 'c' to "[", 'd' to ")", 'e' to "3", 'f' to "|=", 'g' to "&", 'h' to "#", 'i' to "!", 'j' to ",_|", 'k' to ">|", 'l' to "1", 'm' to "/\\/\\", 'n' to "^/", 'o' to "0", 'p' to "|*", 'q' to "(_,)", 'r' to "I2", 's' to "5", 't' to "7", 'u' to "(_)", 'v' to "\\/", 'w' to "\\/\\/", 'x' to "><", 'y' to "j", 'z' to "2", '1' to "L", '2' to "R", '3' to "E", '4' to "A", '5' to "S", '6' to "b", '7' to "T", '8' to "B", '9' to "g", '0' to "o" ) val input = this.lowercase() var output = "" for (letter in input) { if (leetMap[letter].isNullOrEmpty()) output += letter else output += leetMap[letter] } return output }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
1,652
retos-programacion-2023
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2019/Day3.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2019 import com.s13g.aoc.Result import com.s13g.aoc.Solver import kotlin.math.abs /** https://adventofcode.com/2019/day/3 */ class Day3 : Solver { override fun solve(lines: List<String>): Result { val dirs1 = traceWire(lines[0].split(",")) val dirs2 = traceWire(lines[1].split(",")) val intersections = dirs1.intersect(dirs2) val shortest = intersections.map { i -> i.manhattan() }.min() val combinedDistance = intersections.map { i -> dirs1.indexOf(i) + dirs2.indexOf(i) }.min() return Result("$shortest", "${combinedDistance!! + 2}") } private fun traceWire(dirs: List<String>): List<XY> { val result = mutableListOf<XY>() var pos = XY(0, 0) for (dir in dirs) { val dirVec = vecForDir(dir[0]) val amount = dir.substring(1).toInt() for (i in 1..amount) { val newPos = pos.add(dirVec) result.add(newPos) pos = newPos } } return result } private fun vecForDir(d: Char) = when (d) { 'R' -> XY(1, 0) 'L' -> XY(-1, 0) 'U' -> XY(0, -1) 'D' -> XY(0, 1) else -> throw Exception("Invalid dir character") } } private data class XY(val x: Int, val y: Int) { fun add(xy: XY) = XY(x + xy.x, y + xy.y) fun manhattan() = abs(x) + abs(y) }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,292
euler
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/NAryTreePreorderTraversal.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack class NAryNode(var value: Int) { var children: List<NAryNode?> = listOf() } fun interface NAryTreePreorderTraversalStrategy { fun preorder(root: NAryNode?): List<Int> } class NAryTreePreorderTraversalIterative : NAryTreePreorderTraversalStrategy { override fun preorder(root: NAryNode?): List<Int> { var r = root val list: MutableList<Int> = ArrayList() if (r == null) return list val stack: Stack<NAryNode> = Stack() stack.add(r) while (!stack.empty()) { r = stack.pop() list.add(r.value) for (i in r.children.size - 1 downTo 0) stack.add(r.children[i]) } return list } } class NAryTreePreorderTraversalRecursive : NAryTreePreorderTraversalStrategy { var list: MutableList<Int> = ArrayList() override fun preorder(root: NAryNode?): List<Int> { if (root == null) return list list.add(root.value) for (node in root.children) preorder(node) return list } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,689
kotlab
Apache License 2.0
src/Day24.kt
LauwiMeara
572,498,129
false
{"Kotlin": 109923}
enum class Symbol { BLIZZARD_RIGHT, BLIZZARD_DOWN, BLIZZARD_LEFT, BLIZZARD_UP, ELF } fun main() { fun printGrid(grid:Map<Point, MutableList<Symbol>>) { // Make gridArray val gridArray = Array(grid.keys.maxOf{it.y} + 1) { CharArray(grid.keys.maxOf{it.x} + 2) } for (entry in grid) { if (entry.value.isEmpty()) { gridArray[entry.key.y][entry.key.x] = '.' } else if (entry.value.size > 1) { gridArray[entry.key.y][entry.key.x] = entry.value.size.digitToChar() } else when (entry.value.first()) { Symbol.BLIZZARD_RIGHT -> gridArray[entry.key.y][entry.key.x] = '>' Symbol.BLIZZARD_DOWN -> gridArray[entry.key.y][entry.key.x] = 'v' Symbol.BLIZZARD_LEFT -> gridArray[entry.key.y][entry.key.x] = '<' Symbol.BLIZZARD_UP -> gridArray[entry.key.y][entry.key.x] = '^' Symbol.ELF -> gridArray[entry.key.y][entry.key.x] = 'E' } } // Print gridArray for (y in gridArray.indices) { for (x in gridArray[y].indices) { if (gridArray[y][x] == Char.MIN_VALUE) { print('#') } else { print(gridArray[y][x]) } } println() } println() } fun getGrid(input: List<String>): Map<Point, MutableList<Symbol>> { val grid = mutableMapOf<Point, MutableList<Symbol>>() for (y in input.indices) { for (x in input[y].indices) { when (input[y][x]) { '.' -> grid[Point(x, y)] = mutableListOf() '>' -> grid[Point(x, y)] = mutableListOf (Symbol.BLIZZARD_RIGHT) 'v' -> grid[Point(x, y)] = mutableListOf(Symbol.BLIZZARD_DOWN) '<' -> grid[Point(x, y)] = mutableListOf(Symbol.BLIZZARD_LEFT) '^' -> grid[Point(x, y)] = mutableListOf(Symbol.BLIZZARD_UP) } } } val startPosition = grid.filter{it.key.y == 0 && it.value.isEmpty()}.keys.single() grid[startPosition]!!.add(Symbol.ELF) return grid } fun getNeighbours(grid: Map<Point, MutableList<Symbol>>, position: Point): List<Point> { val neighbours = mutableListOf<Point>() val (x, y) = position if (grid.keys.contains(Point(x + 1, y))) neighbours.add(Point(x + 1, y)) if (grid.keys.contains(Point(x, y + 1))) neighbours.add(Point(x, y + 1)) if (grid.keys.contains(Point(x - 1, y))) neighbours.add(Point(x - 1, y)) if (grid.keys.contains(Point(x, y - 1))) neighbours.add(Point(x, y - 1)) return neighbours } fun getGridAfterMovingSymbols(grid: Map<Point, MutableList<Symbol>>): MutableMap<Point, MutableList<Symbol>> { // Create newGrid with the same keys as grid val newGrid = mutableMapOf<Point, MutableList<Symbol>>() for (key in grid.keys) { newGrid[key] = mutableListOf() } // Fill newGrid with new values for (position in grid) { for (symbol in position.value) { when (symbol) { Symbol.BLIZZARD_RIGHT -> { val (x, y) = position.key if (grid.keys.contains(Point(x + 1, y))) { newGrid[Point(x + 1, y)]!!.add(symbol) } else { newGrid[Point(grid.keys.minOf{it.x}, y)]!!.add(symbol) } } Symbol.BLIZZARD_DOWN -> { val (x, y) = position.key if (grid.keys.contains(Point(x, y + 1))) { newGrid[Point(x, y + 1)]!!.add(symbol) } else { if (grid.keys.contains(Point(x, grid.keys.minOf{it.y}))) { newGrid[Point(x, grid.keys.minOf{it.y})]!!.add(symbol) } else { newGrid[Point(x, grid.keys.minOf{it.y} + 1)]!!.add(symbol) } } } Symbol.BLIZZARD_LEFT -> { val (x, y) = position.key if (grid.keys.contains(Point(x - 1, y))) { newGrid[Point(x - 1, y)]!!.add(symbol) } else { newGrid[Point(grid.keys.maxOf{it.x}, y)]!!.add(symbol) } } Symbol.BLIZZARD_UP -> { val (x, y) = position.key if (grid.keys.contains(Point(x, y - 1))) { newGrid[Point(x, y - 1)]!!.add(symbol) } else { if (grid.keys.contains(Point(x, grid.keys.maxOf{it.y}))) { newGrid[Point(x, grid.keys.maxOf{it.y})]!!.add(symbol) } else { newGrid[Point(x, grid.keys.maxOf{it.y} - 1)]!!.add(symbol) } } } Symbol.ELF -> { if (newGrid[position.key]!!.isEmpty()) newGrid[position.key]!!.add(symbol) val neighbours = getNeighbours(grid, position.key) for (neighbour in neighbours) { if (newGrid[neighbour]!!.isEmpty()) { newGrid[neighbour]!!.add(symbol) } } } } } } return newGrid } fun removeElvesWhereBlizzardsAre(grid: Map<Point, MutableList<Symbol>>) { for (position in grid) { if (position.value.size > 1 && position.value.contains(Symbol.ELF)) { position.value.remove(Symbol.ELF) } } } fun removeAllElves(grid: Map<Point, MutableList<Symbol>>) { for (entry in grid) { if (entry.value.contains(Symbol.ELF)) { entry.value.remove(Symbol.ELF) } } } fun getGridAndMinutesToReachEndPosition(initGrid: Map<Point, MutableList<Symbol>>, goalPosition: Point, print: Boolean): Pair<Map<Point, MutableList<Symbol>>, Int> { var grid = initGrid var minute = 0 while (true) { minute++ grid = getGridAfterMovingSymbols(grid) removeElvesWhereBlizzardsAre(grid) if (print) { println("Minute: $minute") printGrid(grid) } if (grid[goalPosition]!!.contains(Symbol.ELF)) break } removeAllElves(grid) grid[goalPosition]!!.add(Symbol.ELF) return Pair(grid, minute) } fun part1(input: List<String>, print: Boolean = false): Int { val grid = getGrid(input) val endPosition = grid.filter{it.key.y == grid.keys.maxOf{jt -> jt.y} && it.value.isEmpty()}.keys.single() val (_, minutes) = getGridAndMinutesToReachEndPosition(grid, endPosition, print) return minutes } fun part2(input: List<String>, print: Boolean = false): Int { var grid = getGrid(input) val startPosition = grid.filter{it.key.y == 0}.keys.single() val endPosition = grid.filter{it.key.y == grid.keys.maxOf{position -> position.y}}.keys.single() // To endPosition val (g1, m1) = getGridAndMinutesToReachEndPosition(grid, endPosition, print) grid = g1 // To startPosition val (g2, m2) = getGridAndMinutesToReachEndPosition(grid, startPosition, print) grid = g2 // To endPosition val (g3, m3) = getGridAndMinutesToReachEndPosition(grid, endPosition, print) grid = g3 return m1 + m2 + m3 } val input = readInputAsStrings("Day24") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
34b4d4fa7e562551cb892c272fe7ad406a28fb69
8,157
AoC2022
Apache License 2.0
src/main/kotlin/com/booleworks/packagesolver/data/Package.kt
booleworks
497,876,711
false
{"Kotlin": 30454}
package com.booleworks.packagesolver.data import org.logicng.formulas.Formula import org.logicng.formulas.FormulaFactory import org.logicng.formulas.Variable import java.util.* const val PREFIX_INSTALLED = "i" const val PREFIX_INSTALLED_GREATER = "ig" const val PREFIX_INSTALLED_LESS = "il" const val PREFIX_UNINSTALLED_GREATER = "ug" const val PREFIX_UNINSTALLED_LESS = "ul" fun vin(f: FormulaFactory, p: String, v: Int): Variable = f.variable("${PREFIX_INSTALLED}_${p}_${v}") fun vig(f: FormulaFactory, p: String, v: Int): Variable = f.variable("${PREFIX_INSTALLED_GREATER}_${p}_$v") fun vil(f: FormulaFactory, p: String, v: Int): Variable = f.variable("${PREFIX_INSTALLED_LESS}_${p}_$v") fun vug(f: FormulaFactory, p: String, v: Int): Variable = f.variable("${PREFIX_UNINSTALLED_GREATER}_${p}_$v") fun vul(f: FormulaFactory, p: String, v: Int): Variable = f.variable("${PREFIX_UNINSTALLED_LESS}_${p}_$v") /** * An enum for relational operators =, !=, >=, >, <=, < between versions */ enum class RelOp { EQ, NE, GE, GT, LE, LT } /** * Main data structure for a package upgrade problem description. Consists of a list of all packages * and a request which packages should be installed and/or removed. */ data class ProblemDescription(val packageMap: Map<Pair<String, Int>, Package>, val request: Request) { constructor(packages: List<Package>, request: Request) : this(packages.associateBy { Pair(it.name, it.version) }, request) fun allPackages(): List<Package> = packageMap.values.toList() fun allPackageNames(): Set<String> = packageMap.values.map { it.name }.toSet() fun currentInstallation(): Map<String, VersionedPackage> = packageMap.values.filter { it.installed }.associate { Pair(it.name, it.toVersionedPackage()) } fun getAllVersions(packageName: String): SortedSet<Int> = packageMap.filter { it.key.first == packageName }.map { it.key.second }.toSortedSet() } /** * A single package has a name and a version. It can depend on or conflict with other packages and can be * currently installed or not. */ data class Package( val name: String, val version: Int, val depends: PackageFormula = Constant(true), val conflicts: List<VersionedPackage> = listOf(), val installed: Boolean = false, ) { fun installed(f: FormulaFactory) = vin(f, name, version) fun installedGreater(f: FormulaFactory) = vig(f, name, version) fun installedGreaterPlusOne(f: FormulaFactory) = vig(f, name, version + 1) fun installedLess(f: FormulaFactory) = vil(f, name, version) fun installedLessMinusOne(f: FormulaFactory) = vil(f, name, version - 1) fun uninstalledGreater(f: FormulaFactory) = vug(f, name, version) fun uninstalledGreaterPlusOne(f: FormulaFactory) = vug(f, name, version + 1) fun uninstalledLess(f: FormulaFactory) = vul(f, name, version) fun uninstalledLessMinusOne(f: FormulaFactory) = vul(f, name, version - 1) fun toVersionedPackage() = VersionedPackage(name, RelOp.EQ, version) } /** * A request has a list of packages which should be installed and a list which packages should be removed. */ data class Request( val install: List<VersionedPackage> = listOf(), val remove: List<VersionedPackage> = listOf() ) /** * A package formula consists of constants true/false, predicates between package versions, and * Boolean operators OR and AND. */ sealed interface PackageFormula { fun translateForDependency(f: FormulaFactory, p: Package, vs: Set<Int>): Formula } data class Constant(val value: Boolean) : PackageFormula { override fun translateForDependency(f: FormulaFactory, p: Package, vs: Set<Int>): Formula = if (value) f.verum() else vin(f, p.name, p.version).negate() } data class VersionedPackage(val name: String, val relOp: RelOp = RelOp.GE, val version: Int = 1) : PackageFormula { fun translateForConflict(f: FormulaFactory, p: Package): Formula = when (relOp) { RelOp.EQ -> f.or(vin(f, p.name, p.version).negate(), vin(f, name, version).negate()) RelOp.NE -> f.and( f.or(vin(f, p.name, p.version).negate(), vul(f, name, version - 1)), f.or(vin(f, p.name, p.version).negate(), vug(f, name, version + 1)) ) RelOp.GE -> f.or(vin(f, p.name, p.version).negate(), vug(f, name, version)) RelOp.GT -> f.or(vin(f, p.name, p.version).negate(), vug(f, name, version + 1)) RelOp.LE -> f.or(vin(f, p.name, p.version).negate(), vul(f, name, version)) RelOp.LT -> f.or(vin(f, p.name, p.version).negate(), vul(f, name, version - 1)) } override fun translateForDependency(f: FormulaFactory, p: Package, vs: Set<Int>): Formula = when (relOp) { RelOp.EQ -> f.or(vin(f, p.name, p.version).negate(), vin(f, name, version)) RelOp.NE -> { val vil = if (vs.contains(version - 1)) vil(f, name, version - 1) else f.falsum() val vig = if (vs.contains(version + 1)) vig(f, name, version + 1) else f.falsum() f.or(vin(f, p.name, p.version).negate(), vil, vig) } RelOp.GE -> f.or(vin(f, p.name, p.version).negate(), vig(f, name, version)) RelOp.GT -> f.or(vin(f, p.name, p.version).negate(), if (vs.contains(version + 1)) vig(f, name, version + 1) else f.falsum()) RelOp.LE -> f.or(vin(f, p.name, p.version).negate(), vil(f, name, version)) RelOp.LT -> f.or(vin(f, p.name, p.version).negate(), if (vs.contains(version - 1)) vil(f, name, version - 1) else f.falsum()) } override fun toString(): String { return "$name $relOp $version" } } data class Or(val operands: List<PackageFormula>) : PackageFormula { constructor(vararg ops: PackageFormula) : this(ops.toList()) override fun translateForDependency(f: FormulaFactory, p: Package, vs: Set<Int>): Formula = f.or(operands.map { it.translateForDependency(f, p, vs) }) } data class And(val operands: List<PackageFormula>) : PackageFormula { constructor(vararg ops: PackageFormula) : this(ops.toList()) override fun translateForDependency(f: FormulaFactory, p: Package, vs: Set<Int>): Formula = f.and(operands.map { it.translateForDependency(f, p, vs) }) }
0
Kotlin
0
0
e99b2e19599720866a0172b5c30047d37862343c
6,147
package-solving-poc
MIT License
src/main/kotlin/adventofcode/year2021/Day06Lanternfish.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2021 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day06Lanternfish(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val fish by lazy { input.split(",").map(String::toInt) } private val fishByAge by lazy { fish.groupingBy { it }.eachCount().map { (age, count) -> age to count.toLong() }.toMap() } override fun partOne() = generateSequence(fish) { previous -> previous.flatMap { if (it == 0) listOf(6, 8) else listOf(it - 1) } } .take(80 + 1) .last() .size override fun partTwo() = generateSequence(fishByAge) { previous -> previous .flatMap { (age, count) -> if (age == 0) listOf(6 to count, 8 to count) else listOf(age - 1 to count) } .groupBy { (age, _) -> age } .map { (age, count) -> age to count.sumOf { it.second } } .toMap() } .take(256 + 1) .last() .values .sum() }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
984
AdventOfCode
MIT License
src/commonMain/kotlin/redblack/RedBlackUtils.kt
EdwarDDay
174,175,328
false
null
/* * Copyright 2019 <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 de.edwardday.sortedlist.redblack import de.edwardday.sortedlist.Tree import de.edwardday.sortedlist.comparePartitioned import de.edwardday.sortedlist.compareTo import de.edwardday.sortedlist.size import kotlin.contracts.contract internal fun Tree<*, Boolean>?.isRed(): Boolean { contract { returns(true) implies (this@isRed != null) } return this?.data == true } internal fun Tree<*, Boolean>?.isBlack(): Boolean { contract { returns(false) implies (this@isBlack != null) } return this?.data != true } internal fun <T> Tree<T, Boolean>.blacken(): Tree<T, Boolean> = if (this.isRed()) copy(data = false) else this internal fun <T> Tree<T, Boolean>.redden(): Tree<T, Boolean> = if (this.isRed()) this else copy(data = true) internal fun <T> Tree<T, Boolean>?.plus(element: T, comparator: Comparator<T>): Tree<T, Boolean> { return when { this == null -> Tree(element, null, null, true) element.compareTo(this, comparator) < 0 -> copy(left = left.plus(element, comparator)).colorBalanceLeft() else -> copy(right = right.plus(element, comparator)).colorBalanceRight() } } internal fun <T> Tree<T, Boolean>?.plus(elements: Collection<T>, comparator: Comparator<T>): Tree<T, Boolean>? = plusInternal(elements, comparator).tree private fun <T> Tree<T, Boolean>?.plusInternal(elements: Collection<T>, comparator: Comparator<T>): JoinResult<T> { return when { elements.isEmpty() -> JoinResult(this, 0) this == null -> elements.first().let { value -> Tree(value, null, null, true).plusInternal(elements.drop(1), comparator) } else -> { val (lefts, rights) = elements.partition { it.compareTo(this, comparator) < 0 } val newLeft = left.plusInternal(lefts, comparator) val newRight = right.plusInternal(rights, comparator) return join(newLeft, value, newRight) } } } internal fun <T> Tree<T, Boolean>.minus(element: T, comparator: Comparator<T>): Tree<T, Boolean>? { val removeResult = minusInternal(element, comparator) return if (removeResult == null) this else removeResult.newChild } private fun <T> Tree<T, Boolean>.minusInternal(element: T, comparator: Comparator<T>): RemoveResult<T, Boolean>? { if (value == element) { return when { left == null -> RemoveResult(right, isBlack()) right == null -> RemoveResult(left, isBlack()) left.size >= right.size -> left.pollMax().let { copy(value = it.polled).heightBalanceLeft(it.removeResult) } else -> right.pollMin().let { copy(value = it.polled).heightBalanceRight(it.removeResult) } } } val compared = element.compareTo(this, comparator) val leftRemoveResult = left?.takeIf { compared <= 0 }?.minusInternal(element, comparator) return when (leftRemoveResult) { null -> right?.takeIf { compared >= 0 }?.minusInternal(element, comparator)?.let { heightBalanceRight(it) } else -> heightBalanceLeft(leftRemoveResult) } } internal fun <T> Tree<T, Boolean>?.minus(elements: Collection<T>, comparator: Comparator<T>): Tree<T, Boolean>? { return minusInternal(elements, comparator).joinResult.tree } private fun <T> Tree<T, Boolean>?.minusInternal( elements: Collection<T>, comparator: Comparator<T> ): RemoveManyResult<T> { return when { this == null || elements.isEmpty() -> RemoveManyResult(JoinResult(this, 0), elements) else -> { val elementsWithoutThis = elements.minus(value) val removeThis = elementsWithoutThis.size != elements.size val (smaller, equal, greater) = elementsWithoutThis.comparePartitioned(value, comparator) val (newLeft, leftToRemove) = left.minusInternal(smaller + equal, comparator) val (newRight, rightToRemove) = right.minusInternal(leftToRemove - smaller + greater, comparator) val toRemove = leftToRemove - equal + rightToRemove if (removeThis) { when { newLeft.tree == null -> RemoveManyResult(newRight, toRemove) newRight.tree == null -> RemoveManyResult(newLeft, toRemove) newLeft.blackHeightLoss < newRight.blackHeightLoss -> newLeft.tree.pollMax().let { (leftPolled, newValue) -> val leftAdditionalHeightLoss = if (leftPolled.tooSmall) 1 else 0 val leftToJoin = JoinResult(leftPolled.newChild, newLeft.blackHeightLoss + leftAdditionalHeightLoss) RemoveManyResult(join(leftToJoin, newValue, newRight), toRemove) } else -> newRight.tree.pollMin().let { (rightPolled, newValue) -> val rightAdditionalHeightLoss = if (rightPolled.tooSmall) 1 else 0 val rightToJoin = JoinResult(rightPolled.newChild, newRight.blackHeightLoss + rightAdditionalHeightLoss) RemoveManyResult(join(newLeft, newValue, rightToJoin), toRemove) } } } else { RemoveManyResult(join(newLeft, value, newRight), toRemove) }.let { it.copy(joinResult = it.joinResult.fixFromTree(this)) } } } } private data class RemoveManyResult<T>(val joinResult: JoinResult<T>, val toRemove: Collection<T>) private data class RemoveResult<T, D>(val newChild: Tree<T, D>?, val tooSmall: Boolean) private data class PollResult<T, D>(val removeResult: RemoveResult<T, D>, val polled: T) private fun <T> Tree<T, Boolean>.pollMax(): PollResult<T, Boolean> { return when (right) { null -> PollResult(RemoveResult(left?.blacken(), isBlack() && left == null), value) else -> right.pollMax().run { copy(removeResult = heightBalanceRight(removeResult)) } } } private fun <T> Tree<T, Boolean>.pollMin(): PollResult<T, Boolean> { return when (left) { null -> PollResult(RemoveResult(right?.blacken(), isBlack() && right == null), value) else -> left.pollMin().run { copy(removeResult = heightBalanceLeft(removeResult)) } } } private fun <T> Tree<T, Boolean>.colorBalance(): Tree<T, Boolean> { return when { left.isBlack() -> colorBalanceRight() right.isBlack() -> colorBalanceLeft() else -> { val leftBalanced = colorBalanceLeft() if (leftBalanced.isBlack()) colorBalanceRight() else leftBalanced.copy(right = leftBalanced.right.colorBalance()) } } } private fun <T> Tree<T, Boolean>.colorBalanceLeft(): Tree<T, Boolean> { val x: Tree<T, Boolean> val y: Tree<T, Boolean> val z: Tree<T, Boolean> = this val b: Tree<T, Boolean>? when { left.isBlack() -> return this left.left.isRed() -> { y = left x = left.left b = x.right } left.right.isRed() -> { x = left y = left.right b = y.left } else -> return this } return y.copy(data = true, left = x.copy(data = false, right = b), right = z.copy(data = false, left = y.right)) } private fun <T> Tree<T, Boolean>.colorBalanceRight(): Tree<T, Boolean> { val x: Tree<T, Boolean> = this val y: Tree<T, Boolean> val z: Tree<T, Boolean> val c: Tree<T, Boolean>? when { right.isBlack() -> return this right.isRed() && right.left.isRed() -> { z = right y = right.left c = y.right } right.isRed() && right.right.isRed() -> { y = right z = right.right c = z.left } else -> return this } return y.copy(data = true, left = x.copy(data = false, right = y.left), right = z.copy(data = false, left = c)) } private fun <T> Tree<T, Boolean>.heightBalanceLeft(removeResult: RemoveResult<T, Boolean>): RemoveResult<T, Boolean> { return if (removeResult.tooSmall) { if (right.isBlack()) { val newChild = copy(data = false, left = removeResult.newChild, right = right?.redden()) .colorBalanceRight() if (newChild.isRed() && isBlack()) RemoveResult(newChild = newChild.blacken(), tooSmall = false) else RemoveResult(newChild = newChild, tooSmall = isBlack()) } else { val newChild = right.left?.copy( left = this.copy(left = removeResult.newChild, right = right.left.left), right = right.copy( data = false, left = right.left.right, right = right.right?.redden() ).colorBalanceRight() ) RemoveResult(newChild = newChild, tooSmall = false) } } else { removeResult.copy(copy(left = removeResult.newChild)) } } private fun <T> Tree<T, Boolean>.heightBalanceRight(removeResult: RemoveResult<T, Boolean>): RemoveResult<T, Boolean> { return if (removeResult.tooSmall) { if (left.isBlack()) { val newChild = copy(data = false, left = left?.redden(), right = removeResult.newChild) .colorBalanceLeft() if (newChild.isRed() && isBlack()) RemoveResult(newChild = newChild.blacken(), tooSmall = false) else RemoveResult(newChild = newChild, tooSmall = isBlack()) } else { val newChild = left.right?.copy( left = left.copy( data = false, left = left.left?.redden(), right = left.right.left ).colorBalanceLeft(), right = this.copy(left = left.right.right, right = removeResult.newChild) ) RemoveResult(newChild = newChild, tooSmall = false) } } else { removeResult.copy(copy(right = removeResult.newChild)) } } internal fun <T> Tree<T, Boolean>.subTree(fromIndex: Int, toIndex: Int): Tree<T, Boolean>? { val leftSize = left.size return when { fromIndex >= toIndex -> null toIndex <= leftSize -> left?.subTree(fromIndex, toIndex) fromIndex > leftSize -> right?.subTree(fromIndex - leftSize - 1, toIndex - leftSize - 1) else -> { val leftSubtreeResult = left.subTreeFromInternal(fromIndex) val rightSubtreeResult = right.subTreeToInternal(toIndex - leftSize - 1) join(leftSubtreeResult, value, rightSubtreeResult).tree } } } internal fun <T> Tree<T, Boolean>.subTree(from: T, to: T, comparator: Comparator<T>): Tree<T, Boolean>? { return when { comparator.compare(from, to) >= 0 -> null to.compareTo(this, comparator) <= 0 -> left?.subTree(from, to, comparator) from.compareTo(this, comparator) > 0 -> right?.subTree(from, to, comparator) else -> { val leftSubtreeResult = left.subTreeFromInternal(from, comparator) val rightSubtreeResult = right.subTreeToInternal(to, comparator) join(leftSubtreeResult, value, rightSubtreeResult).tree } } } internal fun <T> Tree<T, Boolean>.subTreeFrom(from: T, comparator: Comparator<T>): Tree<T, Boolean>? = subTreeFromInternal(from, comparator).tree private fun <T> Tree<T, Boolean>?.subTreeFromInternal(fromIndex: Int): JoinResult<T> { return when { this == null -> JoinResult(null, 0) fromIndex > left.size -> right.subTreeFromInternal(fromIndex - left.size - 1).fixFromTree(this) else -> left.subTreeFromInternal(fromIndex).let { join(it.tree, it.blackHeightLoss, value, right, 0).fixFromTree(this) } } } private fun <T> Tree<T, Boolean>?.subTreeFromInternal(from: T, comparator: Comparator<T>): JoinResult<T> { sequenceOf(1,2).take(2) return when { this == null -> JoinResult(null, 0) from.compareTo(this, comparator) > 0 -> right.subTreeFromInternal(from, comparator).fixFromTree(this) else -> left.subTreeFromInternal(from, comparator).let { join(it.tree, it.blackHeightLoss, value, right, 0).fixFromTree(this) } } } internal fun <T> Tree<T, Boolean>.subTreeTo(to: T, comparator: Comparator<T>): Tree<T, Boolean>? = subTreeToInternal(to, comparator).tree private fun <T> Tree<T, Boolean>?.subTreeToInternal(toIndex: Int): JoinResult<T> { return when { this == null -> JoinResult(null, 0) toIndex <= left.size -> left.subTreeToInternal(toIndex).fixFromTree(this) else -> right.subTreeToInternal(toIndex - left.size - 1).let { join(left, 0, value, it.tree, it.blackHeightLoss).fixFromTree(this) } } } private fun <T> Tree<T, Boolean>?.subTreeToInternal(to: T, comparator: Comparator<T>): JoinResult<T> { return when { this == null -> JoinResult(null, 0) to.compareTo(this, comparator) <= 0 -> left.subTreeToInternal(to, comparator).fixFromTree(this) else -> right.subTreeToInternal(to, comparator).let { join(left, 0, value, it.tree, it.blackHeightLoss).fixFromTree(this) } } } private fun <T> JoinResult<T>.fixFromTree(oldTree: Tree<T, Boolean>): JoinResult<T> { return when { oldTree.isBlack() -> when { tree.isRed() -> copy(tree = tree.blacken()) else -> copy(blackHeightLoss = blackHeightLoss + 1) } else -> this } } private fun <T> JoinResult<T>.fixFromTreeAdjusted(oldTree: Tree<T, Boolean>): JoinResult<T> { return when { oldTree.isBlack() && tree.isRed() -> copy(tree = tree.blacken(), blackHeightLoss = blackHeightLoss - 1) else -> this } } internal data class JoinResult<T>(val tree: Tree<T, Boolean>?, val blackHeightLoss: Int) private fun <T> join(left: JoinResult<T>, value: T, right: JoinResult<T>): JoinResult<T> = join(left.tree, left.blackHeightLoss, value, right.tree, right.blackHeightLoss) private fun <T> join( left: Tree<T, Boolean>?, leftHeightLoss: Int, value: T, right: Tree<T, Boolean>?, rightHeightLoss: Int ): JoinResult<T> { return when { leftHeightLoss == rightHeightLoss -> { val tree: Tree<T, Boolean> val heightIncreased: Boolean when { left.isRed() || right.isRed() -> { tree = Tree(value, left, right, false).colorBalance() heightIncreased = true } else -> { tree = Tree(value, left, right, true) heightIncreased = false } } if (heightIncreased) { if (tree.isBlack()) JoinResult(tree.redden(), leftHeightLoss) else JoinResult(tree, leftHeightLoss - 1) } else { JoinResult(tree, leftHeightLoss) } } left == null -> { val newHeightLoss = if (right.isRed()) rightHeightLoss - 1 else rightHeightLoss JoinResult(right?.blacken().insertMin(value), newHeightLoss) } right == null -> { val newHeightLoss = if (left.isRed()) leftHeightLoss - 1 else leftHeightLoss JoinResult(left.blacken().insertMax(value), newHeightLoss) } leftHeightLoss < rightHeightLoss -> { val leftChildHeightLoss = leftHeightLoss + if (left.isBlack()) 1 else 0 val joinResult = join(left.right, leftChildHeightLoss, value, right, rightHeightLoss) join(left.left, leftChildHeightLoss, left.value, joinResult.tree, joinResult.blackHeightLoss) .fixFromTreeAdjusted(left) } else -> { val rightChildHeightLoss = rightHeightLoss + if (right.isBlack()) 1 else 0 val joinResult = join(left, leftHeightLoss, value, right.left, rightChildHeightLoss) join(joinResult.tree, joinResult.blackHeightLoss, right.value, right.right, rightChildHeightLoss) .fixFromTreeAdjusted(right) } } } private fun <T> Tree<T, Boolean>?.insertMin(value: T): Tree<T, Boolean> { return when { this == null -> Tree(value, null, null, true) else -> copy(left = left.insertMin(value)).colorBalanceLeft() } } private fun <T> Tree<T, Boolean>?.insertMax(value: T): Tree<T, Boolean> { return when { this == null -> Tree(value, null, null, true) else -> copy(right = right.insertMax(value)).colorBalanceRight() } }
0
Kotlin
0
0
219a58640619c74f60c02742baaeb9346524215b
17,161
SortedList
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1269/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1269 /** * LeetCode page: [1269. Number of Ways to Stay in the Same Place After Some Steps](https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/); */ class Solution2 { /* Complexity: * Time O(step * N) and Space O(N) where N represents the minimum * between steps and arrLen; */ fun numWays(steps: Int, arrLen: Int): Int { val modulo = 1_000_000_007 /* dp[i]@step_j::= * number of ways back to index 0 from index_i using j steps */ val dp = IntArray(minOf(arrLen, steps + 1)) dp[0] = 1 // base case dp[0]@step_0 for (numSteps in 1..steps) { var waysFromLeft = 0 for (i in 0..minOf(numSteps, dp.lastIndex)) { var ways = waysFromLeft ways = (ways + dp[i]) % modulo ways = (ways + dp.getOrElse(i + 1) { 0 }) % modulo waysFromLeft = dp[i] dp[i] = ways } } return dp[0] } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,063
hj-leetcode-kotlin
Apache License 2.0
src/com/aaron/helloalgorithm/algorithm/链表/_141_环形链表.kt
aaronzzx
431,740,908
false
null
package com.aaron.helloalgorithm.algorithm.链表 import com.aaron.helloalgorithm.algorithm.LeetCode import com.aaron.helloalgorithm.algorithm.ListNode /** * # 141. 环形链表 * * 给你一个链表的头节点 head ,判断链表中是否有环。 * * 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。 * * 如果链表中存在环,则返回 true 。 否则,返回 false 。 * * 来源:力扣(LeetCode) * * 链接:[https://leetcode-cn.com/problems/linked-list-cycle] * * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author <EMAIL> * @since 2021/11/26 */ class _141_环形链表 fun LeetCode.链表._141_环形链表(head: ListNode?): Boolean { head ?: return false var slow = head var fast = head.next while (slow?.next != null) { if (slow == fast) { return true } slow = slow.next fast = fast?.next?.next } return false }
0
Kotlin
0
0
2d3d823b794fd0712990cbfef804ac2e138a9db3
1,342
HelloAlgorithm
Apache License 2.0
src/Day01/Day01.kt
JamesKing95
574,470,043
false
{"Kotlin": 7225}
package Day01 import readInput fun main() { fun getElfBagTotals(input: List<String>): MutableList<Int> { val bagTotals = mutableListOf<Int>() var currentTotal = 0 input.forEach { line -> if (line == "") { bagTotals.add(currentTotal) currentTotal = 0 } else { currentTotal += line.toInt() } } return bagTotals } fun part1(input: List<String>): Int { val bagTotals = getElfBagTotals(input) return bagTotals.max() } fun part2(input: List<String>): Int { val bagTotals = getElfBagTotals(input) bagTotals.sortDescending() return bagTotals.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01/Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01/Day01") println("Part 1: ".plus(part1(input))) println("Part 2: ".plus(part2(input))) }
0
Kotlin
0
0
cf7b6bd5ae6e13b83d871dfd6f0a75b6ae8f04cf
1,033
aoc-2022-in-kotlin
Apache License 2.0
src/Day06.kt
RickShaa
572,623,247
false
{"Kotlin": 34294}
import java.util.* import kotlin.collections.ArrayDeque import kotlin.math.sign fun main() { val fileName = "day06.txt" val testFileName = "day06_test.txt" val input = FileUtil.getTrimmedText(testFileName); /** * Initial solution */ fun isStarterPacket(packet:List<Char>):Boolean{ //transform to set, because set does not allow duplicates return packet.toSet().size == packet.size } fun List<Char>.findDistinctSequence(size:Byte): Int? { var bufferEnd:Int? = null for (i in this.indices){ bufferEnd = i + size if(isStarterPacket(this.subList(i, bufferEnd ))){ break } } return bufferEnd } /** * Optimized Solution 1 */ val dataStream = input.toCharArray().toList(); /*fun distinctSequence(seqLen:Int): Int? { val windowedData = dataStream.windowed(seqLen) var idx:Int? = null for ((offset,data) in windowedData.withIndex()) { if (data.toHashSet().size == data.size) { idx = offset + seqLen break; } } return idx; }*/ /* Optimized Solution 2 */ /*fun distinctSequence(seqLen:Int): Any { val windowedData = dataStream.windowed(seqLen) val index = windowedData.indexOfFirst{window -> window.toHashSet().size == window.size} return index + seqLen }*/ /** * Optimized Solution 3 BITWISE * Source: https://www.youtube.com/watch?v=U16RnpV48KQ&t=132s * * binary literal in kotlin 0b0101 "0b" meaning binary representation, 0101 = 5 (dez) * * Explanation: * 'a' = 97 * 'b' = 98 .... * * * 'a' % 32 will result in a number between 0 - 31. * This is equal to the amount of bits in an UInt * after using the remainder operator the shl(shift left) operator * shifts a single BIT(1 = 2^0) in to the u32 store, basically setting a switch to ON * (we have the char 'a' stored as one bit within u32 int at index 'a' % 32) * * Now whenever we encounter two numbers as 32bits, * Where one equals our char store with all previous chars stored as an ON switch at a specific index 'a' % 32 * and we bitwise OR those numbers, two scenarios can occur * BITWISE OR: * 1 | 0 = 1 * 1 | 1 = 1 * 0 | 1 = 1 * 0 | 0 = 0 * 1. Our newly calculated index represented as a single 1 (or ON switch) within an u32 int * is bitwise OR with our state, we will receive the exact same state, * because all ON state in our store and the OFF states of our bitwise shifted char will revert to ON (1) * and our match, ON (1) in the store and ON (1) for bitwise shifter char will return 1 * * 2. if the char is not set in our store as on, the resulting "new state" will have one more bit set to ON * and therefore will not be equal. * * Example with Input 'a','a','a','b','c' * char.code.toByte() transforms input to -> [97, 97 ,97, 98, 99] * * First window is [97, 97, 97] * state = 0 * * 1. Iterate over bytes * -> 97 in binary = 1100001 * prev = state = 0 = 00000000 * * 1.1 Modulo * 97 % 32 = 1 = m * 1.2 shl (why start with 1, because 1 in binary is 00000001) * 1 shl m = 00000010 * 1.3 bitwise OR and reassign state * 00000001 * 00000010 * -------- * 00000011 = reassign state * 1.4 compare prev and state * prev = 00000001 != 00000011 * continue loop * * 2. iteration * * prev = state = 00000011 (base2) = 3(base10) * 1.1 Modulo * 97 % 32 = 1 = m * 1.2 shl * 1 shl m = 00000010 * 1.3 bitwise or with state and reassign * 00000011 * 00000010 * -------- * 00000011 state reassigned * 1.4 compare state with prev state * 00000011 = 00000011 * */ fun List<Byte>.bitwise():Boolean{ /** * UInt = 32 bit unsigned (0 up to 2^32 -1) Integers *source: https://kotlinlang.org/docs/unsigned-integer-types.html#unsigned-arrays-and-ranges */ var state:UInt = 0u for(byte in this){ val prev = state state = state.or((1 shl (byte % 32)).toUInt()) if(prev == state){ return false } } return true } fun distinctSequence(seqLen:Int): Any { val windowedData = dataStream.map { it.code.toByte() }.also { println(it) }.windowed(seqLen) return windowedData.indexOfFirst { it.bitwise() } + seqLen } println(distinctSequence(4)) }
0
Kotlin
0
1
76257b971649e656c1be6436f8cb70b80d5c992b
4,934
aoc
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/RemoveZeroSumSublists.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 /** * 1171. Remove Zero Sum Consecutive Nodes from Linked List * @see <a href="https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/">Source</a> */ fun interface RemoveZeroSumSublists { operator fun invoke(head: ListNode?): ListNode? } class RemoveZeroSumSublistsMap : RemoveZeroSumSublists { override operator fun invoke(head: ListNode?): ListNode? { val dummy = ListNode(0) var cur: ListNode? = dummy dummy.next = head var prefix = 0 val m: MutableMap<Int, ListNode> = HashMap() while (cur != null) { prefix += cur.value if (m.containsKey(prefix)) { cur = m[prefix]?.next var p: Int = prefix + (cur?.value ?: 0) while (p != prefix) { m.remove(p) cur = cur?.next p += cur?.value ?: 0 } m[prefix]?.next = cur!!.next } else { m[prefix] = cur } cur = cur?.next } return dummy.next } } class RemoveZeroSumSublistsTwoPasses : RemoveZeroSumSublists { override operator fun invoke(head: ListNode?): ListNode? { var prefix = 0 val dummy = ListNode(0) dummy.next = head val seen: MutableMap<Int, ListNode> = HashMap() seen[0] = dummy var i: ListNode? = dummy while (i != null) { prefix += i.value seen[prefix] = i i = i.next } prefix = 0 i = dummy while (i != null) { prefix += i.value i.next = seen[prefix]!!.next i = i.next } return dummy.next } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,393
kotlab
Apache License 2.0
src/main/java/quam/ComplexMatrix.kt
johnhearn
149,781,062
false
null
package quam class ComplexMatrix(val width : Int, internal val components: List<ComplexNumber>) { constructor(width : Int, vararg components: ComplexNumber) : this(width, listOf(*components)) constructor(width : Int, vararg components: Double) : this(width, components.map { it + 0.0 * i }) constructor(width: Int, vararg components: Int) : this(width, components.map { it.toDouble() + 0.0 * i }) constructor(width: Int, f: (Int, Int) -> ComplexNumber) : this(width, (0 until width).map { x -> (0 until width).map{ y -> f(x,y) } }.flatten().toList()) fun transpose() = ComplexMatrix(width, columns().flatten()) operator fun minus(other: ComplexMatrix): ComplexMatrix { require(this.width == other.width) return ComplexMatrix(width, components.zip(other.components).map { ComplexNumber(it.first.a - it.second.a, it.first.b - it.second.b) }) } operator fun times(d: Double) = ComplexMatrix(width, components.map { d * it }) operator fun times(other: ComplexVector): ComplexVector { require(this.width == other.components.size) { "Matrix($width) not compatible with Vector(${other.components.size})" } return ComplexVector( this.rows().map { it.zip(other.components) .map { it.first * it.second } .fold(ZERO) { a, b -> a + b } }) } operator fun times(other: ComplexMatrix): ComplexMatrix { require(this.rows().size == other.columns().size) { "Matrix(${rows().size}) not compatible with Matrix(${other.columns().size})" } return ComplexMatrix(components.size/width, this.rows().map { lhs -> other.columns() .map { rhs -> lhs.zip(rhs) } .map { it.map { it.first * it.second } } .map { it.fold(ZERO) { a, b -> a + b } } } .flatten()) } infix fun directSum(rhs: ComplexMatrix): ComplexMatrix { return ComplexMatrix(this.width + rhs.width, listOf( rows().map { concat(it, listOfZeros(rhs.width)) }, rhs.rows().map { concat(listOfZeros(width), it) } ).flatten().flatten()) } private fun concat(it: List<ComplexNumber>, elements: List<ComplexNumber>) = listOf(it, elements).flatten() private fun listOfZeros(length: Int) = (1..length).map { ZERO } infix fun tensor(other: ComplexMatrix): ComplexMatrix { val top = rows().flatMap { dup(other.width, it) }.flatten().flatMap { dup(other.width, it) } val bottom = dup(width, other.rows().flatMap { dup(width, it) }.flatten()).flatten() val result = top.zip(bottom).map { it.first * it.second } return ComplexMatrix(width * other.width, result) } private fun columns() = (0 until width).map { this.components.slice(it until this.components.size step this.width) } private fun rows() = components.chunked(width) private fun <T> dup(times: Int, element: T) = MutableList(times) { element } override fun toString(): String { return rows().joinToString("\n") { it.joinToString(" | ") { it.toString() } } } override fun hashCode() = width.hashCode() + 31 * components.hashCode() override fun equals(other: Any?) = when (other) { is ComplexMatrix -> width == other.width && components == other.components else -> false } } operator fun Double.times(rhs: ComplexMatrix) = rhs.times(this) fun permutationMatrix(width: Int, mapping: (Int) -> Int) = ComplexMatrix(width, (0 until width).map { oneHot(width, mapping(it)) }.flatten()) fun permutationMatrix(width: Int, vararg pairs : Pair<Int, Int>) = permutationMatrix(width, mapping(*pairs)) fun mapping(vararg pairs : Pair<Int, Int>) = { x:Int -> mapOf(*pairs)[x] ?: x } private fun oneHot(length: Int, index: Int) = (0 until length).map { if (it == index) ONE else ZERO }
1
Kotlin
0
1
4215d86e7afad97b803ce850745920b63f75a0f9
4,140
quko
MIT License
src/main/kotlin/day19/Grammar.kt
lukasz-marek
317,632,409
false
{"Kotlin": 172913}
package day19 import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking data class RuleMatch(val matched: List<Char>) interface ProductionRule { suspend fun match(input: List<Char>): Flow<RuleMatch> } data class RuleReference(val id: Int, val mapping: Map<Int, ProductionRule>) : ProductionRule { override suspend fun match(input: List<Char>): Flow<RuleMatch> = mapping[id]!!.match(input) } data class TerminalRule(val symbol: Char) : ProductionRule { override suspend fun match(input: List<Char>): Flow<RuleMatch> = flow { if (input.isNotEmpty() && input.first() == symbol) emit(RuleMatch(listOf(input.first()))) } } data class SequenceRule(val symbolSequence: List<ProductionRule>) : ProductionRule { override suspend fun match(input: List<Char>): Flow<RuleMatch> = match(input, symbolSequence) private suspend fun match(input: List<Char>, rules: List<ProductionRule>): Flow<RuleMatch> { val currentRule = rules.first() val remainingRules = rules.drop(1) return flow { currentRule.match(input).collect { possibleMatch -> if (remainingRules.isEmpty()) { emit(possibleMatch) } else { val remainingInput = input.drop(possibleMatch.matched.size) val subMatches = match(remainingInput, remainingRules) emitAll(subMatches.map { RuleMatch(possibleMatch.matched + it.matched) }) } } } } } @FlowPreview data class AlternativeRule(val alternatives: List<ProductionRule>) : ProductionRule { override suspend fun match(input: List<Char>): Flow<RuleMatch> { return alternatives.asFlow().map { it.match(input) }.flattenConcat() } } @FlowPreview fun parseRules(rules: List<String>): Map<Int, ProductionRule> { val registry = mutableMapOf<Int, ProductionRule>() for (line in rules) { val rule = parseRule(line.trim(), registry) registry[rule.first] = rule.second } return registry } private val terminalRulePattern = Regex("^(\\d+): \"(\\w)\"$") private val nonTerminalRulePattern = Regex("^(\\d+): ((\\d+)( (\\d+))*( \\| (\\d+)( (\\d+))*)*)$") @FlowPreview fun parseRule(rule: String, mapping: Map<Int, ProductionRule>): Pair<Int, ProductionRule> { return when { terminalRulePattern.matches(rule) -> { val (ruleId, symbol) = terminalRulePattern.matchEntire(rule)!!.destructured Pair(ruleId.toInt(), TerminalRule(symbol.toCharArray().first())) } nonTerminalRulePattern.matches(rule) -> { val match = nonTerminalRulePattern.matchEntire(rule) val (ruleId, ruleContent) = match!!.destructured val alternatives = ruleContent.split("|") .asSequence() .filter { it.isNotEmpty() } .map { singleRule -> singleRule.split(" ") .asSequence() .filter { it.isNotEmpty() }.map { RuleReference(it.toInt(), mapping) } .toList() } .toList() val parsedRule = if (alternatives.size == 1) { SequenceRule(alternatives.first()) } else { AlternativeRule(alternatives.map { SequenceRule(it) }) } Pair(ruleId.toInt(), parsedRule) } else -> throw IllegalStateException("Failed to parse rule!") } } fun match(rules: Map<Int, ProductionRule>, input: String): Boolean { val rootRule = rules[0]!! val inputSequence = input.toCharArray().toList() return runBlocking(Dispatchers.Default) { rootRule.match(inputSequence).count { it.matched.size == input.length } > 0 } }
0
Kotlin
0
0
a16e95841e9b8ff9156b54e74ace9ccf33e6f2a6
3,897
aoc2020
MIT License
src/main/kotlin/15/15.kt
Wrent
225,133,563
false
null
import java.math.BigInteger fun main() { val ship = mutableMapOf<Coord, ShipBlock>() ship[Coord(0, 0)] = ShipBlock(0, ShipBlockType.EMPTY) val data = mutableMapOf<BigInteger, BigInteger>() INPUT15.split(",").map { it.toBigInteger() }.forEachIndexed { index, i -> data[index.toBigInteger()] = i } var index = BigInteger.ZERO relativeBase = BigInteger.ZERO println("first result") try { while (true) { val instr = parseInstr(index, data, { droidInput(ship) }, { lastOutput = it.intValueExact() }) index = instr.apply(data, index) } } catch (ex: HaltException) { } } var oxygenCoord = Coord(0,0) fun droidInput(ship: MutableMap<Coord, ShipBlock>): BigInteger { when (lastOutput) { 0 -> { ship[current] = ShipBlock(0, ShipBlockType.WALL) current = prev direction = nextDirection(ship, direction, current) } 1 -> { if (ship[current] == null) ship[current] = ShipBlock(ship[prev]!!.steps + 1, ShipBlockType.EMPTY) if (ship[moveDroid(current, nextDirection(direction))] == null || ship[moveDroid(current, nextDirection(direction))]?.type != ShipBlockType.WALL) { direction = nextDirection(ship, direction, current) } } 2 -> { ship[current] = ShipBlock(ship[prev]!!.steps + 1, ShipBlockType.OXYGEN) println("${ship[current]!!.steps}") oxygenCoord = current throw HaltException() } } prev = current current = moveDroid(current, direction) ship.printShip() println() println() return direction.toBigInteger() } private fun MutableMap<Coord, ShipBlock>.printShip() { val minX = this.keys.minBy { it.x }!!.x val minY = this.keys.minBy { it.y }!!.y val maxX = this.keys.maxBy { it.x }!!.x val maxY = this.keys.maxBy { it.y }!!.y for (j in minY..maxY) { for (i in minX..maxX) { if (prev == Coord(i, j)) { print("D") } else { when (this[Coord(i, j)]) { null -> print("?") else -> print(this[Coord(i, j)]!!.type.value) } } } println() } } fun nextDirection(ship: MutableMap<Coord, ShipBlock>, direction: Int, current: Coord): Int { val possibleDirections = listOf(nextDirection(direction), nextDirection(nextDirection(direction)), nextDirection(nextDirection(nextDirection(direction)))) return possibleDirections.firstOrNull { ship[moveDroid(current, it)] == null } ?: possibleDirections .filter { ship[moveDroid(current, it)]?.type != ShipBlockType.WALL } .minBy { ship[moveDroid(current, it)]!!.steps }!! } private fun nextDirection(direction: Int): Int { // return Random.nextInt(1,4) return when (direction) { 1 -> 4 2 -> 3 3 -> 1 4 -> 2 else -> throw RuntimeException("invalid direction") } } fun moveDroid(current: Coord, direction: Int): Coord { return when (direction) { 1 -> current.north() 2 -> current.south() 3 -> current.west() 4 -> current.east() else -> throw RuntimeException("invalid direction") } } var steps = 0 var lastOutput = 1 var current = Coord(0, 0) var prev = Coord(0, 0) var direction = 1 data class ShipBlock(val steps: Int, val type: ShipBlockType) enum class ShipBlockType(val value: Char) { WALL('#'), EMPTY('.'), OXYGEN('T') } const val INPUT15 = """3,1033,1008,1033,1,1032,1005,1032,31,1008,1033,2,1032,1005,1032,58,1008,1033,3,1032,1005,1032,81,1008,1033,4,1032,1005,1032,104,99,102,1,1034,1039,101,0,1036,1041,1001,1035,-1,1040,1008,1038,0,1043,102,-1,1043,1032,1,1037,1032,1042,1105,1,124,1001,1034,0,1039,102,1,1036,1041,1001,1035,1,1040,1008,1038,0,1043,1,1037,1038,1042,1106,0,124,1001,1034,-1,1039,1008,1036,0,1041,102,1,1035,1040,1002,1038,1,1043,101,0,1037,1042,1106,0,124,1001,1034,1,1039,1008,1036,0,1041,1002,1035,1,1040,102,1,1038,1043,101,0,1037,1042,1006,1039,217,1006,1040,217,1008,1039,40,1032,1005,1032,217,1008,1040,40,1032,1005,1032,217,1008,1039,37,1032,1006,1032,165,1008,1040,39,1032,1006,1032,165,1102,2,1,1044,1106,0,224,2,1041,1043,1032,1006,1032,179,1101,0,1,1044,1105,1,224,1,1041,1043,1032,1006,1032,217,1,1042,1043,1032,1001,1032,-1,1032,1002,1032,39,1032,1,1032,1039,1032,101,-1,1032,1032,101,252,1032,211,1007,0,74,1044,1106,0,224,1102,0,1,1044,1106,0,224,1006,1044,247,1002,1039,1,1034,102,1,1040,1035,1002,1041,1,1036,102,1,1043,1038,1001,1042,0,1037,4,1044,1106,0,0,4,35,96,8,87,44,67,40,80,25,91,53,86,23,96,7,76,76,10,30,90,46,47,40,93,75,3,17,1,19,89,7,92,47,95,3,92,39,72,69,6,18,86,94,19,82,98,9,7,91,42,86,29,83,65,43,91,71,92,16,96,82,5,81,6,92,93,76,71,17,91,91,73,64,33,27,89,4,99,81,80,6,57,87,9,42,99,97,13,42,81,82,72,68,35,93,2,99,6,6,94,2,39,39,86,43,97,77,86,21,56,75,61,91,82,56,94,32,47,90,33,72,93,13,87,12,42,68,99,71,34,97,79,87,99,79,25,42,95,97,51,93,80,33,71,68,89,50,49,78,77,24,93,70,13,11,56,29,18,77,77,94,60,80,75,84,42,87,90,58,84,27,78,3,80,70,85,79,4,36,94,65,79,93,94,13,97,75,49,92,15,84,5,85,35,67,96,87,64,32,83,97,20,89,64,18,93,32,46,91,57,53,75,56,7,56,92,99,36,22,93,19,25,29,48,86,94,68,18,95,79,87,97,55,75,44,65,82,99,31,94,42,53,81,72,85,70,93,47,40,77,60,85,87,11,60,98,25,90,88,93,93,85,64,43,88,96,36,83,14,98,40,48,11,18,80,97,49,23,2,91,85,50,88,94,41,75,99,84,15,45,9,81,83,96,51,56,58,76,72,50,94,59,76,87,10,25,88,73,99,20,95,46,93,88,2,50,89,86,26,18,85,72,85,75,66,83,25,97,96,25,94,14,34,94,89,57,88,78,17,92,59,40,29,84,87,55,61,81,9,82,93,17,33,81,81,58,43,91,68,86,80,61,83,23,46,78,60,14,94,79,28,91,57,79,83,48,92,5,49,97,81,56,53,84,42,58,93,20,71,29,29,89,88,34,31,87,92,78,62,78,72,93,3,54,97,82,38,32,89,86,88,38,19,84,51,99,60,90,95,14,78,11,82,89,12,87,98,70,79,33,76,44,97,79,33,19,34,83,58,4,89,21,88,78,46,78,76,66,61,92,91,38,86,27,61,86,46,52,97,44,80,89,53,55,47,83,34,44,97,37,41,92,28,70,95,82,91,76,8,99,2,80,1,66,96,71,94,1,44,89,29,13,99,35,80,89,31,91,19,77,46,85,77,93,61,31,62,14,92,82,73,94,86,20,31,94,72,73,44,61,91,79,40,88,69,85,6,83,96,49,12,77,39,83,91,24,70,13,81,57,39,88,38,23,80,43,92,67,46,87,25,80,93,82,68,98,93,63,85,29,18,78,94,27,89,85,20,63,89,93,96,99,50,71,97,15,28,53,78,85,78,82,64,67,14,94,47,96,65,58,81,20,91,36,82,55,11,85,87,59,84,6,67,87,69,88,81,68,38,84,52,33,79,97,69,89,89,34,96,18,78,67,87,36,93,57,77,77,21,47,99,27,26,79,7,88,37,90,33,25,96,66,83,24,30,82,84,16,82,85,15,55,92,20,80,92,38,20,34,87,67,11,84,28,42,93,26,54,89,85,78,82,60,14,9,76,85,10,80,80,50,85,29,86,20,61,81,80,51,32,88,91,92,34,56,79,58,76,41,47,89,24,40,90,85,88,30,48,91,42,2,91,95,98,60,79,40,86,61,79,81,23,91,91,12,21,78,54,75,61,11,79,89,73,84,13,95,81,6,52,92,37,76,65,82,84,87,40,94,70,78,71,83,46,94,2,79,57,80,35,99,21,83,81,93,64,81,78,99,57,87,49,87,41,92,83,82,58,92,0,0,21,21,1,10,1,0,0,0,0,0,0"""
0
Kotlin
0
0
0a783ed8b137c31cd0ce2e56e451c6777465af5d
7,030
advent-of-code-2019
MIT License
src/main/kotlin/report/cpf/iteration/ReducedProgram.kt
Tiofx
175,697,373
false
null
package report.cpf.iteration import algorithm.CPF import kotlin.math.min class ReducedProgram(val limit: Int = 17, val groupMinSize: Int = 3, val startMinSize: Int = 3, val endMinSize: Int = 6) { lateinit var iteration: CPF.Iteration private val group get() = iteration.groupedOperators private val program get() = iteration.program val startMaxSize get() = group.start val endMaxSize get() = program.lastIndex - group.endInclusive val groupMaxSize get() = group.toList().size fun size(): TempSize = TempSize(startMinSize, groupMinSize, endMinSize) .minimaze() .maxGroupSize() .maxStartSize() .maxEndSize() val groupSize get() = size().group val startSize get() = size().start val endSize get() = size().end val startRange get() = if (startSize > 0) 0..(startSize - 1) else IntRange.EMPTY val groupSkipAdditionalSpace get() = if (groupMaxSize - groupSize == 1) 1 else 0 val groupStartRange get() = group.start..(group.start + groupSize / 2 + groupSize % 2 - 1 - groupSkipAdditionalSpace) val groupEndRange get() = (group.endInclusive - groupSize / 2 + 1)..group.endInclusive val endRange get() = if (endSize > 0) (program.lastIndex - endSize + 1)..program.lastIndex else IntRange.EMPTY fun parse() = Indexes( startRange, groupStartRange, groupEndRange, endRange ) data class Indexes( val start: IntRange, val groupStart: IntRange, val groupEnd: IntRange, val end: IntRange ) { val hasSkipBeforeGroup: Boolean = !start.isEmpty() && start.endInclusive + 1 != groupStart.start val hasSkipInGroup: Boolean = !groupStart.isEmpty() && groupStart.endInclusive + 1 != groupEnd.start val hasSkipBeforeEnd: Boolean = !end.isEmpty() && groupEnd.endInclusive + 1 != end.start } inner class TempSize(val start: Int, val group: Int, val end: Int) { val total get() = start + group + end val rem get() = limit - total fun minimaze(): TempSize = TempSize( min(startMinSize, startMaxSize), min(groupMinSize, groupMaxSize), min(endMinSize, endMaxSize) ) fun maxGroupSize(): TempSize = if (groupMaxSize <= group + rem) copy(group = groupMaxSize) else copy(group = group + rem) fun maxStartSize(): TempSize = if (startMaxSize <= start + rem) copy(start = startMaxSize) else copy(start = start + rem) fun maxEndSize(): TempSize = if (endMaxSize <= end + rem) copy(end = endMaxSize) else copy(end = end + rem) fun copy( start: Int = this.start, group: Int = this.group, end: Int = this.end ) = TempSize(start, group, end) } }
0
Kotlin
0
0
32c1cc3e95940e377ed9a99293eccc871ce13864
3,123
CPF
The Unlicense
day13/Kotlin/day13.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* fun print_day_13() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 13" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Transparent Origami -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_13() Day13().part_1() Day13().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day13 { private val lines = File("../Input/day13.txt").readLines() private val coords = lines.takeWhile { it.trim() != "" }.map { val (x, y) = it.split(",") x.toInt() to y.toInt() } private val folds = lines.drop(coords.size + 1) fun part_1() { val maxX = coords.maxOf { it.first } val maxY = coords.maxOf { it.second } val yFold = folds.first().startsWith("fold along y") val foldAmount = folds.first().split("=")[1].toInt() val afterFold = if (yFold) { val newCoords = coords.filter { it.second < foldAmount }.toMutableList() for (pair in coords.filter {it.second > foldAmount} ) { newCoords.add(pair.first to maxY - pair.second) } newCoords } else { val newCoords = coords.filter { it.first < foldAmount }.toMutableList() for (pair in coords.filter {it.first > foldAmount} ) { newCoords.add(maxX - pair.first to pair.second) } newCoords } println("Puzzle 1: " + afterFold.distinct().size) } fun part_2() { var foldedCoords = coords folds.forEach { fold -> val maxX = foldedCoords.maxOf { it.first } val maxY = foldedCoords.maxOf { it.second } val yFold = fold.startsWith("fold along y") val foldAmount = fold.split("=")[1].toInt() val afterFold = if (yFold) { val newCoords = foldedCoords.filter { it.second < foldAmount }.toMutableList() for (pair in foldedCoords.filter {it.second > foldAmount} ) { newCoords.add(pair.first to maxY - pair.second) } newCoords } else { val newCoords = foldedCoords.filter { it.first < foldAmount }.toMutableList() for (pair in foldedCoords.filter {it.first > foldAmount} ) { newCoords.add(maxX - pair.first to pair.second) } newCoords } foldedCoords = afterFold } val maxX = foldedCoords.maxOf { it.first } val maxY = foldedCoords.maxOf { it.second } println("Puzzle 2: ") for (y in 0..maxY) { for (x in 0..maxX) { print( if ((x to y) in foldedCoords) "#" else " ") } println() } } }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
3,211
AOC2021
Apache License 2.0
src/Day14.kt
er453r
572,440,270
false
{"Kotlin": 69456}
fun main() { fun fallingSand(input: List<String>, hardFloor: Boolean, stopOnOverflow: Boolean, startPoint: Vector2d = Vector2d(500, 0)): Int { val lines = input.map { it.ints().chunked(2).map { (x, y) -> Vector2d(x, y) }.toList() } val xMin = lines.flatten().toMutableList().also { it.add(startPoint) }.minOf { it.x } val yMin = lines.flatten().toMutableList().also { it.add(startPoint) }.minOf { it.y } val xMax = lines.flatten().toMutableList().also { it.add(startPoint) }.maxOf { it.x } val yMax = lines.flatten().toMutableList().also { it.add(startPoint) }.maxOf { it.y } val occupied = mutableSetOf<Vector2d>() for (line in lines) for (n in 0 until line.size - 1) { var current = line[n] val to = line[n + 1] val step = (to - current).normalized() while (current != to + step) { occupied += current current += step } } var unitsResting = 0 unitLoop@ while (true) { var current = startPoint while (true) { when { hardFloor && current.y == yMax + 1 -> { occupied += current unitsResting++ continue@unitLoop } !hardFloor && (current.x !in (xMin..xMax) || current.y !in (yMin..yMax)) -> return unitsResting (current + Vector2d.DOWN) !in occupied -> current += Vector2d.DOWN (current + Vector2d.DOWN + Vector2d.LEFT) !in occupied -> current += Vector2d.DOWN + Vector2d.LEFT (current + Vector2d.DOWN + Vector2d.RIGHT) !in occupied -> current += Vector2d.DOWN + Vector2d.RIGHT else -> { occupied += current unitsResting++ if (stopOnOverflow && current == startPoint) return unitsResting continue@unitLoop } } } } } fun part1(input: List<String>) = fallingSand(input, hardFloor = false, stopOnOverflow = false) fun part2(input: List<String>) = fallingSand(input, hardFloor = true, stopOnOverflow = true) test( day = 14, testTarget1 = 24, testTarget2 = 93, part1 = ::part1, part2 = ::part2, ) }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
2,565
aoc2022
Apache License 2.0
src/main/kotlin/day4.kt
nerok
436,232,451
false
{"Kotlin": 32118}
import java.io.File fun main(args: Array<String>) { day4() } fun day4() { val input = File("day4input.txt").bufferedReader() val drawings = input.readLine().split(",").map { it.toInt() } input.readLines() .asSequence() .windowed(6, step = 6) .map { board -> board.filter { it.isNotEmpty() } } .map { board -> board.map { row -> row.split(" ") .filter { it.isNotEmpty() } .map { it.toInt() } .toMutableList() } } .map { board -> calculateScore(board, drawings) } //.minByOrNull for part 1 //.maxByOrNull for part 2 .maxByOrNull { it.first }!!.also { println(it) } } fun calculateScore(bingoBoard: List<MutableList<Int>>, drawing: List<Int>): Pair<Int, Int> { drawing.forEachIndexed { drawNumber, draw -> bingoBoard.mapIndexed { index, ints -> if (ints.contains(draw)) { index to ints.indexOf(draw) } else { null } }.filterNotNull().forEach { coordinate -> bingoBoard[coordinate.first][coordinate.second] = 0 if (bingoBoard[coordinate.first].none { it != 0 }) { return drawNumber to bingoBoard.sumOf { it.sum() } * drawing[drawNumber] } else if (bingoBoard.map { row -> row[coordinate.second] }.none { it != 0 }) { return drawNumber to bingoBoard.sumOf { it.sum() } * drawing[drawNumber] } } } return 0 to 0 }
0
Kotlin
0
0
4dee925c0f003fdeca6c6f17c9875dbc42106e1b
1,646
Advent-of-code-2021
MIT License
src/twentytwentytwo/day1/Day01.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
fun main() { fun part1(input: List<String>): Int { var maxCalorie = 0 var currentCalorieCount = 0 var currentIndex = 0 input.forEach { line -> val currentInt = line.toIntOrNull() if (currentInt != null) { currentCalorieCount += currentInt } else { if (currentCalorieCount > maxCalorie) { maxCalorie = currentCalorieCount } currentCalorieCount = 0 currentIndex++ } } return maxCalorie } fun part2(input: List<String>): Int { var maxCalorie = 0 var currentCalorieCount = 0 var currentIndex = 0 val calorieList = mutableListOf<Int>() input.forEach { line -> val currentInt = line.toIntOrNull() if (currentInt != null) { currentCalorieCount += currentInt } else { if (currentCalorieCount > maxCalorie) { maxCalorie = currentCalorieCount } calorieList.add(currentCalorieCount) currentCalorieCount = 0 currentIndex++ } } calorieList.sortDescending() return calorieList[0] + calorieList[1] + calorieList[2] } val input = readInput("day1", "Day01_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
1,451
advent-of-code
Apache License 2.0
src/main/kotlin/g1301_1400/s1335_minimum_difficulty_of_a_job_schedule/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1335_minimum_difficulty_of_a_job_schedule // #Hard #Array #Dynamic_Programming #2023_06_06_Time_154_ms_(100.00%)_Space_34.1_MB_(100.00%) class Solution { fun minDifficulty(jobDifficulty: IntArray, d: Int): Int { val totalJobs = jobDifficulty.size if (totalJobs < d) { return -1 } val maxJobsOneDay = totalJobs - d + 1 val map = IntArray(totalJobs) var maxDiff = Int.MIN_VALUE for (k in totalJobs - 1 downTo totalJobs - 1 - maxJobsOneDay + 1) { maxDiff = Math.max(maxDiff, jobDifficulty[k]) map[k] = maxDiff } for (day in d - 1 downTo 1) { val maxEndIndex = totalJobs - 1 - (d - day) val maxStartIndex = maxEndIndex - maxJobsOneDay + 1 for (startIndex in maxStartIndex..maxEndIndex) { map[startIndex] = Int.MAX_VALUE var maxDiffOfTheDay = Int.MIN_VALUE for (endIndex in startIndex..maxEndIndex) { maxDiffOfTheDay = Math.max(maxDiffOfTheDay, jobDifficulty[endIndex]) val totalDiff = maxDiffOfTheDay + map[endIndex + 1] map[startIndex] = Math.min(map[startIndex], totalDiff) } } } return map[0] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,322
LeetCode-in-Kotlin
MIT License
src/main/kotlin/info/dgjones/barnable/domain/general/Group.kt
jonesd
442,279,905
false
{"Kotlin": 474251}
/* * 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 info.dgjones.barnable.domain.general import info.dgjones.barnable.concept.* import info.dgjones.barnable.parser.* /* Group concepts hold a list of other concept of the same head value */ enum class GroupConcept { Group, MultipleGroup, Values } enum class GroupFields(override val fieldName: String): Fields { Conjunction("conjunction"), Elements("elements"), ElementsType("elementsType"), GroupInstances("groupInstances") } class GroupAccessor(private val group: Concept) { val size: Int get() = list()?.size ?: 0 operator fun get(i: Int): Concept? { val listAccessor = list() return if (listAccessor != null) listAccessor[i] else null } fun concepts(): List<Concept> { return list()?.concepts() ?: listOf<Concept>() } fun valueNames(): List<String> { return concepts().map { it.name } } fun elementType(): String? { return group.valueName(GroupFields.ElementsType) } fun conjunctionType(): String? { return group.valueName(GroupFields.Conjunction) } fun add(concept: Concept):Boolean { if (elementType() == concept.name) { list()?.let { list -> list.add(concept) return true } } else { print("ERROR element $concept does not match group type $group") } return false } init { check(group.name == GroupConcept.Group.name) { "should be group rather than ${group.name}"} } private fun list(): ConceptListAccessor? { val elements = group.value(GroupFields.Elements) return if (elements != null) ConceptListAccessor(elements) else null } } /** * Build a group concept structure from the provided elements. * By default the element type of the group will be found from the first element, * however, it can be set/overridden as an optional parameter. */ fun buildGroup(elements: List<Concept>, elementType: Concept? = null): Concept { val root = Concept(GroupConcept.Group.name) val elementsField = buildConceptList(elements, GroupConcept.Values.name) root.with(Slot(GroupFields.Elements, elementsField)) val t = elementType ?: (elements.firstOrNull()?.let { extractConceptHead.transform(it)}) t?.let { root.value(GroupFields.ElementsType, t) } return root } fun addConceptToHomogenousGroup(group: Concept, concept: Concept): Boolean { return GroupAccessor(group).add(concept) } fun LexicalConceptBuilder.addToGroup(matcher: ConceptMatcher, direction: SearchDirection = SearchDirection.After,) { val demon = AddToGroupDemon(matcher, direction, root.wordContext) { elementHolder -> elementHolder.value = null elementHolder.addFlag(ParserFlags.Inside) } root.addDemon(demon) } /* Find the matcher element and add it to the predecessor group. Pass the found element as the demon resulting action */ class AddToGroupDemon(val matcher: ConceptMatcher, val direction: SearchDirection = SearchDirection.After, wordContext: WordContext, val action: (ConceptHolder) -> Unit): Demon(wordContext) { override fun run() { searchContext(matcher, matchNever(), direction = direction, wordContext = wordContext) { elementHolder -> elementHolder.value?.let { element -> searchContext(matchConceptByHead(GroupConcept.Group.name), matchNever(), direction = SearchDirection.Before, wordContext = wordContext) { groupHolder -> groupHolder.value?.let { group -> if (addConceptToHomogenousGroup(group, element)) { active = false println("Added $element to group $group") action(elementHolder) } } } } } } override fun description(): String { return "Match concept and add to the predecessor Group, assuming head type matches" } }
1
Kotlin
0
0
b5b7453e2fe0b2ae7b21533db1b2b437b294c63f
4,607
barnable
Apache License 2.0
src/main/kotlin/day3/Day3.kt
afTrolle
572,960,379
false
{"Kotlin": 33530}
package day3 import Day fun main() { Day3("Day03").solve() } class Day3(input: String) : Day<List<Day3.Rucksack>>(input) { data class Rucksack(val data: String) { private val compartmentSize = data.length / 2 private val a = data.take(compartmentSize).toSet() private val b = data.drop(compartmentSize).toSet() val overlap = a.intersect(b) val items = data.toSet() } private fun Char.priority(): Int = when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("invalid char") } override fun parseInput(): List<Rucksack> = inputByLines.map { Rucksack(it) } override fun part1(input: List<Rucksack>): Any = input.map { it.overlap }.flatten().sumOf { it.priority() } override fun part2(input: List<Rucksack>): Any = input.chunked(3).map { groupBags -> groupBags.map { it.items }.reduce { acc, chars -> acc.intersect(chars) }.first() }.sumOf { it.priority() } }
0
Kotlin
0
0
4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545
1,044
aoc-2022
Apache License 2.0
src/main/kotlin/com/sk/topicWise/tree/medium/236. Lowest Common Ancestor of a Binary Tree.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.tree.medium import com.sk.topicWise.tree.TreeNode class Solution236_1 { fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? { if (root == null || root === p || root === q) return root val left = lowestCommonAncestor(root.left, p, q) val right = lowestCommonAncestor(root.right, p, q) return if (left != null && right != null) root else left ?: right } } class Solution236_2 { fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? { val parent = HashMap<TreeNode?, TreeNode?>() val queue = ArrayDeque<TreeNode>() queue.add(root!!) parent[root] = null // Traverse to p and q, and make parent map while (parent.containsKey(p).not() || parent.containsKey(q).not()) { val n = queue.removeLast() if (n.left != null) { parent[n.left!!] = n queue.add(n.left!!) } if (n.right != null) { parent[n.right!!] = n queue.add(n.right!!) } } val ancestors = HashSet<TreeNode>() // Traverse upward from p to root, make set of path var c = p while (c != null) { ancestors.add(c) c = parent[c] } // Traverse in q parent and find common parent c = q while (ancestors.contains(c).not()) { c = parent[c] } return c } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,529
leetcode-kotlin
Apache License 2.0
src/day06/Day06.kt
MaxBeauchemin
573,094,480
false
{"Kotlin": 60619}
package day06 import readInput fun main() { fun findUniqueBufferStartIndex(input: String, desiredSize: Int): Int { var buffer = "" input.toList().forEachIndexed { index, c -> buffer += c if (buffer.length == desiredSize + 1) { buffer = buffer.slice(1..desiredSize) } if (buffer.length == desiredSize) { if (buffer.toList().distinct().size == desiredSize) return index } } return Int.MIN_VALUE } fun part1(input: String): Int { return findUniqueBufferStartIndex(input, 4) + 1 } fun part2(input: String): Int { return findUniqueBufferStartIndex(input, 14) + 1 } val testInput = readInput("Day06_test").first() val input = readInput("Day06").first() println("Part 1 [Test] : ${part1(testInput)}") check(part1(testInput) == 7) println("Part 1 [Real] : ${part1(input)}") println("Part 2 [Test] : ${part2(testInput)}") check(part2(testInput) == 19) println("Part 2 [Real] : ${part2(input)}") }
0
Kotlin
0
0
38018d252183bd6b64095a8c9f2920e900863a79
1,094
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g0201_0300/s0210_course_schedule_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0201_0300.s0210_course_schedule_ii // #Medium #Top_Interview_Questions #Depth_First_Search #Breadth_First_Search #Graph // #Topological_Sort #Level_2_Day_11_Graph/BFS/DFS // #2022_10_20_Time_266_ms_(96.32%)_Space_45.9_MB_(92.65%) class Solution { fun findOrder(numCourses: Int, prerequisites: Array<IntArray>): IntArray { val indegrees = IntArray(numCourses) { 0 } val graph = buildGraph(numCourses, prerequisites, indegrees) val queue = ArrayDeque<Int>() for ((idx, indegree) in indegrees.withIndex()) { if (indegree == 0) { queue.addLast(idx) } } val ans = IntArray(numCourses) { 0 } var idx = 0 while (queue.isNotEmpty()) { val cur = queue.removeFirst() ans[idx++] = cur for (pre in graph[cur]) { if (--indegrees[pre] == 0) { queue.addLast(pre) } } } if (idx < numCourses) { return intArrayOf() } return ans } private fun buildGraph( numCourses: Int, prerequisites: Array<IntArray>, indegrees: IntArray ): List<List<Int>> { val graph = List(numCourses) { mutableListOf<Int>() } for ((cur, prev) in prerequisites) { graph[prev].add(cur) ++indegrees[cur] } return graph } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,435
LeetCode-in-Kotlin
MIT License
src/main/kotlin/io/github/nillkki/aoc/Day08.kt
Nillkki
572,858,950
false
{"Kotlin": 38345}
package io.github.nillkki.aoc import org.openjdk.jmh.annotations.Benchmark import org.openjdk.jmh.annotations.Measurement import org.openjdk.jmh.annotations.Scope import org.openjdk.jmh.annotations.Setup import org.openjdk.jmh.annotations.State import org.openjdk.jmh.annotations.Warmup @State(Scope.Benchmark) @Warmup(iterations = 1) @Measurement(iterations = 3) class Day08 { companion object { private fun buildGrid(input: List<String>): Array<IntArray> { return input.map { line -> line.map { it.digitToInt() }.toIntArray() }.toTypedArray() } /** * Tree is taller that trees on the same row or column until the edge */ private fun isTallerThanRowOrColumn( tree: Int, top: List<Int>, bottom: List<Int>, left: IntArray, right: IntArray ): Boolean { return top.all { it < tree } || bottom.all { it < tree } || left.all { it < tree } || right.all { it < tree } } fun part1(input: List<String>): Int { val grid = buildGrid(input) // Count the visible trees return grid.mapIndexed column@{ columnIndex, row -> fun isAtEdge(cIdx: Int, rIdx: Int): Boolean { return (cIdx == 0) || (rIdx == 0) || (cIdx == grid.size) || (rIdx == row.size) } return@column row.mapIndexed row@{ rowIndex, tree -> if (isAtEdge(columnIndex, rowIndex)) { // Tree is at the edge, is always visible return@row 1 } // To be visible, // tree must be taller that trees on the same row or column until the edge val top = grid.sliceArray(0 until columnIndex).map { it[rowIndex] } val bottom = grid.sliceArray(columnIndex + 1 until grid.size).map { it[rowIndex] } val left = row.sliceArray(0 until rowIndex) val right = row.sliceArray(rowIndex + 1 until row.size) if (isTallerThanRowOrColumn(tree, top, bottom, left, right)) { return@row 1 } return@row 0 } .sum() } .sum() } /** * Trees seen until taller tree blocks the view or there are no more trees */ private fun getViewingDistance(trees: List<Int>, tree: Int): Int { trees.forEachIndexed { index, t -> // Stop when tree is as tall or taller than the current tree if (t >= tree) { return index + 1 } } // If we never stopped distance is the whole length of trees return trees.size } public fun part2(input: List<String>): Int { val grid = buildGrid(input) // Calculate scenic score for all trees // A tree's scenic score is found by multiplying together its viewing distance in each of // the four directions // To measure the viewing distance from a given tree, look up, down, left, and right from // that tree; stop if you reach an edge or at the first tree that is the same height or // taller than the tree under consideration. (If a tree is right on the edge, at least one // of its viewing distances will be zero.) val scenicScoreGrid = Array(grid.size) { Array(grid[0].size) { 0 } } grid.forEachIndexed { columnIndex, row -> row.forEachIndexed { rowIndex, tree -> // Viewing distance top val treesToTop = grid.slice(0 until columnIndex).map { it[rowIndex] }.reversed() val scoreTop = getViewingDistance(treesToTop, tree) // Viewing distance bottom val treesToBottom = grid.slice(columnIndex + 1 until grid.size).map { it[rowIndex] } val scoreBottom = getViewingDistance(treesToBottom, tree) // Viewing distance left val treesToLeft = row.slice(0 until rowIndex).reversed() val scoreLeft = getViewingDistance(treesToLeft, tree) // Viewing distance right val treesToRight = row.slice(rowIndex + 1 until row.size) val scoreRight = getViewingDistance(treesToRight, tree) val scenicScore = scoreTop * scoreBottom * scoreLeft * scoreRight scenicScoreGrid[columnIndex][rowIndex] = scenicScore } } return scenicScoreGrid.maxOf { it.max() } } } private var input = emptyList<String>() @Setup fun setUp() { input = readInput("Day08") } @Benchmark public fun part1Bench() { part1(input) } @Benchmark public fun part2Bench() { part2(input) } } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(Day08.part1(testInput) == 21) check(Day08.part2(testInput) == 8) val input = readInput("Day08") println(Day08.part1(input)) println(Day08.part2(input)) }
0
Kotlin
0
0
42b38e2a2592a8a5191c221b3dc648b879920ef8
5,414
aoc-2022
Apache License 2.0
src/pl/shockah/aoc/y2021/Day13.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2021 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import pl.shockah.aoc.toCharString import pl.shockah.unikorn.collection.Array2D class Day13: AdventTask<Day13.Input, Int, String>(2021, 13) { data class Input( val dots: List<Pair<Int, Int>>, val folds: List<Fold> ) { data class Fold( val axis: Axis, val position: Int ) { enum class Axis { X, Y } } } override fun parseInput(rawInput: String): Input { val rawInputSplit = rawInput.split("\n\n") val dotsInput = rawInputSplit[0].trim() val foldsInput = rawInputSplit[1].trim() val dots = dotsInput.lines().map { val split = it.split(',') return@map Pair(split[0].toInt(), split[1].toInt()) } val folds = foldsInput.lines().map { val split = it.split(' ').last().split('=') return@map Input.Fold(if (split[0] == "x") Input.Fold.Axis.X else Input.Fold.Axis.Y, split[1].toInt()) } return Input(dots, folds) } private fun fold(data: MutableMap<Pair<Int, Int>, Int>, fold: Input.Fold) { when (fold.axis) { Input.Fold.Axis.X -> { val folding = data.keys.filter { it.first >= fold.position } folding.forEach { if (it.first == fold.position) return@forEach val target = (2 * fold.position - it.first) to it.second data[target] = (data[target] ?: 0) + (data[it] ?: 0) } folding.forEach { data.remove(it) } } Input.Fold.Axis.Y -> { val folding = data.keys.filter { it.second >= fold.position } folding.forEach { if (it.second == fold.position) return@forEach val target = it.first to (2 * fold.position - it.second) data[target] = (data[target] ?: 0) + (data[it] ?: 0) } folding.forEach { data.remove(it) } } } } override fun part1(input: Input): Int { val data = mutableMapOf<Pair<Int, Int>, Int>() input.dots.forEach { data[it] = 1 } fold(data, input.folds.first()) return data.keys.size } override fun part2(input: Input): String { val data = mutableMapOf<Pair<Int, Int>, Int>() input.dots.forEach { data[it] = 1 } input.folds.forEach { fold(data, it) } val keys = data.keys.toSet() val minX = keys.minOf { it.first } val minY = keys.minOf { it.second } val maxX = keys.maxOf { it.first } val maxY = keys.maxOf { it.second } return Array2D(maxX - minX + 1, maxY - minY + 1) { x, y -> data[x + minX to y + minY] ?: 0 } .toCharString(0, '.', '#') } class Tests { private val task = Day13() private val rawInput = """ 6,10 0,14 9,10 0,3 10,4 4,11 6,0 6,12 4,1 0,13 10,12 3,4 3,0 8,4 1,10 2,14 8,10 9,0 fold along y=7 fold along x=5 """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals(17, task.part1(input)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
2,864
Advent-of-Code
Apache License 2.0
src/Day01.kt
kedvinas
572,850,757
false
{"Kotlin": 15366}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 for (i in input) { if (i.isNotEmpty()) { current += i.toInt() } else { max = max(current, max) current = 0 } } return max(current, max) } fun part2(input: List<String>): Int { var total = mutableListOf<Int>() var current = 0 for (i in input) { if (i.isNotEmpty()) { current += i.toInt() } else { total.add(current) current = 0 } } total.add(current) return total.sorted().takeLast(3).sum() } 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
04437e66eef8cf9388fd1aaea3c442dcb02ddb9e
982
adventofcode2022
Apache License 2.0
src/main/kotlin/leetcode/problem0015/ThreeSum.kt
ayukatawago
456,312,186
false
{"Kotlin": 266300, "Python": 1842}
package leetcode.problem0015 class ThreeSum { fun threeSum(nums: IntArray): List<List<Int>> { if (nums.isEmpty()) { return emptyList() } val answerMap = HashMap<Int, Int>() val answerSet = mutableSetOf<List<Int>>() nums.forEachIndexed { index, num -> if (answerMap.containsKey(num)) { return@forEachIndexed } val tmpList = nums.toMutableList() tmpList.removeAt(index) val twoSumList = twoSum(tmpList.toIntArray(), -num) twoSumList.forEach { twoSum -> if (twoSum.size != 2) { return@forEach } val answer = listOf(num, twoSum[0], twoSum[1]).sorted() answerSet.add(answer) } answerMap[num] = index } return answerSet.toList() } private fun twoSum(nums: IntArray, target: Int): List<List<Int>> { val hashmap = HashMap<Int, Int>() val answerList = mutableListOf<List<Int>>() nums.forEachIndexed { index, value -> val missing = target - value if (hashmap.containsKey(missing) && hashmap[missing] != index) { hashmap[missing]?.let { answerList.add(listOf(nums[it], value)) } } hashmap[value] = index } return answerList } }
0
Kotlin
0
0
f9602f2560a6c9102728ccbc5c1ff8fa421341b8
1,442
leetcode-kotlin
MIT License