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/g1601_1700/s1654_minimum_jumps_to_reach_home/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1601_1700.s1654_minimum_jumps_to_reach_home // #Medium #Array #Dynamic_Programming #Breadth_First_Search // #Graph_Theory_I_Day_11_Breadth_First_Search // #2023_06_15_Time_192_ms_(100.00%)_Space_38.3_MB_(100.00%) import java.util.LinkedList import java.util.Queue class Solution { private class Pair(var i: Int, var backward: Boolean) fun minimumJumps(forbidden: IntArray, a: Int, b: Int, x: Int): Int { val limit = 2000 + 2 * b + 1 val v = BooleanArray(limit) for (num in forbidden) { v[num] = true } var step = 0 val q: Queue<Pair> = LinkedList() q.add(Pair(0, false)) v[0] = true while (q.isNotEmpty()) { val size = q.size for (i in 0 until size) { val c = q.poll() if (c.i == x) { return step } if (!c.backward) { val backward = c.i - b if (backward == x) { return step + 1 } if (backward > 0 && !v[backward]) { q.offer(Pair(backward, true)) v[backward] = true } } val forward = c.i + a if (forward == x) { return step + 1 } if (forward < limit && !v[forward]) { q.offer(Pair(forward, false)) v[forward] = true } } step++ } return -1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,627
LeetCode-in-Kotlin
MIT License
src/main/kotlin/me/peckb/aoc/_2023/calendar/day17/Day17.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2023.calendar.day17 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import kotlin.math.max class Day17 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(filename: String) = generatorFactory.forFile(filename).read { input -> runDijkstra(input, minSteps = 1) { node -> mutableListOf<Direction>().apply { addAll(node.directionTraveling.turnDirections()) if (node.stepsInDirection < 3) { add(node.directionTraveling) } } } } fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input -> runDijkstra(input, minSteps = 4) { node -> mutableListOf<Direction>().apply { if (node.stepsInDirection >= 4) { addAll(node.directionTraveling.turnDirections()) } if (node.stepsInDirection < 10) { add(node.directionTraveling) } } } } private fun runDijkstra(input: Sequence<String>, minSteps: Int, neighbors: (Node) -> List<Direction>): Int { val lavaPool = mutableListOf<MutableList<Int>>().apply { input.forEach { row -> add(row.map { it.digitToInt() }.toMutableList()) } } val start = Node(0, 0) val end = Node(lavaPool.lastIndex, lavaPool[0].lastIndex) val dijkstra = LavaPoolDijkstra(lavaPool) { map, node -> val directionsToTravel = neighbors(node) directionsToTravel.mapNotNull { direction -> node.move(direction, map)?.let { it to map[it.row][it.col] } } } val paths = dijkstra.solve(start, end) { searchNode, goalNode -> when (val colCompare = searchNode.col.compareTo(goalNode.col)) { 0 -> when (val rowCompare = searchNode.row.compareTo(goalNode.row)) { 0 -> max(minSteps - searchNode.stepsInDirection, 0) else -> rowCompare } else -> colCompare } } return paths .filter { it.key.row == end.row && it.key.col == end.col } .filter { it.key.stepsInDirection >= minSteps } .minOf { it.value } } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,056
advent-of-code
MIT License
mobile/src/main/java/ch/epfl/sdp/mobile/application/chess/notation/CommonNotationCombinators.kt
epfl-SDP
462,385,783
false
{"Kotlin": 1271815, "Shell": 359}
package ch.epfl.sdp.mobile.application.chess.notation import ch.epfl.sdp.mobile.application.chess.engine.Board import ch.epfl.sdp.mobile.application.chess.engine.Position import ch.epfl.sdp.mobile.application.chess.parser.Combinators.filter import ch.epfl.sdp.mobile.application.chess.parser.Combinators.flatMap import ch.epfl.sdp.mobile.application.chess.parser.Combinators.map import ch.epfl.sdp.mobile.application.chess.parser.Combinators.repeatAtLeast import ch.epfl.sdp.mobile.application.chess.parser.Parser import ch.epfl.sdp.mobile.application.chess.parser.StringCombinators /** An object which contains some convenience parser combinators for any notation. */ object CommonNotationCombinators { /** A [Parser] which returns the column in a position. */ val column = StringCombinators.char().filter { it in 'a'..'h' }.map { it - 'a' } /** A [Parser] which returns the row in a position. */ val row = StringCombinators.digit().map { 8 - it }.filter { it in 0 until Board.Size } /** A [Parser] which returns a [Position]. */ val position = this.computePosition(column, row) /** * Compute the [position] notation given a [column] and a [row]. * * @param column The [Parser] for the column. * @param row The [Parser] for the row. * @return A [Parser] for the [Position]. */ fun computePosition( column: Parser<String, Int>, row: Parser<String, Int> ): Parser<String, Position> { return column.flatMap { x -> row.map { y -> Position(x, y) } }.filter { it.inBounds } } /** A [Parser] which returns a number of spaces. */ val spaces = StringCombinators.char(' ').repeatAtLeast(count = 1) /** A [Parser] which consumes a number of digits representing an integer number. */ val integer = StringCombinators.digit().repeatAtLeast(count = 1).map { it.fold(0) { acc, digit -> acc * 10 + digit } } }
15
Kotlin
2
13
71f6e2a5978087205b35f82e89ed4005902d697e
1,884
android
MIT License
src/main/kotlin/aoc2022/Day21.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import readInput private typealias Name = String object Day21 { private class Monkey( val name: Name, private var number: Long?, private val operation: () -> Long? = { number } ) { companion object { lateinit var allMonkeys: Map<Name, Monkey> val pattern = """(?<name>[a-z]+): ((?<operand1>[a-z]+) (?<op>[+\-*/]) (?<operand2>[a-z]+))?(?<number>\d+)?""".toPattern() fun fromString(input: String): Monkey { val matcher = pattern.matcher(input) if (!matcher.matches()) { throw IllegalArgumentException("Invalid monkey definition: $input") } val number = matcher.group("number")?.toLong() return if (number != null) { Monkey(matcher.group("name"), number) } else { val op = matcher.group("op") val operation = { val n1 = allMonkeys[matcher.group("operand1")]!!.number val n2 = allMonkeys[matcher.group("operand2")]!!.number if (n1 != null && n2 != null) { val result = when (op) { "+" -> n1 + n2 "-" -> n1 - n2 "*" -> n1 * n2 "/" -> n1 / n2 else -> throw UnsupportedOperationException("Unsupported operation: $op") } result } else { null } } Monkey(matcher.group("name"), null, operation) } } } fun getNumber(): Long? { if (number == null) { number = operation() } return number } } private sealed class Result /** * x * multiplier + offset */ private data class UnknownNumber(val multiplier: Double = 1.0, val offset: Double = 0.0) : Result() { override fun toString() = "${multiplier}x ${if (offset >= 0) "+ " else ""}$offset" } private data class Number(val value: Double) : Result() { override fun toString() = value.toString() } private data class Operation( val operand1: String, val operand2: String, val operation: String ) : Result() private class Monkey2(val name: Name, var result: Result) { companion object { lateinit var allMonkeys: Map<Name, Monkey2> fun fromString(input: String): Monkey2 { val matcher = Monkey.pattern.matcher(input) if (!matcher.matches()) { throw IllegalArgumentException("Invalid monkey definition: $input") } val name = matcher.group("name") if (name == "humn") { return Monkey2(name, UnknownNumber()) } val number = matcher.group("number")?.toDouble() return if (number != null) { Monkey2(name, Number(number)) } else { Monkey2( name, Operation( matcher.group("operand1"), matcher.group("operand2"), matcher.group("op") ) ) } } private fun executeOperation(op: String, o1: Result, o2: Result): Result? { return when { o1 is Number && o2 is Number -> when (op) { "+" -> Number(o1.value + o2.value) "-" -> Number(o1.value - o2.value) "*" -> Number(o1.value * o2.value) "/" -> Number(o1.value / o2.value) else -> throw UnsupportedOperationException("$o1 $op $o2") } o1 is UnknownNumber && o2 is Number -> when (op) { "+" -> o1.copy(offset = o1.offset + o2.value) "-" -> o1.copy(offset = o1.offset - o2.value) "*" -> o1.copy(multiplier = o1.multiplier * o2.value, offset = o1.offset * o2.value) "/" -> o1.copy(multiplier = o1.multiplier / o2.value, offset = o1.offset / o2.value) else -> throw UnsupportedOperationException("$o1 $op $o2") } o1 is Number && o2 is UnknownNumber -> when (op) { "+" -> o2.copy(offset = o2.offset + o1.value) "-" -> o2.copy( multiplier = o2.multiplier * -1, offset = o1.value - o2.offset ) "*" -> o2.copy(multiplier = o2.multiplier * o1.value, offset = o2.offset * o1.value) "/" -> o2.copy( multiplier = o1.value / o2.multiplier, offset = o1.value / o2.offset ) else -> throw UnsupportedOperationException("$o1 $op $o2") } o1 is UnknownNumber && o2 is UnknownNumber -> throw UnsupportedOperationException("Not implemented: $o1 $op $o2") else -> null } } } fun reduce(): Result { if (name != "root" && result is Operation) { val op = result as Operation val o1 = allMonkeys[op.operand1]!! val o2 = allMonkeys[op.operand2]!! val newResult = executeOperation(op.operation, o1.result, o2.result) if (newResult != null) { result = newResult } } return result } } fun part1(input: List<String>): Long { Monkey.allMonkeys = input.map { Monkey.fromString(it) }.associateBy { it.name } val root = Monkey.allMonkeys["root"]!! while (root.getNumber() == null) { Monkey.allMonkeys.values.forEach { it.getNumber() } } return root.getNumber()!! } fun part2(input: List<String>): String { Monkey2.allMonkeys = input.map { Monkey2.fromString(it) }.associateBy { it.name } val rootOp = Monkey2.allMonkeys["root"]!!.result as Operation var canBeReduces = true while (canBeReduces) { canBeReduces = Monkey2.allMonkeys.values.any { it.result != it.reduce() } } return "${Monkey2.allMonkeys[rootOp.operand1]!!.result} = ${Monkey2.allMonkeys[rootOp.operand2]!!.result}" } } fun main() { val testInput = readInput("Day21_test", 2022) check(Day21.part1(testInput) == 152L) check(Day21.part2(testInput) == "0.5x -0.5 = 150.0") val input = readInput("Day21", 2022) println(Day21.part1(input)) println(Day21.part2(input)) // use wolframalpha.com to solve... }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
7,228
adventOfCode
Apache License 2.0
Tic-Tac-Toe.kt
AlphaCodingPilot
319,027,540
false
{"Kotlin": 15793}
val brett = mutableListOf( 0, 0, 0, 0, 0, 0, 0, 0, 0 ) fun menschZug(): Int { println("Du bist am Zug") while (true) { val eingabe = readLine()?.toIntOrNull() if (eingabe != null && eingabe > 0 && eingabe < 10) { if (brett[eingabe - 1] == 0) { brett[eingabe - 1] = -1 return eingabe - 1 } } println("Falsche Eingabe") } } data class Knoten(val kinder: List<Knoten>, var wert: Int = 0, val brett: List<Int>, val zug: Int) fun generieren(brett: List<Int>, feld: Int, dran: Int): Knoten { val kinder = mutableListOf<Knoten>() brett.forEachIndexed { feld, _ -> if (brett[feld] == 0) { val brett1 = brett.toMutableList() brett1[feld] = dran if (gewonnen(brett1, 1) || gewonnen(brett1, -1)) { kinder.add(Knoten(listOf(), brett = brett1, zug = feld)) } else { kinder.add(generieren(brett1, feld, dran * -1)) } } } return Knoten(kinder, brett = brett, zug = feld) } fun minMax(minMax: Int, knoten: Knoten) { if (gewonnen(knoten.brett, -1)) { knoten.wert = -1 return } if (gewonnen(knoten.brett, 1)) { knoten.wert = 1 return } knoten.kinder.forEach { kind -> minMax(minMax * -1, kind) } if (knoten.kinder.isEmpty()) { return } if (minMax == 1) { knoten.wert = knoten.kinder.maxOf { kind -> kind.wert } } else { knoten.wert = knoten.kinder.minOf { kind -> kind.wert } } } fun computerZug(knoten: Knoten): Int { val max = knoten.kinder.maxOf { kind -> kind.wert } val liste = mutableListOf<Knoten>() knoten.kinder.forEach { kind -> if (kind.wert == max) { liste.add(kind) } } val zug = liste.random().zug brett[zug] = 1 return zug } fun gewonnen(brett: List<Int>, wer: Int): Boolean { return (brett[0] == wer && brett[1] == wer && brett[2] == wer || brett[3] == wer && brett[4] == wer && brett[5] == wer || brett[6] == wer && brett[7] == wer && brett[8] == wer || brett[1] == wer && brett[4] == wer && brett[7] == wer || brett[2] == wer && brett[5] == wer && brett[8] == wer || brett[0] == wer && brett[4] == wer && brett[8] == wer || brett[2] == wer && brett[4] == wer && brett[6] == wer || brett[0] == wer && brett[3] == wer && brett[6] == wer) } fun start(): Int { while (true) { println("Wills du beginnen (j/n)") val e = readLine() if (e == "j") { return -1 } else if (e == "n") { return 1 } println("Falsche Eingabe") } } fun main() { var dran = start() var k = generieren(brett.toMutableList(), -1, dran) minMax(dran, k) var runde = 0 while (true) { val zug = if (dran == -1) { val z = menschZug() dran = 1 z } else { val z = computerZug(k) dran = -1 z } println("+---------+") println( "| ${if (brett[0] == -1) "x" else if (brett[0] == 0) " " else "o"} " + "${if (brett[1] == -1) "x" else if (brett[1] == 0) " " else "o"} " + "${if (brett[2] == -1) "x" else if (brett[2] == 0) " " else "o"} |" ) println( "| ${if (brett[3] == -1) "x" else if (brett[3] == 0) " " else "o"} " + "${if (brett[4] == -1) "x" else if (brett[4] == 0) " " else "o"} " + "${if (brett[5] == -1) "x" else if (brett[5] == 0) " " else "o"} |" ) println( "| ${if (brett[6] == -1) "x" else if (brett[6] == 0) " " else "o"} " + "${if (brett[7] == -1) "x" else if (brett[7] == 0) " " else "o"} " + "${if (brett[8] == -1) "x" else if (brett[8] == 0) " " else "o"} |" ) println("+---------+") if (gewonnen(brett, 1)) { println("Du hast verloren") return } if (gewonnen(brett, -1)) { println("Du hast gewonnen") return } runde += 1 if (runde == 9) { println("Es ist unentschieden") return } k.kinder.forEach { kind -> if (zug == kind.zug) { k = kind } } } }
0
Kotlin
0
0
2206e08785b879ad1c3c661f1e7d34a019bbfb71
4,549
AI-Collection
MIT License
src/main/kotlin/com/eric/leetcode/ArithmeticSlicesIISubsequence.kt
wanglikun7342
163,727,208
false
{"Kotlin": 172132, "Java": 27019}
package com.eric.leetcode import java.util.HashMap /** * 暴力解法,DFS */ //class ArithmeticSlicesIISubsequence { // // var num = 0 // // // fun numberOfArithmeticSlices(A: IntArray): Int { // num = 0 // for (index in A.indices) { // dfs(A, index, Long.MIN_VALUE, 1) // } // return num // } // // private fun dfs(A: IntArray, s: Int, gap: Long, arraySize: Int) { // if (gap == Long.MIN_VALUE) { // for (index in s + 1..A.lastIndex) { // // dfs(A, index, A[index].toLong() - A[s].toLong(), arraySize + 1) // } // } else { // for (index in s + 1..A.lastIndex) { // if (gap != A[index].toLong() - A[s].toLong()) { // continue // } else { // if (arraySize >= 2) { // num++ // } // } // dfs(A, index, gap, arraySize + 1) // } // } // } //} class ArithmeticSlicesIISubsequence { fun numberOfArithmeticSlices(A: IntArray): Int { var result = 0 val cnt = Array(A.size, { mutableMapOf<Int, Int>()}) for (i in A.indices) { for (j in 0 until i) { val delta = A[i].toLong() - A[j].toLong() if (delta < Integer.MIN_VALUE || delta > Integer.MAX_VALUE) { continue } val diff = delta.toInt() val sum = cnt[j].getOrDefault(diff, 0) val origin = cnt[i].getOrDefault(diff, 0) cnt[i].put(delta.toInt(), origin + sum + 1) result += sum } } return result } } fun main(args: Array<String>) { val input = intArrayOf(2,2,3,3,4,5) val arithmeticSlicesIISubsequence = ArithmeticSlicesIISubsequence() println(arithmeticSlicesIISubsequence.numberOfArithmeticSlices(input)) }
0
Kotlin
2
8
d7fb5ff5a0a64d9ce0a5ecaed34c0400e7c2c89c
1,965
Leetcode-Kotlin
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[66]加一.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。 // // 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 // // 你可以假设除了整数 0 之外,这个整数不会以零开头。 // // // // 示例 1: // // //输入:digits = [1,2,3] //输出:[1,2,4] //解释:输入数组表示数字 123。 // // // 示例 2: // // //输入:digits = [4,3,2,1] //输出:[4,3,2,2] //解释:输入数组表示数字 4321。 // // // 示例 3: // // //输入:digits = [0] //输出:[1] // // // // // 提示: // // // 1 <= digits.length <= 100 // 0 <= digits[i] <= 9 // // Related Topics 数组 数学 // 👍 722 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun plusOne(digits: IntArray): IntArray { //从后往前遍历 加一 时间复杂度 O(n) for (i in digits.size-1 downTo 0){ digits[i] ++ //查看是否有进位 digits[i] = digits[i]%10 if (digits[i] !=0){ //说明没有进位 返回原数组 return digits } } //原数组一直有进位 扩充原数组 val digits1 = IntArray(digits.size+1) digits1[0] = 1 return digits1 } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,433
MyLeetCode
Apache License 2.0
y2019/src/main/kotlin/adventofcode/y2019/Day13.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import adventofcode.language.intcode.IntCodeProgram fun main() = Day13.solve() object Day13 : AdventSolution(2019, 13, "Arcade") { override fun solvePartOne(input: String) = IntCodeProgram.fromData(input).run { execute() generateSequence { output() }.chunked(3).count { it[2] == 2L } } override fun solvePartTwo(input: String): Long { val arcadeProgram: IntCodeProgram = IntCodeProgram.fromData("2" + input.drop(1)) var score = 0L val blocks = mutableSetOf<Pair<Long, Long>>() var ballX = 0L var paddleX = 0L while (true) { arcadeProgram.execute() generateSequence { arcadeProgram.output() } .chunked(3) .forEach { (x, y, value) -> when { x < 0 -> score = value value == 0L -> blocks -= Pair(x, y) value == 2L -> blocks += Pair(x, y) value == 3L -> paddleX = x value == 4L -> ballX = x } } if (blocks.isEmpty()) return score val joystickCommand = ballX.compareTo(paddleX).toLong() arcadeProgram.input(joystickCommand) } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,399
advent-of-code
MIT License
src/main/kotlin/days/Day13.kt
hughjdavey
159,955,618
false
null
package days import util.Tracks import util.infiniteList class Day13 : Day(13) { override fun partOne(): Any { val initialState = Day13.initCarts(inputList) var iteration = 1 while (initialState.flatten().none { it.second != null && it.second!!.state == 'X' }) { Day13.doTick(initialState, iteration++) } return initialState.flatten().find { it.second != null && it.second!!.state == 'X' }?.second?.location ?: -1 } override fun partTwo(): Any { val initialState = Day13.initCarts(inputList) var iteration = 1 while (initialState.flatten().count { it.second != null } > 1) { Day13.doTick(initialState, iteration++, true) } return initialState.flatten().find { it.second != null }?.second?.location ?: -1 } data class Cart(var state: Char, var location: Pair<Int, Int>, val intersectionBehaviour: Iterator<Char> = infiniteList(listOf('l', 's', 'r')).iterator()) { private var moves = 0 fun canMove(iteration: Int) = moves < iteration // todo this function is messy - refactor // todo perhaps some kind of direction abstraction to replace all the charAt stuff fun move(tracks: Tracks, cleanup: Boolean = false) { val newLocation = when (this.state) { '>' -> location.copy(first = location.first + 1) '<' -> location.copy(first = location.first - 1) 'v' -> location.copy(second = location.second + 1) '^' -> location.copy(second = location.second - 1) else -> 0 to 0 } val charAt = tracks[newLocation.second][newLocation.first].first val newState = if (tracks[newLocation.second][newLocation.first].second != null) { 'X' } else if (isIntersection(charAt)) { val direction = intersectionBehaviour.next() when (direction) { 'l' -> if (state == '>') '^' else if (state == '<') 'v' else if (state == 'v') '>' else '<' 's' -> state 'r' -> if (state == '>') 'v' else if (state == '<') '^' else if (state == 'v') '<' else '>' else -> state } } else { when (charAt) { 'X' -> if (cleanup) '.' else 'X' '-', '|' -> state '\\' -> if (state == '>') 'v' else if (state == '<') '^' else if (state == 'v') '>' else '<' '/' -> if (state == '>') '^' else if (state == '<') 'v' else if (state == 'v') '<' else '>' else -> state } } tracks[location.second][location.first] = tracks[location.second][location.first].first to null tracks[newLocation.second][newLocation.first] = tracks[newLocation.second][newLocation.first].first to this if (cleanup && newState == 'X') { tracks[newLocation.second][newLocation.first] = tracks[newLocation.second][newLocation.first].first to null } state = newState location = newLocation moves++ } companion object { fun isCart(char: Char) = char == '>' || char == '<' || char == '^' || char == 'v' fun isIntersection(char: Char) = char == '+' } } companion object { fun initCarts(tracks: List<String>): Tracks { val grid = Array(tracks.size) { Array(tracks.sortedBy { it.length }.last().length) { '.' to null as Cart? } } for (y in 0 .. tracks.lastIndex) { for (x in 0 .. tracks[y].lastIndex) { grid[y][x] = if (Cart.isCart(tracks[y][x])) { val missing = if (tracks[y][x] == '>' || tracks[y][x] == '<') '-' else '|' missing to Cart(tracks[y][x], x to y) } else { tracks[y][x] to null } } } return grid } fun doTick(tracks: Tracks, iteration: Int, partTwo: Boolean = false): Tracks { for (y in 0 .. tracks.lastIndex) { for (x in 0 .. tracks[y].lastIndex) { val maybeCart = tracks[y][x].second if (maybeCart != null && maybeCart.canMove(iteration)) { maybeCart.move(tracks, partTwo) } } } return tracks } fun prettyPrint(tracks: Tracks) { for (y in 0 .. tracks.lastIndex) { for (x in 0 .. tracks[y].lastIndex) { if (tracks[y][x].second != null) print(tracks[y][x].second!!.state) else print(tracks[y][x].first) } println() } } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
4,978
aoc-2018
Creative Commons Zero v1.0 Universal
opta-router-solver/timefold/src/main/kotlin/io/github/pintowar/opta/router/solver/timefold/Extensions.kt
pintowar
120,393,481
false
{"Kotlin": 156826, "Vue": 72961, "TypeScript": 5560, "JavaScript": 463, "HTML": 388, "CSS": 58}
package io.github.pintowar.opta.router.solver.timefold import io.github.pintowar.opta.router.core.domain.models.LatLng import io.github.pintowar.opta.router.core.domain.models.Route import io.github.pintowar.opta.router.core.domain.models.VrpProblem import io.github.pintowar.opta.router.core.domain.models.VrpSolution import io.github.pintowar.opta.router.core.domain.models.matrix.Matrix import io.github.pintowar.opta.router.solver.timefold.domain.Customer import io.github.pintowar.opta.router.solver.timefold.domain.Depot import io.github.pintowar.opta.router.solver.timefold.domain.RoadLocation import io.github.pintowar.opta.router.solver.timefold.domain.Vehicle import io.github.pintowar.opta.router.solver.timefold.domain.VehicleRoutingSolution import java.math.BigDecimal import java.math.RoundingMode /** * Converts the DTO into the VRP Solution representation. (Used on the VRP Solver). * * @param dist distance calculator instance. * @return solution representation used by the solver. */ fun VrpProblem.toSolution(dist: Matrix): VehicleRoutingSolution { val roadLocations = this.locations.map { a -> val distances = locations.asSequence() .map { b -> b.id to dist.distance(a.id, b.id) } .filter { (bId, _) -> a.id != bId } .toMap() RoadLocation(a.id, a.name, a.lat, a.lng, distances) } val roadLocationIds = roadLocations.associateBy { it.id } val depotIds = this.depots.map { Depot(it.id, roadLocationIds.getValue(it.id)) }.associateBy { it.id } return VehicleRoutingSolution( id, name, roadLocations, depotIds.values.toList(), this.vehicles.map { Vehicle(it.id, it.capacity, depotIds.getValue(it.depot.id)) }, this.customers.map { Customer(it.id, it.demand, roadLocationIds.getValue(it.id)) } ) } fun VrpSolution.toSolverSolution(distances: Matrix): VehicleRoutingSolution { val solution = problem.toSolution(distances) val keys = solution.customerList.associateBy { it.id } routes.forEachIndexed { rIdx, route -> val customers = route.customerIds.mapNotNull { keys[it] } customers.forEachIndexed { idx, customer -> if (idx > 0) customer.previousCustomer = customers[idx - 1] if (idx < customers.size - 1) customer.nextCustomer = customers[idx + 1] customer.vehicle = solution.vehicleList[rIdx] } solution.vehicleList[rIdx].customers = customers } return solution } /** * Convert the solver VRP Solution representation into the DTO representation. * * @param graph graphwrapper to calculate the distance/time took to complete paths. * @return the DTO solution representation. */ fun VehicleRoutingSolution.toDTO(instance: VrpProblem, matrix: Matrix): VrpSolution { val vehicles = this.vehicleList val routes = vehicles.map { v -> val origin = v.depot.location.let { LatLng(it.latitude, it.longitude) } var dist = 0.0 var time = 0.0 var locations = emptyList<LatLng>() var customerIds = emptyList<Long>() var totalDemand = 0 var toOriginDist = 0.0 var toOriginTime = 0L var customer = v.customers.firstOrNull() while (customer != null) { locations += LatLng(customer.location.latitude, customer.location.longitude) customerIds += customer.id totalDemand += customer.demand val previousLocationId = customer.previousCustomer?.location?.id ?: v.depot.location.id dist += matrix.distance(previousLocationId, customer.location.id) time += matrix.time(previousLocationId, customer.location.id) toOriginDist = matrix.distance(customer.location.id, v.depot.location.id) toOriginTime = matrix.time(customer.location.id, v.depot.location.id) customer = customer.nextCustomer } dist += toOriginDist time += toOriginTime val rep = (listOf(origin) + locations + listOf(origin)) Route( BigDecimal(dist / 1000).setScale(2, RoundingMode.HALF_UP), BigDecimal(time / (60 * 1000)).setScale(2, RoundingMode.HALF_UP), totalDemand, rep, customerIds ) } return VrpSolution(instance, routes) }
1
Kotlin
2
28
4c49f6c5bbb16ad8a68eb15fae87c6ddc59aede0
4,329
opta-router
Apache License 2.0
src/main/kotlin/endredeak/aoc2023/Day11.kt
edeak
725,919,562
false
{"Kotlin": 26575}
package endredeak.aoc2023 import kotlin.math.abs fun main() { solve("Cosmic Expansion") { fun Pair<Long, Long>.dist(other: Pair<Long, Long>) = abs(other.first - first) + abs(other.second - second) fun coordinate(c: Int, adds: List<Int>, factor: Long) = c.toLong() + adds.count { c > it } * (factor - 1) val input = lines val columns = input[0].indices.filter { i -> input.map { s -> s[i] }.all { it == '.' } } val rows = input.indices.filter { i -> input[i].all { it == '.' } } fun calculate(factor: Long) = input.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == '#') { coordinate(x, columns, factor) to coordinate(y, rows, factor) } else null } } .let { it .flatMap { g -> it.map { n -> g to n } } .sumOf { (g, n) -> g.dist(n) } / 2 } part1(9693756) { calculate(2) } part2(717878258016) { calculate(1000000) } } }
0
Kotlin
0
0
92c684c42c8934e83ded7881da340222ff11e338
1,134
AdventOfCode2023
Do What The F*ck You Want To Public License
src/week3/CourseSchedule.kt
anesabml
268,056,512
false
null
package week3 import java.util.* import kotlin.system.measureNanoTime class CourseSchedule { /** BFS */ fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean { val graph = Array<MutableList<Int>>(numCourses) { mutableListOf() } val inDegree = IntArray(numCourses) for (pre in prerequisites) { inDegree[pre[1]]++ graph[pre[0]].add(pre[1]) } val queue: Queue<Int> = LinkedList<Int>() for (i in inDegree.indices) { if (inDegree[i] == 0) { queue.add(i) } } var count = 0 while (queue.isNotEmpty()) { val course = queue.poll() count++ for (pointer in graph[course]) { inDegree[pointer]-- if (inDegree[pointer] == 0) { queue.add(pointer) } } } return count == numCourses } /** DFS */ fun canFinish2(numCourses: Int, prerequisites: Array<IntArray>): Boolean { val graph = Array<MutableList<Int>>(numCourses) { mutableListOf() } for (pre in prerequisites) { graph[pre[0]].add(pre[1]) } val visited = BooleanArray(numCourses) val dp = BooleanArray(numCourses) for (i in 0 until numCourses) { if (!dfs(i, graph, visited, dp)) return false } return true } private fun dfs(course: Int, graph: Array<MutableList<Int>>, visited: BooleanArray, dp: BooleanArray): Boolean { if (visited[course]) { return dp[course] } visited[course] = true for (i in graph[course]) { if (!dfs(i, graph, visited, dp)) { dp[course] = false return false } } dp[course] = true return true } } fun main() { val numCourses = 2 val prerequisites = arrayOf(intArrayOf(1, 0)) val courseSchedule = CourseSchedule() val firstSolutionTime = measureNanoTime { println(courseSchedule.canFinish(numCourses, prerequisites)) } val secondSolutionTime = measureNanoTime { println(courseSchedule.canFinish2(numCourses, prerequisites)) } println("BFS Solution execution time: $firstSolutionTime") println("DFS Solution execution time: $secondSolutionTime") }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
2,380
leetCode
Apache License 2.0
day10/kotlin/RJPlog/day2110_1_2.kts
razziel89
438,180,535
true
{"Rust": 368326, "Python": 219109, "Go": 200337, "Kotlin": 80185, "Groovy": 67858, "JavaScript": 45619, "TypeScript": 43504, "CSS": 35030, "Shell": 18611, "C": 5260, "Ruby": 2359, "Dockerfile": 2285, "HTML": 227, "C++": 153}
import java.io.File //fun main(args: Array<String>) { var solution1: Int var solution2: Long var points = mutableMapOf<Int, Int>() points.put(3, 0) points.put(57, 0) points.put(1197, 0) points.put(25137, 0) var correctInstructions = mutableListOf<String>() var scoresSolution2 = mutableListOf<Long>() // tag::firstpart[] File("day2110_puzzle_input.txt").forEachLine { var instruction = it var searchEnd: Boolean = false var pattern0 = arrayOf("()", "[]", "{}", "<>") var pattern1 = arrayOf("[)", "{)", "<)") var pattern2 = arrayOf("(]", "{]", "<]") var pattern3 = arrayOf("(}", "[}", "<}") var pattern4 = arrayOf("(>", "[>", "{>") // remove iterative all legal pairs of chunks in string while (!searchEnd) { if (pattern0.any { instruction.contains(it) }) { //if (instruction.contains("()") || instruction.contains("<>") || instruction.contains("[]") || instruction.contains("{}")) { instruction = instruction.replace("()", "") instruction = instruction.replace("[]", "") instruction = instruction.replace("{}", "") instruction = instruction.replace("<>", "") } else { searchEnd = true } } // determine if there is a wrong closing character in remaining string if (pattern1.any { instruction.contains(it) }) { points.put(3, points.getValue(3) + 1) } else if (pattern2.any { instruction.contains(it) }) { points.put(57, points.getValue(57) + 1) } else if (pattern3.any { instruction.contains(it) }) { points.put(1197, points.getValue(1197) + 1) } else if (pattern4.any { instruction.contains(it) }) { points.put(25137, points.getValue(25137) + 1) } else { // add all correct lines to a list, revert them already for later calculation of score for part2 correctInstructions.add(instruction.reversed()) } } solution1 = 3*points.getValue(3) + 57*points.getValue(57) + 1197*points.getValue(1197) + 25137*points.getValue(25137) // end::firstpart[] // tag::secondpart[] // evaluate total score for all incomplete but not corrupted lines correctInstructions.forEach { var totalScore: Long = 0 it.forEach { if (it.equals('(')) { totalScore = totalScore * 5 + 1 } else if (it.equals('[')) { totalScore = totalScore * 5 + 2 } else if (it.equals('{')) { totalScore = totalScore * 5 + 3 } else if (it.equals('<')) { totalScore = totalScore * 5 + 4 } } scoresSolution2.add(totalScore) } scoresSolution2.sort() solution2 = scoresSolution2[scoresSolution2.size / 2] // end::secondpart[] // tag::output[] // print solution for part 1 println("******************************") println("--- Day 10: Syntax Scoring ---") println("******************************") println("Solution for part1") println(" $solution1 is the total syntax error score for those errors") println() // print solution for part 2 println("*********************************") println("Solution for part2") println(" $solution2 is the middle score") println() // end::output[] //}
1
Rust
0
0
91a801b3c812cc3d37d6088a2544227cf158d114
3,003
aoc-2021
MIT License
src/Day02.kt
theofarris27
574,591,163
false
null
fun main() { fun part1(input: List<String>): Int { return input.size } fun part2(input: List<String>): Int { var sum = 0; var win = 6 var loss = 0 var tie = 3 var x = 1 var y = 2 var z = 3 for (lines in input) { if (lines.contains('A')) { if (lines.contains('X')) { sum += z sum += loss } else if (lines.contains('Y')) { sum += x sum += tie } else { sum += y sum += win } } else if (lines.contains('B')) { if (lines.contains('X')) { sum += x sum += loss } else if (lines.contains('Y')) { sum += y sum += tie } else { sum += z sum += win } } else { if (lines.contains('X')) { sum += y sum += loss } else if (lines.contains('Y')) { sum += z sum += tie } else { sum += x sum += win } } } return sum } val testInput = readInput("Day01_test") val input = readInput("Moves") println(part2(testInput)) check(part2(testInput) == 24000) println(part2(input)) }
0
Kotlin
0
0
cf77115471a7f1caeedf13ae7a5cdcbdcec3eab7
1,754
AdventOfCode
Apache License 2.0
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day04.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day04 : Day<Int> { companion object { private val knownProperties = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid") } private val input: List<PassportCandidate> = readDayInput().parse() data class PassportCandidate(val properties: Map<String, String>) private fun String.parse(): List<PassportCandidate> { return split("\n\n") .map { entry -> PassportCandidate( properties = entry.split(' ', '\n') .associate { prop -> val components = prop.split(':') components[0] to components[1] } ) } } private val PassportCandidate.checkPropertiesPresent: Boolean get() { val mandatoryPassportProperties = knownProperties - "cid" val missingAnyMandatoryProperties = mandatoryPassportProperties.any { prop -> prop !in properties.keys } val hasAnyUnknownProperties = properties.any { prop -> prop.key !in knownProperties } return !missingAnyMandatoryProperties && !hasAnyUnknownProperties } private val PassportCandidate.checkPropertiesValid: Boolean get() = properties.all { prop -> when (prop.key) { "byr" -> prop.value.toInt() in 1920..2002 "iyr" -> prop.value.toInt() in 2010..2020 "eyr" -> prop.value.toInt() in 2020..2030 "hgt" -> { val r = Regex("^([0-9]+)(in|cm)$") r.find(prop.value)?.groupValues?.let { groups -> val height = groups[1].toInt() val unit = groups[2] when (unit) { "in" -> height in 59..76 "cm" -> height in 150..193 else -> false } } ?: false } "hcl" -> prop.value.matches(Regex("^#[0-9a-f]{6}$")) "ecl" -> prop.value in listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") "pid" -> prop.value.length == 9 && prop.value.toIntOrNull() != null else -> true } } override fun step1(): Int { return input.count { candidate -> candidate.checkPropertiesPresent } } override fun step2(): Int { return input.count { candidate -> candidate.checkPropertiesPresent && candidate.checkPropertiesValid } } override val expectedStep1: Int = 260 override val expectedStep2: Int = 153 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
2,882
adventofcode
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/RotateList.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 61. Rotate List * @see <a href="https://leetcode.com/problems/rotate-list">Source</a> */ fun interface RotateList { operator fun invoke(head: ListNode?, k: Int): ListNode? } /** * Time Limit Exceeded */ class RotateListBruteForce : RotateList { override operator fun invoke(head: ListNode?, k: Int): ListNode? { var node = head if (node?.next == null) return node for (i in 0 until k) { var temp: ListNode? = node while (temp?.next?.next != null) temp = temp.next val end: ListNode? = temp?.next temp?.next = null end?.next = node node = end } return node } } class RotateListOptimized : RotateList { override operator fun invoke(head: ListNode?, k: Int): ListNode? { var node = head if (node?.next == null || k == 0) { return node } var curr = node var len = 1 while (curr?.next != null) { len++ curr = curr.next } curr?.next = node val ll = len - k % len for (i in 0 until ll) { // 3 times because curr. next is at head but curr is still at end of the linkedlist curr = curr?.next } node = curr?.next curr?.next = null return node } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,988
kotlab
Apache License 2.0
src/day06/Day06.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day06 import readInput fun main() { fun part1(input: String): Int { for (index in 0 until input.length - 4) { val lastsSet = setOf<Char>(input[index], input[index + 1], input[index + 2], input[index + 3]) if (lastsSet.size == 4) { return index + 4 } } return input.length } fun part2(input: String): Int { for (index in 0 until input.length - 4) { val lastsSet = mutableSetOf<Char>() for (i in 0 until 14) { lastsSet.add(input[index + i]) } if (lastsSet.size == 14) { return index + 14 } } return input.length } fun preprocess(input: List<String>): String = input[0] // test if implementation meets criteria from the description, like: val testInput = readInput(6, true) check(part1(preprocess(testInput)) == 10) val input = readInput(6) println(part1(preprocess(input))) check(part2(preprocess(testInput)) == 29) println(part2(preprocess(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
1,110
advent-of-code-2022
Apache License 2.0
src/com/ssynhtn/medium/NQueens.kt
ssynhtn
295,075,844
false
{"Java": 639777, "Kotlin": 34064}
package com.ssynhtn.medium class NQueens { fun solveNQueens2(n: Int): Int { val table = Array<CharArray>(n, {i -> CharArray(n)}) for (i in 0 until n) { for (j in 0 until n) { table[i][j] = '.' } } return putQueens(table, 0) } private fun putQueens(table: Array<CharArray>, fixedRows: Int): Int { if (fixedRows == table.size) { return 1 } var count = 0 for (col in 0 until table.size) { if (checkHasConflictWithPrev(table, fixedRows, col)) continue table[fixedRows][col] = 'Q' count += putQueens(table, fixedRows + 1) table[fixedRows][col] = '.' } return count } fun solveNQueens(n: Int): List<List<String>> { val table = Array<CharArray>(n, {i -> CharArray(n)}) for (i in 0 until n) { for (j in 0 until n) { table[i][j] = '.' } } val collection = mutableListOf<List<String>>() putQueens(table, 0, collection) return collection } private fun putQueens(table: Array<CharArray>, fixedRows: Int, collection: MutableList<List<String>>) { if (fixedRows == table.size) { collection.add(table.map { chs -> String(chs) }) return } for (col in 0 until table.size) { if (checkHasConflictWithPrev(table, fixedRows, col)) continue table[fixedRows][col] = 'Q' putQueens(table, fixedRows + 1, collection) table[fixedRows][col] = '.' } } private fun checkHasConflictWithPrev(table: Array<CharArray>, row: Int, col: Int): Boolean { for (i in 0 until row) { var j = col - row + i if (j >= 0 && j < table.size) { if (table[i][j] == 'Q') { return true } } j = row + col - i if (j >= 0 && j < table.size) { if (table[i][j] == 'Q') { return true } } j = col if (j >= 0 && j < table.size) { if (table[i][j] == 'Q') { return true } } } return false } } fun main(args: Array<String>) { println(NQueens().solveNQueens2(4)) // var queenPlacements = NQueens().solveNQueens(4) // for (table in queenPlacements) { // println(table.joinToString("\n")) // println() // } }
0
Java
0
0
511f65845097782127bae825b07a51fe9921c561
2,585
leetcode
Apache License 2.0
src/2023/Day1_2.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File val numbers = mutableListOf<Int>() val digitsAsStrings = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9", ) fun String.containsAny(map: Map<String, String>) = map.keys.any {contains(it)} File("input/2023/day1").apply { forEachLine { line -> var digits = "" line.forEachIndexed { i, c -> var subString = "$c" var nextIndex = i if (!c.isDigit()) { while (!digitsAsStrings.containsKey(subString) && nextIndex + 1 < line.length) { nextIndex++ subString = "$subString${line[nextIndex]}" } if (digitsAsStrings.containsKey(subString)) digits = "$digits${digitsAsStrings[subString]}" } else digits = "$digits$subString" } numbers.add("${digits.first()}${digits.last()}".toInt()) } } println(numbers.sumOf { it })
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
1,033
adventofcode
MIT License
src/test/kotlin/com/github/mpe85/grampa/grammar/SequenceRuleTests.kt
mpe85
138,511,038
false
{"Kotlin": 269689, "Java": 1073}
package com.github.mpe85.grampa.grammar import com.github.mpe85.grampa.legalCodePoints import com.github.mpe85.grampa.parser.Parser import com.github.mpe85.grampa.rule.Rule import com.github.mpe85.grampa.rule.StringRule import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import io.kotest.property.Arb import io.kotest.property.arbitrary.int import io.kotest.property.arbitrary.list import io.kotest.property.arbitrary.string import io.kotest.property.checkAll class SequenceRuleTests : StringSpec({ fun grammars(rules: List<Rule<Unit>>) = listOf( object : AbstractGrammar<Unit>() { override fun start() = sequence(*rules.toTypedArray()) }, object : AbstractGrammar<Unit>() { override fun start() = sequence(rules) }, object : AbstractGrammar<Unit>() { override fun start() = rules.reduce { acc, rule -> acc and rule } }, object : AbstractGrammar<Unit>() { override fun start() = rules.reduce { acc, rule -> acc + rule } }, ) "Sequence rule matches correct sequence" { checkAll(Arb.list(Arb.string(0..10, legalCodePoints()), 2..10)) { strings -> grammars(strings.map { StringRule(it) }).forEach { grammar -> val joined = strings.reduce(String::plus) Parser(grammar).run(joined).apply { matched shouldBe true matchedEntireInput shouldBe true matchedInput shouldBe joined restOfInput shouldBe "" } } } } "Empty Sequence rule matches any input" { checkAll(Arb.string(0..10, legalCodePoints())) { str -> Parser(object : AbstractGrammar<Unit>() { override fun start() = sequence() }).run(str).apply { matched shouldBe true matchedEntireInput shouldBe str.isEmpty() matchedInput shouldBe "" restOfInput shouldBe str } } } "Sequence rule matches sequence of stack actions" { checkAll(Arb.int(), Arb.int(), Arb.string(1..10, legalCodePoints())) { i1, i2, str -> Parser(object : AbstractGrammar<Int>() { override fun start() = sequence( push(i1), push { peek(it) + i2 }, sequence(push { pop(1, it) + peek(it) }), optional( action { it.stack.push(0) false }, ), ) }).run(str).apply { matched shouldBe true matchedEntireInput shouldBe false matchedInput shouldBe "" restOfInput shouldBe str stackTop shouldBe 2 * i1 + i2 stack.size shouldBe 2 stack.peek() shouldBe 2 * i1 + i2 stack.peek(1) shouldBe i1 + i2 } } } })
0
Kotlin
1
11
b3638090a700d2f6213b0f4e10d525c0e4444d94
3,095
grampa
MIT License
src/Day04.kt
Arclights
574,085,358
false
{"Kotlin": 11490}
fun main() { fun parseInput(input: List<String>) = input .map { line -> line.split(",") .map { elf -> elf.split("-") .let { ids -> ids[0].toInt()..ids[1].toInt() } .toSet() } .let { it[0] to it[1] } } fun part1(input: List<String>) = parseInput(input) .count { elves -> val combined = elves.first.intersect(elves.second) combined.size == elves.first.size || combined.size == elves.second.size } fun part2(input: List<String>) = parseInput(input) .count { elves -> elves.first.intersect(elves.second).isNotEmpty() } val testInput = readInput("Day04_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
121a81ba82ba0d921bd1b689241ffa8727bc806e
915
advent_of_code_2022
Apache License 2.0
aoc2016/src/main/kotlin/io/github/ajoz/aoc16/Day4.kt
ajoz
116,427,939
false
null
package io.github.ajoz.aoc16 import java.io.File /** * --- Day 4: Security Through Obscurity --- * * Finally, you come across an information kiosk with a list of rooms. Of * course, the list is encrypted and full of decoy data, but the instructions to * decode the list are barely hidden nearby. Better remove the decoy data first. * * Each room consists of an encrypted name (lowercase letters separated by * dashes) followed by a dash, a sector ID, and a checksum in square brackets. * * A room is real (not a decoy) if the checksum is the five most common letters * in the encrypted name, in order, with ties broken by alphabetization. * * For example: * * 1) aaaaa-bbb-z-y-x-123[abxyz] is a real room because the most common letters * are a (5), b (3), and then a tie between x, y, and z, which are listed * alphabetically. * * 2) a-b-c-d-e-f-g-h-987[abcde] is a real room because although the letters are * all tied (1 of each), the first five are listed alphabetically. * * 3) not-a-real-room-404[oarel] is a real room. * 4) totally-real-room-200[decoy] is not. * * Of the real rooms from the list above, the sum of their sector IDs is 1514. * * What is the sum of the sector IDs of the real rooms? */ data class Room(val name: String, val id: Int, val checksum: String) fun Room.isValidRoom(): Boolean { return checksum == getChecksum(name) } fun getChecksum(roomName: String) = roomName.groupingBy { it } .eachCount() .filterKeys { it != '-' } .toList() .sortedWith(Comparator { entry1, entry2 -> val diff = entry2.second - entry1.second if (diff != 0) diff else entry1.first.compareTo(entry2.first) }) .map { entry -> entry.first } .take(5) .joinToString(separator = "") fun MatchGroupCollection.toRoom(): Room? { val roomName = this[1]?.value val roomId = this[2]?.value?.toInt() val roomCheckSum = this[3]?.value return if (roomName != null && roomId != null && roomCheckSum != null) { Room(roomName, roomId, roomCheckSum) } else null } fun getValidRooms(rooms: List<String>): List<Room> { val regex = """([a-z\-]+)-([0-9]+)\[([a-z]+)]""".toRegex() return rooms .mapNotNull { regex.matchEntire(it)?.groups } .filter { it.size == 4 } .mapNotNull { it.toRoom() } .filter { it.isValidRoom() } } fun getPart1SumOfSectorIds(rooms: List<String>): Int { return getValidRooms(rooms) .map { it.id } .sum() } /** * --- Part Two --- * * With all the decoy data out of the way, it's time to decrypt this list and * get moving. The room names are encrypted by a state-of-the-art shift cipher, * which is nearly unbreakable without the right software. However, the * information kiosk designers at Easter Bunny HQ were not expecting to deal * with a master cryptographer like yourself. To decrypt a room name, rotate * each letter forward through the alphabet a number of times equal to the * room's sector ID. A becomes B, B becomes C, Z becomes A, and so on. Dashes * become spaces. For example, the real name for qzmt-zixmtkozy-ivhz-343 is * very encrypted name. * * What is the sector ID of the room where North Pole objects are stored? */ const val NUM_OF_LETTERS = 26 const val ASCII_A_CODE = 65 fun rotN(string: String, n: Int) = string .map { if (it.isLetter()) { (it.toAlphabet() + n).rem(NUM_OF_LETTERS).fromAlphabet() } else it } .joinToString("") fun Char.toAlphabet() = this.toUpperCase().toInt() - ASCII_A_CODE fun Int.fromAlphabet() = (this + ASCII_A_CODE).toChar() val inputDay4 = File("src/main/resources/day4-puzzle-input") fun main(args: Array<String>) { println(getPart1SumOfSectorIds(inputDay4.readLines())) val rooms = getValidRooms(inputDay4.readLines()) .filter { rotN(it.name, it.id.rem(NUM_OF_LETTERS)).contains("NORTH") } .map { it.id } .first() println(rooms) }
0
Kotlin
0
0
49ba07dd5fbc2949ed3c3ff245d6f8cd7af5bebe
4,169
challenges-kotlin
Apache License 2.0
src/Day21.kt
frozbiz
573,457,870
false
{"Kotlin": 124645}
class SimpleTree { interface Node { fun value(): Long fun value(target: Long): Long val human: Boolean } class ValueNode(val storedValue: Long): Node { override fun value() = storedValue override val human: Boolean get() = false override fun value(target: Long): Long { throw IllegalStateException("Called set on a value node") } } abstract class CompoundNode( val firstLabel: String, val secondLabel: String, val tree: SimpleTree ): Node { val first get() = tree[firstLabel] val second get() = tree[secondLabel] override val human: Boolean get() = first.human || second.human } class MathNode( firstLabel: String, secondLabel: String, val operation: (Long, Long) -> Long, val reverseFirstOperation: (Long, Long) -> Long, val reverseSecondOperation: (Long, Long) -> Long, tree: SimpleTree ): CompoundNode(firstLabel, secondLabel, tree) { override fun value() = operation(first.value(), second.value()) override fun value(target: Long): Long { if (first.human == second.human) throw IllegalStateException() return if (first.human) first.value(reverseFirstOperation(target, second.value())) else second.value(reverseSecondOperation(first.value(), target)) } } class RootNode( firstLabel: String, secondLabel: String, tree: SimpleTree ): CompoundNode(firstLabel, secondLabel, tree) { override fun value(): Long { if (first.human) return first.value(second.value()) if (second.human) return first.value(second.value()) throw IllegalStateException() } override fun value(target: Long): Long { TODO("Not yet implemented") } } class HumanNode: Node { override val human: Boolean get() = true override fun value(target: Long): Long { return target } override fun value(): Long { TODO("Not yet implemented") } } operator fun get(ix: String): Node { return nodeMap[ix] ?: throw IndexOutOfBoundsException(ix) } val nodeMap = mutableMapOf<String, Node>() fun load(input: List<String>, backSolve: Boolean = false) { for (line in input) { val (key, nodeDesc) = line.split(':') nodeMap[key] = if (backSolve) { when (key) { "root" -> { val (_, first, second) = "(\\w+) . (\\w+)".toRegex().find(nodeDesc)?.groupValues ?: throw IllegalArgumentException() RootNode(first, second, this) } "humn" -> HumanNode() else -> nodeFrom(nodeDesc) } } else { nodeFrom(nodeDesc) } } } private fun List<String>.toMathNode(): Node { val operations: List<(Long, Long) -> Long> = when(this[2]) { "+" -> listOf(Long::plus, Long::minus, { known, target -> target - known }) "-" -> listOf(Long::minus, Long::plus, Long::minus) "*" -> listOf(Long::times, Long::div, { known, target -> target / known }) "/" -> listOf(Long::div, Long::times, Long::div) else -> throw IllegalArgumentException(this[2]) } return MathNode(this[1], this[3], operations[0], operations[1], operations[2], this@SimpleTree) } private fun Long.toValueNode(): ValueNode { return ValueNode(this) } private fun nodeFrom(nodeDesc: String): Node { return "(\\d+)".toRegex().find(nodeDesc)?.groupValues?.get(1)?.toLong()?.toValueNode() ?: "(\\w+) (.) (\\w+)".toRegex().find(nodeDesc)?.groupValues?.toMathNode() ?: throw IllegalArgumentException(nodeDesc) } } fun main() { fun part1(input: List<String>): Long { val tree = SimpleTree() tree.load(input) return tree["root"].value() } fun part2(input: List<String>): Long { val tree = SimpleTree() tree.load(input, true) return tree["root"].value() } // test if implementation meets criteria from the description, like: val testInput = listOf( "root: pppw + sjmn\n", "dbpl: 5\n", "cczh: sllz + lgvd\n", "zczc: 2\n", "ptdq: humn - dvpt\n", "dvpt: 3\n", "lfqf: 4\n", "humn: 5\n", "ljgn: 2\n", "sjmn: drzm * dbpl\n", "sllz: 4\n", "pppw: cczh / lfqf\n", "lgvd: ljgn * ptdq\n", "drzm: hmdt - zczc\n", "hmdt: 32\n" ) check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388
4,971
2022-aoc-kotlin
Apache License 2.0
2020/11/week3/minhyungPark/algorithm/LeetCode1647.kt
Road-of-CODEr
270,008,701
false
{"Java": 199573, "C++": 42297, "JavaScript": 29489, "Kotlin": 28801, "Python": 20313, "HTML": 7981, "Shell": 7160}
/** * Leetcode 1647. Minimum Deletions to Make Character Frequencies Unique * https://leetcode.com/contest/weekly-contest-214/problems/minimum-deletions-to-make-character-frequencies-unique/ */ class LeetCode1647 { fun minDeletions(s: String): Int { val frequency = IntArray(26) s.forEach { c -> frequency[c-'a']++ } println(frequency.contentToString()) val nums = IntArray(frequency.max()!! + 1) frequency.filter { it!=0 }.forEach { nums[it]++ } var result = 0 for (i in nums.size-1 downTo 1) { if (nums[i] >= 2) { result+= nums[i] - 1 nums[i-1] += nums[i] -1 } } return result } }
3
Java
11
36
1c603bc40359aeb674da9956129887e6f7c8c30a
725
stupid-week-2020
MIT License
src/day01/Day01.kt
taer
573,051,280
false
{"Kotlin": 26121}
package day01 import readInput import split fun main() { fun sumElves(input: List<String>): List<Int> { return input.asSequence() .split { it.isBlank() } .map { it.sumOf { a -> a.toInt()} } .toList() } fun part1(input: List<String>): Int { val elves = sumElves(input) return elves.max() } fun part2(input: List<String>): Int { val elves = sumElves(input) return elves.sortedDescending().take(3).sum() } val testInput = readInput("day01", true) check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("day01",) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1bd19df8949d4a56b881af28af21a2b35d800b22
718
aoc2022
Apache License 2.0
src/questions/WordBreak.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import kotlin.collections.HashSet /** * Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a * space-separated sequence of one or more dictionary words. * Note that the same word in the dictionary may be reused multiple times in the segmentation. * * [Source](https://leetcode.com/problems/word-break/) – [Solution](https://leetcode.com/problems/word-break/discuss/43790/Java-implementation-using-DP-in-two-ways) */ @UseCommentAsDocumentation private fun wordBreak(s: String, wordDict: List<String>): Boolean { val dict = HashSet<String>(wordDict) // https://leetcode.com/problems/word-break/discuss/43790/Java-implementation-using-DP-in-two-ways/43003 // canBeBuilt[i] stands for whether subarray(0, i) can be segmented into words from the dictionary. // So canBeBuilt[0] means whether subarray(0, 0) (which is an empty string) can be segmented, and of course the answer is yes. val canBeBuilt = Array<Boolean?>(s.length + 1) { false } // The default value for boolean array is false. Therefore, we need to set canBeBuilt[0] to be true. canBeBuilt[0] = true for (i in 1..s.length) { for (j in 0 until i) { if (canBeBuilt[j] == true && dict.contains(s.substring(j, i))) { canBeBuilt[i] = true break } } } return canBeBuilt[s.length]!! } fun main() { wordBreak(s = "catsandog", wordDict = listOf("cats", "dog", "sand", "and", "cat")) shouldBe false wordBreak(s = "leetcode", wordDict = listOf("leet", "code")) shouldBe true wordBreak(s = "aaaaaaa", wordDict = listOf("aaaa", "aaa")) shouldBe true wordBreak(s = "applepenapple", wordDict = listOf("apple", "pen")) shouldBe true }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,841
algorithms
MIT License
Day6/memory_banks.kt
fpeterek
155,423,059
false
null
// Solves both first and second problem fun redistribute(banks: MutableList<Int>) { val max = banks.max()!! var index = banks.indexOf(max) var blocksToAlloc = max banks[index] = 0 while (blocksToAlloc > 0) { ++index if (index >= banks.size) { index = 0 } ++banks[index] --blocksToAlloc } } fun main(args: Array<String>) { val input = "5 1 10 0 1 7 13 14 3 12 8 10 7 12 0 6" val banks = input.split(" ").map { it.toInt() }.toMutableList() val occuredCombinations = mutableListOf<String>() var combination: String while (true) { redistribute(banks) combination = banks.fold("") { acc: String, i: Int -> "$acc$i " } if (occuredCombinations.find {it == combination} != null) { break } occuredCombinations.add(combination) } val loopSize = (occuredCombinations.size) - occuredCombinations.indexOf(combination) println("Number of combinations: ${occuredCombinations.size + 1}") println("Loop size: $loopSize") }
0
Kotlin
0
0
d5bdf89e106cd84bb4ad997363a887c02cb6664b
1,091
Advent-Of-Code
MIT License
numth/src/main/kotlin/net/fwitz/math/numth/numbers/Divisibility.kt
txshtkckr
410,419,365
false
{"Kotlin": 558762}
package net.fwitz.math.numth.numbers import kotlin.math.absoluteValue import kotlin.math.sqrt object Divisibility { fun factor(n: Int): List<Int> { when (n) { -3 -> return listOf(-1, 1, 3) -2 -> return listOf(-1, 1, 2) -1 -> return listOf(-1, 1) 0 -> return listOf(0) 1 -> return listOf(1) 2 -> return listOf(1, 2) 3 -> return listOf(1, 3) } val factors = ArrayList<Int>() var x = n if (x < 0) { factors.add(-1) x = -x } factors.add(1) val last = sqrt(x.toDouble()).toInt() Primes.upTo(last).forEach { prime -> while (x % prime == 0) { factors.add(prime) x /= prime } } return factors } fun gcd(vararg ints: Int) = gcd(ints.asList()) fun gcd(ints: List<Int>): Int { val values = ints.asSequence().filter { it != 0 }.toMutableList() when (values.size) { 0 -> return 0 1 -> return values[0] } var gcd = -1 for (i in values.indices) { when { values[i] > 0 -> gcd = 1 else -> values[i] = -values[i] } } val last = values.minOf { it } if (last < 2) return gcd Primes.upTo(last).forEach { prime -> while (values.all { it % prime == 0 }) { values.indices.forEach { values[it] /= prime } gcd *= prime } } return gcd } @JvmStatic fun main(args: Array<String>) { println(gcd(54, 162)) println(gcd(3, 0, -54, 162)) println(gcd(-3, 0, -54, -162)) println(gcd(210, 455)) } }
0
Kotlin
1
0
c6ee97ab98115e044a46490ef3a26c51752ae6d6
1,812
fractal
Apache License 2.0
kotlin/0752-open-the-lock.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun openLock(deadends: Array<String>, target: String): Int { val deadEndSet = hashSetOf<String>() deadends.forEach { deadEndSet.add(it) } if (target in deadEndSet || "0000" in deadEndSet) return -1 // [ (String,Level) ] val queue: Queue<Pair<String, Int>> = LinkedList<Pair<String, Int>>().apply { add(Pair("0000", 0)) } val visitedCombinations = hashSetOf<String>() while (queue.isNotEmpty()) { val (currentCombination, levelOfCurrentCombination) = queue.remove() if (currentCombination == target) return levelOfCurrentCombination // increments for (i in currentCombination.indices) { val digitAtIndex = Character.digit(currentCombination[i], 10) val incrementedValue = Character.forDigit((digitAtIndex + 1) % 10, 10) val newCombination = currentCombination.replaceCharAt(i, incrementedValue) if (newCombination in visitedCombinations || newCombination in deadEndSet) continue visitedCombinations.add(newCombination) queue.add(Pair(newCombination, levelOfCurrentCombination + 1)) } // decrements for (i in currentCombination.indices) { val valueAtIndex = Character.digit(currentCombination[i], 10) val decrementedValue = Character.forDigit( (valueAtIndex - 1).takeIf { valueAtIndex - 1 in 0..9 } ?: 9, 10) val newCombination = currentCombination.replaceCharAt(i, decrementedValue) if (newCombination in visitedCombinations || newCombination in deadEndSet) continue visitedCombinations.add(newCombination) queue.add(Pair(newCombination, levelOfCurrentCombination + 1)) } } return -1 } private fun String.replaceCharAt( index: Int, newChar: Char ): String = when (index) { 0 -> newChar + substring(1..this.lastIndex) lastIndex -> substring(0 until this.lastIndex) + newChar else -> substring(0 until index) + newChar + substring(index + 1..this.lastIndex) } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
2,238
leetcode
MIT License
src/main/kotlin/info/dgjones/barnable/grammar/Suffix.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.grammar import info.dgjones.barnable.concept.Concept import info.dgjones.barnable.concept.Slot import info.dgjones.barnable.domain.general.* import info.dgjones.barnable.parser.* /* Suffix Daemons */ fun buildSuffixDemon(suffix: String, wordContext: WordContext): Demon? { return when (suffix) { "ed" -> SuffixEdDemon(wordContext) "s" -> PluralDemon(wordContext) "ing" -> SuffixIngDemon(wordContext) else -> null } } class SuffixEdDemon(wordContext: WordContext): Demon(wordContext) { override fun run() { val def = wordContext.def() if (def != null && def.value(TimeFields.TIME) == null) { def.value(TimeFields.TIME.fieldName, Concept(TimeConcepts.Past.name)) active = false } } override fun description(): String { return "Suffix ED marks word sense as in the past" } } class SuffixIngDemon(wordContext: WordContext): Demon(wordContext) { override fun run() { val def = wordContext.def() // Progressive Detection val previousWord = wordContext.previousWord() if (previousWord != null && formsOfBe.contains(previousWord.toLowerCase())) { def?.let { it.with(Slot(GrammarFields.Aspect, Concept(Aspect.Progressive.name)) ) active = false } } else { active = false } } override fun description(): String { return "Suffix ING mark words sense as progressive when following be" } } // FIXME find a more useful location fo formsOfBe private val formsOfBe = setOf("be", "am", "are", "is", "was", "were", "being", "been")
1
Kotlin
0
0
b5b7453e2fe0b2ae7b21533db1b2b437b294c63f
2,306
barnable
Apache License 2.0
kotlin/594.Longest Harmonious Subsequence(最长和谐子序列).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>We define a harmonious array is an array where the difference between its maximum value and its minimum value is <b>exactly</b> 1.</p> <p>Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible <a href="https://en.wikipedia.org/wiki/Subsequence">subsequences</a>.</p> <p><b>Example 1:</b><br /> <pre> <b>Input:</b> [1,3,2,2,5,2,3,7] <b>Output:</b> 5 <b>Explanation:</b> The longest harmonious subsequence is [3,2,2,2,3]. </pre> </p> <p><b>Note:</b> The length of the input array will not exceed 20,000. </p> <p>和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。</p> <p>现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。</p> <p><strong>示例 1:</strong></p> <pre> <strong>输入:</strong> [1,3,2,2,5,2,3,7] <strong>输出:</strong> 5 <strong>原因:</strong> 最长的和谐数组是:[3,2,2,2,3]. </pre> <p><strong>说明:</strong> 输入的数组长度最大不超过20,000.</p> <p>和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。</p> <p>现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。</p> <p><strong>示例 1:</strong></p> <pre> <strong>输入:</strong> [1,3,2,2,5,2,3,7] <strong>输出:</strong> 5 <strong>原因:</strong> 最长的和谐数组是:[3,2,2,2,3]. </pre> <p><strong>说明:</strong> 输入的数组长度最大不超过20,000.</p> **/ class Solution { fun findLHS(nums: IntArray): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
1,631
leetcode
MIT License
src/main/kotlin/graph/variation/Bipartite.kt
yx-z
106,589,674
false
null
package graph.variation import graph.core.Edge import graph.core.Graph import graph.core.Vertex // check if an undirected graph G = (V, E) is bipartite, that is, // let V be partitioned into two sets A and B, and every edge e in E satisfies // that one endpoint is in A and the other is in B fun <V> Graph<V>.isBipartite(checkIdentity: Boolean = true): Boolean { val marked = HashMap<Vertex<V>, Boolean>() val color = HashMap<Vertex<V>, Boolean>() vertices.forEach { marked[it] = false } val bag = ArrayList<Vertex<V>>() val start = vertices.toList()[0] var curr = true color[start] = curr bag.add(start) // wfs traversal with marking vertices with either TRUE or FALSE while (bag.isNotEmpty()) { val v = bag.removeAt(0) marked[v] = true curr = !curr getEdgesOf(v, checkIdentity).forEach { (s, e) -> // check for all marked vertices, if this edge has to be marked // with the same value (T/F), then G must NOT be bipartite if (color[s] == color[e]) { return false } val u = if ((checkIdentity && s === v) || (!checkIdentity && s == v)) e else s if (marked[u] == false) { bag.add(u) color[u] = curr } } } // O(V + E) return true } fun main(args: Array<String>) { val V = (0..2).map { Vertex(it) } val E = setOf(Edge(V[0], V[2]), Edge(V[1], V[2]), Edge(V[0], V[1])) val G = Graph(V, E) println(G.isBipartite()) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,376
AlgoKt
MIT License
src/main/kotlin/com/meghneelgore/trie/Trie.kt
meghneelgore
210,950,584
false
null
package com.meghneelgore.trie import java.io.File /** * This class creates a Trie from: * 1) A List<String> of a word list * 2) A file containing a word list. Each word must start on the first column of a new line. Words starting with a `#` * will be ignored. * * A Trie is a prefix tree. Each node in the trie holds a value, and a next set of nodes. Traversing down a trie to a * 'terminal' node gives a valid word from the word list loaded into the trie. */ class Trie private constructor() { internal lateinit var root: TrieNode<Char, String> var nWords: Long = 0 private set /** * Returns whether a specific word is in the dictionary. */ fun isWordInDictionary(word: String): Boolean { var tempRoot = root for (character in word) { if (tempRoot.contains(character)) tempRoot = tempRoot.get(character) else return false } return tempRoot.isTerminal } /** * Finds all the words in the dictionary that can complete a given start sequence. For example: * Given a dictionary: {"a, aa, ab, abc, abb, acc, aab"} and a sequence "ab" * the completions list will contain ["ab", "abc", "abb"] */ fun findCompletionsInDictionary(word: String): List<String> { val t = System.currentTimeMillis() val completions = mutableListOf<String>() // Traverse the word var tempRoot = root for (character in word) { if (tempRoot.contains(character)) tempRoot = tempRoot.get(character) else return emptyList() } // If word exists until now, traverse to leaves recursively traverseToLeaves(tempRoot, completions) println("Found ${completions.size} completions in ${System.currentTimeMillis() - t} milliseconds") return completions } /** * Finds all the words that can be produced using a sequence of given characters. * Given a dictionary: {"a, aa, ab, abc, abb, acc, aab, abd"} and a sequence ['a','b', 'c'] * The output list will contain ["a", "ab", "abc"] */ fun findAllWordsFromCharacters(characterString: String): List<String> { val t = System.currentTimeMillis() val foundWords = mutableListOf<String>() traverseTrie(root, characterString.toMutableList()) getFoundWords(root, foundWords) resetTraversal(root) println("Found ${foundWords.size} words in ${System.currentTimeMillis() - t} milliseconds") return foundWords } fun findAllWordsFromCharactersWithFrequency(characterString: String): List<Pair<String, Int>> { val t = System.currentTimeMillis() val foundWords = mutableListOf<Pair<String, Int>>() traverseTrie(root, characterString.toMutableList()) getFoundWordsWithFrequency(root, foundWords) resetTraversal(root) println("Found ${foundWords.size} words in ${System.currentTimeMillis() - t} milliseconds") return foundWords } fun getAllWords(root: TrieNode<Char, String>): List<Pair<String, Int>> { val list = mutableListOf<Pair<String, Int>>() getAllWordsInTrie(root, list) return list } private fun getAllWordsInTrie(root: TrieNode<Char, String>?, wordList: MutableList<Pair<String, Int>>) { if (root == null) return if (root.isTerminal) wordList.add(root.value!! to root.frequency) for (currentRoot in root.next.values) { getAllWordsInTrie(currentRoot, wordList) } } internal fun resetTraversal(root: TrieNode<Char, String>) { for (trieNode in root.next.values) { trieNode.isTraversed = false resetTraversal(trieNode) } } internal fun traverseTrie(root: TrieNode<Char, String>, listOfCharacters: MutableList<Char>) { for (trieNode in root.next.values) { val value: String? = trieNode.value value ?: return if (listOfCharacters.contains(value.last())) { trieNode.isTraversed = true traverseTrie(trieNode, listOfCharacters.apply { listOfCharacters.remove(value.last()) }) listOfCharacters.add(value.last()) } } } private fun getFoundWords(root: TrieNode<Char, String>, foundWords: MutableList<String>) { for (trieNode in root.next.values) { if (trieNode.isTraversed && trieNode.isTerminal) { foundWords.add(trieNode.value.toString()) } getFoundWords(trieNode, foundWords) } } private fun getFoundWordsWithFrequency(root: TrieNode<Char, String>, foundWords: MutableList<Pair<String, Int>>) { for (trieNode in root.next.values) { if (trieNode.isTraversed && trieNode.isTerminal) { foundWords.add(trieNode.value.toString() to trieNode.frequency) } getFoundWordsWithFrequency(trieNode, foundWords) } } private fun traverseToLeaves(tempRoot: TrieNode<Char, String>, completions: MutableList<String>) { if (tempRoot.isTerminal) { tempRoot.value?.let { completions.add(it) } } for (trieNode in tempRoot.next.values) traverseToLeaves(trieNode, completions) } fun setEncountered(input: String) { setEncountered(root, input.toMutableList()) } private fun setEncountered(root: TrieNode<Char, String>?, word: MutableList<Char>) { if (root == null) return if (word.isEmpty() && root.isTerminal) { root.frequency = 1 return } val character = word.removeAt(0) if (root.contains(character)) { val nextRoot = root.get(character) setEncountered(nextRoot, word) } } companion object { /** * Helper function for creating a Trie from a newline delimited word list file. Each word must start on the * first column of a new line. Lines beginning with a # will be ignored * * @param fileName Name of the file to load words from. * @param minLength Minimum length of the words to load. Any words in the file that are shorter than minLength * will be ignored. * @param maxLength Maximum length of the words to load. Any words in the file that are longer than maxLength * will be ignored. */ @JvmOverloads @JvmStatic fun trieFromFilename(fileName: String, minLength: Int = 1, maxLength: Int = 100): Trie = trieOf(File(fileName).readLines(), minLength, maxLength) @JvmOverloads @JvmStatic fun trieWithFrequencyFromFilename(fileName: String, minLength: Int = 1, maxLength: Int = 100): Trie = trieWithFrequencyOf(File(fileName).readLines(), minLength, maxLength) @JvmOverloads @JvmStatic fun trieWithFrequencyOf(wordsWithFrequency: List<String>, minLength: Int = 1, maxLength: Int = 100): Trie { val t = System.currentTimeMillis() val trie = Trie() trie.root = TrieNode() if (wordsWithFrequency.isNullOrEmpty()) return trie for (wordWithFreq in wordsWithFrequency) { val (word, freq) = wordWithFreq.split(",") if (word.length < minLength || word.length > maxLength) continue if (word.first() == '#') continue trie.nWords++ var tempRoot = trie.root word.forEachIndexed { index, character -> val isTerminal = index == word.lastIndex if (tempRoot.contains(character)) { tempRoot = tempRoot.get(character) if (isTerminal) tempRoot.isTerminal = true } else { val newTrieNode = TrieNode<Char, String>( value = if (tempRoot.value != null) tempRoot.value + (character) else character.toString(), isTerminal = isTerminal, frequency = if (isTerminal) freq.trim().toInt() else 0 ) tempRoot.put(character, newTrieNode) tempRoot = newTrieNode } } } println("${trie.nWords} words loaded in ${System.currentTimeMillis() - t} milliseconds") return trie } /** * Helper function for creating a Trie from a list of words. * * @param minLength Minimum length of the words to load. Any words in the list that are shorter than minLength * will be ignored. * @param maxLength Maximum length of the words to load. Any words in the list that are longer than maxLength * will be ignored. */ @JvmOverloads @JvmStatic fun trieOf(words: List<String>?, minLength: Int = 1, maxLength: Int = 100): Trie { val t = System.currentTimeMillis() val trie = Trie() trie.root = TrieNode() if (words.isNullOrEmpty()) return trie for (word in words) { if (word.length < minLength || word.length > maxLength) continue if (word.first() == '#') continue trie.nWords++ var tempRoot = trie.root word.forEachIndexed { index, character -> if (tempRoot.contains(character)) { tempRoot = tempRoot.get(character) if (index == word.lastIndex) tempRoot.isTerminal = true } else { val newTrieNode = TrieNode<Char, String>( value = if (tempRoot.value != null) tempRoot.value + (character) else character.toString(), isTerminal = index == word.lastIndex ) tempRoot.put(character, newTrieNode) tempRoot = newTrieNode } } } println("${trie.nWords} words loaded in ${System.currentTimeMillis() - t} milliseconds") return trie } @JvmStatic fun saveTrieWithFrequenciesToFile(trie: Trie, fileName: String) { val file = File(fileName) val words = trie.getAllWords(trie.root) file.printWriter().use { out -> for (word in words) { out.println("${word.first}, ${word.second}") } } } } }
0
Kotlin
0
0
4e86f3748eb7d417e154015f4fa4e0d0ffde3f5f
10,699
trie
MIT License
2021/src/main/kotlin/com/trikzon/aoc2021/Day1.kt
Trikzon
317,622,840
false
{"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397}
package com.trikzon.aoc2021 fun main() { val input = getInputStringFromFile("/day1.txt") benchmark(Part.One, ::dayOnePartOne, input, 1624, 50000) benchmark(Part.Two, ::dayOnePartTwo, input, 1653, 50000) } fun dayOnePartOne(input: String): Int { val depths = input.lines().map { line -> line.toInt() } var numberOfIncreases = 0 for (i in 1 until depths.size) { if (depths[i] > depths[i - 1]) { numberOfIncreases++ } } return numberOfIncreases } fun dayOnePartTwo(input: String): Int { val depths = input.lines().map { line -> line.toInt() } var numberOfIncreases = 0 for (i in 1 until depths.size - 2) { val iPlusNext = depths[i] + depths[i + 1] val firstSum = depths[i - 1] + iPlusNext val secondSum = iPlusNext + depths[i + 2] if (firstSum < secondSum) { numberOfIncreases++ } } return numberOfIncreases }
0
Kotlin
1
0
d4dea9f0c1b56dc698b716bb03fc2ad62619ca08
947
advent-of-code
MIT License
i18n/src/main/kotlin/com/kamelia/sprinkler/i18n/Plural.kt
Black-Kamelia
579,095,832
false
{"Kotlin": 647359, "Java": 18620}
package com.kamelia.sprinkler.i18n import com.kamelia.sprinkler.i18n.Options.COUNT import java.util.Locale /** * The plural value of the translation. It can be used to disambiguate translations depending on the number of * items. * * @see COUNT * @see TranslatorConfiguration.Builder.pluralMapper */ enum class Plural { /** * Plural value usually used in case the count is 0. */ ZERO, /** * Plural value usually used in case the count is 1. */ ONE, /** * Plural value usually used in case the count is 2. */ TWO, /** * Plural value usually used in case the count represents a few items. */ FEW, /** * Plural value usually used in case the count represents many items. */ MANY, /** * Plural value used as default when no other value matches. */ OTHER, ; /** * A mapper that associates a [Locale] and a [count][Int] to a [Plural] value. */ interface Mapper { /** * Maps the given [count] to a [Plural] value for the given [locale]. This method associates the parameters in * the context of a count of items. * * @param locale the [Locale] to use * @param count the count to use * @return the [Plural] value * @throws IllegalArgumentException if the given [count] is negative */ fun mapPlural(locale: Locale, count: Int): Plural /** * Maps the given [count] to a [Plural] value for the given [locale]. This method associates the parameters in * the context of an ordinal number. * * @param locale the [Locale] to use * @param count the count to use * @return the [Plural] value * @throws IllegalArgumentException if the given [count] is negative or zero */ fun mapOrdinal(locale: Locale, count: Int): Plural } companion object { /** * The default [Mapper] implementation. This implementation always returns plural values as if the locale was * [English][Locale.ENGLISH]. * * @return the default implementation of the [Mapper] interface */ @JvmStatic fun defaultMapper(): Mapper = object : Mapper { override fun mapPlural(locale: Locale, count: Int): Plural { require(count >= 0) { "count must be >= 0, but was $count" } return when (count) { 1 -> ONE else -> OTHER } } override fun mapOrdinal(locale: Locale, count: Int): Plural { require(count >= 1) { "count must be >= 1, but was $count" } return when (count % 10) { 1 -> ONE 2 -> TWO 3 -> FEW else -> OTHER } } override fun toString(): String = "Plural.defaultMapper()" } } internal val representation: String = name.lowercase() }
3
Kotlin
0
6
c86847064925469383cdde0cce68572bcde1e57b
3,084
Sprinkler
MIT License
src/main/kotlin/day19/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day19 import util.readInput data class Robot( val oreCost: Int = 0, val clayCost: Int = 0, val obsidianCost: Int = 0, ) data class Blueprint( val id: Int, val oreRobot: Robot, val clayRobot: Robot, val obsidianRobot: Robot, val geodeRobot: Robot, // We can use this to prune the amount of states. It makes no sense to build more ore-robots than the max ore cost. val maxOreCost: Int = maxOf(oreRobot.oreCost, clayRobot.oreCost, obsidianRobot.oreCost, geodeRobot.oreCost), val maxClayCost: Int = maxOf(oreRobot.clayCost, clayRobot.clayCost, obsidianRobot.clayCost, geodeRobot.clayCost), val maxObsidianCost: Int = maxOf(oreRobot.obsidianCost, clayRobot.obsidianCost, obsidianRobot.obsidianCost, geodeRobot.obsidianCost), ) { companion object { private val regex = Regex("""Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""") fun of(line: String) = regex.matchEntire(line)!! .destructured .let { (blueprintId, oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, obsidianRobotClayCost, geodeRobotOreCost, geodeRobotObsidianCost) -> Blueprint( id = blueprintId.toInt(), oreRobot = Robot(oreCost = oreRobotOreCost.toInt()), clayRobot = Robot(oreCost = clayRobotOreCost.toInt()), obsidianRobot = Robot(oreCost = obsidianRobotOreCost.toInt(), clayCost = obsidianRobotClayCost.toInt()), geodeRobot = Robot(oreCost = geodeRobotOreCost.toInt(), obsidianCost = geodeRobotObsidianCost.toInt()) ) } } } data class GameState( val oreRobotCount: Int = 1, val clayRobotCount: Int = 0, val obsidianRobotCount: Int = 0, val geodeRobotCount: Int = 0, val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0, ): Comparable<GameState> { override fun compareTo(other: GameState): Int { if (geode != other.geode) return other.geode.compareTo(geode) if (geodeRobotCount != other.geodeRobotCount) return other.geodeRobotCount.compareTo(geodeRobotCount) if (obsidian != other.obsidian) return other.obsidian.compareTo(obsidian) if (obsidianRobotCount != other.obsidianRobotCount) return other.obsidianRobotCount.compareTo(obsidianRobotCount) if (clay != other.clay) return other.clay.compareTo(clay) if (clayRobotCount != other.clayRobotCount) return other.clayRobotCount.compareTo(clayRobotCount) if (ore != other.ore) return other.ore.compareTo(ore) if (oreRobotCount != other.oreRobotCount) return other.oreRobotCount.compareTo(oreRobotCount) return 0 } fun canAffordOreRobot(blueprint: Blueprint) = ore >= blueprint.oreRobot.oreCost fun canAffordClayRobot(blueprint: Blueprint) = ore >= blueprint.clayRobot.oreCost fun canAffordObsidianRobot(blueprint: Blueprint) = ore >= blueprint.obsidianRobot.oreCost && clay >= blueprint.obsidianRobot.clayCost fun canAffordGeodeRobot(blueprint: Blueprint) = ore >= blueprint.geodeRobot.oreCost && obsidian >= blueprint.geodeRobot.obsidianCost fun spendOnOreRobot(blueprint: Blueprint) = copy(ore = ore - blueprint.oreRobot.oreCost) fun spendOnClayRobot(blueprint: Blueprint) = copy(ore = ore - blueprint.clayRobot.oreCost) fun spendOnObsidianRobot(blueprint: Blueprint) = copy(ore = ore - blueprint.obsidianRobot.oreCost, clay = clay - blueprint.obsidianRobot.clayCost) fun spendOnGeodeRobot(blueprint: Blueprint) = copy(ore = ore - blueprint.geodeRobot.oreCost, obsidian = obsidian - blueprint.geodeRobot.obsidianCost) fun collect(): GameState = copy( ore = ore + oreRobotCount, clay = clay + clayRobotCount, obsidian = obsidian + obsidianRobotCount, geode = geode + geodeRobotCount, ) } fun getNextStates(state: GameState, blueprint: Blueprint): Set<GameState> { val nextStates = mutableSetOf<GameState>() // Build ore robot? if (state.oreRobotCount < blueprint.maxOreCost && state.canAffordOreRobot(blueprint)) { nextStates += state .spendOnOreRobot(blueprint) .collect() .copy(oreRobotCount = state.oreRobotCount + 1) } // Build clay robot? if (state.clayRobotCount < blueprint.maxClayCost && state.canAffordClayRobot(blueprint)) { nextStates += state .spendOnClayRobot(blueprint) .collect() .copy(clayRobotCount = state.clayRobotCount + 1) } // Build obsidian robot? if (state.obsidianRobotCount < blueprint.maxObsidianCost && state.canAffordObsidianRobot(blueprint)) { nextStates += state .spendOnObsidianRobot(blueprint) .collect() .copy(obsidianRobotCount = state.obsidianRobotCount + 1) } // Build geode robot? if (state.canAffordGeodeRobot(blueprint)) { nextStates += state .spendOnGeodeRobot(blueprint) .collect() .copy(geodeRobotCount = state.geodeRobotCount + 1) } // Or just wait and collect geodes ... nextStates += state.collect() return nextStates } fun play(states: Set<GameState>, blueprint: Blueprint): Set<GameState> = states // calculate all possible states from this state .flatMap { state -> getNextStates(state, blueprint) } // take the best states to keep the state-list smaller .toSortedSet() .take(10000) .toSet() fun main() { val bluePrints = readInput("day19").map { Blueprint.of(it) } val debugPrint = false // part 1 (24 minutes) val rounds = 24 val qualityLevels = bluePrints.map {bluePrint -> var states = setOf(GameState(oreRobotCount = 1)) repeat(rounds) { minute -> if (debugPrint) println("Minute ${minute + 1} (states ${states.size})") states = play(states, bluePrint) if (debugPrint) println(states.take(5).joinToString("\n")) } val qualityLevel = states.first().geode * bluePrint.id println("Blueprint ${bluePrint.id}: $qualityLevel") qualityLevel } println("Overall quality: ${qualityLevels.sum()}") // part 2 (32 minutes, but only 3 blueprints) val part2Rounds = 32 val geodeCounts = bluePrints.take(3).map {bluePrint -> var states = setOf(GameState(oreRobotCount = 1)) repeat(part2Rounds) { minute -> if (debugPrint) println("Minute ${minute + 1} (states ${states.size})") states = play(states, bluePrint) if (debugPrint) println(states.take(5).joinToString("\n")) } val geodeCount = states.first().geode println("Blueprint ${bluePrint.id}: $geodeCount") geodeCount } println("Overall quality part2: ${geodeCounts.reduce {acc, i -> acc * i}}") }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
7,072
advent-of-code-2022
MIT License
src/Day06.kt
ChenJiaJian96
576,533,624
false
{"Kotlin": 11529}
fun main() { fun String.findFirstMarkerIndex(markerLength: Int): Int { for (index in 0 until this.length - markerLength) { this.substring(index, index + markerLength).toSet().also { if (it.size == markerLength) { return index + markerLength } } } return -1 } fun part1(input: List<String>): List<Int> = input.map { it.findFirstMarkerIndex(4) } fun part2(input: List<String>): List<Int> = input.map { it.findFirstMarkerIndex(14) } val testInput = readInput("06", true) check(part1(testInput) == listOf(7, 5, 6, 10, 11)) check(part2(testInput) == listOf(19, 23, 23, 29, 26)) val input = readInput("06") part1(input).println() part2(input).println() }
0
Kotlin
0
0
b1a88f437aee756548ac5ba422e2adf2a43dce9f
850
Advent-Code-2022
Apache License 2.0
app/src/main/java/com/peluso/walletguru/model/Account.kt
pelusodan
351,481,020
false
null
package com.peluso.walletguru.model import com.kirkbushman.araw.models.Submission import com.peluso.walletguru.model.Account.Companion.orderSubmissions import java.util.* import kotlin.collections.ArrayList import kotlin.collections.LinkedHashMap import kotlin.math.abs /** * Class which represents a financial account to be tracked in our application. An account is linked * to certain subreddits, and based on the performance of the account these posts are prioritized */ class Account(val type: PostType, val currentBalance: Float, val percentageChange: Float) { companion object { fun List<Account>.orderSubmissions(accountMap: Map<PostType, List<Submission>>): List<Submission> { // getting the country from the map, and if we find a country adding it to the account sorting val countryPostType = accountMap.keys.find { it is CountryType } var sortedAccounts = this as MutableList countryPostType?.let { sortedAccounts.add(Account(it, 0f, 20f)) } sortedAccounts = sortedAccounts.sortedByDescending { abs(it.percentageChange) }.toMutableList() val subredditRankings = sortedAccounts.map { it.type to sortedAccounts.indexOf(it) }.toMap() // show all first posts in order of priority accounts, then all second posts // in order of priority accounts, then all third posts and so forth val sortedAccountMap = LinkedHashMap<PostType, List<Submission>>() subredditRankings.entries.forEach { if (accountMap.containsKey(it.key)) { sortedAccountMap[it.key] = accountMap.getValue(it.key) } } var maxLoopCounter = 0 // loop through map to find max loop counter for building sorted array sortedAccountMap.entries.forEach { val value = sortedAccountMap.getValue(it.key).size if (value > maxLoopCounter) { maxLoopCounter = value } } val sortedArray = ArrayList<Submission>(); for (i in 0..maxLoopCounter) { sortedAccountMap.entries.forEach { if (i < it.value.size) sortedArray.add(it.value[i]) } } return sortedArray } } } fun List<AccountDto>.toAccounts(): List<Account> { return this.map { Account(AccountType.getViewNameFromTableName(it.accountName).toAccountType(), it.accountBalance, it.percentChange) } }
0
Kotlin
0
0
c4b4bcd766612a4669bbfdba597fc1cbbc89e974
2,641
WalletGuru
MIT License
kotlin/src/main/kotlin/com/zortek/kata/yatzy/DiceRoll.kt
ZorteK
452,356,448
true
{"Java": 18208, "Kotlin": 14204, "C++": 12092, "Swift": 10541, "C#": 10261, "PHP": 10148, "TypeScript": 8658, "JavaScript": 8377, "Perl": 8167, "Clojure": 8035, "Python": 7794, "Ruby": 6749, "Elixir": 6335, "C": 6001, "CMake": 1327, "Makefile": 103, "Batchfile": 69}
package com.zortek.kata.yatzy import java.util.stream.Stream class DiceRoll(private val dice: List<Int>) { fun yatzy(): Boolean { return groupByValue() .values .any { it == 5 } } fun isFullHouse(): Boolean { val hasThreeOfAKind = getDiceWithCountGreaterThan(3) != 0 val hasPair = !findPairs().isEmpty() val isYatzy = yatzy() //todo :it's debatable return hasThreeOfAKind && hasPair && !isYatzy } fun countDice(dice: Int): Int { return groupByValue()[dice] ?: 0 } fun ones(roll: DiceRoll): Int { return roll.countDice(1) } fun twos(roll: DiceRoll): Int { return roll.countDice(2) * 2 } fun threes(roll: DiceRoll): Int { return roll.countDice(3) * 3 } fun fours(roll: DiceRoll): Int { return roll.countDice(4) * 4 } fun fives(roll: DiceRoll): Int { return roll.countDice(5) * 5 } fun sixes(roll: DiceRoll): Int { return roll.countDice(6) * 6 } fun findPairs(): List<Int> { return filterNumberOfDiceGreaterThan(2) .sorted(Comparator.reverseOrder()) .toList() } fun getDiceWithCountGreaterThan(n: Int) = filterNumberOfDiceGreaterThan(n) .findFirst() .orElse(0)!! fun sum() = dice.sum() fun isSmallStraight() = sort() == SMALL_STRAIGHT fun isLargeStraight() = sort() == LARGE_STRAIGHT private fun sort() = dice.sorted() private fun filterNumberOfDiceGreaterThan(n: Int): Stream<Int> { return groupByValue() .entries .stream() .filter { it.value >= n } .map { it.key } } private fun groupByValue(): Map<Int, Int> { return dice .groupingBy { it } .eachCount() } companion object { private val SMALL_STRAIGHT: List<Int> = listOf(1, 2, 3, 4, 5) private val LARGE_STRAIGHT: List<Int> = listOf(2, 3, 4, 5, 6) fun of(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int) = DiceRoll(listOf(d1, d2, d3, d4, d5)) } }
0
Java
0
0
885ee1f9abdd9d88fd28eeea6b61e07d1b97f706
2,115
Yatzy-Refactoring-Kata
MIT License
kabac/src/main/kotlin/no/nav/personoversikt/common/kabac/CombiningAlgorithm.kt
navikt
505,819,547
false
{"Kotlin": 167360}
package no.nav.personoversikt.common.kabac import no.nav.personoversikt.common.kabac.utils.Key interface CombiningAlgorithm { fun combine(policies: List<Kabac.Policy>): Kabac.Policy companion object { val firstApplicable: CombiningAlgorithm = FirstApplicable() val denyOverride: CombiningAlgorithm = DecisionOverride(Decision.Type.DENY) val permitOverride: CombiningAlgorithm = DecisionOverride(Decision.Type.PERMIT) } } private class DecisionOverride(val overrideValue: Decision.Type) : CombiningAlgorithm { override fun combine(policies: List<Kabac.Policy>) = object : Kabac.Policy { override val key = Key<Kabac.Policy>("Combinging policies by ${overrideValue.name.lowercase()}-override rule") override fun evaluate(ctx: Kabac.EvaluationContext): Decision { var decision: Decision = Decision.NotApplicable("No applicable policy found") for (policy in policies) { ctx.report(policy.key.name).indent() val policyDecision = policy .evaluate(ctx) .also { ctx.report("Decision: $it") } decision = when (policyDecision.type) { overrideValue -> { ctx .unindent() .report("Last decision matches override value. Stopping policy evaluation.") return policyDecision } Decision.Type.NOT_APPLICABLE -> decision else -> policyDecision } ctx.unindent() } return decision } } } private class FirstApplicable : CombiningAlgorithm { override fun combine(policies: List<Kabac.Policy>) = object : Kabac.Policy { override val key = Key<Kabac.Policy>("Combinging policies by first-applicable rule") override fun evaluate(ctx: Kabac.EvaluationContext): Decision { for (policy in policies) { ctx.report(policy.key.name).indent() val decision = policy .evaluate(ctx) .also { ctx.report("Decision: $it") } if (decision.isApplicable()) { ctx .unindent() .report("Last decision was applicable. Stopping policy evaluation.") return decision } ctx.unindent() } return Decision.NotApplicable("No applicable policy found") } } }
1
Kotlin
0
0
64707e48b53bf939ee55eead605dd330d2f56e81
2,605
modia-common-utils
MIT License
src/commonMain/kotlin/io/github/alexandrepiveteau/graphs/algorithms/EdmondsKarp.kt
alexandrepiveteau
630,931,403
false
{"Kotlin": 132267}
@file:JvmName("Algorithms") @file:JvmMultifileClass package io.github.alexandrepiveteau.graphs.algorithms import io.github.alexandrepiveteau.graphs.* import io.github.alexandrepiveteau.graphs.builder.buildDirectedNetwork import kotlin.jvm.JvmMultifileClass import kotlin.jvm.JvmName import kotlin.math.min /** Returns the residual network of this [DirectedNetwork], given the current [flow]. */ private fun <N> N.residual( flow: DirectedNetwork, ): DirectedNetwork where N : Directed, N : SuccessorsWeight { return buildDirectedNetwork { forEachVertex { addVertex() } forEachArc { arc -> val forwardCapacity = successorWeight(arc) - flow.successorWeight(arc) if (forwardCapacity > 0) addArc(arc, forwardCapacity) val backwardCapacity = flow.successorWeight(arc) if (backwardCapacity > 0) addArc(arc.reversed(), backwardCapacity) } } } /** Iterates over all the arcs in the path, and calls the [action] for each of them. */ private inline fun VertexArray.forEachArc(action: (Arc) -> Unit) { for (u in 0 ..< size - 1) { action(this[u] arcTo this[u + 1]) } } /** Returns the remaining capacity of the [flow] in the [path]. */ private fun <N> N.remainingCapacity( flow: DirectedNetwork, path: VertexArray, ): Int where N : Directed, N : SuccessorsWeight { var capacity = Int.MAX_VALUE path.forEachArc { arc -> val local = if (arc in this) successorWeight(arc) - flow.successorWeight(arc) else flow.successorWeight(arc.reversed()) capacity = min(capacity, local) } return capacity } /** Augments the [flow] with the given [path] and [flow], and returns the new flow. */ private fun <N> N.augment( path: VertexArray, flow: Int, ): DirectedNetwork where N : Directed, N : SuccessorsWeight { return buildDirectedNetwork { forEachVertex { addVertex() } forEachVertex { u -> forEachSuccessor(u) { v, w -> addArc(u arcTo v, w) } } path.forEachArc { arc -> if (arc in this@augment) addArc(arc, flow) else addArc(arc.reversed(), -flow) } } } /** * Returns the maximum flow from the [from] [Vertex] to the [to] [Vertex] in this [Network], as * constrained by the capacities of the edges. * * @param from the [Vertex] from which the flow should start. * @param to the [Vertex] to which the flow should end. * @return the maximum flow from the [from] [Vertex] to the [to] [Vertex] in this [Network], as * constrained by the capacities of the arcs. * @receiver the [Network] on which to compute the maximum flow. */ public fun <N> N.maxFlowEdmondsKarp( from: Vertex, to: Vertex, ): DirectedNetwork where N : Directed, N : SuccessorsWeight { // TODO : Use some MutableDirectedNetworks once they're implemented. var maxFlow = buildDirectedNetwork { forEachVertex { addVertex() } forEachArc { (u, v) -> addArc(u arcTo v, 0) } } while (true) { val residual = residual(maxFlow) val path = residual.shortestPathBreadthFirst(from, to) ?: break val flow = remainingCapacity(maxFlow, path) maxFlow = maxFlow.augment(path, flow) } return maxFlow }
9
Kotlin
0
6
a4fd159f094aed5b6b8920d0ceaa6a9c5fc7679f
3,109
kotlin-graphs
MIT License
src/day07/Day07.kt
schrami8
572,631,109
false
{"Kotlin": 18696}
package day07 import readInput enum class FileType { DIRECTORY, FILE } interface FileSystemObject { fun getName(): String fun getSize(): Int fun getType(): FileType fun addChild(child: FileSystemObject) fun getChildren(): List<FileSystemObject> fun getParent(): FileSystemObject? fun plusSize(size: Int) } class Directory( private val name: String, private val parent: FileSystemObject?) : FileSystemObject { private val children = mutableListOf<FileSystemObject>() private var size = 0 override fun getName(): String = name override fun getSize(): Int = size override fun getType(): FileType = FileType.DIRECTORY override fun addChild(child: FileSystemObject) { children.add(child) } override fun getChildren(): List<FileSystemObject> = children override fun getParent(): FileSystemObject? = parent override fun plusSize(size: Int) { this.size += size } } class File ( private val name: String, private val size: Int, private val parent: FileSystemObject?) : FileSystemObject { override fun getName(): String = name override fun getSize(): Int = size override fun getType(): FileType = FileType.FILE override fun addChild(child: FileSystemObject) { } override fun getChildren(): List<FileSystemObject> { return emptyList() } override fun getParent(): FileSystemObject? = parent override fun plusSize(size: Int) { } } fun getDirectories(input: List<String>): List<FileSystemObject> { val root = Directory("/", null) var workingDirectory: FileSystemObject? = null val allDirectories = mutableListOf<FileSystemObject>() allDirectories.add(root) input.forEach { line -> val parts = line.split(" ") when (parts[0] ) { "$" -> { if (parts[1] == "cd") { workingDirectory = if (parts[2] == "..") { workingDirectory!!.getParent() } else if (parts[2] == "/") { root } else { var cd: FileSystemObject? = null for (child in workingDirectory!!.getChildren()) if (child.getType() == FileType.DIRECTORY && child.getName() == parts[2]) { cd = child break } cd } } if (parts[1] == "ls") { // nothing to do } } "dir" -> { val tmpDirectory = Directory(parts[1], workingDirectory) workingDirectory!!.addChild(tmpDirectory) allDirectories.add(tmpDirectory) } else -> { val file = File(parts[1], parts[0].toInt(), workingDirectory) workingDirectory!!.addChild(file) workingDirectory!!.plusSize(file.getSize()) var tmp = workingDirectory!!.getParent() while (tmp != null) { tmp.plusSize(file.getSize()) tmp = tmp.getParent() } } } } return allDirectories } fun main() { fun part1(input: List<String>): Int { var size = 0 for (dir in getDirectories(input)) { if (dir.getSize() < 100000) size += dir.getSize() } return size } fun part2(input: List<String>): Int { val directories = getDirectories(input) val root = directories[0] val DISK_SPACE_AVAILABLE = 70000000 val NEED_UNUSED = 30000000 val spaceLeft = DISK_SPACE_AVAILABLE - root.getSize() val spaceToRemove = NEED_UNUSED - spaceLeft val candidates = mutableSetOf<Int>() for (dir in directories) if (dir.getSize() > spaceToRemove) candidates.add(dir.getSize()) return candidates.elementAt(candidates.size -1) } // test if implementation meets criteria from the description, like: val testInput = readInput("day07/Day07_test") check(part1(testInput) == 95437) val input = readInput("day07/Day07") println(part1(input)) check(part2(testInput) == 24933642) println(part2(input)) }
0
Kotlin
0
0
215f89d7cd894ce58244f27e8f756af28420fc94
4,509
advent-of-code-kotlin
Apache License 2.0
src/day6/fr/Day06_1.kt
BrunoKrantzy
433,844,189
false
{"Kotlin": 63580}
package day6.fr import java.io.File private fun readChars(): CharArray = readLn().toCharArray() private fun readLn() = readLine()!! // string line private fun readSb() = StringBuilder(readLn()) private fun readInt() = readLn().toInt() // single int private fun readLong() = readLn().toLong() // single long private fun readDouble() = readLn().toDouble() // single double private fun readStrings() = readLn().split(" ") // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of ints private fun readLongs() = readStrings().map { it.toLong() } // list of longs private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles private fun readIntArray() = readStrings().map { it.toInt() }.toIntArray() // Array of ints private fun readLongArray() = readStrings().map { it.toLong() }.toLongArray() // Array of longs fun readInput(name: String) = File("src", "$name.txt").readLines() fun main() { val vIn = readInput("input6") //val vIn = readInput("test6") var lstFish = vIn[0].split(',').map { it.toInt() } as MutableList var lstWork = mutableListOf<Int>() var rep = 0L val nJours = 80 for (i in (1 .. nJours).asSequence()) { var nbFish = lstFish.size for (j in (0 until nbFish).asSequence()) { var vCycle = lstFish[j] if (vCycle == 0) { lstWork.add(6) lstWork.add(8) } else { lstWork.add(vCycle - 1) } } lstFish = lstWork.toMutableList() lstWork.clear() } rep = lstFish.size.toLong() println(rep) }
0
Kotlin
0
0
0d460afc81fddb9875e6634ee08165e63c76cf3a
1,649
Advent-of-Code-2021
Apache License 2.0
src/test/kotlin/se/radicalcode/aoc/4Tests.kt
gwendo
162,547,004
false
null
package se.radicalcode.aoc import kotlin.test.assertEquals import org.junit.Test as test class TestGuardProblem { @test fun testParseEvent() { val input = "[1518-11-01 00:00] Guard #10 begins shift" val input2 = "[1518-10-16 23:59] Guard #409 begins shift" println(parseDate(input)) println(parseDate(input2)) } @test fun testParseGuardId() { val input = "[1518-11-01 00:00] Guard #10 begins shift" val input2 = "[1518-10-16 23:59] Guard #409 begins shift" val input3 = "[1518-11-05 00:45] falls asleep" val input4 = "[1518-11-05 00:55] wakes up" assertEquals(10, parseGuardId(input)) assertEquals(409, parseGuardId(input2)) assertEquals(-1, parseGuardId(input3)) assertEquals(-1, parseGuardId(input4)) } @test fun testOrderList() { var eventList = readFileAsStrings(ClassLoader.getSystemResource("4.in").file) .map{ parseEvent(it)} .sortedBy { it.dateTime } .toMutableList() var previousEvent: GuardEvent? = null for (guardEvent in eventList) { if (guardEvent.guardId == -1 && previousEvent != null) { guardEvent.guardId = previousEvent.guardId } previousEvent = guardEvent } val guardEventList = eventList .filter{ge -> ge.event == EventType.SLEEP || ge.event == EventType.WAKEUP} .groupBy{e -> e.guardId} .mapValues { entry -> entry.value.groupBy { ge -> ge.monthDay } } .mapValues { entry2 -> entry2.value.entries.map{ el -> initSleepArray(el.value)} } val sleepyHead = guardEventList.mapValues { entry -> entry.value.map{it.sum()}.sum() } .maxBy { entry -> entry.value } val maxSleepMinuteMap = guardEventList .mapValues{ entry -> entry.value.map { it.withIndex().toList() }.flatten().groupBy { it.index }.mapValues{ entry -> entry.value.count{ it.value == 1}}.maxBy { it.value }} maxSleepMinuteMap.forEach { (t, u) -> println("$t->$u") } val maxEntry = maxSleepMinuteMap.maxBy { entry -> entry.value!!.value } if (maxEntry?.value != null) { println(maxEntry.key * maxEntry.value!!.key) } if (sleepyHead != null) { val maxEntry = guardEventList.getValue(sleepyHead.key) .map { it.withIndex().toList() }.flatten().groupBy { it.index }.mapValues{ entry -> entry.value.count{ it.value == 1}}.maxBy { it.value } if (maxEntry != null) { println(maxEntry.key * sleepyHead.key) } } } }
0
Kotlin
0
0
12d0c841c91695e215f06efaf62d06a5480ba7a2
2,672
advent-of-code-2018
MIT License
src/main/kotlin/tr/emreone/adventofcode/days/Day25.kt
EmRe-One
433,772,813
false
{"Kotlin": 118159}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.Logger.logger import tr.emreone.kotlin_utils.automation.Day import tr.emreone.kotlin_utils.math.Point2D class Day25 : Day(25, 2021, "Sea Cucumber") { class SeaCucumber(input: List<String>) { private val width = input.first().length private val height = input.size private val region = input.flatMapIndexed { y: Int, line: String -> line.mapIndexed { x: Int, c: Char -> Point2D(x.toLong(), y.toLong()) to c } }.filterNot { it.second == SIGN_EMPTY }.associate { it.first to it.second } // extend the Point2d class with the following methods: // the east() point is the east neighbor of the point or if reach the border then the most west point in the sea // the south() point is the south neighbor of the point or if reach the border then the most nord point in the sea private fun Point2D.east() = Point2D((x + 1) % width, y) private fun Point2D.south() = Point2D(x, (y + 1) % height) private fun next(region: Map<Point2D, Char>): Map<Point2D, Char> { val nextRegion = region.toMutableMap() // First go to the east nextRegion.filterValues { it == SIGN_EAST } .keys .map { it to it.east() } .filter { it.second !in nextRegion } .forEach { nextRegion.remove(it.first) nextRegion[it.second] = SIGN_EAST } // Then go to the south nextRegion.filterValues { it == SIGN_SOUTH } .keys .map { it to it.south() } .filter { it.second !in nextRegion } .forEach { nextRegion.remove(it.first) nextRegion[it.second] = SIGN_SOUTH } return nextRegion } fun countStepsToStopMoving(): Int { val sequence = generateSequence(this.region) { printSeaCucumber(it) next(it) }.zipWithNext().takeWhile { it.first != it.second } return sequence.count() + 1 } private fun printSeaCucumber(seaCucumber: Map<Point2D, Char>) { val output = buildString { appendLine() for (y in 0 until height) { for (x in 0 until width) { append(seaCucumber[Point2D(x.toLong(), y.toLong())] ?: SIGN_EMPTY) } appendLine() } } logger.debug { output } } companion object { const val SIGN_EMPTY = '.' const val SIGN_EAST = '>' const val SIGN_SOUTH = 'v' } } override fun part1(): Int { val seaCucumber = SeaCucumber(inputAsList) return seaCucumber.countStepsToStopMoving() } }
0
Kotlin
0
0
516718bd31fbf00693752c1eabdfcf3fe2ce903c
3,209
advent-of-code-2021
Apache License 2.0
017. Find Three Largest Numbers/FindThreeLargestNumbers.kt
jerrycychen
461,704,376
false
{"Java": 46772, "Kotlin": 35765}
package com.algoexpert.program fun findThreeLargestNumbers(array: List<Int>): List<Int> { val threeLargest = mutableListOf(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE) for (num in array) { updateLargest(threeLargest, num) } return threeLargest } fun updateLargest(threeLargest: MutableList<Int>, num: Int) { if (num > threeLargest[2]) { shiftAndUpdate(threeLargest, num, 2) } else if (num > threeLargest[1]) { shiftAndUpdate(threeLargest, num, 1) } else if (num > threeLargest[0]) { shiftAndUpdate(threeLargest, num, 0) } } fun shiftAndUpdate(threeLargest: MutableList<Int>, num: Int, index: Int) { for (i in 0 until index + 1) { if (i == index) { threeLargest[i] = num } else { threeLargest[i] = threeLargest[i + 1] } } }
0
Java
3
4
c853c5935c202520f74650c85d1ed70ff398b2ea
846
algoexpert
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day16.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2021 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.StringTokenizer import se.saidaspen.aoc.util.toBinary import java.lang.RuntimeException fun main() = Day16.run() object Day16 : Day(2021, 16) { override fun part1(): Any { val decoder = PacketDecoder() decoder.decode(input) return decoder.versionSum } override fun part2(): Any { val decoder = PacketDecoder() return decoder.decode(input) } } class PacketDecoder { private var stack = mutableListOf<Long>() var versionSum = 0 fun decode(hex: String): Long { val binIn = hex.toCharArray().toList().joinToString("") { Integer.parseInt(it.toString(), 16).toBinary(4) } val tok = StringTokenizer(binIn) fun readPackage(): Int { val leftBefore = tok.left() val version = tok.take(3).toInt(2) versionSum += version val typeId = tok.take(3).toInt(2) if (typeId == 4) { // Literal value var tmp = "" var continueFlag: String do { continueFlag = tok.take(1) tmp += tok.take(4) } while (continueFlag == "1") stack.add(tmp.toLong(2)) } else { val lenTypeId = tok.take(1) var subPackages = 0 if (lenTypeId == "0") { val packageLength = tok.take(15).toInt(2) var tRead = 0 while (tRead < packageLength) { tRead += readPackage() subPackages++ } } else { val numberOfSubPackages = tok.take(11).toInt(2) repeat(numberOfSubPackages) { readPackage() subPackages++ } } val operands = stack.takeLast(subPackages) stack = stack.dropLast(subPackages).toMutableList() val value: Long = when (typeId) { 0 -> operands.sumOf { it } 1 -> operands.fold(1L){ acc, i -> acc * i} 2 -> operands.minOf { it } 3 -> operands.maxOf { it } 5 -> if (operands[0] > operands[1]) 1 else 0 6 -> if (operands[0] < operands[1]) 1 else 0 7 -> if (operands[0] == operands[1]) 1 else 0 else -> throw RuntimeException("Unsupported type $typeId") } stack.add(value) } return leftBefore - tok.left() } while (tok.toString().any { it == '1' }) { readPackage() } return stack[0] } } data class Packet(val version: Int, val type: PacketType, val value: Long? = null, val sub: MutableList<Packet> = mutableListOf()) { val versionSum: Int get() = version + sub.sumOf { it.versionSum } fun eval() : Long = when(type) { PacketType.LIT -> value!! PacketType.SUM -> sub.sumOf { it.eval() } PacketType.PROD -> sub.fold(1L) { acc, n -> acc * n.eval() } PacketType.MIN -> sub.minOf { it.eval() } PacketType.MAX -> sub.maxOf { it.eval() } PacketType.GT -> sub.let { (a, b) -> if(a.eval() > b.eval()) 1 else 0 } PacketType.LT -> sub.let { (a, b) -> if(a.eval() < b.eval()) 1 else 0 } PacketType.EQ -> sub.let { (a, b) -> if(a.eval() == b.eval()) 1 else 0 } } } enum class PacketType { SUM, PROD, MIN, MAX, LIT, GT, LT, EQ }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
3,707
adventofkotlin
MIT License
src/day04/Day04.kt
Frank112
572,910,492
false
null
package day04 import assertThat import readInput fun main() { val inputParseRegex = Regex("^(\\d+)-(\\d+),(\\d+)-(\\d+)$") fun parseInput(input: List<String>): List<Pair<CleaningAssignment, CleaningAssignment>> { return input.map { l -> inputParseRegex.matchEntire(l)!!.groupValues.drop(1).map { s -> s.toInt() } } .map { sectionIds -> Pair(CleaningAssignment(sectionIds[0], sectionIds[1]), CleaningAssignment(sectionIds[2], sectionIds[3])) } } fun part1(input: List<Pair<CleaningAssignment, CleaningAssignment>>): Int { return input.count { p -> CleaningAssignment.isOneContainedByTheOther(p.first, p.second) } } fun part2(input: List<Pair<CleaningAssignment, CleaningAssignment>>): Int { return input.count{ p -> p.first.overlaps(p.second)} } // test if implementation meets criteria from the description, like: val testInput = parseInput(readInput("day04/Day04_test")) println("Parsed test input: $testInput") assertThat(part1(testInput), 2) assertThat(part2(testInput), 4) val input = parseInput(readInput("day04/Day04")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1e927c95191a154efc0fe91a7b89d8ff526125eb
1,175
advent-of-code-2022
Apache License 2.0
kotlin/11.kt
NeonMika
433,743,141
false
{"Kotlin": 68645}
class Day11 : Day<TwoDimensionalArray<Int>>("11") { override fun dataStar1(lines: List<String>): TwoDimensionalArray<Int> = TwoDimensionalArray(lines.map { it.toCharArray().map(Char::digitToInt) }) override fun dataStar2(lines: List<String>): TwoDimensionalArray<Int> = dataStar1(lines) fun step(data: TwoDimensionalArray<Int>): Pair<TwoDimensionalArray<Int>, Int> { var localIncs = 0 val cur = data.map { it + 1 } while (cur.any { it > 9 }) { for (row in 0 until cur.rows) { for (col in 0 until cur.cols) { if (cur[row, col] > 9) { cur[row, col] = Integer.MIN_VALUE localIncs++ cur.mutateAllNeighbors(row, col) { it + 1 } } } } } return cur.map { if (it < 0) 0 else it } to localIncs } override fun star1(data: TwoDimensionalArray<Int>): Number { var cur = data var incs = 0 repeat(100) { step(cur).let { (stepCur, stepIncs) -> cur = stepCur incs += stepIncs } } return incs } override fun star2(data: TwoDimensionalArray<Int>): Number { var cur = data repeat(1_000_000) { runIndex -> step(cur).let { (stepCur, stepIncs) -> cur = stepCur if (stepIncs == 100) return runIndex + 1 } } return -1 } } fun main() { Day11()() }
0
Kotlin
0
0
c625d684147395fc2b347f5bc82476668da98b31
1,563
advent-of-code-2021
MIT License
src/Day1/Day01.kt
lukeqwas
573,403,156
false
null
package Day1 import readInput fun main() { // 4*O(N) == O(N) val testInput = readInput("Day01") val totalElfCalories = mutableListOf<Long>() var curCalorie = 0L for (calorie in testInput) { if(calorie.equals("")) { totalElfCalories.add(curCalorie) curCalorie = 0 } else { curCalorie += calorie.toLong() } } // dont forget the last one totalElfCalories.add(curCalorie) val result1 = findMax(totalElfCalories) val result2 = findMax(result1.list) val result3 = findMax(result2.list) println(result1.max + result2.max + result3.max) } fun findMax(elfCalories: MutableList<Long>): RemoveResult { var max = 0L var maxIndex = 0 var curIndex = 0 for (totalCalorie in elfCalories) { if(totalCalorie > max) { max = totalCalorie maxIndex = curIndex } curIndex++ } elfCalories.removeAt(maxIndex) return RemoveResult(max, elfCalories) } data class RemoveResult(val max: Long, val list: MutableList<Long>)
0
Kotlin
0
0
6174a8215f8d4dc6d33fce6f8300a4a8999d5431
1,082
aoc-kotlin-2022
Apache License 2.0
base/src/main/java/com/mindera/skeletoid/utils/versioning/Versioning.kt
Mindera
85,591,428
false
null
package com.mindera.skeletoid.utils.versioning import kotlin.math.sign object Versioning { /** * Compares two version strings. * Credits to: https://gist.github.com/antalindisguise/d9d462f2defcfd7ae1d4 * * Use this instead of String.compareTo() for a non-lexicographical * comparison that works for version strings. e.g. "1.10".compareTo("1.6"). * * @note It does not work if "1.10" is supposed to be equal to "1.10.0". * * @param str1 a string of ordinal numbers separated by decimal points. * @param str2 a string of ordinal numbers separated by decimal points. * @return The result is a negative integer if str1 is _numerically_ less than str2. * The result is a positive integer if str1 is _numerically_ greater than str2. * The result is zero if the strings are _numerically_ equal. */ fun compareVersions(str1: String, str2: String): Int { if (str1.isBlank() || str2.isBlank()) { throw IllegalArgumentException("Invalid Version") } val vals1 = str1.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val vals2 = str2.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() var i = 0 // set index to first non-equal ordinal or length of shortest version string while (i < vals1.size && i < vals2.size && vals1[i] == vals2[i]) { i++ } // compare first non-equal ordinal number return run { // compare first non-equal ordinal number if (i < vals1.size && i < vals2.size) { vals1[i].toInt().compareTo(vals2[i].toInt()) } else { // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" vals1.size - vals2.size } }.sign } }
7
Kotlin
3
24
881de796fbbe835c74f69f36ccf327bdcb0029f3
1,942
skeletoid
MIT License
src/main/kotlin/at2020/day1/At2020Day1KTS.kt
JeanBarbosa27
575,328,729
false
{"Kotlin": 10872}
package at2020.day1 import java.io.File class At2020Day1KTS { private val numbers = File("src/main/kotlin/at2020/day1/expense-report.txt").readLines().map(String::toInt) private fun partOneEasiestWay(targetSum: Int) { for(firstNumber in numbers) { for (secondNumber in numbers) { if(firstNumber + secondNumber == targetSum) { println("numbers that sum $targetSum: $firstNumber, $secondNumber") println("product from them: ${firstNumber * secondNumber}") return } } } } private fun partTwoEasiestWay(targetSum: Int) { for (firstNumber in numbers) { for (secondNumber in numbers) { for (thirdNumber in numbers) { if (firstNumber + secondNumber + thirdNumber == targetSum) { println("numbers that sum $targetSum: $firstNumber, $secondNumber, $thirdNumber") println("product from them: ${firstNumber * secondNumber * thirdNumber}") return } } } } } private fun List<Int>.partOneEfficientWay(targetSum: Int): Pair<Int, Int>? { return firstNotNullOfOrNull { number -> associateBy { targetSum - it }[number]?.let { complement -> Pair(complement, number) } } } private fun List<Int>.partTwoEfficientWay(targetSum: Int): Triple<Int, Int, Int>? { return firstNotNullOfOrNull { thirdElement -> partOneEfficientWay(targetSum - thirdElement)?.let { pair -> Triple(pair.first, pair.second, thirdElement) } } } fun execute () { val targetSum = 2020 val pair = numbers.partOneEfficientWay(targetSum) val triple = numbers.partTwoEfficientWay(targetSum) println("Two numbers that sum $targetSum: $pair") println( pair?.let { (first, second) -> "Here is there product from these two numbers: ${first * second}" }) println("Three numbers that sum $targetSum: $triple") println(triple?.let { (first, second, third) -> "Here is there product from these three numbers: ${first * second * third}" }) } }
0
Kotlin
0
0
62c4e514cd9a306e6a4b5dbd0c146213f08e05f3
2,328
advent-of-code-solving-kotlin
MIT License
src/main/kotlin/com/github/asher_stern/parser/tree/TreeUtils.kt
asher-stern
109,838,279
false
null
package com.github.asher_stern.parser.tree import com.github.asher_stern.parser.grammar.NakedRule import com.github.asher_stern.parser.grammar.SyntacticItem import com.github.asher_stern.parser.utils.Array1 import java.util.* /** * Created by <NAME> on November-03 2017. */ fun <N, T> extractNakedRuleFromNode(content: N, children: List<TreeNode<N, T>>): NakedRule<N, T> = NakedRule(content, children.map { it.content }) fun <N, T> extractNakedRuleFromNode(node: TreeNode<N, T>): NakedRule<N, T> = extractNakedRuleFromNode(node.content.symbol!!, node.children) fun <N> mergeWordsToTree(sentence: Array1<String>, tree: TreeNode<N, String>): TreeNode<N, PosAndWord> { return WordsToTreeMerger(sentence, tree).merge() } fun <N> removeWordsFromTree(tree: TreeNode<N, PosAndWord>): TreeNode<N, String> = removeWordsOrPosFromTree(tree, true) fun <N> removePosFromTree(tree: TreeNode<N, PosAndWord>): TreeNode<N, String> = removeWordsOrPosFromTree(tree, false) fun <T> treeYield(tree: TreeNode<*, T>): List<T> { val ret = mutableListOf<T>() val stack = Stack<TreeNode<*, T>>() stack.push(tree) while (!stack.empty()) { val node = stack.pop() if (node.content.terminal != null) { ret.add(node.content.terminal) } else { for (child in node.children.asReversed()) { stack.push(child) } } } return ret } private fun <N> removeWordsOrPosFromTree(tree: TreeNode<N, PosAndWord>, wordOrPos: Boolean): TreeNode<N, String> { val content: SyntacticItem<N, String> = when { tree.content.symbol != null -> SyntacticItem.createSymbol(tree.content.symbol) else -> SyntacticItem.createTerminal( if (wordOrPos) tree.content.terminal!!.pos else tree.content.terminal!!.word) } return TreeNode(content, tree.children.map { removeWordsOrPosFromTree(it, wordOrPos) }.toMutableList()) } private class WordsToTreeMerger<N>(private val sentence: Array1<String>, private val tree: TreeNode<N, String>) { fun merge(): TreeNode<N, PosAndWord> = merge(tree) private fun merge(node: TreeNode<N, String>): TreeNode<N, PosAndWord> { if (node.content.terminal != null) { return TreeNode(SyntacticItem.createTerminal(PosAndWord(node.content.terminal, sentence[sentenceIndex++]))) } else { return TreeNode( SyntacticItem.createSymbol<N, PosAndWord>(node.content.symbol!!), node.children.map { merge(it) }.toMutableList() ) } } private var sentenceIndex: Int = 1 }
0
Kotlin
0
0
4d54f49eae47260a299ca375fc5442f002032116
2,708
parser
MIT License
q3/question3.kt
engividal
254,778,920
false
null
// 3. Check words with typos: // There are three types of typos that can be performed on strings: insert a character, // remove a character, or replace a character. Given two strings, write a function to // check if they are one typo (or zero typos) away. // Examples: // pale, ple ­> true // pales, pale ­> true // pale, bale ­> true // pale, bake ­> false // https://www.cuelogic.com/blog/the-levenshtein-algorithm fun main(args: Array<String>) { println(checkTypos("pale", "ple")) //true println(checkTypos("pales", "pale")) //true println(checkTypos("pale", "bale")) //true println(checkTypos("pale", "bake")) //false println(checkTypos("HONDA", "HYUNDAI")) //false } fun checkTypos(s: String, t: String): Boolean { // degenerate cases if (s == t) return true if (s == "") return false if (t == "") return false // create two integer arrays of distances and initialize the first one val v0 = IntArray(t.length + 1) { it } // previous val v1 = IntArray(t.length + 1) // current var cost: Int for (i in 0 until s.length) { // calculate v1 from v0 v1[0] = i + 1 for (j in 0 until t.length) { cost = if (s[i] == t[j]) 0 else 1 v1[j + 1] = Math.min(v1[j] + 1, Math.min(v0[j + 1] + 1, v0[j] + cost)) } // copy v1 to v0 for next iteration for (j in 0 .. t.length) v0[j] = v1[j] } if(v1[t.length]>1){ return false }else{ return true } }
0
Kotlin
0
0
930a76acd5e87c7083785772762be829b92bb917
1,517
code-challenge
MIT License
kt-fuzzy/src/commonMain/kotlin/ca.solostudios.fuzzykt/FuzzyKt.kt
solo-studios
420,274,115
false
{"Kotlin": 201452, "SCSS": 10556, "JavaScript": 3786, "FreeMarker": 2581}
/* * kt-fuzzy - A Kotlin library for fuzzy string matching * Copyright (c) 2021-2023 solonovamax <<EMAIL>> * * The file FuzzyKt.kt is part of kotlin-fuzzy * Last modified on 01-08-2023 10:18 p.m. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * KT-FUZZY IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package ca.solostudios.fuzzykt import ca.solostudios.stringsimilarity.normalized.NormalizedLevenshtein import kotlin.math.min public object FuzzyKt { private val normalizedLevenshtein = NormalizedLevenshtein() /** * The similarity ratio between the two strings. * * @param s1 * @param s2 * @return */ public fun ratio(s1: String, s2: String): Double { return normalizedLevenshtein.similarity(s1, s2) } /** * The ratio between the smallest of the two strings and the most similar substring. * (Longest common substring, adjusted to the same length as the shortest string.) * * @param s1 * @param s2 * @return */ public fun partialRatio(s1: String, s2: String): Double { val (shorter, longer) = if (s1.length > s2.length) s2 to s1 else s1 to s2 val (start, _) = longestCommonSubstring(s1, s2) val upperBound = min(start + shorter.length, longer.length) val lowerBound = upperBound - shorter.length val splitString = longer.substring(lowerBound, upperBound) return normalizedLevenshtein.similarity(splitString, shorter) } /** * Returns the start and end index of the longest common substring, * in reference to the first string passed. * * @param s1 * @param s2 * @return */ public fun longestCommonSubstring(s1: String, s2: String): Pair<Int, Int> { // black magic I took from google var max = 0 val dp = Array(s1.length) { IntArray(s2.length) } var endIndex = -1 for (i in s1.indices) { for (j in s2.indices) { if (s1[i] == s2[j]) { // If first row or column if (i == 0 || j == 0) { dp[i][j] = 1 } else { // Add 1 to the diagonal value dp[i][j] = dp[i - 1][j - 1] + 1 } if (max < dp[i][j]) { max = dp[i][j] endIndex = i } } } } // We want String upto endIndex, we are using endIndex+1 in substring. return (endIndex - max + 1) to (endIndex + 1) } }
2
Kotlin
0
5
b3ae4f9f0e15ee38feb81b0edd88cdad68124b21
3,623
kt-fuzzy
MIT License
src/day06/Day06.kt
skempy
572,602,725
false
{"Kotlin": 13581}
package day06 import readInputAsList fun main() { fun findMarker( input: List<String>, sizeOfPacket: Int, ): Int { return input.first() .windowed(sizeOfPacket) .indexOfFirst { packet -> packet.toSet().size == sizeOfPacket } + sizeOfPacket } fun part1(input: List<String>): Int { return findMarker(input, 4) } fun part2(input: List<String>): Int { return findMarker(input, 14) } // test if implementation meets criteria from the description, like: val testInput = readInputAsList("Day06", "_test") println("Test Part1: ${part1(testInput)}") check(part1(testInput) == 7) val input = readInputAsList("Day06") println("Actual Part1: ${part1(input)}") check(part1(input) == 1804) println("Test Part2: ${part2(testInput)}") check(part2(testInput) == 19) println("Actual Part2: ${part2(input)}") check(part2(input) == 2508) }
0
Kotlin
0
0
9b6997b976ea007735898083fdae7d48e0453d7f
960
AdventOfCode2022
Apache License 2.0
src/main/kotlin/adventofcode/day16/Volcano.kt
jwcarman
573,183,719
false
{"Kotlin": 183494}
/* * Copyright (c) 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package adventofcode.day16 import adventofcode.day16.Valve.Companion.parseGraph import adventofcode.util.graph.Graph class Volcano private constructor(graph: Graph<Valve, Unit>) { private val tunnels: Map<Valve, List<Tunnel>> private val numberOfFlowValves: Int private val valves: List<Valve> private val indexOf: Map<Valve, Int> init { val tmpTunnels = mutableMapOf<Valve, List<Tunnel>>() val start = Valve.start() val flowValves = graph.flowValves() populateTunnels(graph, start, flowValves, tmpTunnels) flowValves.forEach { from -> populateTunnels(graph, from, flowValves, tmpTunnels) } this.tunnels = tmpTunnels this.numberOfFlowValves = tunnels.size - 1 this.valves = tunnels.keys.sortedByDescending { it.flowRate } this.indexOf = valves.withIndex().associate { it.value to it.index } } fun flowValveSubsetPairs() = sequence { (0 until (1 shl valves.size - 1)).forEach { mask -> val inverse = mask.inv() and (1 shl valves.size-1).inv() yield(Pair( valves .filterIndexed { index, _ -> mask and (1 shl index) != 0 } .toSet(), valves .filterIndexed { index, _ -> inverse and (1 shl index) != 0 } .toSet() )) } } fun valves() = tunnels.keys.sortedBy { it.flowRate } fun tunnelsFrom(from: Valve) = tunnels.getOrDefault(from, listOf()) fun tunnelFrom(from: Valve, to: Valve): Tunnel = tunnelsFrom(from).first { it.to == to } private fun populateTunnels( graph: Graph<Valve, Unit>, from: Valve, flowValves: List<Valve>, tunnels: MutableMap<Valve, List<Tunnel>> ) { val shortestPaths = graph.shortestPaths(from) tunnels[from] = flowValves .filter { it != from } .map { Tunnel(from, it, shortestPaths.distanceTo(it).toInt()) } } companion object { fun parse(input: String): Volcano { return Volcano(parseGraph(input)) } } }
0
Kotlin
0
0
d6be890aa20c4b9478a23fced3bcbabbc60c32e0
2,734
adventofcode2022
Apache License 2.0
src/Day05.kt
petoS6
573,018,212
false
{"Kotlin": 14258}
fun main() { fun part1(input: List<String>): String { input.moves().forEach { move -> val crate = crates[move.second].takeLast(move.first).reversed() repeat(move.first) { crates[move.second].removeLast() } crates[move.third] = crates[move.third].apply { addAll(crate) } } return crates.joinToString("") { it.last() } } fun part2(input: List<String>): String { input.moves().forEach { move -> val crate = crates2[move.second].takeLast(move.first) repeat(move.first) { crates2[move.second].removeLast() } crates2[move.third] = crates2[move.third].apply { addAll(crate) } } return crates2.joinToString("") { it.last() } } val testInput = readInput("Day05.txt") println(part1(testInput)) println(part2(testInput)) } private val crates = mutableListOf( mutableListOf("Q","M","G","C","L"), mutableListOf("R","D","L","C","T","F","H","G"), mutableListOf("V","J","F","N","M","T","W","R"), mutableListOf("J","F","D","V","Q","P"), mutableListOf("N","F","M","S","L","B","T"), mutableListOf("R","N","V","H","C","D","P"), mutableListOf("H","C","T"), mutableListOf("G","S","J","V","Z","N","H","P"), mutableListOf("Z","F","H","G") ) private val crates2 = mutableListOf( mutableListOf("Q","M","G","C","L"), mutableListOf("R","D","L","C","T","F","H","G"), mutableListOf("V","J","F","N","M","T","W","R"), mutableListOf("J","F","D","V","Q","P"), mutableListOf("N","F","M","S","L","B","T"), mutableListOf("R","N","V","H","C","D","P"), mutableListOf("H","C","T"), mutableListOf("G","S","J","V","Z","N","H","P"), mutableListOf("Z","F","H","G") ) private fun List<String>.moves(): List<Triple<Int, Int, Int>> { return drop(10).map { val splitted = it.split(" ") Triple(splitted[1].toInt(), splitted[3].toInt() - 1, splitted[5].toInt() - 1) } }
0
Kotlin
0
0
40bd094155e664a89892400aaf8ba8505fdd1986
1,849
kotlin-aoc-2022
Apache License 2.0
classroom/src/main/kotlin/com/radix2/algorithms/week4/MaxPQ.kt
rupeshsasne
190,130,318
false
{"Java": 66279, "Kotlin": 50290}
package com.radix2.algorithms.week4 class MaxPQ<T : Comparable<T>>(capacity: Int) { private var array = Array<Comparable<Any>?>(capacity) { null } private var n = 0 companion object { @Suppress("UNCHECKED_CAST") fun <T : Comparable<T>> sort(array: Array<Comparable<T>>) { for (i in array.lastIndex / 2 downTo 0) { sink(array as Array<Comparable<Any>>, i, array.lastIndex) } var n = array.lastIndex while (n > 0) { exch(array as Array<Comparable<Any>>, 0, n) sink(array as Array<Comparable<Any>>, 0, n--) } } private fun sink(array: Array<Comparable<Any>>, k: Int, n: Int) { var trav = k while (2 * trav + 1 < n) { var j = 2 * trav + 1 if (j < n - 1 && less(array, j, j + 1)) j++ if (!less(array, trav, j)) break exch(array, trav, j) trav = j } } private fun swim(array: Array<Comparable<Any>>, k: Int) { var trav = k while (trav > 0 && less(array,trav / 2, trav)) { exch(array, trav, trav / 2) trav /= 2 } } private fun exch(array: Array<Comparable<Any>>, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } private fun less(array: Array<Comparable<Any>>, lhs: Int, rhs: Int): Boolean = array[lhs] < array[rhs] } @Suppress("UNCHECKED_CAST") fun add(t: T) { array[n++] = t as Comparable<Any> swim(array as Array<Comparable<Any>>, n - 1) } @Suppress("UNCHECKED_CAST") fun deleteMax(): T { val key = array[0] exch(array as Array<Comparable<Any>>,0, --n) sink(array as Array<Comparable<Any>>,0, n) array[n] = null return key as T } fun size() = n override fun toString(): String = array.filter { it != null }.joinToString() } fun main(args: Array<String>) { val maxPQ = MaxPQ<Int>(20) val list = mutableListOf(9, 2, 3, 8, 1, 10, 6, 17, 5, 16, 18, 12, 14, 11, 15, 20, 7, 4, 19, 13) for (i in 0 until 20) { maxPQ.add(list[i]) } println(maxPQ) val array: Array<Comparable<Int>> = list.toTypedArray() MaxPQ.sort(array) println(array.joinToString()) }
0
Java
0
1
341634c0da22e578d36f6b5c5f87443ba6e6b7bc
2,468
coursera-algorithms-part1
Apache License 2.0
2021/src/test/kotlin/Day16.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.test.Test import kotlin.test.assertEquals class Day16 { @Test fun `run part 01`() { val bits = getTransmissionBits() val version = getPacket(bits).first assertEquals(960, version) } @Test fun `run part 02`() { val bits = getTransmissionBits() val value = getPacket(bits).second assertEquals(12301926782560, value) } private fun getPacket(bits: String, idx: Int = 0): Triple<Long, Long, Int> { var idx1 = idx var version = getVersion(bits, idx1).also { idx1 += it.second }.first val label = getType(bits, idx1).also { idx1 += it.second }.first val value = if (label != 4) execOperation(bits, idx1, label) .also { version += it.second idx1 += it.third } .first else getLiteral(bits, idx1).also { idx1 += it.second }.first return version to value to idx1 - idx } private fun getVersion(bits: String, idx: Int) = bits .substring(idx until idx + 3).toLong(2) to 3 private fun getType(bits: String, idx: Int) = bits .substring(idx until idx + 3).toInt(2) to 3 private fun execOperation(bits: String, idx: Int, op: Int): Triple<Long, Long, Int> { var idx1 = idx val packets = mutableListOf<Pair<Long, Long>>() val (lengthIsNumberOfBits, length, _) = getLength(bits, idx1).also { idx1 += it.third } if (lengthIsNumberOfBits) { val end = idx1 + length while (idx1 < end) packets += getPacket(bits, idx1).also { idx1 += it.third } .let { it.first to it.second } } else repeat(length) { _ -> packets += getPacket(bits, idx1).also { idx1 += it.third } .let { it.first to it.second } } val value = when (op) { 0 -> packets.sumOf { it.second } 1 -> packets.fold(1L) { acc, it -> acc * it.second } 2 -> packets.minOf { it.second } 3 -> packets.maxOf { it.second } 5 -> if (packets.first().second > packets.last().second) 1 else 0 6 -> if (packets.first().second < packets.last().second) 1 else 0 7 -> if (packets.first().second == packets.last().second) 1 else 0 else -> throw IllegalStateException() } return value to packets.sumOf { it.first } to idx1 - idx } private fun getLength(bits: String, idx: Int): Triple<Boolean, Int, Int> { val length = if (bits[idx] == '0') 16 else 12 return (bits[idx] == '0') to bits.substring(idx.inc() until idx + length).toInt(2) to length } private fun getLiteral(bits: String, idx: Int): Pair<Long, Int> { var idx1 = idx var literal = "" var hasNext = true while (hasNext) hasNext = getLiteralGroup(bits, idx1) .also { literal += it.second idx1 += it.third } .first return literal.toLong(2) to idx1 - idx } private fun getLiteralGroup(bits: String, idx: Int) = bits.substring(idx until idx + 5) .let { (it[0] == '1') to it.substring(1) to 5 } private fun getTransmissionBits() = Util.getInputAsString("day16-input.txt") .toList() .joinToString("") { it .toString() .toInt(16) .toString(2) .padStart(4, '0') } infix fun <X : Pair<A, B>, A, B, C> X.to(that: C) = Triple(this.first, this.second, that) }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
3,745
adventofcode
MIT License
2019/DEC02/src/main/kotlin/day2/App.kt
PeteShepley
318,600,713
false
{"Java": 34659, "Swift": 17998, "Kotlin": 13744, "JavaScript": 11010, "Python": 10738, "Ruby": 9264, "Groovy": 7165, "TypeScript": 6589, "Clojure": 5976, "C#": 5078, "Lua": 4960, "Pascal": 2496, "Go": 2408, "Rust": 2219, "CMake": 1776, "C++": 776, "C": 640, "Shell": 131}
package day2 class Computer(val program: Array<Int>) { private var pointer: Int = 0 fun execute() { while (pointer < program.size) { when (program[pointer]) { 1 -> { add() pointer += 4 } 2 -> { mult() pointer += 4 } 99 -> pointer = program.size } } } override fun toString(): String { return program.joinToString(" ") } private fun add() { val op1 = program[program[pointer + 1]] val op2 = program[program[pointer + 2]] val loc = program[pointer + 3] program[loc] = op1 + op2 } private fun mult() { val op1 = program[program[pointer + 1]] val op2 = program[program[pointer + 2]] val loc = program[pointer + 3] program[loc] = op1 * op2 } } fun copyOfProgram(): Array<Int> { return arrayOf(1, 0, 0, 3, 1, 1, 2, 3, 1, 3, 4, 3, 1, 5, 0, 3, 2, 1, 10, 19, 1, 6, 19, 23, 2, 23, 6, 27, 2, 6, 27, 31, 2, 13, 31, 35, 1, 10, 35, 39, 2, 39, 13, 43, 1, 43, 13, 47, 1, 6, 47, 51, 1, 10, 51, 55, 2, 55, 6, 59, 1, 5, 59, 63, 2, 9, 63, 67, 1, 6, 67, 71, 2, 9, 71, 75, 1, 6, 75, 79, 2, 79, 13, 83, 1, 83, 10, 87, 1, 13, 87, 91, 1, 91, 10, 95, 2, 9, 95, 99, 1, 5, 99, 103, 2, 10, 103, 107, 1, 107, 2, 111, 1, 111, 5, 0, 99, 2, 14, 0, 0) } fun main(args: Array<String>) { for (noun in 0..99) { print('*') for (verb in 0..99) { print('.') val testProgram = copyOfProgram() testProgram[1] = noun testProgram[2] = verb val comp = Computer(testProgram) comp.execute() if (comp.program[0] == 19690720) { println("Noun: $noun Verb: $verb") } } } }
0
Java
0
0
f9679c17054e7d74b9cb3d1f11cef722aa1df0ec
1,658
advent-of-code
MIT License
src/Day01.kt
StrixG
572,554,618
false
{"Kotlin": 2622}
fun main() { fun part1(input: List<String>): Int { var calories = 0 var maxCalories = 0 for (line: String in input) { if (line.isBlank()) { if (calories > maxCalories) { maxCalories = calories } calories = 0 } else { calories += line.toInt() } } return maxCalories } fun part2(input: List<String>): Int { val allCalories = mutableListOf<Int>() var calories = 0 for (line: String in input) { if (line.isBlank()) { allCalories.add(calories) calories = 0 } else { calories += line.toInt() } } return allCalories.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
85f2f28197ad54d8c4344470f0ba80307b068680
1,089
advent-of-code-2022
Apache License 2.0
src/main/aoc2021/Day18.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2021 import java.util.* /** * Uses a linked list of Tokens as a representation of snailfish numbers. Operations such as * add, explode and split modifies the linked list given as (first) argument. */ class Day18(input: List<String>) { sealed interface Token { data object Open : Token data object Close : Token data object Separator : Token // Separators are not really needed, but they make testing and debugging easier data class Value(val value: Int) : Token companion object { fun tokenFor(char: Char) = when (char) { '[' -> Open ']' -> Close ',' -> Separator else -> Value(char - '0') // Allows for chars with value higher than 10 (used in a few tests) } fun stringify(token: Token): String { return when (token) { Close -> "]" Open -> "[" Separator -> "," is Value -> "${'0' + token.value}" } } } } private val homework = input.map { parse(it) } fun parse(str: String) = LinkedList(str.map { Token.tokenFor(it) }) // Used by tests to compare results against what's given in the problem description fun stringify(input: LinkedList<Token>) = input.joinToString("") { Token.stringify(it) } operator fun LinkedList<Token>.plus(other: LinkedList<Token>) = apply { add(0, Token.Open) add(Token.Separator) addAll(other) add(Token.Close) // Adding two numbers always triggers a reduction while (explode(this) || split(this)) Unit // Keep exploding and splitting until fully reduced } // Adds 'toAdd' to the first regular number in the given range private fun addToFirstRegularNumber(number: LinkedList<Token>, range: IntProgression, toAdd: Int) { for (j in range) { val curr = number[j] if (curr is Token.Value) { number[j] = Token.Value(curr.value + toAdd) return } } } // returns true if an explosion was triggered fun explode(number: LinkedList<Token>): Boolean { var nesting = 0 for (i in number.indices) { when (number[i]) { Token.Open -> nesting++ Token.Close -> nesting-- else -> Unit } if (nesting == 5) { // Need to explode. At this nesting level there are only two real numbers and no pairs // Left value is added to first regular number to the left val left = (number[i + 1] as Token.Value).value addToFirstRegularNumber(number, i - 1 downTo 0, left) // Right value is added to first regular number to the right val right = (number[i + 3] as Token.Value).value addToFirstRegularNumber(number, i + 5 until number.size, right) repeat(5) { number.removeAt(i) } // Remove the current pair number.add(i, Token.Value(0)) // and insert 0 in its place return true } } return false } // returns true if the number was split fun split(number: LinkedList<Token>): Boolean { for (i in number.indices) { val token = number[i] if (token is Token.Value && token.value >= 10) { val l = token.value / 2 val r = token.value - l number.removeAt(i) number.addAll(i, listOf(Token.Open, Token.Value(l), Token.Separator, Token.Value(r), Token.Close)) return true } } return false } private fun LinkedList<Token>.calculateMagnitude(): Int { val stack = mutableListOf<MutableList<Int>>() for (i in indices) { when (val ch = get(i)) { Token.Open -> stack.add(mutableListOf()) Token.Close -> { val (left, right) = stack.removeLast() val magnitude = 3 * left + 2 * right if (stack.isEmpty()) { return magnitude } stack.last().add(magnitude) } is Token.Value -> stack.last().add(ch.value) Token.Separator -> Unit } } return -1 } fun doHomework() = homework.reduce { acc, next -> acc + next } fun solvePart1(): Int { return doHomework().calculateMagnitude() } fun solvePart2(): Int { return sequence { for (i in homework.indices) { for (j in homework.indices) { if (i != j) { // create a copy to avoid modifying the homework val copy = LinkedList(homework[i].toMutableList()) yield((copy + homework[j]).calculateMagnitude()) } } } }.maxOf { it } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
5,144
aoc
MIT License
src/main/kotlin/days/Day8.kt
andilau
726,429,411
false
{"Kotlin": 37060}
package days @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2023/day/8", date = Date(day = 8, year = 2023) ) class Day8(input: List<String>) : Puzzle { private val instructions: String = input.first() private val routeFromTo: Map<String, Pair<String, String>> = input.drop(2).associate { val (from, to) = it.split(" = ") val pair = to.subSequence(1, to.lastIndex).split(", ").let { it[0] to it[1] } from to pair } override fun partOne(): Int = steps("AAA") override fun partTwo(): Long = routeFromTo .keys.filter { it.endsWith('A') } .map { steps(it).toLong() } .reduce { a, b -> lcm(a, b) } private fun steps(from: String) = instructions().runningFold(from) { position, direction -> when (direction) { 'L' -> routeFromTo.getValue(position).first 'R' -> routeFromTo.getValue(position).second else -> error("Should not happen: $direction") } }.takeWhile { !it.endsWith('Z') }.count() private fun instructions() = sequence { while (true) instructions.forEach { yield(it) } } }
3
Kotlin
0
0
9a1f13a9815ab42d7fd1d9e6048085038d26da90
1,184
advent-of-code-2023
Creative Commons Zero v1.0 Universal
utility/src/main/java/org/oppia/android/util/math/PolynomialExtensions.kt
oppia
148,093,817
false
{"Kotlin": 12174721, "Starlark": 666467, "Java": 33231, "Shell": 12716}
package org.oppia.android.util.math import org.oppia.android.app.model.Fraction import org.oppia.android.app.model.Polynomial import org.oppia.android.app.model.Polynomial.Term import org.oppia.android.app.model.Polynomial.Term.Variable import org.oppia.android.app.model.Real /** Represents a single-term constant polynomial with the value of 0. */ val ZERO_POLYNOMIAL: Polynomial = createConstantPolynomial(ZERO) /** Represents a single-term constant polynomial with the value of 1. */ val ONE_POLYNOMIAL: Polynomial = createConstantPolynomial(ONE) private val POLYNOMIAL_VARIABLE_COMPARATOR by lazy { createVariableComparator() } private val POLYNOMIAL_TERM_COMPARATOR by lazy { createTermComparator() } /** Returns whether this polynomial is a constant-only polynomial (contains no variables). */ fun Polynomial.isConstant(): Boolean = termCount == 1 && getTerm(0).variableCount == 0 /** * Returns the first term coefficient from this polynomial. This corresponds to the whole value of * the polynomial iff isConstant() returns true, otherwise this value isn't useful. * * Note that this function can throw if the polynomial is empty (so isConstant() should always be * checked first). */ fun Polynomial.getConstant(): Real = getTerm(0).coefficient /** * Returns a human-readable, plaintext representation of this [Polynomial]. * * The returned string is guaranteed to be a syntactically correct algebraic expression representing * the polynomial, e.g. "1+x-7x^2"). */ fun Polynomial.toPlainText(): String { return termList.map { it.toPlainText() }.reduce { ongoingPolynomialStr, termAnswerStr -> if (termAnswerStr.startsWith("-")) { "$ongoingPolynomialStr - ${termAnswerStr.drop(1)}" } else "$ongoingPolynomialStr + $termAnswerStr" } } /** * Returns a version of this [Polynomial] with all zero-coefficient terms removed. * * This function guarantees that the returned polynomial have at least 1 term (even if it's just the * constant zero). */ fun Polynomial.removeUnnecessaryVariables(): Polynomial { return Polynomial.newBuilder().apply { addAllTerm( [email protected] { term -> !term.coefficient.isApproximatelyZero() } ) }.build().ensureAtLeastConstant() } /** * Returns a version of this [Polynomial] with all rational coefficients potentially simplified to * integer terms. * * A rational coefficient can be simplified iff: * - It has no fractional representation (which includes zero fraction cases). * - It has a denominator of 1 (which represents a whole number, even for improper fractions). */ fun Polynomial.simplifyRationals(): Polynomial { return Polynomial.newBuilder().apply { addAllTerm( [email protected] { term -> term.toBuilder().apply { coefficient = term.coefficient.maybeSimplifyRationalToInteger() }.build() } ) }.build() } /** * Returns a sorted version of this [Polynomial]. * * The returned version guarantees a repeatable and deterministic order that prioritizes variables * earlier in the alphabet (or have lower lexicographical order), and have higher powers. Some * examples: * - 'x' will appear before '1'. * - 'x^2' will appear before 'x'. * - 'x' will appear before 'y'. * - 'xy' will appear before 'x' and 'y'. * - 'x^2y' will appear before 'xy^2', but after 'x^2y^2'. * - 'xy^2' will appear before 'xy'. */ fun Polynomial.sort(): Polynomial = Polynomial.newBuilder().apply { // The double sorting here is less efficient, but it ensures both terms and variables are // correctly kept sorted. Fortunately, most internal operations will keep variables sorted by // default. addAllTerm( [email protected] { term -> Term.newBuilder().apply { coefficient = term.coefficient addAllVariable(term.variableList.sortedWith(POLYNOMIAL_VARIABLE_COMPARATOR)) }.build() }.sortedWith(POLYNOMIAL_TERM_COMPARATOR) ) }.build() /** * Returns whether this [Polynomial] approximately equals an other, that is, that the polynomial has * the exact same terms and approximately equal coefficients (see [Real.isApproximatelyEqualTo]). * * This function assumes that both this and the other [Polynomial] are sorted before checking for * equality (i.e. via [sort]). */ fun Polynomial.isApproximatelyEqualTo(other: Polynomial): Boolean { if (termCount != other.termCount) return false // Terms can be zipped since they should be sorted prior to checking equivalence. return termList.zip(other.termList).all { (first, second) -> first.isApproximatelyEqualTo(second) } } /** * Returns the negated version of this [Polynomial] such that the original polynomial plus the * negative version would yield zero. */ operator fun Polynomial.unaryMinus(): Polynomial { // Negating a polynomial just requires flipping the signs on all coefficients. return toBuilder() .clearTerm() .addAllTerm(termList.map { it.toBuilder().setCoefficient(-it.coefficient).build() }) .build() } /** * Returns the sum of this [Polynomial] with [rhs]. * * The returned polynomial is guaranteed to: * - Have all like terms combined. * - Have simplified rational coefficients (per [simplifyRationals]. * - Have no zero coefficients (unless the entire polynomial is zero, in which case just 1). */ operator fun Polynomial.plus(rhs: Polynomial): Polynomial { // Adding two polynomials just requires combining their terms lists (taking into account combining // common terms). return Polynomial.newBuilder().apply { addAllTerm([email protected] + rhs.termList) }.build().combineLikeTerms().simplifyRationals().removeUnnecessaryVariables() } /** * Returns the subtraction of [rhs] from this [Polynomial]. * * The returned polynomial, when added with [rhs], will always equal the original polynomial. * * The returned polynomial has the same guarantee as those returned from [Polynomial.plus]. */ operator fun Polynomial.minus(rhs: Polynomial): Polynomial { // a - b = a + -b return this + -rhs } /** * Returns the product of this [Polynomial] with [rhs]. * * This will correctly cross-multiply terms, for example: (1+x)*(1-x) will become 1-x^2. * * The returned polynomial has the same guarantee as those returned from [Polynomial.plus]. */ operator fun Polynomial.times(rhs: Polynomial): Polynomial { // Polynomial multiplication is simply multiplying each term in one by each term in the other. val crossMultipliedTerms = termList.flatMap { leftTerm -> rhs.termList.map { rightTerm -> leftTerm * rightTerm } } // Treat each multiplied term as a unique polynomial, then add them together (so that like terms // can be properly combined). Finally, ensure unnecessary variables are eliminated (especially for // cases where no addition takes place, such as 0*x). return crossMultipliedTerms.map { createSingleTermPolynomial(it) }.reduce(Polynomial::plus).simplifyRationals().removeUnnecessaryVariables() } /** * Returns the division of [rhs] from this [Polynomial], or null if there's a remainder after * attempting the division. * * If this function returns non-null, it's guaranteed that the quotient times the divisor will yield * the dividend. * * The returned polynomial has the same guarantee as those returned from [Polynomial.plus]. */ operator fun Polynomial.div(rhs: Polynomial): Polynomial? { // See https://en.wikipedia.org/wiki/Polynomial_long_division#Pseudocode for reference. if (rhs.isApproximatelyZero()) { return null // Dividing by zero is invalid and thus cannot yield a polynomial. } var quotient = ZERO_POLYNOMIAL var remainder = this val leadingDivisorTerm = rhs.getLeadingTerm() ?: return null val divisorVariable = leadingDivisorTerm.highestDegreeVariable() val divisorVariableName = divisorVariable?.name val divisorDegree = leadingDivisorTerm.highestDegree() while (!remainder.isApproximatelyZero() && (remainder.getDegree() ?: return null) >= divisorDegree ) { // Attempt to divide the leading terms (this may fail). Note that the leading term should always // be based on the divisor variable being used (otherwise subsequent division steps will be // inconsistent and potentially fail to resolve). val remainingLeadingTerm = remainder.getLeadingTerm(matchedVariable = divisorVariableName) val newTerm = remainingLeadingTerm?.div(leadingDivisorTerm) ?: return null quotient += newTerm.toPolynomial() remainder -= newTerm.toPolynomial() * rhs } // Either the division was exact, or the remainder is a polynomial (i.e. a failed division). return quotient.takeIf { remainder.isApproximatelyZero() } } /** * Returns the [Polynomial] that represents this [Polynomial] raised to [exp], or null if the result * is not a valid polynomial or if a proper polynomial could not be kept along the way. * * This function will fail in a number of cases, including: * - If [exp] is not a constant polynomial. * - If this polynomial has more than one term (since that requires factoring). * - If the result would yield a polynomial with a negative power. * * The returned polynomial has the same guarantee as those returned from [Polynomial.plus]. */ infix fun Polynomial.pow(exp: Polynomial): Polynomial? { // Polynomial exponentiation is only supported if the right side is a constant polynomial, // otherwise the result cannot be a polynomial (though could still be compared to another // expression by utilizing sampling techniques). return if (exp.isConstant()) { pow(exp.getConstant())?.simplifyRationals()?.removeUnnecessaryVariables() } else null } private fun createConstantPolynomial(constant: Real): Polynomial = createSingleTermPolynomial(Term.newBuilder().setCoefficient(constant).build()) private fun createSingleTermPolynomial(term: Term): Polynomial = Polynomial.newBuilder().apply { addTerm(term) }.build() private fun Term.toPlainText(): String { val productValues = mutableListOf<String>() // Include the coefficient if there is one (coefficients of 1 are ignored only if there are // variables present). productValues += when { variableList.isEmpty() || !abs(coefficient).isApproximatelyEqualTo(1.0) -> when { coefficient.isRational() && variableList.isNotEmpty() -> "(${coefficient.toPlainText()})" else -> coefficient.toPlainText() } coefficient.isNegative() -> "-" else -> "" } // Include any present variables. productValues += variableList.map(Variable::toPlainText) // Take the product of all relevant values of the term. return productValues.joinToString(separator = "") } private fun Variable.toPlainText(): String { return if (power > 1) "$name^$power" else name } private fun Polynomial.combineLikeTerms(): Polynomial { // The following algorithm is expected to grow in space by O(N*M) and in time by O(N*m*log(m)) // where N is the total number of terms, M is the total number of variables, and m is the largest // single count of variables among all terms (this is assuming constant-time insertion for the // underlying hashtable). val newTerms = termList.groupBy { it.variableList.sortedWith(POLYNOMIAL_VARIABLE_COMPARATOR) }.mapValues { (_, coefficientTerms) -> coefficientTerms.map { it.coefficient } }.mapNotNull { (variables, coefficients) -> // Combine like terms by summing their coefficients. val newCoefficient = coefficients.reduce(Real::plus) return@mapNotNull if (!newCoefficient.isApproximatelyZero()) { Term.newBuilder().apply { coefficient = newCoefficient // Remove variables with zero powers (since they evaluate to '1'). addAllVariable(variables.filter { variable -> variable.power != 0 }) }.build() } else null // Zero terms should be removed. } return Polynomial.newBuilder().apply { addAllTerm(newTerms) }.build().ensureAtLeastConstant() } private fun Term.isApproximatelyEqualTo(other: Term): Boolean { // The variable lists can be exactly matched since they're sorted. return coefficient.isApproximatelyEqualTo(other.coefficient) && variableList == other.variableList } private fun Polynomial.pow(exp: Real): Polynomial? { val shouldBeInverted = exp.isNegative() val positivePower = if (shouldBeInverted) -exp else exp val exponentiation = when { // Constant polynomials can be raised by any constant. isConstant() -> (getConstant() pow positivePower)?.let { createConstantPolynomial(it) } // Polynomials can only be raised to positive integers (or zero). exp.isWholeNumber() -> exp.asWholeNumber()?.let { pow(it) } // Polynomials can potentially be raised by a fractional power. exp.isRational() -> pow(exp.rational) // All other cases require factoring most likely will not compute to polynomials (such as // irrational exponents). else -> null } return if (shouldBeInverted) { val onePolynomial = ONE_POLYNOMIAL // Note that this division is guaranteed to fail if the exponentiation result is a polynomial. // Future implementations may leverage root-finding algorithms to factor for integer inverse // powers (such as square root, cubic root, etc.). Non-integer inverse powers will require // sampling. exponentiation?.let { onePolynomial / it } } else exponentiation } private fun Polynomial.pow(rational: Fraction): Polynomial? { // Polynomials with addition require factoring. return if (isSingleTerm()) { termList.first().pow(rational)?.toPolynomial() } else null } private fun Polynomial.pow(exp: Int): Polynomial { // Anything raised to the power of 0 is 1. if (exp == 0) return ONE_POLYNOMIAL if (exp == 1) return this var newValue = this for (i in 1 until exp) newValue *= this return newValue } private operator fun Term.times(rhs: Term): Term { // The coefficients are always multiplied. val combinedCoefficient = coefficient * rhs.coefficient // Next, create a combined list of new variables. val combinedVariables = variableList + rhs.variableList // Simplify the variables by combining the exponents of like variables. Start with a map of 0 // powers, then add in the powers of each variable and collect the final list of unique terms. val variableNamesMap = mutableMapOf<String, Int>() combinedVariables.forEach { variableNamesMap.compute(it.name) { _, power -> if (power != null) power + it.power else it.power } } val newVariableList = variableNamesMap.map { (name, power) -> Variable.newBuilder().setName(name).setPower(power).build() } return Term.newBuilder() .setCoefficient(combinedCoefficient) .addAllVariable(newVariableList) .build() } private operator fun Term.div(rhs: Term): Term? { val dividendPowerMap = variableList.toPowerMap() val divisorPowerMap = rhs.variableList.toPowerMap() // If any variables are present in the divisor and not the dividend, this division won't work // effectively. if (!dividendPowerMap.keys.containsAll(divisorPowerMap.keys)) return null // Division is simply subtracting the powers of terms in the divisor from those in the dividend. val quotientPowerMap = dividendPowerMap.mapValues { (name, power) -> power - divisorPowerMap.getOrDefault(name, defaultValue = 0) } // If there are any negative powers, the divisor can't effectively divide this value. if (quotientPowerMap.values.any { it < 0 }) return null // Remove variables with powers of 0 since those have been fully divided. Also, divide the // coefficients to finish the division. return Term.newBuilder() .setCoefficient(coefficient / rhs.coefficient) .addAllVariable(quotientPowerMap.filter { (_, power) -> power > 0 }.toVariableList()) .build() } private fun Term.pow(rational: Fraction): Term? { // Raising an exponent by an exponent just requires multiplying the two together. val newVariablePowers = variableList.map { variable -> variable.power.toWholeNumberFraction() * rational } // If any powers are not whole numbers then the rational is likely representing a root and the // term in question is not rootable to that degree. if (newVariablePowers.any { !it.isOnlyWholeNumber() }) return null val newCoefficient = coefficient pow Real.newBuilder().apply { this.rational = rational }.build() ?: return null return Term.newBuilder().apply { coefficient = newCoefficient addAllVariable( ([email protected] zip newVariablePowers).map { (variable, newPower) -> variable.toBuilder().apply { power = newPower.toWholeNumber() }.build() } ) }.build() } /** * Returns either this [Polynomial] or [ZERO_POLYNOMIAL] if this polynomial has no terms (i.e. the * returned polynomial is always guaranteed to have at least one term). */ private fun Polynomial.ensureAtLeastConstant(): Polynomial { return if (termCount != 0) this else ZERO_POLYNOMIAL } private fun Polynomial.isSingleTerm(): Boolean = termList.size == 1 private fun Polynomial.isApproximatelyZero(): Boolean = termList.all { it.coefficient.isApproximatelyZero() } // Zero polynomials only have 0 coefs. // Return the highest power to represent the degree of the polynomial. Reference: // https://www.varsitytutors.com/algebra_1-help/how-to-find-the-degree-of-a-polynomial. private fun Polynomial.getDegree(): Int? = getLeadingTerm()?.highestDegree() private fun Polynomial.getLeadingTerm(matchedVariable: String? = null): Term? { // Return the leading term. Reference: https://undergroundmathematics.org/glossary/leading-term. return termList.filter { term -> matchedVariable?.let { variableName -> term.variableList.any { it.name == variableName } } ?: true }.takeIf { it.isNotEmpty() }?.reduce { maxTerm, term -> val maxTermDegree = maxTerm.highestDegree() val termDegree = term.highestDegree() return@reduce if (termDegree > maxTermDegree) term else maxTerm } } private fun Term.highestDegreeVariable(): Variable? = variableList.maxByOrNull(Variable::getPower) private fun Term.highestDegree(): Int = highestDegreeVariable()?.power ?: 0 private fun Term.toPolynomial(): Polynomial { return Polynomial.newBuilder().addTerm(this).build() } private fun List<Variable>.toPowerMap(): Map<String, Int> { return associateBy({ it.name }, { it.power }) } private fun Map<String, Int>.toVariableList(): List<Variable> { return map { (name, power) -> Variable.newBuilder().setName(name).setPower(power).build() } } private fun Real.maybeSimplifyRationalToInteger(): Real = when (realTypeCase) { Real.RealTypeCase.RATIONAL -> { val improperRational = rational.toImproperForm() when { rational.isOnlyWholeNumber() -> { Real.newBuilder().apply { integer = [email protected]() }.build() } // Some fractions are effectively whole numbers. improperRational.denominator == 1 -> { Real.newBuilder().apply { integer = if (improperRational.isNegative) { -improperRational.numerator } else improperRational.numerator }.build() } else -> this } } // Nothing to do in these cases. Real.RealTypeCase.IRRATIONAL, Real.RealTypeCase.INTEGER, Real.RealTypeCase.REALTYPE_NOT_SET, null -> this } private fun createTermComparator(): Comparator<Term> { // First, sort by all variable names to ensure xy is placed ahead of xz. Then, sort by variable // powers in order of the variables (such that x^2y is ranked higher thank xy). Finally, sort by // the coefficient to ensure equality through the comparator works correctly (though in practice // like terms should always be combined). Note the specific reversing happening here. It's done in // this way so that sorted set bigger/smaller list is reversed (which matches expectations since // larger terms should appear earlier in the results). This is implementing an ordering similar to // https://en.wikipedia.org/wiki/Polynomial#Definition, except for multi-variable functions (where // variables of higher degree are preferred over lower degree by lexicographical order of variable // names). val reversedVariableComparator = POLYNOMIAL_VARIABLE_COMPARATOR.reversed() return compareBy<Term, Iterable<Variable>>( reversedVariableComparator::compareIterablesReversed, Term::getVariableList ).thenByDescending(REAL_COMPARATOR, Term::getCoefficient) } private fun createVariableComparator(): Comparator<Variable> { // Note that power is reversed because larger powers should actually be sorted ahead of smaller // powers for the same variable name (but variable name still takes precedence). This ensures // cases like x^2y+y^2x are sorted in that order. return compareBy(Variable::getName).thenByDescending(Variable::getPower) }
508
Kotlin
491
285
4a07d8db69e395c9e076c342c0d1dc3521ff3051
20,936
oppia-android
Apache License 2.0
src/Day04.kt
er453r
572,440,270
false
{"Kotlin": 69456}
fun main() { val inputLineRegex = """\d""".toRegex() fun lineToSets(line: String): Pair<Set<Int>, Set<Int>> { val (start1, end1, start2, end2) = inputLineRegex.findAll(line).map { it.value.toInt() }.toList() return Pair((start1..end1).toSet(), (start2..end2).toSet()) } fun part1(input: List<String>): Int = input .map(::lineToSets) .count { (a, b) -> a.containsAll(b) || b.containsAll(a) } fun part2(input: List<String>): Int = input .map(::lineToSets) .count { (a, b) -> a.intersect(b).isNotEmpty() } test( day = 4, testTarget1 = 2, testTarget2 = 4, part1 = ::part1, part2 = ::part2, ) }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
711
aoc2022
Apache License 2.0
2023/src/day09/Day09.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day09 import java.io.File fun main() { val input = File("src/day09/day09.txt").readLines() println(getSumOfSequence(input)) println(getSumOfSequence(input, false)) } fun getSumOfSequence(input: List<String>, next: Boolean = true) = input.map { it.split(" ").map { value -> value.toLong() } } .sumOf { intList -> getInSequence(intList, next) } fun getInSequence(input: List<Long>, next: Boolean = true): Long { // First get differences var lists = mutableListOf<MutableList<Long>>(input.toMutableList()) var currentList = lists.first() var differenceList = currentList.drop(1).mapIndexed { index: Int, i: Long -> i - currentList[index] } while (differenceList.any { it != 0L }) { currentList = differenceList.toMutableList() lists.add(currentList) differenceList = currentList.drop(1).mapIndexed { index: Int, i: Long -> i - currentList[index] } } lists.add(differenceList.toMutableList()) // OK, now, let's extrapolate while (lists.size > 1) { differenceList = lists.last() currentList = lists[lists.size - 2] if (next) { currentList.add(currentList.last() + differenceList.last()) } else { currentList.add(0, currentList.first() - differenceList.first()) } // now pop lists.remove(differenceList) } return if (next) { currentList.last() } else { currentList.first() } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
1,512
adventofcode
Apache License 2.0
src/Day07.kt
mhuerster
572,728,068
false
{"Kotlin": 24302}
fun main() { val cdRegex = "\\\$\\scd\\s(.*)".toRegex() // Captures directory to cd into, or `..` val directoryRegex = "dir\\s(\\w+)".toRegex() val fileNameRegex = "(\\d+)\\s(\\w+\\.?\\w*)".toRegex() val totalSpace = 70000000 val freeSpaceNeeded = 30000000 open class FakeFile(var name: String, var dirName: String = "/", var size: Int = 0) { constructor(rawFileName: String, dirName: String) : this("", dirName, 0) { val (parsedSize, parsedName) = fileNameRegex.find(rawFileName)!!.destructured this.name = parsedName this.size = parsedSize.toInt() } constructor(rawFileName: String) : this("", "/", 0) { val (parsedSize, parsedName) = fileNameRegex.find(rawFileName)!!.destructured this.name = parsedName this.size = parsedSize.toInt() } override fun toString(): String { return "- $name (file, size=$size)" } } class Directory( name: String, dirName: String = "/", var files: MutableList<FakeFile> = mutableListOf<FakeFile>() ) : FakeFile(name, dirName, 0) { init { for (file in files) { file.dirName = this.name } } fun size(): Int { return files.fold(0) { a, e -> a + e.size } } fun add(file: FakeFile): List<FakeFile> { file.dirName = this.name files.add(file) return files } fun printFiles(offset: Int = 0) { val indent = " ".repeat(offset) println("$indent- $name (dir)") for (file in files) { val newOffset = offset + 2 val newIndent = " ".repeat(newOffset) if (file is Directory) { file.printFiles(newOffset) } else { println("$newIndent$file") } } } fun sumFilesSizes(): Int { return files.fold(0) { totalSize, file -> if (file is Directory) { totalSize + file.sumFilesSizes() } else { totalSize + file.size } } } fun cappedSumFilesSizes(max: Int = Int.MAX_VALUE, topLevel: Boolean = true): Int { return files.fold(0) { totalSize, file -> if (file is Directory) { var dirSize = file.sumFilesSizes() if (dirSize <= max) { totalSize + dirSize + file.cappedSumFilesSizes(max, false) } else { totalSize + 0 + file.cappedSumFilesSizes(max, false) } } else { totalSize + 0 } } } // 8381165 fun dirSizes(size: Int) : List<Int> { return files.fold(listOf<Int>()) { dirs, file -> if (file is Directory) { val nestedSize = file.sumFilesSizes() dirs.plus(nestedSize).plus(file.dirSizes(size)) } else { dirs } }.filter { it > size } } } class Nav(var dirs: MutableList<Directory> = mutableListOf<Directory>()) { fun pwd() : Directory { return dirs.last() } fun reverse() : Nav { dirs.removeLast() return this } fun advance(dir: FakeFile) : Nav { dirs.add(dir as Directory) return this } fun cd(command: String) : Nav { val (input, destination) = cdRegex.find(command)!!.groupValues if (destination == "..") { return this.reverse() } else { val toDir = pwd().files.find { it.name == destination } if (toDir != null) { this.advance(toDir) } return this } } fun createDirFromTerminalOutput(line: String) : Nav { val (input, dirName) = directoryRegex.find(line)!!.groupValues this.pwd().add(Directory(dirName)) return(this) } fun createFileFromTerminalOutput(line: String) : Nav { val (input, size, fileName) = fileNameRegex.find(line)!!.groupValues val dirName = this.pwd().name this.pwd().add(FakeFile(fileName, dirName, size.toInt())) return(this) } } fun parseTerminalOutput(terminalOutput: List<String>): Directory { val root = Directory("/") val nav = Nav(mutableListOf<Directory>(root)) for (line in terminalOutput) { when { directoryRegex.matches(line) -> nav.createDirFromTerminalOutput(line) fileNameRegex.matches(line) -> nav.createFileFromTerminalOutput(line) cdRegex.matches(line) -> nav.cd(line) } } return root } val testInput = readInput("Day07_sample") val input = readInput("Day07") // test if implementation meets criteria from the description, like: val testFs = parseTerminalOutput(testInput) check(testFs.sumFilesSizes() == 48381165) check(testFs.cappedSumFilesSizes(100000) == 95437) // println(testFs.cappedSumFilesSizes(100000)) // println(testFs.dirSizes(100000).min()) // val currentFreeSpace = totalSpace - testFs.sumFilesSizes() // val spaceStillNeeded = freeSpaceNeeded - currentFreeSpace // check(spaceStillNeeded == 8381165) val fs = parseTerminalOutput(input) val currentFreeSpace = totalSpace - fs.sumFilesSizes() val spaceStillNeeded = freeSpaceNeeded - currentFreeSpace println(fs.dirSizes(spaceStillNeeded).min()) // println(fs.cappedSumFilesSizes(100000)) // println(fs.sumFilesSizes()) }
0
Kotlin
0
0
5f333beaafb8fe17ff7b9d69bac87d368fe6c7b6
5,946
2022-advent-of-code
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day10.kt
clechasseur
435,726,930
false
{"Kotlin": 315943}
package io.github.clechasseur.adventofcode2021 import io.github.clechasseur.adventofcode2021.data.Day10Data object Day10 { private val data = Day10Data.data fun part1(): Int = data.lines().map { Line(it).corruptionScore }.filter { it != 0 }.sum() fun part2(): Long { val autocompletedLines = data.lines().map { Line(it) }.filter { it.corruptionScore == 0 }.sortedBy { it.autocompleteScore } return autocompletedLines[autocompletedLines.size / 2].autocompleteScore } private val opposites = mapOf( '(' to ')', '[' to ']', '{' to '}', '<' to '>', ) private val corruptedScores = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137, ) private val autocompletedScores = mapOf( '(' to 1L, '[' to 2L, '{' to 3L, '<' to 4L, ) private data class Line(val content: String) { val corruptionScore: Int by lazy { var score = 0 val stack = ArrayDeque<Char>() for (c in content) { when (c) { '(', '[', '{', '<' -> stack.addLast(c) ')', ']', '}', '>' -> { val top = stack.removeLastOrNull() ?: error("Invalid line: $content") if (c != opposites[top]!!) { score = corruptedScores[c]!! break } } else -> error("Invalid character: $c in line: $content") } } score } val autocompleteScore: Long by lazy { require(corruptionScore == 0) { "To autocomplete a line, it must not be corrupted" } val stack = ArrayDeque<Char>() for (c in content) { when (c) { '(', '[', '{', '<' -> stack.addFirst(c) ')', ']', '}', '>' -> stack.removeFirstOrNull() ?: error("Invalid line: $content") else -> error("Invalid character: $c in line: $content") } } var score = 0L for (c in stack) { score *= 5L score += autocompletedScores[c]!! } score } } }
0
Kotlin
0
0
4b893c001efec7d11a326888a9a98ec03241d331
2,375
adventofcode2021
MIT License
kotlin/1129-shortest-path-with-alternating-colors.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun shortestAlternatingPaths(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray { val redAdj = Array(n) { ArrayList<Int>() } val blueAdj = Array(n) { ArrayList<Int>() } val redVisit = HashSet<Int>() val blueVisit = HashSet<Int>() for ((from, to) in redEdges) redAdj[from].add(to) for ((from, to) in blueEdges) blueAdj[from].add(to) val res = IntArray(n) { -1 } with (LinkedList<Pair<Int, Int>>()) { addFirst(0 to 0) var len = 0 while (isNotEmpty()) { repeat (size) { val (node, c) = removeLast() if (res[node] == -1) res[node] = len if (c != -1) { redAdj[node].forEach { if (it !in redVisit) { addFirst(it to -1) redVisit.add(it) } } } if (c != 1) { blueAdj[node].forEach { if (it !in blueVisit) { addFirst(it to 1) blueVisit.add(it) } } } } len++ } } return res } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,460
leetcode
MIT License
src/main/kotlin/co/csadev/advent2022/Day15.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 15 * Problem Description: http://adventofcode.com/2021/day/15 */ package co.csadev.advent2022 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Point2D import co.csadev.adventOfCode.Resources.resourceAsList import kotlin.math.max import kotlin.math.min class Day15(override val input: List<String> = resourceAsList("22day15.txt")) : BaseDay<List<String>, Int, Long> { private var sensors = mutableMapOf<Point2D, Point2D>() private var allPoints = mutableSetOf<Point2D>() private var minX: Int = Int.MAX_VALUE private var maxX: Int = Int.MIN_VALUE var p1Line = 2_000_000 var p2Max = 4000000L init { input.forEach { val (sensor, beacon) = it.split(":") val s = sensor.asPoint val b = beacon.asPoint allPoints.add(s) allPoints.add(b) sensors[s] = b } minX = sensors.minOf { (s, b) -> min(s.x, b.x) } maxX = sensors.maxOf { (s, b) -> max(s.x, b.x) } } // Arbitrary distance added to each side to ensure we don't miss anything. override fun solvePart1() = (minX - p1Line * 5..maxX + p1Line * 5).asSequence() .map { Point2D(it, p1Line) } .filter { it !in allPoints } .count { it.tooClose } override fun solvePart2() = sensors.mapNotNull { (s, b) -> scanOuter(s, s.distanceTo(b)) }.first() private val String.asPoint: Point2D get() = Point2D( substringBefore(",").substringAfter("=").toInt(), substringAfter("y=").toInt() ) private val Point2D.tooClose: Boolean get() = sensors.any { (s, b) -> distanceTo(s) <= s.distanceTo(b) } private val Point2D.isBeacon: Boolean get() = x in (0..p2Max) && y in (0..p2Max) && this !in allPoints && !tooClose private val explore = listOf(Point2D(1, 1), Point2D(-1, 1), Point2D(-1, -1), Point2D(1, -1)) @Suppress("unused") private fun scanOuter(s: Point2D, dist: Int): Long? { var cur = s + Point2D(0, -dist - 1) for (p in explore) for (step in 0..dist) { cur += p if (cur.isBeacon) { return (cur.x * 4_000_000L) + cur.y } } return null } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,326
advent-of-kotlin
Apache License 2.0
src/hongwei/leetcode/playground/leetcodecba/M56MergeIntervals.kt
hongwei-bai
201,601,468
false
{"Java": 143669, "Kotlin": 38875}
package hongwei.leetcode.playground.leetcodecba import hongwei.leetcode.playground.common.print import kotlin.experimental.or class M56MergeIntervals { fun test() { // val input = arrayOf(intArrayOf(1, 3), intArrayOf(2, 6), intArrayOf(8, 10), intArrayOf(15, 18)) // val input = arrayOf(intArrayOf(5, 6), intArrayOf(3, 3), intArrayOf(4, 4), intArrayOf(1, 2)) // val input = arrayOf(intArrayOf(1, 4), intArrayOf(4, 5)) val input = arrayOf(intArrayOf(1, 4), intArrayOf(5, 6)) // val input = arrayOf(intArrayOf(2, 3), intArrayOf(5, 5), intArrayOf(2, 2), intArrayOf(3, 4), intArrayOf(3, 4)) val output = merge(input) output.print() // testFillArray() // test // var a = YES // a = a or OPEN // println(a) } // companion object { // /* // open: 0x0001 // close: 0x0010 // point: ox0011 // mid: ox0111 // */ // private val NO: Byte = 0 // private const val OPEN: Byte = 1 // private const val CLOSE: Byte = 2 // private const val POINT: Byte = 3 // private const val YES: Byte = 7 // } companion object { /* point: 0x0001 open: 0x0011 close: 0x0101 mid: ox0111 */ private val NO: Byte = 0 private const val POINT: Byte = 1 private const val OPEN: Byte = 3 private const val CLOSE: Byte = 5 private const val YES: Byte = 7 } fun merge(intervals: Array<IntArray>): Array<IntArray> { val result = mutableListOf<IntArray>() val array = ByteArray(10000) { NO } intervals.forEach { val open = it[0] val close = it[1] println("================= round ==================") if (open == close) { array[open] = array[open] or POINT println("open==close: mark index[$open] to ${array[open]}") } else { println("($open ~ $close)") array[open] = array[open] or OPEN println("open!=close: mark index[$open] to ${array[open]}") array[close] = array[close] or CLOSE println("open!=close: mark index[$close] to ${array[close]}") if (open + 1 <= close) { array.fill(YES, open + 1, close) println("close > open + 1: mark {${open + 1} ~ ${close - 1}} as $YES") } } debug(array) } var savedStart = -1 array.forEachIndexed { i, value -> if (value == OPEN) { savedStart = i } else if (value == CLOSE) { result.add(intArrayOf(savedStart, i)) savedStart = -1 } else if (value == POINT) { result.add(intArrayOf(i, i)) } } return result.toTypedArray() } fun testFillArray() { val array = ByteArray(10) { 0 } array.fill(1, 1, 3) array.forEach { print("$it ") } } fun debug(a: ByteArray) { for (i in 0..20) { print("${a[i]} ") } println(" ") } } /* 56. Merge Intervals Medium 6507 358 Add to List Share Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. Constraints: 1 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti <= endi <= 104 Accepted 810,058 Submissions 1,977,511 */
0
Java
0
1
9d871de96e6b19292582b0df2d60bbba0c9a895c
3,949
leetcode-exercise-playground
Apache License 2.0
src/main/kotlin/advent/day2/Dive.kt
hofiisek
434,171,205
false
{"Kotlin": 51627}
package advent.day2 import advent.loadInput import java.io.File /** * @author <NAME> */ data class Position(val horizontalPos: Int = 0, val depth: Int = 0) data class PositionWithAim(val horizontalPos: Int = 0, val depth: Int = 0, val aim: Int = 0) sealed class Move(open val step: Int) data class Up(override val step: Int): Move(step) data class Down(override val step: Int): Move(step) data class Forward(override val step: Int): Move(step) infix fun Position.apply(move: Move) = when (move) { is Up -> copy(depth = depth - move.step) is Down -> copy(depth = depth + move.step) is Forward -> copy(horizontalPos = horizontalPos + move.step) } infix fun PositionWithAim.apply(move: Move) = when (move) { is Up -> copy(aim = aim - move.step) is Down -> copy(aim = aim + move.step) is Forward -> copy(horizontalPos = horizontalPos + move.step, depth = depth + (aim * move.step)) } fun part1(input: File) = input.readLines() .map { val (dir, step) = it.split(" ") when (dir) { "up" -> Up(step.toInt()) "down" -> Down(step.toInt()) "forward" -> Forward(step.toInt()) else -> throw IllegalArgumentException("Unknown direction: $dir") } }.fold(Position()) { currentPos, nextMove -> currentPos apply nextMove } .let { it.horizontalPos * it.depth } .also(::println) fun part2(input: File) = input.readLines() .map { val (dir, step) = it.split(" ") when (dir) { "up" -> Up(step.toInt()) "down" -> Down(step.toInt()) "forward" -> Forward(step.toInt()) else -> throw IllegalArgumentException("Unknown direction: $dir") } }.fold(PositionWithAim()) { currentPos, nextMove -> currentPos apply nextMove } .let { it.horizontalPos * it.depth } .also(::println) fun main() { with(loadInput(day = 2)) { part1(this) part2(this) } }
0
Kotlin
0
2
3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb
1,981
Advent-of-code-2021
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[96]不同的二叉搜索树.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import javax.swing.tree.TreeNode //给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。 // // // // 示例 1: // // //输入:n = 3 //输出:5 // // // 示例 2: // // //输入:n = 1 //输出:1 // // // // // 提示: // // // 1 <= n <= 19 // // Related Topics 树 二叉搜索树 数学 动态规划 二叉树 // 👍 1384 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun numTrees(n: Int): Int { //动态规划 //将 1……(i−1) 序列作为左子树,将 (i+1)……n作为右子树 var intArray = IntArray(n + 1) intArray[0] =1 intArray[1] = 1 for (i in 2..n){ for (j in 1..i){ intArray[i] += intArray[j-1]*intArray[i-j] } } return intArray[n] } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,027
MyLeetCode
Apache License 2.0
src/Day02.kt
AlaricLightin
572,897,551
false
{"Kotlin": 87366}
fun main() { fun part1(inputFilename: String): Int { var result = 0 getInputFile(inputFilename).forEachLine { if (it.isBlank()) return@forEachLine val first = it[0] val second = it[2] result += (when (second) { 'X' -> 1 'Y' -> 2 else -> 3 } + when { first - 'A' == second - 'X' -> 3 (first == 'A' && second == 'Y') || (first == 'B' && second == 'Z') || (first == 'C' && second == 'X') -> 6 else -> 0 }) } return result } fun part2(inputFilename: String): Int { var result = 0 getInputFile(inputFilename).forEachLine { if (it.isBlank()) return@forEachLine val first = it[0] val second = it[2] result += when (second) { 'X' -> when (first) { 'A' -> 3 'B' -> 1 else -> 2 } 'Y' -> 3 + when(first) { 'A' -> 1 'B' -> 2 else -> 3 } else -> 6 + when(first) { 'A' -> 2 'B' -> 3 else -> 1 } } } return result } check(part1("Day02_test") == 15) check(part2("Day02_test") == 12) println(part1("Day02")) println(part2("Day02")) }
0
Kotlin
0
0
ee991f6932b038ce5e96739855df7807c6e06258
1,621
AdventOfCode2022
Apache License 2.0
src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0508_most_frequent_subtree_sum // #Medium #Hash_Table #Depth_First_Search #Tree #Binary_Tree // #2023_01_10_Time_246_ms_(80.00%)_Space_38.4_MB_(93.33%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private val cache = mutableMapOf<Int, Int>() fun findFrequentTreeSum(root: TreeNode?): IntArray { treeSum(root) if (cache.isEmpty()) { return IntArray(0) } val max = cache.maxBy { it.value }.value return cache.filter { it.value == max }.map { it.key }.toIntArray() } private fun treeSum(node: TreeNode?): Int { return if (node == null) { 0 } else { val sum = node.`val` + treeSum(node.left) + treeSum(node.right) cache[sum] = cache.getOrDefault(sum, 0) + 1 sum } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,052
LeetCode-in-Kotlin
MIT License
src/main/kotlin/org/n52/spare/kicker/rankings/MatchpointsAlgorithmImpl.kt
matthesrieke
240,745,271
false
null
package org.n52.spare.kicker.rankings import org.n52.spare.kicker.model.Match import org.n52.spare.kicker.model.Player import org.n52.spare.kicker.model.Rank class MatchpointsAlgorithmImpl : RankingsAlgorithm { private val ranks: MutableMap<Player, Rank> = mutableMapOf() override fun calculateForMatches(matches: List<Match>): List<Rank> { if (matches.isEmpty()) return mutableListOf<Rank>() matches.forEach{m -> if (m.score == null) return@forEach val guest = m.guest!! val home = m.home!! plusMatchForTeam(guest) plusMatchForTeam(home) when { m.score!!.guest == m.score!!.home -> { plusPointsForTeam(guest, 1) plusPointsForTeam(home, 1) } m.score!!.guest > m.score!!.home -> { plusPointsForTeam(guest, 3) } else -> { plusPointsForTeam(home, 3) } } } var result: List<Rank> = ArrayList(ranks.values) result = result.sortedWith(compareByDescending<Rank>{it.points}.thenBy{it.totalMatches}) var currentPoints = result[0].points var currentMatches = result[0].totalMatches var currentRank = 1 var actualRank = 1 result.forEach{t -> if (t.points == currentPoints && t.totalMatches == currentMatches) { t.rank = currentRank } else { t.rank = actualRank currentRank = actualRank } actualRank++ } return result } private fun plusMatchForTeam(players: List<Player>) { players.forEach{p -> plusMatch(p)} } private fun plusMatch(player: Player) { val r: Rank if (ranks.containsKey(player)) { r = ranks[player]!! } else { r = Rank() r.player = player ranks[player] = r } r.totalMatches += 1 } private fun plusPointsForTeam(players: List<Player>, points: Int) { players.forEach{p -> plusPoints(p, points)} } private fun plusPoints(player: Player, points: Int) { if (ranks.containsKey(player)) { val r = ranks[player]!! r.points += points } } }
3
Kotlin
0
0
efe974a4865f8395d6d8fc901050c0e4aafede95
1,926
kicker-league-rest
Apache License 2.0
year2020/day02/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day02/part1/Year2020Day02Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 2: Password Philosophy --- Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan. The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with our computers; we can't log in!" You ask if you can take a look. Their password database seems to be a little corrupted: some of the passwords wouldn't have been allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen. To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set. For example, suppose you have the following list: 1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times. In the above example, 2 passwords are valid. The middle password, <PASSWORD>, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies. How many passwords are valid according to their policies? */ package com.curtislb.adventofcode.year2020.day02.part1 import com.curtislb.adventofcode.year2020.day02.password.CharCountPolicy import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 2, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { val file = inputPath.toFile() return CharCountPolicy.countValidPasswords(file.readLines()) } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
1,925
AdventOfCode
MIT License
src/main/kotlin/days/Day16.kt
butnotstupid
433,717,137
false
{"Kotlin": 55124}
package days class Day16 : Day(16) { private val toValueOne = { packet: Packet -> packet.version.toLong() + packet.subPackets.sumOf { it.value!! } } private val toOperatorOne = { _: Int -> Iterable<Long>::sum } override fun partOne(): Any { val reader = inputList.first().flatMap { toBinary(it) }.let { Reader(it) } val packet = reader.readPacket(toValueOne, toOperatorOne) return packet.value!! } private val toValueTwo = { packet: Packet -> packet.value!! } private val toOperatorTwo = { typeId: Int -> mapOf<Int, Iterable<Long>.() -> Long>( 0 to Iterable<Long>::sum, 1 to { this.reduce { acc, next -> acc * next } }, 2 to { this.minOrNull()!! }, 3 to { this.maxOrNull()!! }, 5 to { if (this.first() > this.last()) 1 else 0 }, 6 to { if (this.first() < this.last()) 1 else 0 }, 7 to { if (this.first() == this.last()) 1 else 0 } ).getValue(typeId) } override fun partTwo(): Any { val reader = inputList.first().flatMap { toBinary(it) }.let { Reader(it) } val packet = reader.readPacket(toValueTwo, toOperatorTwo) return packet.value!! } private fun toBinary(c: Char): List<Int> { val dec = Character.getNumericValue(c) return listOf(8, 4, 2, 1).map { if (dec.and(it) == 0) 0 else 1 } } class Reader(private val binary: List<Int>) { private var pos = 0 fun readPacket(toValue: (Packet) -> Long, toOperator: (Int) -> Iterable<Long>.() -> Long): Packet { val ver = readVersion() val type = readTypeId() return when (type) { 4 -> { val packet = Packet(ver, type, readLiteralValue(), emptyList()) packet.copy(value = toValue(packet)) } else -> { val subPackets = readSubPackets(toValue, toOperator) val reduce = toOperator(type) val packet = Packet(ver, type, subPackets.map(toValue).reduce(), subPackets) packet.copy(value = toValue(packet)) } } } private fun readSubPackets( toValue: (Packet) -> Long, operators: (Int) -> Iterable<Long>.() -> Long ): List<Packet> { val subPackets = mutableListOf<Packet>() when (readBits(1)) { 0 -> { val totalLength = readBits(15) val subPacketsEnd = pos + totalLength while (pos < subPacketsEnd) { subPackets.add(readPacket(toValue, operators)) } } 1 -> { val numOfPackets = readBits(11) repeat(numOfPackets) { subPackets.add(readPacket(toValue, operators)) } } } return subPackets } private fun readVersion(): Int { return readBits(3) } private fun readTypeId(): Int { return readBits(3) } private fun readLiteralValue(): Long { var value = 0L do { val (prefix, part) = readBits(1) to readBits(4) value = value * 16 + part } while (prefix != 0) return value } private fun readBits(n: Int): Int { if (pos + n > binary.size) { throw IllegalArgumentException("Can't read $n bits starting from $pos (only ${binary.size - pos} bits left)") } var sum = 0 repeat(n) { sum = sum * 2 + binary[pos] pos += 1 } return sum } } data class Packet( val version: Int, val type: Int, val value: Long? = null, val subPackets: List<Packet> ) }
0
Kotlin
0
0
a06eaaff7e7c33df58157d8f29236675f9aa7b64
4,028
aoc-2021
Creative Commons Zero v1.0 Universal
classifying-usecase/src/main/java/com/github/kamil1338/classifying_usecase/classifying/ResultCalculator.kt
kamilpierudzki
227,631,855
false
{"Kotlin": 135174}
package com.github.kamil1338.classifying_usecase.classifying import com.github.kamil1338.classifying_usecase.classifying.ClassifyingUseCase.Companion.RESULTS_TO_SHOW import java.util.* import kotlin.Comparator typealias MapEntry = Map.Entry<Int, Float> class ResultCalculator { fun getMostProbableIndexAndItsValue( labels: List<String>, outputBuffer: Array<FloatArray> ): Map.Entry<Int, Float> { val sortedLabels = PriorityQueue<Map.Entry<Int, Float>>(RESULTS_TO_SHOW) { e1, e2 -> e1.value.compareTo(e2.value) } (labels.indices).forEach { i -> sortedLabels.add(object : MapEntry { override val key = i override val value = outputBuffer[0][i] }) if (sortedLabels.size > RESULTS_TO_SHOW) { sortedLabels.poll() } } return sortedLabels.poll() } fun calculateWinner( xEntry: Map.Entry<Int, Float>, yEntry: Map.Entry<Int, Float>, zEntry: Map.Entry<Int, Float> ): Int { val classes = countedClasses(xEntry, yEntry, zEntry) return if (isUnclearCase(classes)) { getWinnerForComparator( xEntry, yEntry, zEntry, Comparator { e1, e2 -> e2.value.compareTo(e1.value) }) } else { getWinnerForComparator( xEntry, yEntry, zEntry, Comparator { e1, e2 -> e1.key.compareTo(e2.key) }) } } fun countedClasses( xEntry: Map.Entry<Int, Float>, yEntry: Map.Entry<Int, Float>, zEntry: Map.Entry<Int, Float> ): List<Int> { val result = arrayListOf(0, 0, 0) result[xEntry.key]++ result[yEntry.key]++ result[zEntry.key]++ return result } fun isUnclearCase(list: List<Int>): Boolean { list.indices.forEach { i -> list.indices.forEach { j -> if (i != j && list[i] == list[j]) { return true } } } return false } fun getWinnerForComparator( xEntry: Map.Entry<Int, Float>, yEntry: Map.Entry<Int, Float>, zEntry: Map.Entry<Int, Float>, comparator: Comparator<Map.Entry<Int, Float>> ): Int = listOf(xEntry, yEntry, zEntry) .sortedWith(comparator) .first() .key fun getWinnerProbability( xEntry: Map.Entry<Int, Float>, yEntry: Map.Entry<Int, Float>, zEntry: Map.Entry<Int, Float> ): Int = listOf(xEntry, yEntry, zEntry) .sortedWith(Comparator { e1, e2 -> e2.value.compareTo(e1.value) }) .first() .key fun getWinnerClass( xEntry: Map.Entry<Int, Float>, yEntry: Map.Entry<Int, Float>, zEntry: Map.Entry<Int, Float> ): Int = listOf(xEntry, yEntry, zEntry) .sortedWith(Comparator { e1, e2 -> e2.key.compareTo(e1.key) }) .first() .key }
0
Kotlin
0
0
710ad15cd83504ae6383c6121ef76b8f0f83f1e0
3,101
ml-androidplatform
Apache License 2.0
src/main/kotlin/engineer/thomas_werner/euler/Problem18.kt
huddeldaddel
183,355,188
true
{"Kotlin": 116039, "Java": 34495}
package engineer.thomas_werner.euler fun main(args: Array<String>) { var problem18 = Problem18("""75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23""".trimIndent()) println(problem18.getMaximumPathSum()) } class Problem18 { private var triangle: List<MutableList<Int>> constructor(input: String) { val lines = input.split("\n") triangle = lines.map { line -> line.split(" ").map { num -> num.toInt() }.toMutableList() } } fun getMaximumPathSum(): Int { val size = triangle.size -1 for(rowIdx in size downTo 1) { for(colIdx in 0 until triangle[rowIdx].size -1) { val oldValue = triangle[rowIdx -1][colIdx] val maxVal = listOf(triangle[rowIdx][colIdx], triangle[rowIdx][colIdx +1]).max() triangle[rowIdx -1][colIdx] = oldValue + maxVal!! } } return triangle[0][0] } }
0
Kotlin
1
0
df514adde8c62481d59e78a44060dc80703b8f9f
1,229
euler
MIT License
src/main/kotlin/day04/Day04.kt
vitalir2
572,865,549
false
{"Kotlin": 89962}
package day04 import Challenge import toIntRange object Day04 : Challenge(4) { override fun part1(input: List<String>): Int { return countNumberOfElvesPairs(input) { firstInterval, secondInterval -> firstInterval.containsAll(secondInterval) || secondInterval.containsAll(firstInterval) } } override fun part2(input: List<String>): Int { return countNumberOfElvesPairs(input) { firstInterval, secondInterval -> (firstInterval intersect secondInterval).isNotEmpty() } } private fun countNumberOfElvesPairs( input: List<String>, predicate: (firstInterval: Set<Int>, secondInterval: Set<Int>) -> Boolean, ): Int { return input .asSequence() .map { pairOfElves -> pairOfElves.split(",") } .map { elves -> elves.map { it.toIntRange("-").toSet() } } .filter { (firstInterval, secondInterval) -> predicate(firstInterval, secondInterval) } .count() } }
0
Kotlin
0
0
ceffb6d4488d3a0e82a45cab3cbc559a2060d8e6
1,017
AdventOfCode2022
Apache License 2.0
src/Day02.kt
Schneider-David
573,092,941
false
{"Kotlin": 2695}
import java.io.File //Nice straightforward way from blog by <NAME> private val part1Scores: Map<String, Int> = mapOf( "A X" to 1 + 3, "A Y" to 2 + 6, "A Z" to 3 + 0, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 1 + 6, "C Y" to 2 + 0, "C Z" to 3 + 3, ) private val part2Scores: Map<String, Int> = mapOf( "A X" to 3 + 0, "A Y" to 1 + 3, "A Z" to 2 + 6, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 2 + 0, "C Y" to 3 + 3, "C Z" to 1 + 6, ) fun part1(input: List<String>): Int { return input.sumOf { part1Scores[it] ?: 0 } } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println(part1(testInput)) println(testInput.sumOf { part2Scores[it] ?: 0 }) }
0
Kotlin
0
1
af9c5991056eccd3d96cdfb09bdbcf853e12a4ef
953
kotlin-avent-of-code-template
Apache License 2.0
src/main/kotlin/g2401_2500/s2488_count_subarrays_with_median_k/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2488_count_subarrays_with_median_k // #Hard #Array #Hash_Table #Prefix_Sum #2023_07_05_Time_464_ms_(100.00%)_Space_51.1_MB_(100.00%) class Solution { fun countSubarrays(nums: IntArray, k: Int): Int { var idx: Int val n = nums.size var ans = 0 idx = 0 while (idx < n) { if (nums[idx] == k) { break } idx++ } val arr = Array(n - idx) { IntArray(2) } var j = 1 for (i in idx + 1 until n) { if (nums[i] < k) { arr[j][0] = arr[j - 1][0] + 1 arr[j][1] = arr[j - 1][1] } else { arr[j][1] = arr[j - 1][1] + 1 arr[j][0] = arr[j - 1][0] } j++ } val map: MutableMap<Int, Int> = HashMap() for (ints in arr) { val d2 = ints[1] - ints[0] map[d2] = map.getOrDefault(d2, 0) + 1 } var s1 = 0 var g1 = 0 for (i in idx downTo 0) { if (nums[i] < k) { s1++ } else if (nums[i] > k) { g1++ } val d1 = g1 - s1 val cur = map.getOrDefault(-d1, 0) + map.getOrDefault(1 - d1, 0) ans += cur } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,345
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/ginsberg/advent2017/Day15.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 /** * AoC 2017, Day 15 * * Problem Description: http://adventofcode.com/2017/day/15 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day15/ */ class Day15(input: List<String>) { private val notNumbers = """[^\d]""".toRegex() private val generatorA = generator(input[0].replace(notNumbers, "").toLong(), 16807) private val generatorB = generator(input[1].replace(notNumbers, "").toLong(), 48271) fun solvePart1(pairs: Int = 40_000_000): Int = generatorA .zip(generatorB) .take(pairs) .count { it.first == it.second } fun solvePart2(pairs: Int = 5_000_000): Int = generatorA.filter { it % 4 == 0 } .zip(generatorB.filter { it % 8 == 0 }) .take(pairs) .count { it.first == it.second } private fun generator(start: Long, factor: Long, divisor: Long = 2147483647): Sequence<Short> = generateSequence((start * factor) % divisor) { past -> (past * factor) % divisor }.map { it.toShort() } }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
1,140
advent-2017-kotlin
MIT License
4/b.kt
DarkoKukovec
159,875,185
false
{"JavaScript": 38238, "Kotlin": 9620}
import java.io.File; data class MostAsleep(val time: Int, val min: Int, val id: String) fun main4B() { var lastGuard: String = ""; var guards: MutableMap<String, MutableMap<Int, Int>> = mutableMapOf(); File("input.txt") .readText(Charsets.UTF_8) .split("\n") .sorted() .map({ line: String -> run { var matchResult = Regex("\\s([0-9]+):([0-9]+)").find(line); var match = matchResult?.groupValues; var time: Int = 0; if ((match?.getOrNull(1)?.toIntOrNull() ?: 0) == 0) { time = match?.getOrNull(2)?.toIntOrNull() ?: 0; } var action: Int = 0; if (line.indexOf("begins shift") != -1) { lastGuard = Regex("Guard #([0-9]+)").find(line)?.groupValues?.getOrNull(1) ?: ""; } else if (line.indexOf("falls asleep") != -1) { action = 1; } else if (line.indexOf("wakes up") != -1) { action = -1; } var guard = guards.getOrPut(lastGuard) { mutableMapOf() } for (i in time until 60) { guard.set(i, guard.getOrDefault(i, 0) + action); } }}); var mostAsleep = MostAsleep(0, 0, ""); guards.keys.forEach({ id -> run { var timetable = guards.getOrDefault(id, mutableMapOf()).toList().map { it.component2() }; var time = timetable.max() ?: 0; if (time > mostAsleep.time) { val min = timetable.indexOf(time); mostAsleep = MostAsleep(time, min, id); } }}); println(mostAsleep.id.toInt() * mostAsleep.min); }
0
JavaScript
0
0
58a46dcb9c3e493f91d773ccc0440db9bd3b24b5
1,490
adventofcode2018
MIT License
src/main/kotlin/year2022/day-13.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2022 import lib.aoc.Day import lib.aoc.Part import kotlin.math.sign fun main() { Day(13, 2022, PartA13(), PartB13()).run() } open class PartA13 : Part() { internal lateinit var packetPairs: List<Pair<List<Any>, List<Any>>> override fun parse(text: String) { val pairs = text.split("\n\n").map { it.split("\n") } packetPairs = pairs.map { Pair(parseList(it[0]).first, parseList(it[1]).first) } } private fun parseList(packet: String, nextId: Int = 1): Pair<List<Any>, Int> { val result = mutableListOf<Any>() var index = nextId var number = "" while (true) { when (val c = packet[index++]) { ']' -> { if (number.isNotEmpty()) { result.add(number.toInt()) } return Pair(result, index) } ',' -> { if (number.isNotEmpty()) { result.add(number.toInt()) } number = "" } '[' -> { val (list, i) = parseList(packet, index) index = i result.add(list) } in '0'..'9' -> number += c } } } override fun compute(): String { return packetPairs.mapIndexed { i, pair -> if (compareLists(pair.first, pair.second) == -1) i + 1 else 0 }.sum().toString() } internal fun compareLists(list1: List<Any>, list2: List<Any>): Int { val mutableList1 = list1.toMutableList() val mutableList2 = list2.toMutableList() while (true) { if (mutableList1.isEmpty() && mutableList2.isEmpty()) { return 0 } if (mutableList1.isEmpty()) { return -1 } if (mutableList2.isEmpty()) { return 1 } val data1 = mutableList1.removeFirst() val data2 = mutableList2.removeFirst() val result = compare(data1, data2) if (result != 0) { return result } } } @Suppress("UNCHECKED_CAST") private fun compare(data1: Any, data2: Any): Int { if (data1 is List<*> && data2 is List<*>) { return compareLists(data1 as List<Any>, data2 as List<Any>) } if (data1 is Int && data2 is Int) { return (data1 - data2).sign } var nextData1 = data1 var nextData2 = data2 if (nextData1 is Int) { nextData1 = listOf(nextData1) } if (nextData2 is Int) { nextData2 = listOf(nextData2) } return compareLists(nextData1 as List<Any>, nextData2 as List<Any>) } override val exampleAnswer: String get() = "13" } class PartB13 : PartA13() { override fun compute(): String { val packets = packetPairs.flatMap { it.toList() }.toMutableList() val sortedPackets: MutableList<Any> = mutableListOf(listOf(listOf(2)), listOf(listOf(6))) while (packets.isNotEmpty()) { val packet = packets.removeFirst() var inserted = false for (i in sortedPackets.indices) { @Suppress("UNCHECKED_CAST") if (compareLists(packet, sortedPackets[i] as List<Any>) == -1) { sortedPackets.add(i, packet) inserted = true break } } if (!inserted) { sortedPackets.add(packet) } } val marker1 = sortedPackets.indexOf(listOf(listOf(2))) + 1 val marker2 = sortedPackets.indexOf(listOf(listOf(6))) + 1 return (marker1 * marker2).toString() } override val exampleAnswer: String get() = "140" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
4,076
Advent-Of-Code-Kotlin
MIT License
src/main/kotlin/me/giacomozama/adventofcode2022/days/Day15.kt
giacomozama
572,965,253
false
{"Kotlin": 75671}
package me.giacomozama.adventofcode2022.days import java.io.File import java.util.PriorityQueue import kotlin.math.abs class Day15 : Day() { private lateinit var input: List<IntArray> override fun parseInput(inputFile: File) { val regex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex() input = inputFile.useLines { lines -> lines.map { line -> val match = requireNotNull(regex.matchEntire(line)) intArrayOf( match.groupValues[1].toInt(), match.groupValues[2].toInt(), match.groupValues[3].toInt(), match.groupValues[4].toInt() ) }.toList() } } // time: O(n * log(n), space: O(n) override fun solveFirstPuzzle(): Int { val segments = mutableListOf<IntArray>() val line = 2_000_000 val beaconsOnLine = hashSetOf<Int>() for ((sensorX, sensorY, beaconX, beaconY) in input) { if (beaconY == line) beaconsOnLine += beaconX val distToBeacon = abs(sensorX - beaconX) + abs(sensorY - beaconY) val distToLine = abs(line - sensorY) if (distToLine > distToBeacon) continue segments.add(intArrayOf(sensorX - distToBeacon + distToLine, sensorX + distToBeacon - distToLine)) } segments.sortBy { it[0] } var result = 1 var end = segments[0][0] for ((from, to) in segments) { if (to > end) { result += if (from <= end) to - end else 1 + from - to end = to } } return result - beaconsOnLine.size } // q = 4_000_000 // time: O(n * q * log(n)), space = O(n) override fun solveSecondPuzzle(): Long { val queue = PriorityQueue<IntArray> { a, b -> a[0].compareTo(b[0]) } for (y in 0..4_000_000) { for ((sensorX, sensorY, beaconX, beaconY) in input) { val distToBeacon = abs(sensorX - beaconX) + abs(sensorY - beaconY) val distToY = abs(y - sensorY) if (distToY <= distToBeacon) { queue.add(intArrayOf(sensorX - distToBeacon + distToY, sensorX + distToBeacon - distToY)) } } var end = -1 var cur = queue.poll() while (cur != null) { if (cur[0] > end + 1) return (end + 1) * 4_000_000L + y end = maxOf(end, cur[1]) cur = queue.poll() } if (end == 3_999_999) return 16_000_000_000_000L + y } error("Beacon not found.") } }
0
Kotlin
0
0
c30f4a37dc9911f3e42bbf5088fe246aabbee239
2,713
aoc2022
MIT License
leetcode2/src/leetcode/queue-reconstruction-by-height.kt
hewking
68,515,222
false
null
package leetcode /** * 406. 根据身高重建队列 * https://leetcode-cn.com/problems/queue-reconstruction-by-height/ * Created by test * Date 2019/11/23 12:12 * Description * 假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。 注意: 总人数少于1100人。 示例 输入: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 输出: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/queue-reconstruction-by-height 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object QueueReconstructionByHeight { class Solution { /** * 思路: * https://leetcode-cn.com/problems/queue-reconstruction-by-height/solution/gui-yue-hou-shi-yong-tan-xin-suan-fa-qiu-jie-ton-2/#comment * [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 排序后 [[7,0],[7,1],[6,1],[5,0],[5,2],[4,4]] 重新排队 [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] 先排序,再插入。it[1] 是指多少人比他高,所以这就是正确的位置,就在多少人,的位置插入 就只需要排下一个人看有多少人比他高,然后就插入到相应位置 */ fun reconstructQueue(people: Array<IntArray>): Array<IntArray> { people.sortWith(Comparator{ o1, o2 -> if (o1[0] == o2[0]) o1[1] - o2[1] else o2[0] - o1[0] }) val ansList = arrayListOf<IntArray>() people.forEach { ansList.add(it[1],it) } return ansList.toTypedArray() } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,855
leetcode
MIT License
src/main/kotlin/day3/Day3.kt
Wicked7000
573,552,409
false
{"Kotlin": 106288}
package day3 import Day import checkWithMessage import readInput import runTimedPart @Suppress("unused") class Day3(): Day() { private fun getItemPriority(item: Char): Int { var score = item.code if(score >= 97){ //Lowercase score -= 96 } else if(score >= 65){ score -= 38 } return score; } data class Rucksack(val firstCompartment: Set<Char>, val secondCompartment: Set<Char>) private fun part1(input: List<String>): Int { var totalPriorities = 0 for(line in input){ val firstHalf = mutableSetOf<Char>() val secondHalf = mutableSetOf<Char>() for(idx in line.indices){ val element = line[idx] if(idx < line.length / 2){ firstHalf.add(element) } else { secondHalf.add(element) } } val overlap = firstHalf.intersect(secondHalf) if(overlap.isEmpty() || overlap.size > 1){ throw Error("Too many elements or the overlap set is empty! $line $overlap") } overlap.firstNotNullOf { totalPriorities += getItemPriority(it) } } return totalPriorities; } private fun part2(input: List<String>): Int { var totalPriorities = 0 val groups = input.chunked(3) for(groupIdx in groups.indices){ val groupContents = List(3) { mutableSetOf<Char>() } for(lineIdx in groups[groupIdx].indices){ groups[groupIdx][lineIdx].map { groupContents[lineIdx].add(it) } } val intersection = groupContents[0].intersect(groupContents[1]).intersect(groupContents[2]) if(intersection.isEmpty() || intersection.size > 1){ throw Error("Too many elements or the overlap set is empty! ${groups[groupIdx]} $intersection") } intersection.firstNotNullOf { totalPriorities += getItemPriority(it) } } return totalPriorities } override fun run(){ val testData = readInput(3,"test") val inputData = readInput(3, "input") val testResult1 = part1(testData) checkWithMessage(testResult1, 157) runTimedPart(1, { part1(it) }, inputData) val testResult2 = part2(testData) checkWithMessage(testResult2, 70) runTimedPart(2, { part2(it) }, inputData) } }
0
Kotlin
0
0
7919a8ad105f3b9b3a9fed048915b662d3cf482d
2,626
aoc-2022
Apache License 2.0
src/Day01.kt
haraldsperre
572,671,018
false
{"Kotlin": 17302}
fun main() { fun getCollections(input: List<String>): List<Int> { return input .chunkedBy { it.isEmpty() } .map { elf -> elf.sumOf { it.toInt() } } } fun part1(input: List<String>): Int = getCollections(input).maxOrNull() ?: 0 fun part2(input: List<String>): Int = getCollections(input).sortedDescending().take(3).sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c4224fd73a52a2c9b218556c169c129cf21ea415
696
advent-of-code-2022
Apache License 2.0
src/Day12.kt
GarrettShorr
571,769,671
false
{"Kotlin": 82669}
import java.util.LinkedList import java.util.PriorityQueue fun main() { // class Point(var row: Int, var col: Int, var height: Int, var parent: Point? = null) { // fun getPos() : Pair<Int, Int> { return Pair(row, col) } // override fun toString(): String { // return "Point(row=$row, col=$col, height=$height)" // } // } class Node( var row: Int, var col: Int, var height: Int, var distance: Int = Integer.MAX_VALUE, var shortestPath: LinkedList<Node> = LinkedList(), var adjacentNodes: MutableMap<Node, Int> = mutableMapOf() ) : Comparable<Node> { fun addAdjacentNode(node: Node, weight: Int) { adjacentNodes[node] = weight } override fun compareTo(other: Node): Int { return Integer.compare(distance, other.distance) } override fun toString(): String { return "Node(row=$row, col=$col, height=$height)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Node if (row != other.row) return false if (col != other.col) return false return true } override fun hashCode(): Int { var result = row result = 31 * result + col return result } } fun evaluateDistanceAndPath(adjacentNode: Node, edgeWeight: Int, sourceNode: Node ) { val newDistance = sourceNode.distance + edgeWeight if(newDistance < adjacentNode.distance) { adjacentNode.distance = newDistance val shortestPath = LinkedList<Node>() shortestPath.addAll(sourceNode.shortestPath) shortestPath.add(sourceNode) adjacentNode.shortestPath = shortestPath } } fun calculateShortestPath(source: Node) : Set<Node> { source.distance = 0 var settled = hashSetOf<Node>() var unsettled = PriorityQueue<Node>() unsettled.add(source) while(unsettled.isNotEmpty()) { var currentNode = unsettled.poll() currentNode.adjacentNodes.entries.filter { !settled.contains(it.key) && !unsettled.contains(it.key) }.forEach { evaluateDistanceAndPath(it.key, it.value, currentNode) unsettled.add(it.key) } settled.add(currentNode) println("unsettled: ${unsettled.size} settled ${settled.size}") } return settled } // fun getNeighbors(r: Int, c: Int, maze: List<List<Int>>) : MutableList<Point> { // val height = maze.size // val width = maze[0].size // var neighbors = mutableListOf<Point>() // for(row in -1..1) { // for(col in -1..1) { // if(r + row < height && r + row >= 0 && c + col < width && c + col >= 0 && !(r==0 && c==0)) { // neighbors.add(Point(r+row, c+col, maze[r+row][c+col])) // } // } // } // return neighbors // } // // fun getNeighbors(r: Int, c: Int, maze: List<List<Int>>) : MutableList<Point> { // val height = maze.size // val width = maze[0].size // var neighbors = mutableListOf<Point>() // // if(r + 1 < height) { // neighbors.add((Point(r + 1, c, maze[r + 1][c]))) // } // if(r - 1 >= 0) { // neighbors.add((Point(r - 1, c, maze[r - 1][c]))) // } // if(c + 1 < width) { // neighbors.add((Point(r, c + 1, maze[r][c + 1]))) // } // if(c - 1 >= 0) { // neighbors.add(Point(r , c - 1, maze[r][c - 1])) // } // // return neighbors // } fun getNeighbors(r: Int, c: Int, maze: List<List<Int>>, locations: MutableList<Node>) : MutableList<Node> { val height = maze.size val width = maze[0].size var neighbors = mutableListOf<Node>() if(r + 1 < height && maze[r][c] >= maze[r+1][c] - 1) { // neighbors.add((Node(r + 1, c, maze[r + 1][c]))) neighbors.add(locations.find { it.row == r + 1 && it.col == c }!!) } if(r - 1 >= 0 && maze[r][c] >= maze[r-1][c] - 1) { // neighbors.add((Node(r - 1, c, maze[r - 1][c]))) neighbors.add(locations.find { it.row == r - 1 && it.col == c }!!) } if(c + 1 < width && maze[r][c] >= maze[r][c+1] - 1) { // neighbors.add((Node(r, c + 1, maze[r][c + 1]))) neighbors.add(locations.find { it.row == r && it.col == c + 1 }!!) } if(c - 1 >= 0 && maze[r][c] >= maze[r][c-1] - 1) { // neighbors.add(Node(r , c - 1, maze[r][c - 1])) neighbors.add(locations.find { it.row == r && it.col == c - 1 }!!) } return neighbors } fun part1(input: List<String>): Int { val START = 'S'.code val END = 'E'.code val maze = input.map { it.windowed(1).map { it.first().toChar().code }.toMutableList() }.toMutableList() val locations = mutableListOf<Node>() maze.forEachIndexed { r, nums -> nums.forEachIndexed { c, value -> locations.add(Node(r, c, maze[r][c])) } } val start = locations.find { it.height == START }!! start.height = 'a'.code maze[start.row][start.col] = 'a'.code val end = locations.find { it.height == END }!! end.height = 'z'.code maze[end.row][end.col] = 'z'.code locations.forEach { val neighbors = getNeighbors(it.row, it.col, maze, locations) // println(neighbors) val neighborMap = neighbors.associateWith { 1 }.toMutableMap() it.adjacentNodes = neighborMap } // println(locations) for(location in locations) { println("node: ${location.row} ${location.col} ${location.adjacentNodes}") } val settled = calculateShortestPath(start) val endNode = settled.find {it.row == end.row && it.col == end.col}!! println("path: ${endNode.shortestPath} distance: ${endNode.distance}") // println(settled.find{ it.height == END}?.shortestPath?.size) // var count = 'a' // for(row in maze.indices) { // for(col in maze[0].indices) { // if(endNode.shortestPath.find { (it.row == row) && (it.col == col) } != null) { // var node = endNode.shortestPath.find { (it.row == row) && (it.col == col) } // print(count+endNode.shortestPath.indexOf(node)) // } else { // print(".") // } // } // println() // } return endNode.distance } // fun part1(input: List<String>): Int { // val START = 'S'.code // val END = 'E'.code // val maze = input.map { // it.windowed(1).map { it.first().toChar().code }.toMutableList() // }.toMutableList() // // val locations = mutableListOf<Point>() // maze.forEachIndexed { r, nums -> // nums.forEachIndexed { c, value -> // locations.add(Point(r, c, value)) // } // } // val (startRow, startCol) = locations.filter { it.height == START }[0].getPos() // locations.filter { it.height == START }[0].height = 'a'.code // // // // you start at a // maze[startRow][startCol] = 'a'.code // // val distances = mutableMapOf<Point, Int>() //// val precedingPoints = mutableMapOf<Point, Point?>() // // locations.forEach { // distances[it] = Int.MAX_VALUE //// precedingPoints[it] = null // } // // // set up start node // distances[locations[0]] = 0 // val start = locations.find { it.row == startRow && it.col == startCol }!! // val dest = locations.find { it.height == END } // val locationQueue = mutableListOf<Point>() // locationQueue.add(start) // // val visited = mutableListOf<Point>() // visited.add(start) //// val finalPath = mutableListOf<Point>() // while(locationQueue.isNotEmpty()) { // val loc = locationQueue.removeAt(0) // println(loc) // for(pos in getNeighbors(loc.row, loc.col, maze).filter { !visited.contains(it) }) { // if(pos.parent == null && loc.height >= pos.height - 1 && !visited.contains(pos)) { // distances[pos] = distances[loc]!! + 1 // pos.parent = loc // locationQueue.add(pos) // visited.add(pos) // if(pos.height == END) { // break // } // } // } // } // val path = mutableListOf<Point>() // path.add(dest!!) // var prev = dest.parent // while(prev != null) { // path.add(prev) // prev = prev.parent // } // println(path) //// println(distances[locations.filter { it.height == END }[0]]) // // // return 0 // } fun part2(input: List<String>): Int { val START = 'S'.code val END = 'E'.code val maze = input.map { it.windowed(1).map { it.first().toChar().code }.toMutableList() }.toMutableList() val locations = mutableListOf<Node>() maze.forEachIndexed { r, nums -> nums.forEachIndexed { c, value -> locations.add(Node(r, c, maze[r][c])) } } val start = locations.find { it.height == START }!! start.height = 'a'.code maze[start.row][start.col] = 'a'.code val end = locations.find { it.height == END }!! end.height = 'z'.code maze[end.row][end.col] = 'z'.code locations.forEach { val neighbors = getNeighbors(it.row, it.col, maze, locations) // println(neighbors) val neighborMap = neighbors.associateWith { 1 }.toMutableMap() it.adjacentNodes = neighborMap } // println(locations) for(location in locations) { println("node: ${location.row} ${location.col} ${location.adjacentNodes}") } val possibleStarts = locations.filter{ it.height == 'a'.code } val distances = mutableListOf<Int>() for(possibleStart in possibleStarts) { val settled = calculateShortestPath(possibleStart) val endNode = settled.find {it.row == end.row && it.col == end.col} if(endNode != null) { distances.add(endNode.distance) } } // println("path: ${endNode.shortestPath} distance: ${endNode.distance}") // println(settled.find{ it.height == END}?.shortestPath?.size) // var count = 'a' // for(row in maze.indices) { // for(col in maze[0].indices) { // if(endNode.shortestPath.find { (it.row == row) && (it.col == col) } != null) { // var node = endNode.shortestPath.find { (it.row == row) && (it.col == col) } // print(count+endNode.shortestPath.indexOf(node)) // } else { // print(".") // } // } // println() // } return distances.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") // println(part1(testInput)) println(part2(testInput)) val input = readInput("Day12") // output(part1(input)) output(part2(input)) }
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
10,400
AdventOfCode2022
Apache License 2.0
2019/day10/asteroids.kt
sergeknystautas
226,467,020
false
null
package aoc2019.day10; import java.io.File; import kotlin.system.exitProcess; import kotlin.math.hypot; import kotlin.math.atan; import kotlin.math.PI; // import kotlin.Double.NaN; fun Loadcodes(filename: String) : List<String> { return File(filename).readLines(); } fun Splitcodes(opcodes: String, delim: String): List<Int> { // println("you gave ops of $opcodes"); var ops: List<Int> = opcodes.split(delim).map{ it.trim().toInt() }; // println("This is ${ops.size} instructions"); return ops; } fun ListAsteroids(lines: List<String>): List<Pair<Int, Int>> { var asteroids = mutableListOf<Pair<Int, Int>>(); for (i in 0..lines.size - 1) { for (j in 0..lines[i].length - 1) { if (lines[i][j] == '#') { asteroids.add(Pair(j, i)); } } } return asteroids; } fun GetDistances(asteroids: List<Pair<Int, Int>>, station: Pair<Int, Int>): List<Double> { var distances = mutableListOf<Double>(); for (asteroid in asteroids) { if (asteroid == station) { distances.add(0.0); } else { distances.add(hypot((asteroid.first - station.first).toDouble(), (asteroid.second - station.second).toDouble())); } } return distances; } fun GetRadians(asteroids: List<Pair<Int, Int>>, station: Pair<Int, Int>): List<Double> { var radians = mutableListOf<Double>(); for (asteroid in asteroids) { if (asteroid == station) { radians.add(Double.NaN); } else { radians.add(Radians(asteroid, station)); } } return radians; } fun ScoreStation(asteroids: List<Pair<Int, Int>>, station: Pair<Int, Int>): Int { // // println("Scoring $station"); var distances = GetDistances(asteroids, station); var radians = GetRadians(asteroids, station); // Now we have all of the distances and radians so we can determine who is in between var count = 0; for (i in 0..asteroids.size - 1) { var visible = true; var asteroid = asteroids[i]; // We iterate thru all to see if anything blocks it for (j in 0..asteroids.size - 1) { if (i == j) { // We skip ourselves continue; } if (asteroid == station) { // Skip the station visible = false; continue; } // If the angle is the same, and it's further away than this, it's not visible if (radians[i] == radians[j] && distances[i] > distances[j]) { // println("Cannot see ${asteroids[i]} blocked by ${asteroids[j]}"); visible = false; break; } } if (visible) { // println("Can see $asteroid with angle ${radians[i]}"); count++; } else { // println("Cannot see $asteroid with angle ${radians[i]}"); } } return count; } fun ShootAsteroids(asteroids: List<Pair<Int, Int>>, station: Pair<Int, Int>): Int { var distances = GetDistances(asteroids, station); var radians = GetRadians(asteroids, station); var radiansMapped = mutableMapOf<Double, MutableList<Pair<Int, Int>>>(); var distancesMapped = mutableMapOf<Pair<Int, Int>, Double>(); asteroids.forEachIndexed { index, it -> // Create map of each radian to asteroid pairs var mapped = radiansMapped.getOrDefault(radians[index], mutableListOf<Pair<Int, Int>>()); mapped.add(it); radiansMapped.put(radians[index], mapped); distancesMapped.put(it, distances[index]); }; radiansMapped.remove(Double.NaN); // Order the asteroids by the distances for (asteroids in radiansMapped.values) { asteroids.sortBy { distancesMapped[it] }; } // Get all of the radians in order var radiansSorted = radiansMapped.keys.toMutableList(); radiansSorted.sortDescending(); // Now sort by distances // radiansMapped.forEach{ println(it)}; // distancesMapped.forEach{ println(it)}; // radiansSorted.forEach{ println(it)}; var next = -PI / 2; var shot = 0; do { var possible = radiansSorted.filter { it < next }; if (possible.size > 0) { next = possible.first(); var shotAsteroid = radiansMapped.getValue(next).removeAt(0); if (radiansMapped.getValue(next).size == 0) { radiansMapped.remove(next); radiansSorted.remove(next); } println("Shot ${shot + 1} is $shotAsteroid"); shot++; } else { // Start over at the top next = PI * 2; // Clean out radians mapped // println("before cleaning ${radiansMapped.size}"); // radiansMapped = radiansMapped.filter { it.value.size > 0 }.toMutableMap(); // println("after cleaning ${radiansMapped.size}"); } } while (shot < 200 && radiansMapped.size > 0); return 0; } fun Radians(station: Pair<Int, Int>, asteroid: Pair<Int, Int>): Double { // println("Comparing $asteroid to $station"); var x = asteroid.first - station.first; var y = -(asteroid.second - station.second); // System.out.println("$x $y"); if (x == 0 && y == 0) { println("You calculated the radians of the same point $asteroid"); exitProcess(-1); } else if (x == 0 && y > 0) { return PI * 0.50; } else if (x == 0 && y < 0) { return PI * 1.50; } else if (x > 0) { return atan(y.toDouble() / x.toDouble()); } else { return atan(y.toDouble() / x.toDouble()) + PI; } } fun main(args: Array<String>) { if (args.size != 1) { println("You done messed up a-a-ron"); println("Usage: cmd filename"); exitProcess(-1); } // Load the data var lines = Loadcodes(args[0]); // println(lines); // Find the asteroids var asteroids = ListAsteroids(lines); // println(asteroids); // Score the site var mostCount = 0; var most: Pair<Int, Int> = Pair(-1, -1); for (station in asteroids) { // println("Checking asteroid $station as possible station..."); var count = ScoreStation(asteroids, station); println("Asteroid $station can see $count"); if (count > mostCount) { mostCount = count; most = station; } } println("$most can see $mostCount"); /* var center = Pair(0, 0); println("Right: ${Radians(center, Pair(1,0))}"); println("Right-down: ${Radians(center, Pair(1,1))}"); println("Down: ${Radians(center, Pair(0,1))}"); println("Down-left: ${Radians(center, Pair(-1,1))}"); println("Left: ${Radians(center, Pair(-1,0))}"); println("Left-up: ${Radians(center, Pair(-1,-1))}"); println("Up: ${Radians(center, Pair(0,-1))}"); println("Up-Right: ${Radians(center, Pair(1,-1))}"); */ ShootAsteroids(asteroids, most); // println(atan(1.0)); // println(atan(-1.0)); }
0
Kotlin
0
0
38966bc742f70122681a8885e986ed69dd505243
7,078
adventofkotlin2019
Apache License 2.0
kotlin/837.Most Common Word(最常见的单词).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>Given a paragraph&nbsp;and a list of banned words, return the most frequent word that is not in the list of banned words.&nbsp; It is guaranteed there is at least one word that isn&#39;t banned, and that the answer is unique.</p> <p>Words in the list of banned words are given in lowercase, and free of punctuation.&nbsp; Words in the paragraph are not case sensitive.&nbsp; The answer is in lowercase.</p> <pre> <strong>Example:</strong> <strong>Input:</strong> paragraph = &quot;Bob hit a ball, the hit BALL flew far after it was hit.&quot; banned = [&quot;hit&quot;] <strong>Output:</strong> &quot;ball&quot; <strong>Explanation:</strong> &quot;hit&quot; occurs 3 times, but it is a banned word. &quot;ball&quot; occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. Note that words in the paragraph are not case sensitive, that punctuation is ignored (even if adjacent to words, such as &quot;ball,&quot;), and that &quot;hit&quot; isn&#39;t the answer even though it occurs more because it is banned. </pre> <p>&nbsp;</p> <p><strong>Note: </strong></p> <ul> <li><code>1 &lt;= paragraph.length &lt;= 1000</code>.</li> <li><code>1 &lt;= banned.length &lt;= 100</code>.</li> <li><code>1 &lt;= banned[i].length &lt;= 10</code>.</li> <li>The answer is unique, and written in lowercase (even if its occurrences in <code>paragraph</code>&nbsp;may have&nbsp;uppercase symbols, and even if it is a proper noun.)</li> <li><code>paragraph</code> only consists of letters, spaces, or the punctuation symbols <code>!?&#39;,;.</code></li> <li>Different words in&nbsp;<code>paragraph</code>&nbsp;are always separated by a space.</li> <li>There are no hyphens or hyphenated words.</li> <li>Words only consist of letters, never apostrophes or other punctuation symbols.</li> </ul> <p>&nbsp;</p><p>给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。题目保证至少有一个词不在禁用列表中,而且答案唯一。</p> <p>禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。</p> <pre> <strong>示例:</strong> <strong>输入:</strong> paragraph = &quot;Bob hit a ball, the hit BALL flew far after it was hit.&quot; banned = [&quot;hit&quot;] <strong>输出:</strong> &quot;ball&quot; <strong>解释:</strong> &quot;hit&quot; 出现了3次,但它是一个禁用的单词。 &quot;ball&quot; 出现了2次 (同时没有其他单词出现2次),所以它是段落里出现次数最多的,且不在禁用列表中的单词。 注意,所有这些单词在段落里不区分大小写,标点符号需要忽略(即使是紧挨着单词也忽略, 比如 &quot;ball,&quot;), &quot;hit&quot;不是最终的答案,虽然它出现次数更多,但它在禁用单词列表中。 </pre> <p><strong>说明: </strong></p> <ul> <li><code>1 &lt;= 段落长度 &lt;= 1000</code>.</li> <li><code>1 &lt;= 禁用单词个数 &lt;= 100</code>.</li> <li><code>1 &lt;= 禁用单词长度 &lt;= 10</code>.</li> <li>答案是唯一的, 且都是小写字母&nbsp;(即使在 <code>paragraph</code> 里是大写的,即使是一些特定的名词,答案都是小写的。)</li> <li><code>paragraph</code>&nbsp;只包含字母、空格和下列标点符号<code>!?&#39;,;.</code></li> <li><code>paragraph</code>&nbsp;里单词之间都由空格隔开。</li> <li>不存在没有连字符或者带有连字符的单词。</li> <li>单词里只包含字母,不会出现省略号或者其他标点符号。</li> </ul> <p>给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。题目保证至少有一个词不在禁用列表中,而且答案唯一。</p> <p>禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。</p> <pre> <strong>示例:</strong> <strong>输入:</strong> paragraph = &quot;Bob hit a ball, the hit BALL flew far after it was hit.&quot; banned = [&quot;hit&quot;] <strong>输出:</strong> &quot;ball&quot; <strong>解释:</strong> &quot;hit&quot; 出现了3次,但它是一个禁用的单词。 &quot;ball&quot; 出现了2次 (同时没有其他单词出现2次),所以它是段落里出现次数最多的,且不在禁用列表中的单词。 注意,所有这些单词在段落里不区分大小写,标点符号需要忽略(即使是紧挨着单词也忽略, 比如 &quot;ball,&quot;), &quot;hit&quot;不是最终的答案,虽然它出现次数更多,但它在禁用单词列表中。 </pre> <p><strong>说明: </strong></p> <ul> <li><code>1 &lt;= 段落长度 &lt;= 1000</code>.</li> <li><code>1 &lt;= 禁用单词个数 &lt;= 100</code>.</li> <li><code>1 &lt;= 禁用单词长度 &lt;= 10</code>.</li> <li>答案是唯一的, 且都是小写字母&nbsp;(即使在 <code>paragraph</code> 里是大写的,即使是一些特定的名词,答案都是小写的。)</li> <li><code>paragraph</code>&nbsp;只包含字母、空格和下列标点符号<code>!?&#39;,;.</code></li> <li><code>paragraph</code>&nbsp;里单词之间都由空格隔开。</li> <li>不存在没有连字符或者带有连字符的单词。</li> <li>单词里只包含字母,不会出现省略号或者其他标点符号。</li> </ul> **/ class Solution { fun mostCommonWord(paragraph: String, banned: Array<String>): String { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
5,583
leetcode
MIT License
src/main/kotlin/com.supesuba.smoothing/Vector.kt
23alot
245,768,268
false
null
package com.supesuba.smoothing import kotlin.math.sqrt data class Vector( val x: Float, val y: Float, val z: Float ) { operator fun div(value: Float): Vector = Vector( x = this.x / value, y = this.y / value, z = this.z / value ) operator fun times(value: Float): Vector = Vector( x = this.x * value, y = this.y * value, z = this.z * value ) operator fun times(other: Vector): Vector = crossProduct(other) operator fun times(transposedVector: TransposedVector): Float = x * transposedVector.p1 + y * transposedVector.p2 + z * transposedVector.p3 operator fun times(vv: VectorOfVector): Vector = Vector( x = this.x * vv.v1.x + this.y * vv.v2.x + this.z * vv.v3.x, y = this.x * vv.v1.y + this.y * vv.v2.y + this.z * vv.v3.y, z = this.x * vv.v1.z + this.y * vv.v2.z + this.z * vv.v3.z ) operator fun plus(value: Float): Vector = Vector( x = this.x + value, y = this.y + value, z = this.z + value ) operator fun plus(value: Vector): Vector = Vector( x = this.x + value.x, y = this.y + value.y, z = this.z + value.z ) operator fun minus(value: Float): Vector = Vector( x = this.x - value, y = this.y - value, z = this.z - value ) operator fun minus(value: Vector): Vector = Vector( x = this.x - value.x, y = this.y - value.y, z = this.z - value.z ) // Векторное произведение fun crossProduct(other: Vector): Vector = Vector( x = this.y * other.z - this.z * other.y, y = this.z * other.x - this.x * other.z, z = this.x * other.y - this.y * other.x ) // Скалярное произведение fun dotProduct(other: Vector): Float = this.x * other.x + this.y * other.y + this.z * other.z fun distance(): Float = sqrt(x * x + y * y + z * z) fun normalize(): Vector = this / this.distance() fun toVertex(): Vertex = Vertex( x = this.x, y = this.y, z = this.z ) fun toList(): List<Float> = listOf(x, y, z) } operator fun Float.times(value: Vector): Vector = value * this fun List<Vector>.average(): Vector { val averageX = this.map(Vector::x).sum() / this.count() val averageY = this.map(Vector::y).sum() / this.count() val averageZ = this.map(Vector::z).sum() / this.count() return Vector( x = averageX, y = averageY, z = averageZ ) } data class VectorOfVector( val v1: Vector, val v2: Vector, val v3: Vector ) { operator fun times(v: Vector): Vector = Vector( x = 0f, y = 0f, z = 0f ) } data class TransposedVector( val p1: Float, val p2: Float, val p3: Float ) { operator fun times(v: Vector): VectorOfVector = VectorOfVector( v1 = Vector(x = this.p1 * v.x, y = this.p1 * v.y, z = this.p1 * v.z), v2 = Vector(x = this.p2 * v.x, y = this.p2 * v.y, z = this.p2 * v.z), v3 = Vector(x = this.p3 * v.x, y = this.p3 * v.y, z = this.p3 * v.z) ) }
0
Kotlin
0
0
2b8283f79d89aff92604e6007b26e11dbd1f888a
3,373
smoothing-algorithm
Apache License 2.0
src/main/kotlin/dynamicprogramming/SplitArrayLargestSum.kt
e-freiman
471,473,372
false
{"Kotlin": 78010}
package dynamicprogramming private var memo = arrayOf<IntArray>() fun dp(nums: IntArray, m: Int, index: Int): Int { if (memo[m][index] != -1) { return memo[m][index] } if (m == 1) { var sum = 0 for (i in index .. nums.lastIndex) { sum += nums[i] } memo[m][index] = sum return sum } var sum = nums[index] var bestDivide = Int.MAX_VALUE for (i in index + 1 .. nums.lastIndex) { val divide = maxOf(sum, dp(nums, m - 1, i)) bestDivide = minOf(divide, bestDivide) sum += nums[i] } memo[m][index] = bestDivide return bestDivide } fun splitArray(nums: IntArray, m: Int): Int { memo = Array(m + 1) { IntArray(nums.size) { -1 } } return dp(nums, m, 0) } fun main() { println(splitArray(intArrayOf(7,2,5,10,8), 2)) }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
847
LeetcodeGoogleInterview
Apache License 2.0
src/test/kotlin/aoc/Day7.kt
Lea369
728,236,141
false
{"Kotlin": 36118}
package aoc_2023 import org.junit.jupiter.api.Nested import java.nio.file.Files import java.nio.file.Paths import java.util.stream.Collectors import kotlin.test.Test import kotlin.test.assertEquals class Day7 { data class Hand(val cards: String, val bet: Int) private val possibleCards: List<Char> = listOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J') @Nested internal inner class Day7Test { private val day7: Day7 = Day7() @Test fun testPart1() { val expected = 251195607 assertEquals(expected, day7.solveP1("./src/test/resources/2023/input7")) } } private fun solveP1(s: String): Int { val hands: List<Hand> = Files.lines(Paths.get(s)).map { Hand(it.split(" ")[0].trim(), it.split(" ")[1].trim().toInt()) } .collect(Collectors.toList()) return hands.sortedWith(handComparator).mapIndexed { i, hand -> (i + 1) * hand.bet }.sum() } val handComparator = Comparator<Hand> { hand1, hand2 -> if (getType(hand1) != getType(hand2)) { getType(hand2) - getType(hand1) } else { hand1.cards.toList() .mapIndexed { i, char -> possibleCards.indexOf(hand2.cards[i]) - possibleCards.indexOf(char) } .firstOrNull { it != 0 } ?: 0 } } private fun getType(hand: Hand): Int { val jokers = hand.cards.count { it == 'J' } val mapCharToOccurence: List<Int> = hand.cards.toSet().filter { it != 'J' }.map { char -> hand.cards.count { it == char } } val actualisedOccurences: List<Int> = listOf((mapCharToOccurence.firstOrNull { it == mapCharToOccurence.max() } ?: 0) + jokers) + mapCharToOccurence.filterIndexed{ i, _ -> i != mapCharToOccurence.indexOf(mapCharToOccurence.max()) } if (actualisedOccurences.max() == 5) { return 0 } if (actualisedOccurences.max() == 4) { return 1 } if (actualisedOccurences.containsAll(listOf(3, 2))) { return 2 } if (actualisedOccurences.max() == 3) { return 3 } if (actualisedOccurences.count { it == 2 } == 2) { return 4 } if (actualisedOccurences.max() == 2) { return 5 } return 6 } }
0
Kotlin
0
0
1874184df87d7e494c0ff787ea187ea3566fbfbb
2,366
AoC
Apache License 2.0
src/Day06_withWindowed.kt
arisaksen
573,116,584
false
{"Kotlin": 42887}
import org.assertj.core.api.Assertions.assertThat // https://adventofcode.com/2022/day/6 fun main() { val moreThanTwoEqual = """^.*(.).*\1.*${'$'}""".toRegex() val part1WindowSize = 4 val part2WindowSize = 14 fun part1(input: String): Int = input.asSequence() .windowed(part1WindowSize) .withIndex() .filterNot { it.value.joinToString("").contains(moreThanTwoEqual) } // replaced with indexOfFirst in part2 .map { it.index } .first() + part1WindowSize fun part2(input: String): Int = input .windowed(part2WindowSize) { it.toSet().count() == it.length } .indexOf(true) + part2WindowSize // Returns the index of the first occurrence of the specified element in the list, or -1 if the specified element is not contained in the list. //.windowedSequence(part2WindowSize) { it.toSet().count() == it.length } // for large data sets. Benchmark: https://github.com/Kotlin/kotlinx-benchmark // test if implementation meets criteria from the description, like: val testInput = readText("Day06_test") assertThat(part1(testInput)).isEqualTo(10) assertThat(part2(testInput)).isEqualTo(29) // print the puzzle answer val input = readText("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
85da7e06b3355f2aa92847280c6cb334578c2463
1,339
aoc-2022-kotlin
Apache License 2.0
src/2022/Day25.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import java.io.File import java.math.BigInteger import java.util.* fun main() { Day25().solve() } class Day25 { val input1 = """ 1=-0-2 12111 2=0= 21 2=01 111 20012 112 1=-1= 1-12 12 1= 122 """.trimIndent() val input2 = """ 2=-1=0 """.trimIndent() val input3 = """ 2011-=2=-1020-1===-1 """.trimIndent() fun solve() { // val f = File("src/2022/inputs/day25.in") // val s = Scanner(f) val s = Scanner(input3) // val s = Scanner(input2) // val s = Scanner(input1) val numbers = mutableListOf<BigInteger>() var sum = BigInteger.ZERO while (s.hasNextLine()) { val line = s.nextLine().trim() val sn = line.map{ when (it) { '=' -> '0' '-' -> '1' else -> (it.digitToInt()+2).digitToChar() } } val sn1 = sn.joinToString("") val twos = "2".repeat(sn1.length) println("$line $sn $sn1") numbers.add(BigInteger(sn1, 5) - BigInteger(twos, 5)) sum += numbers.last() println("${numbers.last()} ${numbers.last().toInt()}") } val twos = "2".repeat(sum.toString(5).length) val sum1 = sum + BigInteger(twos, 5) val sum2s = sum1.toString(5).map{ when (it.digitToInt()) { 0 -> '=' 1 -> '-' else -> (it.digitToInt()-2).digitToChar() } }.joinToString ("") println("$sum ${sum1.toString(5)} $sum2s") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
1,737
advent-of-code
Apache License 2.0
aoc-2023/src/main/kotlin/aoc/aoc23.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.* val testInput = """ #.##################### #.......#########...### #######.#########.#.### ###.....#.>.>.###.#.### ###v#####.#v#.###.#.### ###.>...#.#.#.....#...# ###v###.#.#.#########.# ###...#.#.#.......#...# #####.#.#.#######.#.### #.....#.#.#.......#...# #.#####.#.#.#########v# #.#...#...#...###...>.# #.#.#v#######v###.###v# #...#.>.#...>.>.#.###.# #####v#.#.###v#.#.###.# #.....#...#...#.#.#...# #.#########.###.#.#.### #...###...#...#...#.### ###.###.#.###v#####v### #...#...#.#.>.>.#.>.### #.###.###.#.###.#.#v### #.....###...###...#...# #####################.# """.parselines class MapGrid(val grid: CharGrid) { val start = Coord(grid[0].indexOf('.'), 0) val end = Coord(grid.last().indexOf('.'), grid.size - 1) fun contains(c: Coord) = c.x in grid[0].indices && c.y in grid.indices fun path(c: Coord) = grid.at(c) == '.' fun slope(c: Coord) = grid.at(c) in "v^<>" fun forest(c: Coord) = grid.at(c) == '#' /** Get possible locations from [cur]. */ fun next(prev: Coord, cur: Coord): List<Coord> { return if (slope(cur)) { // must go in the same direction listOf(cur + cur - prev) } else cur.adj2(grid) .filter { it != prev && !forest(it) } .filter { !slope(it) || it-cur == dir(grid.at(it)) } // must go in downhill direction } private fun dir(c: Char) = when (c) { 'v' -> DOWN '^' -> UP '<' -> LEFT '>' -> RIGHT else -> error("invalid direction $c") } /** Get all intersections in grid. */ fun intersections() = grid.allIndices2().filter { it.adj2(grid).count { slope(it) } >= 3 }.toSet() /** Get graph between intersections in grid, including the start and end. */ fun graph(): Map<Coord, Map<Coord, Int>> { val result = mutableMapOf<Coord, MutableMap<Coord, Int>>() val xx = intersections() (listOf(start) + xx).forEach { pos -> result[pos] = mutableMapOf() val step1 = if (pos == start) listOf(start.bottom) else listOf(pos.right, pos.bottom).filter { contains(it) && slope(it) } step1.forEach { pathsToNextIntersection(listOf(pos, it), xx).forEach { path -> result[pos]!![path.last()] = path.size - 1 } } } return result } /** Get paths from a given starting point to next intersection. */ fun pathsToNextIntersection(steps: List<Coord>, intersections: Set<Coord>): List<List<Coord>> { if (steps.last() in intersections || steps.last() == end) return listOf(steps) val next = next(steps[steps.size - 2], steps.last()).filter { it !in steps } return next.flatMap { pathsToNextIntersection(steps + it, intersections) } } /** Get all possible hikes in the grid, starting with given list of steps. */ fun hike(steps: List<Coord>): List<List<Coord>> { if (steps.last() == end) return listOf(steps) val next = next(steps[steps.size - 2], steps.last()).filter { it !in steps } return next.flatMap { hike(steps + it) } } } // part 1 fun List<String>.part1(): Int { val map = MapGrid(this) val hikes = map.hike(listOf(map.start.top, map.start)) println(hikes.map { it.size }.joinToString(" ")) return hikes.maxOf { it.size - 2 } } // part 2 fun List<String>.part2(): Int { val map = MapGrid(this) val graph = map.graph() val coords = graph.keys.toSet() + graph.values.flatMap { it.keys }.toSet() val coordLabel = coords.sortedBy { it.x + it.y }.mapIndexed { i, c -> c to ('A'+i) }.toMap() graph.keys.sortedBy { it.x + it.y }.forEach { print("From ${coordLabel[it]}: ") graph[it]!!.forEach { (c, d) -> print("${coordLabel[c]}=$d, ") } println() } val allCoords = graph.keys.toSet() + map.end val labGraph = allCoords.associateWith { c -> (graph[c]?.keys ?: setOf()) + graph.keys.filter { c in graph[it]!!.keys } } .entries.associate { (c0, adjs) -> coordLabel[c0]!! to adjs.associate { coordLabel[it]!! to (graph[c0]?.get(it) ?: graph[it]!![c0]!!) } } println(labGraph) // return longestPath(labGraph, 'A', coordLabel[map.end]!!) // return longestPath2(labGraph, LongestPathIndex(coordLabel.values.toSet(), 'A', coordLabel[map.end]!!)) return longestPath2(labGraph, LongestPathIndex(coordLabel.values.toSet() - setOf('A', 'B', 'D'), 'E', coordLabel[map.end]!!)) } /** Index for computed values of longest paths for a given restricted set of characters. */ data class LongestPathIndex(val chars: Set<Char>, val start: Char, val end: Char) val longestPathCache = mutableMapOf<LongestPathIndex, Int>() /** * Find the longest possible path in the given adjacency graph from [start] to [end] without repeating nodes. * Paths are restricted to the given [chars]. * Uses the [longestPathCache] to avoid re-computing paths. * Returns the sum of the weights of the edges in the path. */ fun longestPath2(graph: Map<Char, Map<Char, Int>>, index: LongestPathIndex): Int { val nextOptions = graph[index.start]!!.keys.filter { it in index.chars }.map { LongestPathIndex(index.chars - index.start, it, index.end) } if (index.start == index.end) return 0 return if (nextOptions.isEmpty()) Int.MIN_VALUE else nextOptions.maxOf { next -> longestPathCache.getOrPut(next) { longestPath2(graph, next).also { if (it < 0) { // println("No path from ${next.start} to ${next.end} with chars ${next.chars}") } else if (graph.keys.size - next.chars.size <= 4) { println("Longest path from ${(graph.keys - next.chars).sorted()} and then ${next.start}: $it") } else { // too many to print } } } + graph[index.start]!![next.start]!! } } /** * Find the longest possible path in the given adjacency graph from [start] to [end] without repeating nodes. * Returns the sum of the weights of the edges in the path. */ fun longestPath(graph: Map<Char, Map<Char, Int>>, start: Char, end: Char): Int { val paths = mutableListOf(listOf(start)) fun pathLength(path: List<Char>) = path.mapIndexed { i, c -> graph[c]!!.getOrDefault(path.getOrNull(i+1) ?: 'z', 0) }.sum() var longest = 0 while (paths.isNotEmpty()) { val path = paths.removeAt(0) val last = path.last() if (last == end) { val length = pathLength(path) if (length > longest) { longest = length println("new longest path: $path $length") } } else { val next = graph[last]!!.keys.filter { it !in path } next.forEach { paths.add(path + it) } } } return longest } // calculate answers val day = 23 val input = getDayInput(day, 2023) val testResult = testInput.part1().also { it.print } val testResult2 = testInput.part2().also { it.print } val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
7,502
advent-of-code
Apache License 2.0