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/2023/Day12.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2023` import common.BackTracker import java.io.File import java.math.BigInteger import java.util.* import kotlin.collections.ArrayList import kotlin.math.max import kotlin.math.min fun main() { Day12().solve() } class Day12 { val input1 = """ ???.### 1,1,3 .??..??...?##. 1,1,3 ?#?#?#?#?#?#?#? 1,3,1,6 ????.#...#... 4,1,1 ????.######..#####. 1,6,5 ?###???????? 3,2,1 """.trimIndent() val input2 = """ ??????????? 3,1,1 """.trimIndent() fun List<Int>.minLength() = sum() + size - 1 fun String.solve2(ls: List<Int>): BigInteger { if (isEmpty()) { if (ls.isEmpty()) { return BigInteger.ONE } return BigInteger.ZERO } val m1 = indexOf('.') if (m1 == -1) { return solve3(ls) } if (m1 == length-1) { return substring(0, length-1).solve2(ls) } if (m1 == 0) { return substring(1).solve2(ls) } val s1 = substring(0, m1) val s2 = substring(m1 + 1) var r = BigInteger.ZERO for (i in 0 .. ls.size) { val ls1 = ls.subList(0, i) if (ls1.minLength() > s1.length) { break } val a = s1.solve3(ls1) if (a == BigInteger.ZERO) { continue } val ls2 = ls.subList(i, ls.size) if (ls2.minLength() > s2.length) { continue } val b = s2.solve2(ls2) r += a * b } return r } // only '?' and '#' fun String.solve3(ls: List<Int>): BigInteger { val m1 = indexOf('#') if (m1 == -1) { return solve4(ls) } var r = BigInteger.ZERO for (i in ls.indices) { for (j in 0 until ls[i]) { val startIx = m1 - j if (startIx < 0) { continue } if (startIx > 0 && get(startIx-1) == '#') { continue } val endIx = startIx + ls[i] if (endIx > length) { continue } if (endIx < length && get(endIx) == '#') { continue } if (startIx < 2 && endIx > length-2) { if (ls.size == 1) { r++ } continue } if (startIx < 2) { if (i == 0) { val s0 = substring(endIx + 1) val ls0 = ls.subList(1, ls.size) r += s0.solve3(ls0) } continue } if (endIx > length-2) { if (i == ls.size-1) { val s0 = substring(0, startIx-1) val ls0 = ls.subList(0, ls.size-1) r += s0.solve4(ls0) } continue } val s1 = substring(0, startIx-1) val a = s1.solve4(ls.subList(0, i)) if (a == BigInteger.ZERO) { continue } val s2 = substring(endIx+1) val b = s2.solve3(ls.subList(i+1, ls.size)) r += a * b } } return r } fun Long.factorial() = (2..this).fold(BigInteger.ONE){acc, it -> acc * BigInteger.valueOf(it)} fun binomial(n: Long, k: Long) = n.factorial() / (n-k).factorial() / k.factorial() // only '?' fun String.solve4(ls: List<Int>): BigInteger { if (ls.isEmpty()) { return BigInteger.ONE } val n = length - ls.minLength() if (n<0) { return BigInteger.ZERO } val k = ls.size + 1 val b = binomial(n+k-1L, k-1L) return b } class SpringMap(val s: String, val l: List<Int>, val ixs: List<Int> = listOf()) { override fun toString(): String { return s + " " + l.joinToString ("," ) + " " + ixs.joinToString ("," ) + "\n" + ".".repeat(ixs.getOrNull(0)?:0) + ixs.indices.map{ if (it == ixs.size-1) "#".repeat(l[it]) else "#".repeat(l[it]) + ".".repeat(ixs[it+1] - ixs[it] - l[it])}.joinToString("") } } fun solve() { val f = File("src/2023/inputs/day12.in") val s = Scanner(f) // val s = Scanner(input1) // val s = Scanner(input2) var sum = BigInteger.ZERO var sum1 = BigInteger.ZERO var lineix = 0 val lines = mutableListOf<String>() val springMaps = mutableListOf<SpringMap>() while (s.hasNextLine()) { lineix++ val line = s.nextLine().trim() if (line.isEmpty()) { continue } lines.add(line) val halves = line.split(" ") springMaps.add(SpringMap(halves[0], halves[1].split(",").map { it.toInt() })) } val springMaps1 = springMaps.map { val s1 = (it.s + '?').repeat(5) val l1 = mutableListOf<Int>() (1..5).forEach{it1 -> l1.addAll(it.l)} SpringMap(s1.substring(0..s1.length-2), l1) } var e = 0 for (i in springMaps) { val r = i.s.solve2(i.l) println("${e++} $r") sum += r } e = 0 for (i in springMaps1) { val r = i.s.solve2(i.l) println("${e++} $r") sum1 += r } print("$sum $sum1\n") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
5,772
advent-of-code
Apache License 2.0
src/Day10.kt
MwBoesgaard
572,857,083
false
{"Kotlin": 40623}
fun main() { class Register(var value: Int) { val signalStrengths = mutableListOf<Int>() val queue = mutableListOf<Int>() fun executeQueue() { val queueElement = if (queue.size > 0) queue.removeFirst() else 0 value += queueElement } fun checkSignalStrength(cycle: Int) { if (cycle != 0 && (cycle % 20 == 0 && cycle % 40 != 0)) { signalStrengths.add(cycle * value) } } } class Display(val height: Int, val width: Int) { val matrix = MutableList(this.height) { MutableList(this.width) { "░" } } fun getSpritePos(cycle: Int): Set<Int> { val spritePos = mutableSetOf<Int>() for (c in (cycle - 1)..(cycle + 1)) { spritePos.add((c - 1) % 40) } return spritePos } fun drawPixel(cycle: Int, registerValue: Int) { val currentX = (cycle - 1) % 40 val currentY = (cycle - 1) / 40 val spriteRange = getSpritePos(registerValue) if (spriteRange.contains(currentX)) { matrix[currentY][currentX] = "▓" } } fun printScreen() { matrix.forEach { println(it.joinToString(" ")) } } } fun part1(input: List<String>): Int { var cycle = 1 val registerX = Register(1) for (line in input) { if (registerX.queue.size > 0) { registerX.checkSignalStrength(cycle) registerX.executeQueue() cycle++ } val instructions = line.split(" ") val opcode = instructions[0] if (opcode == "addx") { val value = instructions[1].toInt() registerX.queue.add(value) } registerX.checkSignalStrength(cycle) cycle++ } return registerX.signalStrengths.sum() } fun part2(input: List<String>) { var cycle = 1 val registerX = Register(1) val display = Display(6, 40) for (line in input) { if (registerX.queue.size > 0) { registerX.executeQueue() display.drawPixel(cycle, registerX.value) cycle++ } val instructions = line.split(" ") val opcode = instructions[0] if (opcode == "addx") { val value = instructions[1].toInt() registerX.queue.add(value) } display.drawPixel(cycle, registerX.value) cycle++ } return display.printScreen() } printSolutionFromInputLines("Day10", ::part1) printSolutionFromInputLines("Day10", ::part2) }
0
Kotlin
0
0
3bfa51af6e5e2095600bdea74b4b7eba68dc5f83
2,805
advent_of_code_2022
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[738]单调递增的数字.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个非负整数 N,找出小于或等于 N 的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。 // // (当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。) // // 示例 1: // // 输入: N = 10 //输出: 9 // // // 示例 2: // // 输入: N = 1234 //输出: 1234 // // // 示例 3: // // 输入: N = 332 //输出: 299 // // // 说明: N 是在 [0, 10^9] 范围内的一个整数。 // Related Topics 贪心算法 // 👍 140 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun monotoneIncreasingDigits(N: Int): Int { //数字转化为字符数组 val numsArray = N.toString().toCharArray() //获取需要转变为 9 的前一个index 默认是数最后一位 贪心算法 //时间复杂度O(n) var flag = numsArray.size for (i in numsArray.size-1 downTo 1){ if (numsArray[i-1] > numsArray[i]){ flag = i; numsArray[i-1]-- } } //将从flag 位置开始剩余位置设置为 9 for(i in flag until numsArray.size){ numsArray[i] = '9' } return String(numsArray).toInt() } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,375
MyLeetCode
Apache License 2.0
src/main/kotlin/org/github/poel/mazely/generator/algorithm/RecursiveDivision.kt
Poooel
303,827,188
false
null
package org.github.poel.mazely.generator.algorithm import org.github.poel.mazely.entity.Grid import org.github.poel.mazely.generator.Generator import kotlin.random.Random class RecursiveDivision: Generator { override fun on(grid: Grid, random: Random): Grid { grid.cells.flatten().forEach { cell -> cell.neighbors().forEach { neighbor -> cell.link(neighbor, false) } } divide(0, 0, grid.height, grid.width, grid, random) return grid } private fun divide(row: Int, column: Int, height: Int, width: Int, grid: Grid, random: Random) { if (height <= 1 || width <= 1) { return } if (height > width) { divideHorizontally(row, column, height, width, grid, random) } else { divideVertically(row, column, height, width, grid, random) } } private fun divideHorizontally(row: Int, column: Int, height: Int, width: Int, grid: Grid, random: Random) { val divideSouthOf = random.nextInt(height - 1) val passageAt = random.nextInt(width) for (x in 0 until width) { if (passageAt == x) continue val cell = grid.get(column + x, row + divideSouthOf) cell.south?.let { south -> cell.unlink(south) } } divide(row, column, divideSouthOf + 1, width, grid, random) divide(row + divideSouthOf + 1, column, height - divideSouthOf - 1, width, grid, random) } private fun divideVertically(row: Int, column: Int, height: Int, width: Int, grid: Grid, random: Random) { val divideEastOf = random.nextInt(width - 1) val passageAt = random.nextInt(height) for (y in 0 until height) { if (passageAt == y) continue val cell = grid.get(column + divideEastOf, row + y) cell.east?.let { east -> cell.unlink(east) } } divide(row, column, height, divideEastOf + 1, grid, random) divide(row, column + divideEastOf + 1, height, width - divideEastOf - 1, grid, random) } }
1
Kotlin
0
0
e5b365eefe3c6a3e287145f3dc235b4b3841e9af
2,093
mazely
MIT License
2018/kotlin/day16p2/src/main.kt
sgravrock
47,810,570
false
{"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488}
import java.util.* fun main(args: Array<String>) { val start = Date() val classLoader = Opcode::class.java.classLoader val puzzle = PuzzleInput.parse(classLoader.getResource("input.txt").readText()) val opcodeMap = findOpcodes(puzzle.hints) val result = execute(puzzle.program, opcodeMap) println(result[0]) println("in ${Date().time - start.time}ms") } fun findOpcodes(instructionHints: List<InstructionHint>): Map<Int, Opcode> { val found = mutableMapOf<Int, Opcode>() val pending = instructionHints.toMutableList() while (pending.size > 0) { for (ins in pending) { val candidates = ins.behavesLike().filter { !found.containsValue(it) } assert(candidates.size > 0) if (candidates.size == 1) { found[ins.codes[0]] = candidates[0] } } if (!pending.removeIf { found.containsKey(it.codes[0]) }) { throw Error("Stalled at ${found.size} found") } } return found } enum class Opcode { addr, addi, mulr, muli, banr, bani, borr, bori, setr, seti, gtir, gtri, gtrr, eqir, eqri, eqrr } fun evaluate(opcode: Opcode, registers: List<Int>, i1: Int, i2: Int, o: Int): List<Int> { val result = registers.toMutableList() result[o] = when (opcode) { Opcode.addr -> registers[i1] + registers[i2] Opcode.addi -> registers[i1] + i2 Opcode.mulr -> registers[i1] * registers[i2] Opcode.muli -> registers[i1] * i2 Opcode.banr -> registers[i1] and registers[i2] Opcode.bani -> registers[i1] and i2 Opcode.borr -> registers[i1] or registers[i2] Opcode.bori -> registers[i1] or i2 Opcode.setr -> registers[i1] Opcode.seti -> i1 Opcode.gtir -> if (i1 > registers[i2]) 1 else 0 Opcode.gtri -> if (registers[i1] > i2) 1 else 0 Opcode.gtrr -> if (registers[i1] > registers[i2]) 1 else 0 Opcode.eqir -> if (i1 == registers[i2]) 1 else 0 Opcode.eqri -> if (registers[i1] == i2) 1 else 0 Opcode.eqrr -> if (registers[i1] == registers[i2]) 1 else 0 } return result } data class InstructionHint( val input: List<Int>, val codes: List<Int>, val output: List<Int> ) { fun behavesLike(): List<Opcode> { return Opcode.values().filter { opcode -> evaluate(opcode, input, codes[1], codes[2], codes[3]) == output } } companion object { fun parse(input: String): List<InstructionHint> { return input.lines() .filter { it != "" } .chunked(3) .map { chunk -> InstructionHint( input = extractList(chunk[0]), codes = extractList(chunk[1]), output = extractList(chunk[2]) ) } } } } fun extractList(s: String): List<Int> { return s .replace(Regex("[^\\d ]"), "") .replace(Regex("^ *"), "") .split(" ") .map { it.toInt() } } data class PuzzleInput(val hints: List<InstructionHint>, val program: List<List<Int>>) { companion object { fun parse(input: String): PuzzleInput { val parts = input.split("\n\n\n\n") assert(parts.size == 2) return PuzzleInput( InstructionHint.parse(parts[0]), parts[1].lines() .filter { line -> line != "" } .map { line -> line.split(" ").map { it.toInt()} } ) } } } fun execute(program: List<List<Int>>, opcodeMap: Map<Int, Opcode>): List<Int> { var registers = listOf(0, 0, 0, 0) for (instruction in program) { val opcode = opcodeMap[instruction[0]]!! registers = evaluate(opcode, registers, instruction[1], instruction[2], instruction[3] ) } return registers }
0
Rust
0
0
ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3
4,053
adventofcode
MIT License
day11/kotlin/corneil/src/main/kotlin/solution.kt
timgrossmann
224,991,491
true
{"HTML": 2739009, "Python": 169603, "Java": 157274, "Jupyter Notebook": 116902, "TypeScript": 113866, "Kotlin": 89503, "Groovy": 73664, "Dart": 47763, "C++": 43677, "CSS": 34994, "Ruby": 27091, "Haskell": 26727, "Scala": 11409, "Dockerfile": 10370, "JavaScript": 6496, "PHP": 4152, "Go": 2838, "Shell": 2493, "Rust": 2082, "Clojure": 567, "Tcl": 46}
package com.github.corneil.aoc2019.day11 import com.github.corneil.aoc2019.day11.DIRECTION.EAST import com.github.corneil.aoc2019.day11.DIRECTION.NORTH import com.github.corneil.aoc2019.day11.DIRECTION.SOUTH import com.github.corneil.aoc2019.day11.DIRECTION.WEST import com.github.corneil.aoc2019.intcode.Program import com.github.corneil.aoc2019.intcode.readProgram import java.io.File enum class DIRECTION(val direction: Char) { NORTH('^'), EAST('>'), SOUTH('v'), WEST('<') } data class Cell(val color: Int = 0, val painted: Boolean = false) data class Coord(val x: Int, val y: Int) data class Robot(var position: Coord, var direction: DIRECTION) { fun turn(direction: Int) { if (direction == 0) { turnLeft() } else { turnRight() } advance() } fun advance() { position = when (direction) { NORTH -> position.copy(y = position.y - 1) EAST -> position.copy(x = position.x + 1) SOUTH -> position.copy(y = position.y + 1) WEST -> position.copy(x = position.x - 1) } } fun turnLeft() { direction = when (direction) { NORTH -> WEST WEST -> SOUTH SOUTH -> EAST EAST -> NORTH } } fun turnRight() { direction = when (direction) { NORTH -> EAST EAST -> SOUTH SOUTH -> WEST WEST -> NORTH } } } data class Grid(val cells: MutableMap<Coord, Cell> = mutableMapOf()) { fun cellColor(pos: Coord): Int { val cell = cells[pos] ?: Cell() return cell.color } fun paintCell(pos: Coord, color: Int) { cells[pos] = Cell(color, true) } } fun runRobot(input: List<Long>, startingColor: Int): Int { val robot = Robot(Coord(0, 0), NORTH) val grid = Grid() var outputState = false val code = Program(input) val program = code.createProgram(listOf(startingColor.toLong()), fetchInput = { grid.cellColor(robot.position).toLong() }, outputHandler = { output -> if (!outputState) { grid.paintCell(robot.position, output.toInt()) outputState = true } else { robot.turn(output.toInt()) outputState = false } }) do { program.execute() } while (!program.isHalted()) printGrid(grid) return grid.cells.values.count { it.painted } } fun printGrid(grid: Grid) { val maxX = grid.cells.keys.maxBy { it.x }?.x ?: 0 val minX = grid.cells.keys.minBy { it.x }?.x ?: 0 val maxY = grid.cells.keys.maxBy { it.y }?.y ?: 0 val minY = grid.cells.keys.minBy { it.y }?.y ?: 0 for (y in minY..maxY) { for (x in minX..maxX) { val color = grid.cellColor(Coord(x, y)) print(if (color == 0) '.' else '#') } println() } } fun main(args: Array<String>) { val fileName = if (args.size > 1) args[0] else "input.txt" val code = readProgram(File(fileName)) val painted = runRobot(code, 0) println("Painted = $painted") runRobot(code, 1) }
0
HTML
0
1
bb19fda33ac6e91a27dfaea27f9c77c7f1745b9b
3,153
aoc-2019
MIT License
src/main/kotlin/day4/Day4.kt
stoerti
726,442,865
false
{"Kotlin": 19680}
package io.github.stoerti.aoc.day4 import io.github.stoerti.aoc.IOUtils import io.github.stoerti.aoc.StringExt.intValues import kotlin.math.pow fun main(args: Array<String>) { val cards = IOUtils.readInput("day_4_input") .map { Card.fromString(it) } .onEach { println(it) } val result1 = cards .map { it.getMyWinningNumbers() } .map { if (it.isEmpty()) 0 else 2.0.pow(it.size - 1).toInt() } .sumOf { it } val numCards = cards.associate { it.cardNumber to 1 }.toMutableMap() cards.forEach { card -> for (i in 1..card.getNumWinners()) { numCards[card.cardNumber + i] = numCards[card.cardNumber + i]!! + 1 * numCards[card.cardNumber]!! } } val result2 = numCards.values.sum() println("Result 1: $result1") println("Result 2: $result2") } data class Card( val cardNumber: Int, val winningNumbers: List<Int>, val myNumbers: List<Int>, ) { companion object { fun fromString(line: String): Card { val cardNumber = line.split(":")[0].substring(5).trim().toInt() val winningNumbers = line.split(":")[1].split("|")[0].intValues() val myNumbers = line.split(":")[1].split("|")[1].intValues() return Card(cardNumber, winningNumbers, myNumbers) } } fun getMyWinningNumbers(): List<Int> { return myNumbers.filter { winningNumbers.contains(it) } } fun getNumWinners(): Int { return getMyWinningNumbers().size } } class Day4
0
Kotlin
0
0
05668206293c4c51138bfa61ac64073de174e1b0
1,436
advent-of-code
Apache License 2.0
src/main/kotlin/other/FactorialAdvanced.kt
DmitryTsyvtsyn
418,166,620
false
{"Kotlin": 223256}
package other import java.math.BigInteger /** * * This algorithm is taken from Google Guava library * */ class FactorialAdvanced { // precomputed factorials private val factorials = longArrayOf( 1L, 1L, 1L * 2, 1L * 2 * 3, 1L * 2 * 3 * 4, 1L * 2 * 3 * 4 * 5, 1L * 2 * 3 * 4 * 5 * 6, 1L * 2 * 3 * 4 * 5 * 6 * 7, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 ) fun compute(n: Int): BigInteger { if (n <= 0) { return BigInteger.ZERO } if (n < factorials.size) { return BigInteger.valueOf(factorials[n]) } // pre-allocate space for our list of intermediate BigIntegers. val approxSize = divide(n * log2Celling(n), Long.SIZE_BITS) val bigNumbers = ArrayList<BigInteger>(approxSize) // start from the pre-computed maximum long factorial. val startingNumber = factorials.size var number = factorials[startingNumber - 1] // strip off 2s from this value. var shift = number.countTrailingZeroBits() number = number shr shift // use floor(log2(num)) + 1 to prevent overflow of multiplication. var numberBits = log2Floor(number) + 1 var bits = log2Floor(startingNumber.toLong()) + 1 // check for the next power of two boundary, to save us a CLZ operation. var nextPowerOfTwo = 1 shl bits - 1 // iteratively multiply the longs as big as they can go. for (num in startingNumber..n) { // check to see if the floor(log2(num)) + 1 has changed. if ((num and nextPowerOfTwo) != 0) { nextPowerOfTwo = nextPowerOfTwo shl 1 bits++ } // get rid of the 2s in num. val tz = num.toLong().countTrailingZeroBits() val normalizedNum = (num shr tz).toLong() shift += tz // adjust floor(log2(num)) + 1. val normalizedBits = bits - tz // if it won't fit in a long, then we store off the intermediate product. if (normalizedBits + numberBits >= Long.SIZE_BITS) { bigNumbers.add(BigInteger.valueOf(number)) number = 1 numberBits = 0 } number *= normalizedNum numberBits = log2Floor(number) + 1 } // check for leftovers. if (number > 1) { bigNumbers.add(BigInteger.valueOf(number)) } // efficiently multiply all the intermediate products together. return listNumbers(bigNumbers).shiftLeft(shift) } /** * Returns the result of dividing p by q, rounding using the celling * * @throws ArithmeticException if q == 0 */ private fun divide(number: Int, divider: Int): Int { if (divider == 0) { throw ArithmeticException("/ by zero") // for GWT } val div = number / divider val rem = number - divider * div // equal to number % divider if (rem == 0) { return div } val signedNumber = 1 or (number xor divider shr Int.SIZE_BITS - 1) val increment = signedNumber > 0 return if (increment) div + signedNumber else div } private fun listNumbers(numbers: List<BigInteger>, start: Int = 0, end: Int = numbers.size): BigInteger { return when (end - start) { 0 -> BigInteger.ONE 1 -> numbers[start] 2 -> numbers[start].multiply(numbers[start + 1]) 3 -> numbers[start].multiply(numbers[start + 1]).multiply(numbers[start + 2]) else -> { // otherwise, split the list in half and recursively do this. val m = end + start ushr 1 listNumbers(numbers, start, m).multiply(listNumbers(numbers, m, end)) } } } // returns the base-2 logarithm of number, rounded according to the celling. private fun log2Celling(number: Int): Int { return Int.SIZE_BITS - (number - 1).countLeadingZeroBits() } // returns the base-2 logarithm of number rounded according to the floor. private fun log2Floor(number: Long): Int { return Long.SIZE_BITS - 1 - number.countLeadingZeroBits() } }
0
Kotlin
135
767
7ec0bf4f7b3767e10b9863499be3b622a8f47a5f
5,169
Kotlin-Algorithms-and-Design-Patterns
MIT License
src/Day11.kt
fedochet
573,033,793
false
{"Kotlin": 77129}
fun main() { class Monkey( startingItems: List<Long>, private val operation: (Long) -> Long, val divisibleBy: Long, ) { private val queue: ArrayDeque<Long> = ArrayDeque(startingItems) private lateinit var nextMonkeyTrue: Monkey private lateinit var nextMonkeyFalse: Monkey var inspectedItems: Long = 0 private set fun setupTargets(ifTrue: Monkey, ifFalse: Monkey) { nextMonkeyTrue = ifTrue nextMonkeyFalse = ifFalse } private var userOp: ((Long) -> Long)? = null fun addUserOperation(op: (Long) -> Long) { userOp = op } fun processItems() { while (queue.isNotEmpty()) { val initialWorry = queue.removeFirst() val nextWorry = operation(initialWorry) val userReducedWorry = userOp?.invoke(nextWorry) ?: nextWorry val nextMonkey = if (userReducedWorry % divisibleBy == 0L) { nextMonkeyTrue } else { nextMonkeyFalse } nextMonkey.queue.addLast(userReducedWorry) inspectedItems += 1 } } } fun String.removePrefixChecked(prefix: String): String { require(startsWith(prefix)) return removePrefix(prefix) } fun parseOperation(operation: String): (Long) -> Long { val rightHand = operation.removePrefixChecked("new = ") val (left, op, right) = rightHand.split(" ", limit = 3) val longOp: (Long, Long) -> Long = when (op) { "+" -> Long::plus "*" -> Long::times else -> error("Unexpected op '$op'") } fun toNumberSupplier(refOrNumber: String): (Long) -> Long = if (refOrNumber == "old") ({ it }) else ({ refOrNumber.toLong() }) val leftSupplier: (Long) -> Long = toNumberSupplier(left) val rightSupplier: (Long) -> Long = toNumberSupplier(right) return { oldValue -> longOp( leftSupplier(oldValue), rightSupplier(oldValue) ) } } fun parseMonkeys(input: List<String>): List<Monkey> { val monkeysAndTargets = input.windowed(size = 6, step = 7) { monkeyLines -> val ( items, operation, test, ifTrue, ifFalse ) = monkeyLines.drop(1).map { it.trim() } Triple( Monkey( items.removePrefixChecked("Starting items: ").split(", ").map { it.toLong() }, parseOperation(operation.removePrefixChecked("Operation: ")), test.removePrefix("Test: divisible by ").toLong(), ), ifTrue.removePrefixChecked("If true: throw to monkey ").toInt(), ifFalse.removePrefixChecked("If false: throw to monkey ").toInt() ) } val monkeys = monkeysAndTargets.map { it.first } for ((monkey, ifTrue, ifFalse) in monkeysAndTargets) { monkey.setupTargets(monkeys[ifTrue], monkeys[ifFalse]) } return monkeys } fun evaluateMonkeyBusiness(monkeys: List<Monkey>): Long { val processedItems = monkeys.map { it.inspectedItems }.sorted() return processedItems.takeLast(2).reduce(Long::times) } fun part1(input: List<String>): Long { val monkeys = parseMonkeys(input) monkeys.forEach { it.addUserOperation { oldValue -> oldValue / 3 } } repeat(20) { for (monkey in monkeys) { monkey.processItems() } } return evaluateMonkeyBusiness(monkeys) } fun findCommonDivider(monkeys: List<Monkey>): Long { return monkeys.map { it.divisibleBy }.distinct().reduce(Long::times) } fun part2(input: List<String>): Long { val monkeys = parseMonkeys(input) val commonDivider = findCommonDivider(monkeys) monkeys.forEach { it.addUserOperation { oldValue -> oldValue % commonDivider } } repeat(10_000) { for (monkey in monkeys) { monkey.processItems() } } return evaluateMonkeyBusiness(monkeys) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
975362ac7b1f1522818fc87cf2505aedc087738d
4,659
aoc2022
Apache License 2.0
src/test/kotlin/algorithms/sorting/SortingTest.kt
AANikolaev
273,465,105
false
{"Java": 179737, "Kotlin": 13961}
package algorithms.sorting import algorithms.sorting.bubble_sort.BubbleSort import algorithms.sorting.counting_sort.CountingSort import algorithms.sorting.heap_sort.Heapsort import algorithms.sorting.insertion_sort.InsertionSort import algorithms.sorting.merge_sort.MergeSort import algorithms.sorting.quick_sort.QuickSort import algorithms.sorting.radix_sort.RadixSort import algorithms.sorting.selection_sort.SelectionSort import com.google.common.truth.Truth.assertThat import org.junit.Test import java.util.* // Test all sorting algorithms under various constraints. // // Not all sorting algorithms are suitable for every type for test. For instance, // counting sort cannot sort a range of numbers between [Integer.MIN_VALUE, // Integer.MAX_VALUE] without running out of memory. Similarly, radix sort // doesn't play well with negative numbers, etc.. class SortingTest { internal enum class SortingAlgorithm(val sortingAlgorithm: InplaceSort) { BUBBLE_SORT(BubbleSort()), QUICK_SORT(QuickSort()), SELECTION_SORT(SelectionSort()), INSERTION_SORT(InsertionSort()), MERGE_SORT(MergeSort()), HEAP_SORT(Heapsort()), COUNTING_SORT(CountingSort()), RADIX_SORT(RadixSort()) } @Test fun verifySortingAlgorithms_smallPositiveIntegersOnly() { for (size in 0..999) { for (algorithm in sortingAlgorithms) { val sorter = algorithm.sortingAlgorithm val values: IntArray = randomIntegerArray(size, 0, 51) val copy = values.clone() Arrays.sort(values) sorter.sort(copy) assertThat(values).isEqualTo(copy) } } } @Test fun verifySortingAlgorithms_smallNegativeIntegersOnly() { for (size in 0..999) { for (algorithm in sortingAlgorithms) { if (algorithm == SortingAlgorithm.RADIX_SORT) { continue } val sorter = algorithm.sortingAlgorithm val values: IntArray = randomIntegerArray(size, -50, 51) val copy = values.clone() Arrays.sort(values) sorter.sort(copy) assertThat(values).isEqualTo(copy) } } } private val sortingAlgorithms = EnumSet.of( SortingAlgorithm.BUBBLE_SORT, SortingAlgorithm.QUICK_SORT, SortingAlgorithm.SELECTION_SORT, SortingAlgorithm.INSERTION_SORT, SortingAlgorithm.MERGE_SORT, SortingAlgorithm.HEAP_SORT, SortingAlgorithm.COUNTING_SORT, SortingAlgorithm.RADIX_SORT ) // Generates an array of random values where every number is between // [min, max) and there are possible repeats. private fun randomIntegerArray(sz: Int, min: Int, max: Int): IntArray { val ar = IntArray(sz) for (i in 0 until sz) ar[i] = randValue(min, max) return ar } // Generates a random number between [min, max) private fun randValue(min: Int, max: Int): Int { return min + (Math.random() * (max - min)).toInt() } }
0
Java
0
0
f9f0a14a5c450bd9efb712b28c95df9a0d7d589b
3,158
Algorithms
MIT License
src/Day06.kt
WilsonSunBritten
572,338,927
false
{"Kotlin": 40606}
fun main() { fun part1(input: List<String>): Int { return input.first().windowedSequence(4, 1).mapIndexed { index, window -> index to window }.first { (_, window) -> window.toList().distinct().size == 4 }.first + 4 } fun part2(input: List<String>): Int { return input.first().windowedSequence(14, 1).mapIndexed { index, window -> index to window }.first { (_, window) -> window.toList().distinct().size == 14 }.first + 14 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") val input = readInput("Day06") val p1TestResult = part1(testInput) println(p1TestResult) check(p1TestResult == 7) println(part1(input)) println("Part 2") val p2TestResult = part2(testInput) println(p2TestResult) check(part2(testInput) == 19) println(part2(input)) }
0
Kotlin
0
0
363252ffd64c6dbdbef7fd847518b642ec47afb8
922
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/recursion/Permutations.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.recursion fun main() { print(permutations(listOf(1, 2))) // [[1, 2], [2, 1]] } // O(n*n!) time | O(n*n!) space private fun permutations(arr: List<Int>): List<List<Int>> { val perms = mutableListOf<List<Int>>() permutations(arr.toMutableList(), 0, perms) return perms } private fun permutations(arr: MutableList<Int>, i: Int, perms: MutableList<List<Int>>) { val n = arr.size if (i == n - 1) { perms.add(arr.toList()) return } for (j in i until n) { swap(arr, i, j) permutations(arr, i + 1, perms) swap(arr, i, j) } } private fun swap(arr: MutableList<Int>, i: Int, j: Int) { val tmp = arr[i] arr[i] = arr[j] arr[j] = tmp }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
766
algs4-leprosorium
MIT License
Kotlin/src/main/kotlin/org/algorithm/problems/0015_koko_eating_bananas.kt
raulhsant
213,479,201
true
{"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187}
//Problem Statement // Koko loves to eat bananas. // There are N piles of bananas, the i-th pile has piles[i] bananas. // The guards have gone and will come back in H hours. // // Koko can decide her bananas-per-hour eating speed of K. // Each hour, she chooses some pile of bananas, and eats K bananas from that pile. // If the pile has less than K bananas, she eats all of them instead, and won't // eat any more bananas during this hour. // // Koko likes to eat slowly, but still wants to finish eating all the bananas before // the guards come back. // // Return the minimum integer K such that she can eat all the bananas within H hours. package org.algorithm.problems class `0015_koko_eating_bananas` { private fun hoursToEat(piles: IntArray, eatSpeed: Int): Int { var hours: Int = 0; for (pile in piles) { hours += pile / eatSpeed; if (pile % eatSpeed > 0) { hours++; } } return hours; } fun minEatingSpeed(piles: IntArray, H: Int): Int { var minBananas: Int = 1; var maxBananas: Int = 0; for (pile in piles) { maxBananas = maxOf(maxBananas, pile); } while (minBananas < maxBananas) { val midBananas: Int = minBananas + (maxBananas - minBananas) / 2; if (hoursToEat(piles, midBananas) <= H) { maxBananas = midBananas; } else { minBananas = midBananas + 1; } } return minBananas; } }
0
C++
0
0
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
1,546
algorithms
MIT License
src/chapter5/section3/ex25_Streaming.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section3 import edu.princeton.cs.algs4.In import edu.princeton.cs.algs4.Queue /** * 流输入 * 为KMP类添加一个search()方法,接受一个In类型的变量作为参数, * 在不使用其他任何实例变量的条件下在指定的输入流中查找模式字符串。 * 为RabinKarp类也添加一个类似的方法。 */ fun KMP.search(input: In): Int { var i = 0 var j = 0 while (input.hasNextChar() && j < pat.length) { val char = input.readChar() j = dfa[alphabet.toIndex(char)][j] i++ } return if (j == pat.length) i - j else i } fun RabinKarp.search(input: In): Int { val M = pat.length val patHash = hash(pat, M) var i = 0 var txtHash = 0L // 因为计算新hash值时需要减去第一个元素的hash值,所以使用队列保存M个字符 // 从这个角度看,也可以算是需要回退的算法,用额外空间解决流不能回退的问题 val charQueue = Queue<Char>() while (input.hasNextChar() && i < M) { val char = input.readChar() txtHash = (txtHash * alphabet.R() + alphabet.toIndex(char)) % Q i++ charQueue.enqueue(char) } if (i < M) return i if (patHash == txtHash) return 0 // 流输入不能调用check方法 while (input.hasNextChar()) { val nextChar = input.readChar() // 先计算旧hash值排除第一个元素后的hash值 txtHash = (txtHash + Q - RM * alphabet.toIndex(charQueue.dequeue()) % Q) % Q // 再添加新元素重新计算hash值 txtHash = (txtHash * alphabet.R() + alphabet.toIndex(nextChar)) % Q i++ if (txtHash == patHash) return i - M charQueue.enqueue(nextChar) } return i } fun main() { testStreaming<KMP>(KMP::search) { KMP(it) } testStreaming<RabinKarp>(RabinKarp::search) { RabinKarp(it) } println("check succeed.") }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,916
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/SubArray.kt
alexiscrack3
310,484,737
false
{"Kotlin": 44433}
class SubArray { fun getLengthOfLongestContiguousSubarray(array: Array<Int>): Int { var maxLength = 1 for (i in 0 until array.size - 1) { var minimum = array[i] var maximum = array[i] for (j in i + 1 until array.size) { minimum = Math.min(minimum, array[j]) maximum = Math.max(maximum, array[j]) if (maximum - minimum == j - i) { maxLength = Math.max(maxLength, maximum - minimum + 1) } } } return maxLength } fun getSmallestPositiveNumber(array: Array<Int>): Int { var result = 1 var i = 0 while (i < array.size && array[i] <= result) { result += array[i] i++ } return result } fun getSmallestSubarrayWithSumGreaterThanValue(array: Array<Int>, value: Int): Int { var minLength = array.size + 1 for (start in 0 until array.size) { // Initialize sum starting with current start var sum = array[start] // If first element itself is greater if (sum > value) { return 1 } for (end in start + 1 until array.size) { sum += array[end] // If sum becomes more than x and length of // this subarray is smaller than current smallest // length, update the smallest length (or result) val length = end - start + 1 if (sum > value && length < minLength) { minLength = length } } } return minLength } }
0
Kotlin
0
0
a2019868ece9ee319d08a150466304bfa41a8ad3
1,713
algorithms-kotlin
MIT License
classroom/src/main/kotlin/com/radix2/algorithms/week4/BST.kt
rupeshsasne
190,130,318
false
{"Java": 66279, "Kotlin": 50290}
package com.radix2.algorithms.week4 import java.util.* interface SymbolTable<K : Comparable<K>, V> { fun put(key: K, value: V) fun get(key: K): V? fun min(): Pair<K, V>? fun max(): Pair<K, V>? fun floor(key: K): Pair<K, V>? fun ceil(key: K): Pair<K, V>? fun size(): Int fun rank(key: K): Int fun deleteMin() fun deleteMax() fun delete(key: K) override fun toString(): String } class BST<K : Comparable<K>, V> : SymbolTable<K, V> { private class Node<K : Any, V>( var key: K, var data: V, var left: Node<K, V>? = null, var right: Node<K, V>? = null, var count: Int = 1 ) { override fun toString(): String = (key to data).toString() } private var root: Node<K, V>? = null override fun put(key: K, value: V) { root = put(root, key, value) } override fun get(key: K): V? = get(root, key)?.data override fun min(): Pair<K, V>? = min(root)?.let { it.key to it.data } override fun max(): Pair<K, V>? = max(root)?.let { it.key to it.data } override fun floor(key: K): Pair<K, V>? = floor(root, key)?.let { it.key to it.data } override fun ceil(key: K): Pair<K, V>? = ceil(root, key)?.let { it.key to it.data } override fun size(): Int = root?.count ?: 0 override fun rank(key: K): Int = rank(root, key) override fun deleteMin() { deleteMin(root) } override fun deleteMax() { deleteMax(root) } override fun delete(key: K) { delete(root, key) } override fun toString(): String = buildString { levelOrder(root, this) //inOrderWithStack(root, this) //inOrderRecursive(root, this) } private fun put(root: Node<K, V>?, key: K, value: V): Node<K, V>? { if (root == null) return Node(key, value) val cmp = key.compareTo(root.key) when { cmp < 0 -> root.left = put(root.left, key, value) cmp > 0 -> root.right = put(root.right, key, value) else -> root.data = value } root.count = 1 + (root.left?.count ?: 0) + (root.right?.count ?: 0) return root } private fun get(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return root val cmp = key.compareTo(root.key) return when { cmp < 0 -> get(root.left, key) cmp > 0 -> get(root.right, key) else -> root } } private fun min(root: Node<K, V>?): Node<K, V>? { if (root?.left == null) return root return min(root.left) } private fun max(root: Node<K, V>?): Node<K, V>? { if (root?.right == null) return root return max(root.right) } private fun floor(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return null val cmp = key.compareTo(root.key) return when { cmp == 0 -> root cmp < 0 -> floor(root.left, key) else -> floor(root.right, key) ?: root } } private fun ceil(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return null val cmp = key.compareTo(root.key) return when { cmp == 0 -> root cmp < 0 -> ceil(root.left, key) ?: root else -> ceil(root.right, key) } } private fun rank(root: Node<K, V>?, key: K): Int { if (root == null) return 0 val cmp = key.compareTo(root.key) return when { cmp == 0 -> root.left?.count ?: 0 cmp < 0 -> rank(root.left, key) else -> 1 + (root.left?.count ?: 0) + rank(root.right, key) } } private fun deleteMin(root: Node<K, V>?): Node<K, V>? { if (root?.left == null) return root?.right root.left = deleteMin(root.left) root.count = 1 + (root.left?.count ?: 0) + (root.right?.count ?: 0) return root } private fun deleteMax(root: Node<K, V>?): Node<K, V>? { if (root?.right == null) return root?.left root.right = deleteMax(root.right) root.count = 1 + (root.right?.count ?: 0) + (root.left?.count ?: 0) return root } private fun delete(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return null var trav = root val cmp = key.compareTo(trav.key) when { cmp < 0 -> trav.left = delete(trav.left, key) cmp > 0 -> trav.right = delete(trav.right, key) else -> { if (trav.left == null) return trav.right if (trav.right == null) return trav.left val temp = trav trav = min(temp.right) trav?.right = deleteMin(temp.right) trav?.left = temp.left } } trav?.count = 1 + (trav?.left?.count ?: 0) + (trav?.right?.count ?: 0) return trav } private fun inOrderRecursive(root: Node<K, V>?, builder: StringBuilder) { if (root == null) return inOrderRecursive(root.left, builder) builder.append(root.key to root.data) inOrderRecursive(root.right, builder) } private fun inOrderWithStack(root: Node<K, V>?, builder: StringBuilder) { if (root == null) return var trav = root val stack = Stack<Node<K, V>>() while (trav != null || !stack.isEmpty()) { while (trav != null) { stack.push(trav) trav = trav.left } val top = stack.pop() builder.append(top.key to top.data) trav = top.right } } private fun levelOrder(root: Node<K, V>?, builder: StringBuilder) { if (root == null) return val queue: Queue<Node<K, V>> = LinkedList() queue.add(root) with(queue) { while (!queue.isEmpty()) { if (builder.isNotEmpty()) { builder.append(", ") } builder.append(peek()) val front = queue.poll() if (front.left != null) { add(front.left) } if (front.right != null) { add(front.right) } } } } } fun <K : Comparable<K>, V> SymbolTable<K, V?>.put(key: K) = this.put(key, null) fun main() { val st: SymbolTable<Int, String?> = BST() st.put(6) st.put(7) st.put(4) st.put(1) println(st) }
0
Java
0
1
341634c0da22e578d36f6b5c5f87443ba6e6b7bc
6,791
coursera-algorithms-part1
Apache License 2.0
src/Day01.kt
casslabath
573,177,204
false
{"Kotlin": 27085}
fun main() { fun part1(input: List<String>): Int { var most = Int.MIN_VALUE var currentCals = 0 for(cal in input) { if(cal.isEmpty()) { most = currentCals.coerceAtLeast(most) currentCals = 0 } else { currentCals += Integer.parseInt(cal) } } return most } fun part2(input: List<String>): Int { val topThree = mutableListOf(0,0,0) var currentCals = 0 for(cal in input) { if(cal.isEmpty()) { if(currentCals > topThree[0]) { topThree[0] = currentCals topThree.sort() } currentCals = 0 } else { currentCals += Integer.parseInt(cal) } } return topThree.sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f7305e45f41a6893b6e12c8d92db7607723425e
967
KotlinAdvent2022
Apache License 2.0
src/year2021/Day1.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2021 import readLines fun main() { val input = readLines("2021", "day1").map { it.toInt() } val testInput = readLines("2021", "day1_test").map { it.toInt() } check(part1(testInput) == 7) println("Part 1:" + part1(input)) check(part2(testInput) == 5) println("Part 2:" + part2(input)) } private fun part1(input: List<Int>): Int { return (0..input.size - 2) .filter { input[it + 1] > input[it] } .size } private fun part2(input: List<Int>): Int { val measurements = (0..input.size - 3) .map { input[it] + input[it + 1] + input[it + 2] } return part1(measurements) }
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
655
advent_of_code
MIT License
src/main/kotlin/org/geepawhill/dungeon/Area.kt
GeePawHill
308,920,321
false
null
package org.geepawhill.dungeon import java.lang.Integer.max import java.lang.Integer.min data class Area(val west: Int, val north: Int, val east: Int, val south: Int) { val longest: Int get() = max(east - west, south - north) val size = (east - west) * (south - north) fun margin(amount: Int): Area { return Area(west - amount, north - amount, east + amount, south + amount) } fun intersects(other: Area): Boolean { return !(south < other.north || north > other.south || west > other.east || east < other.west) } fun contains(coords: Coords): Boolean { return intersects(Area(coords.x, coords.y, coords.x, coords.y)) } fun fill(map: Map, type: CellType) { for (c in west..east) { for (r in north..south) map[c, r] = type } } fun union(other: Area): Area = Area(min(west, other.west), min(north, other.north), max(east, other.east), max(south, other.south)) override fun toString(): String = "($west,$north) - ($east,$south)" companion object { fun normalized(start: Coords, end: Coords) = Area(min(start.x, end.x), min(start.y, end.y), max(start.x, end.x), max(start.y, end.y)) } }
0
Kotlin
0
1
94bd1d7d1cf204ea08a721592d1b6430141966fd
1,226
dungeon
MIT License
src/main/kotlin/graph/Graph.kt
ghonix
88,671,637
false
null
package graph import java.util.* import kotlin.collections.HashMap import kotlin.collections.HashSet class Graph { companion object { @JvmStatic fun createAdjacencyList(edges: Array<Pair<String, String>>): Map<String, Set<String>> { val graph = HashMap<String, MutableSet<String>>() for (edge in edges) { if (!graph.containsKey(edge.first)) { graph[edge.first] = HashSet() } if (!graph.containsKey(edge.second)) { graph[edge.second] = HashSet() } graph[edge.first]?.add(edge.second) graph[edge.second]?.add(edge.first) } return graph } @JvmStatic fun main(args: Array<String>) { val graph = Graph() // graph.breadthFirst() // graph.findPath() // println(graph.findPathUndirected()) println(graph.connectedComponents()) } } private fun connectedComponents(): Int { // val edges = arrayOf(Pair("1", "2"), Pair("4", "6"), Pair("5", "6"), Pair("6", "7"), Pair("6", "8"), Pair("3")) val graph = HashMap<String, Set<String>>() graph["1"] = setOf("2") graph["2"] = setOf("1") graph["3"] = emptySet() graph["4"] = setOf("6") graph["5"] = setOf("6") graph["6"] = setOf("4", "5", "7", "8") graph["7"] = setOf("6") graph["8"] = setOf("6") val visited = HashSet<String>() return connectedComponents(graph, visited) } private fun connectedComponents( graph: HashMap<String, Set<String>>, visited: HashSet<String> ): Int { var connectedComponents = 0 for (node in graph.keys) { if (!visited.contains(node)) { connectedComponents++ explore(graph, node, visited) } } return connectedComponents } private fun explore( graph: HashMap<String, Set<String>>, node: String, visited: HashSet<String> ) { if (!visited.contains(node)) { visited.add(node) graph[node]?.let { for (neighbor in it) { explore(graph, neighbor, visited) } } } } fun findPathUndirected(): Boolean { val edges = arrayOf(Pair("i", "j"), Pair("k", "i"), Pair("m", "k"), Pair("k", "l"), Pair("o", "n")) val graph = createAdjacencyList(edges) println(graph.toString()) return findPathUndirected(graph, "i", "j") } private fun findPathUndirected(graph: Map<String, Set<String>>, src: String, dst: String): Boolean { val queue: Queue<String> = LinkedList() queue.add(src) val visited = HashSet<String>() while (queue.isNotEmpty()) { val current = queue.poll() if (current.equals(dst)) { return true } if (!visited.contains(current)) { visited.add(current) graph[current]?.let { for (neighbor in graph[current]!!) { queue.add(neighbor) } } } } return false } fun depthFirst(graph: HashMap<String, Set<String>>, source: String) { val stack = Stack<String>() stack.push(source) while (stack.isNotEmpty()) { val current = stack.pop() println(current) graph[current]?.let { for (neighbor in graph[current]!!) { stack.push(neighbor) } } } } fun breadthFirst() { val graph = HashMap<String, Set<String>>() graph["a"] = setOf("b", "c") graph["b"] = setOf("d") graph["c"] = setOf("e") graph["d"] = setOf("f") graph["e"] = emptySet() graph["f"] = emptySet() breadthFirst(graph, "a") } fun breadthFirst(graph: HashMap<String, Set<String>>, source: String) { val queue: Queue<String> = LinkedList() queue.add(source) while (queue.isNotEmpty()) { val current = queue.poll() println(current) graph[current]?.let { for (neighbor in graph[current]!!) { queue.add(neighbor) } } } } private fun findPath() { val graph = HashMap<String, Set<String>>() graph["f"] = setOf("g", "i") graph["g"] = setOf("h") graph["h"] = emptySet() graph["i"] = setOf("g", "k") graph["j"] = setOf("i") graph["k"] = emptySet() println(this.findPath(graph, "j", "h")) } private fun findPath(graph: java.util.HashMap<String, Set<String>>, src: String, dst: String): Boolean { val queue: Queue<String> = LinkedList() queue.add(src) while (queue.isNotEmpty()) { val current = queue.poll() if (current.equals(dst)) { return true } graph[current]?.let { for (neighbor in graph[current]!!) { queue.add(neighbor) } } } return false } }
0
Kotlin
0
2
25d4ba029e4223ad88a2c353a56c966316dd577e
5,582
Problems
Apache License 2.0
2020/december10.kt
cuuzis
318,759,108
false
{"TypeScript": 105346, "Java": 65959, "Kotlin": 17038, "Scala": 5674, "JavaScript": 3511, "Shell": 724}
import java.io.File /** * https://adventofcode.com/2020/day/10 */ fun main() { println(star1()) // 1998 println(star2()) // 347250213298688 } private fun input(): List<String> { return File("2020/december10.txt").readLines(); } private fun star1(): Int { val adapters = input().map(String::toLong).sorted() var prev = 0L var ones = 0 var threes = 0 for (curr in adapters) { if (curr - prev == 3L) { threes++ } else if (curr - prev == 1L) { ones++ } prev = curr } // your device's built-in adapter is always 3 higher than the highest adapter threes++ //println("${ones} * ${threes}") return ones * threes } private fun star2(): Long { val adapters = input().map(String::toLong).sorted() var prev1 = 0L var prev1paths = 1L var prev2 = -99L var prev2paths = 1L var prev3 = -99L var prev3paths = 1L for (curr in adapters) { var pathsToCurr = 0L if (curr - prev1 <= 3L) { pathsToCurr += prev1paths } if (curr - prev2 <= 3L) { pathsToCurr += prev2paths } if (curr - prev3 <= 3L) { pathsToCurr += prev3paths } prev3 = prev2 prev2 = prev1 prev1 = curr prev3paths = prev2paths prev2paths = prev1paths prev1paths = pathsToCurr } return prev1paths }
0
TypeScript
0
1
35e56aa97f33fae5ed3e717dd01d303153caf467
1,439
adventofcode
MIT License
advent-of-code-2022/src/Day17.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import java.util.* fun main() { val testInput = readInput("Day17_test") val input = readInput("Day17") "Part 1" { part1(testInput) shouldBe 3068 measureAnswer { part1(input, print = true) } } "Part 2" { part2(testInput) shouldBe 1514285714288 println() measureAnswer { part2(input) } } } private const val WIDTH = 7 private fun part1(input: String, print: Boolean = false): Long { val chamber = TetrisChamber(input) repeat(times = 2022) { chamber.fallNext() } if (print) chamber.print() return chamber.height } private const val INSANE = 1_000_000_000_000 private fun part2(input: String): Long { val chamber = TetrisChamber(input) val cache = mutableMapOf<Int, Pair<Long, Long>>() var rock = 0L var heightShift = 0L while (rock < INSANE) { chamber.fallNext() val height = chamber.height val stateFingerprint = chamber.getStateFingerprint() if (stateFingerprint in cache) { val (cachedRock, cachedHeight) = cache.getValue(stateFingerprint) val rockDiff = rock - cachedRock val heightDiff = height - cachedHeight val times = (INSANE - rock) / rockDiff heightShift = heightDiff * times rock += rockDiff * times println("Cycle found! $cachedRock..$rock ($rockDiff), height = $heightDiff") println("Skip ${rockDiff * times} rocks") break } cache[stateFingerprint] = rock to height rock++ } println("Add ${INSANE - rock} rocks") while (rock < INSANE) { chamber.fallNext() rock++ } // Why -1? I have no idea... return chamber.height + heightShift - 1 } private class TetrisChamber(private val commands: String) { var height = 0L private val occupied = mutableMapOf<Pair<Long, Int>, String>() private var nextCommand = 0 private fun nextCommand(): Char { return commands[nextCommand].also { nextCommand = (nextCommand + 1) % commands.length } } fun fallNext() { val rock = nextRock() var positionX = START_X var positionY = height + START_Y fun fitsAt(x: Int = positionX, y: Long = positionY): Boolean { return (0 until rock.height) .all { r -> rock[r].none { c -> y + r to x + c in occupied } } } fun moveLeft() { if (positionX == 0) return if (fitsAt(x = positionX - 1)) positionX-- } fun moveRight() { if (positionX == WIDTH - rock.width) return if (fitsAt(x = positionX + 1)) positionX++ } fun moveDown(): Boolean { if (positionY == 0L) return false return if (fitsAt(y = positionY - 1)) { positionY-- true } else { false } } do { when (nextCommand()) { '<' -> moveLeft() '>' -> moveRight() } } while (moveDown()) height = maxOf(height, positionY + rock.height) for (r in 0 until rock.height) { for (c in rock[r]) { occupied[positionY + r to positionX + c] = rock.symbol } } } private var nextRock = 0 private fun nextRock(): Rock = Rock.rocks[nextRock].also { nextRock = (nextRock + 1) % Rock.rocks.size } fun print() { val chamber = Array(height.toInt()) { Array(WIDTH) { AIR } } for ((point, symbol) in occupied) chamber[point.first.toInt()][point.second] = symbol println(chamber.reversed().joinToString("\n") { it.joinToString("") }) } /** * State fingerprint includes `nextRock`, `nextCommand` and `depths`. * * Example of depths calculation: * ``` * [3,1,0,1,5,5,9] <- depths * . . # . . . . * . # # # . . . * # # # . . . . * # # . . . . . * . # . . . . . * . # # # # # . * . # . # . . . * . # . # . . . * . # # # . . . * ``` */ fun getStateFingerprint(): Int { val depths = (0 until WIDTH).map { x -> val y = ((height - 1) downTo 0).find { y -> y to x in occupied } ?: -1 height - y - 1 } return Objects.hash(nextRock, nextCommand, depths) } companion object { private const val AIR = "⬜️️" private const val START_X = 2 private const val START_Y = 3 } } private class Rock(val symbol: String, vararg val lines: IntRange) { val height = lines.size val width = lines.maxOf { it.last } + 1 operator fun get(i: Int) = lines[i] companion object { val rocks = listOf( // -- Rock("🟥", 0..3), // + Rock("🟩", 1..1, 0..2, 1..1), // L Rock("🟨", 0..2, 2..2, 2..2), // | Rock("🟦", 0..0, 0..0, 0..0, 0..0), // ◼ Rock("🟫", 0..1, 0..1), ) } } private fun readInput(name: String) = readText(name)
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
5,185
advent-of-code
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2021/Day16.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.mul import com.s13g.aoc.toBinary /** * --- Day 16: Packet Decoder --- * https://adventofcode.com/2021/day/16 */ class Day16 : Solver { override fun solve(lines: List<String>): Result { val input = Data(lines[0].map { it.toString().toInt(16).toBinary(4) }.reduce { all, it -> all + it }) val versionNumbers = mutableListOf<Int>() val partB = parse(input, versionNumbers) val partA = versionNumbers.sum() return Result("$partA", "$partB") } private fun parse(input: Data, versionNumbers: MutableList<Int>): Long { versionNumbers.add(input.take(3).toInt(2)) val typeId = input.take(3).toInt(2) val value: Long if (typeId == 4) { // Literal Packet var literalStr = "" while (true) { val lastGroup = input.take(1) == "0" literalStr += input.take(4) if (lastGroup) break; } value = literalStr.toLong(2) } else { // Operator Packet val lengthTypeId = input.take(1) var totalLength = Int.MAX_VALUE var numSubPackets = Int.MAX_VALUE if (lengthTypeId == "0") { totalLength = input.take(15).toInt(2) } else { numSubPackets = input.take(11).toInt(2) } // Parse sub-packets val subPacketsStart = input.idx val subResults = mutableListOf<Long>() while ((input.idx - subPacketsStart) < totalLength && subResults.size < numSubPackets) { subResults.add(parse(input, versionNumbers)) } value = when (typeId) { 0 -> subResults.sum() 1 -> subResults.mul() 2 -> subResults.min()!! 3 -> subResults.max()!! 5 -> if (subResults[0] > subResults[1]) 1 else 0 6 -> if (subResults[0] < subResults[1]) 1 else 0 7 -> if (subResults[0] == subResults[1]) 1 else 0 else -> error("Unknown typeId: $typeId") } } return value } private class Data(val input: String, var idx: Int = 0) { fun take(num: Int): String { idx += num return this.input.substring(idx - num, idx) } } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,146
euler
Apache License 2.0
Kotlin/problems/0003_add_two_numbers.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
// Problem Statement // You are given two non-empty linked lists representing two non-negative integers. // The digits are stored in reverse order and each of their nodes contain a single digit. // Add the two numbers and return it as a linked list. // // You may assume the two numbers do not contain any leading zero, except the number 0 itself. // class ListNode(var `val`: Int = 0) { var next: ListNode? = null } class Solution { fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { var irl1: ListNode? = l1; var irl2: ListNode? = l2; var dummy: ListNode? = ListNode(-1); var it: ListNode? = dummy; var carry: Int = 0; while(irl1!=null || irl2!=null){ var v1:Int = 0; var v2:Int = 0; if(irl1!=null){ v1 = irl1.`val`; irl1 = irl1?.next; } if(irl2!=null){ v2 = irl2.`val`; irl2 = irl2?.next; } var sum: Int = v1+v2+carry; if(sum>9){ carry = 1; sum = sum % 10; }else carry = 0; it?.next = ListNode(sum); it = it?.next; } if(carry>0) it?.next = ListNode(carry); return dummy?.next; } } fun vecToLinkedList(vec: IntArray) : ListNode?{ var dummy : ListNode? = ListNode(-1); var iterator : ListNode? = dummy; for(index in vec.indices){ iterator?.next = ListNode(vec[index]); iterator = iterator?.next; } return dummy?.next; } fun printListNode(list : ListNode?){ var iterator: ListNode? = list; while(iterator!=null){ print("${iterator.`val`} "); iterator = iterator.next; } println(); } fun main(args:Array<String>){ val vec1 : IntArray = intArrayOf(2,4,3); val vec2 : IntArray = intArrayOf(5,6,4); val list1 : ListNode? = vecToLinkedList(vec1); val list2 : ListNode? = vecToLinkedList(vec2); printListNode(list1); printListNode(list2); var solution : Solution = Solution(); printListNode(solution.addTwoNumbers(list1,list2)); }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
2,140
algorithms
MIT License
graph/MinimumSpanningTree.kt
wangchaohui
737,511,233
false
{"Kotlin": 36737}
class DisjointSet(size: Int) { private data class Node( var id: Int, ) { var parent: Node = this var size: Int = 1 } private val set = Array(size, ::Node) fun find(i: Int): Int = findNode(i).id private fun findNode(i: Int): Node { var x = set[i] while (x.parent != x) { x.parent = x.parent.parent x = x.parent } return x } fun union(i: Int, j: Int) { var x = findNode(i) var y = findNode(j) if (x == y) return if (x.size < y.size) x = y.also { y = x } y.parent = x x.size += y.size } } class MinimumSpanningTree(private val vertexSize: Int, edges: List<Edge>) { data class Edge( val u: Int, val v: Int, val w: Int, ) private val set = DisjointSet(vertexSize) private val edges = edges.sortedBy { it.w } fun kruskal(): List<Edge> = buildList { for (e in edges) { if (set.find(e.u) != set.find(e.v)) { add(e) set.union(e.u, e.v) } } } }
0
Kotlin
0
0
241841f86fdefa9624e2fcae2af014899a959cbe
1,126
kotlin-lib
Apache License 2.0
kotlin/src/main/kotlin/AoC_Day16.kt
sviams
115,921,582
false
null
import kotlin.streams.asStream object AoC_Day16 { val startState = ('a'..'p').joinToString("").toCharArray() val size = startState.size fun parseMoves(instructions: List<String>) : List<(CharArray) -> CharArray> { return instructions.fold(listOf()) { acc, instruction -> acc + parseInstruction(instruction) } } fun parseInstruction(input: String) : (CharArray) -> CharArray { return when (input.first()) { 's' -> spinFunc(input.substring(1 until input.length).toInt()) 'x' -> { val split = input.substring(1 until input.length).split("/") exchangeFunc(split[0].toInt(), split[1].toInt()) } else -> { val chars = input.toCharArray() partnerFunc(chars[1], chars[3]) } } } fun spinFunc(moves: Int) : (CharArray) -> CharArray = {state -> state.sliceArray(size-moves until size) + state.sliceArray(0 until size-moves)} fun exchangeFunc(first: Int, second: Int) : (CharArray) -> CharArray { val lower = Math.min(first, second) val upper = Math.max(first, second) return {state -> state.sliceArray(0 until lower) + state[upper] + state.sliceArray((lower+1) until upper) + state[lower] + state.sliceArray((upper+1) until size) } } fun partnerFunc(first: Char, second: Char) : (CharArray) -> CharArray = {state -> exchangeFunc(state.indexOf(first), state.indexOf(second))(state)} fun doAll(moves: List<(CharArray) -> CharArray>, initState: CharArray) : CharArray = moves.fold(initState) {state, move -> move(state)} fun solvePt1(input: List<String>) : String { val moveOps = parseMoves(input.first().split(",")) return doAll(moveOps, startState).joinToString("") } fun solvePt2(input: List<String>) : String { val moveOps = parseMoves(input.first().split(",")) val initial = doAll(moveOps, startState) val repeatCycle = generateSequence(initial) { doAll(moveOps, it) }.takeWhileInclusive { !(it contentEquals startState) } return repeatCycle.take(1000000000 % repeatCycle.count()).last().joinToString("") } }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
2,212
aoc17
MIT License
dcp_kotlin/src/main/kotlin/dcp/day207/day207.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day207 // day207.kt // By <NAME>, 2019. /** * A graph is bipartite if it is 2-colourable, and to determine if a graph is 2-colourable can be accomplished by * a greedy algorithm. This is due to detecting odd cycles, and a graph is bipartite iff it has no odd cycles. */ enum class Colour { BLACK, WHITE, UNVISITED } typealias Vertex = Int // We represent an immutable graph using an adjacency list and then just do a DFS. data class Graph(val vertices: List<Vertex>, val adjacencyList: Map<Vertex, Set<Vertex>>) { // We do a lazy calculation of whether or not the immutable graph is bipartite. val isBipartite: Boolean by lazy { calculateBipartite() } private fun calculateBipartite(): Boolean { val colours = mutableMapOf<Int, Colour>() vertices.forEach{ colours[it] = Colour.UNVISITED } while (true) { val v = vertices.find { colours[it] == Colour.UNVISITED } return if (v == null) true else colourVertexAndNeighbours(v, Colour.BLACK, colours) } } // Given a vertex and a colour, try to colour that vertex the specified colour. // Return true if the colouring is consistent, i.e. bipartite, and false if inconsistent, i.e. not bipartite. private fun colourVertexAndNeighbours(v: Vertex, c: Colour, colours: MutableMap<Vertex, Colour>): Boolean { // If the colour is already set, make sure it is consistent. if (colours[v] != Colour.UNVISITED) { if (colours[v] != c) return false if (colours[v] == c) return true } colours[v] = c // Set the colour of all the neighbours to the opposite. val neighbours = adjacencyList[v] if (neighbours != null) { val otherColour = if (c == Colour.BLACK) Colour.WHITE else Colour.BLACK for (n in neighbours.toList()) if (!colourVertexAndNeighbours(n, otherColour, colours)) return false } return true } }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
2,109
daily-coding-problem
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/WordBreak.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.utils.Dp /** * 139. Word Break */ fun interface WordBreak { operator fun invoke(s: String, wordDict: List<String>): Boolean } class WordBreakBruteForce : WordBreak { override operator fun invoke(s: String, wordDict: List<String>): Boolean { return wb(s, HashSet(wordDict)) } private fun wb(s: String, set: Set<String>): Boolean { val len = s.length if (len == 0) { return true } for (i in 1..len) { if (set.contains(s.substring(0, i)) && wb(s.substring(i), set)) { return true } } return false } } @Dp class WordBreakDP : WordBreak { override operator fun invoke(s: String, wordDict: List<String>): Boolean { val dp = BooleanArray(s.length + 1) val set: MutableSet<String> = HashSet() set.addAll(wordDict) dp[0] = true for (i in 1..s.length) { for (j in i - 1 downTo 0) { dp[i] = dp[j] && set.contains(s.substring(j, i)) if (dp[i]) break } } return dp[s.length] } } /** * https://leetcode.com/problems/word-break/ * * Time Complexity: O(L ^ 2) * Space Complexity: O(L) * * References: * https://leetcode.com/problems/word-break/discuss/43819/DFS-with-Path-Memorizing-Java-Solution */ class WordBreakDFS : WordBreak { override operator fun invoke(s: String, wordDict: List<String>): Boolean { if (s.isEmpty()) return false val wordSet = HashSet(wordDict) val seen = HashSet<Int>() return dfs(0, s, seen, wordSet) } private fun dfs( idx: Int, s: String, seen: HashSet<Int>, wordSet: HashSet<String>, ): Boolean { val len = s.length if (idx == len) return true if (seen.contains(idx)) return false for (i in idx + 1..len) { val sub = s.substring(idx, i) if (!wordSet.contains(sub)) continue if (dfs(i, s, seen, wordSet)) return true } seen.add(idx) return false } } /** * https://leetcode.com/problems/word-break/ * * Time Complexity: O(L ^ 2) + O(N * L) / O(N) ~ O(L ^ 2) * Space Complexity: O(N) */ class WordBreakBFS : WordBreak { override operator fun invoke(s: String, wordDict: List<String>): Boolean { if (s.isEmpty()) return false val wordSet = HashSet(wordDict) val queue = ArrayDeque<String>() val seen = HashSet<String>() queue.add(s) seen.add(s) while (queue.isNotEmpty()) { val size = queue.size for (sz in 0 until size) { val cur = queue.removeFirst() val len = cur.length if (processSubstring(cur, len, wordSet, seen, queue)) { return true } } } return false } private fun processSubstring( cur: String, len: Int, wordSet: Set<String>, seen: MutableSet<String>, queue: MutableList<String>, ): Boolean { for (idx in 1..len) { if (!wordSet.contains(cur.substring(0, idx))) continue if (idx == len) return true val sub = cur.substring(idx) if (!seen.add(sub)) continue queue.add(sub) } return false } } /** * https://leetcode.com/problems/word-break/ * * Time Complexity: O(L ^ 2) + O(totalWords) * Space Complexity: O(L) * * References: * https://leetcode.com/problems/word-break/discuss/43790/Java-implementation-using-DP-in-two-ways */ class WordBreakDP2 : WordBreak { override operator fun invoke(s: String, wordDict: List<String>): Boolean { if (s.isEmpty()) return false val len = s.length val wordSet = HashSet(wordDict) val dp = BooleanArray(len + 1) dp[0] = true for (hi in 1..len) { for (lo in 0..hi) { if (dp[lo] && wordSet.contains(s.substring(lo, hi))) { dp[hi] = true break } } } return dp[len] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,897
kotlab
Apache License 2.0
Day18/src/Cave.kt
gautemo
225,219,298
false
null
import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.io.File import kotlin.math.abs import kotlin.system.measureTimeMillis fun main(){ val input = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText() println(bestOneMap(input)) println(bestSplittedMap(input.trim())) // This is slow, just try the numbers on the way } fun bestOneMap(input: String): Int{ val map = Map(input, listOf(Bot(input.indexOf('@'), '@'))) val keyKnower = KeyKnower(map) val finder = Finder(map, keyKnower) return bestPath(finder) } fun bestSplittedMap(input: String): Int{ val newMap = splitMap(input) val singlemaps = singleMaps(newMap).map { Map(it, listOf()) }.toTypedArray() val keyKnower = KeyKnower(*singlemaps) val bot1 = Bot(newMap.indexOf('@'), '@') val bot2 = Bot(newMap.indexOf('&'), '&') val bot3 = Bot(newMap.indexOf('$'), '$') val bot4 = Bot(newMap.indexOf('%'), '%') val finder = Finder(Map(newMap, listOf(bot1, bot2, bot3, bot4)), keyKnower) return bestPath(finder) } fun bestPath(finder: Finder): Int { finder.check() return finder.bestStep } class Finder(map: Map, val keyKnower: KeyKnower){ private val history = History(map.map) var bestStep = Int.MAX_VALUE private val mutex = Mutex() init{ addCanGo(map) } private fun addCanGo(map: Map, alreadySteps: Int = 0){ map.bots.forEach {b -> val canGo = map.canGoToKeys(b, keyKnower).map { val m = map.copy(); ValidPath(m, m.go(b.place, it.first, true, true), alreadySteps + it.second) }.filter { it.steps < bestStep } history.toCheck.addAll(canGo) } } fun check(){ while (history.toCheck.isNotEmpty()) { val t = measureTimeMillis { runBlocking { val runOn = history.toCheck.sortedWith(compareBy { it.map.keysLeft.size }).take(5000) history.toCheck.removeAll(runOn) runOn.forEach { path -> launch { path.map.open(path.goesTo) if (path.map.keysLeft.size == 0) { mutex.withLock { bestStep = minOf(path.steps, bestStep) } println("Found all keys in ${path.steps}") } addCanGo(path.map, path.steps) } } } } //println("Batch took $t. toCheck: ${history.toCheck.size}. Best: $bestStep") } } } class History(initialMap: String){ private val alreadyExistedOnStep = hashMapOf(initialMap to 0) var toCheck = mutableSetOf<ValidPath>() fun exists(map: String, steps: Int): Boolean{ val state = alreadyExistedOnStep[map] return state != null && steps > state } fun addMap(map: String, steps: Int){ alreadyExistedOnStep[map] = steps } } class Map(var map: String, val bots: List<Bot>){ var keysLeft = map.filter { it.isKey() }.toMutableList() private val width = map.lines().first().length + 1 constructor(map: String, bots: List<Bot>, keysLeft: MutableList<Char>) : this(map, bots) { this.keysLeft = keysLeft } fun open(key: Char){ map = map.replace(key.toUpperCase(), '.') keysLeft.remove(key) } private fun on(key: Char) = map.indexOfFirst { it == key } fun go(from: Int, to: Int, changeLastKey: Boolean, markMap: Boolean = false): Char{ val go = map[to] val bot = bots.first { it.place == from } bot.place = to if(markMap) { map = map.replace(from, '.').replace(to, '@') } if(changeLastKey){ bot.lastKey = go } return go } fun canGoToKeys(bot: Bot, keysKnower: KeyKnower): List<Pair<Int, Int>>{ return keysLeft .filter { val link = KeyKnower.keysToKey(bot.lastKey, it); keysKnower.keys.containsKey(link) && keysKnower.keys[link]!!.second.none { blocked -> keysLeft.contains(blocked) } && keysKnower.keys[link]!!.third.none { k -> keysLeft.contains(k) }} .map { Pair(on(it), keysKnower.keys[KeyKnower.keysToKey(bot.lastKey, it)]!!.first) } } fun canGo(bot: Bot): List<Int>{ val up = bot.place - width val down = bot.place + width val left = bot.place-1 val right = bot.place+1 val adjecant = mutableListOf<Int>() if(up >= 0 && map[up].isWalkable()) adjecant.add(up) if(down < map.length && map[down].isWalkable()) adjecant.add(down) if(right < map.length && right / width == bot.place / width && map[right].isWalkable()) adjecant.add(right) if(left >= 0 && left / width == bot.place / width && map[left].isWalkable()) adjecant.add(left) return adjecant.toList() } fun dist(pos: Int, key: Char): Int{ val on = on(key) val x = abs((pos % width) - (on % width)) val y = abs((pos / width) - (on / width)) return x + y } fun copy() = Map(map, bots.map { it.copy() }, keysLeft.toMutableList()) fun print(){ println(map()) } fun map(): String{ var realMap = map.replace('@', '.') bots.forEach { realMap = realMap.replace(it.place, '@') } return realMap } } class KeyKnower(vararg maps: Map){ val keys = hashMapOf<String, Triple<Int, List<Char>, List<Char>>>() init { val t = measureTimeMillis { maps.forEach { map -> val botSign = botSign(map.map) map.keysLeft.forEach { key1 -> keys[keysToKey(botSign, key1)] = findKey(map.map,botSign, key1) map.keysLeft.forEach { key2 -> val hashKey = keysToKey(key1, key2) if (key1 != key2 && !keys.containsKey(hashKey)) { keys[hashKey] = findKey(map.map, key1, key2) } } } } } println("Map keys took ${(t / 1000) / 60}m") } private fun findKey(map: String, key1: Char, key2: Char): Triple<Int, List<Char>, List<Char>>{ val botSign = botSign(map) var startAtKey = map if(key1 != botSign) { startAtKey = startAtKey.replace(botSign, '.').replace(key1, botSign) } val history = History(startAtKey) val useMap = Map(startAtKey, listOf(Bot(startAtKey.indexOf(botSign), botSign))) val startGo = useMap.canGo(useMap.bots.first()).map { val m = useMap.copy(); val dist = m.dist(it, key2); ValidPath(m, m.go(m.bots.first().place, it, true), 0, dist) }.filter { !history.exists(it.map.map(), 1) } history.toCheck.addAll(startGo) var bestStep = Int.MAX_VALUE while (history.toCheck.isNotEmpty()){ val path = history.toCheck.sortedWith(compareBy(ValidPath::steps)).first() history.toCheck.remove(path) path.steps++ if(path.goesTo == key2){ bestStep = minOf(path.steps, bestStep) return Triple(path.steps, path.blockedByKey.toList(), path.keyOnWay.toList()) }else{ if(path.goesTo.isKey()){ path.keyOnWay.add(path.goesTo) }else if(path.goesTo.isDoor()){ path.blockedByKey.add(path.goesTo.toLowerCase()) } val canGo = path.map.canGo(path.map.bots.first()).map { val m = path.map.copy(); val dist = m.dist(it, key2); ValidPath(m, m.go(m.bots.first().place, it, true), path.steps, dist, path.blockedByKey.toMutableList(), path.keyOnWay.toMutableList()) }.filter { !history.exists(it.map.map(), it.steps + 1) && it.steps + 1 < bestStep } history.toCheck.addAll(canGo) } history.addMap(path.map.map(), path.steps) } return Triple(-1, listOf(), listOf()) } companion object{ fun keysToKey(key1: Char, key2: Char): String{ val hashKey = charArrayOf(key1, key2) hashKey.sort() return hashKey.joinToString() } } } data class ValidPath(val map: Map, val goesTo: Char, var steps: Int, val dist: Int = 0, val blockedByKey: MutableList<Char> = mutableListOf(), val keyOnWay: MutableList<Char> = mutableListOf()) fun Char.isKey() = this.isLowerCase() fun Char.isDoor() = this.isUpperCase() fun Char.isWalkable() = this != '#' fun String.replace(pos: Int, c: Char) = this.substring(0, pos) + c + this.substring(pos + 1) fun splitMap(map: String): String { val width = map.lines().first().length val at = map.indexOf('@') return map.replace(at, '#').replace(at - 1, '#').replace(at + 1, '#') .replace(at - (width+1), '#').replace(at + (width+1), '#') .replace(at + 1 - (width+1), '@').replace(at -1 - (width+1), '&') .replace(at + 1 + (width+1), '$').replace(at -1 + (width+1), '%') } fun singleMaps(map: String): List<String>{ val width = map.lines().first().length val height = map.lines().size var map1 = "" var map2 = "" var map3 = "" var map4 = "" for ((i, line) in map.lines().withIndex()){ if(i < height / 2){ map1 += line.substring(0, width / 2) map2 += line.substring((width / 2)+1) map1 += "\n" map2 += "\n" }else if(i > height / 2){ map3 += line.substring(0, width / 2) map4 += line.substring((width / 2)+1) map3 += "\n" map4 += "\n" } } return listOf(map1.trim(), map2.trim(), map3.trim(), map4.trim()) } fun botSign(map: String): Char{ return when{ map.contains('@') -> '@' map.contains('&') -> '&' map.contains('$') -> '$' else -> '%' } } data class Bot(var place: Int, var lastKey: Char)
0
Kotlin
0
0
f8ac96e7b8af13202f9233bb5a736d72261c3a3b
10,180
AdventOfCode2019
MIT License
src/me/bytebeats/algo/kt/Solution11.kt
bytebeats
251,234,289
false
null
package me.bytebeats.algo.kt import me.bytebeats.algs.ds.ListNode import me.bytebeats.algs.ds.TreeNode /** * @author bytebeats * @email <<EMAIL>> * @github https://github.com/bytebeats * @created on 2020/9/3 11:07 * @version 1.0 * @description TO-DO */ class Solution11 { fun solveNQueens(n: Int): List<List<String>> {//51 N Queens val ans = mutableListOf<MutableList<String>>() val queens = IntArray(n) { -1 } val columns = mutableSetOf<Int>() val diagonals1 = mutableSetOf<Int>() val diagonals2 = mutableSetOf<Int>() backtrack(ans, queens, n, 0, columns, diagonals1, diagonals2) return ans } private fun backtrack( ans: MutableList<MutableList<String>>, queens: IntArray, n: Int, row: Int, columns: MutableSet<Int>, diagonals1: MutableSet<Int>, diagonals2: MutableSet<Int> ) { if (row == n) { val board = generateBoard(queens, n) ans.add(board) } else { for (i in 0 until n) { if (columns.contains(i)) continue val diagonal1 = row - i if (diagonals1.contains(diagonal1)) continue val diagonal2 = row + i if (diagonals2.contains(diagonal2)) continue queens[row] = i columns.add(i) diagonals1.add(diagonal1) diagonals2.add(diagonal2) backtrack(ans, queens, n, row + 1, columns, diagonals1, diagonals2) queens[row] = -1 columns.remove(i) diagonals1.remove(diagonal1) diagonals2.remove(diagonal2) } } } private fun generateBoard(queens: IntArray, n: Int): MutableList<String> { val board = mutableListOf<String>() for (i in 0 until n) { val row = CharArray(n) { '.' } row[queens[i]] = 'Q' board.add(String(row)) } return board } fun partitionLabels(S: String): List<Int> {//763 val last = IntArray(26) for (i in S.indices) { last[S[i] - 'a'] = i } val ans = mutableListOf<Int>() var j = 0 var anchor = 0 for (i in S.indices) { j = j.coerceAtLeast(last[S[i] - 'a']) if (i == j) { ans.add(i - anchor + 1) anchor = i + 1 } } return ans } fun getAllElements(root1: TreeNode?, root2: TreeNode?): List<Int> {//1305 val list1 = mutableListOf<Int>() convertTree2List(root1, list1) val list2 = mutableListOf<Int>() convertTree2List(root2, list2) list1.addAll(list2) return list1.sorted() } private fun convertTree2List(root: TreeNode?, list: MutableList<Int>) { if (root == null) return if (root.left != null) { convertTree2List(root.left, list) } list.add(root.`val`) if (root.right != null) { convertTree2List(root.right, list) } } fun diagonalSum(mat: Array<IntArray>): Int {//5491, 1561 var sum = 0 val n = mat.size for (i in 0 until n) { sum += mat[i][i] sum += mat[i][n - i - 1] } if (n and 1 == 1) { val idx = n shr 1 sum -= mat[idx][idx] } return sum } fun mostVisited(n: Int, rounds: IntArray): List<Int> {//1560 val ans = mutableListOf<Int>() var start = rounds.first() var end = rounds.last() if (start <= end) { for (i in start..end) { ans.add(i) } } else { for (i in 1..end) { ans.add(i) } for (i in start..n) { ans.add(i) } } return ans } fun modifyString(s: String): String {//1576 val ans = StringBuilder(s) for (i in s.indices) { if (s[i] == '?') { if (i == 0 && i == s.length - 1) { ans[i] = 'a' } else if (i == 0) { if (s[i + 1] == '?') { ans[i] = 'a' } else { for (j in 'a'..'z') { if (j != s[i + 1]) { ans[i] = j break } } } } else if (i == s.length - 1) { for (j in 'a'..'z') { if (j != ans[i - 1]) { ans[i] = j break } } } else { if (s[i + 1] == '?') { for (j in 'a'..'z') { if (j != ans[i - 1]) { ans[i] = j break } } } else { for (j in 'a'..'z') { if (j != s[i + 1] && j != ans[i - 1]) { ans[i] = j break } } } } } else { continue } } return ans.toString() } private val tmp = mutableListOf<Int>() private val ans = mutableListOf<MutableList<Int>>() fun combine(n: Int, k: Int): List<List<Int>> {//77 dfs(1, n, k) return ans } private fun dfs(cur: Int, n: Int, k: Int) { if (tmp.size + n - cur + 1 < k) return if (tmp.size == k) { val list = mutableListOf<Int>() list.addAll(tmp) ans.add(list) return } tmp.add(cur) dfs(cur + 1, n, k) tmp.removeAt(tmp.lastIndex) dfs(cur + 1, n, k) } private val tmp1 = mutableListOf<Int>() private val ans1 = mutableListOf<MutableList<Int>>() fun combinationSum3(k: Int, n: Int): List<List<Int>> {//216 dfs(1, 9, k, n) return ans1 } private fun dfs(cur: Int, n: Int, k: Int, sum: Int) { if (tmp1.size + n - cur + 1 < k || tmp1.size > k) return if (tmp1.size == k) { var tmpSum = tmp1.sum() if (tmpSum == sum) { val list = mutableListOf<Int>() list.addAll(tmp1) ans1.add(list) return } } tmp1.add(cur) dfs(cur + 1, n, k, sum) tmp1.removeAt(tmp1.lastIndex) dfs(cur + 1, n, k, sum) } fun calculate(s: String): Int {//lccd 1 var x = 1 var y = 0 for (c in s) { if (c == 'A') { x = 2 * x + y } else { y = 2 * y + x } } return x + y } fun breakfastNumber(staple: IntArray, drinks: IntArray, x: Int): Int {//lccd 2 val mode = 1000000007 staple.sort() drinks.sort() var ans = 0 for (i in staple.indices) { if (staple[i] + drinks.first() > x) { break } else if (staple[i] + drinks.last() <= x) { ans = (ans + drinks.size) % mode } else { var s = 0 var e = drinks.lastIndex var mid = 0 while (s < e) { mid = s + (e - s) / 2 if (staple[i] + drinks[mid] > x) { while (mid > 0 && drinks[mid] == drinks[mid - 1]) { mid -= 1 } e = mid } else { while (mid < drinks.lastIndex && drinks[mid] == drinks[mid + 1]) { mid += 1 } s = mid + 1 } } ans = (ans + s) % mode } } return ans } fun minimumOperations(leaves: String): Int {//lccd 3 var ans = 0 val rys = mutableListOf<Char>() val ryCounts = mutableListOf<Int>() var ry = leaves.first() var ryCount = 0 for (c in leaves) { if (c == ry) { ryCount += 1 } else { rys.add(ry) ryCounts.add(ryCount) ry = c ryCount = 1 } } if (rys.isEmpty() || rys.last() != ry) { rys.add(ry) ryCounts.add(ryCount) } if (rys.size == 1) return -1 if (rys.first() != rys.last()) { if (rys.size == 2) return 1 if (rys.first() == 'r') { // ans += ryCounts.last() for (i in 1 until rys.size - 2) { if (rys[i] == 'r') { ans += ryCounts[i] } } } else { // ans += ryCounts.first() for (i in 2 until rys.size - 1) { if (rys[i] == 'r') { ans += ryCounts[i] } } } } else { for (i in 1 until rys.size - 1) { if (rys[i] == 'r') { ans += ryCounts[i] } } } return ans } fun averageOfLevels(root: TreeNode?): DoubleArray {//637 val ans = mutableListOf<Double>() if (root != null) { val q = mutableListOf<TreeNode>() q.add(root) var countDown = 1 var preCount = countDown var count = 0 var n: TreeNode? = null var sum = 0.0 while (q.isNotEmpty()) { n = q.removeAt(0) countDown -= 1 sum += n.`val` if (n.left != null) { count += 1 q.add(n.left) } if (n.right != null) { count += 1 q.add(n.right) } if (countDown == 0) { ans.add(sum / preCount) countDown = count count = 0 sum = 0.0 preCount = countDown } } } return ans.toDoubleArray() } fun findMaximumXOR(nums: IntArray): Int {//421 val max = nums.maxOfOrNull { it } val l = max?.toString(2)?.length ?: 0 var maxXor = 0 var curXor = 0 val prefixes = mutableSetOf<Int>() for (i in l - 1 downTo 0) { maxXor = maxXor shl 1 curXor = maxXor or 1 prefixes.clear() prefixes.addAll(nums.map { it shr i }) for (prefix in prefixes) { if (prefixes.contains(curXor xor prefix)) { maxXor = curXor break } } } return maxXor } fun sequentialDigits(low: Int, high: Int): List<Int> {//1291 val ans = mutableListOf<Int>() for (i in 1..9) { var num = i for (j in i + 1..9) { num = num * 10 + j if (num in low..high) { ans.add(num) } } } return ans.sorted() } fun reorderSpaces(text: String): String {//1592 var space = text.count { it == ' ' } val words = text.split("\\s+".toRegex()).filter { it.isNotEmpty() } val ans = StringBuilder() var span = 0 var suffix = 0 if (words.size == 1) { span = 0 suffix = space } else { span = space / (words.size - 1) suffix = space % (words.size - 1) } var tmp = 0 for (word in words) { if (ans.isNotEmpty()) { tmp = span while (tmp > 0) { ans.append(' ') tmp -= 1 } } ans.append(word) } tmp = suffix while (tmp > 0) { ans.append(' ') tmp -= 1 } return ans.toString() } fun sumOddLengthSubarrays(arr: IntArray): Int {//1588 val n = arr.size val odd = if (n and 1 == 0) n - 1 else n var ans = 0 for (l in 1..odd step 2) { for (i in 0..n - l) { for (j in i until i + l) { ans += arr[j] } } } return ans } fun numSpecial(mat: Array<IntArray>): Int {//1582 val r = mat.size val c = mat[0].size var ans = 0 for (i in 0 until r) for (j in 0 until c) if (mat[i][j] == 1) { var hS = true for (k in 0 until r) { if (k == i) continue if (mat[k][j] == 1) { hS = false break } } var vS = true for (k in 0 until c) { if (k == j) continue if (mat[i][k] == 1) { vS = false break } } if (hS && vS) ans += 1 } return ans } fun convertBST(root: TreeNode?): TreeNode? {//538 if (root != null) { val vals = mutableListOf<Int>() vals(root, vals) dfs(root, vals) } return root } private fun dfs(root: TreeNode?, vals: MutableList<Int>) { if (root != null) { root.`val` += vals.filter { it > root.`val` }.sum() dfs(root.left, vals) dfs(root.right, vals) } } private fun vals(root: TreeNode?, vals: MutableList<Int>) { if (root != null) { vals.add(root.`val`) vals(root.left, vals) vals(root.right, vals) } } fun minCameraCover(root: TreeNode?): Int {//968 val ans = dfs(root) return ans[1] } private fun dfs(root: TreeNode?): IntArray { if (root == null) return intArrayOf(Int.MAX_VALUE / 2, 0, 0) val leftArray = dfs(root.left) val rightArray = dfs(root.right) val arr = IntArray(3) arr[0] = leftArray[2] + rightArray[2] + 1 arr[1] = Math.min(arr[0], Math.min(leftArray[0] + rightArray[1], rightArray[0] + leftArray[1])) arr[2] = Math.min(arr[0], leftArray[1] + rightArray[1]) return arr } fun calcEquation( equations: List<List<String>>, values: DoubleArray, queries: List<List<String>> ): DoubleArray {//399, this is wrong answer. val map = mutableMapOf<String, Double>() for (i in equations.indices) { if (!map.containsKey(equations[i][0]) && !map.containsKey(equations[i][1])) { map[equations[i][1]] = 1.0 map[equations[i][0]] = values[i] } else if (map.containsKey(equations[i][0])) { map[equations[i][1]] = map[equations[i][0]]!! / values[i] } else if (map.containsKey(equations[i][1])) { map[equations[i][0]] = map[equations[i][1]]!! * values[i] } else { } } val ans = DoubleArray(queries.size) for (i in queries.indices) { if (map.containsKey(queries[i][0]) && map.containsKey(queries[i][1])) { ans[i] = map[queries[i][0]]!! / map[queries[i][i]]!! } else { ans[i] = -1.0 } } return ans } fun postorderTraversal(root: TreeNode?): List<Int> {//145 val ans = mutableListOf<Int>() post(root, ans) return ans } private fun post(root: TreeNode?, list: MutableList<Int>) { if (root == null) return post(root.left, list) post(root.right, list) list.add(root.`val`) } fun removeCoveredIntervals(intervals: Array<IntArray>): Int {//1288 intervals.sortWith(Comparator { o1, o2 -> if (o1[0] != o2[0]) { return@Comparator o1[0] - o2[0] } else { return@Comparator -o1[1] + o2[1] } }) var count = 0 var end = 0 var preEnd = 0 for (ints in intervals) { end = ints[1] if (preEnd < end) { count += 1 preEnd = end } } return count } fun findMinArrowShots(points: Array<IntArray>): Int {//452 var arrows = 0 if (points.isNotEmpty()) { points.sortBy { it[1] } arrows = 1 var firstEnd = points.first()[1] for (p in points) { if (firstEnd < p[0]) { arrows += 1 firstEnd = p[1] } } } return arrows } fun canPartition(nums: IntArray): Boolean {//416 if (nums.size < 2) return false var sum = 0 var maxNum = 0 for (num in nums) { sum += num maxNum = maxNum.coerceAtLeast(num) } if (sum and 1 == 1) return false val target = sum / 2 if (maxNum > target) return false val dp = BooleanArray(target + 1) { false } dp[0] = true for (num in nums) { for (j in target downTo num) { dp[j] = dp[j] or dp[j - num] } } return dp[target] } fun removeDuplicateLetters(s: String): String {//316, 1081 val stack = mutableListOf<Char>() val seen = mutableSetOf<Char>() val lastIdx = mutableMapOf<Char, Int>() for (i in s.indices) { lastIdx[s[i]] = i } for (i in s.indices) { if (!seen.contains(s[i])) { while (stack.isNotEmpty() && s[i] < stack.last() && lastIdx[stack.last()]!! > i) { seen.remove(stack.last()) stack.removeAt(stack.lastIndex) } seen.add(s[i]) stack.add(s[i]) } } val ans = StringBuilder() for (c in stack) { ans.append(c) } return ans.toString() } fun swapPairs(head: ListNode?): ListNode? {//24 if (head?.next == null) return head val next = head.next head.next = swapPairs(next.next) next.next = head return next } fun sortList(head: ListNode?): ListNode? {//148 if (head != null) { var s: ListNode? = null var e: ListNode? = null s = head while (s?.next != null) { s = s.next } e = s s = head quickSort(s, e) } return head } private fun quickSort(s: ListNode?, e: ListNode?) { if (s == null || e == null || s == e) return var p = s var q = s.next val v = s.`val` var tmp = 0 while (q != e.next) { if (q.`val` < v) { p = p!!.next tmp = p!!.`val` p!!.`val` = q.`val` q.`val` = tmp } q = q.next } tmp = v s.`val` = p!!.`val` p.`val` = tmp quickSort(s, p) quickSort(p.next, e) } fun insertionSortList(head: ListNode?): ListNode? {//147 val dummy = ListNode(-1) dummy.next = head if (head?.next != null) { var p: ListNode? = head while (p?.next != null) { if (p.`val` <= p.next.`val`) { p = p.next } else { val next = p.next p.next = next.next next.next = null var q = dummy while (q.next != p && q.next.`val` < next.`val`) { q = q.next } next.next = q.next q.next = next } } } return dummy.next } fun insert(head: ListNode?, insertVal: Int): ListNode? {//708 if (head == null) return ListNode(insertVal).apply { next = this } var cur = head while (cur!!.next != head) { if (cur.`val` <= insertVal) { if (cur.next!!.`val` > insertVal) break else if (cur.next!!.`val` < cur.`val`) break } else { if (cur.next!!.`val` < cur.`val` && insertVal < cur.next!!.`val`) break } cur = cur.next } val node = ListNode(insertVal) node.next = cur.next cur.next = node return head } fun totalNQueens(n: Int): Int {//52 val columns = mutableSetOf<Int>() val diagonals1 = mutableSetOf<Int>() val diagonals2 = mutableSetOf<Int>() return backtrack(n, 0, columns, diagonals1, diagonals2) } private fun backtrack( n: Int, row: Int, columns: MutableSet<Int>, diagonals1: MutableSet<Int>, diagonals2: MutableSet<Int> ): Int { if (row == n) return 1 else { var count = 0 for (i in 0 until n) { if (columns.contains(i)) continue val diagonal1 = row - i if (diagonals1.contains(diagonal1)) continue val diagonal2 = row + i if (diagonals2.contains(diagonal2)) continue columns.add(i) diagonals1.add(diagonal1) diagonals2.add(diagonal2) count += backtrack(n, row + 1, columns, diagonals1, diagonals2) columns.remove(i) diagonals1.remove(diagonal1) diagonals2.remove(diagonal2) } return count } } fun findRepeatedDnaSequences(s: String): List<String> {//187 val L = 10 val n = s.length if (n <= L) return emptyList() val a = 4 val aL = Math.pow(a.toDouble(), L.toDouble()).toInt() val toInt = mutableMapOf<Char, Int>() toInt['A'] = 0 toInt['C'] = 1 toInt['G'] = 2 toInt['T'] = 3 val nums = IntArray(n) for (i in 0 until n) { nums[i] = toInt[s[i]]!! } var h = 0 val seen = mutableSetOf<Int>() val output = mutableSetOf<String>() for (i in 0..(n - L)) { if (i == 0) { for (j in 0 until L) { h = h * a + nums[j] } } else { h = h * a - nums[i - 1] * aL + nums[i + L - 1] } if (seen.contains(h)) output.add(s.substring(i, i + L)) seen.add(h) } return output.toList() } fun maxProfit(k: Int, prices: IntArray): Int {//188 if (prices.isEmpty()) return 0 val n = prices.size if (k >= n / 2) { var dp0 = 0 var dp1 = -prices[0] for (i in 1 until n) { val tmp = dp0 dp0 = dp0.coerceAtLeast(dp1 + prices[i]) dp1 = dp1.coerceAtLeast(tmp - prices[i]) } return dp0.coerceAtLeast(dp1) } else { val dp = Array(k + 1) { IntArray(2) } var res = 0 for (i in 0..k) { dp[i][0] = 0 dp[i][1] = -prices[0] } for (i in 1 until n) { for (j in k downTo 1) { dp[j - 1][1] = dp[j - 1][1].coerceAtLeast(dp[j - 1][0] - prices[i]) dp[j][0] = dp[j][0].coerceAtLeast(dp[j - 1][1] + prices[i]) } } return dp[k][0] } } fun minDominoRotations(A: IntArray, B: IntArray): Int {//1007 val n = A.size val rotations = check(A[0], B, A, n) return if (rotations != -1 || A[0] == B[0]) rotations else check(B[0], B, A, n) } private fun check(x: Int, A: IntArray, B: IntArray, n: Int): Int { var rotationA = 0 var rotationB = 0 for (i in 0 until n) { if (A[i] != x && B[i] != x) return -1 else if (A[i] != x) rotationA += 1 else if (B[i] != x) rotationB += 1 } return rotationA.coerceAtMost(rotationB) } fun asteroidCollision(asteroids: IntArray): IntArray {//735 val stack = mutableListOf<Int>() for (a in asteroids) { var aa = a if (aa > 0) { stack.add(a) } else { aa = -a var i = stack.lastIndex while (i > -1) { if (stack[i] < 0) { stack.add(a) break } if (aa < stack[i]) { break } else if (aa == stack[i]) { stack.removeAt(stack.lastIndex) break } else { stack.removeAt(stack.lastIndex) --i } } if (i == -1) { stack.add(a) } } } return stack.toIntArray() } fun find132pattern(nums: IntArray): Boolean {//456 if (nums.size > 2) { val n = nums.size val stack = mutableListOf<Int>() val min = IntArray(n) min[0] = nums[0] for (i in 1 until n) { min[i] = min[i - 1].coerceAtMost(nums[i]) } for (i in n - 1 downTo 0) { if (nums[i] > min[i]) { while (stack.isNotEmpty() && stack.last() <= min[i]) { stack.removeAt(stack.lastIndex) } if (stack.isNotEmpty() && stack.last() < nums[i]) { return true } stack.add(nums[i]) } } } return false } fun videoStitching(clips: Array<IntArray>, T: Int): Int {//1024 val dp = IntArray(T + 1) { Int.MAX_VALUE - 1 } dp[0] = 0 for (i in 1..T) { for (clip in clips) { if (clip[0] < i && i <= clip[1]) { dp[i] = dp[i].coerceAtMost(dp[clip[0]] + 1) } } } return if (dp[T] == Int.MAX_VALUE - 1) -1 else dp[T] } fun bagOfTokensScore(tokens: IntArray, P: Int): Int {//948 tokens.sort() var low = 0 var high = tokens.size - 1 var points = 0 var ans = 0 var p = P while (low <= high && (p >= tokens[low] || points > 0)) { while (low <= high && p >= tokens[low]) { p -= tokens[low++] points += 1 } ans = ans.coerceAtLeast(points) if (low <= high && points > 0) { p += tokens[high--] points-- } } return ans } fun summaryRanges(nums: IntArray): List<String> {//228 val ans = mutableListOf<String>() if (nums.isNotEmpty()) { var i = 0 var j = 1 while (j < nums.size) { if (nums[j - 1] + 1 != nums[j]) { if (i == j - 1) { ans.add("${nums[i]}") } else { ans.add("${nums[i]}->${nums[j - 1]}") } i = j } j += 1 } if (i == j - 1) { ans.add("${nums[i]}") } else { ans.add("${nums[i]}->${nums[j - 1]}") } } return ans } fun findNumberOfLIS(nums: IntArray): Int {//673 val n = nums.size if (n <= 1) return n val lengths = IntArray(n) { 0 } val counts = IntArray(n) { 1 } for (j in 0 until n) for (i in 0 until j) if (nums[i] < nums[j]) { if (lengths[i] >= lengths[j]) { lengths[j] = lengths[i] + 1 counts[j] = counts[i] } else if (lengths[i] + 1 == lengths[j]) { counts[j] += counts[i] } } var longest = 0 for (i in 0 until n) { longest = longest.coerceAtLeast(lengths[i]) } var ans = 0 for (i in 0 until n) { if (lengths[i] == longest) { ans += counts[i] } } return ans } val wordId = mutableMapOf<String, Int>() val edge = mutableListOf<MutableList<Int>>() var nodeNum = 0 fun ladderLength(beginWord: String, endWord: String, wordList: List<String>): Int {//127 for (word in wordList) { addEdge(word) } addEdge(beginWord) if (!wordId.containsKey(endWord)) { return 0 } val dis = IntArray(nodeNum) { Int.MAX_VALUE } val beginId = wordId[beginWord]!! val endId = wordId[endWord]!! dis[beginId] = 0 val q = mutableListOf<Int>() q.add(beginId) while (q.isNotEmpty()) { val x = q.last() if (x == endId) { return dis[endId] / 2 + 1 } for (i in edge[x]) { if (dis[i] == Int.MAX_VALUE) { dis[i] = dis[x] + 1 q.add(i) } } } return 0 } private fun addEdge(word: String) { addWord(word) val id1 = wordId[word]!! val chars = word.toCharArray() val size = word.length for (i in 0 until size) { val tmp = chars[i] chars[i] = '*' val newWord = String(chars) addWord(newWord) val id2 = wordId[newWord]!! edge[id1].add(id2) edge[id2].add(id1) chars[i] = tmp } } private fun addWord(word: String) { if (!wordId.containsKey(word)) { wordId[word] = nodeNum++ edge.add(mutableListOf()) } } fun smallestDivisor(nums: IntArray, threshold: Int): Int {//1283 var low = 1 var high = nums.maxOfOrNull { it }!! var ans = -1 while (low <= high) { val mid = low + (high - low) / 2 var total = 0 for (num in nums) { total += (num - 1) / mid + 1 } if (total <= threshold) { ans = mid high = mid - 1 } else { low = mid + 1 } } return ans } fun nextPermutation(nums: IntArray): Unit {//31 var i = nums.size - 2 while (i >= 0 && nums[i] >= nums[i + 1]) { i-- } if (i >= 0) { var j = nums.size - 1 while (j >= 0 && nums[i] >= nums[j]) { j-- } swap(nums, i, j) } reverse(nums, i + 1) } private fun swap(nums: IntArray, i: Int, j: Int) { val tmp = nums[i] nums[i] = nums[j] nums[j] = tmp } private fun reverse(nums: IntArray, start: Int) { var left = start var right = nums.size - 1 while (left < right) { swap(nums, left, right) left += 1 right -= 1 } } fun validSquare(p1: IntArray, p2: IntArray, p3: IntArray, p4: IntArray): Boolean {//593 val points = listOf( p1, p2, p3, p4 ).sortedWith(Comparator { o1, o2 -> if (o1[0] == o2[0]) o1[1] - o2[1] else o2[0] - o1[0] }) return distance(points[0], points[1]) != 0 && distance(points[0], points[1]) == distance(points[1], points[3]) && distance(points[1], points[3]) == distance(points[3], points[2]) && distance(points[3], points[2]) == distance(points[2], points[0]) && distance(points[0], points[3]) == distance(points[1], points[2]) } private fun distance(p1: IntArray, p2: IntArray): Int { return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]) } fun findRotateSteps(ring: String, key: String): Int {//514 val m = key.length val n = ring.length val pos = Array(26) { mutableListOf<Int>() } for (i in 0 until n) { pos[ring[i] - 'a'].add(i) } val dp = Array(m) { IntArray(n) { 0x3f3f3f } } for (i in pos[key[0] - 'a']) { dp[0][i] = i.coerceAtMost(n - i) + 1 } for (i in 1 until m) { for (j in pos[key[i] - 'a']) { for (k in pos[key[i - 1] - 'a']) { dp[i][j] = dp[i][j].coerceAtMost(dp[i - 1][k] + Math.abs(j - k).coerceAtMost(n - Math.abs(j - k)) + 1) } } } return dp[m - 1].minOfOrNull { it }!! } fun poorPigs(buckets: Int, minutesToDie: Int, minutesToTest: Int): Int {//458 val states = minutesToTest / minutesToDie + 1 return Math.ceil(Math.log(buckets.toDouble()) / Math.log(states.toDouble())).toInt() } fun mirrorReflection(p: Int, q: Int): Int {//858 val gcd = gcd(p, q) var pp = p / gcd pp %= 2 var qq = q / gcd qq %= 2 if (pp == 1 && qq == 1) return 1 return if (pp == 1) 0 else 2 } private fun gcd(m: Int, n: Int): Int { if (n == 0) return m else return gcd(n, m % n) } }
0
Kotlin
0
1
7cf372d9acb3274003bb782c51d608e5db6fa743
34,431
Algorithms
MIT License
feature/home/src/main/kotlin/com/xeladevmobile/medicalassistant/feature/home/Extensions.kt
Alexminator99
702,145,143
false
{"Kotlin": 534097}
package com.xeladevmobile.medicalassistant.feature.home import com.xeladevmobile.medicalassistant.core.model.data.Audio import com.xeladevmobile.medicalassistant.core.model.data.Emotion import com.xeladevmobile.medicalassistant.core.model.data.PatientStatistics import java.text.SimpleDateFormat import java.util.* fun List<Audio>.calculateStatistics(locale: Locale): List<PatientStatistics> { val emotionCount = this.groupingBy { it.emotion }.eachCount() val averageDurationPerEmotion = this.groupBy { it.emotion } .mapValues { (_, audios) -> audios.map { it.duration / 1000.0 }.average() // Convert milliseconds to seconds } val longestRecording = this.maxByOrNull { it.duration } val shortestRecording = this.minByOrNull { it.duration } val emotionTrend = calculateEmotionTrend(this) val emotionDiversity = calculateEmotionDiversity(this) val emotionCountFormatted = emotionCount.entries.joinToString(separator = "\n") { "• ${it.key}: ${it.value}" } val averageDurationFormatted = averageDurationPerEmotion.entries.joinToString(separator = "\n") { "• ${it.key}: ${String.format(if (locale.language == "es") "%.2f seg" else "%.2f sec", it.value)}" } val longestRecordingFormatted = longestRecording?.let { "• ${if (locale.language == "es") "Emoción" else "Emotion"}: ${it.emotion}\n• ${if (locale.language == "es") "Duración" else "Duration"}: ${it.duration / 1000} ${if (locale.language == "es") "seg" else "sec"}" } ?: if (locale.language == "es") "No disponible" else "Not available" val shortestRecordingFormatted = shortestRecording?.let { "• ${if (locale.language == "es") "Emoción" else "Emotion"}: ${it.emotion}\n• ${if (locale.language == "es") "Duración" else "Duration"}: ${it.duration / 1000} ${if (locale.language == "es") "seg" else "sec"}" } ?: if (locale.language == "es") "No disponible" else "Not available" val mostCommonEmotion = emotionCount.maxByOrNull { it.value } val mostCommonEmotionContextualMessage = when (mostCommonEmotion?.key) { Emotion.Anger -> if (locale.language == "es") "La ira puede ser un poderoso motivador. Es importante encontrar salidas saludables para esta energía." else "Anger can be a powerful motivator. It's important to find healthy outlets for this energy." Emotion.Happiness -> if (locale.language == "es") "La felicidad es contagiosa. Comparte alegría con tu presencia." else "Happiness is contagious. Share joy with your presence." Emotion.Disgust -> if (locale.language == "es") "El asco puede ser una respuesta natural a experiencias desagradables. Reflexiona sobre lo que se puede aprender de estos sentimientos." else "Disgust can be a natural response to unpleasant experiences. Reflect on what can be learned from these feelings." Emotion.Fear -> if (locale.language == "es") "El miedo nos puede proteger, pero también puede obstaculizarnos. Enfréntate a tus miedos con valentía y crece más fuerte." else "Fear can protect us, but it can also hold us back. Face your fears with courage and grow stronger." Emotion.Neutral -> if (locale.language == "es") "Un mar en calma no hace un marinero hábil. Acepta las olas de emoción." else "A calm sea does not make a skilled sailor. Embrace the waves of emotion." Emotion.Sadness -> if (locale.language == "es") "La tristeza es una parte natural de la vida. Aprende a aceptarla y a dejarla ir." else "Sadness is a natural part of life. Learn to accept it and let it go." else -> if (locale.language == "es") "Las emociones son complejas, cada una nos dice algo sobre nosotros mismos." else "Emotions are complex, each one tells us something about ourselves." } return listOf( PatientStatistics( header = if (locale.language == "es") "Emoción Más Común" else "Most Common Emotion", description = if (locale.language == "es") "La emoción grabada con más frecuencia" else "The emotion recorded most frequently", value = "• Emoción: ${mostCommonEmotion?.key}\n• Total de veces: ${mostCommonEmotion?.value}\n\n$mostCommonEmotionContextualMessage", updatedAt = System.currentTimeMillis(), ), PatientStatistics( header = if (locale.language == "es") "Duración Promedio por Emoción" else "Average Duration per Emotion", description = if (locale.language == "es") "Duración promedio de las grabaciones para cada emoción" else "Average duration of recordings for each emotion", value = averageDurationFormatted, updatedAt = System.currentTimeMillis(), ), PatientStatistics( header = if (locale.language == "es") "Distribución de Emociones" else "Distribution of Emotions", description = if (locale.language == "es") "Cantidad de cada emoción grabada" else "Quantity of each recorded emotion", value = emotionCountFormatted, updatedAt = System.currentTimeMillis(), ), PatientStatistics( header = if (locale.language == "es") "Grabación Más Larga" else "Longest Recording", description = if (locale.language == "es") "La grabación de audio más larga y su emoción" else "The longest audio recording and its emotion", value = longestRecordingFormatted, updatedAt = System.currentTimeMillis(), ), PatientStatistics( header = if (locale.language == "es") "Grabación Más Corta" else "Shortest Recording", description = if (locale.language == "es") "La grabación de audio más corta y su emoción" else "The shortest audio recording and its emotion", value = shortestRecordingFormatted, updatedAt = System.currentTimeMillis(), ), PatientStatistics( header = if (locale.language == "es") "Tendencia de Emoción a lo Largo del Tiempo" else "Emotion Trend Over Time", description = if (locale.language == "es") "Cómo han variado las emociones a lo largo del tiempo" else "How emotions have varied over time", value = emotionTrend, updatedAt = System.currentTimeMillis(), ), PatientStatistics( header = if (locale.language == "es") "Diversidad de Emociones" else "Diversity of Emotions", description = if (locale.language == "es") "La diversidad de emociones grabadas" else "The diversity of recorded emotions", value = emotionDiversity, updatedAt = System.currentTimeMillis(), ), ) } fun calculateEmotionTrend(audios: List<Audio>): String { val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val emotionsByDate = audios.groupBy { dateFormat.format(Date(it.createdDate)) }.mapValues { entry -> entry.value.groupingBy { it.emotion }.eachCount() } val trendStringBuilder = StringBuilder() emotionsByDate.toSortedMap().forEach { (date, emotions) -> trendStringBuilder.append("\n$date: ") emotions.entries.sortedByDescending { it.value }.forEach { (emotion, count) -> trendStringBuilder.append("$emotion($count) ") } } return trendStringBuilder.toString() } fun calculateEmotionDiversity(audios: List<Audio>): String { val emotionCounts = audios.groupingBy { it.emotion }.eachCount() val totalAudios = audios.count() return emotionCounts.entries.joinToString(separator = "\n") { (emotion, count) -> val percentage = (count.toDouble() / totalAudios) * 100 "• $emotion: ${String.format("%.2f%%", percentage)}" } }
0
Kotlin
0
0
37a35835a2562b0c6b4129e7b86cfca081a24783
7,731
Medical_Assistant
MIT License
src/main/kotlin/day4/Day4.kt
Wicked7000
573,552,409
false
{"Kotlin": 106288}
package day4 import Day import checkWithMessage import readInput import runTimedPart @Suppress("unused") class Day4(): Day() { data class Range(val start: Int, val end: Int) private fun processRange(rangeStr: String): Range { val (start, end) = rangeStr.split("-").map { it.toInt() } return Range(start, end) } private fun doesRangeOverlap(a: Range, b: Range): Boolean { // Overlaps at boundary if(a.start == b.end || a.start == b.start || b.start == a.end){ return true } // B starting position overlaps A if(b.start >= a.start && b.start <= a.end){ return true } // A starting position overlaps B if(a.start >= b.start && a.start <= b.end){ return true; } return false } private fun doesRangeFullyContainOther(a: Range, b: Range): Boolean { // A is fully contained by B if(a.start >= b.start && a.end <= b.end){ return true; } // B is fully contained by A if(b.start >= a.start && b.end <= a.end){ return true; } return false; } private fun part1(input: List<String>): Int { var totalOverlapPairs = 0 for(line in input){ val (elfA, elfB) = line.split(",").map { processRange(it) } if(doesRangeFullyContainOther(elfA, elfB)){ totalOverlapPairs += 1 } } return totalOverlapPairs; } private fun part2(input: List<String>): Int { var totalOverlapPairs = 0 for(line in input){ val (elfA, elfB) = line.split(",").map { processRange(it) } if(doesRangeOverlap(elfA, elfB)){ totalOverlapPairs += 1 } } return totalOverlapPairs; } override fun run(){ val testData = readInput(4,"test") val inputData = readInput(4, "input") val testResult1 = part1(testData) checkWithMessage(testResult1, 2) runTimedPart(1, { part1(it) }, inputData) val testResult2 = part2(testData) checkWithMessage(testResult2, 4) runTimedPart(2, { part2(it) }, inputData) } }
0
Kotlin
0
0
7919a8ad105f3b9b3a9fed048915b662d3cf482d
2,337
aoc-2022
Apache License 2.0
src/main/kotlin/com/anahoret/aoc2022/day22/common.kt
mikhalchenko-alexander
584,735,440
false
null
package com.anahoret.aoc2022.day22 import com.anahoret.aoc2022.ManhattanDistanceAware sealed class Tile(val row: Int, val col: Int) : ManhattanDistanceAware { override val x = col override val y = row companion object { fun parse(row: Int, col: Int, char: Char): Tile? { return when (char) { '.' -> OpenTile(row, col) '#' -> SolidWall(row, col) else -> null } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Tile) return false 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 } } class OpenTile(row: Int, col: Int) : Tile(row, col) { override fun toString(): String = "$col $row" } class SolidWall(row: Int, col: Int) : Tile(row, col) { override fun toString(): String = "$col $row" } enum class Direction(val facing: Int) { LEFT(2), RIGHT(0), UP(3), DOWN(1); fun rotate(direction: Direction): Direction { return when (direction) { LEFT -> rotateLeft() RIGHT -> rotateRight() else -> throw IllegalArgumentException("Cannot rotate $direction") } } override fun toString(): String { return "$name($facing)" } private fun rotateRight(): Direction { return when (this) { LEFT -> UP UP -> RIGHT RIGHT -> DOWN DOWN -> LEFT } } private fun rotateLeft(): Direction { return when (this) { LEFT -> DOWN DOWN -> RIGHT RIGHT -> UP UP -> LEFT } } companion object { private val dirMap = mapOf( 'L' to LEFT, 'R' to RIGHT ) fun fromChar(c: Char): Direction { return dirMap.getValue(c) } } } sealed interface Action class Movement(val steps: Int) : Action { override fun toString(): String { return "Move $steps" } } class Rotation(val direction: Direction) : Action { override fun toString(): String { return "Rotate $direction" } } class Path(val actions: List<Action>) { override fun toString(): String { return actions.joinToString(separator = "") { when (it) { is Movement -> it.steps.toString() is Rotation -> it.direction.name.first().toString() } } } } fun parseTiles(str: String) = str.split("\n").mapIndexed { rowIdx, line -> line.mapIndexedNotNull { colIdx, char -> Tile.parse(rowIdx + 1, colIdx + 1, char) } } fun parsePath(str: String): Path { fun parseActions(str: String, acc: List<Action>): List<Action> { if (str.isEmpty()) return acc return if (str.first().isDigit()) { val steps = str.takeWhile(Char::isDigit).toInt() val movement = Movement(steps) parseActions(str.dropWhile(Char::isDigit), acc + movement) } else { val direction = Direction.fromChar(str.first()) val rotation = Rotation(direction) parseActions(str.drop(1), acc + rotation) } } val actions = parseActions(str, emptyList()) return Path(actions) }
0
Kotlin
0
0
b8f30b055f8ca9360faf0baf854e4a3f31615081
3,442
advent-of-code-2022
Apache License 2.0
src/zh/pufei/src/eu/kanade/tachiyomi/extension/zh/pufei/PufeiFilters.kt
lmk1988
253,204,269
true
{"Kotlin": 4659131}
package eu.kanade.tachiyomi.extension.zh.pufei import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList internal fun getFilters() = FilterList( Filter.Header("排序只对文本搜索和分类筛选有效"), SortFilter(), Filter.Separator(), Filter.Header("以下筛选最多使用一个,使用文本搜索时将会忽略"), CategoryFilter(), AlphabetFilter(), ) internal fun parseSearchSort(filters: FilterList): String = filters.filterIsInstance<SortFilter>().firstOrNull()?.let { SORT_QUERIES[it.state] } ?: "" internal fun parseFilters(page: Int, filters: FilterList): String { val pageStr = if (page == 1) "" else "_$page" var category = 0 var categorySort = 0 var alphabet = 0 for (filter in filters) when (filter) { is SortFilter -> categorySort = filter.state is CategoryFilter -> category = filter.state is AlphabetFilter -> alphabet = filter.state else -> {} } return if (category > 0) { "/${CATEGORY_KEYS[category]}/${SORT_KEYS[categorySort]}$pageStr.html" } else if (alphabet > 0) { "/mh/${ALPHABET[alphabet].lowercase()}/index$pageStr.html" } else { "" } } internal class SortFilter : Filter.Select<String>("排序", SORT_NAMES) private val SORT_NAMES = arrayOf("添加时间", "更新时间", "点击次数") private val SORT_KEYS = arrayOf("index", "update", "view") private val SORT_QUERIES = arrayOf("&orderby=newstime", "&orderby=lastdotime", "&orderby=onclick") internal class CategoryFilter : Filter.Select<String>("分类", CATEGORY_NAMES) private val CATEGORY_NAMES = arrayOf("全部", "少年热血", "少女爱情", "武侠格斗", "科幻魔幻", "竞技体育", "搞笑喜剧", "耽美人生", "侦探推理", "恐怖灵异") private val CATEGORY_KEYS = arrayOf("", "shaonianrexue", "shaonvaiqing", "wuxiagedou", "kehuan", "<KEY>", "<KEY>", "danmeirensheng", "zhentantuili", "kongbulingyi") internal class AlphabetFilter : Filter.Select<String>("字母", ALPHABET) private val ALPHABET = arrayOf("全部", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")
0
Kotlin
0
5
3e1df100b87358d8b50ce8dd998e04552db9c91d
2,250
tachiyomi-extensions
Apache License 2.0
src/Day06.kt
juliantoledo
570,579,626
false
{"Kotlin": 34375}
fun main() { fun compareN (string: CharSequence, n: Int): Boolean { for (i in 0 until n) { for (j in i+1 until n) { if (string[i] == string[j]) return true } } return false } fun part1(input: List<String>): Int { input.forEach { line -> for (i in 0..line.length-4) { val sub = line.subSequence(i, i+4) if (!compareN(sub, 4)) { val j = i+4 println("$sub $j") return@forEach } } } return 0 } fun part2(input: List<String>): Int { input.forEach { line -> for (i in 0..line.length-14) { val sub = line.subSequence(i, i+14) if (!compareN(sub, 14)) { val j = i+14 println("$sub $j") return@forEach } } } return 0 } var input = readInput("Day06_test") part1(input) input = readInput("Day06_input") part1(input) part2(input) }
0
Kotlin
0
0
0b9af1c79b4ef14c64e9a949508af53358335f43
1,144
advent-of-code-kotlin-2022
Apache License 2.0
facebook/y2023/round1/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2023.round1 private fun precalc(s: Int = 41): List<MutableMap<Int, Sequence<Int>>> { val dp = List(s + 1) { List(it + 1) { mutableMapOf<Int, Sequence<Int>>() } } dp[0][0][1] = emptySequence() for (sum in 0 until s) { for (count in 0..sum) { for (entry in dp[sum][count]) { for (x in 1..s - sum) { dp[sum + x][count + 1][entry.key * x] = sequenceOf(x) + entry.value } } } } return dp[s] } private val precalc = precalc() private fun solve(): List<Int> { val p = readInt() val map = precalc.firstOrNull { p in it } ?: return listOf(-1) return map[p]!!.toList().let { listOf(it.size) + it } } fun main() { System.setIn(java.io.File("input.txt").inputStream()) System.setOut(java.io.PrintStream("output.txt")) repeat(readInt()) { println("Case #${it + 1}: ${solve().joinToString(" ")}") } } private fun readInt() = readln().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
887
competitions
The Unlicense
year2017/src/main/kotlin/net/olegg/aoc/year2017/day8/Day8.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2017.day8 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2017.DayOf2017 /** * See [Year 2017, Day 8](https://adventofcode.com/2017/day/8) */ object Day8 : DayOf2017(8) { override fun first(): Any? { val registers = mutableMapOf<String, Int>() lines .map { it.split(" ") } .forEach { list -> val oldValue = registers[list[0]] ?: 0 val shift = list[2].toInt() * (if (list[1] == "dec") -1 else 1) val cmp = registers[list[4]] ?: 0 val apply = when (list[5]) { "<" -> cmp < list[6].toInt() ">" -> cmp > list[6].toInt() "<=" -> cmp <= list[6].toInt() ">=" -> cmp >= list[6].toInt() "==" -> cmp == list[6].toInt() "!=" -> cmp != list[6].toInt() else -> false } registers[list[0]] = if (apply) oldValue + shift else oldValue } return registers.values.max() } override fun second(): Any? { val registers = mutableMapOf<String, Int>() return lines .map { it.split(" ") } .maxOf { list -> val oldValue = registers[list[0]] ?: 0 val shift = list[2].toInt() * (if (list[1] == "dec") -1 else 1) val cmp = registers[list[4]] ?: 0 val apply = when (list[5]) { "<" -> cmp < list[6].toInt() ">" -> cmp > list[6].toInt() "<=" -> cmp <= list[6].toInt() ">=" -> cmp >= list[6].toInt() "==" -> cmp == list[6].toInt() "!=" -> cmp != list[6].toInt() else -> false } val newValue = if (apply) oldValue + shift else oldValue registers[list[0]] = newValue return@maxOf newValue } } } fun main() = SomeDay.mainify(Day8)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,764
adventofcode
MIT License
src/array/ContainsDuplicate.kt
develNerd
456,702,818
false
{"Kotlin": 37635, "Java": 5892}
package array /** * * Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true Constraints: 1 <= nums.length <= 105 -109 <= nums[i] <= 109 * * * * * */ /** * * * */ fun main(){ val nums = intArrayOf(3,3) println(containsDuplicate(nums)) } /** * * The solution for this is quite simple, * we save each integer in a mutablemap as we iterate * through the array if it does not exist already in * the array. * * */ fun containsDuplicate(nums: IntArray): Boolean { /** * Declare a mutable map to hold the key value pair * * */ val numsMap = mutableMapOf<Int,Int>() for(i in nums.indices){ /** * Check if [numsMap[i]] is in the mutable map keys * return true if the number is contained in the map keys * and continue otherwise * */ if (!numsMap.containsKey(nums[i])){ /** * Set the number as the key and the value as the index * */ numsMap[nums[i]] = i // (i1 - {1}) (i2 - {1,2}) (i3 - {1,2,3}) }else{ return true } } /** * Return false if there is no recurring numbers in the array. * */ return false }
0
Kotlin
0
0
4e6cc8b4bee83361057c8e1bbeb427a43622b511
1,461
Blind75InKotlin
MIT License
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day20/day20.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day20 import eu.janvdb.aocutil.kotlin.gcd import eu.janvdb.aocutil.kotlin.readLines import java.util.* //const val FILENAME = "input20-test.txt" //const val OUTPUT_NAME = "output" const val FILENAME = "input20.txt" const val OUTPUT_NAME = "rx" fun main() { val system = System.parse(readLines(2023, FILENAME)) part1(system) part2(system) } private fun part1(system: System) { system.reset() val counts = (1..1000).asSequence() .map { system.signal() } .fold(Pair(0, 0)) { acc, pair -> Pair(acc.first + pair.first, acc.second + pair.second) } println(counts.first * counts.second) } private fun part2(system: System) { // intermediary end nodes: cl, rp, lb, nj, found by inspecting the input val result = sequenceOf("cl", "rp", "lb", "nj") .map { system.subSystem(it).getRepetition() } .fold(1L) { acc, it -> acc * it / gcd(acc, it) } println(result) } enum class SignalType { LOW, HIGH; operator fun not() = if (this == LOW) HIGH else LOW } data class Signal(val from: String, val to: String, val type: SignalType) data class System(val modules: Map<String, Module>, val outputName: String) { val endNode = modules[outputName]!! var buttonPresses = 0 fun reset() = modules.values.forEach(Module::reset) fun signal(): Pair<Int, Int> { buttonPresses++ val todo = LinkedList<Signal>() var count = Pair(0, 0) todo.add(Signal("button", "broadcaster", SignalType.LOW)) while (!todo.isEmpty()) { val signal = todo.removeFirst() count = if (signal.type == SignalType.LOW) Pair(count.first + 1, count.second) else Pair(count.first, count.second + 1) val newSignals = modules[signal.to]!!.trigger(signal, buttonPresses) todo.addAll(newSignals) } return count } fun subSystem(newOutputName: String): System { val newEndModule = this.modules[newOutputName]!! val newModules = mutableSetOf(newEndModule) val todo = LinkedList<Module>() todo.add(newEndModule) while (!todo.isEmpty()) { val module = todo.removeFirst() modules.values.asSequence() .filter { it.outputs.contains(module.name) } .filter { !newModules.contains(it) } .forEach { newModules.add(it) todo.add(it) } } val newModuleNames = newModules.map { it.name }.toSet() val limitedModules = newModules.map { it.limitOutputsTo(newModuleNames) } return System(limitedModules.associateBy { it.name }, newOutputName) } fun getRepetition(): Long { val previousPresses = mutableListOf(0) var previousDifference = 0 while (true) { signal() if (endNode.lowSignals.isNotEmpty()) { val currentPress = endNode.lowSignals.last().second val currentDifference = currentPress - previousPresses.last() if (currentDifference != 0) { if (currentDifference == previousDifference && currentDifference > 1) { return currentDifference.toLong() } previousPresses += currentPress previousDifference = currentDifference } } } } companion object { fun parse(lines: List<String>): System { val modules = lines.map { parse(it) }.associateBy { it.name } + Pair(OUTPUT_NAME, Output(OUTPUT_NAME)) return System(modules, OUTPUT_NAME) } private fun parse(line: String): Module { val parts = line.split(" -> ") val outputs = parts[1].split(", ") return when { parts[0].startsWith('%') -> FlipFlop(parts[0].substring(1), outputs) parts[0].startsWith('&') -> Conjunction(parts[0].substring(1), outputs) else -> Broadcaster(parts[0], outputs) } } } } abstract class Module(val name: String, val outputs: List<String>) { val signals = mutableListOf<Pair<SignalType, Int>>() val lowSignals = mutableListOf<Pair<SignalType, Int>>() open fun reset() { signals.clear() lowSignals.clear() } open fun trigger(signal: Signal, buttonPress: Int): Sequence<Signal> { if (signal.type == SignalType.LOW) { lowSignals.add(Pair(signal.type, buttonPress)) } signals.add(Pair(signal.type, buttonPress)) return sequenceOf() } abstract fun limitOutputsTo(moduleNames: Set<String>): Module } class FlipFlop(name: String, outputs: List<String>) : Module(name, outputs) { private var state = SignalType.LOW override fun reset() { super.reset() state = SignalType.LOW } override fun trigger(signal: Signal, buttonPress: Int): Sequence<Signal> { super.trigger(signal, buttonPress) if (signal.type == SignalType.HIGH) return sequenceOf() state = !state return outputs.asSequence().map { Signal(name, it, state) } } override fun limitOutputsTo(moduleNames: Set<String>): Module { val newOutputs = outputs.intersect(moduleNames) return FlipFlop(name, newOutputs.toList()) } override fun toString() = "%($state) -> [$outputs]" } class Conjunction(name: String, outputs: List<String>) : Module(name, outputs) { private val inputValues = mutableMapOf<String, SignalType>() override fun reset() { super.reset() inputValues.clear() } override fun trigger(signal: Signal, buttonPress: Int): Sequence<Signal> { super.trigger(signal, buttonPress) inputValues[signal.from] = signal.type val allHigh = inputValues.values.all { it == SignalType.HIGH } val value = if (allHigh) SignalType.LOW else SignalType.HIGH return outputs.asSequence().map { Signal(name, it, value) } } override fun limitOutputsTo(moduleNames: Set<String>): Module { val newOutputs = outputs.intersect(moduleNames) return Conjunction(name, newOutputs.toList()) } override fun toString() = "&($inputValues) -> [$outputs]" } class Broadcaster(name: String, outputs: List<String>) : Module(name, outputs) { override fun trigger(signal: Signal, buttonPress: Int): Sequence<Signal> { super.trigger(signal, buttonPress) return outputs.asSequence().map { Signal(name, it, signal.type) } } override fun limitOutputsTo(moduleNames: Set<String>): Module { val newOutputs = outputs.intersect(moduleNames) return Broadcaster(name, newOutputs.toList()) } override fun toString() = "()) -> [$outputs]" } class Output(name: String) : Module(name, listOf()) { override fun limitOutputsTo(moduleNames: Set<String>) = this override fun toString() = "()" }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
6,166
advent-of-code
Apache License 2.0
kotlin/graphs/flows/MinCostFlowDijkstra.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.flows import java.util.stream.Stream // https://cp-algorithms.com/graph/min_cost_flow.html in O(E * V + min(E * logV * FLOW, V^2 * FLOW)) // negative-cost edges are allowed // negative-cost cycles are not allowed class MinCostFlowDijkstra(nodes: Int) { var graph: Array<List<Edge>> inner class Edge(var to: Int, var rev: Int, var cap: Int, var cost: Int) { var f = 0 } fun addEdge(s: Int, t: Int, cap: Int, cost: Int) { graph[s].add(Edge(t, graph[t].size(), cap, cost)) graph[t].add(Edge(s, graph[s].size() - 1, 0, -cost)) } fun bellmanFord(s: Int, dist: IntArray) { val n = graph.size Arrays.fill(dist, Integer.MAX_VALUE) dist[s] = 0 val inqueue = BooleanArray(n) val q = IntArray(n) var qt = 0 q[qt++] = s for (qh in 0 until qt) { val u = q[qh % n] inqueue[u] = false for (i in 0 until graph[u].size()) { val e = graph[u][i] if (e.cap <= e.f) continue val v = e.to val ndist = dist[u] + e.cost if (dist[v] > ndist) { dist[v] = ndist if (!inqueue[v]) { inqueue[v] = true q[qt++ % n] = v } } } } } fun dijkstra( s: Int, t: Int, pot: IntArray, dist: IntArray, finished: BooleanArray, curflow: IntArray, prevnode: IntArray, prevedge: IntArray ) { val q: PriorityQueue<Long> = PriorityQueue() q.add(s.toLong()) Arrays.fill(dist, Integer.MAX_VALUE) dist[s] = 0 Arrays.fill(finished, false) curflow[s] = Integer.MAX_VALUE while (!finished[t] && !q.isEmpty()) { val cur: Long = q.remove() val u = (cur and 0xFFFFFFFFL).toInt() val priou = (cur ushr 32).toInt() if (priou != dist[u]) continue finished[u] = true for (i in 0 until graph[u].size()) { val e = graph[u][i] if (e.f >= e.cap) continue val v = e.to val nprio = dist[u] + e.cost + pot[u] - pot[v] if (dist[v] > nprio) { dist[v] = nprio q.add((nprio.toLong() shl 32) + v) prevnode[v] = u prevedge[v] = i curflow[v] = Math.min(curflow[u], e.cap - e.f) } } } } fun dijkstra2( s: Int, t: Int, pot: IntArray, dist: IntArray, finished: BooleanArray, curflow: IntArray, prevnode: IntArray, prevedge: IntArray ) { Arrays.fill(dist, Integer.MAX_VALUE) dist[s] = 0 val n = graph.size Arrays.fill(finished, false) curflow[s] = Integer.MAX_VALUE var i = 0 while (i < n && !finished[t]) { var u = -1 for (j in 0 until n) if (!finished[j] && (u == -1 || dist[u] > dist[j])) u = j if (dist[u] == Integer.MAX_VALUE) break finished[u] = true for (k in 0 until graph[u].size()) { val e = graph[u][k] if (e.f >= e.cap) continue val v = e.to val nprio = dist[u] + e.cost + pot[u] - pot[v] if (dist[v] > nprio) { dist[v] = nprio prevnode[v] = u prevedge[v] = k curflow[v] = Math.min(curflow[u], e.cap - e.f) } } i++ } } fun minCostFlow(s: Int, t: Int, maxf: Int): IntArray { val n = graph.size val pot = IntArray(n) val dist = IntArray(n) val finished = BooleanArray(n) val curflow = IntArray(n) val prevedge = IntArray(n) val prevnode = IntArray(n) bellmanFord(s, pot) // this can be commented out if edges costs are non-negative var flow = 0 var flowCost = 0 while (flow < maxf) { dijkstra(s, t, pot, dist, finished, curflow, prevnode, prevedge) // E*logV // dijkstra2(s, t, pot, dist, finished, curflow, prevnode, prevedge); // V^2 if (dist[t] == Integer.MAX_VALUE) break for (i in 0 until n) if (finished[i]) pot[i] += dist[i] - dist[t] val df: Int = Math.min(curflow[t], maxf - flow) flow += df var v = t while (v != s) { val e = graph[prevnode[v]][prevedge[v]] e.f += df graph[v][e.rev].f -= df flowCost += df * e.cost v = prevnode[v] } } return intArrayOf(flow, flowCost) } companion object { // Usage example fun main(args: Array<String?>?) { val mcf = MinCostFlowDijkstra(3) mcf.addEdge(0, 1, 3, 1) mcf.addEdge(0, 2, 2, 1) mcf.addEdge(1, 2, 2, 1) val res = mcf.minCostFlow(0, 2, Integer.MAX_VALUE) val flow = res[0] val flowCost = res[1] System.out.println(4 == flow) System.out.println(6 == flowCost) } } init { graph = Stream.generate { ArrayList() }.limit(nodes).toArray { _Dummy_.__Array__() } } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
5,530
codelibrary
The Unlicense
src/day03/Day03.kt
EdwinChang24
572,839,052
false
{"Kotlin": 20838}
package day03 import readInput fun main() { part1() part2() } fun part1() { val input = readInput(3) var total = 0 for (string in input) { val first = string.subSequence(0, string.length / 2) val second = string.subSequence(string.length / 2, string.length) val intersect = first.toSet() intersect second.toSet() for (char in intersect) total += if (char.isLowerCase()) char - 'a' + 1 else char - 'A' + 27 } println(total) } fun part2() { val input = readInput(3) val processed = mutableListOf<MutableList<String>>() var total = 0 input.forEachIndexed { index, s -> when (index % 3) { 0 -> processed += mutableListOf(s) 1, 2 -> processed[processed.size - 1] += s } } for (i in processed) { val intersect = i[0].toSet() intersect i[1].toSet() intersect i[2].toSet() for (c in intersect) total += if (c.isLowerCase()) c - 'a' + 1 else c - 'A' + 27 } println(total) }
0
Kotlin
0
0
e9e187dff7f5aa342eb207dc2473610dd001add3
1,017
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2019/FlawedFrequencyTransmission.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2019 import kotlin.math.absoluteValue fun flawedFrequencyTransmission1(input: String): String { var s = input.map { it - '0' }.toIntArray() repeat(100) { s = phase(s) } return s.take(8).joinToString("") } fun flawedFrequencyTransmission2(input: String): String { val offset = input.take(7).toInt() val data = input.repeat(10_000).map { (it - '0') }.drop(offset).toIntArray() repeat(100) { var sum = 0 for (index in data.indices.reversed()) { sum += data[index] data[index] = sum % 10 } } return data.joinToString("").take(8) } private fun phase(s: IntArray): IntArray = IntArray(s.size) { i -> step(s, i + 1) } private fun step(s: IntArray, position: Int): Int { var sum = 0 for (i in position - 1 until s.size step position * 4) for (j in i until (i + position).coerceAtMost(s.size)) sum += s[j] for (i in position * 3 - 1 until s.size step position * 4) for (j in i until (i + position).coerceAtMost(s.size)) sum -= s[j] return sum.absoluteValue % 10 }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,148
advent-of-code
MIT License
src/main/kotlin/info/jukov/adventofcode/y2022/Day7.kt
jukov
572,271,165
false
{"Kotlin": 78755}
package info.jukov.adventofcode.y2022 import info.jukov.adventofcode.Day import java.io.BufferedReader import java.util.LinkedList import java.util.SortedSet import java.util.TreeSet object Day7 : Day() { override val year: Int = 2022 override val day: Int = 7 private const val NEED_SPACE = 30_000_000 private const val TOTAL_SPACE = 70_000_000 override fun part1(reader: BufferedReader): String { val tree = makeFileTree(reader) return count(tree).toString() } override fun part2(reader: BufferedReader): String { val tree = makeFileTree(reader) val size = tree.size val needToFree = NEED_SPACE - (TOTAL_SPACE - size) val dirs = dirList(tree) return dirs.first { it > needToFree }.toString() } private fun makeFileTree(reader: BufferedReader): Dir { val tree = Dir("/", null) var workingDir: Dir? = null reader.forEachLine { line -> when { line.startsWith("$ cd") -> { val where = line.substring(5) workingDir = when (where) { "/" -> tree ".." -> workingDir?.parent else -> find(where, workingDir!!) as Dir } } line.startsWith("$ ls") -> { } line.startsWith("dir") -> { val name = line.substring(4) workingDir?.files?.add(Dir(name, workingDir)) } else -> { val (size, name) = line.split(' ') workingDir?.files?.add(File(name, size.toLong(), workingDir!!)) } } } return tree } private fun dirList(tree: Dir): SortedSet<Long> { val set = TreeSet<Long>() set += tree.size val workingDirs = LinkedList<Dir>() workingDirs += tree while (workingDirs.isNotEmpty()) { val next = workingDirs[0] next.files.forEach { entry -> if (entry is Dir) { set += entry.size workingDirs += entry } } workingDirs.removeAt(0) } return set } private fun find(name: String, from: Dir): Entry? { from.files.forEach { entry -> if (entry.name == name) { return entry } if (entry is Dir) { find(name, entry) } } return null } private fun count(from: Dir): Long = from.files.sumOf { entry -> if (entry is Dir) { if (entry.size < 100000) { entry.size + count(entry) } else { count(entry) } } else { 0L } } sealed class Entry { abstract val name: String abstract val size: Long abstract val parent: Dir? } class File( override val name: String, override val size: Long, override val parent: Dir ) : Entry() { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as File if (name != other.name) return false if (size != other.size) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + size.hashCode() return result } } class Dir( override val name: String, override val parent: Dir?, ) : Entry() { val files = ArrayList<Entry>() override val size: Long get() = files.sumOf { it.size } override fun toString(): String { return "Dir(name='$name', parent=$parent)" } } }
0
Kotlin
1
0
5fbdaf39a508dec80e0aa0b87035984cfd8af1bb
4,052
AdventOfCode
The Unlicense
src/test/kotlin/com/igorwojda/string/ispalindrome/tolerant/solution.kt
tmdroid
498,808,938
true
{"Kotlin": 217983}
package com.igorwojda.string.ispalindrome.tolerant // iterative solution private object Solution1 { private fun isTolerantPalindrome(str: String): Boolean { var characterRemoved = false str.forEachIndexed { index, c -> var lastIndex = str.lastIndex - index if (characterRemoved) { lastIndex-- } if (index >= lastIndex) { return true } if (c != str[lastIndex]) { if (characterRemoved) { return false } else { characterRemoved = true } } } return false } } // recursive solution private object Solution2 { private fun isTolerantPalindrome(str: String, characterRemoved: Boolean = false): Boolean { return if (str.isEmpty() || str.length == 1) { true } else { if (str.first() == str.last()) { isTolerantPalindrome( str.substring(1 until str.lastIndex), characterRemoved ) } else { if (characterRemoved) { false } else { if (str.length == 2) { return true } println(str) val removeLeftResult = isTolerantPalindrome( str.substring(2 until str.lastIndex), true ) val removeRightResult = isTolerantPalindrome( str.substring(1 until str.lastIndex - 1), true ) return removeLeftResult || removeRightResult } } } } } // recursive solution 2 private object Solution3 { private fun isTolerantPalindrome(str: String, characterRemoved: Boolean = false): Boolean { val revStr = str.reversed() if (revStr == str) return true if (characterRemoved) return false // Remove a single non matching character and re-compare val removeIndex = str.commonPrefixWith(revStr).length if (removeIndex + 1 > str.length) return false // reached end of string val reducedStr = str.removeRange(removeIndex, removeIndex + 1) return isTolerantPalindrome(reducedStr, true) } }
1
Kotlin
2
0
f82825274ceeaf3bef81334f298e1c7abeeefc99
2,466
kotlin-puzzles
MIT License
src/Day05.kt
zfz7
573,100,794
false
{"Kotlin": 53499}
fun main() { println(day5(readFile("Day05"), true)) println(day5(readFile("Day05"), false)) } fun day5(input: String, reverse: Boolean): String { val (moves, startingStack) = input.split("\n").partition { it.startsWith("move") } val stack = buildStack(startingStack.dropLast(2)) moves.forEach { move -> val (count,fromIdx,toIdx) = move.removePrefix("move ").split(" from ", " to ").map { it.toInt() } val temp = if (reverse) (stack[fromIdx-1].subList(0, count)).reversed() else (stack[fromIdx-1].subList(0, count)) stack[fromIdx-1] = stack[fromIdx-1].subList(count, stack[fromIdx-1].size) stack[toIdx-1] = (temp + stack[toIdx-1]) as MutableList<Char> } return stack.map { it[0] }.joinToString("") } fun buildStack(input: List<String>): MutableList<MutableList<Char>> = input.foldRight(generateSequence { mutableListOf<Char>() }.take(9).toMutableList()) { line, acc -> acc.mapIndexed { idx, stack -> if ((line.getOrNull(idx * 4 + 1) ?: ' ') != ' ') stack.add(0, line.getOrNull(idx * 4 + 1) ?: ' ') stack }.toMutableList() }
0
Kotlin
0
0
c50a12b52127eba3f5706de775a350b1568127ae
1,152
AdventOfCode22
Apache License 2.0
src/Day05.kt
vi-quang
573,647,667
false
{"Kotlin": 49703}
/** * Main ------------------------------------------------------------------- */ fun main() { class Move(val numberOfCratesToMove : Int, val indexOfCrateToMoveFrom : Int, val indexOfCrateToMoveTo: Int) { } fun createStackList(input: List<String>) : MutableList<ArrayDeque<Char>> { val returnList = mutableListOf<ArrayDeque<Char>>() for (line in input) { if (line.isEmpty()) { break } for ((index, c) in line.withIndex()) { val modulo = (index-1).mod(4) if (modulo == 0) { val crateIndex = index/4 if (returnList.size < (crateIndex + 1)) { returnList.add(ArrayDeque()) } if (c.isLetter()) { returnList[crateIndex].addLast(c) } } } } return returnList } fun createMoveList(input: List<String>) : MutableList<Move> { val returnList = mutableListOf<Move>() var mode = 0 for (line in input) { if (line.isEmpty()) { mode = 1 continue } if (mode == 0) { continue } var moveLine = line.replace("move ", "") moveLine = moveLine.replace("from ", "") moveLine = moveLine.replace("to ", "") val (crateNumber, fromIndex, toIndex) = moveLine.split(" ").map { it.toInt() } returnList.add(Move(crateNumber, fromIndex, toIndex)) } return returnList } fun part1(input: List<String>): String { val stacks = createStackList(input) val moves = createMoveList(input) for (move in moves) { for (i in 1..move.numberOfCratesToMove) { val crate = stacks[move.indexOfCrateToMoveFrom - 1].removeFirst() stacks[move.indexOfCrateToMoveTo - 1].addFirst(crate) } } var result = "" for (stack in stacks) { result += stack.first() } return result } fun part2(input: List<String>): String { val stacks = createStackList(input) val moves = createMoveList(input) for (move in moves) { val moveQueue = ArrayDeque<Char>() for (i in 1..move.numberOfCratesToMove) { val crate = stacks[move.indexOfCrateToMoveFrom - 1].removeFirst() moveQueue.addFirst(crate) } for (c in moveQueue) { stacks[move.indexOfCrateToMoveTo - 1].addFirst(c) } } var result = "" for (stack in stacks) { result += stack.first() } return result } val input = readInput(5) println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
ae153c99b58ba3749f16b3fe53f06a4b557105d3
2,933
aoc-2022
Apache License 2.0
src/Day05.kt
arksap2002
576,679,233
false
{"Kotlin": 31030}
import java.util.* import kotlin.collections.ArrayDeque fun main() { fun part1(input: List<String>): String { var result = "" val letters = mutableListOf<ArrayDeque<Char>>( ArrayDeque(listOf('V', 'C', 'D', 'R', 'Z', 'G', 'B', 'W')), ArrayDeque(listOf('G', 'W', 'F', 'C', 'B', 'S', 'T', 'V')), ArrayDeque(listOf('C', 'B', 'S', 'N', 'W')), ArrayDeque(listOf('Q', 'G', 'M', 'N', 'J', 'V', 'C', 'P')), ArrayDeque(listOf('T', 'S', 'L', 'F', 'D', 'H', 'B')), ArrayDeque(listOf('J', 'V', 'T', 'W', 'M', 'N')), ArrayDeque(listOf('P', 'F', 'L', 'C', 'S', 'T', 'G')), ArrayDeque(listOf('B', 'D', 'Z')), ArrayDeque(listOf('M', 'N', 'Z', 'W')) ) for (line in input) { if (!line.contains("move")) continue val n = line.split(' ')[1].toInt() val x = line.split(' ')[3].toInt() - 1 val y = line.split(' ')[5].toInt() - 1 for (i in 0 until n) { letters[y].addLast(letters[x].removeLast()) } } for (q in letters) { result += q.removeLast() } return result } fun part2(input: List<String>): String { var result = "" val letters = mutableListOf<ArrayDeque<Char>>( ArrayDeque(listOf('V', 'C', 'D', 'R', 'Z', 'G', 'B', 'W')), ArrayDeque(listOf('G', 'W', 'F', 'C', 'B', 'S', 'T', 'V')), ArrayDeque(listOf('C', 'B', 'S', 'N', 'W')), ArrayDeque(listOf('Q', 'G', 'M', 'N', 'J', 'V', 'C', 'P')), ArrayDeque(listOf('T', 'S', 'L', 'F', 'D', 'H', 'B')), ArrayDeque(listOf('J', 'V', 'T', 'W', 'M', 'N')), ArrayDeque(listOf('P', 'F', 'L', 'C', 'S', 'T', 'G')), ArrayDeque(listOf('B', 'D', 'Z')), ArrayDeque(listOf('M', 'N', 'Z', 'W')) ) for (line in input) { if (!line.contains("move")) continue val n = line.split(' ')[1].toInt() val x = line.split(' ')[3].toInt() - 1 val y = line.split(' ')[5].toInt() - 1 val arr = mutableListOf<Char>() for (i in 0 until n) { arr.add(letters[x].removeLast()) } arr.reverse() for (i in 0 until n) { letters[y].addLast(arr[i]) } } for (q in letters) { result += q.removeLast() } return result } val input = readInput("Day05") part1(input).println() part2(input).println() }
0
Kotlin
0
0
a24a20be5bda37003ef52c84deb8246cdcdb3d07
2,618
advent-of-code-kotlin
Apache License 2.0
src/Day06.kt
ajmfulcher
573,611,837
false
{"Kotlin": 24722}
fun main() { fun findUniqueBlockEnd(input: String, size: Int): Int { val line = input.toCharArray() val set = HashSet<Char>() var idx = 0 while (set.size != size) { set.clear() set.addAll(line.copyOfRange(idx, idx + size).toList()) idx += 1 } return idx + size - 1 } fun part1(input: List<String>): Int { return findUniqueBlockEnd(input[0], 4) } fun part2(input: List<String>): Int { return findUniqueBlockEnd(input[0], 14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") println(part1(testInput)) check(part1(testInput) == 7) val input = readInput("Day06") println(part1(input)) println(part2(testInput)) check(part2(testInput) == 19) println(part2(input)) }
0
Kotlin
0
0
981f6014b09e347241e64ba85e0c2c96de78ef8a
889
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/day02/Day02.kt
tiefenauer
727,712,214
false
{"Kotlin": 11843}
/** * --- Day 2: Cube Conundrum --- * You're launched high into the atmosphere! The apex of your trajectory just barely reaches the surface of a large island floating in the sky. You gently land in a fluffy pile of leaves. It's quite cold, but you don't see much snow. An Elf runs over to greet you. * * The Elf explains that you've arrived at Snow Island and apologizes for the lack of snow. He'll be happy to explain the situation, but it's a bit of a walk, so you have some time. They don't get many visitors up here; would you like to play a game in the meantime? * * As you walk, the Elf shows you a small bag and some cubes which are either red, green, or blue. Each time you play this game, he will hide a secret number of cubes of each color in the bag, and your goal is to figure out information about the number of cubes. * * To get information, once a bag has been loaded with cubes, the Elf will reach into the bag, grab a handful of random cubes, show them to you, and then put them back in the bag. He'll do this a few times per game. * * You play several games and record the information from each game (your puzzle input). Each game is listed with its ID number (like the 11 in Game 11: ...) followed by a semicolon-separated list of subsets of cubes that were revealed from the bag (like 3 red, 5 green, 4 blue). * * For example, the record of a few games might look like this: * * Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green * Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue * Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red * Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red * Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green * In game 1, three sets of cubes are revealed from the bag (and then put back again). The first set is 3 blue cubes and 4 red cubes; the second set is 1 red cube, 2 green cubes, and 6 blue cubes; the third set is only 2 green cubes. * * The Elf would first like to know which games would have been possible if the bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes? * * In the example above, games 1, 2, and 5 would have been possible if the bag had been loaded with that configuration. However, game 3 would have been impossible because at one point the Elf showed you 20 red cubes at once; similarly, game 4 would also have been impossible because the Elf showed you 15 blue cubes at once. If you add up the IDs of the games that would have been possible, you get 8. * * Determine which games would have been possible if the bag had been loaded with only 12 red cubes, 13 green cubes, and 14 blue cubes. What is the sum of the IDs of those games? */ package day02 import readLines private const val LINE_PREFIX = "Game " private const val MAX_RED = 12 private const val MAX_GREEN = 13 private const val MAX_BLUE = 14 private val sample = """ Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green """.trimIndent().split("\n") fun main() { val lines = "day02.txt".readLines() val part1 = lines.part1() println(part1) // 2105 val part2 = lines.part2() println(part2) // 72422 } private fun List<String>.part1() = filter { it.isPossible() }.sumOf { it.id() } private fun List<String>.part2() = sumOf { it.getPower() } private fun String.isPossible(): Boolean { rounds().forEach { val (numberOfCubes, color) = it.getNumberOfCubesAndColor() if (color == "red" && numberOfCubes.toInt() > MAX_RED) { return false } if (color == "green" && numberOfCubes.toInt() > MAX_GREEN) { return false } if (color == "blue" && numberOfCubes.toInt() > MAX_BLUE) { return false } } return true } private fun String.getPower(): Int { val minimums = calculateMinimumsByColor() val minRed = minimums.getOrDefault("red", 0) val minGreen = minimums.getOrDefault("green", 0) val minBlue = minimums.getOrDefault("blue", 0) return minRed * minGreen * minBlue } private fun String.calculateMinimumsByColor() = rounds() .map { val (numberOfCubes, color) = it.getNumberOfCubesAndColor() color to numberOfCubes.toInt() } .groupBy { it.first }.mapValues { it.value.maxBy { it.second }.second } private fun String.rounds() = games().flatMap { it.split(", ") } private fun String.games() = getIdAndGames().last().split("; ") private fun String.id() = getIdAndGames().first().toInt() private fun String.getIdAndGames() = drop(LINE_PREFIX.length).split(": ") private fun String.getNumberOfCubesAndColor() = split(" ")
0
Kotlin
0
0
ffa90fbdaa779cfff956fab614c819274b793d04
4,900
adventofcode-2023
MIT License
solutions/src/NumberOfClosedIslands.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/number-of-closed-islands/ */ class NumberOfClosedIslands { fun closedIsland(grid: Array<IntArray>): Int { var numIslands = 0 val visited = mutableSetOf<Pair<Int,Int>>() for (i in grid.indices) { for (j in grid[0].indices) { val currentSpace = Pair(i,j) if (!visited.contains(currentSpace) && grid[i][j] == 0) { val validIsland = dfsIsland(currentSpace,visited,grid) numIslands+= if (validIsland) 1 else 0 } } } return numIslands } fun dfsIsland(space: Pair<Int,Int>, visited: MutableSet<Pair<Int,Int>>, grid: Array<IntArray>) : Boolean { if (space.first >= grid.size || space.second >= grid[0].size || space.first < 0 || space.second < 0 ) { return false } if (grid[space.first][space.second] == 1) { return true } if (visited.contains(space)) { return true } var valid = true visited.add(space) val possibleMoves = listOf( Pair(space.first-1,space.second), Pair(space.first+1,space.second), Pair(space.first,space.second+1), Pair(space.first,space.second-1) ) for (move in possibleMoves) { valid = dfsIsland(move,visited,grid) && valid } return valid } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,484
leetcode-solutions
MIT License
kotlin/Determinant.kt
indy256
1,493,359
false
{"Java": 545116, "C++": 266009, "Python": 59511, "Kotlin": 28391, "Rust": 4682, "CMake": 571}
import kotlin.math.abs // https://en.wikipedia.org/wiki/Determinant fun det(matrix: Array<DoubleArray>): Double { val EPS = 1e-10 val a = matrix.map { it.copyOf() }.toTypedArray() val n = a.size var res = 1.0 for (i in 0 until n) { val p = (i until n).maxByOrNull { abs(a[it][i]) }!! if (abs(a[p][i]) < EPS) return 0.0 if (i != p) { res = -res a[i] = a[p].also { a[p] = a[i] } } res *= a[i][i] for (j in i + 1 until n) a[i][j] /= a[i][i] for (j in 0 until n) if (j != i && abs(a[j][i]) > EPS /*optimizes overall complexity to O(n^2) for sparse matrices*/) for (k in i + 1 until n) a[j][k] -= a[i][k] * a[j][i] } return res } // Usage example fun main() { val d = det(arrayOf(doubleArrayOf(0.0, 1.0), doubleArrayOf(-1.0, 0.0))) println(abs(d - 1) < 1e-10) }
97
Java
561
1,806
405552617ba1cd4a74010da38470d44f1c2e4ae3
947
codelibrary
The Unlicense
src/main/kotlin/aoc2020/DockingData.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2020 import komu.adventofcode.utils.nonEmptyLines fun dockingData1(input: String): Long { val memory = mutableMapOf<Long, Long>() for ((mask, assignments) in parseDockingData(input)) for ((address, value) in assignments) memory[address] = applyMask(value, mask) return memory.values.sum() } fun dockingData2(input: String): Long { val memory = mutableMapOf<Long, Long>() for ((mask, assignments) in parseDockingData(input)) for ((address, value) in assignments) for (realAddress in applyMask2(address, mask)) memory[realAddress] = value return memory.values.sum() } private fun parseDockingData(input: String): List<Pair<String, List<Pair<Long, Long>>>> { val assignRegex = Regex("""mem\[(.+)] = (.+)""") val result = mutableListOf<Pair<String, List<Pair<Long, Long>>>>() val current = mutableListOf<Pair<Long, Long>>() var mask = "" fun flush() { if (current.isNotEmpty()) { result += Pair(mask, current.toList()) current.clear() } } for (line in input.nonEmptyLines()) { if (line.startsWith("mask = ")) { flush() mask = line.removePrefix("mask = ") } else { val (_, address, value) = assignRegex.matchEntire(line)?.groupValues ?: error("no match for '$line'") current += Pair(address.toLong(), value.toLong()) } } flush() return result } private fun applyMask(value: Long, mask: String): Long { fun recurse(mask: String, acc: Long): Long = if (mask.isNotEmpty()) { val bit = when (mask[0]) { 'X' -> (value shr mask.length - 1) and 1 '1' -> 1 '0' -> 0 else -> error("invalid mask char") } recurse(mask.drop(1), (acc shl 1) or bit) } else acc return recurse(mask, 0) } private fun applyMask2(value: Long, mask: String): List<Long> { fun recurse(mask: String, acc: Long): List<Long> = if (mask.isNotEmpty()) { val bits = when (mask[0]) { '0' -> listOf((value shr mask.length - 1) and 1) '1' -> listOf(1L) 'X' -> listOf(0L, 1L) else -> error("invalid mask char") } bits.flatMap { bit -> recurse(mask.drop(1), (acc shl 1) or bit) } } else listOf(acc) return recurse(mask, 0) }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,526
advent-of-code
MIT License
src/main/kotlin/Chapter05/Map.kt
PacktPublishing
143,155,611
false
null
package Chapter5 fun createMap(){ val map: Map<Int,String> = mapOf( Pair(1,"One"), Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three"), 4 to "Four", 5 to "Five") for(pair in map){ println("${pair.key} ${pair.value}") } val setOfPairs = map.entries for ((key, value) in setOfPairs) { println("$key $value") } } fun mapFunctions(){ val map: Map<Int,String> = mapOf( Pair(1,"One"), Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three"), 4 to "Four", 5 to "Five") //Check if map is empty or not if( map.isNotEmpty()) { println("Map size is ${map.size}" ) val setofkeys = map.keys println("Keys $setofkeys") val setofvalues = map.values println("Values $setofvalues") var key = 1 if(map.containsKey(key)) { val value = map.get(key) println("key: $key value: $value") } } } fun mapDaysOfWeek01(day: Int): String? { var result : String? val daysOfWeek: Map<Int, String> = mapOf(1 to "Monday", 2 to "Tuesday", 3 to "Wednesday", 4 to "Thrusday", 5 to "Firday", 6 to "Saturday", 7 to "Sunday") result = daysOfWeek.get(day) return result } fun mapDaysOfWeek02(day: Int): String { var result : String val daysOfWeek: Map<Int, String> = mapOf(1 to "Monday", 2 to "Tuesday", 3 to "Wednesday", 4 to "Thrusday", 5 to "Firday", 6 to "Saturday", 7 to "Sunday") result = daysOfWeek.getOrDefault(day, "Invalid input") return result } fun mutableMapPutFunction(){ val map : MutableMap<Int,String> = mutableMapOf ( Pair(1,"One"), Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three")) map.put(4 ,"Four") var result = map.put(4 ,"FOUR") println(map) println("Put " + result) result = map.put(1 ,"One") println(map) println("Put " + result) } fun mutableMapRemove(){ val map : MutableMap<Int,String> = mutableMapOf ( Pair(1,"One"),Pair(2,"Two"), Pair(3,"Three"), Pair(4,"Four")) println(map) var result = map.remove(4) println("Remove " + result) var success = map.remove(2,"Two") println("Remove " + success) println(map) } fun clearAndPutAll(){ val map : MutableMap<Int,String> = mutableMapOf ( Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three")) println(map) val miniMap = mapOf(Pair(4,"Four"),Pair(5,"Five")) map.putAll(miniMap) println(map) map.clear() println(map) map.putAll(miniMap) println(map) } fun main(args: Array<String>) { mutableMapPutFunction() }
0
Kotlin
13
22
1d36b576b8763387645a505cb8566c679c1e522b
2,524
Hands-On-Object-Oriented-Programming-with-Kotlin
MIT License
src/algorithm/BubbleSort.kt
DavidZhong003
157,566,685
false
null
package algorithm /** * 冒泡排序算法 * 时间复杂度 O(n²) * 空间复杂度 O(1) * 步骤: * 1. 比较相邻的两个元素,如果第一个大于第二个(或者小于),进行交换. * 2. 重复进行,最后一个元素是最大(最小)元素. * 3. 对所有未排序元素进行上述操作,知道排序完成. * @author doive * on 2018/12/17 10:56 */ class BubbleSort : IArraySort{ override fun sort(array: IntArray): IntArray { for (index in array.indices){ for (j in (0 until array.size-index-1)){ if (array[j]>array[j+1]){ val temp = array[j] array[j] = array[j+1] array[j+1] = temp } } } return array } } fun main(args: Array<String>) { BubbleSort().sort(intArrayOf(1,4,3,5,56,7,89,69,88,12,4,6)).print() SelectionSort().sort(intArrayOf(3,4,5,2,3,7,8,9,10)).print() }
0
Kotlin
0
1
7eabe9d651013bf06fa813734d6556d5c05791dc
953
LeetCode-kt
Apache License 2.0
src/main/kotlin/org/wow/learning/vectorizers/planet/PlanetVectorizer.kt
WonderBeat
22,673,830
false
null
package org.wow.learning.vectorizers.planet import com.epam.starwors.galaxy.Planet import org.wow.evaluation.transition.PlayerGameTurn import org.wow.logger.PlayerMove import org.apache.mahout.vectorizer.encoders.FeatureVectorEncoder import org.wow.learning.vectorizers.Vectorizer import org.apache.mahout.math.Vector import org.apache.mahout.math.RandomAccessSparseVector public data class PlanetTransition(val from: Planet, val to: Planet, val moves: List<PlayerMove>) data class FeatureExtractor(val encoder: FeatureVectorEncoder,val eval: (Planet) -> Double, val weight: Double) fun planetMoves(transition: PlayerGameTurn): List<PlanetTransition> { val nonSymmetricMoves = transition.from.moves.fold(listOf<PlayerMove>(), {(acc, move) -> if(transition.from.moves.any { it.from == move.to && it.to == move.from && it.unitCount > move.unitCount }) acc else acc.plus(move) }) val planetsThatMoves = nonSymmetricMoves.fold(listOf<String>(), { (acc, item) -> acc.plus(item.from).plus(item.to)}).toSet() return transition.from.planets .filter { it.getOwner() == transition.playerName } .filter { planetsThatMoves.contains(it.getId()) } .map { sourcePlanet -> PlanetTransition(sourcePlanet, transition.to.planets.first { it.getId() == sourcePlanet.getId() }, transition.from.moves) } } public class PlanetVectorizer(private val featuresExtractors: List<FeatureExtractor>) : Vectorizer<Planet, Vector> { override fun vectorize(input: Planet): Vector { return featuresExtractors.withIndices() .fold<Pair<Int, FeatureExtractor>, Vector>(RandomAccessSparseVector(featuresExtractors.size), { (acc, extractor) -> acc.set(extractor.first, extractor.second.eval(input) * extractor.second.weight); acc }) } }
0
Kotlin
0
0
92625c1e4031ab4439f8d8a47cfeb107c5bd7e31
2,003
suchmarines
MIT License
src/Day11.kt
nordberg
573,769,081
false
{"Kotlin": 47470}
typealias ApeId = Int data class Event( val inspectedItem: Long, val throwerId: ApeId, val receiverId: ApeId ) data class Ape( val id: ApeId, val items: List<Long>, val worryLevelInc: (Long) -> Long, val throwToTrue: ApeId, val throwToFalse: ApeId, val dividend: Long, val numItemsInspected: Int, val problemPart: Short ) { fun inspect(itemWorryLevel: Long): Long { return if (problemPart == 1.toShort()) { worryLevelInc(itemWorryLevel).floorDiv(3) } else { val new = worryLevelInc(itemWorryLevel) check(new > itemWorryLevel) { "Expected $new > $itemWorryLevel" } return new } } fun getRecipientOf(item: Long): ApeId { return if (item % dividend == 0L) { throwToTrue } else { throwToFalse } } } fun parseOperation(s: List<String>): (Long) -> Long { if (s.last() == "old") { return { x: Long -> x * x } } return when (s.first()) { "+" -> { x: Long -> x + s.last().toLong() } "*" -> { x: Long -> x * s.last().toLong() } else -> throw IllegalStateException("$s") } } fun parseApe(apeAsStr: String, problemPart: Short): Ape { val lines = apeAsStr.split("\n") val id = lines[0].split(" ")[1].dropLast(1).toInt() val startingItems = lines[1].dropWhile { !it.isDigit() }.split(", ").map { it.toLong() }.toList() val operation = parseOperation(lines[2].split(" ").takeLast(2)) val divisibleBy = lines[3].split(" ").last().toInt() val throwToIfTestTrue = lines[4].split(" ").last().toInt() val throwToIfTestFalse = lines[5].split(" ").last().toInt() return Ape( id = id, items = startingItems, worryLevelInc = operation, throwToTrue = throwToIfTestTrue, throwToFalse = throwToIfTestFalse, numItemsInspected = 0, dividend = divisibleBy.toLong(), problemPart = problemPart ) } fun List<Ape>.print(start: Int = 0, selectOnlyApesWithItems: Boolean) { this.drop(start).filter { it.items.isNotEmpty() && selectOnlyApesWithItems}.forEach { println("Ape ${it.id}: ${it.items.joinToString(", ")}") } } fun main() { /** * Generates all events one ape omits during one round */ fun allEventsInOneRoundFor(ape: Ape): List<Event> { return ape.items.map { ape.inspect(it) }.map { inspectedItem -> Event(inspectedItem, ape.id, ape.getRecipientOf(inspectedItem)) } } /** * Applies a list of events to a group of apes */ operator fun List<Ape>.plus(events: List<Event>): List<Ape> { return this.map { val thrownItems = events .filter { e -> e.throwerId == it.id } .map { e -> e.inspectedItem } val itemsAfterThrowing = if (thrownItems.isEmpty()) it.items else listOf() val receivedItems = events .filter { e -> e.receiverId == it.id } .map { e -> e.inspectedItem } it.copy( items = itemsAfterThrowing + receivedItems, numItemsInspected = it.numItemsInspected + thrownItems.size ) } } fun part1(apes: List<Ape>): Int { var currentApes = apes repeat(20) { for (i in 0..apes.indices.max()) { val newState = currentApes + allEventsInOneRoundFor(currentApes[i]) currentApes = newState } } currentApes.print(selectOnlyApesWithItems = false) return currentApes .map { it.numItemsInspected } .sortedDescending() .take(2) .reduce { x, y -> x * y } } fun part2(apes: List<Ape>): Int { var currentApes = apes repeat(10000) { println("Round $it") if (it % 100 == 0) { currentApes.print(selectOnlyApesWithItems = true) } for (i in 0..apes.indices.max()) { val newState = currentApes + allEventsInOneRoundFor(currentApes[i]) currentApes = newState } } currentApes.print(selectOnlyApesWithItems = false) return currentApes .map { it.numItemsInspected } .sortedDescending() .take(2) .reduce { x, y -> x * y } } val input = readInputAsString("Day11") // test if implementation meets criteria from the description, like: /* val testInput = readInputAsString("Day11_test") val testApes = testInput.split("\n\n").map { parseApe(it, 1) }.toList() check(part1(testApes) == 10605) { "Failed on test input, expected 10605 got ${part1(testApes)}" } val apes = input.split("\n\n").map { parseApe(it, 1) }.toList() val answer = part1(apes) check(answer > 87616) { "Got $answer but expected above 87616" } */ val apesPartTwo = input.split("\n\n").map { parseApe(it, 2) }.toList() val answerPartTwo = part2(apesPartTwo) check (answerPartTwo > 326366789) { "Got $answerPartTwo, expected > 326366789" } println(answerPartTwo) }
0
Kotlin
0
0
3de1e2b0d54dcf34a35279ba47d848319e99ab6b
5,249
aoc-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MedianFinder.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Collections import java.util.PriorityQueue /** * Find Median from Data Stream * @see <a href="https://leetcode.com/problems/find-median-from-data-stream/">Source</a> */ interface MedianFinder { fun addNum(num: Int) fun findMedian(): Double } sealed class MedianFinderStrategy { object SimpleSorting : MedianFinder, MedianFinderStrategy() { private val small: PriorityQueue<Int> = PriorityQueue(Collections.reverseOrder()) private val large: PriorityQueue<Int> = PriorityQueue() private var even = true override fun addNum(num: Int) { if (even) { large.offer(num) small.offer(large.poll()) } else { small.offer(num) large.offer(small.poll()) } even = !even } override fun findMedian(): Double { return if (even) { (small.peek() + large.peek()) / 2.0 } else { small.peek().toDouble() } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,711
kotlab
Apache License 2.0
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/FibonacciNumbers.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* Use this technique to solve problems that follow the Fibonacci numbers sequence, i.e., every subsequent number is calculated from the last few numbers. */ //1. Staircase fun countWaysToClimbStairs(n: Int): Int { if (n <= 1) { return 1 } var first = 1 var second = 1 for (i in 2..n) { val current = first + second first = second second = current } return second } fun main() { // Example usage val n = 4 val ways = countWaysToClimbStairs(n) println("Number of ways to climb $n stairs: $ways") } //2. House Thief fun maxStolenValue(houses: IntArray): Int { val n = houses.size if (n == 0) { return 0 } if (n == 1) { return houses[0] } var first = houses[0] var second = maxOf(houses[0], houses[1]) for (i in 2 until n) { val current = maxOf(first + houses[i], second) first = second second = current } return second } fun main() { // Example usage val houses = intArrayOf(6, 7, 1, 30, 8, 2, 4) val maxStolenValue = maxStolenValue(houses) println("Maximum stolen value: $maxStolenValue") } /* Staircase: The countWaysToClimbStairs function calculates the number of ways to climb a staircase with n steps. It uses two variables to represent the previous two Fibonacci numbers, iterating through the steps to calculate the current number of ways. House Thief: The maxStolenValue function calculates the maximum value that can be stolen from a row of houses, where no two adjacent houses can be robbed. It uses two variables to represent the maximum stolen values for the previous two houses, iterating through the houses to calculate the current maximum stolen value. */
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
1,763
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/Day01.kt
bherbst
572,621,759
false
{"Kotlin": 8206}
fun main() { fun getCalories(input: List<String>): List<Int> { var index = 0; return input.fold(mutableListOf(0)) { values, line -> if (line.isBlank()) { index++ values.add(0) } else { values[index] += line.toInt() } values } } fun part1(input: List<String>): Int { return getCalories(input).max() } fun part2(input: List<String>): Int { return getCalories(input) .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
64ce532d7a0c9904db8c8d09ff64ad3ab726ec7e
846
2022-advent-of-code
Apache License 2.0
src/main/kotlin/algos/Sorting.kt
amartya-maveriq
510,824,460
false
{"Kotlin": 42296}
package algos object Sorting { // 100,000 random numbers took 17226 milliseconds fun bubbleSort(arr: IntArray) { for (i in arr.indices) { for (j in 0 until arr.lastIndex - i) { if (arr[j] > arr[j + 1]) { arr[j] += arr[j + 1] arr[j + 1] = arr[j] - arr[j + 1] arr[j] -= arr[j + 1] } } } } // 100,000 random numbers took 34 milliseconds fun quickSort(arr: IntArray) { quickSort(arr, 0, arr.lastIndex) } private fun quickSort(arr: IntArray, left: Int, right: Int) { if (left >= right) { return } val pivot = arr[(left + right) / 2] val partition = partition(arr, left, right, pivot) quickSort(arr, left, partition - 1) quickSort(arr, partition, right) } private fun partition(arr: IntArray, left: Int, right: Int, pivot: Int): Int { var l = left var r = right while (l <= r) { if (arr[l] < pivot) { l++ continue } if (arr[r] > pivot) { r-- continue } swap(arr, l, r) l++ r-- } return l } private fun swap(arr: IntArray, left: Int, right: Int) { val temp = arr[left] arr[left] = arr[right] arr[right] = temp } fun getRandomIntArray(num: Int): IntArray { return IntArray(num) { (1..num).random() } } fun validate(arr: IntArray) { for (i in 0 until arr.lastIndex) { if (arr[i] > arr[i+1]) { println("arr is NOT SORTED!") return } } println("arr is SORTED!") } }
0
Kotlin
0
0
2f12e7d7510516de9fbab866a59f7d00e603188b
1,846
data-structures
MIT License
src/test/kotlin/Day14.kt
FredrikFolkesson
320,692,155
false
null
import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day14 { @Test fun `part1`() { val input = readFileAsLinesUsingUseLines("/Users/fredrikfolkesson/git/advent-of-code/inputs/input-day14.txt") println(getSumOfMemory(input)) } private fun getSumOfMemory(instructions: List<String>): Long { return instructions.fold(Pair("", mapOf<Long,Long>())) { acc, line -> if(line.contains("mask")) { val newMask = line.split(" = ")[1] Pair(newMask,acc.second) } else { val (memoryAddress, value) = toMemoryAddressAndValuePair(line) Pair(acc.first, acc.second + mapOf(memoryAddress to numberAfterMasking(value, acc.first))) } }.second.values.sum().toLong() } @Test fun `test mem-line parsing`() { assertEquals(Pair(24821,349), toMemoryAddressAndValuePair("mem[24821] = 349")) assertEquals(Pair(34917,13006), toMemoryAddressAndValuePair("mem[34917] = 13006")) assertEquals(Pair(53529,733), toMemoryAddressAndValuePair("mem[53529] = 733")) assertEquals(Pair(50289,245744), toMemoryAddressAndValuePair("mem[50289] = 245744")) assertEquals(Pair(23082,6267), toMemoryAddressAndValuePair("mem[23082] = 6267")) } private fun toMemoryAddressAndValuePair(input: String): Pair<Long, Long> { val value = input.split(" = ")[1].toLong() val memoryAddress = input.split("] = ")[0].split("mem[")[1].toLong() return Pair(memoryAddress,value) } @Test fun `test masking of memoryAdress`() { assertEquals(listOf(26L,27L,58L,59L),addressesAfterMasking(42, "000000000000000000000000000000X1001X")) assertEquals(listOf(16L,17L,18L,19L,24L,25L,26L,27L),addressesAfterMasking(26, "00000000000000000000000000000000X0XX")) } @Test fun `demo part 2`() { val instructions = "mask = 000000000000000000000000000000X1001X\n" + "mem[42] = 100\n" + "mask = 00000000000000000000000000000000X0XX\n" + "mem[26] = 1" assertEquals(208, getSumOfMemoryPart2(instructions.lines())) } @Test fun `strict part 2`() { println(getSumOfMemoryPart2(readFileAsLinesUsingUseLines("/Users/fredrikfolkesson/git/advent-of-code/inputs/input-day14.txt"))) } private fun getSumOfMemoryPart2(instructions: List<String>): Long { return instructions.fold(Pair("", mapOf<Long,Long>())) { acc, line -> if(line.contains("mask")) { val newMask = line.split(" = ")[1] Pair(newMask,acc.second) } else { val (memoryAddress, value) = toMemoryAddressAndValuePair(line) Pair(acc.first, acc.second + addressesAfterMasking(memoryAddress, acc.first).map { it to value }.toMap()) } }.second.values.sum() } private fun addressesAfterMasking(memoryAdress: Long, mask: String): List<Long> { val memoryAdressBinaryString = memoryAdress.toString(2).padStart(36,'0') val memoryAdressBinaryStringWithOnesAndXes = mask.mapIndexed{index, it -> if(it =='0') memoryAdressBinaryString[index] else it }.joinToString("").padStart(36,'0') return getMemoryListsWithoutX(memoryAdressBinaryStringWithOnesAndXes) } private fun getMemoryListsWithoutX(memoryMask: String): List<Long> { if(!memoryMask.contains("X")) return listOf(memoryMask.toLong(2)) else { return getMemoryListsWithoutX(memoryMask.replaceFirst("X", "0")) + (getMemoryListsWithoutX(memoryMask.replaceFirst("X", "1"))) } } @Test fun `test masking of number`() { assertEquals(73,numberAfterMasking(11, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X")) assertEquals(101,numberAfterMasking(101, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X")) assertEquals(64,numberAfterMasking(0, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X")) } private fun numberAfterMasking(number: Long, mask: String): Long { val numberAsBinaryString = number.toString(2).padStart(36,'0') val orMaskString = mask.mapIndexed{index, it -> if(it =='1') it else numberAsBinaryString[index] }.joinToString("").padStart(36,'0') val orMaskInt = orMaskString.toLong(2) val andMaskString = mask.mapIndexed{index, it -> if(it =='0') it else orMaskString[index] }.joinToString("").padStart(36,'0') val andMaskInt = andMaskString.toLong(2) return number or orMaskInt and andMaskInt } private fun to36BitStringFormat(number: Int): String { val i = 5 and 2 return "1100" } }
0
Kotlin
0
0
79a67f88e1fcf950e77459a4f3343353cfc1d48a
4,778
advent-of-code
MIT License
src/main/kotlin/tw/gasol/aoc/aoc2022/Day8.kt
Gasol
574,784,477
false
{"Kotlin": 70912, "Shell": 1291, "Makefile": 59}
package tw.gasol.aoc.aoc2022 import org.jetbrains.annotations.TestOnly class Day8 { fun part1(input: String): Int { val treeMap = TreeMap.fromInput(input) // treeMap.printVisibleMap() return treeMap.countVisible() } fun part2(input: String): Int { val treeMap = TreeMap.fromInput(input) return treeMap.computeHighestScenicScore() } } class TreeMap(private val width: Int, private val height: Int, private val heights: List<Char>) { private val treeMap = CharArray(width * height) { index -> heights[index] } fun get(x: Int, y: Int): Char { assert(x in 0 until width) { "x is out of range" } assert(y in 0 until height) { "y is out of range" } return treeMap[y * width + x] } private fun getHeightList(x: Int, y: Int, from: Direction): List<Char> { return when (from) { Direction.TOP -> (0 until height).map { get(x, it) } Direction.BOTTOM -> (height - 1 downTo 0).map { get(x, it) } Direction.LEFT -> (0 until width).map { get(it, y) } Direction.RIGHT -> (width - 1 downTo 0).map { get(it, y) } } } private fun buildVisibleMap(): BooleanArray { val visibleMap = BooleanArray(width * height) { false } val setVisible = { x: Int, y: Int, value: Boolean -> assert(x in 0 until width) { "x ($x) is out of range" } assert(y in 0 until height) { "y ($y) is out of range" } visibleMap[y * width + x] = value } (0 until width).forEach { x -> var baseHeight = '.' getHeightList(x, 0, Direction.TOP).forEachIndexed { y, height -> val visible = if (height > baseHeight) { baseHeight = height true } else false if (visible) { setVisible(x, y, true) } } baseHeight = '.' getHeightList(x, 0, Direction.BOTTOM).forEachIndexed { reversedY, height -> val visible = if (height > baseHeight) { baseHeight = height true } else false if (visible) { val y = this.height - reversedY - 1 setVisible(x, y, true) } } } (0 until height).forEach { y -> var baseHeight = '.' getHeightList(0, y, Direction.LEFT).forEachIndexed { x, height -> val visible = if (height > baseHeight) { baseHeight = height true } else false if (visible) { setVisible(x, y, true) } } baseHeight = '.' getHeightList(0, y, Direction.RIGHT).forEachIndexed { reversedX, height -> val visible = if (height > baseHeight) { baseHeight = height true } else false if (visible) { val x = this.height - reversedX - 1 setVisible(x, y, true) } } } return visibleMap } fun countVisible() = buildVisibleMap().count { it } fun printVisibleMap() { val visibleMap = buildVisibleMap() val getVisible = { x: Int, y: Int -> assert(x in 0 until width) { "x ($x) is out of range" } assert(y in 0 until height) { "y ($y) is out of range" } visibleMap[y * width + x] } (0 until height).forEach { y -> (0 until width).forEach { x -> print(if (getVisible(x, y)) 'V' else ' ') } println() } } fun computeHighestScenicScore(): Int { var highestScore = 0 (0 until height).forEach { y -> (0 until width).forEach { x -> getScenicScore(x, y) .takeIf { it > highestScore } ?.let { highestScore = it } } } return highestScore } private fun computeScore(axis: Axis, pos: Int, range: IntProgression, treeHeight: Char): Int { var score = 0 for (i in range) { val (x, y) = if (axis == Axis.X) { pos to i } else { i to pos } val height = get(x, y) score++ if (height >= treeHeight) { break } } return score } @TestOnly fun computeUpScore(x: Int, y: Int, treeHeight: Char) = computeScore(Axis.X, x, y - 1 downTo 0, treeHeight) @TestOnly fun computeDownScore(x: Int, y: Int, treeHeight: Char) = computeScore(Axis.X, x, y + 1 until height, treeHeight) @TestOnly fun computeLeftScore(x: Int, y: Int, treeHeight: Char) = computeScore(Axis.Y, y, x - 1 downTo 0, treeHeight) @TestOnly fun computeRightScore(x: Int, y: Int, treeHeight: Char) = computeScore(Axis.Y, y, x + 1 until width, treeHeight) private fun getScenicScore(x: Int, y: Int): Int { val treeHeight = get(x, y) return arrayOf(::computeUpScore, ::computeLeftScore, ::computeRightScore, ::computeDownScore) .map { it(x, y, treeHeight) } .reduce(Math::multiplyExact) } companion object { fun fromInput(input: String): TreeMap { val lines = input.lines() .filterNot { it.isBlank() } val heights = lines.flatMap { it.toList() } // flat to 1D return TreeMap(lines.size, lines.first().length, heights) } } } enum class Direction { TOP, BOTTOM, LEFT, RIGHT } enum class Axis { X, Y }
0
Kotlin
0
0
a14582ea15f1554803e63e5ba12e303be2879b8a
5,851
aoc2022
MIT License
src/main/kotlin/day08/Day08.kt
vitalir2
572,865,549
false
{"Kotlin": 89962}
package day08 import Challenge private typealias Forest = List<List<Int>> object Day08 : Challenge(8) { override fun part1(input: List<String>): Any { val forest = createForest(input) val visibleTrees = mutableListOf<Int>() for ((rowIndex, row) in forest.withIndex()) { for ((columnIndex, tree) in row.withIndex()) { if (forest.isOnEdge(rowIndex, columnIndex)) { visibleTrees.add(tree) continue } val isVisibleFrom = mutableListOf<Direction>() for (direction in Direction.values()) { var isVisible = true forest.traverseInDirection(rowIndex, columnIndex, direction) { otherTree -> if (otherTree >= tree) { isVisible = false } } if (isVisible) { isVisibleFrom.add(direction) } } if (isVisibleFrom.isNotEmpty()) { visibleTrees.add(tree) } } } return visibleTrees.count() } override fun part2(input: List<String>): Any { val forest = createForest(input) val viewScores = mutableListOf<Int>() for ((rowIndex, row) in forest.withIndex()) { for ((columnIndex, tree) in row.withIndex()) { if (forest.isOnEdge(rowIndex, columnIndex)) { viewScores.add(0) continue } val visibilityScoresForTree = mutableListOf<Int>() for (direction in Direction.values()) { var stopScoring = false var visibilityScore = 0 forest.traverseInDirection(rowIndex, columnIndex, direction) { otherTree -> if (!stopScoring) { visibilityScore++ } if (otherTree >= tree) { stopScoring = true } } visibilityScoresForTree.add(visibilityScore) } val totalScore = visibilityScoresForTree.reduce { acc, i -> acc * i } viewScores.add(totalScore) } } return viewScores.max() } private fun createForest(input: List<String>): Forest { return buildList { for (treeRow in input) { val treeList = buildList { for (tree in treeRow) { add(tree.digitToInt()) } } add(treeList) } } } private fun Forest.traverseInDirection( xStart: Int, yStart: Int, direction: Direction, action: (currentElement: Int) -> Unit, ) { when (direction) { Direction.LEFT -> { var rowIndex = xStart - 1 while (rowIndex >= 0) { action(this[rowIndex][yStart]) rowIndex-- } } Direction.RIGHT -> { var rowIndex = xStart + 1 while (rowIndex <= this.lastIndex) { action(this[rowIndex][yStart]) rowIndex++ } } Direction.TOP -> { var colIndex = yStart - 1 while (colIndex >= 0) { action(this[xStart][colIndex]) colIndex-- } } Direction.BOTTOM -> { var colIndex = yStart + 1 while (colIndex <= this.first().lastIndex) { action(this[xStart][colIndex]) colIndex++ } } } } private fun Forest.isOnEdge(x: Int, y: Int): Boolean { return x == 0 || x == lastIndex || y == 0 || y == firstOrNull()?.lastIndex } private enum class Direction { LEFT, RIGHT, TOP, BOTTOM, } }
0
Kotlin
0
0
ceffb6d4488d3a0e82a45cab3cbc559a2060d8e6
4,241
AdventOfCode2022
Apache License 2.0
codeforces/vk2021/qual/ad.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.vk2021.qual fun main() { val words = "lock, unlock, red, orange, yellow, green, blue, indigo, violet".split(", ") val wordsMap = words.withIndex().associate { it.value to it.index } val init = List(readInt()) { wordsMap[readLn()]!! } val st = SegmentsTreeSimple(init.size) for (i in init.indices) { st[i] = init[i] } fun answer() { val ans = st.answer() println(words[ans]) } answer() repeat(readInt()/*0*/) { val (indexString, word) = readLn().split(" ") val index = indexString.toInt() - 1 val newWord = wordsMap[word]!! st[index] = newWord answer() } } private class SegmentsTreeSimple(var n: Int) { var lock: IntArray private var colorIfLocked: IntArray private var colorIfUnlocked: IntArray var size = 1 init { while (size <= n) { size *= 2 } lock = IntArray(2 * size) colorIfLocked = IntArray(2 * size) colorIfUnlocked = IntArray(2 * size) } operator fun set(index: Int, value: Int) { var i = size + index if (value >= 2) { colorIfUnlocked[i] = value colorIfLocked[i] = 0 lock[i] = 0 } else { colorIfUnlocked[i] = 0 colorIfLocked[i] = 0 if (value == 0) lock[i] = 1 else lock[i] = -1 } while (i > 1) { i /= 2 val colorIfLockedLeft = colorIfLocked[2 * i] val colorIfUnlockedLeft = colorIfUnlocked[2 * i] val lockLeft = lock[2 * i] val colorIfLockedRight = colorIfLocked[2 * i + 1] val colorIfUnlockedRight = colorIfUnlocked[2 * i + 1] val lockRight = lock[2 * i + 1] lock[i] = if (lockRight != 0) lockRight else if (lockLeft != 0) lockLeft else 0 run { // locked var c = colorIfLockedLeft val l = if (lockLeft == 0) 1 else lockLeft if (l == -1 && colorIfUnlockedRight != 0) c = colorIfUnlockedRight if (l == 1 && colorIfLockedRight != 0) c = colorIfLockedRight colorIfLocked[i] = c } run { // unlocked var c = colorIfUnlockedLeft val l = if (lockLeft == 0) -1 else lockLeft if (l == -1 && colorIfUnlockedRight != 0) c = colorIfUnlockedRight if (l == 1 && colorIfLockedRight != 0) c = colorIfLockedRight colorIfUnlocked[i] = c } } } fun answer(): Int { if (colorIfUnlocked[1] == 0) return 6 return colorIfUnlocked[1] } } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,287
competitions
The Unlicense
test/com/zypus/SLIP/algorithms/genetic/GeneticTest.kt
zypus
213,665,750
false
null
package com.zypus.SLIP.algorithms.genetic import com.zypus.SLIP.algorithms.genetic.builder.evolution import com.zypus.utilities.pickRandom import org.junit.Assert import org.junit.Test import java.util.* /** * TODO Add description * * @author fabian <<EMAIL>> * * @created 03/03/16 */ class GeneticTest { @Test fun testStringEvolutionWithBuilder() { val target = "hello world" val alphabet = " abcdefghijklmnopqrstuvwxyz" val survivalCount = 10 val evolutionRules = evolution<Pair<String, String>, String, Int, HashMap<Any, Int>, String, String, Int, HashMap<Any,Int>> { solution = { // Create a random string of target length. initialize = { alphabet.pickRandom(target.length) to alphabet.pickRandom(target.length)} mapping = { it.first.zip(it.second).map { p -> if ("${p.first}" < "${p.second}") p.first else p.second }.joinToString(separator = "") } select = { population -> val picked = Selections.elitist(population, survivalCount) { (it.behaviour as HashMap<*, *>).values.sumByDouble { it as Double } } val toBeReplaced = population.filter { e -> !picked.contains(e) } Selection(toBeReplaced.size, (0..4).map { picked[2 * it] to picked[2 * it + 1] }, toBeReplaced) } reproduce = { mother, father -> mother.first.crossoverAndMutate(mother.second, alphabet = alphabet, expectedMutations = 1) to father.first.crossoverAndMutate(father.second, alphabet = alphabet, expectedMutations = 1) } } singularProblem = target test = { match = { evolutionState -> evolutionState.solutions.map { it to evolutionState.problems.first() } } evaluate = { first, second -> val matches = first.zip(second).count { it.first.equals(it.second) } matches to matches } } } runEvolution2(evolutionRules, target) } private fun runEvolution(evolution: EvolutionRules<String, String, Int, HashMap<Any,Int>, String, String, Int, HashMap<Any, Int>>, target: String) { var state = evolution.initialize(100, 1) Assert.assertSame("Solution and problem length are not equal.", target.length, state.solutions.first().phenotype.length) println("Initialized:") //state.solutions.forEach { println(it.phenotype) } var generation = 1 val solved: (Entity<String, String, Int, HashMap<Any, Int>>) -> Boolean = { e -> (e.behaviour as HashMap<*,*>).values.any { it as Int == target.length } } while (state.solutions.none(solved) ) { evolution.matchAndEvaluate(state) generation++ // println("Generation ${generation++}:") // state.solutions.forEach { println("${it.phenotype} - ${it.behavior.values.first()}") } state = evolution.selectAndReproduce(state) Assert.assertTrue("To many generations.", generation < 2000) } val solution = state.solutions.first(solved).phenotype println("Final answer is \"$solution\" in $generation generations.") Assert.assertTrue("Solution is not equal to target.", target.equals(solution)) } private fun runEvolution2(evolution: EvolutionRules<Pair<String, String>, String, Int, HashMap<Any, Int>, String, String, Int, HashMap<Any, Int>>, target: String) { var state = evolution.initialize(100, 1) Assert.assertSame("Solution and problem length are not equal.", target.length, state.solutions.first().phenotype.length) println("Initialized:") //state.solutions.forEach { println(it.phenotype) } var generation = 1 val solved: (Entity<Pair<String,String>, String, Int, HashMap<Any, Int>>) -> Boolean = { e -> (e.behaviour as HashMap<*,*>).values.any { it as Int == target.length } } while (state.solutions.none(solved) ) { evolution.matchAndEvaluate(state) generation++ // println("Generation ${generation++}:") // state.solutions.forEach { println("${it.phenotype} - ${it.behavior.values.first()}") } state = evolution.selectAndReproduce(state) Assert.assertTrue("To many generations. ${state.solutions.first().phenotype}", generation < 5000) } val solution = state.solutions.first(solved) println("Final answer is \"${solution.phenotype}\" in $generation generations by ${solution.genotype}") Assert.assertTrue("Solution is not equal to target.", target.equals(solution.phenotype)) } }
0
Kotlin
0
0
418ee8837752143194fd769e86fac85e15136929
4,259
SLIP
MIT License
modules/fathom/src/main/kotlin/silentorb/mythic/fathom/surfacing/CellAccumulation.kt
silentorb
227,508,449
false
null
package silentorb.mythic.fathom.surfacing import silentorb.mythic.spatial.Vector3 import silentorb.mythic.spatial.getCenter import kotlin.math.abs data class MergeConfig( val distanceTolerance: Float, val axis: Int, val boundaryRange: Float, val cellSize: Float ) data class Clump( val first: Vector3, val second: Vector3, val middle: Vector3 ) fun getClumps(distanceTolerance: Float, firstVertices: List<Vector3>, secondVertices: List<Vector3>): List<Clump> = secondVertices .mapNotNull { b -> // TODO: This code may eventually need better neighbor selection for when there are multiple options val a = firstVertices.firstOrNull { it.distance(b) < distanceTolerance } if (a != null) Clump(a, b, getCenter(a, b)) else null } fun synchronizeEdges(vertexMap: List<Pair<Vector3, Vector3>>, edges: Edges): Edges = vertexMap.fold(edges) { accumulator, (from, to) -> accumulator.map { replaceEdgeVertex(it, from, to) } } fun synchronizeEdges(clumps: List<Clump>, firstEdges: Edges, secondEdges: Edges): Pair<Edges, Edges> { val synchronizedFirstEdges = synchronizeEdges(clumps.map { Pair(it.first, it.middle) }, firstEdges) val synchronizedSecondEdges = synchronizeEdges(clumps.map { Pair(it.second, it.middle) }, secondEdges) return Pair(synchronizedFirstEdges, synchronizedSecondEdges) } fun getDuplicates(firstEdges: Edges, secondEdges: Edges): Edges = secondEdges .filter { second -> firstEdges.any { edgesMatch(second, it) } } fun withoutDuplicates(comparison: Edges, pruning: Edges): Edges { val duplicates = getDuplicates(comparison, pruning) if (duplicates.any()) { val k = 0 } return pruning.minus(duplicates) } fun mergeEdges(sharedVertices: List<Vector3>, firstEdges: Edges, secondEdges: Edges): Edges { val edgesNeedingUnifying = sharedVertices .mapNotNull { vertex -> val first = firstEdges.filter { edgeContains(it, vertex) } val second = secondEdges.filter { edgeContains(it, vertex) } if (first.size == 1 && second.size == 1) { val a = first.first() val b = second.first() val firstVector = getEdgeVector(a) val secondVector = getEdgeVector(b) val dot = firstVector.dot(secondVector) if (abs(dot) > 0.8f) Triple(a, b, vertex) else null } else null } val unifiedEdges = edgesNeedingUnifying .map { (first, second, middle) -> val a = getOtherVertex(first, middle) val b = getOtherVertex(second, middle) Edge(a, b) } val firstResult = firstEdges.minus(edgesNeedingUnifying.map { it.first }) val secondResult = secondEdges.minus(edgesNeedingUnifying.map { it.second }) val result = firstResult.plus(secondResult).plus(unifiedEdges) assert(result.size <= firstEdges.size + secondEdges.size) return result } fun mergeCells(config: MergeConfig, boundary: Float, first: Edges, second: Edges, firstVertices: List<Vector3>, secondVertices: List<Vector3>): Edges { val firstBoundary = boundary - config.boundaryRange val secondBoundary = boundary + config.boundaryRange val firstCandidates = firstVertices .filter { it[config.axis] > firstBoundary } val secondCandidates = secondVertices .filter { it[config.axis] < secondBoundary } val clumps = getClumps(config.distanceTolerance, firstCandidates, secondCandidates) val (synced1, synced2) = synchronizeEdges(clumps, first, second) val result = mergeEdges(clumps.map { it.middle }, synced1, withoutDuplicates(synced1, synced2)) return result } fun accumulateRow( config: MergeConfig, cells: List<Edges>, boundary: Float, previousCellVertices: List<Vector3>, accumulator: Edges ): Edges = if (cells.none()) accumulator else { val next = cells.first() val nextCellVertices = getVerticesFromEdges(next) val merged = mergeCells(config, boundary, accumulator, next, previousCellVertices, nextCellVertices) accumulateRow(config, cells.drop(1), boundary + config.cellSize, nextCellVertices, merged) } fun accumulateRows(mergeConfig: MergeConfig, bounds: GridBounds, groups: List<Edges>, rowCount: Int): List<Edges> { val axis = mergeConfig.axis val dimensions = getBoundsDimensions(bounds) val rowLength = dimensions[axis] val cellSize = mergeConfig.cellSize val firstDivision = bounds.start[axis] * cellSize + cellSize return (0 until rowCount) .map { i -> val rowStart = i * rowLength val row = groups.subList(rowStart, rowStart + rowLength) assert(row.size == rowLength) val first = row.first() accumulateRow(mergeConfig, row.drop(1), firstDivision, getVerticesFromEdges(first), first) } } fun accumulateFloors(mergeConfig: MergeConfig, bounds: GridBounds, floors: List<Edges>): Edges { val axis = mergeConfig.axis val cellSize = mergeConfig.cellSize val firstDivision = bounds.start[axis] * cellSize + cellSize val first = floors.first() return accumulateRow(mergeConfig, floors.drop(1), firstDivision, getVerticesFromEdges(first), first) } fun aggregateCells(config: SurfacingConfig, bounds: GridBounds, cells: List<Edges>): Edges { val cellSize = config.cellSize val subCellSize = (cellSize / config.subCells) val mergeConfig = MergeConfig( distanceTolerance = subCellSize * 2.5f, axis = 0, boundaryRange = subCellSize * 2f, cellSize = cellSize ) val dimensions = getBoundsDimensions(bounds) val rowCount = dimensions.y * dimensions.z val rows = accumulateRows(mergeConfig, bounds, cells, rowCount) val floors = accumulateRows(mergeConfig.copy(axis = 1), bounds, rows, dimensions.z) val result = accumulateFloors(mergeConfig.copy(axis = 2), bounds, floors) return result }
0
Kotlin
0
2
74462fcba9e7805dddec1bfcb3431665df7d0dee
5,921
mythic-kotlin
MIT License
AdventOfCodeDay09/src/nativeMain/kotlin/Day09.kt
bdlepla
451,510,571
false
{"Kotlin": 165771}
class Day09(lines:List<String>) { private val data = Matrix.create(lines) fun solvePart1() = generateLowPointValues(data).sumOf{it+1} fun solvePart2() = generateBasins(data) .map{it.count()} .sortedDescending() .take(3).product() private fun generateBasins(data: Matrix): Sequence<Set<Pair<Int, Int>>> = generateLowPoints(data) .map { data.findBasin(it) } //.onEach {println("Found basic of size ${it.count()}")} private fun generateLowPoints(data:Matrix) = data.allPoints() .filter{pt -> pt.validNeighborsValues().all{ data[pt] < it } } private fun Point.validNeighborsValues() = neighbors().filter{it in data}.map{data[it]} private fun generateLowPointValues(data:Matrix) = generateLowPoints(data).map{data[it]} private fun Sequence<Int>.product() = this.reduce{a,b->a*b} }
0
Kotlin
0
0
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
906
AdventOfCode2021
The Unlicense
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec17.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2020 import org.elwaxoro.advent.PuzzleDayTester class Dec17 : PuzzleDayTester(17, 2020) { private data class Coord(val w: Int, val z: Int, val y: Int, val x: Int) override fun part1(): Any = doDumbShit((0..0)) override fun part2(): Any = doDumbShit((-1..1)) private fun doDumbShit(wRange: IntRange): Int = (1..6).fold(parse()) { activeCells, iter -> // skip coords already tried (2x speedup) val alreadyTriedSet = mutableSetOf<Coord>() // only care about active cells for the initial set of coordinates activeCells.map { activeCellCoord -> // from each active coordinate, build a set of ALL its neighbors, these are the coords to test with the rule set buildNeighbors(true, activeCellCoord, wRange).filterNot { alreadyTriedSet.contains(it) } .mapNotNull { testCellCord -> alreadyTriedSet.add(testCellCord) val isActive = activeCells.contains(testCellCord) // from each test cell cord, get ALL of its neighbors to use in the nearby active list val activeNearbyCount = buildNeighbors(false, testCellCord, wRange).filter { activeCells.contains(it) }.size if ((isActive && activeNearbyCount in listOf(2, 3)) || (!isActive && activeNearbyCount == 3)) { testCellCord // activate or keep active } else { null } } }.flatten().toSet()//.also { println("Cycle $iter had ${it.size} active cells") } }.size /** * go in all directions, make a list of all possible nearby coordinates * x,y,z are always checked at (-1..1) range * w is added for puzzle2 */ private fun buildNeighbors( includeSelf: Boolean, coord: Coord, wRange: IntRange = (0..0), range: IntRange = (-1..1) ): Set<Coord> = wRange.map { wMod -> range.map { zMod -> range.map { yMod -> range.mapNotNull { xMod -> if (!includeSelf && wMod == 0 && zMod == 0 && yMod == 0 && xMod == 0) { null } else { Coord(coord.w + wMod, coord.z + zMod, coord.y + yMod, coord.x + xMod) } } }.flatten() }.flatten() }.flatten().toSet() private fun parse(): Set<Coord> = load().mapIndexed { yIdx, row -> row.toCharArray().mapIndexed { xIdx, char -> if (char == '#') { Coord(0, 0, xIdx, yIdx) } else { null } }.filterNotNull() }.flatten().toSet() } //class Dec17FirstTry: PuzzleDayTester(17, 2020) { // // override fun puzzle1(): Any = measureTimeMillis { // var cube = parse3D() // // (1..6).forEach { iteration -> // if (cube.shouldExpand3D()) { // cube = cube.expand3D() // } // cube = cube.iterate3D() // } // // cube.countActive3D() // }.also { // println("Puzzle 1 took ${it}ms") // } // // fun List<List<List<Char>>>.countActive3D(): Int = sumBy { it.countActive2D() } // fun List<List<Char>>.countActive2D(): Int = sumBy { it.countActive1D() } // fun List<Char>.countActive1D(): Int = sumBy { if (it == '#') 1 else 0 } // // fun List<List<List<Char>>>.iterate3D(): List<List<List<Char>>> = mapIndexed { z, layer -> // layer.mapIndexed { y, row -> // row.mapIndexed { x, cell -> // val activeNeighbors = (-1..1).map { zMod -> // (-1..1).map { yMod -> // (-1..1).mapNotNull { xMod -> // if (zMod == 0 && yMod == 0 && xMod == 0) { // null // } else if (value3D(z + zMod, y + yMod, x + xMod) == '#') { // '#' // } else { // null // } // } // }.flatten() // }.flatten() // // if (cell == '#' && activeNeighbors.size in listOf(2, 3)) { // cell // } else if (cell == '.' && activeNeighbors.size == 3) { // '#' // } else { // '.' // } // } // } // } // // fun List<List<List<Char>>>.value3D(z: Int, y: Int, x: Int): Char = // if (z < 0 || z >= size || y < 0 || y >= this[0].size || x < 0 || x >= this[0][0].size) { // '_' // } else { // this[z][y][x] // } // // fun List<List<List<Char>>>.shouldExpand3D(): Boolean = any { layer -> // layer.filterIndexed { rowIdx, row -> // when { // row.first() == '#' -> true//.also { println("Row 1st char is set") } // row.last() == '#' -> true//.also { println("Row last char is set") } // rowIdx == 0 && row.contains('#') -> true//.also { println("First row is $rowIdx and has a #") } // rowIdx + 1 == row.size && row.contains('#') -> true//.also { println("Last row is $rowIdx and has a #") } // else -> false // } // }.isNotEmpty() // } // // fun List<List<List<Char>>>.expand3D(): List<List<List<Char>>> { // val targetSize = first().first().size + 2 // val padRow: List<Char> = (1..targetSize).map { '.' } // val padLayer: List<List<List<Char>>> = listOf((1..targetSize).map { padRow }) // // return padLayer.plus(map { innerLayer -> // listOf(padRow).plus(innerLayer.map { innerRow -> // listOf('.').plus(innerRow).plus('.') // }).plus(listOf(padRow)) // }).plus(padLayer) // } // // fun List<List<List<Char>>>.print3D() { // val mid = size / 2 // forEachIndexed { idx, layer -> // println("z:${idx - mid}") // println(layer.joinToString("\n") { // it.joinToString("") // }) // } // } // // fun parse3D(): List<List<List<Char>>> = listOf(loadInputFile().map { xRow -> // xRow.toCharArray().toList() // }) // //}
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
6,539
advent-of-code
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day17.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.ints fun main() = Day17.run() object Day17 : Day(2015, 17) { override fun part1(): Any { val containers = ints(input) var ways = mapOf(150 to 1) for (container in containers) { val n = ways.toMutableMap() for ((left, v) in ways) { if (left >= container) { n[left - container] = n.getOrDefault(left - container, 0) + v } } ways = n } return ways[0]!! } override fun part2(): Any { val containers = ints(input) var ways = mutableMapOf(150 to mutableMapOf(0 to 1)) for (container in containers) { val n = ways.mapValues { (_, v) -> v.toMutableMap() }.toMutableMap() for ((left, v) in ways) { if (left >= container) { for ((i, j) in v) { val m = n.getOrPut(left - container, ::mutableMapOf) m[i + 1] = m.getOrDefault(i + 1, 0) + j } } } ways = n } return ways[0]!!.entries.minBy { it.key }.value } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,261
adventofkotlin
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem2269/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2269 /** * LeetCode page: [2269. Find the K-Beauty of a Number](https://leetcode.com/problems/find-the-k-beauty-of-a-number/); */ class Solution { /* Complexity: * Time O(LogN) and Space O(LogN) where N equals num; */ fun divisorSubstrings(num: Int, k: Int): Int { val digits = num.getDigits() var countValid = 0 var currWindowValue = getFirstWindowValue(digits, k) if (currWindowValue.isBeauty(num)) countValid++ val multiplierOfLeadingDigit = getMultiplierOfLeadingDigit(k) for (index in digits.lastIndex - k downTo 0) { currWindowValue = currWindowValue / 10 + digits[index] * multiplierOfLeadingDigit if (currWindowValue.isBeauty(num)) countValid++ } return countValid } private fun Int.getDigits(): List<Int> { return this .toString() .map { it - '0' } } private fun Int.isBeauty(num: Int) = this != 0 && num % this == 0 private fun getFirstWindowValue(digits: List<Int>, size: Int): Int { var windowValue = 0 for (index in digits.size - size..digits.lastIndex) { windowValue = windowValue * 10 + digits[index] } return windowValue } private fun getMultiplierOfLeadingDigit(size: Int): Int { var multiplier = 1 repeat(size - 1) { multiplier *= 10 } return multiplier } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,461
hj-leetcode-kotlin
Apache License 2.0
day15/kotlin/corneil/src/main/kotlin/solution.kt
mehalter
317,661,818
true
{"HTML": 2739009, "Java": 348790, "Kotlin": 271053, "TypeScript": 262310, "Python": 198318, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Tcl": 46}
package com.github.corneil.aoc2019.day15 import com.github.corneil.aoc2019.common.Graph import com.github.corneil.aoc2019.common.Graph.Edge import com.github.corneil.aoc2019.day15.DIRECTION.EAST import com.github.corneil.aoc2019.day15.DIRECTION.NORTH import com.github.corneil.aoc2019.day15.DIRECTION.SOUTH import com.github.corneil.aoc2019.day15.DIRECTION.WEST import com.github.corneil.aoc2019.day15.RobotStatus.MOVED import com.github.corneil.aoc2019.day15.RobotStatus.OXYGEN import com.github.corneil.aoc2019.day15.RobotStatus.UNKNOWN import com.github.corneil.aoc2019.day15.RobotStatus.WALL import com.github.corneil.aoc2019.day15.STRATEGY.ALTERNATE import com.github.corneil.aoc2019.day15.STRATEGY.LEFT import com.github.corneil.aoc2019.day15.STRATEGY.RANDOM import com.github.corneil.aoc2019.day15.STRATEGY.RIGHT import com.github.corneil.aoc2019.intcode.Program import com.github.corneil.aoc2019.intcode.readProgram import org.fusesource.jansi.Ansi import org.fusesource.jansi.AnsiConsole import java.io.File import kotlin.random.Random data class Coord(val x: Int, val y: Int) : Comparable<Coord> { override fun compareTo(other: Coord): Int { var result = y.compareTo(other.y) if (result == 0) { result = x.compareTo(other.x) } return result } fun move(direction: DIRECTION): Coord { return when (direction) { NORTH -> copy(y = y - 1) SOUTH -> copy(y = y + 1) EAST -> copy(x = x + 1) WEST -> copy(x = x - 1) } } } enum class DIRECTION(val value: Int) { NORTH(1), SOUTH(2), WEST(3), EAST(4); fun nextLeft(): DIRECTION = when (this) { NORTH -> WEST WEST -> SOUTH SOUTH -> EAST EAST -> NORTH } fun nextRight(): DIRECTION = when (this) { NORTH -> EAST EAST -> SOUTH SOUTH -> WEST WEST -> NORTH } } enum class STRATEGY { LEFT, RIGHT, ALTERNATE, RANDOM } fun direction(direction: DIRECTION): String { return when (direction) { NORTH -> "^" WEST -> "<" SOUTH -> "v" EAST -> ">" } } fun directionFrom(input: Int): DIRECTION { return DIRECTION.values().find { it.value == input } ?: error("Invalid direction $input") } enum class RobotStatus(val input: Int) { WALL(0), MOVED(1), OXYGEN(2), UNKNOWN(-1) } fun robotStatusFrom(input: Int): RobotStatus { return RobotStatus.values().find { it.input == input } ?: error("Invalid RobotStatus $input") } val random = Random(System.currentTimeMillis()) data class Cell(val pos: Coord, val status: RobotStatus, var visits: Int = 0) class Robot( var location: Coord, dir: DIRECTION, var prevLocation: Coord = Coord(0, 0), var prev: DIRECTION = NORTH, var moves: Int = 0, var prevChoice: Boolean = false ) { var direction: DIRECTION = dir set(value) { prev = direction field = value } fun move() { prevLocation = location location = location.move(direction) moves += 1 } fun next(strategy: STRATEGY): DIRECTION { prev = direction return when (strategy) { LEFT -> direction.nextLeft() RIGHT -> direction.nextRight() ALTERNATE -> { val choice = if (prevChoice) direction.nextRight() else direction.nextLeft() prevChoice = !prevChoice choice } RANDOM -> directionFrom(random.nextInt(4) + 1) } } } data class Grid( val cells: MutableMap<Coord, Cell> = mutableMapOf(), var maxX: Int = 0, var minX: Int = 0, var maxY: Int = 0, var minY: Int = 0 ) { fun determineSize() { maxX = (cells.keys.maxBy { it.x }?.x ?: 0) minX = (cells.keys.minBy { it.x }?.x ?: 0) maxY = (cells.keys.maxBy { it.y }?.y ?: 0) minY = (cells.keys.minBy { it.y }?.y ?: 0) } fun printCell(cell: Cell, robot: Robot) { when { cell.status == UNKNOWN -> print(" ") cell.pos == robot.location && cell.status == WALL -> print("%") cell.status == WALL -> print("#") cell.pos == robot.location && cell.status == MOVED -> print(direction(robot.direction)) cell.status == MOVED -> print(".") cell.status == OXYGEN -> print("O") } } fun printGrid(robot: Robot) { determineSize() print(Ansi.ansi().eraseScreen().cursor(1, 1)) for (y in minY..maxY) { for (x in minX..maxX) { val location = Coord(x, y) val cell = cells[location] ?: Cell(location, UNKNOWN) printCell(cell, robot) } println() } } fun setStatus(pos: Coord, status: RobotStatus): Cell { val cell = cells[pos] ?: Cell(pos, status) if (status != UNKNOWN) { cell.visits += 1 } cells[pos] = cell return cell } fun findPosition(robot: Robot, direction: DIRECTION): Coord { return robot.location.move(direction) } fun goStraightOrFindOpen(robot: Robot): DIRECTION { val location = findPosition(robot, robot.direction) val cell = cells[location] ?: Cell(location, UNKNOWN) if (cell.status == UNKNOWN) { return robot.direction } return findOpenSpace(robot) } fun findOpenSpace(robot: Robot): DIRECTION { var test = robot.direction val tried = mutableSetOf<Cell>() val valid = mutableSetOf<Pair<DIRECTION, Cell>>() do { val location = findPosition(robot, test) val cell = cells[location] ?: Cell(location, UNKNOWN) tried.add(cell) if (cell.status == MOVED || cell.status == UNKNOWN) { valid.add(Pair(test, cell)) } test = test.nextRight() } while (test != robot.direction) if (valid.isNotEmpty()) { return findMinVisit(valid) } error("Cannot move from ${robot.location} tried:$tried") } fun findMinVisit(valid: Collection<Pair<DIRECTION, Cell>>): DIRECTION { val minVisit = valid.minBy { it.second.visits }!! val minVisits = valid.filter { it.second.visits == minVisit.second.visits } if (minVisits.size > 1) { return minVisits[random.nextInt(minVisits.size)].first } return minVisit.first } fun modified(maxX: Int, minX: Int, maxY: Int, minY: Int): Boolean { return this.maxX != maxX || this.minX != minX || this.maxY != maxY || this.minY != minY } fun isComplete(): Boolean { determineSize() val width = maxX - minX val height = maxY - minY val hasOxygen = cells.values.any { it.status == OXYGEN } return width * height == cells.size && hasOxygen } } fun determinResponse(grid: Grid, robot: Robot, status: RobotStatus, strategy: STRATEGY): Int { grid.setStatus(grid.findPosition(robot, robot.direction), status) if (status != WALL) { robot.move() } return when (status) { OXYGEN, MOVED -> grid.goStraightOrFindOpen(robot).value WALL -> grid.findOpenSpace(robot).value else -> error("Unexpected response:$status") } } fun printGrid(grid: Grid, robot: Robot, cell: Cell?, printAll: Boolean) { val maxX = (grid.cells.keys.maxBy { it.x }?.x ?: 0) val minX = (grid.cells.keys.minBy { it.x }?.x ?: 0) val maxY = (grid.cells.keys.maxBy { it.y }?.y ?: 0) val minY = (grid.cells.keys.minBy { it.y }?.y ?: 0) if (printAll || grid.modified(maxX, minX, maxY, minY)) { grid.printGrid(robot) } else { if (cell != null) { print(Ansi.ansi().cursor(cell.pos.y - minY + 1, cell.pos.x - minX + 1)) grid.printCell(cell, robot) } } val totalVisits = grid.cells.values.sumBy { it.visits } print(Ansi.ansi().cursor(maxY - minY + 2, 1).render("Total Visits:$totalVisits, Cells = ${grid.cells.size}")) } data class OperationRecord(val start: Coord, val direction: DIRECTION, val response: RobotStatus, val end: Coord) fun discoverGrid( printOutput: Boolean, code: List<Long>, initial: DIRECTION, strategy: STRATEGY, grid: Grid ): List<OperationRecord> { print(Ansi.ansi().eraseScreen()) val robot = Robot(Coord(0, 0), initial) val program = Program(code).createProgram() val record = mutableListOf<OperationRecord>() do { if (printOutput) { printGrid(grid, robot, grid.cells[robot.prevLocation], false) printGrid(grid, robot, grid.cells[robot.location], false) } val start = robot.location val initialDirection = robot.direction val output = program.executeUntilOutput(listOf(initialDirection.value.toLong())) val response = robotStatusFrom(output.first().toInt()) val direction = determinResponse(grid, robot, response, strategy) robot.direction = directionFrom(direction) record.add(OperationRecord(start, initialDirection, response, robot.location)) if (printOutput) { printGrid(grid, robot, grid.cells[robot.prevLocation.move(robot.prev)], false) } } while (!grid.isComplete()) printGrid(grid, robot, grid.cells[robot.location], true) return record } fun main(args: Array<String>) { var printOutput = false AnsiConsole.systemInstall() if (args.contains("-p")) { printOutput = true } val code = readProgram(File("input.txt")) var grid = Grid() val edges = mutableListOf<Edge<Coord>>() val result = discoverGrid(printOutput, code, NORTH, LEFT, grid) result.forEach { record -> edges.add(Edge(record.start, record.end, 1)) } var oxygenLocation = result.find { it.response == OXYGEN }?.end requireNotNull(oxygenLocation) { "Could not find Oxygen" } val spaces = result.filter { it.response == MOVED || it.response == OXYGEN }.map { it.end } println("\nRecords=${result.size}") println("Edges=${edges.size}") val robotLocation = result.first().start val graph = Graph(edges, true) val path = graph.findPath(robotLocation, oxygenLocation) println("From ${path.first()} -> ${path.last()}") val moves = path.last().second println("Moves=$moves") require(moves == 250) val graph2 = Graph(edges, true) graph2.dijkstra(oxygenLocation) val distances = spaces.mapNotNull { val path = graph2.findPath(it) path.lastOrNull() } val furthest = distances.maxBy { it.second } println("Furthest=$furthest") val minutes = furthest!!.second println("Minutes = $minutes") require(minutes == 332) AnsiConsole.systemUninstall() }
0
HTML
0
0
afcaede5326b69fedb7588b1fe771fd0c0b3f6e6
11,001
docToolchain-aoc-2019
MIT License
src/Day04.kt
acrab
573,191,416
false
{"Kotlin": 52968}
import com.google.common.truth.Truth.assertThat fun main() { fun List<String>.parseList(): List<List<List<Int>>> = map { it.split(",").map { sublist -> sublist.split("-").map(String::toInt) } } fun part1(input: List<String>): Int = input.parseList() .count { (it[0][0] <= it[1][0] && it[0][1] >= it[1][1]) || (it[1][0] <= it[0][0] && it[1][1] >= it[0][1]) } fun part2(input: List<String>): Int = input.parseList() .count { it[0][0] in it[1][0]..it[1][1] || it[0][1] in it[1][0]..it[1][1] || it[1][0] in it[0][0]..it[0][1] || it[1][1] in it[0][0]..it[0][1] } val testInput = readInput("Day04_test") assertThat(part1(testInput)).isEqualTo(2) val input = readInput("Day04") println(part1(input)) assertThat(part2(testInput)).isEqualTo(4) println(part2(input)) }
0
Kotlin
0
0
0be1409ceea72963f596e702327c5a875aca305c
902
aoc-2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/RemoveKDigits.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode import java.util.* /** * 402. 移掉K位数字 * * 给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。 * * 注意: * * num 的长度小于 10002 且 ≥ k。 * num 不会包含任何前导零。 * 示例 1 : * * 输入: num = "1432219", k = 3 * 输出: "1219" * 解释: 移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219。 * 示例 2 : * * 输入: num = "10200", k = 1 * 输出: "200" * 解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。 * 示例 3 : * * 输入: num = "10", k = 2 * 输出: "0" * 解释: 从原数字移除所有的数字,剩余为空就是0。 */ class RemoveKDigits { companion object { @JvmStatic fun main(args: Array<String>) { // 1219 println(RemoveKDigits().solution("1432219", 3)) // 200 println(RemoveKDigits().solution("10200", 1)) // 0 println(RemoveKDigits().solution("10", 2)) // 0 println(RemoveKDigits().solution("1234567890", 9)) } } /** * O(n) * 贪心算法 * 从左往右比较,当前的值比后面的大即高位比低位大,就移除当前值 */ fun solution(num: String, k: Int): String { var times = k val stack = LinkedList<Char>() num.forEach { // 高位比低位大 while (stack.isNotEmpty() && times > 0 && stack.peekLast() > it) { stack.removeLast() times-- } stack.add(it) } // 还有次数剩余,直接从后面低位移除 repeat(times) { if (stack.isNotEmpty()) { stack.removeLast() } else { return@repeat } } // 消除高位0 while (stack.isNotEmpty() && stack.peek() == '0') { stack.poll() } val result = StringBuilder().apply { stack.forEach { append(it) } } return if (result.isEmpty()) "0" else result.toString() } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,241
daily_algorithm
Apache License 2.0
src/main/kotlin/chjaeggi/Day9.kt
chjaeggi
296,447,759
false
null
package chjaeggi class Day9(private val input: List<Long>, private val preAmble: Int) { fun solvePart1(): Long { input.forEachIndexed { index, _ -> if (index < (preAmble)) { return@forEachIndexed } else if (index + 1 >= input.size) { return@forEachIndexed } else { val expected = input[index + 1] val subList = input.subList(index - (preAmble - 1), index + 1) if (!subList.hasSumInTwo(expected)) { return expected } } } return -1 } fun solvePart2(): Long { return input.hasSumInRange(solvePart1()) } } fun List<Long>.hasSumInTwo(expectedSum: Long): Boolean { for (first in this.indices) { for (second in this.indices) { if (second == first) { continue } if ((this[first] + this[second]) == expectedSum) { return true } } } return false } fun List<Long>.hasSumInRange(expectedSum: Long): Long { var first = 0 var second = 0 var result = 0L fun reset() { first++ second = first result = 0L } while (first < this.size) { if (second >= this.size) { reset() continue } result += this[second] if (result == expectedSum) { return (this.subList(first, second).minOrNull() ?: -1) + (this.subList(first, second).maxOrNull() ?: -1) } if (result > expectedSum) { reset() continue } second++ } return -1 }
0
Kotlin
0
1
3ab7867a5c3b06b8f5f90380f0ada1a73f5ffa71
1,700
aoc2020
Apache License 2.0
src/main/kotlin/graph/variation/Island.kt
yx-z
106,589,674
false
null
package graph.variation import java.util.* fun main(args: Array<String>) { // given an m * n array representing a map // mark 1 as island, 0 as ocean // and given that islands are four-directionally connected val testMap = arrayOf( intArrayOf(1, 1, 0, 0, 1), intArrayOf(1, 0, 0, 1, 0), intArrayOf(0, 1, 1, 1, 0), intArrayOf(1, 0, 0, 0, 1) ) println(testMap.countIslands()) println(testMap.largestIslandArea()) } // find the number of the islands // e.x. should return 5 for `testMap` fun Array<IntArray>.countIslands(): Int { val m = this.size val n = this[0].size var count = 0 val hasVisited = Array(m, { Array(n) { false } }) for (row in 0 until m) { for (col in 0 until n) { // new island! if (this[row][col] == 1 && !hasVisited[row][col]) { count++ // this.dfs(row, col, hasVisited) this.bfs(row, col, hasVisited) } } } return count } // find the area of the largest island // ex. should return 4 for `testMap` fun Array<IntArray>.largestIslandArea(): Int { val m = this.size val n = this[0].size var maxArea = 0 val hasVisited = Array(m, { Array(n) { false } }) for (row in 0 until m) { for (col in 0 until n) { // new island! if (this[row][col] == 1 && !hasVisited[row][col]) { maxArea = maxOf(this.dfsArea(row, col, hasVisited), maxArea) } } } return maxArea } fun Array<IntArray>.dfs(row: Int, col: Int, hasVisited: Array<Array<Boolean>>) { if (this[row][col] == 0 || hasVisited[row][col]) { return } hasVisited[row][col] = true // up if (row - 1 >= 0) { this.dfs(row - 1, col, hasVisited) } // down if (row + 1 < this.size) { this.dfs(row + 1, col, hasVisited) } // left if (col - 1 >= 0) { this.dfs(row, col - 1, hasVisited) } // right if (col + 1 < this[row].size) { this.dfs(row, col + 1, hasVisited) } } fun Array<IntArray>.bfs(row: Int, col: Int, hasVisited: Array<Array<Boolean>>) { if (this[row][col] == 0 || hasVisited[row][col]) { return } val q: Queue<Pair<Int, Int>> = LinkedList() q.add(row to col) while (q.isNotEmpty()) { val (currRow, currCol) = q.remove() if (this[currRow][currCol] == 1 && !hasVisited[currRow][currCol]) { hasVisited[currRow][currCol] = true // up if (currRow - 1 >= 0) { q.add((currRow - 1) to currCol) } // down if (currRow + 1 < this.size) { q.add((currRow + 1) to currCol) } // left if (currCol - 1 >= 0) { q.add(currRow to (currCol - 1)) } // right if (currCol + 1 < this[currRow].size) { q.add(currRow to (currCol + 1)) } } } } fun Array<IntArray>.dfsArea(row: Int, col: Int, hasVisited: Array<Array<Boolean>>, area: Int = 0): Int { if (this[row][col] == 0 || hasVisited[row][col]) { return area } hasVisited[row][col] = true var sumArea = area + 1 // up if (row - 1 >= 0) { sumArea = this.dfsArea(row - 1, col, hasVisited, area = sumArea) } // down if (row + 1 < this.size) { sumArea = this.dfsArea(row + 1, col, hasVisited, area = sumArea) } // left if (col - 1 >= 0) { sumArea = this.dfsArea(row, col - 1, hasVisited, area = sumArea) } // right if (col + 1 < this[row].size) { sumArea = this.dfsArea(row, col + 1, hasVisited, area = sumArea) } return sumArea }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
3,225
AlgoKt
MIT License
app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateRanker.kt
nekomangaorg
182,704,531
false
{"Kotlin": 3454839}
package eu.kanade.tachiyomi.data.library import eu.kanade.tachiyomi.data.database.models.Manga import kotlin.math.abs /** * This class will provide various functions to Rank mangaList to efficiently schedule mangaList to * update. */ object LibraryUpdateRanker { val rankingScheme = listOf( (this::lexicographicRanking)(), (this::latestFirstRanking)(), (this::nextFirstRanking)(), ) /** * Provides a total ordering over all the MangaList. * * Orders the manga based on the distance between the next expected update and now. The * comparator is reversed, placing the smallest (and thus closest to updating now) first. */ fun nextFirstRanking(): Comparator<Manga> { val time = System.currentTimeMillis() return Comparator { mangaFirst: Manga, mangaSecond: Manga, -> compareValues( abs(mangaSecond.next_update - time), abs(mangaFirst.next_update - time) ) } .reversed() } /** * Provides a total ordering over all the MangaList. * * Assumption: An active [Manga] mActive is expected to have been last updated after an inactive * [Manga] mInactive. * * Using this insight, function returns a Comparator for which mActive appears before mInactive. * * @return a Comparator that ranks manga based on relevance. */ fun latestFirstRanking(): Comparator<Manga> { return Comparator { mangaFirst: Manga, mangaSecond: Manga, -> compareValues(mangaSecond.last_update, mangaFirst.last_update) } } /** * Provides a total ordering over all the MangaList. * * Order the manga lexicographically. * * @return a Comparator that ranks manga lexicographically based on the title. */ fun lexicographicRanking(): Comparator<Manga> { return Comparator { mangaFirst: Manga, mangaSecond: Manga, -> compareValues(mangaFirst.title, mangaSecond.title) } } }
85
Kotlin
111
1,985
4dc7daf0334499ca72c7f5cbc7833f38a9dfa2c3
2,136
Neko
Apache License 2.0
array/src/commonMain/kotlin/array/kotlin-complex.kt
lokedhs
236,192,362
false
null
package array.complex import kotlin.math.* data class Complex(val real: Double, val imaginary: Double) { constructor(value: Double) : this(value, 0.0) fun reciprocal(): Complex { val scale = (real * real) + (imaginary * imaginary) return Complex(real / scale, -imaginary / scale) } fun abs(): Double = hypot(real, imaginary) operator fun unaryMinus(): Complex = Complex(-real, -imaginary) operator fun plus(other: Double): Complex = Complex(real + other, imaginary) operator fun minus(other: Double): Complex = Complex(real - other, imaginary) operator fun times(other: Double): Complex = Complex(real * other, imaginary * other) operator fun div(other: Double): Complex = Complex(real / other, imaginary / other) operator fun plus(other: Complex): Complex = Complex(real + other.real, imaginary + other.imaginary) operator fun minus(other: Complex): Complex = Complex(real - other.real, imaginary - other.imaginary) operator fun times(other: Complex): Complex = Complex( (real * other.real) - (imaginary * other.imaginary), (real * other.imaginary) + (imaginary * other.real)) operator fun div(other: Complex): Complex = this * other.reciprocal() fun pow(complex: Complex): Complex { val arg = atan2(this.imaginary, this.real) val resultAbsolute = exp(ln(this.abs()) * complex.real - (arg * complex.imaginary)) val resultArg = ln(this.abs()) * complex.imaginary + arg * complex.real return fromPolarCoord(resultAbsolute, resultArg) } fun signum(): Complex { return if (real == 0.0 && imaginary == 0.0) { ZERO } else { this / this.abs() } } fun ln(): Complex = Complex(ln(hypot(real, imaginary)), atan2(imaginary, real)) fun log(base: Complex): Complex = ln() / base.ln() fun log(base: Double): Complex = log(base.toComplex()) fun nearestGaussian(): Complex { return Complex(round(real), round(imaginary)) } override fun equals(other: Any?) = other != null && other is Complex && real == other.real && imaginary == other.imaginary override fun hashCode() = real.hashCode() xor imaginary.hashCode() companion object { fun fromPolarCoord(absolute: Double, arg: Double): Complex { return Complex(cos(arg) * absolute, sin(arg) * absolute) } val ZERO = Complex(0.0, 0.0) val I = Complex(0.0, 1.0) } } operator fun Double.plus(complex: Complex) = this.toComplex() + complex operator fun Double.times(complex: Complex) = this.toComplex() * complex operator fun Double.minus(complex: Complex) = this.toComplex() - complex operator fun Double.div(complex: Complex) = this.toComplex() / complex fun Double.toComplex() = Complex(this, 0.0) fun Double.pow(complex: Complex) = this.toComplex().pow(complex) fun Double.log(base: Complex) = this.toComplex().log(base) fun complexSin(v: Complex): Complex { return (E.pow(v * Complex.I) - E.pow(-v * Complex.I)) / Complex(0.0, 2.0) } fun complexCos(v: Complex): Complex { return (E.pow(v * Complex.I) + E.pow(-v * Complex.I)) / 2.0 }
0
Kotlin
2
42
02445a1e8763d0d95860672071d6762f52a8004b
3,196
array
MIT License
Algorithms/432 - All O one Data Structure/src/Solution.kt
mobeigi
202,966,767
false
null
/** * Solution * * We use two maps to allow us to lookup keys by string in O(1) and lookup by frequency in O(1). * We also maintain a key count for the minimum and maximum at all times. * We maintain the maximum and minimum as we increment and decrement. * * The getMaxKey and getMinKey are guaranteed to always be in O(1). * inc are guaranteed to always be in O(1). * However, dec will usually be in O(1) but will be in O(N) in the case where the minimum key is dec to 0 and * removed entirely. This will trigger an O(N) search for the next minimum key. */ class AllOne { private val freq = HashMap<String, Long>() private val countMap = HashMap<Long, MutableSet<String>>() data class KeyCount(var key: String, var count: Long) private fun KeyCount.isEmpty() = key == "" private val maxKC = KeyCount("", 0L) private val minKC = KeyCount("", Long.MAX_VALUE) fun inc(key: String) { // Update maps to be consistent val prevCount = freq.getOrDefault(key, 0) val newCount = prevCount + 1 freq[key] = newCount removePreviousCountMap(key, prevCount) addNewCountMap(key, newCount) // If max or min is empty, set them to this key if (maxKC.isEmpty()) { maxKC.key = key maxKC.count = newCount } if (minKC.isEmpty()) { minKC.key = key minKC.count = newCount } // Inc the maxKey keeps it as max and updates its count if (key == maxKC.key) { maxKC.count = newCount } // Check for a new maxKey if (key != maxKC.key && newCount > maxKC.count) { maxKC.key = key maxKC.count = newCount } // Check to see if we maintain same minKey if (key == minKC.key) { // Check if another min key exists at prevCount if (countMap.containsKey(prevCount) && countMap[prevCount]?.isNotEmpty()!!) { minKC.key = countMap[prevCount]?.first().toString() } else { minKC.key = key minKC.count = newCount } } // Check for a new minKey if (key != minKC.key && newCount < minKC.count) { minKC.key = key minKC.count = newCount } } fun dec(key: String) { val prevCount = freq[key]!! val newCount = prevCount - 1 removePreviousCountMap(key, prevCount) if (newCount == 0L) { freq.remove(key) } else { freq[key] = newCount addNewCountMap(key, newCount) } // Check for new maxKey if (key == maxKC.key) { // Check if other max exists at prevCount if (countMap.containsKey(prevCount) && countMap[prevCount]?.isNotEmpty()!!) { maxKC.key = countMap[prevCount]?.first().toString() } else { if (newCount == 0L) { // No other keys exist so no max or min maxKC.key = "" maxKC.count = 0L minKC.key = "" minKC.count = Long.MAX_VALUE return } else { maxKC.key = key maxKC.count = newCount } } } // Check for new minKey if (key == minKC.key) { if (newCount == 0L) { // We've lost the min key and need to search for next one in O(N) val nextMin = countMap.minBy { it.key } minKC.key = nextMin?.value?.first() ?: "" minKC.count = nextMin?.key ?: Long.MAX_VALUE } else { // Otherwise count just goes down minKC.count = newCount } } } private fun removePreviousCountMap(key: String, prevCount: Long) { countMap[prevCount]?.remove(key) if (countMap[prevCount].isNullOrEmpty()) { countMap.remove(prevCount) } } private fun addNewCountMap(key: String, newCount: Long) { val newSet = countMap.getOrDefault(newCount, mutableSetOf()) newSet.add(key) countMap[newCount] = newSet } fun getMaxKey(): String { return maxKC.key } fun getMinKey(): String { return minKC.key } }
0
Kotlin
0
0
e5e29d992b52e4e20ce14a3574d8c981628f38dc
4,556
LeetCode-Solutions
Academic Free License v1.1
bdd/src/commonTest/kotlin/it/unibo/tuprolog/bdd/TestBinaryDecisionDiagram.kt
tuProlog
230,784,338
false
{"Kotlin": 3879230, "Java": 18690, "ANTLR": 10366, "CSS": 1535, "JavaScript": 894, "Prolog": 818}
package it.unibo.tuprolog.bdd import kotlin.test.Test import kotlin.test.assertTrue class TestBinaryDecisionDiagram { private val doubleEpsilon = 0.0001 private class ComparablePair(val id: Long, val first: String, val second: Double) : Comparable<ComparablePair> { override fun compareTo(other: ComparablePair): Int { var res = this.id.compareTo(other.id) if (res == 0) { res = this.first.compareTo(other.first) } return res } override fun equals(other: Any?): Boolean { return if (other is ComparablePair) this.compareTo(other) == 0 else false } override fun toString(): String { return "[$id] $second::$first" } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + first.hashCode() result = 31 * result + second.hashCode() return result } } /** Internal function to calculate a probability over a probabilistic boolean formula * (a.k.a. a boolean formula in which each variable represents a probability value) through * Weighted Model Counting. This simulates our specific use case for BDDs, which * is what we are really interested in. On the other hand, this also effectively verifies * the correctness of the data structure itself, as the probability computation would * give bad results on badly constructed BDDs. */ private fun BinaryDecisionDiagram<ComparablePair>.probability(): Double { return this.expansion(0.0, 1.0) { node, low, high -> node.second * high + (1.0 - node.second) * low } } /** Test adapted from: https://dtai.cs.kuleuven.be/problog/tutorial/basic/01_coins.html#noisy-or-multiple-rules-for-the-same-head * Probabilities to base-level "someHeads" predicates have been added to simulate "Probabilistic Clauses". */ @Test fun testApplyWithProbSomeHeads() { val solution = ( bddOf(ComparablePair(0, "someHeads", 0.2)) and bddOf(ComparablePair(1, "heads1", 0.5)) ) or ( bddOf(ComparablePair(2, "someHeads", 0.5)) and bddOf(ComparablePair(3, "heads2", 0.6)) ) val prob = solution.probability() assertTrue(prob >= 0.37 - doubleEpsilon) assertTrue(prob <= 0.37 + doubleEpsilon) } /** Test adapted from: https://dtai.cs.kuleuven.be/problog/tutorial/basic/02_bayes.html#probabilistic-clauses * In this test evidence predicates are not considered. */ @Test fun testApplyWithProbAlarmNegationsNoEvidence() { val burglary = bddOf(ComparablePair(0, "burglary", 0.7)) val earthquake = bddOf(ComparablePair(1, "earthquake", 0.2)) val solution = ( bddOf(ComparablePair(2, "alarm", 0.9)) and burglary and earthquake ) or ( bddOf(ComparablePair(3, "alarm", 0.8)) and burglary and earthquake.not() ) or ( bddOf(ComparablePair(4, "alarm", 0.1)) and burglary.not() and earthquake ) val prob = solution.probability() assertTrue(prob >= 0.58 - doubleEpsilon) assertTrue(prob <= 0.58 + doubleEpsilon) } }
71
Kotlin
13
79
804e57913f072066a4e66455ccd91d13a5d9299a
3,424
2p-kt
Apache License 2.0
Array/huangxinyu/kotlin/src/StrStr.kt
JessonYue
268,215,243
false
null
package com.ryujin.algorithm /** * 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1 * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/implement-strstr * * 理解视频:https://www.bilibili.com/video/BV1jb411V78H */ class StrStr { companion object { /** * haystack为空字符 */ private fun test1() { assert(strStr("", "a") == -1) } /** * needle为空字符 */ private fun test2() { assert(strStr("a", "") == 0) } /** * needle比haystack长 */ private fun test3() { assert(strStr("a", "ab") == -1) } /** * needle不在haystack中 */ private fun test4() { assert(strStr("abcd", "abe") == -1) } /** * needle在haystack中 */ private fun test5() { assert(strStr("abcd", "bc") == 1) } fun test() { test1() test2() test3() test4() test5() } private fun getNext(str: String): IntArray { val next = IntArray(str.length) next[0] = 0 var i = 1 var j = 0 while (i < str.length) { if (str[i] == str[j]) { j++ next[i] = j i++ } else { if (j == 0) { next[i] = 0; i++ } else { j = next[j - 1]; } } } return next } private fun strStr(haystack: String, needle: String): Int { if (needle.length > haystack.length) return -1; if ("" == needle) return 0; var i = 0 var j = 0 val next = getNext(needle) while (i < haystack.length) { if (j == needle.length) { return i - needle.length } if (haystack[i] == needle[j]) { i++ j++ } else { if (j != 0) { j = next[j - 1] } else { i++; } } } return -1 } } }
0
C
19
39
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
2,610
LeetCodeLearning
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2023/Day05.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import kotlin.math.min import kotlin.system.measureTimeMillis import kotlin.test.Ignore import kotlin.test.assertEquals class Day05 : AbstractDay() { @Test fun part1Test() { assertEquals(35, compute1(testInput)) } @Test fun part1Puzzle() { assertEquals(261668924, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(46, compute2(testInput)) } @Test @Disabled("brute-forced") fun part2Puzzle() { assertEquals(24261545, compute2(puzzleInput)) } private fun compute1(input: List<String>): Long { val (seeds, maps) = parseInput(input) return seeds.minOf { minLocationValue(it, it, maps) } } private fun minLocationValue( seedStart: Long, seedEnd: Long, maps: Map<String, List<Pair<LongRange, Pair<Long, String>>>>, ): Long { println("Calculating minLocation for: ${seedEnd - seedStart + 1} seeds") var minLocationValue = Long.MAX_VALUE val millis = measureTimeMillis { for (seed in seedStart..seedEnd) { var nextElement = Element("seed", seed) while (nextElement.type != "location") { val map = maps.getValue(nextElement.type) var mapped: Element? = null for ((range, mapping) in map) { val (delta, dstType) = mapping if (range.contains(nextElement.value)) { mapped = Element(dstType, nextElement.value + delta) break } } nextElement = mapped ?: nextElement.shift() } minLocationValue = min(minLocationValue, nextElement.value) } } println("Calculated in ${millis}ms") return minLocationValue } private fun compute2(input: List<String>): Long { val (seedRangesRaw, maps) = parseInput(input) return seedRangesRaw .chunked(2) { (from, range) -> from to range } .minOf { (from, range) -> minLocationValue(from, from + range, maps) } } private fun parseInput(input: List<String>): Pair<List<Long>, Map<String, List<Pair<LongRange, Pair<Long, String>>>>> { val seeds = input.first() .split(" ") .drop(1) .map { it.toLong() } mutableMapOf<Pair<String, String>, List<LongRange>>() val map = parseMaps(input.drop(2)) return seeds to map } private fun parseMaps(input: List<String>): Map<String, List<Pair<LongRange, Pair<Long, String>>>> { if (input.size <= 1) return emptyMap() val mapInput = input .takeWhile { it.isNotBlank() } val restInput = input.drop(mapInput.size + 1) val parsedMap = parseMap(mapInput) return parsedMap + parseMaps(restInput) } private fun parseMap(input: List<String>): Map<String, List<Pair<LongRange, Pair<Long, String>>>> { val (srcType, _, dstType) = input.first().split(" ").first().split("-") val mappings = input .drop(1) .takeWhile { it.isNotBlank() } .map { line -> val (dstStart, srcStart, range) = line.split(" ").map { it.toLong() } val delta = dstStart - srcStart srcStart..<(srcStart + range) to (delta to dstType) } return mapOf(srcType to mappings) } data class Element( val type: String, val value: Long, ) { fun shift(): Element { return Element(typeMap.getValue(type), value) } companion object { private val typeMap = mapOf( "seed" to "soil", "soil" to "fertilizer", "fertilizer" to "water", "water" to "light", "light" to "temperature", "temperature" to "humidity", "humidity" to "location", ) } } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
4,274
aoc
Apache License 2.0
project/src/problems/CaterPillarMethod.kt
informramiz
173,284,942
false
null
package problems /** * https://codility.com/media/train/13-CaterpillarMethod.pdf * * The Caterpillar method is a likeable name for a popular means of solving algorithmic tasks. * The idea is to check elements in a way that’s reminiscent of movements of a caterpillar. * The caterpillar crawls through the array. We remember the front and back positions of the caterpillar, * and at every step either of them is moved forward. */ object CaterPillarMethod { /** * Let’s check whether a sequence a0, a1, . . . , an-1 (1 < ai <= 10^9) * contains a contiguous sub-sequence whose sum of elements equals s. */ fun isThereASequenceOfSum(A: IntArray, givenSum: Int): Boolean { var runningSum = 0 var front = 0 //for each new back position for (back in A) { //keep moving the front until the runningSum <= givenSum //1. If we find a runningSum == givenSum then return true //2. If we find a runningSum > givenSum then stop the // front there, move back by 1 step and then move front while (front < A.size && (runningSum + A[front]) <= givenSum) { runningSum += A[front] front++ } if (runningSum == givenSum) { return true } //we did not find a sum with given back, so remove current back from runningSum and move it by 1 step runningSum -= back } //we did not find a sub-sequence whose sum = givenSum return false } /** * https://codility.com/media/train/13-CaterpillarMethod.pdf * -------Problem---------- * You are given n sticks (of lengths 1 <= a0 <= a1 ̨ ... <= an-1 <= 10^9). The goal is to count the number of triangles * that can be constructed using these sticks. More precisely, we have to count the number of triplets at indices x<y<z, * such that ax+ay > az * * For every pair x,y we can find the largest stick z that can be used to construct the triangle. * Every stick k, less than that largest stick z (such that y < k < z), can also be used to build triangle, * because the condition ax + ay > ak will still be true. We can add up all these triangles at once to calculate * all triangles for given (x, y) using formula (largestZ - y) because each z after y can make up a triangle with * given (x, y). We repeat the same process for remaining (x, y) */ fun countTrianglesOfSticks(A: IntArray): Int { var trianglesCount = 0 //for every x for (x in 0 until A.size) { var z = x + 2 //x + 2 because x+1 will be y to achieve condition (x < y < z) //for every y in range [x+1, n] for (y in x+1 until A.size) { //find the largest z(or you can say all the possible z) that can make triangle with //given (x, y) (i.e, which satisfy condition Ax + Ay > Az while (z < A.size && (A[x] + A[y]) < A[z]) { //current z can make a triangle with given (x, y) so move to next to see if that can z++ //call this currentZ } //all z values in range [x+2, currentZ] can make triangles //NOTE: -1 in (z - y - 1) because the last z is invalid as the while loop broke due to that z //NOTE: we use this calculation for following y because this current z value can make triangles //with all the Ys < currentZ because of given assumption (1 <= a0 <= a1 ̨ ... <= an-1 <= 10^9) so // if Ax + Ay > Az then it will definitely be true for all Ys < currentZ trianglesCount += z - y - 1 } } return trianglesCount } /** * https://app.codility.com/programmers/lessons/15-caterpillar_method/count_distinct_slices/ * CountDistinctSlices * Count the number of distinct slices (containing only unique numbers). * Programming language: * An integer M and a non-empty array A consisting of N non-negative integers are given. All integers in array A are less than or equal to M. * A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The slice consists of the elements A[P], A[P + 1], ..., A[Q]. A distinct slice is a slice consisting of only unique numbers. That is, no individual number occurs more than once in the slice. * For example, consider integer M = 6 and array A such that: * A[0] = 3 * A[1] = 4 * A[2] = 5 * A[3] = 5 * A[4] = 2 * There are exactly nine distinct slices: (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2), (3, 3), (3, 4) and (4, 4). * The goal is to calculate the number of distinct slices. * Write a function: * class Solution { public int solution(int M, int[] A); } * that, given an integer M and a non-empty array A consisting of N integers, returns the number of distinct slices. * If the number of distinct slices is greater than 1,000,000,000, the function should return 1,000,000,000. * For example, given integer M = 6 and array A such that: * A[0] = 3 * A[1] = 4 * A[2] = 5 * A[3] = 5 * A[4] = 2 * the function should return 9, as explained above. * Write an efficient algorithm for the following assumptions: * N is an integer within the range [1..100,000]; * M is an integer within the range [0..100,000]; * each element of array A is an integer within the range [0..M]. */ fun countDistinctSlices(A: IntArray, M: Int): Int { val maxDistinctSlices = 1_000_000_000 //array to keep check of encountered numbers. We will use it to check if we already encountered //a number previously in the given slice or not val isDiscovered = Array(M + 1) { false } var distinctSlicesCount = A.size //each number in A is also a distinct slice of size = 1 as per 0 ≤ P ≤ Q < N var front = 0 for (back in 0 until A.size) { //we keep going for all numbers that are not discovered in this slice (back, front) while (front < A.size && !isDiscovered[A[front]]) { //count this front as we have explored it isDiscovered[A[front]] = true front++ } //all numbers till front-1 can make a slice with given back so //NOTE: -1 because last front is what broke the loop so is not valid for given slice distinctSlicesCount += front - back - 1 //we only need to count slices till MAX_DISTINCT_SLICES if (distinctSlicesCount >= maxDistinctSlices) { return maxDistinctSlices } //as now we are no longer going to consider the current back so we mark it as not discovered isDiscovered[A[back]] = false } return distinctSlicesCount } /** * https://app.codility.com/programmers/lessons/15-caterpillar_method/count_triangles/ * -----------------CountTriangles------------------ * Count the number of triangles that can be built from a given set of edges. * An array A consisting of N integers is given. A triplet (P, Q, R) is triangular if it is possible to build a * triangle with sides of lengths A[P], A[Q] and A[R]. In other words, triplet (P, Q, R) is triangular * if 0 ≤ P < Q < R < N and: * A[P] + A[Q] > A[R], * A[Q] + A[R] > A[P], * A[R] + A[P] > A[Q]. * For example, consider array A such that: * A[0] = 10 A[1] = 2 A[2] = 5 * A[3] = 1 A[4] = 8 A[5] = 12 * There are four triangular triplets that can be constructed from elements of this array, * namely (0, 2, 4), (0, 2, 5), (0, 4, 5), and (2, 4, 5). * Write a function: * class Solution { public int solution(int[] A); } * that, given an array A consisting of N integers, returns the number of triangular triplets in this array. * For example, given array A such that: * A[0] = 10 A[1] = 2 A[2] = 5 * A[3] = 1 A[4] = 8 A[5] = 12 * the function should return 4, as explained above. * Write an efficient algorithm for the following assumptions: * N is an integer within the range [0..1,000]; * each element of array A is an integer within the range [1..1,000,000,000]. */ fun countTrianglesOfEdges(A: IntArray): Int { if (A.size < 3) return 0 //NOTE: I am going to solve it same way as countTrianglesOfSticks() above. //first sort array as in countTrianglesOfSticks() problem, the array was sorted. A.sort() //now that array is sorted we can use the same technique we used in method countTrianglesOfSticks() //except that the condition for triangle is different this time. All other logic will be same var trianglesCount = 0 for (p in 0 until A.size) { //because q will take the value (p+1) and p < q < r so r = q + 1 = p + 2 var r = p + 2 for (q in p+1 until A.size) { while (r < A.size && isTriangularTriplet(A[p], A[q], A[r])) { r++ } trianglesCount += r - q - 1 } } return trianglesCount } private fun isTriangularTriplet(p: Int, q: Int, r: Int): Boolean { val condition1 = p.toLong() + q > r val condition2 = q.toLong() + r > p val condition3 = r.toLong() + p > q return condition1 && condition2 && condition3 } /** * https://app.codility.com/programmers/lessons/15-caterpillar_method/abs_distinct/ * * AbsDistinct * Compute number of distinct absolute values of sorted array elements. * Programming language: Spoken language: * A non-empty array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array. * For example, consider array A such that: * A[0] = -5 * A[1] = -3 * A[2] = -1 * A[3] = 0 * A[4] = 3 * A[5] = 6 * The absolute distinct count of this array is 5, because there are 5 distinct absolute values among the elements of this array, namely 0, 1, 3, 5 and 6. * Write a function: * class Solution { public int solution(int[] A); } * that, given a non-empty array A consisting of N numbers, returns absolute distinct count of array A. * For example, given array A such that: * A[0] = -5 * A[1] = -3 * A[2] = -1 * A[3] = 0 * A[4] = 3 * A[5] = 6 * the function should return 5, as explained above. * Write an efficient algorithm for the following assumptions: * N is an integer within the range [1..100,000]; * each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]; * array A is sorted in non-decreasing order. * */ fun absDistinct(A: IntArray): Int { //NOTE: Any easy solution would be to sort the array by absolute values and the duplicates will //become adjacent values so can be easily discarded in one go or we can pass the array to Set class //to get distinct values but I want to solve it using CaterPillar method var count = 0 var start = 0 var end = A.lastIndex while (start <= end) { //count the current value as distinct because on iteration we will have //a distinct value. We will skip the duplicates using index increments in //the logic below count++ //we are only interested in absolute values val startValue = Math.abs(A[start].toLong()) val endValue = Math.abs(A[end].toLong()) when { startValue == endValue -> { //both start and end values are equal, duplicate encountered. We have considered 1 value above //into our count and in case of duplicates only 1 value should be considered as we are counting //distinct values. //now that current startValue (which is also endValue as both are equal in this case) //is discovered/counted, now remove duplicates on both start and end sides of the array //discard start side duplicates while (start <= end && Math.abs(A[start].toLong()) == endValue) { start++ } //discard end side duplicates while (end >= start && Math.abs(A[end].toLong()) == endValue) { end-- } } //start value > end value so move start by 1 element startValue > endValue -> { //skip start side duplicates while (start <= end && startValue == Math.abs(A[start].toLong())) { start++ } } else -> { // endValue > startValue, move end by 1 element //skip start side duplicates while (end >= start && endValue == Math.abs(A[end].toLong())) { end-- } } } } return count } /** * https://app.codility.com/programmers/lessons/15-caterpillar_method/min_abs_sum_of_two/ * -------------MinAbsSumOfTwo------------------- * Find the minimal absolute value of a sum of two elements. * Programming language: * Let A be a non-empty array consisting of N integers. * The abs sum of two for a pair of indices (P, Q) is the absolute value |A[P] + A[Q]|, for 0 ≤ P ≤ Q < N. * For example, the following array A: * A[0] = 1 * A[1] = 4 * A[2] = -3 * has pairs of indices (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2). * The abs sum of two for the pair (0, 0) is A[0] + A[0] = |1 + 1| = 2. * The abs sum of two for the pair (0, 1) is A[0] + A[1] = |1 + 4| = 5. * The abs sum of two for the pair (0, 2) is A[0] + A[2] = |1 + (−3)| = 2. * The abs sum of two for the pair (1, 1) is A[1] + A[1] = |4 + 4| = 8. * The abs sum of two for the pair (1, 2) is A[1] + A[2] = |4 + (−3)| = 1. * The abs sum of two for the pair (2, 2) is A[2] + A[2] = |(−3) + (−3)| = 6. * Write a function: * class Solution { public int solution(int[] A); } * that, given a non-empty array A consisting of N integers, returns the minimal abs sum of two for any pair of indices in this array. * For example, given the following array A: * A[0] = 1 * A[1] = 4 * A[2] = -3 * the function should return 1, as explained above. * Given array A: * A[0] = -8 * A[1] = 4 * A[2] = 5 * A[3] =-10 * A[4] = 3 * the function should return |(−8) + 5| = 3. * Write an efficient algorithm for the following assumptions: * N is an integer within the range [1..100,000]; * each element of array A is an integer within the range [−1,000,000,000..1,000,000,000]. * * ----------Solution------------ * There are two cases in which we will get a min sum * * 1. A sum of same or very close positive and negative numbers. (like (4, -4) or (-3, 4) etc.) because in * this case we will get a sum that is very small due to close values and opposite signs * 2. A sum of the absolute smallest number with itself like (e.g, (1, 1)) as in this case the total sum * will be small as the number is smallest * * So the smallest sum will be from either of the above two cases. If we sort the array then we will get * negative numbers on start and positive numbers on the end and smallest number in between somewhere. Then we can use * caterpillar method to find the smallest sum. * * Idea behind code: * Idea is to start from both ends (negative extreme end and positive extreme end) while keeping track of min sum * and try to converge on the smallest possible absolute number (case-2). This way we will be able to cover both of the cases * mentioned above */ data class MyName(var name: String, var name2: String) {} fun printStudents(vararg students: MyName) { for (s in students) println(s) } fun minAbsSumOfTwo(A: IntArray): Int { val m = MyName("", "") printStudents(m) //pick sum of first number with itself just to initialize the sum with some valid value var minSum = Math.abs(A[0] + A[0]) //sort the array so that negative and positive numbers are on opposite ends. A.sort() //start from both ends and try to converge to smallest absolute number var start = 0 var end = A.lastIndex while (start <= end) { //only keep the min of the two minSum = Math.min(minSum, Math.abs(A[start] + A[end])) //as we want to converge to smallest absolute number so move the greater of start/end if (Math.abs(A[start]) > Math.abs(A[end])) { start++ } else { end-- } } return minSum } }
0
Kotlin
0
0
a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4
17,499
codility-challenges-practice
Apache License 2.0
src/Day03_part2.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { fun part2(input: List<String>): Int { fun calcPriority(input: Char): Int { return if (input.code <= 'Z'.code) { input.code - 'A'.code + 27 } else { input.code - 'a'.code + 1 } } var priority = 0 var i = 0 while (i < input.size) { val hash = input[i].toHashSet() val hash2 = input[i + 1].toHashSet().filter { hash.contains(it) } val character = input[i + 2].find { hash2.contains(it) } priority += calcPriority(character!!) i += 3 } return priority } val testInput = readInput("Day03_test") check(part2(testInput) == 70) val input = readInput("Day03") println(part2(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
799
advent-of-code-2022
Apache License 2.0
common/src/main/kotlin/combo/bandit/dt/SplitMetric.kt
rasros
148,620,275
false
null
package combo.bandit.dt import combo.math.VarianceEstimator import combo.math.chi2CdfDf1 import combo.math.fCdfDf1 import kotlin.math.log2 import kotlin.math.sqrt interface SplitMetric { fun split(total: VarianceEstimator, pos: Array<VarianceEstimator>, neg: Array<VarianceEstimator>, minSamplesSplit: Float, minSamplesLeaf: Float): SplitInfo { var top1 = 0.0f var top2 = 0.0f var bestI = -1 val tv = totalValue(total) for (i in pos.indices) { val nPos = pos[i].nbrWeightedSamples val nNeg = neg[i].nbrWeightedSamples if (nPos < minSamplesLeaf || nNeg < minSamplesLeaf || nPos + nNeg < minSamplesSplit) continue val v = tv - value(total, pos[i], neg[i]) if (v > top1) { bestI = i top2 = top1 top1 = v } else if (v > top2) top2 = v } return SplitInfo(top1, top2, bestI) } fun totalValue(total: VarianceEstimator): Float = 0.0f fun value(total: VarianceEstimator, pos: VarianceEstimator, neg: VarianceEstimator): Float } data class SplitInfo(val top1: Float, val top2: Float, val i: Int) object VarianceReduction : SplitMetric { override fun totalValue(total: VarianceEstimator) = total.variance override fun value(total: VarianceEstimator, pos: VarianceEstimator, neg: VarianceEstimator): Float { val nPos = pos.nbrWeightedSamples val nNeg = neg.nbrWeightedSamples val n = nPos + nNeg return (nNeg / n) * neg.variance + (nPos / n) * pos.variance } } object TTest : SplitMetric { override fun totalValue(total: VarianceEstimator) = 1.0f override fun value(total: VarianceEstimator, pos: VarianceEstimator, neg: VarianceEstimator): Float { val nPos = pos.nbrWeightedSamples val nNeg = neg.nbrWeightedSamples val n = nPos + nNeg val diff = pos.mean - neg.mean val t = diff / sqrt((pos.variance / nPos + neg.variance / nNeg)) val F = t * t return 1 - fCdfDf1(F, n - 1) } } object EntropyReduction : SplitMetric { override fun totalValue(total: VarianceEstimator): Float { val n = total.nbrWeightedSamples val pos = total.sum val neg = n - total.sum val rp = pos / n val rn = neg / n return -rp * log2(rp) - rn * log2(rn) } override fun value(total: VarianceEstimator, pos: VarianceEstimator, neg: VarianceEstimator): Float { val nPos = pos.nbrWeightedSamples val nNeg = neg.nbrWeightedSamples val n = nPos + nNeg val ePos = totalValue(pos) val eNeg = totalValue(neg) return ePos * nPos / n + eNeg * nNeg / n } } object ChiSquareTest : SplitMetric { override fun totalValue(total: VarianceEstimator) = 1.0f override fun value(total: VarianceEstimator, pos: VarianceEstimator, neg: VarianceEstimator): Float { val nPos = pos.nbrWeightedSamples val nNeg = neg.nbrWeightedSamples val n = nPos + nNeg val actualPN = nPos - pos.sum val actualPP = pos.sum val actualNN = nNeg - neg.sum val actualNP = neg.sum val totalP = pos.sum + neg.sum val totalN = n - totalP val expectedPN = nPos * totalN / n val expectedPP = nPos * totalP / n val expectedNN = nNeg * totalN / n val expectedNP = nNeg * totalP / n val diffPN = actualPN - expectedPN val diffPP = actualPP - expectedPP val diffNN = actualNN - expectedNN val diffNP = actualNP - expectedNP val xPN = diffPN * diffPN / expectedPN val xPP = diffPP * diffPP / expectedPP val xNN = diffNN * diffNN / expectedNN val xNP = diffNP * diffNP / expectedNP val x = xPN + xPP + xNN + xNP return 1 - chi2CdfDf1(x) } } object GiniCoefficient : SplitMetric { override fun totalValue(total: VarianceEstimator): Float { val n = total.nbrWeightedSamples val pos = total.sum val neg = n - total.sum val rp = pos / n val rn = neg / n return -rp * rp - rn * rn } override fun value(total: VarianceEstimator, pos: VarianceEstimator, neg: VarianceEstimator): Float { val nPos = pos.nbrWeightedSamples val nNeg = neg.nbrWeightedSamples val n = nPos + nNeg val gPos = totalValue(pos) val gNeg = totalValue(neg) return gPos * nPos / n + gNeg * nNeg / n } }
0
Kotlin
1
2
2f4aab86e1b274c37d0798081bc5500d77f8cd6f
4,548
combo
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day23.kt
clechasseur
435,726,930
false
{"Kotlin": 315943}
package io.github.clechasseur.adventofcode2021 import io.github.clechasseur.adventofcode2021.dij.Dijkstra import io.github.clechasseur.adventofcode2021.dij.Graph import io.github.clechasseur.adventofcode2021.util.Direction import io.github.clechasseur.adventofcode2021.util.Pt import kotlin.math.min object Day23 { private val dataPart1 = """ ############# #...........# ###D#A#D#C### #B#C#B#A# ######### """.trimIndent() private val dataPart2 = """ ############# #...........# ###D#A#D#C### #D#C#B#A# #D#B#A#C# #B#C#B#A# ######### """.trimIndent() fun part1(): Int = lowestCost(dataPart1.toState(smallRooms, 5)) fun part2(): Int = lowestCost(dataPart2.toState(largeRooms, 7)) private val energyCost = mapOf( 'A' to 1, 'B' to 10, 'C' to 100, 'D' to 1000, ) private data class Room(val pts: List<Pt>, val owners: Char) { fun legalDestinationFor(amphipod: Char, tiles: Map<Pt, Char>): Boolean = amphipod == owners && pts.all { tiles[it]!! in listOf('.', amphipod) } } private val smallRooms = listOf( Room(listOf(Pt(3, 2), Pt(3, 3)), 'A'), Room(listOf(Pt(5, 2), Pt(5, 3)), 'B'), Room(listOf(Pt(7, 2), Pt(7, 3)), 'C'), Room(listOf(Pt(9, 2), Pt(9, 3)), 'D'), ) private val largeRooms = listOf( Room(listOf(Pt(3, 2), Pt(3, 3), Pt(3, 4), Pt(3, 5)), 'A'), Room(listOf(Pt(5, 2), Pt(5, 3), Pt(5, 4), Pt(5, 5)), 'B'), Room(listOf(Pt(7, 2), Pt(7, 3), Pt(7, 4), Pt(7, 5)), 'C'), Room(listOf(Pt(9, 2), Pt(9, 3), Pt(9, 4), Pt(9, 5)), 'D'), ) private val lava = listOf( Pt(3, 1), Pt(5, 1), Pt(7, 1), Pt(9, 1), ) private val hallway = (1..11).map { Pt(it, 1) } private data class State(val tiles: Map<Pt, Char>, val rooms: List<Room>, val depth: Int) { val amphipods: Map<Pt, Char> get() = tiles.filterValues { it.isLetter() } val solved: Boolean get() = rooms.all { room -> room.pts.all { tiles[it]!! == room.owners } } fun legalMove(from: Pt, to: Pt): Boolean = !lava.contains(to) && rooms.all { room -> (!room.pts.contains(to) || room.legalDestinationFor(tiles[from]!!, tiles)) && (!room.pts.contains(from) || !room.legalDestinationFor(tiles[from]!!, tiles)) } && (!hallway.contains(from) || !hallway.contains(to)) fun move(from: Pt, to: Pt): State { val newTiles = tiles.toMutableMap() newTiles[from] = '.' newTiles[to] = tiles[from]!! return State(newTiles, rooms, depth) } override fun toString(): String { return (0 until depth).joinToString("\n") { y -> (0..12).joinToString("") { x -> (tiles[Pt(x, y)] ?: ' ').toString() } } } } private class StateGraph(val state: State, val cost: Int) : Graph<Pt> { override fun allPassable(): List<Pt> = state.tiles.filterValues { it == '.' }.keys.toList() override fun neighbours(node: Pt): List<Pt> = Direction.displacements.mapNotNull { disp -> if (state.tiles.getOrDefault(node + disp, ' ') == '.') node + disp else null } override fun dist(a: Pt, b: Pt): Long = cost.toLong() } private fun String.toState(rooms: List<Room>, depth: Int) = State(lines().flatMapIndexed { y, line -> line.mapIndexed { x, c -> Pt(x, y) to c } }.toMap(), rooms, depth) private fun lowestCost(initialState: State): Int { var states = mapOf(initialState to 0) while (states.isNotEmpty()) { val newStates = mutableMapOf<State, Int>() states.toList().sortedBy { (_, cost) -> cost }.forEach { (state, costSoFar) -> if (state.solved) { return costSoFar } state.amphipods.forEach { (pos, amphipod) -> val (dist, _) = Dijkstra.build(StateGraph(state, energyCost[amphipod]!!), pos) dist.forEach { (to, cost) -> if (cost > 0 && cost != Long.MAX_VALUE && state.legalMove(pos, to)) { val newState = state.move(pos, to) val newCost = costSoFar + cost.toInt() newStates[newState] = min(newStates[newState] ?: Int.MAX_VALUE, newCost) } } } } states = newStates } error("Should have solved by now") } }
0
Kotlin
0
0
4b893c001efec7d11a326888a9a98ec03241d331
4,719
adventofcode2021
MIT License
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day13.kt
akikanellis
600,872,090
false
{"Kotlin": 142932, "Just": 977}
package com.akikanellis.adventofcode.year2022 object Day13 { private val DIVIDER_PACKETS = Pair(packet("[[2]]"), packet("[[6]]")) fun sumOfPacketPairIndicesInRightOrder(input: String) = packetPairs(input) .withIndex() .filter { (_, packetPair) -> rightOrder(packetPair.first, packetPair.second)!! } .sumOf { (index, _) -> index + 1 } fun distressSignalDecoderKey(input: String) = packetPairs(input) .plus(DIVIDER_PACKETS) .flatMap { it.toList() } .sortedWith { a, b -> if (rightOrder(a, b)!!) -1 else 1 } .withIndex() .filter { (_, packet) -> packet == DIVIDER_PACKETS.first || packet == DIVIDER_PACKETS.second } .map { (index, _) -> index + 1 } .reduce(Int::times) private fun packetPairs(input: String) = input .split("\n\n") .map { packetPair -> packetPair.split("\n") } .map { (leftPacketText, rightPacketText) -> Pair( packet(leftPacketText), packet(rightPacketText) ) } private fun packet(packetText: String) = packetData( remainingPacketText = packetText.toMutableList().also { it.removeAt(0) }, currentPacketList = mutableListOf() ) private fun packetData( remainingPacketText: MutableList<Char>, currentPacketList: MutableList<Any> ): List<Any> { val nextPacketPart = remainingPacketText.removeAt(0) return if (nextPacketPart == '[') { val newList = mutableListOf<Any>() currentPacketList.add(newList) packetData(remainingPacketText, newList) packetData(remainingPacketText, currentPacketList) } else if (nextPacketPart.isDigit()) { val remainingDigits = remainingPacketText .subList(0, remainingPacketText.indexOfFirst { !it.isDigit() }) val packetInteger = listOf(nextPacketPart) .plus(remainingDigits) .joinToString("") .toInt() remainingDigits.clear() currentPacketList.add(packetInteger) packetData(remainingPacketText, currentPacketList) } else if (nextPacketPart == ',') { packetData(remainingPacketText, currentPacketList) } else if (nextPacketPart == ']') { currentPacketList.toList() } else { error("Unsupported packet part: '$nextPacketPart'") } } private fun rightOrder(leftPacketPart: Any?, rightPacketPart: Any?): Boolean? = if (leftPacketPart == null && rightPacketPart == null) { null } else if (leftPacketPart == null) { true } else if (rightPacketPart == null) { false } else if (leftPacketPart is List<*> && rightPacketPart is List<*>) { rightOrder(leftPacketPart.firstOrNull(), rightPacketPart.firstOrNull()) ?: rightOrder( leftPacketPart.drop(1).ifEmpty { null }, rightPacketPart.drop(1).ifEmpty { null } ) } else if (leftPacketPart is Int && rightPacketPart is Int) { when { leftPacketPart < rightPacketPart -> true leftPacketPart > rightPacketPart -> false else -> null } } else if (leftPacketPart is Int && rightPacketPart is List<*>) { rightOrder(listOf(leftPacketPart), rightPacketPart) } else if (leftPacketPart is List<*> && rightPacketPart is Int) { rightOrder(leftPacketPart, listOf(rightPacketPart)) } else { error( "Unsupported packet parts. Left: '$leftPacketPart', right: '$rightPacketPart'" ) } }
8
Kotlin
0
0
036cbcb79d4dac96df2e478938de862a20549dce
3,803
advent-of-code
MIT License
src/main/year_2016/day15/day15.kt
rolf-rosenbaum
572,864,107
false
{"Kotlin": 80772}
package year_2016.day15 import readInput val reg = """\b\d+\b""".toRegex() fun main() { val input = readInput("main/year_2016/day15/Day15") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int { return part2(input.dropLast(1)) } fun part2(input: List<String>): Int { val discs = input.map(String::toDisc) var time = 0 while (true) { if (discs.all { (it.layer + it.startingPosition + time) % it.positions == 0 }) return time time++ } } data class Disc( val layer: Int, val positions: Int, val startingPosition: Int ) fun String.toDisc(): Disc { val (layer, positions, _, startingPosition) = reg.findAll(this).toList() return Disc(layer.value.toInt(), positions.value.toInt(), startingPosition.value.toInt()) }
0
Kotlin
0
2
59cd4265646e1a011d2a1b744c7b8b2afe482265
859
aoc-2022
Apache License 2.0
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/common/Space.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.common import kotlin.math.* typealias Point2D = Pair<Int, Int> val Point2D.x: Int get() = first val Point2D.y: Int get() = second operator fun Point2D.plus(other: Point2D) = Point2D(x + other.x, y + other.y) operator fun Point2D.minus(other: Point2D) = Point2D(x - other.x, y - other.y) operator fun Point2D.times(factor: Int) = Point2D(x * factor, y * factor) fun Point2D.distance() = sqrt(x.toDouble().pow(2) + y.toDouble().pow(2)) fun Point2D.distanceTo(other: Point2D) = (this - other).distance() fun Point2D.manhattan() = abs(x) + abs(y) fun Point2D.manhattanTo(other: Point2D) = (this - other).manhattan() fun Point2D.rotateDegrees(degrees: Int) = rotateRadians(degrees.radians()) fun Point2D.rotateRadians(radians: Double) = (x * cos(radians) - y * sin(radians)).roundToInt() to (y * cos(radians) + x * sin(radians)).roundToInt() fun Point2D.pointsNextTo() = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1).map { this + it } fun Point2D.pointsAround() = (-1..1).allPairs().filterNot { it == Pair(0, 0) }.map { this + it }.toList() fun Iterable<Point2D>.print() { for (y in this.minOf { it.y }..this.maxOf { it.y }) { for (x in this.minOf { it.x }..this.maxOf { it.x }) { if (this.contains(x to y)) { print('█') } else { print(' ') } } println() } } typealias Point3D = Triple<Int, Int, Int> val Point3D.x: Int get() = first val Point3D.y: Int get() = second val Point3D.z: Int get() = third operator fun Point3D.plus(other: Point3D) = Point3D(x + other.x, y + other.y, z + other.z) operator fun Point3D.minus(other: Point3D) = Point3D(x - other.x, y - other.y, z - other.z) operator fun Point3D.times(factor: Int) = Point3D(x * factor, y * factor, z * factor) fun Point3D.distance() = sqrt(x.toDouble().pow(2) + y.toDouble().pow(2) + z.toDouble().pow(2)) fun Point3D.distanceTo(other: Point3D) = (this - other).distance() fun Point3D.manhattan() = abs(x) + abs(y) + abs(z) fun Point3D.manhattanTo(other: Point3D) = (this - other).manhattan() fun Point3D.pointsAround() = (-1..1).allTriples().filterNot { it == Triple(0, 0, 0) }.map { this + it }.toList()
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
2,218
advent-of-code
MIT License
src/Day09.kt
RogozhinRoman
572,915,906
false
{"Kotlin": 28985}
import kotlin.math.abs fun main() { fun printGrid( grid: Array<MutableList<String>>, H: Pair<Int, Int>, T: Pair<Int, Int> ) { for (i in grid.indices) { for (j in grid[i].indices) { if (H.first == i && H.second == j) { print("H") continue } if (T.first == i && T.second == j) { print("T") continue } print(grid[i][j]) } println() } } fun isAttainable(newH: Pair<Int, Int>, T: Pair<Int, Int>): Boolean { if (newH.first == T.first) return abs(newH.second - T.second) <= 1 if (newH.second == T.second) return abs(newH.first - T.first) <= 1 return (abs(newH.first - T.first) + abs(newH.second - T.second)) <= 2 } fun getOffset(x1: Int, x2: Int): Int { if (x1 == x2) { return 0 } return if (x1 > x2) 1 else -1 } fun performStep( x: Int, y: Int, H: Pair<Int, Int>, T: Pair<Int, Int>, grid: Array<MutableList<String>>, shouldDraw: Boolean ): Triple<Pair<Int, Int>, Pair<Int, Int>, Array<MutableList<String>>> { val newH = Pair(H.first + x, H.second + y) if (isAttainable(newH, T)) return Triple(newH, T, grid) if (shouldDraw) grid[T.first][T.second] = "#" return Triple( newH, Pair( T.first + getOffset(newH.first, T.first), T.second + getOffset(newH.second, T.second) ), grid ) } fun performStep2( coord1: Int, coord2: Int, snake: Array<Pair<Int, Int>>, grid: Array<MutableList<String>> ): MutableList<Pair<Int, Int>> { val result = snake.toMutableList() val (first, second, _) = performStep(coord1, coord2, result[0], result[1], grid, false) result[0] = first result[1] = second for (i in 2 until result.size) { val (_, target, _) = performStep(0, 0, result[i - 1], result[i], grid, false) result[i] = target } grid[result.last().first][result.last().second] = "#" return result } fun performTravel( input: List<String>, grid: Array<MutableList<String>> ) { var H = Pair(grid.size / 2, grid.size / 2) var T = Pair(grid.size / 2, grid.size / 2) for (command in input) { val parts = command.split(' ') val direction = parts.first().toString() var steps = parts.last().toString().toInt() while (steps > 0) { val result = when (direction) { "R" -> performStep(0, 1, H, T, grid, true) "L" -> performStep(0, -1, H, T, grid, true) "U" -> performStep(-1, 0, H, T, grid, true) else -> performStep(1, 0, H, T, grid, true) } H = result.first T = result.second steps-- } } grid[T.first][T.second] = "#" } fun performTravel2( input: List<String>, grid: Array<MutableList<String>> ) { var snake = Array(10) { Pair(grid.size / 2, grid.size / 2) } for (command in input) { val parts = command.split(' ') val direction = parts.first().toString() var steps = parts.last().toString().toInt() while (steps > 0) { val result = when (direction) { "R" -> performStep2(0, 1, snake, grid) "L" -> performStep2(0, -1, snake, grid) "U" -> performStep2(-1, 0, snake, grid) else -> performStep2(1, 0, snake, grid) } snake = result.toTypedArray() steps-- } } grid[snake.last().first][snake.last().second] = "#" } fun part1(input: List<String>): Int { val size = 10000 val grid = Array(size) { MutableList(size) { "." } } performTravel(input, grid) return grid.flatMap { it }.count { it == "#" } } fun part2(input: List<String>): Int { val size = 10000 val grid = Array(size) { MutableList(size) { "." } } performTravel2(input, grid) return grid.flatMap { it }.count { it == "#" } } val testInput = readInput("Day09_test") val part1 = part1(testInput) check(part1 == 13) // check(part2(testInput) == 70) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
6375cf6275f6d78661e9d4baed84d1db8c1025de
4,765
AoC2022
Apache License 2.0
advent5/src/main/kotlin/Main.kt
thastreet
574,294,123
false
{"Kotlin": 29380}
import java.io.File import java.util.Stack data class Command( val count: Int, val from: Int, val to: Int ) fun main(args: Array<String>) { val lines = File("input.txt").readLines() val commands = parseCommands(lines) val part1Result = part1(getStacks(), commands) println("part1Result: $part1Result") val part2Result = part2(getStacks(), commands) println("part2Result: $part2Result") } fun getStacks(): List<Stack<Char>> = listOf( stackTopToBottom('V', 'Q', 'W', 'M', 'B', 'N', 'Z', 'C'), stackTopToBottom('B', 'C', 'W', 'R', 'Z', 'H'), stackTopToBottom('J', 'R', 'Q', 'F'), stackTopToBottom('T', 'M', 'N', 'F', 'H', 'W', 'S', 'Z'), stackTopToBottom('P', 'Q', 'N', 'L', 'W', 'F', 'G'), stackTopToBottom('W', 'P', 'L'), stackTopToBottom('J', 'Q', 'C', 'G', 'R', 'D', 'B', 'V'), stackTopToBottom('W', 'B', 'N', 'Q', 'Z'), stackTopToBottom('J', 'T', 'G', 'C', 'F', 'L', 'H') ) fun parseCommands(lines: List<String>): List<Command> = lines.map { line -> val parts = line .replace("move", "") .replace("from", ";") .replace("to", ";") .replace(" ", "") .split(";") Command(parts[0].toInt(), parts[1].toInt(), parts[2].toInt()) } fun part1(stacks: List<Stack<Char>>, commands: List<Command>): String { commands.forEach { command -> repeat(command.count) { stacks[command.to - 1].push(stacks[command.from - 1].pop()) } } return getMessage(stacks) } fun part2(stacks: List<Stack<Char>>, commands: List<Command>): String { commands.forEach { command -> val temp = Stack<Char>() repeat(command.count) { temp.push(stacks[command.from - 1].pop()) } repeat(command.count) { stacks[command.to - 1].push(temp.pop()) } } return getMessage(stacks) } fun getMessage(stacks: List<Stack<Char>>): String = stacks.map { it.peek() }.joinToString(separator = "") fun stackTopToBottom(vararg chars: Char): Stack<Char> = Stack<Char>().apply { chars.reversed().forEach { push(it) } }
0
Kotlin
0
0
e296de7db91dba0b44453601fa2b1696af9dbb15
2,229
advent-of-code-2022
Apache License 2.0
app/src/main/java/com/themobilecoder/adventofcode/day5/DayFiveUtils.kt
themobilecoder
726,690,255
false
{"Kotlin": 323477}
package com.themobilecoder.adventofcode.day5 import com.themobilecoder.adventofcode.splitByNewLine fun String.getSeedsToBePlanted(): List<UInt> { val lines = splitByNewLine() return lines.first { it.contains("seeds:") }.split(":")[1] .trim() .split(" ") .map { it.toUInt() } } fun String.getSeedPairsToBePlanted(): List<SeedPair> { val lines = splitByNewLine() return lines.first { it.contains("seeds:") }.split(":")[1] .trim() .split(" ") .map { it.toUInt() } .withIndex() .groupBy { it.index / 2 } .map { SeedPair( start = it.value[0].value, range = it.value[1].value ) } } fun String.getMapAsConversionObjectsFromConversionType(conversionType: ConversionType): List<ConversionObject> { val lines = splitByNewLine() val startIndexOfMap: Int = lines.indexOfFirst { it.contains(conversionType.value) } var i = startIndexOfMap + 1 val conversionObjects = mutableListOf<ConversionObject>() while (i < lines.size && lines[i].isNotEmpty()) { val data = lines[i].split(" ").map { it.toUInt() } conversionObjects.add( ConversionObject( destination = data[0], source = data[1], range = data[2] ) ) ++i } return conversionObjects } fun String.getLocationValueFromSeed(seed: UInt): UInt { val inputString = this fun UInt.getConversionToType(conversionType: ConversionType): UInt { val conversionTypes = inputString.getMapAsConversionObjectsFromConversionType(conversionType) for (cType in conversionTypes) { val source = cType.source val destination = cType.destination val range = cType.range val upperRange = source + range val differenceFromSource = this - source if (this in source until upperRange) { //There is conversion return destination + differenceFromSource } } return this } return seed .getConversionToType(ConversionType.SEED_TO_SOIL) .getConversionToType(ConversionType.SOIL_TO_FERTILIZER) .getConversionToType(ConversionType.FERTILIZER_TO_WATER) .getConversionToType(ConversionType.WATER_TO_LIGHT) .getConversionToType(ConversionType.LIGHT_TO_TEMPERATURE) .getConversionToType(ConversionType.TEMPERATURE_TO_HUMIDITY) .getConversionToType(ConversionType.HUMIDITY_TO_LOCATION) } private fun UInt.getConversionToType( mapOfConversionObjectsByConversionType: Map<ConversionType, List<ConversionObject>>, conversionType: ConversionType ): UInt { val conversionObjects = mapOfConversionObjectsByConversionType[conversionType] ?: listOf() for (cType in conversionObjects) { val source = cType.source val destination = cType.destination val range = cType.range val upperRange = source + range val differenceFromSource = this - source if (this in source until upperRange) { //There is conversion return destination + differenceFromSource } } return this } fun getLocationValueFromSeedOptimised( mapOfConversionObjectsByConversionType: Map<ConversionType, List<ConversionObject>>, seed: UInt ): UInt { return seed .getConversionToType(mapOfConversionObjectsByConversionType, ConversionType.SEED_TO_SOIL) .getConversionToType(mapOfConversionObjectsByConversionType, ConversionType.SOIL_TO_FERTILIZER) .getConversionToType(mapOfConversionObjectsByConversionType, ConversionType.FERTILIZER_TO_WATER) .getConversionToType(mapOfConversionObjectsByConversionType, ConversionType.WATER_TO_LIGHT) .getConversionToType(mapOfConversionObjectsByConversionType, ConversionType.LIGHT_TO_TEMPERATURE) .getConversionToType(mapOfConversionObjectsByConversionType, ConversionType.TEMPERATURE_TO_HUMIDITY) .getConversionToType(mapOfConversionObjectsByConversionType, ConversionType.HUMIDITY_TO_LOCATION) }
0
Kotlin
0
0
b7770e1f912f52d7a6b0d13871f934096cf8e1aa
4,279
Advent-of-Code-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/AnswerQueries.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Arrays import kotlin.math.abs /** * 2389. Longest Subsequence With Limited Sum * @see <a href="https://leetcode.com/problems/longest-subsequence-with-limited-sum/">Source</a> */ fun interface AnswerQueries { operator fun invoke(nums: IntArray, queries: IntArray): IntArray } class AnswerQueriesBinarySearch : AnswerQueries { override operator fun invoke(nums: IntArray, queries: IntArray): IntArray { nums.sort() val n: Int = nums.size val m: Int = queries.size val res = IntArray(m) for (i in 1 until n) { nums[i] += nums[i - 1] } for (i in 0 until m) { val j: Int = Arrays.binarySearch(nums, queries[i]) res[i] = abs(j + 1) } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,427
kotlab
Apache License 2.0
src/main/kotlin/day15/Day15.kt
limelier
725,979,709
false
{"Kotlin": 48112}
package day15 import common.InputReader private fun String.hash(): Int { var hash = 0 for (c in this) { hash += c.code hash *= 17 hash %= 256 } return hash } private data class Lens(val label: String, val focalLength: Int) private sealed interface Step { val label: String } private data class RemoveStep(override val label: String): Step private data class UpsertStep(override val label: String, val focalLength: Int): Step internal fun main() { val instructions = InputReader("day15/input.txt") .lines().first() .split(",") println("Part 1: ${instructions.sumOf { it.hash() }}") val steps: List<Step> = instructions.map { instruction -> val iOp = instruction.indexOfFirst { it in "-=" } val label = instruction.take(iOp) when(instruction[iOp]) { '-' -> RemoveStep(label) '=' -> UpsertStep(label, instruction.drop(iOp + 1).toInt()) else -> throw IllegalArgumentException("Input has invalid step $instruction") } } val boxes = List(256) { mutableListOf<Lens>() } for (step in steps) { val hash = step.label.hash() val box = boxes[hash] when(step) { is RemoveStep -> box.removeIf { it.label == step.label } is UpsertStep -> { val newLens = Lens(step.label, step.focalLength) val i = box.indexOfFirst { it.label == newLens.label } if (i != -1) { box[i] = newLens } else { box.add(newLens) } } } } val focusingPower = boxes.mapIndexed { i, box -> (i + 1) * box.mapIndexed { j, lens -> (j + 1) * lens.focalLength }.sum() }.sum() println("Part 2: $focusingPower") }
0
Kotlin
0
0
0edcde7c96440b0a59e23ec25677f44ae2cfd20c
1,848
advent-of-code-2023-kotlin
MIT License
src/main/kotlin/com/github/dangerground/Day14.kt
dangerground
226,153,955
false
null
package com.github.dangerground import kotlin.math.ceil import kotlin.math.floor typealias Chemical = String class Nanofactory(reactionsInput: String) { val reactions = HashMap<Chemical, Reaction>() init { reactionsInput.lines().forEach { reaction -> val reactionParts = reaction.split(" => ") val inputs = reactionParts.first().split(", ").map { stringToAmount(it) } val output = stringToAmount(reactionParts.last()) reactions[output.chemical] = Reaction(output, inputs) } } private fun stringToAmount(it: String): Amount { val amout = it.split(" "); return Amount(amout.first().toLong(), amout.last()) } //fun findOreForFuel() = resolve("FUEL" as Chemical) val unresolved = HashSet<Chemical>() val totalRequired = HashMap<Chemical, Long>() val totalGenerated = HashMap<Chemical, Long>() fun findOreForFuel() : Long { unresolved.add("FUEL") totalRequired["FUEL"] = 13108426 do { val element = unresolved.first() unresolved.remove(element) if (element != "ORE") { val reaction = reactions[element]!! var totalValue = getGenerated(element) if (totalValue < totalRequired[element]!!) { val required = totalRequired[element]!! - totalValue totalValue += calcProduced(required, reaction.output.value) reaction.inputs.forEach { unresolved.add(it.chemical) setRequired(Amount(it.value * stepCount(required, reaction.output.value), it.chemical)) } totalGenerated[reaction.output.chemical] = totalValue } } println(totalGenerated) } while (unresolved.isNotEmpty()) return totalRequired["ORE"]!! } private fun stepCount(required: Long, produceable: Long) = ceil(required.toDouble() / produceable).toLong() private fun calcProduced(required: Long, produceable: Long) = stepCount(required, produceable) * produceable private fun getGenerated(element: Chemical): Long { if (totalGenerated.containsKey(element)) { return totalGenerated[element]!! } return 0 } private fun setRequired(amount: Amount) { if (totalRequired.containsKey(amount.chemical)) { totalRequired[amount.chemical] = totalRequired[amount.chemical]!! + amount.value } else { totalRequired[amount.chemical] = amount.value } } } class Reaction(val output: Amount, val inputs: List<Amount>) class Amount(val value: Long, val chemical: Chemical)
0
Kotlin
0
1
125d57d20f1fa26a0791ab196d2b94ba45480e41
2,753
adventofcode
MIT License
src/com/ncorti/aoc2023/Day20.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 data class Wire( val name: String, val type: String, val next: List<String>, var status: Boolean = false, var memory: MutableMap<String, Boolean> = mutableMapOf(), ) { fun initMemory(input: Map<String, Wire>) { input.forEach { (key, value) -> if (value.next.contains(this.name)) { memory[key] = false } } } fun isMemoryAllHigh(): Boolean = memory.all { it.value } } data class Pulse(val isHigh: Boolean, val source: String, val dest: String) fun main() { fun parseInput(): Map<String, Wire> { val input = getInputAsText("20") { split("\n").filter(String::isNotBlank).map { it.split(" -> ") } } val map = input.associate { val type = if ("%" in it[0]) { "%" } else if ("&" in it[0]) { "&" } else { it[0] } val name = it[0].removePrefix("%").removePrefix("&") name to Wire(name, type, it[1].split(", ")) } map.forEach { (_, value) -> if (value.type == "&") { value.initMemory(map) } } return map } fun processPulse( map: Map<String, Wire>, queue: MutableList<Pulse>, pulse: Pulse ) { val (isHigh, source, dest) = pulse val value = map[dest] ?: return if (value.type == "broadcaster") { value.next.forEach { next -> queue.add(Pulse(isHigh, dest, next)) } } else if (value.type == "%") { if (isHigh) { // no-op pulse is ignored } else { if (value.status) { value.next.forEach { next -> queue.add(Pulse(false, dest, next)) } } else { value.next.forEach { next -> queue.add(Pulse(true, dest, next)) } } value.status = !value.status } } else if (value.type == "&") { value.memory[source] = isHigh if (value.isMemoryAllHigh()) { value.next.forEach { next -> queue.add(Pulse(false, dest, next)) } } else { value.next.forEach { next -> queue.add(Pulse(true, dest, next)) } } } } fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) fun lcm(a: Long, b: Long): Long = a * b / gcd(a, b) fun part1(): Int { val map = parseInput() var (lowPulses, highPulses) = 0 to 0 repeat(1000) { val queue = mutableListOf(Pulse(false, "button", "broadcaster")) while (queue.isNotEmpty()) { val pulse = queue.removeAt(0) if (pulse.isHigh) { highPulses++ } else { lowPulses++ } processPulse(map, queue, pulse) } } return lowPulses * highPulses } fun part2(): Long { val map = parseInput() val gate = map.filter { it.value.next.contains("rx") }.values.first() val conjunctions = map.filter { it.value.next.contains(gate.name) }.map { it.value.name to -1L }.associate { it.first to it.second }.toMutableMap() var count = 0 while (conjunctions.any { it.value == -1L }) { count++ val queue = mutableListOf(Pulse(false, "button", "broadcaster")) while (queue.isNotEmpty()) { val pulse = queue.removeAt(0) if (!pulse.isHigh && pulse.dest in conjunctions && conjunctions[pulse.dest]!! == -1L) { conjunctions[pulse.dest] = count.toLong() } processPulse(map, queue, pulse) } } return conjunctions.map { it.value }.fold(1L) { acc, i -> lcm(acc, i) } } println(part1()) println(part2()) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
4,235
adventofcode-2023
MIT License
src/Day02.kt
kprow
573,685,824
false
{"Kotlin": 23005}
fun main() { var scoreSum2 = 0 fun part1(input: List<String>): Int { var scoreSum = 0 scoreSum2 = 0 var yours = YourHand.X var theirs = OpponentHand.A var result = YourResult.X for (game in input) { theirs = OpponentHand.valueOf(game[0].toString()) yours = YourHand.valueOf(game[2].toString()) result = YourResult.valueOf(game[2].toString()) scoreSum += yours.score() + yours.playResult(theirs) scoreSum2 += result.resultValue() + result.playShapeValue(theirs) } return scoreSum } fun part2(input: List<String>): Int { part1(input) return scoreSum2 } val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) check(part2(testInput) == 12) println(part2(input)) } enum class YourHand(val shape: String) { X("Rock") { override fun score() = 1 override fun playResult(theirs: OpponentHand): Int { return when(theirs) { OpponentHand.A -> 3 OpponentHand.B -> 0 OpponentHand.C -> 6 } } }, Y("Paper"){ override fun score() = 2 override fun playResult(theirs: OpponentHand): Int { return when(theirs) { OpponentHand.A -> 6 OpponentHand.B -> 3 OpponentHand.C -> 0 } } }, Z("Scissors") { override fun score() = 3 override fun playResult(theirs: OpponentHand): Int { return when(theirs) { OpponentHand.A -> 0 OpponentHand.B -> 6 OpponentHand.C -> 3 } } }; abstract fun score(): Int abstract fun playResult(theirs: OpponentHand): Int } enum class OpponentHand(val shape: String) { A("Rock"), B("Paper"), C("Scissors") } enum class YourResult(val result: String) { X("Lose") { override fun playShapeValue(theirs: OpponentHand): Int { return when(theirs) { OpponentHand.A -> YourHand.Z.score() OpponentHand.B -> YourHand.X.score() OpponentHand.C -> YourHand.Y.score() } } override fun resultValue() = 0 }, Y("Draw"){ override fun playShapeValue(theirs: OpponentHand): Int { return when(theirs) { OpponentHand.A -> YourHand.X.score() OpponentHand.B -> YourHand.Y.score() OpponentHand.C -> YourHand.Z.score() } } override fun resultValue() = 3 }, Z("Win") { override fun playShapeValue(theirs: OpponentHand): Int { return when(theirs) { OpponentHand.A -> YourHand.Y.score() OpponentHand.B -> YourHand.Z.score() OpponentHand.C -> YourHand.X.score() } } override fun resultValue() = 6 }; abstract fun playShapeValue(theirs: OpponentHand): Int abstract fun resultValue(): Int }
0
Kotlin
0
0
9a1f48d2a49aeac71fa948656ae8c0a32862334c
3,156
AdventOfCode2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day02.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.ints fun main() { Day02.run() } object Day02 : Day(2015, 2) { override fun part1() = input.lines().map { ints(it) }.sumOf { surfaceArea(it) + extra(it) } private fun extra(inp: List<Int>) = (inp[0] * inp[1]).coerceAtMost((inp[1] * inp[2]).coerceAtMost(inp[0] * inp[2])) private fun surfaceArea(inp: List<Int>) = 2 * inp[0] * inp[1] + 2 * inp[0] * inp[2] + 2 * inp[1] * inp[2] override fun part2() = input.lines().map { ints(it) }.sumOf { ribbon(it) + bow(it) } private fun bow(inp: List<Int>) = inp[0] * inp[1] * inp[2] private fun ribbon(inp: List<Int>) = (2 * inp[0] + 2 * inp[1]).coerceAtMost((2 * inp[1] + 2 * inp[2]).coerceAtMost(2 * inp[0] + 2 * inp[2])) }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
799
adventofkotlin
MIT License
src/main/kotlin/algorithms/LongestCommonSubsequenceLCS.kt
jimandreas
377,843,697
false
null
@file:Suppress("SameParameterValue", "UnnecessaryVariable", "UNUSED_VARIABLE", "ControlFlowWithEmptyBody", "unused", "MemberVisibilityCanBePrivate", "LiftReturnOrAssignment" ) package algorithms import kotlin.math.max /** Code Challenge: Solve the Longest Common Subsequence Problem. Input: Two strings s and t. Output: A longest common subsequence of s and t. (Note: more than one solution may exist, in which case you may output any one.) * * See also: * stepik: @link: https://stepik.org/lesson/240303/step/5?unit=212649 * rosalind: @link: http://rosalind.info/problems/ba5c/ * book (5.8): https://www.bioinformaticsalgorithms.org/bioinformatics-chapter-5 */ class LongestCommonSubsequenceLCS { enum class Dir { NOTSET, MATCHMISMATCH, INSERTION_RIGHT, DELETION_DOWN } /** * backtrack setup * This algorithm lines up two strings in the row and column directions * of a 2D matrix. It then fills in each entry in the matrix based on the * comparison of the row and column letters. The Dir enum is used to * indicate the state of each entry */ fun backtrack(vColumn: String, wRow: String): Array<Array<Dir>> { val nRows: Int = vColumn.length val mCols: Int = wRow.length // note that the array is filled with zeros val twoD = Array(nRows+1) { IntArray(mCols+1) } val backtrack2D = Array(nRows+1) { Array(mCols+1) { Dir.NOTSET } } for (iRow in 1..nRows) { for (jCol in 1..mCols) { var match = 0 if (vColumn[iRow - 1] == wRow[jCol - 1]) { match = 1 } val cellVal = max(twoD[iRow - 1][jCol], max(twoD[iRow][jCol - 1], twoD[iRow - 1][jCol - 1] + match)) twoD[iRow][jCol] = cellVal when { twoD[iRow][jCol] == twoD[iRow - 1][jCol] -> { backtrack2D[iRow][jCol] = Dir.DELETION_DOWN } twoD[iRow][jCol] == twoD[iRow][jCol - 1] -> { backtrack2D[iRow][jCol] = Dir.INSERTION_RIGHT } twoD[iRow][jCol] == twoD[iRow - 1][jCol - 1] + match -> { backtrack2D[iRow][jCol] = Dir.MATCHMISMATCH } } } } return backtrack2D } fun outputLCS(backtrack2D: Array<Array<Dir>>, vColumn: String, i: Int, j: Int, str: StringBuilder): StringBuilder { if (i == 0 || j == 0) { return str } when { backtrack2D[i][j] == Dir.DELETION_DOWN -> { return outputLCS(backtrack2D, vColumn, i - 1, j, str) } backtrack2D[i][j] == Dir.INSERTION_RIGHT -> { return outputLCS(backtrack2D, vColumn, i, j - 1, str) } else -> { return outputLCS(backtrack2D, vColumn, i - 1, j - 1, str.insert(0, vColumn[i-1])) } } } }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
3,027
stepikBioinformaticsCourse
Apache License 2.0
2020/04/Solution.kt
AdrianMiozga
588,519,359
false
{"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732}
import java.io.File private const val FILENAME = "2020/04/input.txt" fun main() { partOne() partTwo() } private fun partOne() { val passports = File(FILENAME) .readText() .trim() .split("\r\n\r\n") .map { it.replace("\r\n", " ") } val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") // Count good passports val goodPassports = passports.count { passport -> requiredFields.all { field -> passport.contains(field) } } println(goodPassports) } private fun partTwo() { val passports = File(FILENAME) .readText() .trim() .split("\r\n\r\n") .map { it.replace("\r\n", " ") } // Count good passports var goodPassports = 0 val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") val correctEyeColors = listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") passportLoop@ for (passport in passports) { // Check if all fields are present if (!requiredFields.all { passport.contains(it) }) { continue } val fields = passport.split(" ") // Check if fields contain correct values for (field in fields) { val key = field.slice(0..2) val value = field.slice(4 until field.length) when (key) { "byr" -> if (value.toIntOrNull() !in 1920..2002) continue@passportLoop "iyr" -> if (value.toIntOrNull() !in 2010..2020) continue@passportLoop "eyr" -> if (value.toIntOrNull() !in 2020..2030) continue@passportLoop "hgt" -> { val regex = Regex("""^(\d+)(cm|in)$""") val (number, unit) = regex.find(value)?.destructured ?: continue@passportLoop when (unit) { "cm" -> if (number.toIntOrNull() !in 150..193) continue@passportLoop "in" -> if (number.toIntOrNull() !in 59..76) continue@passportLoop } } "hcl" -> if (!(value matches Regex("""^#[0-9a-f]{6}$"""))) continue@passportLoop "ecl" -> if (!correctEyeColors.any { value == it }) continue@passportLoop "pid" -> if (!(value matches Regex("""^\d{9}$"""))) continue@passportLoop } } goodPassports++ } println(goodPassports) }
0
Kotlin
0
0
c9cba875089d8d4fb145932c45c2d487ccc7e8e5
2,481
Advent-of-Code
MIT License
src/main/kotlin/g0401_0500/s0497_random_point_in_non_overlapping_rectangles/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0401_0500.s0497_random_point_in_non_overlapping_rectangles // #Medium #Math #Binary_Search #Prefix_Sum #Ordered_Set #Randomized #Reservoir_Sampling // #2023_01_04_Time_759_ms_(100.00%)_Space_100.1_MB_(100.00%) import java.util.Random @Suppress("kotlin:S2245") class Solution(rects: Array<IntArray>) { private val weights: IntArray private val rects: Array<IntArray> private val random: Random init { weights = IntArray(rects.size) this.rects = rects random = Random() for (i in rects.indices) { val rect = rects[i] val count = (1 + rect[2] - rect[0]) * (1 + rect[3] - rect[1]) weights[i] = (if (i == 0) 0 else weights[i - 1]) + count } } fun pick(): IntArray { val picked: Int = 1 + random.nextInt(weights[weights.size - 1]) val idx = findGreaterOrEqual(picked) return getRandomPoint(idx) } private fun findGreaterOrEqual(target: Int): Int { var left = 0 var right = weights.size - 1 while (left + 1 < right) { val mid = left + (right - left) / 2 if (weights[mid] >= target) { right = mid } else { left = mid + 1 } } return if (weights[left] >= target) left else right } private fun getRandomPoint(idx: Int): IntArray { val r = rects[idx] val left = r[0] val right = r[2] val bot = r[1] val top = r[3] return intArrayOf( left + random.nextInt(right - left + 1), bot + random.nextInt(top - bot + 1) ) } } /* * Your Solution object will be instantiated and called as such: * var obj = Solution(rects) * var param_1 = obj.pick() */
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,782
LeetCode-in-Kotlin
MIT License