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
Kotlin/src/main/kotlin/org/algorithm/problems/0022_partition_labels.kt
raulhsant
213,479,201
true
{"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187}
package org.algorithm.problems class `0022_partition_labels` { fun partitionLabels(S: String): List<Int> { val lettersIntervals = MutableList<Pair<Int, Int>>(26) { _ -> Pair(Int.MAX_VALUE, Int.MIN_VALUE) } val result = mutableListOf<Int>() for (i in 0 until S.length) { val index = S[i] - 'a' if (lettersIntervals[index].first == Int.MAX_VALUE) { lettersIntervals[index] = Pair(i, i) } else { lettersIntervals[index] = Pair(lettersIntervals[index].first, i) } } val intervals = mutableListOf<Pair<Int, Int>>() val mergedIntervals = mutableListOf<Pair<Int, Int>>() for (inter in lettersIntervals) { if (inter.first != Int.MAX_VALUE) { intervals.add(inter) } } intervals.sortWith(Comparator { p1: Pair<Int, Int>, p2: Pair<Int, Int> -> if (p1.first == p2.first) p1.second - p2.second else p1.first - p2.first }) var currInterval = intervals.first() for (i in 1 until intervals.size) { val inter = intervals[i] if (currInterval.second > inter.first) { val first = Math.min(currInterval.first, inter.first) val second = Math.max(currInterval.second, inter.second) currInterval = Pair(first, second) } else { mergedIntervals.add(currInterval) currInterval = inter } } mergedIntervals.add(currInterval) for (inter in mergedIntervals) { result.add(inter.second - inter.first + 1) } return result } }
0
C++
0
0
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
1,728
algorithms
MIT License
src/main/kotlin/com/staricka/adventofcode2022/Day14.kt
mathstar
569,952,400
false
{"Kotlin": 77567}
package com.staricka.adventofcode2022 import kotlin.math.max import kotlin.math.min class Day14 : Day { override val id = 14 enum class Tile { AIR, ROCK, SAND } class Grid { val map = HashMap<Int, MutableMap<Int, Tile>>() private var maxRockY = Int.MIN_VALUE fun get(x: Int, y: Int): Tile = map[x]?.get(y) ?: Tile.AIR fun put(x: Int, y: Int, tile: Tile) { map.computeIfAbsent(x) {HashMap()}[y] = tile } fun putRockSegment(a: Pair<Int, Int>, b: Pair<Int, Int>) { if (a.first == b.first) { val start = min(a.second, b.second) val end = max(a.second, b.second) maxRockY = max(maxRockY, end) for (i in start..end) { put(a.first, i, Tile.ROCK) } } else { val start = min(a.first, b.first) val end = max(a.first, b.first) maxRockY = max(maxRockY, a.second) for (i in start..end) { put(i, a.second, Tile.ROCK) } } } // true if drop terminates fun dropSand(dropX: Int, dropY: Int): Boolean { var x = dropX var y = dropY while (y < maxRockY) { when (Tile.AIR) { get(x, y + 1) -> { y++ } get(x - 1, y + 1) -> { x-- y++ } get(x + 1, y + 1) -> { x++ y++ } else -> { put(x, y, Tile.SAND) return true } } } return false } // true if drop terminates fun dropSandPart2(dropX: Int, dropY: Int): Boolean { var x = dropX var y = dropY while (y < maxRockY + 1) { when (Tile.AIR) { get(x, y + 1) -> { y++ } get(x - 1, y + 1) -> { x-- y++ } get(x + 1, y + 1) -> { x++ y++ } else -> { put(x, y, Tile.SAND) return x != 500 || y != 0 } } } put(x, y, Tile.SAND) return true } } private fun generateGrid(input: String): Grid { val grid = Grid() input.lines().forEach { line -> val split = line.split(" -> ") for (i in 1 until split.size) { val a = split[i - 1].split(",") val b = split[i].split(",") grid.putRockSegment(Pair(a[0].toInt(), a[1].toInt()), Pair(b[0].toInt(), b[1].toInt())) } } return grid } override fun part1(input: String): Any { val grid = generateGrid(input) var sand = 0 while (grid.dropSand(500, 0)) { sand++ } return sand } override fun part2(input: String): Any { val grid = generateGrid(input) var sand = 0 while (grid.dropSandPart2(500, 0)) { sand++ } return sand + 1 } }
0
Kotlin
0
0
2fd07f21348a708109d06ea97ae8104eb8ee6a02
2,823
adventOfCode2022
MIT License
src/main/kotlin/Puzzle12.kt
namyxc
317,466,668
false
null
import kotlin.math.absoluteValue object Puzzle12 { @JvmStatic fun main(args: Array<String>) { val input = Puzzle12::class.java.getResource("puzzle12.txt").readText() val calculatedDistance = calculateDistance(input) println(calculatedDistance) val calculateDistanceWithWaypoint = calculateDistanceWithWaypoint(input) println(calculateDistanceWithWaypoint) } enum class Command { N, S, E, W, L, R, F } enum class Direction { N { override fun toCommand() = Command.N }, S { override fun toCommand() = Command.S }, E { override fun toCommand() = Command.E }, W { override fun toCommand() = Command.W }; abstract fun toCommand() : Command } class ShipData( private var headTo: Direction, private var posEast: Int, private var posNorth: Int, private var waypointPosEast: Int = 0, private var waypointPosNorth: Int = 0){ fun getDistance() = posEast.absoluteValue + posNorth.absoluteValue fun move(command: Command, i: Int){ when (command) { Command.N -> { posNorth += i } Command.S -> { posNorth -= i } Command.E -> { posEast += i } Command.W -> { posEast -= i } Command.L -> { val cnt = (i / 90) val newHeadTo = (headTo.ordinal + cnt ) % 4 headTo = Direction.values()[newHeadTo] } Command.R -> { val cnt = (i / 90) val newHeadTo = (headTo.ordinal - cnt + 4 * cnt ) % 4 headTo = Direction.values()[newHeadTo] } Command.F -> { move(headTo.toCommand(), i) } } } fun moveWithWaypoint(command: Command, i: Int){ when (command) { Command.N -> { waypointPosNorth += i } Command.S -> { waypointPosNorth -= i } Command.E -> { waypointPosEast += i } Command.W -> { waypointPosEast -= i } Command.L -> { moveWithWaypoint(Command.R, -i) } Command.R -> { var num = i if (i < 0) num = i + 360 when ((num / 90)){ 1 -> { val oldWaypointPosNorth = waypointPosNorth val oldWaypointPosEast = waypointPosEast waypointPosNorth = -oldWaypointPosEast waypointPosEast = oldWaypointPosNorth } 2 -> { val oldWaypointPosNorth = waypointPosNorth val oldWaypointPosEast = waypointPosEast waypointPosNorth = -oldWaypointPosNorth waypointPosEast = -oldWaypointPosEast } 3 -> { val oldWaypointPosNorth = waypointPosNorth val oldWaypointPosEast = waypointPosEast waypointPosNorth = oldWaypointPosEast waypointPosEast = -oldWaypointPosNorth } } } Command.F -> { posNorth += i * waypointPosNorth posEast += i * waypointPosEast } } } } fun calculateDistance(input: String): Int { val commands = input.split("\n") val shipData = ShipData(Direction.E, 0, 0) commands.forEach { commandString -> val command = commandString.first().toString() val number = commandString.substring(1).toInt() shipData.move(Command.valueOf(command), number) } return shipData.getDistance() } fun calculateDistanceWithWaypoint(input: String): Int { val commands = input.split("\n") val shipData = ShipData(Direction.E, 0, 0, 10, 1) commands.forEach { commandString -> val command = commandString.first().toString() val number = commandString.substring(1).toInt() shipData.moveWithWaypoint(Command.valueOf(command), number) } return shipData.getDistance() } }
0
Kotlin
0
0
60fa6991ac204de6a756456406e1f87c3784f0af
4,583
adventOfCode2020
MIT License
src/main/kotlin/net/rafaeltoledo/kotlin/advent/Day01.kt
rafaeltoledo
726,542,427
false
{"Kotlin": 11895}
package net.rafaeltoledo.kotlin.advent private val numbers = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9, ) class Day01 { fun invoke(rawInput: String): Int { val lines = rawInput.split("\n").filter { it.isNotEmpty() } return lines.sumOf { "${ it.findDigit( { str -> str.substring(1) }, { first() }, { startsWith(it) }, ) }${ it.findDigit( { str -> str.substring(0, str.length - 1) }, { last() }, { endsWith(it) }) }".toInt() } } } private fun String.findDigit( substring: (String) -> String, charPicker: String.() -> Char, stringEval: String.(String) -> Boolean ): String { var value = this do { if (value.isEmpty()) break val digit = value.findDigit({ charPicker() }, { stringEval(it) }) if (digit == -1) value = substring(value) else return digit.toString() } while (true) return "" } private fun String.findDigit( charPicker: String.() -> Char, stringEval: String.(String) -> Boolean ): Int { if (isEmpty()) { return -1 } if (charPicker().isDigit()) { return charPicker().digitToInt() } numbers.keys.forEach { if (stringEval(it)) return numbers.getOrDefault(it, -1) } return -1 }
0
Kotlin
0
0
7bee985147466cd796e0183d7c719ca6d01b5908
1,370
aoc2023
Apache License 2.0
src/main/kotlin/g1801_1900/s1824_minimum_sideway_jumps/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1824_minimum_sideway_jumps // #Medium #Array #Dynamic_Programming #Greedy // #2023_06_20_Time_726_ms_(100.00%)_Space_98.6_MB_(100.00%) class Solution { fun minSideJumps(obstacles: IntArray): Int { var sideJumps = 0 var currLane = 2 var i = 0 while (i < obstacles.size - 1) { if (obstacles[i + 1] == currLane) { if (obstacles[i] != 0) { currLane = getNextLane(obstacles[i], obstacles[i + 1]) } else { var j = i + 2 while (j < obstacles.size && (obstacles[j] == 0 || obstacles[j] == obstacles[i + 1]) ) { j++ } if (j < obstacles.size) { currLane = getNextLane(obstacles[i + 1], obstacles[j]) } else { i = obstacles.size - 1 } } sideJumps++ } i++ } return sideJumps } private fun getNextLane(nextObstacle: Int, nextNextObstacle: Int): Int { if (nextObstacle == 2 && nextNextObstacle == 3 || nextObstacle == 3 && nextNextObstacle == 2) { return 1 } return if (nextObstacle == 1 && nextNextObstacle == 3 || nextObstacle == 3 && nextNextObstacle == 1 ) { 2 } else { 3 } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,495
LeetCode-in-Kotlin
MIT License
advent-of-code/src/main/kotlin/DayFive.kt
pauliancu97
518,083,754
false
{"Kotlin": 36950}
class DayFive { companion object { private val VOWELS = setOf('a', 'e', 'i', 'o', 'u') private val FORBIDDEN_STRINGS = setOf("ab", "cd", "pq", "xy") } private fun isStringNice(string: String): Boolean { val hasSufficientVowels = string.count { it in VOWELS } >= 3 val hasRepeatedLetter = string.dropLast(1).zip(string.drop(1)) .any { (first, second) -> first == second } val hasNotForbiddenStrings = !FORBIDDEN_STRINGS.any { it in string } return hasSufficientVowels && hasRepeatedLetter && hasNotForbiddenStrings } private fun hasRepeatedTwoCharacters(string: String): Boolean { for (index in 0 until (string.length - 1)) { val testedSubstring = string.substring(index until (index + 2)) val remainingSubstring = string.substring((index + 2) until string.length) if (testedSubstring in remainingSubstring) { return true } } return false } private fun hasSeparatedSameCharacter(string: String): Boolean { for (index in 0 until (string.length - 2)) { if (string[index] == string[index + 2]) { return true } } return false } private fun isSuperNiceString(string: String) = hasRepeatedTwoCharacters(string) && hasSeparatedSameCharacter(string) fun solvePartOne() { val strings = readLines("day_five.txt") val numOfNiceStrings = strings.count { isStringNice(it) } println(numOfNiceStrings) } fun solvePartTwo() { val strings = readLines("day_five.txt") val numOfNiceStrings = strings.count { isSuperNiceString(it) } println(numOfNiceStrings) } } fun main() { DayFive().solvePartTwo() }
0
Kotlin
0
0
3ba05bc0d3e27d9cbfd99ca37ca0db0775bb72d6
1,812
advent-of-code-2015
MIT License
src/main/java/com/kotlinspirit/ext/RangeExtensions.kt
tiksem
494,746,133
false
{"Kotlin": 411301, "HTML": 2017}
package com.kotlinspirit.ext import java.util.StringJoiner internal operator fun CharRange.minus(range: CharRange): List<CharRange> { if (range.first <= this.first && range.last >= this.last) { return emptyList() } return if (range.first > this.first && range.last < this.last) { listOf( first until range.first, (range.last + 1)..last ) } else if (range.first <= this.first && range.last >= this.first) { listOf( (range.last + 1)..this.last ) } else if (range.first > this.first && range.last >= this.last && range.first <= this.last) { listOf( this.first until range.first ) } else { listOf(this) } } internal operator fun CharRange.plus(range: CharRange): List<CharRange> { return when { range.first <= this.first && range.last >= this.last -> { listOf(range) } this.first <= range.first && this.last >= range.last -> { listOf(this) } range.first <= this.first && range.last <= this.last && range.last >= this.first - 1 -> { listOf(range.first..this.last) } range.first > this.first && range.last >= this.last && range.first <= this.last + 1 -> { listOf(this.first..range.last) } else -> { return listOf(this, range) } } } // List should be sorted by first private fun List<CharRange>.optimizeRanges(): List<CharRange> { if (size <= 1) { return this } val result = arrayListOf(this[0]) var i = 1 val size = this.size while (i < size) { result.addAll(result.removeLast() + this[i]) i++ } return result } internal fun List<CharRange>.includeRanges(ranges: List<CharRange>): List<CharRange> { return (this + ranges).sortedBy { it.first }.optimizeRanges() } internal fun List<CharRange>.excludeRange(range: CharRange): List<CharRange> { val result = ArrayList<CharRange>() for (thisRange in this) { result.addAll(thisRange - range) } return result } internal fun List<CharRange>.excludeRanges(ranges: List<CharRange>): List<CharRange> { if (ranges.isEmpty()) { return this } var list = this for (range in ranges) { list = list.excludeRange(range) } return list.sortedBy { it.first }.optimizeRanges() } internal val IntRange.debugString: String get() { if (this.last == Int.MAX_VALUE) { return "$first,max" } else { return "$first,$last" } }
0
Kotlin
0
1
8c2001f632f4a8a13b97a32f38ec327695b8bc75
2,633
KotlinSpirit
MIT License
src/main/kotlin/com/github/aoc/AOCD7P2.kt
frikit
317,914,710
false
null
package com.github.aoc import com.github.aoc.utils.* fun main() { val input = InputParser.parseInput(InputDay7Problem2) .map { it.replace(".", "") } .map { it.replace("bags", "") } .map { it.replace("bag", "") } val bagType = "shiny gold" val res = findOtherColors(input, 1, bagType) Result.stopExecutionPrintResult(res - 1) } private fun findOtherColors(input: List<String>, currNumberOfBags: Int, bagType: String): Int { if (bagType == "no other") return 0 var res = 1 val colors = input.filter { it.split("contain")[0].contains(bagType) } .map { it.split("contain")[1].trim().split(",") .map { clr -> clr.trim() } }.flatten() .map { color -> val times = if (color.contains("no other")) 1 else color.split(" ")[0].trim().toInt() val colorType = color.replace(times.toString(), "").trim() times to colorType } colors.forEach { res += findOtherColors(input, it.first, it.second) } return res * currNumberOfBags }
0
Kotlin
0
0
2fca82225a19144bbbca39247ba57c42a30ef459
1,075
aoc2020
Apache License 2.0
src/Day10.kt
zuevmaxim
572,255,617
false
{"Kotlin": 17901}
private fun List<String>.toSignals(): Sequence<Int> { var value = 1 return sequence { for (line in this@toSignals) { yield(value) if (line != "noop") { yield(value) value += line.substring(5).toInt() } } } } private fun part1(input: List<String>): Int { val signals = input.toSignals().toList() val target = listOf(20, 60, 100, 140, 180, 220) return target.sumOf { it * signals[it - 1] } } private fun part2(input: List<String>): String { val height = 6 val width = 40 val result = List(height) { MutableList(width) { '.' } } var i = 0 input.toSignals().forEach { n -> if (i % width in n - 1..n + 1) { result[i / width][i % width] = '#' } i++ } return result.joinToString("\n") { it.joinToString("") } } fun main() { val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check( part2(testInput) == """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######.....""".trimIndent() ) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
34356dd1f6e27cc45c8b4f0d9849f89604af0dfd
1,422
AOC2022
Apache License 2.0
src/Day20.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
import java.io.File // Advent of Code 2022, Day 20: Grove Positioning System // Keep the original index in order to make each value unique // In input, there are duplicate values. data class Day20(val num: Long, val origIdx: Int) { override fun toString(): String = num.toString() } fun main() { fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim() fun solve(input: String, key: Int, repeatTimes: Int): Long { val numsBackup = input.split("\n").mapIndexed { idx, s -> Day20(s.toLong() * key, idx) } val nums = numsBackup.toMutableList() val size = numsBackup.size val zero = nums.first { it.num == 0L } repeat(repeatTimes) { numsBackup.forEach { val idx = nums.indexOf(it) val thing = nums.removeAt(idx) val newIdx = (idx + thing.num).mod(size-1) nums.add(newIdx, thing) } } val zeroIdx = nums.indexOf(zero) val list = mutableListOf<Long>() list.add(nums[(1_000 + zeroIdx).mod(size)].num) list.add(nums[(2_000 + zeroIdx).mod(size)].num) list.add(nums[(3_000 + zeroIdx).mod(size)].num) return list.sum() } val testInput = readInputAsOneLine("Day20_test") check(solve(testInput, 1, 1)==3L) check(solve(testInput, 811589153, 10)==1623178306L) val input = readInputAsOneLine("Day20") println(solve(input, 1, 1)) println(solve(input, 811589153, 10)) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
1,507
AdventOfCode2022
Apache License 2.0
src/test/kotlin/chapter5/solutions/ex13/listing.kt
DavidGomesh
680,857,367
false
{"Kotlin": 204685}
package chapter5.solutions.ex13 import chapter3.List import chapter3.Nil import chapter4.None import chapter4.Option import chapter4.Some import chapter5.Cons import chapter5.Stream import chapter5.toList import io.kotest.matchers.shouldBe import io.kotest.core.spec.style.WordSpec //tag::map[] fun <A, B> Stream<A>.map(f: (A) -> B): Stream<B> = Stream.unfold(this) { s: Stream<A> -> when (s) { is Cons -> Some(f(s.head()) to s.tail()) else -> None } } //end::map[] //tag::take[] fun <A> Stream<A>.take(n: Int): Stream<A> = Stream.unfold(this) { s: Stream<A> -> when (s) { is Cons -> if (n > 0) Some(s.head() to s.tail().take(n - 1)) else None else -> None } } //end::take[] //tag::takewhile[] fun <A> Stream<A>.takeWhile(p: (A) -> Boolean): Stream<A> = Stream.unfold(this, { s: Stream<A> -> when (s) { is Cons -> if (p(s.head())) Some(s.head() to s.tail()) else None else -> None } }) //end::takewhile[] //tag::zipwith[] fun <A, B, C> Stream<A>.zipWith( that: Stream<B>, f: (A, B) -> C ): Stream<C> = Stream.unfold(this to that) { (ths: Stream<A>, tht: Stream<B>) -> when (ths) { is Cons -> when (tht) { is Cons -> Some( Pair( f(ths.head(), tht.head()), ths.tail() to tht.tail() ) ) else -> None } else -> None } } //end::zipwith[] //tag::zipall[] fun <A, B> Stream<A>.zipAll( that: Stream<B> ): Stream<Pair<Option<A>, Option<B>>> = Stream.unfold(this to that) { (ths, tht) -> when (ths) { is Cons -> when (tht) { is Cons -> Some( Pair( Some(ths.head()) to Some(tht.head()), ths.tail() to tht.tail() ) ) else -> Some( Pair( Some(ths.head()) to None, ths.tail() to Stream.empty<B>() ) ) } else -> when (tht) { is Cons -> Some( Pair( None to Some(tht.head()), Stream.empty<A>() to tht.tail() ) ) else -> None } } } //end::zipall[] class Solution13 : WordSpec({ "Stream.map" should { "apply a function to each evaluated element in a stream" { val s = Stream.of(1, 2, 3, 4, 5) s.map { "${(it * 2)}" }.toList() shouldBe List.of("2", "4", "6", "8", "10") } "return an empty stream if no elements are found" { Stream.empty<Int>() .map { (it * 2).toString() } shouldBe Stream.empty() } } "Stream.take(n)" should { "return the first n elements of a stream" { val s = Stream.of(1, 2, 3, 4, 5) s.take(3).toList() shouldBe List.of(1, 2, 3) } "return all the elements if the stream is exhausted" { val s = Stream.of(1, 2, 3) s.take(5).toList() shouldBe List.of(1, 2, 3) } "return an empty stream if the stream is empty" { val s = Stream.empty<Int>() s.take(3).toList() shouldBe Nil } } "Stream.takeWhile" should { "return elements while the predicate evaluates true" { val s = Stream.of(1, 2, 3, 4, 5) s.takeWhile { it < 4 }.toList() shouldBe List.of(1, 2, 3) } "return all elements if predicate always evaluates true" { val s = Stream.of(1, 2, 3, 4, 5) s.takeWhile { true }.toList() shouldBe List.of(1, 2, 3, 4, 5) } "return empty if predicate always evaluates false" { val s = Stream.of(1, 2, 3, 4, 5) s.takeWhile { false }.toList() shouldBe List.empty() } } "Stream.zipWith" should { "apply a function to elements of two corresponding lists" { Stream.of(1, 2, 3).zipWith( Stream.of(4, 5, 6) ) { x, y -> x + y }.toList() shouldBe List.of(5, 7, 9) } } "Stream.zipAll" should { "combine two streams of equal length" { Stream.of(1, 2, 3).zipAll(Stream.of(1, 2, 3)) .toList() shouldBe List.of( Some(1) to Some(1), Some(2) to Some(2), Some(3) to Some(3) ) } "combine two streams until the first is exhausted" { Stream.of(1, 2, 3, 4).zipAll(Stream.of(1, 2, 3)) .toList() shouldBe List.of( Some(1) to Some(1), Some(2) to Some(2), Some(3) to Some(3), Some(4) to None ) } "combine two streams until the second is exhausted" { Stream.of(1, 2, 3).zipAll(Stream.of(1, 2, 3, 4)) .toList() shouldBe List.of( Some(1) to Some(1), Some(2) to Some(2), Some(3) to Some(3), None to Some(4) ) } } })
0
Kotlin
0
0
41fd131cd5049cbafce8efff044bc00d8acddebd
5,763
fp-kotlin
MIT License
src/main/kotlin/kr/co/programmers/P67257.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers import java.util.* // https://github.com/antop-dev/algorithm/issues/415 class P67257 { // 문자열이 숫자인지 판단하는 정규표현식 val number = Regex("^[0-9]*$") // 연산자 우선 순위 경우의 수 private val ops = listOf( arrayOf('*', '+', '-'), arrayOf('*', '-', '+'), arrayOf('+', '*', '-'), arrayOf('+', '-', '*'), arrayOf('-', '*', '+'), arrayOf('-', '+', '*') ) fun solution(expression: String): Long { var answer = 0L for (op in ops) { val postfix = toPostfix(expression, op) var value = calculate(postfix) if (value < 0) value *= -1 if (value > answer) { answer = value } } return answer } // 중위 표기법 → 후위 표기법 private fun toPostfix(infix: String, op: Array<Char>): List<String> { val stack = Stack<Char>() val postfix = mutableListOf<String>() var num = 0 for (ch in infix) { if (ch in '0'..'9') { num = (num * 10) + (ch - '0') } else { postfix += "$num" num = 0 while (stack.isNotEmpty() && op.indexOf(stack.peek()) <= op.indexOf(ch)) { postfix += "${stack.pop()}" } stack += ch } } // 남은 숫자와 연산자들 처리 postfix += "$num" while (stack.isNotEmpty()) { postfix += "${stack.pop()}" } return postfix } // 후위 표기법으로 계산 private fun calculate(postfix: List<String>): Long { val stack = Stack<Long>() for (v in postfix) { stack += if (v.matches(number)) { v.toLong() } else { val b = stack.pop() val a = stack.pop() when (v[0]) { '+' -> a + b '-' -> a - b else -> a * b } } } return stack.pop() } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
2,171
algorithm
MIT License
src/main/kotlin/com/lucaszeta/adventofcode2020/day24/day24.kt
LucasZeta
317,600,635
false
null
package com.lucaszeta.adventofcode2020.day24 import com.lucaszeta.adventofcode2020.ext.getResourceAsText const val BLACK = '#' const val WHITE = '.' fun main() { val directionsList = getResourceAsText("/day24/directions-list.txt") .split("\n") .filter { it.isNotEmpty() } .map(::parseToDirections) val flippedTiles = flipTiles(directionsList) println("Number of tiles flipped to black: ${flippedTiles.count { it.value == BLACK }}") } fun flipTiles( directionsList: List<List<Direction>> ): Map<Pair<Double, Double>, Char> { val tiles = mutableMapOf<Pair<Double, Double>, Char>() for (directions in directionsList) { val destination = navigateToTile(directions) tiles[destination] = if (tiles.containsKey(destination)) WHITE else BLACK } return tiles.toMap() } fun navigateToTile(directions: List<Direction>): Pair<Double, Double> { var coordinateX = 0.0 var coordinateY = 0.0 directions.forEach { coordinateY += when (it) { Direction.NORTHEAST, Direction.NORTHWEST -> 1.0 Direction.SOUTHEAST, Direction.SOUTHWEST -> -1.0 else -> 0.0 } coordinateX += when (it) { Direction.NORTHEAST, Direction.SOUTHEAST -> 0.5 Direction.NORTHWEST, Direction.SOUTHWEST -> -0.5 Direction.EAST -> 1.0 Direction.WEST -> -1.0 } } return coordinateX to coordinateY } fun parseToDirections(line: String): List<Direction> { val directionsRegex = run { val allDirections = Direction.allDirections().joinToString("|") "($allDirections)".toRegex() } return directionsRegex.findAll(line) .map { Direction.fromCoordinate(it.groupValues[1]) } .toList() }
0
Kotlin
0
1
9c19513814da34e623f2bec63024af8324388025
1,840
advent-of-code-2020
MIT License
kotlin/src/com/s13g/aoc/aoc2021/Day24.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 24: Arithmetic Logic Unit --- * https://adventofcode.com/2021/day/24 */ class Day24 : Solver { override fun solve(lines: List<String>): Result { val partA = OptimizedALU(9 downTo 1).solve(-1, 0, 0, 0, 0).second val partB = OptimizedALU(1..9).solve(-1, 0, 0, 0, 0).second return Result(partA, partB) } private class OptimizedALU(val numRange: IntProgression) { val NO_RESULT = Pair(false, "") // This is extracted from the input... val params = listOf( Parameters(14L, 1L, 7L), Parameters(12L, 1L, 4L), Parameters(11L, 1L, 8L), Parameters(-4L, 26L, 1L), Parameters(10L, 1L, 5L), Parameters(10L, 1L, 14L), Parameters(15L, 1L, 12L), Parameters(-9L, 26L, 10L), Parameters(-9L, 26L, 5L), Parameters(12L, 1L, 7L), Parameters(-15L, 26L, 6L), Parameters(-7L, 26L, 8L), Parameters(-10L, 26L, 4L), Parameters(0L, 26L, 6L) ) // Memoization of the solve function. val cache = mutableMapOf<AluState, Pair<Boolean, String>>() fun solveCached( block: Int, input: Long, xx: Long, yy: Long, zz: Long ): Pair<Boolean, String> { // A bit of a hack, but this shortens the number of tries significantly. if (zz > 5000000) return NO_RESULT val state = AluState(block, input, xx, yy, zz) if (cache.containsKey(state)) return cache[state]!! val result = solve(block, input, xx, yy, zz) cache[state] = result return result } fun solve( block: Int, inp: Long, xx: Long, yy: Long, zz: Long ): Pair<Boolean, String> { var x = xx var y = yy var z = zz if (block >= 0) { // Reverse engineered from the input. x = if ((z % 26 + params[block].a) == inp) 0 else 1 z = (z / params[block].b) * ((25 * x) + 1) + (inp + params[block].c) * x } // This was the last block. if (block == 13) { return Pair(z == 0L, "") } // Continue with the next digits. Depth first search... for (n in numRange) { val res = solveCached(block + 1, n.toLong(), x, y, z) if (res.first) { return Pair(true, "$n${res.second}") } } return NO_RESULT } } /** Used to cache the result. */ private data class AluState( val block: Int, val input: Long, val x: Long, val y: Long, val z: Long ) private data class Parameters(val a: Long, val b: Long, val c: Long) }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,628
euler
Apache License 2.0
src/day11/Day11.kt
idle-code
572,642,410
false
{"Kotlin": 79612}
package day11 import logEnabled import readInput private const val DAY_NUMBER = 11 typealias WorryLevel = Long typealias MonkeyId = Int class Monkey( val id: MonkeyId, startingItems: List<WorryLevel>, private val operation: Operation, val test: TestOperation, private val successTarget: MonkeyId, private val failureTarget: MonkeyId ) { val items: MutableList<WorryLevel> = startingItems.toMutableList() var inspectionCounter: Long = 0 class Operation(private val left: String, private val op: String, private val right: String) { fun run(level: WorryLevel): WorryLevel { val leftValue = tokenToValue(left, level) val rightValue = tokenToValue(right, level) return when (op) { "+" -> leftValue + rightValue "*" -> leftValue * rightValue else -> throw IllegalArgumentException("Invalid operand $op") } } private fun tokenToValue(token: String, oldValue: WorryLevel): WorryLevel { return if (token == "old") oldValue else token.toLong() } override fun toString(): String = "new = $left $op $right" } class TestOperation(val number: Long) { fun run(testedValue: WorryLevel): Boolean { return testedValue % number == 0L } override fun toString(): String = "divisible by $number" } fun inspect(level: WorryLevel, worryLevelDecreaser: (WorryLevel) -> WorryLevel): Pair<WorryLevel, MonkeyId> { ++inspectionCounter var newLevel = operation.run(level) newLevel = worryLevelDecreaser(newLevel) return if (test.run(newLevel)) newLevel to successTarget else newLevel to failureTarget } override fun toString(): String { return """Monkey $id: Items: ${items.joinToString(", ")} Operation: $operation Test: $test If true: throw to monkey $successTarget If false: throw to monkey $failureTarget""" } } fun main() { fun parseMonkey(iterator: Iterator<String>): Monkey { val monkeyId = iterator.next().substringAfter("Monkey ").substringBefore(':').toInt() val startingItems = iterator.next().substringAfter(" Starting items: ").split(", ").map { it.toLong() } val expr = iterator.next().substringAfter(" Operation: new = ") val (left, op, right) = expr.split(' ') val operation = Monkey.Operation(left, op, right) val testOperation = Monkey.TestOperation(iterator.next().substringAfter(" Test: divisible by ").toLong()) val successTarget = iterator.next().substringAfter(" If true: throw to monkey ").toInt() val failureTarget = iterator.next().substringAfter(" If false: throw to monkey ").toInt() if (iterator.hasNext()) iterator.next() // Consume separating empty line return Monkey(monkeyId, startingItems, operation, testOperation, successTarget, failureTarget) } fun parseInput(rawInput: List<String>): List<Monkey> { val iterator = rawInput.iterator() val monkeys = mutableListOf<Monkey>() while (iterator.hasNext()) { monkeys.add(parseMonkey(iterator)) } return monkeys } fun simulateRound(monkeys: List<Monkey>, worryLevelDecreaser: (WorryLevel) -> WorryLevel) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { val itemLevel = monkey.items.removeFirst() val (newItemLevel, targetMonkey) = monkey.inspect(itemLevel, worryLevelDecreaser) monkeys[targetMonkey].items.add(newItemLevel) } } } fun calculateMonkeyBusiness(monkeys: List<Monkey>): Long { val monkeyInspections = monkeys.map { it.inspectionCounter }.sortedDescending() return monkeyInspections[0] * monkeyInspections[1] } fun part1(rawInput: List<String>): Long { val monkeys = parseInput(rawInput) for (round in 1..20) { simulateRound(monkeys) { level -> level / 3 } } return calculateMonkeyBusiness(monkeys) } fun part2(rawInput: List<String>): Long { val monkeys = parseInput(rawInput) val leastCommonMultiplier = monkeys.map { it.test.number }.reduce { acc, l -> acc * l } for (round in 1..10000) { simulateRound(monkeys) { level -> level % leastCommonMultiplier } } return calculateMonkeyBusiness(monkeys) } val sampleInput = readInput("sample_data", DAY_NUMBER) val mainInput = readInput("main_data", DAY_NUMBER) logEnabled = false val part1SampleResult = part1(sampleInput) println(part1SampleResult) check(part1SampleResult == 10605L) val part1MainResult = part1(mainInput) println(part1MainResult) check(part1MainResult == 66802L) val part2SampleResult = part2(sampleInput) println(part2SampleResult) check(part2SampleResult == 2713310158) val part2MainResult = part2(mainInput) println(part2MainResult) check(part2MainResult == 21800916620) }
0
Kotlin
0
0
1b261c399a0a84c333cf16f1031b4b1f18b651c7
5,189
advent-of-code-2022
Apache License 2.0
core-kotlin-modules/core-kotlin-strings-4/src/main/kotlin/com/baeldung/countvowelconsonant/CountVowelConsonant.kt
Baeldung
260,481,121
false
{"Kotlin": 1476024, "Java": 43013, "HTML": 4883}
package com.baeldung.countvowelconsonant val VOWELS = "aAeEiIoOuU" fun countUsingLoopAndIfCondition(sentence: String): Pair<Int, Int> { var vowelCount = 0 var consonantCount = 0 for (char in sentence) { if (char.isLetter()) { if (char in VOWELS) { vowelCount++ } else { consonantCount++ } } } return vowelCount to consonantCount } fun countUsingLoopAndWhenExpression(sentence: String): Pair<Int, Int> { var vowelCount = 0 var consonantCount = 0 for (char in sentence) { when { char.isLetter() && char in VOWELS -> vowelCount++ char.isLetter() && char !in VOWELS -> consonantCount++ } } return vowelCount to consonantCount } fun countUsingFilter(sentence: String): Pair<Int, Int> { val filteredChars = sentence.filter { it.isLetter() } val vowelCount = filteredChars.count { it in VOWELS } val consonantCount = filteredChars.count() - vowelCount return vowelCount to consonantCount } fun countUsingFold(sentence: String): Pair<Int, Int> { val (vowelCount, consonantCount) = sentence.fold(0 to 0) { acc, char -> if (char.isLetter()) { if (char in VOWELS) { acc.first + 1 to acc.second } else { acc.first to acc.second + 1 } } else { acc } } return vowelCount to consonantCount } fun countUsingHigherOrderFunction(sentence: String, condition: (Char) -> Boolean): Int { return sentence.count(condition) } fun countUsingRegex(sentence: String): Pair<Int, Int> { val vowelCount = Regex("[$VOWELS]").findAll(sentence).count() val consonantCount = Regex("[a-zA-Z]").findAll(sentence).count() - vowelCount return vowelCount to consonantCount } fun countUsingMap(sentence: String): Pair<Int, Int> { val letterCounts = sentence.groupingBy { it } .eachCount() val vowelCount = letterCounts.filterKeys { it in VOWELS }.values.sum() val consonantCount = letterCounts.filterKeys { it.isLetter() && it !in VOWELS }.values.sum() return vowelCount to consonantCount }
10
Kotlin
273
410
2b718f002ce5ea1cb09217937dc630ff31757693
2,201
kotlin-tutorials
MIT License
src/Day08.kt
frungl
573,598,286
false
{"Kotlin": 86423}
@OptIn(ExperimentalStdlibApi::class) fun main() { fun List<String>.getRow(i: Int): String = this[i] fun List<String>.getCol(j: Int): String = joinToString("") { it[j].toString() } fun isCovered(s: String, pos: Int): Boolean { val list = s.toCharArray().map { it.digitToInt() } return list.take(pos).max() >= list[pos] && list[pos] <= list.takeLast(list.size - pos - 1).max() } fun List<Int>.aboba(b: Int): Int = when { isEmpty() -> 0 max() < b -> size else -> takeWhile { it < b }.size + 1 } fun countCnt(s: String, pos: Int): Int { val list = s.toCharArray().map { it.digitToInt() } return list.take(pos).asReversed().aboba(list[pos]) * list.takeLast(list.size - pos - 1).aboba(list[pos]) } fun part1(input: List<String>): Int { val height = input.size val width = input[0].length return height * width - (1..<height-1).sumOf { h -> (1..<width-1).count { w -> isCovered(input.getRow(h), w) && isCovered(input.getCol(w), h) } } } fun part2(input: List<String>): Int { val height = input.size val width = input[0].length return (0..<height).maxOf { h -> (0 ..< width).maxOf { w -> countCnt(input.getRow(h), w) * countCnt(input.getCol(w), h) } } } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
1,649
aoc2022
Apache License 2.0
src/main/kotlin/day15.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.Input fun main() { val input = Input.day(15) println(day15A(input)) println(day15B(input)) } fun day15A(input: Input): Int { return input.text.split(',').sumOf(::hash) } fun day15B(input: Input): Int { val hashMap = MyHashMap() input.text.split(',').forEach { if(it.contains('-')) { val label = it.dropLast(1) hashMap.remove(hash(label), label) } else { val (label, focalLength) = it.split('=') hashMap.insert(hash(label), Lens(label, focalLength.toInt())) } } return hashMap.focusingPower() } private fun hash(string: String): Int { var value = 0 for(char in string) { value += char.code value *= 17 value %= 256 } return value } private class MyHashMap { private val boxes = List(256) { mutableListOf<Lens>() } fun insert(box: Int, lens: Lens) { boxes[box].find { it.label == lens.label }?.let { it.focalLength = lens.focalLength return } boxes[box].add(lens) } fun remove(box: Int, label: String) { boxes[box].removeIf { it.label == label } } fun focusingPower(): Int { return boxes.foldIndexed(0) { box, acc, lenses -> acc + lenses.foldIndexed(0) { index, boxAcc, lens -> boxAcc + (box + 1) * (index + 1) * lens.focalLength } } } } private data class Lens(val label: String, var focalLength: Int)
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
1,507
AdventOfCode2023
MIT License
listFunctions.kt
InertExpert2911
348,750,125
false
null
// GATHERING A LIST OF VALUES fun getListOfNumbers() : List<Int> { var myList = mutableListOf <Int> () for(i in 1..7){ println("Enter a number:") var Number = Integer.valueOf(readLine()) myList.add(Number) } return myList } // FINDING THE MAX VALUE fun findMax(maxList : List<Int>) : Int { var largestNumber = maxList[0] // The loop runs for every element in the list and compares it with the largest number. If the conditional is true then, the largest number is updated. for(j in maxList){ if(j > largestNumber){ largestNumber = j } } return largestNumber } // FINDING THE MIN VALUE fun findMin(minList : List<Int>) : Int { var smallestNumber = minList[0] // The loop runs for every element in the list and compares it with the smallest number. If the conditional is true then, the smallest number is updated. for(k in minList){ if(k < smallestNumber){ smallestNumber = k } } return smallestNumber } // FINDING THE AVERAGE fun findAverage(listAvg : List<Int>) : Int { var sum = 0 for(l in listAvg){ sum += l } return sum / listAvg.size } // FINDING IF A LIST CONTAINS A VALUE fun checkIfListContains(checkList : List<Int>, numToCheck : Int) : Boolean { for(m in checkList){ if(m == numToCheck){ return true } } return false } // MAIN FUNCTION fun main() { // OUTPUT OF THE LIST var values = getListOfNumbers() println(values) // OUTPUT FOR THE MAX VALUE var largestValue = findMax(values) println("The largest number is $largestValue") // OUTPUT FOR THE MIN VALUE var smallestValue = findMin(values) println("The smallest number is $smallestValue") // OUTPUT OF THE AVERAGE var average = findAverage(values) println("The average is $average") // TO CHECK IF A VALUE CONTAINS println("Enter the number you want to check:") var numToFind = Integer.valueOf(readLine()) var containsValue = checkIfListContains(values, numToFind) if(containsValue == true){ println("Number Found !!!!") } else { println("Number Not Found ???? WTF !!!") } } // ADDITIONAL CHALLENGES // 1. Create a function that returns the difference between the largest and smallest number in the list. // ANS: For the first prompt, use the logic from findMin() and findMax() to find the smallest and largest numbers. Then, return the difference between the two. /* // FUNC THAT RETURNS THE DIFF BW MIN AND MAX fun minMaxDiff(minMaxDiffList : List<Int>) : Int{ //LARGEST var largest = findMax(minMaxDiffList) //SMALLEST var smallest = findMin(minMaxDiffList) // DIFF var difference = largest - smallest return difference } fun main() { // LARGEST - SMALLEST var diff = minMaxDiff(values) println("The minMaxDiff is $diff") } */ // 2. Create a function that takes in a list of numbers and returns a list with all the values squared. // ANS: For the second prompt, create an empty list. Then, loop through each element of the list argument; inside the loop, add the value of the element multiplied by itself. /* //SQUARE fun squareNum(sqList : List<Int>) : List<Int> { for(z in sqList){ // sqList[z] = z * z var num = z * z // sqList[0] // sqList.remove() sqList.add(num) } return sqList } EROORS WORK IT OUT */
0
Kotlin
0
0
9ec619b2dc2eae4f2b10aed70fb0f9fd33db0951
3,383
Kotlin-Projects
MIT License
src/Day06.kt
mr3y-the-programmer
572,001,640
false
{"Kotlin": 8306}
fun main() { fun part1(input: List<String>): Int { return firstDistinctCharsWindow(input, 4) } fun part2(input: List<String>): Int { return firstDistinctCharsWindow(input, 14) } check(part1(readInput("Day06_sample")) == 10) println(part1(readInput("Day06_input"))) check(part2(readInput("Day06_sample")) == 29) println(part2(readInput("Day06_input"))) } private fun firstDistinctCharsWindow(input: List<String>, windowSize: Int): Int { val dataStream = input.joinToString(separator = "") dataStream.windowed(windowSize).forEach { candidate -> if (candidate.toSet().size == windowSize) { return@firstDistinctCharsWindow dataStream.indexOf(candidate) + candidate.length } } return -1 }
0
Kotlin
0
0
96d1567f38e324aca0cb692be3dae720728a383d
780
advent-of-code-2022
Apache License 2.0
advent-of-code2016/src/main/kotlin/day12/Advent12.kt
REDNBLACK
128,669,137
false
null
package day12 import day12.Operation.Type.* import parseInput import splitToLines /** --- Day 12: Leonardo's Monorail --- You finally reach the top floor of this building: a garden with a slanted glass ceiling. Looks like there are no more stars to be had. While sitting on a nearby bench amidst some tiger lilies, you manage to decrypt some of the files you extracted from the servers downstairs. According to these documents, Easter Bunny HQ isn't just this building - it's a collection of buildings in the nearby area. They're all connected by a local monorail, and there's another building not far from here! Unfortunately, being night, the monorail is currently not operating. You remotely connect to the monorail control systems and discover that the boot sequence expects a password. The password-checking logic (your puzzle input) is easy to extract, but the code it uses is strange: it's assembunny code designed for the new computer you just assembled. You'll have to execute the code and get the password. The assembunny code you've extracted operates on four registers (a, b, c, and d) that start at 0 and can hold any integer. However, it seems to make use of only a few instructions: cpy x y copies x (either an integer or the value of a register) into register y. inc x increases the value of register x by one. dec x decreases the value of register x by one. jnz x y jumps to an instruction y away (positive means forward; negative means backward), but only if x is not zero. The jnz instruction moves relative to itself: an offset of -1 would continue at the previous instruction, while an offset of 2 would skip over the next instruction. For example: cpy 41 a inc a inc a dec a jnz a 2 dec a The above code would set register a to 41, increase its value by 2, decrease its value by 1, and then skip the last dec a (because a is not zero, so the jnz a 2 skips it), leaving register a at 42. When you move past the last instruction, the program halts. After executing the assembunny code in your puzzle input, what value is left in register a? --- Part Two --- As you head down the fire escape to the monorail, you notice it didn't start; register c needs to be initialized to the position of the ignition key. If you instead initialize register c to be 1, what value is now left in register a? */ fun main(args: Array<String>) { val test = """cpy 41 a |inc a |inc a |dec a |jnz a 2 |dec a""".trimMargin() val input = parseInput("day12-input.txt") println(executeOperations(test, mapOf("a" to 0)) == mapOf("a" to 42)) println(executeOperations(input, mapOf("a" to 0, "b" to 0, "c" to 0, "d" to 0))) println(executeOperations(input, mapOf("a" to 0, "b" to 0, "c" to 1, "d" to 0))) } data class Operation(val type: Operation.Type, val args: List<String>) { enum class Type { CPY, INC, DEC, JNZ, TGL } } fun executeOperations(input: String, initial: Map<String, Int>): Map<String, Int> { val operations = parseOperations(input) val registers = initial.values.toIntArray() var index = 0 fun safeIndex(data: String) = when (data[0]) { 'a' -> 0 'b' -> 1 'c' -> 2 'd' -> 3 else -> null } fun safeValue(data: String) = when (data[0]) { 'a' -> registers[0] 'b' -> registers[1] 'c' -> registers[2] 'd' -> registers[3] else -> data.toInt() } while (index < operations.size) { val (type, arg) = operations[index] when (type) { CPY -> safeIndex(arg[1])?.let { registers[it] = safeValue(arg[0]) } INC -> safeIndex(arg[0])?.let { registers[it] += 1 } DEC -> safeIndex(arg[0])?.let { registers[it] -= 1 } JNZ -> if (safeValue(arg[0]) != 0) index += safeValue(arg[1]) - 1 TGL -> { val changeIndex = index + safeValue(arg[0]) if (changeIndex < operations.size) { val changeOperation = operations[changeIndex] val newType = when (changeOperation.type) { CPY -> JNZ JNZ -> CPY TGL -> INC INC -> DEC DEC -> INC } operations[changeIndex] = changeOperation.copy(type = newType) } } } index++ } return initial.keys.toTypedArray().zip(registers.toTypedArray()).toMap() } private fun parseOperations(input: String) = input.splitToLines() .map { val args = it.split(" ") val type = Operation.Type.valueOf(args[0].toUpperCase()) Operation(type, args.drop(1).take(2)) } .toMutableList()
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
4,846
courses
MIT License
src/day11/Code.kt
fcolasuonno
225,219,560
false
null
package day11 import IntCode import IntCodeComputer import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } fun parse(input: List<String>) = input.map { it.split(",").map { it.toLong() } }.requireNoNulls().single() enum class Direction(val dx: Int, val dy: Int) { U(0, -1) { override fun turn(nextDir: Long): Direction = if (nextDir == 0L) L else R }, D(0, 1) { override fun turn(nextDir: Long): Direction = if (nextDir == 0L) R else L }, L(-1, 0) { override fun turn(nextDir: Long): Direction = if (nextDir == 0L) D else U }, R(1, 0) { override fun turn(nextDir: Long): Direction = if (nextDir == 0L) U else D }; abstract fun turn(nextDir: Long): Direction } fun part1(input: List<Long>): Any? { val grid = mutableMapOf<Pair<Int, Int>, Int>().withDefault { 0 } val output = mutableListOf<Long>() val seq = generateSequence((0 to 0) to Direction.U) { (currentPos, currentDir) -> val nextCol = output.removeAt(0) val nextDir = output.removeAt(0) grid[currentPos] = nextCol.toInt() val newDir = currentDir.turn(nextDir) currentPos.copy(currentPos.first + newDir.dx, currentPos.second + newDir.dy) to newDir } val col = seq.map { grid.getValue(it.first) }.iterator() IntCodeComputer(input, IntCode.Input { col.next().toLong() }, IntCode.Output { a -> output.add(a) }).run() return grid.size } fun part2(input: List<Long>): Any? { val grid = mutableMapOf<Pair<Int, Int>, Int>().withDefault { 0 } grid[0 to 0] = 1 val output = mutableListOf<Long>() val seq = generateSequence((0 to 0) to Direction.U) { (currentPos, currentDir) -> val nextCol = output.removeAt(0) val nextDir = output.removeAt(0) grid[currentPos] = nextCol.toInt() val newDir = currentDir.turn(nextDir) currentPos.copy(currentPos.first + newDir.dx, currentPos.second + newDir.dy) to newDir } val col = seq.map { grid.getValue(it.first) }.iterator() IntCodeComputer(input, IntCode.Input { col.next().toLong() }, IntCode.Output { a -> output.add(a) }).run() val xRange = grid.keys.map { it.first }.let { it.min()!!..it.max()!! } return grid.keys.map { it.second }.let { it.min()!!..it.max()!! }.joinToString("\n", prefix = "\n") { y -> xRange.joinToString("") { x -> if (grid.getValue(x to y) == 0) " " else "##" } } }
0
Kotlin
0
0
d1a5bfbbc85716d0a331792b59cdd75389cf379f
2,706
AOC2019
MIT License
src/Day10.kt
D000L
575,350,411
false
{"Kotlin": 23716}
fun main() { fun getSignals(input: List<String>): List<Int> { val signals = mutableListOf(0) var signal = 1 input.forEach { when { it.startsWith("noop") -> { signals.add(signal) } it.startsWith("addx") -> { val va = it.split(" ")[1].toInt() signals.add(signal) signals.add(signal) signal += va } } } return signals } fun part1(input: List<String>): Int { val signals = getSignals(input) var index = 20 var result = 0 while (signals.getOrNull(index) != null) { result += index * signals[index] index += 40 } return result } fun part2(input: List<String>): Int { val signals = getSignals(input) signals.drop(1).mapIndexed { index, value -> val index = index % 40 if (value - 1 <= index && index <= value + 1) "#" else "." }.chunked(40).forEach { println(it.joinToString("")) } return 0 } val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b733a4f16ebc7b71af5b08b947ae46afb62df05e
1,274
adventOfCode
Apache License 2.0
ceria/03/src/main/kotlin/Solution.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File; fun main(args : Array<String>) { val input = File(args.first()).readLines() println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input: List<String>) :Long { val threshold = input.size / 2 var zerosMap = mutableMapOf<Int, Int>() var epsilon = "" var gamma = "" for (diagnostic in input) { for (c in diagnostic.indices) { if (diagnostic.get(c).equals('0')) { val count = zerosMap.get(c)?.let{ zerosMap.get(c) } ?: 0 zerosMap.put(c, count + 1) } } } for (c in input.get(0).indices) { val count = zerosMap.get(c)?.let{ zerosMap.get(c) } ?: 0 if (count > threshold) { gamma += '0' epsilon += '1' } else { gamma += '1' epsilon += '0' } } return gamma.toLong(2) * epsilon.toLong(2) } private fun solution2(input: List<String>) :Long { return filter(input, 0, false).get(0).toLong(2) * filter(input, 0, true).get(0).toLong(2) } private fun filter(input: List<String>, pos: Int, isCo2Filter: Boolean): List<String> { var filterVal = '1' var count = 0 for (diagnostic in input) { if (diagnostic.get(pos).equals('0')) { count++ } } if (count > input.size / 2) { filterVal = '0' } if (isCo2Filter) { if (filterVal.equals('1')){ filterVal = '0' } else { filterVal = '1' } } val filtered = input.filter { it.get(pos) == filterVal } if (filtered.size > 1) { return filter(filtered, pos + 1, isCo2Filter) } return filtered }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
1,804
advent-of-code-2021
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/BraceExpansion2.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue /** * 1096. Brace Expansion II * @see <a href="https://leetcode.com/problems/brace-expansion-ii/">Source</a> */ fun interface BraceExpansion2 { fun braceExpansion2(expression: String): List<String> } class BraceExpansion2DFS : BraceExpansion2 { override fun braceExpansion2(expression: String): List<String> { val queue: Queue<String> = LinkedList() queue.offer(expression) val set: MutableSet<String> = HashSet() while (queue.isNotEmpty()) { val str: String = queue.poll() if (str.indexOf('{') == -1) { set.add(str) continue } var i = 0 var l = 0 while (str[i] != '}') { if (str[i] == '{') l = i i++ } val r: Int = i val before = str.substring(0, l) val after = str.substring(r + 1) val strs = str.substring(l + 1, r).split(",".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray() val sb = StringBuilder() for (ss in strs) { sb.setLength(0) queue.offer(sb.append(before).append(ss).append(after).toString()) } } val ans: List<String> = ArrayList(set) return ans.sorted() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,029
kotlab
Apache License 2.0
src/main/kotlin/CalculateAperture.kt
guilhermealbm
568,980,166
false
{"Kotlin": 4088}
import java.lang.NumberFormatException import kotlin.math.abs val distances = listOf(1.2, 1.8, 2.5, 3.5, 5.0, 7.0) val apertures = listOf(1.2, 1.4, 2, 2.8, 4, 5.6, 8, 11, 16, 22, 32, 45) fun calculateAperture(iso_: String?, distance_: String?) : String { val iso = convertIso(iso_) val distance = convertDistance(distance_) distance?.let { val distanceIndex = distances.reversed().indexOf(it) val isoIndex = iso.index return "Set your aperture to ${apertures[distanceIndex + isoIndex]}" } ?: run { return "Unable to convert distance." } } fun convertDistance(distance_: String?) : Double? = try { distance_?.toDouble()?.let { distances.closestValue(it) } ?: run { null } } catch (exception: NumberFormatException) { null } private fun List<Double>.closestValue(value: Double) = minByOrNull { abs(value - it) } fun convertIso(iso: String?) : ISO = when(iso?.trim()) { "25" -> ISO.I25 "50" -> ISO.I50 "100" -> ISO.I100 "200" -> ISO.I200 "400" -> ISO.I400 "800" -> ISO.I800 "1000" -> ISO.I1000 else -> ISO.I100 } enum class ISO(val index: Int) { I25(0), I50(1), I100(2), I200(3), I400(4), I800(5), I1000(6) }
0
Kotlin
0
0
74f049d5ddb05d9ee1eb5b2e4399187f08c2a468
1,332
ManualFlashSettingsCalculator
MIT License
src/primitives/WeightDiagram.kt
sxhya
31,016,248
false
null
class WeightDiagram(val brs: BasedRootSystem, i: Int) { val myWeights: Set<Vector> = brs.weightOrbit(Vector(brs.myFundamentalWeights.myCoo[i])) val myEdges: MutableMap<Pair<Vector, Vector>, Int> = HashMap() val myWeightsNumbers: MutableMap<Vector, Int> = HashMap() val myWeightsOrdered: MutableList<Vector> = ArrayList() init { //Somehow we should also process zero weights for (source in myWeights) for (target in myWeights) { val d = Vector.minus(source, target) for (j in 0 until brs.rank()) if (d == Vector(brs.myBasis.myCoo[j])) myEdges[Pair(source, target)] = j } var counter = 0; val edgesCopy = HashMap(myEdges).map { it.key }.toMutableSet() val noIncoming = myWeights.minus(edgesCopy.map { it.second }).toMutableSet() while (noIncoming.isNotEmpty()) { val n = noIncoming.first() noIncoming.remove(n) myWeightsNumbers[n] = counter counter++ myWeightsOrdered.add(n) val edgesToRemove = HashSet<Pair<Vector, Vector>>() for (e in edgesCopy) if (e.first == n) edgesToRemove.add(e) edgesCopy.removeAll(edgesToRemove) for (m in edgesToRemove.map { it.second }) if (edgesCopy.none { it.second == m }) noIncoming.add(m) } if (!edgesCopy.isEmpty()) throw IllegalArgumentException() } enum class ComparisonResult{Incomparable, Less, Greater, Equal} fun compare(a: Vector, b: Vector): ComparisonResult { if (!myWeights.contains(a) || !myWeights.contains(b)) throw IllegalArgumentException() if (a == b) return ComparisonResult.Equal val d = Vector.minus(b, a) val isLess = brs.simpleRootCoefficients(d).map { it >= 0 }.fold(true) { f1, f2 -> f1 && f2} // a_i <= b_i val isGreater = brs.simpleRootCoefficients(d).map { it <= 0 }.fold(true) { f1, f2 -> f1 && f2} // b_i <= a_i if (isLess) return ComparisonResult.Less // b > a if (isGreater) return ComparisonResult.Greater // a > b return ComparisonResult.Incomparable } fun leq(a: Vector, b: Vector): Boolean = when (compare(a, b)) { ComparisonResult.Less, ComparisonResult.Equal -> true else -> false } fun sup(a: Vector, b: Vector): Vector { if (!myWeights.contains(a) || !myWeights.contains(b)) throw IllegalArgumentException() val upperBound = HashSet<Vector>() for (v in myWeights) { if (leq(a, v) && leq(b, v)) upperBound.add(v) } if (upperBound.isEmpty()) throw IllegalStateException() var flag: Boolean do { flag = false val badBounds = HashSet<Vector>() for (u in upperBound) for (v in upperBound) if (u != v && compare(u, v) == ComparisonResult.Less) badBounds.add(v) if (badBounds.isNotEmpty()) flag = true upperBound.removeAll(badBounds) } while (flag) if (upperBound.size != 1) throw IllegalStateException() // currently does not work for representations with zero roots return upperBound.first() } fun print() { for (w in myWeightsOrdered) { val targets = myEdges.filter { it.key.first == w } for (e in targets) { System.out.print(""+myWeightsNumbers[w]+"->"+myWeightsNumbers[e.key.second]+" {"+e.value+"} ") } System.out.println() } } fun printSpringy() { System.out.print("graph.addNodes(") myWeightsOrdered.mapIndexed { index, _ -> System.out.print("'w$index'") if (index < myWeightsOrdered.size -1) System.out.print(", ")} System.out.println(")") System.out.print("graph.addEdges(") myEdges.toList().mapIndexed{ index, it -> System.out.print("['w"+myWeightsNumbers[it.first.first]+"', 'w"+myWeightsNumbers[it.first.second]+"', {label: '"+it.second+"'}]") if (index < myEdges.size -1) System.out.print(", ")} System.out.println(")") } fun h(lambda: Vector, mu: Vector, depth: Int = 100): Int { if (depth == 0) throw IllegalStateException() if (lambda == mu) return 0 if (compare(lambda, mu) != ComparisonResult.Incomparable) { return brs.rootHeight(Vector.minus(lambda, mu)) } val nu = sup(lambda, mu) return h(lambda, nu, depth-1) + h(nu, mu, depth-1) } private fun phantomProcedure(weight: Vector, root: Vector, fundamentals: List<Vector>, roots: Set<Vector>): Vector { if (!myWeights.contains(weight) || !roots.contains(root)) throw IllegalArgumentException() for (i in 0 until brs.myBasis.height()) { if (root == fundamentals[i]) { val sum = Vector.add(weight, fundamentals[i]) return if (myWeights.contains(sum)) sum else weight } } for (i in 0 until brs.myBasis.height()) { val diff = Vector.minus(root, fundamentals[i]) if (roots.contains(diff)) return phantomProcedure(phantomProcedure(weight, fundamentals[i], fundamentals, roots), diff, fundamentals, roots) } throw IllegalArgumentException() } fun highestWeight(): Vector { val highestWeight = myWeightsOrdered[0] for (i in 1 until myWeightsOrdered.size) if (compare(highestWeight, myWeightsOrdered[i]) != ComparisonResult.Greater) throw IllegalStateException() return highestWeight } fun phantom(weight: Vector, root: Vector): Vector { if (brs.myPositiveRoots.contains(root)) return phantomProcedure(weight, root, brs.myFundamentalRoots, brs.myPositiveRoots) //if (brs.myNegativeRoots.contains(root)) return phantomProcedure(weight, root, brs.myMinusFundamentalRoots, brs.myNegativeRoots) throw IllegalArgumentException() } fun c(lambda: Vector, alpha: Vector): Int { if (!myWeights.contains(lambda) || !brs.myRootSet.contains(alpha) || !myWeights.contains(Vector.add(lambda, alpha))) throw IllegalArgumentException() if (brs.myNegativeRoots.contains(alpha)) return c(Vector.add(lambda, alpha), Vector.minus(alpha)) val j = h(phantom(lambda, alpha), lambda) - 1 return if (j % 2 == 0) 1 else -1 } fun x(alpha: Vector, xi: Double): Matrix { val result = Array(myWeights.size) { i -> DoubleArray(myWeights.size) { j -> if (i==j) 1.0 else 0.0 } } for (w in myWeights) { val wa = Vector.add(w, alpha) val wi = myWeightsNumbers[w]!! if (myWeights.contains(wa)) { val wai = myWeightsNumbers[wa]!! result[wai][wi] = xi*c(w, alpha) } } return Matrix(result) } }
0
Kotlin
0
0
ac5aebc8af88ed1ff7c9056e54cd7e0bb568f47a
7,057
roots
Apache License 2.0
src/Day02.kt
Sasikuttan2163
647,296,570
false
null
fun main() { val input = readInput("Day02") val part1 = input.fold(0) { sum, l -> sum + when ((l[2] - 'X') - (l[0] - 'A')) { 0 -> 3 1, -2 -> 6 else -> 0 } + (l[2] - 'W') } val part2 = input.fold(0) { sum, l -> val res = l[2] - 'X' sum + res * 3 + when (res) { 0 -> if (l[0] != 'A') l[0] - 'A' else 3 1 -> l[0] - 'A' + 1 2 -> if (l[0] != 'C') l[0] - 'A' + 2 else 1 else -> 0 } } part1.println() part2.println() }
0
Kotlin
0
0
fb2ade48707c2df7b0ace27250d5ee240b01a4d6
564
AoC-2022-Solutions-In-Kotlin
MIT License
kotlin/src/katas/kotlin/leetcode/wildcard_matching/v3/WildcardMatching3.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.wildcard_matching.v3 import datsok.* import org.junit.* class WildcardMatching3 { @Test fun `some examples`() { match("", "") shouldEqual true match("", "a") shouldEqual false match("a", "") shouldEqual false match("a", "a") shouldEqual true match("a", "b") shouldEqual false match("a", "aa") shouldEqual false match("aa", "a") shouldEqual false match("", "?") shouldEqual false match("a", "?") shouldEqual true match("ab", "?") shouldEqual false match("ab", "??") shouldEqual true match("ab", "???") shouldEqual false match("abc", "??") shouldEqual false match("", "*") shouldEqual true match("abc", "*") shouldEqual true match("abc", "a*") shouldEqual true match("abc", "*c") shouldEqual true match("abc", "a*c") shouldEqual true match("abc", "*a") shouldEqual false match("abc", "b*") shouldEqual false match("abc", "****") shouldEqual true } } private typealias Matcher = (input: String) -> Sequence<String> private fun char(c: Char): Matcher = { input -> if (input.isEmpty() || input.first() != c) emptySequence() else sequenceOf(input.drop(1)) } private val questionMark: Matcher = { input -> if (input.isEmpty()) emptySequence() else sequenceOf(input.drop(1)) } private val star: Matcher = { input -> (0..input.length).asSequence().map { input.substring(it, input.length) } } private fun match(s: String, pattern: String): Boolean { val matchers = pattern.map { when (it) { '*' -> star '?' -> questionMark else -> char(it) } } return matchers .fold(sequenceOf(s)) { inputs, matcher -> inputs.flatMap { matcher(it) } } .any { input -> input.isEmpty() } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,878
katas
The Unlicense
src/main/java/challenges/educative_grokking_coding_interview/two_heaps/_3/SlidingWindow.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.two_heaps._3 import challenges.util.PrintHyphens import java.util.* /** Given an integer array, nums, and an integer, k, there is a sliding window of size k, which is moving from the very left to the very right of the array. We can only see the k numbers in the window. Each time the sliding window moves right by one position. Given this scenario, return the median of the each window. Answers within (10 power -5) of the actual value will be accepted. https://www.educative.io/courses/grokking-coding-interview-patterns-java/g2REMP4N4K9 */ object SlidingWindow { private fun medianSlidingWindow(nums: IntArray, k: Int): DoubleArray { // To store the medians val medians: MutableList<Double> = ArrayList() // To keep track of the numbers that need to be removed from the heaps val outgoingNum = HashMap<Int, Int>() // Max heap val smallList = PriorityQueue(Collections.reverseOrder<Int>()) // Min heap val largeList = PriorityQueue<Int>() // Initialize the max heap for (i in 0 until k) smallList.offer(nums[i]) // Transfer the top 50% of the numbers from max heap to min heap for (i in 0 until k / 2) largeList.offer(smallList.poll()) var i = k while (true) { // If the window size is odd if (k and 1 == 1) medians.add(smallList.peek().toDouble()) else medians.add( (smallList.peek().toLong() + largeList.peek() .toLong()).toDouble() * 0.5 ) // Break the loop if all elements have been processed if (i >= nums.size) break // Outgoing number val outNum = nums[i - k] // Incoming number val inNum = nums[i] i++ // Variable to keep the heaps balanced var balance = 0 // If the outgoing number is from max heap if (outNum <= smallList.peek()) balance -= 1 else balance += 1 // Add/Update the outgoing number in the hash map if (outgoingNum.containsKey(outNum)) outgoingNum[outNum] = outgoingNum[outNum]!! + 1 else outgoingNum[outNum] = 1 // If the incoming number is less than the top of the max heap, add it in that heap // Otherwise, add it in the min heap if (smallList.size > 0 && inNum <= smallList.peek()) { balance += 1 smallList.offer(inNum) } else { balance -= 1 largeList.offer(inNum) } // Re-balance the heaps if (balance < 0) smallList.offer(largeList.poll()) else if (balance > 0) largeList.offer(smallList.poll()) // Remove invalid numbers present in the hash map from top of max heap while (smallList.size > 0 && outgoingNum.containsKey(smallList.peek()) && outgoingNum[smallList.peek()]!! > 0) outgoingNum[smallList.peek()] = outgoingNum[smallList.poll()]!! - 1 // Remove invalid numbers present in the hash map from top of min heap while (largeList.size > 0 && outgoingNum.containsKey(largeList.peek()) && outgoingNum[largeList.peek()]!! > 0) outgoingNum[largeList.peek()] = outgoingNum[largeList.poll()]!! - 1 } return medians.stream().mapToDouble { obj: Double -> obj }.toArray() } @JvmStatic fun main(args: Array<String>) { val arr = arrayOf( intArrayOf(3, 1, 2, -1, 0, 5, 8), intArrayOf(1, 2), intArrayOf(4, 7, 2, 21), intArrayOf(22, 23, 24, 56, 76, 43, 121, 1, 2, 0, 0, 2, 3, 5), intArrayOf(1, 1, 1, 1, 1) ) val k = intArrayOf(4, 1, 2, 5, 2) for (i in k.indices) { print(i + 1) println(".\tInput array =" + arr[i].contentToString() + ", k = " + k[i]) val output = medianSlidingWindow(arr[i], k[i]) println("\tMedians =" + output.contentToString()) println(PrintHyphens.repeat("-", 100)) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
4,183
CodingChallenges
Apache License 2.0
src/main/kotlin/_0046_Permutations.kt
ryandyoon
664,493,186
false
null
// https://leetcode.com/problems/permutations fun permute(nums: IntArray): List<List<Int>> { return mutableListOf<List<Int>>().also { buildPermutations( nums = nums, usedNums = BooleanArray(nums.size), permutation = mutableListOf(), permutations = it ) } } private fun buildPermutations( nums: IntArray, usedNums: BooleanArray, permutation: MutableList<Int>, permutations: MutableList<List<Int>> ) { if (permutation.size == nums.size) { permutations.add(permutation.toList()) return } for ((index, num) in nums.withIndex()) { if (usedNums[index]) continue usedNums[index] = true permutation.add(num) buildPermutations(nums = nums, usedNums = usedNums, permutation = permutation, permutations = permutations) permutation.remove(num) usedNums[index] = false } }
0
Kotlin
0
0
7f75078ddeb22983b2521d8ac80f5973f58fd123
929
leetcode-kotlin
MIT License
src/main/kotlin/util/Point2d.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package util import kotlin.math.abs data class Point2d(val x: Int, val y: Int) { fun distanceTo(other: Point2d): Int { return abs(other.x - x) + abs(other.y - y) } operator fun plus(other: Point2d): Point2d { return Point2d(x + other.x, y + other.y) } operator fun minus(other: Point2d): Point2d { return Point2d(x - other.x, y - other.y) } fun neighbors() = listOf( copy(x = x + 1), copy(x = x - 1), copy(y = y + 1), copy(y = y - 1), ) fun allNeighbors() = listOf( copy(x = x - 1, y = y - 1), copy(y = y - 1), copy(x = x + 1, y = y - 1), copy(x = x - 1), copy(x = x + 1), copy(x = x - 1, y = y + 1), copy(y = y + 1), copy(x = x + 1, y = y + 1), ) fun isWithin(inputList: List<String>): Boolean { return y in inputList.indices && x in inputList.first().indices } fun isWithin(array:Array2d<Char>): Boolean { return y in 0 until array.height && x in 0 until array.width } fun isWithin(array:CharArray2d): Boolean { return y in 0 until array.height && x in 0 until array.width } fun isWithin(upperLeft: Point2d, lowerRight: Point2d): Boolean { return x >= upperLeft.x && x <= lowerRight.x && y >= upperLeft.y && y <= lowerRight.y } fun directionTo(other: Point2d): Direction? { return when (other - this) { Direction.East.delta -> Direction.East Direction.West.delta -> Direction.West Direction.North.delta -> Direction.North Direction.South.delta -> Direction.South else -> null } } val westernNeighbor: Point2d by lazy { this.copy(x = this.x - 1) } val easternNeighbor: Point2d by lazy { this.copy(x = this.x + 1) } val northernNeighbor: Point2d by lazy { this.copy(y = this.y - 1) } val southernNeighbor: Point2d by lazy { this.copy(y = this.y + 1) } enum class Direction(val delta: Point2d) { North(Point2d(0,-1)), South(Point2d(0,1)), East(Point2d(1, 0)), West(Point2d(-1, 0)) } } data class Point2dl(val x: Long, val y: Long) { fun distanceTo(other: Point2dl): Long { return abs(other.x - x) + abs(other.y - y) } operator fun plus(other: Point2dl): Point2dl { return Point2dl(x + other.x, y + other.y) } operator fun minus(other: Point2dl): Point2dl { return Point2dl(x - other.x, y - other.y) } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
2,530
Advent-Of-Code
Creative Commons Zero v1.0 Universal
codechef/snackdown2021/preelim/slippers.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codechef.snackdown2021.preelim private const val MAX_S = 200_000 @Suppress("UNUSED_PARAMETER") // Kotlin 1.2 fun main(args: Array<String>) { readLn() val a = readInts() val fenwickTree = FenwickTree(MAX_S + 1) var ans = 1.toModular() for (x in a) { val added = 1 + fenwickTree.sum(x).toModular() fenwickTree[x] = (fenwickTree[x].toInt() + added).x.toLong() ans += added } println(ans) } private fun Int.toModular() = Modular(this)//toDouble() private fun Long.toModular() = Modular(this)//toDouble() private class Modular { companion object { const val M = 998244353 } val x: Int @Suppress("ConvertSecondaryConstructorToPrimary") constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } } constructor(value: Long) { x = (value % M).toInt().let { if (it < 0) it + M else it } } operator fun plus(that: Modular) = Modular((x + that.x) % M) operator fun minus(that: Modular) = Modular((x + M - that.x) % M) operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular() private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt()) operator fun div(that: Modular) = times(that.modInverse()) override fun toString() = x.toString() } private operator fun Int.plus(that: Modular) = Modular(this) + that private operator fun Int.minus(that: Modular) = Modular(this) - that private operator fun Int.times(that: Modular) = Modular(this) * that private operator fun Int.div(that: Modular) = Modular(this) / that class FenwickTree(n: Int) { var t: LongArray fun add(i: Int, value: Long) { var j = i while (j < t.size) { t[j] += value j += j + 1 and -(j + 1) } } fun sum(i: Int): Long { var j = i var res: Long = 0 j-- while (j >= 0) { res += t[j] j -= j + 1 and -(j + 1) } return res } fun sum(start: Int, end: Int): Long { return sum(end) - sum(start) } operator fun get(i: Int): Long { return sum(i, i + 1) } operator fun set(i: Int, value: Long) { add(i, value - get(i)) } init { t = LongArray(n) } } private fun readLn() = readLine()!!.trim() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,205
competitions
The Unlicense
src/day06/day06.kt
Klaus-Anderson
572,740,347
false
{"Kotlin": 13405}
package day06 import readInput fun main() { fun part1(input: List<String>): Int { input.first().let { inputString -> inputString.forEachIndexed { index, char -> val list = List(4) { inputString[index + it] } if (list.all { list.indexOf(it) == list.lastIndexOf(it) }) return index + 4 } } return 0 } fun part2(input: List<String>): Int { input.first().let { inputString -> inputString.forEachIndexed { index, char -> val list = List(14) { inputString[index + it] } if (list.all { list.indexOf(it) == list.lastIndexOf(it) }) return index + 14 } } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("day06", "Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) // val input = readInput("day06", "day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
faddc2738011782841ec20475171909e9d4cee84
1,295
harry-advent-of-code-kotlin-template
Apache License 2.0
src/pl/shockah/aoc/y2018/Day12.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2018 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import pl.shockah.aoc.parse2 import java.util.* import java.util.regex.Pattern class Day12: AdventTask<Day12.Input, Long, Long>(2018, 12) { private val replacementInputPattern: Pattern = Pattern.compile("([.#]+) => ([.#])") data class Input( val state: Set<Int>, val combinations: List<Pair<BooleanArray, Boolean>> ) override fun parseInput(rawInput: String): Input { val lines = LinkedList(rawInput.lines()) val rawInitialState = lines.removeFirst().replace("initial state: ", "") val initialState = rawInitialState.mapIndexed { index: Int, c: Char -> index to (c == '#') }.filter { it.second }.map { it.first }.toSet() lines.removeFirst() val replacements = lines.map { val (rawCombination, rawCombinationOutput) = replacementInputPattern.parse2<String, Char>(it) return@map booleanArrayOf(*rawCombination.map { it == '#' }.toBooleanArray()) to (rawCombinationOutput == '#') } return Input(initialState, replacements) } private fun task(input: Input, iterations: Long): Long { fun advance(input: Set<Int>, combinations: List<Pair<BooleanArray, Boolean>>): Set<Int> { val minX = input.minOrNull()!! val maxX = input.maxOrNull()!! val maxCombinationLength = combinations.maxOf { it.first.size } val maxOffset = (maxCombinationLength - 1) / 2 val output = mutableSetOf<Int>() positions@ for (x in (minX - maxOffset)..(maxX + maxOffset)) { combinations@ for ((combination, combinationOutput) in combinations) { val combinationLength = combination.size val combinationOffset = (combinationLength - 1) / 2 for (i in 0 until combinationLength) { if ((x - combinationOffset + i) in input != combination[i]) continue@combinations } if (combinationOutput) output += x continue@positions } } return output } fun getStringState(input: Set<Int>, withMinMax: Boolean): String { val minX = input.minOrNull()!! val maxX = input.maxOrNull()!! val joined = (minX..maxX).map { if (it in input) '#' else '.' }.joinToString("") return if (withMinMax) "[$minX] $joined [$maxX]" else joined } var current = input.state var lastStringState: String? = null println("> #0: ${getStringState(current, true)}") var currentMod = 1L for (i in 1..iterations) { val newState = advance(current, input.combinations) val newStringState = getStringState(newState, false) val areEqual = lastStringState != null && lastStringState == newStringState val sumDifference = newState.sum() - current.sum() if (i % currentMod == 0L || areEqual) { println("> #$i: ${getStringState(newState, true)}") if (i >= currentMod * 100) currentMod *= 10L } current = newState lastStringState = newStringState if (areEqual) { println("> Finishing early") println("> Current sum: ${current.sum()}") println("> Iterations left: ${iterations - i}, ${if (sumDifference > 0) "+" else ""}$sumDifference each") return current.sum() + (iterations - i) * sumDifference } } return current.sum().toLong() } override fun part1(input: Input): Long { return task(input, 20L) } override fun part2(input: Input): Long { return task(input, 50_000_000_000L) } class Tests { private val task = Day12() private val rawInput = """ initial state: #..#.#..##......###...### ...## => # ..#.. => # .#... => # .#.#. => # .#.## => # .##.. => # .#### => # #.#.# => # #.### => # ##.#. => # ##.## => # ###.. => # ###.# => # ####. => # """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals(325, task.part1(input)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
3,812
Advent-of-Code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindOriginalArray.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.TreeMap /** * 2007. Find Original Array From Doubled Array * @see <a href="https://leetcode.com/problems/find-original-array-from-doubled-array/">Source</a> */ fun interface FindOriginalArray { fun findOriginalArray(changed: IntArray): IntArray } class FindOriginalArrayMatch : FindOriginalArray { override fun findOriginalArray(changed: IntArray): IntArray { val n: Int = changed.size var i = 0 if (n % 2 == 1) return IntArray(0) val res = IntArray(n / 2) val count: MutableMap<Int, Int> = TreeMap() for (a in changed) { count[a] = count.getOrDefault(a, 0) + 1 } for (x in count.keys) { if (count.getOrDefault(x, 0) > count.getOrDefault(x + x, 0)) { return IntArray(0) } for (j in 0 until count.getOrDefault(x, 0)) { res[i++] = x count[x + x] = count.getOrDefault(x + x, 0) - 1 } } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,662
kotlab
Apache License 2.0
2022/main/day_18/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_18_2022 import java.io.File fun Triple<Int, Int, Int>.adjacent(): List<Triple<Int, Int, Int>> { val (a,b,c) = this val res = mutableListOf<Triple<Int, Int, Int>>() res.add(Triple(a+1,b,c)) res.add(Triple(a-1,b,c)) res.add(Triple(a,b+1,c)) res.add(Triple(a,b-1,c)) res.add(Triple(a,b,c+1)) res.add(Triple(a,b,c-1)) return res } fun part1(input: List<String>) { val map = input.map { val (x, y, z) = it.split(",") Triple(x.toInt(), y.toInt(), z.toInt()) } var size = 0 val scanned = mutableSetOf<Triple<Int, Int, Int>>() for (cube in map) { size += 6 for (adj in cube.adjacent()) { if (adj in scanned) { size -= 2 } } scanned.add(cube) } print("The surface area is $size") } fun part2(input: List<String>) { val map = input.map { val (x, y, z) = it.split(",") Triple(x.toInt(), y.toInt(), z.toInt()) } var size = 0 val scanned = mutableSetOf<Triple<Int, Int, Int>>() for (cube in map) { size += 6 for (adj in cube.adjacent()) { if (adj in scanned) { size -= 2 } } scanned.add(cube) } val allPossible = mutableSetOf<Triple<Int,Int,Int>>() for (i in 0 until 20) { for (j in 0 until 20) { for (k in 0 until 20) { allPossible.add(Triple(i,j,k)) } } } val empty = (allPossible - scanned).toMutableSet() val queue = ArrayDeque(listOf(Triple(0,0,0))) while(queue.isNotEmpty()) { val current = queue.removeFirst() if (current in empty) { empty.remove(current) queue.addAll(current.adjacent()) } } for (cube in empty) { size += 6 for (adj in cube.adjacent()) { if (adj in scanned) { size -= 2 } } scanned.add(cube) } print("The exterior surface area is $size") } fun main(){ val inputFile = File("2022/inputs/Day_18.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines()) print("\n----- Part 2 -----\n") part2(inputFile.readLines()) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
2,255
AdventofCode
MIT License
src/leetcodeProblem/leetcode/editor/en/MinimumRemoveToMakeValidParentheses.kt
faniabdullah
382,893,751
false
null
//Given a string s of '(' , ')' and lowercase English characters. // // Your task is to remove the minimum number of parentheses ( '(' or ')', in //any positions ) so that the resulting parentheses string is valid and return any //valid string. // // Formally, a parentheses string is valid if and only if: // // // It is the empty string, contains only lowercase characters, or // It can be written as AB (A concatenated with B), where A and B are valid //strings, or // It can be written as (A), where A is a valid string. // // // // Example 1: // // //Input: s = "lee(t(c)o)de)" //Output: "lee(t(c)o)de" //Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. // // // Example 2: // // //Input: s = "a)b(c)d" //Output: "ab(c)d" // // // Example 3: // // //Input: s = "))((" //Output: "" //Explanation: An empty string is also valid. // // // Example 4: // // //Input: s = "(a(b(c)d)" //Output: "a(b(c)d)" // // // // Constraints: // // // 1 <= s.length <= 10⁵ // s[i] is either'(' , ')', or lowercase English letter. // // Related Topics String Stack 👍 2786 👎 60 package leetcodeProblem.leetcode.editor.en import java.util.* import kotlin.text.StringBuilder class MinimumRemoveToMakeValidParentheses { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun minRemoveToMakeValid(s: String): String { val arr = s.toCharArray() val result = StringBuilder() val stack = Stack<Int>() for (i in s.indices) { val char = s[i] if (char == '(') { stack.push(i) } else if (char == ')') { if (stack.isNotEmpty()) stack.pop() else arr[i] = '~' } } while (stack.isNotEmpty()) { arr[stack.pop()] = '~' } arr.forEach { if (it != '~') result.append(it) } return result.toString() } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,238
dsa-kotlin
MIT License
src/Dec20.kt
karlstjarne
572,529,215
false
{"Kotlin": 45095}
import java.util.Collections.swap import kotlin.math.abs object Dec20 { fun a(): Long { val input = readInput("dec20") val nodes = mutableListOf<Node>() for (i in input.indices) { nodes.add(Node(i, input[i].toLong())) } val output = mixList(nodes, 1) return getTheSum(output, nodes) } fun b(): Long { val input = readInput("dec20") val decryptionKey = 811589153L val nodes = mutableListOf<Node>() for (i in input.indices) { nodes.add(Node(i, input[i].toLong() * decryptionKey)) } val output = mixList(nodes, 10) return getTheSum(output, nodes) } private fun mixList(nodes: MutableList<Node>, mixes: Int): MutableList<Node> { val output = nodes.toMutableList() println("initial: " + output.map { it.number }) for (j in 1..mixes) { for (i in nodes.indices) { // Get the node to move val node = output.find { it.id == i }!! // move it val currentIndex = output.indexOf(node) var newIndex = (currentIndex + node.number.mod(nodes.size - 1)).mod(nodes.size) output.remove(node) output.add(newIndex, node) // println("After (${node.number}): " + output.map { it.number }) } // println("After $j mixes: " + output.map { it.encryptedNumber }) } return output } private fun getTheSum(output: MutableList<Node>, nodes: MutableList<Node>): Long { val indexOfZero = output.indexOf(output.find { it.number == 0L }) var sum = 0L for (i in 1..3) { sum += output[(indexOfZero + i * 1000).mod(nodes.size)].number } return sum } private class Node(val id: Int = 0, val number: Long = 0) }
0
Kotlin
0
0
9220750bf71f39f693d129d170679f3be4328576
1,901
AoC_2022
Apache License 2.0
src/Day04.kt
anilkishore
573,688,256
false
{"Kotlin": 27023}
fun main() { fun part1(input: List<String>): Int { fun IntRange.fullyContains(other: IntRange): Boolean = this.contains(other.first) && this.contains(other.last) return input.count { val ranges = it.split(",").map { s -> val ss = s.split("-") IntRange(ss[0].toInt(), ss[1].toInt()) } (ranges[0].fullyContains(ranges[1]) or ranges[1].fullyContains(ranges[0])) } } fun part2(input: List<String>): Int { return input.count { val ranges = it.split(",").map { s -> val ss = s.split("-") IntRange(ss[0].toInt(), ss[1].toInt()) } ranges[0].intersect(ranges[1]).isNotEmpty() } } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9
884
AOC-2022
Apache License 2.0
2021/src/test/kotlin/Day03.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.test.Test import kotlin.test.assertEquals class Day03 { enum class RateType { GAMMA, EPSILON, OXYGEN, CO2 } @Test fun `run part 01`() { val report = Util.getInputAsListOfString("day03-input.txt") val powerConsumption = report .let { it.getPowerRating(RateType.GAMMA) * it.getPowerRating(RateType.EPSILON) } assertEquals(4103154, powerConsumption) } private fun List<String>.getPowerRating(type: RateType) = this .first() .mapIndexed { index, _ -> this.getCommonBit(index, type).toString() } .toInt() @Test fun `run part 02`() { val report = Util.getInputAsListOfString("day03-input.txt") val lifeSupport = report .let { it.getLifeSupportRating(RateType.OXYGEN) * it.getLifeSupportRating(RateType.CO2) } assertEquals(4245351, lifeSupport) } private fun List<String>.getLifeSupportRating(type: RateType): Int { var filtered = this.toList() this .first() .forEachIndexed { index, _ -> val bit = filtered.getCommonBit(index, type) filtered = filtered.filter { it[index] == bit } } return filtered.toInt() } private fun List<String>.getCommonBit(index: Int, type: RateType) = this .map { it[index].digitToInt() } .groupingBy { it } .eachCount() .entries .sortedBy { if (type == RateType.EPSILON || type == RateType.CO2) it.key else it.key.unaryMinus() } .maxByOrNull { if (type == RateType.GAMMA || type == RateType.OXYGEN) it.value else it.value.unaryMinus() } ?.key?.digitToChar() ?: throw IllegalStateException() private fun List<String>.toInt() = this .joinToString("") .toBigInteger(2) .toInt() }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
1,840
adventofcode
MIT License
year2015/src/main/kotlin/net/olegg/aoc/year2015/day18/Day18.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2015.day18 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.Companion.NEXT_8 import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.fit import net.olegg.aoc.year2015.DayOf2015 /** * See [Year 2015, Day 18](https://adventofcode.com/2015/day/18) */ object Day18 : DayOf2015(18) { private val SIZE = matrix.size private val FIELD = matrix .flatMapIndexed { y, row -> row.mapIndexedNotNull { x, char -> if (char == '#') Vector2D(x, y) else null } } .toSet() override fun first(): Any? { return (1..SIZE).fold(FIELD) { field, _ -> move(field) }.size } override fun second(): Any? { val corners = setOf( Vector2D(0, 0), Vector2D(0, SIZE - 1), Vector2D(SIZE - 1, 0), Vector2D(SIZE - 1, SIZE - 1), ) return (1..SIZE).fold(FIELD + corners) { field, _ -> move(field) + corners }.size } private fun move(field: Set<Vector2D>): Set<Vector2D> { val neighbors = field .flatMap { cell -> NEXT_8.map { cell + it.step } } .filter { matrix.fit(it) } .groupingBy { it } .eachCount() .toList() .partition { it.first in field } return (neighbors.first.filter { it.second in 2..3 } + neighbors.second.filter { it.second == 3 }) .map { it.first } .toSet() } } fun main() = SomeDay.mainify(Day18)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,387
adventofcode
MIT License
src/main/kotlin/aoc/year2021/Day06.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2021 import aoc.Puzzle /** * [Day 6 - Advent of Code 2021](https://adventofcode.com/2021/day/6) */ object Day06 : Puzzle<Long, Long> { override fun solvePartOne(input: String): Long = solve(input, 80) override fun solvePartTwo(input: String): Long = solve(input, 256) private fun solve(input: String, days: Int): Long { val map = input .lineSequence() .single() .split(",") .map { it.toInt() } .groupingBy { it } .eachCount() .mapValues { (_, count) -> count.toLong() } val finalMap = (0 until days).fold(map) { acc, _ -> buildMap { acc.forEach { (time, amount) -> if (time == 0) { add(6, amount) add(8, amount) } else { add(time - 1, amount) } } } } return finalMap.values.sum() } private fun MutableMap<Int, Long>.add(time: Int, amount: Long) { compute(time) { _, old -> (old ?: 0) + amount } } }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,160
advent-of-code
Apache License 2.0
day23/kotlin/corneil/src/main/kotlin/solution.kt
jensnerche
317,661,818
true
{"HTML": 2739009, "Java": 348790, "Kotlin": 271602, "TypeScript": 262310, "Python": 198318, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "C": 3201, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Tcl": 46}
package com.github.corneil.aoc2019.day23 import com.github.corneil.aoc2019.intcode.Program import com.github.corneil.aoc2019.intcode.ProgramState import com.github.corneil.aoc2019.intcode.readProgram import java.io.File data class Packet(val x: Long, val y: Long) class NetWorkController(val address: Long) { val inputQueue: MutableList<Long> = mutableListOf() val outputQueue: MutableList<Long> = mutableListOf() fun provideInput(): List<Long> { return if (inputQueue.isNotEmpty()) { val result = inputQueue.toList() inputQueue.clear() result } else { listOf(-1L) } } fun hasPacket() = outputQueue.size >= 3 fun readAddress() = outputQueue.removeAt(0) fun readPacket(): Packet { val x = outputQueue.removeAt(0) val y = outputQueue.removeAt(0) return Packet(x, y) } fun idle() = inputQueue.isEmpty() fun send(packet: Packet) { inputQueue.add(packet.x) inputQueue.add(packet.y) } } typealias Network = Map<Long, Pair<NetWorkController, ProgramState>> fun createComputers(code: List<Long>, addresses: IntRange): Network { return addresses.map { val netWorkController = NetWorkController(it.toLong()) val state = Program(code).createProgram(listOf(it.toLong())) Pair(netWorkController, state) }.associate { it.first.address to it } } fun runNetwork(network: Network, terminate: (Long, Packet) -> Boolean) { var nat: Packet? = null do { for (item in network.values) { val nic = item.first val programState = item.second programState.executeUntilInput(nic.provideInput()) nic.outputQueue.addAll(programState.extractOutput()) while (nic.hasPacket()) { val address = nic.readAddress() val packet = nic.readPacket() if (terminate(address, packet)) { return } if (address == 255L) { nat = packet println("NAT:SAVE:$packet") } else { val destination = network[address] ?: error("Cannot find NIC $address") destination.first.send(packet) println("Send:$address:$packet") } } } if (network.values.all { it.first.idle() }) { requireNotNull(nat) { "Expected NAT packet waiting when idle" } network[0]?.first?.send(nat) ?: error("Cannot find NIC:0") println("NAT:SEND:$nat") if (terminate(0, nat)) { return } } } while (network.values.all { !it.second.isHalted() }) } fun main() { val code = readProgram(File("input.txt")) val a1 = solution1(code) println("First Packet Y = $a1") require(a1 == 22877L) val a2 = solution2(code) println("NAT Y twice = $a2") require(a2 == 15210L) } fun solution2(code: List<Long>): Long { var lastNAT: Packet? = null val network = createComputers(code, 0..49) var answer = -1L runNetwork(network) { address, packet -> var terminate = false if (address == 0L) { if (lastNAT == null) { lastNAT = packet } else { if (packet.y == lastNAT?.y) { answer = packet.y terminate = true } lastNAT = packet } } terminate } return answer } fun solution1(code: List<Long>): Long { val network = createComputers(code, 0..49) var answer = -1L runNetwork(network) { address, packet -> var terminate = false if (address == 255L) { answer = packet.y terminate = true } terminate } return answer }
0
HTML
0
0
a84c00ddbeb7f9114291125e93871d54699da887
3,917
aoc-2019
MIT License
src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0701_0800.s0770_basic_calculator_iv // #Hard #String #Hash_Table #Math #Stack #Recursion // #2023_03_10_Time_222_ms_(100.00%)_Space_39.2_MB_(100.00%) import java.util.Collections class Solution { internal inner class Node { var mem: MutableMap<List<String>, Int> = HashMap() fun update(cur: List<String>, cnt: Int) { Collections.sort(cur) mem[cur] = mem.getOrDefault(cur, 0) + cnt } fun add(cur: Node): Node { val ans = Node() for (key1 in mem.keys) { ans.update(key1, mem[key1]!!) } for (key2 in cur.mem.keys) { ans.update(key2, cur.mem[key2]!!) } return ans } fun sub(cur: Node): Node { val ans = Node() for (key1 in mem.keys) { ans.update(key1, mem[key1]!!) } for (key2 in cur.mem.keys) { ans.update(key2, -cur.mem[key2]!!) } return ans } fun mul(cur: Node): Node { val ans = Node() for (key1 in mem.keys) { for (key2 in cur.mem.keys) { val next: MutableList<String> = ArrayList() next.addAll(key1) next.addAll(key2) ans.update(next, mem[key1]!! * cur.mem[key2]!!) } } return ans } fun evaluate(vars: Map<String?, Int>): Node { val ans = Node() for (cur in mem.keys) { var cnt = mem[cur]!! val free: MutableList<String> = ArrayList() for (tmp in cur) { if (vars.containsKey(tmp)) { cnt *= vars[tmp]!! } else { free.add(tmp) } } ans.update(free, cnt) } return ans } fun toList(): List<String> { val ans: MutableList<String> = ArrayList() val keys: List<List<String>> = ArrayList(mem.keys) Collections.sort( keys ) { a: List<String>, b: List<String> -> if (a.size != b.size) { return@sort b.size - a.size } for (i in a.indices) { if (a[i].compareTo(b[i]) != 0) { return@sort a[i].compareTo(b[i]) } } 0 } for (key in keys) { if (mem[key] == 0) { continue } var cur = "" + mem[key].toString() for (data in key) { cur += "*" cur += data } ans.add(cur) } return ans } } private fun make(cur: String): Node { val ans: Node = Node() val tmp: MutableList<String> = ArrayList() if (Character.isDigit(cur[0])) { ans.update(tmp, Integer.valueOf(cur)) } else { tmp.add(cur) ans.update(tmp, 1) } return ans } private fun getNext(expression: String, start: Int): Int { var end = start while (end < expression.length && Character.isLetterOrDigit(expression[end])) { end++ } return end - 1 } private fun getPriority(a: Char): Int { if (a == '+' || a == '-') { return 1 } else if (a == '*') { return 2 } return 0 } private fun helper(numS: ArrayDeque<Node>, ops: ArrayDeque<Char>): Node { val b = numS.removeLast() val a = numS.removeLast() val op = ops.removeLast() if (op == '*') { return a.mul(b) } else if (op == '+') { return a.add(b) } return a.sub(b) } fun basicCalculatorIV(expression: String?, evalvarS: Array<String?>?, evalintS: IntArray?): List<String> { val ans: List<String> = ArrayList() if (expression.isNullOrEmpty() || evalvarS == null || evalintS == null) { return ans } val vars: MutableMap<String?, Int> = HashMap() for (i in evalvarS.indices) { vars[evalvarS[i]] = evalintS[i] } val n = expression.length val numS = ArrayDeque<Node>() val ops = ArrayDeque<Char>() var i = 0 while (i < n) { val a = expression[i] if (Character.isLetterOrDigit(a)) { val end = getNext(expression, i) val cur = expression.substring(i, end + 1) i = end val now = make(cur) numS.add(now) } else if (a == '(') { ops.add(a) } else if (a == ')') { while (ops.last() != '(') { numS.add(helper(numS, ops)) } ops.removeLast() } else if (a == '+' || a == '-' || a == '*') { while (ops.isNotEmpty() && getPriority(ops.last()) >= getPriority(a)) { numS.add(helper(numS, ops)) } ops.add(a) } i++ } while (ops.isNotEmpty()) { numS.add(helper(numS, ops)) } return numS.last().evaluate(vars).toList() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
5,547
LeetCode-in-Kotlin
MIT License
src/day20/result.kt
davidcurrie
437,645,413
false
{"Kotlin": 37294}
package day20 import java.io.File fun Array<Array<Boolean>>.count() = sumOf { row -> row.count { it } } fun Array<Array<Boolean>>.enhance(algo: List<Boolean>, infinity: Boolean) = (-1..size).map { y -> (-1..this[0].size).map { x -> algo[index(x, y, infinity)] }.toTypedArray() }.toTypedArray() fun Array<Array<Boolean>>.index(x: Int, y: Int, infinity: Boolean) = (-1..1).map { dy -> (-1..1).map { dx -> if (get(x + dx, y + dy, infinity)) 1 else 0 } } .flatten().joinToString("").toInt(2) fun Array<Array<Boolean>>.get(x: Int, y: Int, infinity: Boolean) = if (y < 0 || y >= size || x < 0 || x >= this[0].size) infinity else this[y][x] fun main() { val lines = File("src/day20/input.txt").readLines() val algo = lines[0].toList().map { it == '#' } var pixels = lines.drop(2) .map { line -> line.toList().map { (it == '#') }.toTypedArray() }.toTypedArray() repeat(2) { pixels = pixels.enhance(algo, algo[0] && (it % 2 != 0)) } println(pixels.count()) repeat(48) { pixels = pixels.enhance(algo, algo[0] && (it % 2 != 0)) } println(pixels.count()) }
0
Kotlin
0
0
dd37372420dc4b80066efd7250dd3711bc677f4c
1,165
advent-of-code-2021
MIT License
src/main/kotlin/text/EditDistance.kt
komu
104,990,960
false
null
package text import utils.readResourceLines fun levenshtein(lhs: String, rhs: String): Int { var cost = Array(lhs.length) { it } var newCost = Array(lhs.length) { 0 } for (i in 1 until rhs.length) { newCost[0] = i for (j in 1 until lhs.length) { val match = if (lhs[j - 1] == rhs[i - 1]) 0 else 1 val costReplace = cost[j - 1] + match val costInsert = cost[j] + 1 val costDelete = newCost[j - 1] + 1 newCost[j] = minOf(costInsert, costDelete, costReplace) } val swap = cost cost = newCost newCost = swap } return cost[lhs.length - 1] } fun List<String>.categorize(distance: Int): Map<String, List<String>> { val unprocessed = toMutableList() val result = mutableMapOf<String, List<String>>() while (unprocessed.isNotEmpty()) { val first = unprocessed.removeAt(0).trim() if (first.length < 6) { result[first] = emptyList() continue } val aliases = unprocessed.drop(1).filter { levenshtein(first.trim(), it.trim()) <= distance } // if (aliases.isNotEmpty()) result[first] = aliases unprocessed -= aliases } return result }
0
Kotlin
0
0
da1b0111a7ef7b214393ad9b135b4b83cb47de05
1,267
scratch
MIT License
code/day_14/src/jvm8Main/kotlin/task1.kt
dhakehurst
725,945,024
false
{"Kotlin": 105846}
package day_14 import kotlin.math.pow class GridAsLongs( /** * list of rows */ val lines: List<Long>, val size:Size ) { val columns = IntRange(0, size.cols - 1).map { col -> val colMask = 2L.pow(size.cols - col) lines.foldIndexed(0L) { x, a, i -> when (i and colMask) { 0L -> a else -> a + x * (2L.pow(x + 1)) } } } override fun toString(): String { return lines.joinToString(separator = "\n") { val s = it.toString(2) s.padStart(size.cols,'0') } } } val Int.numBits get() = this.countOneBits() fun List<String>.toGrids(): List<GridAsLongs> { val grids = mutableListOf<GridAsLongs>() var lastLineLength = -1 var l = mutableListOf<Long>() for (line in this) { when { line.isBlank() -> { val size = Size(lastLineLength, l.size) grids.add(GridAsLongs(l, size)) l = mutableListOf<Long>() } else -> { l.add(line.asBinaryLong) lastLineLength = line.length } } } grids.add(GridAsLongs(l,Size(lastLineLength, l.size))) return grids } fun Long.pow(n: Int): Long = this.toDouble().pow(n).toLong() val String.asBinaryLong: Long get() = this.foldIndexed(0L) { i, a, c -> when (c) { 'O' -> a + (2L.pow((this.length-1)-i )) else -> a } } fun progressionSum(numElements: Int, length: Int) = (length + (length - numElements)) * (numElements / 2) fun String.tiltAndSumWeight(): Long { var sum = 0L var slideToRow = this.length for (i in 0 until this.length) { val c = this[i] when (c) { '.' -> {} '#' -> { slideToRow = this.length - (i + 1) } 'O' -> { sum += slideToRow slideToRow-- } } } return sum } fun task1(lines: List<String>): Long { var total = 0L val grid = GridAsString(lines) for (col in grid.columns) { val t = col.tilt() val v = t.sumWeight() total += v//col.tiltAndSumWeight() } return total }
0
Kotlin
0
0
be416bd89ac375d49649e7fce68c074f8c4e912e
2,280
advent-of-code
Apache License 2.0
kt.kt
darian-catalin-cucer
598,116,446
false
null
import java.util.* fun maxMatching(n: Int, graph: Array<MutableList<Int>>): Int { val matching = IntArray(n) { -1 } val seen = BooleanArray(n) fun dfs(i: Int): Boolean { seen[i].also { seen[i] = true } graph[i].forEach { j -> if (matching[j] == -1 || (!seen[matching[j]] && dfs(matching[j]))) { matching[j] = i return true } } return false } var matches = 0 (0 until n).forEach { i -> if (dfs(i)) { matches++ } seen.fill(false) } return matches } // The code above implements the Hopcroft-Karp algorithm for finding the maximum matching in a bipartite graph. The algorithm starts by initializing the matching array to -1, which represents the fact that no node has been matched yet. The function dfs(i) attempts to find an augmenting path starting from node i, and updates the matching array if it succeeds. The maxMatching function loops over all nodes in one side of the bipartite graph, calling dfs on each node and incrementing the matches counter if a match is found. This process continues until no more augmenting paths can be found. The final value of matches is the size of the maximum matching in the bipartite graph.
0
Kotlin
0
0
db6b2b89e57acef0ad9d1f23999b92e933120376
1,289
maximum-matching
MIT License
src/main/kotlin/com/ginsberg/advent2021/Day10.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright (c) 2021 by <NAME> */ /** * Advent of Code 2021, Day 10 - Syntax Scoring * Problem Description: http://adventofcode.com/2021/day/10 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day10/ */ package com.ginsberg.advent2021 class Day10(private val input: List<String>) { fun solvePart1(): Int = input .map { parseRow(it) } .filterIsInstance<Corrupted>() .sumOf { it.score() } fun solvePart2(): Long = input .map { parseRow(it) } .filterIsInstance<Incomplete>() .map { it.score() } .sorted() .midpoint() private fun parseRow(row: String): ParseResult { val stack = ArrayDeque<Char>() row.forEach { symbol -> when { symbol in openToClose -> stack.addLast(symbol) openToClose[stack.removeLast()] != symbol -> return Corrupted(symbol) } } return if (stack.isEmpty()) Success else Incomplete(stack.reversed()) } private sealed interface ParseResult private object Success : ParseResult private class Corrupted(val actual: Char) : ParseResult { fun score(): Int = scoresPart1.getValue(actual) } private class Incomplete(val pending: List<Char>) : ParseResult { fun score(): Long = pending .map { openToClose.getValue(it) } .fold(0L) { carry, symbol -> (carry * 5) + scoresPart2.getValue(symbol) } } companion object { private val scoresPart1 = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) private val scoresPart2 = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4) private val openToClose = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') } }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
1,890
advent-2021-kotlin
Apache License 2.0
app/src/main/java/io/github/pshegger/gamedevexperiments/algorithms/Graph.kt
PsHegger
99,228,633
false
null
package io.github.pshegger.gamedevexperiments.algorithms /** * @author <EMAIL> */ data class Graph<T>(val nodes: List<T>, val edges: List<Edge<T>>) { fun shortestPath(start: T, end: T): List<T>? { val distances = nodes.associate { it to Float.POSITIVE_INFINITY }.toMutableMap() val previouses = nodes.associate { Pair<T, T?>(it, null) }.toMutableMap() val unvisitedNodes = nodes.toMutableList() distances[start] = 0f while (unvisitedNodes.isNotEmpty()) { val u = unvisitedNodes.sortedBy { distances[it] }.first() unvisitedNodes.remove(u) if (u == end) { break } neighbors(u).forEach { e -> val v = e.otherEnd(u) val alt = e.weight + distances[u]!! if (alt < distances[v]!!) { distances[v] = alt previouses[v] = u } } } val path = arrayListOf<T>() var u: T? = end if (previouses[u] != null || u == start) { while (u != null) { path.add(u) u = previouses[u] } } else { return null } return path.reversed() } fun isRouteAvailable(start: T, end: T) = shortestPath(start, end) != null fun neighbors(n: T): List<Edge<T>> = edges.filter { it.start == n || it.end == n } data class Edge<T>(val start: T, val end: T, val weight: Float = 1f) { fun otherEnd(n: T): T = if (n == start) end else start } }
0
Kotlin
0
0
694d273a6d3dff49cf314cbe16e17b5f77c7738e
1,602
GameDevExperiments
MIT License
src/twentytwentytwo/day9/Day09.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentytwo.day9 import readInput import kotlin.math.abs import kotlin.math.sign fun main() { val tailList = mutableListOf( Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), ) val spaces = mutableSetOf(Pair(0, 0)) fun part1(input: List<String>): Int { var tailX = 0 var tailY = 0 var headX = 0 var headY = 0 input.forEach { val parts = it.split(" ") val direction = parts[0] val amount = parts[1].toInt() for (i in 0 until amount) { when (direction) { "D" -> { headY-- } "U" -> { headY++ } "L" -> { headX-- } "R" -> { headX++ } } moveTail(tailX, tailY, headX, headY, direction) { x, y -> tailX = x tailY = y spaces.add(Pair(tailX, tailY)) } } } return spaces.size } fun moveTail(tailIndex: Int, headX: Int, headY: Int) { if (tailIndex > 8) return if (abs(tailList[tailIndex].first - headX) <= 1 && abs(tailList[tailIndex].second - headY) <= 1) return // Lines if (tailList[tailIndex].first == headX - 2 && tailList[tailIndex].second == headY) { tailList[tailIndex] = Pair(tailList[tailIndex].first + 1, tailList[tailIndex].second) } if (tailList[tailIndex].first == headX + 2 && tailList[tailIndex].second == headY) { tailList[tailIndex] = Pair(tailList[tailIndex].first - 1, tailList[tailIndex].second) } if (tailList[tailIndex].second == headY - 2 && tailList[tailIndex].first == headX) { tailList[tailIndex] = Pair(tailList[tailIndex].first, tailList[tailIndex].second + 1) } if (tailList[tailIndex].second == headY + 2 && tailList[tailIndex].first == headX) { tailList[tailIndex] = Pair(tailList[tailIndex].first, tailList[tailIndex].second - 1) } // Diagonals if (tailList[tailIndex].second == headY + 2 && tailList[tailIndex].first < headX) { tailList[tailIndex] = Pair(tailList[tailIndex].first + 1, tailList[tailIndex].second - 1) } if (tailList[tailIndex].second == headY + 2 && tailList[tailIndex].first > headX) { tailList[tailIndex] = Pair(tailList[tailIndex].first - 1, tailList[tailIndex].second - 1) } if (tailList[tailIndex].second == headY - 2 && tailList[tailIndex].first < headX) { tailList[tailIndex] = Pair(tailList[tailIndex].first + 1, tailList[tailIndex].second + 1) } if (tailList[tailIndex].second == headY - 2 && tailList[tailIndex].first > headX) { tailList[tailIndex] = Pair(tailList[tailIndex].first - 1, tailList[tailIndex].second + 1) } if (tailList[tailIndex].first == headX - 2) { tailList[tailIndex] = Pair( tailList[tailIndex].first + 1, tailList[tailIndex].second + (headY - tailList[tailIndex].second).sign ) } if (tailList[tailIndex].first == headX + 2) { tailList[tailIndex] = Pair( tailList[tailIndex].first - 1, tailList[tailIndex].second + (headY - tailList[tailIndex].second).sign ) } moveTail(tailIndex + 1, tailList[tailIndex].first, tailList[tailIndex].second) } fun part2(input: List<String>): Int { var headX = 0 var headY = 0 input.forEach { val parts = it.split(" ") val direction = parts[0] val amount = parts[1].toInt() for (i in 0 until amount) { when (direction) { "D" -> { headY-- } "U" -> { headY++ } "L" -> { headX-- } "R" -> { headX++ } } moveTail(tailIndex = 0, headX = headX, headY = headY) spaces.add(tailList[8]) } } return spaces.size } val input = readInput("day9", "Day09_input") println(part1(input)) spaces.clear() println(part2(input)) } private fun moveTail( tailX: Int, tailY: Int, headX: Int, headY: Int, direction: String, body: (x: Int, y: Int) -> Unit ) { if (abs(tailX - headX) <= 1 && abs(tailY - headY) <= 1) return when (direction) { "D" -> { body(headX, headY + 1) } "U" -> { body(headX, headY - 1) } "L" -> { body(headX + 1, headY) } "R" -> { body(headX - 1, headY) } } }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
5,307
advent-of-code
Apache License 2.0
src/main/kotlin/solutions/Day9RopeBridge.kt
aormsby
571,002,889
false
{"Kotlin": 80084}
package solutions import models.Coord2d import utils.Input import utils.Solution // run only this day fun main() { Day9RopeBridge() } class Day9RopeBridge : Solution() { init { begin("Day 9 - Rope Bridge") val input = Input.parseToPairList<Char, Int>( filename = "/d9_rope_motion.txt", pairDelimiter = " ", groupDelimiter = "\n" ) val sol1 = trackTailPositions(input, knots = MutableList(size = 2) { Coord2d(0, 0) }) output("2-Knot Tail Trail Count", sol1.size) val sol2 = trackTailPositions(input, knots = MutableList(size = 10) { Coord2d(0, 0) }) output("10-Knot Tail TrailCount", sol2.size) } // simulate the motions using the coordinates of each knot private fun trackTailPositions(input: List<Pair<Char, Int>>, knots: MutableList<Coord2d>): Set<Coord2d> { val tailVisited = mutableSetOf<Coord2d>() // step through instructions input.forEach { instruction -> val move = instruction.motion() var numSteps = instruction.second // while there are steps left in the move... while (numSteps > 0) { var cur = 0 // knot index knots[0] += move // move only the head knot // looping over knots, stop at the last knot while (cur < knots.size - 1) { val next = cur + 1 // if knots not adjacent, add the 'signs' of the diff (e.g. [4,-2] becomes [1,-1]) if (knots[next] != knots[cur] && knots[next] !in knots[cur].allNeighbors()) { knots[next] += (knots[cur] - knots[next]).signs() } // add tail position to set if (next == knots.size - 1) tailVisited.add(knots[next]) cur++ } numSteps-- } } return tailVisited } // parse instruction to directional vector private fun Pair<Char, Int>.motion(): Coord2d = when (first) { 'R' -> Coord2d(1, 0) 'L' -> Coord2d(-1, 0) 'U' -> Coord2d(0, 1) 'D' -> Coord2d(0, -1) else -> throw Exception("something's wrong") } }
0
Kotlin
0
0
1bef4812a65396c5768f12c442d73160c9cfa189
2,355
advent-of-code-2022
MIT License
algorithms-kotlin/src/main/kotlin/io/github/brunogabriel/math/MatrixOperations.kt
brunogabriel
294,995,479
false
null
package io.github.brunogabriel.math fun matrixMultiplication( matrixA: List<List<Long>>, matrixB: List<List<Long>> ): List<List<Long>> { if (matrixA.first().size != matrixB.size) { return emptyList() } val result = Array(matrixA.size) { Array(matrixB.first().size) { 0L } } for (i in matrixA.indices) { for (j in matrixB[i].indices) { for (k in matrixA[i].indices) { result[i][j] += matrixA[i][k] * matrixB[k][j] } } } return result.map { it.toList() } } fun matrixSummation( matrixA: List<List<Long>>, matrixB: List<List<Long>> ): List<List<Long>> { if (matrixA.size != matrixB.size || matrixA.indices != matrixB.indices) { return emptyList() } matrixA.indices.forEach { if (matrixA[it].size != matrixB[it].size) { return emptyList() } } val result = Array(matrixA.size) { Array(matrixA.first().size) { 0L } } for (i in matrixA.indices) { for (j in matrixA[i].indices) { result[i][j] = matrixA[i][j] + matrixB[i][j] } } return result.map { it.toList() } } operator fun List<List<Long>>.times(other: List<List<Long>>): List<List<Long>> = matrixMultiplication(this, other) operator fun List<List<Long>>.plus(other: List<List<Long>>): List<List<Long>> = matrixSummation(this, other)
0
Kotlin
0
3
050a7093c0f2cf3864157c74adb84a969dea8882
1,402
algorithms
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2023/Day06.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import ch.ranil.aoc.AbstractDay import ch.ranil.aoc.product import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day06 : AbstractDay() { @Test fun part1Test() { assertEquals(288, compute1(testInput)) } @Test fun part1Puzzle() { assertEquals(5133600, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(71503, compute2(testInput)) } @Test fun part2Puzzle() { assertEquals(40651271, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { return input .parse() .map { (time, distance) -> countPossibleOptions(time.toLong(), distance.toLong()).toInt() } .product() } private fun compute2(input: List<String>): Long { val (time, distance) = input.parse2() return countPossibleOptions(time, distance) } private fun countPossibleOptions(time: Long, distance: Long): Long { fun getBoundary(range: LongProgression): Long { for (holdButtonForMs in range) { if (holdButtonForMs * (time - holdButtonForMs) > distance) { return holdButtonForMs } } return 0 } val lowerBoundary = getBoundary(1..time) val upperBoundary = getBoundary((1..time).reversed()) return upperBoundary - lowerBoundary + 1 } private fun List<String>.parse(): List<Pair<Int, Int>> { val times = this[0].split("\\s+".toRegex()).mapNotNull { it.trim().toIntOrNull() } val distances = this[1].split("\\s+".toRegex()).mapNotNull { it.trim().toIntOrNull() } return times.zip(distances) } private fun List<String>.parse2(): Pair<Long, Long> { val time = this[0].replace("[^0-9]".toRegex(), "").toLong() val distance = this[1].replace("[^0-9]".toRegex(), "").toLong() return time to distance } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
1,992
aoc
Apache License 2.0
src/main/kotlin/Day04.kt
SimonMarquis
724,825,757
false
{"Kotlin": 30983}
import kotlin.math.pow class Day04(private val input: List<String>) { data class Card(val win: Set<Int>, val hand: Set<Int>) private val cards = input.asSequence().map { card -> card.substringAfter(":") .split("|") .map { it.split(" ").mapNotNull(String::toIntOrNull).toSet() } .let { Card(win = it.first(), hand = it.last()) } } fun part1() = cards .onEach(::println) .map { it.win intersect it.hand } .onEach { println("Winning numbers: $it") } .filter { it.isNotEmpty() } .map { 2.0.pow(it.size - 1).toInt() } .onEach { println("Score: $it") } .sum() fun part2() = cards .onEach(::println) .map { (it.win intersect it.hand).size } .foldIndexedInPlace(MutableList(size = input.size) { 1 }) { index: Int, copies: Int -> repeat(copies) { offset -> this[index.inc() + offset] += this[index] } println("Cards: ${this[index]}, Copies: $copies, Distributed: $this") }.sum() }
0
Kotlin
0
1
043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e
1,054
advent-of-code-2023
MIT License
src/Day01.kt
aamielsan
572,653,361
false
{"Kotlin": 9363}
private class Elf( val calories: List<Int>, ) { val totalCalories: Int get() = calories.sum() companion object { fun fromCalories(string: String): Elf = Elf(calories = string.lines().map(String::toInt)) } } fun main() { // Get the total calories from the elf carrying the most calories fun part1(input: String): Int = input .split("\n\n") .map { Elf.fromCalories(it) } .maxBy { it.totalCalories } .totalCalories // Get the total calories from the top 3 elves carrying the most calories fun part2(input: String): Int = input .split("\n\n") .map { Elf.fromCalories(it) } .sortedByDescending { it.totalCalories } .take(3) .sumOf { it.totalCalories } val input = readInputToText("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9a522271bedb77496e572f5166c1884253cb635b
930
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/colinodell/advent2021/Vector2.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 import kotlin.math.abs import kotlin.math.max data class Vector2 (val x: Int, val y: Int) { operator fun plus(other: Vector2) = Vector2(x + other.x, y + other.y) operator fun minus(other: Vector2) = Vector2(x - other.x, y - other.y) override fun toString() = "($x, $y)" fun neighbors() = listOf( Vector2(x - 1, y), Vector2(x + 1, y), Vector2(x, y - 1), Vector2(x, y + 1) ) fun neighborsIncludingDiagonals() = neighbors() + listOf( Vector2(x - 1, y - 1), Vector2(x - 1, y + 1), Vector2(x + 1, y - 1), Vector2(x + 1, y + 1) ) // Unlike the other functions, the order here is important! fun allNeighborsIncludingSelf() = listOf( Vector2(x - 1, y - 1), Vector2(x, y - 1), Vector2(x + 1, y - 1), Vector2(x - 1, y), this, Vector2(x + 1, y), Vector2(x - 1, y + 1), Vector2(x, y + 1), Vector2(x + 1, y + 1) ) } // A line that is at some multiple of 45 degrees (horizontal, vertical, or diagonal) data class Line(val start: Vector2, val end: Vector2) { val points : List<Vector2> by lazy { val xDiff = end.x - start.x val yDiff = end.y - start.y val stepCount = max(abs(xDiff), abs(yDiff)) val xStep = xDiff / stepCount val yStep = yDiff / stepCount (0 .. stepCount).map { Vector2(start.x + it * xStep, start.y + it * yStep) } } val isHorizontal : Boolean by lazy { start.y == end.y } val isVertical : Boolean by lazy { start.x == end.x } val isDiagonal : Boolean by lazy { ! (isHorizontal || isVertical) } } data class Region(val topLeft: Vector2, val bottomRight: Vector2) { operator fun contains(point: Vector2): Boolean = point.x in topLeft.x..bottomRight.x && point.y in topLeft.y..bottomRight.y } typealias Grid<T> = Map<Vector2, T> data class GridEntry<V>(override val key: Vector2, override val value: V?) : Map.Entry<Vector2, V?> fun <T> Grid<T>.neighborsOf(point: Vector2): Map<Vector2, T> { return point.neighbors().filter { containsKey(it) }.associateWith { get(it)!! } } fun <T> Grid<T>.neighborsIncludingDiagonalsOf(point: Vector2): Map<Vector2, T> { return point.neighborsIncludingDiagonals().filter { containsKey(it) }.associateWith { get(it)!! } } fun <T> Grid<T>.width() = keys.maxOf { it.x } - keys.minOf { it.x } + 1 fun <T> Grid<T>.height() = keys.maxOf { it.y } - keys.minOf { it.y } + 1 fun <T> Grid<T>.topLeft() = Vector2(keys.minOf { it.x }, keys.minOf { it.y }) fun <T> Grid<T>.bottomRight() = Vector2(keys.maxOf { it.x }, keys.maxOf { it.y }) fun <T, O> Grid<T>.mapAllPositions(padding: Int = 0, transform: (GridEntry<T>) -> O): Grid<O> { val grid = mutableMapOf<Vector2, O>() (keys.minOf { it.y } - padding .. keys.maxOf { it.y } + padding).forEach { y -> (keys.minOf { it.x } - padding..keys.maxOf { it.x } + padding).forEach { x -> grid[Vector2(x, y)] = transform(GridEntry(Vector2(x, y), this[Vector2(x, y)])) } } return grid } fun Collection<Vector2>.toStringVisualization(): String { val minX = minOf { it.x } val minY = minOf { it.y } val maxX = maxOf { it.x } val maxY = maxOf { it.y } val grid = Array(maxY - minY + 1) { Array(maxX - minX + 1) { '.' } } for (point in this) { grid[point.y - minY][point.x - minX] = '#' } return grid.map { it.joinToString("") }.joinToString("\n") } fun <T> Grid<T>.toStringVisualization(): String { val minX = minOf { it.key.x } val minY = minOf { it.key.y } val maxX = maxOf { it.key.x } val maxY = maxOf { it.key.y } val grid = Array(maxY - minY + 1) { Array(maxX - minX + 1) { '.' } } for (point in this) { grid[point.key.y - minY][point.key.x - minX] = point.value.toString()[0] } return grid.map { it.joinToString("") }.joinToString("\n") } fun <T> List<String>.toGrid(transform: (Char) -> T) = mutableMapOf<Vector2, T>().apply { forEachIndexed { y, line -> line.forEachIndexed { x, c -> put(Vector2(x, y), transform(c)) } } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
4,169
advent-2021
Apache License 2.0
day3/day3/src/main/kotlin/Main.kt
teemu-rossi
437,894,529
false
{"Kotlin": 28815, "Rust": 4678}
fun main(args: Array<String>) { println("Hello World!") val values = generateSequence(::readLine) .mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } } .toList() values.forEach { println(it) } val bits = values.maxOf { it.length } val gamma = buildString { for (i in 0 until bits) { val mostCommon = if (values.countOnes(i) >= (values.size + 1) / 2) "1" else "0" append(mostCommon) } } println("gamma=$gamma") val epsilon = gamma.map { if (it == '0') '1' else '0' }.joinToString(separator = "") println("epsilon=$epsilon") println("power=${gamma.toInt(2) * epsilon.toInt(2)}") // oxygen generator rating val list1 = values.toMutableList() var oxygenGen: Int? = null for (i in 0 until bits) { val mostCommon = if (list1.countOnes(i) >= (list1.size + 1) / 2) "1" else "0" println("mostCommon[$i]=$mostCommon (ones=${list1.countOnes(i)} list size=${list1.size}}") list1.removeIf { it[i] != mostCommon[0] } if (list1.size <= 1) { println("oxygen generator: ${list1.firstOrNull()}") oxygenGen = list1.firstOrNull()?.toInt(2) break } } // CO2 scrubber rating val list2 = values.toMutableList() var scrubber: Int? = null for (i in 0 until bits) { val leastCommon = if (list2.countOnes(i) < (list2.size + 1) / 2) "1" else "0" list2.removeIf { it[i] != leastCommon[0] } if (list2.size <= 1) { println("scrubber first: ${list2.firstOrNull()}") scrubber = list2.firstOrNull()?.toInt(2) break } } println("oxygenGen=$oxygenGen co2scrubber=$scrubber multi=${oxygenGen?.times(scrubber ?: 0)}") } fun List<String>.countOnes(index: Int): Int = count { it[index] == "1"[0] }
0
Kotlin
0
0
16fe605f26632ac2e134ad4bcf42f4ed13b9cf03
1,878
AdventOfCode
MIT License
src/main/kotlin/days/Day10.kt
vovarova
572,952,098
false
{"Kotlin": 103799}
package days class Day10 : Day(10) { val commands = inputList.map { when (it) { "noop" -> Command.Noop else -> Command.AddX(it.split(" ")[1].toInt()) } } class InstructionExecutor(commandsInput: List<Command>) { private val operations: List<Operation> = commandsInput.flatMap { it.operations } /** * valueRegistry[1] means value for end of 1-st cycle,and value for 2-nd cycle. */ val valueRegistry: List<Int> init { valueRegistry = IntRange(1, operations.size).fold(mutableListOf(1)) { list, endCycle -> list.also { list.add(endCycle, operations[endCycle - 1].execute(list[endCycle - 1])) } } } fun value(cycle: Int): Int { return valueRegistry[cycle - 1] } } open class Command(val operations: List<Operation>) { object Noop : Command(listOf(Operation.Wait)) class AddX(value: Int) : Command(listOf(Operation.Wait, Operation.Change(value))) } abstract class Operation { abstract fun execute(value: Int): Int class Change(private val commandValue: Int) : Operation() { override fun execute(value: Int): Int { return commandValue + value } } object Wait : Operation() { override fun execute(value: Int): Int = value } } override fun partOne(): Any { val instructionExecutor = InstructionExecutor(commands) return arrayOf(20, 60, 100, 140, 180, 220).map { instructionExecutor.value(it) * it }.sum() } override fun partTwo(): Any { val sprite = InstructionExecutor(commands) val screenCrt = listOf( IntRange(1, 40), IntRange(41, 80), IntRange(81, 120), IntRange(121, 160), IntRange(161, 200), IntRange(201, 240) ).map { it.mapIndexed { screenPosition, striteIndex -> IntRange( sprite.value(striteIndex) - 1, sprite.value(striteIndex) + 1, ).contains(screenPosition) }.map { if (it) { '#' } else { '.' } }.joinToString(separator = "") }.joinToString(separator = System.lineSeparator()) return screenCrt } }
0
Kotlin
0
0
e34e353c7733549146653341e4b1a5e9195fece6
2,484
adventofcode_2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/CherryPickup2.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max fun interface CherryPickup2Strategy { operator fun invoke(grid: Array<IntArray>): Int } class CherryPickup2DPTopDown : CherryPickup2Strategy { override operator fun invoke(grid: Array<IntArray>): Int { if (grid.isEmpty()) return 0 val m: Int = grid.size val n: Int = grid[0].size val dpCache = Array(m) { Array(n) { IntArray(n) } } // initial all elements to -1 to mark unseen // initial all elements to -1 to mark unseen for (i in 0 until m) { for (j in 0 until n) { for (k in 0 until n) { dpCache[i][j][k] = -1 } } } return dp(0, 0, n - 1, grid, dpCache) } private fun dp(row: Int, col1: Int, col2: Int, grid: Array<IntArray>, dpCache: Array<Array<IntArray>>): Int { val n = grid[0].size val col1Predicate = colPredicate(col1, n) val col2Predicate = colPredicate(col2, n) if (col1Predicate || col2Predicate) { return 0 } // check cache if (dpCache[row][col1][col2] != -1) { return dpCache[row][col1][col2] } // current cell var result = 0 result += grid[row][col1] if (col1 != col2) { result += grid[row][col2] } // transition if (row != grid.size - 1) { var max = 0 for (newCol1 in col1 - 1..col1 + 1) { for (newCol2 in col2 - 1..col2 + 1) { max = max(max, dp(row + 1, newCol1, newCol2, grid, dpCache)) } } result += max } dpCache[row][col1][col2] = result return result } private fun colPredicate(col: Int, size: Int) = col < 0 || col >= size } class CherryPickup2DPBottomUp : CherryPickup2Strategy { override operator fun invoke(grid: Array<IntArray>): Int { if (grid.isEmpty()) return 0 val m: Int = grid.size val n: Int = grid[0].size val dp = Array(m) { Array(n) { IntArray(n) } } for (row in m - 1 downTo 0) { for (col1 in 0 until n) { for (col2 in 0 until n) { var result = 0 // current cell result += grid[row][col1] if (col1 != col2) { result += grid[row][col2] } // transition if (row != m - 1) { var max = 0 for (newCol1 in col1 - 1..col1 + 1) { for (newCol2 in col2 - 1..col2 + 1) { if (newCol1 in 0 until n && newCol2 >= 0 && newCol2 < n) { max = max(max, dp[row + 1][newCol1][newCol2]) } } } result += max } dp[row][col1][col2] = result } } } return dp[0][0][n - 1] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,786
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LargestUniqueNumber.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode fun interface LargestUniqueNumber { operator fun invoke(arr: IntArray): Int } /** * O(n) time. * O(1) space. */ class LargestUniqueNumberBruteForce : LargestUniqueNumber { override operator fun invoke(arr: IntArray): Int { var res = -1 val temp = IntArray(ARR_SIZE) for (i in arr.indices) { temp[arr[i]]++ } for (i in temp.size - 1 downTo 0) { if (temp[i] == 1) { res = i break } } return res } companion object { private const val ARR_SIZE = 1001 } } /** * Time complexity: O(n). * Space complexity: O(n). */ class LargestUniqueNumberHashMap : LargestUniqueNumber { override operator fun invoke(arr: IntArray): Int { val seen: MutableMap<Int, Int> = HashMap() for (i in arr.indices) { seen[arr[i]] = seen.getOrDefault(arr[i], 0) + 1 } var result = -1 for ((key, value) in seen) { if (value == 1 && key > result) { result = key } } return result } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,770
kotlab
Apache License 2.0
src/test/kotlin/ch/ranil/aoc/aoc2022/Day05.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2022 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.test.assertEquals object Day05 : AbstractDay() { @Test fun tests() { assertEquals("CMZ", compute1(testInput)) assertEquals("VJSFHWGFT", compute1(puzzleInput)) assertEquals("MCD", compute2(testInput)) assertEquals("LCTQFBVZV", compute2(puzzleInput)) } private fun compute1(input: List<String>): String { val (stacks, moves) = input.parse() moves.forEach { applyMove(it, stacks) } return stacks.readAnswer() } private fun compute2(input: List<String>): String { val (stacks, moves) = input.parse() moves.forEach { applyMove2(it, stacks) } return stacks.readAnswer() } private fun applyMove(move: String, stacks: Stacks) { val (count, from, to) = move.parse() repeat(count) { val toMove = stacks[from].removeLast() stacks[to].addLast(toMove) } } private fun applyMove2(move: String, stacks: Stacks) { val (count, from, to) = move.parse() stacks[from] .takeLast(count) .forEach { stacks[from].removeLast() stacks[to].addLast(it) } } private fun String.parse(): Move { val parts = split(" ") return Move( count = parts[1].toInt(), from = parts[3].toInt() - 1, to = parts[5].toInt() - 1, ) } private fun List<String>.parse(): Pair<Stacks, List<String>> { val stackData = this.takeWhile { it.isNotBlank() } val numberOfStacks = stackData .last() .split(" ") .last { it.isNotBlank() } .toInt() val stacks = List(numberOfStacks) { ArrayDeque<Char>() } stackData .dropLast(1) .reversed() .forEach { it.putOnStacks(stacks) } val moves = this.drop(stackData.size + 1) return stacks to moves } private fun String.putOnStacks(stacks: Stacks) { val charArray = this.toCharArray() for (i in stacks.indices) { val idx = 4 * i + 1 val char = charArray.elementAtOrNull(idx) ?: ' ' if (char != ' ') stacks[i].add(char) } } private fun Stacks.readAnswer(): String { return map { it.last() } .joinToString("") } private data class Move(val count: Int, val from: Int, val to: Int) } private typealias Stacks = List<ArrayDeque<Char>>
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
2,673
aoc
Apache License 2.0
src/Day06.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
fun main() { fun solve(input: String, numDistinct: Int): Int { val windowed = input.windowed(numDistinct) for ((index, window) in windowed.withIndex()) { if (window.toList().distinct().size == numDistinct) { return index + numDistinct } } return 0 } fun part1(input: List<String>): Int { return solve(input[0], 4) } fun part2(input: List<String>): Int { return solve(input[0], 14) } val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
700
aoc-2022
Apache License 2.0
libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/ir/buckets.kt
apollographql
69,469,299
false
{"Kotlin": 3427995, "Java": 244871, "CSS": 34435, "HTML": 4780, "JavaScript": 1191}
package com.apollographql.apollo3.compiler.ir import com.apollographql.apollo3.ast.Schema import com.apollographql.apollo3.ast.possibleTypes internal data class Bucket(val typeSet: TypeSet, val possibleTypes: PossibleTypes) /** * This function distributes [incomingTypes] into different buckets. */ internal fun buckets( schema: Schema, incomingTypes: List<String>, userTypeSets: List<TypeSet>, ): List<Bucket> { val typeConditionToPossibleTypes = userTypeSets.union().associateWith { schema.typeDefinition(it).possibleTypes(schema) } /** * Start with the user type sets */ val buckets = userTypeSets.map { userTypeSet -> BucketInternal( userTypeSet, userTypeSet.map { typeConditionToPossibleTypes[it]!! }.intersection(), emptySet() ) }.toMutableList() incomingTypes.forEach { concreteType -> val superShapes = mutableListOf<BucketInternal>() buckets.forEachIndexed { index, shape -> if (buckets[index].schemaPossibleTypes.contains(concreteType)) { superShapes.add(shape) } } if (superShapes.isEmpty()) { // This incoming type is never selected return@forEach } /** * Take all superShapes of a given type. This type will use a shape matching the union of all the superShapes (most qualified typeset). * * It might be that the user did not specifically require this particular typeSet. For an example, with following type conditions: * [A, B] * [A, C] * * A concrete object matching [A, B, C] needs a new shape. */ val bucketTypeSet = superShapes.fold(emptySet<String>()) { acc, shape -> acc.union(shape.typeSet) } val index = buckets.indexOfFirst { it.typeSet == bucketTypeSet } if (index < 0) { buckets.add( BucketInternal( bucketTypeSet, bucketTypeSet.map { typeConditionToPossibleTypes[it]!! }.intersection(), setOf(concreteType) ) ) } else { val existingShape = buckets[index] buckets[index] = existingShape.copy(actualPossibleTypes = existingShape.actualPossibleTypes + concreteType) } } /** * Filter out empty buckets */ return buckets.filter { it.actualPossibleTypes.isNotEmpty() }.map { Bucket(it.typeSet, it.actualPossibleTypes) } } /** * @param schemaPossibleTypes all the possible types in the schema that satisfy [typeSet]. * @param actualPossibleTypes the actual types that will resolve to this shape. This is different from [schemaPossibleTypes] * as a given type will fall into the most qualified bucket */ private data class BucketInternal(val typeSet: TypeSet, val schemaPossibleTypes: PossibleTypes, val actualPossibleTypes: PossibleTypes)
174
Kotlin
659
3,628
42f3208e23d97bd3b6cc62bfc4f135523786365d
2,765
apollo-kotlin
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day16.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2022 import se.saidaspen.aoc.util.* fun main() = Day16.run() object Day16: Day(2022, 16) { data class Valve(val rate: Int, val valves: List<String>) private val state = input.lines().associate { l -> val name = l.split(" ")[1] val rate = ints(l)[0] val valves = l.split(" ").drop(9).map { c -> c.replace(",", "").trim() }.toList() name to Valve(rate, valves) } private var memo1 = mutableMapOf<Triple<Set<String>, Int, String>, Int>() private var memo2 = mutableMapOf<Triple<Set<String>, Int, String>, Int>() override fun part1(): Any { return solve1(setOf(), 30, "AA") } override fun part2(): Any { return solve2(setOf(), 26, "AA") } private fun solve1(opened: Set<String>, minutes : Int, curr: String): Int { val cached = memo1[Triple(opened, minutes, curr)] if (cached != null) return cached if (minutes <= 0) return 0 var currentBest = 0 val s = state[curr]!! for (valve in s.valves) { // Just moving to the next valve directly, might be better than staying. val bestOneMoveAway = solve1(opened, minutes - 1, valve) currentBest = Integer.max(currentBest, bestOneMoveAway) } if (curr notin opened && s.rate > 0) { val minutesNext = minutes - 1 for (valve in s.valves) { val bestAfterTurningOnThenMove = minutesNext * s.rate + solve1(opened + curr, minutesNext - 1, valve) currentBest = Integer.max(currentBest, bestAfterTurningOnThenMove) } } memo1[Triple(opened, minutes, curr)] = currentBest return currentBest } private fun solve2(opened: Set<String>, minutes : Int, curr: String): Int { val cached = memo2[Triple(opened, minutes, curr)] if (cached != null) return cached if (minutes <= 0) return solve1(opened, 26, "AA") var best = 0 val s = state[curr]!! for (valve in s.valves) { best = Integer.max(best, solve2(opened, minutes - 1, valve)) } if (curr notin opened && s.rate > 0) { val minutesNext = minutes -1 for (valve in s.valves) { val bestAfterTurningOnThenMove = minutesNext * s.rate + solve2(opened + curr, minutesNext - 1, valve) best = Integer.max(best, bestAfterTurningOnThenMove) } } memo2[Triple(opened, minutes, curr)] = best return best } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,562
adventofkotlin
MIT License
leetcode2/src/leetcode/IntersectionOfTwoArrays.kt
hewking
68,515,222
false
null
package leetcode import java.util.* /** * 两个数组的交集 * https://leetcode-cn.com/problems/intersection-of-two-arrays/ * Created by test * Date 2019/5/20 23:28 * Description * 给定两个数组,编写一个函数来计算它们的交集。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4] 说明: 输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。 */ object IntersectionOfTwoArrays{ class Solution { fun intersection(nums1: IntArray, nums2: IntArray): IntArray { Arrays.sort(nums1) Arrays.sort(nums2) val minArr = if (nums1.size > nums2.size) nums2 else nums1 val maxArr = if (nums1.size > nums2.size) nums1 else nums2 val arrList = mutableSetOf<Int>() for (num in minArr) { for (num2 in maxArr) { if (num == num2) { arrList.add(num) continue } } } return arrList.toIntArray() } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,183
leetcode
MIT License
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day03.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2018.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues import nl.jstege.adventofcode.aoccommon.utils.extensions.transformTo class Day03 : Day(title = "No Matter How You Slice It") { private companion object Configuration { private const val GRID_WIDTH = 1000 private const val GRID_HEIGHT = 1000 private const val INPUT_PATTERN_STRING = """#(\d+)\s@\s(\d+),(\d+):\s(\d+)x(\d+)""" private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex() private const val ID_INDEX = 1 private const val X_INDEX = 2 private const val Y_INDEX = 3 private const val WIDTH_INDEX = 4 private const val HEIGHT_INDEX = 5 private val PARAM_INDICES = intArrayOf( ID_INDEX, X_INDEX, Y_INDEX, WIDTH_INDEX, HEIGHT_INDEX ) } override fun first(input: Sequence<String>): Any = input .parse() .transformTo(Grid(GRID_WIDTH, GRID_HEIGHT), Grid::set) .count { it > 1 } override fun second(input: Sequence<String>): Any = Grid(GRID_WIDTH, GRID_HEIGHT).let { grid -> input .parse() .onEach(grid::set) .toList() //Make sure all claims have been processed. .first { claim -> grid[claim].all { it == 1 } } .id } private fun Sequence<String>.parse(): Sequence<Claim> = this .map { it.extractValues(INPUT_REGEX, *PARAM_INDICES) } .map { it.map(String::toInt) } .map { (id, x, y, w, h) -> Claim(id, x, y, x + w, y + h) } private data class Claim( val id: Int, val startX: Int, val startY: Int, val endX: Int, val endY: Int ) private class Grid(val width: Int = GRID_WIDTH, height: Int = GRID_HEIGHT) : Iterable<Int> { private val grid = IntArray(width * height) fun set(claim: Claim) = claim.let { (_, startX, startY, endX, endY) -> for (y in startY until endY) { for (x in startX until endX) { grid[y * width + x]++ } } } operator fun get(claim: Claim): List<Int> = claim.let { (_, startX, startY, endX, endY) -> (startY until endY).flatMap { y -> grid.copyOfRange(y * width + startX, y * width + endX).toList() } } override fun iterator(): Iterator<Int> = grid.iterator() } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,685
AdventOfCode
MIT License
src/leetcodeProblem/leetcode/editor/en/SetMatrixZeroes.kt
faniabdullah
382,893,751
false
null
//Given an m x n integer matrix matrix, if an element is 0, set its entire row //and column to 0's, and return the matrix. // // You must do it in place. // // // Example 1: // // //Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] //Output: [[1,0,1],[0,0,0],[1,0,1]] // // // Example 2: // // //Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] //Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]] // // // // Constraints: // // // m == matrix.length // n == matrix[0].length // 1 <= m, n <= 200 // -2³¹ <= matrix[i][j] <= 2³¹ - 1 // // // // Follow up: // // // A straightforward solution using O(mn) space is probably a bad idea. // A simple improvement uses O(m + n) space, but still not the best solution. // Could you devise a constant space solution? // // Related Topics Array Hash Table Matrix 👍 5009 👎 434 package leetcodeProblem.leetcode.editor.en class SetMatrixZeroes { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) internal class Solution { fun setZeroes(matrix: Array<IntArray>) { val R = matrix.size val C: Int = matrix[0].size val rows: MutableSet<Int> = HashSet() val cols: MutableSet<Int> = HashSet() for (i in 0 until R) { for (j in 0 until C) { if (matrix[i][j] == 0) { rows.add(i) cols.add(j) } } } for (i in 0 until R) { for (j in 0 until C) { if (rows.contains(i) || cols.contains(j)) { matrix[i][j] = 0 } } } } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,930
dsa-kotlin
MIT License
src/cn/ancono/math/discrete/UndirectedGraph.kt
140378476
105,762,795
false
{"Java": 1912158, "Kotlin": 1243514}
package cn.ancono.math.discrete //Created by lyc at 2021-03-28 19:32 interface UndirectedGraph : Graph { override fun degIn(a: Node): Int { return deg(a) } override fun degOut(a: Node): Int { return deg(a) } /** * Returns the nodes that are adjacent to `a`. */ fun neighbors(a: Node): Sequence<Node> override fun nodesIn(a: Node): Sequence<Node> { return neighbors(a) } override fun nodesOut(a: Node): Sequence<Node> { return neighbors(a) } /** * Gets the adjacent matrix of this undirected graph. The (i,j)-th element in the adjacent matrix is `1` if * `(i,j)` is an edge, otherwise `0`. */ fun adjacentMatrix(): Array<IntArray> { val mat = Array(n) { IntArray(n) } for (i in nodes) { for (j in neighbors(i)) { mat[i][j] = 1 } } return mat } // override fun inducedN(nodes: Set<Node>): Graph { // return UndirectedNodeSubgraph(this,nodes) // } // // override fun inducedE(edges: Set<Edge>): Graph { // TODO("Not yet implemented") // } /** * Returns the connected components. Each set in the returned list contains the nodes * of a connected component. * * This method uses DFS to find out all the connected components. */ fun connectedComponents(): List<Set<Node>> { val state = Array(n) { VisitState.UNDISCOVERED } val prev = IntArray(n) { -1 } val components = arrayListOf<Set<Node>>() for (i in nodes) { if (state[i] == VisitState.UNDISCOVERED) { val wb = CollectiveWorkBag(StackWorkBag()) Graphs.generalPrioritySearch(this, i, -1, wb, state, prev) components += wb.visited } } return components } /** * Returns the complement graph of `this`. The complement graph of `G` is a graph `H` with * the same nodes, but `(u,v) in E(H)` iff `(u,v) !in E(G)`. */ fun complementGraph(): UndirectedGraph { return UndirectedGraphInMatrix(Array(n) { i -> IntArray(n) { j -> if (containsEdge(i, j)) { 0 } else { 1 } } }) } } internal operator fun Array<IntArray>.get(i: Int, j: Int) = this[i][j] /** * Describes an immutable undirected graph stored in matrix. */ open class UndirectedGraphInMatrix internal constructor( private val matrix: Array<IntArray> ) : UndirectedGraph { init { // require(matrix.isSquare && matrix.rowCount == vertices.size) // require(edges.size == vertices.size && ed) } override val n: Int = matrix.size override val nodes: Sequence<Int> = (matrix.indices).asSequence() override val edges: Sequence<Edge> get() = nodes.flatMap { a -> (0..a).asSequence().filter { b -> containsEdge(a, b) }.map { b -> a to b } } override fun neighbors(a: Node): Sequence<Node> { return nodes.filter { containsEdge(a, it) } } override val edgeCount: Int by lazy { var c = 0 for (i in nodes) { for (j in nodes) { c += matrix[i, j] } } c / 2 } override fun deg(a: Node): Int { var c = 0 for (i in nodes) { c += matrix[a, i] } c += matrix[a, a] return c } override fun containsEdge(a: Node, b: Node): Boolean { return matrix[a, b] > 0 } override fun adjacentMatrix(): Array<IntArray> { return Array(n) { i -> matrix[i].copyOf() } } override fun complementGraph(): UndirectedGraph { return UndirectedGraphInMatrix(Array(n) { i -> IntArray(n) { j -> 1 - matrix[i, j] } }) } } class MatrixUndirectedGraphBuilder(n: Int) : GraphBuilder<UndirectedGraph> { val mat: Array<IntArray> = Array(n) { IntArray(n) } override fun Int.to(y: Int): Int { mat[this][y] = 1 return y } override fun build(): UndirectedGraph { return UndirectedGraphInMatrix(mat) } } open class UndirectedGraphInMatrixWithData<V, E>( matrix: Array<IntArray>, val vertices: List<V>, val edgeData: List<List<E?>>, ) : UndirectedGraphInMatrix(matrix), GraphWithData<V, E> { override fun getNode(a: Node): V { return vertices[a] } override fun getEdge(a: Node, b: Node): E? { return edgeData[a][b] } } internal class UndirectedNodeSubgraph(private val graph: UndirectedGraph, private val ns: Set<Node>) : UndirectedGraph { //TODO override val n: Int = ns.size override val edges: Sequence<Edge> get() = TODO("Not yet implemented") override fun deg(a: Node): Int { return neighbors(a).count() } override fun containsEdge(a: Node, b: Node): Boolean { TODO("Not yet implemented") } override fun neighbors(a: Node): Sequence<Node> { return graph.neighbors(a).filter { it in ns } } } //TODO: connectivity, matching
0
Java
0
6
02c2984c10a95fcf60adcb510b4bf111c3a773bc
5,274
Ancono
MIT License
src/net/sheltem/aoc/y2016/Day03.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2016 suspend fun main() { Day03().run() } class Day03 : Day<Int>(3, 4) { override suspend fun part1(input: List<String>): Int { return input.map { it.toTriangleStringList() }.map { Triangle.from(it) }.count { it.isValid() } } override suspend fun part2(input: List<String>): Int { return input.map { it.toTriangleStringList() }.windowed(3, 3).zipColumns().flatten().map { Triangle.from(it) }.count { it.isValid() } } class Triangle(val a: Int, val b: Int, val c: Int) { fun isValid() = listOf(a, b, c).sorted().take(2).sum() > maxOf(a, b, c) override fun toString() = "$a $b $c" companion object { fun from(sidesList: List<String>) = Triangle(sidesList[0].toInt(), sidesList[1].toInt(), sidesList[2].toInt()) } } private fun List<List<List<String>>>.zipColumns() = map { listOf( listOf( it[0][0], it[1][0], it[2][0], ), listOf( it[0][1], it[1][1], it[2][1], ), listOf( it[0][2], it[1][2], it[2][2], ) ) } private fun String.toTriangleStringList() = replace("\\s+".toRegex(), " ").trim().split(" ").map { it.trim() } }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
1,385
aoc
Apache License 2.0
kotlin/src/main/kotlin/de/p58i/advent-09.kt
mspoeri
573,120,274
false
{"Kotlin": 31279}
package de.p58i import de.p58i.RopeMove.Companion.toRopeMove import java.io.File import java.util.LinkedList import kotlin.math.abs import kotlin.math.sign enum class RopeMove { UP, DOWN, LEFT, RIGHT; companion object { fun Char.toRopeMove(): RopeMove = when (this.lowercaseChar()) { 'r' -> RIGHT 'l' -> LEFT 'u' -> UP 'd' -> DOWN else -> throw IllegalArgumentException("Unable to convert [$this]") } } } data class Position( val x: Int, val y: Int, ) { fun move(ropeMove: RopeMove) = when (ropeMove) { RopeMove.UP -> Position(x, y + 1) RopeMove.DOWN -> Position(x, y - 1) RopeMove.LEFT -> Position(x - 1, y) RopeMove.RIGHT -> Position(x + 1, y) } fun drag(otherPosition: Position): Position { val xOffset = otherPosition.x - x val yOffset = otherPosition.y - y return if (abs(xOffset) < 2 && abs(yOffset) < 2) { this } else if ((xOffset == 0) || (yOffset == 0)) { Position(x + (xOffset/2), y + (yOffset/2)) } else { Position(x + (1 * xOffset.sign),y+ (1 * yOffset.sign)) } } } fun main() { val ropeMoves = LinkedList<RopeMove>() File("./task-inputs/advent-09.input").forEachLine { val moveDirection = it.split(" ")[0].toCharArray().first().toRopeMove() val moveTimes = it.split(" ")[1].toInt() repeat(moveTimes) { ropeMoves.add(moveDirection) } } headTailMove(ropeMoves) multiKnotMove(ropeMoves) } const val knotCount = 10 fun multiKnotMove(ropeMoves: List<RopeMove>) { val knots = ArrayList<LinkedList<Position>>() repeat(knotCount){ knots.add(LinkedList(listOf(Position(0,0)))) } ropeMoves.forEach { move -> knots.first().add(knots.first().last.move(move)) for (knotIndex in 1 until knots.size){ val knotPositions = knots[knotIndex] knotPositions.add(knotPositions.last.drag(knots[knotIndex - 1].last)) } } println("Unique tail positions: ${knots.last().toSet().count()}") } private fun headTailMove(ropeMoves: LinkedList<RopeMove>) { val headPositions = LinkedList<Position>() val tailPositions = LinkedList<Position>() headPositions.add(Position(0, 0)) tailPositions.add(Position(0, 0)) ropeMoves.forEach { val currentHeadPosition = headPositions.last val currentTailPosition = tailPositions.last val nextHeadPosition = currentHeadPosition.move(it) val nextTailPosition = currentTailPosition.drag(nextHeadPosition) headPositions.add(nextHeadPosition) tailPositions.add(nextTailPosition) } println("Unique tail positions: ${tailPositions.toSet().count()}") }
0
Kotlin
0
1
62d7f145702d9126a80dac6d820831eeb4104bd0
2,937
Advent-of-Code-2022
MIT License
src/Day08.kt
Tiebe
579,377,778
false
{"Kotlin": 17146}
@file:Suppress("DuplicatedCode") fun main() { fun List<String>.toMatrix(): Array<IntArray> = this.map { line -> line.map { it.digitToInt() }.toIntArray() }.toTypedArray() fun Array<IntArray>.getTopVisibility(x: Int, y: Int): Pair<Boolean, Int> { val pointValue = this[y][x] for (i in y-1 downTo 0) { if (this[i][x] >= pointValue) { return false to y-i } } return true to y } fun Array<IntArray>.getBottomVisibility(x: Int, y: Int): Pair<Boolean, Int> { val pointValue = this[y][x] for (i in y+1 until size) { if (this[i][x] >= pointValue) { return false to i-y } } return true to size-y-1 } fun Array<IntArray>.getLeftVisibility(x: Int, y: Int): Pair<Boolean, Int> { val pointValue = this[y][x] for (i in x-1 downTo 0) { if (this[y][i] >= pointValue) { return false to x-i } } return true to x } fun Array<IntArray>.getRightVisibility(x: Int, y: Int): Pair<Boolean, Int> { val pointValue = this[y][x] for (i in x+1 until size) { if (this[y][i] >= pointValue) { return false to i-x } } return true to size-x-1 } fun part1(input: List<String>): Int { val matrix = input.toMatrix() var visible = matrix.size*4-4 for (line in 1 until matrix.size-1) { for (tree in 1 until matrix.size-1) { if (matrix.getLeftVisibility(tree, line).first || matrix.getRightVisibility(tree, line).first || matrix.getTopVisibility(tree, line).first || matrix.getBottomVisibility(tree, line).first) visible++ } } return visible } fun part2(input: List<String>): Int { val matrix = input.toMatrix() var topScenicScore = 0 for (line in 1 until matrix.size-1) { for (tree in 1 until matrix.size-1) { var scenicScore = 1 scenicScore *= (matrix.getTopVisibility(tree, line).second * matrix.getRightVisibility(tree, line).second * matrix.getBottomVisibility(tree, line).second * matrix.getLeftVisibility(tree, line).second) if (scenicScore > topScenicScore) topScenicScore = scenicScore } } return topScenicScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") part1(input).println() part2(input).println() }
1
Kotlin
0
0
afe9ac46b38e45bd400e66d6afd4314f435793b3
2,887
advent-of-code
Apache License 2.0
advent-of-code-2022/src/main/kotlin/Day10.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
//Day 10: Cathode-Ray Tube //https://adventofcode.com/2022/day/10 import java.io.File data class Instruction(val registerInc: Int) { val noop = registerInc == 0 companion object { private val ADD = "addx " fun fromString(string: String): Instruction { return if (string.startsWith(ADD)) { Instruction(string.substringAfter(ADD).toInt()) } else { //noop Instruction(0) } } } } fun main() { val lines = File("src/main/resources/Day10.txt").readLines() val instructions = lines.map { Instruction.fromString(it) } val registers = instructions.runningFold(1) { acc, instruction -> acc + instruction.registerInc } val cycles = instructions.map { if (it.noop) 1 else 2 }.runningFold(1) { acc, x -> acc + x } findSignalStrengths(registers, cycles) renderCRTSprites(instructions,registers, cycles) } private fun findSignalStrengths(registers: List<Int>, cycles: List<Int>) { val sixSignalStrengths = (20..220 step 40).sumOf { cycle -> val index = if (cycles.contains(cycle)) cycles.indexOf(cycle) else cycles.indexOf(cycle - 1) cycle * registers[index] } println(sixSignalStrengths) } fun renderCRTSprites(instructions: List<Instruction>, registers: List<Int>, cycles: List<Int>) { val LIT = "#" val DARK = "." var cycle = 1 val crt = mutableListOf<String>() instructions.forEach { val index = if (cycles.contains(cycle)) cycles.indexOf(cycle) else cycles.indexOf(cycle - 1) val sprite = mutableListOf(registers[index], registers[index] + 1, registers[index] + 2) if (it.noop) { crt += if (inSprite(sprite, cycle)) LIT else DARK cycle++ } else { crt += if (inSprite(sprite, cycle)) LIT else DARK cycle++ crt += if (inSprite(sprite, cycle)) LIT else DARK cycle++ } } crt.chunked(40).forEach { println(it.joinToString("")) } } private fun inSprite(sprite: List<Int>, cycle: Int): Boolean { if (cycle % 40 == 0) return 40 in sprite return (cycle % 40 in sprite) }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
2,205
advent-of-code
Apache License 2.0
src/day1/Day01.kt
rafagalan
573,145,902
false
{"Kotlin": 5674}
package day1 import readInput import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var maxCaloriesCarriedPerElf = 0 var elfCaloriesCounter = 0; input.forEach { if(it == "") { maxCaloriesCarriedPerElf = max(maxCaloriesCarriedPerElf, elfCaloriesCounter) elfCaloriesCounter = 0; } else { elfCaloriesCounter += it.toInt(); } } return maxCaloriesCarriedPerElf } fun part2(input: List<String>): Int { var caloriesPerElf = ArrayList<Int>() var elfCaloriesCounter = 0; input.forEach { if(it == "") { caloriesPerElf.add(elfCaloriesCounter) elfCaloriesCounter = 0; } else { elfCaloriesCounter += it.toInt(); } } caloriesPerElf.sortDescending() return caloriesPerElf[0] + caloriesPerElf[1] + caloriesPerElf[2] } val calories = readInput("Day01") val part1Answer = part1(calories) println(part1Answer) val part2Answer = part2(calories) println(part2Answer) }
0
Kotlin
0
0
8e7d3f25fe52a4153479adb56c5924b50f6c0be9
1,167
AdventOfCode2022
Apache License 2.0
src/main/kotlin/katas/4.HighAndLow.kt
ch8n
312,467,034
false
null
//? https://www.codewars.com/kata/554b4ac871d6813a03000035/train/kotlin ? // return the highest and lowest number. @file:Suppress("PackageDirectoryMismatch") package katas.highlow import kotlin.system.measureNanoTime fun main() { val input = "8 3 -5 42 -1 0 0 -9 4 7 4 -4" measure("Chetan-1") { highAndLow1(input) } measure("Chetan-2") { highAndLow2(input) } measure("Community-1") { highAndLowC1(input) } measure("Community-2") { highAndLowC2(input) } measure("Appache-1") { appacheSolution(input) } measure("holloRedditAnswer-1") { holloRedditAnswer(input) } } fun measure(tag: String, block: () -> Unit) { Thread(Runnable { measureNanoTime { block.invoke() }.also { println("""$tag took ${it * 0.000001} ms-----""") } }).start() } fun highAndLow1(numbers: String): String { val nums = numbers.split(" ").map { it.toIntOrNull() }.filterNotNull() val max = nums.maxOrNull() ?: -1 val min = nums.minOrNull() ?: -1 return "$max $min" } fun highAndLow2(numbers: String): String { val firstNumber: Int = numbers.split(" ").get(0).toIntOrNull() ?: -1 val result = numbers.split(" ").fold(Pair</*max*/Int,/*min*/Int>(firstNumber, firstNumber)) { acc, it -> val item = it.toIntOrNull() ?: -1 return@fold when { item > acc.first -> acc.copy(first = item) item < acc.second -> acc.copy(second = item) else -> acc } } return "${result.first} ${result.second}" } fun highAndLowC1(numbers: String) = numbers.split(' ').map(String::toInt).let { "${it.max()} ${it.min()}" } fun highAndLowC2(numbers: String): String { val nums = numbers.split(" ").map { it.toInt() }.sorted() return "${nums.last()} ${nums.first()}" } fun appacheSolution(numbers: String): String { val result = numbers.split(' ') .map(String::toInt) .sorted() return "${result.first()} ${result.last()}" } fun niharikaSolution() { //https://twitter.com/theDroidLady val DEFAULT_MIN = -1 val DEFAULT_MAX = -1 fun getMinAndMax(numberString: String): String = numberString .split(' ') .mapNotNull { stringItem -> stringItem.toIntOrNull() } .distinct() .let { numbersList -> "${numbersList.maxOrNull() ?: DEFAULT_MAX} ${numbersList.minOrNull() ?: DEFAULT_MIN}" } println(getMinAndMax("1 2 13 41 5 hh -1 17 0 5 -1")) } //Reddit fun holloRedditAnswer(numbers: String): String { val seq = numbers.splitToSequence(' ') val first: Int = seq.first().toInt() val result = seq.fold(Pair(first, first)) { acc, item -> val numb = item.toIntOrNull() return@fold if (numb != null) { acc.copy(first = maxOf(acc.first, numb), second = minOf(acc.second, numb)) } else { acc } } return "${result.first} ${result.second}" }
3
Kotlin
0
1
e0619ebae131a500cacfacb7523fea5a9e44733d
3,037
Big-Brain-Kotlin
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day09.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2022 import se.saidaspen.aoc.util.* import kotlin.math.absoluteValue import kotlin.math.sign fun main() = Day09.run() object Day09 : Day(2022, 9) { override fun part1(): Any { var h = P(0, 0) var t = P(0, 0) val visited = mutableSetOf<P<Int, Int>>() for (l in input.lines()) { repeat(ints(l)[0]) { h = h.move(l[0]) t = move(h, t) visited.add(t) } } return visited.size } override fun part2(): Any { val snake = MutableList(10){P(0,0)} val visited = mutableSetOf<P<Int, Int>>() for (l in input.lines()) { repeat(ints(l)[0]) { snake[0] = snake[0].move(l[0]) for (i in 1 until snake.size) snake[i] = move(snake[i - 1], snake[i]) visited.add(snake.last()) } } return visited.size } private fun move(h: Pair<Int, Int>, t: Pair<Int, Int>): Pair<Int, Int> { val dx = h.x - t.x val dy = h.y - t.y return if (dx.absoluteValue > 1 || dy.absoluteValue > 1) { P(t.x + dx.sign, t.y + dy.sign) } else t } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,214
adventofkotlin
MIT License
google/2019/round1_a/2/main.kt
seirion
17,619,607
false
{"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294}
import java.util.* fun main(args: Array<String>) { val (T, N, M) = readLine()!!.split("\\s".toRegex()).map { s -> s.toInt() } repeat(T) { solve(N, M) } } val prime = arrayListOf(5, 7, 9, 11, 13, 16, 17) fun solve(night: Int, max: Int) { val response = ArrayList<Int>() repeat(prime.size) { index -> println(IntArray(18) { prime[index] }.joinToString(" ")) val v = readLine()!!.split("\\s".toRegex()).map { s -> s.toInt() }.sum() % prime[index] response.add(v) } println(calculate(response, max)) readLine() } fun calculate(response: List<Int>, max: Int): Int { for (v in 1..max) { if ((0 until prime.size).all { v % prime[it] == response[it] }) return v } return 0 }
0
C++
4
4
a59df98712c7eeceabc98f6535f7814d3a1c2c9f
744
code
Apache License 2.0
src/main/kotlin/pl/poznan/put/omw/GameFilter.kt
Azbesciak
227,870,505
false
{"Kotlin": 41507, "Java": 18293, "Shell": 803}
package pl.poznan.put.omw import pl.poznan.put.omw.filters.MoveFilter import kotlin.math.abs class GameFilter(private val engineResult: List<EngineResult>, private val filters: List<MoveFilter>) { init { //the best move (the biggest number of CP) at the beginning engineResult.sortedByDescending { it.centipaws } } /** * Returns a list of bestmoves that match all filters with other results from the engine with the same moveID as bestmove. */ fun filterInterestingMoves(depth: Int, minCPBetweenBest: Int): List<Pair<EngineResult, List<EngineResult>>> { val interestingMoves = arrayListOf<Pair<EngineResult, List<EngineResult>>>() engineResult .filter { it.isBestMove && depth == it.depth } .forEach {bestMove -> run { if(bestMove.secondBestIndex == -2 || abs(bestMove.centipaws) - abs(engineResult[bestMove.secondBestIndex].centipaws) > minCPBetweenBest) { // difference between bestmove and second bestmove is greater then minCPBetweenBest // or there was only one result from the engine // so we can apply filters var matchesAllFilters = true for (filter in filters) { matchesAllFilters = matchesAllFilters && filter.match(bestMove.fen, bestMove.getMove()) } if(matchesAllFilters) { val worstThenBestmoveResults = engineResult .filter { it.moveID == bestMove.moveID && it.getMove() != bestMove.getMove()} // sort them by cp depending on the player's color if(bestMove.isWhitePlayerPlaying) { worstThenBestmoveResults.sortedByDescending { it.centipaws } } else { worstThenBestmoveResults.sortedBy { it.centipaws } } interestingMoves.add(Pair(bestMove, worstThenBestmoveResults)) } } } } return interestingMoves } // private fun getSecondBest(bestIndex: Int): EngineResult { // for (i in bestIndex downTo 0) // { // if (engineResult[i].isBestMove) // { // // result with bestmove as the first move should be before bestmove in the result list // for (j in i-1 downTo lastBest+1) // { // if(results[j].getMove() == results[i].getMove()) // { // // result with the same move as bestmove is found // // assign cp to bestmove // results[i].centipaws = results[j].centipaws // results[i].depth = results[j].depth // break // } // } // lastBest = i // } // } // } /** * Returns at most numberOfBestResults engine's results. */ fun getNBestResults(numberOfBestResults: Int) = engineResult .filter { !it.isBestMove } .take(numberOfBestResults) /** * Returns at most numberOfBestResults best moves in UCI format returned by engine. */ fun getNBestMoves(numberOfBestMoves: Int) = getNBestResults(numberOfBestMoves) .map { it.getMove() } }
0
Kotlin
0
0
d788cd791d5b9b695c9501ca395ed1b3bd273279
3,951
ChessStrongMovesExtractor
Apache License 2.0
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day14.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues import nl.jstege.adventofcode.aoccommon.utils.extensions.transformTo /** * * @author <NAME> */ class Day14 : Day(title = "Reindeer Olympics") { private companion object Configuration { private const val TRAVEL_TIME = 2503 private const val INPUT_PATTERN_STRING = """\w+ can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds\.""" private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex() private const val SPEED_INDEX = 1 private const val TRAVEL_TIME_INDEX = 2 private const val REST_TIME_INDEX = 3 private val PARAM_INDICES = intArrayOf(SPEED_INDEX, TRAVEL_TIME_INDEX, REST_TIME_INDEX) } override fun first(input: Sequence<String>) = input .parse() .asSequence() .map { it.travel(TRAVEL_TIME).distanceTravelled } .max()!! override fun second(input: Sequence<String>) = (1..TRAVEL_TIME) .transformTo(input.parse().toList()) { rs, i -> rs.onEach { it.travel(i) } .filter { r -> r.distanceTravelled == rs.map { it.distanceTravelled }.max() } .forEach { it.score++ } } .asSequence() .map { it.score } .max()!! private fun Sequence<String>.parse() = this .map { it.extractValues(INPUT_REGEX, *PARAM_INDICES) } .map { (speed, travelTime, restTime) -> Reindeer(speed.toInt(), travelTime.toInt(), restTime.toInt()) } private data class Reindeer(val speed: Int, val travelTime: Int, val restTime: Int) { var distanceTravelled = 0 var score = 0 fun travel(currentTime: Int): Reindeer { distanceTravelled = speed * (currentTime / (travelTime + restTime) * travelTime + (Math.min(currentTime % (travelTime + restTime), travelTime))) return this } } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,106
AdventOfCode
MIT License
Day2/src/main/kotlin/de/zweistein2/Main.kt
Zweistein2
575,020,168
false
{"Kotlin": 15154}
package de.zweistein2 import de.zweistein2.MatchOutcome.Companion.leadsTo import de.zweistein2.Shape.Companion.against import mu.KotlinLogging private val logger = KotlinLogging.logger {} private val monitoring = LoggerMonitoring() fun main() { val content = InputHandler.readInput("/input.txt") monitoring.withTimer { val finalScoreMyMethod = content.split("\n") .map { Shape.of(it[0]) to Shape.of(it[2]) } .map { it to (it.first against it.second)} .map { it.first.second.value + it.second.value } .reduce { prevCal, cal -> prevCal + cal } val finalScoreElfMethod = content.split("\n") .map { Shape.of(it[0]) to MatchOutcome.of(it[2]) } .map { it to (it.first leadsTo it.second)} .map { it.first.second.value + it.second.value } .reduce { prevCal, cal -> prevCal + cal } logger.debug { "The final score after all rounds with my method is $finalScoreMyMethod" } logger.debug { "The final score after all rounds with the elves method is $finalScoreElfMethod" } } } enum class Shape(val value: Int) { ROCK(1), SCISSOR(3), PAPER(2); companion object { infix fun Shape.against(opponent: Shape): MatchOutcome { return if((this.ordinal + 1) % 3 == opponent.ordinal) { MatchOutcome.LOSS } else if(this.ordinal == opponent.ordinal) { MatchOutcome.DRAW } else { MatchOutcome.WIN } } fun of(value: Char): Shape { return when(value) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSOR else -> throw IllegalArgumentException("Must be one of 'A', 'B', 'C', 'X', 'Y' or 'Z'") } } } } enum class MatchOutcome(val value: Int) { WIN(6), LOSS(0), DRAW(3); companion object { infix fun Shape.leadsTo(wantedOutcome: MatchOutcome): Shape { return if((this.ordinal + 2) % 3 == wantedOutcome.ordinal) { Shape.ROCK } else if(this.ordinal == wantedOutcome.ordinal) { Shape.PAPER } else { Shape.SCISSOR } } fun of(value: Char): MatchOutcome { return when(value) { 'X' -> LOSS 'Y' -> DRAW 'Z' -> WIN else -> throw IllegalArgumentException("Must be one of 'A', 'B', 'C', 'X', 'Y' or 'Z'") } } } }
0
Kotlin
0
2
baf40d39806fd5dde0a63f5075c581a6c8f56a62
2,598
AoC22
Apache License 2.0
src/day02/Day02.kt
PoisonedYouth
571,927,632
false
{"Kotlin": 27144}
package day02 import readInput fun main() { fun part1(input: List<String>): Int { return input.sumOf { when (it) { "A X" -> 1 + 3 "A Y" -> 2 + 6 "A Z" -> 3 + 0 "B X" -> 1 + 0 "B Y" -> 2 + 3 "B Z" -> 3 + 6 "C X" -> 1 + 6 "C Y" -> 2 + 0 "C Z" -> 3 + 3 else -> error("Invalid input!") }.toInt() } } fun part2(input: List<String>): Int { return input.sumOf { when (it) { "A X" -> 3 + 0 "A Y" -> 1 + 3 "A Z" -> 2 + 6 "B X" -> 1 + 0 "B Y" -> 2 + 3 "B Z" -> 3 + 6 "C X" -> 2 + 0 "C Y" -> 3 + 3 "C Z" -> 1 + 6 else -> error("Invalid input!") }.toInt() } } val input = readInput("day02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
dbcb627e693339170ba344847b610f32429f93d1
1,063
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/ctci/chapterone/CheckPermutation.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package ctci.chapterone // 1.2 - page 90 // In Kotlin given two strings, write a method to decide if one is a permutation of the other. //To decide if one string is a permutation of another using a hash table in Kotlin, you can create a mutable map to // store the number of occurrences of each character in the first string, and then iterate through the second string // and decrement the count for each character in the map. If a character is not in the map or its count is already 0, // it means that the character is not present in the first string or it appears more times in the second string than // in the first, so the strings are not permutations of each other. fun main(){ val testCases = listOf( Pair("abcdef", "fedcba"), Pair("abcdea", "aedcba"), Pair("aaa", "aaa"), Pair("", ""), Pair("a", "b") ) for (testCase in testCases) { println("isPermutation(${testCase.first}, ${testCase.second}) = ${isPermutation(testCase.first, testCase.second)}") } } fun isPermutation(str1: String, str2: String): Boolean { if (str1.length != str2.length) { return false } val charCounts = mutableMapOf<Char, Int>() for (c in str1) { charCounts[c] = charCounts.getOrDefault(c, 0) + 1 } for (c in str2) { val count = charCounts.getOrDefault(c, 0) if (count == 0) { return false } charCounts[c] = count - 1 } return true } //The time complexity of this function is O(n), where n is the total number of characters in the two strings, since the // function iterates through each character in the two strings once and performs a constant time operation // (getting or incrementing the count for a character in the map) on each character. The space complexity is also O(n), // since the map used to store the character counts may contain up to n elements if both strings have all // unique characters.
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
1,954
dsa-kotlin
MIT License
src/main/kotlin/leetcode/uber/SlidingPuzzle.kt
Magdi
390,731,717
false
null
package leetcode.uber import java.util.* /** * https://leetcode.com/problems/sliding-puzzle/ * * *BFS O(N) N = number of valid states to the puzzle */ class SlidingPuzzle { fun slidingPuzzle(board: Array<IntArray>): Int { val initBoard = Board(listOf(1, 2, 3, 4, 5, 0)) val q: Queue<Board> = LinkedList() q.offer(initBoard) var level = 0 val visited = hashMapOf<Board, Int>() while (q.size > 0) { val n = q.size for (i in 0 until n) { val cur = q.poll() visited[cur] = level cur.getMoves().forEach { newBoard -> if (!visited.contains(newBoard)) { q.offer(newBoard) } } } level++ } return visited[board.toBoard()] ?: -1 } fun Array<IntArray>.toBoard(): Board { val list = mutableListOf<Int>() this.forEach { it.forEach { num -> list.add(num) } } return Board(list) } data class Board(private val grid: List<Int>) { private val adjMap = mapOf( 0 to listOf(1, 3), 1 to listOf(0, 2, 4), 2 to listOf(1, 5), 3 to listOf(0, 4), 4 to listOf(3, 5, 1), 5 to listOf(2, 4) ) fun getMoves(): List<Board> { val zeroInd = grid.indexOf(0) val result = mutableListOf<Board>() adjMap[zeroInd]!!.map { adj -> val newGrid = grid.toMutableList() newGrid[zeroInd] = grid[adj] newGrid[adj] = 0 result.add(Board(newGrid)) } return result } } }
0
Kotlin
0
0
63bc711dc8756735f210a71454144dd033e8927d
1,794
ProblemSolving
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2017/Day10.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 /** * AoC 2017, Day 10 * * Problem Description: http://adventofcode.com/2017/day/10 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day10/ */ class Day10(input: String, part1: Boolean, ringSize: Int = 256) { private val magicLengths = listOf(17, 31, 73, 47, 23) private val lengths = if (part1) parsePart1Input(input) else parsePart2Input(input) private val ring = IntArray(ringSize) { it } fun solvePart1(): Int { runForLengths() return ring[0] * ring[1] } fun solvePart2(): String { runForLengths(64) return ring .toList() .chunked(16) .joinToString("") { it.xor().toHex(2) } } private fun runForLengths(iterations: Int = 1) { var position = 0 var skip = 0 repeat(iterations) { lengths.forEach { length -> reverseSection(position, length) position = (position + length + skip) % ring.size skip += 1 } } } private fun reverseSection(from: Int, length: Int) { var fromIdx = from % ring.size var toIdx = (fromIdx + length - 1) % ring.size repeat(length / 2) { ring.swap(fromIdx, toIdx) fromIdx = fromIdx.inc() % ring.size toIdx = toIdx.dec().takeIf { it >= 0 } ?: ring.size - 1 } } private fun parsePart1Input(input: String): IntArray = input.split(",").map { it.toInt() }.toIntArray() private fun parsePart2Input(input: String): IntArray = (input.map { it.toInt() } + magicLengths).toIntArray() }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
1,724
advent-2017-kotlin
MIT License
src/main/kotlin/g2401_2500/s2449_minimum_number_of_operations_to_make_arrays_similar/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2449_minimum_number_of_operations_to_make_arrays_similar // #Hard #Array #Sorting #Greedy #2023_07_05_Time_791_ms_(100.00%)_Space_61.9_MB_(100.00%) class Solution { fun makeSimilar(nums: IntArray, target: IntArray): Long { val evenNums = ArrayList<Int>() val oddNums = ArrayList<Int>() val evenTar = ArrayList<Int>() val oddTar = ArrayList<Int>() nums.sort() target.sort() for (i in nums.indices) { if (nums[i] % 2 == 0) { evenNums.add(nums[i]) } else { oddNums.add(nums[i]) } if (target[i] % 2 == 0) { evenTar.add(target[i]) } else { oddTar.add(target[i]) } } var countPositiveIteration: Long = 0 var countNegativeIteration: Long = 0 for (i in evenNums.indices) { val num = evenNums[i] val tar = evenTar[i] val diff = num.toLong() - tar val iteration = diff / 2 if (diff > 0) { countNegativeIteration += iteration } else if (diff < 0) { countPositiveIteration += Math.abs(iteration) } } for (i in oddNums.indices) { val num = oddNums[i] val tar = oddTar[i] val diff = num.toLong() - tar val iteration = diff / 2 if (diff > 0) { countNegativeIteration += iteration } else if (diff < 0) { countPositiveIteration += Math.abs(iteration) } } val totalDifference = countPositiveIteration - countNegativeIteration return if (totalDifference == 0L) countPositiveIteration else countPositiveIteration + Math.abs(totalDifference) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,851
LeetCode-in-Kotlin
MIT License
src/Day10.kt
kpilyugin
572,573,503
false
{"Kotlin": 60569}
import kotlin.math.abs fun main() { fun run(input: List<String>) = buildList { var x = 1 add(x) input.forEach { if (it == "noop") { add(x) } else { add(x) val change = it.split(" ")[1].toInt() x += change add(x) } } } fun part1(input: List<String>): Int { val values = run(input) var res = 0 for (i in 20..220 step 40) { res += i * values[i - 1] } return res } fun part2(input: List<String>) { val positions = run(input) val cycles = 240 val line = CharArray(cycles) { '.' } for (i in 0 until cycles) { if (abs(positions[i] - i % 40) <= 1) { line[i] = '#' } } val image = String(line).chunked(40).joinToString(separator = "\n") println(image) } val testInput = readInputLines("Day10_test") check(part1(testInput), 13140) println(part2(testInput)) val input = readInputLines("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7f0cfc410c76b834a15275a7f6a164d887b2c316
1,178
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2016/calendar/day04/Day04.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2016.calendar.day04 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory class Day04 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::room) { input -> input.filter { it.isValid }.sumOf { it.sectorId } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::room) { input -> input.filter { it.isValid }.firstOrNull { it.decrypt() == NORTHPOLE_ROOM_NAME }?.sectorId } private fun room(line: String): Room { val encryptedData = line.substringBeforeLast("-").split("-") val sectorId = line.substringAfterLast("-").substringBefore("[").toInt() val checksum = line.substringAfter("[").dropLast(1) val unsortedCharData = mutableMapOf<Char, Int>() encryptedData.forEach { word -> word.forEach { c -> unsortedCharData.merge(c, 1, Int::plus) } } val sortedCounters = unsortedCharData.map { Counter(it.key, it.value) }.sortedDescending() return Room(encryptedData, sortedCounters, sectorId, checksum) } data class Room(val encryptedData: List<String>, val sortedCounters: List<Counter>, val sectorId: Int, val checksum: String) { fun decrypt(): String { return encryptedData.joinToString(" ") { word -> word.map { c -> ((c.code - ASCII_TABLE_SHIFT + sectorId) % ALPHABET_LENGTH + ASCII_TABLE_SHIFT).toChar() }.joinToString("") } } val isValid = sortedCounters.take(5).map { it.c }.joinToString("") == checksum } data class Counter(val c: Char, val count: Int) : Comparable<Counter> { override fun compareTo(other: Counter) = when (val countComparison = this.count.compareTo(other.count)) { 0 -> -this.c.compareTo(other.c) // invert the comparison, as we want descending order else -> countComparison } } companion object { const val ASCII_TABLE_SHIFT = 97 const val ALPHABET_LENGTH = 26 const val NORTHPOLE_ROOM_NAME = "northpole object storage" } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,116
advent-of-code
MIT License
src/main/kotlin/adventofcode/day23.kt
Kvest
163,103,813
false
null
package adventofcode import java.io.File import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main(args: Array<String>) { first23(File("./data/day23.txt").readLines()) second23(File("./data/day23.txt").readLines() ) } private val nanobotRegex = Regex("pos=<(-?\\d+),(-?\\d+),(-?\\d+)>, r=(\\d+)") fun first23(data: List<String>) { var radius = IntArray(data.size) { 0 } val pos = Array(data.size) { i -> val (x, y, z, r) = nanobotRegex.find(data[i])!!.destructured radius[i] = r.toInt() XYZ(x.toInt(), y.toInt(), z.toInt()) } var maxR = radius[0] var maxI = 0 radius.forEachIndexed { i, v -> if (v > maxR) { maxR = v maxI = i } } val count = pos.filter { it.manhattanDistance(pos[maxI]) <= maxR }.count() println(count) } private class Nanobot(val c: XYZ, val r: Int) fun second23(data: List<String>) { var xB = Int.MAX_VALUE var xE = Int.MIN_VALUE var yB = Int.MAX_VALUE var yE = Int.MIN_VALUE var zB = Int.MAX_VALUE var zE = Int.MIN_VALUE val allNanobots = Array(data.size) { i -> val (xS, yS, zS, rS) = nanobotRegex.find(data[i])!!.destructured val xC = xS.toInt() val yC = yS.toInt() val zC = zS.toInt() val r = rS.toInt() xB = min(xB, xC - r) xE = max(xE, xC + r) yB = min(yB, yC - r) yE = max(yE, yC + r) zB = min(zB, zC - r) zE = max(zE, zC + r) Nanobot(XYZ(xC, yC, zC), r) } var maxMatches = 0 var dist = 100000000 val best = mutableListOf<XYZ>() while (true) { for (x in xB..xE step dist) { for (y in yB..yE step dist) { for (z in zB..zE step dist) { val probe = XYZ(x, y, z) var inRange = 0 //count nanobots in range of probe allNanobots.forEach { nb -> if (probe.manhattanDistance(nb.c) <= nb.r) { ++inRange } } when { inRange == maxMatches -> best.add(probe) inRange > maxMatches -> { maxMatches = inRange best.clear() best.add(probe) } } } } } //get most perspective point(close to 0,0,0) val p = best.minBy { abs(it.x) + abs(it.y) + abs(it.z) }!! xB = p.x - dist xE = p.x + dist yB = p.y - dist yE = p.y + dist zB = p.z - dist zE = p.z + dist dist /= 10 if (dist == 0) { println(p) println(p.x + p.y + p.z) break } } }
0
Kotlin
0
0
d94b725575a8a5784b53e0f7eee6b7519ac59deb
2,896
aoc2018
Apache License 2.0
Problems/Algorithms/1129. Shortest Path with Alternating Colors/ShortestAlternatingPath.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun shortestAlternatingPaths(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray { val redGraph: MutableMap<Int, MutableList<Int>> = mutableMapOf() for (edge in redEdges) { if (!redGraph.containsKey(edge[0])) { redGraph[edge[0]] = mutableListOf() } redGraph[edge[0]]!!.add(edge[1]) } val blueGraph: MutableMap<Int, MutableList<Int>> = mutableMapOf() for (edge in blueEdges) { if (!blueGraph.containsKey(edge[0])) { blueGraph[edge[0]] = mutableListOf() } blueGraph[edge[0]]!!.add(edge[1]) } val visited: HashSet<String> = hashSetOf() val results = IntArray(n) { -1 } val queue = ArrayDeque<Pair<Int, String>>() queue.add(Pair(0, "null")) var steps = 0 while (!queue.isEmpty()) { val length = queue.size for (i in 0..length-1) { val curr = queue.removeFirst() val node = curr.first val color = curr.second val key = node.toString() + "->" + color if (visited.contains(key)) { continue } visited.add(key) if (results[node] == -1) { results[node] = steps } if (color == "null" || color == "red") { if (blueGraph[node] != null) { for (neighbor in blueGraph[node]!!) { queue.add(Pair(neighbor, "blue")) } } } if (color == "null" || color == "blue") { if (redGraph[node] != null) { for (neighbor in redGraph[node]!!) { queue.add(Pair(neighbor, "red")) } } } } steps++ } return results } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
2,177
leet-code
MIT License
src/main/kotlin/com/hopkins/aoc/day21/main.kt
edenrox
726,934,488
false
{"Kotlin": 88215}
package com.hopkins.aoc.day21 import com.hopkins.aoc.day17.Point import java.io.File const val debug = true const val part = 1 /** Advent of Code 2023: Day 21 */ fun main() { // Step 1: Read the file input val lines: List<String> = File("input/input21-ex1.txt").readLines() if (debug) { println("Step 1: Read file") println("=======") println(" num lines: ${lines.size}") } // Step 2: Build the map var startPoint: Point = Point.of(-1, -1) val mapHeight = lines.size val mapWidth = lines[0].length val mapSize = Point.of(mapWidth, mapHeight) val rocks: Set<Point> = lines.flatMapIndexed {y, line -> line.mapIndexedNotNull { x, c -> if (c == '#') { Point.of(x, y) } else { if (c == 'S') { startPoint = Point.of(x, y) } null } } }.toSet() require(startPoint.x >= 0) require(startPoint.y >= 0) if (debug) { println("Step 2: Build the map") println("=======") println(" map size: $mapSize") println(" start: $startPoint") println(" num rocks: ${rocks.size}") } var current = setOf(startPoint) for (i in 1..50) { val next = current.flatMap { point -> directions.map { direction -> point.add(direction) }} .map { point -> if (point.x == -1) { Point.of(point.x + mapWidth, point.y) } else if (point.y == -1) { Point.of(point.x, point.y + mapWidth) } else if (point.x == mapWidth) { Point.of(0, point.y) } else if (point.y == mapHeight) { Point.of(point.x, 0) } else { point } } .filterNot { point -> rocks.contains(point) } .toSet() println("Step $i:") printMap(mapSize, rocks, next) current = next } println("Num Plots: ${current.size}") } fun printMap(mapSize: Point, rocks: Set<Point>, current: Set<Point>) { for (y in 0 until mapSize.y) { for (x in 0 until mapSize.x) { val point = Point.of(x, y) if (rocks.contains(point)) { print("#") } else if (current.contains(point)) { print("O") } else { print(".") } } println() } } val directions = listOf( Point.of(-1, 0), Point.of(1, 0), Point.of(0, -1), Point.of(0, 1) )
0
Kotlin
0
0
45dce3d76bf3bf140d7336c4767e74971e827c35
2,741
aoc2023
MIT License
algorithms/ciphers/AffineCipher.kt
AllAlgorithms
149,472,181
false
null
import kotlin.math.max import kotlin.test.assertEquals import kotlin.test.assertNotEquals import kotlin.test.assertTrue fun main(args: Array<String>) { val alphabet = List('z' - 'a' + 1) { 'a' + it }.toSet() val input = "lorem ipsum dolor sit amet, consectetur adipiscing elit." val expected = "mpsfn jqtvn epmps tju bnfu, dpotfdufuvs bejqjtdjoh fmju." val output = encrypt(input, alphabet, 1, 1) assertEquals(expected, output) val decoded = decrypt(output, alphabet, 1, 1) assertEquals(input, decoded) } val encrypt = affineGenerator { a, b, m, value -> ((a * value + b) % m) } val decrypt = affineGenerator { a, b, m, value -> (value - b) / a % m } fun affineGenerator(transform: (a: Int, b: Int, m: Int, value: Int) -> Int) = fun(input: String, alphabet: Set<Char>, a: Int, b: Int): String { assertNotEquals(0, alphabet.size, "Alphabet empty") assertTrue(a > 0, "a is not greater than zero") assertTrue(b > 0, "b is not greater than zero") assertTrue(checkCoprime(alphabet.size, a), "'a' is not coprime to alphabet size") return String(CharArray(input.length) { val old = alphabet.indexOf(input[it].toLowerCase()) if (old == -1) { input[it] } else { val new = transform(a, b, alphabet.size, old) alphabet.elementAt(new) } }) } fun checkCoprime(aP: Int, bP: Int): Boolean { var a = aP var b = bP while (a != 0 && b != 0) { if (a > b) { a -= b } else { b -= a } } return max(a, b) == 1 }
1
Kotlin
5
8
210738a3a79473a65048e339223f012faca46d19
1,725
kotlin
MIT License
simpleCykParser/src/main/kotlin/org/michaeldadams/simpleCykParser/grammar/Properties.kt
adamsmd
668,129,808
false
null
/** * Properties that can be computed about lex rules, parse rules and grammars. * * Note that not everything here is actually used for parsing. For example, * some things like [undefinedSymbols] are used for checking if a grammar is * valid. */ package org.michaeldadams.simpleCykParser.grammar /** * Get the terminals defined by a [LexRules]. * * @receiver the lexing rules to get the defined terminals for * @return all the terminals defined in the given lexing rules */ fun LexRules.terminals(): Set<Terminal> = this.terminalRules.map { it.terminal }.toSet() /** * Get the nonterminals defined by a [ParseRules]. * * @receiver the parse rules to get the defined nonterminals for * @return all the nonterminals defined in the given parse rules */ fun ParseRules.nonterminals(): Set<Nonterminal> = this.productionMap.keys fun ParseRules.nonterminalNames(): Set<String> = this.nonterminals().map { it.name }.toSet() /** * Get the symbols (terminals and nonterminals) defined by a [Grammar]. * * @receiver the grammar to get the defined symbols for * @return all the symbols defined in the given grammar */ fun Grammar.symbols(): Set<Symbol> = this.lexRules.terminals() + this.parseRules.nonterminals() /** * Find productions that use undefined symbols. * * In a well-formed grammar, this function will return the empty set. * * @receiver the grammar to get the undefined symbols for * @param symbols the symbols to assume as defined * @return triples of the left-hand size ([Nonterminal]), right-hand side * ([Rhs]) and the position ([Int]) of the undefined symbol in the right-hand * side */ fun ParseRules.undefinedSymbols(symbols: Set<Symbol>): Set<Triple<Nonterminal, Rhs, Int>> = this.productionMap.flatMap { (lhs, rhsSet) -> rhsSet.flatMap { rhs -> rhs.elements.mapIndexedNotNull { i, element -> if (element.symbol in symbols) null else Triple(lhs, rhs, i) } } }.toSet() /** * Get the nonterminals that have no production. * * @receiver the parse rules to get the productionless nonterminals for * @return the nonterminals that have no production in the parse rules */ fun ParseRules.productionlessNonterminals(): Set<Nonterminal> = this.productionMap.filter { it.value.isEmpty() }.map { it.key }.toSet() /** * Get all the symbols used in the right-hand sides ([Rhs]) of a [ParseRules]. * * @receiver the parse rules to get the used symbols for * @return all the symbols used in the right-hand sides of the given parse rules */ fun ParseRules.usedSymbols(): Set<Symbol> = this.productionMap.values.flatten().flatMap { rhs -> rhs.elements.map { it.symbol } }.toSet() + this.start /** * Find the symbols that are defined but not used in a [Grammar]. * * @receiver the grammar to compute the unused symbols for * @return the symbols that are not used anywhere in a grammar */ fun Grammar.unusedSymbols(): Set<Symbol> = this.symbols() - this.parseRules.usedSymbols()
0
Kotlin
0
0
23f1485bc0e56c9f6fa438053fc526066cf5a7f4
2,970
simpleCykParser
MIT License
src/main/kotlin/io/github/pshegger/aoc/y2015/Y2015D13.kt
PsHegger
325,498,299
false
null
package io.github.pshegger.aoc.y2015 import io.github.pshegger.aoc.common.BaseSolver import io.github.pshegger.aoc.common.extractAll import io.github.pshegger.aoc.common.permutations import io.github.pshegger.aoc.common.toExtractor class Y2015D13 : BaseSolver() { override val year = 2015 override val day = 13 private val extractor = "%s would %s %d happiness units by sitting next to %s.".toExtractor() private val input by lazy { parseInput() } private val people by lazy { input.map { it.who }.toSet() } private val changes by lazy { input.associate { Pair("${it.who}:${it.neighbour}", it.change) } } override fun part1(): Int = people.solveForChanges(changes) override fun part2(): Any? { val peopleWithMe = people + MY_NAME val changesWithMe = changes + people.flatMap { listOf( Pair("$it:$MY_NAME", 0), Pair("$MY_NAME:$it", 0) ) } return peopleWithMe.solveForChanges(changesWithMe) } private fun Set<String>.solveForChanges(changes: Map<String, Int>) = permutations().maxOf { sitting -> sitting.mapIndexed { i, who -> val n1 = if (i > 0) sitting[i - 1] else sitting.last() val n2 = if (i < sitting.size - 1) sitting[i + 1] else sitting.first() changes.getOrDefault("$who:$n1", 0) + changes.getOrDefault("$who:$n2", 0) }.sum() } private fun parseInput() = readInput { readLines() .extractAll(extractor) { (who, dir, amount, neighbor) -> val sign = if (dir == "gain") 1 else -1 HappinessChanges( who, neighbor, sign * amount.toInt() ) } } private data class HappinessChanges(val who: String, val neighbour: String, val change: Int) companion object { private const val MY_NAME = "pshegger" } }
0
Kotlin
0
0
346a8994246775023686c10f3bde90642d681474
1,994
advent-of-code
MIT License
src/main/kotlin/me/peckb/aoc/_2018/calendar/day10/Day10.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2018.calendar.day10 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import kotlin.Int.Companion.MAX_VALUE import kotlin.Int.Companion.MIN_VALUE import kotlin.math.abs import kotlin.math.max import kotlin.math.min class Day10 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::day10) { input -> val points = input.toList() val (area, _) = findWord(points) area.joinToString("\n") { it.joinToString("") } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::day10) { input -> val points = input.toList() val (_, time) = findWord(points) time } private fun day10(line: String): Point { // position=< 9, 1> velocity=< 0, 2> val (x, y) = line.substringBefore("> velocity") .substringAfter("<") .split(",") .map { it.trim() } .map { it.toInt() } val (xVel, yVel) = line.substringAfter("velocity=<") .dropLast(1) .split(",") .map { it.trim() } .map { it.toInt() } return Point(x, y, xVel, yVel) } private fun findWord(points: List<Point>): Pair<Array<Array<Char>>, Int> { var currentDistanceSum = points.findDistance() var lastDistanceSum = currentDistanceSum + 1 var time = 0 while(currentDistanceSum < lastDistanceSum) { points.forEach { it.tick() } lastDistanceSum = currentDistanceSum currentDistanceSum = points.findDistance() time++ } var maxX = MIN_VALUE var maxY = MIN_VALUE var minY = MAX_VALUE var minX = MAX_VALUE points.forEach { it.tickBackwards() maxX = max(maxX, it.x) maxY = max(maxY, it.y) minX = min(minX, it.x) minY = min(minY, it.y) } val area = Array(maxY - minY + 1) { Array (maxX - minX + 1) { '.' } } points.forEach { area[it.y - minY][it.x - minX] = '#' } return area to (time - 1) } private fun List<Point>.findDistance(): Long { return sumOf { p1 -> val distanceSums = sumOf { p2 -> p1.distanceFrom(p2) } val average = distanceSums / size average } } data class Point(var x: Int, var y: Int, val xVel: Int, val yVel: Int) { fun tick() { x += xVel y += yVel } fun tickBackwards() { x -= xVel y -= yVel } fun distanceFrom(point: Point): Long { return (abs(x - point.x) + abs(y - point.y)).toLong() } } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,536
advent-of-code
MIT License
src/y2021/d01/Day01.kt
AndreaHu3299
725,905,780
false
{"Kotlin": 31452}
package y2021.d01 import println import readInput fun main() { fun part1(input: List<String>): Int { // take 2 elements in input at a time return input.windowed(2, 1, false).map { val (a, b) = it if (b.toInt() > a.toInt()) 1 else 0 }.sum() } fun part2(input: List<String>): Int { return input .map { it.toInt() } .windowed(3, 1, false).map { it.sum() } .windowed(2, 1, false).map { val (a, b) = it if (b > a) 1 else 0 } .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("y2021/d01/test") part1(testInput).println() // check(part1(testInput) == 7) val input = readInput("y2021/d01/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e
915
aoc
Apache License 2.0
src/Day01.kt
gutyoh
433,854,926
false
null
fun main() { fun part1(input: List<String>): Int { // return input.size var counter = 0 val numberList = input.map { it.toInt() } for (i in numberList.indices) { // if it's the last number end the loop if (i == numberList.size - 1) { break } if (numberList[i+1] > numberList[i]) { counter++ } } return counter } fun part2(input: List<String>): Int { // return input.size var counter = 0 val numberList = input.map { it.toInt() } for (i in numberList.indices) { // if it's the last number end the loop if (i == numberList.size - 3) { break } if (numberList[i+1] + numberList[i+2] + numberList[i+3] > numberList[i] + numberList[i+1] + numberList[i+2]) { counter++ } } return counter } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") // check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3d27c7aa6bf4d07f10d20d6dd05d7fb87f6cae4e
1,229
advent-of-code-kotlin-template
Apache License 2.0
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p09/Leet909.kt
artemkaxboy
513,636,701
false
{"Kotlin": 547181, "Java": 13948}
package com.artemkaxboy.leetcode.p09 import com.artemkaxboy.leetcode.LeetUtils import java.util.LinkedList /** * Accepted * * Runtime: 335ms Beat: 33.33% * Memory: 39.5MB Beat: 33.33% */ class Leet909 { private lateinit var board: Array<IntArray> private val explored = HashSet<Square>() private val toExplore = LinkedList<Square>() private var size = 0 private var lastRow = 0 private var lastCol = 0 private var lastBusinessSquare = 0 fun snakesAndLadders(board: Array<IntArray>): Int { this.board = board size = board.size lastBusinessSquare = size * size lastRow = size - 1 lastCol = lastRow val start = Square(0, lastRow, 0, this::numberOf) toExplore.push(start) return findShortestWay() } private fun findShortestWay(): Int { while (toExplore.isNotEmpty()) { val current = toExplore.pop() if (explored.add(current)) { if (current.number == lastBusinessSquare) return current.moves // println("added: $current") explore(current).forEach { toExplore.add(it) } } } return -1 } private fun numberOf(square: Square): Int { val rowBusinessNumber = size - 1 - square.y val colBusinessNumber = if (rowBusinessNumber % 2 == 0) { square.x } else { size - 1 - square.x } return 1 + colBusinessNumber + rowBusinessNumber * size } private fun businessMove(square: Square, move: Int, count: Boolean = true): Square { return minOf(square.number + move, lastBusinessSquare) .let { number -> val preLast = number - 1 val y = lastCol - preLast / size val x = if ((lastCol - y) % 2 == 0) preLast % size else lastCol - (preLast % size) square.copy(x = x, y = y, moves = if (count) square.moves + 1 else square.moves, parent = square) } } private fun explore(square: Square): Collection<Square> { return (1..6).mapNotNull { businessMove(square, it) } .map { val hack = board[it.y][it.x] if (hack == -1) it else businessMove(it, hack - it.number, false) } .filter { !explored.contains(it) } } data class Square(val x: Int, val y: Int, val moves: Int, val numberCalc: (Square) -> Int, val parent: Square? = null) { var number = 0 get(): Int { if (field == 0) { field = numberCalc(this) } return field } override fun equals(other: Any?): Boolean { other as Square if (x != other.x) return false return y == other.y } override fun hashCode(): Int { var result = x result = 31 * result + y return result } override fun toString(): String { return "Square(x=$x, y=$y, moves=$moves, number=$number)" } } companion object { @JvmStatic fun main(args: Array<String>) { val testCase1 = "[[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]" to 4 doWork(testCase1) val testCase2 = "[[-1,-1],[-1,3]]" to 1 doWork(testCase2) } private fun doWork(data: Pair<String, Int>) { val solution = Leet909() val prepared = data.first.split("],[").map { LeetUtils.stringToIntArray(it) }.toTypedArray() val result = solution.snakesAndLadders(prepared) println("Data: ${data.first}") println("Expected: ${data.second}") println(" Result: $result\n") } } }
0
Kotlin
0
0
516a8a05112e57eb922b9a272f8fd5209b7d0727
3,956
playground
MIT License
src/day15/fr/Day15_2.kt
BrunoKrantzy
433,844,189
false
{"Kotlin": 63580}
package day15.fr import java.io.File private fun readChars(): CharArray = readLn().toCharArray() private fun readLn() = readLine()!! // string line private fun readSb() = StringBuilder(readLn()) private fun readInt() = readLn().toInt() // single int private fun readLong() = readLn().toLong() // single long private fun readDouble() = readLn().toDouble() // single double private fun readStrings() = readLn().split(" ") // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of ints private fun readLongs() = readStrings().map { it.toLong() } // list of longs private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles private fun readIntArray() = readStrings().map { it.toInt() }.toIntArray() // Array of ints private fun readLongArray() = readStrings().map { it.toLong() }.toLongArray() // Array of longs fun incRem(str:String) : String { val strRet = StringBuilder() for (j in str.indices) { var n = str[j].code - 48 if (n + 1 > 9) n = 1 else n += 1 strRet.append(n.toString()) } return strRet.toString() } fun traiteListe(lst:MutableList<String>) : MutableList<String> { var liste = lst for (nLig in 0 until liste.size) { val vLinc = incRem(liste[nLig]) liste[nLig] = vLinc } return liste } fun main() { var rep = 0L var vInGrille = day11.fr.readInput("test15") as MutableList //var vInGrille = day11.fr.readInput("input15") as MutableList val vH = vInGrille.size val vL = vInGrille[0].length val vTabGrille = Array (vH * vH) { Array(vL * vH) { -1 } } var lstDesListes = mutableListOf<MutableList<String>>() lstDesListes.add(vInGrille) var lstWork = vInGrille.toMutableList() for (l in 2..vH * 2) { var newListe = traiteListe(lstWork) lstDesListes.add(newListe) lstWork = newListe.toMutableList() } var lGlob = 0 var cGlob = 0 var offset = 0 for (nLst in 0 .. 4) { for (ligne in 0 until vH) { for (colonne in 0 until vL) { val lstTraitee = lstDesListes[colonne + offset] var lT = lstTraitee[ligne] var lstCol = mutableListOf<Int>() lT.forEach { lstCol.add(it.code - 48) } for (col in 0 until vL) { vTabGrille[lGlob][cGlob] = lstCol[col] cGlob++ } } cGlob = 0 lGlob++ } offset++ } val lstVertex = mutableListOf<Triple<Int, Int, Int>>() var nNode = 0 // lecture tableau for (lig in 0 until (vH * 5)) { for (col in 0 until (vL * 5)) { nNode = col if (lig == 0) { if (col == 0) { lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1])) lstVertex.add(Triple(nNode, nNode+(vL * 5), vTabGrille[lig+1][col])) } else if (col == (vL * 5) - 1) { lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1])) lstVertex.add(Triple(nNode, nNode+(vL * 5), vTabGrille[lig+1][col])) } else { lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1])) lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1])) lstVertex.add(Triple(nNode, nNode+(vL * 5), vTabGrille[lig+1][col])) } } else if (lig == (vH * 5) - 1) { nNode = col + ((vL * 5) * (lig)) if (col == 0) { lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1])) lstVertex.add(Triple(nNode, nNode-(vL * 5), vTabGrille[lig-1][col])) } else if (col == (vL * 5) - 1) { lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1])) lstVertex.add(Triple(nNode, nNode-(vL * 5), vTabGrille[lig-1][col])) } else { lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1])) lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1])) lstVertex.add(Triple(nNode, nNode-(vL * 5), vTabGrille[lig-1][col])) } } else { // lignes intérieures nNode = col + ((vL * 5) * (lig)) if (col == 0) { lstVertex.add(Triple(nNode, nNode-(vL * 5), vTabGrille[lig-1][col])) lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1])) lstVertex.add(Triple(nNode, nNode+(vL * 5), vTabGrille[lig+1][col])) } else if (col == (vL * 5) - 1) { lstVertex.add(Triple(nNode, nNode-(vL * 5), vTabGrille[lig-1][col])) lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1])) lstVertex.add(Triple(nNode, nNode+(vL * 5), vTabGrille[lig+1][col])) } else { lstVertex.add(Triple(nNode, nNode-(vL * 5), vTabGrille[lig-1][col])) lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1])) lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1])) lstVertex.add(Triple(nNode, nNode+(vL * 5), vTabGrille[lig+1][col])) } } } } val nbVertex = lstVertex.size val nbS = (vH * 5) * (vL * 5) val source = 0 val graph: Array<IntArray> = Array (nbS) { IntArray(nbS) { 0 } } for (v in lstVertex) { val s1 = v.first val s2 = v.second val pV = v.third graph[s1][s2] = pV } val obShortPath = ShortestPath(nbS) val taBDist = obShortPath.dijkstra(graph, source) obShortPath.printSolution(taBDist) }
0
Kotlin
0
0
0d460afc81fddb9875e6634ee08165e63c76cf3a
6,010
Advent-of-Code-2021
Apache License 2.0
src/Day01.kt
dannyrm
573,100,803
false
null
fun main() { fun part1(input: List<String>): Int { return splitByElf(input).max() } fun part2(input: List<String>): Int { return splitByElf(input).sortedDescending().take(3).sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) } fun splitByElf(input: List<String>): List<Int> { var allElvesCalorieList = input val elfCaloriesList = mutableListOf<Int>() while (allElvesCalorieList.isNotEmpty()) { elfCaloriesList.add(allElvesCalorieList.takeWhile { it.isNotEmpty()}.sumOf { it.toInt() }) allElvesCalorieList = allElvesCalorieList.dropWhile { it.isNotEmpty() }.drop(1) } return elfCaloriesList }
0
Kotlin
0
0
9c89b27614acd268d0d620ac62245858b85ba92e
709
advent-of-code-2022
Apache License 2.0