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
2015/Day01/src/main/kotlin/Main.kt
mcrispim
658,165,735
false
null
import java.io.File fun main() { fun part1(input: List<String>): Int { val directions = input[0].groupingBy { it }.eachCount() val ups = directions['('] ?: 0 val downs = directions[')'] ?: 0 return ups - downs } fun part2(input: List<String>): Int { var floor = 0 for ((index, instruction) in input[0].withIndex()) { when (instruction) { '(' -> floor++ ')' -> floor-- else -> throw Exception("Wrong data in input!") } if (floor == -1) return index + 1 } throw Exception("Never goes to the basement") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == -1) check(part2(testInput) == 5) val input = readInput("Day01_data") println(part1(input)) println(part2(input)) } /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines()
0
Kotlin
0
0
2f4be35e78a8a56fd1e078858f4965886dfcd7fd
1,090
AdventOfCode
MIT License
src/Day09.kt
wbars
576,906,839
false
{"Kotlin": 32565}
import kotlin.math.abs fun main() { fun newPos(x: Int, y: Int, tx: Int, ty: Int): Pair<Int, Int> { var tx1 = tx var ty1 = ty if (x > tx1 && abs(x - tx1) > 1) { tx1++ if (y > ty1) ty1++ else if (y < ty1) ty1-- } else if (tx1 > x && abs(tx1 - x) > 1) { tx1-- if (y > ty1) ty1++ else if (y < ty1) ty1-- } else if (y > ty1 && abs(y - ty1) > 1) { ty1++ if (x > tx1) tx1++ else if (x < tx1) tx1-- } else if (ty1 > y && abs(ty1 - y) > 1) { ty1-- if (x > tx1) tx1++ else if (x < tx1) tx1-- } return Pair(tx1, ty1) } fun part1(input: List<String>): Int { var x = 0 var y = 0 var pos: Pair<Int, Int> = Pair(0, 0) val v: MutableSet<Pair<Int, Int>> = mutableSetOf() for (s in input) { val parts = s.split(" ") repeat(parts[1].toInt()) { when (parts[0]) { "R" -> { x += 1 } "L" -> { x -= 1 } "U" -> { y += 1 } else -> { y -= 1 } } pos = newPos(x, y, pos.first, pos.second) v.add(pos) } } return v.size } fun part2(input: List<String>): Int { var x = 0 var y = 0 val pos: MutableList<Pair<Int, Int>> = mutableListOf( Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), ) val v: MutableSet<Pair<Int, Int>> = mutableSetOf() for (s in input) { val parts = s.split(" ") repeat(parts[1].toInt()) { when (parts[0]) { "R" -> { x += 1 } "L" -> { x -= 1 } "U" -> { y += 1 } else -> { y -= 1 } } for (i in 0 until pos.size) { val prev = if (i == 0) Pair(x, y) else pos[i - 1] pos[i] = newPos(prev.first, prev.second, pos[i].first, pos[i].second) } v.add(pos.last()) } } return v.size } part1(readInput("input")).println() part2(readInput("input")).println() }
0
Kotlin
0
0
344961d40f7fc1bb4e57f472c1f6c23dd29cb23f
2,834
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/com/kondenko/pocketwaka/domain/summary/model/Project.kt
Kondenko
95,912,101
false
null
package com.kondenko.pocketwaka.domain.summary.model import com.kondenko.pocketwaka.utils.WakaLog data class Project( val name: String, val totalSeconds: Long, val isRepoConnected: Boolean = true, val branches: Map<String, Branch>, val repositoryUrl: String ) interface ProjectInternalListItem data class Branch(val name: String, val totalSeconds: Long, val commits: List<Commit>?) : ProjectInternalListItem data class Commit(val hash: String, val message: String, val totalSeconds: Long) : ProjectInternalListItem object NoCommitsLabel : ProjectInternalListItem infix fun Project.mergeBranches(other: Project): Project { require(name == other.name) { "Projects are different" } require(totalSeconds == other.totalSeconds) { "This project's totalSeconds values should have already been merged when fetching summaries" /* See [StatsEntity.plus(StatsEntity)] */ } return Project( name, totalSeconds, other.isRepoConnected && isRepoConnected, branches.merge(other.branches), other.repositoryUrl ).also { val timeByBranches = it.branches.values.sumBy { it.totalSeconds.toInt() } if (it.totalSeconds.toInt() != timeByBranches) { WakaLog.w("Project's branches time doesn't sum up to project's total time (branches=$timeByBranches, total=$totalSeconds)") } } } private fun Map<String, Branch>.merge(other: Map<String, Branch>): Map<String, Branch> = (keys + other.keys).associateWith { setOf(this[it], other[it]).filterNotNull().reduce(Branch::merge) }.let { HashMap(it) } private fun Branch.merge(other: Branch?): Branch { require(name == other?.name) { "Branches are different" } other ?: return this return Branch(name, totalSeconds + other.totalSeconds, commits.mergeCommits(other.commits)) } private fun List<Commit>?.mergeCommits(other: List<Commit>?): List<Commit> = ((this ?: emptyList()) + (other ?: emptyList())) .groupBy { it.message } .map { (_, branches) -> branches.reduce { a, b -> a.merge(b) } } private fun Commit.merge(other: Commit): Commit { require(hash == other.hash) { "Messages are different" } require(message == other.message) { "Messages are different" } return Commit(hash, message, totalSeconds + other.totalSeconds) }
2
Kotlin
7
58
6f1423415e2a23f12626ac67c9afb25f2df9e302
2,399
pocketwaka
MIT License
src/Day05.kt
MerickBao
572,842,983
false
{"Kotlin": 28200}
import java.util.LinkedList fun main() { val supply = arrayOf("", "BWN", "LZSPTDMB", "QHZWR", "WDVJZR", "SHMB", "LGNJHVPB", "JQZFHDLS", "WSFJGQB", "ZWMSCDJ") fun part1(input: List<String>): String { val stacks = Array(10) {LinkedList<Char>()} for (i in supply.indices) { for (j in supply[i]) { stacks[i].offerLast(j) } } for (i in 10 until input.size) { val now = input[i].split(" ") var cnt = now[1].toInt() val from = now[3].toInt() val to = now[5].toInt() while (cnt-- > 0) { stacks[to].offerLast(stacks[from].pollLast()) } } val ans = StringBuilder() for (i in 1 until stacks.size) { ans.append(if (stacks[i].isEmpty()) " " else stacks[i].peekLast()) } return ans.toString() } fun part2(input: List<String>): String { val stacks = Array(10) {LinkedList<Char>()} for (i in supply.indices) { for (j in supply[i]) { stacks[i].offerLast(j) } } for (i in 10 until input.size) { val now = input[i].split(" ") var cnt = now[1].toInt() val from = now[3].toInt() val to = now[5].toInt() val tmp = LinkedList<Char>() while (cnt-- > 0) { tmp.offerFirst(stacks[from].pollLast()) } while (!tmp.isEmpty()) { stacks[to].offerLast(tmp.pollFirst()) } } val ans = StringBuilder() for (i in 1 until stacks.size) { ans.append(if (stacks[i].isEmpty()) " " else stacks[i].peekLast()) } return ans.toString() } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
70a4a52aa5164f541a8dd544c2e3231436410f4b
1,882
aoc-2022-in-kotlin
Apache License 2.0
year2022/src/cz/veleto/aoc/year2022/Day22.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay import cz.veleto.aoc.core.Pos import cz.veleto.aoc.core.plus import cz.veleto.aoc.core.rotateBy import kotlin.math.roundToInt import kotlin.math.sqrt class Day22(config: Config) : AocDay(config) { override fun part1(): String { val (tiles, walls, instructions) = parseInput() return followInstructions(tiles, walls, instructions) { pos, direction -> findWrapAroundPos(tiles, walls, pos, direction) to direction } } override fun part2(): String { val (tiles, walls, instructions) = parseInput() val grid = tiles + walls val innerGridCorners = findInnerCorners(grid) val sews = sewCube(grid, innerGridCorners) return followInstructions(tiles, walls, instructions) { pos, direction -> sews[pos to direction]!! } } private fun parseInput(): Triple<Set<Pos>, Set<Pos>, List<Instruction>> { val tiles = mutableSetOf<Pos>() val walls = mutableSetOf<Pos>() val instructions = mutableListOf<Instruction>() input.forEachIndexed { x, line -> when { line.isEmpty() -> Unit line[0] in listOf('.', ' ', '#') -> line.forEachIndexed { y, c -> when (c) { ' ' -> Unit '.' -> tiles += x to y '#' -> walls += x to y else -> error("unknown tile $c") } } else -> { var firstDigitIndex: Int? = null for (i in line.indices) { when (val c = line[i]) { in '0'..'9' -> if (firstDigitIndex == null) firstDigitIndex = i else -> { if (firstDigitIndex != null) { instructions += Instruction.Forward( count = line.substring(firstDigitIndex until i).toInt(), ) firstDigitIndex = null } instructions += when (c) { 'R' -> Instruction.TurnRight 'L' -> Instruction.TurnLeft else -> error("unknown instruction $c") } } } } if (firstDigitIndex != null) { instructions += Instruction.Forward( count = line.substring(firstDigitIndex..line.lastIndex).toInt(), ) } } } } return Triple(tiles, walls, instructions) } private fun followInstructions( tiles: Set<Pos>, walls: Set<Pos>, instructions: List<Instruction>, travelThroughEdge: (Pos, Direction) -> Pair<Pos, Direction>, ): String { var pos = tiles.first() var direction = Direction.Right for (instruction in instructions) { if (instruction is Instruction.Forward) { for (step in 1..instruction.count) { pos = when (val forwardPos = pos + getStepMove(direction)) { in tiles -> forwardPos in walls -> pos else -> { val (newPos, newDirection) = travelThroughEdge(pos, direction) when (newPos) { in tiles -> { direction = newDirection newPos } in walls -> pos else -> error("traveled out of grid") } } } } } else { direction = updateDirection(direction, instruction) } } val (x, y) = pos return (1_000 * (x + 1) + 4 * (y + 1) + direction.ordinal).toString() } private fun updateDirection(current: Direction, instruction: Instruction): Direction = when (instruction) { is Instruction.Forward -> 0 Instruction.TurnLeft -> -1 Instruction.TurnRight -> 1 }.let { current.rotateBy(it) } private fun getStepMove(direction: Direction): Pos = when (direction) { Direction.Right -> 0 to 1 Direction.Down -> 1 to 0 Direction.Left -> 0 to -1 Direction.Up -> -1 to 0 } private fun findWrapAroundPos(tiles: Set<Pos>, walls: Set<Pos>, edgePos: Pos, edgeDirection: Direction): Pos { val backDirection = edgeDirection.rotateBy(2) var backPos = edgePos while (true) { val newBackPos = backPos + getStepMove(backDirection) if (newBackPos !in tiles && newBackPos !in walls) break backPos = newBackPos } return backPos } private fun findInnerCorners(grid: Set<Pos>): Set<Triple<Pos, Direction, Direction>> = buildSet { val neighborMoves = Direction.entries.map { getStepMove(it) } val diagonalNeighborMoves = Direction.entries .zip(Direction.entries.map { it.rotateBy(1) }) .map { (d1, d2) -> Triple(d1, d2, getStepMove(d1) + getStepMove(d2)) } for (pos in grid) { val emptyDiagonalNeighbor = diagonalNeighborMoves.singleOrNull { pos + it.third !in grid } val isCorner = neighborMoves.all { pos + it in grid } && emptyDiagonalNeighbor != null if (isCorner) { val (d1, d2) = emptyDiagonalNeighbor!! this += Triple(pos, d1, d2) } } } private fun sewCube( grid: Set<Pos>, corners: Set<Triple<Pos, Direction, Direction>>, ): Map<Pair<Pos, Direction>, Pair<Pos, Direction>> = buildMap { check(grid.size.rem(6) == 0) val sidePointCount = grid.size / 6 val edgePointCount = sqrt(sidePointCount.toDouble()).roundToInt() check(edgePointCount * edgePointCount == sidePointCount) val edgePoints = mutableListOf<Pair<Pair<Pos, Direction>, Pair<Pos, Direction>>>() for ((pos, d1, d2) in corners) { edgePoints += (pos + getStepMove(d1) to d1) to (pos + getStepMove(d2) to d2) } while (edgePoints.isNotEmpty()) { // leftSewSide sews on right, rightSewSide sews on left val (leftSewSide, rightSewSide) = edgePoints.removeFirst() val (leftCornerPos, leftSideDirection) = leftSewSide val (rightCornerPos, rightSideDirection) = rightSewSide val leftOfLeftSideDirection = leftSideDirection.rotateBy(-1) val rightOfLeftSideDirection = leftSideDirection.rotateBy(1) val leftOfRightSideDirection = rightSideDirection.rotateBy(-1) val rightOfRightSideDirection = rightSideDirection.rotateBy(1) // skip if already sewed up before if (leftCornerPos to rightOfLeftSideDirection in this) continue if (rightCornerPos to leftOfRightSideDirection in this) continue var leftEdgePos = leftCornerPos var rightEdgePos = rightCornerPos for (edgePoint in 1..edgePointCount) { this[leftEdgePos to rightOfLeftSideDirection] = rightEdgePos to rightOfRightSideDirection this[rightEdgePos to leftOfRightSideDirection] = leftEdgePos to leftOfLeftSideDirection if (edgePoint < edgePointCount) { leftEdgePos += getStepMove(leftSideDirection) rightEdgePos += getStepMove(rightSideDirection) } } val newLeftSide = findWhereToTurnTo(grid, leftEdgePos, leftSideDirection, isLeftSide = true) val newRightSide = findWhereToTurnTo(grid, rightEdgePos, rightSideDirection, isLeftSide = false) edgePoints += newLeftSide to newRightSide } check(size == (12 - 5) * 2 * edgePointCount) } private fun findWhereToTurnTo( grid: Set<Pos>, edgePos: Pos, sideDirection: Direction, isLeftSide: Boolean, ): Pair<Pos, Direction> { val sign = if (isLeftSide) 1 else -1 val forwardPos = edgePos + getStepMove(sideDirection) check(forwardPos + getStepMove(sideDirection.rotateBy(1 * sign)) !in grid) { "there shouldn't be a corner again" } val turnDirection = sideDirection.rotateBy(-1 * sign) val turnPos = edgePos + getStepMove(turnDirection) return when { forwardPos in grid -> forwardPos to sideDirection turnPos in grid -> edgePos to turnDirection else -> error("no direction to turn into?!") } } private sealed interface Instruction { data class Forward(val count: Int) : Instruction data object TurnLeft : Instruction data object TurnRight : Instruction } private enum class Direction { Right, Down, Left, Up } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
9,335
advent-of-pavel
Apache License 2.0
src/main/kotlin/com/colinodell/advent2016/Day20.kt
colinodell
495,627,767
false
{"Kotlin": 80872}
package com.colinodell.advent2016 class Day20(val input: List<String>) { private val firewallRules = optimize( input .map { it.split("-") } .map { LongRange(it[0].toLong(), it[1].toLong()) } .sortedBy { it.first } ) fun solvePart1() = firewallRules.first().last.inc() fun solvePart2() = 4294967296L - firewallRules.sumOf { (it.last - it.first).inc() } // Shamelessly borrowed from https://github.com/tginsberg/advent-2016-kotlin/blob/master/src/main/kotlin/com/ginsberg/advent2016/Day20.kt private fun optimize(ranges: List<LongRange>): List<LongRange> = ranges.drop(1).fold(ranges.take(1)) { carry, next -> if (carry.last().overlaps(next)) carry.dropLast(1).plusElement(carry.last().plus(next)) else carry.plusElement(next) } private fun LongRange.plus(other: LongRange): LongRange = LongRange(this.first.coerceAtMost(other.first), this.last.coerceAtLeast(other.last)) private fun LongRange.overlaps(other: LongRange) = other.first in this || this.last + 1 in other }
0
Kotlin
0
0
8a387ddc60025a74ace8d4bc874310f4fbee1b65
1,106
advent-2016
Apache License 2.0
src/main/kotlin/g1801_1900/s1830_minimum_number_of_operations_to_make_string_sorted/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1830_minimum_number_of_operations_to_make_string_sorted // #Hard #String #Math #Combinatorics #2023_06_21_Time_226_ms_(100.00%)_Space_36.3_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun makeStringSorted(s: String): Int { val n = s.length val count = IntArray(26) for (i in 0 until n) { count[s[i].code - 'a'.code]++ } val fact = LongArray(n + 1) fact[0] = 1 val mod = 1000000007 for (i in 1..n) { fact[i] = fact[i - 1] * i % mod } var len = n var ans: Long = 0 for (i in 0 until n) { len-- val bound = s[i].code - 'a'.code var first = 0 var rev: Long = 1 for (k in 0..25) { if (k < bound) { first += count[k] } rev = rev * fact[count[k]] % mod } ans = ( ans % mod + ( first * fact[len] % mod * modPow(rev, mod.toLong() - 2, mod) % mod ) % mod ) ans %= mod count[bound]-- } return ans.toInt() } private fun modPow(x: Long, n: Long, m: Int): Long { var x = x var n = n var result: Long = 1 while (n > 0) { if (n and 1L != 0L) { result = result * x % m } x = x * x % m n = n shr 1 } return result } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,636
LeetCode-in-Kotlin
MIT License
src/jvmMain/kotlin/ai/hypergraph/kaliningraph/sat/Debugging.kt
breandan
245,074,037
false
{"Kotlin": 1482924, "Haskell": 744, "OCaml": 200}
package ai.hypergraph.kaliningraph.sat import ai.hypergraph.kaliningraph.graphs.LabeledGraph import ai.hypergraph.kaliningraph.image.toHtmlPage import ai.hypergraph.kaliningraph.parsing.* import ai.hypergraph.kaliningraph.tensor.FreeMatrix import ai.hypergraph.kaliningraph.visualization.html import org.logicng.formulas.* fun FreeMatrix<Set<Tree>>.toGraphTable(): FreeMatrix<String> = data.map { it.mapIndexed { i, t -> t.toGraph("$i") } .fold(LabeledGraph()) { ac, lg -> ac + lg }.html() }.let { FreeMatrix(it) } fun CFG.parseHTML(s: String): String = parseTable(s).toGraphTable().toHtmlPage() @JvmName("summarizeBooleanMatrix") fun FreeMatrix<List<Boolean>?>.summarize(cfg: CFG): String = map { when { it == null -> "?" it.toString().length < 5 -> "" // else -> "C" cfg.toNTSet(it.toBooleanArray()).isEmpty() -> it.distinct() else -> "${cfg.toNTSet(it.toBooleanArray())}".replace("START", "S") } }.toString() fun FreeMatrix<BooleanArray?>.summarize(): String = map { if (it?.any { it } == true) "T" else if (it == null) "?" else " " }.toString() @JvmName("summarizeFormulaMatrix") fun FreeMatrix<SATVector>.summarize(cfg: CFG): String = map { when { it.isEmpty() -> "" it.all { it is Variable } -> "V[${it.size}]" it.all { it is Constant } -> "C${cfg.toNTSet(it.map { it == T }.toBooleanArray())}" // it.all { it is Constant } -> "C[${it.count { it == T }}/${it.size}]" it.any { it is Constant } -> "C[${it.count { it is Constant }}/${it.size}]" it.any { it is Variable } -> "V[${it.count { it is Variable }}/${it.size}]" else -> "F[${it.sumOf(Formula::numberOfAtoms)}]" } }.toString() // Summarize fill structure of bit vector variables fun FreeMatrix<SATVector>.fillStructure(): FreeMatrix<String> = FreeMatrix(numRows, numCols) { r, c -> this[r, c].let { if (it.all { it == F }) "0" else if (it.all { it in setOf(T, F) }) "LV$r$c" else "BV$r$c[len=${it.toString().length}]" } } fun Formula.toPython( params: String = variables().joinToString(", ") { it.name() }, bodyY: String = toString() .replace("~", "neg/") .replace("|", "|V|") .replace("&", "|Λ|"), bodyX: String = toString() .replace("~", "not ") .replace("|", "or") .replace("&", "and") ) = """ def y_constr($params): return $bodyY def x_constr($params): return $bodyX """.trimIndent() fun Formula.getCFGHash() = variables().first().name().substringAfter("cfgHash::").substringBefore("_") fun Map<Variable, Boolean>.toPython() = "assert x_constr(" + entries.joinToString(","){ (k, v) -> k.name() + "=" + v.toString().let { it[0].uppercase() + it.substring(1) } } + ")" fun SATRubix.startVariable(cfg: CFG) = diagonals.last().first()[cfg.bindex[START_SYMBOL]]
0
Kotlin
8
100
c755dc4858ed2c202c71e12b083ab0518d113714
2,827
galoisenne
Apache License 2.0
Course_Schedule_II_v2.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
import java.util.* import kotlin.collections.ArrayList // Given the total number of courses and a list of prerequisite pairs, // return the ordering of courses you should take to finish all courses. class Solution { fun findOrder(numCourses: Int, prerequisites: Array<IntArray>): IntArray { val res = ArrayList<Int>() val indegree = IntArray(numCourses) val edges = ArrayList<ArrayList<Int>>() for (i in 1..numCourses) { edges.add(ArrayList()) } // println(edges.size) for (pre in prerequisites) { edges[pre[1]].add(pre[0]) indegree[pre[0]]++ } val qu = LinkedList<Int>() for (i in 0 until numCourses) { if (indegree[i] == 0) { qu.offer(i) } } while (!qu.isEmpty()) { val node = qu.poll() res.add(node) for (e in edges[node]) { indegree[e]-- if (indegree[e] == 0) { qu.offer(e) } } } return if (res.size == numCourses) res.toIntArray() else IntArray(0) } } fun main(args: Array<String>) { val solution = Solution() val testset = arrayOf( arrayOf( intArrayOf(1, 0) ), arrayOf( intArrayOf(1, 0), intArrayOf(2, 0), intArrayOf(3, 1), intArrayOf(3, 2) ), arrayOf( intArrayOf(1, 0), intArrayOf(0, 1) ) ) val nums = intArrayOf(2, 4, 2) for (i in testset.indices) { solution.findOrder(nums[i], testset[i]).forEach { print("%d ".format(it)) } println() } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,736
leetcode
MIT License
kotlin/src/katas/kotlin/leetcode/sort_colors/SortColors.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.sort_colors import datsok.shouldEqual import nonstdlib.permutationsSequence import nonstdlib.printed import org.junit.jupiter.api.Test /** * https://leetcode.com/problems/sort-colors */ class SortColors { @Test fun `it works`() { listOf(0, 1, 2).permutationsSequence().forEach { list -> list.toIntArray().let { sortColors(it.printed()) it shouldEqual intArrayOf(0, 1, 2) } } listOf(0, 0, 1, 1, 2, 2).permutationsSequence().forEach { list -> list.toIntArray().let { sortColors(it.printed()) it shouldEqual intArrayOf(0, 0, 1, 1, 2, 2) } } } fun sortColors(nums: IntArray) { var left = 0 var right = nums.lastIndex var i = left while (i <= right) { when { nums[i] == 0 -> nums.swap(i++, left++) nums[i] == 2 -> nums.swap(i, right--) else -> i++ } } } } private fun IntArray.swap(i1: Int, i2: Int) { val temp = this[i1] this[i1] = this[i2] this[i2] = temp }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,183
katas
The Unlicense
src/Day01.kt
kuangbin
575,873,763
false
{"Kotlin": 8252}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var ans = 0 var tmp = 0 for (ss in input) { if (ss.isEmpty()) { ans = max(ans, tmp) tmp = 0 continue } tmp += ss.toInt() } ans = max(ans, tmp) return ans } fun part2(input: List<String>): Int { var tmp = 0 val ll = mutableListOf<Int>() for (ss in input) { if (ss.isEmpty()) { ll.add(tmp) tmp = 0 continue } tmp += ss.toInt() } ll.add(tmp) ll.sortDescending() return ll[0] + ll[1] + ll[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) println(part2(testInput)) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ea0d89065b4d3cb4f6f78f768882d5b5473624d1
1,029
advent-of-code-2022
Apache License 2.0
logic/src/main/java/lt/markmerkk/durak/Card.kt
marius-m
733,676,467
false
{"Kotlin": 167943}
package lt.markmerkk.durak import kotlin.random.Random data class Card( val suite: CardSuite, val rank: CardRank, val isTrump: Boolean = false ): Comparable<Card> { override fun compareTo(other: Card): Int { if (weight() > other.weight()) { return 1 } if (weight() == other.weight()) { return 0 } return -1 } fun valueAsString(): String = "${suite.out}${rank.out}" fun weight(): Int = if (isTrump) rank.weight + 100 else rank.weight override fun toString(): String { return "Card(${suite.out}${rank.out})" } companion object { val regexPattern = "[SHDC]([AKQJ]|[0-9]){1,2}" val cardStringMap: Map<String, Card> = CardSuite.values().toList() .combine(CardRank.values().toList()) .fold(mutableMapOf()) { mutableMap, suiteRankPair -> val card = Card(suiteRankPair.first, suiteRankPair.second) mutableMap.put(card.valueAsString(), card) mutableMap } fun generateDeck(cardTypeTrump: CardSuite): List<Card> { val cards = mutableListOf<Card>() for (suite in CardSuite.values()) { val isTrump = suite == cardTypeTrump for (rank in CardRank.values()) { cards.add(Card(suite, rank, isTrump)) } } return cards } fun generateDeckSmall(cardTypeTrump: CardSuite): List<Card> { val cards = mutableListOf<Card>() for (suite in CardSuite.values()) { val isTrump = suite == cardTypeTrump val smallerSetOfRanks = CardRank.values() .filter { it == CardRank.ACE || it == CardRank.KING || it == CardRank.QUEEN || it == CardRank.JACK || it == CardRank.TEN || it == CardRank.NINE } for (rank in smallerSetOfRanks) { cards.add(Card(suite, rank, isTrump)) } } return cards } fun randomSuite(random: Random = Random): CardSuite { val randomNum = (0..3).random(random) return CardSuite.values()[randomNum] } fun fromString(cardAsString: String): Card? { if (cardStringMap.containsKey(cardAsString)) return cardStringMap[cardAsString] return null } } } @Throws(IllegalStateException::class) fun List<Card>.trumpOrThrow(): CardSuite { return this.firstOrNull { it.isTrump }?.suite ?: throw IllegalStateException("No trump found") } fun List<Card>.filterSameRank(rank: CardRank): List<Card> = filter { it.rank == rank } enum class CardSuite( val out: String ) { SPADE("S"), HEART("H"), DIAMOND("D"), CLUB("C"), ; companion object { /** * Returns all suites with first item as trump */ fun valuesWithFirstAsTrump(trumpSuite: CardSuite): List<CardSuite> { return setOf(trumpSuite) .plus(CardSuite.values()) .toList() } } } enum class CardRank( val out: String, val fullOut: String, val weight: Int ) { ACE("A", "Ace", 14), KING("K", "King", 13), QUEEN("Q", "Queen", 12), JACK("J", "Jack", 11), TEN("10", "10", 10), NINE("9", "9", 9), EIGHT("8", "8", 8), SEVEN("7", "7", 7), SIX("6", "6", 6), FIVE("5", "5", 5), FOUR("4", "4", 4), THREE("3", "3", 3), TWO("2", "2", 2), ; }
0
Kotlin
0
0
8f2346cfcbb3c0871fb0db2768fd33d9b2fe277a
3,841
stupid2
Apache License 2.0
src/Day08.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import kotlin.math.max fun main() { fun initGrid(input: List<String>): Array<IntArray> { val result = Array(input.size) { IntArray(input[0].length) } for (i in input.indices) { for (j in input[i].indices) { result[i][j] = input[i][j].digitToInt() } } return result } fun part1(input: Array<IntArray>): Int { val rows = input.size val cols = input[0].size val invalidCoords = mutableSetOf<Pair<Int, Int>>() for (i in 0 until rows) { // Left visibility var maxHeight = -1 for (j in 0 until cols) { if (input[i][j] > maxHeight) { maxHeight = input[i][j] invalidCoords += i to j } } // Right visibility maxHeight = -1 for (j in cols - 1 downTo 0) { if (input[i][j] > maxHeight) { maxHeight = input[i][j] invalidCoords += i to j } } } for (j in 0 until cols) { // Top visibility var maxHeight = -1 for (i in 0 until rows) { if (input[i][j] > maxHeight) { maxHeight = input[i][j] invalidCoords += i to j } } // Bottom visibility maxHeight = -1 for (i in rows - 1 downTo 0) { if (input[i][j] > maxHeight) { maxHeight = input[i][j] invalidCoords += i to j } } } return invalidCoords.size } fun part2(input: Array<IntArray>): Int { val rows = input.size val cols = input[0].size var maxScore = 0 for (i in 0 until rows) { for (j in 0 until cols) { val maxHeight = input[i][j] var topScore = 0 for (ni in i - 1 downTo 0) { topScore++ if (input[ni][j] >= maxHeight) break } var bottomScore = 0 for (ni in i + 1 until rows) { bottomScore++ if (input[ni][j] >= maxHeight) break } var leftScore = 0 for (nj in j - 1 downTo 0) { leftScore++ if (input[i][nj] >= maxHeight) break } var rightScore = 0 for (nj in j + 1 until cols) { rightScore++ if (input[i][nj] >= maxHeight) break } val score = topScore * bottomScore * leftScore * rightScore maxScore = max(maxScore, score) } } return maxScore } val test = readInput("Day08_test") val testGrid = initGrid(test) println(part1(testGrid)) println(part2(testGrid)) val input = readInput("Day08") val grid = initGrid(input) println(part1(grid)) println(part2(grid)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
3,148
Advent-Of-Code-2022
Apache License 2.0
src/Day11.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
import java.util.* class Monkey( items: List<Long>, private val op: (Long) -> Long, private val divisor: Long, private val monkeyTrue: Int, private val monkeyFalse: Int ) { companion object { fun round(monkeys: List<Monkey>, easyMode: Boolean) { monkeys.forEach { it.turn(monkeys, easyMode) } } } private val itemsQueue: Queue<Long> = LinkedList(items) private var inspected = 0 fun countInspected(): Int { return inspected } private fun receive(item: Long) { itemsQueue.add(item) } private fun turn(monkeys: List<Monkey>, easyMode: Boolean) { while (itemsQueue.isNotEmpty()) { inspect(itemsQueue.remove(), monkeys, easyMode) } } private fun inspect(item: Long, monkeys: List<Monkey>, easyMode: Boolean) { val worry = if (easyMode) { op(item) / 3 } else { op(item) % (7 * 11 * 13 * 3 * 17 * 2 * 5 * 19) } if (worry % divisor == 0.toLong()) { monkeys[monkeyTrue].receive(worry) } else { monkeys[monkeyFalse].receive(worry) } ++inspected } } fun main() { fun part1(monkeys: List<Monkey>) { repeat(20) { Monkey.round(monkeys, true) } println(monkeys.map { it.countInspected() }.sorted().takeLast(2).reduce { a, b -> a * b }) } fun part2(monkeys: List<Monkey>) { repeat(10000) { if (it % 100 == 0) { println(it) } Monkey.round(monkeys, false) } monkeys.map { it.countInspected() }.sorted().takeLast(2).forEach { println(it) } println(monkeys.map { it.countInspected().toLong() }.sorted().takeLast(2).reduce { a, b -> a * b }) } fun createList(): List<Monkey> { return listOf( Monkey(listOf(63, 57), { it * 11 }, 7, 6, 2), Monkey(listOf(82, 66, 87, 78, 77, 92, 83), { it + 1 }, 11, 5, 0), Monkey(listOf(97, 53, 53, 85, 58, 54), { it * 7 }, 13, 4, 3), Monkey(listOf(50), { it + 3 }, 3, 1, 7), Monkey(listOf(64, 69, 52, 65, 73), { it + 6 }, 17, 3, 7), Monkey(listOf(57, 91, 65), { it + 5 }, 2, 0, 6), Monkey(listOf(67, 91, 84, 78, 60, 69, 99, 83), { it * it }, 5, 2, 4), Monkey(listOf(58, 78, 69, 65), { it + 7 }, 19, 5, 1), ) } println(part1(createList())) println(part2(createList())) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
2,545
aoc2022-kotlin
Apache License 2.0
Matrix/Matrix.kt
xfl03
154,698,285
false
null
/** * 邻接矩阵 * 1 2 0 0 * 0 0 1 0 * 1 0 0 1 * 0 0 1 0 */ val matrix = arrayOf( "1200", "0010", "1001", "0010" ) /** * 矩阵乘法 */ fun multiply(a: Array<IntArray>, b: Array<IntArray>): Array<IntArray> { val arr = Array(a.size) { IntArray(b[0].size) } for (i in a.indices) { for (j in 0 until b[0].size) { for (k in 0 until a[0].size) { arr[i][j] += a[i][k] * b[k][j] } } } return arr } /** * 输出矩阵 */ fun printMatrix(a: Array<IntArray>, mode: Int = 0) { val n = a.size for (i in 0 until n) { for (j in 0 until n) { print(if (mode == 0) "${a[i][j]} " else "${if (a[i][j] != 0) 1 else 0} ") } println() } } /** * 矩阵内元素和 */ fun sumMatrix(a: Array<IntArray>): Int { val n = a.size var t = 0 for (i in 0 until n) { for (j in 0 until n) { t += a[i][j] } } return t } /** * 矩阵加法 */ fun add(a: Array<IntArray>, b: Array<IntArray>): Array<IntArray> { val n = a.size val arr = Array(n) { IntArray(n) } for (i in 0 until n) { for (j in 0 until n) { arr[i][j] = a[i][j] + b[i][j] } } return arr } /** * 主函数 */ fun main(args: Array<String>) { val n = matrix.size //创建二维数组存储矩阵 val arr = Array(n) { IntArray(n) } //初始化矩阵,将文本形式的矩阵转换成数组形式 (0 until n).forEach { i -> var t = matrix[i].toInt() (0 until n).forEach { arr[i][n - 1 - it] = t % 10 t /= 10 } } //输出邻接矩阵 println("邻接矩阵") printMatrix(arr) println() //计算并存储矩阵的n次方 val arr2 = multiply(arr, arr) val arr3 = multiply(arr, arr2) val arr4 = multiply(arr, arr3) println("邻接矩阵4次方") printMatrix(arr4) println("长度为4的通路") println(sumMatrix(arr4)) println() //合并矩阵 val arrs = add(arr, add(arr2, arr3)) println("可达矩阵") printMatrix(arrs, 1) }
0
Kotlin
0
0
281042e307c349d95a4ec4c49aee40b4ab9fa4b0
2,162
DiscreteCourseWork
MIT License
src/Day02.kt
SpencerDamon
573,244,838
false
{"Kotlin": 6482}
fun main() { fun part1(input: List<String>): Int { var myTotalScore = 0 for (i in input) { val (otherPlayer, myPlay) = i.split(" ") when (otherPlayer) { "A" -> if (myPlay == "X") { myTotalScore += 4 // 1 for rock, 3 for draw } else if (myPlay == "Y") { myTotalScore += 8 // 2 for paper, 6 for win } else myTotalScore += 3 // 3 for scissors, 0 for lose "B" -> if (myPlay == "X") { myTotalScore += 1 // 1 for rock, 0 for lose } else if (myPlay == "Y") { myTotalScore += 5 // 2 for paper, 3 for draw } else myTotalScore += 9 // 3 for scissors, 6 for win "C" -> if (myPlay == "X") { myTotalScore += 7 // 1 for rock, 6 for win } else if (myPlay == "Y") { myTotalScore += 2 // 2 for paper, 0 for lose } else myTotalScore += 6 // 3 for scissors, 3 for draw } } //println(myTotalScore) return myTotalScore } fun part2(input: List<String>): Int { var myTotalScore = 0 for (i in input) { val (otherPlayer, myPlay) = i.split(" ") when (otherPlayer) { "A" -> if (myPlay == "X") { myTotalScore += 3 // 3 for scissors, 0 for lose } else if (myPlay == "Y") { myTotalScore += 4 // 1 for rock, 3 for draw } else myTotalScore += 8// 2 for paper, 6 for win "B" -> if (myPlay == "X") { myTotalScore += 1 // 1 for rock, 0 for lose } else if (myPlay == "Y") { myTotalScore += 5 // 2 for paper, 3 for draw } else myTotalScore += 9 // 3 for scissors, 6 for win "C" -> if (myPlay == "X") { myTotalScore += 2 // 2 for paper, 0 for lose } else if (myPlay == "Y") { myTotalScore += 6// 3 for scissors, 3 for draw } else myTotalScore += 7 // 1 for rock, 6 for win } } //println(myTotalScore) return myTotalScore } // remove comment to test, // 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_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
659a9e9ae4687bd633bddfb924416c80a8a2db2e
2,618
aoc-2022-in-Kotlin
Apache License 2.0
src/main/kotlin/adventofcode2017/potasz/P10KnotHash.kt
potasz
113,064,245
false
null
package adventofcode2017.potasz object P10KnotHash { val SUFFIX = listOf(17, 31, 73, 47, 23) val sampleLengths = arrayListOf(3, 4, 1, 5) val inputLengths = arrayListOf(165,1,255,31,87,52,24,113,0,91,148,254,158,2,73,153) val inputString = "165,1,255,31,87,52,24,113,0,91,148,254,158,2,73,153" private fun sparseHash(lengths: List<Int>, size: Int = 256, rounds: Int = 64): List<Int> { val numbers = IntArray(size) { it } var pos = 0 var skipSize = 0 repeat (rounds) { for (length in lengths) { val subList = IntArray(length) { numbers[(pos + it) % size] } (pos until pos + length).forEach { numbers[it % size] = subList[length - 1 - (it - pos)] } pos = (pos + length + skipSize++) % size } } return numbers.toList() } private fun denseHash(sparseHash: List<Int>, blockSize: Int = 16): List<Int> { if (sparseHash.size % blockSize != 0) throw IllegalArgumentException("Hash size need to be divisible by block size!") return sparseHash.chunked(blockSize) { it.fold(0) { acc, i -> acc xor i } } } fun List<Int>.toHexString(): String = this.joinToString("") { it.toString(16).padStart(2, '0') } fun knotHash(input: String): String = denseHash(sparseHash(input.toCharArray().map {it.toInt()}.plus(SUFFIX))).toHexString() @JvmStatic fun main(args: Array<String>) { // Test on sample val sampleHash1 = sparseHash(sampleLengths, 5, 1) println(sampleHash1[0] * sampleHash1[1]) // Part 1 val inputHash1 = sparseHash(inputLengths, rounds = 1) println(inputHash1[0] * inputHash1[1]) // Part 2 println(knotHash(inputString)) } }
0
Kotlin
0
1
f787d9deb1f313febff158a38466ee7ddcea10ab
1,773
adventofcode2017
Apache License 2.0
src/main/kotlin/leetcode/problem0040/CombinationSumSecond.kt
ayukatawago
456,312,186
false
{"Kotlin": 266300, "Python": 1842}
package leetcode.problem0040 class CombinationSumSecond { fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> { if (candidates.all { it > target }) { return emptyList() } val countMap = hashMapOf<Int, Int>() candidates.forEach { countMap[it] = (countMap[it] ?: 0) + 1 } return combinationSum(countMap, target).toList() } private fun combinationSum(hashMap: HashMap<Int, Int>, target: Int): Set<List<Int>> { val answer = mutableSetOf<List<Int>>() hashMap.forEach { (candidate, count) -> if (count == 0) return@forEach when { target == candidate -> answer.add(listOf(candidate)) target > candidate -> { hashMap[candidate] = count - 1 combinationSum(hashMap, target - candidate).forEach { if (it.isNotEmpty()) { answer.add(it.toMutableList().apply { add(candidate) }.sorted()) } } hashMap[candidate] = count } else -> Unit } } return answer } }
0
Kotlin
0
0
f9602f2560a6c9102728ccbc5c1ff8fa421341b8
1,242
leetcode-kotlin
MIT License
leetcode/kotlin/basic-calculator-ii.kt
PaiZuZe
629,690,446
false
null
class Solution { fun calculate(s: String): Int { val rpn = toReversePolishNotation(toList(s)) val stack = ArrayDeque<Int>() for (x in rpn) { if (x in "+-*/") { val operand2 = stack.removeLast() val operand1 = stack.removeLast() val result = when (x) { "-" -> operand1 - operand2 "/" -> operand1 / operand2 "+" -> operand1 + operand2 "*" -> operand1 * operand2 else -> operand1 } stack.add(result) } else { stack.add(x.toInt()) } } return stack.last().toInt() } private fun toReversePolishNotation(list: List<String>): List<String> { val rpn = ArrayDeque<String>() val operators = ArrayDeque<String>() for (op in list) { if (op in "-+*/") { while (operators.size > 0 && hasLowerPrecedence(op, operators.last())) { rpn.add(operators.removeLast()) } operators.add(op) } else { rpn.add(op) } } while (operators.isNotEmpty()) { rpn.add(operators.removeLast()) } return rpn.toList() } private fun hasLowerPrecedence(operator1: String, operator2: String): Boolean { if (operator1 in "*/" && operator2 in "+-") { return false } return true } private fun toList(s: String): List<String> { val list = mutableListOf<StringBuilder>() for (c in s) { if (c in "+-*/") { list.add(StringBuilder(c.toString())) } else if (c in '0'..'9') { if (list.size == 0 || list.last().toString() in "+-*/") { list.add(StringBuilder(c.toString())) } else { list.last().append(c) } } } return list.map { it.toString() } } } fun main() { val sol = Solution() val s1 = "3+2*2" val s2 = " 3/2 " val s3 = " 3+5 / 2 " val s4 = "0-2147483647" val s5 = "1-1+1" val s6 = "1-1-1" val s7 = "1*2-3/4+5*6-7*8+9/10" val resp1 = sol.calculate(s1) println("resp: $resp1 is expected: ${ resp1 == 7 }") val resp2 = sol.calculate(s2) println("resp: $resp2 is expected: ${ resp2 == 1 }") val resp3 = sol.calculate(s3) println("resp: $resp3 is expected: ${ resp3 == 5 }") val resp4 = sol.calculate(s4) println("resp: $resp4 is expected: ${ resp4 == -2147483647 }") val resp5 = sol.calculate(s5) println("resp: $resp5 is expected: ${ resp5 == 1 }") val resp6 = sol.calculate(s6) println("resp: $resp6 is expected: ${ resp6 == -1 }") val resp7 = sol.calculate(s7) println("resp: $resp7 is expected: ${ resp7 == -24 }") }
0
Kotlin
0
0
175a5cd88959a34bcb4703d8dfe4d895e37463f0
2,968
interprep
MIT License
tegral-niwen/tegral-niwen-lexer/src/main/kotlin/guru/zoroark/tegral/niwen/lexer/matchers/RepeatedRecognizer.kt
utybo
491,247,680
false
{"Kotlin": 1071223, "Nix": 2449}
/* * 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 guru.zoroark.tegral.niwen.lexer.matchers import guru.zoroark.tegral.core.TegralDsl /** * A recognizer that, using another "base" recognizer, will recognize a * repetition of the other recognizer. * * @property baseRecognizer The recognizer which will be repeatedly used. * @property min The minimum amount of repetitions that has to be present for a * successful recognition. * @property max The maximum amount of repetitions that can be present for a * successful recognition. */ class RepeatedRecognizer( val baseRecognizer: TokenRecognizer, val min: Int = 1, val max: Int? = null ) : TokenRecognizer { override fun recognize(s: String, startAt: Int): Pair<String, Int>? { var repetitions = 0 var index = startAt var totalString = "" while (index < s.length) { val (ts, end) = baseRecognizer.recognize(s, index) ?: break repetitions += 1 if (max != null && repetitions > max) { return null // Exceeded max allowed repetitions } index = end totalString += ts } return if (repetitions < min) null else totalString to index } } /** * Create a recognizer that recognizes the given recognizer or pseudo-recognizer * 1 or more times in a row. * * This construct supports any (pseudo-)recognizer that is supported by * [toRecognizer]. * * @return A [RepeatedRecognizer] using the given * recognizer/pseudo-recognizer. */ @TegralDsl val Any.repeated: RepeatedRecognizer get() = RepeatedRecognizer(toRecognizer(this)) /** * Create a recognizer that recognizes the given recognizer or pseudo-recognizer * [min] to [max] (inclusive) times in a row. By default, the * (pseudo)-recognizer is recognized from 1 to an infinite amount of times. * * Any recognizer or pseudo-recognizer that is supported by [toRecognizer] can * be used here. * * @param min The minimum amount of repetitions required to get a successful * match. If the number of repetitions is below the minimum, the recognition * fails. * * @param max The maximum amount of repetitions required to get a successful * match, or null if no such limit should exist. If the number of repetitions * exceeds the maximum, the recognition fails. * * @return A [RepeatedRecognizer] that uses the constraints provided in * the parameters. */ fun Any.repeated(min: Int = 1, max: Int? = null): RepeatedRecognizer = RepeatedRecognizer(toRecognizer(this), min, max)
21
Kotlin
3
33
eb71e752b91cac01f24ad12563c3f25d6a8f8630
3,084
Tegral
Apache License 2.0
src/main/kotlin/adventofcode2019/Day06UniversalOrbitMap.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2019 class Day06UniversalOrbitMap data class OrbitObject(val code: String) data class Orbit(val center: OrbitObject, val satelite: OrbitObject) class SpaceOrbit(val orbitMap: List<String>) { val orbits: List<Orbit> init { orbits = orbitMap.map { val (center, satelite) = it.split(")").take(2) Orbit(OrbitObject(center), OrbitObject(satelite)) } } fun orbitsCount(): Int { return orbits.sumOf { orbit -> findObjectDepth(orbit.satelite, 0) } } private fun findObjectDepth(orbitObject: OrbitObject, currentDepth: Int = 0): Int { val center = orbits.firstOrNull { it.satelite == orbitObject }?.center return if (center == null) { currentDepth } else { findObjectDepth(center, currentDepth + 1) } } fun findYouSanDistance(): Int { val youMap = mutableMapOf<OrbitObject, Int>() val sanMap = mutableMapOf<OrbitObject, Int>() var parent = orbits.firstOrNull { it.satelite.code == "YOU" }?.center var distance = 0 while (parent != null) { youMap[parent] = distance++ parent = orbits.firstOrNull { it.satelite.code == parent?.code }?.center } parent = orbits.first { it.satelite.code == "SAN" }.center distance = 0 while (parent != null) { sanMap[parent] = distance++ parent = orbits.firstOrNull { it.satelite.code == parent?.code }?.center } val intersection = youMap.keys.first { sanMap.contains(it) } val youDistance = youMap[intersection] ?: 0 val sanDistance = sanMap[intersection] ?: 0 return youDistance + sanDistance } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
1,752
kotlin-coding-challenges
MIT License
src/day01/Day01.kt
TheRishka
573,352,778
false
{"Kotlin": 29720}
package day01 import readInput fun main() { fun extractGnomeCalories(input: List<String>): Map<Int, Int> { var gnomeIndex = 0 var gnomeCalories = mutableMapOf<Int, Int>() input.forEach { if (it.isEmpty()) { gnomeIndex++ } else { gnomeCalories[gnomeIndex] = gnomeCalories.getOrDefault(gnomeIndex, 0) + it.toInt() } } return gnomeCalories } fun part1(input: List<String>): Int { val calories = extractGnomeCalories(input) var biggestAmount = 0 calories.forEach { if (it.value > biggestAmount) { biggestAmount = it.value } } return biggestAmount } fun part2(input: List<String>) = extractGnomeCalories(input).values.toList().sortedDescending() val input = readInput("day01/Day01") println(part1(input)) println(part2(input).subList(0, 3).sum()) }
0
Kotlin
0
1
54c6abe68c4867207b37e9798e1fdcf264e38658
970
AOC2022-Kotlin
Apache License 2.0
src/main/aoc2015/Day25.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2015 class Day25(input: List<String>) { private val row = input.first().substringBeforeLast(",").substringAfterLast(" ").toInt() private val col = input.first().substringBeforeLast(".").substringAfterLast(" ").toInt() private val firstCode = 20151125L private val multiplicand = 252533 private val divisor = 33554393 private fun calculateCode(n: Int): Int { var ret = firstCode repeat(n - 1) { ret = (ret * multiplicand) % divisor } return ret.toInt() } // | 1 2 3 4 5 6 //---+---+---+---+---+---+---+ // 1 | 1 3 6 10 15 21 // 2 | 2 5 9 14 20 // 3 | 4 8 13 19 // 4 | 7 12 18 // 5 | 11 17 // 6 | 16 // private fun indexOfRowInColumnOne(row: Int): Int { // first column // row 1 = 1, row 2 = row 1 + 1, row 3 = row 2 + 2, row 4 = row 3 + 3 // ==> row 6 = 1 + 1 + 2 + 3 + 4 + 5 return 1 + (1 until row).sum() } private fun indexOf(row: Int, col: Int): Int { // For column 2 take the index of column one and increase with current row + 1 // For column 3 take the index of column 2 and increase with previous increase + 1 // Example, row 4 // 7, 12 (= 7 + 5), 18 (= 12 + 6), 25 (= 18 + 7), etc return indexOfRowInColumnOne(row) + (1 until col).sumOf { row + it } } fun solvePart1(): Int { return calculateCode(indexOf(row, col)) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,493
aoc
MIT License
src/day-2/part-1/solution-day-2-part-1.kts
d3ns0n
572,960,768
false
{"Kotlin": 31665}
import java.io.File fun convertToPair(string: String): Pair<Char, Char> { val split = string.split(" ") return Pair(split.get(0).first(), split.get(1).first()) } fun letterValue(char: Char): Int { return mapOf('A' to 1, 'B' to 2, 'C' to 3, 'X' to 1, 'Y' to 2, 'Z' to 3).getOrDefault(char, 0) } fun compare(pair: Pair<Char, Char>): Int { return (letterValue(pair.second) - letterValue(pair.first)).mod(3) } var result = File("../input.txt") .readLines() .map { convertToPair(it) } .map { when (compare(it)) { 0 -> letterValue(it.second) + 3 //draw 1 -> letterValue(it.second) + 6 //win else -> letterValue(it.second) //draw } }.sum() println(result) assert(result == 12679)
0
Kotlin
0
0
8e8851403a44af233d00a53b03cf45c72f252045
763
advent-of-code-22
MIT License
src/main/kotlin/16-jun.kt
aladine
276,334,792
false
{"C++": 70308, "Kotlin": 53152, "Java": 10020, "Makefile": 511}
import java.util.* class Solution16Jun { // Regex for digit from 0 to 255. val zeroTo255 = "([0-9]|[1-9]\\d{1}|1\\d{2}|2[0-4]\\d|25[0-5])" val fourHexa = "([0-9A-Fa-f]+)" // "([0-9A-Fa-f]{1,2,3,4})" val rgv4 = zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255 val rgv6 = fourHexa + ":" + fourHexa + ":" + fourHexa + ":" + fourHexa + ":" + fourHexa + ":" + fourHexa + ":" + fourHexa + ":" + fourHexa val v4Reg = Regex(rgv4) val v6Reg = Regex(rgv6) fun isValidIPv6(ip: String): String { ip.split(':').forEach { when { it.length > 4 -> return "Neither" !it.contains(Regex(fourHexa)) -> return "Neither" } } return "IPv6" } fun validIPAddress(IP: String): String { return when { v4Reg.matches(IP) -> "IPv4" v6Reg.matches(IP) -> "IPv6" // IP.split(':').size == 8 -> isValidIPv6(IP) else -> "Neither" } } } /*fun validIPAddress(IP: String): String { return when { IP.split('.').size == 4 -> isValidIPv4(IP) // String[] ipv4 = IP.split("\\.",-1) in java IP.split(':').size == 8 -> isValidIPv6(IP) else -> "Neither" } } fun isValidIPv4(ip: String): String{ ip.split('.').forEach { when{ it.length > 3 -> return "Neither" !it.contains(Regex("^[0-9]+\$")) -> return "Neither" it.length != 1 && it.length != it.trimStart('0').length -> return "Neither" it.toInt() > 255 || it.toInt() < 0 -> return "Neither" } } return "IPv4" } fun isValidIPv6(ip: String): String{ ip.split(':').forEach { when{ it.length > 4 -> return "Neither" !it.contains(Regex("^[0-9A-Fa-f]+\$")) -> return "Neither" } } return "IPv6" } */
0
C++
1
1
54b7f625f6c4828a72629068d78204514937b2a9
1,886
awesome-leetcode
Apache License 2.0
src/main/kotlin/org/kollektions/permutester/Permutator.kt
AlexCue987
224,866,962
false
null
package org.kollektions.permutester class Permutator(val expectedPermutations: List<List<Any>>) { constructor(vararg items: List<Any>): this(permutate(*items)) fun match(actualPermutations: List<List<Any>>) { val duplicates = findDuplicates(actualPermutations) val missing = expectedPermutations.filter { it !in actualPermutations } val unexpected = actualPermutations.filter { it !in expectedPermutations } val possibleProblems = listOf<Pair<String, Collection<Any>>>( Pair("Duplicates", duplicates), Pair("Missing", missing), Pair("Unexpected", unexpected) ) val problems = possibleProblems.filter { it.second.isNotEmpty() } if (problems.isNotEmpty()) { val message = problems.map { "${it.first}:\n${describeList(it.second)}" }.joinToString("\n") throw AssertionError(message) } } } private fun describeList(collection: Collection<Any>) = collection.joinToString("\n") fun permutate(vararg items: List<Any>): List<List<Any>>{ val itemsList = items.toList() require(itemsList.isNotEmpty()){ "Must provide at least one argument" } itemsList.forEach { require(it.isNotEmpty()) { "Each argument must be not empty." } } val offset = itemsList.size - 1 return permutateForOffset(offset, itemsList) } fun permutateForOffset(offset: Int, items: List<List<Any>>): List<List<Any>>{ if(offset == 0){ return items[0].map { listOf(it) } } val headPermutations = permutateForOffset(offset - 1, items) return crossJoin(headPermutations, items[offset]) } fun crossJoin(headPermutations: List<List<Any>>, tails: List<Any>): List<List<Any>> { val ret: MutableList<List<Any>> = mutableListOf() for(headPermutation in headPermutations){ for(tail in tails){ val permutation = mutableListOf<Any>() permutation.addAll(headPermutation) permutation.add(tail) ret.add(permutation) } } return ret }
0
Kotlin
0
0
3ec2425775851f44539542c428f19194c656d87b
2,063
permutester
Apache License 2.0
year2020/day12/part2/src/main/kotlin/com/curtislb/adventofcode/year2020/day12/part2/Year2020Day12Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- Before you can give the destination to the captain, you realize that the actual action meanings were printed on the back of the instructions the whole time. Almost all of the actions indicate how to move a waypoint which is relative to the ship's position: - Action N means to move the waypoint north by the given value. - Action S means to move the waypoint south by the given value. - Action E means to move the waypoint east by the given value. - Action W means to move the waypoint west by the given value. - Action L means to rotate the waypoint around the ship left (counter-clockwise) the given number of degrees. - Action R means to rotate the waypoint around the ship right (clockwise) the given number of degrees. - Action F means to move forward to the waypoint a number of times equal to the given value. The waypoint starts 10 units east and 1 unit north relative to the ship. The waypoint is relative to the ship; that is, if the ship moves, the waypoint moves with it. For example, using the same instructions as above: - F10 moves the ship to the waypoint 10 times (a total of 100 units east and 10 units north), leaving the ship at east 100, north 10. The waypoint stays 10 units east and 1 unit north of the ship. - N3 moves the waypoint 3 units north to 10 units east and 4 units north of the ship. The ship remains at east 100, north 10. - F7 moves the ship to the waypoint 7 times (a total of 70 units east and 28 units north), leaving the ship at east 170, north 38. The waypoint stays 10 units east and 4 units north of the ship. - R90 rotates the waypoint around the ship clockwise 90 degrees, moving it to 4 units east and 10 units south of the ship. The ship remains at east 170, north 38. - F11 moves the ship to the waypoint 11 times (a total of 44 units east and 110 units south), leaving the ship at east 214, south 72. The waypoint stays 4 units east and 10 units south of the ship. After these operations, the ship's Manhattan distance from its starting position is 214 + 72 = 286. Figure out where the navigation instructions actually lead. What is the Manhattan distance between that location and the ship's starting position? */ package com.curtislb.adventofcode.year2020.day12.part2 import com.curtislb.adventofcode.common.geometry.Point import com.curtislb.adventofcode.year2020.day12.navigation.WaypointNavigationShip import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 12, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { val file = inputPath.toFile() val ship = WaypointNavigationShip(waypoint = Point(10, 1)) file.forEachLine { ship.followInstruction(it) } return ship.position.manhattanDistance(Point.ORIGIN) } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,916
AdventOfCode
MIT License
year2019/day06/part2/src/main/kotlin/com/curtislb/adventofcode/year2019/day06/part2/Year2019Day06Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- Now, you just need to figure out how many orbital transfers you (YOU) need to take to get to Santa (SAN). You start at the object YOU are orbiting; your destination is the object SAN is orbiting. An orbital transfer lets you move from any object to an object orbiting or orbited by that object. For example, suppose you have the following map: COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L K)YOU I)SAN Visually, the above map of orbits looks like this: YOU / G - H J - K - L / / COM - B - C - D - E - F \ I - SAN In this example, YOU are in orbit around K, and SAN is in orbit around I. To move from K to I, a minimum of 4 orbital transfers are required: - K to J - J to E - E to D - D to I Afterward, the map of orbits looks like this: G - H J - K - L / / COM - B - C - D - E - F \ I - SAN \ YOU What is the minimum number of orbital transfers required to move from the object YOU are orbiting to the object SAN is orbiting? (Between the objects they are orbiting - not between YOU and SAN.) */ package com.curtislb.adventofcode.year2019.day06.part2 import com.curtislb.adventofcode.year2019.day06.orbits.Universe import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2019, day 6, part 2. * * @param inputPath The path to the input file for this puzzle. * @param start The name of the node representing our starting location. * @param target The name of the node representing the location of our target. */ fun solve( inputPath: Path = Paths.get("..", "input", "input.txt"), start: String = "YOU", target: String = "SAN" ): Int? { val universe = Universe(inputPath.toFile()) return universe.findOrbitalTransferDistance(start, target) } fun main() = when (val solution = solve()) { null -> println("No orbital transfer path found.") else -> println(solution) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,084
AdventOfCode
MIT License
year2019/day04/part2/src/main/kotlin/com/curtislb/adventofcode/year2019/day04/part2/Year2019Day04Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits. Given this additional criterion, but still ignoring the range rule, the following are now true: - 112233 meets these criteria because the digits never decrease and all repeated digits are exactly two digits long. - 123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444). - 111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double 22). How many different passwords within the range given in your puzzle input meet all of the criteria? */ package com.curtislb.adventofcode.year2019.day04.part2 import com.curtislb.adventofcode.common.parse.toIntRange import com.curtislb.adventofcode.year2019.day04.password.ExactLengthGenerator import com.curtislb.adventofcode.year2019.day04.password.ExactRepeatCountDigitGenerator import com.curtislb.adventofcode.year2019.day04.password.InRangeGenerator import com.curtislb.adventofcode.year2019.day04.password.NonDecreasingGenerator import com.curtislb.adventofcode.year2019.day04.password.SatisfiesAllGenerator import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2019, day 4, part 2. * * @param inputPath The path to the input file for this puzzle. * @param passwordLength The number of digits in a valid password. * @param repeatCount The exact number of times a digit must be repeated in a valid password. */ fun solve( inputPath: Path = Paths.get("..", "input", "input.txt"), passwordLength: Int = 6, repeatCount: Int = 2 ): Int { val passwordRange = inputPath.toFile().readText().toIntRange() val generator = SatisfiesAllGenerator( ExactLengthGenerator(passwordLength), InRangeGenerator(passwordRange.first, passwordRange.last), NonDecreasingGenerator(), ExactRepeatCountDigitGenerator(repeatCount) ) return generator.countPasswords() } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,064
AdventOfCode
MIT License
2020/december09.kt
cuuzis
318,759,108
false
{"TypeScript": 105346, "Java": 65959, "Kotlin": 17038, "Scala": 5674, "JavaScript": 3511, "Shell": 724}
import java.io.File /** * https://adventofcode.com/2020/day/9 */ fun main() { val weakNumber = star1() println(weakNumber) // 85848519 println(star2(weakNumber)) // 13414198 } private fun input(): List<String> { return File("2020/december09.txt").readLines(); } private val preambleSize = 25 private fun star1(): Long { val lines = input().map(String::toLong) for (lineNum in preambleSize until lines.size) { val num = lines[lineNum] var isWeak = true for (i in lineNum - preambleSize until lineNum) { val num1 = lines[i] for (j in i + 1 until lineNum) { val num2 = lines[j]; if (num1 + num2 == num) { isWeak = false } } } if (isWeak) { return num } } return -1L } private fun star2(weakNumber: Long): Long { val lines = input().map(String::toLong) var start = 0 var end = 1 var sum = lines[0] + lines[1] while (start < end && end < lines.size) { if (sum < weakNumber) { // increase window end++ sum += lines[end] } else if (sum > weakNumber) { // decrease window sum -= lines[start] start++ } else if (sum == weakNumber) { // find min + max within window var min = lines[start] var max = lines[start] for (i in start..end) { if (lines[i] > max) { max = lines[i] } else if (lines[i] < min) { min = lines[i] } } return min + max } } return -1L }
0
TypeScript
0
1
35e56aa97f33fae5ed3e717dd01d303153caf467
1,754
adventofcode
MIT License
src/Atoi.kt
philipphofmann
236,017,177
false
{"Kotlin": 17647}
/** * Parses the string as an [Int] number and returns the result. * See https://leetcode.com/problems/string-to-integer-atoi/ * * @throws NumberFormatException if the string is not a valid representation of a number. */ fun atoi(string: String): Int { val noWhitespaces = string.trim { it.isWhitespace() } if (!isDigit(noWhitespaces[0])) { return 0 } val digitsAndNegativeSign = noWhitespaces.trim { char -> !isDigit(char) || char == '+' } val isNegative = digitsAndNegativeSign[0] == '-' val digits = if (isNegative) { digitsAndNegativeSign.removeRange(0, 1) } else { digitsAndNegativeSign } var result = 0 var exponent = 1.0 var overflow = false for (i in digits.length - 1 downTo 0) { val digitValue = (charToInt(digits[i]) * exponent).toInt() val r = result + digitValue // HD 2-12 Overflow if both arguments have the opposite sign of r if (result xor r and (digitValue xor r) < 0) { overflow = true break } result = r exponent *= 10 } result = if (isNegative) -result else result return if (overflow) { if (result < 0) { Int.MIN_VALUE } else { Int.MAX_VALUE } } else { result } } private fun isDigit(char: Char) = charToInt(char) >= 0 || char == '-' || char == '+' private fun charToInt(char: Char): Int { return when (char) { '0' -> 0 '1' -> 1 '2' -> 2 '3' -> 3 '4' -> 4 '5' -> 5 '6' -> 6 '7' -> 7 '8' -> 8 '9' -> 9 else -> Int.MIN_VALUE } }
0
Kotlin
0
1
db0889c8b459af683149530f9aad93ce2926a658
1,690
coding-problems
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem54/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem54 /** * LeetCode page: [54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix/); */ class Solution { /* Complexity: * Time O(N) and Auxiliary Space O(1) where N is the number of elements in matrix; */ fun spiralOrder(matrix: Array<IntArray>): List<Int> { val result = mutableListOf<Int>() matrix.spiralTraversal { element -> result.add(element) } return result } private tailrec fun Array<IntArray>.spiralTraversal( fromLayer: Int = 0, onEachElement: (element: Int) -> Unit ) { require(fromLayer >= 0) // Check if the traversal is ended if (fromLayer > lastSpiralLayer()) { return } // Traverse the fromLayer spiralTraversalAt(fromLayer, onEachElement) // Recursive call for the next layer spiralTraversal(fromLayer + 1, onEachElement) } private fun Array<IntArray>.lastSpiralLayer(): Int { val indexLastRow = this.lastIndex val indexLastColumn = this[0].lastIndex val minLastIndex = minOf(indexLastRow, indexLastColumn) return minLastIndex / 2 } private fun Array<IntArray>.spiralTraversalAt( layer: Int, onEachElement: (element: Int) -> Unit ) { require(layer >= 0) val indexLastRow = this.lastIndex val indexLastColumn = this[0].lastIndex val top = layer val bottom = indexLastRow - layer val left = layer val right = indexLastColumn - layer check(top <= bottom) check(left <= right) // Traverse the top row for (column in left..right) { onEachElement(this[top][column]) } // Traverse the right column, except its first and last elements for (row in top + 1 until bottom) { onEachElement(this[row][right]) } // If bottom and top are different, traverse the bottom row in reversed order if (bottom != top) { for (column in right downTo left) { onEachElement(this[bottom][column]) } } /* If left and right are different, traverse the left column in reversed order, * except its first and last elements. */ if (left != right) { for (row in bottom - 1 downTo top + 1) { onEachElement(this[row][left]) } } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,498
hj-leetcode-kotlin
Apache License 2.0
day13/src/main/kotlin/Main.kt
rstockbridge
225,212,001
false
null
fun main() { val inputAsList = resourceFile("input.txt") .readLines()[0] .split(',') .map(String::toLong) val inputAsMap = convertInputToMap(inputAsList) println("Part I: the solution is ${solvePartI(inputAsMap)}.") println("Part II: the solution is ${solvePartII(inputAsMap, 2.toLong())}.") } fun solvePartI(input: Map<Long, Long>): Int { val game = Game(input) return game .getTiles() .filter { tile -> tile.value == TileType.BLOCK } .size } fun solvePartII(input: Map<Long, Long>, numberOfQuarters: Long): Int { val game = Game(input) return game.play(numberOfQuarters) } fun convertInputToMap(inputAsInts: List<Long>): Map<Long, Long> { val result = mutableMapOf<Long, Long>().withDefault { 0 } for (i in inputAsInts.indices) { result[i.toLong()] = inputAsInts[i] } return result.toMap() }
0
Kotlin
0
0
bcd6daf81787ed9a1d90afaa9646b1c513505d75
924
AdventOfCode2019
MIT License
src/main/kotlin/com/github/davio/aoc/general/Matrix.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.general data class Matrix<T>(val data: List<List<T>>) { val maxX: Int = data.lastIndex val maxY: Int = data[0].lastIndex val rows: List<List<T>> get() = data.toList() val columns: List<List<T>> get() = data[0].indices.map { x -> data.indices.map { y -> data[y][x] }.toList() } operator fun get(x: Int, y: Int) : T = data[y][x] operator fun get(p: Point) : T = data[p.y][p.x] fun getAdjacentPoints(p: Point): Sequence<Point> { if (data.isEmpty()) return emptySequence() if (p.x !in (0..maxX) || p.y !in (0..maxY)) return emptySequence() return sequence { ((p.y - 1).coerceAtLeast(0)..(p.y + 1).coerceAtMost(maxY)).forEach { y -> ((p.x - 1).coerceAtLeast(0)..(p.x + 1).coerceAtMost(maxX)).forEach { x -> val otherPoint = Point.of(x, y) if (otherPoint != p) { yield(otherPoint) } } } } } fun getOrthogonallyAdjacentPoints(p: Point): Sequence<Point> { if (data.isEmpty()) return emptySequence() if (p.x !in (0..maxX) || p.y !in (0..maxY)) return emptySequence() return sequence { ((p.y - 1).coerceAtLeast(0)..(p.y + 1).coerceAtMost(maxY)).forEach { y -> ((p.x - 1).coerceAtLeast(0)..(p.x + 1).coerceAtMost(maxX)).forEach { x -> val otherPoint = Point.of(x, y) if ((y == p.y || x == p.x) && otherPoint != p) { yield(Point.of(x, y)) } } } } } fun getPoints(): Sequence<Point> { if (data.isEmpty()) return emptySequence() if (maxX == 0 && maxY == 0) return sequenceOf(Point.ZERO) return data.indices.asSequence().flatMap { y -> data[0].indices.asSequence().map { x -> Point.of(x, y) } } } override fun toString(): String = data.joinToString(separator = System.lineSeparator()) { it.joinToString(separator = " ")} }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
2,172
advent-of-code
MIT License
src/main/kotlin/cloud/dqn/leetcode/FindModeInBinarySearchTreeKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/find-mode-in-binary-search-tree/description/ Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the node's key. The right subtree of a node contains only nodes with keys greater than or equal to the node's key. Both the left and right subtrees must also be binary search trees. For example: Given BST [1,null,2,2], 1 \ 2 / 2 return [2]. Note: If a tree has more than one mode, you can return them in any order. Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count). * */ class FindModeInBinarySearchTreeKt { class TreeNode(var `val`: Int = 0) { var left: TreeNode? = null var right: TreeNode? = null } class Solution { fun inOrderTraversal(root: TreeNode?, body: (TreeNode) -> Unit) { root?.left?.let { inOrderTraversal(it, body) } root?.let { body(it) } root?.right?.let { inOrderTraversal(it, body) } } fun findMode(root: TreeNode?): IntArray { val valueToCount = HashMap<Int, Int>() // 1,2,2 inOrderTraversal(root, body = { valueToCount[it.`val`] = (valueToCount[it.`val`] ?: 0) + 1 }) if (valueToCount.isEmpty()) { return IntArray(0) } else { val maxes = ArrayList<Int>() var count = 0 valueToCount.forEach { value, countOfValue -> if (countOfValue > count) { count = countOfValue maxes.clear() maxes.add(value) } else if (countOfValue == count) { maxes.add(value) } } return maxes.toIntArray() } } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
2,110
cloud-dqn-leetcode
No Limit Public License
advent-of-code-2022/src/main/kotlin/year_2022/Day13.kt
rudii1410
575,662,325
false
{"Kotlin": 37749}
package year_2022 import kotlinx.serialization.json.* import util.Runner import java.util.LinkedList fun main() { fun String.toJsonArray(): JsonArray = Json.parseToJsonElement(this).jsonArray fun checkSignal(left: LinkedList<JsonElement>, right: LinkedList<JsonElement>): Boolean? { while (left.isNotEmpty() && right.isNotEmpty()) { val l = left.remove() val r = right.remove() if (l is JsonArray) { val res = checkSignal( LinkedList(l.jsonArray), LinkedList(if (r is JsonArray) r.jsonArray else JsonArray(listOf(r))) ) if (res != null) return res } else if (r is JsonArray) { val res = checkSignal(LinkedList(JsonArray(listOf(l))), LinkedList(r.jsonArray)) if (res != null) return res } else { if (l.jsonPrimitive.int == r.jsonPrimitive.int) continue return l.jsonPrimitive.int < r.jsonPrimitive.int } } if (left.size == 0 && right.size > 0) return true if (left.size > 0) return false return null } /* Part 1 */ fun part1(input: String): Int { return input.split("\n\n").mapIndexed { i, p -> p.split("\n").let { if (checkSignal(LinkedList(it[0].toJsonArray()), LinkedList(it[1].toJsonArray())) == true) i + 1 else 0 } }.sum() } Runner.runAll(::part1, 13) /* Part 2 */ fun part2(input: String): Int { return input.replace("\n\n", "\n") .split("\n") .toMutableList() .apply { add("[[2]]") add("[[6]]") } .sortedWith { o1, o2 -> when (checkSignal(LinkedList(o1.toJsonArray()), LinkedList(o2.toJsonArray()))) { true -> -1 false -> 1 else -> 0 } } .let { (it.indexOf("[[2]]") + 1) * (it.indexOf("[[6]]") + 1) } } Runner.runAll(::part2, 140) }
1
Kotlin
0
0
ab63e6cd53746e68713ddfffd65dd25408d5d488
2,173
advent-of-code
Apache License 2.0
src/main/kotlin/test1/SparseVector.kt
samorojy
340,891,499
false
null
package test1 data class SparseVectorElementData<T : ArithmeticAvailable<T>>(val positionNumber: Int, var value: T) data class SparseVector<T : ArithmeticAvailable<T>>( private val spaceSize: Int, private val list: MutableList<SparseVectorElementData<T>> ) { private val mapOfSparseVectorElements = mutableMapOf<Int, T>().also { list.forEach { sparseVectorElement -> it[sparseVectorElement.positionNumber] = sparseVectorElement.value } } private fun Map<Int, T>.toSparseVectorElementList(): MutableList<SparseVectorElementData<T>> = mutableListOf<SparseVectorElementData<T>>().also { this.toList() .forEach { pairFromMap -> if (!pairFromMap.second.isZero()) it.add( SparseVectorElementData( pairFromMap.first, pairFromMap.second ) ) } } private fun check(other: SparseVector<T>) = require(other.spaceSize == spaceSize) { "Cannot operate on vectors of size $spaceSize and ${other.spaceSize}" } operator fun plus(other: SparseVector<T>): SparseVector<T> { check(other) val resultedMapOfElements = mapOfSparseVectorElements.toMutableMap() other.list.forEach { resultedMapOfElements[it.positionNumber] = resultedMapOfElements[it.positionNumber]?.plus(it.value) ?: it.value } return SparseVector(spaceSize, resultedMapOfElements.toSparseVectorElementList()) } operator fun minus(other: SparseVector<T>): SparseVector<T> { check(other) val resultedMapOfElements = mapOfSparseVectorElements.toMutableMap() other.list.forEach { resultedMapOfElements[it.positionNumber] = resultedMapOfElements[it.positionNumber]?.minus(it.value) ?: -it.value } return SparseVector(spaceSize, resultedMapOfElements.toSparseVectorElementList()) } operator fun times(other: SparseVector<T>): T? { check(other) require(list.isNotEmpty()) { "Cannot multiply empty vectors" } var scalarTimesResult: T? = null val positions = list.map { it.positionNumber }.intersect(other.list.map { it.positionNumber }) for (i in positions) { val first = list.find { it.positionNumber == i } val second = other.list.find { it.positionNumber == i } if (first == null || second == null) continue scalarTimesResult = scalarTimesResult?.let { it + first.value * second.value } ?: first.value * second.value } return scalarTimesResult } operator fun get(index: Int): T? = list.find { it.positionNumber == index }?.value operator fun set(index: Int, data: SparseVectorElementData<T>) { list.find { it.positionNumber == data.positionNumber }?.also { it.value = data.value } ?: list.add(index, data) } } interface ArithmeticAvailable<T : ArithmeticAvailable<T>> { operator fun plus(other: T): T operator fun minus(other: T): T operator fun times(other: T): T operator fun unaryMinus(): T fun isZero(): Boolean } data class ArithmeticInt(private val actual: Int) : ArithmeticAvailable<ArithmeticInt> { override fun plus(other: ArithmeticInt) = ArithmeticInt(actual + other.actual) override fun minus(other: ArithmeticInt) = ArithmeticInt(actual - other.actual) override fun times(other: ArithmeticInt) = ArithmeticInt(actual * other.actual) override fun unaryMinus(): ArithmeticInt = ArithmeticInt(-actual) override fun isZero() = actual == 0 }
0
Kotlin
0
0
d77c0af26cb55c74ae463f59244de233133b2320
3,728
spbu_kotlin_course
Apache License 2.0
2021/src/day02/Day02.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day02 import readInput fun part1(input: List<String>) : Int { var depth = 0 var horizontal = 0 input.forEach { it.split(" ").let { val instruction = it.firstOrNull() ?: return@let val nb = it.elementAtOrNull(1)?.toInt() ?: return@let if (instruction == "forward") { horizontal += nb } else if (instruction == "down") { depth += nb } else if (instruction == "up") { depth -= nb } } } return depth * horizontal } fun part2(input: List<String>): Int { var aim = 0 var depth = 0 var horizontal = 0 input.forEach { it.split(" ").let { val instruction = it.firstOrNull() ?: return@let val nb = it.elementAtOrNull(1)?.toInt() ?: return@let if (instruction == "forward") { horizontal += nb depth += aim * nb } else if (instruction == "down") { aim += nb } else if (instruction == "up") { aim -= nb } } } return depth * horizontal } fun main() { val testInput = readInput("day02/test") println(part1(testInput)) println(part2(testInput)) val input = readInput("day02/input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
1,385
advent-of-code
Apache License 2.0
src/main/kotlin/adventofcode2020/solution/Day3.kt
lhess
320,667,380
false
null
package adventofcode2020.solution import adventofcode2020.Solution import adventofcode2020.resource.PuzzleInput class Day3(puzzleInput: PuzzleInput<String>) : Solution<String, Any>(puzzleInput) { override fun runPart1() = puzzleInput .traverse(stepsRight = 3, stepsDown = 1) .apply { check(this == 280) } override fun runPart2() = puzzleInput.run { listOf( traverse(stepsRight = 1, stepsDown = 1), traverse(stepsRight = 3, stepsDown = 1), traverse(stepsRight = 5, stepsDown = 1), traverse(stepsRight = 7, stepsDown = 1), traverse(stepsRight = 1, stepsDown = 2) ) } .fold(1L, { total, next -> total * next }) .apply { check(this == 4355551200L) } companion object { private fun List<String>.traverse(stepsRight: Int, stepsDown: Int): Int { var cnt = 0 var xPos = 0 for (yPos in stepsDown until count() step stepsDown) { xPos += stepsRight if (get(yPos).isTree(xPos)) ++cnt } return cnt } private fun String.isTree(xPos: Int): Boolean = this[xPos % length] == '#' } }
0
null
0
1
cfc3234f79c27d63315994f8e05990b5ddf6e8d4
1,281
adventofcode2020
The Unlicense
src/main/kotlin/problems/S05c06p10ManhattenTouristProblem.kt
jimandreas
377,843,697
false
null
@file:Suppress("SameParameterValue", "UnnecessaryVariable", "UNUSED_VARIABLE", "ReplaceManualRangeWithIndicesCalls") package problems import algorithms.ManhattanTouristProblem /** * stepik: @link: https://stepik.org/lesson/240301/step/10?unit=212647 * rosalind: @link: http://rosalind.info/problems/ba5b/ * Code Challenge: Find the length of a longest path in the Manhattan Tourist Problem. Input: Integers n and m, followed by an n × (m + 1) matrix Down and an (n + 1) × m matrix Right. The two matrices are separated by the "-" symbol. Output: The length of a longest path from source (0, 0) to sink (n, m) in the rectangular grid whose edges are defined by the matrices Down and Right. */ fun main() { val quizDataset = """ 12 6 2 1 2 2 4 0 4 2 2 1 4 0 3 4 3 2 0 1 4 3 3 4 4 3 1 2 1 0 1 1 4 4 3 3 3 3 3 3 1 2 2 2 3 4 3 2 0 2 2 0 2 4 2 4 1 1 2 1 4 3 3 3 0 3 0 2 4 3 0 2 1 0 3 3 4 3 1 3 4 3 3 4 3 1 - 3 1 3 1 3 0 1 1 3 3 0 3 1 0 1 4 2 3 0 0 3 1 4 2 4 4 0 3 0 3 1 4 2 1 1 1 0 0 2 2 1 3 3 0 0 4 3 0 1 2 0 3 2 1 1 4 2 4 1 4 3 2 3 4 2 2 2 3 4 4 0 4 0 4 4 1 0 0 """.trimIndent() val mt = ManhattanTouristProblem() val result = mt.readManhattanMatrices(quizDataset) val count = mt.findLongestPathInManhatten(result!!) println(count) }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
1,278
stepikBioinformaticsCourse
Apache License 2.0
src/Day06.kt
uekemp
575,483,293
false
{"Kotlin": 69253}
fun detect(line: String, markerCount: Int): Int { val chars = line.toCharArray() val bucket = mutableSetOf<Char>() for (index in 0 until chars.size - markerCount) { chars.copyTo(index, index + markerCount, bucket) if (bucket.size == markerCount) { return index + markerCount } bucket.clear() } return -1 } fun CharArray.copyTo(from: Int, to: Int, chars: MutableSet<Char>) { for (index in from until to) { chars.add(this[index]) } } fun main() { fun part1(input: List<String>): Int { return detect(input[0], 4) } fun part2(input: List<String>): Int { return detect(input[0], 14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") println(part1(testInput)) val input = readInput("Day06") check(part1(input) == 1140) check(part2(input) == 3495) }
0
Kotlin
0
0
bc32522d49516f561fb8484c8958107c50819f49
949
advent-of-code-kotlin-2022
Apache License 2.0
src/jvmMain/kotlin/matt/math/jmath/jmath.kt
mgroth0
532,380,281
false
{"Kotlin": 233084}
package matt.math.jmath import matt.lang.require.requireNonNegative import matt.math.angle.Sides import matt.math.exp.sq import org.apache.commons.math3.special.Gamma import java.math.BigDecimal import java.math.BigInteger import kotlin.math.pow import kotlin.math.roundToInt val e = Math.E const val eFloat = Math.E.toFloat() val PI = Math.PI val PIFloat = PI.toFloat() fun Int.simpleFactorial(): BigInteger { requireNonNegative(this) /*println("getting simpleFact of ${this}")*/ if (this == 0) return BigInteger.ONE // if (this == 1) return 1 return (1L..this).fold(BigInteger.ONE) { acc, i -> acc*BigInteger.valueOf(i) } // var r = this*(this - 1) // if ((this - 2) > 1) { // ((this - 2)..2).forEach { i -> // r *= i // } // } // return r } fun sigmoid(x: Double): Double = 1/(1 + e.pow(-x)) fun sigmoidDerivative(x: Double): Double = e.pow(-x).let { it/(1 + it).sq() } fun dirAndHypToAdjAndOpp(dirInDegrees: Double, hyp: Double): Sides { val rads = Math.toRadians(dirInDegrees) val opposite = kotlin.math.sin(rads)*hyp val adj = kotlin.math.cos(rads)*hyp return Sides(adj = adj, opp = opposite) } /*https://stackoverflow.com/questions/31539584/how-can-i-make-my-factorial-method-work-with-decimals-gamma*/ fun Double.generalizedFactorial(): Double { /*Gamma(n) = (n-1)! for integer n*/ return Gamma.gamma(this + 1) } fun Double.generalizedFactorialOrSimpleIfInfOrNaN(): BigDecimal { /*Gamma(n) = (n-1)! for integer n*/ println("getting gamma of ${this + 1}") return Gamma.gamma(this + 1).takeIf { !it.isInfinite() && !it.isNaN() }?.toBigDecimal() ?: roundToInt() .simpleFactorial() .toBigDecimal() } fun Number.sigfig(significantFigures: Int): Double { return BigDecimal(this.toDouble()).toSignificantFigures(significantFigures).toDouble() } fun BigDecimal.toSignificantFigures(significantFigures: Int): BigDecimal { val s = String.format("%." + significantFigures + "G", this) return BigDecimal(s) }
0
Kotlin
0
0
f2a1a04cee2b5eb0e577b033984a3df25a2e3983
1,978
math
MIT License
src/ii_collections/n22Fold.kt
shterrett
156,087,921
true
{"Kotlin": 72655, "Java": 4952}
package ii_collections fun example9() { val result = listOf(1, 2, 3, 4).fold(1, { partResult, element -> element * partResult }) result == 24 } // The same as fun whatFoldDoes(): Int { var result = 1 listOf(1, 2, 3, 4).forEach { element -> result = element * result} return result } fun Shop.getSetOfProductsOrderedByEachCustomer(): Set<Product> { val allOrderedProducts = customers.flatMap(Customer::orders) .flatMap(Order::products) .toSet() return customers.fold(allOrderedProducts, { orderedByAll, customer -> orderedByAll.intersect(customer.orders.flatMap(Order::products).toSet()) }) } fun <T> List<T>.fold1(f: (T, T) -> T): T? { val initial = first() ?: return null return drop(1).fold(initial, f) } fun <T> intersection(s: Set<T>, t: Set<T>): Set<T> = s.intersect(t) val Customer.products: List<Product> get() { return orders.flatMap(Order::products) } fun Shop.getSetOfProductsOrderedByEachCustomer2(): Set<Product> { return customers.map(Customer::products) .map(Collection<Product>::toSet) .fold1(::intersection) ?: setOf() }
0
Kotlin
0
0
31058af629263c067a8ebb35ad84b10d3a226df6
1,201
kotlin-koans
MIT License
src/main/kotlin/aoc2022/Day24.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2022 import AoCDay import aoc2022.Blizzard.* import util.illegalInput private enum class Blizzard { UP, DOWN, LEFT, RIGHT } private typealias Blizzards = List<List<Set<Blizzard>>> // https://adventofcode.com/2022/day/24 object Day24 : AoCDay<Int>( title = "Blizzard Basin", part1ExampleAnswer = 18, part1Answer = 297, part2ExampleAnswer = 54, part2Answer = 856, ) { private fun parseBlizzards(input: String): Triple<Blizzards, Int, Int> { val lines = input.lines() val startX = lines.first().indexOf('.') - 1 val goalX = lines.last().indexOf('.') - 1 val blizzards = List(size = lines.size - 2) { y -> val line = lines[y + 1] List(size = line.length - 2) { x -> when (val char = line[x + 1]) { '.' -> emptySet() '^' -> setOf(UP) 'v' -> setOf(DOWN) '<' -> setOf(LEFT) '>' -> setOf(RIGHT) else -> illegalInput(char) } } } require(blizzards.none { row -> UP in row[startX] || DOWN in row[startX] || UP in row[goalX] || DOWN in row[goalX] }) { "Blizzard could run out of map" } return Triple(blizzards, startX, goalX) } private fun Blizzards.move(): Blizzards { val moved = List(size) { y -> List(this[y].size) { mutableSetOf<Blizzard>() } } for ((y, row) in this.withIndex()) { for ((x, blizzards) in row.withIndex()) { for (blizzard in blizzards) { when (blizzard) { UP -> moved[(y - 1).mod(size)][x] DOWN -> moved[(y + 1) % size][x] LEFT -> moved[y][(x - 1).mod(row.size)] RIGHT -> moved[y][(x + 1) % row.size] } += blizzard } } } return moved } private fun steps( blizzards: Blizzards, startX: Int, startY: Int, goalX: Int, goalY: Int, ): Pair<Int, Blizzards> { var curPos = List(blizzards.size) { y -> BooleanArray(blizzards[y].size) } var cur = blizzards for (minute in 1..<Int.MAX_VALUE) { cur = cur.move() // we would do the always possible move to out-of-bounds goal in this minute if (curPos[goalY][goalX]) return Pair(minute, cur) val nextPos = List(curPos.size) { y -> BooleanArray(curPos[y].size) } for ((y, row) in curPos.withIndex()) { for ((x, weCouldBeThere) in row.withIndex()) { if (weCouldBeThere) { if (cur[y][x].isEmpty()) nextPos[y][x] = true if (y > 0 && cur[y - 1][x].isEmpty()) nextPos[y - 1][x] = true if (y < curPos.lastIndex && cur[y + 1][x].isEmpty()) nextPos[y + 1][x] = true if (x > 0 && cur[y][x - 1].isEmpty()) nextPos[y][x - 1] = true if (x < row.lastIndex && cur[y][x + 1].isEmpty()) nextPos[y][x + 1] = true } } } // we could wait forever at the out-of-bounds start, so we could be here after every minute if (cur[startY][startX].isEmpty()) nextPos[startY][startX] = true curPos = nextPos } error("Minute ran out of Int range") } override fun part1(input: String): Int { val (blizzards, startX, goalX) = parseBlizzards(input) return steps(blizzards, startX, startY = 0, goalX, goalY = blizzards.lastIndex).first } override fun part2(input: String): Int { val (b0, startX, goalX) = parseBlizzards(input) val startY = 0 val goalY = b0.lastIndex val (a, b1) = steps(b0, startX, startY, goalX, goalY) val (b, b2) = steps(b1, goalX, goalY, startX, startY) val (c, _) = steps(b2, startX, startY, goalX, goalY) return a + b + c } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
4,080
advent-of-code-kotlin
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day16.kt
clechasseur
568,233,589
false
{"Kotlin": 242914}
package io.github.clechasseur.adventofcode.y2015 import io.github.clechasseur.adventofcode.y2015.data.Day16Data object Day16 { private val target = Day16Data.target private val input = Day16Data.input private val targetRegex = """^(\w+): (\d+)$""".toRegex() private val inputRegex = """^Sue (\d+): ((?:(?:, )?\w+: \d+)+)$""".toRegex() fun part1(): Int { val ourTarget = target.toTarget() return input.toAunts().filter { (_, spec) -> spec.matches1(ourTarget) }.asSequence().single().key } fun part2(): Int { val ourTarget = target.toTarget() return input.toAunts().filter { (_, spec) -> spec.matches2(ourTarget) }.asSequence().single().key } private fun Map<String, Int>.matches1(target: Map<String, Int>): Boolean = all { (name, num) -> target[name]!! == num } private fun Map<String, Int>.matches2(target: Map<String, Int>): Boolean = all { (name, num) -> matches2(name, num, target[name]!!) } private fun matches2(name: String, num: Int, target: Int): Boolean = when (name) { "cats", "trees" -> num > target "pomeranians", "goldfish" -> num < target else -> num == target } private fun String.toTarget(): Map<String, Int> = lines().associate { val match = targetRegex.matchEntire(it) ?: error("Wrong target line: $it") val (name, num) = match.destructured name to num.toInt() } private fun String.toAunts(): Map<Int, Map<String, Int>> = lines().associate { line -> val match = inputRegex.matchEntire(line) ?: error("Wrong aunt spec: $line") val (auntNum, properties) = match.destructured auntNum.toInt() to properties.split(", ").associate { prop -> val propMatch = targetRegex.matchEntire(prop) ?: error("Wrong aut prop spec: $prop") val (propName, num) = propMatch.destructured propName to num.toInt() } } }
0
Kotlin
0
0
e5a83093156cd7cd4afa41c93967a5181fd6ab80
1,958
adventofcode2015
MIT License
src/day02/Game.kt
abhabongse
576,594,038
false
{"Kotlin": 63915}
package day02 /** * Possible actions for the game of Rock Paper Scissors. */ enum class Action(val value: Int) { ROCK(0), PAPER(1), SCISSORS(2); companion object { /** * Reverse lookup for action enum object based of [value]. */ infix fun from(value: Int): Action = Action.values() .firstOrNull { it.value == value } ?: throw IllegalArgumentException("unknown action: $value") } /** * Determines the outcome based on the action of two players. */ infix fun playAgainst(opponent: Action): Outcome = Outcome from Math.floorMod(this.value - opponent.value, 3) } /** * Possible outcomes for the game of Rock Paper Scissors. * The [value] is assigned so that the following identity holds: * outcome ≡ response - opponent (mod 3) */ enum class Outcome(val value: Int) { WIN(1), DRAW(0), LOSE(2); companion object { /** * Reverse lookup for outcome enum object based of [value]. */ infix fun from(value: Int): Outcome = Outcome.values() .firstOrNull { it.value == value } ?: throw IllegalArgumentException("unknown value for outcome: $value") } } /** * Determines the proper response to the [opponent]'s action * in order to obtain the [desiredOutcome]. */ fun getProperResponse(opponent: Action, desiredOutcome: Outcome): Action = Action from Math.floorMod(desiredOutcome.value + opponent.value, 3) /** * Computes the score for a single round of Rock Paper Scissors * based on actions of the [opponent] and your own [response]. */ fun computeRoundScore(opponent: Action, response: Action): Int { val outcome = response playAgainst opponent val outcomeScore = when (outcome) { Outcome.WIN -> 6 Outcome.DRAW -> 3 Outcome.LOSE -> 0 } val responseScore = when (response) { Action.ROCK -> 1 Action.PAPER -> 2 Action.SCISSORS -> 3 } return outcomeScore + responseScore }
0
Kotlin
0
0
8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb
2,066
aoc2022-kotlin
Apache License 2.0
src/main/kotlin/icu/trub/aoc/day13/MirrorValley.kt
dtruebin
728,432,747
false
{"Kotlin": 76202}
package icu.trub.aoc.day13 import icu.trub.aoc.util.Point import icu.trub.aoc.util.collections.rotate import icu.trub.aoc.util.columnToString import icu.trub.aoc.util.rowToString internal class MirrorValley(val patterns: List<Pattern>) { companion object { fun parse(input: List<String>): MirrorValley = MirrorValley(buildList { val patternLines = mutableListOf<String>() for ((index, line) in input.withIndex()) { if (line.isNotBlank() && index < input.lastIndex) { patternLines.add(line) } else { if (index == input.lastIndex) { patternLines.add(line) } add(Pattern.parse(patternLines)) patternLines.clear() } } }) } } class Pattern(val matrix: Map<Point, Char>) { val lastColIndex: Int = matrix.maxOf { it.key.x } val lastRowIndex: Int = matrix.maxOf { it.key.y } val reflection: MirrorReflection = sequence { yield(matrix.lookForHorizontalReflection()) yield(matrix.lookForVerticalReflection()) }.firstNotNullOf { it } val altReflection: MirrorReflection get() = sequence { (0..lastColIndex).map { x -> (0..lastRowIndex).map { y -> val mm = matrix .toMutableMap() .also { it[Point(x, y)] = if (it[Point(x, y)] == '.') '#' else '.' } .toMap() yield(mm.lookForHorizontalReflection(excludeIndex = if (reflection is UpDownReflection) reflection.coordinate - 1 else null)) yield(mm.lookForVerticalReflection(excludeIndex = if (reflection is LeftRightReflection) reflection.coordinate - 1 else null)) } } }.filter { it != reflection }.firstNotNullOf { it } fun getHorizontalLine(y: Int): String = matrix.rowToString(y) fun getVerticalLine(x: Int): String = matrix.columnToString(x) private fun Map<Point, Char>.lookForVerticalReflection(excludeIndex: Int? = null): MirrorReflection? = rotate().lookForHorizontalReflection(excludeIndex)?.let { LeftRightReflection(it.coordinate) } private fun Map<Point, Char>.lookForHorizontalReflection(excludeIndex: Int? = null): MirrorReflection? { val lastRowIndex: Int = maxOf { it.key.y } val pairStartingRowIndices = (0..lastRowIndex).asSequence() .map { rowToString(it) } .zipWithNext() .withIndex() .filter { it.value.first == it.value.second } .map { it.index } .toList() .also { if (it.isEmpty()) return null } val symmetryIndices = pairStartingRowIndices.map { var up = it var down = it + 1 while (rowToString(up) == rowToString(down)) { up-- down++ } it to (up to down) }.filter { it.second.first < 0 || it.second.second > lastRowIndex } .map { it.first } val winningIndex = symmetryIndices.ifEmpty { return null }.lastOrNull { it != excludeIndex } ?: return null return UpDownReflection(winningIndex + 1) } fun getSummary(isClean: Boolean = false): Int = with(if (isClean) altReflection else reflection) { return when (this) { is LeftRightReflection -> coordinate is UpDownReflection -> coordinate * 100 else -> throw IllegalArgumentException() } } override fun toString(): String { return "Pattern(${lastColIndex + 1} by ${lastRowIndex + 1}, 1st line = ${getHorizontalLine(0)})" } companion object { fun parse(input: List<String>): Pattern = Pattern(buildMap { input.forEachIndexed { row, line -> line.forEachIndexed { col, char -> put(Point(col, row), char) } } }) } interface MirrorReflection { /** Row or column number (index+1) after which reflection starts. */ val coordinate: Int } data class LeftRightReflection(override val coordinate: Int) : MirrorReflection data class UpDownReflection(override val coordinate: Int) : MirrorReflection }
0
Kotlin
0
0
1753629bb13573145a9781f984a97e9bafc34b6d
4,317
advent-of-code
MIT License
src/day24/first/Solution.kt
verwoerd
224,986,977
false
null
package day24.first import day24.first.ErisTile.BUG import day24.first.ErisTile.EMPTY import tools.Coordinate import tools.adjacentCoordinates import tools.timeSolution import java.math.BigInteger fun main() = timeSolution { var maze = System.`in`.bufferedReader().readLines() .mapIndexed { y, line -> line.toCharArray().mapIndexed { x, char -> Coordinate(x, y) to char.toTile() } }.flatten() .toMap().withDefault { EMPTY } val seen = mutableSetOf<Map<Coordinate, ErisTile>>() while (seen.add(maze)) { maze = maze.keys.fold(mutableMapOf<Coordinate, ErisTile>()) { acc, coordinate -> val adjacentBugs = adjacentCoordinates(coordinate).map { maze.getValue(it) }.count { it == BUG } acc.also { acc[coordinate] = when (maze.getValue(coordinate)) { BUG -> when (adjacentBugs) { 1 -> BUG else -> EMPTY } EMPTY -> when (adjacentBugs) { 1, 2 -> BUG else -> EMPTY } } } }.withDefault { EMPTY } println( maze.keys.filter { maze.getValue(it) == BUG }.map { 2.toBigInteger().pow(it.x + 5 * it.y) }.reduce( BigInteger::add ) ) } } enum class ErisTile(val char: Char) { BUG('#'), EMPTY('.') } fun Char.toTile() = when (this) { BUG.char -> BUG EMPTY.char -> EMPTY else -> error("Invalid tile encountered") }
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
1,487
AoC2019
MIT License
Actividades/EjerciciosKotlin/src/main/kotlin/Operaciones.kt
alanmalagonb
606,216,253
false
null
fun main() { var option: Int do{ println("- Ejercicios Kotlin -\n" + "1. Par o no\n" + "2. Tabla de multiplicar\n" + "3. Producto mediante sumas\n" + "4. Posicion del mayor valor\n" + "5. Suma de vectores\n" + "6. Media\n" + "7. Ordenar numeros\n" + "8. Longitud, mayusculas y minusculas\n" + "9. Salir\n" + "Elija una opcion:") option = readln().toInt() when(option){ 1 -> esPar() 2 -> tablaDeMultiplicar() 3 -> productoMedianteSumas() 4 -> posicionMayorValor() 5 -> sumaVectores() 6 -> media() 7 -> ordenarNumeros() 8 -> LongMayusMinus() 9 -> continue else -> { print("No existe esa opcion\n") } } println("Presione una tecla para continuar...\n") readln(); } while(option != 9) } // Leer un numero y mostrar si dicho numero es par o no es par fun esPar() { val number = leerNumero() if(number % 2 == 0) println("$number es par.") else println("$number no es par.") } // Leer un numero y mostrar su tabla de multiplicar fun tablaDeMultiplicar() { val number = leerNumero() for(i in 1..10){ println("$number x $i = ${number*i}") } } // Leer dos numeros y realizar el producto mediante sumas fun productoMedianteSumas() { val number = leerNumero() val number2 = leerNumero() var producto = 0 for(i in 1..number2){ producto += number; } println("Producto: $producto") } /* Leer una secuencia de n numeros almacenarlos en un arreglo y mostrar la posicion donde se encuentre el mayor valor leido */ fun posicionMayorValor(){ var numbers = arrayOf<Int>() var mayor = 0 println("Ingrese numeros. (Vacio para detener)") while (true) { val siguiente = readlnOrNull().takeUnless { it.isNullOrEmpty() } ?: break if(numbers.contains(siguiente.toInt())){ println("Ya ingresaste este numero") continue } if(siguiente.toInt() >= mayor) mayor = siguiente.toInt() numbers += siguiente.toInt() } println("Mayor : $mayor , Posicion : ${numbers.indexOf(mayor)}") } /* Dado dos vectores A y B de n elementos cada uno, obtener un arreglo C donde la posicion i se almacena la suma de A[i]+B[i] */ fun sumaVectores(){ println("Ingrese el tamaño de los vectores:") val size = leerNumero(); println("Vector A\n") val vectorA = leerArreglo(size) print("Vector B\n") val vectorB = leerArreglo(size) val vectorC = DoubleArray(size) for (i in 0 until size){ vectorC[i] = vectorA[i]+vectorB[i] } println("Vector C: ${vectorC.contentToString()}"); } // Calcular la media de una secuencia de numeros proporcionados por el usuario fun media(){ val numeros = leerArreglo() val media = numeros.sum() / numeros.size println("Media : $media") } /* Dada una secuencia de numeros leidos y almacenados en un arreglo A mostrar dichos números en orden */ fun ordenarNumeros(){ val numeros = leerNumeros() numeros.sort() println("Numeros Ordenados: ${numeros.contentToString()}") } /* Dado una secuencia de textos proporcionados por el usuario visualizar la longitud, en mayusculas, en minusculas, cada uno de ellas. */ fun LongMayusMinus(){ val textos = leerCadenas(); textos.forEach { println("Longitud: ${it.length}, Mayusculas: ${it.uppercase()}, Minusculas: ${it.lowercase()}") } }
0
Kotlin
0
0
9db7265c6ea553648e092da019ce812f51980ec6
3,699
DesarrolloDeAplicacionesMovilesNativas
MIT License
year2015/src/main/kotlin/net/olegg/aoc/year2015/day22/Day22.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2015.day22 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2015.DayOf2015 import kotlin.math.max import kotlin.math.min /** * See [Year 2015, Day 22](https://adventofcode.com/2015/day/22) */ object Day22 : DayOf2015(22) { private const val HP = 50 private const val MANA = 500 private const val ARMOR = 0 data class Stats( val hp: Int, val armor: Int, val power: Int ) private val ME = Stats( hp = HP, armor = ARMOR, power = MANA, ) private val BOSS = lines .map { it.substringAfterLast(": ").toInt() } .let { (hp, hits) -> Stats(hp, 0, hits) } data class Spell( val cost: Int, val duration: Int, val action: (Pair<Stats, Stats>) -> Pair<Stats, Stats> ) private val MAGIC_MISSILE = Spell(53, 1) { (me, boss) -> me to boss.copy(hp = boss.hp - 4) } private val DRAIN = Spell(73, 1) { (me, boss) -> me.copy(hp = me.hp + 2) to boss.copy(hp = boss.hp - 2) } private val SHIELD = Spell(113, 6) { (me, boss) -> me.copy(armor = 7) to boss } private val POISON = Spell(173, 6) { (me, boss) -> me to boss.copy(hp = boss.hp - 3) } private val RECHARGE = Spell(229, 5) { (me, boss) -> me.copy(power = me.power + 101) to boss } private val BOSS_HIT = Spell(0, 1) { (me, boss) -> me.copy(hp = me.hp - max(boss.power - me.armor, 1)) to boss } private val HARD_BOSS_HIT = Spell(0, 1) { (me, boss) -> me.copy(hp = me.hp - max(boss.power - me.armor, 1) - 1) to boss } private val SPELLS = listOf(MAGIC_MISSILE, DRAIN, SHIELD, POISON, RECHARGE) data class Game( val me: Stats, val boss: Stats, val spells: Map<Spell, Int> = mapOf(), val mana: Int = 0, val myMove: Boolean = true ) private fun countMana( mySpells: List<Spell>, bossSpells: List<Spell> ): Int { val queue = ArrayDeque(listOf(Game(ME, BOSS))) var best = Int.MAX_VALUE while (queue.isNotEmpty()) { val game = queue.removeFirst() val states = game.spells.keys .fold(game.me to game.boss) { acc, spell -> spell.action(acc) } .let { state -> if (game.spells[SHIELD] != 1) { state } else { state.copy(first = state.first.copy(armor = 0)) } } if (states.first.hp <= 0) { continue } if (states.second.hp <= 0) { best = min(best, game.mana) continue } val activeSpells = game.spells .mapValues { it.value - 1 } .filterValues { it > 0 } val spells = if (game.myMove) { mySpells .filter { it.cost <= states.first.power } .filterNot { it in activeSpells } .filter { game.mana + it.cost < best } } else { bossSpells } queue += spells.map { spell -> game.copy( me = states.first.copy(power = states.first.power - spell.cost), boss = states.second, spells = activeSpells + (spell to spell.duration), mana = game.mana + spell.cost, myMove = !game.myMove, ) } } return best } override fun first(): Any? { return countMana(SPELLS, listOf(BOSS_HIT)) } override fun second(): Any? { return countMana(SPELLS, listOf(HARD_BOSS_HIT)) } } fun main() = SomeDay.mainify(Day22)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
3,355
adventofcode
MIT License
src/main/kotlin/com/leetcode/top_interview_questions/easy/merge/Main.kt
frikit
254,842,734
false
null
package com.leetcode.top_interview_questions.easy.merge fun main() { println("Test case 1:") val arr1 = intArrayOf(1, 2, 3, 0, 0, 0) val arr2 = intArrayOf(2, 5, 6) println(Solution().merge(arr1, 3, arr2, 3)) // [1,2,2,3,5,6] println(arr1.toList()) println() println("Test case 2:") val arr3 = intArrayOf(1) val arr4 = intArrayOf() println(Solution().merge(arr3, 1, arr4, 0)) // [1] println(arr3.toList()) println() println("Test case 3:") val arr5 = intArrayOf(0) val arr6 = intArrayOf(1) println(Solution().merge(arr5, 0, arr6, 1)) // [1] println(arr5.toList()) println() println("Test case 4:") val arr7 = intArrayOf(2, 0) val arr8 = intArrayOf(1) println(Solution().merge(arr7, 1, arr8, 1)) // [1, 2] println(arr7.toList()) println() println("Test case 5:") val arr9 = intArrayOf(4, 0, 0, 0, 0, 0) val arr10 = intArrayOf(1, 2, 3, 5, 6) println(Solution().merge(arr9, 1, arr10, 5)) // [1,2,3,4,5,6] println(arr9.toList()) println() } class Solution { fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int) { var p1 = m - 1 var p2 = n - 1 var i = m + n - 1 while (p2 >= 0) { if (p1 >= 0 && nums1[p1] > nums2[p2]) { nums1[i--] = nums1[p1--] } else { nums1[i--] = nums2[p2--] } } } }
0
Kotlin
0
0
dda68313ba468163386239ab07f4d993f80783c7
1,432
leet-code-problems
Apache License 2.0
2023/src/main/kotlin/com/github/akowal/aoc/Day01.kt
akowal
573,170,341
false
{"Kotlin": 36572}
package com.github.akowal.aoc import java.io.File class Day01(input: File) : Problem<Int> { private val lines = input.readLines() override fun solve1(): Int { return lines.sumOf { s -> s.first(Char::isDigit).digitToInt() * 10 + s.last(Char::isDigit).digitToInt() } } override fun solve2(): Int { val words = "three|seven|eight|four|five|nine|six|one|two" val r = "\\d|$words".toRegex() val rr = "\\d|${words.reversed()}".toRegex() return lines.sumOf { s -> val firstDigit = r.find(s)!!.value.asDigit() val lastDigit = rr.find(s.reversed())!!.value.reversed().asDigit() firstDigit * 10 + lastDigit } } private fun String.asDigit() = when (this) { "one" -> 1 "two" -> 2 "three" -> 3 "four" -> 4 "five" -> 5 "six" -> 6 "seven" -> 7 "eight" -> 8 "nine" -> 9 else -> this.single().digitToInt() } } fun main() { Launcher("day01", ::Day01).run() }
0
Kotlin
0
0
02e52625c1c8bd00f8251eb9427828fb5c439fb5
1,063
advent-of-kode
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day15.kt
Walop
573,012,840
false
{"Kotlin": 53630}
import java.io.InputStream import kotlin.math.absoluteValue data class Sensor(val pos: Vec2, val range: Int) class Day15 { companion object { private fun readSensors(input: InputStream?): Pair<List<Sensor>, Set<Vec2>> { if (input == null) { throw Exception("Input missing") } val numRegex = "[\\d\\-]+".toRegex() val coords = input.bufferedReader().useLines { lines -> lines.flatMap { numRegex.findAll(it).map { res -> res.value.toInt() } }.toList() } val filled = coords.chunked(2).map { Vec2(it[0], it[1]) }.toSet() val sensors = coords.chunked(4) .map { Sensor(Vec2(it[0], it[1]), (it[0] - it[2]).absoluteValue + (it[1] - it[3]).absoluteValue) } return Pair(sensors, filled) } fun process(input: InputStream?, rowNum: Int): Long { val (sensors, filled) = readSensors(input) //sensors.forEach { println(it) } //filled.forEach { println(it) } val leftSensor = sensors.minBy { it.pos.x - it.range } val rightSensor = sensors.maxBy { it.pos.x + it.range } val minX = leftSensor.pos.x - leftSensor.range val maxX = rightSensor.pos.x + rightSensor.range println("$minX-$maxX: ${(minX - maxX).absoluteValue}") // val map = mutableListOf<Char>() val sum = (minX..maxX) .toList() .parallelStream() .map { x -> val inRange = sensors.any { sensor -> (sensor.pos.x - x).absoluteValue + (sensor.pos.y - rowNum).absoluteValue <= sensor.range } if (!inRange) { // map.add('.') 0 } else { if (filled.contains(Vec2(x, rowNum))) { // map.add('.') 0 } else { // map.add('#') 1 } } }.filter { it != 0 }.count() // map.add('.') //println(map.joinToString("").trim('.').count { it == '.' }) //File("C:\\Temp\\map_15.txt").writeText(map.joinToString("")) return sum } fun process2(input: InputStream?): Long { val (sensors, filled) = readSensors(input) var maxX = sensors.maxOf { it.pos.x } var current = Vec2(0, 0) var covering: Sensor? = null while (true) { covering = sensors.firstOrNull { sensor -> sensor != covering && (sensor.pos.x - current.x).absoluteValue + (sensor.pos.y - current.y).absoluteValue <= sensor.range } if (covering == null) { break } val newPos = ((covering.pos.x + covering.range) - (covering.pos.y - current.y).absoluteValue) + 1 if (newPos < maxX) { current.x = newPos } else { current.x = 0 current.y++ } } // println(current) return 4_000_000L * current.x.toLong() + current.y.toLong() } } }
0
Kotlin
0
0
7a13f6500da8cb2240972fbea780c0d8e0fde910
3,506
AdventOfCode2022
The Unlicense
LongestPalindrome.kt
linisme
111,369,586
false
null
class LongestPalindromeSolution { fun longestPalindrome(s: String): String { var chars = s.toCharArray() val sourceLength = s.length var maxLength = 0 var maxLeft = 0 var maxRight = 0 for (l in 0 until sourceLength) { if (maxLength > sourceLength - l) { break } test@ for (r in sourceLength - 1 downTo l) { val targetLength = r - l + 1 for (i in 0 until targetLength / 2) { if (chars[l + i] != chars[r - i]) { continue@test } } if (maxLength < targetLength) { maxLength = targetLength maxLeft = l maxRight = r break } } } return s.substring(maxLeft, maxRight + 1) } fun isPalindrome(chars: CharArray, l : Int, r: Int): Boolean { val length = r - l + 1 for (i in 0 until length / 2) { if (chars[l + i] != chars[r - i]) { return false } } return true } } fun main(args: Array<String>) { println(LongestPalindromeSolution().longestPalindrome("abbccbbdl")) }
0
Kotlin
1
0
4382afcc782da539ed0d535c0a5b3a257e0c8097
1,151
LeetCodeInKotlin
MIT License
src/main/kotlin/g2901_3000/s2982_find_longest_special_substring_that_occurs_thrice_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2982_find_longest_special_substring_that_occurs_thrice_ii // #Medium #String #Hash_Table #Binary_Search #Counting #Sliding_Window // #2024_01_19_Time_343_ms_(100.00%)_Space_48.4_MB_(100.00%) import kotlin.math.max class Solution { fun maximumLength(s: String): Int { val arr = Array(26) { IntArray(4) } var prev = s[0] var count = 1 var max = 0 for (index in 1 until s.length) { if (s[index] != prev) { val ints = arr[prev.code - 'a'.code] updateArr(count, ints) prev = s[index] count = 1 } else { count++ } } updateArr(count, arr[prev.code - 'a'.code]) for (values in arr) { if (values[0] != 0) { max = if (values[1] >= 3) { max(max, values[0]) } else if (values[1] == 2 || values[2] == values[0] - 1) { max(max, (values[0] - 1)) } else { max(max, (values[0] - 2)) } } } return if (max == 0) -1 else max } private fun updateArr(count: Int, ints: IntArray) { if (ints[0] == count) { ints[1]++ } else if (ints[0] < count) { ints[3] = ints[1] ints[2] = ints[0] ints[0] = count ints[1] = 1 } else if (ints[2] < count) { ints[2] = count ints[3] = 1 } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,551
LeetCode-in-Kotlin
MIT License
src/main/kotlin/pl/msulima/pkpchecker/Summarize.kt
msulima
96,702,742
false
null
package pl.msulima.pkpchecker import java.io.File fun printSummary(databaseDirectory: File): Unit { val completed = readAllCompleted(databaseDirectory) .mapNotNull { readStatisticsForTrain(it) } completed .sortedBy { -it.stops.last().arrivalDelay } .take(30) .forEach { printTrainStatistics(it) } println("---") val onTrack = findOnTrack(completed, "Katowice", "Warszawa Centralna") .sortedBy { -it.stops.last().arrivalDelay } println("Average: ${onTrack.sumBy { it.stops.last().arrivalDelay }.toDouble() / onTrack.size}") println("75th p: ${onTrack[(onTrack.size * 0.25).toInt()].stops.last().arrivalDelay}") println("90th p: ${onTrack[(onTrack.size * 0.10).toInt()].stops.last().arrivalDelay}") } fun findOnTrack(completed: List<TrainStatistics>, firstStation: String, secondStation: String): List<TrainStatistics> { val trainsByStation = hashMapOf<String, MutableSet<TrainStatistics>>() completed.forEach { train -> train.stops.forEach { (station) -> val trains = trainsByStation.computeIfAbsent(station, { hashSetOf() }) trains.add(train) } } val startTrains = trainsByStation.getOrDefault(firstStation, hashSetOf()) val targetTrains = trainsByStation.getOrDefault(secondStation, hashSetOf()) val commonTrains = startTrains.intersect(targetTrains) return commonTrains.map { train -> val firstIndex = train.stops.indexOfFirst { it.station == firstStation } val secondIndex = train.stops.indexOfFirst { it.station == secondStation } val stopsBetweenStations = if (secondIndex > firstIndex) { train.stops.subList(firstIndex, secondIndex + 1) } else { train.stops.subList(secondIndex, firstIndex + 1) } train.copy(stops = stopsBetweenStations) } }
0
Kotlin
0
0
1ae892bde66be9c226bf80506c92f7e25d4ba7bb
1,894
pkp-checker
Apache License 2.0
src/main/java/io/github/lunarwatcher/aoc/day7/Day7.kt
LunarWatcher
160,042,659
false
null
package io.github.lunarwatcher.aoc.day7 import io.github.lunarwatcher.aoc.commons.readFile import kotlin.math.absoluteValue fun day7part1processor(raw: List<String>) : String{ val letters = raw.map { val split = it.split(" ").filter { it.length == 1 } split[0][0] to split[1][0] } // Char, dependent chars val map = mutableMapOf<Char, MutableList<Char>>() letters.forEach { (char, child) -> if(map[char] == null) map[char] = mutableListOf(child) else map[char]!!.add(child) } val resultBuilder = StringBuilder() while(true) { val freeChars = mutableMapOf<Char, Boolean>() freeChars.putAll(map.map { it.key to true }.toMap()) for ((char, dependents) in map) { for ((freeChar, _) in freeChars.filter { it.value }) { if (freeChar in dependents) { freeChars[freeChar] = false; } } } val char = freeChars.filter { it.value == true }.keys.sorted().first() map[char]!!.let { for(c in it){ if(map[c] == null) map[c] = mutableListOf() } } map.remove(char) resultBuilder.append(char) if(map.isEmpty()) break; } return resultBuilder.toString() } fun day7part2processor(raw: List<String>) : Int { val letters = raw.map { val split = it.split(" ").filter { it.length == 1 } split[0][0] to split[1][0] } // Char, dependent chars val map = mutableMapOf<Char, MutableList<Char>>() letters.forEach { (char, child) -> if(map[char] == null) map[char] = mutableListOf(child) else map[char]!!.add(child) } var workers = 0 var time = -1 val workMapping = mutableMapOf<Char, Int>() while(map.size > 0){ with (workMapping.filter { it.value == time }.keys.sorted()){ forEach { workMapping.remove(it) } workers -= size; for(char in this) { map[char]!!.let { for(c in it){ if(map[c] == null) { map[c] = mutableListOf() } } } map.remove(char) } } val freeChars = mutableMapOf<Char, Boolean>() freeChars.putAll(map.map { it.key to true }.toMap()) for ((char, dependents) in map) { for ((freeChar, _) in freeChars.filter { it.value }) { if (freeChar in dependents || freeChar in workMapping) { freeChars[freeChar] = false; } } } with(freeChars.filter { it.value == true }.keys.toList().sorted()){ take(5 - workers).also { workers += it.size } .forEach {char -> workMapping[char] = time + (char - 'A' + 61) // char - char = int. } } time++; } return time } fun day7(part: Boolean){ val inp = readFile("day7.txt"); @Suppress("IMPLICIT_CAST_TO_ANY") val res = if(!part) day7part1processor(inp) else day7part2processor(inp) println(res); }
0
Kotlin
0
1
99f9b05521b270366c2f5ace2e28aa4d263594e4
3,264
AoC-2018
MIT License
src/Day06.kt
robotfooder
573,164,789
false
{"Kotlin": 25811}
fun main() { fun String.allUnique(): Boolean = all(hashSetOf<Char>()::add) fun part1(input: List<String>): Int { val signalStartLength = 4 return input .map { it.windowed(signalStartLength) } .flatten() .indexOfFirst { it.allUnique() } + signalStartLength } fun part2(input: List<String>): Int { val messageStartLength = 14 return input .map { it.windowed(messageStartLength) } .flatten() .indexOfFirst { it.allUnique() } + messageStartLength } fun runTest(expected: Int, day: String, testFunction: (List<String>) -> Int) { val actual = testFunction(readTestInput(day)) check(expected == actual) { "Failing for day $day, ${testFunction}. " + "Expected $expected but got $actual" } } val day = "06" // test if implementation meets criteria from the description, like: runTest(11, day, ::part1) runTest(26, day, ::part2) val input = readInput(day) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9876a52ef9288353d64685f294a899a58b2de9b5
1,134
aoc2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem981/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem981 /** * LeetCode page: [981. Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/); */ class TimeMap() { private val timeValuesPerKey = hashMapOf<String, MutableList<TimeValue>>() private data class TimeValue(val timestamp: Int, val value: String) /* Complexity: * Time O(K+V) and Space O(K+V) where K and V are the length of key and value; */ fun set(key: String, value: String, timestamp: Int) { val newTimeValue = TimeValue(timestamp, value) val timeValues = timeValuesPerKey.getOrPut(key) { mutableListOf() } // This is the constraint from problem, without which we might go for a TreeMap solution; val isTimestampStrictlyIncreasing = timeValues.isEmpty() || timestamp > timeValues.last().timestamp require(isTimestampStrictlyIncreasing) timeValues.add(newTimeValue) } /* Complexity: * Time O(K+LogN) and Space O(1) where K is the length of key and N is the number of timeValues with key; */ fun get(key: String, timestamp: Int): String { val timeValuesSortedByTime = timeValuesPerKey[key] ?: return "" if (timeValuesSortedByTime.isEmpty()) return "" val insertionIndex = timeValuesSortedByTime .binarySearch { timeValue -> timeValue.timestamp - timestamp } .let { bsIndex -> if (bsIndex < 0) -(bsIndex + 1) else bsIndex } val isFutureTimestamp = insertionIndex == timeValuesSortedByTime.size if (isFutureTimestamp) return timeValuesSortedByTime.last().value val hasMatchedTimestamp = timeValuesSortedByTime[insertionIndex].timestamp == timestamp if (hasMatchedTimestamp) return timeValuesSortedByTime[insertionIndex].value val noEarlierTimestamp = insertionIndex == 0 if (noEarlierTimestamp) return "" return timeValuesSortedByTime[insertionIndex - 1].value } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,969
hj-leetcode-kotlin
Apache License 2.0
Kotlin/BogoSort.kt
argonautica
212,698,136
false
{"Java": 42011, "C++": 24846, "C#": 15801, "Python": 14547, "Kotlin": 11794, "C": 10528, "JavaScript": 9054, "Assembly": 5049, "Go": 3662, "Ruby": 1949, "Lua": 687, "Elixir": 589, "Rust": 447}
import kotlin.random.Random fun main(args : Array<String>) { //Create Array var array = intArrayOf(4,5,3,9,1) array = sort(array) array.forEach { println(it) } } /** * Use Bogo sort to randomly swap two inputs and then check if the list is sorted */ fun sort(input:IntArray):IntArray{ //keep repeating check until sorted while (!isSorted(input)){ //get two randomly picked array locations val index1 = Random.nextInt(0, input.size-1) val index2 = Random.nextInt(0, input.size-1) //swap the values val temp = input[index1] input[index1] = input[index2] input[index2] = temp } return input } /** * Check if the array is sorted from lowest to highest */ fun isSorted(input:IntArray): Boolean{ var max:Int? = null for(x in input.indices){ if(max == null || input[x] >= max){ max = input[x] }else{ return false } } return true }
4
Java
138
45
b9ebd2aadc6b59e5feba7d1fe9e0c6a036d33dba
1,001
sorting-algorithms
MIT License
src/Day01.kt
NatoNathan
572,672,396
false
{"Kotlin": 6460}
fun main() { fun getElivs(input: List<String>): List<Int> { val elivs = mutableListOf<Int>() var current = 0 input.forEach { when (it) { "" -> { elivs.add(current) current = 0 } else -> current += it.toInt() } } elivs.add(current) return elivs } fun part1(input: List<String>): Int { return getElivs(input).max() } fun part2(input: List<String>): Int { return getElivs(input).sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c0c9e2a2d0ca2503afe33684a3fbba1f9eefb2b0
897
advent-of-code-kt
Apache License 2.0
Lab/src/main/kotlin/VisibilityGraph.kt
knu-3-tochanenko
273,871,388
false
{"Java": 81147, "Kotlin": 26815, "Python": 5190}
import java.util.* import kotlin.math.pow import kotlin.math.sqrt object VisibilityGraph { private fun lineOfSight(v1: Vector, v2: Vector): Boolean { val denominator = (v1.p1.x - v1.p0.x) * (v2.p1.y - v2.p0.y) - (v1.p1.y - v1.p0.y) * (v2.p1.x - v2.p0.x) if (denominator == 0.0) { return false } val numerator1 = (v1.p0.y - v2.p0.y) * (v2.p1.x - v2.p0.x) - (v1.p0.x - v2.p0.x) * (v2.p1.y - v2.p0.y) val numerator2 = (v1.p0.y - v2.p0.y) * (v1.p1.x - v1.p0.x) - (v1.p0.x - v2.p0.x) * (v1.p1.y - v1.p0.y) if (numerator1 == 0.0 || numerator2 == 0.0) { return false } val r = numerator1 / denominator val s = numerator2 / denominator return r > 0 && r < 1 && s > 0 && s < 1 } private fun getEdges(convexHulls: Array<Array<Point2D>?>): List<Vector> { val edges: MutableList<Vector> = ArrayList() for (i in convexHulls.indices) { var k = 1 for (j in convexHulls[i]!!.indices) { if (k == convexHulls[i]!!.size) k = 0 edges.add(Vector(convexHulls[i]!![j], convexHulls[i]!![k])) k++ } } return edges } fun dist(p1: Point2D?, p2: Point2D): Double { return sqrt(x = (p2.x - p1!!.x).pow(2.0) + (p2.y - p1.y).pow(2.0)) } fun generatePaths( convexHulls: Array<Array<Point2D>?>, startingPoint: Point2D?, endPoint: Point2D? ): List<Graph.Edge> { val edges = getEdges(convexHulls) val lines: MutableList<Vector> = ArrayList() val paths: MutableList<Graph.Edge> = ArrayList() var s = 0 var intersections: Int for (i in convexHulls.indices) { // .. each polygon for (j in convexHulls[i]!!.indices) { //.. each point in each polygon for (k in convexHulls.indices) { //.. connected to each polygon for (l in convexHulls[k]!!.indices) { //.. each point in each polygon if (s == 0) { intersections = 0 lines.add(Vector(startingPoint!!, convexHulls[k]!![l])) // Every edge on every convex hull for (e in edges.indices) { if (lineOfSight(lines[lines.size - 1], edges[e])) intersections++ } if (intersections < 1) { paths.add(Graph.Edge( startingPoint, lines[lines.size - 1].p1, dist(startingPoint, lines[lines.size - 1].p1) )) } } if (i != k && s != 0) { intersections = 0 lines.add(Vector(convexHulls[i]!![j], convexHulls[k]!![l])) for (e in edges.indices) { if (lineOfSight(lines[lines.size - 1], edges[e])) intersections++ } if (intersections < 1) { paths.add(Graph.Edge( lines[lines.size - 1].p0, lines[lines.size - 1].p1, dist(lines[lines.size - 1].p0, lines[lines.size - 1].p1) )) } } } } s++ } } for (i in convexHulls.indices) { for (element in convexHulls[i]!!) { intersections = 0 lines.add(Vector(endPoint!!, element)) for (e in edges.indices) { if (lineOfSight(lines[lines.size - 1], edges[e])) intersections++ } if (intersections < 1) { paths.add(Graph.Edge( lines[lines.size - 1].p0, lines[lines.size - 1].p1, dist(lines[lines.size - 1].p0, lines[lines.size - 1].p1) )) } } } for (i in edges.indices) { paths.add(Graph.Edge(edges[i].p0, edges[i].p1, dist(edges[i].p0, edges[i].p1))) } return paths } }
0
Java
0
0
e7ce6b3561d0b26f136852b409f5518660e40665
4,696
ComputationalGeometry
MIT License
app/src/main/java/com/problemsolver/androidplayground/utils/SortAlgorithm.kt
odiapratama
283,957,884
false
null
package com.problemsolver.androidplayground.utils import java.util.* object SortAlgorithm { /** * TIME COMPLEXITY * Best : Ω(n) * Average : Θ(n^2) * Worst : O(n^2) * */ fun <T : Comparable<T>> bubbleSort(array: List<T>, asc: Boolean = true) { val length = array.size - 1 var count = 0 if (asc) { while (count < length) { for (i in 0 until length) { if (array[i] > array[i + 1]) { Collections.swap(array, i, i + 1) count = 0 break } else { count++ } } } } else { while (count < length) { for (i in 0 until length) { if (array[i] < array[i + 1]) { Collections.swap(array, i, i + 1) count = 0 break } else { count++ } } } } } /** * TIME COMPLEXITY * Best : Ω(n^2) * Average : Θ(n^2) * Worst : O(n^2) * */ fun <T : Comparable<T>> selectionSort(array: List<T>, asc: Boolean = true) { for (i in 0..array.size - 2) { var pointer = i for (j in (i + 1) until array.size) { if (asc) { if (array[pointer] > array[j]) { pointer = j } } else { if (array[pointer] < array[j]) { pointer = j } } } if (asc) { if (array[pointer] < array[i]) { Collections.swap(array, i, pointer) } } else { if (array[pointer] > array[i]) { Collections.swap(array, i, pointer) } } } } /** * TIME COMPLEXITY * Best : Ω(n log(n)) * Average : Θ(n log(n)) * Worst : O(n^2) * */ fun <T : Comparable<T>> quickSort(array: List<T>, l: Int, r: Int) { if (l < r) { val p = partition(array, l, r) quickSort(array, l, p - 1) quickSort(array, p, r) } } private fun <T : Comparable<T>> partition(array: List<T>, l: Int, r: Int): Int { var left = l var right = r val mid = (left + right) / 2 val pivot = array[mid] while (left <= right) { while (array[left] < pivot) { left++ } while (array[right] > pivot) { right-- } if (left <= right) { Collections.swap(array, left, right) left++ right-- } } return left } /** * TIME COMPLEXITY * Best : Ω(n log(n)) * Average : Θ(n log(n)) * Worst : O(n log(n)) * */ fun <T : Comparable<T>> mergeSort(array: Array<T>, l: Int, r: Int) { if (l >= r) return val mid = (l + r) / 2 val temp = arrayOfNulls<Comparable<T>>(array.size) mergeSort(array, l, mid) mergeSort(array, mid + 1, r) mergeHalves(array, temp, l, r) } private fun <T : Comparable<T>> mergeHalves( array: Array<T>, temp: Array<Comparable<T>?>, leftStart: Int, rightEnd: Int ) { val leftEnd = (leftStart + rightEnd) / 2 val rightStart = leftEnd + 1 val size = rightEnd - leftStart + 1 var left = leftStart var index = leftStart var right = rightStart while (left <= leftEnd && right <= rightEnd) { if (array[left] < array[right]) { temp[index] = array[left] left++ } else { temp[index] = array[right] right++ } index++ } System.arraycopy(array, left, temp, index, leftEnd - left + 1) System.arraycopy(array, right, temp, index, rightEnd - right + 1) System.arraycopy(temp, leftStart, array, leftStart, size) } }
0
Kotlin
0
0
cf1a9a0ff1e7556a283021a79e2b985fed821d69
4,327
Android-Playground
MIT License
2020/src/main/kotlin/de/skyrising/aoc2020/day15/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2020.day15 import de.skyrising.aoc.* import it.unimi.dsi.fastutil.HashCommon import it.unimi.dsi.fastutil.ints.Int2IntMap import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap private fun day15next(mem: Int2IntMap, turn: Int, next: Int): Int { val n = turn - mem.getOrDefault(next, turn) mem[next] = turn return n } private fun day15(starting: List<Int>, limit: Int): Int { val mem = Int2IntOpenHashMap(limit / 4) var turn = 0 var next = 0 for (n in starting) { next = turn - mem.getOrDefault(n, turn) mem[n] = turn++ // println("$turn: $n") } while (turn < limit - 1) { // println("${turn+1}: $next") next = day15next(mem, turn++, next) } // println(mem.size) return next } private const val CACHE_SIZE = 64 private const val CACHE_MASK = (CACHE_SIZE - 1) shl 1 private fun day15v2(starting: List<Int>, limit: Int): Int { // val missTracker = Int2IntOpenHashMap() val mem = IntArray(limit) val cache = IntArray(CACHE_SIZE * 2) { -1 } val first = starting[0] var turn = 0 var next = 0 // var max = 0 for (n in starting) { var last = mem[n] if (last == 0 && n != first) last = turn // max = maxOf(max, next) val idx = HashCommon.mix(n) and CACHE_MASK cache[idx] = n cache[idx + 1] = turn mem[n] = turn next = turn++ - last // println("$turn: $n") } // var misses = 0 // var hits = 0 while (turn < limit - 1) { // println("${turn+1}: $next") // max = maxOf(max, next) val idx = HashCommon.mix(next) and CACHE_MASK val cacheKey = cache[idx] val last = if (cacheKey == next) { cache[idx + 1] } else { val m = mem[next] if (m == 0 && next != first) turn else m } if (cacheKey != next) { // cache key changed, write to mem if (cacheKey >= 0) mem[cacheKey] = cache[idx + 1] cache[idx] = next // missTracker[next] = missTracker[next] + 1 // misses++ } /*else { hits++ }*/ // set cached value cache[idx + 1] = turn next = turn - last turn++ } // println("$hits, $misses, ${misses * 100.0 / (hits + misses)}% miss rate") // println("${hashOr.toString(16)}, ${hashAnd.toString(16)}") // println(missTracker.int2IntEntrySet().stream().filter { it.intValue > 1 }.sorted(Comparator.comparingInt(Int2IntMap.Entry::getIntValue)).limit(20).toList()) return next } val test = TestInput("0,3,6") @PuzzleName("Rambunctious Recitation") fun PuzzleInput.part1v0() = day15(chars.trim().split(",").map(String::toInt), 2020) @PuzzleName("Rambunctious Recitation") fun PuzzleInput.part1v1() = day15v2(chars.trim().split(",").map(String::toInt), 2020) fun PuzzleInput.part2v0() = day15(chars.trim().split(",").map(String::toInt), 30000000) fun PuzzleInput.part2v1() = day15v2(chars.trim().split(",").map(String::toInt), 30000000)
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
3,085
aoc
MIT License
src/main/kotlin/sschr15/aocsolutions/Day23.kt
sschr15
317,887,086
false
{"Kotlin": 184127, "TeX": 2614, "Python": 446}
package sschr15.aocsolutions import sschr15.aocsolutions.util.* import java.util.ArrayDeque import kotlin.time.measureTime /** * AOC 2023 [Day 23](https://adventofcode.com/2023/day/23) * Challenge: How does one take a leisurely walk through a forest, pretending there *isn't* * a global snow shortage mere days before christmas? */ object Day23 : Challenge { @ReflectivelyUsed override fun solve() = challenge(2023, 23) { // test() val grid: Grid<Char> val start: Point val end: Point part1 { fun findSlowestPath(start: Point, end: Point, grid: Grid<Char>, previous: Point = start.up()): Int { var previous = previous var current = start var score = 0 while (true) { when (grid[current]) { '^' -> { previous = current current = current.up() score++ continue } 'v' -> { previous = current current = current.down() score++ continue } '<' -> { previous = current current = current.left() score++ continue } '>' -> { previous = current current = current.right() score++ continue } } val capableDirections = listOfNotNull( current.up().takeIf { it in grid && grid[it] !in arrayOf('#', 'v') }, current.down().takeIf { it in grid && grid[it] !in arrayOf('#', '^') }, current.left().takeIf { it in grid && grid[it] !in arrayOf('#', '>') }, current.right().takeIf { it in grid && grid[it] !in arrayOf('#', '<') } ).filter { it != previous } if (capableDirections.isEmpty()) { return score // only one spot on the grid has no valid moves, and that's the end } val only = capableDirections.singleOrNull() ?: return capableDirections.maxOf { findSlowestPath(it, end, grid, previous) } + score + 1 previous = current current = only score++ } } grid = inputLines.toGrid() start = Point((0..<grid.width).single { grid[it, 0] != '#' }, 0) end = Point((0..<grid.width).single { grid[it, grid.height - 1] != '#' }, grid.height - 1) findSlowestPath(start, end, grid) } part2 { val graph = Graph<Point>() val startNode = graph.addNode(start) val endNode = graph.addNode(end) val junctions = grid.toPointMap() .filterValues { it != '#' } .filterKeys { grid.getNeighbors(it, false).count { (_, c) -> c != '#' } > 2 } .mapValues { (pt) -> graph.addNode(pt) } measureTime { data class QueueEntry( val point: Point, val count: Int, val from: Graph<Point>.Node, val previous: Point ) val queue = ArrayDeque<QueueEntry>() queue.addAll(junctions.flatMap { (pt, node) -> grid.getNeighbors(pt, false) .filterValues { it != '#' } .keys .map(AbstractPoint::toPoint) .map { QueueEntry(it, 1, node, pt) } }) while (queue.isNotEmpty()) { val (point, count, from, previous) = queue.removeFirst() if (point in junctions) { // every junction will meet each other on its own, one-way connections prevent duplicate edges from.oneWayConnectTo(junctions.getValue(point), count) continue } val possibleDirections = grid.getNeighbors(point, false) .filterValues { it != '#' } .keys .map { it.toPoint() } .filter { it != previous } when (possibleDirections.size) { 0 -> when (point) { start -> startNode.connectTo(from, count) end -> endNode.connectTo(from, count) else -> error("Unexpected immovability from $previous to $point") } 1 -> { val toGo = possibleDirections.single() queue.add(QueueEntry(toGo, count + 1, from, point)) } else -> error("Unexpected junction at $point (point ${if (point in junctions) "" else "!"}in junctions)") } } }.also { println("Constructing graph took $it") } fun slowestPath(graph: Graph<Point>, start: Graph<Point>.Node, end: Graph<Point>.Node, alreadyVisited: MaxStatesSet<Graph<Point>.Node>.Immutable): Int { if (start == end) return 0 val possiblePaths = start.edges .filter { it.to !in alreadyVisited } .map { it.weight!! + slowestPath(graph, it.to, end, alreadyVisited + start) } return possiblePaths.maxOrNull() ?: Int.MIN_VALUE } val stateSet = junctions.values.toMutableSet() stateSet.add(startNode) stateSet.add(endNode) slowestPath(graph, startNode, endNode, MaxStatesSet(stateSet).immutable()) } } @JvmStatic fun main(args: Array<String>) = println("Time: ${solve()}") }
0
Kotlin
0
0
e483b02037ae5f025fc34367cb477fabe54a6578
6,355
advent-of-code
MIT License
2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day16.kt
codelicia
627,407,402
false
{"Kotlin": 49578, "PHP": 554, "Makefile": 293}
package com.codelicia.advent2021 class Day16(val input: String) { private fun hexToBinary(input: String): List<Char> = input.map { it.digitToInt(16).toString(2).padStart(4, '0') }.flatMap { it.toList() } private var transmission: Iterator<Char> = hexToBinary(input).iterator() fun Iterator<Char>.next(size: Int): String = (1..size).map { next() }.joinToString("") fun part1(): Long = getPacket(transmission).first fun part2(): Long = getPacket(transmission).second // Version -> Count private fun getPacket(transmission: Iterator<Char>): Pair<Long, Long> { val subPackets = mutableListOf<Long>() val version = transmission.next(3).toInt(2) val typeId = transmission.next(3).toInt(2) var versionSum = version.toLong() when (typeId) { 4 -> { var keepCounting = true; var count = "" while (keepCounting) { val lastBit = transmission.next(1) if (lastBit == "0") keepCounting = false; val rest = transmission.next(4) count += rest } subPackets.add(count.toLong(2)) } else -> { val type = transmission.next(1).toInt(2) when (type) { 0 -> { // 15 val subPacketsLength = transmission.next(15).toInt(2) val subPacketBits = transmission.next(subPacketsLength).toCharArray() val iterator = subPacketBits.iterator() while (iterator.hasNext()) { val p = getPacket(iterator) versionSum += p.first subPackets.add(p.second) } return versionSum to subPackets.operateBy(typeId) } 1 -> { // 11 val subPacketsLength = transmission.next(11).toInt(2) repeat (subPacketsLength) { val p = getPacket(transmission) versionSum += p.first subPackets.add(p.second) } return versionSum to subPackets.operateBy(typeId) } } } } return versionSum to subPackets.operateBy(typeId) } fun MutableList<Long>.operateBy(id: Int) = when (id) { 0 -> sumOf { it } 1 -> reduce { acc, cur -> acc * cur } 2 -> minOf { it } 3 -> maxOf { it } 5 -> if (this[0] > this[1]) 1 else 0 6 -> if (this[0] < this[1]) 1 else 0 7 -> if (this[0] == this[1]) 1 else 0 else -> first() } }
2
Kotlin
0
0
df0cfd5c559d9726663412c0dec52dbfd5fa54b0
2,907
adventofcode
MIT License
src/Day06.kt
dakr0013
572,861,855
false
{"Kotlin": 105418}
import kotlin.test.assertEquals fun main() { fun part1(input: List<String>): Int { val datastream = input.first() return datastream .withIndex() .windowed(4) .map { indexedCharSequence -> if (indexedCharSequence.map { it.value }.toSet().size == 4) { indexedCharSequence.last().index + 1 } else { 0 } } .first { it > 0 } } fun part2(input: List<String>): Int { val datastream = input.first() return datastream .withIndex() .windowed(14) .map { indexedCharSequence -> if (indexedCharSequence.map { it.value }.toSet().size == 14) { indexedCharSequence.last().index + 1 } else { 0 } } .first { it > 0 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") assertEquals(7, part1(testInput)) assertEquals(19, part2(testInput)) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6b3adb09f10f10baae36284ac19c29896d9993d9
1,086
aoc2022
Apache License 2.0
2023/src/main/kotlin/org/suggs/adventofcode/Day03GearRatios.kt
suggitpe
321,028,552
false
{"Kotlin": 156836}
package org.suggs.adventofcode import org.slf4j.LoggerFactory object Day03GearRatios { private val log = LoggerFactory.getLogger(this::class.java) fun sumAllNumbersWithAdjacentSymbolsFrom(data: String) = sumNumbersWithAdjacentSymbols(Grid(data), Coordinate(0, 0), 0) .also { log.debug("Part 1: $it") } private fun sumNumbersWithAdjacentSymbols(grid: Grid, coordinate: Coordinate, accumulator: Int = 0): Int { return if (grid.isEndOfGrid(coordinate)) accumulator else sumNumbersWithAdjacentSymbols(grid, coordinate.down(), accumulator + sumValuesForRow(grid, coordinate)) } private fun sumValuesForRow(grid: Grid, coordinate: Coordinate, accumulator: Int = 0): Int { return if (grid.isEndOfRow(coordinate)) accumulator else if (grid.isNotDigit(coordinate)) sumValuesForRow(grid, coordinate.toTheRight(), accumulator) else { sumValuesForRow(grid, coordinate.toTheRight(grid.getLengthOfNumberFrom(coordinate)), accumulator + calculateValidPartNumber(grid, coordinate)) } } private fun calculateValidPartNumber(grid: Grid, coordinate: Coordinate): Int { return if (!grid.isNumberAdjacentToSymbolAt(coordinate)) 0 else grid.getNumberAt(coordinate) } fun sumAllGearRatios(data: String): Long { val coordinates = findAllNumbersWithGearSymbolFrom(Grid(data), Coordinate(0, 0), listOf<GearLocation>()).filter { it.gearCoordinates.size > 0 } val foo = coordinates.groupBy { it.gearCoordinates }.map { it.value }.filter { it.size > 1 } return foo.sumOf { it.map { oth -> oth.number }.reduce { acc, i -> acc * i } }.toLong() .also { log.debug("Part 2: $it") } } private fun findAllNumbersWithGearSymbolFrom(grid: Grid, coordinate: Coordinate, accumulator: List<GearLocation>): List<GearLocation> { return if (grid.isEndOfGrid(coordinate)) accumulator else findAllNumbersWithGearSymbolFrom(grid, coordinate.down(), accumulator + findAllGearedNumbersForRow(grid, coordinate, listOf())) } private fun findAllGearedNumbersForRow(grid: Grid, coordinate: Coordinate, accumulator: List<GearLocation>): List<GearLocation> { return if (grid.isEndOfRow(coordinate)) accumulator else if (grid.isNotDigit(coordinate)) findAllGearedNumbersForRow(grid, coordinate.toTheRight(), accumulator) else findAllGearedNumbersForRow( grid, coordinate.toTheRight(grid.getLengthOfNumberFrom(coordinate)), accumulator + createGearLocationFor(grid, coordinate) ) } private fun createGearLocationFor(grid: Grid, coordinate: Coordinate): List<GearLocation> { val gearLocations = grid.gearLocationsForNumberAt(coordinate) return if (gearLocations.isEmpty()) listOf() else listOf(GearLocation(grid.getNumberAt(coordinate), gearLocations)) } fun Grid.isDigit(coordinate: Coordinate) = grid[coordinate.y][coordinate.x].isDigit() fun Grid.isNotDigit(coordinate: Coordinate) = !isDigit(coordinate) fun Grid.isNotSymbol(coordinate: Coordinate) = isDigit(coordinate) || valueOf(coordinate) == '.' fun Grid.isSymbol(coordinate: Coordinate) = isNotDigit(coordinate) && valueOf(coordinate) != '.' fun Grid.isGear(coordinate: Coordinate): Boolean = valueOf(coordinate) == '*' fun Grid.getLengthOfNumberFrom(coordinate: Coordinate): Int { fun getLengthOfNumberFrom(coordinate: Coordinate, accumulator: Int): Int { return if (isEndOfRow(coordinate.toTheRight()) || isNotDigit(coordinate.toTheRight())) accumulator else getLengthOfNumberFrom(coordinate.toTheRight(), accumulator + 1) } return getLengthOfNumberFrom(coordinate, 1) } fun Grid.isNumberAdjacentToSymbolAt(coordinate: Coordinate): Boolean { return buildCoordinatesToTestFromNumberAt(coordinate).any { isOnGrid(it) && isSymbol(it) } } fun Grid.gearLocationsForNumberAt(coordinate: Coordinate): List<Coordinate> { return buildCoordinatesToTestFromNumberAt(coordinate).filter { isOnGrid(it) && isGear(it) } } private fun Grid.buildCoordinatesToTestFromNumberAt(coordinate: Coordinate) = coordinate.buildCoordinatesAround(coordinate, getLengthOfNumberFrom(coordinate)) fun Grid.getNumberAt(coordinate: Coordinate): Int { fun getNumberAt(coordinate: Coordinate, length: Int): String { return if (length == 1) valueOf(coordinate).toString() else valueOf(coordinate).toString() + getNumberAt(coordinate.toTheRight(), length - 1) } return getNumberAt(coordinate, getLengthOfNumberFrom(coordinate)).toInt() } fun Coordinate.buildCoordinatesAround(coordinate: Coordinate, length: Int): List<Coordinate> { return listOf(coordinate.toTheLeft(), coordinate.toTheLeft().up(), coordinate.toTheLeft().down()) + listOf(coordinate.toTheRight(length), coordinate.toTheRight(length).up(), coordinate.toTheRight(length).down()) + buildListCoordinatesFrom(coordinate.up(), length) + buildListCoordinatesFrom(coordinate.down(), length) } fun Coordinate.buildListCoordinatesFrom(coordinate: Coordinate, length: Int = 1): List<Coordinate> { return if (length == 1) listOf(coordinate) else listOf(coordinate) + buildListCoordinatesFrom(coordinate.toTheRight(), length - 1) } fun Coordinate.toTheLeft(by: Int = 1) = Coordinate(x - by, y) fun Coordinate.toTheRight(by: Int = 1) = Coordinate(x + by, y) fun Coordinate.rowBelow() = Coordinate(0, y + 1) } data class GearLocation(val number: Int, val gearCoordinates: List<Coordinate>)
0
Kotlin
0
0
9485010cc0ca6e9dff447006d3414cf1709e279e
5,844
advent-of-code
Apache License 2.0
2021/07/main.kt
chylex
433,239,393
false
null
import java.io.File import kotlin.math.abs fun main() { val originalPositions = File("input.txt").readLines().single().split(',').map(String::toInt).toIntArray() val p1 = originalPositions.minOrNull() ?: return val p2 = originalPositions.maxOrNull() ?: return val candidates = p1..p2 part1(originalPositions, candidates) part2(originalPositions, candidates) } fun part1(originalPositions: IntArray, candidates: IntRange) { val cheapestFuel = candidates.minOf { p -> originalPositions.sumOf { abs(it - p) } } println("Cheapest fuel at constant fuel usage: $cheapestFuel") } fun part2(originalPositions: IntArray, candidates: IntRange) { val cheapestFuel = candidates.minOf { p1 -> originalPositions.sumOf { p2 -> abs(p2 - p1).let { steps -> (steps * (steps + 1)) / 2 } } } println("Cheapest fuel at polynomial fuel usage: $cheapestFuel") }
0
Rust
0
0
04e2c35138f59bee0a3edcb7acb31f66e8aa350f
878
Advent-of-Code
The Unlicense
src/main/kotlin/Day09.kt
andrewrlee
434,584,657
false
{"Kotlin": 29493, "Clojure": 14117, "Shell": 398}
import java.io.File import java.nio.charset.Charset.defaultCharset import kotlin.streams.toList typealias Coordinate = Pair<Int, Int> typealias Basin = Set<Coordinate> typealias ValidCells = Set<Coordinate> object Day09 { fun toCoordinates(row: Int, line: String) = line.chars() .map(Character::getNumericValue) .toList() .mapIndexed { col, value -> (row to col) to value } fun getSurroundingCoordinates( validCells: ValidCells, coord: Coordinate, seenCoordinates: HashSet<Coordinate>, deltas: List<Pair<Int, Int>> = listOf(0 to 1, 1 to 0, 0 to -1, -1 to 0) ) = deltas.asSequence() .map { (x2, y2) -> coord.first + x2 to coord.second + y2 } .filter { validCells.contains(it) } .filter { !seenCoordinates.contains(it) } fun findBasin(validCells: ValidCells, coordinate: Coordinate, seenCoordinates: HashSet<Coordinate>): Basin? { if (seenCoordinates.contains(coordinate)) return null seenCoordinates.add(coordinate) val basin = mutableSetOf(coordinate) getSurroundingCoordinates(validCells, coordinate, seenCoordinates) .filter { !seenCoordinates.contains(it) } .map { findBasin(validCells, it, seenCoordinates) } .filterNotNull() .forEach { basin.addAll(it) } return basin } fun run() { val file = File("day09/input-real.txt") val cells = file.readLines(defaultCharset()) .mapIndexed(::toCoordinates) .flatten() val (highs, unseen) = cells.partition { it.second == 9 } val validCells = cells.map { it.first }.toSet() val seenCoordinates = highs.map { it.first }.toHashSet() val toCheck = unseen.map { it.first } val basins = toCheck.fold(mutableListOf<Basin>()) { basins, coordinate -> findBasin(validCells, coordinate, seenCoordinates)?.let { basins.add(it) } basins } val result = basins.map { it.size }.sortedDescending().take(3).reduce(Int::times) println(result) } } fun main() { Day09.run() }
0
Kotlin
0
0
aace0fccf9bb739d57f781b0b79f2f3a5d9d038e
2,139
adventOfCode2021
MIT License
src/pl/shockah/aoc/y2018/Day6.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2018 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import pl.shockah.unikorn.collection.MutableArray2D import java.util.* import kotlin.math.absoluteValue class Day6: AdventTask<List<Day6.Point>, Int, Int>(2018, 6) { data class Point( val x: Int, val y: Int ) { val neighbors: Array<Point> get() = arrayOf(Point(x - 1, y), Point(x + 1, y), Point(x, y - 1), Point(x, y + 1)) } override fun parseInput(rawInput: String): List<Point> { return rawInput.lines().map { val split = it.split(", ") return@map Point(split[0].toInt(), split[1].toInt()) } } private sealed class GridPoint { data class Initial( val point: Point ): GridPoint() data class Closest( val initial: Initial, val distance: Int ): GridPoint() data class Ambiguous( val distance: Int ): GridPoint() object Empty: GridPoint() } override fun part1(input: List<Point>): Int { val minX = input.minOf { it.x } val minY = input.minOf { it.y } val maxX = input.maxOf { it.x } val maxY = input.maxOf { it.y } val grid = MutableArray2D<GridPoint>(maxX - minX + 3, maxY - minY + 3, GridPoint.Empty) val toProcess = LinkedList<Triple<GridPoint.Initial, Point, Int>>() for (point in input) { val translatedPoint = Point(point.x - minX + 1, point.y - minY + 1) val initial = GridPoint.Initial(translatedPoint) grid[translatedPoint.x, translatedPoint.y] = initial toProcess += Triple(initial, translatedPoint, 0) } while (!toProcess.isEmpty()) { val (initial, point, distance) = toProcess.removeFirst() if (point.x < 0 || point.y < 0 || point.x >= grid.width || point.y >= grid.height) continue when (val existing = grid[point.x, point.y]) { GridPoint.Empty -> { grid[point.x, point.y] = GridPoint.Closest(initial, distance) toProcess += point.neighbors.map { Triple(initial, it, distance + 1) } } is GridPoint.Ambiguous -> { if (existing.distance > distance) { grid[point.x, point.y] = GridPoint.Closest(initial, distance) toProcess += point.neighbors.map { Triple(initial, it, distance + 1) } } } is GridPoint.Closest -> { if (existing.distance > distance) { grid[point.x, point.y] = GridPoint.Closest(initial, distance) toProcess += point.neighbors.map { Triple(initial, it, distance + 1) } } else if (existing.distance == distance && existing.initial != initial) { grid[point.x, point.y] = GridPoint.Ambiguous(distance) } } is GridPoint.Initial -> { if (existing == initial) toProcess += point.neighbors.map { Triple(initial, it, distance + 1) } } } } return grid.toMap().filterValues { it is GridPoint.Closest }.mapValues { it.value as GridPoint.Closest }.entries.groupBy { it.value.initial }.filter { !it.value.any { it.key.first == 0 || it.key.second == 0 || it.key.first == grid.width - 1 || it.key.second == grid.height - 1 } // going into infinity }.values.maxOf { it.size } + 1 } fun getLargestSafeRegionSize(input: List<Point>, maxExclusiveTotalDistance: Int): Int { val minX = input.minOf { it.x } val minY = input.minOf { it.y } val maxX = input.maxOf { it.x } val maxY = input.maxOf { it.y } val grid = MutableArray2D<Int?>(maxX - minX + 1, maxY - minY + 1, null) for (y in 0 until grid.height) { for (x in 0 until grid.width) { val sum = input.sumOf { (it.x - x).absoluteValue + (it.y - y).absoluteValue } if (sum < maxExclusiveTotalDistance) grid[x, y] = sum } } val safeRegionSizes = mutableListOf<Int>() for (y in 0 until grid.height) { for (x in 0 until grid.width) { if (grid[x, y] != null) { val toProcess = LinkedList<Point>() toProcess += Point(x, y) var count = 0 while (!toProcess.isEmpty()) { val point = toProcess.removeFirst() if (point.x < 0 || point.y < 0 || point.x >= grid.width || point.y >= grid.height) continue if (grid[point.x, point.y] != null) { count++ toProcess += point.neighbors grid[point.x, point.y] = null } } safeRegionSizes += count } } } return safeRegionSizes.maxOrNull()!! } override fun part2(input: List<Point>): Int { return getLargestSafeRegionSize(input, 10_000) } class Tests { private val task = Day6() private val rawInput = """ 1, 1 1, 6 8, 3 3, 4 5, 5 8, 9 """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals(17, task.part1(input)) } @Test fun getLargestSafeRegionSize() { val input = task.parseInput(rawInput) Assertions.assertEquals(16, task.getLargestSafeRegionSize(input, 32)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
4,762
Advent-of-Code
Apache License 2.0
day09/Part2.kt
anthaas
317,622,929
false
null
import java.io.File fun main(args: Array<String>) { val input = File("input.txt").readLines().map { it.toLong() } var index = 25 var valid = true while (valid) { valid = existsSum(input.subList(index - 25, index), input[index]) index++ } val invalidNumber = input[index - 1] println(findRangeSum(input, invalidNumber)) } private fun existsSum(input: List<Long>, searchValue: Long): Boolean { input.forEach { a -> input.forEach { b -> if (a + b == searchValue) { return true } } } return false } private fun findRangeSum(input: List<Long>, sum: Long): Long { var l = 0 var r = 0 while (true) { val sublistSum = input.subList(l, r).sum() if (sublistSum == sum) { return input.subList(l, r).min()!! + input.subList(l, r).max()!! } if (sublistSum < sum) { r++ } if (sublistSum > sum) { l++ r = l } } }
0
Kotlin
0
0
aba452e0f6dd207e34d17b29e2c91ee21c1f3e41
1,039
Advent-of-Code-2020
MIT License
src/main/kotlin/com/sherepenko/leetcode/solutions/MaximalSquare.kt
asherepenko
264,648,984
false
null
package com.sherepenko.leetcode.solutions import com.sherepenko.leetcode.Solution import kotlin.math.max import kotlin.math.min class MaximalSquare( private val matrix: Array<CharArray> ) : Solution { companion object { fun maximalSquare(matrix: Array<CharArray>): Int { val m = matrix.size + 1 val n = if (matrix.isNotEmpty()) matrix[0].size + 1 else 1 val dp = IntArray(n) dp[0] = 0 var prev = 0 var maxSquareLength = 0 for (i in 1 until m) { for (j in 1 until n) { val tmp = dp[j] if (matrix[i - 1][j - 1] == '1') { dp[j] = min(min(dp[j - 1], prev), dp[j]) + 1 maxSquareLength = max(maxSquareLength, dp[j]) } else { dp[j] = 0 } prev = tmp } } return maxSquareLength * maxSquareLength } } override fun resolve() { println("Maximal Square:") println(" Input:") matrix.forEach { println(" ${it.joinToString(separator = " ")}") } println(" Result: ${maximalSquare(matrix)} \n") } }
0
Kotlin
0
0
49e676f13bf58f16ba093f73a52d49f2d6d5ee1c
1,298
leetcode
The Unlicense
src/Day03/Day03.kt
NST-d
573,224,214
false
null
package Day03 import utils.* fun main() { fun part1(input : List<String>): Int = input .map { it.chunked(it.length/2) } .sumOf { val left = it[0] val right = it[1] var value = 0 (left.toCharArray()).distinct().forEach { c: Char -> if (right.contains(c)){ if(c.isUpperCase()){ value += c - 'A' + 27 }else{ value += c - 'a' +1 } //println("$c $value") } } value } fun part2(input: List<String>): Int = input.withIndex().groupBy { (it.index/3) }.values .sumOf { group -> var value = 0 group[0].value.toCharArray().distinct().forEach { c: Char -> if( group[1].value.contains(c) && group[2].value.contains(c)){ if(c.isUpperCase()){ value += c - 'A' + 27 }else{ value += c - 'a' +1 } } } value } val test = readTestLines("Day03") val input = readInputLines("Day03") println( part2(input) ) }
0
Kotlin
0
0
c4913b488b8a42c4d7dad94733d35711a9c98992
1,412
aoc22
Apache License 2.0
2021/src/day11/Solution.kt
vadimsemenov
437,677,116
false
{"Kotlin": 56211, "Rust": 37295}
package day11 import java.nio.file.Files import java.nio.file.Paths fun main() { fun iterate(octopuses: Input): Int { var flashes = 0 val queue = mutableListOf<Pair<Int, Int>>() val flashed = Array(octopuses.size) { BooleanArray(octopuses[it].size) } for ((i, row) in octopuses.withIndex()) { for (j in row.indices) { row[j]++ if (row[j] > 9) { flashed[i][j] = true queue.add(i to j) } } } var head = 0 while (head < queue.size) { val (i, j) = queue[head++] octopuses[i][j] = 0 flashes++ for (di in -1..1) { for (dj in -1..1) { val ii = i + di val jj = j + dj if (ii !in octopuses.indices || jj !in octopuses[ii].indices) continue if (!flashed[ii][jj]) { octopuses[ii][jj]++ if (octopuses[ii][jj] > 9) { flashed[ii][jj] = true queue.add(ii to jj) } } } } } return flashes } fun part1(octopuses: Input): Int { var flashes = 0 repeat(100) { flashes += iterate(octopuses) } return flashes } fun part2(octopuses: Input): Int { repeat(100500) { val flashes = iterate(octopuses) if (flashes == 100) return it + 1 } error("POLUNDRA") } check(part1(readInput("test-input.txt")) == 1656) check(part2(readInput("test-input.txt")) == 195) println(part1(readInput("input.txt"))) println(part2(readInput("input.txt"))) } private fun readInput(s: String): Input { return Files.newBufferedReader(Paths.get("src/day11/$s")) .readLines() .map { it .map { it.code - '0'.code } .toMutableList() } } private typealias Input = List<MutableList<Int>>
0
Kotlin
0
0
8f31d39d1a94c862f88278f22430e620b424bd68
1,791
advent-of-code
Apache License 2.0
src/boj_14888/Kotlin.kt
devetude
70,114,524
false
{"Java": 564034, "Kotlin": 80457}
package boj_14888 import java.util.StringTokenizer import kotlin.math.max import kotlin.math.min var maxValue = Int.MIN_VALUE var minValue = Int.MAX_VALUE fun main() { val n = readln().toInt() var st = StringTokenizer(readln()) val numbers = IntArray(n) repeat(n) { numbers[it] = st.nextToken().toInt() } st = StringTokenizer(readln()) val opCounts = IntArray(size = 4) repeat(opCounts.size) { opCounts[it] = st.nextToken().toInt() } val opSequences = IntArray(size = n - 1) dfs(numbers, opSequences, opCounts) val result = buildString { appendLine(maxValue) append(minValue) } println(result) } fun dfs(numbers: IntArray, opTypes: IntArray, opCounts: IntArray, opSeq: Int = 0) { if (opSeq == opTypes.size) { var result = numbers.first() for (i in 1..numbers.lastIndex) { val number = numbers[i] result = when (opTypes[i - 1]) { 0 -> result + number 1 -> result - number 2 -> result * number else -> result / number } } maxValue = max(maxValue, result) minValue = min(minValue, result) return } opCounts.forEachIndexed { opType, opCount -> if (0 < opCount) { opTypes[opSeq] = opType --opCounts[opType] dfs(numbers, opTypes, opCounts, opSeq = opSeq + 1) ++opCounts[opType] } } }
0
Java
7
20
4c6acff4654c49d15827ef87c8e41f972ff47222
1,480
BOJ-PSJ
Apache License 2.0
src/main/kotlin/day6/Aoc.kt
widarlein
225,589,345
false
null
package day6 import java.io.File fun main(args: Array<String>) { if (args.isEmpty()) { println("Must provide input orbits") System.exit(0) } val inputLines = File("src/main/kotlin/day6/${args[0]}").readLines() val objects = buildGraph(inputLines) val numberOfOrbits = objects.sumBy { countOrbits(it) } println("Part1: number of orbits is $numberOfOrbits") dfs(objects.find { it.name == "YOU" }?.orbits!!, objects.find { it.name == "SAN" }?.orbits!!) } private fun buildGraph(inputLines: List<String>): MutableSet<OrbitObject> { val objectSet = mutableSetOf<OrbitObject>() inputLines.forEach { val (pivotName, orbitalName) = it.split(")") var pivot = objectSet.find { it.name == pivotName } var orbital = objectSet.find { it.name == orbitalName } if (pivot == null) { pivot = OrbitObject(pivotName, null) objectSet.add(pivot) } if (orbital == null) { orbital = OrbitObject(orbitalName, pivot) objectSet.add(orbital) } else { orbital.orbits = pivot } pivot.orbitals.add(orbital) } return objectSet } internal fun dfs(from: OrbitObject, to: OrbitObject, visited: MutableSet<OrbitObject> = mutableSetOf(), steps: Int = 0) { // YE GODS THIS TOOK A LONG TIME TO DO SINCE I WANTED TO MAKE FUNCTION WITH A RETURN VALUE // BUT IN THE END I GAVE UP. FRUSTRATED. if (from == to) { println("We are here at $steps") } visited.add(from) val nexts = (from.orbitals + from.orbits).filterNotNull().filterNot { visited.contains(it) } nexts.forEach { dfs(it, to, visited, steps + 1) } } internal fun countOrbits(orbitObject: OrbitObject): Int { val orbits = orbitObject.orbits ?: return 0 return 1 + countOrbits(orbits) } class OrbitObject(val name: String, var orbits: OrbitObject? = null, vararg orbitals: OrbitObject) { val orbitals: MutableList<OrbitObject> = orbitals.toMutableList() override fun equals(other: Any?): Boolean { return other != null && other is OrbitObject && name == other.name } override fun hashCode(): Int { return name.hashCode() } }
0
Kotlin
0
0
b4977e4a97ad61177977b8eeb1dcf298067e8ab4
2,233
AdventOfCode2019
MIT License
src/main/kotlin/days/Day1.kt
nicopico-dev
726,255,944
false
{"Kotlin": 37616}
package days import util.allIndexesOf class Day1( inputFileNameOverride: String? = null, ) : Day(1, inputFileNameOverride) { override fun partOne(): Any { return inputList .sumOf { line -> val first = line.first(Char::isDigit) val last = line.last(Char::isDigit) "$first$last".toInt() } } override fun partTwo(): Any { return inputList .map { extractDigits(it) } .sumOf { line -> val first = line.first() val last = line.last() "$first$last".toInt() } } companion object { private val spelledDigits = mapOf( "1" to "1", "2" to "2", "3" to "3", "4" to "4", "5" to "5", "6" to "6", "7" to "7", "8" to "8", "9" to "9", "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9", ) fun extractDigits(line: String): String { return spelledDigits.keys .flatMap { word -> line.allIndexesOf(word) .map { index -> Digit(word, index) } } .sortedBy { it.startIndex } .joinToString(separator = "") { spelledDigits[it.word]!! } } } private data class Digit( val word: String, val startIndex: Int, ) }
0
Kotlin
0
0
1a13c8bd3b837c1ce5b13f90f326f0277249d23e
1,751
aoc-2023
Creative Commons Zero v1.0 Universal
Palindrome_Partitioning.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
class Solution { fun partition(s: String): List<List<String>> { val res = mutableListOf<List<String>>() combine(s, mutableListOf(), res) return res } private fun combine(s: String, path: MutableList<String>, res: MutableList<List<String>>) { if (s.isEmpty()) { res.add(path.toList()) return } path.add(s[0].toString()) combine(s.substring(1), path, res) path.removeAt(path.lastIndex) for (i in 2..s.length) { if (isPalindrome(s.substring(0, i))) { path.add(s.substring(0, i)) combine(s.substring(i), path, res) path.removeAt(path.lastIndex) } } } private fun isPalindrome(s: String): Boolean { val n = s.length for (i in 0 until n / 2) { if (s[i] != s[n - 1 - i]) return false } return true } } fun main() { val solution = Solution() val testCases = arrayOf( "aab", "a", "aaa" ) val res = mutableListOf<List<String>>() val a = mutableListOf("a", "b") res.add(a) a.removeAt(0) println(a) println(res) for (testCase in testCases) { println(solution.partition(testCase).joinToString("\n")) println() } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,336
leetcode
MIT License
src/Day01.kt
Frendzel
573,198,577
false
{"Kotlin": 5336}
fun main() { fun part1(input: List<String>): Int = input.joinToString(",") .split(",,") .map { it.split(",").sumOf(String::toInt) } .maxOf { it } fun part2(input: List<String>): Int = input.joinToString(",") .split(",,") .map { it.split(",").sumOf(String::toInt) } .sortedDescending() .take(3) .sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") val part1 = part1(testInput) println(part1) check(part1 == 67450) val part2 = part2(testInput) println(part2) check(part2 == 199357) }
0
Kotlin
0
0
a8320504be93dfba1f634413a50e7240d16ba6d9
772
advent-of-code-kotlin
Apache License 2.0
kotlin/Determinant.kt
dirask
202,550,220
true
{"Java": 491556, "C++": 207948, "Kotlin": 23977, "CMake": 346}
// https://en.wikipedia.org/wiki/Determinant fun det(matrix: Array<DoubleArray>): Double { val EPS = 1e-10 val a = matrix.map { it.copyOf() }.toTypedArray() val n = a.size var res = 1.0 for (i in 0 until n) { val p = (i until n).maxBy { Math.abs(a[it][i]) }!! if (Math.abs(a[p][i]) < EPS) return 0.0 if (i != p) { res = -res a[i] = a[p].also { a[p] = a[i] } } res *= a[i][i] for (j in i + 1 until n) a[i][j] /= a[i][i] for (j in 0 until n) if (j != i && Math.abs(a[j][i]) > EPS /*optimizes overall complexity to O(n^2) for sparse matrices*/) for (k in i + 1 until n) a[j][k] -= a[i][k] * a[j][i] } return res } // Usage example fun main() { val d = det(arrayOf(doubleArrayOf(0.0, 1.0), doubleArrayOf(-1.0, 0.0))) println(Math.abs(d - 1) < 1e-10) }
0
Java
1
2
75f52966780cdc6af582e00f9460f17a4a80d19e
937
codelibrary
The Unlicense
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/SortingAlgorithms/HeapSort/HeapSort.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
package com.betulnecanli.kotlindatastructuresalgorithms.SortingAlgorithms.HeapSort //Heapsort is another comparison-based algorithm that sorts an array in ascending //order using a heap. private fun leftChildIndex(index: Int) = (2 * index) + 1 private fun rightChildIndex(index: Int) = (2 * index) + 2 fun <T> Array<T>.siftDown( index: Int, upTo: Int, comparator: Comparator<T> ) { var parent = index while (true) { val left = leftChildIndex(parent) val right = rightChildIndex(parent) var candidate = parent if (left < upTo && comparator.compare(this[left], this[candidate]) > 0 ) { candidate = left } if (right < upTo && comparator.compare(this[right], this[candidate]) > 0 ) { candidate = right } if (candidate == parent) { return } this.swapAt(parent, candidate) parent = candidate } } fun <T> Array<T>.heapify(comparator: Comparator<T>) { if (this.isNotEmpty()) { (this.size / 2 downTo 0).forEach { this.siftDown(it, this.size, comparator) } } } fun <T> Array<T>.heapSort(comparator: Comparator<T>) { this.heapify(comparator) for (index in this.indices.reversed()) { // 1 this.swapAt(0, index) // 2 siftDown(0, index, comparator) // 3 } } //1. You reorder the elements so that the array looks like a Heap. //2. You loop through the array, starting from the last element. //3. You swap the first element and the last element. This moves the largest unsorted //element to its correct spot. //4. Because the heap is now invalid, you must sift down the new root node. As a //result, the next largest element will become the new root. fun <T> Array<T>.swapAt(first : Int, second : Int){ val aux = this[first] this[first] = this[second] this[second] = aux } //Even though you get the benefit of in-memory sorting, the performance of heap sort //is O(n log n) for its best, worse and average cases. This is because you have to //traverse the whole array once and, every time you swap elements, you must perform //a sift down, which is an O(log n) operation.
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
2,862
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/questions/WildcardSearchDS.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import kotlin.test.assertFalse import kotlin.test.assertTrue /** * Design a data structure that supports adding new words and finding if a string matches any previously added string. * Your data structure should implement two methods * * `addWord(word)`- Adds word to the data structure * * `searchWorld(word)`- Returns true if there is any string in the data structure that matches word. Word may contain dots where a dot can be matched with any letter (a dot represents a wildcard). */ @UseCommentAsDocumentation class Trie { var value: Char? = null private val trieMap: MutableMap<Char, Trie> = mutableMapOf() fun addWord(word: String) { addWord(word, 0) } private fun addWord(word: String, index: Int) { val letter = word.getOrNull(index) ?: return if (letter !in trieMap) { val newTrie = Trie() trieMap[letter] = newTrie newTrie.value = letter newTrie.addWord(word, index + 1) } else { val trie = trieMap[letter]!! trie.addWord(word, index + 1) } } override fun toString(): String { return "Trie($value, ${trieMap.values})" } private fun depthFirstTraversal(trie: Trie, current: String, word: MutableList<String>) { if (trie.trieMap.isEmpty()) { word.add(current) } trie.trieMap.forEach { (k, v) -> depthFirstTraversal(v, current + k, word) } } fun searchWord(word: String): Boolean { return searchWord(word, 0) } private fun searchWord(word: String, index: Int): Boolean { val letter = word.getOrNull(index) ?: return true if (letter == '.') { // wildcard // Ignore this and try to find any other node that matches next character return trieMap.values.map { it.searchWord(word, index + 1) }.any { it } } else { val nextTrie = trieMap[letter] ?: return false return nextTrie.searchWord(word, index + 1) } } fun branches(): List<String> { val words = mutableListOf<String>() depthFirstTraversal(this, "", words) println(words) return words } } fun main() { run { val trie = Trie() trie.addWord("hello") trie.addWord("word") trie.addWord("woke") trie.addWord("world") assertTrue { trie.searchWord("hello") } assertTrue { trie.searchWord("word") } assertFalse { trie.searchWord("worry") } assertTrue { trie.searchWord("wo.d") } assertTrue { trie.searchWord("wor.d") } trie.addWord("wore") trie.addWord("wop") trie.addWord("won") trie.addWord("worst") assertTrue { trie.searchWord("wor.t") } assertFalse { trie.searchWord("wor.ts") } assertFalse { trie.searchWord("worm") } trie.addWord("worm") assertTrue { trie.searchWord("worm") } assertTrue { trie.searchWord("w.rm") } assertTrue { trie.searchWord("w..m") } assertTrue { trie.searchWord("...m") } assertFalse { trie.searchWord("...ms") } assertTrue { trie.searchWord("w...") } } run { val trie = Trie() trie.addWord("egg") trie.addWord("eggplant") trie.addWord("eggshell") trie.addWord("elephant") trie.addWord("eleanor") trie.addWord("eleven") trie.addWord("elegant") trie.addWord("evil") assertTrue { trie.searchWord("egg") } assertTrue { trie.searchWord("eg.") } assertTrue { trie.searchWord("eg.p.a.t") } assertTrue { trie.searchWord("elep.a.t") } assertFalse { trie.searchWord("elope") } assertFalse { trie.searchWord("el.phat") } assertFalse { trie.searchWord("elev.ns") } assertFalse { trie.searchWord("elevens") } assertFalse { trie.searchWord("eleventh") } assertFalse { trie.searchWord("eleven.") } trie.addWord("watch") trie.addWord("witch") trie.addWord("with") trie.addWord("without") trie.addWord("withe") trie.addWord("wither") trie.addWord("wit") trie.addWord("withering") trie.branches() } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
4,365
algorithms
MIT License
src/main/kotlin/me/grison/aoc/y2022/Day09.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2022 import me.grison.aoc.* class Day09 : Day(9, 2022) { override fun title() = "Rope Bridge" override fun partOne() = solve(2) override fun partTwo() = solve(10) private fun solve(ropeSize: Int): Int { val seen = mutableSetOf<Position>() val movements = mapOf("R" to p(0, 1), "L" to p(0, -1), "D" to p(1, 0), "U" to p(-1, 0)) val rope = mutableList(ropeSize, p(0, 0)) fun distance(predicate: Boolean, head: Int, tail: Int) = if (predicate) (head + tail) / 2 else head inputList .map { it.words() } .forEach { (dir, amount) -> repeat(amount.toInt()) { rope[0] += movements.at(dir) (1 until ropeSize).forEach { i -> val (head, tail) = p(rope[i - 1], rope[i]) val diff = (head - tail).abs() if (diff.max() == 2) rope[i] = tail.first(distance(diff.first == 2, head.first, tail.first)) .second(distance(diff.second == 2, head.second, tail.second)) } seen.add(rope.last()) } } return seen.size } }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
1,271
advent-of-code
Creative Commons Zero v1.0 Universal
src/Day10.kt
tbilou
572,829,933
false
{"Kotlin": 40925}
fun main() { val day = "Day10" fun part1(input: List<String>): Int { val sim = Simulator(input) var cycle = 0 var total = 0 while (cycle < 240) { cycle++ if (cycle in listOf(20, 60, 100, 140, 180, 220)) { total += cycle * sim.register } sim.simulateStep() } return total } fun part2(input: List<String>) { val sim = Simulator(input) var cycle = 0 var pixel = 1 var sprite = 0 var tv = List(6) { mutableListOf("") }.map { list -> repeat(39) { list.add("") } list } while (cycle < 240) { cycle++ val visible = sprite.visible(pixel) tv.draw(pixel, visible) sim.simulateStep() pixel += 1 sprite = sim.register } tv.display() } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") check(part1(testInput) == 13140) // check(part2(testInput) == 0) val input = readInput("$day") println(part1(input)) println(part2(input)) } private fun List<MutableList<String>>.display() { this.forEach { row -> row.forEach { s -> print(s) } println() } } private fun List<MutableList<String>>.draw(pixel: Int, visible: Boolean) { val rowsize = 40 val row = (pixel - 1) / rowsize var col = (pixel - 1) % rowsize this[row][col] = if (visible) "#" else "." } private fun Int.visible(pixel: Int): Boolean { var p = (pixel - 1) % 40 return (this == p || this - 1 == p || this + 1 == p) } private class Simulator(input: List<String>){ var instructions = expandInstructions(input) var register = 1 var pointer = 0 fun simulateStep(): Int { val i = instructions[pointer] if (i != "noop") { val v = i.substringAfter(" ").toInt() register += v } pointer++ return register } fun expandInstructions(input: List<String>): MutableList<String> { var newInstructions = mutableListOf<String>() input.forEach { instruction -> if (instruction == "noop") { newInstructions.add(instruction) } else { newInstructions.add("noop") newInstructions.add(instruction) } } return newInstructions } }
0
Kotlin
0
0
de480bb94785492a27f020a9e56f9ccf89f648b7
2,525
advent-of-code-2022
Apache License 2.0
year2021/day15/part1/src/main/kotlin/com/curtislb/adventofcode/year2021/day15/part1/Year2021Day15Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 15: Chiton --- You've almost reached the exit of the cave, but the walls are getting closer together. Your submarine can barely still fit, though; the main problem is that the walls of the cave are covered in chitons, and it would be best not to bump any of them. The cavern is large, but has a very low ceiling, restricting your motion to two dimensions. The shape of the cavern resembles a square; a quick scan of chiton density produces a map of risk level throughout the cave (your puzzle input). For example: ``` 1163751742 1381373672 2136511328 3694931569 7463417111 1319128137 1359912421 3125421639 1293138521 2311944581 ``` You start in the top left position, your destination is the bottom right position, and you cannot move diagonally. The number at each position is its risk level; to determine the total risk of an entire path, add up the risk levels of each position you enter (that is, don't count the risk level of your starting position unless you enter it; leaving it adds no risk to your total). Your goal is to find a path with the lowest total risk. In this example, a path with the lowest total risk is highlighted here: ``` 1 1 2136511 15 1 13 2 3 21 1 ``` The total risk of this path is 40 (the starting position is never entered, so its risk is not counted). What is the lowest total risk of any path from the top left to the bottom right? */ package com.curtislb.adventofcode.year2021.day15.part1 import com.curtislb.adventofcode.year2021.day15.chiton.RiskLevelMap import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2021, day 15, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long? { val riskLevelMap = RiskLevelMap.fromFile(inputPath.toFile()) return riskLevelMap.findMinimalPathRisk() } fun main() { when (val solution = solve()) { null -> println("No solution") else -> println(solution) } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,078
AdventOfCode
MIT License
src/Day04.kt
rxptr
572,717,765
false
{"Kotlin": 9737}
fun main() { fun parsInput(inputLines: List<String>) = inputLines.map { it.split(',').map { id -> id.split('-') .let { (a, b) -> a.toInt() .. b.toInt() } }.let { (f, s) -> Pair(f, s) } } fun part1(input: List<String>) = parsInput(input).count { val common = it.first intersect it.second (common.isNotEmpty() && ((it.first - common).isEmpty() || (it.second - common).isEmpty())) } fun part2(input: List<String>) = parsInput(input).count { (it.first intersect it.second).isNotEmpty() } val testInput = readInputLines("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInputLines("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
989ae08dd20e1018ef7fe5bf121008fa1c708f09
790
aoc2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SmallestCommonElement.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Arrays.binarySearch import kotlin.math.min private const val LIMIT = 10000 private const val ARRAY_SIZE = LIMIT + 1 private const val NO_SOLUTION = -1 // returns when solution not found /** * Find Smallest Common Element in All Rows * @see <a href="https://leetcode.com/problems/find-smallest-common-element-in-all-rows/">Source</a> */ fun interface SmallestCommonElement { operator fun invoke(mat: Array<IntArray>): Int } /** * Approach 1: Count Elements * Time complexity: O(nm), where nn and mm are the number of rows and columns. * Space complexity: O(k), where k is the number of unique elements. */ class SCECountElements : SmallestCommonElement { override operator fun invoke(mat: Array<IntArray>): Int { val count = IntArray(ARRAY_SIZE) val n: Int = mat.size val m: Int = mat[0].size for (i in 0 until n) { for (j in 0 until m) { ++count[mat[i][j]] } } for (k in 1..LIMIT) { if (count[k] == n) { return k } } return NO_SOLUTION } } /** * Approach 1: Count Elements Improved * Time complexity: O(nm), where nn and mm are the number of rows and columns. * Space complexity: O(1). */ class SCECountElementsImproved : SmallestCommonElement { override operator fun invoke(mat: Array<IntArray>): Int { val count = IntArray(ARRAY_SIZE) val n: Int = mat.size val m: Int = mat[0].size for (j in 0 until m) { for (i in 0 until n) { if (++count[mat[i][j]] == n) { return mat[i][j] } } } return NO_SOLUTION } } /** * Approach 2: Binary Search * Time complexity: O(mn log m). * Space complexity: O(1). */ class SCEBinarySearch : SmallestCommonElement { override operator fun invoke(mat: Array<IntArray>): Int { val n: Int = mat.size val m: Int = mat[0].size for (j in 0 until m) { var found = true var i = 1 while (i < n && found) { found = binarySearch(mat[i], mat[0][j]) >= 0 ++i } if (found) { return mat[0][j] } } return NO_SOLUTION } } /** * Approach 2: Binary Search Improved * Time complexity: O(mn log m). * Space complexity: O(n). */ class SCEBinarySearchImproved : SmallestCommonElement { override operator fun invoke(mat: Array<IntArray>): Int { val n: Int = mat.size val m: Int = mat[0].size val pos = IntArray(n) for (j in 0 until m) { var found = true var i = 1 while (i < n && found) { pos[i] = binarySearch(mat[i], pos[i], m, mat[0][j]) if (pos[i] < 0) { found = false pos[i] = -pos[i] - 1 if (pos[i] >= m) { return NO_SOLUTION } } ++i } if (found) { return mat[0][j] } } return NO_SOLUTION } } /** * Approach 3: Row Positions * Time complexity: O(nm). * Space complexity: O(n). */ class SCERowPositions : SmallestCommonElement { override operator fun invoke(mat: Array<IntArray>): Int { val n: Int = mat.size val m: Int = mat[0].size val pos = IntArray(n) var curMax = 0 var cnt = 0 while (true) { for (i in 0 until n) { while (pos[i] < m && mat[i][pos[i]] < curMax) { ++pos[i] } if (pos[i] >= m) { return NO_SOLUTION } if (mat[i][pos[i]] != curMax) { cnt = 1 curMax = mat[i][pos[i]] } else if (++cnt == n) { return curMax } } } } } /** * Approach 3: Row Positions Improved * Time complexity: O(nm). * Space complexity: O(n). */ class SCERowPositionsImproved : SmallestCommonElement { override operator fun invoke(mat: Array<IntArray>): Int { val n: Int = mat.size val m: Int = mat[0].size val pos = IntArray(n) var curMax = 0 var cnt = 0 while (true) { for (i in 0 until n) { pos[i] = metaSearch(mat[i], pos[i], curMax) if (pos[i] >= m) { return NO_SOLUTION } if (mat[i][pos[i]] != curMax) { cnt = 1 curMax = mat[i][pos[i]] } else if (++cnt == n) { return curMax } } } } private fun metaSearch(row: IntArray, pos: Int, value: Int): Int { var p = pos val sz = row.size var d = 1 while (p < sz && row[p] < value) { d = d shl 1 if (row[min(p + d, sz - 1)] >= value) { d = 1 } p += d } return p } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,855
kotlab
Apache License 2.0
src/Day20.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
import kotlin.system.exitProcess fun main() { val input = readInput("Day20").associate { val (name, out) = it.split(" -> ") name to out.split(", ").toSet() } fun withSign(s: String) = when { input.keys.contains("%$s") -> "%$s" input.keys.contains("&$s") -> "&$s" else -> s } println("flowchart TD") println(input.entries.sortedBy { if (it.key == "broadcaster") 0 else if (it.key == "&vr") 2 else 1 }.flatMap { (from, to) -> to.map { "$from --> ${withSign(it)}{${withSign(it)}}" } }.joinToString("\n")) val flipFlop = HashSet<String>() val conjLow = input.keys.filter { it.startsWith("&") }.map { it.removePrefix("&") }.associateWith { conj -> input.filter { conj in it.value }.map { it.key.removePrefix("&").removePrefix("%") }.toMutableSet() } var res1 = 0 var res2 = 0 for (step in 1..1000) { val queue = ArrayDeque<Triple<String, String, Boolean>>() fun send(from: String, to: Collection<String>, v: Boolean) = to.forEach { queue.add(Triple(from, it, v)) if (v) res2++ else res1++ if (it == "rx" && !v) { println("2:$step") exitProcess(0) } } send("button", listOf("broadcaster"), false) while (queue.isNotEmpty()) { val (s0,s1,v) = queue.removeFirst() input[s1]?.let { s2 -> send(s1, s2, v) } input["%$s1"]?.let { s2 -> if (!v) { if (flipFlop.contains(s1)) { flipFlop.remove(s1) send(s1, s2, false) } else { flipFlop.add(s1) send(s1, s2, true) } } } input["&$s1"]?.let { s2 -> val inputs = conjLow[s1]!! if (v) { inputs.remove(s0) } else { inputs.add(s0) } send(s1, s2, inputs.isNotEmpty()) } } } println(res1.toLong() * res2) val res3 = input["broadcaster"]!!.map { start -> var cycle = 0 var p = 1 var cur = start while (true) { val tos = input["%$cur"]!! if (tos.size == 2) { cycle = cycle or p cur = tos.find { "%$it" in input }!! } else { if ("%"+tos.first() !in input) break cur = tos.first() } p = p shl 1 } cycle or p }.fold(1L) { a, b -> a * b} println(res3) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
2,746
advent-of-code-kotlin
Apache License 2.0
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/char.kt
swanandvk
284,610,632
true
{"Kotlin": 2715433, "HTML": 423, "Java": 145}
package io.kotest.property.arbitrary import io.kotest.property.Arb /** * Returns a [Arb] that generates randomly-chosen Chars. Custom characters can be generated by * providing CharRanges. Distribution will be even across the ranges of Chars. * For example: * Gen.char('A'..'C', 'D'..'E') * Ths will choose A, B, C, D, and E each 20% of the time. */ fun Arb.Companion.char(range: CharRange, vararg ranges: CharRange): Arb<Char> { return Arb.char(listOf(range) + ranges) } /** * Returns a [Arb] that generates randomly-chosen Chars. Custom characters can be generated by * providing a list of CharRanges. Distribution will be even across the ranges of Chars. * For example: * Gen.char(listOf('A'..'C', 'D'..'E') * Ths will choose A, B, C, D, and E each 20% of the time. * * If no parameter is given, ASCII characters will be generated. */ fun Arb.Companion.char(ranges: List<CharRange> = CharSets.BASIC_LATIN): Arb<Char> { require(ranges.all { !it.isEmpty() }) { "Ranges cannot be empty" } require(ranges.isNotEmpty()) { "List of ranges must have at least one range" } fun makeRangeWeightedGen(): Arb<CharRange> { val weightPairs = ranges.map { range -> val weight = range.last.toInt() - range.first.toInt() + 1 Pair(weight, range) } return Arb.choose(weightPairs[0], weightPairs[1], *weightPairs.drop(2).toTypedArray()) } // Convert the list of CharRanges into a weighted Gen in which // the ranges are chosen from the list using the length of the // range as the weight. val arbRange: Arb<CharRange> = if (ranges.size == 1) Arb.constant(ranges.first()) else makeRangeWeightedGen() return arbRange.flatMap { charRange -> arbitrary { charRange.random(it.random) } } } private object CharSets { val CONTROL = listOf('\u0000'..'\u001F', '\u007F'..'\u007F') val WHITESPACE = listOf('\u0020'..'\u0020', '\u0009'..'\u0009', '\u000A'..'\u000A') val BASIC_LATIN = listOf('\u0021'..'\u007E') }
5
Kotlin
0
1
e176cc3e14364d74ee593533b50eb9b08df1f5d1
2,003
kotest
Apache License 2.0
src/main/kotlin/solutions/day10/Day10.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day10 import solutions.Solver class Day10 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { var crt = "" var checkpoint = if (!partTwo) { 20 } else { 40 } var x = 1 var cycles = 0 val readings = mutableListOf<Int>() for (l in input) { if (l.startsWith("addx")) { val nbr = l.removePrefix("addx ").toInt() crt = printPixel(crt, cycles, x) cycles++ if (cycles == checkpoint) { val pair = performCheckpoint(readings, x, checkpoint, crt) checkpoint = pair.first crt = pair.second } crt = printPixel(crt, cycles, x) cycles++ if (cycles == checkpoint) { val pair = performCheckpoint(readings, x, checkpoint, crt) checkpoint = pair.first crt = pair.second } x += nbr } else if (l == "noop") { crt = printPixel(crt, cycles, x) cycles++ if (cycles == checkpoint) { val pair = performCheckpoint(readings, x, checkpoint, crt) checkpoint = pair.first crt = pair.second } } } if (!partTwo) { return readings.sum().toString() } return crt } private fun performCheckpoint( readings: MutableList<Int>, x: Int, checkpoint: Int, crt: String ): Pair<Int, String> { var checkpoint1 = checkpoint var crt1 = crt readings.add(x * checkpoint1) checkpoint1 += 40 crt1 += "\n" return Pair(checkpoint1, crt1) } private fun printPixel(crt: String, cycles: Int, x: Int): String { var crt1 = crt val cyclesRelative = cycles % 40 crt1 += if ((x - 1) == cyclesRelative || x == cyclesRelative || (x + 1) == cyclesRelative) { "#" } else { "." } return crt1 } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
2,234
Advent-of-Code-2022
MIT License
src/main/kotlin/g1901_2000/s1914_cyclically_rotating_a_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1914_cyclically_rotating_a_grid // #Medium #Array #Matrix #Simulation #2023_06_20_Time_282_ms_(100.00%)_Space_39.6_MB_(100.00%) class Solution { fun rotateGrid(grid: Array<IntArray>, k: Int): Array<IntArray> { rotateInternal(grid, 0, grid[0].size - 1, 0, grid.size - 1, k) return grid } private fun rotateInternal(grid: Array<IntArray>, left: Int, right: Int, up: Int, bottom: Int, k: Int) { if (left > right || up > bottom) { return } val loopLen = (right - left + 1) * 2 + (bottom - up + 1) * 2 - 4 val realK = k % loopLen if (realK != 0) { rotateLayer(grid, left, right, up, bottom, realK) } rotateInternal(grid, left + 1, right - 1, up + 1, bottom - 1, k) } private fun rotateLayer(grid: Array<IntArray>, left: Int, right: Int, up: Int, bottom: Int, k: Int) { val startPoint = intArrayOf(up, left) val loopLen = (right - left + 1) * 2 + (bottom - up + 1) * 2 - 4 val arr = IntArray(loopLen) var idx = 0 var currPoint: IntArray? = startPoint var startPointAfterRotation: IntArray? = null while (idx < arr.size) { arr[idx] = grid[currPoint!![0]][currPoint[1]] idx++ currPoint = getNextPosCC(left, right, up, bottom, currPoint) if (idx == k) { startPointAfterRotation = currPoint } } idx = 0 currPoint = startPointAfterRotation if (currPoint != null) { while (idx < arr.size) { grid[currPoint!![0]][currPoint[1]] = arr[idx] idx++ currPoint = getNextPosCC(left, right, up, bottom, currPoint) } } } private fun getNextPosCC(left: Int, right: Int, up: Int, bottom: Int, curr: IntArray?): IntArray { val x = curr!![0] val y = curr[1] return if (x == up && y > left) { intArrayOf(x, y - 1) } else if (y == left && x < bottom) { intArrayOf(x + 1, y) } else if (x == bottom && y < right) { intArrayOf(x, y + 1) } else { intArrayOf(x - 1, y) } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,242
LeetCode-in-Kotlin
MIT License
src/Day13.kt
erwinw
572,913,172
false
{"Kotlin": 87621}
@file:Suppress("MagicNumber") import kotlin.Comparator as KComparator private const val DAY = "13" private const val PART1_CHECK = 13 private const val PART2_CHECK = 140 private enum class Order { RIGHT, WRONG, UNDETERMINED } private sealed interface Lol { class Number(val value: Int) : Lol { override fun toString() = value.toString() } class MyList(val items: List<Lol>) : Lol { override fun toString() = items.joinToString(separator = ",", prefix = "[", postfix = "]") } } private object Parser { private fun demandInput(input: MutableList<Char>, required: Char) { require(input.first() == required) input.removeFirst() } private fun parseLolNumber(input: MutableList<Char>): Lol { var digits = "" while (input.isNotEmpty() && input.first() in '0'..'9') { digits += input.removeFirst() } return Lol.Number(digits.toInt()) } private fun parseLolList(input: MutableList<Char>): Lol { val items = mutableListOf<Lol>() demandInput(input, '[') if (input.isNotEmpty() && input.first() != ']') { items += parse(input) while (input.isNotEmpty() && input.first() == ',') { demandInput(input, ',') items += parse(input) } } demandInput(input, ']') return Lol.MyList(items.toList()) } fun parse(input: MutableList<Char>): Lol = when (input.first()) { '[' -> parseLolList(input) in '0'..'9' -> parseLolNumber(input) else -> throw IllegalArgumentException("Unexpected character '${input.first()}'; expected '[' or digit") } } private object Comparator { fun compareNumbers( left: Lol.Number, right: Lol.Number, ) = when { left.value < right.value -> Order.RIGHT left.value > right.value -> Order.WRONG else -> Order.UNDETERMINED } fun compareLists( left: Lol.MyList, right: Lol.MyList, ): Order { for (index in 0..Int.MAX_VALUE) { val leftItem = left.items.getOrNull(index) val rightItem = right.items.getOrNull(index) if (leftItem == null && rightItem == null) { break } leftItem ?: return Order.RIGHT rightItem ?: return Order.WRONG val compared = compare(leftItem, rightItem) if (compared != Order.UNDETERMINED) { return compared } } return Order.UNDETERMINED } fun compare( left: Lol, right: Lol, ): Order = when { left is Lol.Number && right is Lol.Number -> compareNumbers(left, right) left is Lol.Number && right is Lol.MyList -> compareLists(Lol.MyList(listOf(left)), right) left is Lol.MyList && right is Lol.Number -> compareLists(left, Lol.MyList(listOf(right))) left is Lol.MyList && right is Lol.MyList -> compareLists(left, right) else -> throw IllegalArgumentException("Unexpected unsupported Lol types") } } private fun part1(input: List<String>): Int { val listPairs = input.chunked(3) .map { (a, b) -> val lolA = Parser.parse(a.toMutableList()) val lolB = Parser.parse(b.toMutableList()) Pair(lolA, lolB) } val correctItems = mutableListOf<Int>() listPairs.forEachIndexed { index, (lolLeft, lolRight) -> if (Comparator.compare(lolLeft, lolRight) == Order.RIGHT) { correctItems += (1 + index) } } return correctItems.sum() } private fun part2(input: List<String>): Int { val divider2 = Lol.MyList(listOf(Lol.MyList(listOf(Lol.Number(2))))) val divider6 = Lol.MyList(listOf(Lol.MyList(listOf(Lol.Number(6))))) val packets = input.chunked(3) .flatMap { (a, b) -> val lolA = Parser.parse(a.toMutableList()) val lolB = Parser.parse(b.toMutableList()) listOf(lolA, lolB) } + divider2 + divider6 val sorted = packets.sortedWith { o1, o2 -> when (Comparator.compare(o1, o2)) { Order.RIGHT -> -1 Order.WRONG -> 1 Order.UNDETERMINED -> 0 } } val idxDivider2 = sorted.indexOf(divider2) + 1 val idxDivider6 = sorted.indexOf(divider6) + 1 return idxDivider2 * idxDivider6 } fun main() { println("Day $DAY") // test if implementation meets criteria from the description, like: val testInput = readInput("Day${DAY}_test") check(part1(testInput).also { println("Part1 output: $it") } == PART1_CHECK) check(part2(testInput).also { println("Part2 output: $it") } == PART2_CHECK) val input = readInput("Day$DAY") println("Part1 final output: ${part1(input)}") println("Part2 final output: ${part2(input)}") }
0
Kotlin
0
0
57cba37265a3c63dea741c187095eff24d0b5381
4,955
adventofcode2022
Apache License 2.0
solutions/aockt/y2016/Y2016D08.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2016 import aockt.util.OcrDecoder import aockt.y2016.Y2016D08.Instruction.* import io.github.jadarma.aockt.core.Solution object Y2016D08 : Solution { /** An instruction for building the display. */ private sealed class Instruction { /** Turns on all of the pixels in a rectangle at the top-left of the screen of the given [width] x [height]. */ data class Rectangle(val width: Int, val height: Int) : Instruction() /** Shifts all the pixels in the given [row] by [amount] pixels to the right, looping around. */ data class RotateRow(val row: Int, val amount: Int) : Instruction() /** Shifts all the pixels in the given [column] by [amount] pixels down, looping around. */ data class RotateColumn(val column: Int, val amount: Int) : Instruction() companion object { private val rectRegex = Regex("""rect (\d+)x(\d+)""") private val rowRegex = Regex("""rotate row y=(\d+) by (\d+)""") private val colRegex = Regex("""rotate column x=(\d+) by (\d+)""") /** Returns the [Instruction] described by the [input], throwing [IllegalArgumentException] if invalid. */ fun parse(input: String): Instruction { rectRegex.matchEntire(input)?.destructured?.let { (x, y) -> return Rectangle(x.toInt(), y.toInt()) } rowRegex.matchEntire(input)?.destructured?.let { (y, v) -> return RotateRow(y.toInt(), v.toInt()) } colRegex.matchEntire(input)?.destructured?.let { (x, v) -> return RotateColumn(x.toInt(), v.toInt()) } throw IllegalArgumentException("Invalid input.") } } } /** The pixel state of a card swiper display. */ private class Display(val width: Int, val height: Int) { private val grid = Array(height) { BooleanArray(width) { false } } /** Returns the number of pixels that are currently on. */ fun litCount() = grid.sumOf { row -> row.count { it } } /** Formats a string according to the display state, meant to be printed. */ fun toDisplayString() = buildString { grid.forEach { row -> row.map { if (it) '#' else '.' }.forEach { append(it) } appendLine() } } /** Mutates the state of this display by applying the given [instruction]. */ fun apply(instruction: Instruction) = when (instruction) { is Rectangle -> { for (y in 0 until instruction.height) { for (x in 0 until instruction.width) { grid[y][x] = true } } } is RotateColumn -> { val offset = instruction.amount % height val column = instruction.column val temp = Array(offset) { grid[grid.size - offset + it][column] } for (row in (grid.size - offset - 1) downTo 0) { grid[row + offset][column] = grid[row][column] } for (row in 0 until offset) { grid[row][column] = temp[row] } } is RotateRow -> { val offset = instruction.amount % width val row = instruction.row val temp = grid[row].copyOfRange(grid[row].size - offset, grid[row].size) grid[row].copyInto(grid[row], offset, 0, grid[row].size - offset) temp.copyInto(grid[row]) Unit } } } /** Builds the [Display] state by following the instructions contained in the [input]. */ private fun buildDisplay(input: String): Display = Display(50, 6).apply { input.lineSequence() .map { Instruction.parse(it) } .forEach(::apply) } override fun partOne(input: String): Int = buildDisplay(input).litCount() override fun partTwo(input: String): String = buildDisplay(input).toDisplayString().let(OcrDecoder::decode) }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
4,065
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/solutions/day13/Day13.kt
Dr-Horv
112,381,975
false
null
package solutions.day13 import solutions.Solver data class Scanner(val depth: Int, val range: Int) { fun positionAt(t: Int) = t % ((range-1) * 2) fun caught(t: Int) = positionAt(t) == 0 fun severity() = depth * range } class Day13 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val scanners = input.map { val (depth, range) = it.split(":").map(String::trim) Scanner(depth.toInt(), range.toInt()) } if(!partTwo) { return doRun(scanners, 0).sum().toString() } var start = 0 while (true) { val severities = doRun(scanners, start) if(severities.isEmpty()) { return start.toString() } start++ } } private fun doRun(scanners: List<Scanner>, start: Int): MutableList<Int> { val severities = mutableListOf<Int>() scanners.forEach { scanner -> if (scanner.caught(start + scanner.depth)) { severities.add(scanner.severity()) } } return severities } }
0
Kotlin
0
2
975695cc49f19a42c0407f41355abbfe0cb3cc59
1,139
Advent-of-Code-2017
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/RemoveAllAdjacentDuplicates.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack /** * 1047. Remove All Adjacent Duplicates In String * @see <a href="https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/">Source</a> */ fun interface RemoveAllAdjacentDuplicatesStrategy { operator fun invoke(s: String): String } class RemoveAllAdjacentDuplicatesArray : RemoveAllAdjacentDuplicatesStrategy { override operator fun invoke(s: String): String { var i = 0 val n = s.length val res = s.toCharArray() var j = 0 while (j < n) { res[i] = res[j] if (i > 0 && res[i - 1] == res[i]) { i -= 2 } ++j ++i } return String(res, 0, i) } } class RemoveAllAdjacentDuplicatesStack : RemoveAllAdjacentDuplicatesStrategy { override operator fun invoke(s: String): String { val stack: Stack<Char> = Stack() for (c in s) { if (stack.isNotEmpty() && stack.peek() == c) { stack.pop() } else { stack.push(c) } } val sb = StringBuilder() while (stack.isNotEmpty()) sb.append(stack.pop()) return sb.reverse().toString() } } // Using StringBuilder class RemoveAllAdjacentDuplicatesSB : RemoveAllAdjacentDuplicatesStrategy { override operator fun invoke(s: String): String { val sb = StringBuilder() for (c in s) { val size = sb.length if (size > 0 && sb[size - 1] == c) { sb.deleteCharAt(size - 1) } else { sb.append(c) } } return sb.toString() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,315
kotlab
Apache License 2.0
solutions/src/Day18.kt
khouari1
573,893,634
false
{"Kotlin": 132605, "HTML": 175}
fun main() { fun part1(input: List<String>): Int { val coords = toCoords(input) var count = 0 coords.forEach { (x, y, z) -> val front = CubeCoord(x, y, z - 1) if (front !in coords) { count++ } val back = CubeCoord(x, y, z + 1) if (back !in coords) { count++ } val top = CubeCoord(x, y - 1, z) if (top !in coords) { count++ } val bottom = CubeCoord(x, y + 1, z) if (bottom !in coords) { count++ } val left = CubeCoord(x - 1, y, z) if (left !in coords) { count++ } val right = CubeCoord(x + 1, y, z) if (right !in coords) { count++ } } return count } fun part2(input: List<String>): Int { val coords = toCoords(input) var count = 0 val knownAirPocketCubes = mutableSetOf<CubeCoord>() coords.forEach { (x, y, z) -> val front = CubeCoord(x, y, z - 1) if (front !in knownAirPocketCubes) { val frontInAirPocket = isAirPocket(front, coords, knownAirPocketCubes) if (!frontInAirPocket && front !in coords) { count++ } } val back = CubeCoord(x, y, z + 1) if (back !in knownAirPocketCubes) { val backInAirPocket = isAirPocket(back, coords, knownAirPocketCubes) if (!backInAirPocket && back !in coords) { count++ } } val top = CubeCoord(x, y - 1, z) if (top !in knownAirPocketCubes) { val topInAirPocket = isAirPocket(top, coords, knownAirPocketCubes) if (!topInAirPocket && top !in coords) { count++ } } val bottom = CubeCoord(x, y + 1, z) if (bottom !in knownAirPocketCubes) { val bottomInAirPocket = isAirPocket(bottom, coords, knownAirPocketCubes) if (!bottomInAirPocket && bottom !in coords) { count++ } } val left = CubeCoord(x - 1, y, z) if (left !in knownAirPocketCubes) { val leftInAirPocket = isAirPocket(left, coords, knownAirPocketCubes) if (!leftInAirPocket && left !in coords) { count++ } } val right = CubeCoord(x + 1, y, z) if (right !in knownAirPocketCubes) { val rightInAirPocket = isAirPocket(right, coords, knownAirPocketCubes) if (!rightInAirPocket && right !in coords) { count++ } } } return count } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) } typealias CubeCoord = Triple<Int, Int, Int> private fun toCoords(input: List<String>): Set<CubeCoord> = input.map { line -> val (x, y, z) = line.split(",") CubeCoord(x.toInt(), y.toInt(), z.toInt()) }.toSet() private fun isAirPocket( cube: CubeCoord, coords: Set<CubeCoord>, knownAirPocketCubes: MutableSet<CubeCoord>, ): Boolean { val visited = mutableSetOf<CubeCoord>() val queue = ArrayDeque<CubeCoord>() queue.add(cube) while (queue.isNotEmpty()) { val cubeToCheck = queue.removeFirst() visited.add(cubeToCheck) val (x, y, z) = cubeToCheck val cubesInFront = coords.firstOrNull { (x2, y2, z2) -> x2 == x && y2 == y && z2 < z } val cubesBehind = coords.firstOrNull { (x2, y2, z2) -> x2 == x && y2 == y && z2 > z } val cubesAbove = coords.firstOrNull { (x2, y2, z2) -> x2 == x && y2 > y && z2 == z } val cubesBelow = coords.firstOrNull { (x2, y2, z2) -> x2 == x && y2 < y && z2 == z } val cubesLeft = coords.firstOrNull { (x2, y2, z2) -> x2 < x && y2 == y && z2 == z } val cubesRight = coords.firstOrNull { (x2, y2, z2) -> x2 > x && y2 == y && z2 == z } if (cubesInFront == null || cubesBehind == null || cubesAbove == null || cubesBelow == null || cubesLeft == null || cubesRight == null ) { // not air pocket return false } else { val front = CubeCoord(x, y, z - 1) if (front !in coords && front !in visited) { queue.add(front) visited.add(front) } val back = CubeCoord(x, y, z + 1) if (back !in coords && back !in visited) { queue.add(back) visited.add(back) } val top = CubeCoord(x, y + 1, z) if (top !in coords && top !in visited) { queue.add(top) visited.add(top) } val bottom = CubeCoord(x, y - 1, z) if (bottom !in coords && bottom !in visited) { queue.add(bottom) visited.add(bottom) } val left = CubeCoord(x - 1, y, z) if (left !in coords && left !in visited) { queue.add(left) visited.add(left) } val right = CubeCoord(x + 1, y, z) if (right !in coords && right !in visited) { queue.add(right) visited.add(right) } } } knownAirPocketCubes.addAll(visited) return true }
0
Kotlin
0
1
b00ece4a569561eb7c3ca55edee2496505c0e465
5,857
advent-of-code-22
Apache License 2.0
src/main/aoc2021/Day13.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2021 import AMap import Pos class Day13(input: List<String>) { sealed class Fold(val at: Int) { class Horizontal(at: Int) : Fold(at) class Vertical(at: Int) : Fold(at) } private val paper = AMap() private val folds: List<Fold> init { input.takeWhile { it.isNotBlank() } .map { it.split(",") } .forEach { (x, y) -> paper[Pos(x.toInt(), y.toInt())] = '#' } folds = input.takeLastWhile { it.isNotBlank() } .map { it.substringAfter("fold along ") } .map { it.split("=") } .map { when (it.first()) { "x" -> Fold.Vertical(it.last().toInt()) else -> Fold.Horizontal(it.last().toInt()) } }.toList() } /** * Generic folding function. The part that's not folded starts at 0 and goes to xyMax. xyFoldStart notes * the xy coordinate to read from to be in the part being folded while xyFoldStep say in which direction * to step each iteration. * * Horizontal folds (fold along a horizontal line / y coordinate) has -1 yFoldStep and yFoldStart at 2 * fold point * while xFoldStep is 1 and xFoldStart is 0 as only points along the y-axis should move. * * Vertical folds works the opposite way with -1 xFoldStep and xFoldStart at 2 * fold point. */ private fun genericFold(xMax: Int, xFoldStart: Int, xFoldStep: Int, yMax: Int, yFoldStart: Int, yFoldStep: Int) { for (y in 0..yMax) { for (x in 0..xMax) { val toFold = Pos(xFoldStart + x * xFoldStep, yFoldStart + y * yFoldStep) if (paper[toFold] == '#') { paper[Pos(x, y)] = '#' paper.keys.remove(toFold) } } } } private fun doFold(fold: Fold) { when (fold) { is Fold.Horizontal -> { genericFold( paper.xRange().last, 0, 1, fold.at, fold.at * 2, -1 ) } is Fold.Vertical -> { genericFold( fold.at, fold.at * 2, -1, paper.yRange().last, 0, 1, ) } } } fun solvePart1(): Int { doFold(folds.first()) return paper.keys.size } fun solvePart2(): String { folds.forEach { doFold(it) } return paper.toString(' ') } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,542
aoc
MIT License
src/Day05.kt
Longtainbin
573,466,419
false
{"Kotlin": 22711}
fun main() { val input = readInput("inputDay05") val operations = initOperation(input) fun part1(input: List<String>): String { val stack = initStack(input) for (ope in operations) { for (count in 1..ope[0]) { stack[ope[2] - 1].add(stack[ope[1] - 1].removeLast()) } } val sb = StringBuilder(stack.size) stack.forEach { sb.append(it.last()) } return sb.toString() } fun part2(input: List<String>): String { val stack = initStack(input) for (ope in operations) { val count = ope[0] val source = ope[1] - 1 val dest = ope[2] - 1 val tempStack = mutableListOf<Char>() for (i in 1..count) { tempStack.add(stack[source].removeLast()) } for (i in 1..count) { stack[dest].add(tempStack.removeLast()) } } val sb = StringBuilder(stack.size) stack.forEach { sb.append(it.last()) } return sb.toString() } println(part1(input)) println(part2(input)) } private fun initStack(input: List<String>): Array<MutableList<Char>> { var lineIndex = 0; for (str in input) { if (str.isBlank()) { lineIndex-- break } lineIndex++ } val n = input[lineIndex].trim().split(" ").last().toInt() val result = Array<MutableList<Char>>(n) { arrayListOf() } while (lineIndex > 0) { lineIndex-- val str = input[lineIndex].trim() var charIndex = 0 for (i in 1 until str.length step 4) { if (str[i] in 'A'..'Z') { result[charIndex].add(str[i]) } charIndex++ } } return result } private fun initOperation(input: List<String>): Array<IntArray> { var lineIndex = 0; for (str in input) { if (str.isBlank()) { lineIndex++ break } lineIndex++ } val result = Array<IntArray>(input.size - lineIndex) { IntArray(3) } for (index in lineIndex until input.size) { val strArr = input[index].split(" ") val i = index - lineIndex result[i][0] = strArr[1].toInt() result[i][1] = strArr[3].toInt() result[i][2] = strArr[5].toInt() } return result }
0
Kotlin
0
0
48ef88b2e131ba2a5b17ab80a0bf6a641e46891b
2,387
advent-of-code-2022
Apache License 2.0
Kotlin/problems/0022_partition_labels.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
class Solution { fun partitionLabels(S: String): List<Int> { val lettersIntervals = MutableList<Pair<Int,Int>>(26) { _ -> Pair(Int.MAX_VALUE,Int.MIN_VALUE)} val result = mutableListOf<Int>() for(i in 0 until S.length){ val index = S[i]-'a' if(lettersIntervals[index].first == Int.MAX_VALUE){ lettersIntervals[index] = Pair(i,i) }else{ lettersIntervals[index] = Pair(lettersIntervals[index].first,i) } } val intervals = mutableListOf<Pair<Int,Int>>() val mergedIntervals = mutableListOf<Pair<Int,Int>>() for(inter in lettersIntervals){ if(inter.first != Int.MAX_VALUE){ intervals.add(inter) } } intervals.sortWith(Comparator{ p1: Pair<Int,Int>, p2: Pair<Int,Int> -> if(p1.first == p2.first) p1.second - p2.second else p1.first - p2.first }) var currInterval = intervals.first() for(i in 1 until intervals.size){ val inter = intervals[i] if(currInterval.second>inter.first){ val first = Math.min(currInterval.first,inter.first) val second = Math.max(currInterval.second,inter.second) currInterval = Pair(first,second) }else{ mergedIntervals.add(currInterval) currInterval = inter } } mergedIntervals.add(currInterval) for(inter in mergedIntervals){ result.add(inter.second - inter.first+1) } return result } } fun main(args: Array<String>) { val word = "ababcbacadefegdehijhklij" val sol = Solution() println(sol.partitionLabels(word)) }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
1,788
algorithms
MIT License