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
calendar/day05/Day5.kt
maartenh
572,433,648
false
{"Kotlin": 50914}
package day05 import Day import Lines import java.util.Stack class Day5 : Day() { override fun part1(input: Lines): Any { val stacks = initStacks(input.filter { it.contains('[') }) input.filter { it.contains("move") } .forEach {command -> val move = parseMove(command) stacks.runMove(move) } return stacks.tops().joinToString(separator = "") } override fun part2(input: Lines): Any { val stacks = initStacks(input.filter { it.contains('[') }) input.filter { it.contains("move") } .forEach {command -> val move = parseMove(command) stacks.runMoveGroup(move) } return stacks.tops().joinToString(separator = "") } private fun initStacks(lines: Lines) : Map<Int, Stack<Char>> { val stacks = mutableMapOf<Int, Stack<Char>>() lines.reversed().forEach { line -> for (i in 1 until line.length step 4) { val stackNumber = 1 + (i - 1) / 4 val container = line[i] if (container.isLetter()) { stacks.addContainer(stackNumber, container) } } } return stacks.toMap() } private fun parseMove(line: String): Move { val pattern = Regex("""move (\d+) from (\d+) to (\d+)""") val (count, from, to) = pattern.find(line)!!.destructured return Move(from.toInt(), to.toInt(), count.toInt()) } } private fun MutableMap<Int, Stack<Char>>.addContainer(stackNumber: Int, container: Char) { if (!containsKey(stackNumber)) { put(stackNumber, Stack()) } this[stackNumber]!!.push(container) } private fun Map<Int, Stack<Char>>.runMove(move: Move) { for (i in 1..move.count) { this[move.to]!!.push(this[move.from]!!.pop()) } } private fun Map<Int, Stack<Char>>.runMoveGroup(move: Move) { val holder = Stack<Char>() for (i in 1..move.count) { holder.push(this[move.from]!!.pop()) } for (i in 1..move.count) { this[move.to]!!.push(holder.pop()) } } private fun Map<Int, Stack<Char>>.tops(): List<Char> { return keys.sorted().map { get(it)!!.peek() } } data class Move(val from: Int, val to: Int, val count: Int)
0
Kotlin
0
0
4297aa0d7addcdc9077f86ad572f72d8e1f90fe8
2,328
advent-of-code-2022
Apache License 2.0
2015/src/main/kotlin/com/koenv/adventofcode/Day16.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode object Day16 { public fun getIdOfMatchedSue(input: String, rangedValues: Boolean = false): Int { val aunts = input.lines().map { val result = INSTRUCTION_REGEX.find(it)!! val id = result.groups[1]!!.value.toInt() var children: Int? = null var cats: Int? = null var samoyeds: Int? = null var pomeranians: Int? = null var akitas: Int? = null var vizslas: Int? = null var goldfish: Int? = null var trees: Int? = null var cars: Int? = null var perfumes: Int? = null val rest = result.groups[2]!!.value.trim().split(", ") rest.forEach { val parts = it.split(": ") val key = parts[0] val value = parts[1].toInt() when (key) { "children" -> children = value "cats" -> cats = value "samoyeds" -> samoyeds = value "pomeranians" -> pomeranians = value "akitas" -> akitas = value "vizslas" -> vizslas = value "goldfish" -> goldfish = value "trees" -> trees = value "cars" -> cars = value "perfumes" -> perfumes = value } } Sue(id, children, cats, samoyeds, pomeranians, akitas, vizslas, goldfish, trees, cars, perfumes) } return aunts.find { 3.matches(it.children) && 7.matches(it.cats, greaterThan = rangedValues) && 2.matches(it.samoyeds) && 3.matches(it.pomeranians, fewerThan = rangedValues) && 0.matches(it.akitas) && 0.matches(it.vizslas) && 5.matches(it.goldfish, fewerThan = rangedValues) && 3.matches(it.trees, greaterThan = rangedValues) && 2.matches(it.cars) && 1.matches(it.perfumes) }!!.id } fun Int.matches(actual: Int?, greaterThan: Boolean = false, fewerThan: Boolean = false): Boolean { if (actual == null) { return true } if (greaterThan) { return actual > this } if (fewerThan) { return this > actual } return this == actual } data class Sue( val id: Int, val children: Int?, val cats: Int?, val samoyeds: Int?, val pomeranians: Int?, val akitas: Int?, val vizslas: Int?, val goldfish: Int?, val trees: Int?, val cars: Int?, val perfumes: Int? ) val INSTRUCTION_REGEX = "Sue (\\d+): (.*)".toRegex() }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
2,893
AdventOfCode-Solutions-Kotlin
MIT License
src/main/kotlin/dp/LPS.kt
yx-z
106,589,674
false
null
package dp import util.get import util.max import util.set // Longest Palindrome Subsequence fun main(args: Array<String>) { val A = intArrayOf(1, 5, 2, 6, 6, 5) println(lps(A)) } fun lps(A: IntArray): Int { val n = A.size // dp(i, j): len of lps of A[i..j] // use a 2d array dp[1..n, 1..n] : dp[i, j] = dp(i, j) val dp = Array(n) { IntArray(n) } // space complexity: O(n^2) // base cases: // dp(i, j) = 0 if i > j // = 1 if i = j for (i in 0 until n) { for (j in 0 until n) { if (i == j) { dp[i, j] = 1 } } } // recursive cases: // dp(i, j) = max{ 2 + dp(i + 1, j - 1), dp(i + 1, j), dp(i, j - 1)} if A[i] = A[j] // = max{ dp(i, j - 1), dp(i + 1, j), dp(i, j - 1) } o/w // dependency: dp(i, j) depends on dp(i + 1, j - 1), dp(i + 1, j), and dp(i, j - 1) // that is, left, lower-left, and lower entry // evaluation order: outer loop for i: bottom to top, i.e. n down to 1, // inner loop for j: left to right, i.e. 1 to n for (i in n - 1 downTo 0) { // the following has been evaluated as base cases above // dp[i, j] = 0 for all j < i // dp[i, j] = 1 for all j = i for (j in i + 1 until n) { dp[i, j] = max(dp[i + 1, j - 1], dp[i + 1, j], dp[i, j - 1]) if (A[i] == A[j]) { dp[i, j] = max(dp[i, j], 2 + dp[i + 1, j - 1]) } } } // time complexity: O(n^2) // we want dp[1, n] return dp[0, n - 1] }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,411
AlgoKt
MIT License
src/main/kotlin/util/VersionRange.kt
minecraft-dev
42,327,118
false
null
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2023 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util /** * A [SemanticVersion] range whose [lower] bound is **inclusive** and [upper] bound is **exclusive** (uncapped if `null`) */ data class VersionRange(val lower: SemanticVersion, val upper: SemanticVersion? = null) { /** * Whether this range consists of only one specific version */ val isFixed: Boolean = lower == upper private val displayString: String by lazy { "[$lower,${upper ?: ""})" } init { if (upper != null && !isFixed) { check(lower <= upper) { "Upper bound ($upper) must be greater than lower bound ($lower)" } } } operator fun contains(version: SemanticVersion): Boolean { if (isFixed) { return version == lower } return version >= lower && (upper == null || version < upper) } /** * Produces a [VersionRange] combining the highest [lower] bound and lowest [upper] bound of * `this` and the [other] ranges. * * If this results in an empty intersection, `null` is returned. * * E.g. `[1.6,2)` and `[2.1,2.5)` because `2` in the first range is smaller than `2.1` in the second range */ fun intersect(other: VersionRange): VersionRange? { val highestLowerBound = maxOf(this.lower, other.lower) val lowestUpperBound = minOf(this.upper, other.upper, nullsLast()) if (lowestUpperBound != null && highestLowerBound > lowestUpperBound) { return null } return VersionRange(highestLowerBound, lowestUpperBound) } override fun toString(): String = displayString companion object { /** * Creates a fixed range strictly consisting of the given [version] * @see [isFixed] */ fun fixed(version: SemanticVersion): VersionRange = VersionRange(version, version) } } operator fun VersionRange?.contains(version: SemanticVersion): Boolean = this == null || this.contains(version) infix fun SemanticVersion.until(upperExclusive: SemanticVersion?): VersionRange = VersionRange(this, upperExclusive)
204
Kotlin
152
1,154
36cc3d47f7f39c847c0ebdcbf84980bc7262dab7
2,227
MinecraftDev
MIT License
src/day9/Day9.kt
quinlam
573,215,899
false
{"Kotlin": 31932}
package day9 import utils.Day import kotlin.math.abs /** * Actual answers after submitting; * part1: 5619 * part2: 2376 */ class Day9 : Day<Int, List<Movement>>( testPart1Result = 13, testPart2Result = 1, ) { override fun part1Answer(input: List<Movement>): Int { return trackTail(input, 2) } override fun part2Answer(input: List<Movement>): Int { return trackTail(input, 10) } private fun trackTail(input: List<Movement>, ropeSize: Int): Int { val ropeSegments = List(ropeSize) { Position(0, 0) } val tailVisited = mutableSetOf<Position>() for (movement in input) { ropeSegments[0].move(movement) for (i in 1 until ropeSegments.size) { val segmentMovement = calculateMovement(ropeSegments[i - 1], ropeSegments[i]) ropeSegments[i].move(segmentMovement) } tailVisited.add(ropeSegments.last().copy()) } return tailVisited.size } private fun calculateMovement(head: Position, tail: Position): Movement { if (abs(head.x - tail.x) > 1 || abs(head.y - tail.y) > 1) { return Movement((head.x - tail.x).coerceIn(-1, 1), (head.y - tail.y).coerceIn(-1, 1)) } return Movement(0, 0) } override fun modifyInput(input: List<String>): List<Movement> { return input.map { val instruction = it.split(" ") val direction = instruction[0] val distance = instruction[1].toInt() when (direction) { "L" -> { List(distance) { Movement(-1, 0) } } "R" -> { List(distance) { Movement(1, 0) } } "D" -> { List(distance) { Movement(0, -1) } } "U" -> { List(distance) { Movement(0, 1) } } else -> { throw RuntimeException("Instruction not understood") } } }.flatten() } }
0
Kotlin
0
0
d304bff86dfecd0a99aed5536d4424e34973e7b1
2,111
advent-of-code-2022
Apache License 2.0
solutions/src/Day01.kt
khouari1
573,893,634
false
{"Kotlin": 132605, "HTML": 175}
fun main() { fun part1(input: List<String>): Int { var leaderCalories = 0 var runningTotal = 0 input.forEach { line -> if (line == "") { if (runningTotal > leaderCalories) { leaderCalories = runningTotal } runningTotal = 0 } else { runningTotal += line.toInt() } } return leaderCalories } fun part2(input: List<String>): Int { val allElves = mutableListOf<Int>() var runningTotal = 0 input.forEach { line -> if (line == "") { allElves += runningTotal runningTotal = 0 } else { runningTotal += line.toInt() } } return allElves.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
b00ece4a569561eb7c3ca55edee2496505c0e465
1,107
advent-of-code-22
Apache License 2.0
2020/kotlin/src/main/kotlin/io/franmosteiro/aoc2020/Day04.kt
franmosteiro
433,734,642
false
{"Kotlin": 27170, "Ruby": 16611, "Shell": 389}
package io.franmosteiro.aoc2020 /** * Advent of Code 2020 - Day 4: Passport Processing - * Problem Description: http://adventofcode.com/2020/day/4 */ class Day04(input: String) { private val passports = input.split("\\n\\n".toRegex()).map { line -> line.split("\\s".toRegex()).associate { val (field, value) = it.split(":") field to value } } fun resolvePartOne(): Int { val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") return passports.count { passport -> requiredFields.all { it in passport } } } fun resolvePartTwo(): Int = passports.count { valid(it) } private fun valid(field: Map<String, String>): Boolean { return field["byr"]?.toIntOrNull() in 1920..2002 && field["iyr"]?.toIntOrNull() in 2010..2020 && field["eyr"]?.toIntOrNull() in 2020..2030 && field["ecl"] in listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") && field["pid"]?.matches("\\d{9}".toRegex()) == true && field["hcl"]?.matches("#[0-9a-f]{6}".toRegex()) == true && when (field["hgt"]?.takeLast(2)) { "cm" -> field["hgt"]?.dropLast(2)?.toIntOrNull() in 150..193 "in" -> field["hgt"]?.dropLast(2)?.toIntOrNull() in 59..76 else -> false } } }
0
Kotlin
0
0
dad555d9cd0c3060c4b1353c7c6f170aa340c285
1,423
advent-of-code
MIT License
src/main/kotlin/github/walkmansit/aoc2020/Day24.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 class Day24(val input: List<String>) : DayAoc<Int, Int> { class Floor { private val deltaForSideMap = mapOf( "e" to Pair(1, 0), "se" to Pair(0, 1), "sw" to Pair(-1, 1), "w" to Pair(-1, 0), "nw" to Pair(0, -1), "ne" to Pair(1, -1) ) private var tilesSet: MutableSet<Pair<Int, Int>> = mutableSetOf() fun addRoute(route: String) { fun getDirectionsFromRoute(route: String) = sequence { var i = 0 do { val candidate = route[i] if (candidate != 'n' && candidate != 's') yield(candidate.toString()) else { yield(candidate.toString() + route[++i]) } i++ } while (i != route.length) } var current = 0 to 0 for (direction in getDirectionsFromRoute(route)) { val delta = deltaForSideMap[direction]!! current = current.first + delta.first to current.second + delta.second } if (!tilesSet.contains(current)) { tilesSet.add(current) } else tilesSet.remove(current) } fun turnOneDay() { fun countBlackNeighbors(current: Pair<Int, Int>): Int { var sum = 0 for (direction in deltaForSideMap.values) { val candidate = current.first + direction.first to current.second + direction.second if (tilesSet.contains(candidate)) sum++ } return sum } val blackCountForWhiteTile: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() val buffer: MutableSet<Pair<Int, Int>> = mutableSetOf() for (blackTile in tilesSet) { for (direction in deltaForSideMap.values) { val candidate = blackTile.first + direction.first to blackTile.second + direction.second if (!tilesSet.contains(candidate)) { if (!blackCountForWhiteTile.containsKey(candidate)) blackCountForWhiteTile[candidate] = 1 else blackCountForWhiteTile[candidate] = blackCountForWhiteTile[candidate]!! + 1 } } val blackNeighbors = countBlackNeighbors(blackTile) if (blackNeighbors == 1 || blackNeighbors == 2) { buffer.add(blackTile) } } for (whiteForTurn in blackCountForWhiteTile.filterValues { it == 2 }) { buffer.add(whiteForTurn.key) } tilesSet = buffer } fun countBlackTiles(): Int { return tilesSet.count() } } override fun getResultPartOne(): Int { val floor = Floor() for (route in input) { floor.addRoute(route) } return floor.countBlackTiles() } override fun getResultPartTwo(): Int { val floor = Floor() for (route in input) { floor.addRoute(route) } repeat(100) { floor.turnOneDay() } return floor.countBlackTiles() } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
3,454
AdventOfCode2020
MIT License
src/main/kotlin/Day13.kt
clechasseur
267,632,210
false
null
import org.clechasseur.adventofcode2016.Direction import org.clechasseur.adventofcode2016.Pt import org.clechasseur.adventofcode2016.dij.Dijkstra import org.clechasseur.adventofcode2016.dij.Graph import org.clechasseur.adventofcode2016.manhattan object Day13 { private const val input = 1362 fun part1(): Int { val (dist, _) = Dijkstra.build(SpaceGraph(), Pt(1, 1)) return dist[Pt(31, 39)]!!.toInt() } fun part2(): Int = Dijkstra.build(SpaceGraph(), Pt(1, 1)).dist.values.count { it <= 50 } private val Pt.passable: Boolean get() = (x * x + 3 * x + 2 * x * y + y + y * y + input).toString(2).count { it == '1' } % 2 == 0 private class SpaceGraph : Graph<Pt> { override fun allPassable(): List<Pt> = (0..120).flatMap { y -> (0..120).map { x -> Pt(x, y) } }.filter { it.passable } override fun neighbours(node: Pt): List<Pt> = Direction.displacements.map { node + it }.filter { it.x >= 0 && it.y >= 0 && it.passable } override fun dist(a: Pt, b: Pt): Long = manhattan(a, b).toLong() } }
0
Kotlin
0
0
120795d90c47e80bfa2346bd6ab19ab6b7054167
1,128
adventofcode2016
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2023/Day17.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import ch.ranil.aoc.AbstractDay import ch.ranil.aoc.PrintColor import ch.ranil.aoc.aoc2023.Direction.* import ch.ranil.aoc.print import ch.ranil.aoc.printColor import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day17 : AbstractDay() { @Test fun part1Test() { assertEquals(102, compute1(testInput)) } @Test fun neighborsTest() { SearchState(Point(0, 0), E, sameDirectionCount = 0).let { assertEquals(it.neighbors(), it.neighbors2()) } SearchState(Point(0, 0), E, sameDirectionCount = 1).let { assertEquals(it.neighbors(), it.neighbors2()) } SearchState(Point(0, 0), E, sameDirectionCount = 2).let { assertEquals(it.neighbors(), it.neighbors2()) } SearchState(Point(0, 0), E, sameDirectionCount = 3).let { assertEquals(it.neighbors(), it.neighbors2()) } SearchState(Point(0, 1), S, sameDirectionCount = 0).let { assertEquals(it.neighbors(), it.neighbors2()) } } @Test fun part1CompareWithTestSolution() { val directions: List<Direction> = listOf( E, E, S, E, E, E, N, E, E, E, S, S, E, E, S, S, E, S, S, S, E, S, S, S, W, S, S, E ) val heatData = mutableListOf(HeatData(0, listOf(Point(0, 0)))) directions.forEach { d -> val h = heatData.last() val p = h.path.single().move(d) val v = testInput[p.y][p.x].digitToInt() heatData.add(HeatData(h.heatLoss + v, listOf(p))) } testInput.print { point, c -> if (heatData.map { it.path.single() }.contains(point)) { printColor(PrintColor.GREEN, c) } else { print(c) } } println() heatData.forEach { println("${it.path.single()}: ${it.heatLoss}") } } @Test fun part1Puzzle() { assertEquals(0, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(0, compute2(testInput)) } @Test fun part2Puzzle() { assertEquals(0, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { val graph = input.map { line -> line.map { it.digitToInt() } } val start = Point(0, 0) val end = Point(graph.first().size - 1, graph.size - 1) val (minHeat, path) = findShortestPath(start, end, graph) input.print { point, c -> if (path.contains(point) || point == end) { printColor(PrintColor.GREEN, c) } else { print(c) } } return minHeat } private fun findShortestPath(start: Point, end: Point, boxes: List<List<Int>>): HeatData { val queue = mutableSetOf(SearchState(start, E, -1)) val shortestPaths = mutableMapOf(start to HeatData(0, emptyList())) while (queue.isNotEmpty()) { val current = queue.minBy { boxes.heatLossOf(it.point) } queue.remove(current) if (current.point == end) return shortestPaths.getValue(end) val neighbors = current.neighbors().filter { it.point containedIn boxes } neighbors .filter { it.point !in shortestPaths } .forEach { neighbor -> val (heatLossSoFar, path) = shortestPaths.getValue(current.point) val minHeatLossToNeighbor = shortestPaths[neighbor.point]?.heatLoss ?: Int.MAX_VALUE val nextHeatLoss = boxes.heatLossOf(neighbor.point) if (heatLossSoFar + nextHeatLoss < minHeatLossToNeighbor) { shortestPaths[neighbor.point] = HeatData(heatLossSoFar + nextHeatLoss, path + current.point) } queue.add(neighbor) } } throw IllegalArgumentException("Couldn't find path to $end") } data class HeatData( val heatLoss: Int, val path: List<Point> ) : Comparable<HeatData> { override fun compareTo(other: HeatData): Int = heatLoss.compareTo(other.heatLoss) } private fun List<List<Int>>.heatLossOf(point: Point): Int { return this[point.y][point.x] } private fun compute2(input: List<String>): Int { TODO() } private data class SearchState( val point: Point, val direction: Direction, val sameDirectionCount: Int = 0, ) { fun neighbors(): List<SearchState> { val leftRight = when (direction) { N, S -> listOf(SearchState(point.west(), W), SearchState(point.east(), E)) E, W -> listOf(SearchState(point.north(), N), SearchState(point.south(), S)) } return if (sameDirectionCount < 2) { leftRight + SearchState(point.move(direction), direction, sameDirectionCount + 1) } else { leftRight } } fun neighbors2(): List<SearchState> { val validDirections = listOf(N, S, W, E) .minus(direction.opposite) .run { if (sameDirectionCount >= 2) minus(direction) else this } return validDirections.map { direction -> val nextPoint = point.move(direction) val nextState = SearchState( point = nextPoint, direction = direction, sameDirectionCount = if (this.direction == direction) sameDirectionCount.inc() else 0, ) nextState } } } } private fun Point.move(direction: Direction): Point { return when (direction) { N -> this.north() E -> this.east() S -> this.south() W -> this.west() } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
5,903
aoc
Apache License 2.0
kotlin/2421-number-of-good-paths.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { class UnionFind(val n: Int) { val parent = IntArray (n) { it } val size = IntArray (n) { 1 } fun find(i: Int): Int { if (i != parent[i]) parent[i] = find(parent[i]) return parent[i] } fun union(a: Int, b: Int): Boolean { val pa = find(a) val pb = find(b) if (pa == pb) return false if (size[pa] > size[pb]) { parent[pb] = pa size[pa] += size[pb] } else { parent[pa] = pb size[pb] += size[pa] } return true } } fun numberOfGoodPaths(vals: IntArray, edges: Array<IntArray>): Int { val adj = HashMap<Int, MutableList<Int>>().apply { for ((a, b) in edges) { this[a] = getOrDefault(a, mutableListOf<Int>()).apply { add(b) } this[b] = getOrDefault(b, mutableListOf<Int>()).apply { add(a) } } } val valueToIndex = TreeMap<Int, MutableList<Int>>().apply { for ((i, v) in vals.withIndex()) { this[v] = getOrDefault(v, mutableListOf<Int>()).apply { add(i) } } } var res = 0 val uf = UnionFind(vals.size) valueToIndex.keys.forEach { value -> valueToIndex[value]?.forEach { i -> adj[i]?.forEach { nei -> if (vals[nei] <= vals[i]) uf.union(nei, i) } } val count = HashMap<Int, Int>() valueToIndex[value]?.forEach { i -> val value = uf.find(i) count[value] = count.getOrDefault(value, 0) + 1 res += count[value] ?: 0 } } return res } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,851
leetcode
MIT License
src/test/kotlin/days/y2022/Day03Test.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2032 import days.Day import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.Is.`is` import org.junit.jupiter.api.Test class Day03Test { @Test fun scores() { assertThat('a'.itemScore(), `is`(1)) assertThat('z'.itemScore(), `is`(26)) assertThat('A'.itemScore(), `is`(27)) assertThat('Z'.itemScore(), `is`(52)) } @Test fun testExampleOne() { assertThat( Day03().partOne( """ vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw """.trimIndent() ), `is`(157) ) } @Test fun testPartOne() { assertThat(Day03().partOne(), `is`(7817)) } @Test fun testExampleTwo() { assertThat( Day03().partTwo( """ vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw """.trimIndent() ), `is`(70) ) } @Test fun testPartTwo() { assertThat(Day03().partTwo(), `is`(2444)) } } class Day03 : Day(2022, 3) { override fun partOne(input: String): Any = parseInput(input).sumOf { it.rucksackScore() } override fun partTwo(input: String): Any = parseInput2(input).windowsScore() private fun parseInput(input: String): List<String> = input.trim().lines() private fun parseInput2(input: String): List<Triple<String, String, String>> = input.trim().lines().chunked(3).map { (a, b, c) -> Triple(a, b, c) } } private fun Triple<String, String, String>.intersection(): Set<Char> = first.toList().intersect(second.toSet()).intersect(third.toSet()) private fun String.rucksackScore(): Int { val firstHalf = this.substring(0, this.length / 2) val secondHalf = this.substring(this.length / 2) val appearsInBoth = firstHalf.toList().intersect(secondHalf.toList().toSet()) return appearsInBoth.toCharArray().sumOf { it.itemScore() } } private fun Char.itemScore(): Int = when (code) { in 'a'.code..'z'.code -> code - 'a'.code + 1 in 'A'.code..'Z'.code -> code - 'A'.code + 27 else -> error("wtf $this") } private fun List<Triple<String, String, String>>.windowsScore(): Int = sumOf { chunk -> chunk.intersection().sumOf { item -> item.itemScore() } }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
2,698
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day14.kt
mstar95
317,305,289
false
null
package days class Day14 : Day(14) { override fun partOne(): Any { val input = prepareInput(inputList) val result = input.fold(Program(Mask(""), mutableMapOf())) { program, op -> program.op(op, program::write) } println(input) print(result) return result.memory.values.sum() } override fun partTwo(): Any { val input = prepareInput(inputList) val result = input.fold(Program(Mask(""), mutableMapOf())) { program, op -> program.op(op, program::write2) } println(input) print(result) return result.memory.values.sum() } private fun prepareInput(list: List<String>): List<Operation> { return list .map { if (it.startsWith("mask")) createMask(it) else createWrite(it) } } private fun createMask(string: String) = Mask(string.drop("mask = ".length)) private fun createWrite(string: String): Write { val split = string.drop("mem[".length).split("]") val address = split[0].toLong() val int = split[1].drop(" = ".length).toLong() return Write(address, int) } } private sealed class Operation private data class Mask(val mask: String) : Operation() private data class Write(val address: Long, val int: Long) : Operation() private data class Program(var mask: Mask, val memory: MutableMap<Long, Long>) { fun op(op: Operation, w: (Write) -> Unit): Program { if(op is Mask) { mask = op } if(op is Write) { w(op) } return this } fun write(write: Write) { val curr = write.int.toString(2).padStart(36, '0') assert(curr.length == mask.mask.length ) {"$curr ${curr.length} $mask ${mask.mask.length}"} val toSave = mask.mask.foldIndexed(curr) { idx, value, m -> when (m) { 'X' -> value '1' -> put(value, idx, '1') '0' -> put(value, idx, '0') else -> error("Unsupported value $value") } } println(toSave) memory[write.address] = toSave.toLong(2) } private fun put(s: String, idx: Int, value: Char) = s.substring(0, idx) + value + s.substring(idx + 1) fun write2(write: Write) { val curr = write.address.toString(2).padStart(36, '0') assert(curr.length == mask.mask.length ) {"$curr ${curr.length} $mask ${mask.mask.length}"} val addresses = mask.mask.foldIndexed(listOf(curr)) { idx, list, m -> when (m) { 'X' -> list.flatMap { listOf(put(it, idx, '0'), put(it, idx, '1')) } '1' -> list.map { put(it, idx, '1') } '0' -> list else -> error("Unsupported value $m") } } addresses.forEach{ memory[it.toLong(2)] = write.int } } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
2,872
aoc-2020
Creative Commons Zero v1.0 Universal
src/Day25.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
import java.util.* //const val RIGHT = 0 //const val DOWN = 1 //const val LEFT = 2 //const val UP = 3 //const val GND = '.' //const val ELF = '#' //const val N = 0 //const val S = 1 //const val W = 2 //const val E = 3 fun main() { fun part1(input: List<String>): String { fun convert(s: String): Long { var result = 0L s.forEach { c -> result *= 5 result += when (c) { '2' -> 2 '1' -> 1 '0' -> 0 '-' -> -1 '=' -> -2 else -> error("wrong char $c") } } return result } var sum = 0L input.forEach { line -> sum += convert(line) } println(sum) var result = "" while (sum != 0L) { val frac = sum % 5 // 10- = 24 4, 4, 0 val digit = when (frac.toInt()) { 4 -> { sum += 5; "-" } 3 -> { sum += 5; "=" } 2 -> "2" 1 -> "1" 0 -> "0" else -> error("wrong digit $frac") } result = digit + result sum /= 5 } return result } fun part2(input: List<String>): Int { return TODO("Return not defined") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day25_test") // val testInput2 = readInput("Day25_test2") println(part1(testInput)) // println(part1(testInput2)) // check(part1(testInput2) == ) // check(part1(testInput) == "2=-1=0") // 4890 // println(part2(testInput)) // check(part2(testInput) == 54) @Suppress("UNUSED_VARIABLE") val input = readInput("Day25") // check(part1(input)) == 3947 // check(part2(input)) == println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
1,965
AoC-2022
Apache License 2.0
src/Day14.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
fun main() { // ktlint-disable filename fun getSandCount(input: List<String>, addFloor: Boolean = false): Int { // find grid size var numRows = 0 var numCols = 0 for (line in input) { val coordinates = line.split(" -> ") coordinates.windowed(2, 1) { val from = it[0].split(",") val to = it[1].split(",") numRows = Math.max(numRows, from[1].toInt() + 1) numRows = Math.max(numRows, to[1].toInt() + 1) numCols = Math.max(numCols, from[0].toInt() + 1) numCols = Math.max(numCols, to[0].toInt() + 1) } } // println("Grid size: numCols:$numCols, numRows:$numRows") if (addFloor) { numRows += 2 numCols = 1000 } val grid = Array(numRows) { CharArray(numCols) { '.' } } // mark obstacles if (addFloor) { for (i in 0 until numCols) { grid[numRows - 1][i] = '#' } } for (line in input) { val coordinates = line.split(" -> ") coordinates.windowed(2, 1) { val from = it[0].split(",").map { num -> num.toInt() } val to = it[1].split(",").map { num -> num.toInt() } val rowRange = if (from[1] < to[1]) (from[1]..to[1]) else (to[1]..from[1]) val colRange = if (from[0] < to[0]) (from[0]..to[0]) else (to[0]..from[0]) for (row in rowRange) { for (col in colRange) { grid[row][col] = '#' } } } } // simulate drops var sandCount = 0 var sandRow = 0 var sandCol = 500 while (true) { try { if (grid[sandRow + 1][sandCol] == '.') { // check straight down sandRow++ } else if (grid[sandRow + 1][sandCol - 1] == '.') { // check down left sandRow++ sandCol-- } else if (grid[sandRow + 1][sandCol + 1] == '.') { // check down right sandRow++ sandCol++ } else { // landed...next sand unit sandCount++ // println("Sand $sandCount landed at col:$sandCol row:$sandRow") grid[sandRow][sandCol] = 'O' sandRow = 0 sandCol = 500 // if entrance blocked (needs to include the one blocking the hole) if (grid[1][499] == 'O' && grid[1][500] == 'O' && grid[1][501] == 'O') return sandCount+1 } } catch (ex: ArrayIndexOutOfBoundsException) { // check fell off edge return sandCount } } } fun part1(input: List<String>): Int { return getSandCount(input) } fun part2(input: List<String>): Int { return getSandCount(input, addFloor = true) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") println("Test #Sand units: ${part1(testInput)}") check(part1(testInput) == 24) println("Test #Sand units with floor: ${part2(testInput)}") check(part2(testInput) == 93) val input = readInput("Day14_input") println("#Sand units: ${part1(input)}") println("#Sand units with floor: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
3,633
KotlinAdventOfCode2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/medium/LongestPalindrome.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 5. 最长回文子串 * 给你一个字符串 s,找到 s 中最长的回文子串。 */ class LongestPalindrome { companion object { @JvmStatic fun main(args: Array<String>) { println(LongestPalindrome().longestPalindrome("babad")) println(LongestPalindrome().longestPalindrome("cbbd")) println(LongestPalindrome().longestPalindrome("a")) println(LongestPalindrome().longestPalindrome("ac")) println(LongestPalindrome().longestPalindrome("ccc")) } } var finalStart = 0 var finalEnd = 0 var maxLength = 0 fun longestPalindrome(s: String): String { val length = s.length s.forEachIndexed { index, _ -> checkPalindrome(s, index, index) if (index + 1 < length) { checkPalindrome(s, index, index + 1) } } return s.substring(finalStart, finalEnd + 1) } private fun checkPalindrome(s: String, left: Int, right: Int) { val length = s.length var start = left var end = right while (start >= 0 && end < length) { if (s[start] == s[end]) { start-- end++ continue } break } end-- start++ if (end - start + 1 > maxLength) { maxLength = end - start + 1 finalStart = start finalEnd = end } } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,535
daily_algorithm
Apache License 2.0
src/main/kotlin/pl/jpodeszwik/aoc2023/Day08.kt
jpodeszwik
729,812,099
false
{"Kotlin": 55101}
package pl.jpodeszwik.aoc2023 private fun part1(instructions: String, nodes: Map<String, Pair<String, String>>) { var currentNode = "AAA" var steps = 0L while (currentNode != "ZZZ") { for (i in instructions) { when (i) { 'L' -> currentNode = nodes[currentNode]!!.first 'R' -> currentNode = nodes[currentNode]!!.second else -> println("invalid instruction") } steps++ if (currentNode == "ZZZ") { break } } } println(steps) } data class NodeData(val node: String, val nodeAfterCycle: String, val zNodesAfter: Set<Long>) private fun part2(instructions: String, nodes: Map<String, Pair<String, String>>) { val nodeDatas = mutableMapOf<String, NodeData>() val combinedCycles = 10000 val cycleLength = combinedCycles * instructions.length nodes.keys.map { var currentNode = it val zAfterNodes = HashSet<Long>() if (currentNode.endsWith("Z")) { zAfterNodes.add(0) } for (i in 0..<combinedCycles) { instructions.forEachIndexed { idx, instruction -> when (instruction) { 'L' -> currentNode = nodes[currentNode]!!.first 'R' -> currentNode = nodes[currentNode]!!.second else -> println("invalid instruction") } if (currentNode.endsWith("Z")) { zAfterNodes.add((i * instructions.length) + idx.toLong() + 1) } } } NodeData(it, currentNode, zAfterNodes) }.forEach { nodeDatas[it.node] = it } println("cycles built") var currentNodes = nodes.keys.filter { it.endsWith("A") } var steps = 0L var fullCycles = 0L while (true) { val cycleMetadata = currentNodes.map { nodeDatas[it]!! } val res = cycleMetadata .asSequence() .map { it.zNodesAfter }.flatten().groupBy { it } .filter { it.value.size == currentNodes.size } .map { it.key } .minOrNull() if (res != null) { steps += res.toLong() break } else { steps += cycleLength.toLong() } currentNodes = cycleMetadata.map { it.nodeAfterCycle } fullCycles++ } println(steps) } private fun combineNodeDatas(nodeDatas: Map<String, NodeData>, cycleLength: Long): MutableMap<String, NodeData> { val newNodeDatas = mutableMapOf<String, NodeData>() nodeDatas.values.forEach { val nodeDataAfterCycle = nodeDatas[it.nodeAfterCycle]!! newNodeDatas[it.node] = NodeData( it.node, nodeDataAfterCycle.nodeAfterCycle, it.zNodesAfter.toSet() + nodeDataAfterCycle.zNodesAfter.map { it2 -> it2 + cycleLength }) } return newNodeDatas } private fun part2v2(instructions: String, nodes: MutableMap<String, Pair<String, String>>) { var nodeDatas: MutableMap<String, NodeData> = mutableMapOf() var cycleLength = instructions.length.toLong() nodes.keys.map { var currentNode = it val zAfterNodes = HashSet<Long>() if (currentNode.endsWith("Z")) { zAfterNodes.add(0) } instructions.forEachIndexed { idx, instruction -> when (instruction) { 'L' -> currentNode = nodes[currentNode]!!.first 'R' -> currentNode = nodes[currentNode]!!.second else -> println("invalid instruction") } if (currentNode.endsWith("Z")) { zAfterNodes.add(idx.toLong() + 1) } } NodeData(it, currentNode, zAfterNodes) }.forEach { nodeDatas[it.node] = it } for (i in 1..21) { nodeDatas = combineNodeDatas(nodeDatas, cycleLength) cycleLength *= 2 } println("cycles built") var currentNodes = nodes.keys.filter { it.endsWith("A") } var steps = 0L var fullCycles = 0L while (true) { val cycleMetadata = currentNodes.map { nodeDatas[it]!! } val res = cycleMetadata .asSequence() .map { it.zNodesAfter }.flatten().groupBy { it } .filter { it.value.size == currentNodes.size } .map { it.key } .minOrNull() if (res != null) { steps += res.toLong() break } else { steps += cycleLength } currentNodes = cycleMetadata.map { it.nodeAfterCycle } fullCycles++ } println(steps) } fun main() { val lines = loadFile("/aoc2023/input8") val instructions = lines[0] val nodes = mutableMapOf<String, Pair<String, String>>() for (i in 2..<lines.size) { val parts = lines[i].split(" = (", ")") val targetNodes = parts[1].split(", ") nodes[parts[0]] = Pair(targetNodes[0], targetNodes[1]) } part1(instructions, nodes) measureTimeSeconds { part2(instructions, nodes) } measureTimeSeconds { part2v2(instructions, nodes) } }
0
Kotlin
0
0
2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63
5,137
advent-of-code
MIT License
src/main/kotlin/_2022/Day04.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readInput fun main() { fun toRanges(it: String) = it.split(",") .map { range -> val (start, end) = range.split("-").map(String::toInt) (start..end).toList() } fun part1(input: List<String>): Int { return input.map(::toRanges).count { val (first, second) = it val minSize = minOf(first.size, second.size) first.intersect(second.toSet()).size == minSize } } fun part2(input: List<String>): Int { return input.map(::toRanges).count { val (first, second) = it first.intersect(second.toSet()).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
951
advent-of-code
Apache License 2.0
src/main/kotlin/be/tabs_spaces/advent2021/days/Day05.kt
janvryck
433,393,768
false
{"Kotlin": 58803}
package be.tabs_spaces.advent2021.days import java.lang.IllegalStateException import kotlin.math.max import kotlin.math.min class Day05 : Day(5) { private val steamVents = inputList .map { it.split(" -> ") } .map { coordinates -> coordinates .map { it.split(",").map(String::toInt) } .map { it[0] to it[1] } } .map { SteamVent(it[0], it[1]) } override fun partOne(): Any { return steamVents .filterNot(SteamVent::isDiagonal) .flatMap(SteamVent::allPoints) .groupingBy { it }.eachCount() .filter { it.value > 1 }.count() } override fun partTwo(): Any { return steamVents .flatMap(SteamVent::allPoints) .groupingBy { it }.eachCount() .filter { it.value > 1 }.count() } data class SteamVent( val start: Pair<Int, Int>, val end: Pair<Int, Int>, ) { private val direction = when { start.first != end.first && start.second != end.second -> Direction.DIAGONAL start.first == end.first -> Direction.HORIZONTAL start.second == end.second -> Direction.VERTICAL else -> throw IllegalStateException() } fun allPoints() = when(direction) { Direction.DIAGONAL -> (directionlessProgression(start.first, end.first)).zip(directionlessProgression(start.second, end.second)) else -> (min(start.first, end.first)..max(start.first, end.first)) .map { x -> (min(start.second, end.second)..max(start.second, end.second)).map { y -> x to y } } .flatten() } private fun directionlessProgression(from: Int, to: Int) = if (from < to) from..to else from downTo to fun isDiagonal() = direction == Direction.DIAGONAL } enum class Direction { HORIZONTAL, VERTICAL, DIAGONAL } }
0
Kotlin
0
0
f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9
1,938
advent-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/day24/Day24.kt
daniilsjb
572,664,294
false
{"Kotlin": 69004}
package day24 import java.io.File fun main() { val data = parse("src/main/kotlin/day24/Day24.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 24 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Point( val x: Int, val y: Int, ) private data class Blizzard( val origin: Point, val offset: Point, ) private data class World( val source: Point, val target: Point, val blizzards: Set<Blizzard>, ) @Suppress("SameParameterValue") private fun parse(path: String): World { val lines = File(path).readLines() val source = Point(lines.first().indexOf('.'), 0) val target = Point(lines.last().indexOf('.'), lines.lastIndex) val blizzards = mutableSetOf<Blizzard>() for ((y, row) in lines.withIndex()) { for ((x, col) in row.withIndex()) { when (col) { '>' -> blizzards += Blizzard(Point(x, y), Point(+1, +0)) '<' -> blizzards += Blizzard(Point(x, y), Point(-1, +0)) '^' -> blizzards += Blizzard(Point(x, y), Point(+0, -1)) 'v' -> blizzards += Blizzard(Point(x, y), Point(+0, +1)) } } } return World(source, target, blizzards) } private val World.minX get() = source.x private val World.maxX get() = target.x private val World.minY get() = source.y + 1 private val World.maxY get() = target.y - 1 private fun World.next(): World { val newBlizzards = mutableSetOf<Blizzard>() for ((origin, offset) in blizzards) { var nx = origin.x + offset.x var ny = origin.y + offset.y if (nx < minX) nx = maxX if (nx > maxX) nx = minX if (ny < minY) ny = maxY if (ny > maxY) ny = minY newBlizzards += Blizzard(Point(nx, ny), offset) } return copy(blizzards = newBlizzards) } private fun Point.neighbors(): List<Point> = listOf( Point(x + 0, y + 1), Point(x + 0, y - 1), Point(x + 1, y + 0), Point(x - 1, y + 0), ) private fun World.withinBounds(point: Point): Boolean = (point.x in minX..maxX) && (point.y in minY..maxY) private fun World.safe(point: Point): Boolean = blizzards.find { it.origin == point } == null private fun solve(world: World, source: Point, target: Point, stepCount: Int = 0): Pair<Int, World> { val worlds = mutableMapOf(stepCount to world) val queue = ArrayDeque<Pair<Int, Point>>().apply { add(stepCount to source) } val visited = mutableSetOf<Pair<Int, Point>>() while (queue.isNotEmpty()) { val attempt = queue.removeFirst() if (attempt in visited) { continue } val (steps, position) = attempt val nextWorld = worlds.computeIfAbsent(steps + 1) { worlds.getValue(steps).next() } val neighbors = position.neighbors() if (target in neighbors) { return steps + 1 to nextWorld } for (neighbor in position.neighbors()) { if (nextWorld.withinBounds(neighbor) && nextWorld.safe(neighbor)) { queue += steps + 1 to neighbor } } visited += attempt if (nextWorld.safe(position)) { queue += steps + 1 to position } } error("Could not find the path.") } private fun part1(data: World): Int = solve(data, data.source, data.target).let { (steps, _) -> steps } private fun part2(w0: World): Int { val (s1, w1) = solve(w0, w0.source, w0.target) val (s2, w2) = solve(w1, w0.target, w0.source, s1) val (s3, _) = solve(w2, w0.source, w0.target, s2) return s3 }
0
Kotlin
0
0
6f0d373bdbbcf6536608464a17a34363ea343036
3,776
advent-of-code-2022
MIT License
kotlin/src/main/kotlin/AoC_Day9.kt
sviams
115,921,582
false
null
object AoC_Day9 { const val START_GARBAGE = '<' const val END_GARBAGE = '>' const val START_GROUP = '{' const val END_GROUP = '}' const val NONE = ' ' const val IGNORE = '!' fun solvePt1(input: Sequence<String>) : Int = input.fold(0) {acc, line -> acc + line.toCharArray().fold(Pair(listOf<Char>(NONE), 0)) { carry, currentChar -> if (carry.first.first() == IGNORE) Pair(carry.first.drop(1), carry.second) else when (currentChar) { START_GARBAGE -> if (carry.first.first() != START_GARBAGE) Pair(listOf(currentChar) + carry.first, carry.second) else carry START_GROUP -> if (carry.first.first() != START_GARBAGE) Pair(listOf(currentChar) + carry.first, carry.second) else carry END_GROUP -> when (carry.first.first()) { START_GROUP -> Pair(carry.first.drop(1), carry.second + carry.first.count { it == START_GROUP }) else -> carry } IGNORE -> Pair(listOf(IGNORE) + carry.first, carry.second) END_GARBAGE -> when (carry.first.first()) { START_GARBAGE -> Pair(carry.first.drop(1), carry.second) else -> carry } else -> carry } }.second } fun solvePt2(input: Sequence<String>) : Int = input.fold(0) {acc, line -> acc + line.toCharArray().fold(Pair(listOf<Char>(NONE), 0)) { carry, currentChar -> when (carry.first.first()) { IGNORE -> Pair(carry.first.drop(1), carry.second) else -> when (currentChar) { IGNORE -> Pair(listOf(IGNORE) + carry.first, carry.second) START_GARBAGE -> when (carry.first.first()) { START_GARBAGE -> Pair(carry.first, carry.second + 1) else -> Pair(listOf(currentChar) + carry.first, carry.second) } END_GARBAGE -> if (carry.first.first() == START_GARBAGE) Pair(carry.first.drop(1), carry.second) else carry else -> when (carry.first.first()) { START_GARBAGE -> Pair(carry.first, carry.second + 1) else -> carry } } } }.second } }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
2,520
aoc17
MIT License
kotlin/src/com/s13g/aoc/aoc2019/Day6.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2019 import com.s13g.aoc.Result import com.s13g.aoc.Solver import kotlin.math.min /** https://adventofcode.com/2019/day/6 */ class Day6 : Solver { private var map = mutableMapOf<String, Node>() override fun solve(lines: List<String>): Result { map = lines.map { l -> l.split(")") } .map { s -> Pair(s[1], Node(s[1], s[0])) }.toMap().toMutableMap() augmentData() val solutionA = map.keys.map { n -> countOrbits(n) }.sum() val solutionB = distance(map["YOU"]!!.orb, map["SAN"]!!.orb, "YOU") return Result("$solutionA", "$solutionB") } private fun countOrbits(node: String): Int { return if (node == "COM") 0 else 1 + countOrbits(map[node]!!.orb) } private fun augmentData() { map["COM"] = Node("COM") for (entry in map.filter { !it.value.orb.isBlank() }) { entry.value.conns.add(map[entry.value.orb]!!) map[entry.value.orb]!!.conns.add(entry.value) } } private fun distance(from: String, to: String, orig: String): Int? { if (from == to) return 0 var result: Int? = null for (conn in map[from]!!.conns.filter { it.name != orig && !it.name.isBlank() }) { result = bMin(result, distance(conn.name, to, from)) } if (result != null) result++ return result } private fun bMin(a: Int?, b: Int?): Int? { val min = min(a ?: Int.MAX_VALUE, b ?: Int.MAX_VALUE) return if (min == Int.MAX_VALUE) null else min } data class Node(val name: String, val orb: String = "") { val conns = mutableSetOf<Node>() } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,560
euler
Apache License 2.0
src/main/kotlin/g1201_1300/s1255_maximum_score_words_formed_by_letters/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1201_1300.s1255_maximum_score_words_formed_by_letters // #Hard #Array #String #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask // #2023_06_07_Time_131_ms_(100.00%)_Space_34.4_MB_(66.67%) class Solution { private lateinit var score: IntArray private fun updateArr(arr: IntArray, s: String, add: Int): Int { var sum = 0 for (c in s.toCharArray()) { val ind = c.code - 'a'.code arr[ind] += add if (arr[ind] < 0) { sum = -1 } if (sum != -1) { sum += score[ind] } } return sum } private fun findMaxScore(words: Array<String>, ind: Int, arr: IntArray): Int { if (ind == words.size) { return 0 } val excl = findMaxScore(words, ind + 1, arr) var incl = 0 val cscore = updateArr(arr, words[ind], -1) if (cscore != -1) { incl = cscore + findMaxScore(words, ind + 1, arr) } updateArr(arr, words[ind], 1) return Math.max(incl, excl) } fun maxScoreWords(words: Array<String>, letters: CharArray, score: IntArray): Int { val arr = IntArray(26) for (c in letters) { arr[c.code - 'a'.code]++ } this.score = score return findMaxScore(words, 0, arr) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,375
LeetCode-in-Kotlin
MIT License
src/Day22.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
private enum class CubeSides { TOP, DOWN, RIGHT, LEFT, FRONT, BACK } private enum class Moves(val coords: Pair<Int, Int>, val ind: Int) { RIGHT(0 to 1, 0), DOWN(1 to 0, 1), LEFT(0 to -1, 2), UP(-1 to 0, 3) } // // L.---. // E.TOP. // F.---. // T FRONT private abstract class MapWithMover(val map: List<String>) { var dir: Moves = Moves.RIGHT val n: Int = map.size val ms: List<Int> = map.map { it.length } val begins = map.map { it.indexOfFirst { it2 -> it2 != ' ' } } var x: Int = 0 var y: Int = begins[0] abstract fun move() fun getPassword(): Int { return (x + 1) * 1000 + (y + 1) * 4 + dir.ind } fun rotateSelf(clockwise: Boolean) { dir = rotate(dir, clockwise) } fun isOutside(nx: Int, ny: Int) = (nx < 0) || (nx >= n) || (ny < 0) || (ny >= ms[nx]) || (map[nx][ny] == ' ') companion object { val rotations = listOf(Moves.RIGHT, Moves.DOWN, Moves.LEFT, Moves.UP) fun rotate(toDir: Moves, clockwise: Boolean): Moves { return if (clockwise) rotations[(toDir.ind + 1) % 4] else rotations[(toDir.ind + 3) % 4] } } } private class CubicMap(map: List<String>) : MapWithMover(map) { val cubeEdge: Int = ms.zip(begins).minOf { it.first - it.second } val sides: MutableMap<CubeSides, Pair<IntRange, IntRange>> = mutableMapOf() val distances: MutableMap<CubeSides, Int> = mutableMapOf() val relativeDistances: MutableMap<Pair<CubeSides, CubeSides>, Int> = mutableMapOf() init { fun dfs(currentSide: CubeSides, currentPos: Pair<Int, Int>, dist: Int) { sides[currentSide] = ((currentPos.first until (currentPos.first + cubeEdge)) to (currentPos.second until (currentPos.second + cubeEdge))) distances[currentSide] = dist for (dir in rotations) { val nPos = currentPos + dir.coords * cubeEdge val fixedDir = fixedDir(currentSide, dir, cubeEdge) val nextSide = whichSideNext[currentSide to fixedDir]!! // This 'function' is total if (!isOutside(nPos.first, nPos.second) && nextSide !in sides) { dfs(nextSide, nPos, dist + 1) } } } fun distOnlyDfs(currentSide: CubeSides, currentPos: Pair<Int, Int>, dist: Int, distTo: CubeSides, used: MutableSet<CubeSides>) { used.add(currentSide) relativeDistances[distTo to currentSide] = dist for (dir in rotations) { val nPos = currentPos + dir.coords * cubeEdge val fixedDir = fixedDir(currentSide, dir, cubeEdge) val nextSide = whichSideNext[currentSide to fixedDir]!! // This 'function' is total if (!isOutside(nPos.first, nPos.second) && nextSide !in used) { distOnlyDfs(nextSide, nPos, dist + 1, distTo, used) } } } dfs(CubeSides.TOP, 0 to begins[0], 0) assert(sides.size == 6) for (side1 in sides.keys) { distOnlyDfs(side1, sides[side1]!!.first.first to sides[side1]!!.second.first, 0, side1, mutableSetOf()) } } override fun move() { val (nx, ny) = (x to y) + dir.coords if (!isOutside(nx, ny)) { if (map[nx][ny] == '.') { x = nx y = ny } return } val ourSide = sides.filter { x in it.value.first && y in it.value.second }.keys.first() val (relX, relY) = (x to y) - (sides[ourSide]!!.first.first to sides[ourSide]!!.second.first) val ourFixedDir = fixedDir(ourSide, dir, cubeEdge) val nextSide = whichSideNext[ourSide to ourFixedDir]!! var nextDir = dir var (fixX, fixY) = relX to relY repeat(relativeDistances[ourSide to nextSide]!! - 1) { nextDir = rotate(nextDir, cubeEdge == 4) // I HATE IT val temp = fixX fixX = fixY fixY = cubeEdge - 1 - temp } when (nextDir) { Moves.UP -> { fixX = 3 } Moves.RIGHT -> { fixY = 0 } Moves.DOWN -> { fixX = 0 } Moves.LEFT -> { fixY = 3 } } val fx = sides[nextSide]!!.first.first + fixX val fy = sides[nextSide]!!.second.first + fixY if (map[fx][fy] == '#') return x = fx y = fy dir = nextDir } companion object { val orderPerimeter = listOf(CubeSides.FRONT, CubeSides.RIGHT, CubeSides.BACK, CubeSides.LEFT, CubeSides.FRONT) val whichSideNext = buildMap(12 * 2) { for (i in 0..3) { put(orderPerimeter[i] to Moves.RIGHT, orderPerimeter[i + 1]) put(orderPerimeter[i + 1] to Moves.LEFT, orderPerimeter[i]) put(CubeSides.TOP to rotations[(3 - i + 2) % 4], orderPerimeter[i]) put(orderPerimeter[i] to Moves.UP, CubeSides.TOP) put(orderPerimeter[i] to Moves.DOWN, CubeSides.DOWN) put( CubeSides.DOWN to if (rotations[(3 - i + 2) % 4] == Moves.UP || rotations[(3 - i + 2) % 4] == Moves.DOWN) rotate( rotate(rotations[(3 - i + 2) % 4], false), false ) else rotations[(3 - i + 2) % 4], orderPerimeter[i] ) } } val fixes = mapOf((4 to CubeSides.RIGHT) to 3, (50 to CubeSides.RIGHT) to 1, (50 to CubeSides.LEFT) to 1, (50 to CubeSides.BACK) to 1) fun fixedDir(plane: CubeSides, dir: Moves, cubeEdge: Int): Moves { if ((cubeEdge to plane) !in fixes) return dir var fixedDir = dir repeat(fixes[cubeEdge to plane]!!) { fixedDir = rotate(fixedDir, true) } return fixedDir } } } private class MapWithMoverPlain(map: List<String>) : MapWithMover(map) { override fun move() { // if (areWeOnCube) { // moveOnCube() // } var (nx, ny) = (x to y) + dir.coords if (dir.coords.first == -1) { if (nx < 0) { nx = n - 1 } } if (dir.coords.first == 1) { if (nx >= n) { nx = 0 } } if (dir.coords.second == -1) { if (ny < begins[nx]) { ny = ms[nx] } } if (dir.coords.second == 1) { if (ny >= ms[nx]) { ny = begins[nx] } } while (ny >= ms[nx] || ny < begins[nx] || map[nx][ny] == ' ') { nx = (nx + dir.coords.first + n) % n ny += dir.coords.second } if (map[nx][ny] == '#') return x = nx y = ny } } private enum class Command { FORWARD, RIGHT, LEFT } fun main() { fun splitStringToCommands(mess: String): List<Pair<Command, Int>> { val result = mutableListOf<Pair<Command, Int>>() var currentCounter = 0 mess.forEach { if (it.isDigit()) { currentCounter = currentCounter * 10 + it.digitToInt() } else { if (currentCounter != 0) { result.add(Command.FORWARD to currentCounter) } currentCounter = 0 result.add((if (it == 'R') Command.RIGHT else Command.LEFT) to 1) } } if (currentCounter != 0) { result.add(Command.FORWARD to currentCounter) } return result } fun workTheGame(input: List<String>, onCube: Boolean): Int { val directions = input.takeLast(1)[0] val mapWithMover = if (!onCube) MapWithMoverPlain(input.takeWhile { it.isNotBlank() }) else CubicMap(input.takeWhile { it.isNotBlank() }) val commands = splitStringToCommands(directions) for ((command, amount) in commands) { repeat(amount) { when (command) { Command.FORWARD -> mapWithMover.move() else -> mapWithMover.rotateSelf(command == Command.RIGHT) } } } return mapWithMover.getPassword() } fun part1(input: List<String>): Int { return workTheGame(input, false) } fun part2(input: List<String>): Int { return workTheGame(input, true) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day22_test") check(part1(testInput) == 6032) check(part2(testInput) == 5031) val input = readInput("Day22") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
8,807
advent-of-kotlin-2022
Apache License 2.0
endlessRunnersEvo/src/main/kotlin/cz/woitee/endlessRunners/evolution/utils/MathUtils.kt
woitee
219,872,458
false
null
package cz.woitee.endlessRunners.evolution.utils import kotlin.math.sqrt object MathUtils { fun divisorsOf(value: Int): ArrayList<Int> { var reducingValue = value val intSqrt = (sqrt(value.toDouble()) + 0.0001).toInt() val sieve = IntArray(intSqrt + 1) for (potentialDivisor in 2 .. intSqrt) { if (sieve[potentialDivisor] == -1) continue while (reducingValue % potentialDivisor == 0) { sieve[potentialDivisor] += 1 reducingValue /= potentialDivisor } if (sieve[potentialDivisor] > 0) { for (i in 2 * potentialDivisor .. intSqrt step potentialDivisor) { sieve[i] = -1 } } } val res = ArrayList<Int>() sieve.forEachIndexed { divisor, pow -> repeat(pow) { res.add(divisor) } } return res } fun allDivisorsOf(value: Int): ArrayList<Int> { val divisorsMap = HashMap<Int, Int>() for (divisor in divisorsOf(value)) { divisorsMap[divisor] = divisorsMap.getOrDefault(divisor, 0) + 1 } val divisors = divisorsMap.keys.toIntArray() val multiplicities = divisorsMap.values.toIntArray() val res = ArrayList<Int>() divisorsRecursive(1, 0, divisors, multiplicities, res) res.sort() return res } private fun divisorsRecursive(current: Int, i: Int, divisors: IntArray, multiplicities: IntArray, results: ArrayList<Int>) { if (i >= divisors.size) { results.add(current) return } var cur = current divisorsRecursive(cur, i + 1, divisors, multiplicities, results) repeat(multiplicities[i]) { cur *= divisors[i] divisorsRecursive(cur, i + 1, divisors, multiplicities, results) } } }
0
Kotlin
0
1
5c980f44397f0b4f122e7b2cb51b82cf1c0419df
1,935
endlessRunners
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[1]两数之和.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 // // 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 // // // // 示例: // // 给定 nums = [2, 7, 11, 15], target = 9 // //因为 nums[0] + nums[1] = 2 + 7 = 9 //所以返回 [0, 1] // // Related Topics 数组 哈希表 // 👍 9778 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun twoSum(nums: IntArray, target: Int): IntArray { //使用HashMap 来保存已经计算过的值 //时间复杂度 O(n) val res = IntArray(2) val map = HashMap<Int,Int>() for ((index,item) in nums.withIndex()){ val temp = target - item if(map.containsKey(temp)){ res[0] = map[temp]!! res[1] = index }else{ map[item] = index } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,126
MyLeetCode
Apache License 2.0
codeforces/round637/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round637 fun main() { readLn() val d = readInts().sorted() val (g, r) = readInts() val inf = Int.MAX_VALUE val mark = Array(g) { BooleanArray(d.size) { false } } val queue = Array(g) { IntArray(d.size) } val queueLow = IntArray(g) val queueHigh = IntArray(g) mark[0][0] = true queueHigh[0] = 1 var ans = inf var time = 0 while (time < ans) { val mod = time % (g + r) repeat(queueHigh[mod] - queueLow[mod]) { val i = queue[mod][queueLow[mod]++] if (mod + d.last() - d[i] <= g) ans = minOf(ans, time + d.last() - d[i]) for (i2 in intArrayOf(i - 1, i + 1)) { val mod2 = (((d.getOrNull(i2) ?: continue) - d[i]).abs() + mod) .let { if (it == g) 0 else it } if (mod2 > g || mark[mod2][i2]) continue mark[mod2][i2] = true queue[mod2][queueHigh[mod2]++] = i2 } } if (++time % (g + r) == g) { time += r if (queueLow[0] == queueHigh[0]) break } } println(if (ans < inf) ans else -1) } private fun Int.abs() = kotlin.math.abs(this) private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,149
competitions
The Unlicense
src/main/kotlin/days/Day12.kt
andilau
429,206,599
false
{"Kotlin": 113274}
package days @AdventOfCodePuzzle( name = "The N-Body Problem", url = "https://adventofcode.com/2019/day/12", date = Date(day = 12, year = 2019) ) class Day12(scan: List<String>) : Puzzle { private val moons = scan.map(Moon::from) override fun partOne(): Int = (0 until 1000) .fold(moons.deepCopy()) { m, _ -> m.tick() } .sumOf { it.energy() } override fun partTwo(): Long { // X-Y-Z frequencies are independent val moonsX = moons.map { it.position.x } val moonsY = moons.map { it.position.y } val moonsZ = moons.map { it.position.z } var frequencyX: Long? = null var frequencyY: Long? = null var frequencyZ: Long? = null generateSequence(moons.deepCopy()) { it.tick() } .drop(1) .forEachIndexed { index, m -> if (frequencyX == null && m.map { it.position.x } == moonsX) frequencyX = index + 2L // <- 1-based & first-dropped if (frequencyY == null && m.map { it.position.y } == moonsY) frequencyY = index + 2L if (frequencyZ == null && m.map { it.position.z } == moonsZ) frequencyZ = index + 2L if (frequencyX != null && frequencyY != null && frequencyZ != null) return lcm(frequencyX!!, frequencyY!!, frequencyZ!!) } error("Cycle not found.") } private fun List<Moon>.deepCopy(): List<Moon> = this.map { it.copy() } private fun List<Moon>.tick(): List<Moon> { // update velocity by applying gravity to pairs of moons pairs().forEach { (one, another) -> one.updateVelocity(another).also { another.updateVelocity(one) } } // update position by applying velocity forEach { it.updatePosition() } return this } internal fun stepAndMoonsAsString(steps: Int) = (0 until steps) .fold(moons.deepCopy()) { acc, _ -> acc.tick() } .joinToString("\n") { it.shortString() } private fun <T> List<T>.pairs(): Iterable<Pair<T, T>> = flatMapIndexed { ix, first -> drop(ix + 1).map { second -> Pair(first, second) } } data class Moon(var position: Point3D, var velocity: Point3D = Point3D.ORIGIN) { fun updateVelocity(other: Moon) = run { velocity += (position sign other.position) } fun updatePosition() = run { position += velocity } fun energy() = position.manhattanDistance() * velocity.manhattanDistance() fun shortString() = buildString { append("pos=<x=${position.x},y=${position.y},z=${position.z}>,") append("vel=<x=${velocity.x},y=${velocity.y},z=${velocity.z}>") } companion object { fun from(line: String): Moon = POSITIONS_PATTERN.matchEntire(line)?.let { val (x, y, z) = it.destructured Moon(position = Point3D(x.toInt(), y.toInt(), z.toInt())) } ?: throw IllegalArgumentException("Can't parse position data from line: $line") private val POSITIONS_PATTERN = Regex("""<x=(-?\d+), y=(-?\d+), z=(-?\d+)>""") } } }
2
Kotlin
0
0
f51493490f9a0f5650d46bd6083a50d701ed1eb1
3,218
advent-of-code-2019
Creative Commons Zero v1.0 Universal
src/Day10.kt
Kbzinho-66
572,299,619
false
{"Kotlin": 34500}
private data class CycleState(val tick: Int, val register: Int ) { val signalStrength = tick * register val pixelIsVisible = (tick - 1) % 40 in register - 1 .. register + 1 } fun main() { fun getAllStates(input: List<String>): List<CycleState> { val states: MutableList<CycleState> = mutableListOf() var x = 1 var tick = 1 input.forEach { instruction -> val op = instruction.substringBefore(' ') if (op == "noop") { states.add(CycleState(tick, x)) tick++ } else { val value = instruction.substringAfter(' ').toInt() repeat(2) { states.add(CycleState(tick, x)) tick++ } x += value } } return states } fun part1(states: List<CycleState>): Int { val sample = arrayOf(20, 60, 100, 140, 180, 220) return states .filter { s -> s.tick in sample } .sumOf { s -> s.signalStrength } } fun part2(states: List<CycleState>) { val pixels = states.map { s -> if (s.pixelIsVisible) '#' else '.' } pixels.chunked(40).forEach { println(it.joinToString(" ")) } } // Testar os casos básicos val testInput = readInput("../inputs/Day10_test") val testStates = getAllStates(testInput) sanityCheck(part1(testStates), 13140) // part2(testStates) val input = readInput("../inputs/Day10") val states = getAllStates(input) println("Parte 1 = ${part1(states)}") println("Parte 2") part2(states) }
0
Kotlin
0
0
e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b
1,637
advent_of_code_2022_kotlin
Apache License 2.0
src/main/kotlin/Day17.kt
clechasseur
318,029,920
false
null
import org.clechasseur.adventofcode2020.Pt3D import org.clechasseur.adventofcode2020.Pt4D object Day17 { private val input = """ ##.##### #.##..#. .##...## ###.#... .####### ##....## ###.###. .#.#.#.. """.trimIndent() fun part1(): Int = generateSequence(input.toSpace()) { it.nextCycle() }.drop(6).first().activeCubes.size fun part2(): Int = generateSequence(input.toSpace4D()) { it.nextCycle() }.drop(6).first().activeCubes.size private val neighbourDisplacements = (-1..1).flatMap { x -> (-1..1).flatMap { y -> (-1..1).map { z -> Pt3D(x, y, z) } } }.filter { it != Pt3D.ZERO } private val neighbourDisplacements4D = (-1..1).flatMap { x -> (-1..1).flatMap { y -> (-1..1).flatMap { z -> (-1..1).map { w -> Pt4D(x, y, z, w) } } } }.filter { it != Pt4D.ZERO } private class Space(val activeCubes: Set<Pt3D>) { val xIndices: IntRange get() = (activeCubes.minBy { it.x }?.x?.minus(1) ?: 0)..(activeCubes.maxBy { it.x }?.x?.plus(1) ?: 0) val yIndices: IntRange get() = (activeCubes.minBy { it.y }?.y?.minus(1) ?: 0)..(activeCubes.maxBy { it.y }?.y?.plus(1) ?: 0) val zIndices: IntRange get() = (activeCubes.minBy { it.z }?.z?.minus(1) ?: 0)..(activeCubes.maxBy { it.z }?.z?.plus(1) ?: 0) fun cubeState(pt: Pt3D): Boolean = activeCubes.contains(pt) fun nextCycle(): Space = Space(xIndices.flatMap { x -> yIndices.flatMap { y -> zIndices.map { z -> Pt3D(x, y, z) } } }.mapNotNull { pt -> val state = cubeState(pt) val activeNeighbours = neighbourDisplacements.map { cubeState(pt + it) }.count { it } if (when (state) { false -> activeNeighbours == 3 true -> activeNeighbours in 2..3 }) pt else null }.toSet()) } private fun String.toSpace(): Space = Space(lines().withIndex().flatMap { (y, line) -> line.mapIndexedNotNull { x, c -> if (c == '#') Pt3D(x, y, 0) else null } }.toSet()) private class Space4D(val activeCubes: Set<Pt4D>) { val xIndices: IntRange get() = (activeCubes.minBy { it.x }?.x?.minus(1) ?: 0)..(activeCubes.maxBy { it.x }?.x?.plus(1) ?: 0) val yIndices: IntRange get() = (activeCubes.minBy { it.y }?.y?.minus(1) ?: 0)..(activeCubes.maxBy { it.y }?.y?.plus(1) ?: 0) val zIndices: IntRange get() = (activeCubes.minBy { it.z }?.z?.minus(1) ?: 0)..(activeCubes.maxBy { it.z }?.z?.plus(1) ?: 0) val wIndices: IntRange get() = (activeCubes.minBy { it.w }?.w?.minus(1) ?: 0)..(activeCubes.maxBy { it.z }?.z?.plus(1) ?: 0) fun cubeState(pt: Pt4D): Boolean = activeCubes.contains(pt) fun nextCycle(): Space4D = Space4D(xIndices.flatMap { x -> yIndices.flatMap { y -> zIndices.flatMap { z -> wIndices.map { w -> Pt4D(x, y, z, w) } } } }.mapNotNull { pt -> val state = cubeState(pt) val activeNeighbours = neighbourDisplacements4D.map { cubeState(pt + it) }.count { it } if (when (state) { false -> activeNeighbours == 3 true -> activeNeighbours in 2..3 }) pt else null }.toSet()) } private fun String.toSpace4D(): Space4D = Space4D(lines().withIndex().flatMap { (y, line) -> line.mapIndexedNotNull { x, c -> if (c == '#') Pt4D(x, y, 0, 0) else null } }.toSet()) }
0
Kotlin
0
0
6173c9da58e3118803ff6ec5b1f1fc1c134516cb
3,688
adventofcode2020
MIT License
src/com/saurabhtotey/trianglesolver/Triangle.kt
SaurabhTotey
102,925,664
false
null
package com.saurabhtotey.trianglesolver import kotlin.math.* val hasBeenInitialized = { a: Double -> a > 0 } //A function that will return whether a triangle angle or side has been initialized /** * A function that will return indices given a certain predicate */ fun getIndicesSuchThat(predicate: (Int) -> Boolean): List<Int> { return arrayOf(0, 1, 2).filter { predicate(it) } } /** * A function that will convert radian angles to degrees */ fun asDegrees(radians: Double): Double { return radians * 180 / PI } /** * A function that will convert degrees angles to radians */ fun asRadians(degrees: Double): Double { return degrees * PI / 180 } /** * A class that defines a triangle * This is where all the math of the triangle is handled * This logic class uses radians as do all people of logic */ class Triangle(var sides: Array<Double>, var angles: Array<Double>) { constructor() : this(Array(3, { _ -> -1.0 }), Array(3, { _ -> -1.0 })) /** * This just figures out if the triangle is valid or not with the given inputs * If the triangle isn't solved, it calls this method on the solutions of the triangles */ fun isValid(): Boolean { if (this.isSolved) { val acceptableError = 0.005 val anglesAddToPi = this.angles.sum() < PI + acceptableError && this.angles.sum() > PI - acceptableError val sidesFulfillLegInequality = this.sides[0] < this.sides[1] + this.sides[2] && this.sides[1] < this.sides[0] + this.sides[2] && this.sides[2] < this.sides[0] + this.sides[1] return anglesAddToPi && sidesFulfillLegInequality } else { return try { //If any of the solutions aren't valid, the unsolved triangle isn't valid this.solutions().filter { !it.isSolved || !it.isValid() }.forEach { return false } true } catch (e: Exception) { //The triangle can't be made into a solution and is thus invalid false } } } /** * The type of the triangle * Is dynamically calculated */ private val type: TriangleType get() = TriangleType(this.sides, this.angles) /** * Whether the triangle has been solved completely * Is dynamically calculated */ val isSolved: Boolean get() = this.sides.filter { hasBeenInitialized(it) }.size == 3 && this.angles.filter { hasBeenInitialized(it) }.size == 3 /** * Returns a triangle with all of the sides and angles solved * Doesn't actually modify base triangle * Returns an array because solving for an ASS triangle with the law of sines may return two triangles */ fun solutions(): Array<Triangle> { var solved = arrayOf(this.copy()) var primary = solved[0] fun reSolve() { solved = primary.solutions() } when (this.type) { SSS -> { primary.angles[0] = acos((primary.sides[1].pow(2.0) + primary.sides[2].pow(2.0) - primary.sides[0].pow(2.0)) / (2 * primary.sides[1] * primary.sides[2])) //Using the law of cosines primary.angles[1] = acos((primary.sides[0].pow(2.0) + primary.sides[2].pow(2.0) - primary.sides[1].pow(2.0)) / (2 * primary.sides[0] * primary.sides[2])) //Using the law of cosines primary.angles[2] = PI - primary.angles[0] - primary.angles[1] //Because all angles must add up to π } SAS -> { val unknownSideIndex = getIndicesSuchThat { !hasBeenInitialized(primary.sides[it]) }[0] val unknownAngleIndices = getIndicesSuchThat { it != unknownSideIndex } primary.sides[unknownSideIndex] = sqrt(solved[0].sides[unknownAngleIndices[0]].pow(2.0) + primary.sides[unknownAngleIndices[1]].pow(2.0) - 2 * primary.sides[unknownAngleIndices[0]] * primary.sides[unknownAngleIndices[1]] * cos(primary.angles[unknownSideIndex])) //Using the law of cosines reSolve() //Will solve the triangle as if it were SSS } AAA -> { val smallestSide = getIndicesSuchThat { primary.angles[it] == primary.angles.min() }[0] primary.sides[smallestSide] = 1.0 //Because no sides are defined, the smallest side is then assumed to be 1 reSolve() //Will solve the triangle as if it were ASA } ASA -> { val knownAngleIndices = getIndicesSuchThat { hasBeenInitialized(primary.angles[it]) } val knownSideIndices = getIndicesSuchThat { hasBeenInitialized(primary.sides[it]) } if (knownAngleIndices.size == 2) { //Will solve the remaining angle if it is yet unsolved primary.angles[getIndicesSuchThat { it !in knownAngleIndices }[0]] = PI - primary.angles[knownAngleIndices[0]] - primary.angles[knownAngleIndices[1]] //Because all angles must add up to π } for (unknownIndex in getIndicesSuchThat { it !in knownSideIndices }) { //Will solve for any unsolved sides now that all angles are solved primary.sides[unknownIndex] = sin(primary.angles[unknownIndex]) * primary.sides[knownSideIndices[0]] / sin(primary.angles[knownSideIndices[0]]) //Using the law of sines } } AAS -> { val unknownAngleIndex = getIndicesSuchThat { !hasBeenInitialized(primary.angles[it]) }[0] val knownAngleIndices = getIndicesSuchThat { it != unknownAngleIndex } primary.angles[unknownAngleIndex] = PI - primary.angles[knownAngleIndices[0]] - primary.angles[knownAngleIndices[1]] //Because all angles must add up to π reSolve() //Will solve the triangle as if it were ASA } ASS -> { val knownSides = getIndicesSuchThat { hasBeenInitialized(primary.sides[it]) } val knownAngle = getIndicesSuchThat { hasBeenInitialized(primary.angles[it]) }[0] val unknownOppositeAngle = knownSides.filter { it != knownAngle }[0] val ASSType = primary.sides[unknownOppositeAngle] / primary.sides[knownAngle] * sin(primary.angles[knownAngle]) if (primary.sides[knownAngle] >= primary.sides[unknownOppositeAngle]) { primary.angles[unknownOppositeAngle] = asin(ASSType) reSolve() } else { primary = solved[0] val secondary = this.copy() primary.angles[unknownOppositeAngle] = asin(ASSType) secondary.angles[unknownOppositeAngle] = PI - asin(ASSType) solved = arrayOf(primary.solutions()[0], secondary.solutions()[0]) } } } return solved } /** * Gets the area of the triangle using Heron's method * Only works if this is a solved triangle * Doesn't return the area of this triangle's solved triangle because there is the possibility (from ASS triangles) that 2 areas might be returned */ fun area(): Double { if (!this.isSolved) return 0.0 val s = this.sides.sum() / 2 return sqrt(s * (s - this.sides[0]) * (s - this.sides[1]) * (s - this.sides[2])) } /** * Creates a copy of this triangle with the same initial properties */ private fun copy(): Triangle { val clone = Triangle() clone.sides = this.sides.copyOf() clone.angles = this.angles.copyOf() return clone } } //Defines all triangle types below val SSS = TriangleType("SSS") val SAS = TriangleType("SAS") val AAA = TriangleType("AAA") //Does not define a unique triangle val ASA = TriangleType("ASA") val AAS = TriangleType("AAS") val ASS = TriangleType("ASS") //Does not necessarily define a unique triangle /** * A class that defines the type of a triangle */ class TriangleType { /** * An enum for the parts of a triangle */ enum class Part { SIDE, ANGLE, UNKNOWN } /** * The type of the triangle this is * Contains 3 Parts */ var type = Array(3, { _ -> Part.UNKNOWN }) /** * Uses the given parameters to figure out the type of triangle */ constructor(sides: Array<Double>, angles: Array<Double>) { val initializedSides = getIndicesSuchThat { hasBeenInitialized(sides[it]) } val initializedAngles = getIndicesSuchThat { hasBeenInitialized(angles[it]) } if (initializedSides.size + initializedAngles.size < 3) return //Sets the type to the first applicable found triangle type; order is checked in terms of desirability (eg. least desirable types checked last) //That way if a triangle fulfills the condition of a desirable type and an undesirable type, it will get checked against the desirable type first and thus become it this.type = when (initializedSides.size) { 3 -> arrayOf(Part.SIDE, Part.SIDE, Part.SIDE) 1 -> //1 is checked before 2 because 2 has the possibility of making an ASS triangle when a AAS triangle is possible, and ASS is the least desirable triangle //If there are 3 angles and 1 side or if the side opposite the uninitialized angle is initialized, the triangle is ASA, otherwise it is AAS if (initializedAngles.size == 3 || hasBeenInitialized(sides[getIndicesSuchThat { it !in initializedAngles }[0]])) arrayOf(Part.ANGLE, Part.SIDE, Part.ANGLE) else arrayOf(Part.ANGLE, Part.ANGLE, Part.SIDE) 2 -> when { //If the angle opposite the uninitialized side is initialized, the triangle is SAS, or if all 3 angles are initialized hasBeenInitialized(angles[getIndicesSuchThat { it !in initializedSides }[0]]) || initializedAngles.size == 3 -> arrayOf(Part.SIDE, Part.ANGLE, Part.SIDE) //If there are two angles and two sides, but there is no included angle initializedAngles.size > 1 -> arrayOf(Part.ANGLE, Part.ANGLE, Part.SIDE) else -> arrayOf(Part.ANGLE, Part.SIDE, Part.SIDE) } 0 -> arrayOf(Part.ANGLE, Part.ANGLE, Part.ANGLE) else -> this.type } } /** * Just makes a type based on the given string */ constructor(stringType: String) { this.type = stringType.map { when (it.toLowerCase()) { 's' -> Part.SIDE 'a' -> Part.ANGLE else -> Part.UNKNOWN } }.toTypedArray() } /** * A string representation of this triangle type */ override fun toString(): String { return type.joinToString("") { when (it) { Part.SIDE -> "S" Part.ANGLE -> "A" Part.UNKNOWN -> "?" } } } /** * Returns whether two triangle types are equal * Accounts for palindromes */ override fun equals(other: Any?): Boolean { return other is TriangleType && (other.type.contentEquals(this.type) || other.type.contentEquals(this.type.reversedArray())) } }
1
Kotlin
0
0
8f0198c3b9066a4d745a6db072ebd6d41af8c2f3
11,295
Triangle-Solver
MIT License
src/main/kotlin/_2022/Day10.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readInput import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { val queue = ArrayDeque<SimpleCommand>() input.forEach { if ("noop" == it) { queue.add(NoopCommand()) } else if (it.startsWith("addx")) { queue.add(AddXCommand(incX = it.split(" ")[1].toInt())) } } val stateMachine = StateMachine(commands = queue) return stateMachine.run() } fun part2(input: List<String>): List<String> { val queue = ArrayDeque<SimpleCommand>() input.forEach { if ("noop" == it) { queue.add(NoopCommand()) } else if (it.startsWith("addx")) { queue.add(AddXCommand(incX = it.split(" ")[1].toInt())) } } val stateMachine = StateMachine(commands = queue) val str = stateMachine.run2() return str.chunked(40) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") println(part1(testInput)) part2(testInput).forEach(::println) val input = readInput("Day10") println(part1(input)) part2(input).forEach(::println) } data class StateMachine(var x: Int = 1, var commands: ArrayDeque<SimpleCommand>) { fun run(): Int { var cycle = 0 var flag = true var currentCommand = commands.removeFirst() var signalStrength = 0 while (flag) { cycle++ currentCommand.beforeCycle(this) if (cycle == 20 || (cycle - 20) % 40 == 0) { signalStrength += cycle * x } currentCommand.popCycle() currentCommand.afterCycle(this) if (currentCommand.cycleCount == 0) { if (commands.isEmpty()) { flag = false } else { currentCommand = commands.removeFirst() } } } return signalStrength } fun run2(): String { var cycle = 0 var flag = true var currentCommand = commands.removeFirst() var str = "" while (flag) { cycle++ currentCommand.beforeCycle(this) str += if (abs(cycle % 40 - (x + 1)) < 2) { "#" } else { "." } currentCommand.popCycle() currentCommand.afterCycle(this) if (currentCommand.cycleCount == 0) { if (commands.isEmpty()) { flag = false } else { currentCommand = commands.removeFirst() } } } return str } } interface Command { fun beforeCycle(stateMachine: StateMachine) fun duringCycle(stateMachine: StateMachine) fun afterCycle(stateMachine: StateMachine) fun popCycle() } abstract class SimpleCommand(open var cycleCount: Int) : Command { override fun popCycle() { cycleCount-- } } data class NoopCommand(override var cycleCount: Int = 1) : SimpleCommand(cycleCount) { override fun beforeCycle(stateMachine: StateMachine) { } override fun duringCycle(stateMachine: StateMachine) { } override fun afterCycle(stateMachine: StateMachine) { } } data class AddXCommand(override var cycleCount: Int = 2, var incX: Int) : SimpleCommand(cycleCount) { override fun beforeCycle(stateMachine: StateMachine) { } override fun duringCycle(stateMachine: StateMachine) { } override fun afterCycle(stateMachine: StateMachine) { if (cycleCount == 0) { stateMachine.x += incX } } }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
3,776
advent-of-code
Apache License 2.0
src/main/kotlin/cloud/dqn/leetcode/self/CoinsFromEarlyFallKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode.self /** * "Problem from after lunch" * Designer: JN */ object CoinsFromEarlyFallKt { @JvmStatic fun main(args: Array<String>) { val coinValues = intArrayOf(5, 25, 50, 100) val possible = possibleSums(coinValues, intArrayOf(4, 3, 2, 1)) println(possible) } /** * Example coinValues = [5, 10, 25], quantity = [1, 3, 2] * Calulate the number of possible sums * so * coins in hand == [5, 10, 10, 10, 25, 25] * possibles = [ * 0, * (5), (5,10), (5, 10, 10), (5, 10, 10, 25), (5, 10, 10, 25, 25), * (5, 25), (5, 25, 25), (5, 10) ... * ... * ] * return possibles.uniqueCount * @param coinValues value of each coin * @param quantity number of coins */ fun possibleSums(coinValues: IntArray, quantity: IntArray): Int { // sanity if (coinValues.isEmpty() || quantity.isEmpty() || coinValues.size != quantity.size) { return 0 } val totals = HashSet<Int>() // create unified list var totalSize = 0 quantity.forEach { totalSize += it } val allCoins = IntArray(totalSize, { 0 }) var allCoinsIndex = 0 coinValues.forEachIndexed { index, value -> val quant = quantity[index] if (quant > 0) { var inner = 0 while (inner < quant) { allCoins[allCoinsIndex] = value allCoinsIndex++ inner++ } } } possibleSumsHelper(0, allCoins, totals) return totals.size } private fun possibleSumsHelper(total: Int, coinsList: IntArray, totals: HashSet<Int>) { totals.add(total) if (coinsList.isEmpty()) { return } else { coinsList.forEachIndexed { index, value -> removeSingle(index, coinsList)?.let { possibleSumsHelper(total + value, it, totals) } } } } // alternative is to use System.arrayCopy private fun removeSingle(indexToRemove: Int, arr: IntArray): IntArray? { return if (indexToRemove < 0 || indexToRemove >= arr.size) { null } else { var index = 0 var insertionIndex = 0 val result = IntArray(arr.size - 1) while (index < arr.size) { if (index != indexToRemove) { result[insertionIndex] = arr[index] insertionIndex++ } index++ } result } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
2,700
cloud-dqn-leetcode
No Limit Public License
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day09/day09.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day09 import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input09-test.txt" const val FILENAME = "input09.txt" fun main() { val histories = readLines(2023, FILENAME).map { History.parse(it) } val extrapolated = histories.map { it.extrapolate() } val sum = extrapolated.sumOf { it.values.last() } println(sum) val extrapolatedBack = histories.map { it.extrapolateBack() } val sumBack = extrapolatedBack.sumOf { it.values.first() } println(sumBack) } data class History (val values: List<Long>) { fun extrapolate(): History { if (this.containsOnlyZero()) return History(values + 0L) val next = differences().extrapolate() val extraValue = values.last() + next.values.last() return History(values + extraValue) } fun extrapolateBack(): History { if (this.containsOnlyZero()) return History(listOf(0L) + values) val next = differences().extrapolateBack() val extraValue = values.first() - next.values.first() return History(listOf(extraValue) + values) } private fun differences(): History { return History(values.zipWithNext { a, b -> b - a }) } private fun containsOnlyZero(): Boolean { return values.all { it == 0L } } companion object { fun parse(input: String): History { return History(input.split(" ").map { it.toLong() }) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,330
advent-of-code
Apache License 2.0
src/day09/Day09.kt
martinhrvn
724,678,473
false
{"Kotlin": 27307, "Jupyter Notebook": 1336}
package day09 import readInput import readNumbers class Day09(val input: List<String>) { private fun getSequence() = generateSequence(0) { it + 1 } private fun parseInput(): List<List<Long>> { return input.map { it.readNumbers() } } private fun predictNextValue(numbers: List<Long>): Long { val predictionRows = getSequence() .scan(numbers) { row, _ -> row.windowed(2).map { (i1, i2) -> i2 - i1 } } .takeWhile { it.any { n -> n != 0L } } .toList() return predictionRows.sumOf { it.last() } } private fun predictPreviousValue(numbers: List<Long>): Long { return predictNextValue(numbers.reversed()) } fun part1(): Long { return parseInput().map(::predictNextValue).sum() } fun part2(): Long { return parseInput().map(::predictPreviousValue).sum() } } fun main() { val day09 = Day09(readInput("day09/Day09")) println(day09.part1()) println(day09.part2()) }
0
Kotlin
0
0
59119fba430700e7e2f8379a7f8ecd3d6a975ab8
960
advent-of-code-2023-kotlin
Apache License 2.0
src/main/kotlin/week2/DistressSignal.kt
waikontse
572,850,856
false
{"Kotlin": 63258}
package week2 import shared.Puzzle import shared.ReadUtils.Companion.debug class DistressSignal : Puzzle(13) { override fun solveFirstPart(): Any { return puzzleInput.asSequence().filter { it.isNotBlank() } .chunked(2) .map { parseEntry(it[0], 0) to parseEntry(it[1], 0) } .map { compareValues(it.first, it.second) } .mapIndexed { index, isInOrder -> if (isInOrder) index.inc() else -1 } .filter { it > 0 } .sum() } override fun solveSecondPart(): Any { val comparator = Comparator { left: List<*>, right: List<*> -> if (compareValues(left, right)) -1 else 1 } val target1 = listOf(listOf(2)) val target2 = listOf(listOf(6)) puzzleInput.asSequence().filter { it.isNotBlank() } .map { parseEntry(it, 0) } .plus(target1) .plus(target2) .sortedWith(comparator).toList() .let { val index1 = it.indexOf(listOf(2)).inc() val index2 = it.indexOf(listOf(6)).inc() return index1 * index2 } } private fun parseEntry(entry: String, currPos: Int): List<Any> { debug("parsing $entry on pos: $currPos") return if (entry[currPos] == '[') { parseList(entry, currPos.inc()).second } else if (entry[currPos] == ',') { parseEntry(entry, currPos.inc()) } else { throw IllegalArgumentException() } } private fun parseList(entry: String, currPos: Int): Pair<Int, List<Any>> { debug("Parsing list $entry on currPos: $currPos") val newList = mutableListOf<Any>() var currPosTemp = currPos while (entry[currPosTemp] != ']') { if (entry[currPosTemp] == '[') { val parsedList = parseList(entry, currPosTemp.inc()) newList.add(parsedList.second) currPosTemp = parsedList.first debug("new currPosTemp: $currPosTemp") } else if (entry[currPosTemp] == ',') { debug("parsing comma") currPosTemp += 1 } else { val parsedNumber = parseNumber(entry, currPosTemp) newList.add(parsedNumber.second) currPosTemp = parsedNumber.first } } return currPosTemp.inc() to newList } private fun parseNumber(entry: String, currPos: Int): Pair<Int, Int> { debug("Parsing number: $entry currPos: $currPos") var currPosTemp = currPos while (entry[currPosTemp].isDigit()) { currPosTemp += 1 } val parsedInt = entry.subSequence(currPos, currPosTemp).toString().toInt() return currPosTemp to parsedInt } private fun compareValues(left: List<*>, right: List<*>): Boolean { return compareValues(left, right, isInOrder = false, shouldStop = false).first } private tailrec fun compareValues( left: List<*>, right: List<*>, isInOrder: Boolean, shouldStop: Boolean ): Pair<Boolean, Boolean> { debug("Comparing values $left * $right ** isInOrder: $isInOrder *** shouldStop: $shouldStop") if (isInOrder) { return true to true } else if (shouldStop) { debug("returning result == $isInOrder") return isInOrder to true } else if (left.isEmpty() && right.isNotEmpty()) { return true to true } else if (left.isNotEmpty() && right.isEmpty()) { return false to true } else if (left.isEmpty() && right.isEmpty()) { debug("return false for left.empty right.empty") return isInOrder to shouldStop } val leftFirst = left.first() val rightFirst = right.first() val comparisonResult: Boolean val shouldStopNew: Boolean if (leftFirst is Int && rightFirst is Int) { val compareIntResult = compareInts(leftFirst, rightFirst) comparisonResult = compareIntResult.first shouldStopNew = compareIntResult.second } else if (leftFirst is List<*> && rightFirst is List<*>) { val compareListResult = compareLists(leftFirst, rightFirst) comparisonResult = compareListResult.first shouldStopNew = compareListResult.second } else if (leftFirst is List<*> && rightFirst is Int) { val compareListResult = compareLists(leftFirst, listOf(rightFirst)) comparisonResult = compareListResult.first shouldStopNew = compareListResult.second } else if (leftFirst is Int && rightFirst is List<*>) { val compareListResult = compareLists(listOf(leftFirst), rightFirst) comparisonResult = compareListResult.first shouldStopNew = compareListResult.second } else { throw IllegalArgumentException() } return compareValues(left.drop(1), right.drop(1), comparisonResult, shouldStopNew) } private fun compareInts(left: Int, right: Int): Pair<Boolean, Boolean> { debug("Comparing ints: $left : $right") return (left < right) to (left != right) } private fun compareLists(left: List<*>, right: List<*>): Pair<Boolean, Boolean> { debug("Comparing lists: $left * $right") return compareValues(left, right, isInOrder = false, shouldStop = false) } }
0
Kotlin
0
0
860792f79b59aedda19fb0360f9ce05a076b61fe
5,499
aoc-2022-in-kotllin
Creative Commons Zero v1.0 Universal
day12/Kotlin/day12.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* fun print_day_12() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 12" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Passage Pathing -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_12() Day12().part_1() Day12().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day12 { data class Node(val name: String, val isLarge: Boolean = false, var connections: List<Node> = mutableListOf()) fun part_1() { val nodes = mutableMapOf<String, Node>() fun followPaths(node: Node, path: List<Node>): List<List<Node>> { val newPath = path+node return if (node.name == "end" || (path.contains(node) && !node.isLarge)) { listOf(newPath) } else { node.connections.flatMap { followPaths(it, newPath) } } } File("../Input/day12.txt").readLines().forEach { val pathway = it.split("-").map { node -> if (!nodes.containsKey(node)) { nodes[node] = Node(node, node.isUpperCase()) } nodes[node]!! } pathway[0].connections += pathway[1] pathway[1].connections += pathway[0] } val start = nodes["start"]!! val paths = followPaths(start, listOf()).filter { it.last().name == "end" } // only keep nodes that actually end println("Puzzle 1: ${paths.size}") } fun part_2() { val nodes = HashMap<String, HashSet<String>>() File("../Input/day12.txt").readLines().forEach { val (a,b) = it.split("-") nodes.getOrPut(a) { HashSet() }.add(b) nodes.getOrPut(b) { HashSet() }.add(a) } fun canVisit(name: String, path: List<String>): Boolean = when { name.isUpperCase() -> true name == "start" -> false name !in path -> true else -> path.filterNot { it.isUpperCase() }.groupBy { it }.none { it.value.size == 2 } } fun followPaths(path: List<String> = listOf("start")): List<List<String>> = if (path.last() == "end") listOf(path) else nodes.getValue(path.last()) .filter { canVisit(it, path) } .flatMap { followPaths( path + it) } println("Puzzle 2: ${followPaths().size}") } } private fun String.isUpperCase(): Boolean = this == this.uppercase()
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
2,879
AOC2021
Apache License 2.0
src/problems/day4/part1/part1.kt
klnusbaum
733,782,662
false
{"Kotlin": 43060}
package problems.day4.part1 import java.io.File import kotlin.math.pow //private const val testFile = "input/day4/test.txt" private const val cardsFile = "input/day4/cards.txt" fun main() { val cardValueSum = File(cardsFile).bufferedReader().useLines { sumCardValues(it) } println("Card Values Sum: $cardValueSum") } private fun sumCardValues(lines: Sequence<String>) = lines.map { it.toCard() }.sumOf { it.value() } private fun String.toCard() = Card( id = this.toCardID(), winningNumbers = this.toWinningNumbers(), possessedNumbers = this.toPossessedNumbers() ) private fun String.toCardID(): Int = this.substringBefore(":").substringAfter(" ").trim().toInt() private fun String.toWinningNumbers() = this.substringAfter(":").substringBefore("|").trim().split(" ").filter { it != "" }.map { it.toInt() } .toSet() private fun String.toPossessedNumbers(): Set<Int> = this.substringAfter("|").trim().split(" ").filter { it != "" }.map { it.trim().toInt() }.toSet() private data class Card(val id: Int, val winningNumbers: Set<Int>, val possessedNumbers: Set<Int>) { fun value(): Int = 2.0.pow(numMatching() - 1).toInt() fun numMatching() = winningNumbers.intersect(possessedNumbers).count() }
0
Kotlin
0
0
d30db2441acfc5b12b52b4d56f6dee9247a6f3ed
1,244
aoc2023
MIT License
Kotlin for Java Developers. Week 3/Taxi Park/Task/src/taxipark/TaxiParkTask.kt
vnay
251,709,901
false
null
package taxipark /* * Task #1. Find all the drivers who performed no trips. */ fun TaxiPark.findFakeDrivers(): Set<Driver> = allDrivers - trips.map { it.driver } /* * Task #2. Find all the clients who completed at least the given number of trips. */ fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> = allPassengers.filter { passenger -> trips.count { passenger in it.passengers} >= minTrips }.toSet() /* * Task #3. Find all the passengers, who were taken by a given driver more than once. */ fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> = trips .filter { trip -> trip.driver == driver } .flatMap { trip -> trip.passengers } .groupingBy { passenger -> passenger } .eachCount() .filter { entry -> entry.value > 1 } .keys /* * Task #4. Find the passengers who had a discount for majority of their trips. */ fun TaxiPark.findSmartPassengers(): Set<Passenger> { val (withDiscount, withoutDiscount) = trips.partition { it.discount != null } return allPassengers .filter { passenger -> withDiscount.count { passenger in it.passengers } > withoutDiscount.count { passenger in it.passengers } }.toSet() } /* * Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on. * Return any period if many are the most frequent, return `null` if there're no trips. */ fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? { val ids = trips.groupBy { trip -> trip.duration / 10 } .map { group -> group.key to group.value.count() } .maxBy { pair -> pair.second } ?.first val min = ids?.times(10) val max = min?.plus(9) ?: 0 return min?.rangeTo(max) } /* * Task #6. * Check whether 20% of the drivers contribute 80% of the income. */ fun TaxiPark.checkParetoPrinciple(): Boolean { if(trips.isEmpty()) return false val totalIncome = trips.sumByDouble(Trip::cost) val sortedDrivers = trips .groupBy(Trip::driver) .map { (_, tripByDriver) -> tripByDriver.sumByDouble(Trip::cost) } .sortedDescending() val topDrivers = (0.2 * allDrivers.size).toInt() val incomeByTopDrivers = sortedDrivers .take(topDrivers) .sum() return incomeByTopDrivers >= 0.8 * totalIncome }
0
Kotlin
0
0
ce638b0272bd5fac80891a669cd17848bf6d0721
2,458
Kotlin-for-Java-Developers
MIT License
src/main/kotlin/org/example/e3fxgaming/adventOfCode/aoc2023/day08/Day08.kt
E3FxGaming
726,041,587
false
{"Kotlin": 38290}
package org.example.e3fxgaming.adventOfCode.aoc2023.day08 import org.example.e3fxgaming.adventOfCode.utility.Day import org.example.e3fxgaming.adventOfCode.utility.InputParser import org.example.e3fxgaming.adventOfCode.utility.Math import org.example.e3fxgaming.adventOfCode.utility.MultiLineInputParser class Day08(input: String) : Day<Day08.Maps, Day08.Maps> { data class Maps( val instructions: List<Char>, val map: Map<String, Pair<String, String>> ) override val partOneParser: InputParser<Maps> = object : MultiLineInputParser<Maps>(input) { override fun parseFullInput(fullInput: String): List<Maps> { val lines = fullInput.split(System.lineSeparator()) val instructions = lines.first().toList() val map = lines.drop(2).associate { mapLine -> val (from, toString) = mapLine.split(" = ") val (l, r) = toString.substring(1, toString.lastIndex).split(", ") from to (l to r) } return listOf(Maps(instructions, map)) } } override val partTwoParser: InputParser<Maps> = partOneParser override fun solveFirst(given: List<Maps>): String { val onlyMaps = given.first() var currentPosition = "AAA" var steps = 0 val instructionIterator = iterator { while (true) yieldAll(onlyMaps.instructions) } while (currentPosition != "ZZZ") { ++steps val currentOptions = onlyMaps.map.getValue(currentPosition) currentPosition = if (instructionIterator.next() == 'L') currentOptions.first else currentOptions.second } return steps.toString() } override fun solveSecond(given: List<Maps>): String { val onlyMaps = given.first() val startNodes = onlyMaps.map.keys.filter { it.last() == 'A' } val endPositionsAfterSteps = startNodes.map { startPosition -> val instructionIterator = iterator<IndexedValue<Char>> { while (true) yieldAll(onlyMaps.instructions.withIndex()) } var nextInstruction = instructionIterator.next() var currentPosition = onlyMaps.map.getValue(startPosition).let { if (nextInstruction.value == 'L') it.first else it.second } val visited = mutableSetOf(startPosition + nextInstruction) nextInstruction = instructionIterator.next() var steps = 1 buildList<Int> { while (currentPosition + nextInstruction.index !in visited) { visited.add(currentPosition + nextInstruction.index) if (currentPosition.endsWith('Z')) add(steps) currentPosition = onlyMaps.map.getValue(currentPosition).let { if (nextInstruction.value == 'L') it.first else it.second } nextInstruction = instructionIterator.next() ++steps } } } val math = Math() return endPositionsAfterSteps.fold(1L) { acc, (a) -> math.lcm(acc, a.toLong()) }.toString() } } fun main() = Day08( Day08::class.java.getResource("/2023/day08/realInput1.txt")!!.readText() ).runBoth()
0
Kotlin
0
0
3ae9e8b60788733d8bc3f6446d7a9ae4b3dabbc0
3,334
adventOfCode
MIT License
src/2022/Day20.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import java.io.File import java.math.BigInteger import java.util.* fun main() { Day20().solve() } class Day20 { val input1 = """ 1 2 -3 3 -2 0 4 """.trimIndent() fun MutableList<Pair<Int, BigInteger>>.move(ix: Int) { val ix0 = indexOfFirst { it.first == ix } val number = get(ix0) val moves = number.second var ix1 = moves.add(ix0.toBigInteger()) val s = size.toBigInteger() val s1 = s.minus(BigInteger.ONE) if (ix1 >= s) { val a0 = (ix1 - s) / (s1) - BigInteger.ONE for (i in 0..4) { val ix2 = ix1 - a0.plus(i.toBigInteger()) * s1 if (ix2 < s && ix2 >= BigInteger.ZERO) { ix1 = ix2 break } } } if (ix1 < BigInteger.ZERO) { val a0 = ix1.negate() / (s1) - BigInteger.ONE for (i in 0..4) { val ix2 = ix1 + a0.plus(i.toBigInteger()) * s1 if (ix2 < s && ix2 >= BigInteger.ZERO) { ix1 = ix2 break } } } if (moves < BigInteger.ZERO && ix1 == BigInteger.ZERO) { ix1 = s1 } val ix11 = ix1.toInt() if (ix0 != ix11) { removeAt(ix0) add(ix11, number) } } fun solve() { val f = File("src/2022/inputs/day20.in") val s = Scanner(f) // val s = Scanner(input1) val numbers: MutableList<Pair<Int, BigInteger>> = mutableListOf() var ix = 0 // val key = BigInteger("811589153") val key = BigInteger("811589153") while (s.hasNextLine()) { val line = s.nextLine().trim() if (!line.isEmpty()) { numbers.add(ix to BigInteger(line).times(key)) ++ix } } // val mixer = numbers.toMutableList() // println(numbers.map{it.second}) for (j in 0 until 10) { for (i in 0 until numbers.size) { numbers.move(i) } println(numbers.map{it.second}) } println("${numbers.size} ${numbers.toSet().size}") println(numbers) val ix0 = numbers.indexOfFirst { it.second.equals(BigInteger.ZERO) } val ix1 = (ix0+1000)%numbers.size val ix2 = (ix0+2000)%numbers.size val ix3 = (ix0+3000)%numbers.size println("$ix0 ${numbers[ix1].second} ${numbers[ix2].second} ${numbers[ix3].second}") println("$ix0 ${numbers[ix1].second} + ${numbers[ix2].second} + ${numbers[ix3].second} = ${numbers[ix1].second + numbers[ix2].second + numbers[ix3].second}") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
2,810
advent-of-code
Apache License 2.0
src/Day09.kt
jbotuck
573,028,687
false
{"Kotlin": 42401}
import kotlin.math.abs import kotlin.math.sign fun main() { val lines = readInput("Day09") var rope = Rope() for (line in lines) { rope.execute(line) } println(rope.countOfSpotsTailVisited()) rope = Rope(10) for (line in lines) { rope.execute(line) } println(rope.countOfSpotsTailVisited()) } private data class Point(val x: Int = 0, val y: Int = 0) { fun follow(other: Point): Point { val xDiff = other.x - x val yDiff = other.y - y return if (abs(xDiff) > 1 || abs(yDiff) > 1) { Point( x + sign(xDiff.toDouble()).toInt(), y + sign(yDiff.toDouble()).toInt() ) } else this } } private class Rope(knotCount: Int = 2) { val knots = Array(knotCount) { Point() } val visited = mutableSetOf(knots.last()) fun countOfSpotsTailVisited() = visited.size fun execute(line: String) { val (direction, distance) = line.split(" ") val move: Point.() -> Point = when (direction) { "U" -> { { copy(y = y.inc()) } } "D" -> { { copy(y = y.dec()) } } "L" -> { { copy(x = x.dec()) } } "R" -> { { copy(x = x.inc()) } } else -> throw IllegalArgumentException() } repeat(distance.toInt()) { knots[0] = knots[0].move() for (i in 1..knots.lastIndex) { knots[i] = knots[i].follow(knots[i.dec()]) } visited.add(knots.last()) } } }
0
Kotlin
0
0
d5adefbcc04f37950143f384ff0efcd0bbb0d051
1,654
aoc2022
Apache License 2.0
src/Day01.kt
ianredman26
572,914,381
false
{"Kotlin": 3237}
fun main() { fun part1(input: List<String>): List<Pair<Int, Int>> { val elves: MutableMap<Int, Int> = mutableMapOf() var total = 0 input.map { total = if (it.isEmpty()) { elves[elves.size.plus(1)] = total 0 } else { total.plus(it.toInt()) } } return elves.toList().sortedByDescending { (_, value) -> value } } fun part2(input: List<Pair<Int, Int>>): Int { val total = input[0].second.plus(input[1].second).plus(input[3].second) return total } val testInput = readInput("Day01_part1") // test if implementation meets criteria from the description, like: // check(part1(testInput) == 4) // val input = readInput("Day01") println(part1(testInput)) println(part2(part1(testInput))) }
0
Kotlin
0
0
dcd9fae4531622cc974d2eb3d5ded94bf268ad1e
864
advent-of-code-2022
Apache License 2.0
src/Day03.kt
emmanueljohn1
572,809,704
false
{"Kotlin": 12720}
fun main() { fun getScore(ch: Char): Int { if(ch.isLowerCase()) { return (ch.code - 97) + 1 } return (ch.code - 65) + 27 } fun part1(input: List<String>): Int { return input.flatMap { line -> val (chest1, chest2) = line.chunked(line.length / 2) chest1.toSet().intersect(chest2.toSet()) }.sumOf(::getScore) } fun badgeScore(chunk: List<String>): Int { return chunk.map { it.toSet() } .reduce{ acc, cur -> acc.intersect(cur) } .map{ getScore(it) }.first() } fun part2(input: List<String>): Int { return input.windowed(3, 3).sumOf { badgeScore(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("inputs/Day03_test") println(part1(testInput)) println(part2(testInput)) println("----- Real input -------") val input = readInput("inputs/Day03") println(part1(input)) println(part2(input)) } // 157 // 70 // ----- Real input ------- // 7990 // 2602
0
Kotlin
0
0
154db2b1648c9d12f82aa00722209741b1de1e1b
1,080
advent22
Apache License 2.0
2015/src/main/kotlin/day18.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Grid import utils.MutableGrid import utils.Solution import utils.createMutableGrid import utils.toMutable fun main() { Day18.run() } object Day18 : Solution<Grid<Char>>() { override val name = "day18" override val parser = Grid.chars(oobBehaviour = Grid.OobBehaviour.Default('.')) private const val STEPS = 100 private fun simulate(prev: Grid<Char>, next: MutableGrid<Char>) { next.coords.forEach { p -> val neighbours = p.surrounding.count { prev[it] == '#' } if (prev[p] == '#') { next[p] = if (neighbours in 2 .. 3) '#' else '.' } else { next[p] = if (neighbours == 3) '#' else '.' } } } private fun solve(input: Grid<Char>, modify: MutableGrid<Char>.() -> Unit = {}): Int { var a = input.toMutable() var b = createMutableGrid<Char>(a.width, a.height, input.oobBehaviour) { '.' } repeat(STEPS) { simulate(a, b) b.modify() a = b.also { b = a } } return a.values.count { it == '#' } } override fun part1(input: Grid<Char>): Any? { return solve(input) } override fun part2(input: Grid<Char>): Any? { return solve(input) { // turn on the 4 corners corners.forEach { (p, _) -> this[p] = '#' } } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,281
aoc_kotlin
MIT License
src/main/kotlin/day04/Day04.kt
daniilsjb
434,765,082
false
{"Kotlin": 77544}
package day04 import java.io.File fun main() { val (numbers, boards) = parse("src/main/kotlin/day04/Day04.txt") val answer1 = part1(numbers, boards.map(List<Int>::toMutableList)) val answer2 = part2(numbers, boards.map(List<Int>::toMutableList)) println("🎄 Day 04 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private fun parse(path: String): Pair<List<Int>, List<List<Int>>> { val entries = File(path) .readText() .trim() .split("""\s+""".toRegex()) val numbers = entries.first() .split(",") .map(String::toInt) val boards = entries.subList(1, entries.size) .map(String::toInt) .chunked(25) return Pair(numbers, boards) } // We need to keep track of each board's state as the game progresses. // The simplest and most effective approach would be to mutate the board itself. private typealias Board = MutableList<Int> // Boards have a sense of dimensionality, but all numbers are stored as flat lists. // This structure allows us to fully describe a given number's position. private data class Position( val col: Int, val row: Int, val idx: Int, ) // It is important to remember that a number is not guaranteed to appear on every // board, therefore it may not always have a position. private fun Board.findPosition(number: Int): Position? = (0 until 5).firstNotNullOfOrNull { row -> (0 until 5).firstNotNullOfOrNull { col -> val index = row * 5 + col if (this[index] == number) Position(col, row, index) else null } } // There are several approaches we could use to signify that a given number was // marked, here's one of them: all numbers that appear on boards are always positive; // therefore, we can use the sign of the number as the "marked" flag. // // Since a marked number is never needed again, we are free to discard it during // the calculations and replace it with something completely different. This may // not be the cleanest approach, but it lets us reuse space efficiently, avoid // introducing extra data classes, etc. private fun Board.mark(idx: Int) { this[idx] = -1 } // Naturally, the board may be put into a winning position only after a number // was marked, and the number can only affect one row and one column. It's enough // to just check these two, without bothering the rest of the board. private fun Board.hasWon(col: Int, row: Int) = (0 until 5).all { i -> this[row * 5 + i] < 0 } || (0 until 5).all { i -> this[i * 5 + col] < 0 } // For the first part of the problem, the algorithm is straightforward: // we mark each number, in turn, on each board, until we encounter a winning // position, in which case the result is directly returned. private fun part1(numbers: List<Int>, boards: List<Board>) = numbers.firstNotNullOf { number -> boards.firstNotNullOfOrNull { board -> board.findPosition(number)?.let { (col, row, idx) -> board.mark(idx) if (board.hasWon(col, row)) number * board.sumOf { i -> if (i >= 0) i else 0 } else null } } } // For the second part, the approach is a little more involved: we go through // each board and find the first winning turn (each board is guaranteed to win // at some point); we then find the victory that happened on the latest turn // and use it to calculate the final result. private data class Victory( val turn: Int, val number: Int, val board: Board ) private fun part2(numbers: List<Int>, boards: List<Board>) = boards.map { board -> numbers.indexOfFirst { number -> board.findPosition(number)?.let { (col, row, idx) -> board.mark(idx) board.hasWon(col, row) } ?: false } .let { turn -> Victory(turn, numbers[turn], board) } } .maxByOrNull(Victory::turn)!! .let { (_, number, board) -> number * board.sumOf { i -> if (i >= 0) i else 0 } }
0
Kotlin
0
1
bcdd709899fd04ec09f5c96c4b9b197364758aea
4,206
advent-of-code-2021
MIT License
src/main/kotlin/QuickSort.kt
Codextor
453,514,033
false
{"Kotlin": 26975}
/** * Swap two elements in an array. */ private fun swap(arr: Array<Int>, i: Int, j: Int) { val temp = arr[i] arr[i] = arr[j] arr[j] = temp } /** * Partition the array around a randomly selected pivot. * Return the index of the pivot. */ private fun partition(arr: Array<Int>, left: Int, right: Int): Int { val randomIndex = (left..right).random() swap(arr, randomIndex, right) val pivot = arr[right] var pivotIndex = left - 1 for (index in left..right) { if (arr[index] <= pivot) { pivotIndex++ swap(arr, pivotIndex, index) } } return pivotIndex } /** * Quick sort the array. */ private fun quickSort(arr: Array<Int>, left: Int, right: Int) { if (left < right) { val pivotIndex = partition(arr, left, right) quickSort(arr, left, pivotIndex - 1) quickSort(arr, pivotIndex + 1, right) } } fun main() { val arrayOfIntegers = readLine()?.trimEnd()?.split(" ")?.map { it.toInt() }?.toTypedArray() ?: return quickSort(arrayOfIntegers, 0, arrayOfIntegers.size-1) arrayOfIntegers.forEach { print("$it ") } }
0
Kotlin
1
0
68b75a7ef8338c805824dfc24d666ac204c5931f
1,139
kotlin-codes
Apache License 2.0
leetcode-75-kotlin/src/main/kotlin/UniqueNumberOfOccurrences.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * Given an array of integers arr, * return true if the number of occurrences of each value in the array is unique or false otherwise. * * * * Example 1: * * Input: arr = [1,2,2,1,1,3] * Output: true * Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. * Example 2: * * Input: arr = [1,2] * Output: false * Example 3: * * Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] * Output: true * * * Constraints: * * 1 <= arr.length <= 1000 * -1000 <= arr[i] <= 1000 * @see <a href="https://leetcode.com/problems/unique-number-of-occurrences/">LeetCode</a> */ fun uniqueOccurrences(arr: IntArray): Boolean { val mapOfNumbers = mutableMapOf<Int, Int>() arr.forEach { number -> mapOfNumbers[number] = 1 + mapOfNumbers.getOrDefault(number, 0) } val setOfFrequencies = mutableSetOf<Int>() mapOfNumbers.values.forEach { frequency -> if (!setOfFrequencies.add(frequency)) { return false } } return true }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,039
leetcode-75
Apache License 2.0
src/Day08.kt
gojoel
573,543,233
false
{"Kotlin": 28426}
import kotlin.math.max enum class Direction { UP, DOWN, LEFT, RIGHT } // TODO: improve performance fun main() { val input = readInput("08") // val input = readInput("08_test") fun buildGrid(input: List<String>) : ArrayList<IntArray> { val numCols = input[0].length val grid: ArrayList<IntArray> = arrayListOf() input.forEach { treeRow -> val arr = IntArray(numCols) treeRow.forEachIndexed { index, c -> arr[index] = Character.getNumericValue(c) } grid.add(arr) } return grid } fun previousMax(grid: ArrayList<IntArray>, row: Int, col: Int, direction: Direction) : Int { var max = 0 when (direction) { Direction.UP -> { var pos = row while (pos >= 0) { max = max(max, grid[pos][col]) pos-- } } Direction.DOWN -> { var pos = row while (pos < grid.size) { max = max(max, grid[pos][col]) pos++ } } Direction.RIGHT -> { var pos = col while (pos < grid[row].size) { max = max(max, grid[row][pos]) pos++ } } Direction.LEFT -> { var pos = col while (pos >= 0) { max = max(max, grid[row][pos]) pos-- } } } return max } fun viewingDistance(tree: Int, grid: ArrayList<IntArray>, row: Int, col: Int, direction: Direction) : Int { var distance = 0 when (direction) { Direction.UP -> { var pos = row while (pos >= 0) { distance++ if (grid[pos][col] >= tree) { break } pos-- } } Direction.DOWN -> { var pos = row while (pos < grid.size) { distance++ if (grid[pos][col] >= tree) { break } pos++ } } Direction.LEFT -> { var pos = col while (pos >= 0) { distance++ if (grid[row][pos] >= tree) { break } pos-- } } Direction.RIGHT -> { var pos = col while (pos < grid[row].size) { distance++ if (grid[row][pos] >= tree) { break } pos++ } } } return distance; } fun part1(input: List<String>): Int { val grid = buildGrid(input) var visible = 0 grid.forEachIndexed { rowIdx, row -> row.forEachIndexed { treeIdx, tree -> if (rowIdx == 0 || rowIdx == grid.size - 1 || treeIdx == 0 || treeIdx == row.size - 1) { // edges visible++ } else { val left = previousMax(grid, rowIdx, treeIdx - 1, Direction.LEFT) val right = previousMax(grid, rowIdx, treeIdx + 1, Direction.RIGHT) val top = previousMax(grid, rowIdx - 1, treeIdx, Direction.UP) val bottom = previousMax(grid, rowIdx + 1, treeIdx, Direction.DOWN) if (left < tree || right < tree || top < tree || bottom < tree) { visible++ } } } } return visible } fun part2(input: List<String>): Int { val grid = buildGrid(input) var scenicScore = 0 grid.forEachIndexed { rowIdx, row -> row.forEachIndexed { treeIdx, tree -> val left = viewingDistance(tree, grid, rowIdx, treeIdx - 1, Direction.LEFT) val right = viewingDistance(tree, grid, rowIdx, treeIdx + 1, Direction.RIGHT) val top = viewingDistance(tree, grid, rowIdx - 1, treeIdx, Direction.UP) val bottom = viewingDistance(tree, grid, rowIdx + 1, treeIdx, Direction.DOWN) val score = left * right * top * bottom scenicScore = max(scenicScore, score) } } return scenicScore } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0690030de456dad6dcfdcd9d6d2bd9300cc23d4a
4,753
aoc-kotlin-22
Apache License 2.0
src/main/kotlin/day02/Problem.kt
xfornesa
572,983,494
false
{"Kotlin": 18402}
package day02 fun solveProblem01(input: List<Pair<String, String>>): Int { var score = 0 input.forEach { score += round01(it) } return score } // A for Rock, B for Paper, and C for Scissors // X for Rock, Y for Paper, and Z for Scissors // score: (1 for Rock, 2 for Paper, and 3 for Scissors) + (0 if you lost, 3 if the round was a draw, and 6 if you won) private fun round01(pair: Pair<String, String>): Int { var figureScore = 0 when (pair.second) { "X" -> figureScore = 1 "Y" -> figureScore = 2 "Z" -> figureScore = 3 } var winningScore = 0 when (pair) { Pair("A", "X") -> winningScore = 3 Pair("A", "Y") -> winningScore = 6 Pair("A", "Z") -> winningScore = 0 Pair("B", "X") -> winningScore = 0 Pair("B", "Y") -> winningScore = 3 Pair("B", "Z") -> winningScore = 6 Pair("C", "X") -> winningScore = 6 Pair("C", "Y") -> winningScore = 0 Pair("C", "Z") -> winningScore = 3 } return figureScore + winningScore } fun solveProblem02(input: List<Pair<String, String>>): Int { var score = 0 input.forEach { score += round02(it) } return score } // A for Rock, B for Paper, and C for Scissors // X for lose, Y for draw, and Z for win // score: (1 for Rock, 2 for Paper, and 3 for Scissors) + (0 if you lost, 3 if the round was a draw, and 6 if you won) private fun round02(pair: Pair<String, String>): Int { var winningScore = 0 when (pair.second) { "X" -> winningScore = 0 "Y" -> winningScore = 3 "Z" -> winningScore = 6 } var figureScore = 0 when (pair) { // rock Pair("A", "X") -> figureScore = 3 // lose with scissors Pair("A", "Y") -> figureScore = 1 // draw with rock Pair("A", "Z") -> figureScore = 2 // win with paper // paper Pair("B", "X") -> figureScore = 1 // lose with rock Pair("B", "Y") -> figureScore = 2 // draw with paper Pair("B", "Z") -> figureScore = 3 // win with scissors // scissors Pair("C", "X") -> figureScore = 2 // lose with paper Pair("C", "Y") -> figureScore = 3 // draw with scissors Pair("C", "Z") -> figureScore = 1 // win with rock } return figureScore + winningScore }
0
Kotlin
0
0
dc142923f8f5bc739564bc93b432616608a8b7cd
2,333
aoc2022
MIT License
src/main/kotlin/endredeak/aoc2023/Day03.kt
edeak
725,919,562
false
{"Kotlin": 26575}
package endredeak.aoc2023 import endredeak.aoc2023.lib.utils.productOf import kotlin.math.max import kotlin.math.min data class Symbol(val x: Int, val y: Int, val c: Char) data class Number(val x: Int, val y: Int, var value: Long) fun Char.isSymbol() = !this.isDigit() && this != '.' fun createMap(lines: List<String>) = lines .let { grid -> val map = mutableMapOf<Symbol, MutableSet<Number>>() grid.indices.forEach { y -> var num = "" var offset = -1 grid[0].indices.forEach { x -> val c = grid[y][x] if (c.isDigit()) { if (num.isBlank()) { offset = x } num += c } if (x == grid[0].lastIndex || !c.isDigit()) { if (num.isNotBlank()) { val number = Number(x, y, num.toLong()) (max(y - 1, 0)..min(grid.lastIndex, y + 1)).forEach { ny -> (max(offset - 1, 0)..min(grid[0].lastIndex, x)).forEach { nx -> val nc = grid[ny][nx] if (nc.isSymbol()) { map.computeIfAbsent(Symbol(nx, ny, nc)) { mutableSetOf() }.add(number) } } } num = "" offset = -1 } } } } map } fun main() { solve("Gear Ratios") { val input = createMap(lines) part1(556367) { input.values .flatten() .sumOf { it.value } } part2(89471771) { input.filterKeys { it.c == '*' } .filterValues { it.size == 2 } .values .sumOf { it.productOf { n -> n.value } } } } }
0
Kotlin
0
0
92c684c42c8934e83ded7881da340222ff11e338
1,983
AdventOfCode2023
Do What The F*ck You Want To Public License
src/main/kotlin/com/staricka/adventofcode2022/Day5.kt
mathstar
569,952,400
false
{"Kotlin": 77567}
package com.staricka.adventofcode2022 import com.staricka.adventofcode2022.Day5.Stacks.Companion.parseToStacks class Day5 : Day { override val id = 5 class Stacks(n: Int) { val stacks = ArrayList<ArrayDeque<Char>>(n) init { for (x in 1..n) { stacks.add(ArrayDeque()) } } fun apply(move: Move) { for (i in 1..move.count) { stacks[move.dest - 1].addLast(stacks[move.source - 1].removeLast()) } } fun applyPart2(move: Move) { val moving = ArrayList<Char>() for (i in 1..move.count) { moving.add(stacks[move.source - 1].removeLast()) } moving.reversed().forEach{stacks[move.dest - 1].addLast(it)} } companion object { fun String.parseToStacks(): Stacks { val count = this.lines().first().length / 4 + 1 val stacks = Stacks(count) for (line in this.lines()) { if (!line.trim().startsWith('[')) continue for (i in 0 until count) { val crate = line[1 + 4 * i] if (!crate.isWhitespace()) { stacks.stacks[i].addFirst(crate) } } } return stacks } } } data class Move(val count: Int, val source: Int, val dest: Int) { companion object { val MOVE_REGEX = Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)") } } private fun parseInput(input: String): Pair<Stacks, List<Move>> { var stacksInput = "" val moves = ArrayList<Move>() var inStacks = true for (line in input.lines()) { if (inStacks) { if (line.isBlank()) { inStacks = false continue } stacksInput += line + "\n" } else { val match = Move.MOVE_REGEX.matchEntire(line) moves.add(Move(match!!.groups[1]!!.value.toInt(), match.groups[2]!!.value.toInt(), match.groups[3]!!.value.toInt())) } } return Pair(stacksInput.parseToStacks(), moves) } override fun part1(input: String): Any { val (stacks, moves) = parseInput(input) moves.forEach {stacks.apply(it)} return stacks.stacks.map {it.last()}.joinToString(separator = "") } override fun part2(input: String): Any { val (stacks, moves) = parseInput(input) moves.forEach {stacks.applyPart2(it)} return stacks.stacks.map {it.last()}.joinToString(separator = "") } }
0
Kotlin
0
0
2fd07f21348a708109d06ea97ae8104eb8ee6a02
2,367
adventOfCode2022
MIT License
src/main/kotlin/com/github/michaelbull/advent2021/day11/Grid.kt
michaelbull
433,565,311
false
{"Kotlin": 162839}
package com.github.michaelbull.advent2021.day11 import com.github.michaelbull.advent2021.math.Vector2 import com.github.michaelbull.advent2021.math.Vector2.Companion.CARDINAL_DIRECTIONS import com.github.michaelbull.advent2021.math.Vector2.Companion.ORDINAL_DIRECTIONS fun Sequence<String>.toGrid(): Grid { val cells = buildMap { for ((y, line) in withIndex()) { for ((x, char) in line.withIndex()) { set(Vector2(x, y), char.digitToInt()) } } } return Grid(cells) } data class Grid( val cells: Map<Vector2, Int> ) { val flashedCount: Int get() = cells.values.count(::flashed) val allFlashed: Boolean get() = cells.values.all(::flashed) fun step(): Grid { return increment() .flash() .reset() } fun stepSequence(): Sequence<Grid> { return generateSequence(this, Grid::step) } private fun flashed(energy: Int): Boolean { return energy == ENERGY_RANGE.first } private fun flashing(energy: Int): Boolean { return energy > ENERGY_RANGE.last } private fun flashingPositions(): Set<Vector2> { return cells.filterValues(::flashing).keys } private fun increment(): Grid { val incremented = cells.mapValues { it.value + 1 } return copy(cells = incremented) } private fun flash(): Grid { val flashingPositions = flashingPositions().toMutableSet() val flashedPositions = flash(flashingPositions) val flashed = cells.mapValues { (position, energy) -> val adjacentFlashes = adjacentPositions(position).count(flashedPositions::contains) energy + adjacentFlashes } return copy(cells = flashed) } private fun reset(): Grid { val reset = cells.mapValues { (_, energy) -> if (flashing(energy)) { ENERGY_RANGE.first } else { energy } } return copy(cells = reset) } private tailrec fun flash(positions: MutableSet<Vector2>): Set<Vector2> { val adjacentFlashingPositions = adjacentFlashingPositions(positions) return if (positions.containsAll(adjacentFlashingPositions)) { positions } else { positions += adjacentFlashingPositions flash(positions) } } private fun adjacentFlashingPositions(positions: Set<Vector2>): List<Vector2> { return positions .flatMap(::adjacentPositions) .filter { it.willFlashFrom(positions) } } private fun Vector2.willFlashFrom(flashingPositions: Set<Vector2>): Boolean { val adjacentFlashes = adjacentPositions(this).intersect(flashingPositions) val energy = cells.getValue(this) return flashing(energy + adjacentFlashes.size) } private fun adjacentPositions(position: Vector2): List<Vector2> { return ADJACENT_DIRECTIONS .map { position + it } .filter { it in cells } } private companion object { private val ENERGY_RANGE = 0..9 private val ADJACENT_DIRECTIONS = CARDINAL_DIRECTIONS + ORDINAL_DIRECTIONS } }
0
Kotlin
0
4
7cec2ac03705da007f227306ceb0e87f302e2e54
3,246
advent-2021
ISC License
src/main/kotlin/us/jwf/aoc2021/Day08SevenSegmentSearch.kt
jasonwyatt
318,073,137
false
null
package us.jwf.aoc2021 import java.io.Reader import us.jwf.aoc.Day /** * AoC 2021 - Day 8 */ class Day08SevenSegmentSearch : Day<Int, Int> { override suspend fun executePart1(input: Reader): Int { return input.readLines() .sumOf { it.countDigitsDumb() } } override suspend fun executePart2(input: Reader): Int { return input.readLines() .map { it.findOutput() } .sum() } fun String.countDigitsDumb(): Int { val (_, output) = split("|") return output.trim().split(" ").count { it.length in setOf(2, 3, 7, 4) } } fun String.findOutput(): Int { val (samples, output) = split(" | ").map { it.trim().split(" ") } val oneStr = samples.find { it.length == 2 }!! val fourStr = samples.find { it.length == 4 }!! val sevenStr = samples.find { it.length == 3 }!! val findings = mutableMapOf( samples.find { it.length == 2 }!!.toSet().sorted().joinToString("") to 1, samples.find { it.length == 4 }!!.toSet().sorted().joinToString("") to 4, samples.find { it.length == 3 }!!.toSet().sorted().joinToString("") to 7, samples.find { it.length == 7 }!!.toSet().sorted().joinToString("") to 8, ) val nonBasics = samples.filter { it.length !in setOf(2, 3, 4, 7) }.map { it.toSet() } val bottomAndBottomLeft = (nonBasics.fold(setOf<Char>()) { acc, i -> acc + i }) - (sevenStr.toSet() + fourStr.toSet()) val bottom = bottomAndBottomLeft - (sevenStr.toSet() - fourStr.toSet()) val middleAndTopLeft = fourStr.toSet() - oneStr.toSet() val five = nonBasics.find { it.size == 5 && (it - middleAndTopLeft).size == 3 }!! findings[five.sorted().joinToString("")] = 5 val three = nonBasics.find { it.size == 5 && it != five && (it - sevenStr.toSet()).size == 2 }!! findings[three.sorted().joinToString("")] = 3 val middle = three - sevenStr.toSet() - bottom val two = nonBasics.find { it.size == 5 && it != three && it != five }!! findings[two.sorted().joinToString("")] = 2 val zero = nonBasics.find { it.size == 6 && it - middle == it }!! println("zero = $zero") findings[zero.sorted().joinToString("")] = 0 val nine = nonBasics.find { it.size == 6 && it != zero && (it - sevenStr.toSet()).size == 3 }!! findings[nine.sorted().joinToString("")] = 9 val six = nonBasics.find { it.size == 6 && it != zero && it != nine }!! findings[six.sorted().joinToString("")] = 6 return output.map { findings[it.toList().sorted().joinToString("")]!! } .joinToString("") .toInt() } }
0
Kotlin
0
0
0c92a62ba324aaa1f21d70b0f9f5d1a2c52e6868
2,539
AdventOfCode-Kotlin
Apache License 2.0
src/Day05.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
class Day05(l: List<String>) { init { // println(l) } private val lines = l.joinToString("\n").split("\n\n") private val startingStacks = this.lines[0].lines() private val stackCount = startingStacks.reversed()[0].last().digitToInt() private val moves = this.lines[1].lines() fun part1(): String { val stacks = MutableList<MutableList<Char>>(stackCount) { mutableListOf() } startingStacks.reversed().drop(1) .forEach { it.chunked(4).forEachIndexed { i, str -> if (str[1].isLetter()) stacks[i].add(str[1]) } } for (m in moves) { val parts = m.split(" ") val num = parts[1].toInt() val s = parts[3].toInt() - 1 val d = parts[5].toInt() - 1 stacks[d].addAll(stacks[s].takeLast(num).reversed()) repeat(num) { stacks[s].removeLast() } } return stacks.joinToString(separator = "") { if (it.isNotEmpty()) it.last().toString() else "" } } fun part2(): String { val stacks = MutableList<MutableList<Char>>(stackCount) { mutableListOf() } startingStacks.reversed().drop(1) .forEach { it.chunked(4).forEachIndexed { i, str -> if (str[1].isLetter()) stacks[i].add(str[1]) } } for (m in moves) { val parts = m.split(" ") val num = parts[1].toInt() val s = parts[3].toInt() - 1 val d = parts[5].toInt() - 1 stacks[d].addAll(stacks[s].takeLast(num)) repeat(num) { stacks[s].removeLast() } } return stacks.joinToString(separator = "") { if (it.isNotEmpty()) it.last().toString() else "" } } } fun main() { val day = "day5_input" val today = Day05(readInput(day)).part2() println(today) // println("Day $day: pt 2") // Wrong guess: FWNSHLDNZ }
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
1,980
advent22
Apache License 2.0
src/Day04.kt
JonahBreslow
578,314,149
false
{"Kotlin": 6978}
import java.io.File import kotlin.math.min fun main () { fun parseInput(input: String) : List<List<Set<Int>>>{ return File(input) .readLines() .map { it.split(",") } .map{ val set1 = (it[0].split("-")[0].toInt() until it[0].split("-")[1].toInt()+1).map{it}.toSet() val set2 = (it[1].split("-")[0].toInt() until it[1].split("-")[1].toInt()+1).map{it}.toSet() listOf(set1, set2) } } fun part1(input: String) : Int{ val overlaps = parseInput(input) .map{ if((it[0].intersect(it[1]).size) == min(it[0].size, it[1].size)){ 1 } else { 0 } } return overlaps.sum() } fun part2(input: String) : Int{ val overlaps = parseInput(input) .map{ if((it[0].intersect(it[1]).size) > 0 ){ 1 } else { 0 } } return overlaps.sum() } val testFile = "data/day4_test.txt" check(part1(testFile) == 2) check(part2(testFile) == 4) val inputFile = "data/day4.txt" println(part1(inputFile)) println(part2(inputFile)) }
0
Kotlin
0
1
c307ff29616f613473768168cc831a7a3fa346c2
1,261
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/aoc2023/Day22.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import Point3 import overlaps import readInput import kotlin.math.max import kotlin.math.min object Day22 { private data class Brick(private val start: Point3, private val end: Point3) { val xRange = min(start.x, end.x)..max(start.x, end.x) val yRange = min(start.y, end.y)..max(start.y, end.y) val zRange = min(start.z, end.z)..max(start.z, end.z) companion object { fun fromString(input: String): Brick { val split = input.split("~") return Brick(Point3.fromCsvString(split.first()), Point3.fromCsvString(split.last())) } } /** * Move the brick downwards by the given delta * @param dz the distance to move in z direction */ fun moveDown(dz: Int) = Brick(start.move(0, 0, -dz), end.move(0, 0, -dz)) /** * @return true, if this brick lays directly on any of the bricks given in [other] */ fun laysOnAny(other: Set<Brick>) = other.any { otherBrick -> xRange.overlaps(otherBrick.xRange) && yRange.overlaps(otherBrick.yRange) && zRange.first == otherBrick.zRange.last + 1 } /** * @return true, if this brick supports the [other] brick from falling down */ fun supports(other: Brick) = xRange.overlaps(other.xRange) && yRange.overlaps(other.yRange) && zRange.last == other.zRange.first - 1 } private fun getBricksInFinalPosition(input: List<String>): Set<Brick> { val fallingBricks = input.map { Brick.fromString(it) } val bricksInFinalPosition = mutableSetOf<Brick>() // fall down fallingBricks.sortedBy { it.zRange.first }.forEach { brick -> if (brick.zRange.first == 1L) { bricksInFinalPosition.add(brick) } else { var tmpBrick = brick while (!tmpBrick.laysOnAny(bricksInFinalPosition) && tmpBrick.zRange.first > 1) { tmpBrick = tmpBrick.moveDown(1) } bricksInFinalPosition.add(tmpBrick) } } return bricksInFinalPosition } /** * @return bricks, which are only supported by [toTest] (e.g. which would fall down if [toTest] was removed) */ private fun getDependantBricks(toTest: Brick, bricks: Collection<Brick>): Collection<Brick> { val bricksSupportedByTheCurrentBrick = bricks.filter { it.zRange.first == toTest.zRange.last + 1 }.filter { toTest.supports(it) } val possibleOtherSupports = bricks.filter { it != toTest && it.zRange.last == toTest.zRange.last } val unsupportedBricks = bricksSupportedByTheCurrentBrick.filter { brickToTest -> possibleOtherSupports.none { support -> support.supports(brickToTest) } } return unsupportedBricks } /** * Tests, how many bricks would fall when removing a set of bricks. * * @param removedBricks the bricks to remove * @param remainingBricks the bricks, which are still standing (all bricks except those in [removedBricks]) * @return the number of bricks, which would fall further down if the bricks in [removedBricks] are removed */ private fun wouldFall(removedBricks: Set<Brick>, remainingBricks: Collection<Brick>): Int { val unsupportedBricks = remainingBricks.filter { brick -> brick.zRange.first > 1 && remainingBricks.none { it.supports(brick) } } return if (unsupportedBricks.isNotEmpty()) { wouldFall(removedBricks + unsupportedBricks, remainingBricks.filter { it !in removedBricks }) } else { removedBricks.size } } fun part1(input: List<String>): Int { val allBricks = getBricksInFinalPosition(input) val bricksSafeToRemove = allBricks.filter { brick -> getDependantBricks(brick, allBricks).isEmpty() } return bricksSafeToRemove.size } fun part2(input: List<String>): Int { val allBricks = getBricksInFinalPosition(input) val bricksUnSafeToRemove = allBricks.filter { brick -> getDependantBricks(brick, allBricks).isNotEmpty() } // fast enough for the puzzle input, no need to optimize return bricksUnSafeToRemove.parallelStream().map { brickToRemove -> // -1 because we must not count the 'brickToRemove' itself wouldFall(setOf(brickToRemove), allBricks.filter { it != brickToRemove }) - 1 }.reduce(0) { a, b -> a + b } } } fun main() { val testInput = readInput("Day22_test", 2023) check(Day22.part1(testInput) == 5) check(Day22.part2(testInput) == 7) val input = readInput("Day22", 2023) println(Day22.part1(input)) println(Day22.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
4,813
adventOfCode
Apache License 2.0
day-02/src/main/kotlin/Dive.kt
diogomr
433,940,168
false
{"Kotlin": 92651}
fun main() { println("Part One Solution: ${partOne()}") println("Part Two Solution: ${partTwo()}") } private fun partOne(): Int { var horizontal = 0 var depth = 0 readInput() .forEach { when (it.first) { Command.FORWARD -> horizontal += it.second Command.DOWN -> depth += it.second Command.UP -> depth -= it.second } } return horizontal * depth } private fun partTwo(): Int { var aim = 0 var horizontal = 0 var depth = 0 readInput() .forEach { when (it.first) { Command.FORWARD -> { horizontal += it.second depth += aim * it.second } Command.DOWN -> aim += it.second Command.UP -> aim -= it.second } } return horizontal * depth } private fun readInput(): List<Pair<Command, Int>> { return {}::class.java.classLoader.getResource("input.txt") .readText() .split("\n") .filter { it.isNotBlank() } .map { val split = it.split(" ") val command = Command.valueOf(split[0].uppercase()) val value = split[1].toInt() Pair(command, value) } } enum class Command { FORWARD, DOWN, UP, }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
1,364
aoc-2021
MIT License
kotlin/src/katas/kotlin/skiena/combinatorial_search/Backtracking.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.skiena.combinatorial_search import katas.kotlin.skiena.combinatorial_search.SudokuTests.Sudoku.Companion.columnIndicesAt import katas.kotlin.skiena.combinatorial_search.SudokuTests.Sudoku.Companion.rowIndicesAt import katas.kotlin.skiena.combinatorial_search.SudokuTests.Sudoku.Companion.squareIndicesAt import katas.kotlin.skiena.graphs.Edge import katas.kotlin.skiena.graphs.Graph import katas.kotlin.skiena.graphs.UnweightedGraphs import nonstdlib.join import nonstdlib.printed import datsok.shouldEqual import nonstdlib.joinBy import org.junit.Test import java.util.ArrayList import kotlin.math.abs class SubsetsTests { @Test fun `find all subsets`() { subsets(setOf(1, 2, 3)).toString() shouldEqual "[[1, 2, 3], [2, 3], [3], [], [2], [1, 3], [1], [1, 2]]" subsets2(listOf(1, 2, 3)).toString() shouldEqual "[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]" } data class Subset( private val list: List<Int>, override val value: List<Int> = emptyList(), private val index: Int = 0 ) : Solution<List<Int>> { override fun hasNext() = index < list.size override fun skipNext() = copy(index = index + 1) override fun next() = copy(value = value + list[index], index = index + 1) override fun isComplete() = !hasNext() } private fun subsets2(list: List<Int>): List<List<Int>> = backtrack(Subset(list)).map { it.value } fun subsets(set: Set<Int>): Set<Set<Int>> { return setOf(set) + set.flatMap { subsets(set - it) } } } class AllPathsTests { @Test fun `find all paths in a graph`() { UnweightedGraphs.linearGraph.let { it.findAllPaths(from = 1, to = 1).toString() shouldEqual "[[1]]" it.findAllPaths(from = 1, to = 2).toString() shouldEqual "[[1, 2]]" it.findAllPaths(from = 1, to = 3).toString() shouldEqual "[[1, 2, 3]]" } UnweightedGraphs.disconnectedGraph.findAllPaths(from = 1, to = 4).toString() shouldEqual "[]" UnweightedGraphs.diamondGraph.findAllPaths(from = 1, to = 3).toString() shouldEqual "[[1, 4, 3], [1, 2, 3]]" UnweightedGraphs.meshGraph.findAllPaths(from = 1, to = 3).toString() shouldEqual "[[1, 4, 3], [1, 4, 2, 3], [1, 3], [1, 2, 4, 3], [1, 2, 3]]" } data class Path( private val graph: Graph<Int>, private val from: Int, private val to: Int, override val value: List<Int> = listOf(from), private val skipped: Set<Edge<Int>> = emptySet() ) : Solution<List<Int>> { private val nextEdge = graph.edgesByVertex[value.last()]!!.find { it.to !in value && it !in skipped } override fun hasNext() = nextEdge != null && !isComplete() override fun skipNext() = copy(skipped = skipped + nextEdge!!) override fun next() = copy(value = value + nextEdge!!.to) override fun isComplete() = value.last() == to } private fun Graph<Int>.findAllPaths(from: Int, to: Int): List<List<Int>> { return backtrack(Path(this, from, to)).map { it.value } } } class EightQueenTests { @Test fun `find queens positions on 4x4 board`() { eightQueen(boardSize = 4).map { it.toBoardString(4) } shouldEqual listOf( """|-*-- |---* |*--- |--*- """, """|--*- |*--- |---* |-*-- """ ).map { it.trimMargin() } } @Test fun `find queens positions on 8x8 board`() { val solutions = eightQueen(boardSize = 8) val (solution1, solution2, solution3) = solutions.take(3).map { it.toBoardString(8) } solution1 shouldEqual """ |--*----- |-----*-- |---*---- |-*------ |-------* |----*--- |------*- |*------- """.trimMargin() solution2 shouldEqual """ |--*----- |----*--- |-*------ |-------* |-----*-- |---*---- |------*- |*------- """.trimMargin() solution3 shouldEqual """ |----*--- |-*------ |---*---- |------*- |--*----- |-------* |-----*-- |*------- """.trimMargin() solutions.size shouldEqual 92 } private data class Queen(val row: Int, val column: Int) { override fun toString() = "[$row,$column]" } private data class EightQueenSolution( val boardSize: Int, override val value: List<Queen> = emptyList(), val row: Int = 0, val column: Int = 0, val valid: Boolean = true ) : Solution<List<Queen>> { override fun hasNext() = !isComplete() && valid override fun skipNext() = if (row + 1 < boardSize) copy(row = row + 1) else copy(row = 0, column = column + 1, valid = false) override fun next() = Queen(row, column).let { queen -> copy(value = value + queen, row = 0, column = column + 1, valid = isValid(queen)) } override fun isComplete() = boardSize == value.size && valid private fun isValid(queen: Queen): Boolean { val notOnTheSameLine = value.none { it.row == queen.row || it.column == queen.column } val notOnTheSameDiagonal = value.none { abs(it.row - queen.row) == abs(it.column - queen.column) } return notOnTheSameLine && notOnTheSameDiagonal } } private fun eightQueen(boardSize: Int): List<List<Queen>> { return backtrack(EightQueenSolution(boardSize)).map { it.value } } private fun List<Queen>.toBoardString(boardSize: Int) = 0.until(boardSize).joinBy("\n") { row -> 0.until(boardSize).joinBy("") { column -> if (contains(Queen(row, column))) "*" else "-" } } } class SudokuTests { private val sudokuBoardString = """ |6..|...|2.3 |...|4.3|8.. |.3.|7..|..9 |---+---+--- |...|.2.|1.. |49.|...|.65 |..6|.9.|... |---+---+--- |1..|..5|.8. |..9|6..|... |8.4|...|..2 """.trimMargin() private val sudoku = Sudoku.parse(sudokuBoardString) @Test fun `find easy sudoku solutions`() { val solutions = backtrack(sudoku) solutions.forEach { it.printed("\n\n") } solutions.first() shouldEqual Sudoku.parse(""" |648|951|273 |927|463|851 |531|782|649 |---+---+--- |785|326|194 |492|817|365 |316|594|728 |---+---+--- |173|245|986 |259|638|417 |864|179|532 """.trimIndent()) } @Test fun `sudoku solution steps`() { sudoku.hasNext() shouldEqual true sudoku.next().let { it.toString().lines().first() shouldEqual "61.|...|2.3" it.hasNext() shouldEqual true } sudoku.next().next().let { it.toString().lines().first() shouldEqual "611|...|2.3" it.hasNext() shouldEqual false } sudoku.skipNext().next().let { it.toString().lines().first() shouldEqual "62.|...|2.3" it.hasNext() shouldEqual false } sudoku.skipNext().skipNext().next().let { it.toString().lines().first() shouldEqual "63.|...|2.3" it.hasNext() shouldEqual false } sudoku.skipNext().skipNext().skipNext().next().let { it.toString().lines().first() shouldEqual "64.|...|2.3" it.hasNext() shouldEqual true } } @Test fun `sudoku conversion to string`() { sudoku.toString() shouldEqual sudokuBoardString } @Test fun `indices of sudoku rows`() { 0.until(9).forEach { rowIndicesAt(index = it) shouldEqual listOf(0, 1, 2, 3, 4, 5, 6, 7, 8) } 9.until(18).forEach { rowIndicesAt(index = it) shouldEqual listOf(9, 10, 11, 12, 13, 14, 15, 16, 17) } 72.until(81).forEach { rowIndicesAt(index = it) shouldEqual listOf(72, 73, 74, 75, 76, 77, 78, 79, 80) } } @Test fun `indices of sudoku columns`() { 0.until(9).map { it * 9 }.forEach { columnIndicesAt(index = it) shouldEqual listOf(0, 9, 18, 27, 36, 45, 54, 63, 72) } 0.until(9).map { it * 9 + 1 }.forEach { columnIndicesAt(index = it) shouldEqual listOf(1, 10, 19, 28, 37, 46, 55, 64, 73) } 0.until(9).map { it * 9 + 8 }.forEach { columnIndicesAt(index = it) shouldEqual listOf(8, 17, 26, 35, 44, 53, 62, 71, 80) } } @Test fun `indices of sudoku squares`() { listOf(0, 1, 2).forEach { squareIndicesAt(index = it) shouldEqual listOf(0, 1, 2, 9, 10, 11, 18, 19, 20) } listOf(9, 10, 11).forEach { squareIndicesAt(index = it) shouldEqual listOf(0, 1, 2, 9, 10, 11, 18, 19, 20) } listOf(18, 19, 20).forEach { squareIndicesAt(index = it) shouldEqual listOf(0, 1, 2, 9, 10, 11, 18, 19, 20) } listOf(3, 4, 5, 12, 13, 14, 21, 22, 23).forEach { squareIndicesAt(index = it) shouldEqual listOf(3, 4, 5, 12, 13, 14, 21, 22, 23) } listOf(6, 7, 8, 15, 16, 17, 24, 25, 26).forEach { squareIndicesAt(index = it) shouldEqual listOf(6, 7, 8, 15, 16, 17, 24, 25, 26) } listOf(60, 61, 62, 69, 70, 71, 78, 79, 80).forEach { squareIndicesAt(index = it) shouldEqual listOf(60, 61, 62, 69, 70, 71, 78, 79, 80) } } private data class Sudoku( override val value: List<Int>, private val guessIndex: Int = value.indexOf(0).let { if (it == -1) value.size else it }, private val guess: Int = 1 ) : Solution<List<Int>> { private val isValid = isValid() override fun hasNext() = guess <= 9 && guessIndex >= 0 && guessIndex < value.size && isValid override fun skipNext() = copy(guess = guess + 1) override fun next(): Solution<List<Int>> { val newValue = ArrayList(value).apply<ArrayList<Int>> { set(guessIndex, guess) } return Sudoku(value = newValue, guess = 1) } override fun isComplete() = isValid && 0 !in value private fun isValid(): Boolean = 0.until(guessIndex).all { index -> val n = value[index] rowIndicesAt(index).count { value[it] == n } == 1 && columnIndicesAt(index).count { value[it] == n } == 1 && squareIndicesAt(index).count { value[it] == n } == 1 } override fun toString(): String { return value.windowed(size = 9, step = 9).mapIndexed { i, row -> val separator = if (i == 3 || i == 6) "---+---+---\n" else "" separator + row.windowed(size = 3, step = 3).joinToString("|") { it.joinToString("").replace('0', '.') } }.joinToString("\n") } companion object { fun parse(s: String): Sudoku { val cells = s.replace(Regex("[|\\-+\n]"), "").mapTo(ArrayList()) { c -> if (c == '.') 0 else c.toString().toInt() } return Sudoku(cells, guess = 1) } fun rowIndicesAt(index: Int): List<Int> { val result = ArrayList<Int>() val firstColumnInRow = index / 9 * 9 firstColumnInRow.until(firstColumnInRow + 9).forEach { result.add(it) } return result } fun columnIndicesAt(index: Int): List<Int> { val result = ArrayList<Int>() val column = index.rem(9) 0.until(9).map { it * 9 + column }.forEach { result.add(it) } return result } fun squareIndicesAt(index: Int): List<Int> { val result = ArrayList<Int>() val firstColumnInSquare = (index / 3 * 3).rem(9) val firstColumnInRow = index / (9 * 3) * (9 * 3) 0.until(3).map { firstColumnInRow + it * 9 }.forEach { startOfRow -> 0.until(3).map { firstColumnInSquare + it }.forEach { colShift -> result.add(startOfRow + colShift) } } return result } } } } interface Solution<T> { val value: T fun hasNext(): Boolean fun skipNext(): Solution<T> fun next(): Solution<T> fun isComplete(): Boolean } fun <T> backtrack(solution: Solution<T>): List<Solution<T>> { val solutions = if (solution.hasNext()) backtrack(solution.skipNext()) + backtrack(solution.next()) else emptyList() return if (solution.isComplete()) solutions + solution else solutions }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
13,043
katas
The Unlicense
src/Day24.kt
frozbiz
573,457,870
false
{"Kotlin": 124645}
const val wall = '#' const val left = '<' const val right = '>' const val up = '^' const val down = 'v' class Maze() { constructor(input: List<String>) : this() { load(input) } var maze = listOf<List<Set<Char>>>() var mazeWidth = 0 val start = Point(1, 0) lateinit var end: Point fun load(input: List<String>) { for (line in input) { addRow(line) } end = Point(mazeWidth-2, maze.size-1) } private fun addRow(line: String) { val row = line.trim().map { if (it == '.') mutableSetOf() else mutableSetOf(it) } if (wall !in row.first() || wall !in row.last()) throw IllegalArgumentException() maze += listOf(row) if (mazeWidth == 0) { mazeWidth = row.size } else if (mazeWidth != row.size) throw IllegalArgumentException() } fun available(point: Point): Boolean { if ((point.x !in 0 until mazeWidth) || (point.y !in 0 until maze.size)) return false return maze[point.y][point.x].size == 0 } fun tick() { val newMaze = maze.map { it.map { mutableSetOf<Char>() } } val effectiveRowWidth = mazeWidth - 2 val colAdjL = effectiveRowWidth - 2 val colAdjR = 0 val effectiveColHeight = maze.size - 2 val rowAdjU = effectiveColHeight - 2 val rowAdjD = 0 for ((row, cols) in maze.withIndex()) { for ((col, icons) in cols.withIndex()) { if (wall in icons) { newMaze[row][col].add(wall) continue } if (left in icons) { val nextX = (col + colAdjL) % effectiveRowWidth + 1 newMaze[row][nextX].add(left) } if (right in icons) { val nextX = (col + colAdjR) % effectiveRowWidth + 1 newMaze[row][nextX].add(right) } if (up in icons) { val nextY = (row + rowAdjU) % effectiveColHeight + 1 newMaze[nextY][col].add(up) } if (down in icons) { val nextY = (row + rowAdjD) % effectiveColHeight + 1 newMaze[nextY][col].add(down) } } maze = newMaze } } } fun main() { fun part1(input: List<String>): Int { val maze = Maze(input) var routes = setOf(maze.start) var count = 0 while (maze.end !in routes && routes.isNotEmpty()) { ++count maze.tick() routes = routes.flatMap { listOf(it) + it.cardinalDirectionsFromPoint() }.toSet().filter { maze.available(it) } .toSet() } return count } fun part2(input: List<String>): Int { val maze = Maze(input) var count = 0 var routes = setOf(maze.start) while (maze.end !in routes && routes.isNotEmpty()) { ++count maze.tick() routes = routes.flatMap { listOf(it) + it.cardinalDirectionsFromPoint() }.toSet().filter { maze.available(it) } .toSet() } routes = setOf(maze.end) while (maze.start !in routes && routes.isNotEmpty()) { ++count maze.tick() routes = routes.flatMap { listOf(it) + it.cardinalDirectionsFromPoint() }.toSet().filter { maze.available(it) } .toSet() } routes = setOf(maze.start) while (maze.end !in routes && routes.isNotEmpty()) { ++count maze.tick() routes = routes.flatMap { listOf(it) + it.cardinalDirectionsFromPoint() }.toSet().filter { maze.available(it) } .toSet() } return count } // test if implementation meets criteria from the description, like: val testInput = listOf( "#.######\n", "#>>.<^<#\n", "#.<..<<#\n", "#>v.><>#\n", "#<^v^^>#\n", "######.#\n", ) check(part1(testInput) == 18) check(part2(testInput) == 54) val input = readInput("day24") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388
4,229
2022-aoc-kotlin
Apache License 2.0
src/main/kotlin/g0901_1000/s0987_vertical_order_traversal_of_a_binary_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0987_vertical_order_traversal_of_a_binary_tree // #Hard #Hash_Table #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_05_10_Time_189_ms_(66.67%)_Space_36.8_MB_(66.67%) import com_github_leetcode.TreeNode import java.util.PriorityQueue import java.util.Queue import java.util.TreeMap /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private class Node internal constructor(var row: Int, var `val`: Int) fun verticalTraversal(root: TreeNode?): List<List<Int>> { val map = TreeMap<Int, Queue<Node>>() helper(root, map, 0, 0) val ret: MutableList<List<Int>> = ArrayList() for (entry in map.iterator()) { val list: MutableList<Int> = ArrayList() ret.add(list) while (entry.value.isNotEmpty()) { list.add(entry.value.poll().`val`) } } return ret } private fun helper(cur: TreeNode?, map: TreeMap<Int, Queue<Node>>, r: Int, c: Int) { if (cur == null) { return } map.putIfAbsent( c, PriorityQueue { a: Node, b: Node -> if (a.row != b.row) a.row - b.row else a.`val` - b.`val` } ) map.getValue(c).add(Node(r, cur.`val`)) helper(cur.left, map, r + 1, c - 1) helper(cur.right, map, r + 1, c + 1) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,525
LeetCode-in-Kotlin
MIT License
kotlin/graphs/dfs/StronglyConnectedComponents.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.dfs import java.util.stream.Stream // https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm object StronglyConnectedComponents { fun scc(graph: Array<List<Integer>>): List<List<Integer>> { val n = graph.size val used = BooleanArray(n) val order: List<Integer> = ArrayList() for (i in 0 until n) if (!used[i]) dfs(graph, used, order, i) val reverseGraph: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() } for (i in 0 until n) for (j in graph[i]) reverseGraph[j].add(i) val components: List<List<Integer>> = ArrayList() Arrays.fill(used, false) Collections.reverse(order) for (u in order) if (!used[u]) { val component: List<Integer> = ArrayList() dfs(reverseGraph, used, component, u) components.add(component) } return components } fun dfs(graph: Array<List<Integer>>, used: BooleanArray, res: List<Integer?>, u: Int) { used[u] = true for (v in graph[u]) if (!used[v]) dfs(graph, used, res, v) res.add(u) } // DAG of strongly connected components fun sccGraph(graph: Array<List<Integer>>, components: List<List<Integer>>): Array<List<Integer>> { val comp = IntArray(graph.size) for (i in 0 until components.size()) for (u in components[i]) comp[u] = i val g: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(components.size()).toArray { _Dummy_.__Array__() } val edges: Set<Long> = HashSet() for (u in graph.indices) for (v in graph[u]) if (comp[u] != comp[v] && edges.add( (comp[u] .toLong() shl 32) + comp[v] ) ) g[comp[u]].add(comp[v]) return g } // Usage example fun main(args: Array<String?>?) { val g: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(3).toArray { _Dummy_.__Array__() } g[2].add(0) g[2].add(1) g[0].add(1) g[1].add(0) val components: List<List<Integer>> = scc(g) System.out.println(components) System.out.println(Arrays.toString(sccGraph(g, components))) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
2,258
codelibrary
The Unlicense
year2016/src/main/kotlin/net/olegg/aoc/year2016/day15/Day15.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2016.day15 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2016.DayOf2016 /** * See [Year 2016, Day 15](https://adventofcode.com/2016/day/15) */ object Day15 : DayOf2016(15) { private val PATTERN = "Disc #(\\d+) has (\\d+) positions; at time=(\\d+), it is at position (\\d+).".toRegex() override fun first(): Any? { val discs = lines .mapNotNull { line -> PATTERN.find(line)?.groupValues?.let { Triple(it[1].toInt(), it[2].toInt(), it[4].toInt()) } } return solve(discs) } override fun second(): Any? { val discs = lines .mapNotNull { line -> PATTERN.find(line)?.groupValues?.let { Triple(it[1].toInt(), it[2].toInt(), it[4].toInt()) } } return solve(discs + listOf(Triple(discs.size + 1, 11, 0))) } private fun solve(discs: List<Triple<Int, Int, Int>>): Int { return generateSequence(0) { it + 1 } .first { time -> discs.all { (it.third + it.first + time) % it.second == 0 } } } } fun main() = SomeDay.mainify(Day15)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,062
adventofcode
MIT License
src/main/kotlin/com/colinodell/advent2022/Day14.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 class Day14(input: List<String>) { private val grid = input.flatMap { line -> line.split(" -> ") // Things in between -> arrows are points .map { point -> point.split(",").let { (x, y) -> Vector2(x.toInt(), y.toInt()) } } // Group each point with the following one .zipWithNext() // Create a line from them .map { (a, b) -> Line(a, b) } // And then gather all the points that are part of those lines .flatMap { l -> l.points } }.toGrid { '#' } private val sandStart = Vector2(500, 0) private val maxY = grid.keys.maxOf { it.y } fun solvePart1() = dropAllSand(null, maxY) fun solvePart2() = dropAllSand(maxY + 2, null) + 1 private fun nextPositions(current: Vector2) = listOf( current + Vector2(0, 1), current + Vector2(-1, 1), current + Vector2(1, 1), ) /** * Continue dropping sand until we fall into the void or reach the source point */ private fun dropAllSand(floorY: Int?, voidY: Int?): Int { var pos = sandStart var count = 0 while (true) { val next = nextPositions(pos).firstOrNull { grid[it] == null } pos = when { // End condition 1: We fell into the void next != null && next.y == voidY -> return count // End condition 2: We reached the source point next == null && pos == sandStart -> return count // The sand unit is now at rest next == null || next.y == floorY -> { // Record it grid[pos] = 'o' count++ // Drop the next sand unit sandStart } // The sand unit is still falling else -> next } } } }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
1,945
advent-2022
MIT License
Minimum_Size_Subarray_Sum_v1.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}
// Given an array of n positive integers and a positive integer s, find the minimal // length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. class Solution { fun minSubArrayLen(s: Int, nums: IntArray): Int { if (nums.isEmpty()) return 0 val preSum = IntArray(nums.size) preSum[0] = nums[0] for (i in 1..preSum.lastIndex) { preSum[i] = preSum[i - 1] + nums[i] } var res = Int.MAX_VALUE for (i in nums.indices) { for (j in i..nums.lastIndex) { if (preSum[j] - preSum[i] + nums[i] >= s) { res = Math.min(j-i + 1, res) break } } } return if (res == Int.MAX_VALUE) 0 else res } } fun main() { val solution = Solution() val testset = arrayOf( intArrayOf(2, 3, 1, 2, 4, 3), intArrayOf(2, 3, 1, 2, 4, 3), intArrayOf(2, 3, 1, 2, 4, 3), intArrayOf(1, 2, 3, 4, 5) ) val ss = intArrayOf(7, 8, 11, 11) for (i in testset.indices) { println(solution.minSubArrayLen(ss[i], testset[i])) } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,168
leetcode
MIT License
src/main/kotlin/icfp2019/Parsers.kt
teemobean
193,332,580
true
{"JavaScript": 797310, "Kotlin": 85937, "CSS": 9434, "HTML": 5859}
package icfp2019 import com.google.common.base.CharMatcher import com.google.common.base.Splitter import com.google.common.collect.Range import com.google.common.collect.TreeRangeSet import icfp2019.model.* import org.pcollections.TreePVector class Splitters { companion object { val PAREN_MATCHER = CharMatcher.anyOf("()")!! val COMMA_SPLITTER = Splitter.on(',').omitEmptyStrings()!! val HASH_SPLITTER = Splitter.on('#')!! val SEMI_SPLITTER = Splitter.on(';').omitEmptyStrings()!! } } fun parsePoint(mapEdges: String): Point { return parseEdges(mapEdges).first() } fun parseEdges(mapEdges: String): List<Point> { // split a string like: // (1,2),(3,4),(5,6) // in to: // (1 2) (3 4) (5 6) // then read 2 at a time, trimming the parens return Splitters.COMMA_SPLITTER.split(mapEdges) .map { Splitters.PAREN_MATCHER.trimFrom(it) } .windowed(2, step = 2) .map { (first, second) -> Point(Integer.parseInt(first), Integer.parseInt(second)) } } fun parseObstacles(obstacles: String): List<List<Point>> { return Splitters.SEMI_SPLITTER.split(obstacles) .map { parseEdges(it) } } fun parseDesc(problem: String): Problem { val (mapEdges, startPosition, obstacles, boosters) = Splitters.HASH_SPLITTER.splitToList(problem) val startPoint = parsePoint(startPosition) val vertices = parseEdges(mapEdges) val obstacleEdges = parseObstacles(obstacles) val parsedBoosters = parseBoosters(boosters) val maxY = vertices.maxBy { it.y }?.y ?: throw IllegalArgumentException("No Vertices") val maxX = vertices.maxBy { it.x }?.x ?: throw IllegalArgumentException("No Vertices") val xArrayIndices = 0.until(maxX) val yArrayIndices = 0.until(maxY) // Initialize grid with each cell starting out as an obstacle val grid: Array<Array<Node>> = xArrayIndices.map { x -> yArrayIndices.map { y -> Node(Point(x, y), isObstacle = false) }.toTypedArray() }.toTypedArray() // Build a mapping of all the edges per column along the x-axis // Edges are represented as a Closed range between sorted why coordinates in the column val xEdgeGroups = (vertices + obstacleEdges.flatten()).groupBy { it.x }.mapValues { entry -> val set: TreeRangeSet<Int> = TreeRangeSet.create() val points: List<Point> = entry.value val sortedBy = points.map { it.y }.sortedBy { it } sortedBy.windowed(2, step = 2).forEach { val (y1, y2) = it set.add(Range.closed(y1, y2)) } set } // this is the actual fill method for the map // This walks along the grid, one Y row at a time // Then walks the X axis for that row and for every edges crossed // it flips its inObstacle state yArrayIndices.forEach { y -> var inObstacle = true val currentYEdge = Range.closed(y, y + 1) xArrayIndices.forEach { x -> val yEdges = xEdgeGroups[x] if (yEdges?.encloses(currentYEdge) == true) { inObstacle = inObstacle.not() } val column = grid[x] column[y] = column[y].copy(isObstacle = inObstacle) } } parsedBoosters.forEach { grid[it.location.x][it.location.y] = grid[it.location.x][it.location.y].copy(booster = it.booster) } // Read lines /* 1. Read lines 2. Parse map Grammar: x,y: Nat point ::= (x,y) map ::= repSep(point,”,”) BoosterCode ::= B|F|L|X boosterLocation ::= BoosterCode point obstacles ::= repSep(map,”; ”) boosters ::= repSep(boosterLocation,”; ”) task ::= map # point # obstacles # boosters */ return Problem( MapSize(maxX, maxY), startPoint, map = TreePVector.from(grid.map { TreePVector.from(it.toList()) }) ) } data class ParsedBooster(val booster: Booster, val location: Point) fun parseBoosters(boosters: String): List<ParsedBooster> { return Splitters.SEMI_SPLITTER .split(boosters) .map { ParsedBooster(Booster.fromChar(it[0]), parsePoint(it.substring(1))) } }
13
JavaScript
12
0
afcf5123ffb72ac10cfa6b0772574d9826f15e41
4,289
icfp-2019
The Unlicense
src/main/kotlin/com/ginsberg/advent2019/Day24.kt
tginsberg
222,116,116
false
null
/* * Copyright (c) 2019 by <NAME> */ /** * Advent of Code 2019, Day 24 - Planet of Discord * Problem Description: http://adventofcode.com/2019/day/24 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day24/ */ package com.ginsberg.advent2019 import java.math.BigInteger import java.util.BitSet class Day24(input: List<String>) { private val bounds: Point2D = Point2D(input.first().length - 1, input.size - 1) private val startGrid: BitSet = parseInput(input) private var layers = mutableMapOf(0 to startGrid) private val midPoint = Point2D(bounds.x / 2, bounds.y / 2) fun solvePart1(): BigInteger = firstDuplicate(startGrid).toBigInteger() fun solvePart2(minutes: Int): Int = (1..minutes).fold(layers) { carry, _ -> carry.next() }.values.sumBy { it.cardinality() } private fun firstDuplicate(start: BitSet): BitSet { val seen = mutableSetOf<BitSet>() var latest = start do { seen += latest latest = latest.next() } while (latest !in seen) return latest } private fun BitSet.at(point: Point2D): Boolean = this[point.offset()] private fun BitSet.bitAt(point: Point2D): Int = if (this[point.offset()]) 1 else 0 private fun BitSet.columnCardinality(x: Int): Int = (0..bounds.y).map { y -> this[(y * bounds.y.inc()) + x] }.count { it } private fun BitSet.countNeighbors(at: Point2D): Int = at.neighbors() .filter { it.x >= 0 && it.y >= 0 } .filter { it.x <= bounds.x && it.y <= bounds.y } .count { this.at(it) } private fun BitSet.next(): BitSet = BitSet().also { newBitSet -> bounds.upTo().forEach { point -> val neighbors = this.countNeighbors(point) val alive = this[point.offset()] newBitSet.setNextRound(point, alive, neighbors) } } private fun BitSet.rowCardinality(y: Int): Int { val start = y * (bounds.x.inc()) return this[start, start + bounds.y + 1].cardinality() } private fun BitSet.setNextRound(point: Point2D, alive: Boolean, neighbors: Int) { this[point.offset()] = when { alive -> neighbors == 1 !alive && neighbors in setOf(1, 2) -> true else -> alive } } private fun MutableMap<Int, BitSet>.addEmptyEdges(): MutableMap<Int, BitSet> { val min = this.keys.min()!! if (!this[min]!!.isEmpty) { this[min - 1] = BitSet() } val max = this.keys.max()!! if (!this[max]!!.isEmpty) { this[max + 1] = BitSet() } return this } private fun MutableMap<Int, BitSet>.next(): MutableMap<Int, BitSet> = this.addEmptyEdges() .map { (layer, board) -> layer to BitSet().also { newBitSet -> bounds.upTo().filterNot { it == midPoint }.forEach { point -> val neighbors = this.countNeighbors(point, layer) val alive = board[point.offset()] newBitSet.setNextRound(point, alive, neighbors) } } }.toMap().toMutableMap() private fun Map<Int, BitSet>.countNeighbors(at: Point2D, layer: Int = 0): Int = at.neighbors() .filterNot { it == midPoint } .filter { it.x >= 0 && it.y >= 0 } .filter { it.x <= bounds.x && it.y <= bounds.y } .count { this.getValue(layer).at(it) } .plus(counterOuterNeighbors(layer, at)) .plus(this.countInnerNeighbors(layer, at)) private fun Map<Int, BitSet>.countInnerNeighbors(layer: Int, at: Point2D): Int = this[layer+1]?.let { when (at) { midPoint.north() -> it.rowCardinality(0) midPoint.south() -> it.rowCardinality(bounds.y) midPoint.east() -> it.columnCardinality(bounds.x) midPoint.west() -> it.columnCardinality(0) else -> 0 } } ?: 0 private fun Map<Int, BitSet>.counterOuterNeighbors(layer: Int, at: Point2D): Int = this[layer - 1]?.let { listOf( if (at.x == 0) it.bitAt(midPoint.west()) else 0, if (at.x == bounds.x) it.bitAt(midPoint.east()) else 0, if (at.y == 0) it.bitAt(midPoint.north()) else 0, if (at.y == bounds.y) it.bitAt(midPoint.south()) else 0 ).sum() } ?: 0 private fun Point2D.offset(): Int = this.x + (this.y * (bounds.y + 1)) private fun Point2D.upTo(): Sequence<Point2D> = sequence { (0..y).forEach { y -> (0..x).forEach { x -> yield(Point2D(x, y)) } } } private fun parseInput(input: List<String>): BitSet = BitSet().also { bitSet -> bounds.upTo().forEach { at -> bitSet[at.offset()] = input[at.y][at.x] == '#' } } }
0
Kotlin
2
23
a83e2ecdb6057af509d1704ebd9f86a8e4206a55
5,109
advent-2019-kotlin
Apache License 2.0
src/pl/shockah/aoc/y2021/Day9.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2021 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import pl.shockah.unikorn.collection.Array2D class Day9: AdventTask<Array2D<Int>, Int, Int>(2021, 9) { override fun parseInput(rawInput: String): Array2D<Int> { val lines = rawInput.trim().lines() return Array2D(lines.first().length, lines.size) { x, y -> lines[y][x].digitToInt() } } private fun getNeighborPoints(input: Array2D<Int>, point: Pair<Int, Int>): Set<Pair<Int, Int>> { val neighbors = mutableSetOf<Pair<Int, Int>>() if (point.first > 0) neighbors += Pair(point.first - 1, point.second) if (point.first < input.width - 1) neighbors += Pair(point.first + 1, point.second) if (point.second > 0) neighbors += Pair(point.first, point.second - 1) if (point.second < input.height - 1) neighbors += Pair(point.first, point.second + 1) return neighbors } private fun getLowPoints(input: Array2D<Int>): Set<Pair<Int, Int>> { return (0 until input.height).flatMap { y -> return@flatMap (0 until input.width).mapNotNull { x -> val value = input[x, y] return@mapNotNull if (getNeighborPoints(input, Pair(x, y)).any { (x, y) -> input[x, y] <= value }) null else Pair(x, y) } }.toSet() } private fun getBasin(input: Array2D<Int>, lowPoint: Pair<Int, Int>): Set<Pair<Int, Int>> { val checked = mutableSetOf<Pair<Int, Int>>() val toCheck = mutableListOf<Pair<Int, Int>>().apply { this += lowPoint } val points = mutableSetOf<Pair<Int, Int>>() while (toCheck.isNotEmpty()) { val point = toCheck.removeFirst() if (input[point.first, point.second] == 9) continue points += point toCheck += getNeighborPoints(input, point) - checked checked += point } return points } override fun part1(input: Array2D<Int>): Int { return getLowPoints(input).sumOf { (x, y) -> input[x, y] + 1 } } override fun part2(input: Array2D<Int>): Int { val lowPoints = getLowPoints(input) val basins = lowPoints.map { getBasin(input, it) } return basins.sortedByDescending { it.size }.take(3).fold(1) { acc, basin -> acc * basin.size } } class Tests { private val task = Day9() private val rawInput = """ 2199943210 3987894921 9856789892 8767896789 9899965678 """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals(15, task.part1(input)) } @Test fun part2() { val input = task.parseInput(rawInput) Assertions.assertEquals(1134, task.part2(input)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
2,543
Advent-of-Code
Apache License 2.0
src/main/kotlin/cc/stevenyin/algorithms/_02_sorts/_06_QuickSort_Basic.kt
StevenYinKop
269,945,740
false
{"Kotlin": 107894, "Java": 9565}
package cc.stevenyin.algorithms._02_sorts import cc.stevenyin.algorithms.RandomType import cc.stevenyin.algorithms.swap import cc.stevenyin.algorithms.testSortAlgorithm import kotlin.random.Random /** * 存在的问题: * 1. 对于一个已经有序或近乎有序的数组来说, * 每一次从第一个位置选取一个元素, * 很可能导致两侧的子数组变得极其不平衡。 * 所以可以采取随机选择的方法来确定待比较元素。 * 2. 对于一个存在大量重复数据的数组来说, * 例如 [1,2,3,1,2,3,1,2,2,3,1,1,1,3,4,0,2,1,2,5] * 这样会导致左侧存在大量与标定点处相同值的数据 * */ class _06_QuickSort_Basic : SortAlgorithm { override val name: String = "Quick Sort" override fun <T : Comparable<T>> sort(array: Array<T>) { quickSort(array, 0, array.size - 1) } private fun <T : Comparable<T>> quickSort(array: Array<T>, left: Int, right: Int) { if (left >= right) { return } // 采取随机选择的方法来确定待比较元素。 val randomIndex = Random.nextInt(array.size) swap(array, randomIndex, left) val pivot = partition(array, left, right) quickSort(array, left, pivot - 1) quickSort(array, pivot + 1, right) } /*** * 1. 对数组进行一分为二 * 2. 基准点左侧的元素全部小于或等于基准点处的值 * 3. 基准点右侧的元素全部大于基准点处的值 */ private fun <T : Comparable<T>> partition(array: Array<T>, left: Int, right: Int): Int { val e = left var cursor = e + 1 var i = left while (cursor <= right) { if (array[cursor] <= array[e]) { swap(array, i + 1, cursor) i++ } cursor++ } swap(array, e, i) return i } } fun main() { testSortAlgorithm(100000, RandomType.NEARLY_ORDERED, _04_MergeSort(), _05_MergeSort_BottomUp(), _06_QuickSort_Basic()) }
0
Kotlin
0
1
748812d291e5c2df64c8620c96189403b19e12dd
2,115
kotlin-demo-code
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[290]单词规律.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 // // 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。 // // 示例1: // // 输入: pattern = "abba", str = "dog cat cat dog" //输出: true // // 示例 2: // // 输入:pattern = "abba", str = "dog cat cat fish" //输出: false // // 示例 3: // // 输入: pattern = "aaaa", str = "dog cat cat dog" //输出: false // // 示例 4: // // 输入: pattern = "abba", str = "dog dog dog dog" //输出: false // // 说明: //你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。 // Related Topics 哈希表 // 👍 270 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun wordPattern(pattern: String, s: String): Boolean { //使用 HashMap 存储对应值元素 时间复杂度 O(n) val ss = s.split(" ") if(pattern.length != ss.size) return false val map = HashMap<Char,String>() for ( i in pattern.indices){ val c = pattern[i] if(map.containsKey(c)){ if(!map[c].equals(ss[i])) return false }else { if(map.containsValue(ss[i])){ return false }else{ map[c] = ss[i] } } } return true } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,579
MyLeetCode
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem2007/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2007 /** * LeetCode page: [2007. Find Original Array From Doubled Array](https://leetcode.com/problems/find-original-array-from-doubled-array/); */ class Solution { /* Complexity: * Time O(N+M) and Aux_Space O(M) where N is size of changed and M is maximum value of changed; */ fun findOriginalArray(changed: IntArray): IntArray { val isSizeOfChangedOdd = changed.size and 1 == 1 if (isSizeOfChangedOdd) return intArrayOf() val sortedNumberToChangedFrequency = getSortedNumberToFrequency(changed) return constructOriginalArray(changed.size shr 1, sortedNumberToChangedFrequency) } private fun getSortedNumberToFrequency(numbers: IntArray): IntArray { val maxNumber = checkNotNull(numbers.max()) val sortedNumberToFrequency = IntArray(maxNumber + 1) for (number in numbers) sortedNumberToFrequency[number]++ return sortedNumberToFrequency } private fun constructOriginalArray(size: Int, sortedNumberToChangedFrequency: IntArray): IntArray { val attemptRevertZeroFailed = !attemptRevertFrequencyChangeOfZero(sortedNumberToChangedFrequency) if (attemptRevertZeroFailed) return intArrayOf() val original = IntArray(size) var currIndexOfOriginal = sortedNumberToChangedFrequency[0] for (number in 1..sortedNumberToChangedFrequency.lastIndex) { val frequencyOfNumber = sortedNumberToChangedFrequency[number] if (frequencyOfNumber == 0) continue val attemptRevertDoubleFailed = !attemptRevertFrequencyChangeOfItsDoubled(number, sortedNumberToChangedFrequency) if (attemptRevertDoubleFailed) return intArrayOf() repeat(frequencyOfNumber) { original[currIndexOfOriginal++] = number } } return original } private fun attemptRevertFrequencyChangeOfZero(numberToFrequency: IntArray): Boolean { val frequencyOfZero = numberToFrequency[0] val isFrequencyOfZeroOdd = frequencyOfZero and 1 == 1 if (isFrequencyOfZeroOdd) return false numberToFrequency[0] = frequencyOfZero shr 1 return true } private fun attemptRevertFrequencyChangeOfItsDoubled(positiveNumber: Int, numberToFrequency: IntArray): Boolean { val maxNumber = numberToFrequency.lastIndex val frequencyOfNumber = numberToFrequency[positiveNumber] val double = positiveNumber shl 1 val isInvalidDouble = double > maxNumber || numberToFrequency[double] < frequencyOfNumber if (isInvalidDouble) return false numberToFrequency[double] -= frequencyOfNumber return true } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,724
hj-leetcode-kotlin
Apache License 2.0
src/Day23.kt
mrugacz95
572,881,300
false
{"Kotlin": 102751}
private val neighbours = listOf( Pos(-1, -1), Pos(-1, 0), Pos(-1, 1), Pos(0, 1), Pos(1, 1), Pos(1, 0), Pos(1, -1), Pos(0, -1), ) private val directionNeighbours = mapOf( // direction to move in neighbour occupied Direction.UP to listOf( Pos(-1, -1), Pos(-1, 0), Pos(-1, 1), ), Direction.DOWN to listOf( Pos(1, 1), Pos(1, 0), Pos(1, -1), ), Direction.LEFT to listOf( Pos(-1, -1), Pos(0, -1), Pos(1, -1), ), Direction.RIGHT to listOf( Pos(-1, 1), Pos(0, 1), Pos(1, 1), ), ) private data class Elf( val id: Int, var proposedMove : Direction? = null, var pos : Pos, val moves: MutableList<Direction> = Direction.values().toMutableList()) { override fun toString(): String { return "Elf(id=$id, pos=$pos, proposedMove=$proposedMove, moves=$moves)" } } private fun List<Elf>.print() { val x = this.map { it.pos.x } val y = this.map { it.pos.y } val minX = x.min() - 1 val maxX = x.max() + 1 val minY = y.min() - 1 val maxY = y.max() + 1 val result = List(maxY - minY + 1) { MutableList(maxX - minX + 1){ "." } } map { result[it.pos.y - minY][it.pos.x - minX] = "#" } println(result.joinToString("\n") {it.joinToString("") } + "\n") } fun main() { fun List<String>.parse(): MutableSet<Pos> { val elves = mutableSetOf<Pos>() mapIndexed { y, line -> line.mapIndexed { x, c -> if (c == '#') { elves.add(Pos(y, x)) } } } return elves } fun simulate(parsedElvesPositions: MutableSet<Pos>, stopCondition : (round: Int, moves: Boolean) -> Boolean): Pair<Int, Int> { val elves = mutableListOf<Elf>() for(parsed in parsedElvesPositions) { elves.add(Elf(elves.size, pos = parsed)) } var round = 1 while (true) { // elves.print() val elvesList = elves.toList() val elvesPositions = elves.map { it.pos }.toSet() val proposedOccupiedPositions = mutableMapOf<Pos, Int>() var anyMovement = false for (elf in elvesList) { var willMove = false for (dir in neighbours) { if ((elf.pos + dir) in elvesPositions) { willMove = true break } } if (willMove) { for (dir in elf.moves) { val neighbours = directionNeighbours[dir] ?: error("unknown direction") if (neighbours.none { (elf.pos + it) in elvesPositions }) { elf.proposedMove = dir proposedOccupiedPositions[elf.pos + dir.delta] = (proposedOccupiedPositions[elf.pos + dir.delta] ?: 0) + 1 break } } } } // use proposed moves for (elf in elves){ val move = elf.proposedMove if(move != null && proposedOccupiedPositions[elf.pos + move.delta] == 1){ elf.pos = elf.pos + move.delta anyMovement = true } val moveToRoll = elf.moves.first() // find { it == elf.proposedMove } ?: error("Cant find proposed move") elf.moves.remove(moveToRoll) elf.moves.add(moveToRoll) } elves.map { it.proposedMove = null } round += 1 // elves.print() if (stopCondition(round, anyMovement)){ break } } val x = elves.map { it.pos.x } val y = elves.map { it.pos.y } val minX = x.min() val maxX = x.max() val minY = y.min() val maxY = y.max() val emptyTiles = ((maxX - minX + 1) * (maxY - minY + 1) - elves.size) return round - 1 to emptyTiles } fun part1(input: List<String>): Int { val parsedElvesPositions = input.parse() val (_, emptyTiles) = simulate(parsedElvesPositions) { round, _ -> round > 10 } return emptyTiles } fun part2(input: List<String>): Int { val parsedElvesPositions = input.parse() val (rounds, _) = simulate(parsedElvesPositions) { _, anyMovement -> !anyMovement } return rounds } val testInput = readInput("Day23_test") val input = readInput("Day23") assert(part1(testInput), 110) println(part1(input)) assert(part2(testInput), 20) println(part2(input)) } // Time: 2:00
0
Kotlin
0
0
29aa4f978f6507b182cb6697a0a2896292c83584
4,822
advent-of-code-2022
Apache License 2.0
kotlin/2022/day04/Day04.kt
nathanjent
48,783,324
false
{"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966}
class Day04 { fun part1(input: Iterable<String>): Int { return findPairCountBy(input) { ranges -> ranges[0].all { ranges[1].contains(it) } || ranges[1].all { ranges[0].contains(it) } } } fun part2(input: Iterable<String>): Int { return findPairCountBy(input) { it[0].intersect( it[1].asIterable().toSet() ) .any() } } private fun findPairCountBy( input: Iterable<String>, predicate: (Array<IntRange>) -> Boolean, ): Int { return input .filter { it.isNotBlank() } .map { it.split(",") } .map { it.map { pair -> pair.split("-") } } .map { it.flatten() } .map { pair -> pair.map { it.toInt() } } .map { arrayOf( it[0]..it[1], it[2]..it[3], ) } .filter { predicate(it) } .size } }
0
Rust
0
0
7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf
870
adventofcode
MIT License
lib_algorithms_sort_kotlin/src/main/java/net/chris/lib/algorithms/sort/kotlin/KTMergeSorter.kt
chrisfang6
105,401,243
false
{"Java": 68669, "Kotlin": 26275, "C++": 12503, "CMake": 2182, "C": 1403}
package net.chris.lib.algorithms.sort.kotlin /** * Merge sort. * * @param <T> </T> */ abstract class KTMergeSorter : KTSorter() { override fun subSort(array: IntArray) { if (array == null) { return } mergeSort(array, 0, array.size - 1) } private fun mergeSort(A: IntArray, p: Int, r: Int) { if (p < r) { val q = Math.floor((p + r).toDouble() / 2).toInt() mergeSort(A, p, q) mergeSort(A, q + 1, r) merge(A, p, q, r) } } private fun merge(A: IntArray, p: Int, q: Int, r: Int) { // p<=q<r if (p > q || q >= r) { return } val n1 = q - p + 1 // [p, q] val L = A.copyOf(n1 + 1) for (i in 0 until n1) { L[i] = A[p + i] } L[n1] = infinity val n2 = r - q // (q, r] val R = A.copyOf(n2 + 1) for (j in 0..n2 - 1) { R[j] = A[q + j + 1] } R[n2] = infinity var i = 0 var j = 0 var k = p while (k < r + 1) { // [p, r] if (compareTo(L[i], R[j]) < 1) { // L[i] <= R[j] A[k] = L[i] i++ doUpdate(A) } else { A[k] = R[j] j++ doUpdate(A) } k++ } } protected abstract val infinity: Int }
0
Java
0
0
1f1c2206d5d9f0a3d6c070a7f6112f60c2714ec0
1,427
sort
Apache License 2.0
src/main/kotlin/Main.kt
NextTurnGames
453,470,447
false
{"Kotlin": 9350}
package games.nextturn import java.io.File import java.lang.RuntimeException var allWords = setOf<String>() var commonWords = setOf<String>() fun main() { loadWords() println("Available choices:") println("[1] Input grades (use as aide)") println("[2] Test against random word") println("[3] Test against input word") println("[4] Find best first guess") println("[5] Build cheat sheet") println("[6] Test all words") print("Enter choice > ") val highSelection = 6 var menuChoice = 0 while (menuChoice < 1 || menuChoice > highSelection) { try { menuChoice = readLine()?.toInt() ?: 0 } catch (ex: Exception) { println("Please make a selection between 1 and $highSelection") } } when (menuChoice) { 1 -> runAide() 2 -> runTest(null) 3 -> testAnswer() 4 -> bestFirstGuess() 5 -> buildCheatSheet() 6 -> testAllWords() } } fun runAide() { val remaining = allWords.toMutableSet() var tries = 0 var guess = "lares" var grade = 1 while (grade != 0 && remaining.size > 0) { println("There are still ${remaining.size} possible words left") tries++ var gradeIn = "" println("Guessing $guess") while (gradeIn.length != 5 && gradeIn.filter { listOf('.', 'c', 'W').contains(it) }.length != 5) { print(" Grade? > ") gradeIn = readLine() ?: "" if (gradeIn == "p") { for (w in remaining) { println(w) } } if (gradeIn.length != 5 && gradeIn.filter { listOf('.', 'c', 'W').contains(it) }.length != 5) { println("Grade must be 5 characters. Use '.' for not in answer, 'w' for wrong sport and 'C' for Correct") } } grade = stringToGrade(gradeIn) remaining.removeIf { !checkWord(guess, it, grade) } guess = bestGuess(remaining) } println("Word is $guess, took $tries tries") } fun runTest(input: String?) { val answer = input ?: allWords.random() println("Testing for the answer $answer") val remaining = allWords.toMutableSet() var tries = 1 var guess = "lares" while (guess != answer && remaining.size > 0) { tries++ val grade = gradeWord(guess, answer) println("Guessing $guess, scored a ${prettyGrade(grade)}") remaining.removeIf { !checkWord(guess, it, grade) } println("There are ${remaining.size} potential words left") guess = bestGuess(remaining) } println("Word is $guess, took $tries tries") } fun testAnswer() { var answer = "" while (answer.length != 5 || !allWords.contains(answer)) { print("Enter answer > ") answer = readLine() ?: "" if (answer.length != 5 || !allWords.contains(answer)) { println("Please enter a valid 5 letter word") } } runTest(answer) } fun bestFirstGuess() { val rankedWords = allWords.associateWith { guess -> var totalRemaining = 0L for (answer in allWords) { val grade = gradeWord(guess, answer) totalRemaining += allWords.filter { checkWord(guess, it, grade) }.size } println("$guess scored a ${totalRemaining.toFloat() / allWords.size}") File("results.txt").appendText("$guess scored a ${totalRemaining.toFloat() / allWords.size}\n") totalRemaining } println(); println(); println(); println(); println() println("RESULTS - ") val sorted = rankedWords.toList().sortedBy { it.second } for (result in sorted) { println("${result.first} - ${result.second.toFloat() / allWords.size}") File("sorted.txt").appendText("${result.first} - ${result.second.toFloat() / allWords.size}\n") } } fun buildCheatSheet() { val first = getValidWord() for (l1 in 0..2) { for (l2 in 0..2) { for (l3 in 0..2) { for (l4 in 0..2) { for (l5 in 0..2) { val grade = (l1 shl 8) or (l2 shl 6) or (l3 shl 4) or (l4 shl 2) or l5 val remaining = allWords.filter { checkWord(first, it, grade) } if (remaining.isNotEmpty()) { val best = bestGuess(remaining = remaining.toSet()) println("${prettyGrade(grade)} - $best") File("$first.txt").appendText("${prettyGrade(grade)} - $best\n") } } } } } } } fun bestGuess(remaining: Set<String>): String { var best = "" var bestTotal = Long.MAX_VALUE for (guess in remaining) { var totalRemaining = 0L for (answer in remaining) { val grade = gradeWord(guess, answer) totalRemaining += remaining.filter { checkWord(guess, it, grade) }.size if (totalRemaining > bestTotal) break } if (totalRemaining < bestTotal) { bestTotal = totalRemaining best = guess } } return best } fun prettyGrade(grade: Int): String { var retval = "" for (i in 8 downTo 0 step 2) { retval += when ((grade shr i) and 3) { 0 -> "C" 1 -> "w" 2 -> "." else -> throw RuntimeException("Invalid grade sent in") } } return retval } fun stringToGrade(input: String): Int { if (input.length != 5) throw RuntimeException("Invalid grade input") var grade = 0 for (i in input) { grade = grade shl 2 grade += when (i) { 'C' -> 0 'w' -> 1 '.' -> 2 else -> throw RuntimeException("Invalid grade input") } } return grade } fun loadWords() { val uncommon = mutableSetOf<String>() val common = mutableSetOf<String>() File("assets/wordlists/uncommon.txt").forEachLine { uncommon.add(it) } File("assets/wordlists/common.txt").forEachLine { common.add(it) } commonWords = common.toSet() allWords = uncommon union common } // TODO - This doesn't do repeat letters correctly. Still works, just not optimal fun gradeWord(guess: String, answer: String) : Int { // Return 5 sets of 2 bits // 00 - Correct // 01 - Wrong spot // 10 - Not in string var total = 0 for (i in 0 until 5) { total = total shl 2 val thisSpot = when { guess[i] == answer[i] -> 0 answer.contains(guess[i]) -> 1 else -> 2 } total += thisSpot } return total } fun checkWord(guess: String, answer: String, grade: Int) : Boolean { return gradeWord(guess, answer) == grade } fun getValidWord(remaining: Set<String> = allWords): String { var word = "" while (word.length != 5 || !remaining.contains(word)) { print("Enter word > ") word = readLine() ?: "" if (word.length != 5 || !allWords.contains(word)) { println("Please enter a valid 5 letter word") } } return word } fun getSecondGuesses(first: String): Map<Int, String> { val seconds = mutableMapOf<Int, String>() val lines = File("$first.txt").readLines() for (line in lines) { val grade = stringToGrade(line.substring(0, 5)) seconds[grade] = line.substring(8, 13) } return seconds } fun testAllWords() { val first = getValidWord() val seconds = getSecondGuesses(first) val totalTries = IntArray(20) { 0 } for (answer in allWords) { println("Testing for the answer $answer") val remaining = allWords.toMutableSet() // First guess var tries = 1 var guess = first if (answer != guess) { val grade = gradeWord(guess, answer) remaining.removeIf { !checkWord(guess, it, grade) } guess = seconds[grade] ?: throw Exception("Second word not found for ${prettyGrade(grade)}") tries++ } while (guess != answer && remaining.size > 0) { val grade = gradeWord(guess, answer) remaining.removeIf { !checkWord(guess, it, grade) } guess = bestGuess(remaining) tries++ } totalTries[tries]++ println("Word is $guess, took $tries tries") } for (i in 0 until 20) { println("Number of words in $i tries: ${totalTries[i]}, ${totalTries[i].toFloat() * 100.0f / allWords.size.toFloat()}%") } }
0
Kotlin
0
0
5e0f21a7794b762fd169368b352a146138d4950b
8,698
Wordle
MIT License
src/main/kotlin/days/Day3.kt
Kamefrede
434,954,548
false
{"Kotlin": 9152}
package days class Day3 : Day(3) { override fun partOne(): Any { val bitCount = getBitCount(inputList) val (epsilon, gamma) = getGammaEpsilon(bitCount) return Integer.parseInt(gamma, 2) * Integer.parseInt(epsilon, 2) } override fun partTwo(): Any { val co2 = mostCommon(inputList, 0, false) val oxygen = mostCommon(inputList, 0, true) return Integer.parseInt(co2, 2) * Integer.parseInt(oxygen, 2) } private fun getBitCount(inputList: List<String>): Array<IntArray> { val bitCount = Array(2) { IntArray(inputList[0].length) } inputList.forEach { bits -> bits.forEachIndexed { index, bit -> if (bit == '1') bitCount[1][index] = bitCount[1][index] + 1 else bitCount[0][index] = bitCount[0][index] + 1 } } return bitCount } private fun mostCommon(list: List<String>, idxToCheck: Int, mostCommon: Boolean): String { if (list.size == 1) return list[0] val bitCount = getBitCount(list) var toCheckAgainst = "" bitCount[1].zip(bitCount[0]) { oneCount, zeroCount -> if (oneCount == zeroCount) { toCheckAgainst += if (mostCommon) '1' else '0' return@zip } toCheckAgainst += if (oneCount > zeroCount) { if (mostCommon) '1' else '0' } else { if (mostCommon) '0' else '1' } } val newList = list.filter { it[idxToCheck] == toCheckAgainst[idxToCheck] } return mostCommon(newList, idxToCheck + 1, mostCommon) } private fun getGammaEpsilon(bitCount: Array<IntArray>): Pair<String, String> { var epsilon = "" var gamma = "" bitCount[1].zip(bitCount[0]) { oneCount, zeroCount -> if (oneCount > zeroCount) { gamma += '1' epsilon += '0' } else { gamma += '0' epsilon += '1' } } return Pair(epsilon, gamma) } }
0
Kotlin
0
0
97cae5cd9d38254b1dc75022fc24f10aa868531a
2,204
AoC2021
Creative Commons Zero v1.0 Universal
kotlin/app/src/main/kotlin/coverick/aoc/day5/SupplyStacks.kt
RyTheTurtle
574,328,652
false
{"Kotlin": 82616}
package coverick.aoc.day5 import readResourceFile import splitOn val INPUT_FILE = "supplyStacks-input.txt" fun parseConfigLine(s:String): List<String>{ var idx = 0 val result = ArrayList<String>() val eatCrate = fun() { if(idx < s.length && s[idx] == '['){ idx++ result.add(s[idx].toString()) idx+= 2 // skip closing ] } else { idx += 3 // nothing in this slot, advance past crate width result.add("") } } val eatSpace = fun(){ if(idx < s.length && s[idx].isWhitespace()){ idx++ } } while(idx < s.length){ eatCrate() eatSpace() } return result } /* string format is expected to be "move [crates] from [start] to [end]" returns a triple of [crates to move, source stack, destination stack] */ fun parseMoveInstruction(s:String): Triple<Int,Int,Int> { val parts = s.split(" ") return Triple(parts[1].toInt() , parts[3].toInt() - 1, parts[5].toInt() - 1) } fun applyMoveInstruction(stacks:ArrayList<ArrayDeque<String>>, instruction: Triple<Int,Int,Int>) { for(i in 1..instruction.first){ stacks.get(instruction.third).addLast( stacks.get(instruction.second).removeLast() ) } } fun applyMultiCrateMoveInstruction(stacks:ArrayList<ArrayDeque<String>>, instruction: Triple<Int,Int,Int>) { val movedCrates = stacks.get(instruction.second) .takeLast(instruction.first) stacks.get(instruction.third) .addAll(movedCrates) for(i in 0..instruction.first-1){ stacks.get(instruction.second).removeLast() } } fun getStartingCrates(input: List<String>): ArrayList<ArrayDeque<String>> { val stacks = ArrayList<ArrayDeque<String>>() val startingConfig = input.map{parseConfigLine(it)} for(cratesRow in startingConfig){ while(stacks.size < cratesRow.size){ stacks.add(ArrayDeque<String>()) } for((idx,crate) in cratesRow.withIndex()){ if(crate.isNotEmpty()){ stacks.get(idx).addFirst(crate) } } } return stacks } fun part1(): String { val inputs = readResourceFile(INPUT_FILE).splitOn{it.isEmpty()} val stacks = getStartingCrates(inputs[0]) inputs[1].map{parseMoveInstruction(it)} .forEach{applyMoveInstruction(stacks,it)} return stacks.map{it.last()}.joinToString(separator="") } fun part2(): String { val inputs = readResourceFile(INPUT_FILE).splitOn{it.isEmpty()} val stacks = getStartingCrates(inputs[0]) inputs[1].map{parseMoveInstruction(it)} .forEach{applyMultiCrateMoveInstruction(stacks,it) } return stacks.map{it.last()}.joinToString(separator="") } fun solution(){ println("Supply Stacks part 1 solution: ${part1()}") println("Supply Stacks part 2 solution: ${part2()}") }
0
Kotlin
0
0
35a8021fdfb700ce926fcf7958bea45ee530e359
2,991
adventofcode2022
Apache License 2.0
solutions/aockt/y2023/Y2023D18.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.parse import aockt.util.spacial.Direction import aockt.util.spacial.Direction.* import aockt.util.spacial.Point import aockt.util.spacial.move import aockt.util.spacial.polygonArea import io.github.jadarma.aockt.core.Solution object Y2023D18 : Solution { /** * A single step of a dig plan. * @property direction The direction to dig in from the current point. * @property length How long should the next segment be. */ private data class DigPlanStep(val direction: Direction, val length: Int) /** Follow the [DigPlanStep]s from a [start] point, and return the coordinates of all corners of the polygon. */ private fun List<DigPlanStep>.digTrench(start: Point): List<Point> = buildList { var point = start for ((direction, length) in this@digTrench) { point = point.move(direction, length.toLong()) add(point) } check(point == start) { "Trench invalid, did not loop back to start." } } /** * Parse the input and return the dig plan. * @param input The puzzle input. * @param inColorEncoding Whether to take the steps from the colors or from the plain text. */ private fun parseInput(input: String, inColorEncoding: Boolean): List<DigPlanStep> = parse { val stepRegex = Regex("""^([LRUD]) (\d+) \(#([0-9a-f]{6})\)$""") val directions = listOf(Right, Down, Left, Up) fun String.parseDirection(): Direction = directions["RDLU".indexOf(first())] fun String.parseColorPlan(): DigPlanStep = DigPlanStep( direction = directions[last().digitToInt()], length = substring(0, 5).toInt(16), ) input .lineSequence() .map { stepRegex.matchEntire(it)!!.destructured } .map { (direction, length, color) -> if (inColorEncoding) color.parseColorPlan() else DigPlanStep(direction.parseDirection(), length.toInt()) } .toList() } /** Simulate digging a trench following the steps, and return the total volume of the hollowed out structure. */ private fun List<DigPlanStep>.solve(): Long = digTrench(Point.Origin).polygonArea(includingPerimeter = true) override fun partOne(input: String) = parseInput(input, inColorEncoding = false).solve() override fun partTwo(input: String) = parseInput(input, inColorEncoding = true).solve() }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
2,478
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/day8/Day8.kt
Mee42
433,459,856
false
{"Kotlin": 42703, "Java": 824}
package dev.mee42.day8 import dev.mee42.* val testShort = """ acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf """.trimIndent() val test = """ be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce """.trimIndent().trim() // 0000 //1 2 //1 2 // 3333 //4 5 //4 5 // 6666 fun main() { val inputStr = if (0 == 0) input(day = 8, year = 2021).trim() else test.trim() val input = inputStr.split("\n").map { it.trim() } val numbers = mutableMapOf<Int, Int>() val sol = input.map { line -> val (firstPart, secondPart) = line.split("|").map { it.trim() } // remove elements as we strike them out val couldBe = mutableMapOf<Int, MutableList<Char>>() for(i in 0..6) { couldBe[i] = ('a'..'g').toMutableList() } firstPart.split(" ").forEach { n -> val (weKnow, numberFound) = when (n.length) { 3 -> listOf(0, 2, 5) to 7 4 -> listOf(1, 2, 3, 5) to 4 2 -> listOf(2, 5) to 1 7 -> listOf(0, 1, 2, 3, 4, 5, 6) to 8 else -> null to -1 } if(weKnow != null) {// the list of chars we know it is for(i in 0..6) { if(i !in weKnow) { couldBe[i]!!.removeAll(n.toList()) } } } } // simplify down to pairs for(x in 0..10) { for (i1 in 0..6) { for (i2 in 0..6) { if (i1 == i2) continue if (couldBe[i1]!! == couldBe[i2]!! && couldBe[i1]!!.size == 2) { for (i3 in 0..6) { if (i3 != i1 && i3 != i2) couldBe[i3]!!.removeAll(couldBe[i1]!!) } } } } for(i1 in 0..6) { if(couldBe[i1]!!.size == 1) { for (i2 in 0..6) { if(i1 != i2) couldBe[i2]!!.remove(couldBe[i1]!!.first()) } } } } // disambiguate 6 and 2 val sixCode = firstPart.split(" ").first { n -> n.length == 6 && (couldBe[0]!! + couldBe[1]!! + couldBe[4]!!).all { it in n } } val fiveLetter = sixCode.toMutableList().run { removeAll(couldBe[0]!!) removeAll(couldBe[1]!!) removeAll(couldBe[4]!!) this }.first() couldBe[5]!!.removeIf { it != fiveLetter } couldBe[2]!!.removeIf { it == fiveLetter } // disambiguate 1 and 3 val twoCode = firstPart.split(" ").first { n -> n.length == 5 && (couldBe[0]!! + couldBe[2]!! + couldBe[6]!!).all { it in n} } val threeLetter = twoCode.toMutableList().run { removeAll(couldBe[0]!!) removeAll(couldBe[2]!!) removeAll(couldBe[4]!!) this }.first() couldBe[3]!!.removeIf { it != threeLetter } couldBe[1]!!.removeIf { it == threeLetter } val fiveCodeAlready = couldBe[0]!! + couldBe[1]!! + couldBe[3]!! + couldBe[5]!! val fiveCode = firstPart.split(" ").first { n -> n.length == 5 && fiveCodeAlready.all { it in n } } val sixLetter = fiveCode.toMutableList().run { removeAll(fiveCodeAlready) this }.first() couldBe[6]!!.removeIf { it != sixLetter } couldBe[4]!!.removeIf { it == sixLetter } val solution = couldBe.map { it.value.first() to it.key }.toMap() println(solution) // maps the char to the physical position val number = secondPart.split(" ").map { n -> "" + when(val x = n.map { solution[it]!! }.sorted()) { listOf(0, 1, 2, 4, 5, 6) -> 0 listOf(2, 5) -> 1 listOf(0, 2, 3, 4, 6) -> 2 listOf(0, 2, 3, 5, 6) -> 3 listOf(1, 2, 3, 5) -> 4 listOf(0, 1, 3, 5, 6) -> 5 listOf(0, 1, 3, 4, 5, 6) -> 6 listOf(0, 2, 5) -> 7 listOf(0, 1, 2, 3, 4, 5, 6) -> 8 listOf(0, 1, 2, 3, 5, 6) -> 9 else -> error("FUCK YOU $x $n") } }.joinToString("").toInt() // find one that's six println(number) number }.sum() println(sol) }
0
Kotlin
0
0
db64748abc7ae6a92b4efa8ef864e9bb55a3b741
5,257
aoc-2021
MIT License
src/main/aoc2016/Day24.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2016 import Direction import Pos import org.magicwerk.brownies.collections.GapList import java.util.* class Day24(input: List<String>) { val theMap = Map(input) /** * A node in the graph. * * A node is a place where the road splits into more than one new direction * or a named location (where a number exists). * @property address the location of this node. * @property name the name of this node (0, 1, 2, etc), '.' if it doesn't have any name. * @property neighbours A list of all this nodes neighbours as a Pair of address, distance */ data class Node(val address: Pos, val name: Char, val neighbours: MutableList<Pair<Pos, Int>>) /** * The current state of walking trough the graph while searching for the solution. * @property currentAddress the address where we're currently standing * @property steps the number of steps taken to come to this position * @property visitedPlaces a list of all places (0, 1, 2, 3 etc) that has been visited so far * @property visitedNodes a list of the coordinates of all nodes visited since the last * place. There is no reason to go back to a previously visited node until a new place * has been reached. * @property goingHome true if we have found all places and are trying to find the way back home */ data class WalkedPath(val currentAddress: Pos, val steps: Int, val visitedPlaces: List<Char>, val visitedNodes: List<Pos>, val goingHome: Boolean = false) // A representation of the map. Takes the ascii map as input and can generate a graph // that can be traversed more easily. data class Map(val theMap: List<String>) { private val theGraph = mutableMapOf<Pos, Node>() fun findStart(): Pos { theMap.forEachIndexed { y, s -> if (s.contains('0')) { return Pos(s.indexOf('0'), y) } } return Pos(-1, -1) } // Get all the direction that it's possible to move in from the given coordinate private fun getPossibleDirectionsFrom(address: Pos): List<Direction> { val ret = mutableListOf<Direction>() for (direction in Direction.entries) { val next = theMap[address.y + direction.dy][address.x + direction.dx] if (next != '#') { ret.add(direction) } } return ret } // Get the node at the given address and create one if needed private fun createNodeIfNeeded(address: Pos): Node { if (!theGraph.containsKey(address)) { theGraph[address] = Node(address, theMap[address.y][address.x], mutableListOf()) } return theGraph[address]!! } // Start at the given coordinate and walk to the next node. Return the coordinate of the next node // and the distance walked to get to that node. private tailrec fun walkToNextNode(address: Pos, comingFrom: Direction, distanceWalked: Int): Pair<Pos, Int>? { val dirs = getPossibleDirectionsFrom(address).filterNot { it == comingFrom } return when { theMap[address.y][address.x] in '0'..'9' || dirs.size > 1 -> { createNodeIfNeeded(address) Pair(address, distanceWalked) } dirs.isEmpty() -> null dirs.size == 1 -> { walkToNextNode(dirs[0].from(address), dirs[0].opposite(), distanceWalked + 1) } else -> throw(RuntimeException("Unexpected state")) } } // Given a node, find all it's neighbours and populate the neighbours list in order of closest to // furthers away. private fun findNeighboursOf(node: Node) { val dirs = getPossibleDirectionsFrom(node.address) // Room for improvement: No need to walk already known paths dirs.forEach { dir -> val nextNode = walkToNextNode(dir.from(node.address), dir.opposite(), 1) if (nextNode != null) { node.neighbours.add(nextNode) } } node.neighbours.sortBy { it.second } } // Convert the ascii map into a graph that can be traversed more easily (a map of coordinates to nodes). fun buildGraph(): MutableMap<Pos, Node> { val nodesToCheck = ArrayDeque<Node>() nodesToCheck.add(createNodeIfNeeded(findStart())) while (nodesToCheck.size > 0) { val node = nodesToCheck.removeFirst() findNeighboursOf(node) node.neighbours.filter { theGraph[it.first]!!.neighbours.isEmpty() }.forEach { if (!nodesToCheck.contains(theGraph[it.first])) { nodesToCheck.add(theGraph[it.first]) } } } return theGraph } } // Possible improvement that I never had to try: First make a reduced graph with // the shortest distances between all individual named nodes. Then do the below // algorithm of that tiny graph. Should probably reduce the total amount of nodes // that needs to be checked greatly. // Start at 0 and search trough the whole graph for the shortest path that passes // by each place of interest at least once. Optionally also returns back to the // start when all places of interest have been visited. // Returns the number of steps required for this. private fun searchGraph(theGraph: MutableMap<Pos, Node>, returnToStartWhenAllFound: Boolean = false): Int { val numPlacesToVisit = theGraph.filter { it.value.name != '.' }.size val alreadyChecked = mutableSetOf<Pair<Pos, List<Char>>>() val goingHomeFrom = mutableSetOf<Char>() val toCheck = GapList<WalkedPath>() // Time to solve Part 1 with: GapList ~6s, ArrayList: ~7s LinkedList: ~3m toCheck.add(WalkedPath(theMap.findStart(), 0, listOf(), listOf())) while (toCheck.isNotEmpty()) { val pathSoFar = toCheck.removeAt(0) if (!pathSoFar.visitedPlaces.containsAll(goingHomeFrom)) { // This path haven't yet found at least one node that a faster // path is already returning home from. There is no way this // path can be faster at finding all and going back to the goal // than that one. continue } // Check the current node that we're currently standing at val currentNode = theGraph[pathSoFar.currentAddress]!! alreadyChecked.add(Pair(pathSoFar.currentAddress, pathSoFar.visitedPlaces)) val visitedNodes = pathSoFar.visitedNodes.toMutableList() val visitedPlaces = pathSoFar.visitedPlaces.toMutableList() var goingHome = pathSoFar.goingHome if (!pathSoFar.goingHome && currentNode.name != '.' && !visitedPlaces.contains(currentNode.name)) { // We're visiting a place of interest for the first time visitedPlaces.add(currentNode.name) if (visitedPlaces.size == numPlacesToVisit) { if (returnToStartWhenAllFound) { goingHome = true goingHomeFrom.add(currentNode.name) } else { // When all places have been visited and we have no interest in // going back home, abort and return return pathSoFar.steps } } // After visiting a place of interest, it's OK to go back to a previous node again. // The shortest path might be by going back in the same direction we just came from. visitedNodes.clear() } else if (pathSoFar.goingHome && currentNode.name == '0') { // We're home and now we're finally done return pathSoFar.steps } visitedNodes.add(currentNode.address) // The node we're standing in wasn't the goal. We need to check all the neighbours. // But skip neighbours that we have already visited in the past val neighboursToCheck = currentNode.neighbours.filterNot { alreadyChecked.contains(Pair(it.first, visitedPlaces)) } for (neighbourNodeToCheck in neighboursToCheck) { val totalDistance = pathSoFar.steps + neighbourNodeToCheck.second val nextPath = WalkedPath(neighbourNodeToCheck.first, totalDistance, visitedPlaces, visitedNodes, goingHome) // Insert the WalkedPath at the correct place in the queue based on distance. if (toCheck.isEmpty()) { toCheck.add(nextPath) } else { val queuedWithSameState = toCheck.toList().filter { queuedPath -> queuedPath.currentAddress == nextPath.currentAddress && queuedPath.visitedPlaces == nextPath.visitedPlaces } var i = toCheck.size - 1 if (queuedWithSameState.isNotEmpty()) { if (queuedWithSameState.first().steps > totalDistance) { // remove the already queued one with more steps from the queue and start // searching for the correct place to add the new node at the place of the // removed one i = toCheck.indexOf(queuedWithSameState.first()) - 1 toCheck.remove(queuedWithSameState.first()) } else { // the one we are about to insert has more steps than something in the queue // already. Don't insert it at all. Move on to the next one instead. continue } } while (i >= 0) { if (totalDistance > toCheck[i].steps) { toCheck.add(i + 1, nextPath) break } else if (i == 0) { toCheck.add(0, nextPath) break } i-- } } } } return -1 } fun solvePart1(): Int { val graph = theMap.buildGraph() return searchGraph(graph) } fun solvePart2(): Int { val graph = theMap.buildGraph() return searchGraph(graph, true) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
10,983
aoc
MIT License
src/main/kotlin/solutions/day09/Day9.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day09 import solutions.Solver import utils.Coordinate import utils.Direction import utils.step import kotlin.math.abs class Day9 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val rope = mutableListOf<Coordinate>() val ropeLength = if (!partTwo) { 2 } else { 10 } for (i in 0 until ropeLength) { rope.add(Coordinate(0, 0)) } val visited = mutableSetOf<Coordinate>() for (line in input) { val parts = line.split(" ") val direction = when (parts[0]) { "R" -> Direction.RIGHT "D" -> Direction.DOWN "L" -> Direction.LEFT "U" -> Direction.UP else -> throw Error("Unsupported direction " + parts[0]) } val steps = parts[1].toInt() for (i in 0 until steps) { performStep(rope, direction, visited) } } return visited.size.toString() } private fun performStep( rope: MutableList<Coordinate>, direction: Direction, visited: MutableSet<Coordinate> ) { rope[0] = rope[0].step(direction) for (i in 1 until rope.size) { rope[i] = moveTail(rope[i], rope[i - 1]) } visited.add(rope.last()) } private fun moveTail(tail: Coordinate, head: Coordinate): Coordinate { if (abs(tail.x - head.x) <= 1 && abs(tail.y - head.y) <= 1) { return tail } if (tail.x == head.x) { return if (tail.y < head.y) { tail.step(Direction.UP) } else { tail.step(Direction.DOWN) } } if (tail.y == head.y) { return if (tail.x < head.x) { tail.step(Direction.RIGHT) } else { tail.step(Direction.LEFT) } } var newTailPos = tail newTailPos = if (tail.y < head.y) { newTailPos.step(Direction.UP) } else { newTailPos.step(Direction.DOWN) } newTailPos = if (tail.x < head.x) { newTailPos.step(Direction.RIGHT) } else { newTailPos.step(Direction.LEFT) } return newTailPos } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
2,376
Advent-of-Code-2022
MIT License
Kotlin Heroes 6 -Practice/G.kt
julianferres
163,219,585
false
{"C++": 768665, "Python": 164172, "Makefile": 51615, "C": 20271, "CMake": 15247, "Kotlin": 4329, "ReScript": 23}
data class Edge(val from: Int, val to: Int, val cost: Long) class DSU(val n: Int){ var par: MutableList<Int> = MutableList<Int>(n){ it } var sz: MutableList<Int> = MutableList<Int>(n){ 1 } fun find(x: Int): Int { if(par[x] != x) par[x] = find(par[x]) return par[x] } fun join(ii: Int, jj: Int): Boolean{ var i=find(ii); var j=find(jj); if(i == j) return false; if(sz[i] < sz[j]){ run { val temp = i; i = j; j = temp } } sz[i] += sz[j]; par[j] = i; return true } } fun main() { var (n, m) = readLine()!!.split(" ").map { it.toInt() } var a = readLine()!!.split(" ").map { it.toLong() } var mindex = a.indexOf(a.minBy{ it }) var edges = mutableListOf<Edge>() repeat(m){ var line = readLine()!!.split(" ") var from = line[0].toInt() var to = line[1].toInt() var cost = line[2].toLong() edges.add(Edge(from-1, to-1, cost)) } for (i in 0 until n){ edges.add(Edge(i, mindex, a[mindex] + a[i])) } edges.sortWith(compareBy {it.cost}) var dsu = DSU(n) var ans = 0L for(edge in edges){ if(dsu.find(edge.from) == dsu.find(edge.to)) continue else{ ans += edge.cost dsu.join(edge.from, edge.to) } } println(ans) }
0
C++
0
4
14e8369e82a2403094183d6f7824201f681c9f65
1,392
Codeforces
MIT License
2022/main/day_03/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_03_2022 import java.io.File val map = mapOf( 'a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5, 'f' to 6, 'g' to 7, 'h' to 8, 'i' to 9, 'j' to 10, 'k' to 11, 'l' to 12, 'm' to 13, 'n' to 14, 'o' to 15, 'p' to 16, 'q' to 17, 'r' to 18, 's' to 19, 't' to 20, 'u' to 21, 'v' to 22, 'w' to 23, 'x' to 24, 'y' to 25, 'z' to 26, 'A' to 27, 'B' to 28, 'C' to 29, 'D' to 30, 'E' to 31, 'F' to 32, 'G' to 33, 'H' to 34, 'I' to 35, 'J' to 36, 'K' to 37, 'L' to 38, 'M' to 39, 'N' to 40, 'O' to 41, 'P' to 42, 'Q' to 43, 'R' to 44, 'S' to 45, 'T' to 46, 'U' to 47, 'V' to 48, 'W' to 49, 'X' to 50, 'Y' to 51, 'Z' to 52 ) fun part1(input: List<String>) { val result = mutableListOf<Int>() for (line in input){ val first = line.subSequence(0, line.length / 2) val second = line.subSequence(line.length / 2, line.length) for (char in first) { if (second.contains(char)) { result.add(map[char]!!) break } } } print("The sum of the results is: ${result.sum()}") } fun part2(input: MutableList<String>) { val result = mutableListOf<Int>() while (input.size > 0){ val first = input.removeFirst().toSet() val second = input.removeFirst().toSet() val third = input.removeFirst().toSet() result.add(map[first.intersect(second).intersect(third).first()]!!) } print("The sum of the results is: ${result.sum()}") } fun main(){ val inputFile = File("src/inputs/Day_03.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines()) print("\n----- Part 2 -----\n") part2(inputFile.readLines().toMutableList()) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
1,700
AdventofCode
MIT License
src/main/kotlin/me/circuitrcay/euler/challenges/fiftyOneToSeventyFive/Problem60.kt
adamint
134,989,381
false
null
package me.circuitrcay.euler.challenges.fiftyOneToSeventyFive import me.circuitrcay.euler.Problem import me.circuitrcay.euler.utils.convertSieveToPlaces import me.circuitrcay.euler.utils.sieveOf class Problem60 : Problem<String>() { override fun calculate(): Any { val primes = sieveOf(10000).convertSieveToPlaces() return getPrimes(792,primes) val found = mutableListOf<Int>() for (a in primes) { println(a) for (b in primes) { if (!checkPrimes(a, b)) continue for (c in primes) { if (!checkPrimes(a, c) || !checkPrimes(b, c)) continue for (d in primes) { if (!checkPrimes(a, d) || !checkPrimes(b, d) || !checkPrimes(c, d)) continue found += a + b + c + d continue /* for (e in primes) { if (!checkPrimes(a, e) || !checkPrimes(b, e) || !checkPrimes(c, e) || !checkPrimes(d, e)) continue return a + b + c + d + e }*/ } } } } return found println(primes.size) println(primes.filter { it % 2 != 0 && it % 3 != 0 }.size) return 0 } private fun checkPrimes(a: Int, b: Int) = ((a.toString() + b.toString()).toBigInteger().isProbablePrime(90)) && ((b.toString() + a.toString()).toBigInteger().isProbablePrime(90)) private fun getPrimes(num: Int, primes: List<Int>): List<Int> { val matches = mutableListOf<Int>() primes.forEach { if (it > num) return matches else if (num % it == 0) matches.add(it) } return matches } }
0
Kotlin
0
0
cebe96422207000718dbee46dce92fb332118665
1,770
project-euler-kotlin
Apache License 2.0
src/main/kotlin/com/frankandrobot/rapier/nlp/generalize.kt
frankandrobot
62,833,944
false
null
/* * Copyright 2016 <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 com.frankandrobot.rapier.nlp import com.frankandrobot.rapier.pattern.* import com.frankandrobot.rapier.util.combinations import java.util.* /** * - if the two constraints are identical, then the new constraint is simply the same * as the original constraints. * - If either constraint is empty (the word or tag is unconstrained), then the * generalized constraint is also empty. * - If either constraint is a superset of the other, the new constraint will be the * superset. * - In all other cases, two alternative generalizations are created: one is the * union of the two constraints and one is the empty constraint. */ internal fun <T : Constraint> generalize(a : HashSet<out T>, b : HashSet<out T>) : List<HashSet<out T>> { // is one of the contraints empty? if (a.size == 0 || b.size == 0) { return listOf(hashSetOf()) } // is one a superset of the other? else if (a.size <= b.size && b.containsAll(a)) { return listOf(b) } else if (b.size <= a.size && a.containsAll(b)) { return listOf(a) } return listOf(hashSetOf(), (a + b) as HashSet<T>) } /** * Currently generalizes only words and POS tags so... * returns at most 4 pattern elements. */ fun generalize(a : PatternElement, b : PatternElement) : List<PatternElement> { var wordGeneralizations = generalize(a.wordConstraints, b.wordConstraints) var tagGeneralizations = generalize(a.posTagConstraints, b.posTagConstraints) return combinations(wordGeneralizations, tagGeneralizations) { wordConstraints : HashSet<out Constraint>, tagConstraints : HashSet<out Constraint> -> if (a is PatternItem && b is PatternItem) { PatternItem( wordConstraints as HashSet<out WordConstraint>, tagConstraints as HashSet<out PosTagConstraint> ) } else { val aLength = if (a is PatternList) a.length else 0 val bLength = if (b is PatternList) b.length else 0 val length = Math.max(aLength, bLength) PatternList( wordConstraints as HashSet<out WordConstraint>, tagConstraints as HashSet<out PosTagConstraint>, length = length ) } } }
1
Kotlin
1
1
ddbc0dab60ca595e63a701e2f8cd6694ff009adc
2,826
rapier
Apache License 2.0
week7fewestfactors/FewestFactors.kt
laitingsheng
341,616,623
false
null
class FewestFactors { private fun IntArray.swap(l: Int, r: Int) { val tmp = this[l] this[l] = this[r] this[r] = tmp } private val IntArray.number: Int get() = fold(0) { acc, it -> 10 * acc + it } private val Int.factors: Int get() { var nf = 0 var f = 1 while (f * f < this) { if (this % f == 0) nf += 2 ++f } if (f * f == this) ++nf return nf } fun number(digits: IntArray): Int { var mn = digits.number var mnf = mn.factors val s = digits.size val weights = IntArray(s) var i = 1 while (i < s) { if (weights[i] < i) { digits.swap(i, if (i % 2 == 0) 0 else weights[i]) val n = digits.number val nf = n.factors if (nf < mnf) { mnf = nf mn = n } else if (nf == mnf && n < mn) mn = n ++weights[i] i = 1 } else { weights[i] = 0 ++i } } return mn } }
0
Kotlin
0
0
2fc3e7a23d37d5e81cdf19a9ea19901b25941a49
1,268
2020S1-COMP-SCI-7007
ISC License
src/main/kotlin/year2022/day20/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2022.day20 import IProblem class Problem : IProblem { private val input = javaClass .getResource("/2022/20.txt")!! .readText() .lines() .filter(String::isNotEmpty) .map(String::toLong) private fun nthForward(node: Node, n: Int): Node { var curr = node for (i in 0 until n) { curr = curr.next!! } return curr } private fun sum(nodes: Array<Node>): Long { var curr = nodes.first() var n = 0L while (curr.value != 0L) { curr = curr.next!! } for (i in 0 until 3) { curr = nthForward(curr, 1000) n += curr.value } return n } private fun decrypt(list: List<Long>, shuffles: Int): Long { val nodes = Array(list.size) { Node(list[it], null, null) } for ((i, node) in nodes.withIndex()) { node.prev = nodes[(i - 1).mod(input.size)] node.next = nodes[(i + 1).mod(input.size)] } for (i in 0 until shuffles) { for (node in nodes) { val n = node.value.mod(nodes.size - 1) if (n == 0) { continue } val curr = nthForward(node, n) node.prev!!.next = node.next node.next!!.prev = node.prev node.prev = curr node.next = curr.next!! curr.next!!.prev = node curr.next = node } } return sum(nodes) } override fun part1(): Long { return decrypt(input, 1) } override fun part2(): Long { return decrypt(input.map { it * 811589153 }, 10) } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
1,759
advent-of-code
The Unlicense
src/main/kotlin/g1301_1400/s1339_maximum_product_of_splitted_binary_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1339_maximum_product_of_splitted_binary_tree // #Medium #Depth_First_Search #Tree #Binary_Tree // #2023_06_06_Time_384_ms_(100.00%)_Space_57.2_MB_(66.67%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private var maxProduct: Long = 0 private var total: Long = 0 fun sumTree(node: TreeNode?): Int { if (node == null) { return 0 } node.`val` += sumTree(node.left) + sumTree(node.right) return node.`val` } private fun helper(root: TreeNode?) { if (root == null) { return } helper(root.left) helper(root.right) val leftSubtreeVal = if (root.left != null) root.left!!.`val`.toLong() else 0L val leftProduct = leftSubtreeVal * (total - leftSubtreeVal) val rightSubtreeVal = if (root.right != null) root.right!!.`val`.toLong() else 0L val rightProduct = rightSubtreeVal * (total - rightSubtreeVal) maxProduct = Math.max(maxProduct, Math.max(leftProduct, rightProduct)) } fun maxProduct(root: TreeNode?): Int { if (root == null) { return 0 } total = sumTree(root).toLong() helper(root) return (maxProduct % 1000000007L).toInt() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,481
LeetCode-in-Kotlin
MIT License
core/src/main/kotlin/dev/komu/kraken/model/region/ShortestPathSearcher.kt
komu
83,556,775
false
{"Kotlin": 225797}
package dev.komu.kraken.model.region import java.util.* open class ShortestPathSearcher(val region: Region) { open val allowSubDirections = true fun findFirstCellOnShortestPath(start: Cell, goal: Cell): Cell? = findShortestPath(start, goal)?.drop(1)?.firstOrNull() fun findShortestPath(start: Cell, goal: Cell): Iterable<Cell>? { val openHeap = PriorityQueue<Node>() val openMap = CellMap<Node>(region) val closedMap = CellMap<Node>(region) val startNode = Node(goal, null, 0) startNode.heuristic = estimateCost(goal, start) openHeap.add(startNode) while (!openHeap.isEmpty()) { val current = openHeap.remove() if (current.cell == start) return current for (successor in current.successors(allowSubDirections)) { val closedNode = closedMap[successor.cell] if (closedNode != null) { if (closedNode.cost <= successor.cost) continue else closedMap.remove(successor.cell) } successor.parent = current successor.heuristic = successor.cost + estimateCost(successor.cell, goal) val openNode = openMap[successor.cell] if (openNode == null || openNode.heuristic > successor.heuristic) { openHeap.offer(successor) openMap[successor.cell] = successor } } closedMap[current.cell] = current } return null } protected open fun estimateCost(from: Cell, target: Cell): Int = from.distance(target) protected open fun costToEnter(cell: Cell): Int = 1 protected open fun canEnter(cell: Cell): Boolean = cell.isPassable private inner class Node(val cell: Cell, var parent: Node?, val cost: Int): Comparable<Node>, Iterable<Cell> { var heuristic = 0 override fun iterator() = iterator { var node: Node? = this@Node while (node != null) { yield(node.cell) node = node.parent } } fun successors(allowSubDirections: Boolean): Sequence<Node> { val adjacentCells = if (allowSubDirections) cell.adjacentCells else cell.adjacentCellsInMainDirections return adjacentCells.asSequence() .filter { it != parent?.cell && canEnter(it) } .map { Node(it, this, cost + costToEnter(it)) } } override fun compareTo(other: Node) = heuristic - other.heuristic override fun toString() = cell.toString() } }
0
Kotlin
0
0
680362d8e27c475b4ef1e2d13b67cb87f67249f6
2,715
kraken
Apache License 2.0
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day14.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day14 : Day<Long> { companion object { private val maskRegex = Regex("^mask = ([01X]+)$") private val setRegex = Regex("^mem\\[([0-9]+)] = ([0-9]+)$") } private val actions: Sequence<Action> = readDayInput() .lineSequence() .map { line -> val maskRes = maskRegex.find(line) val setRes = setRegex.find(line) when { maskRes != null -> Action.SetMask(maskRes.groupValues[1]) setRes != null -> Action.SetValue( addr = setRes.groupValues[1].toLong(), value = setRes.groupValues[2].toLong() ) else -> throw IllegalArgumentException() } } private data class Mask(val mask: String) { private fun Long.setBit(n: Int): Long = this or (1L shl n) private fun Long.clearBit(n: Int): Long = this and (1L shl n).inv() private val reverseMask: String = mask.reversed() fun maskValue(value: Long): Long = reverseMask.foldIndexed(value) { n: Int, acc: Long, bit: Char -> when (bit) { '0' -> acc.clearBit(n) '1' -> acc.setBit(n) else -> acc } } fun maskAddress(addr: Long): List<Long> = reverseMask.foldIndexed(listOf(addr)) { n: Int, acc: List<Long>, bit: Char -> when (bit) { '0' -> acc '1' -> acc.map { addr -> addr.setBit(n) } else -> acc.map { addr -> listOf( addr.setBit(n), addr.clearBit(n) ) }.flatten() } } } private data class State( val mask: Mask = Mask(""), val memory: Map<Long, Long> = mapOf() ) private sealed class Action { data class SetMask(val mask: String) : Action() data class SetValue(val addr: Long, val value: Long) : Action() } private fun State.reduceV1(action: Action): State = when (action) { is Action.SetMask -> copy(mask = Mask(action.mask)) is Action.SetValue -> copy(memory = memory.toMutableMap().apply { put(action.addr, mask.maskValue(action.value)) }) } private fun State.reduceV2(action: Action): State = when (action) { is Action.SetMask -> copy(mask = Mask(action.mask)) is Action.SetValue -> copy(memory = memory.toMutableMap().apply { mask.maskAddress(action.addr).forEach { addr -> put(addr, action.value) } }) } override fun step1(): Long { return actions .fold(State()) { acc, action -> acc.reduceV1(action) } .memory.values .sum() } override fun step2(): Long { return actions .fold(State()) { acc, action -> acc.reduceV2(action) } .memory.values .sum() } override val expectedStep1: Long = 13556564111697 override val expectedStep2: Long = 4173715962894 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
3,367
adventofcode
Apache License 2.0
mazes-for-programmers/kotlin/src/main/kotlin/io/github/ocirne/mazes/colorization/Colorization.kt
ocirne
496,354,199
false
{"Kotlin": 128908, "Python": 88203}
package io.github.ocirne.mazes.colorization import io.github.ocirne.mazes.grids.Cell import io.github.ocirne.mazes.grids.Maze import java.awt.Color import kotlin.math.roundToInt open class Colorization( private val grid: Maze, private val fromColor: Color = Color.DARK_GRAY, private val toColor: Color = Color.GREEN ){ private val defaultColor = Color.MAGENTA private val weights: MutableMap<Cell, Int> = mutableMapOf() private val texts: MutableMap<Cell, String> = mutableMapOf() var start: Cell? = null var goal: Cell? = null operator fun set(cell: Cell, value: String) { texts[cell] = value } private fun max(): Map.Entry<Cell, Int> { return weights.entries.maxBy { it.value } } fun dijkstra(startAt: Cell = grid.randomCell()): Colorization { weights[startAt] = 0 var frontier = mutableListOf(startAt) while (frontier.isNotEmpty()) { val newFrontier: MutableList<Cell> = mutableListOf() for (cell in frontier) { for (linked in cell.links()) { if (weights.contains(linked)) { continue } weights[linked] = weights[cell]!! + 1 newFrontier.add(linked) } } frontier = newFrontier } return this } fun longestPath(): Colorization { val bestStart = Colorization(grid).dijkstra().max().key start = bestStart val distances = Colorization(grid).dijkstra(bestStart) var current = distances.max().key goal = current weights[current] = distances.weights[current]!! while (current != start) { for (parent in current.links()) { if (distances.weights[parent]!! < distances.weights[current]!!) { weights[parent] = distances.weights[parent]!! current = parent break } } } return this } fun countLinks(): Colorization { val max = grid.eachCell().maxOf { it.links().size } grid.eachCell().forEach { weights[it] = max - it.links().size } return this } fun isValuedCell(cell: Cell?): Boolean { return weights.contains(cell) } open fun valueFor(cell: Cell): Color { val distance = weights[cell] ?: return defaultColor val maximum = max().value if (maximum == 0) { return defaultColor } val intensity = (maximum - distance).toFloat() / maximum val rangeRed = toColor.red - fromColor.red val rangeGreen = toColor.green - fromColor.green val rangeBlue = toColor.blue - fromColor.blue val r = (fromColor.red + rangeRed * intensity).roundToInt() val g = (fromColor.green + rangeGreen * intensity).roundToInt() val b = (fromColor.blue + rangeBlue * intensity).roundToInt() return Color(r, g, b) } fun marker(cell: Cell): String? { return texts[cell] } }
0
Kotlin
0
0
9f67bad218f6160fd0459ad258e9f7554c7f0527
3,114
mazes
The Unlicense
src/main/kotlin/ru/timakden/aoc/year2016/Day02.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2016 import ru.timakden.aoc.util.Point import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 2: Bathroom Security](https://adventofcode.com/2016/day/2). */ object Day02 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2016/Day02") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): String { var point = Point(1, 1) return input.map { point = goToTheNextPointPart1(point, it) keypadPart1[point.y][point.x] }.joinToString("") } fun part2(input: List<String>): String { var point = Point(0, 2) return input.map { point = goToTheNextPointPart2(point, it) keypadPart2[point.y][point.x] }.joinToString(separator = "") } private val keypadPart1 = arrayOf( charArrayOf('1', '2', '3'), charArrayOf('4', '5', '6'), charArrayOf('7', '8', '9') ) private val keypadPart2 = arrayOf( charArrayOf(' ', ' ', '1', ' ', ' '), charArrayOf(' ', '2', '3', '4', ' '), charArrayOf('5', '6', '7', '8', '9'), charArrayOf(' ', 'A', 'B', 'C', ' '), charArrayOf(' ', ' ', 'D', ' ', ' ') ) private fun goToTheNextPointPart1(point: Point, instruction: String): Point { var (x, y) = point instruction.forEach { when (it) { 'U' -> if (y != 0) y-- 'D' -> if (y != 2) y++ 'R' -> if (x != 2) x++ 'L' -> if (x != 0) x-- } } return Point(x, y) } private fun goToTheNextPointPart2(point: Point, instruction: String): Point { var (x, y) = point instruction.forEach { when (it) { 'U' -> if (!(y == 0 || keypadPart2[y - 1][x] == ' ')) y-- 'D' -> if (y != 4 && keypadPart2[y + 1][x] != ' ') y++ 'R' -> if (x != 4 && keypadPart2[y][x + 1] != ' ') x++ 'L' -> if (!(x == 0 || keypadPart2[y][x - 1] == ' ')) x-- } } return Point(x, y) } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,271
advent-of-code
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day22.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.ints fun main() { Day22.run() } object Day22 : Day(2015, 22) { private val costs = mapOf( 'M' to 53, 'D' to 73, 'S' to 113, 'P' to 173, 'R' to 229 ) private val bossHp = ints(input)[0] private val bossDmg = ints(input)[1] private const val hp = 50 private const val mana = 500 data class Result(val seq: String, val cost: Int) data class Effect(val spell: Char, var left: Int) override fun part1(): Any { val results = mutableMapOf<String, Int>() while(results.values.minOrNull() == null) { for (i in 0..4_000_000) { val r = play(false) if (r.cost < Int.MAX_VALUE) { results.putIfAbsent(r.seq, r.cost) } } } return results.values.minOrNull()!! } private fun play(hardMode : Boolean): Result { var hpLeft = hp var manaLeft = mana var bossHpLeft = bossHp var playerArmor = 0 var seq = "" val effects = mutableListOf<Effect>() var turn = 0 while (true) { val effectsIt = effects.iterator() while (effectsIt.hasNext()) { val effect = effectsIt.next() effect.left-- when (effect.spell) { 'R' -> { manaLeft += 101 } 'P' -> { bossHpLeft -= 3 if (bossHpLeft < 1) return Result(seq, seq.toCharArray().map { costs[it]!! }.sum()) } } if (effect.left == 0) { effectsIt.remove() if (effect.spell == 'S') { playerArmor -= 7 } } } if (turn % 2 == 0) { if (hardMode) { hpLeft-- if (hpLeft < 1) { return Result(seq, Int.MAX_VALUE) } } val activeEffects = effects.map { e -> e.spell }.toList() val candidateSpells = costs.filter { it.value <= manaLeft }.map { it.key }.filter { !activeEffects.contains(it) }.toList() if (candidateSpells.isEmpty()) { return Result(seq, Int.MAX_VALUE) } val s = candidateSpells.random() seq += s when (s) { 'M' -> { bossHpLeft -= 4 if (bossHpLeft < 1) return Result(seq, seq.toCharArray().map { costs[it]!! }.sum()) manaLeft -= 53 } 'D' -> { bossHpLeft -= 2 if (bossHpLeft < 1) return Result(seq, seq.toCharArray().map { costs[it]!! }.sum()) hpLeft += 2 manaLeft -= 73 } 'S' -> { playerArmor += 7 effects.add(Effect('S', 6)) manaLeft -= 113 } 'P' -> { effects.add(Effect('P', 6)) manaLeft -= 173 } 'R' -> { effects.add(Effect('R', 5)) manaLeft -= 229 } } } else { hpLeft -= (bossDmg - playerArmor) if (hpLeft < 1) { return Result(seq, Int.MAX_VALUE) } } turn ++ } } override fun part2(): Any { val results = mutableMapOf<String, Int>() while(results.values.minOrNull() == null) { for (i in 0..4_000_000) { val r = play(true) if (r.cost < Int.MAX_VALUE) { results.putIfAbsent(r.seq, r.cost) } } } return results.values.minOrNull()!! } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
4,257
adventofkotlin
MIT License
src/Day06.kt
alexdesi
575,352,526
false
{"Kotlin": 9824}
import java.io.File fun String.occurrences(c: Char) = this.count { it == c } fun main() { fun duplicatesPresent(string4: String): Boolean { string4.forEach { println(string4.occurrences(it)) if (string4.occurrences(it) > 1) return true } return false } fun part1(code: String): Int { (0..code.length - 4).forEach { i -> if (!duplicatesPresent(code.substring(i, i + 4))) { return i + 4 } } return -1 } // Part 2 is identical to part 1, it just use 14 instead of 4 for the packet size // This would need refactor. fun part2(code: String): Int { (0..code.length - 4).forEach { i -> if (!duplicatesPresent(code.substring(i, i + 14))) { return i + 14 } } return -1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") println(part1(testInput[0])) check(part1(testInput[0]) == 5) val input = readInput("Day06") println(part1(input[0])) println(part2(input[0])) }
0
Kotlin
0
0
56a6345e0e005da09cb5e2c7f67c49f1379c720d
1,175
advent-of-code-kotlin
Apache License 2.0
app/src/main/java/com/canerkorkmaz/cicek/jobdistribution/solver/GreedySolver.kt
nberktumer
173,110,988
false
{"Kotlin": 47340}
package com.canerkorkmaz.cicek.jobdistribution.solver import com.canerkorkmaz.cicek.jobdistribution.model.InputDataFormatted import com.canerkorkmaz.cicek.jobdistribution.model.JobData import com.canerkorkmaz.cicek.jobdistribution.model.Solution import com.canerkorkmaz.cicek.jobdistribution.model.SolutionPack import com.canerkorkmaz.cicek.jobdistribution.model.StoreData import com.canerkorkmaz.cicek.jobdistribution.model.distanceSqr /** * Greedy valid solution generator with a simple heuristic */ class GreedySolver(data: InputDataFormatted) : SolverBase(data) { override fun solve(): SolutionPack { val solutions = data.stores.keys.associateWith { mutableSetOf<JobData>() } val jobs = data.jobList.toMutableSet() // Put min number of closest jobs to each store for (store in data.storeList) { val jobsSorted = jobs.sortedBy { it.distanceSqr(store) } .take(store.min) solutions.getValue(store.name).addAll(jobsSorted) jobs.removeAll(jobsSorted) } val remainingDistances: Map<JobData, List<StoreData>> = jobs.associateWith { data.storeList.sortedBy { store -> store.distanceSqr(it) } } val availableStores = data.stores.keys.toMutableSet() for (store in data.stores) { if (solutions.getValue(store.key).size >= store.value.max) { availableStores.remove(store.key) } } // Put remaining jobs to the closest store that has available space for((job, stores) in remainingDistances) { val store = stores.first { availableStores.contains(it.name) } val sol = solutions.getValue(store.name) sol.add(job) if(sol.size >= store.max) { availableStores.remove(store.name) } } return SolutionPack( solutions.map { (key, value) -> Solution(data.stores.getValue(key), value) } .associateBy { it.store.name }, data ) } }
0
Kotlin
0
0
bd3356d1dcd0da1fa4a4ed5967205ea488724d3a
2,081
CicekSepeti-Hackathon
Apache License 2.0
src/Day06Alternate.kt
aneroid
572,802,061
false
{"Kotlin": 27313}
class Day06Alternate(private val input: String) { private fun String.indexForUniqSeqLen(size: Int): Int { val checkArray = IntArray(26) { 0 } return withIndex().first { (index, char) -> checkArray[char - 'a']++ if (index >= size) { checkArray[elementAt(index - size) - 'a']-- } index >= size - 1 && checkArray.none { it > 1 } }.index + 1 } fun partOne(): Int = input.indexForUniqSeqLen(4) fun partTwo(): Int = input.indexForUniqSeqLen(14) } fun main() { val testInputs = readInput("Day06_test") val input = readInput("Day06").first() println("part One:") assertThat(testInputs.map { Day06Alternate(it).partOne() }).isEqualTo(listOf(7, 5, 6, 10, 11)) println("actual: ${Day06Alternate(input).partOne()}\n") println("part Two:") assertThat(testInputs.map { Day06Alternate(it).partTwo() }).isEqualTo(listOf(19, 23, 23, 29, 26)) println("actual: ${Day06Alternate(input).partTwo()}\n") }
0
Kotlin
0
0
cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd
1,040
advent-of-code-2022-kotlin
Apache License 2.0
src/sorting/AdvancedSorting.kt
ArtemBotnev
136,745,749
false
{"Kotlin": 79256, "Shell": 292}
package sorting import java.util.* /** * sorts array by quick sort algorithm * * @param array which isn't sorted * @return sorted array */ fun quickSort(array: Array<Int>): Array<Int> { /** * sorts array * * @param arr which isn't sorted * @param low lower border in array which should be sorted * @param high higher border in array which should be sorted */ fun sort(arr: Array<Int>, low: Int, high: Int) { if (low >= high) return // determine pivot element of array, just using random val pivot = arr[Random().nextInt(high - low + 1) + low] var left = low var right = high while (left <= right) { // move toward pivot // check that elements on the left of pivot are smaller than pivot while (arr[left] < pivot) left++ // check that elements on the right of pivot are bigger than pivot while (arr[right] > pivot) right-- // if not, sorting.swap it if (left <= right) { swap(arr, left, right) left++ right-- } } // recursively do the same for array's parts until its size is 1 sort(arr, low, right) sort(arr, left, high) } // sort array sort(array, 0, array.size - 1) println("Quick sort:") println(Arrays.toString(array)) return array } /** * sorts array by quick sort algorithm with last right element as a pivot * * @param array which isn't sorted * @return sorted array */ fun rightEdgePivotQuickSort(array: Array<Int>): Array<Int> { /** * partitions array or sub array to two part whit elements less than pivot * and elements more than pivot * * @param left - edge array or sub array * @param right - edge array or sub array * @param pivot element * @return index of pivot's final position */ fun partition(left: Int, right: Int, pivot: Int): Int { var leftPointer = left - 1 var rightPointer = right while (true) { // search element more than pivot into left part while (array[++leftPointer] < pivot) {} // search element less than pivot into right part while (rightPointer > 0 && array[--rightPointer] > pivot) {} // pointers' intersection if (leftPointer >= rightPointer) { break } else { // replace elements swap(array, leftPointer, rightPointer) } } // replace last left element and pivot swap(array, leftPointer, right) return leftPointer } /** * sorts array * * @param left border in array which should be sorted * @param right border in array which should be sorted */ fun sort(left: Int, right: Int) { if (right - left <= 0) return // last right element as a pivot val pivot = array[right] val part = partition(left, right, pivot) sort(left, part - 1) sort(part + 1, right) } sort(0, array.size - 1) println("Right edge pivot quick sort:") println(Arrays.toString(array)) return array } /** * sorts array by quick sort algorithm with median as a pivot * * @param array which isn't sorted * @return sorted array */ fun medianQuickSort(array: Array<Int>): Array<Int> { /** * finds median according to 3 points * * @param left - edge array or sub array * @param right - edge array or sub array * @return median */ fun getMedian(left: Int, right: Int): Int { val center = (left + right) shr 1 if (array[left] > array[center]) swap(array, left, center) if (array[left] > array[right]) swap(array, left, right) if (array[center] > array[right]) swap(array, center, right) // place median to right edge swap(array, center, right - 1) return array[right - 1] } /** * partitions array or sub array to two part whit elements less than pivot * and elements more than pivot * * @param left - edge array or sub array * @param right - edge array or sub array * @param pivot element * @return index of pivot's final position */ fun partition(left: Int, right: Int, pivot: Int): Int { var leftPointer = left var rightPointer = right - 1 while (true) { // search element more than pivot into left part while (array[++leftPointer] < pivot) {} // search element less than pivot into right part while (array[--rightPointer] > pivot) {} // pointers' intersection if (leftPointer >= rightPointer) { break } else { // replace elements swap(array, leftPointer, rightPointer) } } // replace last left element and pivot swap(array, leftPointer, right -1) return leftPointer } /** * simple insert sort for part of array * * @param left - edge array or sub array * @param right - edge array or sub array */ fun insertSort(left: Int, right: Int) { for (j in left + 1..right) { val temp = array[j] var i = j while (i > 0 && array[i - 1] > temp) { array[i] = array[i - 1] i-- } array[i] = temp } } /** * sorts array * * @param left - edge array or sub array * @param right - edge array or sub array */ fun sort(left: Int, right: Int) { // if amount of elements less than 7 - apply simple sort algorithm if (right - left + 1 < 7) { insertSort(left, right) } else { // median as a pivot val pivot = getMedian(left, right) val part = partition(left, right, pivot) sort(left, part - 1) sort(part + 1, right) } } sort(0, array.size - 1) println("Median quick sort:") println(Arrays.toString(array)) return array } /** * sorts array by merge sort algorithm * * @param array which isn't sorted * @return sorted array */ fun mergeSort(array: Array<Int>): Array<Int> { /** * merges two arrays * * @param ar1 first array * @param ar2 second array * @return array that is the result of merge ar1 and ar2 */ fun merge(ar1: Array<Int>, ar2: Array<Int>): Array<Int> { val resSize = ar1.size + ar2.size val arRes = Array(resSize) { 0 } var index1 = 0 var index2 = 0 for (i in 0..(resSize - 1)) { arRes[i] = when { index1 == ar1.size -> ar2[index2++] index2 == ar2.size -> ar1[index1++] else -> if (ar1[index1] < ar2[index2]) ar1[index1++] else ar2[index2++] } } return arRes } /** * splits source array into left and right part of it * does the same recursively until size of parts 1 * * @param arr source array * @return final result */ fun sort(arr: Array<Int>): Array<Int> { if (arr.size < 2) return arr val middle = arr.size shr 1 // create copies of left and right parts val ar1 = Arrays.copyOfRange(arr, 0, middle) val ar2 = Arrays.copyOfRange(arr, middle, arr.size) val a = sort(ar1) val b = sort(ar2) return merge(a, b) } println("Merge sort: ") println(Arrays.toString(sort(array))) return array } /** * sorts array by Shell sort algorithm * * @param array which isn't sorted * @return sorted array */ fun shellSort(array: Array<Int>): Array<Int> { val size = array.size var j: Int var temp: Int var gap = 1 while (gap <= size / 3) gap = 3 * gap + 1 while (gap > 0) { for (i in gap until size) { temp = array[i] j = i while (j > gap - 1 && array[j - gap] >= temp) { array[j] = array[j - gap] j -= gap } array[j] = temp } gap = (gap - 1) / 3 } println("Shell sort: ") println(Arrays.toString(array)) return array } /** * just swaps two elements of array * * @param ar array * @param i index of first element * @param j index of second element */ private fun swap(ar: Array<Int>, i: Int, j: Int) { if (ar[i] > ar[j]) { val temp = ar[i] ar[i] = ar[j] ar[j] = temp } }
0
Kotlin
0
0
530c02e5d769ab0a49e7c3a66647dd286e18eb9d
8,720
Algorithms-and-Data-Structures
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day12.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
import se.saidaspen.aoc.util.* fun main() = Day12.run() object Day12 : Day(2022, 12) { private val map = toMap(input) private fun costOf(b: Pair<Int, Int>, a: Pair<Int, Int>) = (map[b]!!.code - 'a'.code) - (map[a]!!.code - 'a'.code) private val startPos = map.entries.first { it.value == 'S' }.key private val endPos = map.entries.first { it.value == 'E' }.key init { map[startPos] = 'a' map[endPos] = 'z' } override fun part1() = search(startPos).second override fun part2(): Any { val candidateStarts = map.entries.filter { it.value == 'a' }.map { it.key } return candidateStarts.map { search(it) }.filter { it.first != null }.minOf { it.second } } private fun search(s: P<Int, Int>) = bfs(s, { it == endPos }, { t -> t.neighborsSimple().filter { map.containsKey(it) } .filter { costOf(it, t) <= 1 } .toMutableList() }) }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
945
adventofkotlin
MIT License
src/day10/Day10.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day10 import readInput import readTestInput private fun computeRegisterValues(input: List<String>) = sequence { var registerValue = 1 for (instruction in input) { val instructionParts = instruction.split(' ') val op = instructionParts.first() val args = instructionParts.drop(1) when (op) { "noop" -> yield(registerValue) "addx" -> { yield(registerValue) yield(registerValue) registerValue += args.single().toInt() } } } } private fun part1(input: List<String>): Int { val register = computeRegisterValues(input) val signalStrengths = register.mapIndexedNotNull { index, registerValue -> val cycle = index + 1 if ((cycle - 20) % 40 == 0) { cycle * registerValue } else null } return signalStrengths.sum() } private fun part2(input: List<String>): String { val register = computeRegisterValues(input) val display = register .mapIndexed { index, registerValue -> val crtPosition = index % 40 when { registerValue - crtPosition in -1..1 -> '#' else -> '.' } } .windowed(size = 40, step = 40) { characters -> String(characters.toCharArray()) } return display.joinToString(separator = "\n") } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day10") check(part1(testInput) == 13140) check( part2(testInput) == """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """.trimIndent()) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
2,016
advent-of-code-kotlin-2022
Apache License 2.0
project/src/problems/GreedyAlgorithms.kt
informramiz
173,284,942
false
null
package problems /** * Created by <NAME> on 2019-06-19 * https://codility.com/media/train/14-GreedyAlgorithms.pdf * * ----------Description--------------- * We consider problems in which a result comprises a sequence of steps or choices that have to be made to achieve the * optimal solution. Greedy programming is a method by which a solution is determined based on making the locally * optimal choice at any given moment. In other words, we choose the best decision from the viewpoint of the * current stage of the solution. * Depending on the problem, the greedy method of solving a task may or may not be the best approach. * If it is not the best approach, then it often returns a result which is approximately correct but suboptimal. * In such cases dynamic programming or brute-force can be the optimal approach. On the other hand, * if it works correctly, its running time is usually faster than those of dynamic programming or brute-force. */ object GreedyAlgorithms { /** * https://codility.com/media/train/14-GreedyAlgorithms.pdf * --------Problem--------- * There are n > 0 canoeists(people to ride to a paddle boat) weighing * respectively 1 <= w0 <= w1 <= . . . <= wn−1 <= 10^9. * The goal is to seat them in the minimum number of double canoes(paddle boats) * whose displacement (the maximum load) equals k. * You may assume that wi <= k. * * -------Solution----------- * The fattest canoeist is seated with the thinnest, as long as their weight is less than or equal to k. * If not, the fattest canoeist is seated alone in the canoe. */ fun greedyCanoeist(W: IntArray, k: Int): Int { var start = 0 var end = W.lastIndex var canoesCount = 0 while (start <= end) { //try to seat a fattest (highest w) with lightest (smallest w), otherwise seat fattest alone if (W[start] + W[end] <= k) { //both skinny and fattest were seated start++ end-- } else { //lightest skinny and fattest were not seated together so seat fattest alone end-- } canoesCount++ } return canoesCount } /** * https://app.codility.com/programmers/lessons/16-greedy_algorithms/tie_ropes/ * * TieRopes * Tie adjacent ropes to achieve the maximum number of ropes of length >= K. * Programming language: * There are N ropes numbered from 0 to N − 1, whose lengths are given in an array A, lying on the floor in a line. For each I (0 ≤ I < N), the length of rope I on the line is A[I]. * We say that two ropes I and I + 1 are adjacent. Two adjacent ropes can be tied together with a knot, and the length of the tied rope is the sum of lengths of both ropes. The resulting new rope can then be tied again. * For a given integer K, the goal is to tie the ropes in such a way that the number of ropes whose length is greater than or equal to K is maximal. * For example, consider K = 4 and array A such that: * A[0] = 1 * A[1] = 2 * A[2] = 3 * A[3] = 4 * A[4] = 1 * A[5] = 1 * A[6] = 3 * The ropes are shown in the figure below. * We can tie: * rope 1 with rope 2 to produce a rope of length A[1] + A[2] = 5; * rope 4 with rope 5 with rope 6 to produce a rope of length A[4] + A[5] + A[6] = 5. * After that, there will be three ropes whose lengths are greater than or equal to K = 4. It is not possible to produce four such ropes. * Write a function: * class Solution { public int solution(int K, int[] A); } * that, given an integer K and a non-empty array A of N integers, returns the maximum number of ropes of length greater than or equal to K that can be created. * For example, given K = 4 and array A such that: * A[0] = 1 * A[1] = 2 * A[2] = 3 * A[3] = 4 * A[4] = 1 * A[5] = 1 * A[6] = 3 * the function should return 3, as explained above. * Write an efficient algorithm for the following assumptions: * N is an integer within the range [1..100,000]; * K is an integer within the range [1..1,000,000,000]; * each element of array A is an integer within the range [1..1,000,000,000]. */ fun tieRopes(A: IntArray, K: Int): Int { var count = 0 var runningLength = 0L for (length in A) { runningLength += length if (runningLength >= K) { count++ runningLength = 0 } } return count } /** * https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ * ---------MaxNonoverlappingSegments-------------- * Find a maximal set of non-overlapping segments. * Programming language: * Located on a line are N segments, numbered from 0 to N − 1, whose positions are given in arrays A and B. For each I (0 ≤ I < N) the position of segment I is from A[I] to B[I] (inclusive). The segments are sorted by their ends, which means that B[K] ≤ B[K + 1] for K such that 0 ≤ K < N − 1. * Two segments I and J, such that I ≠ J, are overlapping if they share at least one common point. In other words, A[I] ≤ A[J] ≤ B[I] or A[J] ≤ A[I] ≤ B[J]. * We say that the set of segments is non-overlapping if it contains no two overlapping segments. The goal is to find the size of a non-overlapping set containing the maximal number of segments. * For example, consider arrays A, B such that: * A[0] = 1 B[0] = 5 * A[1] = 3 B[1] = 6 * A[2] = 7 B[2] = 8 * A[3] = 9 B[3] = 9 * A[4] = 9 B[4] = 10 * The segments are shown in the figure below. * The size of a non-overlapping set containing a maximal number of segments is 3. For example, possible sets are {0, 2, 3}, {0, 2, 4}, {1, 2, 3} or {1, 2, 4}. There is no non-overlapping set with four segments. * Write a function: * class Solution { public int solution(int[] A, int[] B); } * that, given two arrays A and B consisting of N integers, returns the size of a non-overlapping set containing a maximal number of segments. * For example, given arrays A, B shown above, the function should return 3, as explained above. * Write an efficient algorithm for the following assumptions: * N is an integer within the range [0..30,000]; * each element of arrays A, B is an integer within the range [0..1,000,000,000]; * A[I] ≤ B[I], for each I (0 ≤ I < N); * B[K] ≤ B[K + 1], for each K (0 ≤ K < N − 1). * * * ----------Solution----------- * As segments are sorted by their ends (B[0] <= B[1] ... <= B[N-1]) so pick the segments which finish * early, verify that it does not overlap with the previously picked segment. If it does not overlap then * count it */ fun maxNonOverlappingSegments(A: IntArray, B: IntArray): Int { if (A.isEmpty()) return 0 var count = 1 var lastEnd = B[0] for (i in 1 until A.size) { if (A[i] > lastEnd) { count++ lastEnd = B[i] } } return count } }
0
Kotlin
0
0
a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4
7,322
codility-challenges-practice
Apache License 2.0