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
Problems/Algorithms/417. Pacific Atlantic Water Flow/PacificAtlantic.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 { private val neighbors: Array<IntArray> = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)) fun pacificAtlantic(heights: Array<IntArray>): List<List<Int>> { val n = heights.size val m = heights[0].size val reachableAtlantic: Array<BooleanArray> = Array(n) { BooleanArray(m) { false } } for (c in 0..m-1) { dfs(heights, n, m, n-1, c, reachableAtlantic) } for (r in 0..n-1) { dfs(heights, n, m, r, m-1, reachableAtlantic) } val reachablePacific: Array<BooleanArray> = Array(n) { BooleanArray(m) { false } } for (c in 0..m-1) { dfs(heights, n, m, 0, c, reachablePacific) } for (r in 0..n-1) { dfs(heights, n, m, r, 0, reachablePacific) } val results: MutableList<List<Int>> = mutableListOf() for (r in 0..n-1) { for (c in 0..m-1) { if (reachableAtlantic[r][c] && reachablePacific[r][c]) { results.add(listOf(r, c)) } } } return results } private fun dfs(heights: Array<IntArray>, n: Int, m: Int, r: Int, c: Int, reachable: Array<BooleanArray>): Unit { reachable[r][c] = true for (neighbor in neighbors) { val x = r + neighbor[0] val y = c + neighbor[1] if (isValid(n, m, x, y) && !reachable[x][y] && heights[x][y] >= heights[r][c]) { dfs(heights, n, m, x, y, reachable) } } } private fun isValid(n: Int, m: Int, r: Int, c: Int): Boolean { return r >= 0 && r < n && c >= 0 && c < m } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,762
leet-code
MIT License
src/Day04.kt
MarkRunWu
573,656,261
false
{"Kotlin": 25971}
import java.lang.Math.abs fun main() { fun parseSectionsAssignments(input: List<String>): List<List<Pair<Int, Int>>> { return input.map { it -> it.split(',') .map { val pairs = it.split('-') Pair(pairs[0].toInt(), pairs[1].toInt()) } } } fun part1(input: List<String>): Int { return parseSectionsAssignments(input) .map { it -> it.sortedBy { it.first } } .count { (it[0].second >= it[1].second) or ( (it[0].first == it[1].first) and (it[0].second < it[1].second)) } } fun part2(input: List<String>): Int { return parseSectionsAssignments(input) .map { it -> it.sortedBy { it.first } } .count { it[0].second >= it[1].first } } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ced885dcd6b32e8d3c89a646dbdcf50b5665ba65
988
AOC-2022
Apache License 2.0
ceria/24/src/main/kotlin/Solution.kt
VisionistInc
317,503,410
false
null
import java.io.File val tokenMap = mapOf<String, Pair<Int, Int>>( "e" to Pair(2, 0), "w" to Pair(-2, 0), "se" to Pair(1, -1), "sw" to Pair(-1, -1), "ne" to Pair(1, 1), "nw" to Pair(-1, 1) ) 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>) :Int { var landingTiles = mutableMapOf<Pair<Int, Int>, Int>() for (line in input) { val landingTile = findLandingTile(tokenize(line)) if (landingTiles.contains(landingTile)) { var numTimesFlipped = landingTiles.get(landingTile)!! landingTiles.put(landingTile, numTimesFlipped + 1) } else { landingTiles.put(landingTile, 1) } } return landingTiles.filter{ it.value.rem(2) == 1 }.size } private fun solution2(input :List<String>) :Int { var landingTiles = mutableMapOf<Pair<Int, Int>, Int>() for (line in input) { val landingTile = findLandingTile(tokenize(line)) if (landingTiles.contains(landingTile)) { var numTimesFlipped = landingTiles.get(landingTile)!! landingTiles.put(landingTile, numTimesFlipped + 1) } else { landingTiles.put(landingTile, 1) } } var blackTiles = landingTiles.filter{ it.value.rem(2) == 1 }.keys.toMutableSet() var day = 0 while (day < 100) { val blackTilesCopy = blackTiles.toSet() var whiteTiles = fillInWhiteTiles(blackTilesCopy).toMutableSet() for (tile in blackTilesCopy) { val adjacentTiles = getAdjacentTiles(tile) val adjacentBlackTiles = blackTilesCopy.intersect(adjacentTiles) if (adjacentBlackTiles.size == 0 || adjacentBlackTiles.size > 2) { // flips to white (remove from black) blackTiles.remove(tile) } } for (tile in whiteTiles) { val adjacentTiles = getAdjacentTiles(tile) val adjacentBlackTiles = adjacentTiles.intersect(blackTilesCopy) if (adjacentBlackTiles.size == 2) { // flips to black (remove from white) blackTiles.add(tile) } } day++ } return blackTiles.size } private fun tokenize(line :String) :List<String> { var tokens = mutableListOf<String>() var index = 0 while (index < line.length) { if (line[index] == 'e' || line[index] == 'w') { tokens.add(line[index].toString()) index++ } else { tokens.add(line[index].toString() + line[index + 1].toString()) index += 2 } } return tokens } private fun findLandingTile(tokens :List<String>) :Pair<Int, Int> { var landingTile = Pair(0, 0) for (token in tokens) { val pos = tokenMap.get(token)!! landingTile = Pair(landingTile.first + pos.first, landingTile.second + pos.second) } return landingTile } private fun fillInWhiteTiles(blackTiles :Set<Pair<Int, Int>>) :Set<Pair<Int, Int>> { return blackTiles.map{ getAdjacentTiles(it).minus(blackTiles) }.flatten().toSet() } private fun getAdjacentTiles(tile :Pair<Int, Int>) :Set<Pair<Int, Int>> { return setOf<Pair<Int, Int>>( Pair(tile.first + 2, tile.second), Pair(tile.first - 2, tile.second), Pair(tile.first + 1, tile.second + 1), Pair(tile.first + 1, tile.second - 1), Pair(tile.first - 1, tile.second + 1), Pair(tile.first - 1, tile.second - 1) ) }
0
Rust
0
0
002734670384aa02ca122086035f45dfb2ea9949
3,498
advent-of-code-2020
MIT License
src/aoc2022/Day13.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
@file:Suppress("UNCHECKED_CAST") package aoc2022 import utils.* import java.rmi.UnexpectedException import kotlin.math.min private class Day13(val lines: List<String>) { val pairs = lines.filter { it.isNotEmpty() } .map { parseList(it).first } /** * Recursively parses a list where each element is a sub-list or an int. * * Returns the first list encountered and the remainder of the unparsed string. * * Example: [4, [2], 2] -> a list of 3 elements and "" * Example: [2], 2] -> a list of one element [2] and ", 2]" as the unparsed string. */ private fun parseList(input: String): Pair<List<Any>, String> { var currS = input val list = mutableListOf<Any>() assert(input.startsWith("[")) currS = currS.removePrefix("[") // Go until we hit the end of this list. // Nested lists are handled by the parse sublist branch so we know // when this loop hits end bracket that this is the end of this lis. while (currS.first() != ']') { when { // Parse separator currS.first() == ',' -> { currS = currS.substring(1) } // Parse number currS.first().isDigit() -> { val numS = currS.takeWhile { it !in setOf(',', ']') } list.add(numS.toInt()) currS = currS.substring(numS.length) } // Parse sublist currS.first() == '[' -> { val (sublistElement, unparsedString) = parseList(currS) list.add(sublistElement) currS = unparsedString } else -> throw UnexpectedException("oops") } } assert(input.startsWith("[")) currS = currS.removePrefix("]") return list to currS } fun compare(a: List<Any>, b: List<Any>): Int { for (i in 0 until min(a.size, b.size)) { val firstItem = a[i] val secondItem = b[i] val result = if (firstItem is Int && secondItem is Int) { compareValues(firstItem, secondItem) } else { val firstList = if (firstItem is Int) listOf(firstItem) else firstItem val secondList = if (secondItem is Int) listOf(secondItem) else secondItem compare(firstList as List<Any>, secondList as List<Any>) } if (result != 0) { return result } } return compareValues(a.size, b.size) } fun part1(): Int { return pairs .chunked(2) .mapIndexed { index, it -> if (compare(it[0], it[1]) < 0) index + 1 else 0 }.sum() } fun part2(): Int { return pairs .sortedWith { a, b -> compare(a as List<Any>, b as List<Any>) }.mapIndexed { index, it -> // Keep indexes of the two elements if (it.toString() in setOf("[[2]]", "[[6]]")) index + 1 else 1 }.reduce { a, b -> a * b } // Compute the product of the list. } } fun main() { val day = "13".toInt() val todayTest = Day13(readInput(day, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 13) val today = Day13(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1", 6420) // 6485 val todayTest2 = Day13(readInput(day, 2022, true, 2)) execute(todayTest2::part2, "Day[Test] $day: pt 2", 140) val todayPt2 = Day13(readInput(day, 2022, inputIndex = 2)) execute(todayPt2::part2, "Day $day: pt 2", 22000) }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
3,303
aoc2022
Apache License 2.0
app/src/y2021/day17/Day17TrickShot.kt
henningBunk
432,858,990
false
{"Kotlin": 124495}
package y2021.day17 import common.* import common.annotations.AoCPuzzle import helper.Point import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.sign fun main(args: Array<String>) { Day17TrickShot().solveThem() } @AoCPuzzle(2021, 17) class Day17TrickShot : AocSolution { override val answers = Answers(samplePart1 = 45, samplePart2 = 112, part1 = 5050, part2 = 2223) override fun solvePart1(input: List<String>): Any { val target = parseToTarget(input.first()) var maxY = 0 for (y in (0..100)) { var yHasAHit = false for(x in (0..100)) { val candidate = Probe(Point(x, y)) while(candidate.isOnTrack(target)) { candidate.step() if(candidate.isInTarget(target)) { maxY = max(maxY, candidate.highestReachedY) yHasAHit = true break } } if(yHasAHit) break } } return maxY } override fun solvePart2(input: List<String>): Any { val target = parseToTarget(input.first()) var hitCount = 0 for (y in (target.y.first..100)) { for(x in (0..target.x.last)) { val candidate = Probe(Point(x, y)) while(candidate.isOnTrack(target) && !candidate.isInTarget(target)) { candidate.step() if(candidate.isInTarget(target)) { hitCount++ break } } } } return hitCount } private fun parseToTarget(input: String): Target { val (xStart, xEnd, yStart, yEnd) = """target area: x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)""" .toRegex() .find(input) ?.destructured ?: error("Did not match") return Target(x = (xStart.toInt()..xEnd.toInt()), y = (yStart.toInt()..yEnd.toInt())) } } class Probe(private var velocity: Point) { private var _position = Point(0, 0) val position: Point get() = _position private var _highestReachedY = 0 val highestReachedY: Int get() = _highestReachedY fun step() { _position += velocity velocity = Point(velocity.x.decrease(), velocity.y - 1) _highestReachedY = max(_highestReachedY, _position.y) } fun isInTarget(target: Target): Boolean = position.x in target.x && position.y in target.y fun isOnTrack(target: Target): Boolean = position.y >= target.y.first private fun Int.decrease(): Int = when { this == 0 -> 0 else -> sign * (absoluteValue - 1) } } data class Target(val x: IntRange, val y: IntRange)
0
Kotlin
0
0
94235f97c436f434561a09272642911c5588560d
2,828
advent-of-code-2021
Apache License 2.0
src/main/kotlin/Day7.kt
amitdev
574,336,754
false
{"Kotlin": 21489}
import java.nio.file.Path fun fileSizeToDelete(lines: Sequence<String>) = directorySizes(lines).smallestFileToDelete() fun fileSize(lines: Sequence<String>) = directorySizes(lines).directorySizes.values .filter { it <=100000 } .sum() private fun directorySizes(lines: Sequence<String>) = lines.fold(DirectoryStructure()) { acc, line -> when { line.startsWith("$ cd ") -> acc.cd(line.split(" ")[2]) line[0].isDigit() -> acc.addSizes(line.split(" ")[0].toInt()) else -> acc } } data class DirectoryStructure( val directorySizes: Map<Path, Int> = mapOf(), val current: Path = ROOT_PATH ) { fun cd(dirName: String) = when (dirName) { ROOT -> copy(current = ROOT_PATH) PARENT -> copy(current = current.parent) else -> copy(current = current.resolve(dirName)) } fun addSizes(size: Int) = copy(directorySizes = directorySizes + findSizes(current, size)) fun totalSize() = directorySizes[ROOT_PATH]!! private fun findSizes(current: Path, size: Int): List<Pair<Path, Int>> = listOf(current to directorySizes.getOrDefault(current, 0) + size) + parentSize(current, size) private fun parentSize(current: Path, size: Int) = if (current.parent == null) listOf() else findSizes(current.parent, size) fun smallestFileToDelete() = directorySizes.values .sorted().first { totalSize() - it <= 40000000 } companion object { val ROOT = "/" val PARENT = ".." val ROOT_PATH = Path.of(ROOT) } }
0
Kotlin
0
0
b2cb4ecac94fdbf8f71547465b2d6543710adbb9
1,480
advent_2022
MIT License
src/Day14.kt
underwindfall
573,471,357
false
{"Kotlin": 42718}
fun main() { val dayId = "14" val input = readInput("Day${dayId}") data class P(val x: Int, val y: Int) val ps = input.map { s -> s.split(" -> ").map { t -> val (x, y) = t.split(",").map { it.toInt() } P(x, y) } } val pf = ps.flatten() + P(500, 0) val y0 = pf.minOf { it.y } val y1 = pf.maxOf { it.y } + 1 val h = y1 - y0 + 10 val x0 = pf.minOf { it.x } - h val x1 = pf.maxOf { it.x } + h val f = Array(x1 - x0 + 1) { BooleanArray(y1 - y0 + 1) } fun set(x: Int, y: Int) { f[x - x0][y - y0] = true } fun get(x: Int, y: Int): Boolean { if (x !in x0..x1 || y !in y0..y1) return false return f[x - x0][y - y0] } for (p in ps) { for (i in 1..p.lastIndex) { val a = p[i - 1] val b = p[i] when { a.x == b.x -> { for (y in minOf(a.y, b.y)..maxOf(a.y, b.y)) set(a.x, y) } a.y == b.y -> { for (x in minOf(a.x, b.x)..maxOf(a.x, b.x)) set(x, a.y) } else -> error("$a $b") } } } var ans = 0 while (true) { var x = 500 var y = 0 if (get(x, y)) break while (true) { if (y == y1) break when { !get(x, y + 1) -> { y++ } !get(x - 1, y + 1) -> { x--; y++ } !get(x + 1, y + 1) -> { x++; y++ } else -> break } } set(x, y) ans++ } println(ans) }
0
Kotlin
0
0
0e7caf00319ce99c6772add017c6dd3c933b96f0
1,604
aoc-2022
Apache License 2.0
src/Day04.kt
jorander
571,715,475
false
{"Kotlin": 28471}
fun main() { val day = "Day04" fun assignmentsAsIntRanges(assignments: String) = assignments.split(",") .map { it.split("-") } .map { (firstSection, lastSection) -> firstSection.toInt()..lastSection.toInt() } fun part1(input: List<String>): Int { return input.map(::assignmentsAsIntRanges) .count { (firstAssignment, secondAssignment) -> (firstAssignment - secondAssignment).isEmpty() || (secondAssignment - firstAssignment).isEmpty() } } fun part2(input: List<String>): Int { return input.map(::assignmentsAsIntRanges) .count { (firstAssignment, secondAssignment) -> (firstAssignment intersect secondAssignment).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 2) val result1 = part1(input) println(result1) check(result1 == 518) check(part2(testInput) == 4) val result2 = part2(input) println(result2) check(result2 == 909) }
0
Kotlin
0
0
1681218293cce611b2c0467924e4c0207f47e00c
1,146
advent-of-code-2022
Apache License 2.0
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day5/Day5.kt
jntakpe
433,584,164
false
{"Kotlin": 64657, "Rust": 51491}
package com.github.jntakpe.aoc2021.days.day5 import com.github.jntakpe.aoc2021.shared.Day import com.github.jntakpe.aoc2021.shared.readInputLines import kotlin.math.abs object Day5 : Day { override val input = readInputLines(5).map { it.split("->").parseLine() } override fun part1() = input.flatMap { it.straight }.result() override fun part2() = input.flatMap { it.straight + it.diagonal }.result() private fun List<Position>.result() = groupingBy { it }.eachCount().filter { it.value >= 2 }.count() private fun List<String>.parseLine() = map { it.trim().split(",").parsePosition() }.run { Line(first(), last()) } private fun List<String>.parsePosition() = Position(first().toInt(), last().toInt()) data class Line(val from: Position, val to: Position) { val straight = from straight to val diagonal = from diagonal to } data class Position(val x: Int, val y: Int) { infix fun straight(other: Position): List<Position> { return if (notEqual(other) { x } xor notEqual(other) { y }) { if (notEqual(other) { x }) { progression(other) { x }.map { copy(x = it) } } else { progression(other) { y }.map { copy(y = it) } } } else { emptyList() } } infix fun diagonal(other: Position): List<Position> { return if (notEqual(other) { x } && notEqual(other) { y } && abs(x - other.x) == abs(y - other.y)) { progression(other) { x }.zip(progression(other) { y }).map { Position(it.first, it.second) } } else { emptyList() } } private inline fun notEqual(other: Position, extract: Position.() -> Int) = extract() != other.extract() private inline fun progression(other: Position, extract: Position.() -> Int): IntProgression { return if (extract() < other.extract()) (extract()..other.extract()) else (extract() downTo other.extract()) } } }
0
Kotlin
1
5
230b957cd18e44719fd581c7e380b5bcd46ea615
2,077
aoc2021
MIT License
src/Day05.kt
adrianforsius
573,044,406
false
{"Kotlin": 68131}
import org.assertj.core.api.Assertions.assertThat fun main() { fun part1(input: String): String { val parts = input.split("\n\n") val crates = parts[0].split("\n").map { it.toCharArray().filterIndexed { index, c -> ((index-1)%4) == 0 } } var stacks: List<ArrayDeque<Char>> = List(crates.size) {ArrayDeque()} crates.slice(0..(crates.size-2)).asReversed().map {chars -> chars.mapIndexed { index, c -> if (c != ' ' && c != '-') { stacks[index].addLast(c) } } } var lines = parts[1].split("\n") lines = lines.slice(0..lines.size-2) lines.map { val commandParts = it.split(" from ") val move = commandParts[0].split(" ")[1].toInt() val directionPart = commandParts[1].split(" to ") val src = directionPart[0].toInt()-1 val dst = directionPart[1].toInt()-1 var srcStack = stacks[src] var dstStack = stacks[dst] val moved = srcStack.takeLast(move) dstStack.addAll(moved.asReversed()) stacks[src].dropLast(move) for (i in 1..move) { stacks[src].removeLast() } } return stacks.map { it.takeLast(1).getOrNull(0) ?: "" }.joinToString("").trim() } fun part2(input: String): String { val parts = input.split("\n\n") val crates = parts[0].split("\n").map { it.toCharArray().filterIndexed { index, c -> ((index-1)%4) == 0 } } var stacks: List<ArrayDeque<Char>> = List(crates.size) {ArrayDeque()} crates.slice(0..(crates.size-2)).asReversed().map {chars -> chars.mapIndexed { index, c -> if (c != ' ' && c != '-') { stacks[index].addLast(c) } } } var lines = parts[1].split("\n") lines = lines.slice(0..lines.size-2) lines.map { val commandParts = it.split(" from ") val move = commandParts[0].split(" ")[1].toInt() val directionPart = commandParts[1].split(" to ") val src = directionPart[0].toInt()-1 val dst = directionPart[1].toInt()-1 var srcStack = stacks[src] var dstStack = stacks[dst] val moved = srcStack.takeLast(move) dstStack.addAll(moved) stacks[src].dropLast(move) for (i in 1..move) { stacks[src].removeLast() } } return stacks.map { it.takeLast(1).getOrNull(0) ?: "" }.joinToString("").trim() } // test if implementation meets criteria from the description, like: // Test val testInput = readText("Day05_test") val output1 = part1(testInput) assertThat(output1).isEqualTo("CMZ") // Answer val input = readText("Day05") val outputAnswer1 = part1(input) assertThat(outputAnswer1).isEqualTo("NTWZZWHFV") // Test val output2 = part2(testInput) assertThat(output2).isEqualTo("MCD") // Answer val outputAnswer2 = part2(input) assertThat(outputAnswer2).isEqualTo("BRZGFVBTJ") }
0
Kotlin
0
0
f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb
3,273
kotlin-2022
Apache License 2.0
src/aoc23/Day12.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc23.day12 import lib.Collections.headTail import lib.Solution import lib.Strings.extractInts data class ConditionRecord(val conditions: String, val groups: List<Int>) { fun unfold(times: Int): ConditionRecord { val newConditions = List(times) { conditions }.joinToString("?") val newGroups = List(times) { groups }.flatten() return ConditionRecord(newConditions, newGroups) } companion object { fun parse(lineStr: String): ConditionRecord { val (conditions, groups) = lineStr.split(" ") return ConditionRecord(conditions, groups.extractInts()) } } } typealias Input = List<ConditionRecord> typealias Output = Long private val solution = object : Solution<Input, Output>(2023, "Day12") { override fun parse(input: String): Input = input.lines().map { ConditionRecord.parse(it) } override fun format(output: Output): String = "$output" override fun part1(input: Input): Output = input.sumOf { arrangements(it) } override fun part2(input: Input): Output = part1(input.map { it.unfold(5) }) fun arrangements(conditionRecord: ConditionRecord): Long { // Dynamic programming cache to avoid recomputing the same sub-problems. val dp: MutableMap<ConditionRecord, Long> = mutableMapOf() fun solve(conditionRecord: ConditionRecord): Long { // Return dp value if already computed. if (conditionRecord in dp) return dp[conditionRecord]!! val (group, nextGroups) = conditionRecord.groups.headTail() // Base case: no more groups to match. if (group == null) { // If there are still damages in the remaining conditions, this arrangement is invalid. return if (conditionRecord.conditions.any { it == '#' }) 0 else 1 } // The following regex matches a group of `group` consecutive damaged characters (either `#` // or `?`). We use a lookahead to simulate overlapping matches. The match must not be followed // by a `#` character, which would make the arrangement invalid. return Regex("""[^.](?=[^.]{${group - 1}}([^#]|$))""") .findAll(conditionRecord.conditions) .map { it.range.first } // Filter out matches that are preceded by a `#` character. .filter { '#' !in conditionRecord.conditions.take(it) } .sumOf { // Drop `group` characters from the conditions and one extra character to account for the // fact that two groups cannot be adjacent. val nextConditions = conditionRecord.conditions.drop(it + group + 1) val nextConditionRecord = ConditionRecord(nextConditions, nextGroups) // Recursively solve the sub-problem. solve(nextConditionRecord) }.also { // Cache the result. dp[conditionRecord] = it } } return solve(conditionRecord) } } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
2,909
aoc-kotlin
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day20.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part20A : PartSolution() { private lateinit var lut: List<Int> private lateinit var image: List<List<Int>> open val numRounds = 2 override fun parseInput(text: String) { val parts = text.split("\n\n") lut = parts[0].trim().filter { it != '\n' }.map { if (it == '#') 1 else 0 } image = parts[1].split("\n").map { line -> line.trim().map { if (it == '#') 1 else 0 } } } override fun compute(): Int { var background = 0 repeat(numRounds) { image = enhance(background) background = lut[if (background == 0) 0 else 1] } return image.sumOf { it.sum() } } private fun enhance(background: Int): List<List<Int>> { val width = image.first().size val height = image.size val newImage = List(height + 2) { MutableList(width + 2) { 0 } } for (y in -1..height) { for (x in -1..width) { val w = getWindow(x, y, background) val v = getEnhancedValue(w) newImage[y + 1][x + 1] = v } } return newImage } private fun getWindow(cX: Int, cY: Int, background: Int): List<List<Int>> { val window = List(3) { MutableList(3) { background} } for (y in cY - 1..cY+1) { for (x in cX - 1 .. cX + 1) { if (y < 0 || y >= image.size || x < 0 || x >= image.first().size) { continue } window[y - cY + 1][x - cX + 1] = image[y][x] } } return window } private fun getEnhancedValue(window: List<List<Int>>): Int { val flattened = window.flatten() var index = 0 for (i in flattened.indices) { index += flattened[i] shl (8 - i) } return lut[index] } override fun getExampleAnswer(): Int { return 35 } } class Part20B : Part20A() { override val numRounds = 50 override fun getExampleAnswer(): Int { return 3351 } } fun main() { Day(2021, 20, Part20A(), Part20B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
2,233
advent-of-code-kotlin
MIT License
src/main/aoc2022/Day18.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2022 class Day18(input: List<String>) { private data class Pos3D(val x: Int, val y: Int, val z: Int) { fun allNeighbours() = listOf( Pos3D(x, y, z - 1), Pos3D(x, y, z + 1), Pos3D(x, y + 1, z), Pos3D(x, y - 1, z), Pos3D(x + 1, y, z), Pos3D(x - 1, y, z), ) } private val cubes = input .map { it.split(",").let { (x, y, z) -> Pos3D(x.toInt(), y.toInt(), z.toInt()) } } .toSet() // Count number of sides that is not next to another cube fun solvePart1(): Int { return cubes.sumOf { 6 - it.allNeighbours().count { n -> n in cubes } } } /** * Find all the air on the outside using a BFS approach */ private fun findOutsideAir(xRange: IntRange, yRange: IntRange, zRange: IntRange): Set<Pos3D> { val air = mutableSetOf<Pos3D>() val toCheck = mutableListOf(Pos3D(xRange.first, yRange.first, zRange.first)) while (toCheck.isNotEmpty()) { val current = toCheck.removeLast() air.add(current) current.allNeighbours().forEach { if (it !in cubes && it !in air && it.x in xRange && it.y in xRange && it.z in zRange) { toCheck.add(it) } } } return air } // Count number of sides that is next to the air on the outside fun solvePart2(): Int { // bounding box that leaves a bit of air outside the outermost cube. val xRange = cubes.minBy { it.x }.x - 1..cubes.maxBy { it.x }.x + 1 val yRange = cubes.minBy { it.y }.y - 1..cubes.maxBy { it.y }.y + 1 val zRange = cubes.minBy { it.z }.z - 1..cubes.maxBy { it.z }.z + 1 val outsideAir = findOutsideAir(xRange, yRange, zRange) return cubes.sumOf { it.allNeighbours().count { n -> n in outsideAir } } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,907
aoc
MIT License
2019/src/test/kotlin/Day12.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.math.abs import kotlin.test.Test import kotlin.test.assertEquals class Day12 { data class Vector(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Vector) = Vector(x + other.x, y + other.y, z + other.z) fun energy(): Int = abs(x) + abs(y) + abs(z) } data class Moon(val position: Vector, val velocity: Vector) { fun applyGravity(others: List<Moon>) = others .fold(velocity) { acc, moon -> Vector( calcAxis(position.x, moon.position.x, acc.x), calcAxis(position.y, moon.position.y, acc.y), calcAxis(position.z, moon.position.z, acc.z) ) } private fun calcAxis(axis: Int, otherAxis: Int, axisVelocity: Int) = axis .compareTo(otherAxis).negate() + axisVelocity fun applyVelocity(velocity: Vector) = position + velocity } @Test fun runPart01() { var moons = getMoons() repeat(1000) { moons = turn(moons) } val energy = moons.sumOf { it.position.energy() * it.velocity.energy() } assertEquals(9743, energy) } @Test fun runPart02() { var moons = getMoons() var allXZeroAt = 0L var allYZeroAt = 0L var allZZeroAt = 0L var times = 0L while (allXZeroAt == 0L || allYZeroAt == 0L || allZZeroAt == 0L) { moons = turn(moons).also { times++ } if (allXZeroAt == 0L && moons.all { it.velocity.x == 0 }) allXZeroAt = times if (allYZeroAt == 0L && moons.all { it.velocity.y == 0 }) allYZeroAt = times if (allZZeroAt == 0L && moons.all { it.velocity.z == 0 }) allZZeroAt = times } val previousStateAt = 2 * allXZeroAt.lcm(allYZeroAt).lcm(allZZeroAt) assertEquals(288684633706728, previousStateAt) } private fun turn(moons: List<Moon>) = moons .map { moon -> val velocity = moon.applyGravity(moons - moon) Moon(moon.applyVelocity(velocity), velocity) } private fun getMoons() = Util.getInputAsListOfString("day12-input.txt") .map { val (x, y, z) = re.findAll(it) .map { match -> match.value.toInt() } .toList() Moon(Vector(x, y, z), Vector(0, 0, 0)) } private val re = "-?\\d+".toRegex() }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,467
adventofcode
MIT License
src/day10/Day10.kt
diesieben07
572,879,498
false
{"Kotlin": 44432}
package day10 import streamInput import java.lang.StringBuilder private val file = "Day10" //private val file = "Day10Example" private sealed interface Instruction { fun decompose(): Sequence<Instruction> fun nextState(state: CpuState): CpuState object NOOP : Instruction { override fun decompose(): Sequence<Instruction> { return sequenceOf(this) } override fun nextState(state: CpuState): CpuState { return state.copy(cycle = state.cycle + 1) } } data class AddX(val amount: Int) : Instruction { override fun decompose(): Sequence<Instruction> { return sequence { yield(NOOP) yield(this@AddX) } } override fun nextState(state: CpuState): CpuState { return state.copy(x = state.x + this.amount, cycle = state.cycle + 1) } } companion object { fun parse(line: String): Instruction { return when { line == "noop" -> NOOP line.startsWith("addx ") -> AddX(line.substring(5).toInt()) else -> throw UnsupportedOperationException() } } } } private data class CpuState(val x: Int, val cycle: Int) private fun Sequence<String>.getStates(): Sequence<CpuState> { return map { Instruction.parse(it) } .flatMap { it.decompose() } .runningFold(CpuState(1, 1)) { state, instruction -> instruction.nextState(state) } } private fun part1() { streamInput(file) { input -> val cycles = setOf(20, 60, 100, 140, 180, 220) val states = input.getStates() println(states.sumOf { if (it.cycle in cycles) it.x * it.cycle else 0 }) } } private fun part2() { streamInput(file) { input -> val states = input.getStates() val output = StringBuilder() for (state in states) { val spritePosition = state.x val currentPixel = (state.cycle - 1) % 40 if (currentPixel == 0 && state.cycle > 1) { output.append('\n') } val pixelLit = currentPixel in (spritePosition - 1)..(spritePosition + 1) output.append(if (pixelLit) '#' else '.') } println(output) } } fun main() { part1() part2() }
0
Kotlin
0
0
0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6
2,378
aoc-2022
Apache License 2.0
src/questions/LetterCombinationsOfPhoneNumber.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.assertIterableSameInAnyOrder /** * Given a string containing digits from 2-9 inclusive, return all possible * letter combinations that the number could represent. Return the answer in any order. * A mapping of digit to letters (just like on the telephone buttons) is given below. * Note that 1 does not map to any letters. * * <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png" height="150" width="300"/> * * [Source](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) * */ @UseCommentAsDocumentation fun letterCombinations(digits: String): List<String> { val map = mapOf( 2 to arrayOf('a', 'b', 'c'), 3 to arrayOf('d', 'e', 'f'), 4 to arrayOf('g', 'h', 'i'), 5 to arrayOf('j', 'k', 'l'), 6 to arrayOf('m', 'n', 'o'), 7 to arrayOf('p', 'q', 'r', 's'), 8 to arrayOf('t', 'u', 'v'), 9 to arrayOf('w', 'x', 'y', 'z'), ) val digit = digits.split("").filter { it != "" } val result = mutableListOf<String>() generateCombination(digit, map, index = 0, result) return result } /** * Start from first character, generate all result when there's only one number present i.e "2" in "234" * Then consider next character and using previous result, generate the newer result. i.e. "23" in "234", "234" in "234" */ private fun generateCombination( digit: List<String>, map: Map<Int, Array<Char>>, index: Int, result: MutableList<String> ) { if (index > digit.lastIndex) { return } val currentNumber: Int = digit[index].toInt() val characters: Array<Char> = map[currentNumber]!! // Store previous result val copy = ArrayList(result) if (result.isEmpty()) { result.addAll(characters.map { it.toString() }) } else { result.clear() for (i in 0..copy.lastIndex) { // Use previous result to build the next result for (j in 0..characters.lastIndex) { result.add(copy[i] + characters[j]) } } } generateCombination(digit, map, index + 1, result) } fun main() { assertIterableSameInAnyOrder( expected = listOf("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"), actual = letterCombinations(digits = "23") ) assertIterableSameInAnyOrder( expected = listOf( "adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi" ), actual = letterCombinations(digits = "234") ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,774
algorithms
MIT License
src/day03/Day03.kt
Mini-Stren
573,128,699
false
null
package day03 import readInputLines fun main() { val day = 3 fun part1(input: List<String>): Int { return input.sumOf { line -> line.chunked(line.length / 2, CharSequence::toSet) .let { it[0] intersect it[1] } .first() .let(Char::priority) } } fun part2(input: List<String>): Int { return input.chunked(3) { elvesGroup -> elvesGroup.map(String::toSet) .let { it[0] intersect it[1] intersect it[2] } .first() }.sumOf(Char::priority) } val testInput = readInputLines("/day%02d/input_test".format(day)) val input = readInputLines("/day%02d/input".format(day)) check(part1(testInput) == 157) println("part1 answer is ${part1(input)}") check(part2(testInput) == 70) println("part2 answer is ${part2(input)}") } private val Char.priority: Int get() = 1 + when { isUpperCase() -> this - 'A' + 26 else -> this - 'a' }
0
Kotlin
0
0
40cb18c29089783c9b475ba23c0e4861d040e25a
1,023
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/days/Day20.kt
andilau
399,220,768
false
{"Kotlin": 85768}
package days import days.Day20.Orientation.* @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2020/day/20", date = Date(day = 20, year = 2020) ) class Day20(input: String) : Puzzle { private val tiles: List<Tile> = readTiles(input) private val seaMonster: Set<Point> = getMonsterAsPoints() override fun partOne(): Long = tiles .filter { tile -> tile.sharedSideCount(tiles) == 2 } .take(4) .fold(1L) { a, t -> a * t.id } override fun partTwo(): Int { val lineOfTiles: List<Tile> = tiles.solvePuzzle() val width = tiles.count().sqrt() val image = lineOfTiles .windowed(width, width) .flatMap { it.asString(withHeader = false, trimmed = true).lines().dropLast(1) } val tile = Tile(0, image) .allVariations() .dropWhile { tile -> tile.countMonsters(seaMonster).isEmpty() } .first() return tile.countHashes() - tile.countMonsters(seaMonster).size } private fun List<Tile>.solvePuzzle(): List<Tile> { val width = this.count().sqrt() var recentTile = findTopLeftTile() var firstInRowTile = recentTile return (this.indices).map { x -> val y = x % width when { x == 0 && y == 0 -> recentTile y == 0 -> { recentTile = firstInRowTile.findTileAndOrient(BOTTOM, TOP, this) firstInRowTile = recentTile recentTile } else -> { recentTile = recentTile.findTileAndOrient(RIGHT, LEFT, this) recentTile } } }.toList() } private fun Tile.findTileAndOrient( tileOrientation: Orientation, otherOrientation: Orientation, tiles: List<Tile> ): Tile { val tileSide = sideOn(tileOrientation) return tiles .filter { it.id != id } .first { it.hasSide(tileSide) } .allVariations() .first { tileSide == it.sideOn(otherOrientation) } } private fun getMonsterAsPoints(): Set<Point> { return """ | # |# ## ## ### | # # # # # # """ .trimMargin() .lines() .mapIndexed { y, row -> row.mapIndexedNotNull { x, c -> if (c == '#') x to y else null } }.flatten().toSet() } private fun Tile.countHashes(): Int = content.sumOf { line -> line.count { it == '#' } } private fun Tile.countMonsters(points: Set<Point>): Set<Point> { val seaMonsterPoints = mutableSetOf<Point>() val maxX = points.maxByOrNull { point -> point.first }?.first ?: 0 val maxY = points.maxByOrNull { point -> point.second }?.second ?: 0 (0..(content.indices.last - maxY)).forEach { y -> (0..(content.first().indices.last - maxX)).forEach { x -> val checkPoints = points .map { it + Point(x, y) } // if (checkPoints.all { content[it.second][it.first] == '#' }) { seaMonsterPoints.addAll(checkPoints) } } } return seaMonsterPoints } private fun Iterable<Tile>.asString( withHeader: Boolean = true, withBody: Boolean = true, trimmed: Boolean = false ) = buildString { if (withHeader) appendLine(this@asString.joinToString(" ") { tile -> "Tile ${tile.id}:" }) if (withBody) { if (!trimmed) tiles.first().content.indices.forEach { row -> appendLine(this@asString.joinToString(" ") { tile -> tile.content[row] }) } else { tiles.first().inset.indices.forEach { row -> appendLine(this@asString.joinToString("") { tile -> tile.inset[row] }) } } } } private fun findTopLeftTile(): Tile { return tiles .first { tile -> tile.sharedSideCount(tiles) == 2 } .allVariations() .first { it.isSideShared(BOTTOM, tiles) && it.isSideShared(RIGHT, tiles) } } private fun readTiles(input: String): List<Tile> { val newLine = System.lineSeparator() return input .trim() .split("$newLine$newLine") .map { Tile.parse(it.lines()) } } data class Tile(val id: Int, val content: List<String>) { private val sides: List<String> = listOf( content.first(), content.map { row -> row.last() }.joinToString(""), content.last(), content.map { row -> row.first() }.joinToString(""), ) private val reversedSides: List<String> = sides.map { it.reversed() } fun sharedSideCount(tiles: List<Tile>): Int { return sides.sumOf { side -> tiles .filterNot { it.id == id } .count { it.hasSide(side) } } } fun isSideShared(dir: Orientation, tiles: List<Tile>): Boolean = tiles .filter { it.id != id } .any { tile -> tile.hasSide(sideOn(dir)) || tile.hasSide(reverseSideOn(dir)) } fun rotate(): Tile { val contentRotated = content.mapIndexed { x, row -> row.mapIndexed { y, _ -> content[y][x] }.reversed().joinToString("") } return copy(content = contentRotated) } fun flip(): Tile { val contentFlipped = content.map { it.reversed() } return copy(content = contentFlipped) } fun allVariations() = sequence { var tile: Tile = this@Tile repeat(2) { repeat(times = 4) { tile = tile.rotate() yield(tile) } tile = tile.flip() } } val inset: List<String> get() { val insetRange = (content.indices.first + 1) until content.indices.last return insetRange.map { y -> content[y].slice(insetRange) }.toList() } fun getAsString(): String = buildString { appendLine("Tile $id:") content.forEach { appendLine(it) } } fun hasSide(side: String): Boolean = side in sides || side in reversedSides fun sideOn(orientation: Orientation): String = sides[orientation.ordinal] private fun reverseSideOn(orientation: Orientation): String = reversedSides[orientation.ordinal] companion object { fun parse(lines: List<String>): Tile { val id = lines[0].substringAfter(" ").substringBefore(":").toInt() val content = lines.drop(1).takeWhile { it.isNotBlank() } return Tile(id, content) } } } enum class Orientation { TOP, RIGHT, BOTTOM, LEFT } private fun Int.sqrt(): Int = generateSequence(2) { i -> i + 1 } .takeWhile { it * it <= this }.last() }
7
Kotlin
0
0
2809e686cac895482c03e9bbce8aa25821eab100
7,436
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/Day13.kt
a2xchip
573,197,744
false
{"Kotlin": 37206}
import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.* import java.io.File class SignalPacket(val data: JsonArray) : Comparable<SignalPacket> { private fun compare(a: JsonElement, b: JsonElement): Int { when (Pair(a !is JsonArray, b !is JsonArray)) { true to true -> { return a.jsonPrimitive.content.toInt().compareTo(b.jsonPrimitive.content.toInt()) } false to false -> { var i = 0 while (i < (a as JsonArray).size && i < (b as JsonArray).size) { val result = compare(a[i], b[i]) if (result == 1) return 1 if (result == -1) return -1 i += 1 } if (a.size > (b as JsonArray).size) return 1 if (a.size < b.size) return -1 return 0 } false to true -> { return compare(a, JsonArray(listOf(b))) } true to false -> { return compare(JsonArray(listOf(a)), b as JsonArray) } } error("Unexpected state") } override fun compareTo(other: SignalPacket): Int { return compare(this.data, other.data) } companion object { fun fromInput(item: String): SignalPacket { return SignalPacket(Json.decodeFromString(item)) } } } fun main() { fun readPairedInput(name: String) = File("src", "$name.txt").readText().split("\n\n") fun readMergedInput(name: String) = File("src", "$name.txt").readText().split("\n").filter { it.length > 0 } fun List<String>.toPairs() = this.map { pairString -> val split = pairString.split("\n") Pair(SignalPacket.fromInput(split.first()), SignalPacket.fromInput(split.last())) } fun List<String>.toPackages() = this.map { pairString -> SignalPacket.fromInput(pairString) } fun part1(input: List<String>): Int { var result = 0 for ((i, v) in input.toPairs().withIndex()) { if (v.first > v.second) continue result += i + 1 } return result } fun part2(input: List<String>): Int { val packages = input.toPackages().toMutableList() packages.add(SignalPacket.fromInput("[[2]]")) packages.add(SignalPacket.fromInput("[[6]]")) val indexes = mutableListOf<Int>() for ((i, v) in packages.sorted().withIndex()) { if (v.data.toString() == "[[2]]" || v.data.toString() == "[[6]]") indexes.add(i + 1) } return indexes.reduce(Int::times) } val testInput = readPairedInput("Day13_test") val testInput2 = readMergedInput("Day13_test") println("Test 1 - ${part1(testInput)}") println("Test 2 - ${part2(testInput2)}") println() val input = readPairedInput("Day13") val input2 = readMergedInput("Day13") println("Part 1 - ${part1(input)}") println("Part 2 - ${part2(input2)}") }
0
Kotlin
0
2
19a97260db00f9e0c87cd06af515cb872d92f50b
3,029
kotlin-advent-of-code-22
Apache License 2.0
src/main/kotlin/com/ryanmoelter/advent/day01/Calories.kt
ryanmoelter
573,615,605
false
{"Kotlin": 84397}
package com.ryanmoelter.advent.day01 fun main() { println(countTopCalories(day01Input, 3)) } fun countTopCalories(input: String, numberOfDwarfs: Int): Int { var heaviestDwarves = emptyList<Int>() var currentDwarf = 0 input.lines().forEach { line -> if (line.isNotBlank()) { currentDwarf += line.toInt() } else { val min = heaviestDwarves.minOrNull() if (min == null || currentDwarf > min) { if (min != null && heaviestDwarves.size >= numberOfDwarfs) { heaviestDwarves = heaviestDwarves - min } heaviestDwarves = heaviestDwarves + currentDwarf } currentDwarf = 0 } } val min = heaviestDwarves.min() if (currentDwarf > min) { if (heaviestDwarves.size >= numberOfDwarfs) { heaviestDwarves = heaviestDwarves - min } heaviestDwarves = heaviestDwarves + currentDwarf } return heaviestDwarves.sum() } fun countCalories(input: String): Int { var heaviestDwarf = 0 var currentDwarf = 0 input.lines().forEach { line -> if (line.isNotBlank()) { currentDwarf += line.toInt() } else { if (currentDwarf > heaviestDwarf) { heaviestDwarf = currentDwarf } currentDwarf = 0 } } if (currentDwarf > heaviestDwarf) { heaviestDwarf = currentDwarf } return heaviestDwarf }
0
Kotlin
0
0
aba1b98a1753fa3f217b70bf55b1f2ff3f69b769
1,328
advent-of-code-2022
Apache License 2.0
src/Day04.kt
jordanfarrer
573,120,618
false
{"Kotlin": 20954}
fun main() { val day = "Day04" fun isFullyContained(sectionPairs: List<Int>): Boolean { val (firstStart, firstEnd, secondStart, secondEnd) = sectionPairs return (firstStart >= secondStart && firstEnd <= secondEnd) || (secondStart >= firstStart && secondEnd <= firstEnd) } fun hasOverlap(sectionPairs: List<Int>): Boolean { val (firstStart, firstEnd, secondStart, secondEnd) = sectionPairs val firstRange = firstStart..firstEnd val secondRange = secondStart..secondEnd return firstRange.intersect(secondRange).any() } fun part1(input: List<String>): Int { return input.map { pair -> pair.split(',','-').map { it.toInt() } }.count { isFullyContained(it) } } fun part2(input: List<String>): Int { return input.map { pair -> pair.split(',','-').map { it.toInt() } }.count { hasOverlap(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val part1Result = part1(testInput) println("Part 1 (test): $part1Result") check(part1Result == 2) val part2Result = part2(testInput) println("Part 2 (test): $part2Result") // check(part2Result == 4) val input = readInput(day) println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
aea4bb23029f3b48c94aa742958727d71c3532ac
1,319
advent-of-code-2022-kotlin
Apache License 2.0
src/Day05.kt
kent10000
573,114,356
false
{"Kotlin": 11288}
fun main() { fun loadStacks(input: List<String>): List<MutableList<Char>> { var stacks = input.subList(0, input.indexOf(String())) val num = stacks.last().dropLastWhile { !it.isDigit() }.last().digitToInt() stacks = stacks.dropLast(1) val list: List<MutableList<Char>> = List(num) { mutableListOf()} for (line in stacks) { val items = line.chunked(4) //items.forEach { println(it) } for ((cursor, i) in items.withIndex()) { if (i.isNotBlank()) { list[cursor].add(i[1]) } } } list.forEach { it.reverse() } return list } fun List<MutableList<Char>>.executeInstruction(instruction: String, new: Boolean = false) { val actions = instruction.split(" ") //1,3,6 val (count, from, to) = Triple(actions[1].toInt(), actions[3].toInt() - 1, actions[5].toInt() - 1) //println("$count, $from, $to") val chars = this[from].subList(this[from].size - count, this[from].size) if (new) { this[to].addAll(chars) } else { this[to].addAll(chars.reversed()) } (0 until count).forEach { _ -> this[from].removeLast()} //chars.forEach{ println(it)} } fun part1(input: List<String>): String { val stacks = loadStacks(input) val instructions = input.subList(input.indexOf(String()) + 1, input.size) //instructions.forEach { executeInstruction(it); return@forEach} for (instruction in instructions) { stacks.executeInstruction(instruction) } var crates = "" stacks.forEach { crates += it.lastOrNull() ?: " " } return crates } fun part2(input: List<String>): String { val stacks = loadStacks(input) val instructions = input.subList(input.indexOf(String()) + 1, input.size) //instructions.forEach { executeInstruction(it); return@forEach} for (instruction in instructions) { stacks.executeInstruction(instruction, true) } var crates = "" stacks.forEach { crates += it.lastOrNull() ?: " " } return crates } /* test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 1) */ val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c128d05ab06ecb2cb56206e22988c7ca688886ad
2,494
advent-of-code-2022
Apache License 2.0
src/main/kotlin/advent/Advent3.kt
v3rm0n
225,866,365
false
null
package advent import kotlin.math.abs class Advent3 : Advent { override fun firstTask(input: List<String>) = intersections(wires(input)).map { (x, y) -> abs(0 - x) + abs(0 - y) }.min() ?: "Not found!" override fun secondTask(input: List<String>) = wires(input).let { (first, second) -> intersections(first to second).map { first.indexOf(it) + second.indexOf(it) }.min() ?: "Not found!" } private fun intersections(wires: Pair<List<Pair<Int, Int>>, List<Pair<Int, Int>>>) = wires.first.intersect(wires.second).drop(1) private fun wires(input: List<String>): Pair<List<Pair<Int, Int>>, List<Pair<Int, Int>>> { val (first, second) = input.map { mapWireToCoordinates(it.split(',')) } return first to second } private fun mapWireToCoordinates(wire: List<String>): List<Pair<Int, Int>> { return wire.fold(listOf(0 to 0)) { result, i -> val amount = i.drop(1).toInt() result + when (i[0]) { 'D' -> move(0, -amount, result.last()) 'U' -> move(0, amount, result.last()) 'L' -> move(-amount, 0, result.last()) 'R' -> move(amount, 0, result.last()) else -> throw IllegalStateException("Illegal move") } } } private fun move(xd: Int, yd: Int, start: Pair<Int, Int>): List<Pair<Int, Int>> { val (x1, y1) = start val (x2, y2) = x1 + xd to y1 + yd return (if (xd < 0) x1.downTo(x2) else x1..x2).flatMap { x -> (if (yd < 0) y1.downTo(y2) else y1..y2).mapNotNull { y -> if (y != y1 || x != x1) x to y else null } } } }
0
Kotlin
0
1
5c36cb254100f80a6e9c16adff5e7aadc8c9e98f
1,696
aoc2019
MIT License
src/Day17.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
fun main() { class Rock(val x: Long, val y: Long) { override fun toString(): String { return "($x, $y)" } } class Map { private val rocks = mutableListOf<Rock>() private var highest = 0L fun add(block: List<Rock>) { rocks.addAll(block) highest = maxOf(highest, block.maxOf { it.y }) } fun highest(): Long { return highest } fun canMoveDown(block: List<Rock>): Boolean { // Possible optimization : filter block to keep only bottom rocks return block.all { blockRock -> blockRock.y > 1 && !rocks.any { mapRock -> mapRock.x == blockRock.x && mapRock.y + 1 == blockRock.y } } } fun canMoveLeft(block: List<Rock>): Boolean { // Possible optimization : filter block to keep only left rocks return block.all { blockRock -> blockRock.x > 0L && !rocks.any { mapRock -> mapRock.y == blockRock.y && mapRock.x + 1 == blockRock.x } } } fun canMoveRight(block: List<Rock>): Boolean { // Possible optimization : filter block to keep only right rocks return block.all { blockRock -> blockRock.x < 6L && !rocks.any { mapRock -> mapRock.y == blockRock.y && mapRock.x == blockRock.x + 1 } } } override fun toString(): String { // Show the top of the map return rocks.filter { it.y > highest - 30 }.joinToString(", ", "[", "]") } } class Block(val rocks: List<Rock>, private val map: Map) { constructor(map: Map, vararg parts: Rock): this(parts.toList(), map) fun spawn(): Block { return Block(rocks.map { Rock(it.x, it.y + map.highest() + 4L) }, map) } fun moveLeft(): Block { if (map.canMoveLeft(rocks)) { return Block(rocks.map { Rock(it.x - 1L, it.y) }, map) } return this } fun moveRight(): Block { if (map.canMoveRight(rocks)) { return Block(rocks.map { Rock(it.x + 1L, it.y) }, map) } return this } fun moveDown(): Block? { if (map.canMoveDown(rocks)) { return Block(rocks.map { Rock(it.x, it.y - 1L) }, map) } map.add(this.rocks) return null } override fun toString(): String = rocks.joinToString(", ", "[", "]") } fun initBlocks(map: Map) = listOf( Block(map, Rock(2, 0), Rock(3, 0), Rock(4, 0), Rock(5, 0)), Block(map, Rock(3, 0), Rock(2, 1), Rock(3, 1), Rock(4, 1), Rock(3, 2)), Block(map, Rock(2, 0), Rock(3, 0), Rock(4, 0), Rock(4, 1), Rock(4, 2)), Block(map, Rock(2, 0), Rock(2, 1), Rock(2, 2), Rock(2, 3)), Block(map, Rock(2, 0), Rock(3, 0), Rock(2, 1), Rock(3, 1)), ) fun part1(input: String): Long { val map = Map() val initBlocks = initBlocks(map) var i = 0 val printUntil = 0 var block: Block? repeat(2022) { block = initBlocks[it % 5].spawn() if (it < printUntil) println("init: $block") while (block != null) { if (input[i++ % input.length] == '<') { block = block!!.moveLeft() if (it < printUntil) println("left: $block") } else { block = block!!.moveRight() if (it < printUntil) println("right: $block") } block = block!!.moveDown() if (it < printUntil) println("down: $block") } if (it < printUntil) println() } return map.highest() } fun part2(input: String): Long { // After any multiple of 10091 steps, the situation is the same with an additional height of 2610. // So we let the simulation run for 10091 steps, then we fast-forward to the last iteration of 10091 steps before reaching 1_000_000_000_000 steps. // Drop 1704 blocks (to reach blow 10091) // There remain 999999998296 blocks to drop. Dropping 1695 blocks is the same as performing 10091 blows. // We skip 1695 * (999999998296 / 1695) blocks, of height 2610 * (999999998296 / 1695). // We drop the remaining 999999998296 % 1695 blocks. // Total of blocks to drop = 1704 + (999999998296 % 1695) = 2500 // Total height is map height + 2610 * (999999998296 / 1695) val map = Map() val initBlocks = initBlocks(map) var blowId = 0 var blockId = 0 var block: Block? repeat(2500) { block = initBlocks[blockId++ % 5].spawn() while (block != null) {// && blowId < 10091) { if (input[blowId++ % input.length] == '<') { block = block!!.moveLeft() } else { block = block!!.moveRight() } block = block!!.moveDown() } } return map.highest() + 2610L * (999999998296L / 1695L) } val input = readInput("Day17")[0] println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
5,446
aoc2022-kotlin
Apache License 2.0
src/Day05.kt
Kietyo
573,293,671
false
{"Kotlin": 147083}
fun main() { fun part1(input: List<String>): Unit { // val stacks = listOf( // "ZN", "MCD", "P" // ).map { it.toMutableList() } val stacks = listOf( "BZT", "VHTDN", "BFMD", "TJGWVQL", "WDGPVFQM", "VZQGHFS", "ZSNRLTCW", "ZHWDJNRM", "MQLFDS" ).map { it.toMutableList() } input.forEach { line -> val matchResult = line.split(" ") val count = matchResult[1].toInt() val stackIndex1 = matchResult[3].toInt() - 1 val stackIndex2 = matchResult[5].toInt() - 1 repeat(count) { stacks[stackIndex2].add(stacks[stackIndex1].removeLast()) } } println(stacks.map { it.last() }.joinToString("")) println(stacks) } fun part2(input: List<String>): Unit { // val stackString = """ //,D, //N,C, //Z,M,P // """.trimIndent() val stacks = listOf( "BZT", "VHTDN", "BFMD", "TJGWVQL", "WDGPVFQM", "VZQGHFS", "ZSNRLTCW", "ZHWDJNRM", "MQLFDS" ).map { it.toMutableList() } println(stacks) val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") input.forEach { val matchResult = regex.matchEntire(it) val (_, count, stackIndex1, stackIndex2) = matchResult!!.groupValues.map { it.toIntOrNull() ?: 0 } println("count: $count, stackIndex1: $stackIndex1, stackIndex2: $stackIndex2") val tempStack = mutableListOf<Char>() repeat(count) { val e = stacks[stackIndex1 - 1].removeLast() tempStack.add(e) } repeat(count) { stacks[stackIndex2 - 1].add(tempStack.removeLast()) } } println(stacks.map { it.last() }.joinToString("")) } val dayString = "day5" // test if implementation meets criteria from the description, like: val testInput = readInput("${dayString}_test") // part1(testInput) // part2(testInput) val input = readInput("${dayString}_input") part1(input) part2(input) }
0
Kotlin
0
0
dd5deef8fa48011aeb3834efec9a0a1826328f2e
2,100
advent-of-code-2022-kietyo
Apache License 2.0
src/Day07.kt
dyomin-ea
572,996,238
false
{"Kotlin": 21309}
fun main() { val cd = "\\$ cd (.+)".toRegex() val dir = "dir (.+)".toRegex() val file = "(\\d+) (.+)".toRegex() val ls = "\\$ ls".toRegex() fun EditableDir.dir(name: String): EditableDir = object : EditableDir { override val children = mutableListOf<Node>() override val parent get() = this@dir override val name get() = name override fun toString(): String = "/$name $size" override val size: Int by lazy { children.sumOf { it.size } } } fun EditableDir.parse(input: Iterator<String>): Node { while (input.hasNext()) { val line = input.next() when { line matches ls -> Unit line matches file -> { val (size, name) = file.find(line)!!.destructured children += Fl(this, name, size.toInt()) } line matches dir -> { val (name) = dir.find(line)!!.destructured children += dir(name) } line matches cd -> { val (name) = cd.find(line)!!.destructured val parseDir = if (name == "..") parent else children.first { it.name == name } as EditableDir parseDir.parse(input) } } } return this } fun part1(root: EditableDir): Int { return root.iterable .filter { it is Dir && it.size < 100000 } .sumOf { it.size } } fun part2(root: EditableDir): Int { val alreadyFree = 70_000_000 - root.size val toFreeUp = 30_000_000 - alreadyFree return root.iterable .filter { it is Dir && it.size > toFreeUp } .minByOrNull { it.size }!! .size } fun root() = object : EditableDir { override val parent: EditableDir = this override val children = mutableListOf<Node>() override val name: String = "/" override val size: Int by lazy { children.sumOf { it.size } } override fun toString(): String { return "/" } } val testRoot = root() .apply { val inputIterator = readInput("Day07_test").iterator() inputIterator.next() parse(inputIterator) } check(part1(testRoot) == 95437) check(part2(testRoot) == 24933642) val solutionRoot = root() .apply { val inputIterator = readInput("Day07").iterator() inputIterator.next() parse(inputIterator) } println(part1(solutionRoot)) println(part2(solutionRoot)) } sealed interface Node { val parent: Node val name: String val size: Int } data class Fl( override val parent: Node, override val name: String, override val size: Int, ) : Node { override fun toString(): String { return "$name $size" } } interface Dir : Node { val children: List<Node> } interface EditableDir : Dir { override val parent: EditableDir override val children: MutableList<Node> } val Node.iterable get() = Iterable { nodeIterator(this) } fun nodeIterator(node: Node): Iterator<Node> { return when (node) { is Fl -> iterator { yield(node) } is Dir -> iterator { yield(node) node.children .forEach { yieldAll(nodeIterator(it)) } } } } fun printNode(prefix: String, node: Node) { println("$prefix$node") when (node) { is Fl -> Unit is Dir -> node.children.forEach { printNode(" $prefix", it) } } }
0
Kotlin
0
0
8aaf3f063ce432207dee5f4ad4e597030cfded6d
3,083
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem2306/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2306 /** * LeetCode page: [2306. Naming a Company](https://leetcode.com/problems/naming-a-company/); */ class Solution { /* Complexity: * Time O(L) and Space O(L) where L is the flat length of ideas; */ fun distinctNames(ideas: Array<String>): Long { val suffixGroups = groupSuffixByFirstLetter(ideas) var numDistinctNames = 0L for (i in 0 until suffixGroups.lastIndex) { val group1 = suffixGroups[i] if (group1.isEmpty()) continue for (j in i + 1 until suffixGroups.size) { val group2 = suffixGroups[j] if (group2.isEmpty()) continue val numCommonSuffix = group1.count { it in group2 } val numExclusiveSuffix1 = group1.size - numCommonSuffix val numExclusiveSuffix2 = group2.size - numCommonSuffix // times 2 since if idea1+idea2 is valid, then idea2+idea1 is also valid numDistinctNames += numExclusiveSuffix1 * numExclusiveSuffix2 * 2 } } return numDistinctNames } /** * Group the suffix (from index 1) of each idea by first letter of the idea. * * Return a list of size 26 that element at index 0 to 25 corresponding to the found suffix * of first letter 'a' to 'z'. * * Require each idea starts with a lowercase english letter, which is stated in the problem * constraints. */ private fun groupSuffixByFirstLetter(ideas: Array<String>): List<Set<String>> { val groups = List(26) { hashSetOf<String>() } for (idea in ideas) { val firstLetter = idea[0] val suffix = idea.slice(1 until idea.length) groups[firstLetter - 'a'].add(suffix) } return groups } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,844
hj-leetcode-kotlin
Apache License 2.0
src/day10/Day10.kt
JakubMosakowski
572,993,890
false
{"Kotlin": 66633}
package day10 import readInput private fun main() { fun part1(input: List<String>): Int { val cycles = input.toCycles() val importantCycles = listOf(20, 60, 100, 140, 180, 220) return importantCycles.sumOf { index -> index * cycles[index - 1] } } fun part2(input: List<String>) { val cycles = input.toCycles() cycles.forEachIndexed { index, value -> if (index == cycles.size - 1) return if (index % 40 == 0) { print("\n") } val sprite = listOf(value - 1, value, value + 1) if (index % 40 in sprite) { print("#") } else { print(".") } } } val testInput = readInput("test_input") check(part1(testInput) == 13140) part2(testInput) val input = readInput("input") println(part1(input)) part2(input) } private fun List<String>.toCycles(): List<Int> { var currentValue = 1 val cycles = mutableListOf(currentValue) forEach { line -> if (line == "noop") { cycles.add(currentValue) } else { val (_, num) = line.split(" ") cycles.add(currentValue) currentValue += num.toInt() cycles.add(currentValue) } } return cycles }
0
Kotlin
0
0
f6e9a0b6c2b66c28f052d461c79ad4f427dbdfc8
1,344
advent-of-code-2022
Apache License 2.0
src/day2/day2.kt
bienenjakob
573,125,960
false
{"Kotlin": 53763}
package day2 import day2.Hand.* import day2.Outcome.* import inputTextOfDay import testTextOfDay enum class Hand(val value: Int) { Rock(1), Paper(2), Scissors(3) } enum class Outcome(val value: Int) { Loose(0), Draw(3), Win(6) } fun part1(text: String): Int { return text.lines().sumOf { evaluate(toHand(it[0]), toHand(it[2])) } } fun part2(text: String): Int { return text.lines().sumOf { evaluate(toHand(it[0]), toOutcome(it[2])) } } fun evaluate(elf: Hand, me: Hand): Int = when (elf) { Rock -> me + when (me) { Rock -> Draw Paper -> Win Scissors -> Loose } Paper -> me + when (me) { Rock -> Loose Paper -> Draw Scissors -> Win } Scissors -> me + when (me) { Rock -> Win Paper -> Loose Scissors -> Draw } } fun evaluate(elf: Hand, outcome: Outcome): Int = when (elf) { Rock -> outcome + when (outcome) { Loose -> Scissors Draw -> Rock Win -> Paper } Paper -> outcome + when (outcome) { Loose -> Rock Draw -> Paper Win -> Scissors } Scissors -> outcome + when (outcome) { Loose -> Paper Win -> Rock Draw -> Scissors } } fun toHand(hand: Char): Hand = when (hand) { 'A', 'X' -> Rock 'B', 'Y' -> Paper else -> Scissors } fun toOutcome(result: Char): Outcome = when (result) { 'X' -> Loose 'Y' -> Draw else -> Win } private operator fun Hand.plus(outcome: Outcome): Int = this.value + outcome.value private operator fun Outcome.plus(hand: Hand): Int = this.value + hand.value fun main() { val day = 2 val test = testTextOfDay(day) check(part1(test) == 15) val input = inputTextOfDay(day) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6ff34edab6f7b4b0630fb2760120725bed725daa
1,806
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/day3/Part2.kts
holmesdev
726,678,749
false
{"Kotlin": 9531}
import java.io.File val partNumberRegex = Regex("\\d+") val partRegex = Regex("\\*") data class PartNumber(val partNumber: Int, val range: IntRange) fun getPartNumbers(line: String): List<PartNumber> { return partNumberRegex.findAll(line).map { PartNumber(it.value.toInt(), it.range) }.toList() } fun getParts(line: String): List<Int> { return partRegex.findAll(line).map { it.range.first }.toList() } fun isGear(part: Int, previousPartNumbers: List<PartNumber>, currentPartNumbers: List<PartNumber>, nextPartNumbers: List<PartNumber>): Boolean { val previousCount = previousPartNumbers.count { part >= (it.range.first - 1) && part <= (it.range.last + 1) } val currentCount = currentPartNumbers.count { part >= (it.range.first - 1) && part <= (it.range.last + 1) } val nextCount = nextPartNumbers.count { part >= (it.range.first - 1) && part <= (it.range.last + 1) } println("$previousCount, $currentCount, $nextCount") return previousCount + currentCount + nextCount == 2 } fun getGearRatio(part: Int, previousPartNumbers: List<PartNumber>, currentPartNumbers: List<PartNumber>, nextPartNumbers: List<PartNumber>): Int { val previousPartNumbers = previousPartNumbers.filter { part >= (it.range.first - 1) && part <= (it.range.last + 1) } val currentPartNumbers = currentPartNumbers.filter { part >= (it.range.first - 1) && part <= (it.range.last + 1) } val nextPartNumbers = nextPartNumbers.filter { part >= (it.range.first - 1) && part <= (it.range.last + 1) } return (previousPartNumbers.fold(1, { acc, pn -> acc * pn.partNumber }) * currentPartNumbers.fold(1, { acc, pn -> acc * pn.partNumber }) * nextPartNumbers.fold(1, { acc, pn -> acc * pn.partNumber })) } val partsMap = mutableListOf<List<Int>>() val partNumbersMap = mutableListOf<List<PartNumber>>() var value = 0 File("input.txt").bufferedReader().useLines { lines -> lines.forEach { partsMap.add(getParts(it)) partNumbersMap.add(getPartNumbers(it)) } } for (y in 0 until partsMap.size) { for(part in partsMap[y]) { if(isGear(part, partNumbersMap.getOrElse(y - 1, { listOf() }), partNumbersMap[y], partNumbersMap.getOrElse(y + 1, { listOf() }))) { println("$part, $y") value += getGearRatio(part, partNumbersMap.getOrElse(y - 1, { listOf() }), partNumbersMap[y], partNumbersMap.getOrElse(y + 1, { listOf() })) } } } println(value)
0
Kotlin
0
0
6098b7e304e3e388467168a69d51c281035c04db
2,422
advent-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/PermutationInString.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 private const val MAX = 25 fun interface StringPermutationStrategy { operator fun invoke(s1: String, s2: String): Boolean fun matches(s1map: IntArray, s2map: IntArray): Boolean { for (i in 0..MAX) { if (s1map[i] != s2map[i]) return false } return true } } class PermutationBruteForce : StringPermutationStrategy { private var flag = false override operator fun invoke(s1: String, s2: String): Boolean { permute(s1, s2, 0) return flag } fun swap(s: String, i0: Int, i1: Int): String { if (i0 == i1) return s val s1 = s.substring(0, i0) val s2 = s.substring(i0 + 1, i1) val s3 = s.substring(i1 + 1) return s1 + s[i1] + s2 + s[i0] + s3 } private fun permute(str1: String, s2: String, l: Int) { var s1 = str1 if (l == s1.length) { if (s2.indexOf(s1) >= 0) flag = true } else { for (i in l until s1.length) { s1 = swap(s1, l, i) permute(s1, s2, l + 1) s1 = swap(s1, l, i) } } } } class PermutationSorting : StringPermutationStrategy { override operator fun invoke(s1: String, s2: String): Boolean { for (i in 0..s2.length - s1.length) { if (s1 == sort(s2.substring(i, i + s1.length))) return true } return false } private fun sort(s: String): String { val t = s.toCharArray() t.sort() return String(t) } } class PermutationHashmap : StringPermutationStrategy { override operator fun invoke(s1: String, s2: String): Boolean { if (s1.length > s2.length) return false val s1map: HashMap<Char?, Int?> = HashMap() for (i in s1.indices) s1map[s1[i]] = s1map.getOrDefault(s1[i], 0)!! + 1 for (i in 0..s2.length - s1.length) { val s2map: HashMap<Char?, Int> = HashMap() for (j in s1.indices) { s2map[s2[i + j]] = s2map.getOrDefault(s2[i + j], 0) + 1 } if (matches(s1map, s2map)) return true } return false } private fun matches(s1map: HashMap<Char?, Int?>, s2map: HashMap<Char?, Int>): Boolean { for (key in s1map.keys) { s1map[key]?.let { if (it - s2map.getOrDefault(key, -1) != 0) return false } } return true } } class PermutationArray : StringPermutationStrategy { override operator fun invoke(s1: String, s2: String): Boolean { if (s1.length > s2.length) return false val s1map = IntArray(MAX + 1) for (i in s1.indices) s1map[s1[i] - 'a']++ for (i in 0..s2.length - s1.length) { val s2map = IntArray(MAX + 1) for (j in s1.indices) { s2map[s2[i + j] - 'a']++ } if (matches(s1map, s2map)) return true } return false } } class PermutationSlidingWindow : StringPermutationStrategy { override operator fun invoke(s1: String, s2: String): Boolean { if (s1.length > s2.length) return false val s1map = IntArray(MAX + 1) val s2map = IntArray(MAX + 1) for (i in s1.indices) { s1map[s1[i] - 'a']++ s2map[s2[i] - 'a']++ } for (i in 0 until s2.length - s1.length) { if (matches(s1map, s2map)) return true s2map[s2[i + s1.length] - 'a']++ s2map[s2[i] - 'a']-- } return matches(s1map, s2map) } } class PermutationOptimizedSlidingWindow : StringPermutationStrategy { override operator fun invoke(s1: String, s2: String): Boolean { if (s1.length > s2.length) return false val s1map = IntArray(MAX + 1) val s2map = IntArray(MAX + 1) for (i in s1.indices) { s1map[s1[i] - 'a']++ s2map[s2[i] - 'a']++ } var count = 0 for (i in 0..MAX) if (s1map[i] == s2map[i]) count++ for (i in 0 until s2.length - s1.length) { val r: Int = s2[i + s1.length] - 'a' val l: Int = s2[i] - 'a' if (count == MAX + 1) return true s2map[r]++ if (s2map[r] == s1map[r]) count++ else if (s2map[r] == s1map[r] + 1) count-- s2map[l]-- if (s2map[l] == s1map[l]) count++ else if (s2map[l] == s1map[l] - 1) count-- } return count == MAX + 1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,143
kotlab
Apache License 2.0
src/main/kotlin/advent2019/day4/day4.kt
davidpricedev
225,621,794
false
null
package advent2019.day4 fun main() { runRangePart1(264360, 746325) runRangePart2(264360, 746325) } fun runRangePart1(start: Int, end: Int) = println((start..end).filter(::filterPart1).count()) fun runRangePart2(start: Int, end: Int) = println((start..end).filter(::filterPart2).count()) fun filterPart1(number: Int): Boolean { val digits = number.toString().map { it.toInt() } val uniqueDigits = digits.toSet() val is6Digits = digits.count() == 6 val hasDouble = uniqueDigits.count() < 6 val isIncreasing = digits.mapIndexed { i, it -> i == 0 || it >= digits[i - 1] }.reduce { acc, it -> acc && it } return is6Digits && hasDouble && isIncreasing } fun filterPart2(number: Int): Boolean { val digits = number.toString().map { it.toInt() } return filterPart1(number) && hasDigitAppearingExactlyTwice(digits) } fun hasDigitAppearingExactlyTwice(digits: List<Int>) = digits.groupBy { it }.map { it.value.count() }.contains(2)
0
Kotlin
0
0
2283647e5b4ed15ced27dcf2a5cf552c7bd49ae9
980
adventOfCode2019
Apache License 2.0
src/day09/Day09ToddGinsbergSolution.kt
commanderpepper
574,647,779
false
{"Kotlin": 44999}
package day09 import readInput import kotlin.math.absoluteValue import kotlin.math.sign // I was unable to solve part two of day nine, so I am using Todd's solution to learn more about the problem // His solution https://todd.ginsberg.com/post/advent-of-code/2022/day9/ fun main(){ val input = readInput("day09") val headPath: String = parseInput(input) println(headPath) fun solvePart1(): Int = followPath(headPath, 2) fun solvePart2(): Int = followPath(headPath, 10) println(solvePart1()) println(solvePart2()) } private fun parseInput(input: List<String>): String = input.joinToString("") { row -> val direction = row.substringBefore(" ") val numberOfMoves = row.substringAfter(' ').toInt() direction.repeat(numberOfMoves) } data class Point(val x: Int = 0, val y: Int = 0) { fun move(direction: Char): Point = when (direction) { 'U' -> copy(y = y - 1) 'D' -> copy(y = y + 1) 'L' -> copy(x = x - 1) 'R' -> copy(x = x + 1) else -> throw IllegalArgumentException("Unknown Direction: $direction") } } fun followPathToBeRefactored(headPath: String): Int { var head = Point() var tail = Point() val tailVisits = mutableSetOf(Point()) headPath.forEach { direction -> head = head.move(direction) if (head.touches(tail).not()) { tail = tail.moveTowards(head) } tailVisits += tail } return tailVisits.size } fun Point.touches(other: Point): Boolean = (x - other.x).absoluteValue <= 1 && (y - other.y).absoluteValue <= 1 fun Point.moveTowards(other: Point): Point = Point( (other.x - x).sign + x, (other.y - y).sign + y ) private fun followPath(headPath: String, knots: Int): Int { val rope = Array(knots) { Point() } val tailVisits = mutableSetOf(Point()) headPath.forEach { direction -> rope[0] = rope[0].move(direction) rope.indices.windowed(2, 1) { (head, tail) -> if (rope[head].touches(rope[tail]).not()) { rope[tail] = rope[tail].moveTowards(rope[head]) } } tailVisits += rope.last() } return tailVisits.size }
0
Kotlin
0
0
fef291c511408c1a6f34a24ed7070ceabc0894a1
2,249
advent-of-code-kotlin-2022
Apache License 2.0
src/day05/Day05.kt
scottpeterson
573,109,888
false
{"Kotlin": 15611}
fun main() { data class Move(val count: Int, val from: Int, val to: Int) fun parseInput(stringInput: List<String>): Pair<List<MutableList<Char>>, List<Move>> { val blankLineIndex = stringInput.indexOfFirst(String::isBlank) val crateCount = stringInput[blankLineIndex - 1] .last(Char::isDigit) .digitToInt() val crates = List(size = crateCount) { mutableListOf<Char>() } stringInput.subList(0, blankLineIndex - 1).asReversed().forEach { line -> line.chunked(4).forEachIndexed { index, content -> content[1].takeIf(Char::isLetter)?.let(crates[index]::plusAssign) } } val moves = stringInput.subList(blankLineIndex + 1, stringInput.size) .map { val split = it.split(" ") Move(split[1].toInt(), split[3].toInt() - 1, split[5].toInt() - 1) } return Pair(crates, moves) } fun tops(crates: List<MutableList<Char>>) = crates.map(List<Char>::last).joinToString(separator = "") fun partOne(stringInput: List<String>): String { val (crates, moves) = parseInput(stringInput) moves.forEach { move -> repeat(move.count) { crates[move.to] += crates[move.from].removeLast() } } println(tops(crates)) return tops(crates) } fun <T> MutableList<T>.removeLast(count: Int): List<T> { val removeIndex = this.size - count return List(size = count) { this.removeAt(removeIndex) } } fun partTwo(stringInput: List<String>): String { val (crates, moves) = parseInput(stringInput) moves.forEach { move -> crates[move.to] += crates[move.from].removeLast(move.count) } println(tops(crates)) return tops(crates) } partOne(readInput("day05/Day05_input")) partTwo(readInput("day05/Day05_input")) }
0
Kotlin
0
0
0d86213c5e0cd5403349366d0f71e0c09588ca70
1,959
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day24.kt
Yeah69
317,335,309
false
{"Kotlin": 73241}
class Day24 : Day() { override val label: String get() = "24" private enum class Direction { EAST, SOUTHEAST, SOUTHWEST, WEST, NORTHWEST, NORTHEAST } private val initialBlackTiles by lazy { input .lineSequence() .map { var rest = it val instructions = mutableListOf<Direction>() while (rest.isBlank().not()) { var takeTwo = true when { rest.startsWith("e" ) -> { instructions.add(Direction.EAST ); takeTwo = false } rest.startsWith("w" ) -> { instructions.add(Direction.WEST ); takeTwo = false } rest.startsWith("se") -> instructions.add(Direction.SOUTHEAST) rest.startsWith("sw") -> instructions.add(Direction.SOUTHWEST) rest.startsWith("ne") -> instructions.add(Direction.NORTHEAST) rest.startsWith("nw") -> instructions.add(Direction.NORTHWEST) } rest = rest.substring(if(takeTwo) 2 else 1) } instructions } .map { it.fold(0 to 0) { acc, direction -> when (direction) { Direction.WEST -> acc.first - 2 to acc.second Direction.EAST -> acc.first + 2 to acc.second Direction.NORTHWEST -> acc.first - 1 to acc.second - 1 Direction.NORTHEAST -> acc.first + 1 to acc.second - 1 Direction.SOUTHWEST -> acc.first - 1 to acc.second + 1 Direction.SOUTHEAST -> acc.first + 1 to acc.second + 1 } } } .groupBy { it } .filter { it.value.count() % 2 == 1 } .map { it.key } .toList() } override fun taskZeroLogic(): String = initialBlackTiles.count().toString() override fun taskOneLogic(): String = (1..100) .fold(initialBlackTiles.toHashSet()) { acc, _ -> fun Pair<Int, Int>.neighbors(): Sequence<Pair<Int, Int>> { val it = this return sequence { yield(it.first - 1 to it.second - 1); yield(it.first + 1 to it.second - 1) yield(it.first - 2 to it.second); yield(it.first + 2 to it.second) yield(it.first - 1 to it.second + 1); yield(it.first + 1 to it.second + 1) } } val stayBlack = acc .filter { val blackNeighbors = it.neighbors().filter { n -> acc.contains(n) }.count() blackNeighbors == 1 || blackNeighbors == 2 } val flipToBlack = acc .flatMap { it.neighbors() } .filterNot { acc.contains(it) } .filter { it.neighbors().filter { n -> acc.contains(n) }.count() == 2 } (stayBlack + flipToBlack).toHashSet() } .count() .toString() }
0
Kotlin
0
0
23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec
2,926
AdventOfCodeKotlin
The Unlicense
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-13.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.TspGraph import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2015, "13-input") val test1 = readInputLines(2015, "13-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val graph = parse(input) return graph.solveCircularTsp { o1, o2 -> o2 - o1 } } private fun part2(input: List<String>): Int { val graph = parse(input) return graph.solveTsp { o1, o2 -> o2 - o1 } } private fun parse(input: List<String>): TspGraph { val map = mutableMapOf<Set<String>, Int>() input.map { val (p1, op, value, p2) = regex.matchEntire(it)!!.destructured val set = setOf(p1, p2) val newValue = map.getOrDefault(set, 0) + if (op == "gain") value.toInt() else -value.toInt() map[set] = newValue } val graph = TspGraph() map.forEach { (key, value) -> val (p1, p2) = key.toList() graph.addBidirectionalEdge(p1, p2, value) } return graph } private val regex = """(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+).""".toRegex()
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,383
advent-of-code
MIT License
games-impl/src/commonMain/kotlin/net/zomis/games/common/cards/probabilities/CardProbabilityUtils.kt
Zomis
125,767,793
false
{"Kotlin": 1346310, "Vue": 212095, "JavaScript": 43020, "CSS": 4513, "HTML": 1459, "Shell": 801, "Dockerfile": 348}
package net.zomis.games.cards.probabilities enum class CountStyle { EQUAL, NOT_EQUAL, MORE_THAN, LESS_THAN, UNKNOWN, DONE } object Combinatorics { fun NNKKnoDiv(N: Int, n: Int, K: Int, k: Int): Double { return nCr(K, k) * nCr(N - K, n - k) } fun NNKKdistribution(N: Int, n: Int, K: Int): DoubleArray? { val nnkkArray = DoubleArray(K + 1) for (i in 0..K) { nnkkArray[i] = NNKKwithDiv(N, n, K, i) } return nnkkArray } fun NNKKwithDiv(N: Int, n: Int, K: Int, k: Int): Double { return NNKKnoDiv(N, n, K, k) / nCr(N, n) } fun nPr(n: Int, r: Int): Double { var result = 1.0 for (i in n downTo n - r + 1) result *= i return result } fun nCr(n: Int, r: Int): Double { if (r > n || r < 0) return 0.0 if (r == 0 || r == n) return 1.0 var start = 1.0 for (i in 0 until r) { start = start * (n - i) / (r - i) } return start } fun specificCombination(elements: Int, size: Int, combinationNumber: Double): IntArray { require(combinationNumber > 0) { "Combination must be positive" } require(!(elements < 0 || size < 0)) { "Elements and size cannot be negative" } val result = IntArray(size) var resultIndex = 0 var nextNumber = 0 var combination = combinationNumber var remainingSize = size var remainingElements = elements while (remainingSize > 0) { val ncr = nCr(remainingElements - 1, remainingSize - 1) require(ncr > 0) { "Combination out of range: $combinationNumber with $elements elements and size $size" } if (combination.compareTo(ncr) <= 0) { result[resultIndex] = nextNumber remainingSize-- resultIndex++ } else { combination -= ncr } remainingElements-- nextNumber++ } return result } fun specificPermutation(elements: Int, combinationNumber: Int): IntArray { require(elements >= 1) require(combinationNumber >= 0) { "combination number must be >= 0" } val factorial = nPr(elements, elements) require(combinationNumber < factorial) { "combination number must be < factorial(elements) ($factorial)" } val result = IntArray(elements) var remainingCombinationNumber = combinationNumber val numbers = (0 until elements).toMutableList() for (i in 0 until elements) { val elementsRemaining = elements - i val div = remainingCombinationNumber / elementsRemaining val mod = remainingCombinationNumber % elementsRemaining result[i] = numbers[mod] numbers.removeAt(mod) remainingCombinationNumber = div } return result } }
89
Kotlin
5
17
dd9f0e6c87f6e1b59b31c1bc609323dbca7b5df0
2,913
Games
MIT License
src/day02/Day02_Part2.kt
m-jaekel
570,582,194
false
{"Kotlin": 13764}
package day02 import readInput fun main() { /** * X -> lose * Y -> draw * Z -> win */ fun part2(input: List<String>): Int { var score = 0 input.forEach { val shapes: List<String> = it.chunked(1) val round = playRound(shapes[0], shapes[2]) score += round.second + getShapeScore(round.first) } return score } val testInput = readInput("day02/test_input") check(part2(testInput) == 12) val input = readInput("day02/input") println(part2(input)) } private fun playRound(opponent: String, condition: String): Pair<String, Int> = when { opponent == "A" && condition == "Y" -> Pair("A", 3) opponent == "A" && condition == "X" -> Pair("C", 0) opponent == "A" && condition == "Z" -> Pair("B", 6) opponent == "B" && condition == "X" -> Pair("A", 0) opponent == "B" && condition == "Y" -> Pair("B", 3) opponent == "B" && condition == "Z" -> Pair("C", 6) opponent == "C" && condition == "X" -> Pair("B", 0) opponent == "C" && condition == "Z" -> Pair("A", 6) opponent == "C" && condition == "Y" -> Pair("C", 3) else -> throw Exception("invalid") } private fun getShapeScore(shape: String): Int = when (shape) { "A" -> 1 "B" -> 2 else -> 3 }
0
Kotlin
0
1
07e015c2680b5623a16121e5314017ddcb40c06c
1,306
AOC-2022
Apache License 2.0
src/main/kotlin/kr/co/programmers/P160585.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://github.com/antop-dev/algorithm/issues/506 class P160585 { fun solution(board: Array<String>): Int { val (oCount, oWin) = check(board, 'O') val (xCount, xWin) = check(board, 'X') return when { // "O"나 "X"의 개수 차이가 나면 안된다. oCount - xCount > 1 || xCount > oCount -> 0 // "O"와 "X"의 개수가 같을 때, 무승부 이거나 후공인 "X"가 이겨야 된다. oCount == xCount && ((oWin == 0 && xWin == 0) || (oWin == 0 && xWin > 0)) -> 1 // "O"가 "X"보다 1개만 더 많을 때, 무승부 이거나 선공인 "O"가 이겨야 된다. oCount > xCount && ((oWin == 0 && xWin == 0) || (oWin > 0 && xWin == 0)) -> 1 // 나머지 경우는 비정상적인 게임 else -> 0 } } private fun check(b: Array<String>, ch: Char): IntArray { val check = intArrayOf(0, 0) // 개수 for (i in 0 until 3) { for (j in 0 until 3) { if (b[i][j] == ch) { check[0]++ } } } // 가로줄 if (b[0][0] == ch && b[0][1] == ch && b[0][2] == ch) check[1]++ if (b[1][0] == ch && b[1][1] == ch && b[1][2] == ch) check[1]++ if (b[2][0] == ch && b[2][1] == ch && b[2][2] == ch) check[1]++ // 세로중 if (b[0][0] == ch && b[1][0] == ch && b[2][0] == ch) check[1]++ if (b[0][1] == ch && b[1][1] == ch && b[2][1] == ch) check[1]++ if (b[0][2] == ch && b[1][2] == ch && b[2][2] == ch) check[1]++ // 대각선 if (b[0][0] == ch && b[1][1] == ch && b[2][2] == ch) check[1]++ if (b[0][2] == ch && b[1][1] == ch && b[2][0] == ch) check[1]++ return check } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,835
algorithm
MIT License
src/y2022/Day24.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.Cardinal import util.Cardinal.EAST import util.Cardinal.NORTH import util.Cardinal.SOUTH import util.Cardinal.WEST import util.Cardinal.values import util.Pos import util.printGrid import util.readInput import kotlin.system.measureTimeMillis object Day24 { data class Blizzard(val pos: Pos, val dir: Cardinal) data class Valley( var blizzards: List<Blizzard>, val height: Int, val width: Int, ) { val end = height to width - 1 fun step() { blizzards = blizzards.map { val (newR, newC) = it.dir.of(it.pos) it.copy(pos = newR.mod(height) to newC.mod(width)) } } } private fun parse(input: List<String>): Valley { val blizzards = input.drop(1).dropLast(1).mapIndexed { rowIdx, ln -> ln.drop(1).dropLast(1).mapIndexed { colIdx, c -> fromChar(c)?.let { Blizzard(rowIdx to colIdx, it) } } }.flatten().filterNotNull() return Valley(blizzards, input.size - 2, input.first().length - 2) } fun fromChar(c: Char) = when (c) { '>' -> EAST '<' -> WEST '^' -> NORTH 'v' -> SOUTH else -> null } fun part1(input: List<String>): Int { val valley = parse(input) var frontier = setOf(-1 to 0) var minutes = 0 while (valley.end !in frontier) { minutes++ valley.step() frontier = nextFrontier(frontier, valley) } return minutes } fun part2(input: List<String>): Int { val valley = parse(input) val sizes = mutableListOf(1) var frontier = setOf(-1 to 0) var minutes = 0 while (valley.end !in frontier) { minutes++ valley.step() frontier = nextFrontier(frontier, valley) sizes.add(frontier.size) } printGrid(frontier.associateWith { "[]" } + valley.blizzards.associate { it.pos to "**" }, 2) frontier = setOf(valley.end) while (-1 to 0 !in frontier) { minutes++ valley.step() frontier = nextFrontier(frontier, valley) sizes.add(frontier.size) } printGrid(frontier.associateWith { "[]" } + valley.blizzards.associate { it.pos to "**" }, 2) frontier = setOf(-1 to 0) while (valley.end !in frontier) { minutes++ valley.step() frontier = nextFrontier(frontier, valley) sizes.add(frontier.size) } printGrid(frontier.associateWith { "[]" } + valley.blizzards.associate { it.pos to "**" }, 2) println("max frontier: ${sizes.max()}") return minutes } private fun nextFrontier( frontier: Set<Pair<Int, Int>>, valley: Valley, ) = frontier.flatMap { p -> values().map { it.of(p) } + p } .filter { (it.first in 0 until valley.height && it.second in 0 until valley.width) || it == -1 to 0 || it == valley.end }.toSet() - valley.blizzards.map { it.pos }.toSet() } fun main() { val testInput = """ #.###### #>>.<^<# #.<..<<# #>v.><># #<^v^^># ######.# """.trimIndent().split("\n") println("------Tests------") println(Day24.part1(testInput)) println(Day24.part2(testInput)) println("------Real------") val input = readInput("resources/2022/day24") println(Day24.part1(input)) val t = measureTimeMillis { println(Day24.part2(input)) } println("millis elapsed: $t") }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
3,668
advent-of-code
Apache License 2.0
day23/src/main/kotlin/Day23.kt
bzabor
160,240,195
false
null
import kotlin.math.abs class Day23(private val input: List<String>) { // pos=<0,0,0>, r=4 // pos=<1,0,0>, r=1 // pos=<4,0,0>, r=3 // pos=<0,2,0>, r=1 // pos=<0,5,0>, r=3 // pos=<0,0,3>, r=1 // pos=<1,1,1>, r=1 // pos=<1,1,2>, r=1 // pos=<1,3,1>, r=1 // [, 0, 0, 0, 4] // [, 1, 0, 0, 1] // [, 4, 0, 0, 3] // [, 0, 2, 0, 1] val posList = mutableListOf<Node>() private fun init() { var idx = 0 for (line in input) { val a = line.split("""[^-0-9]+""".toRegex()).drop(1).map{it.toLong()} posList.add(Node(a[0], a[1], a[2], a[3])) println(a) } } fun part1(): Int { init() posList.sortByDescending { it.r } posList.forEach { println(it) } val largest = posList.take(1)[0] val countInRadius = posList.filter { abs(largest.x - it.x) + abs(largest.y - it.y) + abs(largest.z - it.z) <= largest.r }.count() return countInRadius } fun part2(): Int { posList.sortBy { it.x } val minX = posList.first().x val maxX = posList.last().x posList.sortBy { it.y } val minY = posList.first().y val maxY = posList.last().y posList.sortBy { it.z } val minZ = posList.first().z val maxZ = posList.last().z println("minx: $minX maxX: $maxX minY: $minY maxY: $maxY minZ: $minZ maxZ: $maxZ") for (x in minX..maxX) { for (y in minY..maxY) { for (z in minZ..maxZ) { for (pos in posList) { } } } } return 0 } } class Node( val x: Long = 0, val y: Long = 0, val z: Long = 0, val r: Long = 0) { override fun toString() = "$x:$y:$z - $r" }
0
Kotlin
0
0
14382957d43a250886e264a01dd199c5b3e60edb
1,907
AdventOfCode2018
Apache License 2.0
2021/src/main/kotlin/Day14.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
class Day14(val input: List<String>) { private val template = input[0] private val rules = input[1].split("\n").groupBy({ it.substringBefore(" -> ") }, { it.substringAfter(" -> ") }) .mapValues { it.value.single() } private fun transform(steps: Int): Long { val initial = template.windowed(2).groupingBy { it }.eachCount().mapValues { it.value.toLong() } val pairsCount = (0 until steps).fold(initial) { current, _ -> buildMap { current.forEach { (pair, count) -> with(pair[0] + rules.getValue(pair)) { put(this, getOrDefault(this, 0) + count) } with(rules.getValue(pair) + pair[1]) { put(this, getOrDefault(this, 0) + count) } } } } val charsCount = buildMap<Char, Long> { put(template[0], 1) pairsCount.forEach { (pair, count) -> put(pair[1], getOrDefault(pair[1], 0) + count) } } return charsCount.maxOf { it.value } - charsCount.minOf { it.value } } fun solve1(): Long { return transform(10) } fun solve2(): Long { return transform(40) } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
1,203
adventofcode-2021-2025
MIT License
2022/src/day07/Day07.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day07 import java.io.File fun main() { val input = File("src/day07/day07input.txt").readLines() val parser = FileSystemParser(input) parser.processCommands() val node = parser.getRootNode() println(getSumDirectoriesAtMost(node as FolderNode, 100000)) println(getCandidateDir(node as FolderNode, 70000000, 30000000)!!.getSize()) } class FileSystemParser { private var _currentNode: FolderNode? = null private var _rootNode: FolderNode? = null private val _commands: List<String> var index: Int constructor(commands: List<String>) { this._commands = commands index = 0 } fun getRootNode(): Node? { return _rootNode } fun processCommands() { var processingFiles: Boolean = false while (index < this._commands.size) { val command = _commands[index] if (command.startsWith("$ cd")) { processingFiles = false // create child or root with name changeDirectory(command.substring(5)) } else if (command.startsWith("$ ls")) { // Now process the list of files processingFiles = true } else { if (processingFiles) { if (command.startsWith("dir")) { // create a new directory in the current node _currentNode!!.addChild(FolderNode(command.substring(4), _currentNode)) } else { // This is a file val (size, name) = command.split(" ") _currentNode!!.addChild(FileNode(name, size.toInt())) } } else { throw Exception("Processing file before ls called") } } index++ } } private fun changeDirectory(name: String) { if (name == "/") { // Create the root node if (_rootNode == null) { _rootNode = FolderNode("/", null) } _currentNode = _rootNode } else if (name == "..") { if (_currentNode == null) { throw Exception("Can't go up from null directory") } _currentNode = _currentNode!!.getParent() } else { if (_currentNode != null) { var node = _currentNode!!.getChildFolder(name) if (node == null) { // create the node node = FolderNode(name, _currentNode) _currentNode!!.addChild(node) } _currentNode = node } else { throw Exception("Can't create a non root node when there is no current node. $name") } } } } fun getSumDirectoriesAtMost(node: FolderNode, limit: Int): Int { val nodes = mutableListOf<FolderNode>(node) val foundNodes = mutableListOf<FolderNode>() while (nodes.isNotEmpty()) { val currentNode = nodes.removeFirst() if (currentNode.getSize() <= limit) { foundNodes.add(currentNode) } nodes.addAll(currentNode.getFolderChildren()) } return foundNodes.sumOf { it.getSize() } } fun getDirectoriesBySize(node: FolderNode): List<FolderNode> { val nodes = mutableListOf(node) val returnNodes = mutableListOf<FolderNode>() while (nodes.isNotEmpty()) { val currentNode = nodes.removeFirst() returnNodes.add(currentNode) nodes.addAll(currentNode.getFolderChildren()) } return returnNodes.sortedBy { it.getSize() } } fun getCandidateDir(root: FolderNode, maxSize: Int, updateSize: Int): FolderNode? { val requiredSize = root.getSize() - (maxSize - updateSize) val nodes = getDirectoriesBySize(root) return nodes.find { it.getSize() >= requiredSize } } abstract class Node { private val _name: String constructor(name: String) { this._name = name } fun getName(): String { return _name } abstract fun getSize(): Int abstract fun toString(indent: Int = 0): String } class FolderNode : Node { private val _parent: FolderNode? private val _children: MutableList<Node> constructor(name: String, parent: FolderNode?) : super(name) { this._parent = parent this._children = mutableListOf() } fun getParent(): FolderNode? { return _parent } fun getFolderChildren(): List<FolderNode> { return _children.filterIsInstance<FolderNode>() } override fun getSize(): Int { return _children.sumOf { it.getSize() } } override fun toString(indent: Int): String { val childString = _children.joinToString("\n") { it.toString(indent + 2) } return ' '.toString().repeat(indent) + "- ${getName()} (dir)\n$childString" } fun getChildFolder(name: String): FolderNode? { var node = this._children.find { it.getName() == name } return if (node is FolderNode) { node } else { null } } fun addChild(node: Node) { _children.add(node) } } class FileNode : Node { private val _size: Int constructor(name: String, size: Int) : super(name) { this._size = size } override fun getSize(): Int { return _size } override fun toString(indent: Int): String { return ' '.toString().repeat(indent) + "- ${getName()} (file, size=$_size)" } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
5,562
adventofcode
Apache License 2.0
src/main/kotlin/Day3.kt
FredrikFolkesson
320,692,155
false
null
class Day3 { fun getNumberOfTrees(input: List<String>, right: Int, down: Int): Int { val sizeOfOneLine = input[0].length return input.filterIndexed { index, it -> index % down == 0 && it[((right / down.toDouble()) * index).toInt() % sizeOfOneLine] == '#' } .count() } } fun numberOfTrees(input: List<String>): Long { return numberOfTrees(input, 1, 1) * numberOfTrees(input, 3, 1) * numberOfTrees(input, 5, 1) * numberOfTrees( input, 7, 1 ) * numberOfTrees(input, 1, 2) } private fun numberOfTrees(input: List<String>, slopeRight: Int, slopeDown: Int): Long { var count = 0L var previousPosition = 0 for (i in slopeDown until input.size step slopeDown) { val line = input[i] val position = (previousPosition + slopeRight) % line.length if (line[position] == '#') count++ previousPosition = position } return count }
0
Kotlin
0
0
79a67f88e1fcf950e77459a4f3343353cfc1d48a
941
advent-of-code
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1162/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1162 /** * LeetCode page: [1162. As Far from Land as Possible](https://leetcode.com/problems/as-far-from-land-as-possible/); */ class Solution { /* Complexity: * Time O(N^2) and Space O(N^2) where N is the size of grid; */ fun maxDistance(grid: Array<IntArray>): Int { val visited = grid.clone() val allCurrentNeighbours = ArrayDeque<Cell>() var maxDistance = 0 allCurrentNeighbours.addAllLands(visited) val isAllWatersOrAllLands = allCurrentNeighbours.size.let { it == 0 || it == grid.size * grid.size } if (isAllWatersOrAllLands) return -1 while (allCurrentNeighbours.isNotEmpty()) { repeat(allCurrentNeighbours.size) { val cell = allCurrentNeighbours.removeFirst() val neighbours = cell.neighbours() for (neighbour in neighbours) { val isWaterAndNotVisited = visited.has(neighbour) && visited.valueAt(neighbour) == 0 if (isWaterAndNotVisited) { allCurrentNeighbours.addLast(neighbour) visited.setValueAt(neighbour, 1) } } } if (allCurrentNeighbours.isNotEmpty()) maxDistance++ } return maxDistance } private data class Cell(val row: Int, val column: Int) private fun ArrayDeque<Cell>.addAllLands(grid: Array<IntArray>) { for (row in grid.indices) { for (column in grid[row].indices) { val isLand = grid[row][column] == 1 if (isLand) { addLast(Cell(row, column)) } } } } private fun Cell.neighbours(): List<Cell> { return listOf( Cell(row - 1, column), Cell(row + 1, column), Cell(row, column - 1), Cell(row, column + 1) ) } private fun Array<IntArray>.has(cell: Cell): Boolean { return cell.row in indices && cell.column in this[cell.row].indices } private fun Array<IntArray>.valueAt(cell: Cell): Int { return this[cell.row][cell.column] } private fun Array<IntArray>.setValueAt(cell: Cell, newValue: Int) { this[cell.row][cell.column] = newValue } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,382
hj-leetcode-kotlin
Apache License 2.0
src/day9/Day09.kt
JoeSkedulo
573,328,678
false
{"Kotlin": 69788}
package day9 import Runner import day9.Direction.* import kotlin.math.abs fun main() { Day9Runner().solve() } class Day9Runner : Runner<Int>( day = 9, expectedPartOneTestAnswer = 13, expectedPartTwoTestAnswer = 1 ) { override fun partOne(input: List<String>, test: Boolean): Int { return getPositions(input) .filter { knot -> knot.index == 1 } .distinctBy { knot -> "${knot.x}:${knot.y}" } .count() } override fun partTwo(input: List<String>, test: Boolean): Int { return getPositions(input, knots = 10) .filter { knot -> knot.index == 9 } .distinctBy { knot -> "${knot.x}:${knot.y}" } .count() } private fun getPositions( input: List<String>, knots: Int = 2 ) : List<KnotPosition> { return buildList { addAll(initialPositions(knots)) moves(input).forEach { move -> addAll(moveRope(this, move, knots)) } } } private fun moveRope( currentPositions: List<KnotPosition>, move: Move, knots: Int = 2 ) : List<KnotPosition> { return buildList { val currentFirstKnotPosition = currentPositions.last { it.index == 0 } repeat(move.steps) { step -> repeat(knots) { index -> if (index == 0) { add(currentFirstKnotPosition.move(direction = move.direction, step = step + 1)) } else { val currentKnotPosition = this.lastOrNull { it.index == index } ?: currentPositions.last { it.index == index } val newKnotBeforePosition = this.last { it.index == index - 1 } add(knotPosition(currentKnotPosition, newKnotBeforePosition)) } } } } } private fun knotPosition( currentKnotPosition: KnotPosition, knotToTouch: KnotPosition ) : KnotPosition { val touching = currentKnotPosition.isTouching(knotToTouch) return if (touching) { currentKnotPosition } else { currentKnotPosition.determineMove(knotToTouch) } } private fun initialPositions(count: Int = 2) = buildList { repeat(count) { add(KnotPosition( x = 0, y = 0, index = it )) } } private fun moves(input: List<String>) : List<Move> { return input.map { line -> val split = line.split(" ") Move( direction = split.first().toDirection(), steps = split.last().toInt() ) } } private fun KnotPosition.determineMove(positionToTouch: KnotPosition) : KnotPosition { return if (this.x == positionToTouch.x || this.y == positionToTouch.y) { straightMoves().first { position -> position.isTouching(positionToTouch) } } else { diagonalMoves().first { position -> position.isTouching(positionToTouch) } } } private fun KnotPosition.straightMoves() : List<KnotPosition> { return Direction.values().map { direction -> this.move(direction) } } private fun KnotPosition.diagonalMoves(): List<KnotPosition> { return listOf( this.move(Left).move(Up), this.move(Left).move(Down), this.move(Right).move(Up), this.move(Right).move(Down) ) } private fun KnotPosition.isTouching(other: KnotPosition) : Boolean { val xDifference = other.x - this.x val yDifference = other.y - this.y return (abs(xDifference) <= 1 && abs(yDifference) <= 1) } private fun KnotPosition.move(direction: Direction, step: Int = 1) : KnotPosition = when (direction) { Left -> this.copy(x = this.x - step) Right -> this.copy(x = this.x + step) Up -> this.copy(y = this.y + step) Down -> this.copy(y = this.y - step) } private fun String.toDirection() :Direction = when (this) { "R" -> Right "L" -> Left "U" -> Up "D" -> Down else -> throw RuntimeException() } } data class KnotPosition( val x: Int, val y: Int, val index : Int ) enum class Direction { Left, Right, Up, Down } data class Move( val direction: Direction, val steps: Int )
0
Kotlin
0
0
bd8f4058cef195804c7a057473998bf80b88b781
4,508
advent-of-code
Apache License 2.0
src/Day10.kt
cvb941
572,639,732
false
{"Kotlin": 24794}
import kotlin.math.absoluteValue fun main() { class Crt { private var X = 1 fun processCommands(commands: List<String>): Sequence<Int> = sequence { commands.forEach { val sequence = processCommand(it) yieldAll(sequence) } } fun processCommand(it: String): Sequence<Int> = sequence { // Update X // Read instruction when { it == "noop" -> { // Count score yield(X) } it.split(" ").first() == "addx" -> { val number = it.split(" ")[1].toInt() // Do one empty tick yield(X) // Update X after the second tick yield(X) X += number } } } } fun part1(input: List<String>): Int { var score = 0 val crt = Crt() val history = crt.processCommands(input).toList() history.forEachIndexed { clock, X -> val clock = clock + 1 if ((clock + 20) % 40 == 0) { score += X * clock } } return score } fun part2(input: List<String>): Int { val crt = Crt() val spritePositions = crt.processCommands(input).toList() val buffer = List(spritePositions.size) { '.' }.toMutableList() spritePositions.forEachIndexed { clock, spritePos -> val x = clock % 40 if ((x - spritePos).absoluteValue <= 1) { buffer[clock] = '#' } } // Render buffer buffer.chunked(40).forEach { println(it.joinToString("")) } return 0 } // test if implementation meets criteria from the description, like: val smallInput = readInput("Day10_small") // part1(smallInput) val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check(part2(testInput) == 0) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
fe145b3104535e8ce05d08f044cb2c54c8b17136
2,170
aoc-2022-in-kotlin
Apache License 2.0
src/Day11.kt
arhor
572,349,244
false
{"Kotlin": 36845}
fun main() { val input = readInput {} println("Part 1: ${solvePuzzle(input)}") } private fun solvePuzzle(list: List<String>): ULong { val monkeys = list.split("").map(::Monkey) val factor = lcm(monkeys.map { it.divisor.toInt() }.toIntArray()) fun tick() { for (monkey in monkeys) { for (item in monkey.items) { val newItem = monkey.worry(item % factor) // newItem /= 3 val newMonkey = monkey.whereToThrow(newItem) monkeys[newMonkey].items.add(newItem) } monkey.items.clear() } } repeat(10_000) { tick() } val (a, b) = monkeys.map { it.inspections }.sorted().takeLast(2).map { it.toULong() } return a * b } private class Monkey(info: List<String>) { val items: MutableList<Long> val worry: (Long) -> Long val divisor: Long val onSuccess: Int val onFailure: Int var inspections = 0 private set init { items = info[1].substringAfter("Starting items: ").split(", ").map(String::toLong).toMutableList() worry = info[2].substringAfter("Operation: new = ").split(" ").let { (a, b, c) -> val operator: (Long, Long) -> Long = when (b) { "+" -> Long::plus "-" -> Long::minus "*" -> Long::times "/" -> Long::div else -> throw IllegalStateException("Unsupported operator: $b") } return@let { item -> inspections++ val one = if (a == "old") item else a.toLong() val two = if (c == "old") item else c.toLong() operator(one, two) } } divisor = info[3].substringAfter("divisible by ").toLong() onSuccess = info[4].substringAfter("If true: throw to monkey ").toInt() onFailure = info[5].substringAfter("If false: throw to monkey ").toInt() } fun whereToThrow(item: Long): Int = if (item % divisor == 0L) onSuccess else onFailure }
0
Kotlin
0
0
047d4bdac687fd6719796eb69eab2dd8ebb5ba2f
2,072
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/nl/tiemenschut/aoc/y2023/day10.kt
tschut
723,391,380
false
{"Kotlin": 61206}
package nl.tiemenschut.aoc.y2023 import nl.tiemenschut.aoc.lib.dsl.aoc import nl.tiemenschut.aoc.lib.dsl.day import nl.tiemenschut.aoc.lib.dsl.parser.InputParser import nl.tiemenschut.aoc.lib.util.points.Point import nl.tiemenschut.aoc.lib.util.points.PointInt import nl.tiemenschut.aoc.lib.util.points.by data class TubeMap( val grid: List<MutableList<Char>>, val start: PointInt, ) { fun findConnections(p: Point<Int>): List<Point<Int>> = buildList { if (get(p).connectsUp() && get(p.up()).connectsDown()) add(p.up()) if (get(p).connectsDown() && get(p.down()).connectsUp()) add(p.down()) if (get(p).connectsLeft() && get(p.left()).connectsRight()) add(p.left()) if (get(p).connectsRight() && get(p.right()).connectsLeft()) add(p.right()) } fun get(p: Point<Int>): Char = grid[p.x][p.y] } fun Char.connectsUp() = this in listOf('S', '|', 'L', 'J') fun Char.connectsDown() = this in listOf('S', '|', 'F', '7') fun Char.connectsLeft() = this in listOf('S', '-', 'J', '7') fun Char.connectsRight() = this in listOf('S', '-', 'F', 'L') object TubeMapParser : InputParser<TubeMap> { override fun parse(input: String): TubeMap { val lines = input.split("\n") var start = 0 by 0 val grid = List(lines[0].length + 2) { MutableList(lines.size + 2) { '.' } }.also { grid -> for (y in lines.indices) { for (x in lines[y].indices) { grid[x + 1][y + 1] = lines[y][x] if (grid[x + 1][y + 1] == 'S') start = x by y } } } return TubeMap(grid, start) } } fun main() { aoc(TubeMapParser) { puzzle { 2023 day 10 } part1 { input -> tailrec fun findDistance(c1: Point<Int>, c2: Point<Int>, seen: Set<Point<Int>>, distance: Int): Int { val connections = input.findConnections(c1) + input.findConnections(c2) val newConnections = connections.filter { it !in seen }.toSet() return if (newConnections.size == 1) { distance } else { findDistance(newConnections.first(), newConnections.last(), seen + newConnections, distance + 1) } } findDistance(input.start, input.start, mutableSetOf(input.start), 1) } part2 { input -> tailrec fun findLoop(c1: Point<Int>, c2: Point<Int>, loop: Set<Point<Int>>): Set<Point<Int>> { val connections = input.findConnections(c1) + input.findConnections(c2) val newConnections = connections.filter { it !in loop }.toSet() return if (newConnections.size == 1) { newConnections + loop } else { findLoop(newConnections.first(), newConnections.last(), loop + newConnections) } } val loop = findLoop(input.start, input.start, mutableSetOf(input.start)) val gridWithLoop = input.copy(grid = input.grid.mapIndexed { x, line -> line.mapIndexed { y, c -> if (x by y in loop) c else '.' }.toMutableList() }) val expandedGrid = gridWithLoop.copy( grid = List(gridWithLoop.grid.size * 2) { MutableList(gridWithLoop.grid[0].size * 2) { '.' } }.also { grid -> for (y in grid[0].indices) { for (x in grid.indices) { if (x % 2 == 0 && y % 2 == 0) { grid[x][y] = gridWithLoop.grid[x / 2][y / 2] } else { if (y % 2 == 0 && gridWithLoop.grid[x / 2][y / 2].connectsRight() && gridWithLoop.grid[x / 2 + 1][y / 2].connectsLeft()) { grid[x][y] = '-' } else if (x % 2 == 0 && gridWithLoop.grid[x / 2][y / 2].connectsDown() && gridWithLoop.grid[x / 2][y / 2 + 1].connectsUp()) { grid[x][y] = '|' } } } } }) tailrec fun floodGrid(q: ArrayDeque<Point<Int>>, map: TubeMap) { if (q.isEmpty()) return q.removeFirst().surrounding() .filter { it.x >= 0 && it.y >= 0 && it.x < map.grid.size && it.y < map.grid[0].size } .filter { map.get(it) == '.' }.forEach { map.grid[it.x][it.y] = 'O' q.add(it) } floodGrid(q, map) } floodGrid(ArrayDeque<Point<Int>>().also { it.add(0 by 0) }, expandedGrid) var sum = 0 expandedGrid.grid.forEachIndexed { x, line -> line.forEachIndexed { y, c -> if (x % 2 == 0 && y % 2 == 0 && c == '.') sum++ } } sum } } }
0
Kotlin
0
1
a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3
5,077
aoc-2023
The Unlicense
2021/src/main/kotlin/com/trikzon/aoc2021/Day14.kt
Trikzon
317,622,840
false
{"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397}
package com.trikzon.aoc2021 fun main() { val input = getInputStringFromFile("/day14.txt") benchmark(Part.One, ::day14Part1, input, 3009, 5000) benchmark(Part.Two, ::day14Part2, input, 3459822539451L, 5000) } fun day14Part1(input: String): Int { val lines = input.lines() var template = lines[0] val rules = HashMap<String, String>() for (i in 2 until lines.size) { val rule = lines[i].split(" -> ") rules[rule[0]] = rule[1] } for (i in 0 until 10) { val newTemplate = StringBuilder() for (j in 0 until template.length - 1) { val firstElement = template[j].toString() val secondElement = template[j + 1].toString() val insertElement = rules[firstElement + secondElement] newTemplate.append(firstElement + insertElement) if (j == template.length - 2) { newTemplate.append(secondElement) } } template = newTemplate.toString() } val counts = HashMap<Char, Int>() for (char in template) { if (counts.contains(char)) { counts[char] = counts[char]!! + 1 } else { counts[char] = 1 } } var mostCommonQuantity = Int.MIN_VALUE var leastCommonQuantity = Int.MAX_VALUE for (char in counts.keys) { if (counts[char]!! > mostCommonQuantity) { mostCommonQuantity = counts[char]!! } else if (counts[char]!! < leastCommonQuantity) { leastCommonQuantity = counts[char]!! } } return mostCommonQuantity - leastCommonQuantity } fun day14Part2(input: String): Long { val rules = HashMap<Pair<Char, Char>, Char>() var pairCounts = HashMap<Pair<Char, Char>, Long>() var charCounts = HashMap<Char, Long>() val lines = input.lines() for (i in 2 until lines.size) { val rule = lines[i].split(" -> ") rules[Pair(rule[0][0], rule[0][1])] = rule[1][0] } // Insert initial template into hashmaps val template = lines[0] val lastChar = template[template.lastIndex] for (i in 0 until template.length - 1) { val char = template[i] if (charCounts.contains(char)) charCounts[char] = charCounts[char]!! + 1 else charCounts[char] = 1 val pair = Pair(char, template[i + 1]) if (pairCounts.contains(pair)) pairCounts[pair] = pairCounts[pair]!! + 1 else pairCounts[pair] = 1 if (i == template.length - 2) { if (charCounts.contains(template[i + 1])) charCounts[template[i + 1]] = charCounts[template[i + 1]]!! + 1 else charCounts[template[i + 1]] = 1 } } for (i in 0 until 40) { val newPairCounts = HashMap<Pair<Char, Char>, Long>() val newCharCounts = HashMap<Char, Long>() for ((left, right) in pairCounts.keys) { val pairCount = pairCounts[Pair(left, right)]!! val insertChar = rules[Pair(left, right)]!! if (newPairCounts.contains(Pair(left, insertChar))) newPairCounts[Pair(left, insertChar)] = newPairCounts[Pair(left, insertChar)]!! + pairCount else newPairCounts[Pair(left, insertChar)] = pairCount if (newPairCounts.contains(Pair(insertChar, right))) newPairCounts[Pair(insertChar, right)] = newPairCounts[Pair(insertChar, right)]!! + pairCount else newPairCounts[Pair(insertChar, right)] = pairCount if (newCharCounts.contains(left)) newCharCounts[left] = newCharCounts[left]!! + pairCount else newCharCounts[left] = pairCount if (newCharCounts.contains(insertChar)) newCharCounts[insertChar] = newCharCounts[insertChar]!! + pairCount else newCharCounts[insertChar] = pairCount } newCharCounts[lastChar] = newCharCounts[lastChar]!! + 1 pairCounts = newPairCounts charCounts = newCharCounts } var mostCommonQuantity = Long.MIN_VALUE var leastCommonQuantity = Long.MAX_VALUE for (counts in charCounts.values) { if (counts > mostCommonQuantity) mostCommonQuantity = counts else if (counts < leastCommonQuantity) leastCommonQuantity = counts } return mostCommonQuantity - leastCommonQuantity }
0
Kotlin
1
0
d4dea9f0c1b56dc698b716bb03fc2ad62619ca08
4,245
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumLengthRepeatedSubarray.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD import java.math.BigInteger import kotlin.math.max import kotlin.math.min /** * 718. Maximum Length of Repeated Subarray * @see <a href="https://leetcode.com/problems/maximum-length-of-repeated-subarray/">Source</a> */ fun interface MaximumLengthRepeatedSubarray { fun findLength(nums1: IntArray, nums2: IntArray): Int } sealed class MaximumLengthRepeatedSubarrayStrategy { /** * Approach #1: Brute Force with Initial Character Map [Time Limit Exceeded] */ class BruteForce : MaximumLengthRepeatedSubarray { override fun findLength(nums1: IntArray, nums2: IntArray): Int { var ans = 0 val bstarts: MutableMap<Int, ArrayList<Int>> = HashMap() for (j in nums2.indices) { bstarts.computeIfAbsent( nums2[j], ) { ArrayList() }.add(j) } for (i in nums1.indices) if (bstarts.containsKey(nums1[i])) { for (j in bstarts[nums1[i]]!!) { var k = 0 while (i + k < nums1.size && j + k < nums2.size && nums1[i + k] == nums2[j + k]) { k++ } ans = max(ans, k) } } return ans } } /** * Approach #2: Binary Search with Naive Check [Time Limit Exceeded] */ class BinarySearch : MaximumLengthRepeatedSubarray { override fun findLength(nums1: IntArray, nums2: IntArray): Int { var lo = 0 var hi: Int = min(nums1.size, nums2.size) + 1 while (lo < hi) { val mi = (lo + hi) / 2 if (check(mi, nums1, nums2)) lo = mi + 1 else hi = mi } return lo - 1 } fun check(length: Int, nums1: IntArray, nums2: IntArray): Boolean { val seen: MutableSet<String> = HashSet() var i = 0 while (i + length <= nums1.size) { seen.add(nums1.copyOfRange(i, i + length).contentToString()) ++i } var j = 0 while (j + length <= nums2.size) { if (seen.contains(nums2.copyOfRange(j, j + length).contentToString())) { return true } ++j } return false } } /** * Approach #3: Dynamic Programming (Accepted) */ class DynamicProgramming : MaximumLengthRepeatedSubarray { override fun findLength(nums1: IntArray, nums2: IntArray): Int { var ans = 0 val memo = Array(nums1.size + 1) { IntArray(nums2.size + 1) } for (i in nums1.size - 1 downTo 0) { for (j in nums2.size - 1 downTo 0) { if (nums1[i] == nums2[j]) { memo[i][j] = memo[i + 1][j + 1] + 1 if (ans < memo[i][j]) ans = memo[i][j] } } } return ans } } /** * Approach #4: Binary Search with Rolling Hash [Accepted] */ class DPRollingHash : MaximumLengthRepeatedSubarray { companion object { const val P = 113L } var pinv: Int = BigInteger.valueOf(P).modInverse(BigInteger.valueOf(MOD.toLong())).intValueExact() override fun findLength(nums1: IntArray, nums2: IntArray): Int { var lo = 0 var hi: Int = min(nums1.size, nums2.size) + 1 while (lo < hi) { val mi = (lo + hi) / 2 if (check(mi, nums1, nums2)) lo = mi + 1 else hi = mi } return lo - 1 } private fun rolling(source: IntArray, length: Int): IntArray { val ans = IntArray(source.size - length + 1) var h: Long = 0 var power: Long = 1 if (length == 0) return ans for (i in source.indices) { h = (h + source[i] * power) % MOD if (i < length - 1) { power = power * P % MOD } else { ans[i - (length - 1)] = h.toInt() h = (h - source[i - (length - 1)]) * pinv % MOD if (h < 0) h += MOD } } return ans } private fun check(guess: Int, a: IntArray, b: IntArray): Boolean { val hashes: MutableMap<Int?, MutableList<Int>?> = HashMap() var k = 0 for (x in rolling(a, guess)) { hashes.computeIfAbsent(x) { ArrayList() }?.add(k++) } for ((j, x) in rolling(b, guess).withIndex()) { for (i in hashes.getOrDefault(x, ArrayList())!!) { if (a.copyOfRange(i, i + guess).contentEquals(b.copyOfRange(j, j + guess))) { return true } } } return false } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,675
kotlab
Apache License 2.0
src/Day05.kt
dmdrummond
573,289,191
false
{"Kotlin": 9084}
import java.util.* fun main() { fun charPositionFor(i: Int): Int { return when (i) { 1 -> 1 else -> 4 * i - 3 } } fun parseInput(input: List<String>): Pair<ElfStack, List<Instruction>> { val elfStack = mutableListOf<Stack<Char>>() val instructions = mutableListOf<Instruction>() // Parse initial stack state val endOfStack = input.indexOfFirst { it.isEmpty() } val stackNumberLine = input[endOfStack-1] val numberOfStacks = stackNumberLine .substring(1, stackNumberLine.length) .split("\\s+".toRegex()) .maxOfOrNull { it.toInt() } ?: throw Error("Error parsing stack number") for(i in 1..numberOfStacks) { elfStack.add(Stack()) } for (line in endOfStack-1 downTo 0) { for (i in 1..numberOfStacks) { val charPosition = charPositionFor(i) if (input[line].length >= charPosition) { val char = input[line][charPositionFor(i)] if (char != ' ') { elfStack[i - 1].push(char) } } } } //Parse instructions for (index in endOfStack+1 until input.size) { val tokens = input[index].split(" ") instructions.add(Instruction(tokens[1].toInt(), tokens[3].toInt(), tokens[5].toInt())) } return elfStack to instructions } fun processInstruction(stack: ElfStack, instruction: Instruction) { for (i in 0 until instruction.count) { stack[instruction.destination - 1].push( stack[instruction.source - 1].pop() ) } } fun processInstructionCrateMover9001(stack: ElfStack, instruction: Instruction) { val tempStack = Stack<Char>() for (i in 0 until instruction.count) { tempStack.push(stack[instruction.source - 1].pop()) } for (i in 0 until instruction.count) { stack[instruction.destination - 1].push( tempStack.pop() ) } } fun part1(input: List<String>): String { val (stack, instructions) = parseInput(input) instructions.forEach { processInstruction(stack, it) } return stack.map { it.last() }.joinToString("") } fun part2(input: List<String>): String { val (stack, instructions) = parseInput(input) instructions.forEach { processInstructionCrateMover9001(stack, it) } return stack.map { it.last() }.joinToString("") } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } data class Instruction(val count: Int, val source: Int, val destination: Int) typealias ElfStack = List<Stack<Char>>
0
Kotlin
0
0
2493256124c341e9d4a5e3edfb688584e32f95ec
3,026
AoC2022
Apache License 2.0
src/aoc2022/Day03.kt
Playacem
573,606,418
false
{"Kotlin": 44779}
package aoc2022 import utils.readInput object Day03 { override fun toString(): String { return this.javaClass.simpleName } } fun main() { fun CharRange.asLongString(): String = this.toList().joinToString(separator = "", prefix = "", postfix = "") val alphabet: String = ('a'..'z').asLongString() + ('A'..'Z').asLongString() fun splitInParts(string: String): List<String> { return listOf(string.substring(0, string.length / 2), string.substring(string.length / 2)) } fun findCommonCharacter(list: List<String>): Char { val commonChars = list.map { it.toCharArray().toSet() }.reduce { acc, chars -> acc.intersect(chars) } check(commonChars.size == 1) { "Unexpected size: ${commonChars.size} - $commonChars" } return commonChars.first() } fun getPriorityOfItem(item: Char): Int { return alphabet.indexOf(item) + 1 } fun part1(input: List<String>): Int { return input.map { splitInParts(it) }.map { findCommonCharacter(it) }.sumOf { getPriorityOfItem(it) } } fun part2(input: List<String>): Int { return input.chunked(3).map { findCommonCharacter(it) }.sumOf { getPriorityOfItem(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput(2022, "${Day03}_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput(2022, Day03.toString()) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4ec3831b3d4f576e905076ff80aca035307ed522
1,512
advent-of-code-2022
Apache License 2.0
src/main/kotlin/year_2022/Day09.kt
krllus
572,617,904
false
{"Kotlin": 97314}
package year_2022 import utils.readInput import kotlin.math.pow fun main() { fun getCandidatesToMove(grid: Array<Array<String>>, headPosition: Position): List<Position> { val positions = mutableListOf<Position>() val size = grid[0].size positions.add(headPosition.copy(i = headPosition.i - 1, j = headPosition.j - 1)) positions.add(headPosition.copy(i = headPosition.i - 1, j = headPosition.j)) positions.add(headPosition.copy(i = headPosition.i - 1, j = headPosition.j + 1)) positions.add(headPosition.copy(i = headPosition.i, j = headPosition.j - 1)) positions.add(headPosition.copy(i = headPosition.i, j = headPosition.j + 1)) positions.add(headPosition.copy(i = headPosition.i + 1, j = headPosition.j - 1)) positions.add(headPosition.copy(i = headPosition.i + 1, j = headPosition.j)) positions.add(headPosition.copy(i = headPosition.i + 1, j = headPosition.j + 1)) positions.removeIf { position -> position.i < 0 || position.j < 0 || position.i >= size || position.j >= size } return positions } fun moveTail( headPosition: Position, oldHeadPosition: Position, tailPosition: Position, ): Position { val dht = headPosition.distance(tailPosition) val doft = oldHeadPosition.distance(tailPosition) if (dht == 2.0 && doft == 1.0) { return oldHeadPosition } if (dht <= 1.5) { return tailPosition } if (doft > 1.4) { return oldHeadPosition } return tailPosition } fun part1(input: List<String>): Int { val rowSize = 400 val columnSize = 400 val grid = Array(rowSize) { Array(columnSize) { "." } } // initial position var headPosition = Position(rowSize / 2, columnSize / 2) var tailPosition = Position(rowSize / 2, columnSize / 2) grid[headPosition.j][headPosition.i] = "s" for (movement in input.asRopeMovements()) { repeat(movement.moveSteps) { val oldHeadPosition = headPosition.copy() headPosition = when (movement.direction) { Direction.UP -> headPosition.copy(j = headPosition.j - 1) Direction.DOWN -> headPosition.copy(j = headPosition.j + 1) Direction.RIGHT -> headPosition.copy(i = headPosition.i + 1) Direction.LEFT -> headPosition.copy(i = headPosition.i - 1) } tailPosition = moveTail(headPosition, oldHeadPosition, tailPosition) if (tailPosition.i >= rowSize) { error("a tail greater then board size: $tailPosition, head: $headPosition prevHead: $oldHeadPosition input:$movement") } if (tailPosition.j >= columnSize) { error("b tail greater then board size: $tailPosition") } grid[tailPosition.j][tailPosition.i] = "#" } } var sum = 0 for (i in 0 until columnSize) { for (j in 0 until rowSize) { if (grid[j][i] != ".") sum++ } } return sum } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 0) val input = readInput("Day09") println(part1(input)) println(part2(input)) } fun Collection<String>.asRopeMovements(): Collection<RopeMovement> { return this.map { it.asRopeMovement() } } fun String.asRopeMovement(): RopeMovement { val (first, second) = this.split(" ") return RopeMovement(first.asDirection(), second.toInt()) } data class Position(val i: Int, val j: Int) { fun distance(other: Position): Double { return kotlin.math.sqrt( (other.i - this.i).toDouble().pow(2.0) + (other.j - this.j).toDouble().pow(2.0) ) } } data class Rope( val head : RopeSegment, val tail : RopeSegment ) data class RopeSegment( val position: Position, val nextSegment : RopeSegment? = null, val prevSegment : RopeSegment? = null ) data class RopeMovement(val direction: Direction, val moveSteps: Int, var processed: Boolean = false) fun String.asDirection(): Direction { return when (this) { "U" -> Direction.UP "D" -> Direction.DOWN "R" -> Direction.RIGHT "L" -> Direction.LEFT else -> error("no direction found") } } enum class Direction { UP, DOWN, RIGHT, LEFT; }
0
Kotlin
0
0
b5280f3592ba3a0fbe04da72d4b77fcc9754597e
4,817
advent-of-code
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem2306/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2306 /** * LeetCode page: [2306. Naming a Company](https://leetcode.com/problems/naming-a-company/); */ class Solution2 { /* Complexity: * Time O(L) and Space O(L) where L is the flat length of ideas; */ fun distinctNames(ideas: Array<String>): Long { val numSwappable = buildNumSwappable(ideas) return countDistinctName(numSwappable) } /** * Return a 26 x 26 2D Array that cell(m, n) is the number of ideas that start with * letter ('a' + m) and is not in original ideas if replace it's first letter with * letter ('a' + n). */ private fun buildNumSwappable(ideas: Array<String>): Array<IntArray> { val ideaSet = ideas.toHashSet() val numSwappable = Array(26) { IntArray(26) } for (idea in ideaSet) { for (c in 'a'..'z') { val swapped = idea.replaceRange(0..0, c.toString()) val isSwappable = swapped !in ideaSet if (isSwappable) { numSwappable[idea[0] - 'a'][c - 'a']++ } } } return numSwappable } private fun countDistinctName(numSwappable: Array<IntArray>): Long { var numDistinctName = 0L for (i in 0 until 25) { for (j in i + 1 until 26) { // times 2 since if idea1+idea2 is valid, then idea2+idea1 is also valid numDistinctName += numSwappable[i][j] * numSwappable[j][i] * 2 } } return numDistinctName } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,570
hj-leetcode-kotlin
Apache License 2.0
src/Day24.kt
palex65
572,937,600
false
{"Kotlin": 68582}
@file:Suppress("PackageDirectoryMismatch") package day24 import readInput import day24.Dir.* import java.util.Comparator import java.util.PriorityQueue import kotlin.math.* data class Pos(val row: Int, val col: Int) { override fun toString() = "($row,$col)" } data class Offset(val dRow: Int, val dCol: Int) fun Offset.distance() = abs(dRow)+abs(dCol) operator fun Pos.plus(off: Offset) = Pos(row + off.dRow, col + off.dCol) operator fun Pos.minus(pos: Pos) = Offset(row - pos.row, col - pos.col) fun Pos.mod(rows: Int, cols: Int) = Pos( row.mod(rows), col.mod(cols) ) fun Pos.inArea(rows: Int, cols: Int) = row in 0 until rows && col in 0 until cols enum class Dir(val offset: Offset, val symbol: Char) { RIGHT(0,+1,'>'), DOWN(+1,0,'v'), LEFT(0,-1,'<'), UP(-1,0,'^'); constructor(dRow: Int, dCol: Int, symbol: Char): this( Offset(dRow,dCol), symbol) } fun Char.toDir() = Dir.values().first { it.symbol==this } operator fun Pos.plus(dir: Dir) = this + dir.offset data class Blizzard(val pos: Pos, val dir: Dir) typealias Blizzards = List<Blizzard> fun Blizzards(lines: List<String>): Blizzards = buildList { lines.forEachIndexed { row, line -> line.forEachIndexed { col, c -> if (c in ">v<^") add(Blizzard( Pos(row-1,col-1), c.toDir())) } } } data class Context( val rows: Int, val cols: Int, val start: Pos, val target: Pos, val blizzards: MutableList<List<Blizzard>>, ) data class State( val minute: Int, val expedition: Pos, ) fun State.print(ctx: Context) { println("== Minute $minute ==") for(r in 0 until ctx.rows) println( (0 until ctx.cols).joinToString(""){ c -> val pos = Pos(r,c) val bs = ctx.blizzards[minute].filter { it.pos == pos } when { bs.size == 1 -> bs.first().dir.symbol bs.size > 1 -> bs.size.toString()[0] expedition == pos -> 'E' else -> '.' }.toString() } ) } fun State.doStep(ctx: Context): List<State> = buildList { val min = minute+1 val bliz = if (min==ctx.blizzards.size) ctx.blizzards[minute].map{ it.copy(pos = (it.pos + it.dir).mod(ctx.rows, ctx.cols)) }.also { ctx.blizzards.add(it) } else ctx.blizzards[min] Dir.values().map { dir -> expedition + dir }.forEach{ exp -> if ((exp.inArea(ctx.rows, ctx.cols)||exp==ctx.target) && bliz.none { it.pos == exp }) add( State(min, exp)) } if (bliz.none { it.pos == expedition }) add( State(min,expedition)) } fun Context.compareStates(s1: State, s2: State): Int { val d2 = (target - s2.expedition).distance() val d1 = (target - s1.expedition).distance() return d1-d2 } fun solve(ctx: Context): Int { val visited = mutableSetOf<State>() val open = PriorityQueue(Comparator<State> { s1, s2 -> ctx.compareStates(s1,s2) }) open.add( State(0, ctx.start) ) var bestMinutes = Int.MAX_VALUE while (open.isNotEmpty()) { val state = open.remove() if (state.minute + (ctx.target-state.expedition).distance() > bestMinutes) continue visited.add(state) if (state.expedition==ctx.target) bestMinutes = min(state.minute,bestMinutes) else for (s in state.doStep(ctx)) if (s !in open && s !in visited) open.add(s) } return bestMinutes } fun Context(lines: List<String>): Context { val rows = lines.size-2 val cols = lines[0].length-2 return Context( rows, cols, start = Pos(row = -1, col= 0), target = Pos(row = rows, col = cols - 1), blizzards = mutableListOf(Blizzards(lines)), ) } fun part1(lines: List<String>) = solve( Context(lines) ) fun part2(lines: List<String>): Int { val ctx = Context(lines) val toGoal = solve(ctx) val ctx2 = ctx.copy(start = ctx.target, target = ctx.start, blizzards = mutableListOf( ctx.blizzards[toGoal])) val toBack = solve( ctx2 ) val toGoalAgain = solve( ctx.copy( blizzards = mutableListOf( ctx2.blizzards[toBack]) ) ) return toGoal + toBack + toGoalAgain } fun main() { val testInput = readInput("Day24_test") check(part1(testInput) == 18) check(part2(testInput) == 54) val input = readInput("Day24") println(part1(input)) // 314 println(part2(input)) // 896 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
4,368
aoc2022
Apache License 2.0
src/day02/Day02.kt
chskela
574,228,146
false
{"Kotlin": 9406}
package day02 import java.io.File fun main() { fun parseInput(input: String) = input.lines().map { it.split(" ") }.map { it.first() to it.last() } val points = mapOf("X" to 1, "Y" to 2, "Z" to 3) val winsPlayer = listOf("A" to "Y", "B" to "Z", "C" to "X") val drawPlayer = listOf("A" to "X", "B" to "Y", "C" to "Z") val lossPlayer = listOf("A" to "Z", "B" to "X", "C" to "Y") fun getPointPerRound(pair: Pair<String, String>): Int = when (pair) { in winsPlayer -> 6 in drawPlayer -> 3 else -> 0 } fun part1(input: String): Int { val data = parseInput(input) .fold(0) { acc, pair -> acc + getPointPerRound(pair) + points.getOrDefault(pair.second, 0) } return data } fun part2(input: String): Int { val data = parseInput(input) .map { (first, second) -> when (second) { "Z" -> winsPlayer.first { it.first == first } "Y" -> drawPlayer.first { it.first == first } else -> lossPlayer.first { it.first == first } } } .fold(0) { acc, pair -> acc + getPointPerRound(pair) + points.getOrDefault(pair.second, 0) } return data } val testInput = File("src/day02/Day02_test.txt").readText() println(part1(testInput)) println(part2(testInput)) val input = File("src/day02/Day02.txt").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
951d38a894dcf0109fd0847eef9ff3ed3293fca0
1,557
adventofcode-2022-kotlin
Apache License 2.0
src/BicliqueCoverProblem.kt
SzybkiDanny
224,013,942
false
null
class BicliqueCoverProblem(private val problemGraph: Graph) { private val solution = mutableSetOf<BipartiteGraph>() fun solve() { val vertices = problemGraph.vertices.filterNot { problemGraph.hasSelfLoop(it) }.toHashSet() var isAnyChange = false generateInitialSolution(vertices) do { isAnyChange = mergeSubgraphs().or(removeRedundantSubgraphs()) } while (isAnyChange) } fun getResult() = solution.map { Pair(it.predecessors, it.successors) } private fun generateInitialSolution(vertices: Set<Int>) { vertices.forEach { predecessor -> problemGraph.getSuccessors(predecessor) .filter { successor -> vertices.contains(successor) } .filterNot { successor -> problemGraph.hasDirectedEdgeBetween(successor, predecessor) } .forEach { successor -> solution.add(BipartiteGraph(mutableSetOf(predecessor), mutableSetOf(successor))) } } } private fun mergeSubgraphs(): Boolean { val currentSubgraphs = solution.toList() var isAnyChange = false for (x in currentSubgraphs.indices) { for (y in x + 1 until currentSubgraphs.size) { val newSubgraph = tryToMergeSubgraphs( currentSubgraphs[x], currentSubgraphs[y] ) if (newSubgraph != null) { isAnyChange = solution.add(newSubgraph) || isAnyChange } } } return isAnyChange } private fun removeRedundantSubgraphs(): Boolean { val currentSubgraphs = solution.toList() var isAnyChange = false for (x in currentSubgraphs.indices) { for (y in x + 1 until currentSubgraphs.size) { if (currentSubgraphs[x] isSubgraphOf currentSubgraphs[y]) { isAnyChange = solution.remove(currentSubgraphs[x]) || isAnyChange } else if (currentSubgraphs[y] isSubgraphOf currentSubgraphs[x]) { isAnyChange = solution.remove(currentSubgraphs[y]) || isAnyChange } } } return isAnyChange } private fun tryToMergeSubgraphs( firstSubgraph: BipartiteGraph, secondSubgraph: BipartiteGraph): BipartiteGraph? { if (canSetsBeMerged(firstSubgraph.predecessors, secondSubgraph.predecessors)) { val newSubgraph = firstSubgraph.unionPredecessorsIntersectSuccessors(secondSubgraph) if (!newSubgraph.isAnyPartEmpty() && !newSubgraph.isSubgraphOf(firstSubgraph)) { return newSubgraph } } if (canSetsBeMerged(firstSubgraph.successors, secondSubgraph.successors)) { val newSubgraph = firstSubgraph.intersectPredecessorsUnionSuccessors(secondSubgraph) if (!newSubgraph.isAnyPartEmpty() && !newSubgraph.isSubgraphOf(firstSubgraph)) { return newSubgraph } } return null } private fun canSetsBeMerged(firstSet: Set<Int>, secondSet: Set<Int>) = firstSet.all { firstSetElement -> secondSet.all { secondSetElement -> firstSetElement == secondSetElement || !problemGraph.hasAnyEdgeBetween( firstSetElement, secondSetElement ) } } private inner class BipartiteGraph(val predecessors: Set<Int>, val successors: Set<Int>) { fun unionPredecessorsIntersectSuccessors(otherGraph: BipartiteGraph) = BipartiteGraph(predecessors.union(otherGraph.predecessors), successors.intersect(otherGraph.successors)) fun intersectPredecessorsUnionSuccessors(otherGraph: BipartiteGraph) = BipartiteGraph(predecessors.intersect(otherGraph.predecessors), successors.union(otherGraph.successors)) fun isAnyPartEmpty() = predecessors.isEmpty() || successors.isEmpty() infix fun isSubgraphOf(otherGraph: BipartiteGraph) = otherGraph.predecessors.containsAll(predecessors) && otherGraph.successors.containsAll(successors) override fun hashCode() = predecessors.hashCode() + successors.hashCode() override fun equals(other: Any?) = if (other != null) equals(other as BipartiteGraph) else false private fun equals(other: BipartiteGraph) = predecessors == other.predecessors && successors == other.successors } }
0
Kotlin
0
0
67625c8697858bb74a4d582b56ff6e9343a760d1
4,609
FindCompleteBipartiteSubgraphs
MIT License
kotlin/src/com/s13g/aoc/aoc2020/Day19.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 19: Monster Messages --- * https://adventofcode.com/2020/day/19 */ class Day19 : Solver { private fun parseRule(str: String): Pair<Int, Val> { val split = str.split(": ") val ruleNo = split[0].toInt() return if (split[1].contains('"')) Pair(ruleNo, Val(emptyList(), split[1][1])) else Pair(ruleNo, Val(split[1].split(" | ").map { list -> list.split(' ').map { it.toInt() } }.toList())) } override fun solve(lines: List<String>): Result { // Parse the Input val rules = mutableMapOf<Int, Val>() val messages = mutableListOf<String>() for (line in lines) { if (line.contains(":")) parseRule(line).apply { rules[first] = second } else if (line.isNotBlank()) messages.add(line) } // Solve as is for Part 1: Find all matching messages. val resultA = messages.map { m -> m in rules[0]!!.eval("", m, rules) }.count { it } // Patch the rules, which will introduce loops in Part 2 listOf("8: 42 | 42 8", "11: 42 31 | 42 11 31").forEach { parseRule(it).apply { rules[first] = second } } val resultB = messages.map { m -> m in rules[0]!!.eval("", m, rules) }.count { it } return Result("$resultA", "$resultB") } // A value either as a concrete value 'v' or needs to be evaluated through its reference lists. private data class Val(val ref: List<List<Int>>, val v: Char = ' ') private fun Val.eval(base: String, match: String, rules: Map<Int, Val>): Set<String> { if (v != ' ') return setOf("$base$v") // Return early if this is a concrete value. val result = mutableSetOf<String>() for (list in ref) { // Create all permutations using all the reference lists. var str = mutableListOf(base) for (r in list) { val bak = str str = mutableListOf() // Empty str and fill it with all combinations. for (s in bak) { // Only keep matching candidates. rules[r]!!.eval(s, match, rules).filter { match.startsWith(it) }.forEach { str.add(it) } } } result.addAll(str) } return result } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,147
euler
Apache License 2.0
solutions/aockt/util/Search.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.util import java.util.PriorityQueue /** A type implementing this interface can represent a network of nodes usable for search algorithms. */ interface Graph<T : Any> { /** Returns all the possible nodes to visit starting from this [node] associated with the cost of travel. */ fun neighboursOf(node: T): Iterable<Pair<T, Int>> } /** * The result of a [Graph] search. * * @property startedFrom The origin node from where the search began. * @property destination The closest node that fulfilled the search criteria, or `null` if not found. * If multiple such nodes exist, the one with the lowest cost is chosen. * @property searchTree Extra information about the search, associating visited nodes to their previous node in the * path back to the origin, as well as their total cost from the origin. */ data class SearchResult<T : Any>( val startedFrom: T, val destination: T?, val searchTree: Map<T, Pair<T, Int>>, ) /** * A slice of a [SearchResult], showing the complete path towards a particular node. * * @property path The list of all nodes in this path, including the origin and destination nodes. * @property cost The total cost of this path. */ data class SearchPath<T : Any>( val path: List<T>, val cost: Int, ) : List<T> by path /** * Narrow down a [SearchResult] to a [node] of interest. * Returns the shortest known path towards that [node], or `null` if the node is unreachable from the origin, or if the * node has not been visited by the search algorithm before reaching a destination. */ fun <T : Any> SearchResult<T>.pathTo(node: T): SearchPath<T>? { val cost = searchTree[node]?.second ?: return null val path = buildList { var current = node while(true) { add(current) val previous = searchTree.getValue(current).first if(previous == current) break current = previous } }.asReversed() return SearchPath(path, cost) } /** * Narrow down a [SearchResult] to the node of interest. * Returns the shortest known path towards the node that fulfilled the destination criteria. * If multiple such nodes exist, the one with the lowest cost is chosen. */ fun <T : Any> SearchResult<T>.path(): SearchPath<T>? = when(destination) { null -> null else -> pathTo(destination) } /** * Performs a search on the graph. * If a [heuristic] is given, it is A*, otherwise Dijkstra. * * @param start The origin node from where to start searching. * @param maximumCost If specified, will stop searching if no destination was found with a cost smaller than this value. * @param onVisited Side effect callback triggered every time a new node is searched. * @param heuristic A function that estimates the cost of reaching a destination from the given node. * Must never overestimate, otherwise the search result might not be the most cost-effective. * @param goalFunction A predicate to determine which nodes are a destination. * The search will stop upon the first such node to be found. * If no function is defined, the entire graph will be searched. */ fun <T : Any> Graph<T>.search( start: T, maximumCost: Int = Int.MAX_VALUE, onVisited: (T) -> Unit = {}, heuristic: (T) -> Int = { 0 }, goalFunction: (T) -> Boolean = { false }, ): SearchResult<T> { val queue = PriorityQueue(compareBy<Pair<T, Int>> { it.second }) queue.add(start to 0) val searchTree = mutableMapOf(start to (start to 0)) while (true) { val (node, costSoFar) = queue.poll() ?: return SearchResult(start, null, searchTree) onVisited(node) if (goalFunction(node)) return SearchResult(start, node, searchTree) neighboursOf(node) .filter { it.first !in searchTree } .forEach { (next, cost) -> val nextCost = costSoFar + cost if (nextCost <= maximumCost && nextCost <= (searchTree[next]?.second ?: Int.MAX_VALUE)) { queue.add(next to heuristic(next).plus(nextCost)) searchTree[next] = node to nextCost } } } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
4,155
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/com/ginsberg/advent2020/Day17.kt
tginsberg
315,060,137
false
null
/* * Copyright (c) 2020 by <NAME> */ /** * Advent of Code 2020, Day 17 - Conway Cubes * Problem Description: http://adventofcode.com/2020/day/17 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day17/ */ package com.ginsberg.advent2020 class Day17(private val input: List<String>) { fun solvePart1() = solve { x, y -> Point3D(x, y, 0) } fun solvePart2(): Int = solve { x, y -> Point4D(x, y, 0, 0) } private fun solve(rounds: Int = 6, pointFunction: (Int, Int) -> Point): Int { var conwayGrid = parseInput(input, pointFunction) repeat(rounds) { conwayGrid = conwayGrid.nextCycle() } return conwayGrid.count { it.value } } private fun Map<Point, Boolean>.nextCycle(): Map<Point, Boolean> { val nextMap = this.toMutableMap() keys.forEach { point -> point.neighbors.forEach { neighbor -> nextMap.putIfAbsent(neighbor, false) } } nextMap.entries.forEach { (point, active) -> val activeNeighbors = point.neighbors.count { this.getOrDefault(it, false) } nextMap[point] = when { active && activeNeighbors in setOf(2, 3) -> true !active && activeNeighbors == 3 -> true else -> false } } return nextMap } private fun parseInput(input: List<String>, pointFunction: (Int, Int) -> Point): Map<Point, Boolean> = input.flatMapIndexed { x, row -> row.mapIndexed { y, point -> pointFunction(x, y) to (point == '#') } }.toMap() }
0
Kotlin
2
38
75766e961f3c18c5e392b4c32bc9a935c3e6862b
1,716
advent-2020-kotlin
Apache License 2.0
src/Day20.kt
SimoneStefani
572,915,832
false
{"Kotlin": 33918}
fun main() { fun decrypt(input: List<Long>, decryptKey: Int = 1, iterations: Int = 1): Long { val original = input.mapIndexed { index, n -> index to n * decryptKey } val shifted = original.toMutableList() repeat(iterations) { original.forEach { p -> shifted.indexOf(p).also { idx -> shifted.removeAt(idx) shifted.add((idx + p.second).mod(shifted.size), p) } } } val mixed = shifted.map(Pair<Int, Long>::second) return sequenceOf(1000, 2000, 3000).sumOf { mixed[(mixed.indexOf(0) + it) % mixed.size] } } fun parseInput(lines: List<String>): List<Long> = lines.map { it.toLong() } fun part1(input: List<String>): Long { val sequence = parseInput(input) return decrypt(sequence) } fun part2(input: List<String>): Long { val sequence = parseInput(input) return decrypt(sequence, decryptKey = 811589153, iterations = 10) } val testInput = readInput("Day20_test") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b3244a6dfb8a1f0f4b47db2788cbb3d55426d018
1,239
aoc-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimizeTheDifference.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 kotlin.math.abs import kotlin.math.min /** * 1981. Minimize the Difference Between Target and Chosen Elements * @see <a href="https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements"> * Source</a> */ fun interface MinimizeTheDifference { operator fun invoke(mat: Array<IntArray>, target: Int): Int } /** * DP + Memo */ class MinimizeTheDifferenceDP : MinimizeTheDifference { override operator fun invoke(mat: Array<IntArray>, target: Int): Int { val dp = Array(mat.size) { arrayOfNulls<Int>(SIZE) } return minDiff(mat, 0, target, 0, dp) } private fun minDiff(mat: Array<IntArray>, index: Int, target: Int, value: Int, dp: Array<Array<Int?>>): Int { if (index == mat.size) { return abs(value - target) } if (dp[index][value] != null) { return dp[index][value] ?: 0 } var res = Int.MAX_VALUE for (i in mat[0].indices) { res = min(res, minDiff(mat, index + 1, target, value + mat[index][i], dp)) } return res.also { dp[index][value] = it } } companion object { private const val SIZE = 5001 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,840
kotlab
Apache License 2.0
src/main/kotlin/co/csadev/advent2022/Day21.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 21 * Problem Description: http://adventofcode.com/2021/day/21 */ package co.csadev.advent2022 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsList import kotlin.math.abs class Day21(override val input: List<String> = resourceAsList("22day21.txt")) : BaseDay<List<String>, Long, Long> { companion object { private const val ROOT = "root" private const val HUMAN = "humn" } private data class Monkey(var name: String, var yell: Long?, val wait1: String?, var operator: Operator?, val wait2: String?) { fun contains(name: String) = wait1 == name || wait2 == name } private enum class Operator(val op: String, val compute: (Long, Long) -> Long, val solve: (Long, Long, Int) -> Long) { Plus("+", { l, r -> l + r }, { curr, l, _ -> curr - l }), Minus("-", { l, r -> l - r }, { curr, l, idx -> if (idx == 2) (l + curr) else (l - curr) }), Mult("*", { l, r -> l * r }, { curr, l, _ -> curr / l }), Div("/", { l, r -> l / r }, { curr, l, idx -> if (idx == 2) (l * curr) else (l / curr) }), Equal("=", { l, r -> abs(l - r) }, { curr, l, _ -> curr + l }); override fun toString() = op } private fun List<String>.asMonkey(): Monkey = Monkey(this[0], getOrNull(1)?.toLongOrNull(), getOrNull(1), getOrNull(2)?.toOperator(), getOrNull(3)) private fun String.toOperator() = Operator.values().firstOrNull { it.op == this } private val monkeys = input.map { it.replace(":", "").split(" ") } .associate { it[0] to it.asMonkey() } override fun solvePart1() = monkeys[ROOT]!!.yelled override fun solvePart2(): Long { monkeys[ROOT]!!.operator = Operator.Equal monkeys[HUMAN]!!.yell = null return generateSequence(monkeys[HUMAN]) { m -> monkeys.entries.firstOrNull { (_, e) -> e.contains(m.name) }?.value }.drop(1).stopYelling() } private fun Sequence<Monkey>.stopYelling(): Long { var humanChain = HUMAN return fold(emptyList<Any?>()) { acc, monkey -> if (monkey.wait1 == humanChain) { listOf(acc, monkey.operator, monkeys[monkey.wait2]?.yelled) } else { listOf(monkeys[monkey.wait1]?.yelled, monkey.operator, acc) }.also { humanChain = monkey.name } }.solve() } private val Monkey.yelled: Long get() = yell ?: operator!!.compute(monkeys[wait1]!!.yelled, monkeys[wait2]!!.yelled) private fun List<Any?>.solve(): Long { // Do some magic to unroll this and return var computed = 0L var currEq = this while (currEq.isNotEmpty()) { val unsolvedIdx = if (currEq[0] is List<*>) 0 else 2 val solvedIdx = if (unsolvedIdx == 0) 2 else 0 val solved = currEq[solvedIdx] as Long println("$computed = ${if (solvedIdx == 2) ("[ME] ${currEq[1]} $solved") else ("$solved ${currEq[1]} [ME]")}") computed = (currEq[1] as Operator).solve(computed, solved, solvedIdx) currEq = currEq[unsolvedIdx] as List<Any?> } return computed } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
3,245
advent-of-kotlin
Apache License 2.0
src/Day08A.kt
zsmb13
572,719,881
false
{"Kotlin": 32865}
fun main() { fun part1(testInput: List<String>): Int { val map = testInput.map { line -> line.map { digit -> digit.digitToInt() } } val xValues = testInput.first().indices val yValues = testInput.indices val visible = mutableSetOf<Pair<Int, Int>>() // rows for (y in yValues) { var max = -1 for (x in xValues) { val height = map[y][x] if (height > max) { visible += (x to y) max = height } } } for (y in yValues) { var max = -1 for (x in xValues.reversed()) { val height = map[y][x] if (height > max) { visible += (x to y) max = height } } } for (x in xValues) { var max = -1 for (y in yValues) { val height = map[y][x] if (height > max) { visible += (x to y) max = height } } } for (x in xValues) { var max = -1 for (y in yValues.reversed()) { val height = map[y][x] if (height > max) { visible += (x to y) max = height } } } return visible.size } fun part2(testInput: List<String>): Int { val xValues = testInput.first().indices val yValues = testInput.indices var maxScenicScore = 0 for (y in yValues) { for (x in xValues) { val height = testInput[y][x] val left = testInput[y].substring(0, x) .indexOfLast { it >= height } .let { if (it == -1) x else x - it } val right = testInput[y].substring(x + 1) .indexOfFirst { it >= height } .let { if (it == -1) xValues.last - x else it + 1 } val top = testInput .take(y) .indexOfLast { it[x] >= height } .let { if (it == -1) y else y - it } val bottom = testInput .drop(y + 1) .indexOfFirst { it[x] >= height } .let { if (it == -1) yValues.last - y else it + 1 } val score = left * right * top * bottom if (score > maxScenicScore) { maxScenicScore = score } } } return maxScenicScore } 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
6
32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35
2,913
advent-of-code-2022
Apache License 2.0
src/Day09.kt
jinie
572,223,871
false
{"Kotlin": 76283}
import kotlin.math.sign //Advent of Code 2022 Day 9, Rope Physics class Day09 { private class Rope(knotAmt: Int){ val knots = mutableListOf<Point2d>() val tailPositions = mutableSetOf<Pair<Int,Int>>() val maxKnotDistance = 1 init { tailPositions.add(Pair(0,0)) for(i in 1..knotAmt){ val knot = Point2d(0,0) knots.add(knot) tailPositions.add(Pair(knot.x,knot.y)) } } fun move(dir: String, amt: Int){ for(j in 0 until amt){ when(dir){ "U" -> knots[0].y++ "D" -> knots[0].y-- "R" -> knots[0].x++ "L" -> knots[0].x-- } for(i in 1 until knots.size){ if(knots[i-1].chebyshevDistance(knots[i]) > maxKnotDistance){ val knot = knots[i] val prevKnot = knots[i-1] val xDelta = (prevKnot.x - knot.x).sign val yDelta = (prevKnot.y - knot.y).sign knot.x += xDelta knot.y += yDelta } } tailPositions.add(Pair(knots.last().x,knots.last().y)) } } } fun part1(input: List<String>): Int { val rope = Rope(2) input.forEach { val (d,v) = it.trim().split(" ") rope.move(d, v.toInt()) } return rope.tailPositions.size } fun part2(input: List<String>): Int { val rope = Rope(10) input.forEach { val (d,v) = it.trim().split(" ") rope.move(d, v.toInt()) } return rope.tailPositions.size } } fun main(){ val testInput = readInput("Day09_test") check(Day09().part1(testInput) == 13) measureTimeMillisPrint { val input = readInput("Day09") println("Part 1: ${Day09().part1(input)}") println("Part 2: ${Day09().part2(input)}") } }
0
Kotlin
0
0
4b994515004705505ac63152835249b4bc7b601a
2,096
aoc-22-kotlin
Apache License 2.0
src/day02/Day02Answer5.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day02 import readInput /** * Answers from [Advent of Code 2022 - Day 2, in Kotlin - Rock Paper Scissors](https://todd.ginsberg.com/post/advent-of-code/2022/day2/) */ fun main() { fun part1(input: List<String>): Int { return Day02(input).solvePart1() } fun part2(input: List<String>): Int { return Day02(input).solvePart2() } val testInput = readInput("day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day02") println(part1(input)) // 12586 println(part2(input)) // 13193 } class Day02(private val input: List<String>) { private val part1Scores: Map<String, Int> = mapOf( "A X" to 1 + 3, "A Y" to 2 + 6, "A Z" to 3 + 0, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 1 + 6, "C Y" to 2 + 0, "C Z" to 3 + 3, ) private val part2Scores: Map<String, Int> = mapOf( "A X" to 3 + 0, "A Y" to 1 + 3, "A Z" to 2 + 6, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 2 + 0, "C Y" to 3 + 3, "C Z" to 1 + 6, ) fun solvePart1(): Int = input.sumOf { part1Scores[it] ?: 0 } fun solvePart2(): Int = input.sumOf { part2Scores[it] ?: 0 } }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
1,443
advent-of-code-2022
Apache License 2.0
src/main/kotlin/advent/of/code/day08/Solution.kt
brunorene
160,263,437
false
null
package advent.of.code.day08 import java.io.File data class Node( val children: List<Node>, val metadata: List<Int> ) { val length: Int = 2 + metadata.size + children.sumBy { it.length } val metadataSum: Int = metadata.sum() + children.sumBy { it.metadataSum } val metadataValue: Int = if (children.isEmpty()) metadataSum else metadata.sumBy { if (it <= children.size) children[it - 1].metadataValue else 0 } } private val tree = tree(File("day08.txt") .readText() .trim() .split(" ") .map { it.toInt() }) fun tree(input: List<Int>): Node { val childCount = input[0] val metadataCount = input[1] val children = mutableListOf<Node>() var childInput = input.drop(2) for (s in (1..childCount)) { val child = tree(childInput) children += child childInput = childInput.drop(child.length) } return Node(children, input.drop(2 + children.sumBy { it.length }).take(metadataCount)) } fun part1() = tree.metadataSum fun part2() = tree.metadataValue
0
Kotlin
0
0
0cb6814b91038a1ab99c276a33bf248157a88939
1,038
advent_of_code_2018
The Unlicense
src/main/kotlin/days/Day17.kt
felix-ebert
317,592,241
false
null
package days class Day17 : Day(17) { // adapted from: https://todd.ginsberg.com/post/advent-of-code/2020/day17/ override fun partOne(): Any { var grid = parseInput { x, y -> Cube3D(x, y, 0) } repeat(6) { grid = grid.simulate() } return grid.count { it.value } } override fun partTwo(): Any { var grid = parseInput { x, y -> Cube4D(x, y, 0, 0) } repeat(6) { grid = grid.simulate() } return grid.count { it.value } } interface Cube { fun findNeighbours(): List<Cube> } data class Cube3D(val x: Int, val y: Int, val z: Int) : Cube { override fun findNeighbours(): List<Cube> { return (x - 1..x + 1).flatMap { dx -> (y - 1..y + 1).flatMap { dy -> (z - 1..z + 1).mapNotNull { dz -> Cube3D(dx, dy, dz).takeUnless { it == this } } } } } } data class Cube4D(val x: Int, val y: Int, val z: Int, val w: Int) : Cube { override fun findNeighbours(): List<Cube> { return (x - 1..x + 1).flatMap { dx -> (y - 1..y + 1).flatMap { dy -> (z - 1..z + 1).flatMap { dz -> (w - 1..w + 1).mapNotNull { dw -> Cube4D(dx, dy, dz, dw).takeUnless { it == this } } } } } } } private fun parseInput(cubeFunction: (Int, Int) -> Cube): Map<Cube, Boolean> { return inputList.flatMapIndexed { y, row -> row.mapIndexed { x, char -> cubeFunction(x, y) to (char == '#') } }.toMap() } private fun Map<Cube, Boolean>.simulate(): Map<Cube, Boolean> { val nextMap = this.toMutableMap() keys.forEach { cube -> cube.findNeighbours().forEach { neighbor -> nextMap.putIfAbsent(neighbor, false) // add only if no such mapping exists } } nextMap.entries.forEach { (cube, active) -> val activeNeighbours = cube.findNeighbours().count { this.getOrDefault(it, false) } nextMap[cube] = when { active && activeNeighbours in 2..3 -> true !active && activeNeighbours == 3 -> true else -> false } } return nextMap } }
0
Kotlin
0
4
dba66bc2aba639bdc34463ec4e3ad5d301266cb1
2,478
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/Day04.kt
tsschmidt
572,649,729
false
{"Kotlin": 24089}
fun main() { fun parse(input: List<String>): List<Pair<IntRange, IntRange>> { return input.map { val (a, b) = it.split(",") val rangeA = IntRange(a.split("-")[0].toInt(), a.split("-")[1].toInt()) val rangeB = IntRange(b.split("-")[0].toInt(), b.split("-")[1].toInt()) rangeA to rangeB } } fun part1(input: List<String>): Int { return parse(input).count { it.first.toList().containsAll(it.second.toList()) || it.second.toList().containsAll(it.first.toList()) } } fun part2(input: List<String>): Int { return parse(input).count { it.first.intersect(it.second).size > 0 } } //val input = readInput("Day04_test") //check(part1(input) == 2) val input = readInput("Day04") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7bb637364667d075509c1759858a4611c6fbb0c2
845
aoc-2022
Apache License 2.0
archive/2022/Day25.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 4890L private const val EXPECTED_2 = 0 val ch = mapOf('=' to -2, '-' to -1, '0' to 0, '1' to 1, '2' to 2) fun decode(p: String): Long { var value = 0L var multiplier = 1L var index = 0 while (index < p.length) { value += multiplier * ch[p[p.length -1 - index]]!! multiplier = Math.multiplyExact(5, multiplier) index++ } return value } val ch2 = listOf('0', '1', '2', '=', '-') val adjust = listOf(0, 1, 2, -2, -1) fun encode(l: Long): String { if (l == 0L) return "" val rem = l.mod(5) val newVal = (l - adjust[rem]) / 5 return encode(newVal ) + ch2[rem] } private class Day25(isTest: Boolean) : Solver(isTest) { fun part1(): Any { val sum = readAsLines().map { decode(it) }.sum() println(encode(sum)) return sum } fun part2(): Any { return 0 } } fun main() { val testInstance = Day25(true) val instance = Day25(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
1,273
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1601_1700.s1697_checking_existence_of_edge_length_limited_paths // #Hard #Array #Sorting #Graph #Union_Find // #2023_06_15_Time_1411_ms_(72.90%)_Space_101.6_MB_(99.07%) import java.util.Arrays class Solution { private class Dsu(n: Int) { private val parent: IntArray init { parent = IntArray(n) parent.fill(-1) } fun find(num: Int): Int { if (parent[num] == -1) { return num } parent[num] = find(parent[num]) return parent[num] } fun union(a: Int, b: Int) { val p1 = find(a) val p2 = find(b) if (p1 != p2) { parent[p2] = p1 } } } fun distanceLimitedPathsExist(n: Int, edgeList: Array<IntArray>, queries: Array<IntArray>): BooleanArray { Arrays.sort(edgeList) { o1: IntArray, o2: IntArray -> Integer.compare(o1[2], o2[2]) } val data = Array(queries.size) { IntArray(4) } for (i in queries.indices) { data[i] = intArrayOf(queries[i][0], queries[i][1], queries[i][2], i) } Arrays.sort(data) { o1: IntArray, o2: IntArray -> Integer.compare(o1[2], o2[2]) } val d = Dsu(n) var j = 0 val ans = BooleanArray(queries.size) for (datum in data) { while (j < edgeList.size && edgeList[j][2] < datum[2]) { d.union(edgeList[j][0], edgeList[j][1]) j++ } if (d.find(datum[0]) == d.find(datum[1])) { ans[datum[3]] = true } } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,659
LeetCode-in-Kotlin
MIT License
2016/src/main/kotlin/day4.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.mapItems import utils.withCounts fun main() { Day4.run() } object Day4 : Solution<List<Day4.Room>>() { override val name = "day4" override val parser = Parser.lines.mapItems { parseRoom(it) } fun parseRoom(line: String): Room { val checksumStart = line.lastIndexOf('[') val idStart = line.lastIndexOf('-') return Room( line.substring(0, idStart), line.substring(idStart + 1, checksumStart).toInt(), line.substring(checksumStart + 1, line.length - 1), ) } data class Room( val name: String, val id: Int, val checksum: String, ) { fun computeChecksum(): String { val chars = name.toCharArray().filter { it != '-' }.withCounts() return chars.entries.sortedWith(compareBy({ -it.value }, { it.key })).take(5).joinToString("") { it.key.toString() } } fun decrypt(): String { return name.toCharArray().map { if (it == '-') ' ' else { 'a' + (((it - 'a') + id) % ('z' - 'a' + 1)) } }.joinToString("") } val valid: Boolean get() = checksum == computeChecksum() } override fun part1(): Int { return input.filter { it.valid }.sumOf { it.id } } override fun part2(): Int { return input.first { it.decrypt() == "northpole object storage" }.id } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,344
aoc_kotlin
MIT License
src/shmulik/klein/day05/Day05.kt
shmulik-klein
573,426,488
false
{"Kotlin": 9136}
package shmulik.klein.day05 import readInput /* [V] [T] [J] [Q] [M] [P] [Q] [J] [W] [B] [N] [Q] [C] [T] [M] [C] [F] [N] [G] [W] [G] [B] [W] [J] [H] [L] [R] [B] [C] [N] [R] [R] [W] [W] [W] [D] [N] [F] [Z] [Z] [Q] [S] [F] [P] [B] [Q] [L] [C] [H] [F] [Z] [G] [L] [V] [Z] [H] 1 2 3 4 5 6 7 8 9 */ fun part1(input: List<String>): MutableList<Char>? { val stacks = mutableListOf("CZNBMWQV", "HZRWCB", "FQRJ", "ZSWHFNMT", "GFWLNQP", "LPW", "VBDRGCQJ", "ZQNBW", "HLFCGTJ") // val stacks = mutableListOf("ZN", "MCD", "P") for (line in input) { val move = line.split(" ").filter { it.toIntOrNull() != null }.map { it.toInt() }.toList() println(move) for (i in 1..move[0]) { println(stacks) val crateToMove = stacks[move[1] - 1].last() stacks[move[2] - 1] = stacks[move[2] - 1] + crateToMove stacks[move[1] - 1] = stacks[move[1] - 1].removeSuffix(crateToMove.toString()) } } return stacks.stream().map { it.last() }.toList() } fun main() { val input = readInput("shmulik/klein/day05/Day05_test") val result1 = part1(input) println(result1) val result2 = part2(input) println(result2) } fun part2(input: List<String>): MutableList<Char>? { val stacks = mutableListOf("CZNBMWQV", "HZRWCB", "FQRJ", "ZSWHFNMT", "GFWLNQP", "LPW", "VBDRGCQJ", "ZQNBW", "HLFCGTJ") // val stacks = mutableListOf("ZN", "MCD", "P") for (line in input) { val move = line.split(" ").filter { it.toIntOrNull() != null }.map { it.toInt() }.toList() println(move) println(stacks) val crateToMove = stacks[move[1] - 1].takeLast(move[0]) stacks[move[2] - 1] = stacks[move[2] - 1] + crateToMove stacks[move[1] - 1] = stacks[move[1] - 1].removeSuffix(crateToMove) } return stacks.stream().map { it.last() }.toList() }
0
Kotlin
0
0
4d7b945e966dad8514ec784a4837b63a942882e9
1,951
advent-of-code-2022
Apache License 2.0
src/main/kotlin/solutions/day11/Day11.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day11 import solutions.Solver data class Monkey( val nbr: Long, val items: MutableList<Long>, val operation: (Long) -> Long, val test: (Long) -> Boolean, val testNbr: Long, val trueTarget: Long, val falseTarget: Long, var inspections: Long ) class Day11 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val inputList = input.toMutableList() val monkeys = mutableMapOf<Long, Monkey>() val monkeyList = mutableListOf<Monkey>() while (inputList.isNotEmpty()) { val monkeyNbr = inputList.removeFirst().trim().removePrefix("Monkey ").removeSuffix(":").toLong() val items = inputList.removeFirst().trim().removePrefix("Starting items: ") .split(",") .map(String::trim) .map(String::toLong) .toMutableList() val operation = parseOperation(inputList.removeFirst().trim()) val pair = parseTest(inputList.removeFirst().trim()) val trueTarget = inputList.removeFirst().trim().removePrefix("If true: throw to monkey ").toLong() val falseTarget = inputList.removeFirst().trim().removePrefix("If false: throw to monkey ").toLong() val monkey = Monkey(monkeyNbr, items, operation, pair.first, pair.second, trueTarget, falseTarget, 0) monkeys[monkeyNbr] = monkey monkeyList.add(monkey) if (inputList.isNotEmpty() && inputList.first() == "") { inputList.removeFirst() } } val worryDivider = if (!partTwo) { 3 } else { monkeyList.map { it.testNbr }.reduce { a, b -> a * b } } val rounds = if (!partTwo) { 20 } else { 10_000 } for (r in 1..rounds) { for (m in monkeyList) { m.inspections += m.items.size while (m.items.isNotEmpty()) { val item = m.items.removeFirst() val newWorryLevel = if (!partTwo) { m.operation(item) / worryDivider } else { m.operation(item) % worryDivider } if (m.test(newWorryLevel)) { monkeys[m.trueTarget]!!.items.add(newWorryLevel) } else { monkeys[m.falseTarget]!!.items.add(newWorryLevel) } } } } monkeyList.sortBy { it.inspections } monkeyList.reverse() return monkeyList.take(2).map { it.inspections }.reduce { a, b -> a * b }.toString() } private fun parseTest(testStr: String): Pair<(Long) -> Boolean, Long> { val nbr = testStr.removePrefix("Test: divisible by ").toLong() return Pair({ it % nbr == 0L }, nbr) } private fun parseOperation(operationStr: String): (Long) -> Long { val operationStrClean = operationStr.removePrefix("Operation: new = ") val parts = operationStrClean.split(" ") val operator = when (parts[1]) { "*" -> { i1: Long, i2: Long -> i1 * i2 } "+" -> { i1: Long, i2: Long -> i1 + i2 } else -> throw Error("Unexpected operator ${parts[1]}") } return if (parts[0] == "old" && parts[2] == "old") { { i -> operator.invoke(i, i) } } else if (parts[0] == "old") { { i -> operator.invoke(parts[2].toLong(), i) } } else if (parts[0] == "old") { { i -> operator.invoke(i, parts[0].toLong()) } } else { throw Error("Failed to parse operation: $operationStr") } } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
3,778
Advent-of-Code-2022
MIT License
src/main/kotlin/com/ginsberg/advent2021/Day12.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright (c) 2021 by <NAME> */ /** * Advent of Code 2021, Day 12 - Passage Pathing * Problem Description: http://adventofcode.com/2021/day/12 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day12/ */ package com.ginsberg.advent2021 class Day12(input: List<String>) { private val caves: Map<String, List<String>> = parseInput(input) fun solvePart1(): Int = traverse(::part1VisitRule).size fun solvePart2(): Int = traverse(::part2VisitRule).size private fun traverse( allowedToVisit: (String, List<String>) -> Boolean, path: List<String> = listOf("start") ): List<List<String>> = if (path.last() == "end") listOf(path) else caves.getValue(path.last()) .filter { allowedToVisit(it, path) } .flatMap { traverse(allowedToVisit, path + it) } private fun part1VisitRule(name: String, path: List<String>): Boolean = name.isUpperCase() || name !in path private fun part2VisitRule(name: String, path: List<String>): Boolean = when { name.isUpperCase() -> true name == "start" -> false name !in path -> true else -> path .filterNot { it.isUpperCase() } .groupBy { it } .none { it.value.size == 2 } } private fun String.isUpperCase(): Boolean = all { it.isUpperCase() } private fun parseInput(input: List<String>): Map<String, List<String>> = input .map { it.split("-") } .flatMap { listOf( it.first() to it.last(), it.last() to it.first() ) } .groupBy({ it.first }, { it.second }) }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
1,820
advent-2021-kotlin
Apache License 2.0
src/aoc2022/day13/Day13.kt
svilen-ivanov
572,637,864
false
{"Kotlin": 53827}
package aoc2022.day13 import readInput import kotlin.math.min enum class CompareResult(val comparatorOutcome: Int) { CORRECT(-1), INCORRECT(1), SAME(0), } sealed class Packet { abstract fun toNumList(): NumList data class Num(val num: Int) : Packet() { override fun toNumList(): NumList = NumList(mutableListOf(this)) fun compareWith(right: Num): CompareResult { return if (num < right.num) { CompareResult.CORRECT } else if (num > right.num) { CompareResult.INCORRECT } else { CompareResult.SAME } } } data class NumList( val items: MutableList<Packet> = mutableListOf() ) : Packet(), Comparable<NumList> { override fun toNumList() = this override fun compareTo(other: NumList): Int { return compareWith(other).comparatorOutcome } fun compareWith(rightSide: NumList): CompareResult { val len = min(items.size, rightSide.items.size) for (i in 0 until len) { val left = items[i] val right = rightSide.items[i] val result = if (left is Num && right is Num) { left.compareWith(right) } else { left.toNumList().compareWith(right.toNumList()) } if (result == CompareResult.SAME) { continue } else { return result } } return if (items.size < rightSide.items.size) { CompareResult.CORRECT } else if (items.size > rightSide.items.size) { CompareResult.INCORRECT } else { CompareResult.SAME } } } } val tokens = Regex("(])|(\\[)|(,)|(\\d+)") fun main() { fun parseLine(line: String): Packet.NumList { val stack = ArrayDeque<Packet.NumList>() val tokens = tokens.findAll(line) stack.addLast(Packet.NumList()) for (tokenMatch in tokens) { when (val token = tokenMatch.value) { "," -> {} "[" -> Packet.NumList().let { stack.last().items.add(it) stack.addLast(it) } "]" -> stack.removeLast() else -> stack.last().items.add(Packet.Num(token.toInt())) } } require(stack.size == 1) { "Wrong size; ${stack.size}" } return stack.last().items.single() as Packet.NumList } fun part1(input: List<String>) { var sum = 0 for ((i, chunk) in input.chunked(3).withIndex()) { val line = i + 1 val (leftLine, rightLine, _) = chunk val leftPacket = parseLine(leftLine) val rightPacket = parseLine(rightLine) println("Line $line") println(leftPacket) println(rightPacket) val orderResults = leftPacket.compareWith(rightPacket) if (orderResults == CompareResult.CORRECT) { sum += line } println(orderResults) println("---------------") } println(sum) } fun part2(input: List<String>) { val packets = mutableListOf<Packet.NumList>() val div1 = Packet.NumList(mutableListOf(Packet.NumList(mutableListOf(Packet.Num(2))))) packets.add(div1) val div2 = Packet.NumList(mutableListOf(Packet.NumList(mutableListOf(Packet.Num(6))))) packets.add(div2) for (chunk in input.chunked(3)) { val (leftLine, rightLine, _) = chunk val leftPacket = parseLine(leftLine) val rightPacket = parseLine(rightLine) packets.add(leftPacket) packets.add(rightPacket) } packets.sort() println((packets.indexOf(div1) + 1) * (packets.indexOf(div2) + 1)) } val testInput = readInput("day13/day13") part1(testInput) part2(testInput) }
0
Kotlin
0
0
456bedb4d1082890d78490d3b730b2bb45913fe9
4,120
aoc-2022
Apache License 2.0
app/src/main/java/com/itscoder/ljuns/practise/algorithm/QuickSort.kt
ljuns
148,606,057
false
{"Java": 26841, "Kotlin": 25458}
package com.itscoder.ljuns.practise.algorithm /** * Created by ljuns at 2019/1/5. * I am just a developer. * 快速排序 * 例如:3, 1, 1, 6, 2, 4, 19 * 1、定义 left 为最左边,right 为最右边; * 2、选定 left 位置的元素为 temp; * 3、用 temp 从最右边开始比较,大于等于 temp 就 right--,否则 right 位置的元素替换掉 left 的元素,并且 left++; * 4、用 temp 从 left 开始比较,小于等于 temp 就 left++,否则 left 位置的元素替换掉 right 的元素,并且 right--; * 5、此时以 temp 为中心分为两部分,左边的都比 temp 小,右边的都比 temp 大。 * 左边:left 仍为最左边,right 为 temp,右边:left 为 temp+1,right 为最右边;重复2~5,直到 left >= temp 的位置 */ //class QuickSort { fun main(args: Array<String>) { val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19) quickSort(arr, 0, arr.size - 1) for (i in arr) { println(i) } } private fun quickSort(arr: IntArray, left: Int, right: Int) { if (left >= right || arr.size <= 1) return // val mid = partition(arr, left, right) val mid = partition2(arr, left, right) quickSort(arr, left, mid) quickSort(arr, mid + 1, right) } private fun partition2(arr: IntArray, left: Int, right: Int) : Int { var l = left + 1 var r = right val temp = arr[left] while (l <= r) { if (temp < arr[l] && temp > arr[r]) { val t = arr[l] arr[l] = arr[r] arr[r] = t l++ r-- } if (temp >= arr[l]) l++ if (temp <= arr[r]) r-- } arr[left] = arr[r] arr[r] = temp return r } private fun partition(arr: IntArray, left: Int, right: Int) : Int { var left = left var right = right val temp = arr[left] while (left < right) { // 比较右边 while (temp <= arr[right] && left < right) { -- right } // 右边的比 temp 小,需要把 right 放在 left 的位置,并且 left 从下一个位置开始 if (left < right) { arr[left] = arr[right] left ++ } // 比较左边 while (temp >= arr[left] && left < right) { ++ left } // 左边的比 temp 大,需要把 left 放在 right 的位置,并且 right 从前一个位置开始 if (left < right) { arr[right] = arr[left] right -- } } // 此时 left == right arr[left] = temp return left } //}
0
Java
0
0
365062b38a7ac55468b202ebeff1b760663fc676
2,819
Practise
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day13.kt
EmRe-One
434,793,519
false
{"Kotlin": 44202}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.Logger.logger import tr.emreone.kotlin_utils.extensions.permutations object Day13 { class Person(val name: String) { private val happinessMatrix = mutableMapOf<String, Int>() fun addPossibleNeighbor(other: String, happiness: Int) { happinessMatrix[other] = happiness } fun getHappinessTo(other: String): Int { return happinessMatrix[other] ?: 0 } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Person if (name != other.name) return false return true } override fun hashCode(): Int { return name.hashCode() } } class CircularTable(input: List<String>) { /* David would lose 7 happiness units by sitting next to Bob. David would gain 41 happiness units by sitting next to Carol. */ val persons = mutableMapOf<String, Person>() init { val pattern = """^(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+).$""".toRegex() input.forEach { line -> val (name, type, happiness, neighbor) = pattern.matchEntire(line)?.destructured!! val p = persons.getOrPut(name) { Person(name) } val h = if (type == "gain") happiness.toInt() else -happiness.toInt() p.addPossibleNeighbor(neighbor, h) } } fun addMe() { val me = Person("Me") this.persons.values.forEach { person -> person.addPossibleNeighbor("Me", 0) me.addPossibleNeighbor(person.name, 0) } this.persons["Me"] = me } fun calcHappinessOfSeating(seating: List<Pair<String, Person>>): Int { var happinessSum = 0 // beacause of the circularity, we need to add the first person to the end // 1 - 2 - 3 - ... - n - 1 val modifiedSeating = seating + seating.first() modifiedSeating.windowed(2).forEach { (p1, p2) -> happinessSum += p1.second.getHappinessTo(p2.first) + p2.second.getHappinessTo(p1.first) } logger.debug { "Seating arrangement: ${ modifiedSeating.map { it.first }.joinToString(", ") }, happiness: $happinessSum" } return happinessSum } fun findOptimalSeatingArrangement(): List<Pair<String, Person>> { val optimalSeating = this.persons.toList() .permutations() .maxByOrNull { calcHappinessOfSeating(it) } return optimalSeating ?: emptyList() } } fun part1(input: List<String>): Int { val table = CircularTable(input) val optimalSeating = table.findOptimalSeatingArrangement() return table.calcHappinessOfSeating(optimalSeating) } fun part2(input: List<String>): Int { val table = CircularTable(input) table.addMe() val optimalSeating = table.findOptimalSeatingArrangement() return table.calcHappinessOfSeating(optimalSeating) } }
0
Kotlin
0
0
57f6dea222f4f3e97b697b3b0c7af58f01fc4f53
3,389
advent-of-code-2015
Apache License 2.0
src/main/kotlin/_2023/Day14.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2023 import Coordinate import Day import InputReader import atCoordinates class Day14 : Day(2023, 14) { override val firstTestAnswer = 136 override val secondTestAnswer = 64 override fun first(input: InputReader): Int { val schema = input.asLines().map { it.toCharArray() } for (row in schema.indices) { for (column in 0 until schema[row].size) { if (schema[row][column] == 'O') { var newRow = row - 1 while (newRow >= 0 && schema[newRow][column] == '.') { newRow-- } schema[row][column] = '.' schema[newRow + 1][column] = 'O' } } } return schema.mapIndexed { index, row -> row.count { it == 'O' } * (schema.size - index) }.sum() } override fun second(input: InputReader): Int { data class Rock( var coordinate: Coordinate ) val directions = listOf( Coordinate(-1, 0), // top Coordinate(0, -1), // left Coordinate(1, 0), // bottom Coordinate(0, 1), //right ) val schema = input.asLines().map { it.toCharArray() } val rocks = mutableSetOf<Rock>() for (row in schema.indices) { for (column in 0 until schema[row].size) { if (schema[row][column] == 'O') { rocks.add(Rock(Coordinate(row, column))) } } } val cycleHistories = mutableListOf<Set<Rock>>() var cycle = 0 do { directions.forEach { direction -> rocks.sortedBy { if (direction.x != 0) { it.coordinate.x * -direction.x } else { it.coordinate.y * -direction.y } }.forEach { rock -> var newCoordinate = rock.coordinate + direction while (schema.atCoordinates(newCoordinate) == '.') { newCoordinate += direction } newCoordinate -= direction schema[rock.coordinate.x][rock.coordinate.y] = '.' schema[newCoordinate.x][newCoordinate.y] = 'O' rock.coordinate = newCoordinate } } val currentRocks = rocks.mapTo(mutableSetOf()) { it.copy() } val cycleStart = cycleHistories.indexOf(currentRocks) if (cycleStart >= 0) { val endIndex = (1000000000 - cycleStart + 1) % (cycle - cycleStart) - 1 val endRocks = cycleHistories[cycleStart + endIndex - 1] return endRocks.groupBy { it.coordinate.x }.map { (schema.size - it.key) * it.value.size }.sum() } else { cycleHistories.add(currentRocks) cycle++ } } while (cycle < 1000000000) error("cycle not found ") } } fun main() { Day14().solve() }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
3,124
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MeetingScheduler.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import kotlin.math.max import kotlin.math.min /** * Meeting Scheduler * @see <a href="https://leetcode.com/problems/meeting-scheduler/">Source</a> */ fun interface MeetingScheduler { operator fun invoke(slots1: Array<IntArray>, slots2: Array<IntArray>, duration: Int): List<Int> } /** * Approach 1: Two pointers */ class MSTwoPointers : MeetingScheduler { override operator fun invoke(slots1: Array<IntArray>, slots2: Array<IntArray>, duration: Int): List<Int> { slots1.sortWith { a, b -> a[0] - b[0] } slots2.sortWith { a, b -> a[0] - b[0] } var pointer1 = 0 var pointer2 = 0 while (pointer1 < slots1.size && pointer2 < slots2.size) { // find the boundaries of the intersection, or the common slot val intersectLeft = max(slots1[pointer1][0], slots2[pointer2][0]) val intersectRight = min(slots1[pointer1][1], slots2[pointer2][1]) if (intersectRight - intersectLeft >= duration) { return listOf(intersectLeft, intersectLeft + duration) } // always move the one that ends earlier if (slots1[pointer1][1] < slots2[pointer2][1]) { pointer1++ } else { pointer2++ } } return emptyList() } } /** * Approach 2: Heap */ class MSHeap : MeetingScheduler { override operator fun invoke(slots1: Array<IntArray>, slots2: Array<IntArray>, duration: Int): List<Int> { val timeslots: PriorityQueue<IntArray> = PriorityQueue { slot1, slot2 -> slot1[0] - slot2[0] } for (slot in slots1) { if (slot[1] - slot[0] >= duration) timeslots.offer(slot) } for (slot in slots2) { if (slot[1] - slot[0] >= duration) timeslots.offer(slot) } while (timeslots.size > 1) { val slot1: IntArray = timeslots.poll() val slot2: IntArray = timeslots.peek() if (slot1[1] >= slot2[0] + duration) { return listOf(slot2[0], slot2[0] + duration) } } return emptyList() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,802
kotlab
Apache License 2.0
kotlin-examples/src/main/kotlin/de/rieckpil/learning/fpbook/propertytesting/Boilerplate.kt
rieckpil
127,932,091
false
null
package de.rieckpil.learning.fpbook.propertytesting interface RNG { fun nextInt(): Pair<Int, RNG> } data class SimpleRNG(val seed: Long) : RNG { override fun nextInt(): Pair<Int, RNG> { val newSeed = (seed * 0x5DEECE66DL + 0xBL) and 0xFFFFFFFFFFFFL val nextRNG = SimpleRNG(newSeed) val n = (newSeed ushr 16).toInt() return Pair(n, nextRNG) } } fun nonNegativeInt(rng: RNG): Pair<Int, RNG> { val (i1, rng2) = rng.nextInt() return Pair(if (i1 < 0) -(i1 + 1) else i1, rng2) } fun nextBoolean(rng: RNG): Pair<Boolean, RNG> { val (i1, rng2) = rng.nextInt() return Pair(i1 >= 0, rng2) } fun double(rng: RNG): Pair<Double, RNG> { val (i, rng2) = nonNegativeInt(rng) return Pair(i / (Int.MAX_VALUE.toDouble() + 1), rng2) } data class State<S, out A>(val run: (S) -> Pair<A, S>) { companion object { fun <S, A> unit(a: A): State<S, A> = State { s: S -> Pair(a, s) } fun <S, A, B, C> map2( ra: State<S, A>, rb: State<S, B>, f: (A, B) -> C ): State<S, C> = ra.flatMap { a -> rb.map { b -> f(a, b) } } fun <S, A> sequence( fs: List<State<S, A>> ): State<S, List<A>> = fs.foldRight(unit(emptyList())) { f, acc -> map2(f, acc) { h, t -> listOf(h) + t } } } fun <B> map(f: (A) -> B): State<S, B> = flatMap { a -> unit<S, B>(f(a)) } fun <B> flatMap(f: (A) -> State<S, B>): State<S, B> = State { s: S -> val (a: A, s2: S) = this.run(s) f(a).run(s2) } }
23
Java
7
11
33d8f115c81433abca8f4984600a41350a1d831d
1,521
learning-samples
MIT License
advent2022/src/main/kotlin/year2022/Day18.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay import Point3D import exploreFrom class Day18 : AdventDay(2022, 18) { enum class Plane { XY, YZ, XZ } // needed because you have to differentiate data class Face(val point: Point3D, val plane: Plane) private val Point3D.faces get() = setOf( Face(this, Plane.XY), Face(this, Plane.XZ), Face(this, Plane.YZ), Face(this + Point3D.UP, Plane.XY), Face(this + Point3D.RIGHT, Plane.XZ), Face(this + Point3D.FRONT, Plane.YZ) ) data class Boundary3D(val topFrontRight: Point3D, val bottomBackLeft: Point3D) { operator fun contains(other: Point3D) = other.x in (topFrontRight.x..bottomBackLeft.x) && other.y in (topFrontRight.y..bottomBackLeft.y) && other.z in (topFrontRight.z..bottomBackLeft.z) companion object { fun from(points: Collection<Point3D>): Boundary3D { val topFrontRight = Point3D(points.minOf { it.x } - 1, points.minOf { it.y } - 1, points.minOf { it.z } - 1) val bottomBackLeft = Point3D(points.maxOf { it.x } + 1, points.maxOf { it.y } + 1, points.maxOf { it.z } + 1) return Boundary3D(topFrontRight, bottomBackLeft) } } } override fun part1(input: List<String>): Int { val lavaDroplets = input.map { it.split(",").let { (x, y, z) -> Point3D(x.toInt(), y.toInt(), z.toInt()) } }.toSet() return lavaDroplets.sumOf { it.neighbors.count { n -> n !in lavaDroplets } } } override fun part2(input: List<String>): Int { val lavaDroplets = input.map(Point3D.Companion::parse) val potentiallyExposedToAir = lavaDroplets.flatMap { it.faces }.toSet() val boundary = Boundary3D.from(lavaDroplets) val visitedFaces = mutableSetOf<Face>() exploreFrom(Point3D.ORIGIN) { if (item !in lavaDroplets) { visitedFaces.addAll(potentiallyExposedToAir.intersect(item.faces)) markElementsAsToVisit(item.neighbors.filter { it in boundary }) } } return visitedFaces.size } } fun main() = Day18().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
2,332
advent-of-code
Apache License 2.0
src/net/sheltem/aoc/y2023/Day08.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2023 import net.sheltem.common.lcm import net.sheltem.common.regex import net.sheltem.aoc.y2023.Day08.Tree import net.sheltem.aoc.y2023.Day08.Tree.Node suspend fun main() { Day08().run() } class Day08 : Day<Long>(2, 6) { override suspend fun part1(input: List<String>): Long = input .drop(2) .toTree() .traverse("AAA", "ZZZ", input[0]) override suspend fun part2(input: List<String>): Long = input .drop(2) .toTree() .let { tree -> tree.nodes .keys .filter { it.endsWith("A") } .map { tree.traverse(it, "ZZZ", input[0], true) }.lcm() } internal class Tree(val nodes: Map<String, Node>) { fun traverse(start: String, goal: String, instructions: String, shortGoal: Boolean = false): Long { return step(start, goal, instructions, 0, 0, shortGoal) } private tailrec fun step(current: String, goal: String, instructions: String, instructionsIndex: Int, steps: Long, shortGoal: Boolean): Long = when { shortGoal && current.endsWith(goal[2]) -> steps current == goal -> steps else -> step( this.traverseNode(current, instructions[instructionsIndex] == 'L'), goal, instructions, (instructionsIndex + 1).mod(instructions.length), steps + 1, shortGoal ) } private fun traverseNode(name: String, left: Boolean) = nodes[name]!!.let { if (left) it.left else it.right } internal data class Node(val name: String, val left: String, val right: String) } } private fun List<String>.toTree() = map { line -> line.regex("\\w+") .let { Node(it[0], it[1], it[2]) } }.associateBy { it.name } .let(::Tree)
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
1,949
aoc
Apache License 2.0
src/Day03.kt
djleeds
572,720,298
false
{"Kotlin": 43505}
fun main() { fun Char.toPriority() = if (code <= 'Z'.code) this - 'A' + 27 else this - 'a' + 1 fun part1(input: List<String>): Int = input .map { rucksack -> rucksack.chunked(rucksack.length / 2) } .map { (compartment1, compartment2) -> compartment1.first { it in compartment2 } } .sumOf { it.toPriority() } fun part2(input: List<String>): Int = input .chunked(3) .map { (sack1, sack2, sack3) -> sack1.first { it in sack2 && it in sack3 } } .sumOf { it.toPriority() } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
4
98946a517c5ab8cbb337439565f9eb35e0ce1c72
774
advent-of-code-in-kotlin-2022
Apache License 2.0
src/Day12.kt
nordberg
573,769,081
false
{"Kotlin": 47470}
import kotlin.streams.toList fun main() { data class Point(val x: Int, val y: Int) fun getWalkableAdjacent(grid: List<List<Int>>, mid: Point): List<Point> { val maxX = grid.first().indices.max() check(mid.x in 0..maxX) val maxY = grid.indices.max() check(mid.y in 0..maxY) val adjacentPoints = mutableListOf<Point>() if (mid.x > 0) { adjacentPoints.add(mid.copy(x = mid.x - 1)) } if (mid.x < maxX) { adjacentPoints.add(mid.copy(x = mid.x + 1)) } if (mid.y > 0) { adjacentPoints.add(mid.copy(y = mid.y - 1)) } if (mid.y < maxY) { adjacentPoints.add(mid.copy(y = mid.y + 1)) } return adjacentPoints.filter { val adjPointHeight = if (grid[it.y][it.x] == 'E'.code) 'z'.code else grid[it.y][it.x] val currHeight = if (grid[mid.y][mid.x] == 'S'.code) 'a'.code else grid[mid.y][mid.x] currHeight <= adjPointHeight + 1 } } fun calcDistancesToAdjAndFindNewPointsToVisit( input: List<List<Int>>, currentPoint: Point, stepDistances: List<MutableList<Int>>, ): List<Point> { val adjacentPoints = getWalkableAdjacent(input, currentPoint) val pointsToVisit = mutableListOf<Point>() adjacentPoints.forEach { stepDistances[it.y][it.x] = stepDistances[currentPoint.y][currentPoint.x] + 1 pointsToVisit += it } return pointsToVisit } fun part1(mountainMap: List<List<Int>>): Int { val startY = mountainMap.indexOfFirst { y -> y.indexOfFirst { x -> x == 'S'.code } != -1 } val startX = mountainMap[startY].indexOfFirst { x -> x == 'S'.code } val startPoint = Point(startX, startY) val targetY = mountainMap.indexOfFirst { y -> y.indexOfFirst { x -> x == 'E'.code } != -1 } val targetX = mountainMap[startY].indexOfFirst { x -> x == 'E'.code } val targetPoint = Point(targetX, targetY) val stepDistances = mountainMap.map { i -> i.map { if (it == 'S'.code) { 0 } else { Int.MAX_VALUE } }.toMutableList() } val pointsToVisit = mutableSetOf(startPoint) while (stepDistances[targetPoint.y][targetPoint.x] == Int.MAX_VALUE) { val toRemove = mutableSetOf<Point>() val toAdd = mutableSetOf<Point>() pointsToVisit.forEach { toRemove.add(it) toAdd += calcDistancesToAdjAndFindNewPointsToVisit(mountainMap, it, stepDistances) } pointsToVisit.removeAll(toRemove) pointsToVisit.addAll(toAdd.sortedBy { stepDistances[it.y][it.x] }) check(pointsToVisit.size > 0) } return stepDistances[targetPoint.y][targetPoint.x] } fun stepDistFound(mMap: List<List<Int>>, p: Point): Boolean { return mMap[p.y][p.x] < Int.MAX_VALUE } fun part2(mountainMap: List<List<Int>>): Int { val targetPoints = mutableSetOf<Point>() mountainMap.forEachIndexed { y, row -> row.forEachIndexed { x, value -> if (setOf('a', 'S').contains(value.toChar())) { targetPoints.add(Point(x, y)) } } } val targetY = mountainMap.indexOfFirst { y -> y.indexOfFirst { x -> x == 'E'.code } != -1 } val targetX = mountainMap[targetY].indexOfFirst { x -> x == 'E'.code } val startPoint = Point(targetX, targetY) val stepDistances = mountainMap.mapIndexed { y, row -> List(row.size) { x -> if (x == startPoint.x && y == startPoint.y) { 0 } else { Int.MAX_VALUE } }.toMutableList() } val pointsToVisit = mutableSetOf(startPoint) while (targetPoints.none { stepDistFound(stepDistances, it) }) { val toRemove = mutableSetOf<Point>() val toAdd = mutableSetOf<Point>() pointsToVisit.forEach { toRemove.add(it) toAdd += calcDistancesToAdjAndFindNewPointsToVisit(mountainMap, it, stepDistances) } pointsToVisit.removeAll(toRemove) pointsToVisit.addAll(toAdd.sortedBy { stepDistances[it.y][it.x] }) check(pointsToVisit.size > 0) } return targetPoints.minOf { stepDistances[it.y][it.x] } } val input = readInput("Day12").map { it.chars().toList() } val minDist = part2(input) println(minDist) }
0
Kotlin
0
0
3de1e2b0d54dcf34a35279ba47d848319e99ab6b
4,720
aoc-2022
Apache License 2.0
src/Day02.kt
camina-apps
572,935,546
false
{"Kotlin": 7782}
fun main() { fun outcomeRound(opponent: String, you: String): Int { when (you) { "A" -> { if (opponent == "A") return 3 } // rock "B" -> { if (opponent == "B") return 3 } // paper "C" -> { if (opponent == "C") return 3 } // scissor } when (you) { "A" -> { if (opponent == "C") return 6 } // rock - scissor "B" -> { if (opponent == "A") return 6 } // paper - rock "C" -> { if (opponent == "B") return 6 } // scissor - paper } return 0 } fun scoreShape(shape: String): Int { return when (shape) { "X", "A" -> 1 "Y", "B" -> 2 "Z", "C" -> 3 else -> 0 } } fun getLooseShape(opponent: String): String { return when (opponent) { "A" -> "C" "B" -> "A" "C" -> "B" else -> "" } } fun getWinShape(opponent: String): String { return when (opponent) { "A" -> "B" "B" -> "C" "C" -> "A" else -> "" } } fun mapOutcomeToShape(oppponent: String, outcome: String): String { return when (outcome) { "Y" -> oppponent "X" -> getLooseShape(oppponent) "Z" -> getWinShape(oppponent) else -> "" } } fun totalScoreRound(opponent: String, you: String): Int { return outcomeRound(opponent, you) + scoreShape(you) } fun part1(input: List<String>): Int { val strategyGuide = input var sum = 0 strategyGuide.forEach { sum += totalScoreRound(it.take(1), it.takeLast(1)) } return sum } fun part2(input: List<String>): Int { var sum = 0 input.forEach { val opponent = it.take(1) val outcome = it.takeLast(1) val you = mapOutcomeToShape(opponent, outcome) sum += totalScoreRound(opponent, you) } return sum } val testInput = readInput("Day02_test") // check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
fb6c6176f8c127e9d36aa0b7ae1f0e32b5c31171
2,429
aoc_2022
Apache License 2.0
src/Day07.kt
andydenk
573,909,669
false
{"Kotlin": 24096}
import java.lang.IllegalStateException fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<String>): Int { val directoryTree = createDirectoryTree(input) return calculateTotalSizesOfMatchingDirectories(directoryTree) } private fun part2(input: List<String>): Int { val directoryTree = createDirectoryTree(input) return calculateDirectoryToDelete(directoryTree) } private fun createDirectoryTree(input: List<String>): Directory { val lines = input.drop(1) val directoryTree = Directory("root", emptyList()) var currentDirectory = directoryTree for (line in lines) { line.apply { if (line == "$ cd ..") { currentDirectory = directoryTree.findDirectory(currentDirectory.path) } else if (startsWith("$ cd ")) { currentDirectory = currentDirectory.findDirectory(drop(5)) } else if (isDirectory() || isFile()) { currentDirectory.children.add(asStructure(currentDirectory)) } } } return directoryTree } private fun calculateTotalSizesOfMatchingDirectories(directory: Directory): Int { val matchingDirectories: MutableSet<Directory> = mutableSetOf() saveMatchingDirectories(directory, matchingDirectories) { it.getSize() < 100000 } return matchingDirectories.sumOf { it.getSize() } } private fun calculateDirectoryToDelete(directory: Directory): Int { val matchingDirectories: MutableSet<Directory> = mutableSetOf() saveMatchingDirectories(directory, matchingDirectories) { true } val neededSpace = directory.getSize() - (70000000 - 30000000) return matchingDirectories.map { it.getSize() }.filter { it > neededSpace }.min() } private fun saveMatchingDirectories( currentDirectory: Directory, matchingDirectories: MutableSet<Directory>, directoryIsRelevant: (Directory) -> Boolean ) { if (directoryIsRelevant.invoke(currentDirectory)) { matchingDirectories.add(currentDirectory) } val childDirectories = currentDirectory.getChildDirectories() if (childDirectories.isEmpty()) { return } childDirectories.forEach { saveMatchingDirectories(it, matchingDirectories, directoryIsRelevant) } } private typealias Line = String private typealias PathComponent = String private fun Line.asStructure(currentDirectory: Directory): Structure { val directory = asDirectory(currentDirectory).takeIf { isDirectory() } return directory ?: asFile().takeIf { isFile() } ?: throw IllegalStateException("Neither file nor directory") } private fun Line.isDirectory(): Boolean = startsWith("dir") private fun Line.asDirectory(parent: Directory): Directory { val path = parent.name.takeUnless { it == "root" }?.let { parent.path + it } ?: parent.path return Directory(name = drop(4), path, children = mutableSetOf()) } private fun Line.isFile(): Boolean = first().isDigit() private fun Line.asFile() = split(" ").let { File(fileSize = it[0].toInt(), name = it[1]) } private data class Directory( override val name: String, val path: List<PathComponent>, val children: MutableSet<Structure> = mutableSetOf() ) : Structure { override fun isDirectory(): Boolean = true override fun getSize() = children.sumOf { it.getSize() } fun getChildDirectories() = children.mapNotNull { it as? Directory } fun findDirectory(name: String): Directory { val directSubDirectory = children.find { it.name == name } as? Directory return directSubDirectory ?: throw IllegalStateException("No directory with this name found.") } fun findDirectory(path: List<String>): Directory { var target = this path.forEach { name -> target = target.findDirectory(name) } return target } } private data class File(override val name: String, val fileSize: Int) : Structure { override fun isDirectory(): Boolean = false override fun getSize(): Int = fileSize } private interface Structure { val name: String fun isDirectory(): Boolean fun getSize(): Int }
0
Kotlin
0
0
1b547d59b1dc55d515fe8ca8e88df05ea4c4ded1
4,377
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day13.kt
kevinrobayna
436,414,545
false
{"Ruby": 195446, "Kotlin": 42719, "Shell": 1288}
import java.lang.Math.floorMod fun day13ProblemReader(text: String): Pair<Int, List<String>> { val lines = text.split('\n') return Pair( lines[0].toInt(), lines[1].split(",") ) } // https://adventofcode.com/2020/day/13 class Day13( private val problem: Pair<Int, List<String>>, ) { fun solvePart1(): Int { val (target, schedule) = problem val ids = schedule.filter { it != "x" } val nextDeparture = ids.map { val id = it.toDouble() val lastDeparture = target % id ((target - lastDeparture) + id - target) } val minutesToNextBus = nextDeparture.minOrNull() return if (minutesToNextBus != null) { (minutesToNextBus.toInt() * ids[nextDeparture.indexOf(minutesToNextBus)].toInt()) } else 0 } // i do not fully understand this // source https://github.com/ephemient/aoc2020/blob/main/kt/src/main/kotlin/io/github/ephemient/aoc2020/Day13.kt fun solvePart2(): Long { val (_, schedule) = problem return schedule.withIndex() .filter { (_, id) -> id != "x" } .map { (inx, id) -> inx to id.toInt() } .map { (inx, id) -> floorMod(-inx, id).toLong() to id.toLong() } .fold(0L to 1L) { (r1, q1), (r2, q2) -> crt(r1, q1, r2, q2) }.first } private fun crt(r1: Long, q1: Long, r2: Long, q2: Long): Pair<Long, Long> { var a = r1 var b = r2 while (a != b) { if (a < b) { a += (b - a + q1 - 1) / q1 * q1 } else { b += (a - b + q2 - 1) / q2 * q2 } } return a to q1 * q2 } } fun main() { val problem = day13ProblemReader(Day13::class.java.getResource("day13.txt").readText()) println("solution = ${Day13(problem).solvePart1()}") println("solution part2 = ${Day13(problem).solvePart2()}") }
0
Ruby
0
0
9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577
1,954
adventofcode_2020
MIT License
src/Day18.kt
sabercon
648,989,596
false
null
fun main() { fun evaluate1(expression: List<String>): Long { val ops = ArrayDeque<String>() val nums = ArrayDeque<Long>() for (token in expression) { when (token) { "+", "*", "(" -> { ops.add(token) continue } ")" -> ops.removeLast() else -> nums.add(token.toLong()) } if (ops.lastOrNull() in listOf("+", "*")) { when (ops.removeLast()) { "+" -> nums.add(nums.removeLast() + nums.removeLast()) "*" -> nums.add(nums.removeLast() * nums.removeLast()) } } } return nums.single() } fun evaluate2(expression: List<String>): Long { val ops = ArrayDeque<String>() val nums = ArrayDeque<Long>() for (token in expression) { when (token) { "+", "*", "(" -> { ops.add(token) continue } ")" -> while (ops.removeLast() != "(") nums.add(nums.removeLast() * nums.removeLast()) else -> nums.add(token.toLong()) } if (ops.lastOrNull() == "+") { ops.removeLast() nums.add(nums.removeLast() + nums.removeLast()) } } return nums.single() } val input = readLines("Day18") .map { "($it)".replace("(", "( ").replace(")", " )").split(" ") } input.sumOf { evaluate1(it) }.println() input.sumOf { evaluate2(it) }.println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
1,629
advent-of-code-2020
MIT License
src/Day05.kt
DiamondMiner88
573,073,199
false
{"Kotlin": 26457, "Rust": 4093, "Shell": 188}
fun main() { d5part1() d5part2() } fun d5part1() { val input = readInput("input/day05.txt") .split("\n\n") val stackSplits = input[0].split("\n") val stacksCount = stackSplits.last().count { it.isDigit() } val stacks = MutableList<MutableList<Char>>(9) { mutableListOf() } for (stack in stackSplits.take(stackSplits.size - 1)) { val indexes = (0 until stacksCount).map { 1 + it * 4 } indexes.mapIndexed { i, index -> val char = stack.getOrNull(index) if (char != null && char != ' ') { stacks[i] += char } } } stacks.forEachIndexed { index, stack -> stacks[index] = stack.reversed().toMutableList() } val regex = "move (\\d{1,2}) from (\\d) to (\\d)".toRegex() for (inst in input[1].split("\n").filter { it.isNotBlank() }) { val (_, count, from, to) = regex.find(inst)!!.groupValues val src = stacks[from.toInt() - 1] val dst = stacks[to.toInt() - 1] val removed = src.takeLast(count.toInt()).reversed() for (i in (0 until count.toInt())) src.removeLast() dst.addAll(removed.toTypedArray()) } println(stacks.joinToString("") { it.last().toString() }) } fun d5part2() { val input = readInput("input/day05.txt") .split("\n\n") val stackSplits = input[0].split("\n") val stacksCount = stackSplits.last().count { it.isDigit() } val stacks = MutableList<MutableList<Char>>(9) { mutableListOf() } for (stack in stackSplits.take(stackSplits.size - 1)) { val indexes = (0 until stacksCount).map { 1 + it * 4 } indexes.mapIndexed { i, index -> val char = stack.getOrNull(index) if (char != null && char != ' ') { stacks[i] += char } } } stacks.forEachIndexed { index, stack -> stacks[index] = stack.reversed().toMutableList() } val regex = "move (\\d{1,2}) from (\\d) to (\\d)".toRegex() for (inst in input[1].split("\n").filter { it.isNotBlank() }) { val (_, count, from, to) = regex.find(inst)!!.groupValues val src = stacks[from.toInt() - 1] val dst = stacks[to.toInt() - 1] val removed = src.takeLast(count.toInt()) for (i in (0 until count.toInt())) src.removeLast() dst.addAll(removed.toTypedArray()) } println(stacks.joinToString("") { it.last().toString() }) }
0
Kotlin
0
0
55bb96af323cab3860ab6988f7d57d04f034c12c
2,462
advent-of-code-2022
Apache License 2.0
src/main/kotlin/solutions/day20/Day20.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day20 import solutions.Solver import kotlin.math.abs var INDEX = 0 fun getIndex(): Int = INDEX++ data class Chain<T>( val value: T, var next: Chain<T>?, var prev: Chain<T>? ) { val index: Int = getIndex() fun move(steps: Long) { var next = this.next!! var prev = this.prev!! prev.next = next next.prev = prev val chainToMove = this var curr = chainToMove if (steps > 0) { for (s in 0 until steps) { curr = curr.next!! } } else { for (s in 0..abs(steps)) { curr = curr.prev!! } } chainToMove.prev = curr chainToMove.next = curr.next curr.next = chainToMove chainToMove.next!!.prev = chainToMove } fun toList(): List<Chain<T>> { val indexToStopAt = this.index var curr = this val list = mutableListOf<Chain<T>>() do { list += curr curr = curr.next!! } while (curr.index != indexToStopAt) return list } } class Day20 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val nbrs = input.map { it.trim().toLong() } .map { if (!partTwo) { it } else { it * 811589153 } } val start: Chain<Long> = chainFromList(nbrs) val list = start.toList() val mixes = if (!partTwo) { 1 } else { 10 } for (s in 1..mixes) { mix(list) } val zeroLink = start.toList().first { it.value == 0L } var curr = zeroLink val mixedNbrs = mutableListOf<Long>() for (s in 1..3000) { curr = curr.next!! if (s % 1000 == 0) { mixedNbrs += curr.value } } return mixedNbrs.sum().toString() } fun chainFromList(nbrs: List<Long>): Chain<Long> { INDEX = 0 val start: Chain<Long> = Chain(nbrs.first(), next = null, prev = null) var prev: Chain<Long> = start for (n in nbrs.drop(1)) { val curr = Chain(n, next = null, prev = prev) prev.next = curr prev = curr } prev.next = start start.prev = prev return start } private fun mix(chain: List<Chain<Long>>) { for (n in chain) { val rest = abs(n.value) % (chain.size - 1) val move = if (n.value < 0) { -rest } else { rest } n.move(move) } } private fun printChain(start: Chain<Long>) { var s = "[" var curr = start do { s += "${curr.value}," curr = curr.next!! } while (curr.index != 0) println("${s.removeSuffix(",")}]") } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
2,993
Advent-of-Code-2022
MIT License
src/main/kotlin/day1/day1.kt
lavong
317,978,236
false
null
/* --- Day 1: Report Repair --- After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island. Surely, Christmas will go on without you. The tropical island has its own currency and is entirely cash-only. The gold coins used there have a little picture of a starfish; the locals just call them stars. None of the currency exchanges seem to have heard of them, but somehow, you'll need to find fifty of these coins by the time you arrive so you can pay the deposit on your room. To save your vacation, you need to get all fifty stars by December 25th. Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! Before you leave, the Elves in accounting just need you to fix your expense report (your puzzle input); apparently, something isn't quite adding up. Specifically, they need you to find the two entries that sum to 2020 and then multiply those two numbers together. For example, suppose your expense report contained the following: 1721 979 366 299 675 1456 In this list, the two entries that sum to 2020 are 1721 and 299. Multiplying them together produces 1721 * 299 = 514579, so the correct answer is 514579. --- Part Two --- The Elves in accounting are thankful for your help; one of them even offers you a starfish coin they had left over from a past vacation. They offer you a second one if you can find three numbers in your expense report that meet the same criteria. Using the above example again, the three entries that sum to 2020 are 979, 366, and 675. Multiplying them together produces the answer, 241861950. In your expense report, what is the product of the three entries that sum to 2020? */ package day1 import kotlin.system.exitProcess const val target = 2020 fun main() { val input = AdventOfCode.file("day1/input") .lines() .filter { it.isNotEmpty() } .map { it.toInt() } .toHashSet() .filter { it < target } solvePartOne(input) solvePartTwo(input) } fun solvePartOne(input: List<Int>) { input.listIterator().forEach { candidate -> (target - candidate) .takeIf { input.contains(it) } ?.let { println("solution part1: $candidate x $it = ${candidate * it}") } ?.also { return } } } fun solvePartTwo(input: List<Int>) { input.listIterator().forEach { n1 -> val n2CandidatesWithSums = mutableMapOf<Int, Int>().apply { input.filter { it < (target - n1) } .onEach { put(it, n1 + it) } } n2CandidatesWithSums.forEach { (n2, sumN1N2) -> (target - sumN1N2) .takeIf { input.contains(it) } ?.let { println("solution part2: $n1 x $n2 x $it = ${n1 * n2 * it}") } ?.also { exitProcess(0) } } } }
0
Kotlin
0
1
a4ccec64a614d73edb4b9c4d4a72c55f04a4b77f
2,963
adventofcode-2020
MIT License
src/Day04.kt
BrianEstrada
572,700,177
false
{"Kotlin": 22757}
fun main() { // Test Case val testInput = readInput("Day04_test") val part1TestResult = Day04.part1(testInput) println(part1TestResult) check(part1TestResult == 2) val part2TestResult = Day04.part2(testInput) println(part2TestResult) check(part2TestResult == 4) // Actual Case val input = readInput("Day04") println("Part 1: " + Day04.part1(input)) println("Part 2: " + Day04.part2(input)) } private object Day04 { fun part1(input: List<String>): Int { var total = 0 for (line in input) { val (first, second) = line.split(',') val firstSet = first.toNumberSet() val secondSet = second.toNumberSet() when { (firstSet intersect secondSet) == firstSet -> total++ (firstSet intersect secondSet) == secondSet -> total++ (secondSet intersect firstSet) == firstSet -> total++ (secondSet intersect firstSet) == secondSet -> total++ } } return total } fun part2(input: List<String>): Int { var total = 0 for (line in input) { val (first, second) = line.split(',') val firstSet = first.toNumberSet() val secondSet = second.toNumberSet() val intersecting = (firstSet intersect secondSet) if (intersecting.isNotEmpty()) { total++ } } return total } private fun String.toNumberSet(): Set<Int> { val (start, end) = this.split("-") return (start.toInt()..end.toInt()).toSet() } }
1
Kotlin
0
1
032a4693aff514c9b30e979e63560dc48917411d
1,639
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/tw/gasol/aoc/aoc2022/Day13.kt
Gasol
574,784,477
false
{"Kotlin": 70912, "Shell": 1291, "Makefile": 59}
package tw.gasol.aoc.aoc2022 typealias Packet = List<Any> class Day13 { fun part1(input: String): Int { val pairs = input.split("\n\n") .map { val (first, second) = it.split("\n") toPacket(first) to toPacket(second) } return pairs.map { isRightOrder(it.first, it.second) } .mapIndexed { index, b -> if (b!!) index + 1 else 0 } .sum() } fun isRightOrder(first: List<Any>, second: List<Any>): Boolean? { for (i in first.indices) { val left = first.getOrNull(i) val right = second.getOrNull(i) if (left is Int && right is Int) { return if (left > right) { false } else if (left < right) { true } else { continue } } else if (left is List<*> && right is List<*>) { isRightOrder(left.filterIsInstance<Any>(), right.filterIsInstance<Any>()) ?.let { return it } } else if (left is Int && right is List<*>) { isRightOrder(listOf(left), right.filterIsInstance<Any>())?.let { return it } } else if (right is Int && left is List<*>) { isRightOrder(left.filterIsInstance<Any>(), listOf(right))?.let { return it } } } return if (first.size > second.size) { false } else if (first.size < second.size) { true } else { null } } fun toPacket(line: String): Packet { val lists = mutableListOf<MutableList<Any>>() val sb = StringBuilder() for (c in line.toCharArray()) { when (c) { '[' -> { lists.add(mutableListOf()) } ']' -> { val item = sb.toString() if (item.isNotBlank()) { lists.last().add(item.toInt()) sb.clear() } val list = lists.removeLast() if (lists.size == 0) { return list } else { lists.last().add(list) } } ',' -> { val item = sb.toString() if (item.isNotBlank()) { lists.last().add(item.toInt()) } sb.clear() } else -> sb.append(c) } } error("Invalid line - $line") } fun sortPackets(packets: List<Packet>): List<Packet> { return packets.sortedWith { o1, o2 -> isRightOrder(o1, o2)?.let { if (it) { -1 } else { 1 } } ?: 0 } } fun part2(input: String): Int { val dividerPackets = listOf("[[2]]", "[[6]]") val packets = buildList { addAll(dividerPackets.map { toPacket(it) }) addAll( input.lines() .filterNot { it.isBlank() } .map { toPacket(it) } ) } return sortPackets(packets).map { it.toString().replace(" ", "") } .mapIndexed { index, s -> if (dividerPackets.contains(s.trim())) index + 1 else 0 }.filter { it > 0 } .reduce(Int::times) } }
0
Kotlin
0
0
a14582ea15f1554803e63e5ba12e303be2879b8a
3,588
aoc2022
MIT License
src/Day05.kt
makobernal
573,037,099
false
{"Kotlin": 16467}
typealias ElfStack = ArrayDeque<Char> typealias Warehouse = List<ElfStack> data class Command(val quantity: Int, val source: Int, val destination: Int) fun calculateRealIndex(currentIndex: Int): Int { //2,1,1 --> f(1) = 1 //6,5,2 --> f(2) = f(1) + 4 //10,9,3 --> f(3) = f(2) + 4 //14,13,4 //18,17,5 //22,21,6 return if (currentIndex <= 1) { 1 } else { calculateRealIndex(currentIndex - 1) + 4 } } fun memoizeIndexes(size: Int): List<Pair<Int, Int>> { return (1..size).map { Pair(it, calculateRealIndex(it)) } } fun extractNumbers(str: String): List<Int> { val numbers = mutableListOf<Int>() val numberRegex = Regex("\\d+") val matches = numberRegex.findAll(str) for (match in matches) { numbers.add(match.value.toInt()) } return numbers } fun extractLettersWithIndices(s: String): Map<Int, Char> { val result = mutableMapOf<Int, Char>() for (i in s.indices) { val c = s[i] if (c.isLetter()) { result[i] = c } } return result } fun transposeIndex(badIndex: Int, indexMap: List<Pair<Int, Int>>): Int { return indexMap.find { it.second == badIndex }!!.first } fun main() { fun buildInput(input: List<String>): Pair<Warehouse, List<Command>> { val rawWarehouse = input.subList(0, input.indexOf("")) val numberOfElfStacks = extractNumbers(rawWarehouse.last()).last() val indexMap = memoizeIndexes(numberOfElfStacks) val lettersWithIndices = rawWarehouse.dropLast(1).map { extractLettersWithIndices(it) } val emptyWarehouse = (1..numberOfElfStacks).map { ArrayDeque<Char>() } //fillWarehouse lettersWithIndices.forEach { level -> level.forEach { index: Int, content: Char -> emptyWarehouse[transposeIndex(index, indexMap) - 1].addLast(content) } } val rawCommands = input.subList((input.indexOf("") + 1), input.size) val commands = rawCommands.map { extractNumbers(it) }.map { Command(it[0], it[1], it[2]) } return Pair(emptyWarehouse, commands) } fun applyCommandCrateMover9001(warehouse: List<ArrayDeque<Char>>, command: Command) { println("moving ${command.quantity} from ${command.source} to ${command.destination}") println("b = $warehouse") val tempDeque = ArrayDeque<Char>() repeat(command.quantity) { tempDeque.addLast(warehouse[command.source-1].removeFirst()) } repeat(command.quantity) { warehouse[command.destination-1].addFirst(tempDeque.removeLast()) } println("a = $warehouse") } fun applyCommandCrateMover9000(warehouse: List<ArrayDeque<Char>>, command: Command) { repeat(command.quantity) { // println("moving ${warehouse[command.source-1].first()} from ${command.source} to ${command.destination}") // println("b = $warehouse") warehouse[command.destination-1].addFirst(warehouse[command.source-1].removeFirst()) // println("a = $warehouse") } } fun orderWarehouse(typedInput: Pair<List<ArrayDeque<Char>>, List<Command>>): Unit { typedInput.second.forEach { applyCommandCrateMover9000(typedInput.first, it) } } fun orderWarehouse2(typedInput: Pair<List<ArrayDeque<Char>>, List<Command>>): Unit { typedInput.second.forEach { applyCommandCrateMover9001(typedInput.first, it) } } fun part1(input: List<String>): String { val typedInput = buildInput(input) orderWarehouse(typedInput) val topElements = typedInput.first.map { it.first() } return String(topElements.toCharArray()) } fun part2(input: List<String>): String { val typedInput = buildInput(input) orderWarehouse2(typedInput) val topElements = typedInput.first.map { it.first() } return String(topElements.toCharArray()) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") val testResult = part1(testInput) val testResult2 = part2(testInput) check(testResult == "CMZ") { "wrong input $testResult is not CMZ" } check(testResult2 == "MCD") { "wrong input $testResult is not MCD" } val input = readInput("Day05") val result1 = part1(input) val result2 = part2(input) println("solution for your input, part 1 = $result1") println("solution for your input, part 2 = $result2") }
0
Kotlin
0
0
63841809f7932901e97465b2dcceb7cec10773b9
4,622
kotlin-advent-of-code-2022
Apache License 2.0
2023/src/main/kotlin/de/skyrising/aoc2023/day1/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2023.day1 import de.skyrising.aoc.* fun digitToInt(s: String) = when (s) { "0", "zero" -> 0 "1", "one" -> 1 "2", "two" -> 2 "3", "three" -> 3 "4", "four" -> 4 "5", "five" -> 5 "6", "six" -> 6 "7", "seven" -> 7 "8", "eight" -> 8 "9", "nine" -> 9 else -> error("Invalid digit: $s") } val test = TestInput( """ 1abc2 pqr3stu8vwx a1b2c3d4e5f treb7uchet """.trimIndent() ) val test2 = TestInput( """ two1nine eightwothree abcone2threexyz xtwone3four 4nineeightseven2 zoneight234 7pqrstsixteen """.trimIndent() ) @PuzzleName("Trebuchet?!") fun PuzzleInput.part1() = lines.sumOf { val digits = it.filter(Char::isDigit) digits[0].digitToInt() * 10 + digits.last().digitToInt() } val regexStart = Regex("\\d|one|two|three|four|five|six|seven|eight|nine") val regexEnd = Regex(".*(\\d|one|two|three|four|five|six|seven|eight|nine)") fun PuzzleInput.part2() = lines.sumOf { val first = regexStart.find(it)?.value ?: error("No first digit") val last = regexEnd.find(it)?.groups?.get(1)?.value ?: error("No last digit") val result = digitToInt(first) * 10 + digitToInt(last) // val digits = regexStart.findAll(it).map(MatchResult::value).toList() // val result2 = digitToInt(digits[0]) * 10 + digitToInt(digits.last()) // if (result != result2) error("Mismatch: $result != $result2 $it $digits") result }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
1,455
aoc
MIT License
Day_11/Solution_Pat1.kts
0800LTT
317,590,451
false
null
import java.io.File enum class Seat { Empty, Occupied, Floor } fun File.readSeats(): Array<Array<Seat>> { return readLines().map { line -> line.map { when (it) { '.' -> Seat.Floor 'L' -> Seat.Empty else -> Seat.Occupied } }.toTypedArray() }.toTypedArray() } fun printSeats(seats: Array<Array<Seat>>) { for (row in seats) { for (seat in row) { print(when (seat) { Seat.Empty -> 'L' Seat.Occupied -> '#' Seat.Floor -> '.' }) } println("") } println("") } fun countOccupiedNeighbors(seats: Array<Array<Seat>>, row: Int, column: Int): Int { var count = 0 for (rowOffset in -1..1) { for (colOffset in -1..1) { val rr = row + rowOffset val cc = column + colOffset // bounds check if ((rr == row && cc == column) || (rr < 0 || rr >= seats.size) || (cc < 0 || cc >= seats[0].size)) { continue } if (seats[rr][cc] == Seat.Occupied) count++ } } return count } fun countOccupiedSeats(seats: Array<Array<Seat>>): Int = seats.map { it.count { it == Seat.Occupied }}.reduce { acc, n -> acc + n } fun simulate(seats: Array<Array<Seat>>): Int { val rows = seats.size val cols = seats[0].size var current = seats var next = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}} while (true) { var changed = false // printSeats(current) for (i in 0..rows-1) { for (j in 0..cols-1) { val numOccupiedNeighbors = countOccupiedNeighbors(current, i, j) if (current[i][j] == Seat.Empty && numOccupiedNeighbors == 0) { next[i][j] = Seat.Occupied changed = true } else if (current[i][j] == Seat.Occupied && numOccupiedNeighbors >= 4) { next[i][j] = Seat.Empty changed = true } else { next[i][j] = current[i][j] } } } val tmp = current current = next next = tmp if (!changed) { break } } return countOccupiedSeats(current) } fun main() { val seats = File("small_input2.txt").readSeats() println(simulate(seats)) } main()
0
Kotlin
0
0
191c8c307676fb0e7352f7a5444689fc79cc5b54
2,047
advent-of-code-2020
The Unlicense
src/Day20.kt
jordan-thirus
573,476,470
false
{"Kotlin": 41711}
import kotlin.math.abs fun main() { fun mix(lst: MutableList<Node>, verbose: Boolean) { for (index in lst.indices) { val i = lst.indexOfFirst { it.mixOrder == index } val node = lst[i] val moveAmount = node.value if (abs(moveAmount) > lst.size) moveAmount % lst.size if (moveAmount != 0L) { lst.removeAt(i) var newIndex = i + moveAmount if (newIndex > lst.lastIndex) { newIndex %= lst.size } else if (newIndex <= 0) { newIndex = newIndex % lst.size + lst.size } lst.add(newIndex.toInt(), node) } printVerbose(lst.toString(), verbose) } } fun part1(input: List<String>, verbose: Boolean): Long { val lst = input.mapIndexed { index, it -> Node(it.toLong(), index) }.toMutableList() mix(lst, verbose) val indexOfZero = lst.indexOfFirst { it.value == 0L } val indexOfZeroPlus1000 = (indexOfZero + 1000) % lst.size val indexOfZeroPlus2000 = (indexOfZero + 2000) % lst.size val indexOfZeroPlus3000 = (indexOfZero + 3000) % lst.size return lst[indexOfZeroPlus1000].value + lst[indexOfZeroPlus2000].value + lst[indexOfZeroPlus3000].value } fun part2(input: List<String>, verbose: Boolean): Long { val lst = input.mapIndexed { index, it -> Node(it.toLong() * 811589153, index) }.toMutableList() repeat(10){ mix(lst, false) printVerbose(lst.toString(), verbose) } val indexOfZero = lst.indexOfFirst { it.value == 0L } val indexOfZeroPlus1000 = (indexOfZero + 1000) % lst.size val indexOfZeroPlus2000 = (indexOfZero + 2000) % lst.size val indexOfZeroPlus3000 = (indexOfZero + 3000) % lst.size return lst[indexOfZeroPlus1000].value + lst[indexOfZeroPlus2000].value + lst[indexOfZeroPlus3000].value } // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test") check(part1(testInput, true) == 3L) check(part2(testInput, true) == 1623178306L) val input = readInput("Day20") println(part1(input, false)) println(part2(input, false)) } data class Node(val value: Long, val mixOrder: Int) { override fun toString() = value.toString() }
0
Kotlin
0
0
59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e
2,418
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day02.kt
rgawrys
572,698,359
false
{"Kotlin": 20855}
import Outcome.DRAW import Outcome.LOST import Outcome.WON import Shape.PAPER import Shape.ROCK import Shape.SCISSORS import utils.readInput fun main() { fun part1(strategyGuide: List<String>): Int = strategyGuide .toGameRounds() .calculateGameTotalScore() fun part2(input: List<String>): Int = input .toGameRoundsWithIndicatedOutcome() .calculateGameTotalScore2() // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") part1(testInput).let { check(it == 15) { "Part 1: Incorrect result. Is `$it`, but should be `15`" } } val input = readInput("Day02") println(part1(input)) println(part2(input)) } private enum class Shape { ROCK, PAPER, SCISSORS } private enum class Outcome { LOST, DRAW, WON } private data class Round(val opponentShape: Shape, val myShape: Shape) private data class RoundWithIndicatedOutcome(val opponentShape: Shape, val indicatedOutcome: Outcome) private val shapeByOpponentEncryptedCodes = mapOf( "A" to ROCK, "B" to PAPER, "C" to SCISSORS ) private val shapeByMyEncryptedCodes = mapOf( "X" to ROCK, "Y" to PAPER, "Z" to SCISSORS ) private val indicatedOutcomeByEncryptedCodes = mapOf( "X" to LOST, "Y" to DRAW, "Z" to WON ) private val scoreByShapes = mapOf( ROCK to 1, PAPER to 2, SCISSORS to 3 ) private val scoreByRoundOutcomes = mapOf( LOST to 0, DRAW to 3, WON to 6 ) private val roundOutcomeByPlays = mapOf( Round(ROCK, ROCK) to DRAW, Round(ROCK, PAPER) to WON, Round(ROCK, SCISSORS) to LOST, Round(PAPER, ROCK) to LOST, Round(PAPER, PAPER) to DRAW, Round(PAPER, SCISSORS) to WON, Round(SCISSORS, ROCK) to WON, Round(SCISSORS, PAPER) to LOST, Round(SCISSORS, SCISSORS) to DRAW, ) // private val shapeToChooseByRoundsWithIndicatedOutcome = // roundOutcomeByPlays // .map { RoundWithIndicatedOutcome(it.key.opponentShape, it.value) to it.key.myShape } // .toMap() private fun Round.calculateRoundScore() = this.myShape.toScore() + roundOutcome(this).toScore() private fun RoundWithIndicatedOutcome.calculateRoundScore() = this.indicatedOutcome.toScore() + shapeToChooseForOutcome(this).toScore() private fun List<Round>.calculateGameTotalScore(): Int = this.sumOf(Round::calculateRoundScore) private fun List<RoundWithIndicatedOutcome>.calculateGameTotalScore2(): Int = this.sumOf(RoundWithIndicatedOutcome::calculateRoundScore) private fun roundOutcome(round: Round): Outcome = roundOutcomeByPlays[round]!! private fun shapeToChooseForOutcome(round: RoundWithIndicatedOutcome): Shape = with(round) { roundOutcomeByPlays .filterValues { it == indicatedOutcome } .filterKeys { it.opponentShape == opponentShape } .firstNotNullOf { it } .key .myShape } // private fun shapeToChooseForOutcome(round: RoundWithIndicatedOutcome): Shape = // shapeToChooseByRoundsWithIndicatedOutcome[round]!! private fun Outcome.toScore(): Int = scoreByRoundOutcomes[this]!! private fun Shape.toScore(): Int = scoreByShapes[this]!! private fun List<String>.toGameRounds(): List<Round> = this.map(String::toRound) private fun List<String>.toGameRoundsWithIndicatedOutcome(): List<RoundWithIndicatedOutcome> = this.map(String::toRoundWithIndicatedOutcome) private fun String.toRound(): Round = this.split(" ").let { Round(it[0].toOpponentShape(), it[1].toMyShape()) } private fun String.toRoundWithIndicatedOutcome(): RoundWithIndicatedOutcome = this.split(" ").let { RoundWithIndicatedOutcome(it[0].toOpponentShape(), it[1].toIndicatedOutcome()) } private fun String.toOpponentShape(): Shape = shapeByOpponentEncryptedCodes[this]!! private fun String.toMyShape(): Shape = shapeByMyEncryptedCodes[this]!! private fun String.toIndicatedOutcome(): Outcome = indicatedOutcomeByEncryptedCodes[this]!!
0
Kotlin
0
0
5102fab140d7194bc73701a6090702f2d46da5b4
3,988
advent-of-code-2022
Apache License 2.0