path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/me/consuegra/algorithms/KOneAway.kt
aconsuegra
91,884,046
false
{"Java": 113554, "Kotlin": 79568}
package me.consuegra.algorithms /** * There are three types of edits that can be performed on strings: insert a character, remove a character, or * replace a character. Given two strings, write a function to check if they are one edit (or) zero edits away. * <p> * Examples: * <p> * pale, ple -> true * pales, pale -> true * pale, bale -> true * pale, bake -> false */ class KOneAway { fun oneAway(s1: String, s2: String) : Boolean { if (Math.abs(s1.length - s2.length) > 1) { return false } val (shorterString, longerString) = categorizeStrings(s1, s2) var numChanges = 0 var indexShorterString = 0 var indexLongerString = 0 while (indexShorterString < shorterString.length && indexLongerString < longerString.length) { if (shorterString[indexShorterString] != longerString[indexLongerString]) { if (numChanges == 1) { return false } numChanges++ if (s1.length == s2.length) { indexShorterString++ } } else { indexShorterString++ } indexLongerString++ } return true } private fun categorizeStrings(s1: String, s2: String) : Pair<String, String> { when { s1.length > s2.length -> return s2 to s1 else -> return s1 to s2 } } }
0
Java
0
7
7be2cbb64fe52c9990b209cae21859e54f16171b
1,467
algorithms-playground
MIT License
wordy/src/main/kotlin/Wordy.kt
3mtee
98,672,009
false
null
import kotlin.math.pow object Wordy { private const val PREFIX = "What is " private const val SUFFIX = "?" private val operations = mapOf<String, (a: Int, b: Int) -> Int>( "+" to { a, b -> a + b }, "-" to { a, b -> a - b }, "*" to { a, b -> a * b }, "/" to { a, b -> a / b }, "^" to { a, b -> a.toDouble().pow(b).toInt() }, ) fun answer(input: String): Int { return clearInput(input) .also { validateInput(it) } .split(" ") .asSequence() .also { if (it.count() == 1) return it.first().toInt() } .zipWithNext() .foldIndexed(0) { index, acc, piece -> when { index == 0 -> piece.first.toInt() index % 2 == 1 -> operations[piece.first]!!.invoke(acc, piece.second.toInt()) else -> acc } } } private fun validateInput(input: String) { if (!input.matches(Regex("^-?\\d+( [+\\-*/^] -?\\d+)*"))) { throw IllegalArgumentException("Wrong input") } } private fun clearInput(input: String): String = input .replace(PREFIX, "") .replace("plus", "+") .replace("minus", "-") .replace("multiplied by", "*") .replace("divided by", "/") .replace(Regex("raised to the (\\d+)th power"), "^ $1") .replace(SUFFIX, "") }
0
Kotlin
0
0
6e3eb88cf58d7f01af2236e8d4727f3cd5840065
1,448
exercism-kotlin
Apache License 2.0
src/main/kotlin/com/staricka/adventofcode2022/Day7.kt
mathstar
569,952,400
false
{"Kotlin": 77567}
package com.staricka.adventofcode2022 import kotlin.math.min class Day7 : Day { override val id = 7 enum class FileType { DIRECTORY, REGULAR_FILE } interface File { val fileType: FileType val name: String val size: Int } data class Directory(override val name: String, val parent: Directory? = null) : File { override val fileType = FileType.DIRECTORY val children = HashMap<String, File>() override val size: Int get() = children.values.sumOf { it.size } } data class RegularFile(override val name: String, override val size: Int) : File { override val fileType = FileType.REGULAR_FILE } private val rootCdRegex = Regex("""\$ cd /""") private val upCdRegex = Regex("""\$ cd \.\.""") private val cdRegex = Regex("""\$ cd (.+)""") private val lsRegex = Regex("""\$ ls""") private val dirRegex = Regex("dir (.+)") private val fileRegex = Regex("([0-9]+) (.+)") private fun parseFileSystem(input: String): Directory { val root = Directory("/") var pwd = root input.lines().forEach {line -> if (rootCdRegex.matches(line)) { pwd = root } else if (upCdRegex.matches(line)) { pwd = pwd.parent!! } else if (cdRegex.matches(line)) { pwd = pwd.children[cdRegex.matchEntire(line)!!.groups[1]!!.value] as Directory } else if (lsRegex.matches(line)) { // noop } else if (dirRegex.matches(line)) { val match = dirRegex.matchEntire(line) pwd.children[match!!.groups[1]!!.value] = Directory(match.groups[1]!!.value, pwd) } else if (fileRegex.matches(line)) { val match = fileRegex.matchEntire(line) pwd.children[match!!.groups[2]!!.value] = RegularFile(match.groups[2]!!.value, match.groups[1]!!.value.toInt()) } } return root } private fun walkFileSystemDirectories(root: Directory, action: (Directory) -> Unit) { action(root) for (file in root.children.values) { if (file.fileType == FileType.DIRECTORY) { walkFileSystemDirectories(file as Directory, action) } } } override fun part1(input: String): Any { val fileSystem = parseFileSystem(input) var sum = 0 walkFileSystemDirectories(fileSystem) { if (it.size <= 100000) sum += it.size } return sum } override fun part2(input: String): Any { val fileSystem = parseFileSystem(input) var candidateSize = Int.MAX_VALUE val neededSpace = 30000000 - (70000000 - fileSystem.size) walkFileSystemDirectories(fileSystem) { if (it.size >= neededSpace) candidateSize = min(candidateSize, it.size) } return candidateSize } }
0
Kotlin
0
0
2fd07f21348a708109d06ea97ae8104eb8ee6a02
2,659
adventOfCode2022
MIT License
2022/03/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 = "2022/03/input.txt" fun main() { partOne() partTwo() } private fun partOne() { val file = File(FILENAME).readLines() var sum = 0 for (line in file) { val half = line.length / 2 val first = line.slice(0 until half) val second = line.slice(half until line.length) val firstMap = first.groupingBy { it }.eachCount() val secondMap = second.groupingBy { it }.eachCount() for (i in firstMap) { if (secondMap[i.key] != null) { sum += if (i.key in 'a'..'z') { i.key.code - 96 } else { i.key.code - 38 } } } } println(sum) } private fun partTwo() { val file = File(FILENAME).readLines() var sum = 0 for (index in file.indices step 3) { for (element in file[index]) { if (file[index + 1].contains(element) && file[index + 2].contains(element)) { sum += if (element in 'a'..'z') { element.code - 96 } else { element.code - 38 } break } } } println(sum) }
0
Kotlin
0
0
c9cba875089d8d4fb145932c45c2d487ccc7e8e5
1,265
Advent-of-Code
MIT License
2021/src/main/kotlin/org/suggs/adventofcode/Day06LanternFish.kt
suggitpe
321,028,552
false
{"Kotlin": 156836}
package org.suggs.adventofcode object Day06LanternFish { fun calculateNumberOfFishFrom(verySmallDataSet: List<Int>): FishCounter { return FishCounter(verySmallDataSet) } } /** * Summary of the algo: * 1. Don't try and calculate each fish ... there are 9 variants so pre-calc them * 2. Optimise the calculation by using subtraction and count additions rather than actually creating the fish and recursing */ class FishCounter(private val dataSet: List<Int>) { companion object { private const val MAX_FISH = 8 } fun after(days: Int) = countAllTheFishProduced(dataSet, calculateVariantCountsIntoMap(days)) private fun countAllTheFishProduced(dataSet: List<Int>, variants: Map<Int, Long>) = dataSet.map { variants[it] }.sumOf { it!! } private fun calculateVariantCountsIntoMap(days: Int) = (0..MAX_FISH).associateWith { countFishProducedFrom(it, days) } private fun countFishProducedFrom(fish: Int, days: Int): Long { return when { (days - fish > 0) -> countFishProducedFrom(6, days - fish - 1) + countFishProducedFrom(8, days - fish - 1) else -> 1 } } }
0
Kotlin
0
0
9485010cc0ca6e9dff447006d3414cf1709e279e
1,180
advent-of-code
Apache License 2.0
src/Day04.kt
karloti
573,006,513
false
{"Kotlin": 25606}
fun main() { fun Sequence<String>.splitBounds() = map { it.split('-', ',').map(String::toInt) } fun part1(input: Sequence<String>): Int = input.splitBounds().count { (a, b, c, d) -> (a <= c) && (b >= d) || (a >= c) && (b >= d) } fun part2(input: Sequence<String>): Int = input.splitBounds().count { (a, b, c, d) -> a <= d && c <= b } check(part1(readInputAsSequence("Day04_test")) == 2) check(part2(readInputAsSequence("Day04_test")) == 4) println(part1(readInputAsSequence("Day04"))) println(part2(readInputAsSequence("Day04"))) check(part1(readInputAsSequence("Day04")) == 580) check(part2(readInputAsSequence("Day04")) == 895) }
0
Kotlin
1
2
39ac1df5542d9cb07a2f2d3448066e6e8896fdc1
688
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/leetcode/Problem1604.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/ */ class Problem1604 { fun alertNames(keyName: Array<String>, keyTime: Array<String>): List<String> { val map = mutableMapOf<String, MutableList<String>>() for (i in keyName.indices) { val times = map[keyName[i]] ?: mutableListOf() times += keyTime[i] map[keyName[i]] = times } val answer = mutableListOf<String>() for ((key, value) in map) { var i = 0 value.sort() while (i < value.size - 2) { val t = difference(value[i], value[i + 1]) + difference(value[i + 1], value[i + 2]) if (t <= 60) { answer += key break } i++ } } answer.sort() return answer } private fun difference(from: String, to: String): Int { val (fromHour, fromMinute) = from.split(":") val (toHour, toMinute) = to.split(":") val minute = toMinute.toInt() - fromMinute.toInt() val hour = (toHour.toInt() - fromHour.toInt()) * 60 return minute + hour } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,255
leetcode
MIT License
src/Day10.kt
MickyOR
578,726,798
false
{"Kotlin": 98785}
import java.lang.Math.abs fun main() { fun part1(input: List<String>): Int { var cycle = 0; var neededCycles = listOf<Int>(20, 60, 100, 140, 180, 220); var x = 1; var ans = 0; for (line in input) { var vs = line.split(" "); if (vs[0] == "noop") { cycle++; if (cycle in neededCycles) { ans += x * cycle; } continue; } else { var delta = vs[1].toInt(); cycle++; if (cycle in neededCycles) { ans += x * cycle; } cycle++; if (cycle in neededCycles) { ans += x * cycle; } x += delta; } } return ans; } fun part2(input: List<String>) { var cycle = 0; var x = 1; var row = 0; var ans: String = ""; for (line in input) { var vs = line.split(" "); if (vs[0] == "noop") { cycle++; if (cycle == 41) { cycle = 1; row++; } if (abs(ans.length - row * 40 - x) <= 1) ans += '\u2588'; else ans += ' '; continue; } var delta = vs[1].toInt(); cycle++; if (cycle == 41) { cycle = 1; row++; } if (abs(ans.length - row * 40 - x) <= 1) ans += '\u2588'; else ans += ' '; cycle++; if (cycle == 41) { cycle = 1; row++; } if (abs(ans.length - row * 40 - x) <= 1) ans += '\u2588'; else ans += ' '; x += delta; } for (i in ans.indices step 40) { println(ans.substring(i, i + 40)); } } val input = readInput("Day10") part1(input).println() part2(input).println() }
0
Kotlin
0
0
c24e763a1adaf0a35ed2fad8ccc4c315259827f0
2,091
advent-of-code-2022-kotlin
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day10/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day10 fun launchDay10(testCase: String) { val env = readEnv(testCase) ensureStart(env) println("Day 10, part 1: ${calcPart1(env)}") println("Day 10, part 2: ${calcPart2(env)}") } private fun calcPart2(env: Env): Int { val flood = cleanDebris(env) for (row in 0..<env.grid.size) { var fill = false for (col in 0..<env.grid.first().size) { val x = env.grid[row][col].x if (x == '-') { continue } if (x == '.' && fill) { flood[row][col] = true continue } if (x == '|' || x == 'F' || x == '7') { fill = !fill continue } } } return flood.fold(0) { acc, row -> acc + row.filter { it }.size } } private fun cleanDebris(env: Env): MutableList<MutableList<Boolean>> { val walked = calcWalkedSet(env) val flood = mutableListOf<MutableList<Boolean>>() for (row in 0..<env.grid.size) { val items = mutableListOf<Boolean>() for (col in 0..<env.grid.first().size) { items.add(false) val pos = Pos(row, col) if (pos in walked) continue env.grid[row][col] = Pipe.BLANK } flood.add(items) } return flood } private fun calcWalkedSet(env: Env): Set<Pos> { val hist = Pair(mutableSetOf(env.pos), mutableSetOf(env.pos)) var pos = findStarts(env) do { hist.first.add(pos.first) hist.second.add(pos.second) pos = Pair( walk(pos.first, hist.first, env.grid), walk(pos.second, hist.second, env.grid) ) } while (hist.first.intersect(hist.second).size == 1) return hist.first + hist.second } private fun calcPart1(env: Env): Int { val hist = Pair(mutableSetOf(env.pos), mutableSetOf(env.pos)) var pos = findStarts(env) var step = 0 do { hist.first.add(pos.first) hist.second.add(pos.second) pos = Pair( walk(pos.first, hist.first, env.grid), walk(pos.second, hist.second, env.grid) ) step++ } while (hist.first.intersect(hist.second).size == 1) return step } private fun walk(p: Pos, h: Hist, g: Grid): Pos { val d = g[p.row][p.col] return when (d) { Pipe.WEST_EAST -> { val p1 = p.copy(col = p.col - 1) val p2 = p.copy(col = p.col + 1) if (p1 in h) p2 else p1 } Pipe.NORTH_SOUTH -> { val p1 = p.copy(row = p.row - 1) val p2 = p.copy(row = p.row + 1) if (p1 in h) p2 else p1 } Pipe.NORTH_WEST -> { val p1 = p.copy(row = p.row - 1) val p2 = p.copy(col = p.col - 1) if (p1 in h) p2 else p1 } Pipe.SOUTH_WEST -> { val p1 = p.copy(row = p.row + 1) val p2 = p.copy(col = p.col - 1) if (p1 in h) p2 else p1 } Pipe.NORTH_EAST -> { val p1 = p.copy(row = p.row - 1) val p2 = p.copy(col = p.col + 1) if (p1 in h) p2 else p1 } Pipe.SOUTH_EAST -> { val p1 = p.copy(row = p.row + 1) val p2 = p.copy(col = p.col + 1) if (p1 in h) p2 else p1 } else -> throw Exception("Invalid state, cannot progress/walk a position") } } private fun findStarts(e: Env): Pair<Pos, Pos> { val p = e.pos val d = e.grid[p.row][p.col] if (d == Pipe.WEST_EAST) return Pair(p.copy(col = p.col - 1), p.copy(col = p.col + 1)) if (d == Pipe.NORTH_SOUTH) return Pair(p.copy(row = p.row - 1), p.copy(row = p.row + 1)) if (d == Pipe.NORTH_WEST) return Pair(p.copy(row = p.row - 1), p.copy(col = p.col - 1)) if (d == Pipe.SOUTH_WEST) return Pair(p.copy(row = p.row + 1), p.copy(col = p.col - 1)) if (d == Pipe.NORTH_EAST) return Pair(p.copy(row = p.row - 1), p.copy(col = p.col + 1)) if (d == Pipe.SOUTH_EAST) return Pair(p.copy(row = p.row + 1), p.copy(col = p.col + 1)) throw Exception("Invalid state, cannot find the pair of starts") } private fun ensureStart(e: Env) { val north = if (e.pos.row == 0) Pipe.BLANK else e.grid[e.pos.row - 1][e.pos.col] val south = if (e.pos.row == e.grid.size - 1) Pipe.BLANK else e.grid[e.pos.row + 1][e.pos.col] val west = if (e.pos.col == 0) Pipe.BLANK else e.grid[e.pos.row][e.pos.col - 1] val east = if (e.pos.col == e.grid[0].size) Pipe.BLANK else e.grid[e.pos.row][e.pos.col + 1] e.grid[e.pos.row][e.pos.col] = ensureStartEx(north, south, west, east) } private fun ensureStartEx(north: Pipe, south: Pipe, west: Pipe, east: Pipe): Pipe { val n = north in arrayOf(Pipe.NORTH_SOUTH, Pipe.SOUTH_WEST, Pipe.SOUTH_EAST) val s = south in arrayOf(Pipe.NORTH_SOUTH, Pipe.NORTH_WEST, Pipe.NORTH_EAST) val w = west in arrayOf(Pipe.WEST_EAST, Pipe.NORTH_EAST, Pipe.SOUTH_EAST) val e = east in arrayOf(Pipe.WEST_EAST, Pipe.NORTH_WEST, Pipe.SOUTH_WEST) if (n && s) return Pipe.NORTH_SOUTH if (w && e) return Pipe.WEST_EAST if (n && w) return Pipe.NORTH_WEST if (n && e) return Pipe.NORTH_EAST if (s && w) return Pipe.SOUTH_WEST if (s && e) return Pipe.SOUTH_EAST throw Exception("Invalid state, cannot ensure the start") } private fun readEnv(testCase: String): Env { val reader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() ?: throw Exception("Invalid state, cannot read the input") val result = Env(pos = Pos(-1, -1)) var row = 0 while (true) { val rawLine = reader.readLine() ?: break result.grid.add(rawLine.mapIndexed { col, it -> val pipe = Pipe.fromChar(it) if (pipe == Pipe.START) result.pos = Pos(row, col) pipe }.toMutableList()) row++ } return result } private enum class Pipe(val v: Byte, val x: Char) { NORTH_SOUTH('|'.code.toByte(), '|'), // 124 WEST_EAST('-'.code.toByte(), '-'), // 45 NORTH_EAST('L'.code.toByte(), 'L'), // 76 NORTH_WEST('J'.code.toByte(), 'J'), // 74 SOUTH_WEST('7'.code.toByte(), '7'), // 55 SOUTH_EAST('F'.code.toByte(), 'F'), // 70 BLANK('.'.code.toByte(), '.'), // 46 START('S'.code.toByte(), 'S'); // 83 companion object { private val values = entries fun fromChar(v: Char) = values.firstOrNull { it.v == v.code.toByte() } ?: throw Exception("Invalid state, cannot parse a pipe") } } private data class Pos(val row: Int = 0, val col: Int = 0) private data class Env(val grid: Grid = mutableListOf(), var pos: Pos = Pos()) private typealias Grid = MutableList<MutableList<Pipe>> private typealias Hist = MutableSet<Pos>
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
6,800
advent-of-code-2023
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year19/Day15.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year19 import com.grappenmaker.aoc.* import com.grappenmaker.aoc.year19.MazeEntity.* import com.grappenmaker.aoc.Direction.* fun PuzzleSet.day15() = puzzle(15) { val pc = startComputer(input) fun Direction.asLong() = when (this) { UP -> 1L DOWN -> 2L LEFT -> 3L RIGHT -> 4L } fun getResponse(command: Direction): Long { pc.addInput(command.asLong()) return pc.stepUntilOutput() } fun generate( curr: Point = Point(0, 0), acc: HashMap<Point, MazeEntity> = hashMapOf() ): HashMap<Point, MazeEntity> { curr.adjacentSidesInf().filter { it !in acc }.forEach { adj -> val dir = curr.deltaDir(adj) val res = getResponse(dir) if (res == 0L) acc[adj] = WALL else { acc[adj] = if (res == 2L) OXYGEN else NOTHING generate(adj, acc) getResponse(-dir) } } return acc } val graph = generate() val target = graph.entries.first { (_, v) -> v == OXYGEN }.key val neighs: (Point) -> Iterable<Point> = { it.adjacentSidesInf().filter { p -> graph[p] != WALL } } partOne = bfsDistance(Point(0, 0), { it == target }, neighs).dist.s() partTwo = fillDistance(target, neighs).values.max().s() } enum class MazeEntity { WALL, OXYGEN, NOTHING }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,406
advent-of-code
The Unlicense
src/main/kotlin/icu/trub/aoc/day07/Hand.kt
dtruebin
728,432,747
false
{"Kotlin": 76202}
package icu.trub.aoc.day07 data class Hand(val cards: List<Card>) : Comparable<Hand> { val type: HandType get() = with(cards.groupingBy { it }.eachCount()) { if (containsKey(Card.CJJ)) { val jokerCount = this[Card.CJJ] when { containsValue(5) -> HandType.FIVE_OF_A_KIND containsValue(4) && jokerCount == 1 -> HandType.FIVE_OF_A_KIND containsValue(3) && jokerCount == 2 -> HandType.FIVE_OF_A_KIND containsValue(2) && jokerCount == 3 -> HandType.FIVE_OF_A_KIND jokerCount == 4 -> HandType.FIVE_OF_A_KIND containsValue(4) -> HandType.FOUR_OF_A_KIND containsValue(3) && jokerCount == 1 -> HandType.FOUR_OF_A_KIND count { it.value == 2 } == 2 && jokerCount == 2 -> HandType.FOUR_OF_A_KIND jokerCount == 3 -> HandType.FOUR_OF_A_KIND containsValue(3) && containsValue(2) -> HandType.FULL_HOUSE count { it.value == 2 } == 2 && jokerCount == 1 -> HandType.FULL_HOUSE containsValue(3) -> HandType.THREE_OF_A_KIND containsValue(2) && jokerCount == 1 -> HandType.THREE_OF_A_KIND jokerCount == 2 -> HandType.THREE_OF_A_KIND else -> HandType.ONE_PAIR } } else when { containsValue(5) -> HandType.FIVE_OF_A_KIND containsValue(4) -> HandType.FOUR_OF_A_KIND containsValue(3) && containsValue(2) -> HandType.FULL_HOUSE containsValue(3) -> HandType.THREE_OF_A_KIND count { it.value == 2 } == 2 -> HandType.TWO_PAIR containsValue(2) -> HandType.ONE_PAIR else -> HandType.HIGH_CARD } } override fun compareTo(other: Hand): Int = when { this.type != other.type -> this.type.compareTo(other.type) else -> this.cards.compareTo(other.cards) } companion object { fun parse(line: String, withJokers: Boolean = false): Hand = Hand( line.map { "C$it" }.map { Card.valueOf(it) }.map { when (it == Card.CJ && withJokers) { true -> Card.CJJ false -> it } } ) } } private operator fun List<Card>.compareTo(other: List<Card>): Int = this.zip(other).map { pair -> pair.first.compareTo(pair.second) }.firstOrNull { it != 0 } ?: 0
0
Kotlin
0
0
1753629bb13573145a9781f984a97e9bafc34b6d
2,566
advent-of-code
MIT License
2022/src/Day05.kt
Saydemr
573,086,273
false
{"Kotlin": 35583, "Python": 3913}
package src import java.util.Stack fun main() { fun part2(input: List<String>): String { val stackIndex = input.indexOfFirst { it.isEmpty() } val stackInput = input.subList(0, stackIndex-1) val numStacks = input.subList(stackIndex-1, stackIndex) .map { it.replace(" ", "") .trim() .replace(" ", ",") }[0] .split(",") .map { it.toInt() } .last() val mutableList = mutableListOf<Stack<Char>>() val stack = stackInput.reversed() .asSequence() .map { it.replace("] ", "]") .replace("]", "") .replace("[","") } .toMutableList() for (i in 0 until numStacks) { mutableList.add(Stack()) } for (i in 0 until stack.size) { for (j in 0 until stack[i].length) { mutableList[j].push(stack[i][j]) } } mutableList.forEach { it.removeAll {it2 -> it2 == ' '} } val moves = input.subList(stackIndex+1, input.size) .map { it.split(" ") } .map { Triple(it[1].toInt(), it[3].toInt(), it[5].toInt() ) } for (i in moves.indices) { val (num, from, to) = moves[i] val fromStack = mutableList[from-1] val toStack = mutableList[to-1] val order = mutableListOf<Char>() for (j in 0 until num) { order.add(fromStack.pop()) } order.reversed() .toMutableList() .forEach { toStack.push(it) } } return mutableList.map { it.peek().toString() } .joinToString { it } .replace(", ", "") } fun part1(input: List<String>): String { val stackIndex = input.indexOfFirst { it.isEmpty() } val stackInput = input.subList(0, stackIndex - 1) val numStacks = input.subList(stackIndex - 1, stackIndex) .map { it.replace(" ", "") .trim() .replace(" ", ",") }[0] .split(",") .map { it.toInt() }.last() val mutableList = mutableListOf<Stack<Char>>() val stack = stackInput.reversed() .asSequence() .map { it.replace("] ", "]") .replace("]", "") .replace("[", "") } .toMutableList() for (i in 0 until numStacks) { mutableList.add(Stack()) } for (i in 0 until stack.size) { for (j in 0 until stack[i].length) { mutableList[j].push(stack[i][j]) } } mutableList.forEach { it.removeAll {it2 -> it2 == ' '} } val moves = input.subList(stackIndex + 1, input.size) .map { it.split(" ") } .map { Triple(it[1].toInt(), it[3].toInt(), it[5].toInt()) } for (i in moves.indices) { val (num, from, to) = moves[i] val fromStack = mutableList[from - 1] val toStack = mutableList[to - 1] for (j in 0 until num) { toStack.push(fromStack.pop()) } } return mutableList.map { it.peek().toString() } .joinToString { it } .replace(", ", "") } val input = readInput("input5") val less = parseDay05Input(input) println(part1(less)) println(part2(less)) }
0
Kotlin
0
1
25b287d90d70951093391e7dcd148ab5174a6fbc
3,525
AoC
Apache License 2.0
src/main/kotlin/search/BinarySearch.kt
alexiscrack3
310,484,737
false
{"Kotlin": 44433}
package search class BinarySearch { fun binarySearch(arr: IntArray, l: Int, r: Int, key: Int): Int { if (r < l) return -1 val mid = (l + r) / 2 if (key == arr[mid]) { return mid } return if (key > arr[mid]) { binarySearch(arr, mid + 1, r, key) } else { binarySearch(arr, l, mid - 1, key) } } fun pivotedBinarySearch(array: IntArray, n: Int, value: Int): Int { val pivot = findPivot(array, 0, n - 1) // If we didn't find a pivot, then // array is not rotated at all if (pivot == -1) { return binarySearch(array, 0, n - 1, value) } // If we found a pivot, then first // compare with pivot and then // search in two subarrays around pivot if (array[pivot] == value) { return pivot } return if (array[0] <= value) { binarySearch(array, 0, pivot - 1, value) } else { binarySearch(array, pivot + 1, n - 1, value) } } /* Function to get pivot. For array 3, 4, 5, 6, 1, 2 it returns 3 (index of 6) */ fun findPivot(arr: IntArray, l: Int, r: Int): Int { // base cases if (r < l) { return -1 } if (r == l) { return l } /* low + (high - low)/2; */ val mid = (l + r) / 2 if (mid < r && arr[mid] > arr[mid + 1]) { return mid } if (mid > l && arr[mid] < arr[mid - 1]) { return mid - 1 } return if (arr[l] >= arr[mid]) { findPivot(arr, l, mid - 1) } else { findPivot(arr, mid + 1, r) } } }
0
Kotlin
0
0
a2019868ece9ee319d08a150466304bfa41a8ad3
1,754
algorithms-kotlin
MIT License
2023/src/main/kotlin/de/skyrising/aoc2023/day14/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2023.day14 import de.skyrising.aoc.* import it.unimi.dsi.fastutil.ints.IntArrayList import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap inline fun CharGrid.shift(i: Int, range: IntProgression, rocks: Int, sett: CharGrid.(Int,Int,Char)->Unit) { var r = rocks val dist = (if (range.step > 0) range.last - range.first else range.first - range.last) + 1 if (rocks > 0 && dist > 0 && rocks != dist) { for (j1 in range) { sett(i, j1, if (r-- > 0) 'O' else '.') } } } inline fun CharGrid.slide(iterI: IntProgression, iterJ: IntProgression, gett: CharGrid.(Int, Int)->Char, sett: CharGrid.(Int, Int, Char)->Unit) { for (i in iterI) { var start = iterJ.first var rocks = 0 for (j in iterJ) { when(gett(i, j)) { '#' -> { shift(i, IntProgression.fromClosedRange(start, j - iterJ.step, iterJ.step), rocks, sett) rocks = 0 start = j + iterJ.step } 'O' -> rocks++ } } shift(i, IntProgression.fromClosedRange(start, iterJ.last, iterJ.step), rocks, sett) } } fun CharGrid.slideNorth() { slide(0 until width, 0 until height, CharGrid::get, CharGrid::set) } fun CharGrid.slideWest() { slide(0 until height, 0 until width, CharGrid::getT, CharGrid::setT) } fun CharGrid.slideSouth() { slide(0 until width, (0 until height).reversed(), CharGrid::get, CharGrid::set) } fun CharGrid.slideEast() { slide(0 until height, (0 until width).reversed(), CharGrid::getT, CharGrid::setT) } val test = TestInput(""" O....#.... O.OO#....# .....##... OO.#O....O .O.....O#. O.#..O.#.# ..O..#O..O .......O.. #....###.. #OO..#.... """) val test2 = TestInput(""" .#. .O. ... """) @PuzzleName("Parabolic Reflector Dish") fun PuzzleInput.part1(): Any { val grid = charGrid grid.slideNorth() return grid.sumOf { if (it.charValue == 'O') grid.height - it.key.y else 0 } } fun PuzzleInput.part2(): Any { val grid = charGrid val limit = 1_000_000_000 val grids = IntArrayList() val indexes = Object2IntOpenHashMap<String>().apply { defaultReturnValue(-1) } for (i in 1 .. limit) { var sum = 0 grid.forEach { _, y, c -> if (c == 'O') sum += grid.height - y } grids.add(sum) grid.slideNorth() grid.slideWest() grid.slideSouth() grid.slideEast() val previous = indexes.putIfAbsent(String(grid.data), i) if (previous >= 0) return grids.getInt( previous + (limit - i) % (i - previous)) } error("Expected cycle") }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
2,713
aoc
MIT License
src/Day10.kt
spaikmos
573,196,976
false
{"Kotlin": 83036}
fun main() { fun part1(input: List<String>): Int { var tick = 1 var x = 1 var score = 0 val signal = setOf(20, 60, 100, 140, 180, 220) for (i in input) { // Whether nop or addx, increment the tick and calculate the score tick++ if (signal.contains(tick)) { score += x * tick } if (i.contains("addx")) { x += i.split(' ')[1].toInt() tick++ if (signal.contains(tick)) { score += x * tick } } } return score } fun part2(input: List<String>): Int { val crt = Array(6){ CharArray(40){'.'} } var tick = 0 var x = 1 for (i in input) { if (tick.mod(40) in (x-1)..(x+1)) { crt[tick / 40][tick.mod(40)] = '#' } tick++ if (i.contains("addx")) { if (tick.mod(40) in (x-1)..(x+1)) { crt[tick / 40][tick.mod(40)] = '#' } x += i.split(' ')[1].toInt() tick++ } } for (i in crt) { println(String(i)) } return 0 } val input = readInput("../input/Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6fee01bbab667f004c86024164c2acbb11566460
1,379
aoc-2022
Apache License 2.0
src/main/kotlin/com/sk/leetcode/kotlin/189. Rotate Array.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.leetcode.kotlin class Solution189 { // time-O(n*k); n is size of array fun rotate(nums: IntArray, k: Int) { var count = k % nums.size repeat(count) { val last = nums.last() for (j in nums.lastIndex downTo 1) { nums[j] = nums[j - 1] } nums[0] = last } } // time-O(n), space-O(n); n is size of array fun rotate2(nums: IntArray, k: Int) { val arr = IntArray(nums.size) for (i in nums.indices) { arr[(i + k) % nums.size] = nums[i] } for (i in arr.indices) { nums[i] = arr[i] } } fun rotate3(nums: IntArray, k: Int) { if (k == 0) return val rotation = k % nums.size var swap = 0 var startIdx = 0 while (startIdx < nums.size) { var currIdx = startIdx var prev = nums[startIdx] do { val nextIdx = (currIdx + rotation) % nums.size val temp = nums[nextIdx] nums[nextIdx] = prev prev = temp currIdx = nextIdx swap++ if (swap == nums.size) return } while (startIdx != currIdx) startIdx++ } } // time-O(n), space-O(1); n is size of array fun rotate4(nums: IntArray, k: Int) { val rotation = k % nums.size reverseInRange(nums, 0, nums.size - 1) reverseInRange(nums, 0, rotation - 1) reverseInRange(nums, rotation, nums.size - 1) } fun reverseInRange(nums: IntArray, start: Int, end: Int) { var l = start var r = end while (l < r) { nums[l] = nums[r].also { nums[r] = nums[l] } l++ r-- } } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,828
leetcode-kotlin
Apache License 2.0
src/main/kotlin/realjenius/evernote/noteslurp/evernote/TagStrategies.kt
realjenius
179,378,196
false
{"Kotlin": 48752}
package realjenius.evernote.noteslurp.evernote import realjenius.evernote.noteslurp.KeywordTag import realjenius.evernote.noteslurp.KeywordType import realjenius.evernote.noteslurp.TagConfig import java.nio.file.Path import java.nio.file.Paths data class TagContext(val rootDir: Path = Path.of("/"), val filePath: Path = Path.of("/"), val textContent: String = "") interface TagStrategy { fun findTags(ctx: TagContext): Set<String> companion object { fun forConfig(config: TagConfig): List<TagStrategy> { val keywords = if (config.keywords.isNotEmpty()) KeywordStrategy(config.keywords) else null val list = arrayListOf<TagStrategy>() if (config.folderTags) list.add(FolderStrategy(keywords)) if (keywords != null) list.add(keywords) return list } } } class KeywordStrategy(keywords: List<KeywordTag>) : TagStrategy { private val matchers: List<KeywordMatcher> = keywords.map { if (it.type == KeywordType.Regex) RegexMatcher(it.mapping, it.target) else TextMatcher(it.mapping, it.target) } override fun findTags(ctx: TagContext): Set<String> = matchers .map { it.findTag(ctx.textContent) } .filter { it != null } .filterNotNull().toSet() } private interface KeywordMatcher { fun findTag(input: String): String? } private class RegexMatcher(search: String, private val target: String) : KeywordMatcher { private val regex: Regex = Regex(search) override fun findTag(input: String): String? { val matcher = regex.toPattern().matcher(input) val groups = matcher.groupCount() return if (matcher.find()) { if (groups == 0) target else (0 until groups).fold(target) { acc, it -> acc.replace(oldValue = "{$it}", newValue = matcher.group(it + 1)) } } else null } } private class TextMatcher(private val search: String, private val target: String) : KeywordMatcher { override fun findTag(input: String) : String? { val at = input.indexOf(string = search, ignoreCase = true) return if (at >= 0) { val startsClean = at == 0 || isAllowedBoundary(input[at - 1]) val endsClean = at + search.length >= input.length || isAllowedBoundary(input[at + search.length]) if (startsClean && endsClean) target else null } else null } private fun isAllowedBoundary(char: Char) = !BOUNDARY_REGEX.matches("$char") companion object { private val BOUNDARY_REGEX = Regex("[a-zA-Z0-9]") } } class FolderStrategy(private val keywords: KeywordStrategy?) : TagStrategy { override fun findTags(ctx: TagContext) = findTagNext(ctx.rootDir, ctx.filePath).let { if (keywords != null) it.flatMap { tag -> keywords.findTags(ctx.copy(textContent = tag)) } else it }.toSet() private fun findTagNext(rootDir: Path, path: Path): MutableList<String> = if (path.parent == rootDir || path.parent == null) arrayListOf() else findTagNext(rootDir, path.parent).apply { add(path.parent.fileName.toString()) } }
0
Kotlin
0
2
324d809b84e9d70521422db3e969ed4b2f640dc1
2,968
noteslurp
Apache License 2.0
src/main/kotlin/Day8.kt
corentinnormand
725,992,109
false
{"Kotlin": 40576}
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking fun main(args: Array<String>) { Day8().two() } class Day8 : Aoc("day8.txt") { val test = """ LR 11A = (11B, XXX) 11B = (XXX, 11Z) 11Z = (11B, XXX) 22A = (22B, XXX) 22B = (22C, 22C) 22C = (22Z, 22Z) 22Z = (22B, 22B) XXX = (XXX, XXX) """.trimIndent().lines() override fun one() { val input = readFile("day8.txt").lines() val directions = input[0].toList() val instructions = input.subList(2, input.size) .map { it.split(" = ") } .associate { val a = """[A-Z]{3}""".toRegex().findAll(it[1]) .map { res -> res.value } .toList() Pair(it[0], Pair(a[0], a[1])) } var value = "AAA" var steps = 0 while (value != "ZZZ") { for (d in directions) { val pair = instructions.get(value) value = if (d == 'L') pair!!.first else pair!!.second steps++ } } println(steps) } override fun two() { val input = readFile("day8.txt").lines() val directions = input[0].toList() val instructions = input.subList(2, input.size) .map { it.split(" = ") } .associate { val a = """[1-9A-Z]{3}""".toRegex().findAll(it[1]) .map { res -> res.value } .toList() Pair(it[0], Pair(a[0], a[1])) } val values = instructions.filterKeys { it.last() == 'A' }.keys fun getSteps(value: String): Long { var steps = 0L var tmp = value while (tmp.last() != 'Z') { for (d in directions) { val pair = instructions.get(tmp) tmp = if (d == 'L') pair!!.first else pair!!.second steps++ } } return steps } fun gcd(a: Long, b: Long): Long { var a1: Long = a var b1: Long = b while (b1 != 0L) { val temp = b1; b1 = a1 % b1; a1 = temp; } return a1; } fun lcm(a: Long, b: Long): Long { return (a / gcd(a, b)) * b; } val reduce = values .map { getSteps(it) } .reduce { acc, l -> lcm(acc, l) } println(reduce) } }
0
Kotlin
0
0
2b177a98ab112850b0f985c5926d15493a9a1373
2,604
aoc_2023
Apache License 2.0
src/Day06.kt
Excape
572,551,865
false
{"Kotlin": 36421}
fun main() { fun findFirstDistinct(input: String, n: Int) = input.windowed(n).indexOfFirst { it.toSet().size == n } + n fun part1(input: String) = findFirstDistinct(input, 4) fun part2(input: String) = findFirstDistinct(input, 14) println(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb")) check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) val input = readInputAsString("Day06") println("part 1: ${part1(input)}") println("part 2: ${part2(input)}") }
0
Kotlin
0
0
a9d7fa1e463306ad9ea211f9c037c6637c168e2f
697
advent-of-code-2022
Apache License 2.0
src/main/kotlin/ca/warp7/frc/path/SplineOptimizer.kt
Team865
198,131,314
false
null
package ca.warp7.frc.path import ca.warp7.frc.geometry.* import kotlin.math.sqrt fun List<QuinticSegment2D>.sumDCurvature2(): Double = sumByDouble { segment -> (0 until 100).sumByDouble { segment[it / 100.0].dCurvatureSquared() } } fun fitParabola(p1: Translation2D, p2: Translation2D, p3: Translation2D): Double { val a = p3.x * (p2.y - p1.y) + p2.x * (p1.y - p3.y) + p1.x * (p3.y - p2.y) val b = p3.x * p3.x * (p1.y - p2.y) + p2.x * p2.x * (p3.y - p1.y) + p1.x * p1.x * (p2.y - p3.y) return -b / (2 * a) } fun List<QuinticSegment2D>.optimized(): List<QuinticSegment2D> = toMutableList().apply { optimize() } fun MutableList<QuinticSegment2D>.optimize() { var count = 0 var prev = sumDCurvature2() while (count < 100) { runOptimizationIteration() val current = sumDCurvature2() if (prev - current < 0.001) return prev = current count++ } } private class ControlPoint(var ddx: Double, var ddy: Double) fun QuinticSegment2D.getStartPose(): Pose2D { return Pose2D(Translation2D(x0, y0), Translation2D(dx0, dy0).direction()) } fun QuinticSegment2D.getEndPose(): Pose2D { return Pose2D(Translation2D(x1, y1), Translation2D(dx1, dy1).direction()) } fun QuinticSegment2D.updateD2End(ddx: Double, ddy: Double): QuinticSegment2D { return QuinticSegment2D( x0, x1, dx0, dx1, ddx0, ddx1 + ddx, y0, y1, dy0, dy1, ddy0, ddy1 + ddy ) } fun QuinticSegment2D.updateD2Start(ddx: Double, ddy: Double): QuinticSegment2D { return QuinticSegment2D( x0, x1, dx0, dx1, ddx0 + ddx, ddx1, y0, y1, dy0, dy1, ddy0 + ddy, ddy1 ) } private const val kEpsilon = 1E-5 private const val kStepSize = 1.0 fun MutableList<QuinticSegment2D>.runOptimizationIteration() { //can't optimize anything with less than 2 splines if (size <= 1) { return } val controlPoints = Array(size - 1) { ControlPoint(0.0, 0.0) } var magnitude = 0.0 for (i in 0 until size - 1) { //don't try to optimize co-linear points if (this[i].getStartPose().isColinear(this[i + 1].getStartPose()) || this[i].getEndPose().isColinear(this[i + 1].getEndPose())) continue val original = sumDCurvature2() val now = this[i] val next = this[i + 1] //calculate partial derivatives of sumDCurvature2 this[i] = now.copy(ddx1 = now.ddx1 + kEpsilon) this[i + 1] = next.copy(ddx0 = next.ddx0 + kEpsilon) controlPoints[i].ddx = (sumDCurvature2() - original) / kEpsilon this[i] = now.copy(ddy1 = now.ddy1 + kEpsilon) this[i + 1] = next.copy(ddy0 = next.ddy0 + kEpsilon) controlPoints[i].ddy = (sumDCurvature2() - original) / kEpsilon this[i] = now this[i + 1] = next magnitude += controlPoints[i].ddx * controlPoints[i].ddx + controlPoints[i].ddy * controlPoints[i].ddy } magnitude = sqrt(magnitude) //minimize along the direction of the gradient //first calculate 3 points along the direction of the gradient //middle point is at the current location val p2 = Translation2D(0.0, sumDCurvature2()) for (i in 0 until size - 1) { //first point is offset from the middle location by -stepSize if (this[i].getStartPose().isColinear(this[i + 1].getStartPose()) || this[i].getEndPose().isColinear(this[i + 1].getEndPose())) continue //normalize to step size controlPoints[i].ddx *= kStepSize / magnitude controlPoints[i].ddy *= kStepSize / magnitude //move opposite the gradient by step size amount //recompute the spline's coefficients to account for new second derivatives this[i] = this[i].updateD2End(-controlPoints[i].ddx, -controlPoints[i].ddy) this[i + 1] = this[i + 1].updateD2Start(-controlPoints[i].ddx, -controlPoints[i].ddy) } val p1 = Translation2D(-kStepSize, sumDCurvature2()) for (i in 0 until size - 1) { //last point is offset from the middle location by +stepSize if (this[i].getStartPose().isColinear(this[i + 1].getStartPose()) || this[i].getEndPose().isColinear(this[i + 1].getEndPose())) continue //move along the gradient by 2 times the step size amount (to return to original location and move by 1 // step) //recompute the spline's coefficients to account for new second derivatives this[i] = this[i].updateD2End(2 * controlPoints[i].ddx, 2 * controlPoints[i].ddy) this[i + 1] = this[i + 1].updateD2Start(2 * controlPoints[i].ddx, 2 * controlPoints[i].ddy) } val p3 = Translation2D(kStepSize, sumDCurvature2()) val stepSize = fitParabola(p1, p2, p3) //approximate step size to minimize sumDCurvature2 along the gradient for (i in 0 until size - 1) { if (this[i].getStartPose().isColinear(this[i + 1].getStartPose()) || this[i].getEndPose().isColinear(this[i + 1].getEndPose())) continue //move by the step size calculated by the parabola fit (+1 to offset for the final transformation to find // p3) controlPoints[i].ddx *= 1 + stepSize / kStepSize controlPoints[i].ddy *= 1 + stepSize / kStepSize //recompute the spline's coefficients to account for new second derivatives this[i] = this[i].updateD2End(controlPoints[i].ddx, controlPoints[i].ddy) this[i + 1] = this[i + 1].updateD2Start(controlPoints[i].ddx, controlPoints[i].ddy) } }
0
Kotlin
2
1
d65cc67eccd04fece3a1510094aa656628dce301
5,481
FRC-Commons-Kotlin
MIT License
src/main/kotlin/y2023/day05/Day05.kt
niedrist
726,105,019
false
{"Kotlin": 19919}
package y2023.day05 import BasicDay import util.FileReader import kotlin.math.min val d = FileReader.readResource("2023/day05.txt").split("\n\n") val seeds = d[0].split(":")[1].split(" ").filter { it != "" }.map { it.toLong() } fun String.toMapping() = this.split("\n").filter { it.first().isDigit() }.map { it.split(" ") } .map { Mapping(it[1].toLong(), it[0].toLong(), it[2].toLong()) } val mappings = List(7) { d[it + 1].toMapping() } fun main() = Day05.run() object Day05 : BasicDay() { override fun part1() = seeds.minOf { it.seedToLocation() } override fun part2(): Long { val allSeedRanges = seeds.chunked(2).map { it[0] until it[0] + it[1] } var min = Long.MAX_VALUE for (range in allSeedRanges) { range.forEach { min = min(min, it.seedToLocation()) } } return min } } fun Long.seedToLocation() = mappings.fold(this) { acc, m -> m.mapOnce(acc) } data class Mapping(val sourceStart: Long, val destinationStart: Long, val range: Long) fun List<Mapping>.mapOnce(n: Long): Long { return this.firstOrNull { n in it.sourceStart until (it.sourceStart + it.range) }?.let { it.destinationStart - it.sourceStart + n } ?: n }
0
Kotlin
0
1
37e38176d0ee52bef05f093b73b74e47b9011e24
1,247
advent-of-code
Apache License 2.0
AoC2021day11-DumboOctopus/src/main/kotlin/Main.kt
mcrispim
533,770,397
false
{"Kotlin": 29888}
import java.io.File const val LINES = 10 const val COLS = 10 const val STEPS = 100 fun main() { val input = File("data.txt").readLines() val grid = MutableList(LINES) { line -> MutableList(COLS) { col -> input[line][col].digitToInt() } } var nFlashes = 0 var totalFlashes = 0 var step = 0 while (nFlashes != LINES * COLS) { processStep(grid) step += 1 nFlashes = flashGrid(grid) totalFlashes += nFlashes if (step == STEPS) { println("In $STEPS steps ocurred $totalFlashes flashes.") } } println("All the octopus flashed at step $step.") } fun processStep(grid: MutableList<MutableList<Int>>) { for(l in grid.indices) { for (c in grid[l].indices) { increaseEnergy(grid, l, c) } } var flashed = true while (flashed) { flashed = false for (l in grid.indices) { for (c in grid[l].indices) { if (grid[l][c] > 9) { flashAndExpand(grid, l, c) flashed = true } } } } } fun increaseEnergy(grid: MutableList<MutableList<Int>>, l: Int, c: Int) { grid[l][c] = grid[l][c] + 1 } fun flashAndExpand(grid: MutableList<MutableList<Int>>, line: Int, col: Int) { grid[line][col] = -1 val cells = listOf( Pair(-1, -1), Pair(-1, 0), Pair(-1, 1), Pair( 0, -1), Pair( 0, 1), Pair( 1, -1), Pair( 1, 0), Pair( 1, 1)) for ((l, c) in cells) { if (line + l in 0 until LINES && col + c in 0 until COLS && grid[line + l][col + c] != -1) { increaseEnergy(grid, line + l, col + c) } } } fun flashGrid(grid: MutableList<MutableList<Int>>): Int { var flashes = 0 for(l in grid.indices) { for (c in grid[l].indices) { if (grid[l][c] == -1) { grid[l][c] = 0 flashes += 1 } } } return flashes }
0
Kotlin
0
0
ac4aa71c9b5955fa4077ae40fc7e3fc3d5242523
2,031
AoC2021
MIT License
src/day13/Main.kt
nikwotton
572,814,041
false
{"Kotlin": 77320}
package day13 import day13.Packet.List import day13.Packet.Number import java.io.File import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonPrimitive const val workingDir = "src/day13" fun main() { val sample = File("$workingDir/sample.txt") val input1 = File("$workingDir/input_1.txt") println("Step 1a: ${runStep1(sample)}") println("Step 1b: ${runStep1(input1)}") println("Step 2a: ${runStep2(sample)}") println("Step 2b: ${runStep2(input1)}") } sealed class Packet { data class List(val contents: MutableList<Packet>) : Packet() data class Number(val num: Int) : Packet() } typealias PacketPair = Pair<Packet, Packet> operator fun Packet.compareTo(other: Packet): Int { if (this is Number && other is Number) return this.num.compareTo(other.num) if (this is List && other is List) { (0 until maxOf(this.contents.size, other.contents.size)).forEach { try { if (this.contents[it] < other.contents[it]) return -1 if (this.contents[it] > other.contents[it]) return 1 } catch (e: IndexOutOfBoundsException) { if(this.contents.size < other.contents.size) return -1 if(this.contents.size > other.contents.size) return 1 } } return 0 } if (this is Number) return List(arrayListOf(this)).compareTo(other) if (other is Number) return this.compareTo(List(arrayListOf(other))) TODO() } val json by lazy { Json } fun JsonArray.toPacket(): Packet = List(map { try { it.jsonArray.toPacket() } catch (e: IllegalArgumentException) { Number(it.jsonPrimitive.int) } }.toMutableList()) fun String.toPacket(): Packet = json.decodeFromString<JsonArray>(this).toPacket() fun runStep1(input: File): String { val pairs = ArrayList<PacketPair>() input.readText().split("\n\n").forEach { val (p1, p2) = it.split("\n") pairs.add(Pair(p1.toPacket(), p2.toPacket())) } return pairs.mapIndexed { index, pair -> if (pair.first < pair.second) index+1 else -1 }.filter { it != -1 }.sum().toString() } fun runStep2(input: File): String { val decoderPackets = listOf("[[2]]", "[[6]]").map { it.toPacket() } return input.readLines() .filter { it.isNotBlank() } .map { it.toPacket() } .let { it + decoderPackets } .sortedWith { o1, o2 -> o1.compareTo(o2) } .let { list -> decoderPackets.map { list.indexOf(it)+1 }.fold(1) { acc, a, -> acc * a } }.toString() }
0
Kotlin
0
0
dee6a1c34bfe3530ae6a8417db85ac590af16909
2,741
advent-of-code-2022
Apache License 2.0
hierarchy/src/commonMain/kotlin/io/data2viz/hierarchy/treemap/Binary.kt
data2viz
89,368,762
false
null
/* * Copyright (c) 2018-2021. data2viz sàrl. * * 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 io.data2viz.hierarchy.treemap import io.data2viz.hierarchy.ParentValued import io.data2viz.hierarchy.TreemapNode public fun <D> treemapBinary(parent: ParentValued<TreemapNode<D>>, x0: Double, y0: Double, x1: Double, y1: Double): Unit = TreemapBinary<D>().binary(parent, x0, y0, x1, y1) /** * Recursively partitions the specified nodes into an approximately-balanced binary tree, choosing horizontal * partitioning for wide rectangles and vertical partitioning for tall rectangles. */ public class TreemapBinary<D> { public var nodes: MutableList<ParentValued<TreemapNode<D>>> = mutableListOf() public var sums: MutableList<Double> = mutableListOf() public fun binary(parent: ParentValued<TreemapNode<D>>, x0: Double, y0: Double, x1: Double, y1: Double) { nodes = parent.children.toMutableList() val size = nodes.size sums = MutableList(size + 1, { .0 }) var sum = .0 for (i in 0 until size) { sum += nodes[i].value!! sums[i + 1] = sum } partition(0, size, parent.value!!, x0, y0, x1, y1) } private fun partition(i: Int, j: Int, value: Double, x0: Double, y0: Double, x1: Double, y1: Double) { if (i >= j - 1) { val node = nodes[i] as TreemapNode node.x0 = x0 node.y0 = y0 node.x1 = x1 node.y1 = y1 return } val valueOffset = sums[i] val valueTarget = (value / 2) + valueOffset var k = i + 1 var hi = j - 1 while (k < hi) { val mid = (k + hi).ushr(1) // TODO raw conversion from JS : k + hi >>> 1... need explanation (unsigned right shift .... WHY ?) if (sums[mid] < valueTarget) k = mid + 1 else hi = mid } if ((valueTarget - sums[k - 1]) < (sums[k] - valueTarget) && i + 1 < k) --k val valueLeft = sums[k] - valueOffset val valueRight = value - valueLeft if ((x1 - x0) > (y1 - y0)) { val xk = (x0 * valueRight + x1 * valueLeft) / value partition(i, k, valueLeft, x0, y0, xk, y1) partition(k, j, valueRight, xk, y0, x1, y1) } else { val yk = (y0 * valueRight + y1 * valueLeft) / value partition(i, k, valueLeft, x0, y0, x1, yk) partition(k, j, valueRight, x0, yk, x1, y1) } } }
79
Kotlin
29
389
5640d3e8f1ce4cd4e5d651431726869e329520fc
3,021
data2viz
Apache License 2.0
project_euler_kotlin/src/main/kotlin/Solution0017.kt
NekoGoddessAlyx
522,068,054
false
{"Kotlin": 44135, "Rust": 24687}
class Solution0017 : Solution() { override fun solve(): String { return (1L..1000L) .sumOf { makeWordy(it).length.toLong() } .toString() } private val onesMap = mapOf( '0' to "zero", '1' to "one", '2' to "two", '3' to "three", '4' to "four", '5' to "five", '6' to "six", '7' to "seven", '8' to "eight", '9' to "nine" ) private val tensMap = mapOf( '0' to "", '1' to "", '2' to "twenty", '3' to "thirty", '4' to "forty", '5' to "fifty", '6' to "sixty", '7' to "seventy", '8' to "eighty", '9' to "ninety" ) private val teensMap = mapOf( '0' to "ten", '1' to "eleven", '2' to "twelve", '3' to "thirteen", '4' to "fourteen", '5' to "fifteen", '6' to "sixteen", '7' to "seventeen", '8' to "eighteen", '9' to "nineteen" ) /** Magically turns your number into words! Spaces and hyphens not included */ private fun makeWordy(n: Long): String { if (n !in 1 .. 1000) throw IllegalArgumentException("Number must be in range 1 <= n <= 1000") // thousands if (n == 1000L) return "onethousand" val digits = n.toString() var index = 0 val sb = StringBuilder() // hundreds if (n >= 100) { sb.append(onesMap[digits[0]]) sb.append("hundred") if (digits[1] != '0' || digits[2] != '0') sb.append("and") // this is for checking the tens place index++ } // tens if (n >= 10) { when (digits[index]) { '0' -> {} '1' -> { sb.append(teensMap[digits[index + 1]]) return sb.toString() } else -> sb.append(tensMap[digits[index]]) } index++ if (digits[index] == '0') return sb.toString() } // ones sb.append(onesMap[digits[index]]) return sb.toString() } }
0
Kotlin
0
0
f899b786d5ea5ffd79da51604dc18c16308d2a8a
2,201
Project-Euler
The Unlicense
2023/14/solve-2.kts
gugod
48,180,404
false
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
import java.io.File class Platform (val grid: List<List<Char>>) { val rowIndices = grid.indices val colIndices = grid[0].indices fun northTilted(): Platform { val newGrid = grid.map { it.toMutableList() } colIndices.forEach { x -> rowIndices.forEach { y -> if (newGrid[y][x] == '.') { val y2 = (y+1 .. rowIndices.last()).firstOrNull { newGrid[it][x] == 'O' || newGrid[it][x] == '#' } if (y2 != null && newGrid[y2][x] == 'O') { newGrid[y][x] = 'O' newGrid[y2][x] = '.' } } } } return Platform(newGrid) } fun southTilted(): Platform { val newGrid = grid.map { it.toMutableList() } colIndices.forEach { x -> rowIndices.reversed().forEach { y -> if (newGrid[y][x] == '.') { val y2 = (0 .. y-1).reversed().firstOrNull { newGrid[it][x] == 'O' || newGrid[it][x] == '#' } if (y2 != null && newGrid[y2][x] == 'O') { newGrid[y][x] = 'O' newGrid[y2][x] = '.' } } } } return Platform(newGrid) } fun eastTilted(): Platform { val newGrid = grid.map { it.toMutableList() } rowIndices.forEach { y -> colIndices.reversed().forEach { x -> if (newGrid[y][x] == '.') { val x2 = (0 .. x-1).reversed().firstOrNull { newGrid[y][it] == 'O' || newGrid[y][it] == '#' } if (x2 != null && newGrid[y][x2] == 'O') { newGrid[y][x] = 'O' newGrid[y][x2] = '.' } } } } return Platform(newGrid) } fun westTilted(): Platform { val newGrid = grid.map { it.toMutableList() } rowIndices.forEach { y -> colIndices.forEach { x -> if (newGrid[y][x] == '.') { val x2 = (x+1 .. colIndices.last()).firstOrNull { newGrid[y][it] == 'O' || newGrid[y][it] == '#' } if (x2 != null && newGrid[y][x2] == 'O') { newGrid[y][x] = 'O' newGrid[y][x2] = '.' } } } } return Platform(newGrid) } fun totalLoad(): Int { val rows = rowIndices.count() return rowIndices .map { y -> colIndices.filter { x -> grid[y][x] == 'O' }.count() * (rows - y) } .sum() } fun visual() { rowIndices.forEach { println(grid[it].joinToString("")) } println("") } } var initialLoads = mutableListOf<Int>() var p = Platform(File(args.getOrNull(0) ?: "input").readLines().map { it.toList() }) var cycles = 0 while (cycles++ < 1000) { p = p.northTilted().westTilted().southTilted().eastTilted() initialLoads.add(p.totalLoad()) } val repeatLength = (1..999).first { len -> ( (initialLoads.lastIndex - len + 1) .. initialLoads.lastIndex ).all { i -> initialLoads[i] == initialLoads[i-len] } } val k = (1000000000 - 1000) % repeatLength initialLoads[1000 - 1 - (repeatLength - (k % repeatLength))]
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
3,380
advent-of-code
Creative Commons Zero v1.0 Universal
src/Day08.kt
flexable777
571,712,576
false
{"Kotlin": 38005}
fun main() { fun part1(input: List<String>): Int { val countedTrees = mutableSetOf<Pair<Int, Int>>() //read input as ints val matrix = input.map { r -> r.toList().map { it.digitToInt() } } val indices = matrix.first().indices var previouslyHighestTree: Int //first from left to right for (x in indices) { previouslyHighestTree = -1 for (y in indices) { if (matrix[x][y] > previouslyHighestTree) { countedTrees += x to y previouslyHighestTree = matrix[x][y] } } } //then from right to left for (x in indices) { previouslyHighestTree = -1 for (y in indices.reversed()) { if (matrix[x][y] > previouslyHighestTree) { countedTrees += x to y previouslyHighestTree = matrix[x][y] } } } //then from up to down for (x in indices) { previouslyHighestTree = -1 for (y in indices) { if (matrix[y][x] > previouslyHighestTree) { countedTrees += y to x previouslyHighestTree = matrix[y][x] } } } //then from down to up for (x in indices) { previouslyHighestTree = -1 for (y in indices.reversed()) { if (matrix[y][x] > previouslyHighestTree) { countedTrees += y to x previouslyHighestTree = matrix[y][x] } } } return countedTrees.size } //TODO heavy refactor needed fun getScenicScoreLeftToRight(x: Int, y: Int, matrix: List<List<Int>>): Int { val myTreeHeight = matrix[x][y] var previouslyHighestTree = myTreeHeight var count = 0 if (y == matrix.lastIndex) { return 0 } for (j in (y + 1)..matrix.lastIndex) { count++ if (matrix[x][j] >= myTreeHeight) { break } if (matrix[x][j] <= previouslyHighestTree) { if (matrix[x][j] == myTreeHeight) { return count } if (matrix[x][j] > previouslyHighestTree) { previouslyHighestTree = matrix[x][j] } } else { break } } return count } fun getScenicScoreRightToLeft(x: Int, y: Int, matrix: List<List<Int>>): Int { val myTreeHeight = matrix[x][y] var previouslyHighestTree = myTreeHeight var count = 0 if (y == 0) { return 0 } for (j in (0 until y).reversed()) { count++ if (matrix[x][j] >= myTreeHeight) { break } if (matrix[x][j] <= previouslyHighestTree) { if (matrix[x][j] == myTreeHeight) { return count } if (matrix[x][j] > previouslyHighestTree) { previouslyHighestTree = matrix[x][j] } } else { break } } return count } fun getScenicScoreUpToDown(x: Int, y: Int, matrix: List<List<Int>>): Int { val myTreeHeight = matrix[x][y] var previouslyHighestTree = myTreeHeight var count = 0 if (x == matrix.lastIndex) { return 0 } for (i in (x + 1)..matrix.lastIndex) { count++ if (matrix[i][y] >= myTreeHeight) { break } if (matrix[i][y] <= previouslyHighestTree) { if (matrix[i][y] == myTreeHeight) { return count } if (matrix[i][y] > previouslyHighestTree) { previouslyHighestTree = matrix[i][y] } } else { break } } return count } fun getScenicScoreDownToUp(x: Int, y: Int, matrix: List<List<Int>>): Int { val myTreeHeight = matrix[x][y] var previouslyHighestTree = myTreeHeight var count = 0 if (x == 0) { return 0 } for (i in (0 until x).reversed()) { count++ if (matrix[i][y] >= myTreeHeight) { break } if (matrix[i][y] <= previouslyHighestTree) { if (matrix[i][y] == myTreeHeight) { return count } if (matrix[i][y] > previouslyHighestTree) { previouslyHighestTree = matrix[i][y] } } else { break } } return count } fun part2(input: List<String>): Int { val countedTrees = mutableMapOf<Pair<Int, Int>, Int>() //read input as ints val matrix = input.map { row -> row.toList().map { it.digitToInt() } } for (x in matrix.indices) { for (y in matrix.indices) { if (x to y in countedTrees) { continue } val scoreLeftToRight = getScenicScoreLeftToRight(x, y, matrix) if (scoreLeftToRight == 0) { countedTrees += x to y to 0 continue } val scoreRightToLeft = getScenicScoreRightToLeft(x, y, matrix) if (scoreRightToLeft == 0) { countedTrees += x to y to 0 continue } val scoreUpToDown = getScenicScoreUpToDown(x, y, matrix) if (scoreUpToDown == 0) { countedTrees += x to y to 0 continue } val scoreDownToUp = getScenicScoreDownToUp(x, y, matrix) if (scoreDownToUp == 0) { countedTrees += x to y to 0 continue } countedTrees += x to y to scoreLeftToRight * scoreRightToLeft * scoreUpToDown * scoreDownToUp } } return countedTrees.maxOf { it.value } } val testInput = readInputAsLines("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInputAsLines("Day08") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
d9a739eb203c535a3d83bc5da1b6a6a90a0c7bd6
6,641
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g0601_0700/s0695_max_area_of_island/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0695_max_area_of_island // #Medium #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find // #Algorithm_I_Day_7_Breadth_First_Search_Depth_First_Search // #Graph_Theory_I_Day_2_Matrix_Related_Problems // #2023_02_22_Time_324_ms_(24.06%)_Space_47.2_MB_(21.92%) @Suppress("NAME_SHADOWING") class Solution { fun maxAreaOfIsland(grid: Array<IntArray>): Int { if (grid.isEmpty()) { return 0 } val m = grid.size val n = grid[0].size var max = 0 for (i in 0 until m) { for (j in 0 until n) { if (grid[i][j] == 1) { val area = dfs(grid, i, j, m, n, 0) max = Math.max(area, max) } } } return max } private fun dfs(grid: Array<IntArray>, i: Int, j: Int, m: Int, n: Int, area: Int): Int { var area = area if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { return area } grid[i][j] = 0 area++ area = dfs(grid, i + 1, j, m, n, area) area = dfs(grid, i, j + 1, m, n, area) area = dfs(grid, i - 1, j, m, n, area) area = dfs(grid, i, j - 1, m, n, area) return area } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,280
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day18.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2022 import com.dvdmunckhof.aoc.common.Vector3d class Day18(input: List<String>) { private val cubes = input.mapTo(mutableSetOf()) { val (x, y, z) = it.split(",").map(String::toInt) Vector3d(x, y, z) } private val neighbours = arrayOf( Vector3d(-1, 0, 0), Vector3d(1, 0, 0), Vector3d(0, -1, 0), Vector3d(0, 1, 0), Vector3d(0, 0, -1), Vector3d(0, 0, 1), ) fun solvePart1(): Int { return cubes.sumOf { cube -> 6 - neighbours.count { offset -> (cube + offset) in cubes } } } fun solvePart2(): Int { val boundsX = -1..cubes.maxOf { it.x } + 1 val boundsY = -1..cubes.maxOf { it.y } + 1 val boundsZ = -1..cubes.maxOf { it.z } + 1 var visibleSides = 0 val processed = mutableSetOf<Vector3d>() val queue = ArrayDeque<Vector3d>() queue.add(Vector3d(-1, -1, -1)) // Breadth-first search while (queue.isNotEmpty()) { val cube = queue.removeFirst() if (!processed.add(cube)) { continue } for (offset in neighbours) { val neighbour = cube + offset if (neighbour in cubes) { visibleSides += 1 } else if (neighbour.x in boundsX && neighbour.y in boundsY && neighbour.z in boundsZ) { queue += neighbour } } } return visibleSides } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
1,532
advent-of-code
Apache License 2.0
baparker/12/main.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File import kotlin.collections.mutableListOf open class Cave(val name: String) { val destList: MutableList<String> = mutableListOf() } class SmallCave(name: String) : Cave(name) { var visited = false } var counter = 0 fun traverseCaves( caveMap: MutableMap<String, Cave>, caveName: String, secondVisit: Boolean = false, path: MutableList<String> = mutableListOf(), ) { val currentCave = caveMap.get(caveName) path.add(caveName) if (caveName != "end") { currentCave?.destList?.forEach { val nextCave = caveMap.get(it) if (nextCave is SmallCave) { if (!nextCave.visited) { nextCave.visited = true traverseCaves(caveMap, it, secondVisit, path) nextCave.visited = false } else if (!secondVisit) { traverseCaves(caveMap, it, true, path) } } else { traverseCaves(caveMap, it, secondVisit, path) } } } else { counter++ } path.removeLast() } fun addNodes(caveMap: MutableMap<String, Cave>, first: String, second: String) { if (second != "start") { val cave = caveMap.getOrPut(first) { if (first[0].isLowerCase()) SmallCave(first) else Cave(first) } cave.destList.add(second) } } fun main(args: Array<String>) { var useSecondVisit = !args.getOrElse(0) { "false" }.toBoolean() val caveMap: MutableMap<String, Cave> = mutableMapOf() File("input.txt").forEachLine { val input = it.split("-") addNodes(caveMap, input[0], input[1]) addNodes(caveMap, input[1], input[0]) } traverseCaves(caveMap, "start", useSecondVisit) println(counter) }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
1,856
advent-of-code-2021
MIT License
src/main/kotlin/hu/advent/of/code/year2020/day9/Puzzle9B.kt
sztojkatamas
568,512,275
false
{"Kotlin": 157914}
package hu.advent.of.code.year2020.day9 import hu.advent.of.code.AdventOfCodePuzzle import hu.advent.of.code.BaseChallenge @AdventOfCodePuzzle class Puzzle9B : BaseChallenge(2020) { override fun run() { printPuzzleName() val data = loadLongDataFromFile("data9.txt") val preamble = 25 val num = getThatNumber(data, preamble) val limitpos = data.indexOf(num) for (s in 1 until limitpos) { print("${(s/limitpos.toFloat())*100f}% [$s\t$limitpos]\r") for (i in 1 until data.size) { val potentialData = data.takeFrom(s-1, i) val sum = potentialData.sumOf { it } when { sum == num -> { println("--== Finally, after crunching ${(s/limitpos.toFloat())*100f}% of the data. ==--\n" + "${potentialData.minOrNull()!! + potentialData.maxOrNull()!!}") return } sum > num -> { break } } } } } private fun getThatNumber(data :List<Long>, preamble :Int): Long { for (i in 1..(data.size - preamble)) { val workData = data.takeFrom(i-1, preamble) val wannabe = data[i -1 + preamble] val pair = hasValidNumbers(workData, wannabe) if (pair.first * pair.second == 1L) { return wannabe } } return -1L } private fun hasValidNumbers(workData :List<Long>, target :Long): Pair<Long, Long> { for (a in workData) { for (b in workData) { if ((a + b) == target ) { return Pair(a, b) } } } return Pair(-1L, -1L) } private fun List<Long>.takeFrom(from :Int, n :Int) :List<Long> { return this.take(from + n).takeLast(n) } }
0
Kotlin
0
0
6aa9e53d06f8cd01d9bb2fcfb2dc14b7418368c9
1,980
advent-of-code-universe
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/Maximum69Number.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.DECIMAL import kotlin.math.pow private const val FIRST_SIX = 6 private const val CD = 3 fun interface Maximum69Number { operator fun invoke(num: Int): Int } /** * Approach 1: Convert the integer to an iterable object */ class Max69NumberIterable : Maximum69Number { override operator fun invoke(num: Int): Int { // Convert the input 'num' to a string builder 'numSB'. val numSB = StringBuilder() numSB.append(num) // Iterate over the string builder (from high to low). for (i in numSB.indices) { // If we find the first '6', replace it with '9' and break the loop. if (numSB[i] == '6') { numSB.setCharAt(i, '9') break } } // Convert the modified string builder to integer and return it. return numSB.toString().toInt() } } /** * Approach 2: Use built-in function */ class Max69NumberBuildIn : Maximum69Number { override operator fun invoke(num: Int): Int { // Use the built-in function to replace the first '6' with '9'. // Return the integer converted from the modified 'numString'. return "$num".replaceFirst("6".toRegex(), "9").toInt() } } /** * Approach 3: Check the remainder */ class Max69NumberRem : Maximum69Number { override operator fun invoke(num: Int): Int { var firstSix = -1 var number: Int = num var i = 0 while (number > 0) { if (number % DECIMAL == FIRST_SIX) { firstSix = i } number /= DECIMAL i++ } return num + CD * DECIMAL.toDouble().pow(firstSix.toDouble()).toInt() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,373
kotlab
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day11.kt
EmRe-One
568,569,073
false
{"Kotlin": 166986}
package tr.emreone.adventofcode.days import tr.emreone.adventofcode.isDivisibleBy import tr.emreone.adventofcode.lcm import tr.emreone.adventofcode.product object Day11 { val OPERATION_PATTERN = """Operation: new = old (\+|\*) (\d+|old)""".toRegex() val DIVISIBLE_PATTERN = """Test: divisible by (\d+)""".toRegex() val THROW_TO_PATTERN = """throw to monkey (\d+)""".toRegex() class Monkey( val id: Int, val recipients: MutableList<Long>, val operation: (Long) -> Long, val divisor: Int, val ifTrue: Int, val ifFalse: Int ) { var numberOfInspects = 0L companion object { /** * Monkey <id>: * Starting items: <arrayOfItems> * Operation: new = <formula> * Test: divisible by <divisor> * If true: throw to monkey <id> * If false: throw to monkey <id> */ fun parseFromString(input: String): Monkey { val lines = input.split("\n") val id = """Monkey (\d+):""".toRegex() .find(lines[0])!! .destructured .component1() .toInt() val recipients = lines[1] .split(":")[1] .split(",") .map { it.trim().toLong() } .toMutableList() val match = OPERATION_PATTERN.find(lines[2]) val (op, value) = match!!.destructured val operation: (Long) -> Long = when (op) { "+" -> { old -> old + (value.toLongOrNull() ?: old) } "*" -> { old -> old * (value.toLongOrNull() ?: old) } else -> throw IllegalArgumentException("Unknown operation: $op") } val divisor = DIVISIBLE_PATTERN.find(lines[3])!!.destructured.component1().toInt() val ifTrue = THROW_TO_PATTERN.find(lines[4])!!.destructured.component1().toInt() val ifFalse = THROW_TO_PATTERN.find(lines[5])!!.destructured.component1().toInt() return Monkey(id, recipients, operation, divisor, ifTrue, ifFalse) } } fun inspectItemOnTop(modifyWorryLevel: Boolean = false, worryLevelModifier: Long = 1L): Pair<Int, Long> { val worryLevel = this.recipients.removeFirst() val operatedWorryLevel = if (!modifyWorryLevel) { this.operation(worryLevel) / 3 } else { this.operation(worryLevel) % worryLevelModifier } val testResult = operatedWorryLevel isDivisibleBy this.divisor val id = if (testResult) this.ifTrue else this.ifFalse this.numberOfInspects++ return id to operatedWorryLevel } override fun toString(): String { return "Monkey $id (${numberOfInspects.toString().padStart(5, )}): " + this.recipients.joinToString(", ") } } fun part1(input: String): Long { val monkeys = input.split("\n\n").map(Monkey::parseFromString) repeat(20) { monkeys.forEach {monkey -> while(monkey.recipients.isNotEmpty()) { val (id, worryLevel) = monkey.inspectItemOnTop() monkeys[id].recipients.add(worryLevel) } } } return monkeys.map(Monkey::numberOfInspects) .sortedByDescending { it } .take(2) .product() } fun part2(input: String): Long { val monkeys = input.split("\n\n").map(Monkey::parseFromString) val commonDivisor = monkeys.map { it.divisor.toLong() }.lcm() repeat(10_000) { monkeys.forEach {monkey -> while(monkey.recipients.isNotEmpty()) { val (id, worryLevel) = monkey.inspectItemOnTop(true, commonDivisor) monkeys[id].recipients.add(worryLevel) } } } return monkeys.map(Monkey::numberOfInspects) .sortedByDescending { it } .take(2) .product() } }
0
Kotlin
0
0
a951d2660145d3bf52db5cd6d6a07998dbfcb316
4,319
advent-of-code-2022
Apache License 2.0
src/Day21.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { val human = "humn" fun parseInput(input: List<String>): MutableMap<String, String> { val out = mutableMapOf<String, String>() for (it in input) { val parts = it.split(": ") out[parts[0]] = parts[1] } return out } fun monkeyYell(monkeys: MutableMap<String, String>, monkey: String): Long { val yell = monkeys[monkey] val num = yell?.toLongOrNull() if (num != null) { return num } val str = yell!!.split(" ") return when (str[1]) { "+" -> monkeyYell(monkeys, str[0]) + monkeyYell(monkeys, str[2]) "-" -> monkeyYell(monkeys, str[0]) - monkeyYell(monkeys, str[2]) "*" -> monkeyYell(monkeys, str[0]) * monkeyYell(monkeys, str[2]) else -> monkeyYell(monkeys, str[0]) / monkeyYell(monkeys, str[2]) } } fun isHumanHere(monkeys: MutableMap<String, String>, monkey: String): Boolean { if (monkey == human) { return true } val yell = monkeys[monkey] val num = yell?.toLongOrNull() if (num != null) { return false } val str = yell!!.split(" ") if (isHumanHere(monkeys, str[0])) return true if (isHumanHere(monkeys, str[2])) return true return false } fun workBackwards(monkeys: MutableMap<String, String>, monkey: String, result: Long): Long { val yell = monkeys[monkey] val str = yell!!.split(" ") val humanIsRight = isHumanHere(monkeys, str[2]) val num = if (humanIsRight) { monkeyYell(monkeys, str[0]) } else { monkeyYell(monkeys, str[2]) } val nextResult = when (str[1]) { "+" -> result - num "-" -> { if (humanIsRight) { num - result } else { result + num } } "*" -> result / num else -> { if (humanIsRight) { (num / result) + 1 } else { num * result } } } if (str[0] == human) { return nextResult } if (str[1] == human) { return nextResult } return if (humanIsRight) { workBackwards(monkeys, str[2], nextResult) } else { workBackwards(monkeys, str[0], nextResult) } } fun monkeyYell2(monkeys: MutableMap<String, String>): Long { val str = monkeys["root"]!!.split(" ") val humanIsRight = isHumanHere(monkeys, str[2]) val num = if (humanIsRight) { monkeyYell(monkeys, str[0]) } else { monkeyYell(monkeys, str[2]) } return if (humanIsRight) { workBackwards(monkeys, str[2], num) } else { workBackwards(monkeys, str[0], num) } } fun part1(input: List<String>): Long { val monkeys = parseInput(input) return monkeyYell(monkeys, "root") } fun part2(input: List<String>): Long { val monkeys = parseInput(input) return monkeyYell2(monkeys) } val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
3,475
advent-of-code-2022
Apache License 2.0
src/main/kotlin/ca/kiaira/advent2023/day12/Day12.kt
kiairatech
728,913,965
false
{"Kotlin": 78110}
package ca.kiaira.advent2023.day12 import ca.kiaira.advent2023.Puzzle /** * Object representing the solution to the "Advent of Code - Day 12: Hot Springs" puzzle. * * This object extends the [Puzzle] class, specifically handling puzzles with [SpringConditionRecords] as input. * It provides implementations for parsing the puzzle input and solving both parts of the puzzle. * * @constructor Creates an instance of Day12 puzzle solver. * * @author <NAME> <<EMAIL>> * @since December 12th, 2023 */ object Day12 : Puzzle<SpringConditionRecords>(12) { /** * A cache to store computed results to avoid redundant calculations. * It maps a triple of spring condition (String?), current run size (Int?), and remaining damaged sizes (List<Int>) * to the count of possible arrangements (Long). */ private val cache = mutableMapOf<Triple<String?, Int?, List<Int>>, Long>() /** * Parses the input into [SpringConditionRecords], which encapsulate the spring conditions and damaged groups. * * @param input The input sequence containing the rows of spring conditions. * @return An instance of [SpringConditionRecords] representing the parsed input. */ override fun parse(input: Sequence<String>): SpringConditionRecords { val rows = input.toList() val springConditions = rows.map { HotSpringsArranger(it.split(" ")[0]) } val damagedGroups = rows.map { DamagedGroup(it.split(" ")[1].split(",").map { size -> size.toInt() }) } return SpringConditionRecords(springConditions, damagedGroups) } /** * Solves Part 1 of the puzzle: Count all the different arrangements of operational and broken springs that meet * the given criteria for each row. * * @param input An instance of [SpringConditionRecords] representing the puzzle input. * @return The sum of possible arrangement counts for Part 1. */ override fun solvePart1(input: SpringConditionRecords): Any { return input.springConditions.zip(input.damagedGroups).sumOf { (condition, group) -> condition.countPossibleArrangements(group.sizes, cache) } } /** * Solves Part 2 of the puzzle: Count all the different arrangements of operational and broken springs that meet * the given criteria for each row after unfolding the condition records. * * @param input An instance of [SpringConditionRecords] representing the puzzle input. * @return The sum of possible arrangement counts for Part 2 after unfolding the records. */ override fun solvePart2(input: SpringConditionRecords): Any { return input.springConditions.zip(input.damagedGroups).sumOf { (condition, group) -> val duplicatedCondition = HotSpringsArranger((1..5).joinToString("") { "?${condition.description}" }.drop(1)) duplicatedCondition.countPossibleArrangements(List(5) { group.sizes }.flatten(), cache) } } }
0
Kotlin
0
1
27ec8fe5ddef65934ae5577bbc86353d3a52bf89
2,824
kAdvent-2023
Apache License 2.0
KotlinAdvent2018/week1/src/main/kotlin/net/twisterrob/challenges/adventOfKotlin2018/week1/Map.kt
TWiStErRob
136,539,340
false
{"Kotlin": 104880, "Java": 11319}
package net.twisterrob.challenges.adventOfKotlin2018.week1 class Map(private val cells: Array<Array<Cell>>) { val rows: Int = cells.rows val cols: Int = cells.cols override fun toString() = cells.joinToString("\n") { row -> row.joinToString(separator = "", transform = Cell::format) } operator fun get(row: Int, col: Int) = cells[row][col] operator fun set(row: Int, col: Int, value: Cell) { cells[row][col] = value } enum class Cell(private val display: Char) { Empty('◌'), Obstacle('■'), Start('S'), End('X'), Path('●'); fun format() = display.toString() companion object { fun parse(cell: Char) = enumValues<Cell>().find { it.display == cell } ?: error("Unknown cell: ${cell}") } } companion object { fun parse(inputMap: String): Map { val rows = inputMap.split('\n') val rowCount = rows.size check(rowCount != 0) { "No rows in input map" } val columnCount = rows.first().length check(rows.all { it.length == columnCount }) { "Map not rectangular: not all rows have the same column count: " + rows.filter { it.length != columnCount } } fun parseRow(row: String) = row.map(Map.Cell.Companion::parse).toTypedArray() return Map(cells = rows.map(::parseRow).toTypedArray()) } private val Array<Array<Cell>>.rows: Int get() = this.size private val Array<Array<Cell>>.cols: Int get() = firstOrNull()?.size ?: 0 } }
1
Kotlin
1
2
5cf062322ddecd72d29f7682c3a104d687bd5cfc
1,413
TWiStErRob
The Unlicense
src/Day07.kt
ixtryl
575,312,836
false
null
import java.lang.IllegalArgumentException import java.util.* object DAY07 { fun run(fileName: String, sizeLimit: Int): Int { val lines = readInput(fileName) val root: Directory = buildTree(lines) var result = 0 root.visit { val size = it.size() when (it) { is Directory -> { println("${it.name} (dir) -> $size") if (size <= sizeLimit) result += size } is FileEntry -> println("${it.name} (file) -> $size") } } println("Result: $result") val targetSize = 30000000 - (70000000 - root.size()) println("Target size: $targetSize") var bestDir: Directory = root var bestDiff = root.size() root.visit { when (it) { is Directory -> { val size = it.size() val diff = size - targetSize if (size > targetSize && bestDiff > diff) { bestDiff = diff bestDir = it } } } } println("Diff: $bestDiff Directory: ${bestDir.name} ${bestDir.size()}") return result } private fun buildTree(lines: List<String>): Directory { val root = Directory("/") var currentDirectory: Directory = root var isListing = false for (line in lines) { val parts = line.split(' ') when { isCommand(parts) -> { if (isListing) isListing = false when (val command = parts[1]) { "cd" -> { val parameter = parts[2] currentDirectory = when (parameter) { "/" -> root ".." -> currentDirectory.parent ?: root else -> currentDirectory.getDirectory(parameter) ?: currentDirectory } } "ls" -> isListing = true else -> throw IllegalArgumentException("Unknown command $command") } } isListing -> { currentDirectory.addChild( when (parts[0]) { "dir" -> Directory(parts[1], currentDirectory) else -> FileEntry( parts[1], Integer.parseInt(parts[0]), currentDirectory ) } ) } else -> throw RuntimeException("Bad command state") } } return root } private fun isCommand(parts: List<String>): Boolean { return parts[0] == "$" } } typealias Visitor = (Node) -> Unit abstract class Node(val name: String, val parent: Directory?) { abstract fun visit(visitor: Visitor) abstract fun size(): Int } class Directory(name: String, parent: Directory? = null) : Node(name, parent) { private val children = mutableListOf<Node>() fun addChild(child: Node) { if (children.firstOrNull { it.name == child.name } == null) { children.add(child) } else { println("Will not add new child $child since there already exists a child with the same name") } } override fun visit(visitor: Visitor) { visitor(this) children.forEach { it.visit(visitor) } } override fun size(): Int { var result = 0 children.forEach { result += it.size() } return result } fun getDirectory(directoryName: String): Directory? { return children.filterIsInstance(Directory::class.java).firstOrNull { it.name == directoryName } } } class FileEntry(name: String, private val fileSize: Int, parent: Directory) : Node(name, parent) { override fun visit(visitor: Visitor) { visitor(this) } override fun size(): Int { return this.fileSize } } fun main() { // if (DAY07.run("Day07_test", 100000) != 95437) { // throw RuntimeException("Fail: Expected 95437") // } // if (DAY07.run("Day07", 100000) != 1443806) { // throw RuntimeException("Fail: Expected 1443806") // } DAY07.run("Day07", 100000) // 70000000 // 30000000 // 21618835 // 8381165 // 70000000 // 40913445 }
0
Kotlin
0
0
78fa5f6f85bebe085a26333e3f4d0888e510689c
4,567
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/day21/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day21 fun main() { val player1 = Player(4) val player2 = Player(3) val die = DeterministicDie() var roundNumber = 0 var losingPlayer: Player while (player1.score < 1000 && player2.score < 1000) { if (roundNumber % 2 == 0) { val score = die.roll() + die.roll() + die.roll() player1.addScore(score) } else { val score = die.roll() + die.roll() + die.roll() player2.addScore(score) } roundNumber++ } losingPlayer = if (player1.score >= 1000) { player2 } else { player1 } println(losingPlayer.score * die.numberOfRolls) val thrownValueToNumberOfUniverses = mapOf<Int, Long>( 3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1, ) val (player1WonUniverses, player2WonUniverses) = thrownValueToNumberOfUniverses.keys .map { playRound( true, it, 4, 0, 3, 0, 1, thrownValueToNumberOfUniverses ) } .reduce { p1, p2 -> p1.first + p2.first to p1.second + p2.second } println(maxOf(player1WonUniverses, player2WonUniverses)) } fun playRound( playsFirstPlayer: Boolean, thrownValue: Int, player1Position: Int, player1Score: Int, player2Position: Int, player2Score: Int, numberOfUniverses: Long, thrownValueToNumberOfUniverses: Map<Int, Long> ): Pair<Long, Long> { val newPlayer1Position: Int val newPlayer1Score: Int val newPlayer2Position: Int val newPlayer2Score: Int val newNumberOfUniverses: Long if (playsFirstPlayer) { newPlayer1Position = (player1Position + thrownValue - 1) % 10 + 1 newPlayer1Score = player1Score + newPlayer1Position newNumberOfUniverses = numberOfUniverses * thrownValueToNumberOfUniverses.getValue(thrownValue) newPlayer2Position = player2Position newPlayer2Score = player2Score if (newPlayer1Score >= 21) return newNumberOfUniverses to 0L } else { newPlayer2Position = (player2Position + thrownValue - 1) % 10 + 1 newPlayer2Score = player2Score + newPlayer2Position newNumberOfUniverses = numberOfUniverses * thrownValueToNumberOfUniverses.getValue(thrownValue) newPlayer1Position = player1Position newPlayer1Score = player1Score if (newPlayer2Score >= 21) return 0L to newNumberOfUniverses } return thrownValueToNumberOfUniverses.keys .map { playRound( !playsFirstPlayer, it, newPlayer1Position, newPlayer1Score, newPlayer2Position, newPlayer2Score, newNumberOfUniverses, thrownValueToNumberOfUniverses ) } .reduce { p1, p2 -> p1.first + p2.first to p1.second + p2.second} } data class Player(var position: Int) { var score: Int = 0 fun addScore(value: Int) { position = (position + value - 1) % 10 + 1 score += position } } data class DeterministicDie(var currentValue: Int = 0) { var numberOfRolls: Int = 0 fun roll(): Int { numberOfRolls++ return (++currentValue - 1) % 100 + 1 } }
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
3,539
aoc-2021
MIT License
src/main/kotlin/days_2021/Day3.kt
BasKiers
434,124,805
false
{"Kotlin": 40804}
package days_2021 import util.Day import util.Util class Day3 : Day(3) { val input = inputList.map { it.toCharArray().toList() }; val transposedInput = Util.transpose(input) fun invertBitChar(char: Char) = when (char) { '1' -> '0' '0' -> '1' else -> char } fun getOccurrences(list: List<Char>) = list.groupBy { it }.toList().sortedBy { it.first }.map { (key, occurrences) -> key to occurrences.size } fun getMostOccuringChar(list: List<Char>): Char { val charOccurences = getOccurrences(list); val (mostOccuringChar, mostOccurences) = charOccurences.maxByOrNull { (_, occurrences) -> occurrences }!! val isSingleMostOccuring = charOccurences.count { (_, occurences) -> occurences == mostOccurences } == 1 return when { !isSingleMostOccuring -> '1' else -> mostOccuringChar } } fun getLeastOccuringChar(list: List<Char>) = getMostOccuringChar(list).let(::invertBitChar) fun getSecondLevelData( getFilterChar: (list: List<Char>) -> Char, list: List<List<Char>>, index: Int = 0 ): List<List<Char>> { if (list.size <= 1) { return list } val filterOnChar = getFilterChar(Util.transpose(list)[index]) return getSecondLevelData( getFilterChar, list.filter { chars -> chars[index] == filterOnChar }, index + 1 ) } fun bitCharArrayToInt(charArray: List<Char>) = charArray.joinToString("").toInt(2) override fun partOne(): Any { val gamma = transposedInput.map(::getMostOccuringChar).let(::bitCharArrayToInt) val epsilon = transposedInput.map(::getLeastOccuringChar).let(::bitCharArrayToInt) return gamma * epsilon } override fun partTwo(): Any { val oxygen = getSecondLevelData(::getMostOccuringChar, input).first().let(::bitCharArrayToInt) val scrubber = getSecondLevelData(::getLeastOccuringChar, input).first().let(::bitCharArrayToInt) return oxygen * scrubber } }
0
Kotlin
0
0
870715c172f595b731ee6de275687c2d77caf2f3
2,093
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/manerfan/althorithm/sort/QuickSort.kt
manerfan
122,578,493
false
null
/* * ManerFan(http://manerfan.com). All Rights Reserved. * * 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 com.manerfan.althorithm.sort import java.util.concurrent.ForkJoinPool import java.util.concurrent.RecursiveTask /** * 快速排序 * @author manerfan * @date 2018/2/24 */ internal fun <T : Comparable<T>> Array<T>.partition(lo: Int, hi: Int): Int { var i = lo var j = hi var v = this[lo] // 切分值 while (i <= hi && j >= lo && i < j) { while (this[++i] < v) if (i >= hi) break while (this[--j] > v) if (j <= lo) break if (i >= j) break this.exch(i, j) // 将小于v的值放到左侧,反之放到右侧 } val mid = if (this[i] < v) i else j // 将v放到中间 this.exch(lo, mid) return mid } /** * 三向切分 */ internal fun <T : Comparable<T>> Array<T>.partition3w(lo: Int, hi: Int): Array<Int> { var lt = lo var gt = hi var i = lo + 1 var v = this[lo] while (i <= gt && i <= hi) { when { v > this[i] -> this.exch(i, gt--) v < this[i] -> this.exch(i++, lt++) else -> i++ } } return arrayOf(lt, gt) } internal fun <T : Comparable<T>> quickSort(array: Array<T>, lo: Int, hi: Int): Array<T> { return when { hi - lo < 10 -> array.shellSort() // 小范围使用希尔排序 hi > lo -> { val mid = array.partition(lo, hi) // 切分 quickSort(array, lo, mid - 1) // 递归排序左侧 quickSort(array, mid + 1, hi) // 递归排序右侧 array } else -> array } } class QuickSortTask<T : Comparable<T>>( private var array: Array<T>, private val lo: Int, private val hi: Int ) : RecursiveTask<Array<T>>() { override fun compute() = when { hi - lo < 10 -> array.shellSort() hi > lo -> { val midPair = array.partition3w(lo, hi) val left = MergeSortTask(array, lo, midPair[0]) val right = MergeSortTask(array, midPair[1], hi) left.fork(); right.fork() left.join(); right.join() array } else -> array } } internal val quickPool = ForkJoinPool() fun <T : Comparable<T>> Array<T>.quickSort(parallel: Boolean = false) = when (parallel) { true -> quickSort(this, 0, this.size - 1) else -> quickPool.submit(QuickSortTask(this, 0, this.size - 1)).get() }!!
0
Kotlin
0
0
9210934e15acefd1b5bafc7f11b2078643ded239
2,964
algorithm-with-kotlin
Apache License 2.0
src/main/kotlin/g2601_2700/s2641_cousins_in_binary_tree_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2601_2700.s2641_cousins_in_binary_tree_ii // #Medium #Hash_Table #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_07_18_Time_922_ms_(90.91%)_Space_67.3_MB_(36.36%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private var horizontalSum: MutableList<Int?>? = null private fun traverse(root: TreeNode?, depth: Int) { if (root == null) { return } if (depth < horizontalSum!!.size) { horizontalSum!![depth] = horizontalSum!![depth]!! + root.`val` } else { horizontalSum!!.add(root.`val`) } traverse(root.left, depth + 1) traverse(root.right, depth + 1) } private fun traverse1(root: TreeNode?, depth: Int) { if (root == null) { return } if (depth > 0) { var sum = 0 if (root.left != null) { sum += root.left!!.`val` } if (root.right != null) { sum += root.right!!.`val` } if (root.left != null) { root.left!!.`val` = horizontalSum!![depth + 1]!! - sum } if (root.right != null) { root.right!!.`val` = horizontalSum!![depth + 1]!! - sum } } traverse1(root.left, depth + 1) traverse1(root.right, depth + 1) } fun replaceValueInTree(root: TreeNode?): TreeNode { horizontalSum = ArrayList() root!!.`val` = 0 if (root.left != null) { root.left!!.`val` = 0 } if (root.right != null) { root.right!!.`val` = 0 } traverse(root, 0) traverse1(root, 0) return root } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,955
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/leetcode/random_problems/easy/roman_to_integer/Main.kt
frikit
254,842,734
false
null
package com.leetcode.random_problems.easy.roman_to_integer fun main() { println("Test case 1:") println(Solution().romanToInt("III")) // 3 println() println("Test case 2:") println(Solution().romanToInt("IV")) // 4 println() println("Test case 3:") println(Solution().romanToInt("IX")) // 9 println() println("Test case 4:") println(Solution().romanToInt("LVIII")) // 58 Explanation: L = 50, V= 5, III = 3. println() println("Test case 5:") println(Solution().romanToInt("MCMXCIV")) // 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. println() } class Solution { val numberMap = mapOf( 'I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000 ) fun romanToInt(s: String): Int { var current: Int var previous = -1 val operations = s.map { c -> current = numberMap[c] ?: throw IllegalArgumentException("Map doesnt contain $c") when { previous == -1 -> { previous = current +current } previous < current -> { +(current - (previous * 2)) } else -> { previous = current current } } } return operations.reduce { acc, i -> acc + i } } }
0
Kotlin
0
0
dda68313ba468163386239ab07f4d993f80783c7
1,477
leet-code-problems
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DecodeWays.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT /** * 91. Decode Ways * @see <a href="https://leetcode.com/problems/decode-ways">Source</a> */ fun interface DecodeWays { operator fun invoke(str: String): Int } class DecodeWaysDP : DecodeWays { override fun invoke(str: String): Int { if (str.isEmpty()) { return 0 } val n: Int = str.length val dp = IntArray(n + 1) dp[0] = 1 dp[1] = if (str.first() != '0') 1 else 0 for (i in 2..n) { val first: Int = Integer.valueOf(str.substring(i - 1, i)) val second: Int = Integer.valueOf(str.substring(i - 2, i)) if (first in 1..9) { dp[i] += dp[i - 1] } if (second in 10..ALPHABET_LETTERS_COUNT) { dp[i] += dp[i - 2] } } return dp[n] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,529
kotlab
Apache License 2.0
src/main/kotlin/twentytwentytwo/Day2.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo fun main() { val input = {}.javaClass.getResource("input-2.txt")!!.readText().split("\n"); val day = Day2(input) println(day.part1()) println(day.part2()) } class Day2(private val input: List<String>) { fun part1(): Int { fun toScore(l: String): Int { return when (l) { "A X" -> 4; "A Y" -> 8; "A Z" -> 3; "B X" -> 1; "B Y" -> 5; "B Z" -> 9; "C X" -> 7; "C Y" -> 2; "C Z" -> 6; else -> { 0 } } } return input .sumOf { l -> toScore(l) } } fun part2(): Int { fun toScore(l: String): Int { return when (l) { "A X" -> 3; "A Y" -> 4; "A Z" -> 8; "B X" -> 1; "B Y" -> 5; "B Z" -> 9; "C X" -> 2; "C Y" -> 6; "C Z" -> 7; else -> { 0 } } } return input.sumOf { l -> toScore(l) }; } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
1,235
aoc202xkotlin
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/GenerateParentheses.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 /** * Generate Parentheses. * @see <a href="https://leetcode.com/problems/generate-parentheses/">Source</a> */ fun interface GenerateParentheses { operator fun invoke(n: Int): List<String> } /** * Approach 1: Brute Force */ class GenerateParenthesesBruteForce : GenerateParentheses { override operator fun invoke(n: Int): List<String> { val combinations: MutableList<String> = ArrayList() generateAll(CharArray(2 * n), 0, combinations) return combinations } private fun generateAll(current: CharArray, pos: Int, result: MutableList<String>) { if (pos == current.size) { if (valid(current)) result.add(String(current)) } else { current[pos] = '(' generateAll(current, pos + 1, result) current[pos] = ')' generateAll(current, pos + 1, result) } } private fun valid(current: CharArray): Boolean { var balance = 0 for (c in current) { if (c == '(') balance++ else balance-- if (balance < 0) return false } return balance == 0 } } /** * Approach 2: Backtracking */ class GenerateParenthesesBacktracking : GenerateParentheses { override operator fun invoke(n: Int): List<String> { val ans: MutableList<String> = ArrayList() backtrack(ans, "", 0, 0, n) return ans } private fun backtrack(ans: MutableList<String>, cur: String, open: Int, close: Int, max: Int) { if (cur.length == max * 2) { ans.add(cur) return } if (open < max) backtrack(ans, "$cur(", open + 1, close, max) if (close < open) backtrack(ans, "$cur)", open, close + 1, max) } } /** * Approach 3: Closure Number */ class GenerateParenthesesClosureNumber : GenerateParentheses { override operator fun invoke(n: Int): List<String> { val ans: MutableList<String> = ArrayList() if (n == 0) { ans.add("") } else { for (c in 0 until n) for (left in invoke(c)) for (right in invoke(n - 1 - c)) ans.add( "($left)$right", ) } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,834
kotlab
Apache License 2.0
reposilite-backend/src/main/kotlin/com/reposilite/storage/Comparators.kt
dzikoysk
96,474,388
false
{"Kotlin": 732353, "Vue": 113305, "JavaScript": 100693, "CSS": 9405, "Java": 6529, "HTML": 4488, "Shell": 2402, "Dockerfile": 1654}
/* * Copyright (c) 2023 dzikoysk * * 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 com.reposilite.storage import java.math.BigInteger import kotlin.math.max class FilesComparator<T>( cachedValue: (T) -> List<String>, private val isDirectory: (T) -> Boolean ) : VersionComparator<T>(cachedValue) { override fun compare(version: T, toVersion: T): Int = when { isDirectory(version) == isDirectory(toVersion) -> super.compare(version, toVersion) isDirectory(toVersion) -> 1 else -> -1 } } open class VersionComparator<T>( private val versionMapper: (T) -> List<String>, ) : Comparator<T> { companion object { private val defaultVersionPattern = Regex("[-._]") fun asVersion(value: String): List<String> = defaultVersionPattern.split(value) fun sortStrings(sequence: Sequence<String>): Sequence<String> = sequence .map { it to asVersion(it) } .sortedWith(VersionComparator { cache -> cache.second }) .map { it.first } } override fun compare(version: T, toVersion: T): Int = compareVersions(versionMapper(version), versionMapper(toVersion)) private fun compareVersions(version: List<String>, toVersion: List<String>): Int { for (index in 0 until max(version.size, toVersion.size)) { val fragment = version.getOrElse(index) { "0" } val baseIsDigit = fragment.isDigit() val toFragment = toVersion.getOrElse(index) { "0" } val result = // Compare current version to the other if (baseIsDigit && toFragment.isDigit()) { try { fragment.toLong().compareTo(toFragment.toLong()) } catch (numberFormatException: NumberFormatException) { BigInteger(fragment).compareTo(BigInteger(toFragment)) } } // Prioritize digits over strings else if (baseIsDigit || toFragment.isDigit()) { if (baseIsDigit) 1 else -1 } // Compare strings else { fragment.compareTo(toFragment) } if (result != 0) { return result } } return version.size.compareTo(toVersion.size) } } private fun String.isDigit(): Boolean = isNotEmpty() && !toCharArray().any { !Character.isDigit(it) }
26
Kotlin
160
1,163
d0042d564bf664329c5b0107b7580655cefb1238
3,078
reposilite
Apache License 2.0
day17/src/main/kotlin/dev/fwcd/adventofcode2021/Day17.kt
fwcd
432,520,714
false
null
package dev.fwcd.adventofcode2021 import kotlin.math.sign data class Vec(val x: Int, val y: Int) { operator fun plus(rhs: Vec) = Vec(x + rhs.x, y + rhs.y) } data class Rect(val min: Vec, val max: Vec) { operator fun contains(pos: Vec): Boolean = pos.x >= min.x && pos.x <= max.x && pos.y >= min.y && pos.y <= max.y } data class SimulationResults(val hitTarget: Boolean, val maxY: Int) fun simulate(startVelocity: Vec, target: Rect): SimulationResults { var pos = Vec(0, 0) var velocity = startVelocity var maxY = 0 while (pos.x <= target.max.x && pos.y >= target.min.y) { if (pos in target) { return SimulationResults(hitTarget = true, maxY) } pos += velocity maxY = Math.max(pos.y, maxY) velocity = Vec(velocity.x - velocity.x.sign, velocity.y - 1) } return SimulationResults(hitTarget = false, maxY) } fun main() { val input = object {}.javaClass.getResource("/input.txt").readText() val pattern = """target area: x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)""".toRegex() val (x1, x2, y1, y2) = pattern.find(input)!!.groupValues.drop(1).map { it.toInt() } val target = Rect(Vec(x1, y1), Vec(x2, y2)) val radius = Math.max( Math.max(Math.abs(x1), Math.abs(x2)), Math.max(Math.abs(y1), Math.abs(y2)) ) var maxY = 0 var hitCount = 0 for (dy in -radius..radius) { for (dx in -radius..radius) { val results = simulate(Vec(dx, dy), target) if (results.hitTarget) { maxY = Math.max(maxY, results.maxY) hitCount++ } } } println("Part 1: $maxY") println("Part 2: $hitCount") }
0
Rust
0
5
9327e74340af776b68649fcbbb2a9eec1db7533b
1,725
advent-of-code-2021
MIT License
2020/src/main/kotlin/de/skyrising/aoc2020/day12/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2020.day12 import de.skyrising.aoc.* import kotlin.math.* val test = TestInput(""" F10 N3 F7 R90 F11 """) @PuzzleName("Rain Risk") fun PuzzleInput.part1(): Any { var x = 0 var y = 0 var angle = 0 for (line in lines) { val command = line[0] val amount = line.substring(1).toInt() when (command) { 'N' -> y += amount 'S' -> y -= amount 'E' -> x += amount 'W' -> x -= amount 'L' -> angle += amount 'R' -> angle -= amount 'F' -> { val rad = Math.toRadians(angle.toDouble()) x += round(cos(rad) * amount).toInt() y += round(sin(rad) * amount).toInt() } } } return abs(x) + abs(y) } fun PuzzleInput.part2(): Any { var x = 0 var y = 0 var wx = 10 var wy = 1 for (line in lines) { val command = line[0] val amount = line.substring(1).toInt() when (command) { 'N' -> wy += amount 'S' -> wy -= amount 'E' -> wx += amount 'W' -> wx -= amount 'L' -> { val dist = sqrt((wx * wx + wy * wy).toDouble()) val r = atan2(wy.toDouble(), wx.toDouble()) + Math.toRadians(amount.toDouble()) wx = round(cos(r) * dist).toInt() wy = round(sin(r) * dist).toInt() } 'R' -> { val dist = sqrt((wx * wx + wy * wy).toDouble()) val r = atan2(wy.toDouble(), wx.toDouble()) - Math.toRadians(amount.toDouble()) wx = round(cos(r) * dist).toInt() wy = round(sin(r) * dist).toInt() } 'F' -> { x += wx * amount y += wy * amount } } } return abs(x) + abs(y) }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
1,907
aoc
MIT License
ConceptOfTheDay/Kotlin/src/main/java/org/redquark/conceptoftheday/AnagramSubstringSearch.kt
ani03sha
297,402,125
false
null
package org.redquark.conceptoftheday /** * @author <NAME> * * We are given two strings "text" and "pattern" of size n and m respectively where m < n. * Find all the indices in text where anagrams of pattern are found. */ private fun findIndices(text: String, pattern: String): List<Int> { // Lengths of strings val n = text.length val m = pattern.length // List that will store the indices val indices: MutableList<Int> = ArrayList() // Frequency arrays - assuming we have a set of 256 characters val textCount = IntArray(256) val patternCount = IntArray(256) // Loop until m for (i in 0 until m) { textCount[text[i].toInt()]++ patternCount[pattern[i].toInt()]++ } // At this point, we have traversed m characters in both the arrays. // Now we will loop through the remaining characters for (i in m until n) { // Check if the counts of characters in frequency arrays are equal or not if (isCountEqual(textCount, patternCount)) { indices.add(i - m) } // Discard left most character textCount[text[i - m].toInt()]-- // Include current character textCount[text[i].toInt()]++ } // Check for the last window if (isCountEqual(textCount, patternCount)) { indices.add(n - m) } return indices } private fun isCountEqual(textCount: IntArray, patternCount: IntArray): Boolean { for (i in 0..255) { if (textCount[i] != patternCount[i]) { return false } } return true } fun main() { var text = "BACDGABCDA" var pattern = "ABCD" println("Anagrams are found at: " + findIndices(text, pattern)) text = "XYYZXZYZXXYZ" pattern = "XYZ" println("Anagrams are found at: " + findIndices(text, pattern)) }
2
Java
40
64
67b6ebaf56ec1878289f22a0324c28b077bcd59c
1,832
RedQuarkTutorials
MIT License
src/main/kotlin/days/Day08.kt
poqueque
430,806,840
false
{"Kotlin": 101024}
package days class Day08 : Day(8) { override fun partOne(): Any { val lengths = mutableListOf(0, 0, 0, 0, 0, 0, 0, 0) inputList.forEach { val (_, output) = it.split(" | ") val outputs = output.split(" ") for (o in outputs) lengths[o.length]++ } return lengths[2] + lengths[3] + lengths[4] + lengths[7] } override fun partTwo(): Any { var total = 0 inputList.forEach { val (input, output) = it.split(" | ") val inputs = input.split(" ") val outputs = output.split(" ") val decoded = mutableMapOf( 0 to "", 1 to "", 2 to "", 3 to "", 4 to "", 5 to "", 6 to "", 9 to "", 8 to "", 0 to "", ) for (i in inputs) { if (i.length == 2) decoded[1] = i.toSortedSet().joinToString("") if (i.length == 3) decoded[7] = i.toSortedSet().joinToString("") if (i.length == 4) decoded[4] = i.toSortedSet().joinToString("") if (i.length == 7) decoded[8] = i.toSortedSet().joinToString("") } for (i in inputs) { if (i.length == 6) { if (i.contains(decoded[4]?.get(0) ?: 'z') && i.contains(decoded[4]?.get(1) ?: 'z') && i.contains(decoded[4]?.get(2) ?: 'z') && i.contains(decoded[4]?.get(3) ?: 'z') ) decoded[9] = i.toSortedSet().joinToString("") else if (i.contains(decoded[7]?.get(0) ?: 'z') && i.contains(decoded[7]?.get(1) ?: 'z') && i.contains(decoded[7]?.get(2) ?: 'z') ) decoded[0] = i.toSortedSet().joinToString("") else decoded[6] = i.toSortedSet().joinToString("") } } for (i in inputs) { if (i.length == 5) { if (i.contains(decoded[1]?.get(0) ?: 'z') && i.contains(decoded[1]?.get(1) ?: 'z') ) decoded[3] = i.toSortedSet().joinToString("") else if (decoded[6]?.contains(i[0]) == true && decoded[6]?.contains(i[1]) == true && decoded[6]?.contains(i[2]) == true && decoded[6]?.contains(i[3]) == true && decoded[6]?.contains(i[4]) == true ) decoded[5] = i.toSortedSet().joinToString("") else decoded[2] = i.toSortedSet().joinToString("") } } var n = 0 for (o in outputs) { n *= 10 n += decoded.filter { it.value == o.toSortedSet().joinToString("") }.keys.first() } total += n } return total } }
0
Kotlin
0
0
4fa363be46ca5cfcfb271a37564af15233f2a141
3,040
adventofcode2021
MIT License
src/main/java/challenges/educative_grokking_coding_interview/linkedlist_inplace_reveresal/_3/ReverseLinkedList.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.linkedlist_inplace_reveresal._3 import challenges.educative_grokking_coding_interview.LinkedList import challenges.educative_grokking_coding_interview.LinkedListNode import challenges.educative_grokking_coding_interview.PrintList.printListWithForwardArrow import challenges.util.PrintHyphens /** Given a singly linked list with n nodes and two positions, left and right, the objective is to reverse the nodes of the list from left to right. Return the modified list. https://www.educative.io/courses/grokking-coding-interview-patterns-java/gx9zZnEEM7r */ object ReverseLinkedList { // Assume that the linked list has left to right nodes. // Reverse left to right nodes of the given linked list. fun reverse(head: LinkedListNode, left: Int, right: Int): LinkedListNode? { var right = right var prev: LinkedListNode? = null var curr: LinkedListNode? = head while (right >= left) { val next: LinkedListNode? = curr?.next curr?.next = prev prev = curr curr = next right-- } return prev // Returns the head of the reversed list } // Reverses the sublist between left and right in the linked list fun reverseBetween(head: LinkedListNode?, left: Int, right: Int): LinkedListNode? { var curr: LinkedListNode? = head var lpn: LinkedListNode? = null // Previous node before the sublist var right_n: LinkedListNode? = null // Node after the sublist var reverse_head: LinkedListNode? = null // Head of the reversed sublist var count = 1 while (count < left && curr != null) { lpn = curr curr = curr.next count++ } if (curr != null) { var rpn: LinkedListNode? = curr while (count <= right && rpn != null) { right_n = rpn rpn = right_n.next count++ } if (right_n != null) { reverse_head = reverse(curr, left, right) } if (lpn != null) { lpn.next = reverse_head // Connects the previous node to the reversed sublist } if (rpn != null) { var tmp: LinkedListNode? = reverse_head while (tmp?.next != null) { tmp = tmp.next } // Connects the last node of the reversed sublist to the next node after the sublist tmp?.next = rpn } } return if (lpn != null) { head // Returns the original head if there are nodes before the sublist } else { reverse_head // Returns the head of the reversed sublist if there are no nodes before the sublist } } // Driver Code @JvmStatic fun main(args: Array<String>) { val input = arrayOf( intArrayOf(1, 2, 3, 4, 5, 6, 7), intArrayOf(6, 9, 3, 10, 7, 4, 6), intArrayOf(6, 9, 3, 4), intArrayOf(6, 2, 3, 6, 9), intArrayOf(6, 2) ) val left = intArrayOf(1, 3, 2, 1, 1) val right = intArrayOf(5, 6, 4, 3, 2) for (i in input.indices) { print(i + 1) val list = LinkedList() list.createLinkedList(input[i]) print(".\tOriginal linked list is: ") printListWithForwardArrow(list.head) print("\tReversed linked list is: ") printListWithForwardArrow( reverseBetween( list.head, left[i], right[i] ) ) println(PrintHyphens.repeat("-", 100)) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,789
CodingChallenges
Apache License 2.0
src/Day06.kt
nielsz
573,185,386
false
{"Kotlin": 12807}
fun main() { fun part1(input: String): Int { return input.firstUniquePartWithSize(4).first } fun part2(input: String): Int { return input.firstUniquePartWithSize(14).first } val input = readInput("Day06").first() println(part1(input)) // 1210 println(part2(input)) // 3476 } private fun String.onlyUniqueCharacters(): Boolean { val characters = HashSet<Char>() for (c in this) { if (characters.contains(c)) return false characters.add(c) } return true } private fun String.firstUniquePartWithSize(size: Int): Pair<Int, String> { var offset = size return windowed(size = size) .map { Pair(offset++, it) } .first { it.second.onlyUniqueCharacters() } }
0
Kotlin
0
0
05aa7540a950191a8ee32482d1848674a82a0c71
756
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/danielmichalski/algorithms/data_structures/_12_dijkstra_algorithm/Runner.kt
DanielMichalski
288,453,885
false
{"Kotlin": 101963, "Groovy": 19141}
package com.danielmichalski.algorithms.data_structures._12_dijkstra_algorithm object Runner { private const val VERTEX_A = "A" private const val VERTEX_B = "B" private const val VERTEX_C = "C" private const val VERTEX_D = "D" private const val VERTEX_E = "E" private const val VERTEX_F = "F" @JvmStatic fun main(args: Array<String>) { println("------------------ Initial weighted graph ------------------ ") var weightedGraph = getWeightedGraph() printWeightedGraph(weightedGraph) println("------------------ Finding the shortest path using Dijkstra algorithm ------------------ ") weightedGraph = getWeightedGraph() val shortestPath = weightedGraph.dijkstra(VERTEX_A, VERTEX_E) println("Shortest path between $VERTEX_A and $VERTEX_E: $shortestPath") } /** * It returns weighted graph like this: * <pre> * * 4 * A ---------- B * / | * 2 / | * / | * / 2 | * C -------- D | 3 * \ / \ | * \ / \ | * 4 \ 1 / 3 \ | * \ / \ | * \/ \ | * F --------- E * 1 * </pre> */ private fun getWeightedGraph(): WeightedGraph { val weightedGraph = WeightedGraph() weightedGraph.addVertex(VERTEX_A) weightedGraph.addVertex(VERTEX_B) weightedGraph.addVertex(VERTEX_C) weightedGraph.addVertex(VERTEX_D) weightedGraph.addVertex(VERTEX_E) weightedGraph.addVertex(VERTEX_F) weightedGraph.addEdge(VERTEX_A, VERTEX_B, 4) weightedGraph.addEdge(VERTEX_A, VERTEX_C, 2) weightedGraph.addEdge(VERTEX_B, VERTEX_E, 3) weightedGraph.addEdge(VERTEX_C, VERTEX_D, 2) weightedGraph.addEdge(VERTEX_C, VERTEX_F, 4) weightedGraph.addEdge(VERTEX_D, VERTEX_E, 3) weightedGraph.addEdge(VERTEX_D, VERTEX_F, 1) weightedGraph.addEdge(VERTEX_E, VERTEX_F, 1) return weightedGraph } private fun printWeightedGraph(weightedGraph: WeightedGraph) { println(weightedGraph) } }
0
Kotlin
1
7
c8eb4ddefbbe3fea69a172db1beb66df8fb66850
2,298
algorithms-and-data-structures-in-kotlin
MIT License
src/main/kotlin/Puzzle5.kt
darwineee
578,563,140
false
{"Kotlin": 17166}
import java.io.File private val numberRegex = "\\d+".toRegex() /** * With this puzzle we do not use stack data structure in part 1, even though it is maybe easier. * Because I want to keep most common logic from both part of the puzzle. */ fun puzzle5(args: Array<String>, isOnWrongShip: Boolean) { val graphStacks = args[0] val moveStrategy = args[1] val graphMatrix = graphStacks.getGraphMatrix() File(moveStrategy) .readLines() .map { it.getCraneMove().mapWithArrayIndex() } .forEach { if (isOnWrongShip) { moveCraneOn9000Ship(graphMatrix, it) } else { moveCraneOn9001Ship(graphMatrix, it) } } println( graphMatrix.mapNotNull { it.lastOrNull() }.joinToString("") ) } private fun moveCraneOn9000Ship( graphMatrix: List<MutableList<Char>>, moveStrategy: Triple<Int, Int, Int> ) { val (quantity, from, to) = moveStrategy repeat(quantity) { _ -> graphMatrix[from].lastOrNull()?.let { item -> graphMatrix[to].add(item) graphMatrix[from].removeLast() } } } private fun moveCraneOn9001Ship( graphMatrix: List<MutableList<Char>>, moveStrategy: Triple<Int, Int, Int> ) { val (quantity, from, to) = moveStrategy graphMatrix[to].addAll(graphMatrix[from].takeLast(quantity)) repeat(quantity) { graphMatrix[from].removeLastOrNull() } } private fun String.getGraphMatrix(): List<MutableList<Char>> { val graphMatrix = mutableListOf<MutableList<Char>>() File(this) .readLines() .map { it.toCharArray() } .forEach { row -> for ((columnIndex, rowIndex) in (1 until row.size step 4).withIndex()) { if (columnIndex > graphMatrix.lastIndex) { graphMatrix.add(mutableListOf()) } val item = row[rowIndex] if (item.isLetter()) { graphMatrix[columnIndex].add(0, item) } } } return graphMatrix } private fun String.getCraneMove(): Triple<Int, Int, Int> { val (first, second, third) = numberRegex .findAll(this) .mapNotNull { it.value.toIntOrNull() } .toList() return Triple(first, second, third) } private fun Triple<Int, Int, Int>.mapWithArrayIndex(): Triple<Int, Int, Int> { return Triple( first = this.first, second = this.second - 1, third = this.third - 1 ) }
0
Kotlin
0
0
f4354b88b657a6d6f803632bc6b43b5abb6943f1
2,573
adventOfCode2022
Apache License 2.0
src/test/kotlin/dev/bogwalk/model/util.kt
bog-walk
454,630,193
false
{"Kotlin": 72261}
package dev.bogwalk.model import java.io.File typealias TestPlay = Pair<CardHand, CardHand> fun getTestResource( filePath: String, lineTrim: CharArray = charArrayOf(' ', '\n'), lineSplit: String = " " ): List<List<String>> { val resource = mutableListOf<List<String>>() File(filePath).useLines { lines -> lines.forEach { line -> resource.add(line.trim(*lineTrim).split(lineSplit)) } } return resource } fun TestPlay.validated(): Set<Card>? { val uniqueCards = first.cards.toSet() + second.cards.toSet() return if (uniqueCards.size == 10) uniqueCards else null } /** * Converts test resource hand ranking into a List<List<Int>>, as would be returned by the class * property CardHand.ranked. * * Input contains 10 comma-separated elements each representing a rank, with 0 indicating that the * rank is not present in the hand and should therefore become an empty list. The first input * element is wrapped in parentheses if more than 1 high cards are present in the hand. */ fun convertTestRanked(input: String): List<List<Int>> { val ranked = mutableListOf<List<Int>>() var highCards: MutableList<Int>? = null input.split(",").forEach { when { it.startsWith('(') -> highCards = mutableListOf(it.drop(1).toInt()) it.endsWith(')') -> { highCards?.add(it.dropLast(1).toInt()) highCards?.let { highs -> ranked.add(highs) } highCards = null } it == "0" -> ranked.add(emptyList()) else -> highCards?.add(it.toInt()) ?: ranked.add(listOf(it.toInt())) } } return ranked } /** * Converts test resource into 2 CardHand instances for comparison. * * The final element in the input list represents the expected winner as an integer in [0, 2], * which corresponds to the ordinal positions of the enum class Winner. */ fun convertTestGame(input: List<String>): Pair<TestPlay, Winner> { val player1 = CardHand(input.slice(0..4).map(::getCard)) val player2 = CardHand(input.slice(5..9).map(::getCard)) val winner = Winner.values()[input.last().toInt()] return Pair(player1 to player2, winner) } /** * Converts test resource into 2 CardHand instances for generation of rank info. * * The 2nd component in the returned Pair represents the list of expected Triples of the * involved cards in each hand, as well as the involved rank titles, for each relevant rank in * a play. */ fun convertTestInfo( input: List<List<String>> ): List<Pair<TestPlay, List<RankInfo>>> { val sampleInfo = mutableListOf<Pair<TestPlay, List<RankInfo>>>() var i = 0 while (i < input.size) { val player1 = CardHand(input[i].slice(0..4).map(::getCard)) val player2 = CardHand(input[i].slice(5..9).map(::getCard)) val info = mutableListOf<RankInfo>() for (j in input[i+1].indices) { val player1Ranks = input[i+1][j].split(",").map(String::toInt) val player2Ranks = input[i+2][j].split(",").map(String::toInt) val rankTitles = input[i+3][j].split(",").map(String::toInt) info.add(Triple(player1Ranks, player2Ranks, rankTitles)) } sampleInfo.add(Pair(player1 to player2, info)) i += 4 } return sampleInfo }
0
Kotlin
0
1
c1b9daf3102f857cd84b81344af272f82fc18bf4
3,335
poker-hands
MIT License
src/rationals/Rational.kt
jihedamine
242,868,210
false
null
package rationals import java.lang.IllegalArgumentException import java.lang.NumberFormatException import java.math.BigInteger class Rational { private val numerator: BigInteger private val denominator: BigInteger constructor(numerator: BigInteger) : this(numerator, BigInteger.ONE) constructor(numerator: Number): this(numerator, 1) constructor(numerator: Number, denominator: Number) : this(BigInteger.valueOf(numerator.toLong()), BigInteger.valueOf(denominator.toLong())) constructor(numerator: BigInteger, denominator: BigInteger) { if (denominator == BigInteger.ZERO) throw IllegalArgumentException("Denominator cannot be zero") val sign = denominator.signum().toBigInteger() val signedNumerator = sign * numerator val signedDenominator = sign * denominator val gcd = signedNumerator.gcd(signedDenominator) this.numerator = signedNumerator.divide(gcd) this.denominator = signedDenominator.divide(gcd) } operator fun plus(that: Rational) = Rational( (this.numerator * that.denominator) + (that.numerator * this.denominator), this.denominator * that.denominator) operator fun minus(that: Rational) = plus(-that) operator fun times(that: Rational) = Rational(this.numerator * that.numerator, this.denominator * that.denominator) operator fun div(that: Rational) = Rational(this.numerator * that.denominator, this.denominator * that.numerator) operator fun unaryMinus() = Rational(-numerator, denominator) operator fun compareTo(that: Rational) : Int { return ((this.numerator * that.denominator) - (that.numerator * this.denominator)).signum() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Rational) return false return this.numerator == other.numerator && this.denominator == other.denominator } override fun toString() = if (denominator == BigInteger.ONE) "$numerator" else "$numerator/$denominator" operator fun rangeTo(that: Rational): RationalRange { return RationalRange(this, that) } override fun hashCode(): Int { var result = numerator.hashCode() result = 31 * result + denominator.hashCode() return result } class RationalRange(val startRational: Rational, val endRational: Rational) { operator fun contains(rational: Rational) = rational >= startRational && rational <= endRational } } infix fun <T : Number> T.divBy(denominator: T) = Rational(this, denominator) fun String.toRational() : Rational { fun String.toBigIntegerOrFail() = toBigIntegerOrNull() ?: throw IllegalArgumentException("${this@toRational} cannot be converted to a Rational") if (!contains("/")) return Rational(toBigIntegerOrFail()) val (elem1, elem2) = split("/") return Rational(elem1.toBigIntegerOrFail(), elem2.toBigIntegerOrFail()) } fun Int.toRational() = Rational(this) fun main() { "a/f".toRational() val half = 1 divBy 2 val third = 1 divBy 3 val sum: Rational = half + third println(5 divBy 6 == sum) val difference: Rational = half - third println(1 divBy 6 == difference) val product: Rational = half * third println(1 divBy 6 == product) val quotient: Rational = half / third println(3 divBy 2 == quotient) val negation: Rational = -half println(-1 divBy 2 == negation) println((2 divBy 1).toString() == "2") println((-2 divBy 4).toString() == "-1/2") println("117/1098".toRational().toString() == "13/122") val twoThirds = 2 divBy 3 println(half < twoThirds) println(half in third..twoThirds) println(3.toRational().toString() == "3") println(2000000000L divBy 4000000000L == 1 divBy 2) println("912016490186296920119201192141970416029".toBigInteger() divBy "1824032980372593840238402384283940832058".toBigInteger() == 1 divBy 2) }
0
Kotlin
1
0
61e7156c6ce59df6e2dc9137853ce08f9070b633
3,985
kotlin_coursera
Apache License 2.0
src/binary.kt
dlew
54,331,937
false
null
/** * Proof for the Riddler problem from March 18, 2016 * * http://fivethirtyeight.com/features/can-you-best-the-mysterious-man-in-the-trench-coat/ */ fun main(args: Array<String>) { findBestOutcome(1, 1000, 9) } fun findBestOutcome(lowerBound: Int, upperBound: Int, maxGuesses: Int, verbose: Boolean = false) { var best = 0 var bestGuess = 0 for (guess in lowerBound..upperBound) { val outcome = outcome(lowerBound, upperBound, maxGuesses, guess) if (outcome > best) { best = outcome bestGuess = guess } if (verbose) { println(String.format("Guessing %d yields an outcome of %d", guess, outcome)) } } println(String.format("Best outcome: guess %d", bestGuess)) } /** * A measure of how profitable a guess will be - the sum of all successful amounts it can get to */ fun outcome(lowerBound: Int, upperBound: Int, maxGuesses: Int, guess: Int): Int { var outcome = 0 for (actual in lowerBound..upperBound) { val result = binary(lowerBound, upperBound, guess, actual) if (result <= maxGuesses) { outcome += actual } } return outcome } /** * Counts how many times it takes to guess the amount of money. * * This is a non-standard binary search because it allows you to start * on any number (but splits the halves after that). */ fun binary(lowerBound: Int, upperBound: Int, guess: Int, actual: Int): Int { if (lowerBound > upperBound || guess < lowerBound || guess > upperBound || actual < lowerBound || actual > upperBound) { throw IllegalArgumentException("You entered something wrong...") } var left: Int = lowerBound var right: Int = upperBound var iterations: Int = 0 var isFirst: Boolean = true while (true) { // On the first runthrough, don't calculate the midpoint; use the guess provided val current = if (isFirst) guess else (left + right) / 2 isFirst = false iterations += 1 // Each time we do this, it counts as a guess if (current == actual) { break; } else if (current < actual) { left = current + 1 } else if (current > actual) { right = current - 1 } } return iterations }
0
Kotlin
1
6
55e9d2f6c56bdf1f2f7502c23d581b59ff1d4d80
2,166
kotlin-riddler
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/TwoArraysEqualReversing.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode fun interface CanBeEqualStrategy { operator fun invoke(target: IntArray, arr: IntArray): Boolean } class CanBeEqualSort : CanBeEqualStrategy { override operator fun invoke(target: IntArray, arr: IntArray): Boolean { target.sort() arr.sort() return target.contentEquals(arr) } } class CanBeEqualMap : CanBeEqualStrategy { override operator fun invoke(target: IntArray, arr: IntArray): Boolean { val n = arr.size val map = HashMap<Int, Int?>() for (i in 0 until n) { if (!map.containsKey(arr[i])) map[arr[i]] = 1 else map[arr[i]] = map[arr[i]]!! + 1 } for (i in 0 until n) { if (!map.containsKey(target[i])) return false var count = map[target[i]]!! count-- if (count == 0) map.remove(target[i]) else map[target[i]] = count } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,544
kotlab
Apache License 2.0
app/src/test/java/tdc/com/bidirectionaldijkstrasalgorithm/model/forkotlin/BidirectionalDijkstraTest.kt
tangxiaocheng
287,857,886
false
null
package tdc.com.bidirectionaldijkstrasalgorithm.model.forkotlin import com.google.common.truth.Truth import org.junit.Test import java.util.* import java.util.Collections.sort class BidirectionalDijkstraTest { private fun Int.generateDirectedGraph( numOfNodes: Int, numOfEdges: Int, distanceUpBound: Int, directedGraph: Boolean ) { val random = Random() val graph = Graph(numOfNodes) val nodes = generateNodesSourceArr(numOfNodes) for (i in 0 until numOfEdges) { val nodePair = generateOneEdge(nodes, random) val from = nodePair[0] val to = nodePair[1] val cost = random.nextInt(distanceUpBound + 1) if (directedGraph) { graph.addDirectedEdge(from.toString(), to.toString(), cost.toDouble()) } else { graph.addUndirectedEdge(from.toString(), to.toString(), cost.toDouble()) } } val bidirectionalDijkstras = BidirectionalDijkstrasAlgorithm(graph, directedGraph) for (i in 0..this) { val randomNodePair = getRandomTwoNodes(graph.nodeSet) val start: String? = randomNodePair[0] val end: String? = randomNodePair[1] val (thePath: LinkedList<String>, shortestDistance: Double) = bidirectionalDijkstras.runBidirectionalDijkstra(start!!, end!!) Truth.assertThat(shortestDistance) .isEqualTo( getShortestDistanceFromThePath( graph, thePath ) ) println(thePath) } } private fun getShortestDistanceFromThePath(graph: Graph, thePath: LinkedList<String>): Double { if (thePath.size == 0) { return Double.POSITIVE_INFINITY } var sumPath = 0.0 val iterator = thePath.iterator() if (iterator.hasNext()) { var from: String = iterator.next() while (iterator.hasNext()) { val to = iterator.next() val edges = graph.getEdges(from) // why we sort the edges here, because in this graph which we randomly generated, it might // exist parallel edges, if so, the distance might be different. So we just fetch the // minimum. sort(edges!!) { a: Edge, b: Edge -> a.distance.compareTo(b.distance) } for (edge in edges) { if (edge.to == to) { sumPath += edge.distance break } } from = to } } return sumPath } @Test fun testBidirectionalDijkstrasAlgorithmForDirectedGraph() { 100.generateDirectedGraph(400, 8000, 800, true) } @Test fun testBidirectionalDijkstrasAlgorithmForUndirectedGraph() { 100.generateDirectedGraph(400, 8000, 800, false) } companion object { fun getRandomTwoNodes(nodeSet: MutableSet<String?>): Array<String?> { // using reservoir sample to choose two random nodes. val random = Random() val pair: Array<String?> = arrayOfNulls(2) val iterator = nodeSet.iterator() pair[0] = iterator.next() pair[1] = iterator.next() val k = 2 var j = k while (iterator.hasNext()) { j++ val node = iterator.next() val randomI = random.nextInt(j) if (randomI < k) { pair[randomI] = node } } return pair } private fun generateOneEdge(nodes: IntArray, random: Random): IntArray { // using reservoir sample to choose two random node to form an edge. val k = 2 val nodePair = IntArray(k) System.arraycopy(nodes, 0, nodePair, 0, k) for (j in k until nodes.size) { val temp = nodes[j] val randomIdx = random.nextInt(j + 1) if (randomIdx < k) { nodePair[randomIdx] = temp } } return nodePair } private fun generateNodesSourceArr(numOfNodes: Int): IntArray { val nodes = IntArray(numOfNodes) for (i in nodes.indices) { nodes[i] = i } return nodes } } }
0
Kotlin
0
0
7614166ac676114df26435c7709c7dc2d9b52875
4,604
BidirectionalDijkstrasAlgorithm
MIT License
src/main/kotlin/days_2021/Day7.kt
BasKiers
434,124,805
false
{"Kotlin": 40804}
package days_2021 import util.Day import kotlin.math.abs import kotlin.math.max import kotlin.math.min class Day7 : Day(7) { val input = inputString.split(",").map(String::toInt) val minInputVal = input.reduce { a, b -> min(a, b) } val maxInputVal = input.reduce { a, b -> max(a, b) } fun getExponentialFuelCost(num: Int) = if (num < 1) num else (1..num).reduce(Int::plus) fun getCostToTarget(positions: List<Int>, target: Int, costFunc: (num: Int) -> Int) = positions.fold(0) { fuelCost, position -> fuelCost + costFunc(abs(target - position)) } fun getMinCost(min: Int, max: Int, positions: List<Int>, costFunc: (num: Int) -> Int = { it }): Int { val step = (max - min) / 3 val left = min + step val right = max - step val leftRes = getCostToTarget(positions, left, costFunc) val rightRes = getCostToTarget(positions, right, costFunc); return if (leftRes < rightRes) { if (left == min) leftRes else getMinCost(min, right, positions, costFunc) } else { if (left == max) rightRes else getMinCost(left, max, positions, costFunc) } } override fun partOne(): Any { return getMinCost(minInputVal, maxInputVal, input) } override fun partTwo(): Any { return getMinCost(minInputVal, maxInputVal, input, ::getExponentialFuelCost) } }
0
Kotlin
0
0
870715c172f595b731ee6de275687c2d77caf2f3
1,390
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day02.kt
rogierbom1
573,165,407
false
{"Kotlin": 5253}
package main.kotlin import readInput fun String.toShape() = when (this) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> throw ShapeException.InvalidShapeException } fun String.toStrategicShape(opponentShape: Shape) = when (this) { "X" -> opponentShape.trumps() "Y" -> opponentShape "Z" -> opponentShape.losesTo() else -> throw ShapeException.InvalidShapeException } fun draw(player1: Shape, player2: Shape): Int = when(player1.value - player2.value) { -1,2 -> 6 0 -> 3 else -> 0 } fun main() { fun part1(input: List<String>): Int = input.sumOf { round -> val opponent = round.substringBefore(" ").toShape() val player = round.substringAfter(" ").toShape() draw(opponent, player) + player.value } fun part2(input: List<String>): Int = input.sumOf { round -> val opponent = round.substringBefore(" ").toShape() val player = round.substringAfter(" ").toStrategicShape(opponent) draw(opponent, player) + player.value } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b7a03e95785cb4a2ec0bfa170f4f667fc574c1d2
1,322
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/io/recursion/IntegerToRoman.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.recursion import io.utils.runTests // https://leetcode.com/problems/integer-to-roman/ class IntegerToRoman { fun execute(input: Int): String = input.toRomanNumber() } private fun Int.toRomanNumber(): String = when (this) { in Int.MIN_VALUE..0 -> "" in 1..3 -> "I".repeat(this) 4 -> "IV" in 5..8 -> "V" + (this - 5).toRomanNumber() 9 -> "IX" in 10 until 40 -> "X".repeat(this / 10) + (this.rem(10)).toRomanNumber() in 40 until 50 -> "XL" + (this - 40).toRomanNumber() in 50 until 90 -> "L" + (this - 50).toRomanNumber() in 90 until 100 -> "XC" + (this - 90).toRomanNumber() in 100 until 400 -> "C".repeat(this / 100) + (this.rem(100)).toRomanNumber() in 400 until 500 -> "CD" + (this - 400).toRomanNumber() in 500 until 900 -> "D" + (this - 500).toRomanNumber() in 900 until 1000 -> "CM" + (this - 900).toRomanNumber() else -> "M" + (this - 1000).toRomanNumber() } fun main(){ runTests(listOf( 4 to "IV", 3 to "III", 9 to "IX", 58 to "LVIII", 80 to "LXXX", 1994 to "MCMXCIV", 1989 to "MCMLXXXIX" )){(input,value) -> value to IntegerToRoman().execute(input)} }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,151
coding
MIT License
year2015/src/main/kotlin/net/olegg/aoc/year2015/day11/Day11.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2015.day11 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.series import net.olegg.aoc.year2015.DayOf2015 import java.math.BigInteger import java.math.BigInteger.ONE import java.math.BigInteger.ZERO /** * See [Year 2015, Day 11](https://adventofcode.com/2015/day/11) */ object Day11 : DayOf2015(11) { private val ALPHABET = 'a'..'z' private val MAPPINGS = ALPHABET .withIndex() .associate { (index, char) -> char to index.toBigInteger() } private val UNMAPPINGS = ALPHABET .withIndex() .associate { (index, char) -> index.toBigInteger() to char } private val TRIPLES = ALPHABET .windowed(3) .map { it.joinToString(separator = "") } private val SHIFT = 26.toBigInteger() private fun wrap(password: String): BigInteger { return password.fold(ZERO) { acc, char -> acc * SHIFT + (MAPPINGS[char] ?: ZERO) } } private fun unwrap(wrapped: BigInteger): String { return buildString { var curr = wrapped do { val (next, rem) = curr.divideAndRemainder(SHIFT) append(UNMAPPINGS[rem] ?: "?") curr = next } while (curr > ZERO) reverse() } } private fun passwordList(password: String) = generateSequence(wrap(password)) { it + ONE }.map { unwrap(it) } private fun password(password: String): String { return passwordList(password) .drop(1) .filterNot { string -> "iol".any { it in string } } .filter { string -> TRIPLES.any { it in string } } .filter { string -> string .toList() .series() .filter { it.second > 1 } .sumOf { it.second } > 3 } .first() } override fun first(): Any? { return password(data) } override fun second(): Any? { return password(password(data)) } } fun main() = SomeDay.mainify(Day11)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,859
adventofcode
MIT License
src/chapter1/section4/ex15a_TwoSumFaster.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter1.section4 import extensions.inputPrompt import extensions.readAllInts /** * 快速3-sum * 作为热身,使用一个线性级别的算法(而非基于二分查找的线性对数级别的算法) * 实现TwoSumFaster来计算已排序的数组中和为0的整数对的数量。 * 用相同的思想为3-sum问题给出一个平方级别的算法。 * * 解:先找到值为0的元素数量,当多于一个时,用组合公式计算组合数,需要查找N次 * 从两侧向中间查找,如果和大于0,右侧向左移一位,和小于0,左侧向右移一位 * 如果和为0,判断元素值是否为0,为0则直接结束(因为第一步已经计算过包含0的组合数了) * 如果元素不为0,分别判断左侧相等的元素数量和右侧相等的元素数量,相乘后就是总的组合数 */ fun ex15a_TwoSumFaster(array: IntArray): Long { require(array.size > 1) fun getZeroCount(array: IntArray): Int { var count = 0 array.forEach { if (it == 0) count++ } return count } var count = 0L var left = 0 var right = array.size - 1 val zeroCount = getZeroCount(array) if (zeroCount > 1) { count += combination(zeroCount, 2) } while (left < right) { when { array[left] + array[right] > 0 -> right-- array[left] + array[right] < 0 -> left++ else -> { val value = array[left] if (value == 0) return count var leftEqualCount = 1 //因为上面value==0时直接return,当索引left>=right时和不可能为0 while (array[++left] == value) { leftEqualCount++ } var rightEqualCount = 1 while (array[--right] == -value) { rightEqualCount++ } count += leftEqualCount * rightEqualCount } } } return count } fun main() { inputPrompt() //-2 -1 -1 -1 0 0 0 1 1 2 3 4 5 val array = readAllInts() println("twoSum: count=${twoSum(array)}") array.sort() println("ex15a: count=${ex15a_TwoSumFaster(array)}") }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,246
Algorithms-4th-Edition-in-Kotlin
MIT License
2020/kotlin/day-8/main.kt
waikontse
330,900,073
false
null
import util.FileUtils data class Accumulator(val acc: Int) data class ProgramCounter(val pc: Int) data class CPU(val acc: Accumulator, val pc: ProgramCounter) fun main() { val fileUtils: FileUtils = FileUtils("input.txt") fileUtils.printLines() // Challenge #1 val cpu: CPU = runProgram1(fileUtils.lines) println ("Challenge #1 CPU values: $cpu") // Challenge #2 val cpu2: CPU = runProgram2(fileUtils.lines) println ("Challenge #2 CPU values: $cpu2") } fun runProgram1(program: List<String>): CPU { return runProgram1Helper(program, CPU(Accumulator(0), ProgramCounter(0)), mutableSetOf<Int>()) } // Code for solving 2nd challenge fun runProgram2(program: List<String>): CPU { // Create a zipped list, appending an index to the instruction // modify the operand and run the program val endStates: List<CPU> = (0..program.size).toList().zip(program) .filter { (_, item) -> item.startsWith("nop") || item.startsWith("jmp") } .map { (index, item) -> Pair(index, flipOperator(item)) } .map { patch -> patchProgram(program, patch) } .map { patchedProgram -> runProgram1Helper(patchedProgram, CPU(Accumulator(0), ProgramCounter(0)), mutableSetOf<Int>()) } // Filter the correct ended program return endStates.first { cpu -> cpu.pc.pc == program.size } } // Code for solving 1st challenge fun runProgram1Helper(program: List<String>, cpu: CPU, seen: MutableSet<Int>): CPU { if (seen.contains(cpu.pc.pc) || cpu.pc.pc >= program.size || cpu.pc.pc < 0) { return cpu } // Execute current line val newCPU: CPU = executeLine(program, cpu, seen); return runProgram1Helper(program, newCPU, seen); } fun executeLine(program: List<String>, cpu: CPU, seen: MutableSet<Int>): CPU { val op: Pair<String, Int> = tokenize(program[cpu.pc.pc]) val newCPU: CPU = when(op.first) { "nop" -> nop(cpu, seen) "acc" -> acc(cpu, seen, op.second) "jmp" -> jmp(cpu, seen, op.second) else -> cpu } return newCPU } fun tokenize(line: String): Pair<String, Int> { val tokenized: List<String> = line.split(" ") return Pair(tokenized[0], Integer.parseInt(tokenized[1])) } fun nop(cpu: CPU, seen: MutableSet<Int>): CPU { seen.add(cpu.pc.pc) return cpu.copy(pc = ProgramCounter(cpu.pc.pc + 1)) } fun acc(cpu: CPU, seen: MutableSet<Int>, operand: Int): CPU { seen.add(cpu.pc.pc) return cpu.copy(acc = Accumulator(cpu.acc.acc + operand), ProgramCounter(cpu.pc.pc + 1)) } fun jmp(cpu: CPU, seen: MutableSet<Int>, operand: Int): CPU { seen.add(cpu.pc.pc) return cpu.copy(pc = ProgramCounter(cpu.pc.pc + operand)) } // Code needed for solving the 2nd challenge fun patchProgram(program: List<String>, patch: Pair<Int, String>): List<String> { val mutableProgram = program.toMutableList() mutableProgram.set(patch.first, patch.second); return mutableProgram.toList(); } fun flipOperator(op: String): String { if (op.startsWith("nop")) { return op.replace("nop", "jmp") } else { return op.replace("jmp", "nop") } }
0
Kotlin
0
0
abeb945e74536763a6c72cebb2b27f1d3a0e0ab5
3,152
advent-of-code
Creative Commons Zero v1.0 Universal
src/main/kotlin/g1801_1900/s1840_maximum_building_height/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1840_maximum_building_height // #Hard #Array #Math #2023_06_22_Time_1210_ms_(100.00%)_Space_118.6_MB_(100.00%) class Solution { fun maxBuilding(n: Int, restrictions: Array<IntArray>): Int { if (restrictions.isEmpty()) { return n - 1 } val m = restrictions.size restrictions.sortWith(compareBy { a: IntArray -> a[0] }) for (i in m - 2 downTo 0) { restrictions[i][1] = restrictions[i][1].coerceAtMost(restrictions[i + 1][1] + restrictions[i + 1][0] - restrictions[i][0]) } var id = 1 var height = 0 var res = 0 for (r in restrictions) { var currMax: Int if (r[1] >= height + r[0] - id) { currMax = height + r[0] - id height = currMax } else { currMax = (height + r[0] - id + r[1]) / 2 height = r[1] } id = r[0] res = res.coerceAtLeast(currMax) } if (id != n) { res = res.coerceAtLeast(height + n - id) } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,147
LeetCode-in-Kotlin
MIT License
src/main/kotlin/wtf/log/xmas2021/day/day06/Day06.kt
damianw
434,043,459
false
{"Kotlin": 62890}
package wtf.log.xmas2021.day.day06 import wtf.log.xmas2021.Day import java.io.BufferedReader @Suppress("SameParameterValue") object Day06 : Day<List<Int>, Long, Long> { override fun parseInput(reader: BufferedReader): List<Int> { return reader.readLine().split(',').map { it.toInt() } } override fun part1(input: List<Int>): Long { return solveNaively(input, dayCount = 80) } private fun solveNaively(input: List<Int>, dayCount: Int): Long { var currentTimers = input.map { it.toLong() } repeat(dayCount) { val nextTimers = mutableListOf<Long>() var newFishCount = 0 for (timer in currentTimers) { if (timer == 0L) { nextTimers += 6L newFishCount += 1 } else { nextTimers += timer - 1L } } nextTimers += Array(newFishCount) { 8 } currentTimers = nextTimers } return currentTimers.size.toLong() } override fun part2(input: List<Int>): Long { return solveQuickly(input, dayCount = 256) } private fun solveQuickly(input: List<Int>, dayCount: Int): Long { val newByDay = LongArray(dayCount + 1) repeat(dayCount) { previousDay -> val today = previousDay + 1 val newFromSeedToday = input.count { startingValue -> (previousDay - startingValue) % 7 == 0 } var extraNewToday = 0L var lookBack = today - 9 while (lookBack >= 0) { extraNewToday += newByDay[lookBack] lookBack -= 7 } val totalNewToday = newFromSeedToday + extraNewToday newByDay[today] = totalNewToday } return input.size + newByDay.sum() } }
0
Kotlin
0
0
1c4c12546ea3de0e7298c2771dc93e578f11a9c6
1,869
AdventOfKotlin2021
BSD Source Code Attribution
src/Day10.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
import kotlin.math.absoluteValue fun main() { val testInput = readInput("Day10_test") check(part1(testInput) == 13140) val part2Test = """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """.trimIndent() check(part2(testInput) == part2Test) val input = readInput("Day10") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val cycles = calculateCycles(input) return (20..220 step 40).sumOf { cycles[it] * it } } private fun part2(input: List<String>): String { val cycles = calculateCycles(input) return (0 until 240) .joinToString("") { time -> when { (cycles[time + 1] - time % 40).absoluteValue <= 1 -> "#" else -> "." } } .chunked(40) .joinToString("\n") } private fun calculateCycles(input: List<String>): List<Int> { return listOf(1) + input.flatMap { when (it) { "noop" -> listOf(0) else -> listOf(0, it.substringAfter("addx ").toInt()) } }.runningFold(1) { acc, value -> acc + value } }
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
1,371
aoc-22
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions42.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 fun test42() { intArrayOf(1, -2, 3, 10, -4, 7, 2, -5).printlnResult() intArrayOf().printlnResult() intArrayOf(1, 1, 1, 1, 1, 1, 1, 1).printlnResult() intArrayOf(-1, -1, -1, -1, -1, -1, -1, -1).printlnResult() } /** * Questions 42: Find the biggest sum of sub-array in a IntArray */ private fun IntArray.getBiggestSubArraySum(): Int { var biggest = 0 var preSum = 0 forEachIndexed { index, i -> preSum = if (index == 0 || preSum <= 0) i else preSum + i if (preSum > biggest) biggest = preSum } return biggest } private fun IntArray.printlnResult() = println("The biggest sum of sub-array in IntArray: ${toList()} is: ${getBiggestSubArraySum()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
757
Algorithm
Apache License 2.0
day-4/src/Part1.kt
woojiahao
225,170,972
false
null
fun pairInput(i: Int, predicate: (Int, Int) -> Boolean) = i.toString().zipWithNext { a, b -> predicate(a.toInt(), b.toInt()) } fun hasRepeating(i: Int) = pairInput(i) { a, b -> a == b }.any { it } fun isAscending(i: Int) = pairInput(i) { a, b -> a <= b }.all { it } fun validate(i: Int) = hasRepeating(i) && isAscending(i) fun solve(lower: Int, upper: Int) = (lower..upper).filter { validate(it) }.size fun main() = timeAndAnswer(::solve)
0
Kotlin
0
2
4c9220a49dbc093fbe7f0d6692fa0390a63e702a
446
aoc-19
MIT License
test/leetcode/TwoSum.kt
andrej-dyck
340,964,799
false
null
package leetcode import lib.IntArrayArg import org.assertj.core.api.Assertions import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.converter.ConvertWith import org.junit.jupiter.params.provider.CsvSource /** * https://leetcode.com/problems/two-sum/ * * 1. Two Sum * [Easy] * * Given an array of integers nums and an integer target, * return indices of the two numbers such that they add up to target. * * You may assume that each input would have exactly one solution, * and you may not use the same element twice. * * You can return the answer in any order. * * Constraints: * - 2 <= nums.length <= 104 * - -109 <= nums[i] <= 109 * - -109 <= target <= 109 * - Only one valid answer exists. */ fun twoSum(nums: Array<Int>, target: Int) = twoSumRec(nums.asSequence().withIndex(), target) ?: throw IllegalArgumentException("no valid answer exists") @Suppress("NestedBlockDepth") private tailrec fun twoSumRec( nums: Sequence<IndexedValue<Int>>, target: Int, seenValues: Map<Int, Int> = emptyMap() ): Pair<Int, Int>? { val (head, tails) = nums.firstOrNull() to nums.drop(1) return if(head == null) null else when (val otherIndex = seenValues[target - head.value]) { null -> twoSumRec(tails, target, seenValues = seenValues + (head.value to head.index)) else -> otherIndex to head.index } } /** * Unit Tests */ class TwoSumTest { @ParameterizedTest @CsvSource( "[2,7,11,15]; 9; (0,1)", "[3,2,4]; 6; (1,2)", "[3,3]; 6; (0,1)", delimiter = ';' ) fun `indices of the numbers in nums with nums_i1 + nums_i2 = target`( @ConvertWith(IntArrayArg::class) nums: Array<Int>, target: Int, expectedIndices: String ) { Assertions.assertThat( twoSum(nums, target) ).isEqualTo( expectedIndices.toIntPair() ) } } private fun String.toIntPair() = removeSurrounding("(", ")") .split(",") .let { it[0].toInt() to it[1].toInt() }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
2,067
coding-challenges
MIT License
year2019/day03/wire/src/main/kotlin/com/curtislb/adventofcode/year2019/day03/wire/Wire.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2019.day03.wire import com.curtislb.adventofcode.common.geometry.Direction import com.curtislb.adventofcode.common.geometry.Point import com.curtislb.adventofcode.common.geometry.Segment /** * A wire consisting of a series of segments laid out in a 2D grid. * * @param wireString A string representation of the wire, where each comma-separated value * represents the [Direction] and length of the next wire segment (e.g. `"U3"` for [Direction.UP], * length 3), starting from the point `(0, 0)`. */ class Wire(wireString: String) { /** * A list containing all segments of the wire in order. */ private val segments: List<Segment> init { val segmentStrings = wireString.split(',') val segmentArrayList = ArrayList<Segment>(segmentStrings.size) var start = Point.ORIGIN for (segmentString in segmentStrings) { // Construct each segment and add it to the list in order val direction = Direction.fromChar(segmentString[0]) val length = segmentString.substring(1).toInt() val segment = Segment.from(start, direction, length) segmentArrayList.add(segment) // The next segment starts from the opposite end of the current one start = segment.otherEndpoint(start) } segments = segmentArrayList } /** * Finds the intersection point of this wire and [other] that is closest to the origin `(0, 0)`. * * The origin is not considered an intersection point unless both wires return to that point. * Additionally, parallel wire segments are not considered intersecting, even if they overlap at * one or more points. * * @return A pair containing the nearest intersection point and its Manhattan distance from the * origin. If this wire and [other] do not intersect, this function instead returns * [NO_INTERSECT]. */ infix fun nearestIntersect(other: Wire): Pair<Point?, Int> { var bestIntersection: Point? = null var bestDistance = Int.MAX_VALUE segments.forEachIndexed { i, segment -> other.segments.forEachIndexed { j, otherSegment -> // Ignore the "intersection" of the first two segments at the origin if (i != 0 || j != 0) { // Check for a new nearest intersection point val intersection = segment intersect otherSegment val distance = intersection?.manhattanDistance(Point.ORIGIN) ?: Int.MAX_VALUE if (distance < bestDistance) { bestIntersection = intersection bestDistance = distance } } } } return Pair(bestIntersection, bestDistance) } /** * Finds the intersection point of this wire and [other] with the shortest combined distance * along both wires from the origin `(0, 0)` to that point. * * The origin is not considered an intersection point unless both wires return to that point. * Additionally, parallel wire segments are not considered intersecting, even if they overlap at * one or more points. * * @return A pair containing the shortest-path intersection point and its total distance along * both wires. If this wire and [other] do not intersect, this function instead returns * [NO_INTERSECT]. */ infix fun shortestIntersect(other: Wire): Pair<Point?, Int> { var bestIntersection: Point? = null var bestLength = Int.MAX_VALUE var pathLength = 0 var segmentStart = Point.ORIGIN segments.forEachIndexed { i, segment -> var otherPathLength = 0 var otherSegmentStart = Point.ORIGIN other.segments.forEachIndexed { j, otherSegment -> // Ignore the "intersection" of the first two segments at the origin if (i != 0 || j != 0) { val intersection = segment intersect otherSegment if (intersection != null) { // Calculate the total path length to this intersection point val totalPathLength = pathLength + otherPathLength + (segmentStart manhattanDistance intersection) + (otherSegmentStart manhattanDistance intersection) // Check if we've found a new shortest (nonzero length) path intersection if (totalPathLength in 1 until bestLength) { bestIntersection = intersection bestLength = totalPathLength } } } otherPathLength += otherSegment.distance otherSegmentStart = otherSegment.otherEndpoint(otherSegmentStart) } pathLength += segment.distance segmentStart = segment.otherEndpoint(segmentStart) } return Pair(bestIntersection, bestLength) } companion object { /** * Placeholder value returned by [Wire.nearestIntersect] and [Wire.shortestIntersect] if the * wires do not intersect. */ val NO_INTERSECT: Pair<Point?, Int> = Pair(null, Int.MAX_VALUE) } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
5,409
AdventOfCode
MIT License
src/org/aoc2021/Day21.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path import kotlin.math.max object Day21 { data class Key(val p1Pos: Int, val p1Score: Int, val p2Pos: Int, val p2Score: Int, val isP1Turn: Boolean) private fun solvePart1(lines: List<String>): Int { var (p1Pos, p2Pos) = parseStartingPositions(lines) var die = 1 var rolls = 0 var p1Score = 0 var p2Score = 0 while (true) { (1..3).forEach { _ -> p1Pos += die die = (die % 100) + 1 rolls++ } p1Pos = ((p1Pos - 1) % 10) + 1 p1Score += p1Pos if (p1Score >= 1000) { return rolls * p2Score } (1..3).forEach { _ -> p2Pos += die die = (die % 100) + 1 rolls++ } p2Pos = ((p2Pos - 1) % 10) + 1 p2Score += p2Pos if (p2Score >= 1000) { return rolls * p1Score } } } private fun solvePart2(lines: List<String>): Long { val (start1, start2) = parseStartingPositions(lines) val (p1Wins, p2Wins) = computeWinningUniverses(Key(start1, 0, start2, 0, true)) return max(p1Wins, p2Wins) } private fun computeWinningUniverses( key: Key, memoizedResults: MutableMap<Key, Pair<Long, Long>> = mutableMapOf(), ): Pair<Long, Long> { memoizedResults[key]?.let { return it } if (key.p1Score >= 21) { return 1L to 0L } if (key.p2Score >= 21) { return 0L to 1L } var p1WinSum = 0L var p2WinSum = 0L for (i in 1..3) { for (j in 1..3) { for (k in 1..3) { val (newP1Pos, newP1Score) = if (key.isP1Turn) { computeNewPosScore(key.p1Pos, key.p1Score, i, j, k) } else { key.p1Pos to key.p1Score } val (newP2Pos, newP2Score) = if (!key.isP1Turn) { computeNewPosScore(key.p2Pos, key.p2Score, i, j, k) } else { key.p2Pos to key.p2Score } val newKey = Key(newP1Pos, newP1Score, newP2Pos, newP2Score, !key.isP1Turn) val (p1Wins, p2Wins) = computeWinningUniverses(newKey, memoizedResults) p1WinSum += p1Wins p2WinSum += p2Wins } } } memoizedResults[key] = p1WinSum to p2WinSum return p1WinSum to p2WinSum } private fun computeNewPosScore(pos: Int, score: Int, i: Int, j: Int, k: Int): Pair<Int, Int> { val newPos = ((pos + i + j + k - 1) % 10) + 1 return newPos to (score + newPos) } private fun parseStartingPositions(lines: List<String>): Pair<Int, Int> { return lines[0].split(" ").last().toInt() to lines[1].split(" ").last().toInt() } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input21.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
3,360
advent-of-code-2021
The Unlicense
year2021/day14/polymer/src/main/kotlin/com/curtislb/adventofcode/year2021/day14/polymer/PolymerizationProcess.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2021.day14.polymer import com.curtislb.adventofcode.common.collection.Counter import com.curtislb.adventofcode.common.collection.mapToMap import com.curtislb.adventofcode.common.comparison.minMaxByOrNull import com.curtislb.adventofcode.common.io.forEachSection import java.io.File /** * The specifications for a polymerization process, consisting of an initial polymer template and a * collection of rules describing how that template changes during each step. * * @param template A string of elements (represented as [Char]s) that form the initial polymer. * @param insertionRuleStrings An unordered collection of strings, representing pair insertion rules * that are applied to the current polymer during each step of the process. Each string must be of * the form `"$A$B -> $C"`, where each of `A`, `B`, and `C` is a single non-whitespace [Char], * representing an element. See [applyPairInsertions] for information on how the rules are applied. */ class PolymerizationProcess(val template: String, insertionRuleStrings: Collection<String>) { /** * A map from pairs of adjacent elements to the element that should be inserted between them * during each step of the process. */ val insertionRules: Map<Pair<Char, Char>, Char> = insertionRuleStrings.mapToMap { ruleString -> val matchResult = INSERTION_RULE_REGEX.matchEntire(ruleString) require(matchResult != null) { "Malformed insertion rule string: $ruleString" } val (pairFirstString, pairSecondString, elementString) = matchResult.destructured val pair = Pair(pairFirstString.first(), pairSecondString.first()) val element = elementString.first() pair to element } /** * A [Counter] of element [Char]s in the current polymer string. */ private val elementCounts = Counter<Char>().apply { addAll(template.asIterable()) } /** * A [Counter] of adjacent element [Pair]s in the current polymer string. */ private var pairCounts = Counter<Pair<Char, Char>>().apply { for (index in 0 until template.length - 1) { val element = template[index] val nextElement = template[index + 1] this[Pair(element, nextElement)]++ } } /** * Runs the polymerization process for a number of steps equal to [stepCount]. * * During each step of the process, the current polymer is modified by applying [insertionRules] * simultaneously to all adjacent element pairs in the polymer. Specifically, for each pair of * elements with a corresponding [Pair] key in [insertionRules], the [Char] value for that key * is inserted between those elements in the polymer. */ fun applyPairInsertions(stepCount: Int = 1) { repeat(stepCount) { val newPairCounts = Counter<Pair<Char, Char>>() for ((pair, count) in pairCounts.entries) { val element = insertionRules[pair] if (element != null) { newPairCounts[Pair(pair.first, element)] += count newPairCounts[Pair(element, pair.second)] += count } else { newPairCounts[pair] += count } } pairCounts = newPairCounts } elementCounts.clear() for ((pair, count) in pairCounts.entries) { elementCounts[pair.first] += count } elementCounts[template.last()]++ } /** * Returns the difference in quantities between the most common element and least common element * in the current polymer. */ fun maxElementCountDifference(): Long { val minMaxEntries = elementCounts.entries.minMaxByOrNull { it.value } val maxCount = minMaxEntries?.max?.value ?: 0L val minCount = minMaxEntries?.min?.value ?: 0L return maxCount - minCount } companion object { /** * A regex matching the string representation of a pair insertion rule. */ private val INSERTION_RULE_REGEX = Regex("""\s*(\S)(\S)\s*->\s*(\S)\s*""") /** * Returns a [PolymerizationProcess] from a [file] with the following contents: * * ``` * $template * * $insertionRuleString1 * $insertionRuleString2 * ... * $insertionRuleStringN * ``` * * `template` is a string representing the initial polymer, and each `insertionRuleString` * must be a string of the form `"$A$B -> $C"`, representing an insertion rule. * * @throws IllegalArgumentException If the contents of [file] don't match the required * format. */ fun fromFile(file: File): PolymerizationProcess { val sections = mutableListOf<List<String>>() file.forEachSection { sections.add(it) } require(sections.size == 2) { "Malformed input file: $file" } val template = sections[0].first().trim() val insertionRuleStrings = sections[1] return PolymerizationProcess(template, insertionRuleStrings) } } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
5,220
AdventOfCode
MIT License
src/main/kotlin/day07/part2/main.kt
TheMrMilchmann
225,375,010
false
null
/* * Copyright (c) 2019 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package day07.part2 import utils.* import java.lang.Exception import kotlin.math.* fun main() { val input = readInputText("/day07/input.txt") val program = input.split(',').map(String::toInt) val phases = (5..9).toList() fun <T, O> List<T>.cartesianProduct(other: List<O>): List<Pair<T, O>> = flatMap { t -> other.map { o -> t to o } } val permutations = phases.cartesianProduct(phases).flatMap { (a, b) -> phases.cartesianProduct(phases).flatMap { (c, d) -> phases.map { e -> listOf(a, b, c, d, e) } } }.filter { list -> list.groupBy { it }.map { it.value.size }.max() == 1 } val signal = permutations.map { phaseSettings -> var signal = 0 var turn = 0 val nextInput = sequence { yieldAll(phaseSettings) while (true) yield(signal) }.iterator()::next val inputFun = fun IntComputer.(id: Int): Int { if (turn == id) { turn = (turn + 1) % phaseSettings.size return nextInput() } else { suspend() } } val computers = sequence { val tmp = phaseSettings.mapIndexed { index, _ -> IntComputer(program, { inputFun(index) }) { output -> signal = output } } while (true) yieldAll(tmp) }.iterator() var current: IntComputer var id = 0 do { current = computers.next() id = (id + 1) % phaseSettings.size } while (!(current.run() && id == 0)) return@map signal }.max() println(signal) } private class IntComputer( program: List<Int>, private val input: IntComputer.() -> Int, private val output: (Int) -> Unit ) { private val memory = program.toMutableList() var instrPtr = 0 fun run(): Boolean { while (true) { val instr = memory[instrPtr] fun modeOf(param: Int) = ((instr / (10.0.pow(param + 1))) % 10).toInt() fun read(param: Int) = when (val mode = modeOf(param)) { 0 -> memory[memory[instrPtr + param]] 1 -> memory[instrPtr + param] else -> error("Encountered unexpected mode during read: $mode") } fun write(param: Int, value: Int): Unit = when (val mode = modeOf(param)) { 0 -> memory[memory[instrPtr + param]] = value else -> error("Encountered unexpected mode during write: $mode") } when (val opcode = instr % 100) { 1 -> { write(3, read(1) + read(2)) instrPtr += 4 } 2 -> { write(3, read(1) * read(2)) instrPtr += 4 } 3 -> { try { write(1, input()) instrPtr += 2 } catch (e: SuspendException) { return false } } 4 -> { output(read(1)) instrPtr += 2 } 5 -> { if (read(1) != 0) instrPtr = read(2) else instrPtr += 3 } 6 -> { if (read(1) == 0) instrPtr = read(2) else instrPtr += 3 } 7 -> { write(3, if (read(1) < read(2)) 1 else 0) instrPtr += 4 } 8 -> { write(3, if (read(1) == read(2)) 1 else 0) instrPtr += 4 } 99 -> return true else -> error("Encountered unexpected opcode: $opcode") } } } fun suspend(): Nothing { throw SuspendException() } private class SuspendException : Exception() }
0
Kotlin
0
1
9d6e2adbb25a057bffc993dfaedabefcdd52e168
5,238
AdventOfCode2019
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ClimbingStairs.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.pow import kotlin.math.sqrt /** * 70. Climbing Stairs * @see <a href="https://leetcode.com/problems/climbing-stairs">Source</a> */ fun interface ClimbingStairsStrategy { operator fun invoke(n: Int): Int } class ClimbingStairsBruteForce : ClimbingStairsStrategy { override operator fun invoke(n: Int): Int { return climbStairs(0, n) } private fun climbStairs(i: Int, n: Int): Int { if (i > n) { return 0 } return if (i == n) { 1 } else { climbStairs(i + 1, n) + climbStairs(i + 2, n) } } } class ClimbingStairsRecursionMemo : ClimbingStairsStrategy { override operator fun invoke(n: Int): Int { val memo = IntArray(n + 1) return climbStairs(0, n, memo) } private fun climbStairs(i: Int, n: Int, memo: IntArray): Int { if (i > n) { return 0 } if (i == n) { return 1 } if (memo[i] > 0) { return memo[i] } memo[i] = climbStairs(i + 1, n, memo) + climbStairs(i + 2, n, memo) return memo[i] } } class ClimbingStairsDP : ClimbingStairsStrategy { override operator fun invoke(n: Int): Int { if (n == 1) { return 1 } else if (n == 0) { return 0 } val dp = IntArray(n + 1) dp[1] = 1 dp[2] = 2 for (i in 3..n) { dp[i] = dp[i - 1] + dp[i - 2] } return dp[n] } } class ClimbingStairsFibonacci : ClimbingStairsStrategy { override operator fun invoke(n: Int): Int { if (n == 1) { return 1 } var first = 1 var second = 2 for (i in 3..n) { val third = first + second first = second second = third } return second } } class ClimbingStairsBinetsMethod : ClimbingStairsStrategy { override operator fun invoke(n: Int): Int { val q = arrayOf(intArrayOf(1, 1), intArrayOf(1, 0)) val res = pow(q, n) return res[0][0] } private fun pow(arr: Array<IntArray>, s: Int): Array<IntArray> { var a = arr var n = s var ret: Array<IntArray> = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1)) while (n > 0) { if (n and 1 == 1) { ret = multiply(ret, a) } n = n shr 1 a = multiply(a, a) } return ret } private fun multiply(a: Array<IntArray>, b: Array<IntArray>): Array<IntArray> { val c = Array(2) { IntArray(2) } for (i in 0..1) { for (j in 0..1) { c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] } } return c } } class ClimbingStairsFibonacciFormula : ClimbingStairsStrategy { override operator fun invoke(n: Int): Int { val sqrt5 = sqrt(FIB_FORMULA_VALUE) val firstPart = 1.plus(sqrt5).div(2).pow(n.plus(1).toDouble()) val secondPart = 1.minus(sqrt5).div(2).pow((n + 1).toDouble()) val fibN = firstPart - secondPart return fibN.div(sqrt5).toInt() } companion object { private const val FIB_FORMULA_VALUE = 5.0 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,913
kotlab
Apache License 2.0
jvm_sandbox/projects/advent_of_code/src/main/kotlin/year2021/Day4.kt
jduan
166,515,850
false
{"Rust": 876461, "Kotlin": 257167, "Java": 139101, "Python": 114308, "Vim Script": 100117, "Shell": 96665, "C": 67784, "Starlark": 23497, "JavaScript": 20939, "HTML": 12920, "Ruby": 5087, "Thrift": 4518, "Nix": 2919, "HCL": 1069, "Lua": 926, "CSS": 826, "Assembly": 761, "Makefile": 591, "Haskell": 585, "Dockerfile": 501, "Scala": 322, "Smalltalk": 270, "CMake": 252, "Smarty": 97, "Clojure": 91}
package year2021 import java.io.File import java.lang.RuntimeException class Board(private val board: List<List<Int>>) { private val state: MutableMap<Pair<Int, Int>, Boolean> = mutableMapOf() init { for (i in board.indices) { for (j in 0 until board[0].size) { state[Pair(i, j)] = false } } } fun playBingo(num: Int) { for (i in board.indices) { for (j in 0 until board[0].size) { if (board[i][j] == num) { state[Pair(i, j)] = true } } } } fun checkState(): Boolean { // check all rows for (i in board.indices) { val row = mutableListOf<Boolean>() for (j in 0 until board[0].size) { row.add(state[Pair(i, j)]!!) } if (row.all { it }) { return true } } // check all columns for (col in 0 until board[0].size) { val bools = mutableListOf<Boolean>() for (row in board.indices) { bools.add(state[Pair(row, col)]!!) } if (bools.all { it }) { return true } } return false } fun remainingSum(): Int { var sum = 0 for (i in board.indices) { for (j in 0 until board[0].size) { if (! state[Pair(i, j)]!!) { sum += board[i][j] } } } return sum } } fun countScore(inputFile: String): Int { val (firstLine, boards) = processInput(inputFile) firstLine.forEach { num -> boards.forEach { board -> board.playBingo(num) if (board.checkState()) { return num * board.remainingSum() } } } throw RuntimeException("Failed to find a board that wins") } // let the squid win fun countScore2(inputFile: String): Int { var (firstLine, boards) = processInput(inputFile) var count = 0 val totalBoards = boards.size firstLine.forEach { num -> val remainingBoards = mutableListOf<Board>() boards.forEach { board -> board.playBingo(num) if (board.checkState()) { count++ } else { remainingBoards.add(board) } if (count == totalBoards) { // last board return num * board.remainingSum() } } boards = remainingBoards } throw RuntimeException("Failed to find a board that wins last") } private fun processInput(inputFile: String): Pair<List<Int>, List<Board>> { val file = File(inputFile) val lines = file.readLines() val firstLine = lines.first().split(",").map { Integer.parseInt(it) } val boards = mutableListOf<Board>() val board = mutableListOf<List<Int>>() lines.drop(1).forEach { line -> if (line.isEmpty()) { if (board.isNotEmpty()) { boards.add(Board(board.toList())) board.clear() } } else { board.add(line.split(" ").filterNot { it.isEmpty() }.map { Integer.parseInt(it) }) } } return Pair(firstLine, boards) }
58
Rust
1
0
d5143e89ce25d761eac67e9c357620231cab303e
3,335
cosmos
MIT License
src/main/kotlin/day19.kt
Gitvert
433,947,508
false
{"Kotlin": 82286}
fun day19() { val lines: List<String> = readFile("day19.txt") day19part1(lines) day19part2(lines) } fun day19part1(lines: List<String>) { val scanner0 = initScanner0(lines.subList(0, lines.indexOf("--- scanner 1 ---"))) val unknownRotationScanners = initUnknownRotationScanners(lines.subList(lines.indexOf("--- scanner 1 ---"), lines.size)) findAllBeacons(scanner0, unknownRotationScanners) val answer = scanner0.beacons.size println("19a: $answer") } fun day19part2(lines: List<String>) { val scanner0 = initScanner0(lines.subList(0, lines.indexOf("--- scanner 1 ---"))) val unknownRotationScanners = initUnknownRotationScanners(lines.subList(lines.indexOf("--- scanner 1 ---"), lines.size)) findAllBeacons(scanner0, unknownRotationScanners) val scannerPositions = mutableListOf<Position>() scannerPositions.add(scanner0.position) unknownRotationScanners.forEach { scannerPositions.add(it.position!!) } var maxManhattanDistance = -1 for (i in 0 until scannerPositions.size) { for (j in 0 until scannerPositions.size) { val manhattanDistance = findManhattanDistance(scannerPositions[i], scannerPositions[j]) if (manhattanDistance > maxManhattanDistance) { maxManhattanDistance = manhattanDistance } } } val answer = maxManhattanDistance println("19b: $answer") } fun findManhattanDistance(s1: Position, s2: Position): Int { return kotlin.math.abs(s1.x - s2.x) + kotlin.math.abs(s1.y - s2.y) + kotlin.math.abs(s1.z - s2.z) } fun findAllBeacons(scanner0: Scanner, unknownRotationScanners: List<UnknownRotationScanner>) { findBeaconDistances(scanner0) unknownRotationScanners.forEach { findUnknownRotationScannerBeaconDistances(it) } for (element in unknownRotationScanners) { findOverlappers(scanner0, element) } for (element in unknownRotationScanners) { findOverlappers(scanner0, element) } for (element in unknownRotationScanners) { findOverlappers(scanner0, element) } for (element in unknownRotationScanners) { findOverlappers(scanner0, element) } } fun findRelativePosition(o1: List<Beacon>, o2: List<Beacon>, s1: Scanner, beaconsToAdd: Set<Beacon>): Position { val xAdd = mutableListOf<Int>() val xSubtract = mutableListOf<Int>() val yAdd = mutableListOf<Int>() val ySubtract = mutableListOf<Int>() val zAdd = mutableListOf<Int>() val zSubtract = mutableListOf<Int>() for (i in o1.indices) { xAdd.add(o1[i].position.x + o2[i].position.x) xSubtract.add(o1[i].position.x - o2[i].position.x) yAdd.add(o1[i].position.y + o2[i].position.y) ySubtract.add(o1[i].position.y - o2[i].position.y) zAdd.add(o1[i].position.z + o2[i].position.z) zSubtract.add(o1[i].position.z - o2[i].position.z) } val addX = xAdd.all { it == xAdd.first() } val addY = yAdd.all { it == yAdd.first() } val addZ = zAdd.all { it == zAdd.first() } val x = if (addX) { xAdd.first() } else { xSubtract.first() } val y = if (addY) { yAdd.first() } else { ySubtract.first() } val z = if (addZ) { zAdd.first() } else { zSubtract.first() } val newPosition = Position( x + s1.position.x, y + s1.position.y, z + s1.position.z ) beaconsToAdd.forEach { s1.beacons.add(Beacon( Position( if (addX) { newPosition.x - it.position.x } else { newPosition.x + it.position.x }, if (addY) { newPosition.y - it.position.y } else { newPosition.y + it.position.y }, if (addZ) { newPosition.z - it.position.z } else { newPosition.z + it.position.z } ), it.distances )) } return newPosition } fun findOverlappers(s1: Scanner, s2: UnknownRotationScanner) { val overlappers0 = mutableSetOf<Beacon>() val overlappers1 = mutableSetOf<Beacon>() val beaconsToAdd = mutableSetOf<Beacon>() s1.beacons.forEach { outer -> s2.possibleBeacons.forEach { middle -> middle.forEach { inner -> val intersections = inner.distances.intersect(outer.distances.toSet()) if (intersections.size > 10 && !overlappers0.contains(outer)) { overlappers0.add(outer) overlappers1.add(inner) beaconsToAdd.addAll(middle) } } } } if (overlappers0.size > 1) { s2.position = findRelativePosition(overlappers0.toList(), overlappers1.toList(), s1, beaconsToAdd) } } fun findBeaconDistances(scanner: Scanner) { scanner.beacons.forEachIndexed { i, outer -> scanner.beacons.forEachIndexed inner@ { j, inner -> if (i == j) { return@inner } val xDist = kotlin.math.abs(outer.position.x - inner.position.x) val yDist = kotlin.math.abs(outer.position.y - inner.position.y) val zDist = kotlin.math.abs(outer.position.z - inner.position.z) outer.distances.add(BeaconDistance(xDist, yDist, zDist)) } } } fun findUnknownRotationScannerBeaconDistances(scanner: UnknownRotationScanner) { scanner.possibleBeacons.forEach { it.forEachIndexed { i, outer -> it.forEachIndexed inner@ { j, inner -> if (i == j) { return@inner } val xDist = kotlin.math.abs(outer.position.x - inner.position.x) val yDist = kotlin.math.abs(outer.position.y - inner.position.y) val zDist = kotlin.math.abs(outer.position.z - inner.position.z) outer.distances.add(BeaconDistance(xDist, yDist, zDist)) } } } } fun initUnknownRotationScanners(lines: List<String>): List<UnknownRotationScanner> { val scanners = mutableListOf<UnknownRotationScanner>() var currentScanner: UnknownRotationScanner? = null var beaconSet = mutableSetOf<Beacon>() lines.forEachIndexed { index, it -> if (it.contains("scanner")) { if (currentScanner != null) { currentScanner!!.possibleBeacons = mutableListOf(beaconSet) beaconSet = mutableSetOf() } val id = Integer.valueOf(it.substring("\\d+".toRegex().find(it)!!.range)) currentScanner = UnknownRotationScanner(id, mutableListOf(mutableSetOf()), null ) scanners.add(currentScanner!!) } else if (it.isNotEmpty()) { val coordinates = it.split(",") val xCoordinate = Integer.valueOf(coordinates[0]) val yCoordinate = Integer.valueOf(coordinates[1]) val zCoordinate = Integer.valueOf(coordinates[2]) beaconSet.add(Beacon(Position(xCoordinate, yCoordinate, zCoordinate), mutableListOf())) } } currentScanner!!.possibleBeacons = mutableListOf(beaconSet) scanners.forEach { var additionalBeaconSet = mutableSetOf<Beacon>() it.possibleBeacons.toList()[0].forEach { beacon -> additionalBeaconSet.add(Beacon(Position(beacon.position.x, beacon.position.z, beacon.position.y), mutableListOf())) } it.possibleBeacons.add(additionalBeaconSet) additionalBeaconSet = mutableSetOf() it.possibleBeacons.toList()[0].forEach { beacon -> additionalBeaconSet.add(Beacon(Position(beacon.position.y, beacon.position.x, beacon.position.z), mutableListOf())) } it.possibleBeacons.add(additionalBeaconSet) additionalBeaconSet = mutableSetOf() it.possibleBeacons.toList()[0].forEach { beacon -> additionalBeaconSet.add(Beacon(Position(beacon.position.y, beacon.position.z, beacon.position.x), mutableListOf())) } it.possibleBeacons.add(additionalBeaconSet) additionalBeaconSet = mutableSetOf() it.possibleBeacons.toList()[0].forEach { beacon -> additionalBeaconSet.add(Beacon(Position(beacon.position.z, beacon.position.x, beacon.position.y), mutableListOf())) } it.possibleBeacons.add(additionalBeaconSet) additionalBeaconSet = mutableSetOf() it.possibleBeacons.toList()[0].forEach { beacon -> additionalBeaconSet.add(Beacon(Position(beacon.position.z, beacon.position.y, beacon.position.x), mutableListOf())) } it.possibleBeacons.add(additionalBeaconSet) } return scanners } fun initScanner0(lines: List<String>): Scanner { val scanner0 = Scanner(0, mutableSetOf(), Position(0, 0, 0)) lines.forEach { if (!it.contains("scanner")) { if (it.isEmpty()) { return scanner0 } else { val coordinates = it.split(",") val xCoordinate = Integer.valueOf(coordinates[0]) val yCoordinate = Integer.valueOf(coordinates[1]) val zCoordinate = Integer.valueOf(coordinates[2]) scanner0.beacons.add(Beacon(Position(xCoordinate, yCoordinate, zCoordinate), mutableListOf())) } } } return scanner0 } data class Position(val x: Int, val y: Int, val z: Int) data class BeaconDistance(val x: Int, val y: Int, val z: Int) class Beacon(val position: Position, var distances: MutableList<BeaconDistance>) { override fun equals(other: Any?): Boolean { return this::class == other!!::class && this.position == (other as Beacon).position } override fun hashCode(): Int { return position.hashCode() } } data class Scanner(val id: Int, val beacons: MutableSet<Beacon>, var position: Position) data class UnknownRotationScanner(val id: Int, var possibleBeacons: MutableList<MutableSet<Beacon>>, var position: Position?)
0
Kotlin
0
0
02484bd3bcb921094bc83368843773f7912fe757
9,877
advent_of_code_2021
MIT License
src/main/kotlin/days/day15/Day15.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day15 import days.Day class Day15 : Day(false) { override fun partOne(): Any { return readInput()[0].split(",").sumOf { inp -> var currentValue = 0 inp.forEach { c -> currentValue += c.code currentValue *= 17 currentValue %= 256 } currentValue } } override fun partTwo(): Any { val boxes: HashMap<Int, MutableList<String>> = HashMap() readInput()[0].split(",").forEach { inp -> var hash = 0 inp.substringBefore("=").substringBefore("-").forEach { c -> hash += c.code hash *= 17 hash %= 256 } if (inp.contains('-')) { boxes[hash]?.removeIf { it.contains(inp.substringBefore("-")) } } else if (inp.contains("=")) { if (boxes.containsKey(hash)) { val indexOfElement = boxes[hash]!!.indexOfFirst { it.substringBefore("=") == inp.substringBefore("=") } if (indexOfElement == -1) { boxes[hash]?.add(inp) } else { boxes[hash]?.set(indexOfElement, inp) } } else { boxes[hash] = mutableListOf(inp) } } } var result = 0 for (i in 0..255) { if (boxes.containsKey(i)) { boxes[i]?.forEachIndexed { j, label -> result += (i + 1) * (j + 1) * (label.substringAfter("=").toInt()) } } } return result } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
1,699
advent-of-code_2023
The Unlicense
src/day06/Day06.kt
Ciel-MC
572,868,010
false
{"Kotlin": 55885}
package day06 import readInput fun main() { fun String.findDistinctOf(size: Int): Int { return this.windowed(size).withIndex().first { it.value.toSet().size == size }.index + size } fun part1(input: String): Int { return input.findDistinctOf(4) } fun part2(input: String): Int { return input.findDistinctOf(14) } val testInput = readInput(6, true) testInput.drop(1).zip(listOf(5, 6, 10, 11)).forEachIndexed { index, (input, expected) -> val actual = part1(input) check(actual == expected) { "Test $index failed: expected $expected, actual $actual" } } testInput.zip(listOf(19, 23, 23, 29, 26)).forEachIndexed { index, (input, expected) -> val actual = part2(input) check(actual == expected) { "Test $index failed: expected $expected, actual $actual" } } val input = readInput(6)[0] println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7eb57c9bced945dcad4750a7cc4835e56d20cbc8
947
Advent-Of-Code
Apache License 2.0
src/Day14.kt
MickyOR
578,726,798
false
{"Kotlin": 98785}
import kotlin.math.max import kotlin.math.min fun main() { fun part1(input: List<String>): Int { val matrix = Array(1001) { CharArray(1001) } for (i in matrix.indices) { for (j in matrix[i].indices) { matrix[i][j] = '.' } } for (line in input) { var lastRow = -1 var lastCol = -1 if (line.isEmpty()) continue; var points = line.split(" -> ") for (point in points) { var (col, row) = point.split(",").map { it.toInt() } if (lastCol == -1) { lastRow = row lastCol = col continue } for (j in min(lastCol, col) .. max(lastCol, col)) { for (i in min(lastRow, row) .. max(lastRow, row)) { matrix[i][j] = '#' } } lastRow = row lastCol = col } } var ans = 0 while (true) { var row = 0 var col = 500 while (row < 1000) { if (matrix[row+1][col] == '.') { row++ continue } if (matrix[row+1][col-1] == '.') { row++ col-- continue } if (matrix[row+1][col+1] == '.') { row++ col++ continue } break } if (row == 1000) break matrix[row][col] = 'o' ans++ } return ans } fun part2(input: List<String>): Int { val matrix = Array(1001) { CharArray(3001) } for (i in matrix.indices) { for (j in matrix[i].indices) { matrix[i][j] = '.' } } var maxRow = 0 for (line in input) { var lastRow = -1 var lastCol = -1 if (line.isEmpty()) continue; var points = line.split(" -> ") for (point in points) { var (col, row) = point.split(",").map { it.toInt() } col += 1000 maxRow = maxRow.coerceAtLeast(row) if (lastCol == -1) { lastRow = row lastCol = col continue } for (j in min(lastCol, col) .. max(lastCol, col)) { for (i in min(lastRow, row) .. max(lastRow, row)) { matrix[i][j] = '#' } } lastRow = row lastCol = col } } for (j in 0 .. 3000) { matrix[maxRow+2][j] = '#' } var ans = 0 while (true) { var row = 0 var col = 1500 while (row < 1000) { if (matrix[row+1][col] == '.') { row++ continue } if (matrix[row+1][col-1] == '.') { row++ col-- continue } if (matrix[row+1][col+1] == '.') { row++ col++ continue } break } if (row == 0) break matrix[row][col] = 'o' ans++ } return ans+1 } val input = readInput("Day14") part1(input).println() part2(input).println() }
0
Kotlin
0
0
c24e763a1adaf0a35ed2fad8ccc4c315259827f0
3,690
advent-of-code-2022-kotlin
Apache License 2.0
kotlin/src/com/leetcode/42_TrappingRainWater.kt
programmerr47
248,502,040
false
null
package com.leetcode import kotlin.math.* /** * We make two projection arrays. And after that combine then with subtraction of original h[i]. * In more details: * 1. We put ray of lights from left to right and consider h[i] as an obstacle, so it will put shadow after itself * 2. We put ray of lights from right to left and consider h[i] as an obstacle, so it will put shadow before itself * 3. For each i we find minimum of two projections, that's the place filled with water * 4. For each i we subtract h[i] from that minimum, so we will have level of whater for the given i. * 5. Sum up all volumes. * * Here is more less visual representation, given the leetcode example. * * 1. Original: [0,1,0,2,1,0,1,3,2,1,2,1] * Visual: | | * | ║ | * | ║ ║║ ║ | * | ║ ║║ ║║║║║║| * * 2. Right Projection: [0,1,1,2,2,2,2,3,3,3,3,3] * Visual: | | * | ║****| * | ║***║║*║*| * | ║*║║*║║║║║║| * * 3. Left Projection: [3,3,3,3,3,3,3,3,2,2,2,1] * Visual: | | * |*******║ | * |***║***║║*║ | * |*║*║║*║║║║║║| * * 4. Min Projection: [0,1,1,2,2,2,2,3,2,2,2,1] * Visual: | | * | ║ | * | ║***║║*║ | * | ║*║║*║║║║║║| * * Num of * = 6 <--- answer! * * Time: O(n), Space: O(n) * * P.S.: actually lProj is introduced for the readability and clarity, but it can be easily omitted */ private class Solution42 { fun trap(height: IntArray): Int { val rProj = IntArray(height.size) height.forEachIndexed { i, h -> rProj[i] = max(rProj[max(0, i - 1)], h) } val lProj = IntArray(height.size) for (i in height.lastIndex downTo 0) { lProj[i] = max(lProj[min(height.lastIndex, i + 1)], height[i]) } var result = 0 height.forEachIndexed { i, h -> result += min(lProj[i], rProj[i]) - h } return result } } fun main() { val solution = Solution42() println(solution.trap(intArrayOf(1, 10, 0, 0, 0, 0, 0, 10, 1))) println(solution.trap(intArrayOf(1, 10, 0, 5, 9, 6, 1, 10, 1))) println(solution.trap(intArrayOf(1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1))) println(solution.trap(intArrayOf(1, 2, 3, 4, 5, 6))) println(solution.trap(intArrayOf(6, 5, 4, 3, 2, 1))) println(solution.trap(intArrayOf(6, 5, 4, 3, 2, 1))) println(solution.trap(intArrayOf(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1))) }
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
2,844
problemsolving
Apache License 2.0
src/Day06.kt
kipwoker
572,884,607
false
null
fun main() { fun getDiffIndex(input: List<String>, diffCount: Int): Int { val line = input[0].toCharArray() for (i in 0..line.size - diffCount) { if (line.slice(i until i + diffCount).toSet().size == diffCount) { return i + diffCount } } return -1 } fun part1(input: List<String>): Int { return getDiffIndex(input, 4) } fun part2(input: List<String>): Int { return getDiffIndex(input, 14) } assert(part1(readInput("Day06_test_1")), 7) assert(part1(readInput("Day06_test_2")), 5) assert(part1(readInput("Day06_test_3")), 11) assert(part2(readInput("Day06_test_1")), 19) assert(part2(readInput("Day06_test_2")), 23) assert(part2(readInput("Day06_test_3")), 26) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8aeea88d1ab3dc4a07b2ff5b071df0715202af2
892
aoc2022
Apache License 2.0
src/main/kotlin/d10/D10.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d10 fun findConnections(diagram: List<String>, loc: Pair<Int, Int>): List<Pair<Int, Int>> { val here = diagram[loc.first][loc.second] return when (here) { 'S' -> { val connections = mutableListOf<Pair<Int, Int>>() if ("F7|".contains(diagram[loc.first - 1][loc.second])) connections.add(Pair(loc.first - 1, loc.second)) if ("LJ|".contains(diagram[loc.first + 1][loc.second])) connections.add(Pair(loc.first + 1, loc.second)) if ("FL-".contains(diagram[loc.first][loc.second - 1])) connections.add(Pair(loc.first, loc.second - 1)) if ("J7-".contains(diagram[loc.first][loc.second + 1])) connections.add(Pair(loc.first, loc.second + 1)) connections } '-' -> { listOf(Pair(loc.first, loc.second - 1), Pair(loc.first, loc.second + 1)) } '|' -> { listOf(Pair(loc.first - 1, loc.second), Pair(loc.first + 1, loc.second)) } 'F' -> { listOf(Pair(loc.first + 1, loc.second), Pair(loc.first, loc.second + 1)) } '7' -> { listOf(Pair(loc.first + 1, loc.second), Pair(loc.first, loc.second - 1)) } 'L' -> { listOf(Pair(loc.first - 1, loc.second), Pair(loc.first, loc.second + 1)) } 'J' -> { listOf(Pair(loc.first - 1, loc.second), Pair(loc.first, loc.second - 1)) } else -> throw RuntimeException("did not recognise pipe segment") } } fun padInput(lines: List<String>): MutableList<String> { val diagram = mutableListOf<String>() diagram.add(".".repeat(lines[0].length + 2)) diagram.addAll( lines.map { ".$it." } ) diagram.add(".".repeat(lines[0].length + 2)) return diagram } fun findStart(diagram: List<String>): Pair<Int, Int> { for (i in diagram.indices) { for (j in diagram[i].indices) { if (diagram[i][j] == 'S') return Pair(i, j) } } throw RuntimeException("could not find start") }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
2,044
aoc2023-kotlin
MIT License
src/Day06.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
fun main() { fun solve(s: String, k: Int): Int { return s.indices.first { i -> s.substring(i, i + k).toSet().size == k } + k } fun part1(input: List<String>): Int { return solve(input[0], 4) } fun part2(input: List<String>): Int { return solve(input[0], 14) } val day = String.format("%02d", 6) val testInput = readInput("Day${day}_test") println("Part 1 test - " + part1(testInput)) println("Part 2 test - " + part2(testInput)) val input = readInput("Day$day") println("Part 1 real - " + part1(input)) println("Part 2 real - " + part2(input)) }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
626
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g2001_2100/s2050_parallel_courses_iii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2001_2100.s2050_parallel_courses_iii // #Hard #Dynamic_Programming #Graph #Topological_Sort // #2023_06_23_Time_974_ms_(100.00%)_Space_84.4_MB_(100.00%) import java.util.ArrayDeque import java.util.Queue class Solution { fun minimumTime(n: Int, relations: Array<IntArray>, time: IntArray): Int { val v = time.size val adj: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until v) { adj.add(ArrayList()) } val indegree = IntArray(v) val requiredTime = IntArray(v) for (relation in relations) { val vertices = adj[relation[0] - 1] vertices.add(relation[1] - 1) indegree[relation[1] - 1]++ } val q: Queue<Int> = ArrayDeque() for (i in 0 until v) { if (indegree[i] == 0) { q.add(i) requiredTime[i] = time[i] } } while (q.isNotEmpty()) { val vertex = q.poll() val edges: List<Int> = adj[vertex] for (e in edges) { indegree[e]-- if (indegree[e] == 0) { q.add(e) } val totalTime = time[e] + requiredTime[vertex] if (requiredTime[e] < totalTime) { requiredTime[e] = totalTime } } } var maxMonth = 0 for (i in 0 until n) { maxMonth = Math.max(maxMonth, requiredTime[i]) } return maxMonth } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,547
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MakeAllStringsEqual.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT /** * 1897. Redistribute Characters to Make All Strings Equal * @see <a href="https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal">Source</a> */ fun interface MakeAllStringsEqual { operator fun invoke(words: Array<String>): Boolean } class StringCharacterCountChecker : MakeAllStringsEqual { override fun invoke(words: Array<String>): Boolean { val characterCounts: MutableMap<Char, Int> = HashMap() // Count occurrences of each character in all words for (word in words) { for (char in word.toCharArray()) { characterCounts[char] = characterCounts.getOrDefault(char, 0) + 1 } } val wordCount: Int = words.size // Check if the character counts are evenly divisible by the number of words for (count in characterCounts.values) { if (count % wordCount != 0) { return false } } return true } } class MakeAllStringsEqualArray : MakeAllStringsEqual { override fun invoke(words: Array<String>): Boolean { val characterCounts = IntArray(ALPHABET_LETTERS_COUNT) // Count occurrences of each character in all words for (word in words) { for (char in word.toCharArray()) { characterCounts[char.code - 'a'.code]++ } } val wordCount: Int = words.size // Check if the character counts are evenly divisible by the number of words for (count in characterCounts) { if (count % wordCount != 0) { return false } } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,373
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/search/BinaryRecursiveSearch.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.search /** * Binary search is an algorithm which finds the position of a target value within an array (Sorted) * * Worst-case performance O(log(n)) * Best-case performance O(1) * Average performance O(log(n)) * Worst-case space complexity O(1) */ class BinaryRecursiveSearch<T : Comparable<T>> : AbstractSearchStrategy<T> { override fun perform(arr: Array<T>, element: T): Int { return arr.search(0, arr.size - 1, element) } private fun Array<T>.search(low: Int, high: Int, element: T): Int { if (high >= low) { val mid = low.plus(high).div(2) if (this[mid] == element) { return mid } if (this[mid] > element) { return this.search(low, mid - 1, element) } return search(mid + 1, high, element) } return -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,528
kotlab
Apache License 2.0
src/main/kotlin/Day07.kt
arosenf
726,114,493
false
{"Kotlin": 40487}
import kotlin.system.exitProcess fun main(args: Array<String>) { if (args.isEmpty() or (args.size < 2)) { println("Hands not specified") exitProcess(1) } val fileName = args.first() println("Reading $fileName") val result = if (args[1] == "part1") { val hands = readHands(readLines(fileName), ::evaluateHandType) Day07().evaluateHands(hands, handValues) } else { val hands = readHands(readLines(fileName), ::evaluateHandTypeWithJoker) Day07().evaluateHands(hands, handValuesWithJoker) } println("Result: $result") } fun readHands(lines: Sequence<String>, handEvaluator: (Hand) -> Hand): Hands { val hands: List<List<Char>> = arrayListOf() val bids: List<Int> = arrayListOf() lines.forEach { val line = it.split(' ') hands.addLast(line.first().toList()) bids.addLast(line.last().toInt()) } return Hands( hands .map { Hand(it, HandType.HIGH_CARD) } .map(handEvaluator) .toList(), bids ) } fun evaluateHandType(hand: Hand): Hand { val handTuples = countTuples(hand.hand) val handType = when { handTuples.fivesCount == 1 -> HandType.FIVE_OF_A_KIND handTuples.foursCount == 1 -> HandType.FOUR_OF_A_KIND handTuples.triplesCount == 1 && handTuples.pairsCount == 1 -> HandType.FULL_HOUSE handTuples.triplesCount == 1 -> HandType.THREE_OF_A_KIND handTuples.pairsCount == 2 -> HandType.TWO_PAIR handTuples.pairsCount == 1 -> HandType.ONE_PAIR else -> HandType.HIGH_CARD } return Hand(hand.hand, handType) } /** * four of a kind with joker * === * aaaaJ -> becomes a five of a kind * aJJJJ -> becomes a five of a kind * * full house with joker * === * aaaJJ -> becomes five of a kind * aaJJJ -> becomes five of a kind * * three of a kind with joker * === * aaabJ -> becomes four of a kind * abJJJ -> becomes four of a kind * * two pairs with joker * === * aabbJ -> becomes full house * aabJJ -> becomes four of a kind * * one pair with joker * === * xxyzJ -> becomes three of a kind * xyzJJ -> becomes three of a kind * * high card with joker * === * wxyzJ -> high card becomes pair */ fun evaluateHandTypeWithJoker(hand: Hand): Hand { return if (!hand.hand.contains('J')) { return evaluateHandType(hand) } else { val handTuples = countTuples(hand.hand) val handType = when { handTuples.fivesCount == 1 -> HandType.FIVE_OF_A_KIND handTuples.foursCount == 1 -> HandType.FIVE_OF_A_KIND handTuples.triplesCount == 1 && handTuples.pairsCount == 1 -> HandType.FIVE_OF_A_KIND handTuples.triplesCount == 1 -> HandType.FOUR_OF_A_KIND handTuples.pairsCount == 2 && handTuples.jokersCount == 1 -> HandType.FULL_HOUSE handTuples.pairsCount == 2 && handTuples.jokersCount == 2 -> HandType.FOUR_OF_A_KIND handTuples.pairsCount == 1 -> HandType.THREE_OF_A_KIND else -> HandType.ONE_PAIR } Hand(hand.hand, handType) } } fun countTuples(hand: List<Char>): HandTuples { val groups = hand.groupBy { it } return HandTuples( groups.filter { it.value.size == 2 }.size, groups.filter { it.value.size == 3 }.size, groups.filter { it.value.size == 4 }.size, groups.filter { it.value.size == 5 }.size, hand.filter { it == 'J' }.size ) } class Day07 { fun evaluateHands(hands: Hands, values: Map<Char, Int>): Int { return hands.hands .sortedWith(compareBy( { it.type.value }, // Ok, that's a bit cheap 🤷🏽‍♀️ { values[it.hand[0]] }, { values[it.hand[1]] }, { values[it.hand[2]] }, { values[it.hand[3]] }, { values[it.hand[4]] } )) .mapIndexed { i, hand -> (i + 1) * hands.bids[hands.hands.indexOf(hand)] } .sum() } } data class Hands(val hands: List<Hand>, val bids: List<Int>) data class Hand(val hand: List<Char>, val type: HandType) data class HandTuples( val pairsCount: Int, val triplesCount: Int, val foursCount: Int, val fivesCount: Int, val jokersCount: Int ) val handValues = mapOf( 'A' to 14, 'K' to 13, 'Q' to 12, 'J' to 11, 'T' to 10, '9' to 9, '8' to 8, '7' to 7, '6' to 6, '5' to 5, '4' to 4, '3' to 3, '2' to 2 ) val handValuesWithJoker = mapOf( 'A' to 14, 'K' to 13, 'Q' to 12, // Joker is lowest value 'J' to 1, 'T' to 10, '9' to 9, '8' to 8, '7' to 7, '6' to 6, '5' to 5, '4' to 4, '3' to 3, '2' to 2 ) enum class HandType(val value: Int) { FIVE_OF_A_KIND(7), FOUR_OF_A_KIND(6), FULL_HOUSE(5), THREE_OF_A_KIND(4), TWO_PAIR(3), ONE_PAIR(2), HIGH_CARD(1) }
0
Kotlin
0
0
d9ce83ee89db7081cf7c14bcad09e1348d9059cb
5,010
adventofcode2023
MIT License
src/Day01.kt
robinpokorny
572,434,148
false
{"Kotlin": 38009}
typealias Backpack = List<Int> private fun parse(input: String): List<Backpack> = input .split("\n\n") .map { it.lines().map(String::toInt) } private fun sumOfLargestBackpack(input: List<Backpack>): Int = input .maxOf { it.sum() } private fun sumOf3LargestBackpacks(input: List<Backpack>): Int = input .map { it.sum() } .sorted() .takeLast(3) .sum() fun main() { val input = parse(readDayInput(1).joinToString("\n")) val testInput = parse(rawTestInput) // PART 1 assertEquals(sumOfLargestBackpack(testInput), 24000) println("Part1: ${sumOfLargestBackpack(input)}") // PART 2 assertEquals(sumOf3LargestBackpacks(testInput), 45000) println("Part2: ${sumOf3LargestBackpacks(input)}") } private val rawTestInput = """ 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 """.trimIndent()
0
Kotlin
0
2
56a108aaf90b98030a7d7165d55d74d2aff22ecc
852
advent-of-code-2022
MIT License
src/day16.kts
miedzinski
434,902,353
false
{"Kotlin": 22560, "Shell": 113}
enum class PacketType(val id: Int) { SUM(0), PRODUCT(1), MINIMUM(2), MAXIMUM(3), LITERAL(4), GREATER_THAN(5), LESS_THAN(6), EQUALS(7), } class BitStream(private val chars: String) { private val RADIX: Int = 16 private val BITS_PER_CHAR = 4 val bits = chars.asSequence().map { it.digitToInt(RADIX).run(Integer::toBinaryString).padStart(BITS_PER_CHAR, '0') }.joinToString("") var position: Int = 0 private set fun read(count: Int): Int = bits.substring(position until (position + count)) .toInt(2) .also { position += count } } val stream = BitStream(readLine()!!) var part1 = 0L fun BitStream.readPacket(): Long { part1 += stream.read(3) return when (stream.read(3)) { PacketType.LITERAL.id -> stream.readLiteral() PacketType.SUM.id -> stream.readSubPackets().sumOf { it } PacketType.PRODUCT.id -> stream.readSubPackets().reduce(Long::times) PacketType.MINIMUM.id -> stream.readSubPackets().minOf { it } PacketType.MAXIMUM.id -> stream.readSubPackets().maxOf { it } PacketType.GREATER_THAN.id -> stream.readSubPackets().compare { a, b -> a > b } PacketType.LESS_THAN.id -> stream.readSubPackets().compare { a, b -> a < b } PacketType.EQUALS.id -> stream.readSubPackets().compare { a, b -> a == b } else -> throw IllegalStateException() } } fun BitStream.readLiteral(): Long { val groupSize = 4 return sequence { do { val shouldContinue = stream.read(1) == 1 yield(stream.read(groupSize)) } while (shouldContinue) }.fold(0L) { acc, elt -> acc shl groupSize or elt.toLong() } } fun BitStream.readSubPackets(): Sequence<Long> { return when (stream.read(1)) { 0 -> { val subPacketsLength = stream.read(15) val start = stream.position sequence { while (stream.position < start + subPacketsLength) { yield(stream.readPacket()) } } } 1 -> generateSequence { stream.readPacket() }.take(stream.read(11)) else -> throw IllegalStateException() } } fun <T : Comparable<T>> Sequence<T>.compare(operator: (T, T) -> Boolean): Long = toList().let { (first, second) -> when { operator(first, second) -> 1 else -> 0 } } val part2 = stream.readPacket() println("part1: $part1") println("part2: $part2")
0
Kotlin
0
0
6f32adaba058460f1a9bb6a866ff424912aece2e
2,532
aoc2021
The Unlicense
src/main/kotlin/io/rbrincke/dice/core/MultisetPermutationIterator.kt
rbrincke
167,712,634
false
{"Kotlin": 13146}
package io.rbrincke.dice.core /** * Multiset permutation iterator. Not thread safe. * * See *"Loopless Generation of Multiset Permutations using a Constant Number * of Variables by Prefix Shifts."*, <NAME>, 2009. */ class MultisetPermutationIterator<E : Comparable<E>>(input: Collection<E>) : Iterator<List<E>> { private val nodes: List<Node<E>> private var head: Node<E> private var i: Node<E>? = null private var afteri: Node<E> private var pristine = true init { check(input.isNotEmpty()) nodes = initializeNodeList(input) head = nodes[0] if (input.size > 1) { i = nodes[nodes.size - 2] } afteri = nodes[nodes.size - 1] } private fun initializeNodeList(input: Collection<E>): List<Node<E>> { val nodes = input.reversed().map { Node(it) }.toList() for (i in 0 until nodes.size - 1) { nodes[i].next = nodes[i + 1] } return nodes } /** * Returns `true` if another permutation is available. (In other words, returns * true if the next call to [next] would return a permutation rather than * throwing an exception). */ override fun hasNext(): Boolean { return pristine || afteri.next != null || afteri.value < head.value } /** * Returns the next permutation. * @throws NoSuchElementException if there are no more permutations */ override fun next(): List<E> { if (!hasNext()) { throw NoSuchElementException() } if (pristine) { pristine = false return visit(head) } val afteriNext = afteri.next val beforek: Node<E> = if (afteriNext != null && i!!.value >= afteriNext.value) { afteri } else { i!! } val k = beforek.next checkNotNull(k) beforek.next = k.next k.next = head if (k.value < head.value) { i = k } afteri = i!!.next!! head = k return visit(head) } private fun visit(node: Node<E>): List<E> { val values = ArrayList<E>(nodes.size) values.add(node.value) var current = node while (current.next != null) { current = current.next!! values.add(current.value) } return values } } private class Node<E : Comparable<E>>(val value: E) { var next: Node<E>? = null }
0
Kotlin
0
0
fc5aa0365d91ce360bf6e9c7589e3f5fc6bc8a82
2,499
nontransitive-dice
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions9.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import com.qiaoyuang.algorithm.round0.Queue import com.qiaoyuang.algorithm.round0.Stack fun test9() { val stack = TwoQueuesStack<Int>() val queue = TwoStacksQueue<Int>() repeat(10) { stack.push(it) queue.enqueue(it) } println("Stack input: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]") repeat(3) { stack.pop() } repeat(3) { stack.push(7 + it) } print("Stack output: ") while (!stack.isEmpty) print(stack.pop()) println() println("Queue input: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]") print("Queue output: ") while (!queue.isEmpty) print(queue.dequeue()) println() } /** * Questions 9-1: Use two queues to implement a stack. */ private class TwoQueuesStack<T> { private val queue1 = Queue<T>() private val queue2 = Queue<T>() fun push(t: T) { val queue = if (queue2.isEmpty) queue1 else queue2 queue.enqueue(t) } fun pop(): T { val (queue, emptyQueue) = when { !queue1.isEmpty && queue2.isEmpty -> queue1 to queue2 !queue2.isEmpty && queue1.isEmpty -> queue2 to queue1 queue1.isEmpty && queue2.isEmpty -> throw IllegalStateException("The stack is empty") else -> throw IllegalStateException("Stack state exception") } while (queue.size != 1) emptyQueue.enqueue(queue.dequeue()) return queue.dequeue() } val isEmpty: Boolean get() = queue1.isEmpty && queue2.isEmpty } /** * Questions 9-2: Use two stacks to implement a queue. */ private class TwoStacksQueue<T> { private val stack1 = Stack<T>() private val stack2 = Stack<T>() fun enqueue(t: T) { while (!stack2.isEmpty) stack1.push(stack2.pop()) stack1.push(t) } fun dequeue(): T = when { !stack2.isEmpty -> stack2.pop() stack1.isEmpty -> throw IllegalStateException("The queue is empty") else -> { while (stack1.size != 1) stack2.push(stack1.pop()) stack1.pop() } } val isEmpty: Boolean get() = stack1.isEmpty && stack2.isEmpty }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,209
Algorithm
Apache License 2.0
src/com/ssynhtn/medium/UniquePermutations.kt
ssynhtn
295,075,844
false
{"Java": 639777, "Kotlin": 34064}
package com.ssynhtn.medium import java.util.* class UniquePermutations { fun permuteUnique(nums: IntArray): List<List<Int>> { nums.sort() val collection = mutableListOf<List<Int>>() permute(nums, 0, collection) return collection } private fun permute(nums: IntArray, fixCount: Int, collection: MutableList<List<Int>>) { if (!checkIncreasing(nums, fixCount)) { return } if (fixCount == nums.size) { collection.add(nums.toList()) return } permute(nums, fixCount + 1, collection) val index = fixCount for (i in index + 1 until nums.size) { if (nums[i] == nums[i - 1]) continue shiftRight(nums, index, i) permute(nums, fixCount + 1, collection) shiftLeft(nums, index, i) } } private fun shiftLeft(nums: IntArray, index: Int, i: Int) { val temp = nums[index] System.arraycopy(nums, index + 1, nums, index, i - index) nums[i] = temp } private fun shiftRight(nums: IntArray, index: Int, i: Int) { val temp = nums[i] System.arraycopy(nums, index, nums, index + 1, i - index) nums[index] = temp } private fun checkIncreasing(nums: IntArray, fixCount: Int): Boolean { for (i in fixCount until nums.size - 1) { if (nums[i] > nums[i + 1]) { // println("bad " + nums.toList() + ", fixCount " + fixCount) return false; } } // println("good " + nums.toList() + ", fixCount " + fixCount) return true; } fun swap(nums: IntArray, i: Int, j: Int) { val temp = nums[i] nums[i] = nums[j] nums[j] = temp } } fun main(args: Array<String>) { val nums = intArrayOf(0, 0, 1, 2) val res = UniquePermutations().permuteUnique(nums) println(res) }
0
Java
0
0
511f65845097782127bae825b07a51fe9921c561
1,929
leetcode
Apache License 2.0
src/week-day-1/Pangram.kt
luix
573,258,926
false
{"Kotlin": 7897, "Java": 232}
package week1 /** * Pangram (easy) * Problem Statement * A pangram is a sentence where every letter of the English alphabet * appears at least once. * * Given a string sentence containing English letters (lower or upper-case), * return true if sentence is a pangram, or false otherwise. * * Note: The given sentence might contain other characters like digits or spaces, * your solution should handle these too. * * Example 1: * * Input: sentence = "TheQuickBrownFoxJumpsOverTheLazyDog" * Output: true * Explanation: The sentence contains at least one occurrence of every letter of * the English alphabet either in lower or upper case. * Example 2: * * Input: sentence = "This is not a pangram" * Output: false * Explanation: The sentence doesn't contain at least one occurrence of every * letter of the English alphabet. */ class Pangram { private val alphabet = "abcdefghijklmnopqrstuvwxyz" fun isPangram(string: String): Boolean { val set = alphabet.toHashSet() string.lowercase().forEach { set.remove(it) } return set.isEmpty() } } fun main() { val solution = Pangram() val tests = listOf( "TheQuickBrownFoxJumpsOverTheLazyDog", "This is not a pangram" ) tests.forEach { assert(solution.isPangram(it)) println("$it is pangram: ${solution.isPangram(it)}") } }
0
Kotlin
0
0
8e9b605950049cc9a0dced9c7ba99e1e2458e53e
1,399
advent-of-code-kotlin-2022
Apache License 2.0
com/ztoais/dailycoding/algoexpert/medium/ThreeNumberSum.kt
RanjithRagavan
479,563,314
false
{"Kotlin": 7371}
package com.ztoais.dailycoding.algoexpert.medium import kotlin.io.path.createTempDirectory /* Three Number Sum Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should find all triplets in the array that sum up to the target sum and return a two-dimensional array of all these triplets. The numbers in each triplet should be ordered in ascending order, and the triplets themselves should be ordered in ascending order with respect to the numbers they hold. If no three numbers sum up to the target sum, the function should return an empty array. Sample Input: array = [12,3,1,2,-6,5,-8,6] targetSum = 0 Sample Output: [[-8,2,6],[-8,3,5],[-6,1,5]] */ fun threeNumberSum(array: MutableList<Int>, targetSum: Int):List<List<Int>>{ //1. Sort the array //2. Current number firs //3. User Right and left pointer movement one at time. //4. Left pointer movement increase the current sum //5. Right pointer movement decrease the current sum //6. If the target sum equal then move the left and right same time //7. Time : O(N2) Space: O(N) array.sort() val result = mutableListOf<List<Int>>() for(i in 0..array.size-2){ var left = i+1 var right = array.size-1 while(left < right){ val currentSum = array[i]+array[left]+array[right] if(currentSum == targetSum){ result.add(listOf(array[i],array[left],array[right])) left+=1 right-=1 }else if(currentSum < targetSum){ left+=1 }else if(currentSum > targetSum){ right-=1 } } } return result } /* Tests Test Case 1 { "array": [12, 3, 1, 2, -6, 5, -8, 6], "targetSum": 0 } Test Case 2 { "array": [1, 2, 3], "targetSum": 6 } Test Case 3 { "array": [1, 2, 3], "targetSum": 7 } Test Case 4 { "array": [8, 10, -2, 49, 14], "targetSum": 57 } Test Case 5 { "array": [12, 3, 1, 2, -6, 5, 0, -8, -1], "targetSum": 0 } Test Case 6 { "array": [12, 3, 1, 2, -6, 5, 0, -8, -1, 6], "targetSum": 0 } Test Case 7 { "array": [12, 3, 1, 2, -6, 5, 0, -8, -1, 6, -5], "targetSum": 0 } Test Case 8 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 18 } Test Case 9 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 32 } Test Case 10 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 33 } Test Case 11 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 5 } */
0
Kotlin
0
0
a5f29dd82c0c50fc7d2490fd1be6234cdb4d1d8a
2,553
daily-coding
MIT License
src/main/kotlin/org/sjoblomj/adventofcode/day3/Visualizer.kt
sjoblomj
161,537,410
false
null
package org.sjoblomj.adventofcode.day3 import org.sjoblomj.adventofcode.printJson class Grid(val claims: List<Claim>, val cells: List<List<List<Int>>>) internal fun visualizeArea(area: Area): String { var output = "" for (y in area.indices) { for (x in area[0].indices) { val claims = area[y][x] output += when { claims.isEmpty() -> "." claims.size == 1 -> claims[0].id.toChar() else -> "#" } } output += "\n" } return output } internal fun createGrid(area: Array<Array<Claims>>, claims: List<Claim>): Grid { if (area.isEmpty() || claims.isEmpty()) { throw IllegalArgumentException("Expected non-empty area and list of claims") } val cellsWithIds = matrix2d(area.size, area[0].size) { emptyList<Int>() } for (y in area[0].indices) for (x in area.indices) cellsWithIds[x][y] = area[x][y].map { it.id } val cells = cellsWithIds.map { it.toList() } return Grid(claims, cells) } internal fun printJson(area: Area, claims: List<Claim>) = printJson(createGrid(area, claims))
0
Kotlin
0
0
80db7e7029dace244a05f7e6327accb212d369cc
1,079
adventofcode2018
MIT License
src/test/kotlin/adventofcode/day05/Day05.kt
jwcarman
573,183,719
false
{"Kotlin": 183494}
/* * Copyright (c) 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package adventofcode.day05 import adventofcode.util.head import adventofcode.util.readAsString import adventofcode.util.tail import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day05 { @Test fun example1() { val input = readAsString("day05-example.txt") assertEquals("CMZ", calculatePart1(input)) } @Test fun part1() { val input = readAsString("day05.txt") assertEquals("QPJPLMNNR", calculatePart1(input)) } @Test fun example2() { val input = readAsString("day05-example.txt") assertEquals("MCD", calculatePart2(input)) } @Test fun part2() { val input = readAsString("day05.txt") assertEquals("BQDNWJPVJ", calculatePart2(input)) } private fun calculatePart1(input: String): String { return calculateAnswer(input, CrateMover9000()) } private fun calculatePart2(input: String): String { return calculateAnswer(input, CrateMover9001()) } private fun calculateAnswer(input: String, crane: Crane): String { val splits = input.split("\n\n") val stacksMap = parseStacksMap(splits[0]) splits[1].lines() .forEach { instruction -> val (amount, srcNum, destNum) = Regex("move (\\d+) from (\\d+) to (\\d+)").matchEntire(instruction)!!.destructured val src = stacksMap[srcNum.toInt()]!! val dest = stacksMap[destNum.toInt()]!! crane.moveCrates(src, dest, amount.toInt()) } return stacksMap.keys.sorted() .map { k -> stacksMap[k]?.head() } .joinToString(separator = "") } private fun parseStacksMap(input: String): Map<Int, CargoStack> { val stacksMap = mutableMapOf<Int, CargoStack>() input .replace("] ", "] [-]") .replace(" [", "[-] [") .replace(" ", " [-] ") .replace("[", "") .replace("]", "") .lines().reversed().tail() .forEach { line -> line.split(' ').forEachIndexed{ index, label -> if("-" != label) { val stack = stacksMap.getOrPut(index + 1, ::mutableListOf) stack.push(label.first()) } } } return stacksMap.toMap() } interface Crane { fun moveCrates(src: CargoStack, dest: CargoStack, amount: Int) } class CrateMover9000 : Crane { override fun moveCrates(src: CargoStack, dest: CargoStack, amount: Int) { repeat(amount) { dest.push(src.pop()) } } } class CrateMover9001 : Crane { override fun moveCrates(src: CargoStack, dest: CargoStack, amount: Int) { val tmp = mutableListOf<Char>() repeat(amount) { tmp.push(src.pop()) } repeat(amount) { dest.push(tmp.pop()) } } } } typealias CargoStack = MutableList<Char> fun CargoStack.push(element: Char) = add(0, element) fun CargoStack.pop() = removeFirst()
0
Kotlin
0
0
d6be890aa20c4b9478a23fced3bcbabbc60c32e0
3,792
adventofcode2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ArrIntoConsecutiveSubsequences.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue /** * Split Array into Consecutive Subsequences. */ fun interface ArrIntoConsecutiveSubsequences { operator fun invoke(nums: IntArray): Boolean } /** * Approach #1: Opening and Closing Event. * Time Complexity: O(N). * Space Complexity: O(N). */ class ArrIntoConsecutiveSubsequencesQueue : ArrIntoConsecutiveSubsequences { override fun invoke(nums: IntArray): Boolean { var prev: Int? = null var prevCount = 0 val starts: Queue<Int> = LinkedList() var anchor = 0 for (i in nums.indices) { val t = nums[i] if (i == nums.size - 1 || nums[i + 1] != t) { val count = i - anchor + 1 if (prev != null && t - prev != 1) { while (prevCount-- > 0) if (prev < starts.poll() + 2) return false prev = null } if (prev == null || t - prev == 1) { while (prevCount > count) { prevCount-- if (t - 1 < starts.poll() + 2) return false } while (prevCount++ < count) starts.add(t) } prev = t prevCount = count anchor = i + 1 } } while (prevCount-- > 0) if (nums[nums.size - 1] < starts.poll() + 2) return false return true } } /** * Approach #2: Greedy. * Time Complexity: O(N). * Space Complexity: O(N). */ class ArrIntoConsecutiveSubsequencesGreedy : ArrIntoConsecutiveSubsequences { override fun invoke(nums: IntArray): Boolean { val count = CounterMap() val tails = CounterMap() for (x in nums) count.add(x, 1) for (x in nums) { when { count[x] == 0 -> { continue } tails[x] > 0 -> { tails.add(x, -1) tails.add(x + 1, 1) } count[x + 1] > 0 && count[x + 2] > 0 -> { count.add(x + 1, -1) count.add(x + 2, -1) tails.add(x + 3, 1) } else -> { return false } } count.add(x, -1) } return true } } class CounterMap : HashMap<Int, Int>() { override operator fun get(key: Int): Int { return if (containsKey(key)) super.getOrDefault(key, 0) else 0 } fun add(k: Int, v: Int) { put(k, get(k) + v) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,267
kotlab
Apache License 2.0
src/main/kotlin/arrayandlist/medium/ProductOfArrayExceptSelf.kt
jiahaoliuliu
747,189,993
false
{"Kotlin": 97631}
package arrayandlist.medium import org.junit.Assert.assertTrue import org.junit.Test /** * Given an integer array nums, return an array answer such that answer[i] is equal to the product of all * the elements of nums except nums[i]. * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. * You must write an algorithm that runs in O(n) time and without using the division operation. * * Example 1: * Input: nums = [1,2,3,4] * Output: [24,12,8,6] * * Example 2: * Input: nums = [-1,1,0,-3,3] * Output: [0,0,9,0,0] * * Constraints: * 2 <= nums.length <= 10^5 * -30 <= nums[i] <= 30 * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. * * Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra * space for space complexity analysis.) */ class ProductOfArrayExceptSelf { private fun productExceptSelf(nums: IntArray): IntArray { // 1. Init the data val pre = IntArray(nums.size) pre[0] = 1 val suff = IntArray(nums.size) suff[nums.size -1] = 1; // 2. Loop // prefix array nums.forEachIndexed { i, item -> if (i > 0) pre[i] = pre[i - 1] * nums[i - 1] } // suffix array for (i in nums.size - 2 downTo 0) { // From nums.length -2 to 0 (included) print(i) suff[i] = suff[i + 1] * nums[i + 1] } // collect the result val result = IntArray(nums.size) result.forEachIndexed { i, _ -> result[i] = pre[i] * suff[i] } return result } @Test fun test1() { // Given val input = intArrayOf(1, 2, 3, 4) // When val result = productExceptSelf(input) // Then assertTrue(intArrayOf(24, 12, 8, 6) contentEquals result) } @Test fun test2() { // Given val input = intArrayOf(-1,1,0,-3,3) // When val result = productExceptSelf(input) // Then assertTrue(intArrayOf(0, 0, 9, 0, 0) contentEquals result) } }
0
Kotlin
0
0
c5ed998111b2a44d082fc6e6470d197554c0e7c9
2,229
CodingExercises
Apache License 2.0