path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/dev/claudio/adventofcode2022/Day7Part2.kt | ClaudioConsolmagno | 572,915,041 | false | {"Kotlin": 41573} | package dev.claudio.adventofcode2022
fun main() {
Day7().main()
}
private class Day7 {
fun main() {
val input = Support.readFileAsListString("2022/day7-input.txt")
val tree : Directory = buildTree(input)
val sumedVal: Long = calcResult(tree)
println(sumedVal)
}
private fun calcResult(tree: Directory): Long {
var result: Long = 0
val maxSize = 100000L
tree.dirs.forEach{
val calcSize = it.calcSize()
if (calcSize <= maxSize) result += calcSize
result += it.dirs.sumOf { innerDir -> calcResult(innerDir) }
}
val calcSize = tree.calcSize()
if (calcSize <= maxSize) result += calcSize
return result
}
private fun buildTree(input: List<String>): Directory {
var curDir = Directory("/", null)
val root: Directory = curDir
input
.drop(1)
.map { it.split(" ") }
.forEach{
if (it[0] == "$" && it[1] == "cd") {
// change dir
curDir = if (it[2] == "..") {
curDir.parentDir!!
} else {
curDir.dirs.find { node -> node.name == it[2] } as Directory
}
} else if (it[0] == "$" && it[1] == "ls") {
// list dir
} else {
val newNode: Node
if (it[0].startsWith("dir")) {
newNode = Directory(it[1], curDir)
curDir.dirs.add(newNode)
} else {
newNode = File(it[1], it[0].toLong())
curDir.files.add(newNode)
}
}
}
println(root)
return root
}
abstract class Node (val name: String) {
abstract fun calcSize() : Long
}
data class File(val fileName: String, val fileSize: Long) : Node(fileName) {
override fun calcSize(): Long {
return fileSize
}
}
data class Directory(
val dirName: String,
val parentDir: Directory?,
val dirs: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf(),
) : Node(dirName) {
override fun calcSize(): Long {
return dirs.sumOf { it.calcSize() } + files.sumOf { it.calcSize() }
}
override fun toString(): String {
return "Directory(dirName='$dirName', parentDir=${parentDir?.name}, directories=$dirs, files=$files)"
}
}
} | 0 | Kotlin | 0 | 0 | 43e3f1395073f579137441f41cd5a63316aa0df8 | 2,641 | adventofcode-2022 | Apache License 2.0 |
src/Day05.kt | k3vonk | 573,555,443 | false | {"Kotlin": 17347} | import java.util.LinkedList
fun main() {
fun createStacks(crates: List<String>): List<LinkedList<Char>> {
val stacks: List<LinkedList<Char>> = List(9) { LinkedList<Char>() }
for (crate in crates) {
val arr = crate.toCharArray()
for (i in arr.indices) {
if (arr[i].isLetter()) {
stacks[(i-1)/4].add(arr[i])
}
}
}
return stacks
}
fun topOfEachStack(stacks: List<LinkedList<Char>>) =
stacks.map { it.peek() }.joinToString(separator = "")
fun part1(stacks: List<LinkedList<Char>>, from: Int, to: Int, numberOfCrates: Int) {
for(i in 0 until numberOfCrates) {
val item = stacks[from - 1].pop()
stacks[to - 1].push(item)
}
}
fun part2(stacks: List<LinkedList<Char>>, from: Int, to: Int, numberOfCrates: Int) {
val tempStack = LinkedList<Char>()
for(i in 0 until numberOfCrates) {
val itemInStack2 = stacks[from - 1].pop()
tempStack.add(itemInStack2)
}
stacks[to - 1].addAll(0, tempStack)
}
val data = readInput("Day05_test")
val crates = data.take(8)
val stacksPart1 = createStacks(crates)
val stacksPart2 = createStacks(crates)
val moves = data.takeLast(data.size - 10) // I like magic numbers
for (move in moves) {
val pattern = "[0-9]+".toRegex()
val digits = pattern.findAll(move).map { it.value.toInt() }.toList()
val numberOfCrates = digits.first()
val ( from, to ) = digits.takeLast(2)
part1(stacksPart1, from, to, numberOfCrates)
part2(stacksPart2, from, to, numberOfCrates)
}
println(topOfEachStack(stacksPart1))
println(topOfEachStack(stacksPart2))
}
| 0 | Kotlin | 0 | 1 | 68a42c5b8d67442524b40c0ce2e132898683da61 | 1,803 | AOC-2022-in-Kotlin | Apache License 2.0 |
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day20/DonutMaze.kt | jrhenderson1988 | 289,786,400 | false | {"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37} | package com.github.jrhenderson1988.adventofcode2019.day20
import com.github.jrhenderson1988.adventofcode2019.common.Direction
import com.github.jrhenderson1988.adventofcode2019.common.bfs
class DonutMaze(
private val map: Map<Pair<Int, Int>, Cell>,
private val innerPortals: Map<Pair<Int, Int>, Pair<Int, Int>>,
private val outerPortals: Map<Pair<Int, Int>, Pair<Int, Int>>,
private val start: Pair<Int, Int>,
private val end: Pair<Int, Int>
) {
private val maxRecursionDepth = 100
fun calculateDistanceOfShortestPath(): Int {
val pathPoints = map.filter { it.value == Cell.PATH }.keys
val path = bfs(start, end) { point ->
val neighbours = Direction.neighboursOf(point).filter { pathPoints.contains(point) }.toMutableSet()
if (point in innerPortals.keys) {
neighbours.add(innerPortals[point] ?: error("Should not happen"))
} else if (point in outerPortals.keys) {
neighbours.add(outerPortals[point] ?: error("Should not happen"))
}
neighbours
}
return path!!.size - 1
}
fun calculateDistanceOfShortestRecursivePath(): Int? {
val start = Triple(this.start.first, this.start.second, 0)
val end = Triple(this.end.first, this.end.second, 0)
val pathPoints = map.filter { it.value == Cell.PATH }.keys
val shortestPath = bfs(start, end, { point ->
val pointAsPair = Pair(point.first, point.second)
val neighbours = Direction.neighboursOf(pointAsPair)
.filter { pathPoints.contains(it) }
.map { Triple(it.first, it.second, point.third) }
.toMutableSet()
if (pointAsPair in innerPortals.keys) {
val target = innerPortals[pointAsPair] ?: error("Should not happen")
if (point.third + 1 < maxRecursionDepth) {
neighbours.add(Triple(target.first, target.second, point.third + 1))
}
} else if (pointAsPair in outerPortals.keys && point.third > 0) {
val target = outerPortals[pointAsPair] ?: error("Should not happen")
neighbours.add(Triple(target.first, target.second, point.third - 1))
}
neighbours
})
// At level 0, there are no outer portals (only inner portals), AA and ZZ are the only outer points
// At level 1+ AA and ZZ do not exist but all portals exist
// Walking onto an inner portal transports 1 level deeper (level + 1) and walking onto an outer portal
// transports 1 level back up
// The map is the same layout otherwise
return if (shortestPath == null) null else shortestPath.size - 1
}
private fun render(path: Set<Pair<Int, Int>>): String {
val maxX = map.keys.map { it.first }.max()!!
val maxY = map.keys.map { it.second }.max()!!
return " " + (0..maxX).joinToString("") { (it % 10).toString() } + (0..maxY).joinToString("\n") { y ->
(y % 10).toString() + (0..maxX).joinToString("") { x ->
when {
Pair(x, y) in path -> "+"
Pair(x, y) == start -> "@"
Pair(x, y) == end -> "X"
Pair(x, y) in innerPortals.keys -> "*"
Pair(x, y) in outerPortals.keys -> "*"
map[Pair(x, y)] == Cell.PATH -> "."
map[Pair(x, y)] == Cell.WALL -> "#"
else -> " "
}
}
}
}
enum class Cell {
PATH,
WALL;
companion object {
fun parse(ch: Char) = when (ch) {
'.' -> PATH
'#' -> WALL
else -> error("Invalid cell character [$ch].")
}
}
}
companion object {
fun parse(input: String): DonutMaze {
val grid = mutableMapOf<Pair<Int, Int>, Char>()
input.lines().forEachIndexed { y, line ->
line.mapIndexed { x, ch ->
grid[Pair(x, y)] = ch
}
}
val map = grid.filterValues { it in setOf('.', '#') }.mapValues { Cell.parse(it.value) }
val labels = extractLabels(grid)
val start = (labels["AA"] ?: error("No start point defined")).first()
val end = (labels["ZZ"] ?: error("No end point defined")).first()
val mazeOnly = grid.filterValues { it in setOf('.', '#') }.keys
val topLeft = Pair(mazeOnly.map { it.first }.min()!!, mazeOnly.map { it.second }.min()!!)
val bottomRight = Pair(mazeOnly.map { it.first }.max()!!, mazeOnly.map { it.second }.max()!!)
val outerPortals = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
val innerPortals = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
labels.filterKeys { it !in listOf("AA", "ZZ") }.values.forEach {
if (it.size != 2) {
error("Expected exactly 2 portal coordinates, ${it.size} received.")
}
val a = it.first()
val b = it.last()
if (isOuter(a, topLeft, bottomRight)) {
outerPortals[a] = b
innerPortals[b] = a
} else {
outerPortals[b] = a
innerPortals[a] = b
}
}
return DonutMaze(map, innerPortals, outerPortals, start, end)
}
private fun isOuter(point: Pair<Int, Int>, topLeft: Pair<Int, Int>, bottomRight: Pair<Int, Int>) =
point.first in setOf(topLeft.first, bottomRight.first) || point.second in setOf(topLeft.second, bottomRight.second)
private fun extractLabels(grid: Map<Pair<Int, Int>, Char>): Map<String, Set<Pair<Int, Int>>> {
val labels = mutableMapOf<String, Set<Pair<Int, Int>>>()
grid.filter { it.value.isLetter() }
.forEach { (point, _) ->
val neighbours = Direction.neighboursOf(point).filter {
grid.containsKey(it) && grid[it]?.isLetter() ?: false
}
val points = listOf(listOf(point), neighbours)
.flatten()
.sortedWith(compareBy({ it.first }, { it.second }))
val label = points.map { grid[it] }.joinToString("")
val isHorizontal = points.map { it.second }.distinct().size == 1
val targetPoint = points
.mapIndexed { i, pt ->
Pair(
pt.first + when {
isHorizontal && i == 0 -> -1
isHorizontal && i != 0 -> 1
else -> 0
},
pt.second + when {
!isHorizontal && i == 0 -> -1
!isHorizontal && i != 0 -> 1
else -> 0
}
)
}.first { grid[it] == '.' }
val existing = (labels[label] ?: emptySet()).toMutableSet()
existing.add(targetPoint)
labels[label] = existing
}
return labels
}
}
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 7,541 | advent-of-code | Apache License 2.0 |
src/Day05.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | fun main() {
class Crates(input: List<String>) {
private val data: MutableList<MutableList<Char>>
init {
val columns = input.last().length / 4 + 1
data = MutableList(columns) { mutableListOf() }
for (line in input.dropLast(1).reversed()) {
var column = 0
for (index in 1 until line.length step 4) {
if (line[index] != ' ')
data[column].add(line[index])
column += 1
}
}
}
fun move(count: Int, from: Int, to: Int) {
repeat(count) {
val tmp = data[from].removeLast()
data[to].add(tmp)
}
}
fun moveSameOrder(count: Int, from: Int, to: Int) {
val tmpList = data[from].takeLast(count)
data[from] = data[from].dropLast(count).toMutableList()
data[to] = (data[to] + tmpList).toMutableList()
}
fun getTopElements(): String = data.joinToString(separator = "") { it.last().toString() }
}
fun part1(input: List<String>): String {
val splitPosition = input.indexOf("")
val crates = Crates(input.take(splitPosition))
val moves = input.drop(splitPosition + 1)
for (line in moves) {
val regex = """move ([0-9]+) from ([0-9]+) to ([0-9]+)""".toRegex()
val matchResult = regex.find(line)
val (count, from, to) = matchResult!!.destructured
crates.move(count.toInt(), from.toInt() - 1, to.toInt() - 1)
}
return crates.getTopElements()
}
fun part2(input: List<String>): String {
val splitPosition = input.indexOf("")
val crates = Crates(input.take(splitPosition))
val moves = input.drop(splitPosition + 1)
for (line in moves) {
val regex = """move ([0-9]+) from ([0-9]+) to ([0-9]+)""".toRegex()
val matchResult = regex.find(line)
val (count, from, to) = matchResult!!.destructured
crates.moveSameOrder(count.toInt(), from.toInt() - 1, to.toInt() - 1)
}
return crates.getTopElements()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 2,488 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/g1201_1300/s1293_shortest_path_in_a_grid_with_obstacles_elimination/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1201_1300.s1293_shortest_path_in_a_grid_with_obstacles_elimination
// #Hard #Array #Breadth_First_Search #Matrix
// #2023_06_08_Time_189_ms_(100.00%)_Space_36.6_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
fun shortestPath(grid: Array<IntArray>, k: Int): Int {
if (grid.size == 1 && grid[0].size == 1 && grid[0][0] == 0) {
return 0
}
// 4 potential moves:
val moves = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1))
val m = grid.size
val n = grid[0].size
// use obs to record the min total obstacles when traverse to the position
val obs = Array(m) { IntArray(n) }
for (i in 0 until m) {
for (j in 0 until n) {
obs[i][j] = Int.MAX_VALUE
}
}
obs[0][0] = 0
// Queue to record {x cord, y cord, total obstacles when trvavers to this position}
val que: Queue<IntArray> = LinkedList()
que.add(intArrayOf(0, 0, 0))
var level = 0
while (que.isNotEmpty()) {
val size = que.size
level++
for (i in 0 until size) {
val current = que.poll()
for (move in moves) {
val next = intArrayOf(current[0] + move[0], current[1] + move[1])
if (next[0] == m - 1 && next[1] == n - 1) {
return level
}
if (next[0] < 0 || next[0] > m - 1 || next[1] < 0 || next[1] > n - 1) {
continue
}
if (current[2] + grid[next[0]][next[1]] < obs[next[0]][next[1]] &&
current[2] + grid[next[0]][next[1]] <= k
) {
obs[next[0]][next[1]] = current[2] + grid[next[0]][next[1]]
que.add(intArrayOf(next[0], next[1], obs[next[0]][next[1]]))
}
}
}
}
return -1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,075 | LeetCode-in-Kotlin | MIT License |
project/src/problems/Initial.kt | informramiz | 173,284,942 | false | null | package problems
object Initial {
//val minDiff = minAbsoluteDifference(arrayOf(-2, -3, -4, -1).toIntArray())
// val minDiff = minAbsoluteDifference(arrayOf(1,1).toIntArray())
// val minDiff = minAbsoluteDifference(arrayOf(3, 1, 2, 4, 3).toIntArray())
// val minDiff = minAbsoluteDifference(arrayOf(-1000, 1000).toIntArray())
fun minAbsoluteDifference(A: IntArray): Int {
val totalSum = A.sum()
println("totalSum: $totalSum")
//calculate for p=1 -> p-1=0
var minDiff = calculateAbsDiff(A[0], totalSum)
var sum = A[0]
for (p in 2 until A.size) {
//partition at point p so ranges:[0,p-1], [p, n-1]
sum += A[p - 1]
val absDiff = calculateAbsDiff(sum, totalSum)
if (absDiff < minDiff) {
minDiff = absDiff
}
}
return minDiff
}
private fun calculateAbsDiff(
forwardSum: Int,
totalSum: Int
): Int {
val p1Sum = forwardSum
val p2Sum = totalSum - p1Sum
val absDiff = Math.abs(p1Sum - p2Sum)
println("(p1Sum, p2Sum, absDiff) = ($p1Sum, $p2Sum, $absDiff)")
return absDiff
}
fun missingPermutation(A: IntArray): Int {
//given sequence will be: 1, 2, 3, 4 ... N+1
//last element in sequence
val N = A.size + 1L
val An = N
val A1 = 1L
val expectedSumOfSequence = N * (A1 + An) / 2
val actualSum = A.sum()
val missingElement = expectedSumOfSequence - actualSum
return missingElement.toInt()
}
fun countJumps1(X: Int, Y: Int, D: Int): Int {
return Math.ceil(((Y - X) / D.toDouble())).toInt()
}
fun total1(n: Int) {
val result = n * (n + 1) / 2
println("total: $result")
}
fun countOddElement(A: IntArray): Int {
var a = 0
A.forEach { a = a xor it }
return a
}
fun rotateArray(A: Array<Int>, K: Int) {
if (A.isEmpty()) return
val n = A.size
for (i in 0 until K) {
val end = A[n - 1]
for (j in n - 1 downTo 1) {
A[j] = A[j - 1]
}
A[0] = end
}
}
fun reverseArray(array: Array<Int>) {
val n = array.size
for (i in 0 until n / 2) {
val end = (n - 1) - i
val start = array[i]
array[i] = array[end]
array[end] = start
}
}
//given a positive integer N, returns the length of its longest binary gap.
// The function should return 0 if N doesn't contain a binary gap.
private fun maximumBinaryGap(N: Int): Int {
var maximumGap = 0
var quotient = N
var remainder: Int
var continuousZeroCount = 0
var isOneEncountered = false
while (quotient > 0) {
remainder = quotient % 2
quotient /= 2
if (remainder == 1) {
isOneEncountered = true
}
if (isOneEncountered) {
if (remainder == 0) {
continuousZeroCount++
} else {
if (continuousZeroCount > maximumGap) {
maximumGap = continuousZeroCount
}
continuousZeroCount = 0
}
}
}
return maximumGap
}
private fun printFibonacci(n: Int) {
var secondLast = 0
var last = 1
print("$secondLast, $last")
while (last <= n) {
val newLast = last + secondLast
print(",$newLast")
secondLast = last
last = newLast
}
}
private fun printSymmetricTriangle() {
val n = 3
for (i in n downTo 1) {
for (j in 1..n - i) {
print(" ")
}
for (k in 1..(2 * i - 1)) {
print("*")
}
println()
}
}
} | 0 | Kotlin | 0 | 0 | a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4 | 4,003 | codility-challenges-practice | Apache License 2.0 |
src/Day25.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import java.lang.StringBuilder
import kotlin.math.pow
import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): SNAFU {
return input.sumOf { SNAFU(it).toLong() }.toSNAFU()
}
val decimalSnafuPairs =
mapOf(
1 to "1",
2 to "2",
3 to "1=",
4 to "1-",
5 to "10",
6 to "11",
7 to "12",
8 to "2=",
9 to "2-",
10 to "20",
15 to "1=0",
20 to "1-0",
2022 to "1=11-2",
12345 to "1-0---0",
314159265 to "1121-1110-1=0",
)
// test snafu to decimal and decimal to snafu conversion
for (decimalSnafuPair in decimalSnafuPairs) {
val decimal = decimalSnafuPair.key.toLong()
val snafu = SNAFU(decimalSnafuPair.value)
assertEquals(decimal, snafu.toLong())
assertEquals(snafu, decimal.toSNAFU())
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
assertEquals(SNAFU("2=-1=0"), part1(testInput))
val input = readInput("Day25")
println(part1(input))
}
data class SNAFU(val value: String) {
fun toLong(): Long {
return value
.reversed()
.mapIndexed { index, c ->
5.0.pow(index).toLong() *
when (c) {
'=' -> -2
'-' -> -1
'0' -> 0
'1' -> 1
'2' -> 2
else -> error("unknown SNAFU digit '$c', should not happen")
}
}
.sum()
}
override fun toString() = value
}
fun Long.toSNAFU(): SNAFU {
val snafuValue = StringBuilder()
var quotient = this
var carry = 0
while (quotient != 0L) {
val remainder = quotient.mod(5)
when (remainder + carry) {
0 -> {
snafuValue.insert(0, "0")
carry = 0
}
1 -> {
snafuValue.insert(0, "1")
carry = 0
}
2 -> {
snafuValue.insert(0, "2")
carry = 0
}
3 -> {
snafuValue.insert(0, "=")
carry = 1
}
4 -> {
snafuValue.insert(0, "-")
carry = 1
}
5 -> {
snafuValue.insert(0, "0")
carry = 1
}
}
quotient /= 5
}
if (carry != 0) {
snafuValue.insert(0, carry)
}
return SNAFU(snafuValue.toString())
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 2,356 | aoc2022 | Apache License 2.0 |
2021/src/main/kotlin/Day05.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | import kotlin.math.sign
class Day05(private val input: List<String>) {
private fun List<String>.prepareInput(): List<List<Int>> = this.map {
"(\\d+),(\\d+) -> (\\d+),(\\d+)".toRegex().matchEntire(it)!!.destructured.toList().map { it.toInt() }
}
private fun countMatrix(input: List<List<Int>>, matrix: Array<IntArray>, includeDiagonal: Boolean): Int {
input.forEach {
var (x1, y1) = arrayOf(it[0], it[1])
var (x2, y2) = arrayOf(it[2], it[3])
if (includeDiagonal || x1 == x2 || y1 == y2) {
val dx = (x2 - x1).sign
val dy = (y2 - y1).sign
matrix[y2][x2]++
while (x1 != x2 || y1 != y2) {
matrix[y1][x1]++
x1 += dx
y1 += dy
}
}
}
return matrix.sumOf { it.count { it > 1 } }
}
private fun createMatrix(input: List<List<Int>>): Array<IntArray> {
val matrix = Array(input.maxOf { maxOf(it[1], it[3]) } + 1) {
IntArray(input.maxOf { maxOf(it[0], it[2]) } + 1)
}
return matrix
}
fun solve1(): Int {
return countMatrix(input.prepareInput(), createMatrix(input.prepareInput()), false)
}
fun solve2(): Int {
return countMatrix(input.prepareInput(), createMatrix(input.prepareInput()), true)
}
}
| 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 1,400 | adventofcode-2021-2025 | MIT License |
src/aoc2021/Day08.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2021
import readInput
fun main() {
val (year, day) = "2021" to "Day08"
fun part1(input: List<String>) = input.map {
it.split(" | ").last()
}.flatMap {
it.split(" ")
}.count {
it.length in listOf(2, 3, 4, 7)
}
fun part2(input: List<String>) = input.sumOf { line ->
val (before, after) = line.split(" | ").map {
it.split(" ").map { words -> words.toSet() }
}
val sizes = before.groupBy { it.size }
val number = Array(10) { setOf<Char>() }
number[1] = sizes[2]!!.first()
number[4] = sizes[4]!!.first()
number[7] = sizes[3]!!.first()
number[8] = sizes[7]!!.first()
number[6] = sizes[6]!!.first { number[8] == number[1] + it }
number[5] = sizes[5]!!.first { number[8] != number[6] + it }
number[2] = sizes[5]!!.first { number[8] == number[5] + it }
number[9] = sizes[6]!!.first { number[8] != number[4] + it }
number[0] = sizes[6]!!.first { number[8] == number[5] + it }
number[3] = sizes[5]!!.first { it !in number }
after.map { number.indexOf(it) }.joinToString("").toInt()
}
val testInput = readInput(name = "${day}_test", year = year)
val input = readInput(name = day, year = year)
check(part1(testInput) == 26)
println(part1(input))
check(part2(testInput) == 61229)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,415 | aoc-kotlin | Apache License 2.0 |
2023/src/main/kotlin/Day18.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day18 {
private enum class Direction { UP, DOWN, LEFT, RIGHT }
private data class Dig(val direction: Direction, val number: Long)
private sealed class Line {
data class Vertical(val x: Long, val yRange: LongRange) : Line()
data class Horizontal(val y: Long, val xRange: LongRange) : Line()
}
private data class Pos(val x: Long, val y: Long)
fun part1(input: String) = dig(parsePartOne(input))
fun part2(input: String) = dig(parsePartTwo(input))
private fun dig(plan: List<Dig>): Long {
val lines = mutableListOf<Line>()
var minY = 0L
var maxY = 0L
var minX = 0L
var maxX = 0L
// Find all vertical lines & the bounds
var curr = Pos(0, 0)
plan.forEach { dig ->
val next = curr.move(dig.direction, dig.number)
when (dig.direction) {
Direction.UP -> {
lines.add(Line.Vertical(curr.x, next.y..curr.y))
if (next.y < minY) {
minY = next.y
}
}
Direction.DOWN -> {
lines.add(Line.Vertical(curr.x, curr.y..next.y))
if (next.y > maxY) {
maxY = next.y
}
}
Direction.LEFT -> {
lines.add(Line.Horizontal(curr.y, next.x..curr.x))
if (next.x < minX) {
minX = next.x
}
}
Direction.RIGHT -> {
lines.add(Line.Horizontal(curr.y, curr.x..next.x))
if (next.x > maxX) {
maxX = next.x
}
}
}
curr = next
}
check(curr == Pos(0, 0)) { "Dig plan must end at start" }
lines.sortBy {
when (it) {
is Line.Vertical -> it.x.toDouble()
is Line.Horizontal -> it.xRange.first + ((it.xRange.last - it.xRange.first) / 2.0) // Make sure horizontal lines are between vertical lines
}
}
val horizontalLines = lines.filterIsInstance<Line.Horizontal>().sortedBy { it.y }.map { it.y }
var total = 0L
var y = minY + 1
while (y < maxY) {
val filtered = lines.filter {
when (it) {
is Line.Vertical -> y in it.yRange
is Line.Horizontal -> y == it.y
}
}
// Add up inside points (paying attention to corners)
var amount = 0L
var inside = false
filtered.zipWithNext().forEach { (l1, l2) ->
if ((l1 is Line.Horizontal && l2 is Line.Vertical && l1.y == l2.yRange.last)
|| (l1 is Line.Vertical && l2 is Line.Horizontal && l2.y == l1.yRange.last)
) {
inside = !inside
} else if (l1 is Line.Vertical && l2 is Line.Vertical) {
if (y != l1.yRange.first && y != l1.yRange.last) {
inside = !inside
}
if (inside) {
amount += l2.x - l1.x - 1
}
}
}
// Skip ahead to the next different row
if (filtered.firstOrNull { it is Line.Horizontal } != null) {
total += amount
y++
} else {
val nextY = horizontalLines.first { it > y }
val diff = nextY - y
total += amount * diff
y = nextY
}
}
val edges = lines.sumOf {
when (it) {
is Line.Horizontal -> it.xRange.last - it.xRange.first
is Line.Vertical -> it.yRange.last - it.yRange.first
}
}
return total + edges
}
private fun Pos.move(direction: Direction, amount: Long) = when (direction) {
Direction.UP -> copy(y = y - amount)
Direction.DOWN -> copy(y = y + amount)
Direction.LEFT -> copy(x = x - amount)
Direction.RIGHT -> copy(x = x + amount)
}
private fun parsePartOne(input: String): List<Dig> {
val regex = Regex("([UDLR]) (\\d+) \\((#\\w{6})\\)")
return input.splitNewlines().map {
val result = regex.matchEntire(it)!!
Dig(
direction = when (val dir = result.groupValues[1]) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> throw IllegalStateException("Unrecognized direction: $dir")
},
number = result.groupValues[2].toLong(),
)
}
}
private fun parsePartTwo(input: String): List<Dig> {
val regex = Regex("[UDLR] \\d+ \\(#(\\w{5})([0-3])\\)")
return input.splitNewlines().map {
val result = regex.matchEntire(it)!!
Dig(
direction = when (val dir = result.groupValues[2]) {
"0" -> Direction.RIGHT
"1" -> Direction.DOWN
"2" -> Direction.LEFT
"3" -> Direction.UP
else -> throw IllegalStateException("Unrecognized direction: $dir")
},
number = result.groupValues[1].toLong(radix = 16),
)
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 4,677 | advent-of-code | MIT License |
src/Day07.kt | jalex19100 | 574,686,993 | false | {"Kotlin": 19795} | import com.sun.org.apache.xpath.internal.operations.Bool
class Node(name: String, parent: Node?) {
val name = name
val parent = parent
val children: MutableList<Node> = mutableListOf()
var size: Int = 0
fun addChild(child: Node): Boolean {
val existingChild = getChild(child.name) ?: return children.add(child)
return false
}
fun getChild(name: String): Node? {
return children.find {
it.name == name
}
}
fun getRoot(): Node? {
return parent?.getRoot() ?: this
}
fun findDir(criteria: (Int) -> Boolean): List<String> {
val results: MutableList<String> = mutableListOf()
if (this.size == 0) {
val recursiveSize = this.getRecursizeSize()
if (criteria(recursiveSize)) {
results.add("${this.name}:$recursiveSize")
// println("${this.name}: $recursiveSize")
}
this.getRecursizeSize()
} else {
0
}
children.forEach { child ->
if (child.size == 0) results.addAll(child.findDir(criteria))
}
return results
}
fun getRecursizeSize(): Int {
var recursizeSize = size
children.forEach { child ->
recursizeSize += child.getRecursizeSize()
}
return recursizeSize
}
override fun equals(other: Any?): Boolean {
return (other is Node && other.name == this.name)
}
override fun toString(): String {
val sb = StringBuilder()
if (this.parent != null) sb.append("${this.parent.name} -> ")
sb.append("${this.name}\n")
this.children.forEach { child ->
sb.append(" ${child.toString()}")
}
return sb.toString()
}
}
fun changeDirectory(currentNode: Node, newDirectory: String): Node {
return when (newDirectory) {
"/" -> currentNode.getRoot() ?: currentNode
".." -> currentNode?.parent ?: currentNode
else -> {
val existingChild = currentNode.getChild(newDirectory)
if (existingChild == null) {
val newChild = Node(newDirectory, currentNode)
currentNode.children.add(newChild)
newChild
} else existingChild
}
}
}
fun populateTree(input: List<String>): Node {
val rootNode = Node("/", null)
var currentNode = rootNode
input.forEach { line ->
val splits = line.split(' ')
if (line.startsWith("$ ")) {
if (line.startsWith("$ cd")) {
currentNode = changeDirectory(currentNode, splits[2])
}
} else {
val newChild = Node(splits[1], currentNode)
if (!line.startsWith("dir ")) newChild.size = splits[0].toInt()
currentNode.addChild(newChild)
}
}
return rootNode
}
fun main() {
fun part1(input: List<String>): Int {
val rootNode = populateTree(input)
var sum = 0
rootNode.findDir { x -> x in 1..100000 }.forEach {
val value = it.split(':')[1].toInt()
sum += value
}
return sum
}
fun part2(input: List<String>): Int {
val rootNode = populateTree(input)
var result = Int.MAX_VALUE
rootNode.findDir { x -> x >= 8381165 }.forEach {
val value = it.split(':')[1].toInt()
result = result.coerceAtMost(value)
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
println("Part 2: ${part2(testInput)}")
println("Part 1: ${part1(testInput)}")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | a50639447a2ef3f6fc9548f0d89cc643266c1b74 | 3,888 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/Day07.kt | lifeofchrome | 574,709,665 | false | {"Kotlin": 19233} | package main
import readInput
fun main() {
val input = readInput("Day07")
val day7 = Day07(input)
print("Part 1: ${day7.part1()}\n")
print("Part 2: ${day7.part2()}")
}
class Day07(input: List<String>) {
private val root = Node("/", false, 0, mutableListOf())
private var path = ArrayDeque<Node>()
init {
path.addLast(root)
for(line in input.drop(1)) {
if(line[0] == '$') {
val rawCmd = line.drop(2).split(" ")
val cmd = rawCmd[0]
val args = if(rawCmd[0] == "ls") "" else rawCmd[1]
when(cmd) {
"ls" -> continue
"cd" -> if(args != "..") {
path.addLast(path.last().children.find { it.name == args } ?: error("[\$ cd $args]: Can't find directory $args"))
} else {
path.removeLast()
}
else -> error("Invalid command: $cmd")
}
} else { // reading files from ls
path.last().children.add(fileToNode(line))
}
}
}
private fun fileToNode(file: String) =
if(file[0] == 'd') Node(file.drop(4), false, 0, mutableListOf())
else Node(file.split(" ")[1], true, file.split(" ")[0].toInt(), mutableListOf())
private fun calculateSize(node: Node): Int {
return if(node.children.size == 0) {
node.size
} else {
var total = 0
node.children.forEach { total += calculateSize(it) }
total
}
}
private fun getAllDirs(node: Node): List<Node> {
return if(node.children.size == 0) {
if(!node.isFile) listOf(node) else listOf()
} else {
val dirs = mutableListOf<Node>()
if(!node.isFile) {
dirs.add(node)
}
node.children.forEach {
dirs.addAll(getAllDirs(it)) }
dirs.toList()
return dirs
}
}
fun part1(): Int {
var total = 0
for(dir in getAllDirs(root)) {
val size = calculateSize(dir)
if(size <= 100000) {
total += size
}
}
return total
}
fun part2(): Int {
val needed = 30000000 - (70000000 - calculateSize(root)) // needed: 3M - free space: (7M - used space)
var smallest = Int.MAX_VALUE
for(dir in getAllDirs(root)) {
val size = calculateSize(dir)
if(size in needed until smallest) {
smallest = size
}
}
return smallest
}
}
class Node(var name: String, var isFile: Boolean, var size: Int, var children: MutableList<Node>)
| 0 | Kotlin | 0 | 0 | 6c50ea2ed47ec6e4ff8f6f65690b261a37c00f1e | 2,777 | aoc2022 | Apache License 2.0 |
code/day_05/src/jvm8Main/kotlin/common.kt | dhakehurst | 725,945,024 | false | {"Kotlin": 105846} | package day_05
class Range(
val start: Long,
val length: Long
) : Iterable<Long> {
val max = start + length
var limit = length
override fun iterator(): Iterator<Long> = object : AbstractIterator<Long>() {
var i = 0
override fun computeNext() {
when {
i >= length -> done()
else -> {
setNext(start + i)
i++
}
}
}
}
fun limitTo(maxSeedNum: Long) {
limit = kotlin.math.min(length, maxSeedNum - start)
}
override fun toString(): String = "[$start-${start + length}]"
}
data class Mapper(
val name: String
) {
val ranges = mutableListOf<RangeMap>()
lateinit var filtered: List<RangeMap>
fun map(inp: Long): Long =
ranges.firstNotNullOfOrNull { it.mapOrNull(inp) } ?: inp
fun filteredMap(inp: Long): Long =
filtered.firstNotNullOfOrNull { it.mapOrNull(inp) } ?: inp
val srcForMinDstMax by lazy {
ranges.sortedBy { it.dstMax }.first().src
}
val filteredSrcForMinDstMax by lazy {
filtered.minBy { it.dstMax }.src
}
fun filterToRangesWithDstLessThan(dstMax: Long) {
println("Mapper '$name' limited to dst $dstMax")
filtered = ranges.filter {
it.dstMax <= dstMax
}
}
fun mapRanges(inp: List<LongRange>): List<LongRange> {
val unmapped = inp.toMutableList()
val mapped = mutableListOf<LongRange>()
while (unmapped.isNotEmpty()) {
val toMap = unmapped.removeFirst()
val rng = ranges.firstOrNull { toMap.intersect(it.srcRange) != null }
when (rng) {
null -> mapped.add(toMap) //direct maping
else -> {
val i = toMap.intersect(rng.srcRange)!!
mapped.add(rng.mapRange(i.covered))
i.before?.let { unmapped.add(it) }
i.after?.let { unmapped.add(it) }
}
}
}
return mapped
}
}
data class LongRangeIntersection(
val before: LongRange?,
val covered: LongRange,
val after: LongRange?
)
fun LongRange.isSubsetOf(other: LongRange) = this.first >= other.first && this.last <= other.last
fun LongRange.intersect(other: LongRange) = when {
this.last > other.first && this.first < other.last -> LongRangeIntersection(
before = when {
this.first < other.first -> LongRange(this.start, other.start - 1)
else -> null
},
covered = LongRange(kotlin.math.max(this.first, other.first), kotlin.math.min(this.last, other.last)),
after = when {
this.last > other.last -> LongRange(other.last + 1, this.last)
else -> null
}
)
else -> null
}
data class RangeMap(
val dst: Long,
val src: Long,
val rng: Long
) {
val srcRange = LongRange(src, src + rng - 1)
val dstRange = LongRange(dst, dst + rng - 1)
val srcMax get() = src + (rng - 1)
val dstMax get() = dst + (rng - 1)
fun mapOrNull(inp: Long): Long? =
when {
inp in src..srcMax -> dst + (inp - src)
else -> null
}
fun mapRange(inp: LongRange): LongRange = when {
inp.first >= src && inp.last <= srcMax -> LongRange(mapOrNull(inp.first)!!, mapOrNull(inp.last)!!)
else -> error("Input out of range")
}
override fun toString(): String = "Range [$src-${src + rng}] ==> [$dst-${dst + rng}]"
}
| 0 | Kotlin | 0 | 0 | be416bd89ac375d49649e7fce68c074f8c4e912e | 3,551 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/staricka/adventofcode2022/Day16.kt | mathstar | 569,952,400 | false | {"Kotlin": 77567} | package com.staricka.adventofcode2022
import kotlin.math.max
class Day16 : Day {
override val id = 16
data class Valve(val id: String, val flowRate: Int)
private val regex = Regex("""Valve ([A-Z]+) has flow rate=([0-9]+); tunnels? leads? to valves? ([A-Z]+(, [A-Z]+)*)""")
private fun parseInput(input: String): Pair<Map<String, Valve>, Map<String, List<String>>> {
val valves = HashMap<String, Valve>()
val tunnels = HashMap<String, List<String>>()
input.lines().forEach { line ->
val match = regex.matchEntire(line)
val valve = Valve(
match!!.groups[1]!!.value,
match.groups[2]!!.value.toInt()
)
valves[valve.id] = valve
tunnels[valve.id] = match.groups[3]!!.value.split(", ")
}
return Pair(valves, tunnels)
}
/**
* Compute distance to travel from each valve to each other valve
*/
private fun distances(tunnels: Map<String, List<String>>): Map<String, Map<String, Int>> {
var result = HashMap<String, HashMap<String, Int>>()
for ((k, l) in tunnels) {
for (v in l) {
result.computeIfAbsent(k) { HashMap() }[k] = 0
result.computeIfAbsent(k) { HashMap() }[v] = 1
result.computeIfAbsent(v) { HashMap() }[k] = 1
}
}
var changed = true
while (changed) {
val nextResult = result.map { (k, v) -> k to HashMap(v) }.toMap(HashMap())
changed = false
for (k in tunnels.keys) {
for (v in tunnels.keys) {
if (!result[k]!!.containsKey(v)) {
val minConnection = result[k]!!.filter { (intermediate, _) ->
result[intermediate]!!.containsKey(v)
}.map { (intermediate, iCost) ->
iCost + result[intermediate]!![v]!!
}.minOrNull()
if (minConnection != null) {
nextResult[k]!![v] = minConnection
nextResult[v]!![k] = minConnection
changed = true
}
}
}
}
result = nextResult
}
return result
}
private fun maxPressure(
toVisit: List<String>,
valves: Map<String, Valve>,
distances: Map<String, Map<String, Int>>,
location: String,
time: Int,
flowRate: Int,
pressureReleased: Int
) : Int {
if (time > 30) {
return -1
}
var max = pressureReleased + (30 - time) * flowRate
for (v in toVisit) {
max = max(max, maxPressure(
toVisit.filter { j -> j != v },
valves,
distances,
v,
time + distances[location]!![v]!! + 1,
flowRate + valves[v]!!.flowRate,
pressureReleased + flowRate * (distances[location]!![v]!! + 1)
))
}
return max
}
/*
* PART 2 Optimizations Section
*/
// cull redundant paths
private val pathCullingSet = HashSet<String>()
private fun haveNotEncounteredPath(path1: String, path2: String): Boolean =
if (path1 < path2) {
pathCullingSet.add("$path1,$path2")
} else {
pathCullingSet.add("$path2,$path1")
}
// heuristic for whether this path could possibly improve the result
private var globalMax = 0
private fun canImprove(
currentEndValue: Int,
toVisit: List<String>,
valves: Map<String, Valve>,
initialTimeRemaining: Int
) : Boolean {
// assume it takes two minutes to open each valve (i.e. shortest possible path)
var result = currentEndValue
var timeRemaining = initialTimeRemaining
val sortedValves = toVisit.sortedBy { valves[it]!!.flowRate }.toMutableList()
while (sortedValves.size > 0 && timeRemaining > 2) {
timeRemaining -= 2
result += valves[sortedValves.removeLast()]!!.flowRate * timeRemaining
if (sortedValves.size > 0) {
result += valves[sortedValves.removeLast()]!!.flowRate * timeRemaining
}
}
return result > globalMax
}
private fun maxPressureTwoWorkers(
toVisit: List<String>,
valves: Map<String, Valve>,
distances: Map<String, Map<String, Int>>,
location1: String,
worker1Transit: Pair<String, Int>?,
worker1Path: String,
location2: String,
worker2Transit: Pair<String, Int>?,
worker2Path: String,
time: Int,
flowRate: Int,
pressureReleased: Int
) : Int {
if (time > 26) {
return -1
}
var max = pressureReleased + (26 - time) * flowRate
if (worker1Transit != null) {
max += max(0, 26 - worker1Transit.second - time) * valves[worker1Transit.first]!!.flowRate
}
if (worker2Transit != null) {
max += max(0, 26 - worker2Transit.second - time) * valves[worker2Transit.first]!!.flowRate
}
val base = max
if (worker1Transit == null && canImprove(base, toVisit, valves, 26 - time)) {
for (v in toVisit) {
if (haveNotEncounteredPath(worker1Path + v, worker2Path)) {
max = max(
max, maxPressureTwoWorkers(
toVisit.filter { j -> j != v },
valves,
distances,
v,
Pair(v, distances[location1]!![v]!! + 1),
worker1Path + v,
location2,
worker2Transit,
worker2Path,
time,
flowRate,
pressureReleased
)
)
}
}
} else if (worker1Transit != null && (toVisit.isEmpty() || (worker2Transit != null && worker1Transit.second <= worker2Transit.second))) {
max = max(max, maxPressureTwoWorkers(
toVisit,
valves,
distances,
location1,
null,
worker1Path,
location2,
if (worker2Transit != null) Pair(worker2Transit.first, worker2Transit.second - worker1Transit.second) else null,
worker2Path,
time + worker1Transit.second,
flowRate + valves[worker1Transit.first]!!.flowRate,
pressureReleased + flowRate * worker1Transit.second
))
}
if (worker2Transit == null && canImprove(base, toVisit, valves, 26 - time)) {
for (v in toVisit) {
if (haveNotEncounteredPath(worker1Path, worker2Path + v)) {
max = max(
max, maxPressureTwoWorkers(
toVisit.filter { j -> j != v },
valves,
distances,
location1,
worker1Transit,
worker1Path,
v,
Pair(v, distances[location2]!![v]!! + 1),
worker2Path + v,
time,
flowRate,
pressureReleased
)
)
}
}
} else if (worker2Transit != null && (toVisit.isEmpty() || (worker1Transit != null && worker2Transit.second < worker1Transit.second))){
max = max(max, maxPressureTwoWorkers(
toVisit,
valves,
distances,
location1,
if (worker1Transit != null) Pair(worker1Transit.first, worker1Transit.second - worker2Transit.second) else null,
worker1Path,
location2,
null,
worker2Path,
time + worker2Transit.second,
flowRate + valves[worker2Transit.first]!!.flowRate,
pressureReleased + flowRate * worker2Transit.second
))
}
globalMax = max(globalMax, max)
return max
}
override fun part1(input: String): Any {
val (valves, tunnels) = parseInput(input)
val distances = distances(tunnels)
return maxPressure(
valves.filter { (_, v) -> v.flowRate > 0 }.keys.toList(),
valves,
distances,
"AA",
0,
0,
0
)
}
override fun part2(input: String): Any {
val (valves, tunnels) = parseInput(input)
val distances = distances(tunnels)
return maxPressureTwoWorkers(
valves.filter { (_, v) -> v.flowRate > 0 }.keys.toList(),
valves,
distances,
"AA",
null,
"",
"AA",
null,
"",
0,
0,
0
)
}
} | 0 | Kotlin | 0 | 0 | 2fd07f21348a708109d06ea97ae8104eb8ee6a02 | 7,868 | adventOfCode2022 | MIT License |
src/Day05.kt | zuevmaxim | 572,255,617 | false | {"Kotlin": 17901} | private data class State(val stacks: List<MutableList<String>>)
private data class Command(val count: Int, val from: Int, val to: Int)
private fun parseInput(input: List<String>, commands: MutableList<Command>): State {
val stacksCount = (input[0].length + 1) / 4
val stacks = List(stacksCount) { mutableListOf<String>() }
var i = 0
while (i < input.size) {
if (!input[i].contains("[")) break
var lastIndex = 0
while (true) {
val index = input[i].indexOf("[", lastIndex)
if (index == -1) break
val group = index / 4
val value = input[i][index + 1].toString()
stacks[group].add(value)
lastIndex = index + 1
}
i++
}
for (stack in stacks) {
stack.reverse()
}
while (i < input.size) {
if (input[i].startsWith("move ")) {
val fromIndex = input[i].indexOf(" from ")
val toIndex = input[i].indexOf(" to ")
val count = input[i].substring("move ".length, fromIndex).toInt()
val from = input[i].substring(fromIndex + " from ".length, toIndex).toInt() - 1
val to = input[i].substring(toIndex + " to ".length).toInt() - 1
commands.add(Command(count, from, to))
}
i++
}
return State(stacks)
}
private fun part1(input: List<String>): String {
val commands = mutableListOf<Command>()
val state = parseInput(input, commands)
for (command in commands) {
repeat(command.count) {
val last = state.stacks[command.from].removeLast()
state.stacks[command.to].add(last)
}
}
return state.stacks.joinToString("") { it.last() }
}
private fun part2(input: List<String>): String {
val commands = mutableListOf<Command>()
val state = parseInput(input, commands)
for (command in commands) {
val top = MutableList(command.count) { state.stacks[command.from].removeLast() }
state.stacks[command.to].addAll(top.reversed())
}
return state.stacks.joinToString("") { it.last() }
}
fun main() {
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 34356dd1f6e27cc45c8b4f0d9849f89604af0dfd | 2,325 | AOC2022 | Apache License 2.0 |
src/Day10.kt | AndreiShilov | 572,661,317 | false | {"Kotlin": 25181} | import kotlin.math.abs
fun getCommandValue(command: String) = command.split(" ").last().toInt()
fun main() {
fun part1(input: List<String>): Int {
val computer = Computer()
input.forEach { computer.executeCommand(it) }
return computer.result()
}
fun part2(input: List<String>) {
val computer = Computer()
input.forEach { computer.executeCommand(it) }
computer.printCrt()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
class Computer {
private val meaningfulCycles = List(6) { it -> it * 40 + 20 }.toSet()
private var stack = 1
private var cycles = 1
private var results = mutableListOf<Int>()
val crt = Array(6) { Array(40) { '.' } }
fun executeCommand(command: String) {
increase()
if (command != "noop") {
increase()
stack += getCommandValue(command)
}
}
fun result() = results.sum()
fun printCrt() {
crt.forEach { println(it.joinToString("")) }
}
private fun increase() {
val col = (cycles - 1) % 40
val row = (cycles - 1) / 40
if (abs(stack - col) <= 1) crt[row][col] = '#'
if (meaningfulCycles.contains(cycles)) results.add(cycles * stack)
cycles++
}
}
| 0 | Kotlin | 0 | 0 | 852b38ab236ddf0b40a531f7e0cdb402450ffb9a | 1,476 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2022/Day19.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 19 - Not Enough Minerals
* Problem Description: http://adventofcode.com/2022/day/19
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day19/
*/
package com.ginsberg.advent2022
import java.util.PriorityQueue
import kotlin.math.ceil
class Day19(input: List<String>) {
private val blueprints: List<Blueprint> = input.map { Blueprint.of(it) }
fun solvePart1(): Int =
blueprints.sumOf { it.id * calculateGeodesFound(it, 24) }
fun solvePart2(): Int =
blueprints.take(3).map { calculateGeodesFound(it, 32) }.reduce(Int::times)
private fun calculateGeodesFound(blueprint: Blueprint, timeBudget: Int): Int {
var maxGeodes = 0
val queue = PriorityQueue<ProductionState>().apply { add(ProductionState()) }
while(queue.isNotEmpty()){
val state = queue.poll()
if (state.canOutproduceBest(maxGeodes, timeBudget)) {
queue.addAll(state.calculateNextStates(blueprint, timeBudget))
}
maxGeodes = maxOf(maxGeodes, state.geodes)
}
return maxGeodes
}
private data class ProductionState(
val time: Int = 1,
val ore: Int = 1,
val oreRobots: Int = 1,
val clay: Int = 0,
val clayRobots: Int = 0,
val obsidian: Int = 0,
val obsidianRobots: Int = 0,
val geodes: Int = 0,
val geodeRobots: Int = 0
): Comparable<ProductionState> {
override fun compareTo(other: ProductionState): Int = other.geodes.compareTo(geodes)
fun canOutproduceBest(bestSoFar: Int, timeBudget: Int): Boolean {
val timeLeft = timeBudget - time
val potentialProduction = (0 until timeLeft).sumOf { it + geodeRobots }
return geodes + potentialProduction > bestSoFar
}
fun calculateNextStates(blueprint: Blueprint, timeBudget: Int): List<ProductionState> {
val nextStates = mutableListOf<ProductionState>()
if (time < timeBudget) {
if (blueprint.maxOre > oreRobots && ore > 0) {
nextStates += blueprint.oreRobot.scheduleBuild(this)
}
if (blueprint.maxClay > clayRobots && ore > 0) {
nextStates += blueprint.clayRobot.scheduleBuild(this)
}
if (blueprint.maxObsidian > obsidianRobots && ore > 0 && clay > 0) {
nextStates += blueprint.obsidianRobot.scheduleBuild(this)
}
if (ore > 0 && obsidian > 0) {
nextStates += blueprint.geodeRobot.scheduleBuild(this)
}
}
return nextStates.filter { it.time <= timeBudget }
}
}
private data class RobotBlueprint(
val oreRobotsBuilt: Int,
val clayRobotsBuilt: Int,
val obsidianRobotsBuilt: Int,
val geodeRobotsBuilt: Int,
val oreCost: Int,
val clayCost: Int = 0,
val obsidianCost: Int = 0
) {
private fun timeUntilBuild(productionState: ProductionState): Int =
maxOf(
if (oreCost <= productionState.ore) 0 else ceil((oreCost - productionState.ore) / productionState.oreRobots.toFloat()).toInt(),
if (clayCost <= productionState.clay) 0 else ceil((clayCost - productionState.clay) / productionState.clayRobots.toFloat()).toInt(),
if (obsidianCost <= productionState.obsidian) 0 else ceil((obsidianCost - productionState.obsidian) / productionState.obsidianRobots.toFloat()).toInt()
) + 1
fun scheduleBuild(state: ProductionState): ProductionState {
val timeRequired = timeUntilBuild(state)
return state.copy(
time = state.time + timeRequired,
ore = (state.ore - oreCost) + (timeRequired * state.oreRobots),
oreRobots = state.oreRobots + oreRobotsBuilt,
clay = (state.clay - clayCost) + (timeRequired * state.clayRobots),
clayRobots = state.clayRobots + clayRobotsBuilt,
obsidian = (state.obsidian - obsidianCost) + (timeRequired * state.obsidianRobots),
obsidianRobots = state.obsidianRobots + obsidianRobotsBuilt,
geodes = state.geodes + (timeRequired * state.geodeRobots),
geodeRobots = state.geodeRobots + geodeRobotsBuilt
)
}
}
private data class Blueprint(
val id: Int,
val oreRobot: RobotBlueprint,
val clayRobot: RobotBlueprint,
val obsidianRobot: RobotBlueprint,
val geodeRobot: RobotBlueprint
) {
val maxOre: Int =
maxOf(oreRobot.oreCost, clayRobot.oreCost, obsidianRobot.oreCost, geodeRobot.oreCost)
val maxClay: Int =
maxOf(oreRobot.clayCost, clayRobot.clayCost, obsidianRobot.clayCost, geodeRobot.clayCost)
val maxObsidian: Int =
maxOf(oreRobot.obsidianCost, clayRobot.obsidianCost, obsidianRobot.obsidianCost, geodeRobot.obsidianCost)
companion object {
fun of(input: String): Blueprint {
val parts = input.split(" ", ": ")
return Blueprint(
id = parts[1].toInt(),
oreRobot = RobotBlueprint(1, 0, 0, 0, parts[6].toInt()),
clayRobot = RobotBlueprint(0, 1, 0, 0, parts[12].toInt()),
obsidianRobot = RobotBlueprint(0, 0, 1, 0, parts[18].toInt(), parts[21].toInt()),
geodeRobot = RobotBlueprint(0, 0, 0, 1, parts[27].toInt(), 0, parts[30].toInt()),
)
}
}
}
}
| 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 5,765 | advent-2022-kotlin | Apache License 2.0 |
src/day4.kts | AfzalivE | 317,962,201 | false | null | println("Start")
val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
val input = readInput("day4.txt").readText()
val validNum = input.split("\n\n")
.asSequence()
.map { passport ->
val fullString = passport.replace("\n", " ")
return@map if (requiredFields.all {
fullString.contains(it)
}) {
fullString
} else {
null
}
}
.filter { it != null && Passport.fromString(it).isValid() }
.toList()
.size
println("$validNum valid passports")
data class Passport(
val byr: Int,
val iyr: Int,
val eyr: Int,
val hgt: String,
val hcl: String,
val ecl: String,
val pid: String,
val cid: Int?
) {
private val eyeColors = listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
fun isValid(): Boolean {
return byr in 1920..2002 &&
iyr in 2010..2020 &&
eyr in 2020..2030 &&
isValidHeight() &&
hcl.matches(Regex("#[0-9a-f]{6}")) &&
ecl in eyeColors &&
pid.length == 9
}
private fun isValidHeight(): Boolean {
return when {
hgt.matches(Regex("\\d{3}cm")) -> hgt.substring(0, 3).toInt() in 150..193
hgt.matches(Regex("\\d{2}in")) -> hgt.substring(0, 2).toInt() in 59..76
else -> false
}
}
companion object {
fun fromString(str: String): Passport {
val propMap = str.trim().split(" ").map {
val (key, value) = it.split(":")
return@map (key to value)
}.toMap()
return Passport(
propMap["byr"]!!.toInt(),
propMap["iyr"]!!.toInt(),
propMap["eyr"]!!.toInt(),
propMap["hgt"]!!,
propMap["hcl"]!!,
propMap["ecl"]!!,
propMap["pid"]!!,
propMap["cid"]?.toInt(),
)
}
}
}
| 0 | Kotlin | 0 | 0 | cc5998bfcaadc99e933fb80961be9a20541e105d | 2,049 | AdventOfCode2020 | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2023/Day11.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2023
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.XY
import com.s13g.aoc.resultFrom
import kotlin.math.max
import kotlin.math.min
typealias Universe = List<String>
/**
* --- Day 11: Cosmic Expansion ---
* https://adventofcode.com/2023/day/11
*/
class Day11 : Solver {
override fun solve(image: Universe): Result {
val gals = image.galaxies()
val expCols = image.expandingCols()
val expRows = image.expandingRows()
var sumA = 0L
var sumB = 0L
for (i in gals.indices) {
for (j in gals.indices.drop(i + 1)) {
sumA += shortestPathLength(gals[i], gals[j], expCols, expRows, 1)
sumB += shortestPathLength(gals[i], gals[j], expCols, expRows, 999_999)
}
}
return resultFrom(sumA, sumB)
}
private fun Universe.galaxies(): List<XY> {
val result = mutableListOf<XY>()
for ((y, line) in this.withIndex()) {
for ((x, ch) in line.withIndex()) {
if (ch == '#') result.add(XY(x, y))
}
}
return result;
}
private fun shortestPathLength(
a: XY,
b: XY,
expCols: Set<Int>,
expRows: Set<Int>,
expandBy: Int
): Long {
var len = 0L
for (p in shortestPath(a, b)) {
len++
if (p.x in expCols) len += expandBy
if (p.y in expRows) len += expandBy
}
return len
}
private fun shortestPath(a: XY, b: XY): List<XY> {
val path1 = (min(a.x, b.x) + 1..max(a.x, b.x)).map { XY(it, b.y) }
val path2 = (min(a.y, b.y) + 1..max(a.y, b.y)).map { XY(b.x, it) }
return path1.plus(path2)
}
private fun Universe.expandingCols() =
this[0].indices.filter { c -> column(c).count { it != '.' } == 0 }.toSet()
private fun Universe.expandingRows() =
this.withIndex().filter { (_, line) -> line.count { it != '.' } == 0 }
.map { (i, _) -> i }.toSet()
private fun Universe.column(col: Int) = this.map { it[col] }.joinToString("")
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,945 | euler | Apache License 2.0 |
src/Day07.kt | HaydenMeloche | 572,788,925 | false | {"Kotlin": 25699} | fun main() {
val input = readInput("Day07")
.toMutableList()
input.removeAt(0) // hardcoded first node
var currentNode = Node("/", Type.DIR, null, 0, mutableListOf())
val root = currentNode
input.forEach { line ->
when {
line == "$ ls" -> {}
line.startsWith("$ cd") -> {
val locationToJump = line.takeLastWhile { it != ' ' }
currentNode = when (locationToJump) {
".." -> currentNode.parent!!
else -> currentNode.children!!.find { it.name == locationToJump }!!
}
}
line.startsWith("dir") -> {
currentNode.children!!.add(Node(line.takeLastWhile { it != ' ' }, Type.DIR, currentNode, 0, mutableListOf()))
}
else -> run {
val (size, name) = line.split(" ")
currentNode.children!!.add(Node(name, Type.FILE, currentNode, size.toInt(), null))
}
}
}
// part two fields
val actualSpace = 70000000 - root.getSize()
val requiredSpace = 30000000
val spaceToTrim = (actualSpace - requiredSpace).times(-1)
val possibleDirectoriesToDelete = mutableListOf<Node>()
var answerOne = 0
fun navigate(node: Node) {
node.children?.forEach { navigate(it) }
if (node.type == Type.DIR) {
if (node.getSize() <= 100000) {
answerOne += node.getSize()
}
if (node.getSize() >= spaceToTrim) {
possibleDirectoriesToDelete.add(node)
}
}
}
navigate(root)
println("answer one: $answerOne")
println("answer two: ${possibleDirectoriesToDelete.minBy { it.getSize() }.getSize()}")
}
data class Node(
val name: String,
val type: Type,
val parent: Node?,
private val size: Int?,
val children: MutableList<Node>?
) {
fun getSize(): Int {
return (size ?: 0) + (children?.sumOf { it.getSize() } ?: 0)
}
}
enum class Type {
FILE,
DIR
} | 0 | Kotlin | 0 | 1 | 1a7e13cb525bb19cc9ff4eba40d03669dc301fb9 | 2,057 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/de/jball/aoc2022/day05/Day05.kt | fibsifan | 573,189,295 | false | {"Kotlin": 43681} | package de.jball.aoc2022.day05
import de.jball.aoc2022.Day
import java.util.Stack
class Day05(test: Boolean = false): Day<String>(test, "CMZ", "MCD") {
private val crates1: List<Stack<Char>>
private val crates2: List<Stack<Char>>
init {
val crateNumbers = input[input.indexOf("") - 1]
.split(" ")
.filter { it.isNotBlank() }
.map { it.toInt() }
val crateLines = input.subList(0,input.indexOf("")-1)
.map { line ->
line.chunked(4)
.map { crate -> crate.trim() }
.map { crate -> if (crate.matches("\\[\\w]".toRegex())) crate[1] else null }
}
crates1 = crateNumbers.map { Stack<Char>() }
crates2 = crateNumbers.map { Stack<Char>() }
crateLines.reversed()
.forEach { list -> list
.forEachIndexed { index, crate ->
if (crate != null) {
crates1[index].push(crate)
crates2[index].push(crate)
}
}
}
}
private val instructions = input.subList(input.indexOf("")+1, input.size)
.map { Regex("move (\\d+) from (\\d+) to (\\d+)").find(it)!!.groups }
.map { groups -> (1..3).map { match -> groups[match]!!.value.toInt() } }
override fun part1(): String {
instructions.forEach { instruction -> repeat(instruction[0]) {
crates1[instruction[2]-1].push(crates1[instruction[1]-1].pop())
} }
return crates1.map { it.pop() }.joinToString("")
}
override fun part2(): String {
instructions.forEach { instruction -> (1..instruction[0])
.map { crates2[instruction[1]-1].pop() }
.reversed()
.forEach { crates2[instruction[2]-1].push(it)}
}
return crates2.map { it.pop() }.joinToString("")
}
}
fun main() {
Day05().run()
}
| 0 | Kotlin | 0 | 3 | a6d01b73aca9b54add4546664831baf889e064fb | 1,954 | aoc-2022 | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day10/Day10.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day10
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 10](https://adventofcode.com/2021/day/10)
*/
object Day10 : DayOf2021(10) {
override fun first(): Any? {
return lines
.sumOf { line ->
val queue = ArrayDeque<Char>()
line.forEach { char ->
when (char) {
in "(<[{" -> queue.addLast(char)
')' -> if (queue.lastOrNull() == '(') queue.removeLast() else return@sumOf 3L
']' -> if (queue.lastOrNull() == '[') queue.removeLast() else return@sumOf 57L
'}' -> if (queue.lastOrNull() == '{') queue.removeLast() else return@sumOf 1197L
'>' -> if (queue.lastOrNull() == '<') queue.removeLast() else return@sumOf 25137L
}
}
return@sumOf 0L
}
}
override fun second(): Any? {
return lines
.mapNotNull { line ->
val queue = ArrayDeque<Char>()
line.forEach { char ->
when (char) {
in "(<[{" -> queue.addLast(char)
')' -> if (queue.lastOrNull() == '(') queue.removeLast() else return@mapNotNull null
']' -> if (queue.lastOrNull() == '[') queue.removeLast() else return@mapNotNull null
'}' -> if (queue.lastOrNull() == '{') queue.removeLast() else return@mapNotNull null
'>' -> if (queue.lastOrNull() == '<') queue.removeLast() else return@mapNotNull null
}
}
return@mapNotNull queue.toList().reversed()
}
.filter { it.isNotEmpty() }
.map { tail ->
tail.fold(0L) { acc, char ->
acc * 5L + when (char) {
'(' -> 1
'[' -> 2
'{' -> 3
'<' -> 4
else -> 0
}
}
}
.sorted()
.let { it[it.size / 2] }
}
}
fun main() = SomeDay.mainify(Day10)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,896 | adventofcode | MIT License |
src/aoc2022/Day08.kt | Playacem | 573,606,418 | false | {"Kotlin": 44779} | package aoc2022
import aoc2022.Day08.calculateScore
import aoc2022.Day08.isNotVisible
import utils.createDebug
import utils.readInput
object Day08 {
data class TreeView(
val value: Int,
val left: List<Int>,
val right: List<Int>,
val top: List<Int>,
val bottom: List<Int>,
val rowIndex: Int,
val columnIndex: Int
)
fun TreeView.isNotVisible(): Boolean {
return left.any { it >= value } &&
right.any { it >= value } &&
top.any { it >= value } &&
bottom.any { it >= value }
}
// like takeWhile with first predicate match
inline fun <T> Iterable<T>.takeDoWhile(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
list.add(item)
if (!predicate(item))
break
}
return list
}
fun TreeView.calculateScore(): Int {
val rightView = right.takeDoWhile { it < value }.count()
val leftView = left.reversed().takeDoWhile { it < value }.count()
val bottomView = bottom.takeDoWhile { it < value }.count()
val topView = top.reversed().takeDoWhile { it < value }.count()
return rightView * leftView * bottomView * topView
}
}
fun main() {
val (year, day) = 2022 to "Day08"
fun List<List<Int>>.getColumnValues(index: Int): List<Int> {
return this.map { it[index] }
}
fun List<List<Int>>.getRowValues(index: Int): List<Int> {
return this[index]
}
fun parseInput(input: List<String>): List<List<Int>> {
return input.map { line ->
line.chunked(1) {
it.toString().toInt(radix = 10)
}
}
}
fun List<List<Int>>.asTreeView(row: Int, column: Int): Day08.TreeView {
val value = this[row][column]
val rowValues = this.getRowValues(row)
val columnValues = this.getColumnValues(column)
val leftOfTarget = rowValues.subList(0, column)
val rightOfTarget = rowValues.subList(column + 1, rowValues.size)
val topOfTarget = columnValues.subList(0, row)
val bottomOfTarget = columnValues.subList(row + 1, columnValues.size)
return Day08.TreeView(
value = value,
left = leftOfTarget,
right = rightOfTarget,
top = topOfTarget,
bottom = bottomOfTarget,
rowIndex = row,
columnIndex = column
)
}
fun List<List<Int>>.isVisible(row: Int, column: Int): Boolean {
fun isNotVisible(): Boolean {
return asTreeView(row, column).isNotVisible()
}
return when {
row == 0 -> true
column == 0 -> true
row == this.size - 1 -> true
column == this[row].size - 1 -> true
else -> isNotVisible().not()
}
}
fun part1(input: List<String>, debugActive: Boolean = false): Int {
val debug = createDebug(debugActive)
val parsed = parseInput(input).also { debug { "$it" } }
val res = parsed.mapIndexed { rowIndex, rows ->
List(rows.size) { columnIndex ->
parsed.isVisible(rowIndex, columnIndex)
}
}
return res.flatten().count { it }
}
fun part2(input: List<String>, debugActive: Boolean = false): Int {
val debug = createDebug(debugActive)
val parsed = parseInput(input).also { debug { "$it" } }
val res = parsed.mapIndexed { rowIndex, rows ->
List(rows.size) { columnIndex ->
parsed.asTreeView(rowIndex, columnIndex)
}
}
return res.flatten().maxOf { it.calculateScore().also { score -> debug { "$it: $score" } } }
}
val testInput = readInput(year, "${day}_test")
val input = readInput(year, day)
// test if implementation meets criteria from the description, like:
check(part1(testInput, debugActive = true) == 21)
println(part1(input))
check(part2(testInput, debugActive = true) == 8)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4ec3831b3d4f576e905076ff80aca035307ed522 | 4,141 | advent-of-code-2022 | Apache License 2.0 |
y2016/src/main/kotlin/adventofcode/y2016/Day22.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2016
import adventofcode.io.AdventSolution
object Day22 : AdventSolution(2016, 22, "Grid Computing") {
override fun solvePartOne(input: String): String {
val nodes = parseInput(input)
return nodes.sumOf { source ->
nodes.count { target ->
(source.x != target.x || source.y != target.y)
&& source.used > 0
&& source.used <= target.available
}
}.toString()
}
override fun solvePartTwo(input: String): String =
parseInput(input)
.sortedBy { it.x }
.groupingBy { it.y }
.fold("") { str, n ->
str + when {
n.used == 0 -> "O"
n.size in 1..100 -> "_"
else -> "#"
}
}
.values
.joinToString("\n")
private fun parseInput(input: String): List<Node> = input
.lines()
.drop(2)
.map { it.split(Regex("\\s+")) }
.map {
Node(matchNodeName(it[0]).first, matchNodeName(it[0]).second,
it[1].dropLast(1).toInt(),
it[2].dropLast(1).toInt(),
it[3].dropLast(1).toInt())
}
private fun matchNodeName(descriptor: String): Pair<Int, Int> {
val (x, y) = Regex("/dev/grid/node-x(\\d+)-y(\\d+)").matchEntire(descriptor)!!.destructured
return Pair(x.toInt(), y.toInt())
}
private data class Node(val x: Int,
val y: Int,
val size: Int,
val used: Int,
val available: Int
)
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,347 | advent-of-code | MIT License |
src/Day09.kt | zfz7 | 573,100,794 | false | {"Kotlin": 53499} | import kotlin.math.abs
fun main() {
println(day9A(readFile("Day09")))
println(day9B(readFile("Day09")))
}
fun isTouching(head: Pair<Int, Int>, tail: Pair<Int, Int>): Boolean =
abs(head.first - tail.first) <= 1 && abs(head.second - tail.second) <= 1
fun moveHead(head: Pair<Int, Int>, mv: String): Pair<Int, Int> =
when (mv) {
"U" -> Pair(head.first, head.second + 1)
"D" -> Pair(head.first, head.second - 1)
"R" -> Pair(head.first + 1, head.second)
"L" -> Pair(head.first - 1, head.second)
else -> throw Exception("help")
}
fun day9B(input: String): Int {
var head = Pair<Int, Int>(0, 0)
val tails = generateSequence { Pair<Int,Int>(0,0) }.take(9).toList().toMutableList()
val allTailPos = mutableListOf<Pair<Int, Int>>()
input.split("\n").forEach { move ->
val mv = move.split(" ")
repeat(mv[1].toInt()) {
head = moveHead(head, mv[0])
if (!isTouching(head, tails[0])) {
tails[0] = moveTail(head, tails[0])
}
repeat(8) {idx ->
if (!isTouching(tails[idx], tails[idx+1])) {
tails[idx +1] = moveTail(tails[idx], tails[idx+1])
}
}
allTailPos.add( tails[8] )
}
}
return allTailPos.toSet().size
}
fun day9A(input: String): Int {
var head = Pair<Int, Int>(0, 0)
var tail = Pair<Int, Int>(0, 0)
val allTailPos = mutableListOf<Pair<Int, Int>>()
input.split("\n").forEach { move ->
val mv = move.split(" ")
repeat(mv[1].toInt()) {
head = moveHead(head, mv[0])
if (!isTouching(head, tail)) {
tail = moveTail(head,tail)
}
allTailPos.add(tail)
}
}
return allTailPos.toSet().size
}
fun moveTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
val xDiff = head.first - tail.first
val yDiff = head.second - tail.second
if (xDiff > 1 && yDiff == 0)
return Pair(tail.first + 1, tail.second)
else if (xDiff < -1 && yDiff == 0)
return Pair(tail.first - 1, tail.second)
else if (xDiff == 0 && yDiff > 1)
return Pair(tail.first, tail.second + 1)
else if (xDiff == 0 && yDiff < -1)
return Pair(tail.first, tail.second - 1)
else if (xDiff >= 1 && yDiff >= 1)
return Pair(tail.first + 1, tail.second + 1)
else if (xDiff <= -1 && yDiff >= 1)
return Pair(tail.first - 1, tail.second + 1)
else if (xDiff >= 1 && yDiff <= -1)
return Pair(tail.first + 1, tail.second - 1)
else if (xDiff <= -1 && yDiff <= -1)
return Pair(tail.first - 1, tail.second - 1)
throw Exception("Help")
}
| 0 | Kotlin | 0 | 0 | c50a12b52127eba3f5706de775a350b1568127ae | 2,743 | AdventOfCode22 | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[1128]等价多米诺骨牌对的数量.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给你一个由一些多米诺骨牌组成的列表 dominoes。
//
// 如果其中某一张多米诺骨牌可以通过旋转 0 度或 180 度得到另一张多米诺骨牌,我们就认为这两张牌是等价的。
//
// 形式上,dominoes[i] = [a, b] 和 dominoes[j] = [c, d] 等价的前提是 a==c 且 b==d,或是 a==d 且
//b==c。
//
// 在 0 <= i < j < dominoes.length 的前提下,找出满足 dominoes[i] 和 dominoes[j] 等价的骨牌对 (i,
// j) 的数量。
//
//
//
// 示例:
//
// 输入:dominoes = [[1,2],[2,1],[3,4],[5,6]]
//输出:1
//
//
//
//
// 提示:
//
//
// 1 <= dominoes.length <= 40000
// 1 <= dominoes[i][j] <= 9
//
// Related Topics 数组
// 👍 101 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun numEquivDominoPairs(dominoes: Array<IntArray>): Int {
val map = IntArray(100)
var res = 0
for (i in dominoes.indices) {
val m = dominoes[i][0]
val n = dominoes[i][1]
val k = if (m > n) m * 10 + n else n * 10 + m
map[k]++
}
for (i in 0..99) {
res += map[i] * (map[i] - 1) / 2
}
return res
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,295 | MyLeetCode | Apache License 2.0 |
y2017/src/main/kotlin/adventofcode/y2017/Day14.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2017
import adventofcode.io.AdventSolution
fun main() =Day14.solve()
object Day14 : AdventSolution(2017, 14, "Disk Defragmentation") {
override fun solvePartOne(input: String): String = (0..127).asSequence()
.map { "$input-$it" }
.flatMap { knotHash(it).asSequence() }
.flatMap { it.toBits().asSequence() }
.count { it }
.toString()
override fun solvePartTwo(input: String): String {
val rows = (0..127)
.map { "$input-$it" }
.map { knotHash(it) }
.map { hash -> hash.flatMap { it.toBits() }.toBooleanArray() }
.toTypedArray()
return rows.indices.asSequence().flatMap { y -> rows[0].indices.asSequence().map { x -> x to y } }
.filter { (x, y) -> rows[y][x] }
.onEach { (x, y) -> clearGroup(rows, x, y) }
.count()
.toString()
}
private fun clearGroup(rows: Array<BooleanArray>, x: Int, y: Int) {
if (rows.getOrNull(y)?.getOrNull(x) != true) {
return
}
rows[y][x] = false
clearGroup(rows, x + 1, y)
clearGroup(rows, x - 1, y)
clearGroup(rows, x, y + 1)
clearGroup(rows, x, y - 1)
}
}
private fun Int.toBits() = List(8) { bit -> this and (1 shl 7 - bit) != 0 }
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,164 | advent-of-code | MIT License |
src/main/kotlin/days/Day2.kt | MisterJack49 | 574,081,723 | false | {"Kotlin": 35586} | package days
private enum class Shape(val score: Int) {
Rock(1), Paper(2), Scissors(3)
}
private enum class Outcome(val score: Int) {
Lose(0), Draw(3), Win(6)
}
class Day2 : Day(2) {
override fun partOne(): Any {
return inputList.map { entry -> entry.first().toShape() to entry.last().toShape() }
.sumOf { round -> shifumi(round.first, round.second).score + round.second.score }
}
override fun partTwo(): Any {
return inputList.map { entry -> entry.first().toShape() to entry.last().toOutcome() }
.sumOf { round -> move(round.first, round.second).score + round.second.score }
}
private fun shifumi(opponent: Shape, player: Shape): Outcome =
when (opponent) {
Shape.Rock -> if (player == Shape.Scissors) Outcome.Lose else if (player == Shape.Rock) Outcome.Draw else Outcome.Win
Shape.Paper -> if (player == Shape.Rock) Outcome.Lose else if (player == Shape.Paper) Outcome.Draw else Outcome.Win
Shape.Scissors -> if (player == Shape.Paper) Outcome.Lose else if (player == Shape.Scissors) Outcome.Draw else Outcome.Win
}
private fun move(opponent: Shape, outcome: Outcome): Shape {
if (outcome == Outcome.Draw)
return opponent
return when (opponent) {
Shape.Rock -> if (outcome == Outcome.Lose) Shape.Scissors else Shape.Paper
Shape.Paper -> if (outcome == Outcome.Lose) Shape.Rock else Shape.Scissors
Shape.Scissors -> if (outcome == Outcome.Lose) Shape.Paper else Shape.Rock
}
}
}
private fun Char.toShape() =
when (this) {
'A', 'X' -> Shape.Rock
'B', 'Y' -> Shape.Paper
'C', 'Z' -> Shape.Scissors
else -> throw IllegalArgumentException()
}
private fun Char.toOutcome() =
when (this) {
'X' -> Outcome.Lose
'Y' -> Outcome.Draw
'Z' -> Outcome.Win
else -> throw IllegalArgumentException()
}
| 0 | Kotlin | 0 | 0 | e82699a06156e560bded5465dc39596de67ea007 | 1,977 | AoC-2022 | Creative Commons Zero v1.0 Universal |
src/Day04.kt | CrazyBene | 573,111,401 | false | {"Kotlin": 50149} | fun main() {
data class SectionAssignment(val start: Int, val end: Int)
fun String.toSectionAssignment(): SectionAssignment {
return split("-")
.map { it.toInt() }
.zipWithNext()
.map { SectionAssignment(it.first, it.second) }
.also { if(it.size != 1) error("Could not convert $this to SectionAssignment.") }
.first()
}
fun String.toSectionAssignmentPair(): Pair<SectionAssignment, SectionAssignment> {
return split(",")
.map { it.toSectionAssignment()}
.zipWithNext()
.also { if(it.size != 1) error("Could not convert $this to SectionAssignmentPair.") }
.first()
}
fun part1(input: List<String>): Int {
return input
.map { it.toSectionAssignmentPair() }
.count { pair ->
(pair.first.start <= pair.second.start && pair.first.end >= pair.second.end) ||
(pair.first.start >= pair.second.start && pair.first.end <= pair.second.end)
}
}
fun part2(input: List<String>): Int {
return input
.map { it.toSectionAssignmentPair() }
.count { pair ->
(pair.first.start <= pair.second.start && pair.first.end >= pair.second.start) ||
(pair.first.start >= pair.second.start && pair.first.start <= pair.second.end)
}
}
val testInput = readInput("Day04Test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println("Question 1 - Answer: ${part1(input)}")
println("Question 2 - Answer: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26 | 1,671 | AdventOfCode2022 | Apache License 2.0 |
calendar/day08/Day8.kt | starkwan | 573,066,100 | false | {"Kotlin": 43097} | package day08
import Day
import Lines
class Day8 : Day() {
override fun part1(input: Lines): Any {
val rows: List<List<Int>> = input.map { it.toList().map { it.toString().toInt() } }
val columns: List<List<Int>> = buildList {
for (i in 0 until rows[0].size) {
add(buildList { rows.forEach { add(it[i]) } })
}
}
var visibleCount = 0
rows.forEachIndexed { rIndex, row ->
row.forEachIndexed { cIndex, _ ->
val fromLeft = rows[rIndex].take(cIndex + 1)
val fromRight = rows[rIndex].reversed().take(row.size - cIndex)
val fromTop = columns[cIndex].take(rIndex + 1)
val fromBottom = columns[cIndex].reversed().take(columns.size - rIndex)
if (isVisible(fromLeft) || isVisible(fromRight) || isVisible(fromTop) || isVisible(fromBottom)) {
visibleCount++
}
}
}
return visibleCount
}
private fun isVisible(trees: List<Int>): Boolean {
return trees.max() == trees.last() && !trees.dropLast(1).contains(trees.last())
}
override fun part2(input: Lines): Any {
val rows: List<List<Int>> = input.map { it.toList().map { it.toString().toInt() } }
val columns: List<List<Int>> = buildList {
for (i in 0 until rows[0].size) {
add(buildList { rows.forEach { add(it[i]) } })
}
}
var highestScore = 0
rows.forEachIndexed { rIndex, row ->
row.forEachIndexed { cIndex, self ->
val toLeft = rows[rIndex].take(cIndex).reversed()
val toRight = rows[rIndex].takeLast(columns.size - cIndex - 1)
val toTop = columns[cIndex].take(rIndex).reversed()
val toBottom = columns[cIndex].takeLast(rows.size - rIndex - 1)
val score =
toLeft.getScore(self) * toRight.getScore(self) * toTop.getScore(self) * toBottom.getScore(self)
highestScore = maxOf(highestScore, score)
}
}
return highestScore
}
private fun List<Int>.getScore(self: Int): Int {
val numOfVisibleTrees = this.indexOfFirst { it >= self } + 1
return if (numOfVisibleTrees == 0) {
this.size
} else {
numOfVisibleTrees
}
}
} | 0 | Kotlin | 0 | 0 | 13fb66c6b98d452e0ebfc5440b0cd283f8b7c352 | 2,422 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day22/Day22.kt | daniilsjb | 434,765,082 | false | {"Kotlin": 77544} | package day22
import java.io.File
import kotlin.math.max
import kotlin.math.min
fun main() {
val data = parse("src/main/kotlin/day22/Day22.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 22 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Cuboid(
val x0: Int, val x1: Int,
val y0: Int, val y1: Int,
val z0: Int, val z1: Int,
val on: Boolean = true,
)
private fun Cuboid.overlap(other: Cuboid): Cuboid? {
val (ax0, ax1, ay0, ay1, az0, az1) = this
val (bx0, bx1, by0, by1, bz0, bz1) = other
val ox0 = max(ax0, bx0)
val ox1 = min(ax1, bx1)
val oy0 = max(ay0, by0)
val oy1 = min(ay1, by1)
val oz0 = max(az0, bz0)
val oz1 = min(az1, bz1)
return if (ox0 <= ox1 && oy0 <= oy1 && oz0 <= oz1) {
Cuboid(ox0, ox1, oy0, oy1, oz0, oz1)
} else {
null
}
}
/*
* A recursive solution based on the principle of exclusion and inclusion.
* To be fair, this is not the first solution I came up with. My initial idea
* was to maintain a list of non-overlapping cuboids by splitting every cuboid
* into smaller ones whenever overlaps occur, and then calculating the sum of
* their volumes.
*
* However, I found out about this principle and thought that this was a much
* neater way of implementing this, and it works quite fast, too. There is
* always something new to learn! :)
*/
private fun count(cuboids: List<Cuboid>): Long {
if (cuboids.isEmpty()) {
return 0
}
val (head, rest) = cuboids.first() to cuboids.drop(1)
return if (head.on) {
val intersections = rest.mapNotNull(head::overlap)
head.volume() + count(rest) - count(intersections)
} else {
count(rest)
}
}
private fun Cuboid.volume(): Long {
val xs = (x1 - x0 + 1).toLong()
val ys = (y1 - y0 + 1).toLong()
val zs = (z1 - z0 + 1).toLong()
return xs * ys * zs
}
private fun parse(path: String): List<Cuboid> =
File(path)
.readLines()
.map(String::toCuboid)
private fun String.toCuboid(): Cuboid {
val (valuePart, coordinatesPart) = this.split(" ")
val (x, y, z) = coordinatesPart
.split(",")
.map { it.drop(2) }
val (x0, x1) = x.toBounds()
val (y0, y1) = y.toBounds()
val (z0, z1) = z.toBounds()
val on = valuePart == "on"
return Cuboid(x0, x1, y0, y1, z0, z1, on)
}
private fun String.toBounds(): Pair<Int, Int> =
this.split("..")
.map(String::toInt)
.let { (a, b) -> a to b }
private fun part1(cuboids: List<Cuboid>): Long =
cuboids
.filter { (x0, x1, y0, y1, z0, z1) -> arrayOf(x0, x1, y0, y1, z0, z1).all { it in -50..50 } }
.let(::count)
private fun part2(cuboids: List<Cuboid>): Long =
count(cuboids)
| 0 | Kotlin | 0 | 1 | bcdd709899fd04ec09f5c96c4b9b197364758aea | 2,897 | advent-of-code-2021 | MIT License |
src/day08/Day08.kt | barbulescu | 572,834,428 | false | {"Kotlin": 17042} | package day08
import readInput
fun main() {
val lines: List<List<Int>> = readInput("day08/Day08")
.map { line -> line.toCharArray().map { it.toString().toInt() } }
.toList()
val grid = Grid(lines)
.markEdgeVisible()
.markFromLeft()
.markFromRight()
.markFromTop()
.markFromBottom()
println("Visible: ${grid.countVisible()}")
grid.calculateHighestScenicScore()
}
private class Grid(values: List<List<Int>>) {
private val size = values.size
private val storage: List<List<Position>> = values
.onEach { require(it.size == size) }
.map { row -> row.map { Position(it) } }
override fun toString(): String {
return storage.joinToString("\n") { it.toString() }
}
fun markEdgeVisible(): Grid {
storage.first().forEach { it.visible = true }
storage.last().forEach { it.visible = true }
(0 until size).forEach { storage[it][0].visible = true }
(0 until size).forEach { storage[it][size - 1].visible = true }
return this
}
fun markFromLeft(): Grid {
for (row in (0 until size)) {
var max = 0
for (col in (0 until size)) {
max = storage[row][col].markVisible(max)
}
}
return this
}
fun markFromRight(): Grid {
for (row in (0 until size)) {
var max = 0
for (col in (size - 1 downTo 0)) {
max = storage[row][col].markVisible(max)
}
}
return this
}
fun markFromTop(): Grid {
for (col in (0 until size)) {
var max = 0
for (row in (0 until size)) {
max = storage[row][col].markVisible(max)
}
}
return this
}
fun markFromBottom(): Grid {
for (col in (0 until size)) {
var previous = 0
for (row in (size - 1 downTo 0)) {
previous = storage[row][col].markVisible(previous)
}
}
return this
}
fun countVisible(): Int {
return storage
.flatten()
.count { it.visible }
}
fun calculateHighestScenicScore() {
var highest = 0
for (row in (1..size - 2)) {
for (col in (1..size - 2)) {
val score = calculateScenicScore(row, col)
if (score > highest) {
highest = score
}
}
}
println("Highest score is $highest")
}
private fun calculateScenicScore(row: Int, col: Int): Int {
val tree = storage[row][col].value
val score1 = calculateScore(tree, (row - 1 downTo 0)) { storage[it][col] }
val score2 = calculateScore(tree, (row + 1 until size)) { storage[it][col] }
val score3 = calculateScore(tree, (col - 1 downTo 0)) { storage[row][it] }
val score4 = calculateScore(tree, (col + 1 until size)) { storage[row][it] }
val score = score1 * score2 * score3 * score4
println("Score is $score for position ($row, $col) with $score1 $score2 $score3 $score4")
return score
}
private fun calculateScore(tree: Int, range: IntProgression, valueExtractor: (Int) -> Position): Int {
val values = range
.map(valueExtractor)
.map { it.value }
values.forEachIndexed {index, value ->
if (value >= tree) {
return index + 1
}
}
return values.size
}
}
private class Position(val value: Int, var visible: Boolean = false) {
override fun toString(): String {
return "$value${visible.toString().take(1)}"
}
fun markVisible(max: Int): Int =
if (value > max) {
visible = true
value
} else {
max
}
} | 0 | Kotlin | 0 | 0 | 89bccafb91b4494bfe4d6563f190d1b789cde7a4 | 3,885 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2020/d22/Day22.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2020.d22
import com.groundsfam.advent.DATAPATH
import kotlin.io.path.div
import kotlin.io.path.useLines
fun scoreDeck(deck: List<Int>): Int = deck.reversed()
.mapIndexed { i, card ->
card * (i + 1)
}.sum()
fun simulateCombat(deck1: List<Int>, deck2: List<Int>): Int {
val mDeck1 = ArrayDeque(deck1)
val mDeck2 = ArrayDeque(deck2)
while (mDeck1.isNotEmpty() && mDeck2.isNotEmpty()) {
val card1 = mDeck1.removeFirst()
val card2 = mDeck2.removeFirst()
if (card1 > card2) {
mDeck1.addLast(card1)
mDeck1.addLast(card2)
} else {
mDeck2.addLast(card2)
mDeck2.addLast(card1)
}
}
return scoreDeck(if (mDeck1.isEmpty()) mDeck2 else mDeck1)
}
// returns pair of (winnerIsPlayerOne, score)
fun simulateRecursiveCombat(deck1: ArrayDeque<Int>, deck2: ArrayDeque<Int>): Pair<Boolean, Int> {
val prevGames = mutableSetOf<Pair<List<Int>, List<Int>>>()
while (deck1.isNotEmpty() && deck2.isNotEmpty()) {
if (!prevGames.add(deck1.toList() to deck2.toList())) {
return true to scoreDeck(deck1)
}
val card1 = deck1.removeFirst()
val card2 = deck2.removeFirst()
val nextWinnerPlayerOne = if (card1 <= deck1.size && card2 <= deck2.size) {
val nextDeck1 = ArrayDeque(deck1.take(card1))
val nextDeck2 = ArrayDeque(deck2.take(card2))
simulateRecursiveCombat(nextDeck1, nextDeck2).first
} else {
card1 > card2
}
if (nextWinnerPlayerOne) {
deck1.addLast(card1)
deck1.addLast(card2)
} else {
deck2.addLast(card2)
deck2.addLast(card1)
}
}
return if (deck1.isNotEmpty()) {
true to scoreDeck(deck1)
} else {
false to scoreDeck(deck2)
}
}
fun main() {
val decks = Array(2) { mutableListOf<Int>() }
(DATAPATH / "2020/day22.txt").useLines { lines ->
var i = 0
lines.forEach { line ->
if (line.isBlank()) i++
line.toIntOrNull()?.let {
decks[i].add(it)
}
}
}
simulateCombat(decks[0], decks[1])
.also { println("Part one: $it") }
simulateRecursiveCombat(ArrayDeque(decks[0]), ArrayDeque(decks[1]))
.also { println("Part two: ${it.second}") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,414 | advent-of-code | MIT License |
src/Day03.kt | k3vonk | 573,555,443 | false | {"Kotlin": 17347} | fun main() {
fun convertToPriority(item: Char): Int {
return if (item.isUpperCase()) {
item.code - 'A'.code + 27
} else {
item.code - 'a'.code + 1
}
}
fun part1(rucksacks: List<String>): Int {
var priority = 0
rucksacks.forEach { rucksack ->
val half = rucksack.length / 2
val compartments = listOf(
rucksack.substring(0, half).toHashSet(),
rucksack.substring(half).toHashSet()
)
for (item in compartments[0]) {
if (compartments[1].contains(item)) {
priority += convertToPriority(item)
break
}
}
}
return priority
}
fun part2(rucksacks: List<String>): Int {
var priorty = 0
for (i in rucksacks.indices step 3) {
val rucksack1 = rucksacks[i].toHashSet()
val rucksack2 = rucksacks[i + 1].toHashSet()
val rucksack3 = rucksacks[i + 2].toHashSet()
val item = rucksack1.intersect(rucksack2).intersect(rucksack3)
priorty += convertToPriority(item.first())
}
return priorty
}
val rucksacks = readInput("Day03_test")
println(part1(rucksacks))
println(part2(rucksacks))
} | 0 | Kotlin | 0 | 1 | 68a42c5b8d67442524b40c0ce2e132898683da61 | 1,341 | AOC-2022-in-Kotlin | Apache License 2.0 |
src/Day02.kt | pedroldk | 573,424,273 | false | {"Kotlin": 4625} | fun main() {
fun processRound1(theirPlay: Char, myPlay: Char): Int {
return when (theirPlay) {
'A' -> when(myPlay) {
'X' -> 1 + 3
'Y' -> 2 + 6
'Z' -> 3 + 0
else -> -1
}
'B' -> when(myPlay) {
'X' -> 1 + 0
'Y' -> 2 + 3
'Z' -> 3 + 6
else -> -1
}
'C' -> when(myPlay) {
'X' -> 1 + 6
'Y' -> 2 + 0
'Z' -> 3 + 3
else -> -1
}
else -> -1
}
}
fun processRound2(theirPlay: Char, myPlay: Char): Int {
return when (theirPlay) {
'A' -> when(myPlay) {
'X' -> 3 + 0
'Y' -> 1 + 3
'Z' -> 2 + 6
else -> -1
}
'B' -> when(myPlay) {
'X' -> 1 + 0
'Y' -> 2 + 3
'Z' -> 3 + 6
else -> -1
}
'C' -> when(myPlay) {
'X' -> 2 + 0
'Y' -> 3 + 3
'Z' -> 1 + 6
else -> -1
}
else -> -1
}
}
fun part1(input: List<String>): Int {
return input.sumOf {
processRound1(it.first(), it.last())
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
processRound2(it.first(), it.last())
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
//check(part2(testInput) == 45000)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 68348bbfc308d257b2d02fa87dd241f8f584b444 | 1,808 | aoc-2022-in-kotlin | Apache License 2.0 |
kotlin/src/main/kotlin/io/github/piszmog/aoc/Day3.kt | Piszmog | 433,651,411 | false | null | package io.github.piszmog.aoc
import java.time.Instant
import kotlin.math.pow
fun main(args: Array<String>) {
val start = Instant.now()
val parser = getCSVParser(args[0])
val report = parser.map { it -> it[0].toCharArray().map { it == '1' } }.toList()
val part1Solution = day3Part1(report)
println("Part 1: $part1Solution")
val part2Solution = day3Part2(report)
println("Part 2: $part2Solution")
printElapsedTime(start)
}
fun day3Part1(input: List<List<Boolean>>): Int {
var gammaRate = IntArray(input[0].size) { 0 }
input.forEach { row ->
var col = 0
row.forEach {
when (it) {
true -> gammaRate[col]++
false -> gammaRate[col]--
}
col++
}
}
gammaRate = gammaRate.map { if (it > 0) 1 else 0 }.toIntArray()
val epsilonRate = gammaRate.map { if (it == 1) 0 else 1 }.toIntArray()
return binaryToDecimal(gammaRate) * binaryToDecimal(epsilonRate)
}
fun day3Part2(input: List<List<Boolean>>) =
getRating(input, true) * getRating(input, false)
private fun getRating(input: List<List<Boolean>>, bitType: Boolean): Int {
var data = input
var binaryBool = listOf<Boolean>()
var mostCommon = 0
for (col in 0..input[0].size) {
if (data.size == 1) {
binaryBool = data.first()
break
}
if (data.size == 2) {
binaryBool = data.first { it[col] == bitType }
break
}
data.forEach { row ->
when (row[col]) {
true -> mostCommon++
false -> mostCommon--
}
}
val mostCommonBit = when (bitType) {
true -> if (mostCommon > 0) true else mostCommon >= 0
false -> if (mostCommon > 0) false else mostCommon < 0
}
mostCommon = 0
data = data.filter { it[col] == mostCommonBit }.toList()
}
val binary = binaryBool.map { if (it) 1 else 0 }.toIntArray()
return binaryToDecimal(binary)
}
private fun binaryToDecimal(input: IntArray): Int {
var result = 0
for ((power, i) in input.reversed().withIndex()) {
result += i * 2.0.pow(power.toDouble()).toInt()
}
return result
}
| 0 | Rust | 0 | 0 | a155cb7644017863c703e97f22c8338ccb5ef544 | 2,255 | aoc-2021 | MIT License |
src/year2023/21/Day21.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`21`
import readInput
import kotlin.math.pow
import kotlin.math.roundToLong
private const val CURRENT_DAY = "21"
private data class Point(
val x: Int,
val y: Int,
) {
override fun toString(): String {
return "[$x,$y]"
}
}
private fun Point.neighbours(): Set<Point> {
return setOf(
Point(x = x, y = y + 1),
Point(x = x, y = y - 1),
Point(x = x + 1, y = y),
Point(x = x - 1, y = y),
)
}
private fun parseMap(input: List<String>, initialPoint: Point): Map<Point, String> {
val mutableMap = mutableMapOf<Point, String>()
input.forEachIndexed { y, line ->
line.split("")
.filter { it.isNotBlank() }
.forEachIndexed { x, value ->
val currentPoint = Point(x, y)
mutableMap[currentPoint] = if (currentPoint == initialPoint) {
"S"
} else {
value.takeIf { it != "S" } ?: "."
}
}
}
return mutableMap
}
private fun processMap(
initialMap: Map<Point, String>,
setOfCurrentPoints: Set<Point>,
): Map<Point, String> {
val newPoints = setOfCurrentPoints.flatMap { point ->
point.neighbours()
}
.filter { it in initialMap.keys }
.filter { initialMap[it] != "#" }
val mutableMap = mutableMapOf<Point, String>()
initialMap.forEach { (point, value) ->
when (value) {
"#" -> mutableMap[point] = "#"
"S", "." -> mutableMap[point] = "O".takeIf { point in newPoints } ?: "."
"O" -> mutableMap[point] = "O".takeIf { mutableMap[point] == "O" } ?: "."
else -> error("Illegal Point: $point Value:$value")
}
}
return mutableMap
}
fun main() {
fun part1(
input: List<String>,
repeatCount: Int = 64,
sPoint: Point = Point(input.size / 2, input.size / 2)
): Int {
val map = parseMap(input, sPoint)
var currentMap = map
repeat(repeatCount) {
currentMap = processMap(
initialMap = currentMap,
setOfCurrentPoints = currentMap.keys.filter { currentMap[it] in listOf("O", "S") }
.toSet(),
)
}
return currentMap.count { it.value == "O" }
}
fun part2(input: List<String>): Long {
val useCachedValue = true
assert(input.size == input[0].length)
val size = input.size
val startX = size / 2
val startY = size / 2
val steps = 26501365
println("size:$size")
assert(steps % size == size / 2)
val gridWidth = steps.floorDiv(size) - 1
println("gridWidth:$gridWidth")
val odd = (gridWidth.floorDiv(2) * 2 + 1).toDouble().pow(2).roundToLong()
val even = (gridWidth.inc().floorDiv(2) * 2).toDouble().pow(2).roundToLong()
println("odd : $odd")
println("even : $even")
val oddPoints = if (useCachedValue) 7496 else part1(input, size * 2 + 1)
val evenPoints = if (useCachedValue) 7570 else part1(input, size * 2)
println()
println("oddPoints : $oddPoints")
println("evenPoints : $evenPoints")
val edgeTop = if (useCachedValue) 5670 else part1(
input = input,
repeatCount = size - 1,
sPoint = Point(startX, size - 1),
)
val edgeRight = if (useCachedValue) 5637 else part1(
input = input,
repeatCount = size - 1,
sPoint = Point(0, startY),
)
val edgeBottom = if (useCachedValue) 5623 else part1(
input = input,
repeatCount = size - 1,
sPoint = Point(startX, 0),
)
val edgeLeft = if (useCachedValue) 5656 else part1(
input = input,
repeatCount = size - 1,
sPoint = Point(size - 1, startY),
)
println()
println("edgeTop: $edgeTop")
println("edgeRight: $edgeRight")
println("edgeBottom: $edgeBottom")
println("edgeLeft: $edgeLeft")
val smallTopRight = if (useCachedValue) 980 else part1(
input = input,
repeatCount = size.floorDiv(2) - 1,
sPoint = Point(0, size - 1),
)
val smallTopLeft = if (useCachedValue) 965 else part1(
input = input,
repeatCount = size.floorDiv(2) - 1,
sPoint = Point(size - 1, size - 1),
)
val smallBottomRight = if (useCachedValue) 963 else part1(
input = input,
repeatCount = size.floorDiv(2) - 1,
sPoint = Point(0, 0),
)
val smallBottomLeft = if (useCachedValue) 945 else part1(
input = input,
repeatCount = size.floorDiv(2) - 1,
sPoint = Point(size - 1, 0),
)
val totalSmallCount: Long = (gridWidth + 1L) *
(smallBottomRight + smallBottomLeft + smallTopRight + smallTopLeft)
println()
println("smallTopRight: $smallTopRight")
println("smallTopLeft: $smallTopLeft")
println("smallBottomRight: $smallBottomRight")
println("smallBottomLeft: $smallBottomLeft")
println()
println("totalSmallCount: $totalSmallCount")
val largeTopRight = if (useCachedValue) 6584 else part1(
input = input,
repeatCount = size.times(3).floorDiv(2) - 1,
sPoint = Point(0, size - 1),
)
val largeTopLeft = if (useCachedValue) 6582 else part1(
input = input,
repeatCount = size.times(3).floorDiv(2) - 1,
sPoint = Point(size - 1, size - 1),
)
val largeBottomRight = if (useCachedValue) 6549 else part1(
input = input,
repeatCount = size.times(3).floorDiv(2) - 1,
sPoint = Point(0, 0),
)
val largeBottomLeft = if (useCachedValue) 6570 else part1(
input = input,
repeatCount = size.times(3).floorDiv(2) - 1,
sPoint = Point(size - 1, 0),
)
val totalLargeCount = (gridWidth.toLong()) *
(largeBottomRight + largeBottomLeft + largeTopRight + largeTopLeft)
println()
println("largeTopRight: $largeTopRight")
println("largeTopLeft: $largeTopLeft")
println("largeBottomRight: $largeBottomRight")
println("largeBottomLeft: $largeBottomLeft")
println()
val countTotal = odd * oddPoints +
even * evenPoints +
edgeTop + edgeBottom + edgeLeft + edgeRight +
totalSmallCount +
totalLargeCount
println("Total Count: $countTotal")
return countTotal
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 42)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input)
println(part1)
check(part1 == 3716)
// Part 2
val part2 = part2(input)
println(part2)
check(part2 == 1L)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 7,226 | KotlinAdventOfCode | Apache License 2.0 |
codeforces/vk2021/round1/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.vk2021.round1
import kotlin.random.Random
import kotlin.system.exitProcess
private fun solveSmart(a: List<Int>): List<Int> {
val used = BooleanArray(a.size)
val ans = IntArray(a.size) { -1 }
for (i in a.indices) {
if (a[i] == i) continue
if (used[a[i]]) continue
used[a[i]] = true
ans[i] = a[i]
}
val unused = used.indices.filter { !used[it] }.toMutableList()
val weakIndices = ans.indices.filter { ans[it] == -1 }
for (i in weakIndices) {
ans[i] = unused.last()
unused.removeAt(unused.lastIndex)
}
for (i in weakIndices) {
if (ans[i] == i) {
val j = if (weakIndices.size > 1) {
weakIndices.first { it != i }
} else {
val jj = ans.indices.firstOrNull { it != i && ans[it] == a[i] }
jj ?: ans.indices.first { it != i && ans[it] != i }
}
val t = ans[i]; ans[i] = ans[j]; ans[j] = t
break
}
}
return ans.toList()
}
private fun solve() {
readLn()
val a = readInts().map { it - 1 }
val ans = solveSmart(a)
println(a.indices.count { a[it] == ans[it] })
println(ans.map { it + 1 }.joinToString(" "))
}
fun main() {
// stress()
repeat(readInt()) { solve() }
}
private fun solveDumb(a: List<Int>): List<Int> {
var bestCommon = -1
var best: List<Int>? = null
fun search(prefix: List<Int>) {
if (prefix.size == a.size) {
val common = a.indices.count { a[it] == prefix[it] }
if (common > bestCommon) {
bestCommon = common
best = prefix
}
return
}
for (i in a.indices - prefix - listOf(prefix.size)) {
search(prefix + i)
}
}
search(listOf())
return best!!
}
@Suppress("unused")
private fun stress() {
val r = Random(566)
while (true) {
val n = 2 + r.nextInt(5)
val a = List(n) { r.nextInt(n) }
val smart = solveSmart(a)
val dumb = solveDumb(a)
println(a)
println(smart)
println(dumb)
fun quality(b: List<Int>): Int {
return b.indices.count { b[it] == a[it] }
}
if (quality(smart) != quality(dumb)) {
exitProcess(0)
}
}
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,145 | competitions | The Unlicense |
src/Day03.kt | allwise | 574,465,192 | false | null | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
val rucksacks = Rocksacks(input)
return rucksacks.process()
}
fun part2(input: List<String>): Int {
val rucksacks = Rocksacks(input)
return rucksacks.processGroups()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
class Rocksacks(val input:List<String>) {
//val input_test = File("C:\\Users\\kimha\\Downloads\\rucksack_test.txt").readLines()
fun process(): Int {
val s = input.map{ stringy ->
val splitLine = stringy.chunked(stringy.length/2)
findAllSame(splitLine[0],splitLine[1]).first().getValue()}.sum()
println(s)
return s
}
fun processGroups(): Int {
val s = input.chunked(3)
val g = s.map{findAllSame(findAllSame(it[0],it[1]), it[2]).first().getValue()}.sum()
println("sum " +g)
return g
}
fun findSame(str1:String,str2:String): Char {
//println("str1 "+str1)
for(cha in str1.toCharArray()){
if (str2.contains(cha))
return cha
}
return ' '
}
fun findAllSame(str1:String,str2:String): String {
// println("str1 "+str1.toCharArray().filter { str2.contains(it) }.distinct().joinToString())
return str1.toCharArray().filter { str2.contains(it) }.distinct().joinToString()
}
fun Char.getValue():Int{
if(this in ('a'..'z')){
// println("small " +this + " " + this.code + " " + (this - 'a'+1))
return (this -'a'+1)
}
if(this in ('A'..'Z')){
// println("big " +this + " " + this.code + " "+ (this -'A'+27))
return (this -'A'+27)
}
return -1
}
} | 0 | Kotlin | 0 | 0 | 400fe1b693bc186d6f510236f121167f7cc1ab76 | 1,998 | advent-of-code-2022 | Apache License 2.0 |
src/Day21.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | const val ROOT_MONKEY = "root"
const val HUMN_MONKEY = "humn"
data class Equation(val n1: String, val operation: Char, val n2: String)
fun main() {
fun getMonkeys(input: List<List<String>>): Pair<MutableMap<String, Long>, MutableMap<String, Equation>> {
val numberMonkeys = mutableMapOf<String, Long>()
val equationMonkeys = mutableMapOf<String, Equation>()
for (line in input) {
val name = line.first()
if (line.last().toIntOrNull() != null) {
numberMonkeys[name] = line.last().toLong()
} else {
val (n1, operation, n2) = line.last().split(" ")
equationMonkeys[name] = Equation(n1, operation.single(), n2)
}
}
return Pair(numberMonkeys, equationMonkeys)
}
fun calculateEquation(numberMonkeys: MutableMap<String, Long>, equation: Equation): Long {
val n1 = numberMonkeys[equation.n1]!!
val n2 = numberMonkeys[equation.n2]!!
return when (equation.operation) {
'+' -> n1 + n2
'-' -> n1 - n2
'*' -> n1 * n2
'/' -> n1 / n2
else -> if (n1 == n2) 1L else 0L
}
}
/**
* Transfers equationMonkeys to numberMonkeys. Returns true if numberMonkeys for ROOT_MONKEY's equation are found.
*/
fun addNumberMonkeysAndFindRootMonkey(equationMonkeys: MutableMap<String, Equation>, numberMonkeys: MutableMap<String, Long>): Boolean {
val transferredMonkeys = mutableListOf<String>()
for (monkey in equationMonkeys.entries) {
val name = monkey.key
val equation = monkey.value
if (numberMonkeys.keys.contains(equation.n1) && numberMonkeys.keys.contains(equation.n2)) {
if (name == ROOT_MONKEY) {
return true
}
numberMonkeys[name] = calculateEquation(numberMonkeys, equation)
transferredMonkeys.add(name)
}
}
for (name in transferredMonkeys) {
equationMonkeys.remove(name)
}
return false
}
fun part1(input: List<List<String>>): Long {
val (numberMonkeys, equationMonkeys) = getMonkeys(input)
while (true) {
if (addNumberMonkeysAndFindRootMonkey(equationMonkeys, numberMonkeys)) break
}
return calculateEquation(numberMonkeys, equationMonkeys[ROOT_MONKEY]!!)
}
fun part2(input: List<List<String>>): Long {
var humnNumber = 1L
var step = 1000000000000
var humnNumberGoesUp = true
var originalEvaluationN1BiggerThanN2 = false
while (true) {
val (numberMonkeys, equationMonkeys) = getMonkeys(input)
numberMonkeys[HUMN_MONKEY] = humnNumber
while (true) {
if (addNumberMonkeysAndFindRootMonkey(equationMonkeys, numberMonkeys)) break
}
val n1 = numberMonkeys[equationMonkeys[ROOT_MONKEY]!!.n1]!!
val n2 = numberMonkeys[equationMonkeys[ROOT_MONKEY]!!.n2]!!
if (n1 == n2) break // If n1 equals n2, the correct humnNumber is found.
// Binary Search
if (humnNumber == 1L) {
originalEvaluationN1BiggerThanN2 = n1 > n2
humnNumber += step
} else if (n1 > n2 == originalEvaluationN1BiggerThanN2) {
if (!humnNumberGoesUp) {
humnNumberGoesUp = true
step /= 10
}
humnNumber += step
} else {
if (humnNumberGoesUp) {
humnNumberGoesUp = false
step /= 10
}
humnNumber -= step
}
}
return humnNumber
}
val input = readInputAsStrings("Day21")
.map{it.split(": ")}
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 3,934 | AoC2022 | Apache License 2.0 |
src/main/kotlin/day13.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.chunks
import shared.getText
fun main() {
val input = getText("day13.txt")
println(day13A(input))
println(day13B(input))
}
fun day13A(input: String): Int {
var sum = 0
input.chunks().forEachIndexed { index, s ->
val left = Packet(s.lines().first())
val right = Packet(s.lines().last())
if(left.compareTo(right) == -1) sum += index + 1
}
return sum
}
fun day13B(input: String): Int {
val d1 = Packet("[[2]]")
val d2 = Packet("[[6]]")
val packets = input.lines().filter { it.isNotEmpty() }.map { Packet(it) } + d1 + d2
val sortedPackets = packets.sorted()
return (sortedPackets.indexOf(d1) + 1) * (sortedPackets.indexOf(d2) + 1)
}
private class Packet(val value: String): Comparable<Packet>{
override fun compareTo(other: Packet): Int {
var left = value
var right = other.value
while (true) {
when {
left.isInt() && right.isInt() -> {
return left.toInt().compareTo(right.toInt())
}
!left.isInt() && !right.isInt() -> {
val firstLeft = left.popFirst { newValue -> left = newValue }
val firstRight = right.popFirst { newValue -> right = newValue }
if (firstLeft == null && firstRight == null) return 0
if (firstLeft == null) return -1
if (firstRight == null) return 1
val compareFirst = firstLeft.compareTo(firstRight)
if (compareFirst != 0) return compareFirst
}
left.isInt() -> {
left = "[$left]"
}
right.isInt() -> {
right = "[$right]"
}
}
}
}
private fun String.popFirst(update: (newValue: String) -> Unit): Packet? {
if(this == "[]") return null
val commaIndex = firstRootComma()
if(commaIndex == null) {
val firstPacket = Packet(substring(1, length-1))
update(removeRange(1, length-1))
return firstPacket
}
val firstPacket = Packet(substring(1, commaIndex))
update(removeRange(1, commaIndex+1))
return firstPacket
}
private fun String.firstRootComma(): Int? {
for((i,c) in withIndex()){
if(c == ',' && take(i).count { it == '[' } - 1 == take(i).count { it == ']' }){
return i
}
}
return null
}
private fun String.isInt() = toIntOrNull() != null
} | 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 2,610 | AdventOfCode2022 | MIT License |
src/main/kotlin/cc/stevenyin/leetcode/_0026_RemoveDuplicatesfromSortedArray.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.leetcode
/**
* https://leetcode.com/problems/remove-duplicates-from-sorted-array/
* Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once.
* The relative order of the elements should be kept the same.
* Since it is impossible to change the length of the array in some languages,
* you must instead have the result be placed in the first part of the array nums.
* More formally, if there are k elements after removing the duplicates,
* then the first k elements of nums should hold the final result.
* It does not matter what you leave beyond the first k elements.
* Return k after placing the final result in the first k slots of nums.
* Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
[1, 1]
[1, _]
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
*/
class _0026_RemoveDuplicatesfromSortedArray {
fun removeDuplicates(nums: IntArray): Int {
if (nums.size <= 1) return nums.size
var p = 1
for (idx in 1 until nums.size) {
if (nums[idx] != nums[idx - 1]) {
nums[p] = nums[idx]
p ++
}
}
return p
}
}
fun main() {
val solution = _0026_RemoveDuplicatesfromSortedArray()
val nums = intArrayOf(0,0,1,1,1,2,2,3,3,4)
val expectedNums = intArrayOf(0,1,2,3,4)
val k = solution.removeDuplicates(nums)
assert(k == expectedNums.size)
for (i in 0 until k) {
assert(nums[i] == expectedNums[i])
}
}
| 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 2,647 | kotlin-demo-code | MIT License |
src/Day11.kt | SebastianHelzer | 573,026,636 | false | {"Kotlin": 27111} |
data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: (Long) -> Boolean,
val testDivisor: Int,
val onTrueMonkeyIndex: Int,
val onFalseMonkeyIndex: Int,
)
object OperationFunctionParser {
fun parse(operation: String): Function1<Long, Long> {
val (p0, command, p1) = operation.trim().split(' ')
return { old ->
val start = if(p0 == "old") {
old
} else {
p0.toLong()
}
val end = if(p1 == "old") {
old
} else {
p1.toLong()
}
when(command) {
"*" -> start * end
"+" -> start + end
else -> error("unknown command: $command")
}
}
}
}
object TestFunctionParser {
fun parse(input: String): Pair<Int,Function1<Long, Boolean>> {
val divisor = input.takeLastWhile { it.isDigit() }.toInt()
return divisor to { value -> value % divisor == 0L }
}
}
fun main() {
fun parseInput(input: List<String>): List<Monkey> {
return input.chunked(7).map {
val items = it[1].filter { it.isWhitespace() || it.isDigit() }.split(" ").mapNotNull { it.toLongOrNull() }
val operation = it[2].substringAfter('=')
val test = it[3].substringAfter(':')
val onTrueIndex = it[4].takeLastWhile { it.isDigit() }.toInt()
val onFalseIndex = it[5].takeLastWhile { it.isDigit() }.toInt()
val (divisor, testFunction) = TestFunctionParser.parse(test)
Monkey(
items.toMutableList(),
OperationFunctionParser.parse(operation),
testFunction,
divisor,
onTrueIndex,
onFalseIndex,
).also {
println(it)
println(operation)
println(test)
}
}
}
fun simulateRound(input: List<Monkey>, onInspect: (Int, Int, Long) -> Long) {
input.forEachIndexed { index, monkey ->
monkey.items.replaceAll {
val newValue = monkey.operation(it)
val storedWorry = onInspect(index, monkey.testDivisor, newValue)
storedWorry
}
monkey.items.forEach {
if(monkey.test(it)) {
input[monkey.onTrueMonkeyIndex].items.add(it)
} else {
input[monkey.onFalseMonkeyIndex].items.add(it)
}
}
monkey.items.clear()
}
}
fun part1(input: List<String>): Int {
val monkeys = parseInput(input)
val inspectionCount = MutableList(monkeys.size) { 0 }
repeat(20) {
simulateRound(monkeys) { value, _, newValue -> inspectionCount[value]++; newValue / 3 }
}
val greatestTwo = inspectionCount.sorted().takeLast(2)
val (nextToTop, top) = greatestTwo
return top * nextToTop
}
fun part2(input: List<String>): Long {
val monkeys = parseInput(input)
val inspectionCount = MutableList(monkeys.size) { 0 }
val roundsToPrint = (listOf(1,20) + (1000 until 10001 step 1000))
val gcm = monkeys.map { it.testDivisor }.fold(1) { acc, i -> acc * i }
println("gcm=$gcm")
repeat(10000) {
simulateRound(monkeys) { monkeyIndex, divisor, value ->
inspectionCount[monkeyIndex]++
if(value > gcm) { value % gcm } else value
}
if((it + 1) in roundsToPrint) {
println("After round ${it + 1}")
inspectionCount.forEachIndexed { index, i ->
println("Monkey $index inspected items $i times")
}
}
}
val greatestTwo = inspectionCount.sorted().takeLast(2)
val (nextToTop, top) = greatestTwo
println("top=$top nextToTop=$nextToTop")
return top.toLong() * nextToTop.toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
checkEquals(10605, part1(testInput))
checkEquals(2713310158, part2(testInput))
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e48757626eb2fb5286fa1c59960acd4582432700 | 4,388 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/24/Day24.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`24`
import java.util.PriorityQueue
import readInput
import utils.doWithPrintedTime
data class Point(
val x: Int,
val y: Int
)
enum class Direction { LEFT, RIGHT, BOTTOM, TOP }
/**
* Sealed class representing either Blizzard or Wall
*/
sealed class Structure {
abstract val position: Point
data class Blizzard(
override val position: Point,
val direction: Direction
) : Structure()
data class Wall(
override val position: Point,
) : Structure()
}
data class State(
val minute: Int,
val ourPosition: Point,
val currentGrid: Set<Structure>,
) : Comparable<State> {
override fun compareTo(other: State): Int {
return compareValuesBy(this, other) { it.minute }
}
}
private fun parseInput(input: List<String>): Set<Structure> {
return input.mapIndexed { y, line ->
line.split("")
.filter { it.isNotEmpty() }
.mapIndexedNotNull { x, cell ->
if (cell == "#") return@mapIndexedNotNull Structure.Wall(Point(x, y))
val direction = when (cell) {
">" -> Direction.RIGHT
"<" -> Direction.LEFT
"^" -> Direction.TOP
"v" -> Direction.BOTTOM
"." -> null
else -> error("Illegal state")
}
if (direction == null) {
null
} else {
Structure.Blizzard(
position = Point(x, y),
direction = direction
)
}
}
}
.flatten()
.toSet()
}
fun Point.calculateNewPosition(
direction: Direction
): Point {
return when (direction) {
Direction.LEFT -> Point(y = y, x = x - 1)
Direction.RIGHT -> Point(y = y, x = x + 1)
Direction.BOTTOM -> Point(y = y + 1, x = x)
Direction.TOP -> Point(y = y - 1, x = x)
}
}
/**
* Helper method to print grid of all points in current set
*/
fun Set<Structure>.printGrid() {
val minX = minOf { it.position.x }
val minY = minOf { it.position.y }
val maxX = maxOf { it.position.x }
val maxY = maxOf { it.position.y }
(minY..maxY).forEach { y ->
(minX..maxX).forEach { x ->
val cells = filter { Point(x, y) == it.position }
val whatToPrint = when {
cells.isEmpty() -> "."
cells.size == 1 -> when (val cell = cells.first()) {
is Structure.Blizzard -> when (cell.direction) {
Direction.LEFT -> "<"
Direction.RIGHT -> ">"
Direction.BOTTOM -> "v"
Direction.TOP -> "^"
}
is Structure.Wall -> "#"
}
else -> cells.size
}
print(whatToPrint)
}
println()
}
println()
}
fun Set<Point>.calculateEdgePosition(
currentPoint: Point,
direction: Direction
): Point {
val minX = minOf { it.x }
val minY = minOf { it.y }
val maxX = maxOf { it.x }
val maxY = maxOf { it.y }
return when (direction) {
Direction.LEFT -> currentPoint.copy(x = maxX - 1)
Direction.RIGHT -> currentPoint.copy(x = minX + 1)
Direction.BOTTOM -> currentPoint.copy(y = minY + 1)
Direction.TOP -> currentPoint.copy(y = maxY - 1)
}
}
fun processBlizzard(
wallPoints: Set<Point>,
point: Point,
direction: Direction
): Point {
val proposedPosition = point.calculateNewPosition(direction)
return if (wallPoints.contains(proposedPosition)) {
wallPoints.calculateEdgePosition(point, direction)
} else {
proposedPosition
}
}
fun processOurPosition(
wallPoints: Set<Point>,
point: Point,
direction: Direction
): Point? {
val proposedPosition = point.calculateNewPosition(direction)
return if (wallPoints.contains(proposedPosition)) {
null
} else {
proposedPosition
}
}
fun round(
wallPoints: Set<Point>,
grid: Set<Structure>,
): Set<Structure> {
val resultSet = mutableSetOf<Structure>()
grid.forEach {
when (it) {
is Structure.Blizzard -> {
val newPosition = processBlizzard(wallPoints, it.position, it.direction)
resultSet.add(Structure.Blizzard(newPosition, it.direction))
}
is Structure.Wall -> {
resultSet.add(it)
}
}
}
return resultSet
}
private val directions = Direction.values()
fun Point.neighbours(
maxY: Int,
wallPoints: Set<Point>
): Set<Point> {
return directions
.mapNotNull { processOurPosition(wallPoints, this, it) }
.filter { it.y in 0..maxY }
.toSet()
.let { it + this }
}
typealias StateCache = MutableMap<Int, Set<Structure>>
fun StateCache.cacheAndGet(
wallPoints: Set<Point>,
currentState: State
): Set<Structure> {
val newGrid = if (this.contains(currentState.minute)) {
this[currentState.minute]!!
} else {
val calculatedRound = round(wallPoints, currentState.currentGrid)
this[currentState.minute] = calculatedRound
calculatedRound
}
return newGrid
}
typealias BlizzardCache = MutableMap<Int, Set<Point>>
private fun BlizzardCache.cacheAndGetBlizzards(
newGrid: Set<Structure>,
currentState: State
): Set<Point> {
return if (contains(currentState.minute)) {
this[currentState.minute]!!
} else {
val calculatedRound = newGrid.blizzardPoints()
this[currentState.minute] = calculatedRound
calculatedRound
}
}
@SuppressWarnings("all")
fun solve(
cachedStates: StateCache,
blizzardCache: BlizzardCache,
initialTime: Int,
initialGrid: Set<Structure>,
initialPoint: Point,
destination: Point
): Int {
val wallPoints: Set<Point> = initialGrid.wallPoints()
val maxY = wallPoints.maxOf { it.y }
val queue = PriorityQueue<State>().also {
it.add(
State(
minute = initialTime,
ourPosition = initialPoint,
currentGrid = initialGrid
)
)
}
val visitedStates = mutableSetOf<State>()
var resultTime = Int.MAX_VALUE
while (queue.isNotEmpty()) {
val currentState = queue.remove()
if (currentState in visitedStates) continue
visitedStates.add(currentState)
if (currentState.ourPosition == destination) {
resultTime = minOf(currentState.minute, resultTime)
continue
}
if (currentState.minute > resultTime) continue
val newGrid = cachedStates.cacheAndGet(wallPoints, currentState)
val blizzardPoints = blizzardCache.cacheAndGetBlizzards(newGrid, currentState)
val nextStates = currentState.ourPosition
.neighbours(maxY, wallPoints)
.filter { it !in blizzardPoints }
.map {
State(
minute = currentState.minute + 1,
ourPosition = it,
currentGrid = newGrid
)
}
.toList()
queue.addAll(nextStates)
}
return resultTime
}
fun Set<Structure>.wallPoints(): Set<Point> {
return asSequence()
.filterIsInstance<Structure.Wall>()
.map { it.position }
.toSet()
}
fun Set<Structure>.blizzardPoints(): Set<Point> {
return asSequence()
.filterIsInstance<Structure.Blizzard>()
.map { it.position }
.toSet()
}
fun main() {
fun part1(input: List<String>): Int {
val parsedInput = parseInput(input)
val cachedStates: StateCache = mutableMapOf()
val cachedBlizzards: BlizzardCache = mutableMapOf()
val walls = parsedInput.wallPoints()
val maxX = walls.maxOf { it.x }
val maxY = walls.maxOf { it.y }
val initialPosition = Point(1, 0)
val destinationPosition = Point(maxX - 1, maxY)
return solve(
cachedStates = cachedStates,
blizzardCache = cachedBlizzards,
initialTime = 0,
initialGrid = parsedInput,
initialPoint = initialPosition,
destination = destinationPosition
)
}
fun part2(input: List<String>): Int {
val parsedInput = parseInput(input)
val cachedStates: StateCache = mutableMapOf()
val cachedBlizzards: BlizzardCache = mutableMapOf()
val walls = parsedInput.wallPoints()
val maxX = walls.maxOf { it.x }
val maxY = walls.maxOf { it.y }
val initialPosition = Point(1, 0)
val destinationPosition = Point(maxX - 1, maxY)
val time1 = solve(
cachedStates = cachedStates,
blizzardCache = cachedBlizzards,
initialTime = 0,
initialGrid = parsedInput,
initialPoint = initialPosition,
destination = destinationPosition
)
val time2 = solve(
cachedStates = cachedStates,
blizzardCache = cachedBlizzards,
initialTime = time1,
initialGrid = cachedStates[time1]!!,
initialPoint = destinationPosition,
destination = initialPosition,
)
val time3 = solve(
cachedStates = cachedStates,
blizzardCache = cachedBlizzards,
initialTime = time2,
initialGrid = cachedStates[time2]!!,
initialPoint = initialPosition,
destination = destinationPosition
)
return time3
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day24_test")
val part1Test = doWithPrintedTime("Test 1") { part1(testInput) }
val part2Test = doWithPrintedTime("Test 2") { part2(testInput) }
check(part1Test == 18)
check(part2Test == 54)
val input = readInput("Day24")
doWithPrintedTime("Part 1") { part1(input) }
doWithPrintedTime("Part 2") { part2(input) }
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 10,228 | KotlinAdventOfCode | Apache License 2.0 |
src/main/kotlin/de/takeweiland/aoc2019/day3/Day3.kt | diesieben07 | 226,095,130 | false | null | package de.takeweiland.aoc2019.day3
import de.takeweiland.aoc2019.inputReader
import java.io.FileWriter
import java.util.*
import kotlin.Comparator
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.math.abs
private data class Position(val x: Int, val y: Int) {
companion object {
val origin = Position(0, 0)
}
operator fun plus(movement: Movement) = Position(
x = this.x + movement.direction.xMul * movement.length,
y = this.y + movement.direction.yMul * movement.length
)
fun manhattan(other: Position): Int = abs(this.x - other.x) + abs(this.y - other.y)
override fun toString(): String = "($x,$y)"
}
private class OrderByDistanceTo(private val reference: Position) : Comparator<Position> {
override fun compare(o1: Position, o2: Position): Int {
return reference.manhattan(o1).compareTo(reference.manhattan(o2))
}
}
private data class Movement(val direction: Direction, val length: Int) {
constructor(spec: String) : this(
direction = enumValueOf<Direction>(spec[0].toString()),
length = spec.substring(1).toInt()
)
fun asSingleSteps(): List<Movement> {
return Collections.nCopies(length, copy(length = 1))
}
companion object {
fun list(spec: String) = spec.split(',').map { Movement(it) }
}
}
private enum class Direction(val xMul: Int = 0, val yMul: Int = 0) {
U(yMul = 1), D(yMul = -1), L(xMul = -1), R(xMul = 1)
}
private fun readInput(): List<List<Movement>> {
return inputReader(3).useLines { lines ->
lines.mapTo(mutableListOf()) { line ->
Movement.list(line)
}
}
}
private fun findIntersections(directions: List<List<Movement>>): SortedSet<Position> {
val intersections = TreeSet(OrderByDistanceTo(Position.origin))
val seenPositions = HashMap<Position, MutableSet<Int>>()
val stepsToPositions = HashMap<Position, IntArray>()
val map = HashMap<Position, Char>()
map[Position.origin] = 'o'
for ((index, lineDirections) in directions.withIndex()) {
var pos = Position.origin
var stepCount = 0
for (dir in lineDirections) {
for (step in dir.asSingleSteps()) {
pos += step
stepCount++
if (pos != Position.origin) {
val prevSteps = stepsToPositions.getOrPut(pos) { IntArray(directions.size) }
if (prevSteps[index] == 0) prevSteps[index] = stepCount
val set = seenPositions.getOrPut(pos, ::HashSet)
set += index
if (set.size > 1) {
intersections += pos
map[pos] = 'X'
} else {
map[pos] = '0' + index
}
}
}
}
}
// val minX = map.keys.map { it.x }.min()!!
// val maxX = map.keys.map { it.x }.max()!!
// val minY = map.keys.map { it.y }.min()!!
// val maxY = map.keys.map { it.y }.max()!!
//
// FileWriter("map.txt").buffered().use { writer ->
// for (y in maxY downTo minY) {
// for (x in minX..maxX) {
// writer.write((map[Position(x, y)] ?: '.').toInt())
// }
// writer.newLine()
// }
// }
val bestIntersection = intersections.map { stepsToPositions[it]?.sum() ?: Int.MAX_VALUE }.min()
println(bestIntersection)
return intersections
}
fun main() {
val directions = readInput()
// val directions = listOf(
// Movement.list("R75,D30,R83,U83,L12,D49,R71,U7,L72"),
// Movement.list("U62,R66,U55,R34,D71,R55,D58,R83")
// )
val intersections = findIntersections(directions)
println(intersections)
println(intersections.firstOrNull()?.manhattan(Position.origin))
}
| 0 | Kotlin | 0 | 0 | 2b778201213941de7f37dbc18864a04ce3601f32 | 3,867 | advent-of-code-2019 | MIT License |
src/Day05.kt | 3n3a-archive | 573,389,832 | false | {"Kotlin": 41221, "Shell": 534} |
data class Instruction(val amount: Int, val from: Int, val to: Int)
data class Day05PreprocessResult(val containers: MutableList<MutableList<String>>, val instructions: List<Instruction>)
fun Day05() {
fun preprocess(input: String): Day05PreprocessResult {
val containersRegex = "\\[(.)\\]".toRegex()
val instructionsRegex = "move.(.*).from.(.*).to.(.*)".toRegex()
val (containers, instructions) = input.split("\n\n")
// get storage containers
val matchedContainers = containers
.split("\n")
.dropLast(1)
.map {
containersRegex
.findAll(it)
.map {
it2 ->
val pos = it2.groups[0]!!.range
val value = it2.groupValues[0][1].toString()
mapOf<IntRange, String>(pos to value)
}
.toMutableList()
}
.flatten()
.toMutableList()
.groupBy(keySelector = { it.keys }, valueTransform = { it.values })
.map { Pair(it.key.toList()[0], it.value) }
.sortedBy { it.first.toList().sum() }
.map {
it.second.reversed()
}
.map {
it.map {
it2 -> it2.toList()[0]
}
.toMutableList()
}
.toMutableList()
//println(matchedContainers)
// get instructions
val matchedInstructions = instructions
.split("\n")
.map {
instructionsRegex
.findAll(it)
.map { it2 ->
val amount = Integer.parseInt(it2.groupValues[1])
val from = Integer.parseInt(it2.groupValues[2])
val to = Integer.parseInt(it2.groupValues[3])
val instruction = Instruction(amount, from, to)
instruction
}
.toList()[0]
}
.toList()
/*for (instruction in matchedInstructions) {
val (amount, from, to) = instruction()
println("$amount $from $to")
}*/
return Day05PreprocessResult(matchedContainers, matchedInstructions)
}
fun getTopMostContainers(containers: MutableList<MutableList<String>>): List<String> {
return containers
.map {
it.last()
}
.toList()
}
fun part1(input: String): String {
var (containers, instructions) = preprocess(input)
//println(containers)
for (instruction in instructions) {
val (amount, from, to) = instruction
val containersToMove = containers[from - 1].takeLast(amount).reversed()
containers[from - 1] = containers[from - 1].dropLast(amount).toMutableList()
containers[to - 1].addAll(containersToMove)
//println("move $amount from $from to $to")
//println(containers)
}
//println(containers)
return getTopMostContainers(containers).joinToString("")
}
fun part2(input: String): String {
var (containers, instructions) = preprocess(input)
//println(containers)
for (instruction in instructions) {
val (amount, from, to) = instruction
val containersToMove = containers[from - 1].takeLast(amount)
containers[from - 1] = containers[from - 1].dropLast(amount).toMutableList()
containers[to - 1].addAll(containersToMove)
//println("move $amount from $from to $to")
//println(containers)
}
//println(containers)
return getTopMostContainers(containers).joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInputToText("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInputToText("Day05")
println("1: " + (part1(input) == "QNHWJVJZW"))
println("2: " + (part2(input) == "BPCZJLFJW"))
}
| 0 | Kotlin | 0 | 0 | fd25137d2d2df0aa629e56981f18de52b25a2d28 | 4,246 | aoc_kt | Apache License 2.0 |
src/Day13.kt | TheGreatJakester | 573,222,328 | false | {"Kotlin": 47612} | package day13
import utils.forForEach
import utils.readInputAsText
import utils.runSolver
import utils.string.asLines
import utils.string.asParts
private typealias SolutionType = Int
private const val defaultSolution = 0
private const val dayNumber: String = "13"
private val testSolution1: SolutionType? = 13
private val testSolution2: SolutionType? = 140
sealed class Member : Comparable<Member>
private data class ListMember(val list: MutableList<Member> = mutableListOf()) : MutableList<Member> by list, Member() {
override fun compareTo(other: Member): Int {
if (other is IntMember) {
return compareTo(other.asListMember())
} else if (other is ListMember) {
for (i in list.indices) {
val here = list[i]
val there = other.list.getOrNull(i) ?: return 1
val comparison = here.compareTo(there)
if (comparison != 0) {
return comparison
}
}
return list.size - other.list.size
}
throw Exception("Shouldn't")
}
}
private data class IntMember(val value: Int) : Member() {
fun asListMember(): ListMember {
return ListMember(mutableListOf(this))
}
override fun compareTo(other: Member): Int {
if (other is IntMember) {
return this.value - other.value
} else if (other is ListMember) {
return this.asListMember().compareTo(other)
}
throw Exception("Shouldn't")
}
}
private typealias PacketPair = Pair<ListMember, ListMember>
private fun PacketPair.isValid(): Boolean = first < second
private fun parsePairs(input: String): List<PacketPair> {
val pairString = input.asParts()
return pairString.map(::parsePair)
}
private fun parsePair(input: String): PacketPair {
val (left, right) = input.asLines()
return parsePacket(left) to parsePacket(right)
}
private fun parsePacket(input: String): ListMember {
val deque = ArrayDeque<ListMember>()
var curNumberString = ""
var out = ListMember()
fun pushNumber() {
if (curNumberString.isEmpty()) return
val number = curNumberString.toInt()
deque.first().add(IntMember(number))
curNumberString = ""
}
fun startNew() {
deque.add(0, ListMember())
}
fun end() {
pushNumber()
val oldFirst = deque.removeFirst()
deque.firstOrNull()?.add(oldFirst)
out = oldFirst
}
input.forEach {
when (it) {
'[' -> startNew()
']' -> end()
',' -> pushNumber()
else -> curNumberString += it
}
}
return out
}
private fun part1(input: String): SolutionType {
val pairs = parsePairs(input)
// val four = pairs[3]
// four.isValid()
val values = pairs.mapIndexed { index, pair ->
if (pair.isValid()) index + 1 else 0
}
return values.sum()
//6499 too high
return defaultSolution
}
private fun part2(input: String): SolutionType {
val packets = input.replace("\n\n", "\n")
.asLines().map(::parsePacket).toMutableList()
val div1 = ListMember(mutableListOf(ListMember(mutableListOf(IntMember(2)))))
val div2 = ListMember(mutableListOf(ListMember(mutableListOf(IntMember(6)))))
packets.add(div1)
packets.add(div2)
val sortedPackets = packets.sorted()
val di1 = sortedPackets.indexOf(div1) + 1
val di2 = sortedPackets.indexOf(div2) + 1
return di1 * di2
}
fun main() {
runSolver("Test 1", readInputAsText("Day${dayNumber}_test"), testSolution1, ::part1)
runSolver("Part 1", readInputAsText("Day${dayNumber}"), null, ::part1)
runSolver("Test 2", readInputAsText("Day${dayNumber}_test"), testSolution2, ::part2)
runSolver("Part 2", readInputAsText("Day${dayNumber}"), null, ::part2)
}
| 0 | Kotlin | 0 | 0 | c76c213006eb8dfb44b26822a44324b66600f933 | 3,883 | 2022-AOC-Kotlin | Apache License 2.0 |
src/Day03.kt | pedroldk | 573,424,273 | false | {"Kotlin": 4625} | fun main() {
fun findCommonItem(rucksack: String): Char {
val compartments = rucksack.substring(0 until (rucksack.length / 2)) to rucksack.substring(rucksack.length / 2)
return compartments.first.toCharArray().first { compartments.second.contains(it) }
}
fun findBadgeItem(rucksack: List<String>): Char {
return rucksack.first().toCharArray().first { rucksack[1].contains(it) && rucksack[2].contains(it) }
}
val charString = "0abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun part1(input: List<String>): Int {
return input.map { findCommonItem(it) }.sumOf { charString.indexOf(it) }
}
fun part2(input: List<String>): Int {
return input.chunked(3).map { findBadgeItem(it) }.sumOf { charString.indexOf(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
//check(part1(testInput) == 15)
//check(part2(testInput) == 45000)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 68348bbfc308d257b2d02fa87dd241f8f584b444 | 1,079 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day07.kt | RandomUserIK | 572,624,698 | false | {"Kotlin": 21278} | data class Directory(
val name: String,
val children: MutableMap<String, Directory> = hashMapOf(),
var filesSize: Int = 0,
) {
val dirSize: Int
get() = filesSize + children.values.sumOf { it.dirSize }
}
fun List<String>.toFileSystem(): Directory {
val callStack = ArrayDeque<Directory>().also { it.add(Directory("/")) }
forEach { line ->
when {
line == "$ ls" -> {}
line == "$ cd /" -> callStack.removeIf { it.name != "/" }
line == "$ cd .." -> callStack.removeFirst()
line.startsWith("dir") -> {}
line.startsWith("$ cd") -> {
val currentDir = callStack.first()
val name = line.substringAfter("$ cd ")
callStack.addFirst(currentDir.children.getOrPut(name) { Directory(name) })
}
else -> {
callStack.first().filesSize += line.split(" ").first().toInt()
}
}
}
return callStack.last()
}
fun main() {
fun part1(input: List<String>): Int {
fun findDirectories(dir: Directory): List<Directory> =
dir.children.values.filter { it.dirSize <= 100000 } + dir.children.values.flatMap { findDirectories(it) }
val root = input.toFileSystem()
return findDirectories(root).sumOf { it.dirSize }
}
fun part2(input: List<String>): Int {
fun findDirectories(dir: Directory, diff: Int): List<Directory> =
dir.children.values.filter { it.dirSize >= diff } + dir.children.values.flatMap {
findDirectories(
it,
diff
)
}
val filesystemSize = 70000000
val root = input.toFileSystem()
val unused = filesystemSize - root.dirSize
val neededSpace = 30000000 - unused
return findDirectories(root, neededSpace).minOf { it.dirSize }
}
val input = readInput("inputs/day07_input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | f22f10da922832d78dd444b5c9cc08fadc566b4b | 1,704 | advent-of-code-2022 | Apache License 2.0 |
src/main/day10/day10.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day10
import readInput
fun main() {
val input = readInput("main/day10/Day10")
println(part1(input))
part2(input)
}
fun part1(input: List<String>): Int {
val cycles = input.toCycles()
val interestingCycles = listOf(20, 60, 100, 140, 180, 220)
return interestingCycles.sumOf { cycles[it - 1] * it }
}
fun part2(input: List<String>) {
val cycleMap = input.toCycles()
val crt = cycleMap.mapIndexed { index, register ->
val sprite = register - 1..register + 1
if (index % 40 in sprite) "#" else " "
}
crt.forEachIndexed { index, s ->
print(s)
if (index % 40 == 39) println()
}
}
private fun List<String>.toCycles(): List<Int> {
var x = 1
val cycles = mutableListOf<Int>()
forEach {
if (it.startsWith("noop")) {
cycles.add(x)
} else {
repeat(2) { cycles.add(x) }
x += it.split(" ").last().toInt()
}
}
return cycles
}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 984 | aoc-2022 | Apache License 2.0 |
advent-of-code-2022/src/Day06.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | fun main() {
val testInput = readInput("Day06_test")
val input = readInput("Day06")
check(part1(testInput) == 7)
println("Part 1: " + part1(input))
check(part2(testInput) == 19)
println("Part 2: " + part2(input))
}
private fun part1(input: String): Int = findStartMessageMarker(input, windowSize = 4)
private fun part2(input: String): Int = findStartMessageMarker(input, windowSize = 14)
// Time - O(N), Space - O(M)
// where N - number of chars in input, M - window size
private fun findStartMessageMarker(input: String, windowSize: Int): Int {
// Count of each character in the window
val counts = mutableMapOf<Char, Int>()
// Init window with first N chars
for (i in 0 until windowSize) counts.change(input[i], +1)
// Remove most left character from window, and add the char next after window
for (prevIndex in 0 until input.length - windowSize) {
if (counts.size == windowSize) return prevIndex + windowSize
counts.change(input[prevIndex], -1)
counts.change(input[prevIndex + windowSize], +1)
}
error("Where is the start-of-message marker?")
}
// Changes count for the given [key]. Removes it from the map if result value is 0
private fun MutableMap<Char, Int>.change(key: Char, diff: Int) {
this[key] = this.getOrDefault(key, 0) + diff
if (this[key] == 0) this.remove(key)
}
private fun readInput(name: String) = readText(name)
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 1,432 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Solution18.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import adventOfCode.util.Point2D
import adventOfCode.util.plus
import adventOfCode.util.times
import kotlin.math.abs
typealias LagoonInstruction = PairOf<Pair<Point2D, Int>>
object Solution18 : Solution<List<LagoonInstruction>>(AOC_YEAR, 18) {
private val directionMap = mapOf(
"R" to (0 to 1),
"D" to (1 to 0),
"L" to (0 to -1),
"U" to (-1 to 0),
)
private val hexDirectionMap = mapOf(
'0' to (0 to 1),
'1' to (1 to 0),
'2' to (0 to -1),
'3' to (-1 to 0),
)
override fun getInput(handler: InputHandler) = handler.getInput("\n").map { line ->
val (d, l, h) = line.split(' ')
val pair1 = directionMap.getValue(d) to l.toInt()
val hex = h.trim('(', '#', ')')
val pair2 = hexDirectionMap.getValue(hex.last()) to hex.take(hex.length - 1).toInt(16)
pair1 to pair2
}
private val Iterable<Point2D>.shoelaceArea
get() = abs(this.zip(this.drop(1) + this.take(1)).sumOf { (p1, p2) ->
p1.first.toLong() * p2.second - p1.second.toLong() * p2.first
}) / 2
private fun getLagoonVolume(instructions: Iterable<Pair<Point2D, Int>>): Long {
val vertices =
listOf(0 to 0) + instructions.runningFold(0 to 0) { pos, (direction, distance) -> pos + direction * distance }
val pathLength = instructions.sumOf { it.second }
return vertices.shoelaceArea + pathLength / 2 + 1
}
override fun solve(input: List<LagoonInstruction>): PairOf<Long> {
val ans1 = getLagoonVolume(input.map { it.first })
val ans2 = getLagoonVolume(input.map { it.second })
return ans1 to ans2
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 1,796 | Advent-of-Code-2023 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximalPathQuality.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import kotlin.math.max
/**
* 2065. Maximum Path Quality of a Graph
* @see <a href="https://leetcode.com/problems/maximum-path-quality-of-a-graph/">Source</a>
*/
fun interface MaximalPathQuality {
operator fun invoke(values: IntArray, edges: Array<IntArray>, maxTime: Int): Int
}
class MaximalPathQualityDFS : MaximalPathQuality {
override operator fun invoke(values: IntArray, edges: Array<IntArray>, maxTime: Int): Int {
if (values.isEmpty()) return 0
if (edges.isEmpty()) return 0
if (edges.first().isEmpty()) return 0
val n: Int = values.size
val adj: Array<MutableList<IntArray>> = Array(n) { mutableListOf() }
for (i in 0 until n) {
adj[i] = LinkedList()
}
for (e in edges) {
val i = e[0]
val j = e[1]
val t = e[2]
adj[i].add(intArrayOf(j, t))
adj[j].add(intArrayOf(i, t))
}
val res = IntArray(1)
val seen = IntArray(n)
seen[0]++
dfs(adj, 0, values, maxTime, seen, res, values[0])
return res[0]
}
private fun dfs(
adj: Array<MutableList<IntArray>>,
src: Int,
values: IntArray,
maxTime: Int,
seen: IntArray,
res: IntArray,
sum: Int,
) {
if (0 == src) {
res[0] = max(res[0], sum)
}
if (0 > maxTime) return
for (data in adj[src]) {
val dst = data[0]
val t = data[1]
if (0 > maxTime - t) continue
seen[dst]++
dfs(adj, dst, values, maxTime - t, seen, res, sum + if (1 == seen[dst]) values[dst] else 0)
seen[dst]--
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,384 | kotlab | Apache License 2.0 |
2022/Day09/problems.kt | moozzyk | 317,429,068 | false | {"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794} | import java.io.File
data class Point(val x: Int, val y: Int) {}
fun main(args: Array<String>) {
val lines = File(args[0]).readLines()
println(problem1(lines))
println(problem2(lines))
}
fun problem1(moves: List<String>): Int {
return solve(Array(2) { Point(0, 0) }, moves)
}
fun problem2(moves: List<String>): Int {
return solve(Array(10) { Point(0, 0) }, moves)
}
fun solve(rope: Array<Point>, moves: List<String>): Int {
var regex = """(.) (\d+)""".toRegex()
val visited = mutableListOf(Point(0, 0))
for (m in moves) {
val (direction, steps) = regex.matchEntire(m)!!.destructured
for (s in 1..steps.toInt()) {
rope[0] = moveHead(rope[0], direction.first())
for (i in 1 until rope.size) {
rope[i] = moveTail(rope[i - 1], rope[i])
}
visited.add(rope.last())
}
}
println(visited.size)
return visited.toSet().size
}
fun moveHead(headPos: Point, direction: Char): Point {
when (direction) {
'R' -> return Point(headPos.x + 1, headPos.y)
'L' -> return Point(headPos.x - 1, headPos.y)
'U' -> return Point(headPos.x, headPos.y - 1)
'D' -> return Point(headPos.x, headPos.y + 1)
else -> throw Exception("Unexpected direction: ${direction}")
}
}
fun moveTail(headPos: Point, tailPos: Point): Point {
if (tailPos.x == headPos.x - 2) {
if (tailPos.y == headPos.y - 1 || tailPos.y == headPos.y - 2)
return Point(tailPos.x + 1, tailPos.y + 1)
if (tailPos.y == headPos.y + 1 || tailPos.y == headPos.y + 2)
return Point(tailPos.x + 1, tailPos.y - 1)
return Point(tailPos.x + 1, tailPos.y)
} else if (tailPos.x == headPos.x + 2) {
if (tailPos.y == headPos.y - 1 || tailPos.y == headPos.y - 2)
return Point(tailPos.x - 1, tailPos.y + 1)
if (tailPos.y == headPos.y + 1 || tailPos.y == headPos.y + 2)
return Point(tailPos.x - 1, tailPos.y - 1)
return Point(tailPos.x - 1, tailPos.y)
} else if (tailPos.y == headPos.y - 2) {
if (tailPos.x == headPos.x - 1 || tailPos.x == headPos.x - 2)
return Point(tailPos.x + 1, tailPos.y + 1)
if (tailPos.x == headPos.x + 1 || tailPos.x == headPos.x + 2)
return Point(tailPos.x - 1, tailPos.y + 1)
return Point(tailPos.x, tailPos.y + 1)
} else if (tailPos.y == headPos.y + 2) {
if (tailPos.x == headPos.x - 1 || tailPos.x == headPos.x - 2)
return Point(tailPos.x + 1, tailPos.y - 1)
if (tailPos.x == headPos.x + 1 || tailPos.x == headPos.x + 2)
return Point(tailPos.x - 1, tailPos.y - 1)
return Point(tailPos.x, tailPos.y - 1)
}
return tailPos
}
| 0 | Rust | 0 | 0 | c265f4c0bddb0357fe90b6a9e6abdc3bee59f585 | 2,799 | AdventOfCode | MIT License |
src/Day02.kt | ben-dent | 572,931,260 | false | {"Kotlin": 10265} | fun main() {
fun getPairs(input: List<String>): List<List<String>> {
return input.map { it.split(" ") }
}
fun winScore(input: List<String>): Long {
val opponentMove = input[0]
val myMove = input[1]
val wins = HashMap<Pair<String, String>, Long>()
wins[Pair("A", "X")] = 3L
wins[Pair("A", "Y")] = 6L
wins[Pair("A", "Z")] = 0L
wins[Pair("B", "X")] = 0L
wins[Pair("B", "Y")] = 3L
wins[Pair("B", "Z")] = 6L
wins[Pair("C", "X")] = 6L
wins[Pair("C", "Y")] = 0L
wins[Pair("C", "Z")] = 3L
return wins[Pair(opponentMove, myMove)]!!
}
fun getScore(input: List<List<String>>): Long {
var score = 0L
val moveScores = HashMap<String, Int>()
moveScores["X"] = 1
moveScores["Y"] = 2
moveScores["Z"] = 3
input.forEach { score += moveScores[it[1]]!! + winScore(it)}
return score
}
fun convertToNeeded(input: List<String>): List<String> {
val needed = HashMap<Pair<String, String>, String>()
needed[Pair("A", "X")] = "Z"
needed[Pair("A", "Y")] = "X"
needed[Pair("A", "Z")] = "Y"
needed[Pair("B", "X")] = "X"
needed[Pair("B", "Y")] = "Y"
needed[Pair("B", "Z")] = "Z"
needed[Pair("C", "X")] = "Y"
needed[Pair("C", "Y")] = "Z"
needed[Pair("C", "Z")] = "X"
val opponentMove = input[0]
val outcome = input[1]
val toReturn = ArrayList<String>()
toReturn.add(opponentMove)
toReturn.add(needed[Pair(opponentMove, outcome)]!!)
return toReturn
}
fun part1(input: List<String>): Long {
return getScore(getPairs(input))
}
fun part2(input: List<String>): Long {
return getScore(getPairs(input).map { convertToNeeded(it) })
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15L)
check(part2(testInput) == 12L)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2c3589047945f578b57ceab9b975aef8ddde4878 | 2,148 | AdventOfCode2022Kotlin | Apache License 2.0 |
src/codility/NailingFlanks.kt | faniabdullah | 382,893,751 | false | null | package codility
import java.util.*
class NailingFlanks {
fun solution(A: IntArray, B: IntArray, C: IntArray): Int {
// the main algorithm is that getting the minimal index of nails which
// is needed to nail every plank by using the binary search
val N = A.size
val M = C.size
// two dimension array to save the original index of array C
val sortedNail = Array(M) { IntArray(2) }
for (i in 0 until M) {
sortedNail[i][0] = C[i]
sortedNail[i][1] = i
}
// use the lambda expression to sort two dimension array
Arrays.sort(sortedNail) { x: IntArray, y: IntArray -> x[0] - y[0] }
var result = 0
for (i in 0 until N) { //find the earlist position that can nail each plank, and the max value for all planks is the result
result = getMinIndex(A[i], B[i], sortedNail, result)
if (result == -1) return -1
}
return result + 1
}
// for each plank , we can use binary search to get the minimal index of the
// sorted array of nails, and we should check the candidate nails to get the
// minimal index of the original array of nails.
private fun getMinIndex(startPlank: Int, endPlank: Int, nail: Array<IntArray>, preIndex: Int): Int {
var min = 0
var max = nail.size - 1
var minIndex = -1
while (min <= max) {
val mid = (min + max) / 2
if (nail[mid][0] < startPlank) min = mid + 1 else if (nail[mid][0] > endPlank) max = mid - 1 else {
max = mid - 1
minIndex = mid
}
}
if (minIndex == -1) return -1
var minIndexOrigin = nail[minIndex][1]
//find the smallest original position of nail that can nail the plank
for (i in minIndex until nail.size) {
if (nail[i][0] > endPlank) break
minIndexOrigin = Math.min(minIndexOrigin, nail[i][1])
// we need the maximal index of nails to nail every plank, so the
// smaller index can be omitted
if (minIndexOrigin <= preIndex) return preIndex
}
return minIndexOrigin
}
}
fun main() {
println(NailingFlanks().solution(intArrayOf(1, 4, 5, 8), intArrayOf(4, 5, 9, 10), intArrayOf(4, 6, 7, 10, 2)))
} | 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,333 | dsa-kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxSumAfterPartitioning.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.max
/**
* 1043. Partition Array for Maximum Sum
* @see <a href="https://leetcode.com/problems/partition-array-for-maximum-sum/">Source</a>
*/
fun interface MaxSumAfterPartitioning {
operator fun invoke(arr: IntArray, k: Int): Int
}
class MaxSumAfterPartitioningDP : MaxSumAfterPartitioning {
override operator fun invoke(arr: IntArray, k: Int): Int {
val dp = IntArray(arr.size)
for (to in arr.indices) {
var currMax = 0
for (j in 0 until k) {
val from = to - j
if (from < 0) {
continue
}
currMax = max(currMax, arr[from])
val newSplitVal = currMax * (j + 1) + getVal(dp, from - 1)
dp[to] = max(dp[to], newSplitVal)
}
}
return dp[arr.size - 1]
}
private fun getVal(dp: IntArray, i: Int): Int {
return if (i < 0) {
0
} else {
dp[i]
}
}
}
class MaxSumAfterPartitioningMemo : MaxSumAfterPartitioning {
override operator fun invoke(arr: IntArray, k: Int): Int {
val memo = arrayOfNulls<Int>(arr.size)
return maxSumAfterPartitioning(arr, k, 0, memo)
}
private fun maxSumAfterPartitioning(arr: IntArray, k: Int, i: Int, memo: Array<Int?>): Int {
if (i == arr.size) {
return 0
}
if (memo[i] != null) {
return memo[i] ?: 0
}
var currMax = 0
var sumMax = 0
for (j in 0 until k) {
val to = i + j
if (to >= arr.size) {
break
}
currMax = max(currMax, arr[to])
sumMax = max(sumMax, currMax * (j + 1) + maxSumAfterPartitioning(arr, k, to + 1, memo))
}
return sumMax.also { memo[i] = it }
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,503 | kotlab | Apache License 2.0 |
src/Day10.kt | robotfooder | 573,164,789 | false | {"Kotlin": 25811} | fun main() {
fun part1(input: List<String>): Int {
val signalStrengths = listOf(20, 60, 100, 140, 180, 220)
return input
.flatMap { it.toNumberList() }
.runningFold(1) { acc, num -> acc + num }
.filterIndexed { index, _ -> signalStrengths.contains(index + 1) }
.mapIndexed { index, i -> i * signalStrengths[index] }
.sum()
}
fun part2(input: List<String>): Int {
val cycles = input
.flatMap { it.toNumberList() }
.runningFold(1) { acc, num -> acc + num }
.chunked(40)
cycles.forEach { rows ->
rows.forEachIndexed { index, cycleVal ->
if (index in cycleVal - 1..cycleVal + 1) {
print("#")
} else {
print(".")
}
}
println()
}
return 0
}
val day = "10"
// test if implementation meets criteria from the description, like:
runTest(13140, day, ::part1)
runTest(0, day, ::part2)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
private fun String.toNumberList(): List<Int> {
val test = this.split(" ")
return if (test[0] == "noop") {
listOf(0)
} else if (test[0] == "addx") {
listOf(0, test[1].toInt())
} else {
error(this)
}
}
| 0 | Kotlin | 0 | 0 | 9876a52ef9288353d64685f294a899a58b2de9b5 | 1,418 | aoc2022 | Apache License 2.0 |
FindInMountainArray.kt | prashantsinghpaliwal | 537,191,958 | false | {"Kotlin": 9473} | // Question link - https://leetcode.com/problems/find-in-mountain-array/
// Steps required :-
// 1.) Find peak element and divide array in one ascending and one descending order arrays.
// 2.) Apply binary search in asc part.
// 3.) If not found, then apply binary search in desc part.
fun main() {
val arr = arrayOf(2, 3, 4, 7, 9, 11, 12, 15, 23, 30, 31, 34, 35, 36)
val target = 35
val peak = findPeak(arr)
val searchInAsc = orderAgnosticBinarySearch(arr, target, 0, peak)
val index = if (searchInAsc != -1) searchInAsc
else orderAgnosticBinarySearch(arr, target, peak + 1, arr.size)
println("index is $index")
}
fun orderAgnosticBinarySearch(
arr: Array<Int>,
target: Int,
s: Int,
e: Int
): Int {
var start = s
var end = e
val ifAscending = arr[start] < arr[end]
while (start <= end) {
val mid = start + (end - start) / 2
if (ifAscending) {
if (target < arr[mid]) {
end = mid - 1
} else if (target > arr[mid]) {
start = mid + 1
} else {
return mid
}
} else {
if (target < arr[mid]) {
start = mid + 1
} else if (target > arr[mid]) {
end = mid - 1
} else {
return mid
}
}
}
return -1
}
fun findPeak(
arr: Array<Int>
): Int {
var start = 0
var end = arr.size -1
while (start < end) {
val mid = start + (end - start) / 2
if (arr[mid] > arr[mid+1]) {
// we are in decreasing part, so this may be the answer. But look at left
// this is why end != mid - 1
end = mid
} else if (arr[mid] < arr[mid+1]) {
// we are in increasing part, so this may be the answer. But look at right
// because we know mid + 1 is greater than mid element and we are finding
// greater elements only, so we are ignoring mid element
start = mid + 1
}
}
// In the end, start & end will point to largest element
// because of 2 checks.
// look closely, since start and end are trying to find max element only
// hence when both start and end will point to same element,
// that's the maximum element.
// so we can now return anything, start or end. After running above checks, now
// they are pointing to same max elements.
return start
}
| 0 | Kotlin | 0 | 0 | e66599817508beb4e90de43305939d200a9e3964 | 2,482 | DsAlgo | Apache License 2.0 |
src/Day06.kt | hoppjan | 433,705,171 | false | {"Kotlin": 29015, "Shell": 338} | fun main() {
fun part1(input: IntArray) = countSimulatedFishPopulation(fish = input, days = 80)
fun part2(input: IntArray) = countSimulatedFishPopulation(fish = input, days = 256)
// test if implementation meets criteria from the description
val testInput = IntInputReader2.read("Day06_test")
// testing part 1
val testOutput1 = part1(testInput)
val testSolution1 = 5934L
printTestResult(1, testOutput1, testSolution1)
check(testOutput1 == testSolution1)
// testing part 2
val testOutput2 = part2(testInput)
val testSolution2 = 26_984_457_539L
printTestResult(2, testOutput2, testSolution2)
check(testOutput2 == testSolution2)
// using the actual input for
val input = IntInputReader2.read("Day06")
printResult(1, part1(input).also { check(it == 352_151L) })
printResult(2, part2(input).also { check(it == 1_601_616_884_019L) })
}
fun countSimulatedFishPopulation(fish: IntArray, days: Int) =
fish.countByAgeGroup()
.simulatePopulationIn(days)
.sum()
fun IntArray.countByAgeGroup() =
LongArray(9) { age -> filter { it == age }.size.toLong() }
fun LongArray.simulatePopulationIn(days: Int): LongArray =
if (days > 0)
simulatePopulationInOneDay()
.simulatePopulationIn(days - 1)
else this
fun LongArray.simulatePopulationInOneDay() =
rotateToLeft(1) // simulates the aging/birth cycle
.apply { this[6] += last() } // resets the mothers' cycles after birth
/**
* Returns [LongArray] shifted by [amount] wrapping the first [amount] of elements around to the end.
*/
fun LongArray.rotateToLeft(amount: Int) = (drop(amount) + take(amount)).toLongArray()
| 0 | Kotlin | 0 | 0 | 04f10e8add373884083af2a6de91e9776f9f17b8 | 1,697 | advent-of-code-2021 | Apache License 2.0 |
src/Utils.kt | rhavran | 250,959,542 | false | null | import kotlin.math.sqrt
/**
* https://www.youtube.com/watch?v=V08g_lkKj6Q
*/
class EratosthenesSieve(n: Int) {
val numbers: List<Boolean>
init {
val numbersArray = BooleanArray(n + 1)
numbersArray.fill(true)
var potentialPrime = 2
while (potentialPrime * potentialPrime <= n) {
// If prime[p] is not changed, then it is a prime
if (numbersArray[potentialPrime]) { // Update all multiples of p
var nextPow = potentialPrime * potentialPrime
while (nextPow <= n) {
numbersArray[nextPow] = false
nextPow += potentialPrime
}
}
potentialPrime++
}
numbers = numbersArray.toList()
}
fun isPrime(n: Int): Boolean {
return numbers[n]
}
}
object PrimeFactorization {
private val incrementFunc: (t: Long, u: Long?) -> Long? = { _, old -> if (old == null) 1L else old + 1L }
fun primeFactors(n: Long): Map<Long, Long> {
val numberToPower = hashMapOf<Long, Long>()
// Add the number of 2s that divide n.
var number = n
while (number % 2L == 0L) {
numberToPower.compute(2L, incrementFunc)
number /= 2L
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2) as per sieve of Eratosthenes.
var i = 3L
while (i <= sqrt(number.toDouble())) {
// While i divides n, add i and divide n
while (number % i == 0L) {
numberToPower.compute(i, incrementFunc)
number /= i
}
i += 2L
}
// This condition is to handle the case when
// n is a prime number greater than 2
if (number > 2L) {
numberToPower.compute(number, incrementFunc)
}
return numberToPower
}
}
/**
* σ0(N)
* https://en.wikipedia.org/wiki/Divisor_function
*/
fun Long.dividers(): Long {
var dividers = 1L
val numberToPower = PrimeFactorization.primeFactors(this)
for (entry in numberToPower) {
dividers *= (entry.value + 1)
}
return dividers
}
fun Long.sequenceSumStartingFrom(a0: Long): Long {
return sumFromTo(a0, this)
}
fun sumFromTo(a0: Long, aN: Long): Long {
val n = aN - a0 + 1
return (n.toDouble() / 2.0 * (a0 + aN)).toLong()
} | 0 | Kotlin | 0 | 0 | 11156745ef0512ab8aee625ac98cb6b7d74c7e92 | 2,420 | ProjectEuler | MIT License |
src/Day04.kt | dcbertelsen | 573,210,061 | false | {"Kotlin": 29052} | import java.io.File
fun main() {
fun stringToPair(data: String) : IntRange {
val nums = data.split("-")
return IntRange(nums[0].toInt(), nums[1].toInt())
}
fun processInput(pair: String): Pair<IntRange, IntRange> {
val areas = pair.split(",")
.map { stringToPair(it) }
return Pair(areas.first(), areas.last())
}
fun part1(input: List<String>): Int {
return input.map { processInput(it) }
.count { pair ->
pair.first.subsumes(pair.second) || pair.second.subsumes(pair.first) }
}
fun part2(input: List<String>): Int {
return input.map { processInput(it) }
.count { pair ->
pair.first.intersect(pair.second).any() }
}
val testInput = listOf(
"2-4,6-8",
"2-3,4-5",
"5-7,7-9",
"2-8,3-7",
"6-6,4-6",
"2-6,4-8"
)
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = File("./src/resources/Day04.txt").readLines()
println(part1(input))
println(part2(input))
}
fun IntRange.subsumes(other: IntRange): Boolean =
contains(other.first) && contains(other.last)
| 0 | Kotlin | 0 | 0 | 9d22341bd031ffbfb82e7349c5684bc461b3c5f7 | 1,273 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions62.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
fun test62() {
val trieTree = TrieTree()
val boy = "boy"
trieTree.insert(boy)
val boss = "boss"
val cowboy = "cowboy"
trieTree.insert(boss)
trieTree.insert(cowboy)
println("Is this trie tree contain $boy: ${trieTree.search(boy)}")
println("Is this trie tree contain $boss: ${trieTree.search(boss)}")
println("Is this trie tree contain $cowboy: ${trieTree.search(cowboy)}")
val bos = "bos"
println("Is this trie tree contain $bos: ${trieTree.search(bos)}")
println("Is this trie tree start with $bos: ${trieTree.startWith(bos)}")
val cow = "cow"
println("Is this trie tree start with $cow: ${trieTree.startWith(cow)}")
}
/**
* Questions 62: Design a trie tree
*/
class TrieTree {
val head = TrieNode(' ')
fun insert(word: String) {
var pointer = head
word.forEach { c ->
val nextPointer = pointer.next.find { it?.character == c }
if (nextPointer == null) {
var insertIndex = 0
for (i in pointer.next.indices)
if (pointer.next[i] == null) {
insertIndex = i
break
}
val newNode = TrieNode(c)
pointer.next[insertIndex] = newNode
pointer = newNode
} else
pointer = nextPointer
}
}
fun search(word: String): Boolean {
var pointer = head
word.forEach { c ->
val nextPointer = pointer.next.find { it?.character == c }
if (nextPointer == null)
return false
else
pointer = nextPointer
}
return true
}
fun searchWith1Char(word: String): Boolean {
var pointer = head
var index = 0
var isFinish = true
while (index < word.length) {
val c = word[index++]
val nextPointer = pointer.next.find { it?.character == c }
if (nextPointer == null) {
isFinish = false
break
} else
pointer = nextPointer
}
if (isFinish) return false
return pointer.next.filterNotNull().any { newHead ->
var newPointer = newHead
var newIndex = index
while (newIndex < word.length) {
val c = word[newIndex++]
val nextPointer = newPointer.next.find { node -> node?.character == c }
if (nextPointer == null)
return@any false
else
newPointer = nextPointer
}
true
}
}
fun startWith(prefix: String): Boolean = search(prefix)
fun findTrie(str: String): String? {
var pointer = head
str.forEachIndexed { i, c ->
val nextPointer = pointer.next.find { it?.character == c }
if (nextPointer == null) {
return if (pointer.next.all { it == null })
str.substring(0, i)
else
null
} else
pointer = nextPointer
}
return null
}
fun lengthOfAllWords(): Int = lengthOfAllWords(head)
private fun lengthOfAllWords(start: TrieNode): Int {
var count = 0
start.next.forEach {
it?.let { node ->
count++
count += lengthOfAllWords(node)
}
}
if (start.next.all { it == null })
count++
return count
}
}
class TrieNode(val character: Char) {
var next = Array<TrieNode?>(8) { null }
private set
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 3,732 | Algorithm | Apache License 2.0 |
src/main/kotlin/de/dikodam/calendar/Day10.kt | dikodam | 433,719,746 | false | {"Kotlin": 51383} | package de.dikodam.calendar
import de.dikodam.AbstractDay
import de.dikodam.executeTasks
import java.util.*
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
Day10().executeTasks()
}
class Day10 : AbstractDay() {
val input = readInputLines()
// val input = """[({(<(())[]>[[{[]{<()<>>
//[(()[<>])]({[<{<<[]>>(
//{([(<{}[<>[]}>{[]{[(<()>
//(((({<>}<{<{<>}{[]{[]{}
//[[<[([]))<([[{}[[()]]]
//[{[{({}]{}}([{[{{{}}([]
//{<[[]]>}<{[{[{[]{()[[[]
//[<(<(<(<{}))><([]([]()
//<{([([[(<>()){}]>(<<{{
//<{([{{}}[<[[[<>{}]]]>[]]""".trim().lines()
override fun task1(): String {
fun Char.toPoints() =
when (this) {
')' -> 3
']' -> 57
'}' -> 1197
'>' -> 25137
else -> error("unknown char $this")
}
val result = input
.map { it.diagnose() }
.filterIsInstance<InvalidLine>()
.map { it.firstInvalidChar }
.map { it.toPoints() }
.sumOf { it }
return "$result"
}
override fun task2(): String {
val sortedScores = input
.map { it.diagnose() }
.filterIsInstance<IncompleteLine>()
.map { calculateAutocompletePoints(it.remainingOpeningTokens) }
.sorted()
return sortedScores[sortedScores.size / 2].toString()
}
}
fun calculateAutocompletePoints(queue: Deque<Char>): Long {
var sum = 0L
while (queue.isNotEmpty()) {
sum *= 5
val next = queue.removeFirst() // TODO why not removeLast?
sum += when (next) {
'(' -> 1
'[' -> 2
'{' -> 3
'<' -> 4
else -> error("unknown char $next")
}
}
return sum
}
fun Char.isOpening() = this in setOf('(', '{', '[', '<')
fun Char.matches(opening: Char) =
when (this) {
')' -> opening == '('
']' -> opening == '['
'}' -> opening == '{'
'>' -> opening == '<'
else -> error("unknown char $this")
}
fun Char.isClosing() = this in setOf(')', '}', ']', '>')
fun String.diagnose(): DiagnosticReport {
val stack: Deque<Char> = ArrayDeque()
for (token in this) {
if (token.isOpening()) {
stack.addFirst(token)
continue
}
val opening: Char = stack.removeFirst()
if (!token.matches(opening)) {
return InvalidLine(token)
}
}
return if (stack.isNotEmpty()) {
IncompleteLine(stack)
} else {
ValidLine
}
}
sealed class DiagnosticReport
object ValidLine : DiagnosticReport()
data class IncompleteLine(val remainingOpeningTokens: Deque<Char>) : DiagnosticReport()
data class InvalidLine(val firstInvalidChar: Char) : DiagnosticReport()
| 0 | Kotlin | 0 | 1 | 4934242280cebe5f56ca8d7dcf46a43f5f75a2a2 | 2,809 | aoc-2021 | MIT License |
src/Day01.kt | SebastianAigner | 573,086,864 | false | {"Kotlin": 2101} | import java.io.File
import java.util.PriorityQueue
fun main() {
fun parseInput(input: String) = input.split("\n\n").map { elf ->
elf.lines().map { it.toInt() }
}
// O(size * log size) -> O(size * log n) -> O(size)
fun List<List<Int>>.topNElves(n: Int): Int {
fun findTopN(n: Int, element: List<Int>): List<Int> {
if (element.size == n) return element
val x = element.random()
val small = element.filter { it < x }
val equal = element.filter { it == x }
val big = element.filter { it > x }
if (big.size >= n) return findTopN(n, big)
if (equal.size + big.size >= n) return (equal + big).takeLast(n)
return findTopN(n - equal.size - big.size, small) + equal + big
}
return findTopN(n, this.map { it.sum() }).sum()
}
fun part1(input: String): Int {
val data = parseInput(input)
return data.topNElves(1)
}
fun part2(input: String) : Int {
val data = parseInput(input)
return data.topNElves(3)
}
// test if implementation meets criteria from the description, like:
val testInput = File("src/Day01_test.txt").readText()
check(part1(testInput) == 24000)
val input = File("src/Day01.txt").readText()
println(part1(input))
println(part2(input))
// val input = readInput("Day01")
// println(part1(input))
// println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 2b5033019a6710d41adf6e6960eac7c1b59679d7 | 1,457 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/day19_beacon_scanner/BeaconScanner.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day19_beacon_scanner
import geom.Vec
import histogram.count
import histogram.mutableHistogramOf
import java.util.*
/**
* Another graph walk, reminiscent of Jurassic Jigsaw (2020 day 20), but this
* time in three dimensions! Based on the example, assume scanner zero's coord
* system is The One True System, and reorient/position all the scanners based
* on their shared beacons to those coordinates. Finding the shared beacons has
* its own pile of fun, as do the coordinate transforms. Goblins and elves? Once
* the scanners are all sharing a single system, the beacons are trivially
* plotted in that same system, and then count the unique locations. BAM!
*
* Part two is mindless if you did the "whole" solution to part one. If you
* "cheated" and didn't actually assemble a shared coordinate system, time to do
* so! Iterate over each pair of scanners and measure is the simple way. There's
* a tiny bit of room to avoid checking pairs which both aren't on the border,
* but it doesn't save much with only 30-something scanners.
*/
fun main() {
util.solve(436, ::partOne) // 394 is too low, 514 is too high
util.solve(10918, ::partTwo)
}
fun String.toScanners(): List<Scanner> {
val result = mutableListOf<Scanner>()
var scanner = Scanner(-1)
for (l in lines()) {
if (l.startsWith("--- scanner ")) {
val idx = l.indexOf(' ', 12)
scanner = Scanner(l.substring(12, idx).toInt())
result.add(scanner)
} else if (l.isNotBlank()) {
scanner.add(
Vec(
l.split(",")
.map(String::toLong)
.toTypedArray()
)
)
}
}
return result
}
fun Collection<Scanner>.relativize(): Collection<Scanner> {
val first = first()
first.location = Vec.origin(first.beacons[0].dimensions)
val queue: Queue<Scanner> = ArrayDeque()
queue.add(first)
val theOthers = drop(1)
while (queue.isNotEmpty()) {
val scanA = queue.remove()
for (scanB in theOthers) {
if (scanB.location != null) continue
if (scanA == scanB) continue
repeat(24) {
val hist = mutableHistogramOf<Vec>() // locations of B
for (a in scanA.beacons) {
for (b in scanB.beacons) {
hist.count(Vec(a.x - b.x, a.y - b.y, a.z - b.z))
}
}
val things = hist.entries
.filter { (_, v) -> v >= 12 }
if (things.isNotEmpty()) {
if (things.size > 1)
throw IllegalStateException("scanner ${scanB.id} (rel ${scanA.id}) could be at any of ${things.map { it.key }}")
val loc = things[0].key + scanA.location!!
when (scanB.location) {
null -> {
scanB.location = loc
queue.add(scanB)
}
loc -> {}
else -> throw IllegalStateException("Scanner ${scanB.id} moved to $loc?!")
}
return@repeat
}
scanB.twist()
}
}
}
return this
}
fun partOne(input: String): Int {
val scanners = input.toScanners()
.relativize()
val allBeacons = HashSet<Vec>()
scanners.forEach { scanner ->
scanner.beacons.forEach { beacon ->
allBeacons.add(beacon + scanner.location!!)
}
}
return allBeacons.size
}
fun partTwo(input: String): Long {
val scanners = input.toScanners()
.relativize()
var max = Long.MIN_VALUE
for (a in scanners) {
for (b in scanners) {
max = max.coerceAtLeast(
a.location!!.manhattanDistance(b.location!!)
)
}
}
return max
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 3,988 | aoc-2021 | MIT License |
Day 5/Part 1/src/Task.kt | marc-bouvier-katas | 434,007,210 | false | {"Kotlin": 46389} | fun overlaps(ventsLines: Array<String>): Int {
val lines = Lines()
return if (ventsLines.size >= 2) {
repeat(ventsLines.size){
lines.mergeWith(Line.fromLineOfVent(LineOfVent.fromString(ventsLines[it])))
}
return lines.overlaps()
} else 0
}
data class Lines(private val data:MutableMap<Int,Line> = mutableMapOf()
){
fun mergeWith(line: Line){
data.merge(line.y,line,Line::mergeWith)
}
fun overlaps(): Int {
println(data)
return data.values.sumOf { it.overlaps() }
}
}
data class Line(val y: Int, private val xValues: Map<Int, Int> = mutableMapOf()) {
fun mergeWith(other:Line): Line {
val mergedXValues = xValues.toMutableMap()
other.xValues.forEach{
if(mergedXValues.containsKey(it.key)){
mergedXValues[it.key]=it.value+mergedXValues[it.key]!!
}else{
mergedXValues[it.key]=it.value
}
}
return Line(y, mergedXValues)
}
fun overlaps(): Int {
return xValues.values.count { it > 1 }
}
companion object{
fun fromLineOfVent(lineOfVent: LineOfVent):Line{
val xValues = mutableMapOf<Int, Int>()
(lineOfVent.x1 .. lineOfVent.x2).forEach{xValues[it]=1}
println("fromlineofvent: "+xValues)
return Line(lineOfVent.y1, xValues.toMap())
}
}
}
class LineOfVent(
val x1: Int,
val y1: Int,
val x2: Int,
val y2: Int
) {
fun numberOfOverlapsWith(other: LineOfVent): Int {
return if (!onTheSameYCoordinate(other))
0
else
arrayOf(this.x2, other.x2)
.minOrNull()!! - arrayOf(
this.x1,
other.x1
).maxOrNull()!! + 1
}
private fun onTheSameYCoordinate(other: LineOfVent) = this.y1 == other.y1
companion object {
fun fromString(string: String): LineOfVent {
val (left, right) = string.split(" -> ")
val (x1, y1) = left.split(",").map(String::toInt)
val (x2, y2) = right.split(",").map(String::toInt)
return LineOfVent(x1, y1, x2, y2)
}
}
}
| 0 | Kotlin | 0 | 1 | 12cf74ca5ac5985b00da89ffd43b750e105e0cec | 2,177 | Kotlin_EduTools_Advent_of_Code_2021 | MIT License |
src/Day13.kt | kipwoker | 572,884,607 | false | null | import java.util.Comparator
fun main() {
class TreeNode(
val value: Int?,
val parent: TreeNode?,
val str: String?,
var children: MutableList<TreeNode> = mutableListOf()
)
class TreeNodeComparator(val f: (o1: TreeNode?, o2: TreeNode?) -> Int) : Comparator<TreeNode> {
override fun compare(o1: TreeNode?, o2: TreeNode?): Int {
return f(o1, o2)
}
}
fun parseTree(input: String): TreeNode {
val root = TreeNode(null, null, input)
var currentNode = root
var level = 0
val size = input.length
var i = 0
while (i < size) {
var c = input[i]
when (c) {
'[' -> {
val child = TreeNode(null, currentNode, null)
currentNode.children.add(child)
currentNode = child
level++
}
']' -> {
currentNode = currentNode.parent!!
level--
}
',' -> {
}
in '0'..'9' -> {
var number = ""
while (c in '0'..'9') {
number += c
++i
c = input[i]
}
--i
val child = TreeNode(number.toInt(), currentNode, null)
currentNode.children.add(child)
}
}
++i
}
return root
}
fun parse(input: List<String>): List<Pair<TreeNode, TreeNode>> {
return input
.chunked(3)
.map { chunk ->
parseTree(chunk[0]) to parseTree(chunk[1])
}
}
fun compare(left: Int, right: Int): Boolean? {
if (left == right) {
return null
}
return left < right
}
fun compare(left: TreeNode, right: TreeNode): Boolean? {
if (left.value != null && right.value != null) {
return compare(left.value, right.value)
}
if (left.value == null && right.value == null) {
var i = 0
while (i < left.children.size || i < right.children.size) {
if (left.children.size < right.children.size && i >= left.children.size) {
return true
}
if (left.children.size > right.children.size && i >= right.children.size) {
return false
}
val leftChild = left.children[i]
val rightChild = right.children[i]
val result = compare(leftChild, rightChild)
if (result != null) {
return result
}
++i
}
}
if (left.value != null) {
val subNode = TreeNode(null, left.parent, null)
val subChild = TreeNode(left.value, subNode, null)
subNode.children.add(subChild)
return compare(subNode, right)
}
if (right.value != null) {
val subNode = TreeNode(null, right.parent, null)
val subChild = TreeNode(right.value, subNode, null)
subNode.children.add(subChild)
return compare(left, subNode)
}
return null
}
fun part1(input: List<String>): Int {
val pairs = parse(input)
return pairs
.map { item -> compare(item.first, item.second) }
.mapIndexed { index, r -> if (r == true) index + 1 else 0 }
.sum()
}
fun part2(input: List<String>): Int {
val input1 = input.toMutableList()
input1.add("\n")
input1.add("[[2]]")
input1.add("[[6]]")
input1.add("\n")
val pairs = parse(input1)
val comparator = TreeNodeComparator { o1, o2 ->
when (compare(o1!!, o2!!)) {
true -> -1
false -> 1
else -> 0
}
}
return pairs
.flatMap { item -> listOf(item.first, item.second) }
.sortedWith(comparator)
.mapIndexed { index, treeNode ->
if (treeNode.str == "[[2]]" || treeNode.str == "[[6]]") {
index + 1
} else {
1
}
}
.reduce { acc, i -> acc * i }
}
val testInput = readInput("Day13_test")
assert(part1(testInput), 13)
assert(part2(testInput), 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 4,679 | aoc2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/BestTeamScore.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.max
/**
* 1626. Best Team With No Conflicts
* @see <a href="https://leetcode.com/problems/best-team-with-no-conflicts/">Source</a>
*/
fun interface BestTeamScore {
operator fun invoke(scores: IntArray, ages: IntArray): Int
}
class BestTeamScoreDP : BestTeamScore {
override operator fun invoke(scores: IntArray, ages: IntArray): Int {
val n: Int = ages.size
val candidate = Array(n) { IntArray(2) }
for (i in 0 until n) {
candidate[i][0] = ages[i]
candidate[i][1] = scores[i]
}
candidate.sortWith { a, b -> if (a[0] == b[0]) a[1] - b[1] else a[0] - b[0] }
val dp = IntArray(n)
dp[0] = candidate[0][1]
var max = dp[0]
for (i in 1 until n) {
dp[i] = candidate[i][1]
for (j in 0 until i) {
if (candidate[j][1] <= candidate[i][1]) {
dp[i] = max(dp[i], candidate[i][1] + dp[j])
}
}
max = max(dp[i], max)
}
return max
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,707 | kotlab | Apache License 2.0 |
src/2021/Day9_2.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
class DepthMap(val input: List<String>) {
fun findBasins(): Collection<List<Pair<Int, Int>>> {
val coordsWithBasinLabels = mutableMapOf<Pair<Int, Int>, Int>()
var label = 0
val coords = input.indices.product(input[0].indices)
val depths = coords.associateWith { (i, j) -> input[i][j] }.withDefault { '@' }
coords.filter { point ->
depths.getValue(point) < point.neighbors().minOf { depths.getValue(it) }
}
coords.forEach { point -> searchBasin(point, coordsWithBasinLabels, label++, depths) }
return coordsWithBasinLabels.entries.groupBy({ it.value }) { it.key }.values
}
private fun searchBasin(point: Pair<Int, Int>, coordsWithBasinLabels: MutableMap<Pair<Int,Int>, Int>, label: Int, depths: Map<Pair<Int, Int>, Char>) {
if (point !in coordsWithBasinLabels && depths.getValue(point) < '9') {
coordsWithBasinLabels[point] = label
point.neighbors().forEach { searchBasin(it, coordsWithBasinLabels, label, depths) }
}
}
}
fun IntRange.product(other: IntRange) = this.flatMap { i -> other.map {
j -> i to j
}}
fun Pair<Int, Int>.neighbors() = listOf(
this.first - 1 to this.second,
this.first + 1 to this.second,
this.first to this.second - 1,
this.first to this.second + 1,
)
val result = DepthMap(File("input/2021/day9")
.readLines())
.findBasins().map { it.size }.sortedBy { it }.takeLast(3).reduce { a, b -> a * b }
println(result) | 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 1,530 | adventofcode | MIT License |
src/Day14.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} | import java.util.regex.Pattern
fun main() {
// 498,4 -> 498,6 -> 496,6
// 503,4 -> 502,4 -> 502,9 -> 494,9
data class Point(val x: Int, val y: Int)
fun sign(a: Int): Int =
if (a > 0) {
1
} else if (a < 0) {
-1
} else {
0
}
fun simulation(map: Array<CharArray>, bottom: Int): Int {
var points = 0
while (true) {
var x = 500
var y = 0
while (true) {
if (y > bottom || map[y][x] != Char(0)) {
return points
}
if (map[y + 1][x] == Char(0)) {
y += 1
continue
}
if (map[y + 1][x - 1] == Char(0)) {
x -= 1
y += 1
continue
}
if (map[y + 1][x + 1] == Char(0)) {
x += 1
y += 1
continue
}
map[y][x] = 'o'
points += 1
break
}
}
}
fun part1(input: String): Int {
val lines = input.lines()
.map { line ->
line.split(Pattern.compile(" -> "))
.map {
val (x, y) = it.split(",")
Point(x.toInt(), y.toInt())
}
}
val map = Array(1000) { CharArray(1000) }
val bottom = lines.flatten().maxOf { it.y }
for (line in lines) {
for (i in 1 until line.size) {
val dx = sign(line[i].x - line[i - 1].x)
val dy = sign(line[i].y - line[i - 1].y)
var x = line[i - 1].x
var y = line[i - 1].y
do {
map[y][x] = '#'
x += dx
y += dy
} while (!(line[i].x == x && line[i].y == y))
map[y][x] = '#'
}
}
val result = simulation(map, bottom)
return result
}
fun part2(input: String): Int {
val lines = input.lines()
.map { line ->
line.split(Pattern.compile(" -> "))
.map {
val (x, y) = it.split(",")
Point(x.toInt(), y.toInt())
}
}
val map = Array(1000) { CharArray(1000) }
val bottom = lines.flatten().maxOf { it.y }
for (line in lines + listOf(listOf(Point(0, bottom + 2), Point(999, bottom+2)))) {
for (i in 1 until line.size) {
val dx = sign(line[i].x - line[i - 1].x)
val dy = sign(line[i].y - line[i - 1].y)
var x = line[i - 1].x
var y = line[i - 1].y
do {
map[y][x] = '#'
x += dx
y += dy
} while (!(line[i].x == x && line[i].y == y))
map[y][x] = '#'
}
}
val result = simulation(map, Int.MAX_VALUE)
return result
}
// test if implementation meets criteria from the description, like:
val testInputExample = readText("Day14_example")
check(part1(testInputExample) == 24)
check(part2(testInputExample) == 93)
val testInput = readText("Day14_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 3,514 | aoc-2022-in-kotlin | Apache License 2.0 |
codeforces/round572/a2.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round572
private fun solve() {
val n = readInt()
val nei = List(n) { mutableListOf<Edge>() }
repeat(n - 1) {
val (aInput, bInput, value) = readInts()
val a = aInput - 1
val b = bInput - 1
nei[a].add(Edge(a, b, value))
nei[b].add(Edge(b, a, value))
}
if (nei.any { it.size == 2 }) {
println("NO")
return
}
println("YES")
val ans = nei.flatten().filter { it.from < it.to }.flatMap { edge ->
val a = dfs(edge.from, edge.to, false, nei)
val b = dfs(edge.from, edge.to, true, nei)
val c = dfs(edge.to, edge.from, false, nei)
val d = dfs(edge.to, edge.from, true, nei)
val halfValue = edge.value / 2
listOf(
Edge(a, c, halfValue),
Edge(b, d, halfValue),
Edge(a, b, -halfValue),
Edge(c, d, -halfValue)
).filter { it.from != it.to }
}
println(ans.size)
for (edge in ans) {
println("${edge.from + 1} ${edge.to + 1} ${edge.value}")
}
}
private data class Edge(val from: Int, val to: Int, val value: Int)
private fun dfs(v: Int, p: Int, order: Boolean, nei: List<List<Edge>>): Int {
if (nei[v].size == 1) return v
for (edge in (if (order) nei[v] else nei[v].reversed())) {
val u = edge.to
if (u == p) continue
return dfs(u, v, order, nei)
}
error("")
}
fun main() {
val stdStreams = (false to true)
val isOnlineJudge = System.getProperty("ONLINE_JUDGE") == "true"
if (!isOnlineJudge) {
if (!stdStreams.first) System.setIn(java.io.File("input.txt").inputStream())
if (!stdStreams.second) System.setOut(java.io.PrintStream("output.txt"))
}
val tests = if (isOnlineJudge) 1 else readInt()
repeat(tests) { solve() }
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,788 | competitions | The Unlicense |
kotlin/src/com/daily/algothrim/leetcode/medium/SearchRange.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode.medium
/**
* 34. 在排序数组中查找元素的第一个和最后一个位置
*
* 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
* 如果数组中不存在目标值 target,返回 [-1, -1]。
*
* 进阶:
*
* 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
*/
class SearchRange {
companion object {
@JvmStatic
fun main(args: Array<String>) {
SearchRange().searchRange(intArrayOf(5, 7, 7, 8, 8, 10), 8).forEach {
println(it)
}
SearchRange().searchRange(intArrayOf(5, 7, 7, 8, 8, 10), 6).forEach {
println(it)
}
SearchRange().searchRange(intArrayOf(), 0).forEach {
println(it)
}
SearchRange().searchRange(intArrayOf(2, 2), 3).forEach {
println(it)
}
}
}
// nums = [5,7,7,8,8,10], target = 8
// [3,4]
fun searchRange(nums: IntArray, target: Int): IntArray {
if (nums.isEmpty()) return intArrayOf(-1, -1)
val result = IntArray(2)
val start = binarySearch(nums, target, true)
val end = binarySearch(nums, target)
if (start in 0..end && end < nums.size && nums[start] == target && nums[end] == target) {
result[0] = start
result[1] = end
} else {
result[0] = -1
result[1] = -1
}
return result
}
private fun binarySearch(nums: IntArray, target: Int, start: Boolean = false): Int {
var left = 0
var right = nums.size - 1
while (left <= right) {
val mid = left + (right - left).shr(1)
if (target < nums[mid] || (start && target <= nums[mid])) {
right = mid - 1
} else {
left = mid + 1
}
}
return if (start) right + 1 else left - 1
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,069 | daily_algorithm | Apache License 2.0 |
src/2021-Day06.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | fun main() {
fun part1(input: List<String>): Int {
val counts = ArrayDeque(List(9) { 0 })
input[0].trim().split(',').map { it.toInt() }.forEach { ++counts[it] }
var days = 80
while (days > 0) {
val newFish = counts.removeFirst()
counts.add(newFish)
counts[6] += newFish
--days
}
return counts.sum()
}
fun part2(input: List<String>): Long {
val counts = ArrayDeque<Long>(List(9) { 0 })
input[0].trim().split(',').map { it.toInt() }.forEach { ++counts[it] }
var days = 256
while (days > 0) {
val newFish = counts.removeFirst()
counts.add(newFish)
counts[6] += newFish
--days
}
return counts.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"3,4,3,1,2\n"
)
val pt1 = part1(testInput)
println(pt1)
check(pt1 == 5934)
check(part2(testInput) == 26984457539)
val input = readInput("2021-day6")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 1,146 | 2022-aoc-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2016/2016-13.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2016
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.searchGraph
import com.github.ferinagy.adventOfCode.singleStep
fun main() {
println("Part1:")
println(part1(testInput1, Coord2D(7, 4)))
println(part1(input, Coord2D(31, 39)))
println()
println("Part2:")
println(part2())
}
private fun part1(input: Int, target: Coord2D): Int {
val start = Coord2D(1, 1)
return searchGraph(
start = start,
isDone = { it == target },
nextSteps = { from -> adjacent(from, input).toSet().singleStep() },
heuristic = { it.distanceTo(target) }
)
}
private fun part2(): Int {
val start = Coord2D(1, 1)
val canVisit = mutableSetOf<Coord2D>()
val steps = mutableMapOf(start to 0)
searchGraph(
start = start,
isDone = { 50 < steps[it]!! },
nextSteps = { from ->
canVisit += from
val currentSteps = steps[from]!!
val next = adjacent(from, input)
next.forEach { steps[it] = currentSteps + 1 }
next.toSet().singleStep()
}
)
return canVisit.size
}
private fun adjacent(
from: Coord2D,
input: Int
) = from.adjacent(includeDiagonals = false).filter { 0 <= it.x && 0 <= it.y && !it.isWall(input) }
private fun Coord2D.isWall(n: Int): Boolean {
val num = x * x + 3 * x + 2 * x * y + y + y * y + n
return num.countOneBits() % 2 == 1
}
private const val testInput1 = 10
private const val input = 1364
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,562 | advent-of-code | MIT License |
src/Day13.kt | maewCP | 579,203,172 | false | {"Kotlin": 59412} | fun main() {
fun parse(str: String): List<String> {
var output = str
var openBracketCount = 0
(str.indices).forEach { i ->
if (str[i] == '[') openBracketCount++
if (str[i] == ']') openBracketCount--
if (str[i] == ',' && openBracketCount == 0) output = output.substring(0, i) + "\n" + output.substring(i + 1, output.length)
}
return output.split("\n")
}
fun readStringToModel(str: String): Day13Model {
return if (str[0] == '[' && str[str.length - 1] == ']') {
val members = mutableListOf<Day13Model>()
val textToParse = str.substring(1, str.length - 1)
if (textToParse.isNotEmpty()) {
parse(textToParse).forEach { memberStr ->
members.add(readStringToModel(memberStr))
}
Day13Model(members)
} else Day13Model()
} else {
Day13Model(str.toInt())
}
}
fun part1(input: List<String>): Int {
val allInput = input.joinToString(separator = "\n")
var sumOfRightOrderIdx = 0
allInput.split("\n\n").forEachIndexed { i, pair ->
val (left, right) = pair.split("\n").map { readStringToModel(it) }
if (left <= right) sumOfRightOrderIdx += i + 1
}
return(sumOfRightOrderIdx)
}
fun part2(input: List<String>): Int {
val allInput = input.joinToString(separator = "\n")
val firstDivider = readStringToModel("[[2]]")
val secondDivider = readStringToModel("[[6]]")
val packets = mutableListOf(firstDivider, secondDivider)
allInput.split("\n\n").forEach { pair ->
val (left, right) = pair.split("\n").map { readStringToModel(it) }
packets.add(left)
packets.add(right)
}
packets.sort()
val x = packets.indexOf(firstDivider) + 1
val y = packets.indexOf(secondDivider) + 1
return(x*y)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
part1(input).println()
part2(input).println()
}
class Day13Model : Comparable<Day13Model> {
private var members = mutableListOf<Day13Model>()
private var value: Int? = null
constructor()
constructor(members: MutableList<Day13Model>) {
this.members = members
}
constructor(value: Int) {
this.value = value
}
override fun compareTo(other: Day13Model): Int {
if (value == null && members.isEmpty() && other.value == null && other.members.isEmpty()) return 0
else if (value == null && members.isEmpty()) return -1
else if (other.value == null && other.members.isEmpty()) return 1
else if (value != null && other.value != null) return value!!.compareTo(other.value!!)
else {
// compare first item
if (members.size == 0) {
members = mutableListOf(Day13Model(value!!))
value = null
}
if (other.members.size == 0) {
other.members = mutableListOf(Day13Model(other.value!!))
other.value = null
}
val left = members[0]
val right = other.members[0]
val firstCompare = left.compareTo(right)
return if (firstCompare == 0) {
// compare the rest
Day13Model(members.drop(1).toMutableList()).compareTo(Day13Model(other.members.drop(1).toMutableList()))
} else firstCompare
}
}
}
| 0 | Kotlin | 0 | 0 | 8924a6d913e2c15876c52acd2e1dc986cd162693 | 3,718 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinDifference.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.min
/**
* 1906. Minimum Absolute Difference Queries
* @see <a href="https://leetcode.com/problems/minimum-absolute-difference-queries/">Source</a>
*/
fun interface MinDifference {
operator fun invoke(nums: IntArray, queries: Array<IntArray>): IntArray
}
class MinDifferencePrefixSum : MinDifference {
override operator fun invoke(nums: IntArray, queries: Array<IntArray>): IntArray {
val n: Int = nums.size
val count = Array(n + 1) { IntArray(LIMIT) }
val q: Int = queries.size
val ans = IntArray(q)
for (i in 0 until n) {
for (j in 0 until LIMIT) count[i + 1][j] = count[i][j]
++count[i + 1][nums[i] - 1]
}
for (i in 0 until q) {
val low = queries[i][0]
val high = queries[i][1] + 1
val present: MutableList<Int> = ArrayList()
var min = LIMIT
for (j in 0 until LIMIT) if (count[high][j] - count[low][j] != 0) present.add(j)
for (j in 1 until present.size) min = min(min, present[j] - present[j - 1])
if (present.size == 1) min = -1
ans[i] = min
}
return ans
}
companion object {
private const val LIMIT = 100
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,904 | kotlab | Apache License 2.0 |
src/Day05.kt | JohannesPtaszyk | 573,129,811 | false | {"Kotlin": 20483} | import kotlin.math.min
fun main() {
data class MoveInstruction(val amount: Int, val fromIndex: Int, val toIndex: Int)
fun getStacks(stackInput: List<String>): MutableList<MutableList<String>> =
stackInput.fold(mutableListOf()) { stacks: MutableList<MutableList<String>>, line: String ->
line.windowed(3, 4).forEachIndexed { index, stackValue ->
val currentStack = stacks.getOrElse(index) { mutableListOf() }
if(stackValue.isNotBlank()) {
currentStack.add(stackValue.removeSurrounding("[", "]"))
}
if (stacks.getOrNull(index) == null) {
stacks.add(currentStack)
} else {
stacks[index] = currentStack
}
}
stacks
}
fun getInstructions(
input: List<String>,
fileSeparatorIndex: Int
) = input.subList(fileSeparatorIndex + 1, input.size).map { instruction ->
val (amount, from, to) = Regex("[0-9]+").findAll(instruction).map { it.value.toInt() }.toList()
MoveInstruction(amount, from - 1, to - 1)
}
fun getStacksAndInstructions(input: List<String>): Pair<MutableList<MutableList<String>>, List<MoveInstruction>> {
val fileSeparatorIndex = input.indexOfFirst { it.isBlank() }
val stackInput = input.subList(0, fileSeparatorIndex - 1)
val stacks = getStacks(stackInput)
val instructions = getInstructions(input, fileSeparatorIndex)
return Pair(stacks, instructions)
}
fun MutableList<MutableList<String>>.joinToResult() = map { it.first() }.joinToString(separator = "") { it }
fun part1(input: List<String>): String {
val (stacks, instructions) = getStacksAndInstructions(input)
instructions.forEach { instruction ->
repeat(instruction.amount) {
val from = stacks[instruction.fromIndex]
val movable = from.removeFirst()
stacks[instruction.toIndex].add(0, movable)
}
}
return stacks.joinToResult()
}
fun part2(input: List<String>): String {
val (stacks, instructions) = getStacksAndInstructions(input)
instructions.forEach { instruction ->
val from = stacks[instruction.fromIndex]
val movables = from.subList(0, min(instruction.amount, from.size)).toList()
repeat(instruction.amount) {
from.removeFirst()
}
stacks[instruction.toIndex].addAll(0, movables)
}
return stacks.joinToResult()
}
val testInput = readInput("Day05_test")
val input = readInput("Day05")
println("Part1 test: ${part1(testInput)}")
check(part1(testInput) == "CMZ")
println("Part 1: ${part1(input)}")
println("Part2 test: ${part2(testInput)}")
check(part2(testInput) == "MCD")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 1 | 6f6209cacaf93230bfb55df5d91cf92305e8cd26 | 2,981 | advent-of-code-2022 | Apache License 2.0 |
src/day25/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day25
import println
import readInput
class Snowverload(input: List<String>) {
private val graph = buildMap {
input.forEach {row ->
val (key, values) = row.split(':')
put(key.trim(), values.split(' ').map(String::trim).filter { it.isNotEmpty() })
}
}
private val nodes = buildSet {
addAll(graph.values.flatten())
addAll(graph.keys)
}
private val connections = buildSet {
graph.forEach {left ->
addAll(left.value.map { setOf(left.key, it) })
}
}
private fun partsOfGraph(connections: Set<Set<String>>): List<Set<String>> {
val seenNodes = mutableSetOf<String>()
fun findConnected(node: String, seen: MutableSet<String> = mutableSetOf()): Set<String> {
seen += node
val newConnections = connections
.filter { it.contains(node) }
.flatten()
.filter {!seen.contains(it)}
.toSet()
seen.addAll(newConnections.map { findConnected(it, seen) }.flatten())
return seen
}
val result = mutableListOf<Set<String>>()
do {
result += findConnected(nodes.first { !seenNodes.contains(it) })
seenNodes.addAll(result.last())
} while (seenNodes.size != nodes.size)
return result
}
fun solve(): Int {
val nodesToRemove = setOf(setOf("hvm", "grd"), setOf("pmn", "kdc"), setOf("zfk", "jmn"))
val connectionsToTest = connections.toMutableSet()
connectionsToTest.removeAll(nodesToRemove)
val subGraphs = partsOfGraph(connectionsToTest)
return if (subGraphs.size == 2)
subGraphs[0].size * subGraphs[1].size
else
0
}
// Visualise with
// brew install graphviz
// dot -Tsvg -Kneato graph.dot > graph.svg
fun printGraph(): String{
return buildString {
appendLine("strict graph {")
connections.forEach {
val list = it.toList()
appendLine("${list[0]} -- ${list[1]}")
}
appendLine("}")
}
}
}
fun main() {
"Part 1:".println()
Snowverload(readInput("day25/input"))
.printGraph()
.println()
Snowverload(readInput("day25/input"))
.solve()
.println()
} | 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 2,384 | advent-of-code-2023 | Apache License 2.0 |
src/day13/Day13.kt | JoeSkedulo | 573,328,678 | false | {"Kotlin": 69788} | package day13
import Runner
fun main() {
Day13Runner().solve()
}
class Day13Runner : Runner<Int>(
day = 13,
expectedPartOneTestAnswer = 13,
expectedPartTwoTestAnswer = 140
) {
override fun partOne(input: List<String>, test: Boolean): Int {
return packetPairs(input)
.map { (left, right) -> left.compareTo(right) }
.mapIndexedNotNull { index, comparison -> if (comparison == -1) { index + 1 } else { null } }
.sum()
}
override fun partTwo(input: List<String>, test: Boolean): Int {
val dividerPackets = listOf("[[2]]", "[[6]]").map { s -> s.toPacket() }
return (packetPairs(input).flatten() + dividerPackets)
.sortedWith { a, b -> a.compareTo(b) }
.let { sorted ->
(sorted.indexOf(dividerPackets.first()) + 1) * (sorted.indexOf(dividerPackets.last()) + 1)
}
}
private fun packetPairs(input: List<String>) : List<PacketPair> {
return input.windowed(2, 3).map { lines ->
PacketPair(
left = lines.first().toPacket(),
right = lines.last().toPacket()
)
}
}
private fun List<PacketPair>.flatten() : List<Packet> {
return flatMap { (left, right) ->
listOf(left, right)
}
}
private fun Packet.compareTo(other: Packet): Int = let { source ->
fun ListPacket.compareTo(other: ListPacket) : Int = let { source ->
source.packets.zip(other.packets).forEach { (a, b) ->
val c = a.compareTo(b)
if (c != 0) {
return c
}
}
return when {
source.packets.size == other.packets.size -> 0
source.packets.size < other.packets.size -> -1
else -> 1
}
}
return when {
source is IntPacket && other is IntPacket -> source.int.compareTo(other.int)
source is ListPacket && other is ListPacket -> source.compareTo(other)
source is ListPacket && other is IntPacket -> source.compareTo(ListPacket(listOf(other)))
source is IntPacket && other is ListPacket -> ListPacket(listOf(source)).compareTo(other)
else -> throw RuntimeException()
}
}
private fun String.toPacket() : Packet {
val input = removeSurrounding("[", "]")
return ListPacket(if (input.isEmpty()) {
emptyList()
} else {
buildList {
var inputIndex = 0
while (inputIndex <= input.lastIndex) {
inputIndex = when (input[inputIndex]) {
'[' -> {
val closingIndex = input.closingIndex(inputIndex)
add(input.substring(inputIndex, closingIndex + 1).toPacket())
closingIndex + 1
}
else -> {
val nextComma = input.nextCommaIndex(inputIndex)
add(IntPacket(input.substring(inputIndex, nextComma).toInt()))
nextComma
}
}
inputIndex++
}
}
})
}
private fun String.nextCommaIndex(startIndex: Int) : Int {
return when (val commaIndex = indexOf(",", startIndex = startIndex + 1)) {
-1 -> lastIndex + 1
else -> commaIndex
}
}
private fun String.closingIndex(startIndex: Int) : Int {
return substring(startIndex + 1).indexOfClosingBrace() +
substring(0, startIndex).count()
}
private fun String.indexOfClosingBrace() : Int {
val stack = ArrayDeque<Char>()
var index = 0
stack.add('[')
while (stack.isNotEmpty()) {
when (val c = get(index)) {
'[' -> stack.add(c)
']' -> stack.removeLast()
}
index++
}
return index
}
}
data class PacketPair(
val left: Packet,
val right: Packet
)
sealed interface Packet
data class ListPacket(
val packets : List<Packet> = emptyList()
) : Packet {
override fun toString(): String {
return packets.toString()
}
}
data class IntPacket(
val int: Int
) : Packet {
override fun toString(): String {
return int.toString()
}
} | 0 | Kotlin | 0 | 0 | bd8f4058cef195804c7a057473998bf80b88b781 | 4,502 | advent-of-code | Apache License 2.0 |
src/main/kotlin/endredeak/aoc2022/Day21.kt | edeak | 571,891,076 | false | {"Kotlin": 44975} | package endredeak.aoc2022
private abstract class Expression(open val id: String) {
abstract fun eval(map: Map<String, Expression>): Long
fun print(map: Map<String, Expression>): String =
when(this) {
is Literal -> if (this.id == "humn") "x" else "${this.eval(emptyMap())}"
is Composite -> "(${map[this.left]!!.print(map)}${this.op}${map[this.right]!!.print(map)})"
else -> error("waat")
}
}
private data class Literal(override val id: String, val value: Long) : Expression(id) {
override fun eval(map: Map<String, Expression>): Long = value
}
private data class Composite(
override val id: String,
val left: String,
val op: String,
val right: String
) : Expression(id) {
override fun eval(map: Map<String, Expression>): Long =
when (op) {
"+" -> map[left]!!.eval(map) + map[right]!!.eval(map)
"*" -> map[left]!!.eval(map) * map[right]!!.eval(map)
"-" -> map[left]!!.eval(map) - map[right]!!.eval(map)
"/" -> map[left]!!.eval(map) / map[right]!!.eval(map)
else -> error("waat")
}
}
fun main() {
solve("Monkey Math") {
val input = lines
.map { it.split(": ", " ") }
.map { parts ->
if (parts.size == 2) {
Literal(parts[0], parts[1].toLong())
} else {
Composite(parts[0], parts[1], parts[2], parts[3])
}
}
.associateBy { it.id }
.toMutableMap()
part1(72664227897438) { input["root"]!!.eval(input) }
part2(3916491093817) {
input["z"] = Literal("z", 21973580688943L)
(input["root"] as Composite).let { r ->
// throw it into a solver
input["root"] = Composite("root", r.left, "=", "z")
}
println(input["root"]!!.print(input))
3916491093817
}
}
} | 0 | Kotlin | 0 | 0 | e0b95e35c98b15d2b479b28f8548d8c8ac457e3a | 1,986 | AdventOfCode2022 | Do What The F*ck You Want To Public License |
src/main/kotlin/aoc23/Day08.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc23
import aoc23.Day08Domain.Network
import aoc23.Day08Parser.toNetwork
import aoc23.Day08Solution.part1Day08
import aoc23.Day08Solution.part2Day08
import common.Math.toLowestCommonMultiple
import common.Space3D.Parser.valuesFor
import common.Year23
object Day08 : Year23 {
fun List<String>.part1(): Long = part1Day08()
fun List<String>.part2(): Long = part2Day08()
}
object Day08Solution {
fun List<String>.part1Day08(): Long =
toNetwork()
.toEndSingle()
fun List<String>.part2Day08(): Long =
toNetwork()
.toEndParallel()
}
object Day08Domain {
data class Network(
val instructions: String,
val nodeMap: Map<String, Pair<String, String>>,
) {
private var steps: Long = 0L
private var current = ""
private var endFn: () -> Boolean = { false }
fun toEndSingle(): Long =
stepsToEndWith {
steps = 0L
current = "AAA"
endFn = { current == "ZZZ" }
}
fun toEndParallel(): Long =
startsWithA().map { start ->
stepsToEndWith {
steps = 0L
current = start
endFn = { current.endsWith("Z") }
}
}.toLowestCommonMultiple()
private fun startsWithA(): Set<String> = nodeMap.filter { it.key.endsWith("A") }.keys
private fun stepsToEndWith(setup: () -> Unit): Long {
setup()
stepToEnd()
return steps
}
private fun Network.stepToEnd() {
while (!endFn()) {
instructions.forEach { instruction ->
current = nodeMap[current]!!.nextFor(instruction)
}
steps += instructions.length
}
}
private fun Pair<String, String>.nextFor(c: Char): String =
when (c) {
'L' -> first
'R' -> second
else -> error("bad instruction")
}
}
}
object Day08Parser {
private val nodeRegex = Regex("([A-Z0-9]+) = \\(([A-Z0-9]+|), ([A-Z0-9]+)\\)")
fun List<String>.toNetwork(): Network =
Network(
instructions = this.first().trim(),
nodeMap = this.drop(2).associate { line ->
val (name, left, right) = nodeRegex.valuesFor(line)
name to Pair(left, right)
}
)
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 2,486 | aoc | Apache License 2.0 |
2023/src/main/kotlin/day14.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Grid
import utils.MutableGrid
import utils.Parser
import utils.Solution
import utils.debugString
import utils.rotateCw
import utils.toMutable
fun main() {
Day14.run()
}
object Day14 : Solution<Grid<Char>>() {
override val name = "day14"
override val parser = Parser.charGrid
override fun part1(): Int {
val g = input.toMutable()
tiltNorth(g)
return score(g)
}
override fun part2(): Int {
val limit = 1_000_000_000
val seenAt = mutableMapOf<String, Int>()
val scores = mutableListOf<Int>()
var g = input.toMutable()
var loop = 0 to 0
for (i in 0 until limit) {
g = cycle(g)
scores.add(score(g))
val loopStart = seenAt[g.debugString]
if (loopStart != null) {
loop = loopStart to i
break
}
seenAt[g.debugString] = i
}
return scores[loop.first - 1 + (limit - loop.first) % (loop.second - loop.first)]
}
private fun cycle(grid: MutableGrid<Char>): MutableGrid<Char> {
var g = grid
repeat(4) {
tiltNorth(g)
g = g.rotateCw().toMutable()
}
return g
}
private fun tiltNorth(g: MutableGrid<Char>) {
for (x in 0 until g.width) {
var lastEdge = 0
for (y in 0 until g.height) {
when (g[x][y]) {
'#' -> lastEdge = y + 1
'O' -> {
if (lastEdge != y) {
g[x][lastEdge++] = 'O'
g[x][y] = '.'
} else {
lastEdge++
}
}
else -> { /* ignore */ }
}
}
}
}
private fun score(g: Grid<Char>) = g.cells.sumOf { (p, c) -> if (c != 'O') 0 else (g.height - p.y) }
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,666 | aoc_kotlin | MIT License |
src/UsefulStuff.kt | JaydenPease | 574,590,496 | false | {"Kotlin": 11645} | fun main() {
val input = readInput("numbers")
println("Sum: ${sumAllNums(input)}")
println("Min: ${findMin(input)}")
val wordInput = readInput("sentences")
println(countWords(wordInput))
println(countHWords(wordInput))
val hiWordInput = wordInput.map{
"hi $it"
}
}
fun sumAllNums(input : List<String>): Int {
// var total = 0
// for(num in input) {
// total += num.toInt()
// }
//
// return total
return input.sumOf {
it.toInt()
}
}
fun findMin(input : List<String>) : Int {
return input.minOf {
it.toInt()
}
}
fun findTwoSmallest(input: List<String>) : List<Int> {
// val sorted = input.map {
// it.toInt()
// }.sorted()
//
// return sorted.take(2)
return input.map{
it.toInt()
}.sorted().take(2)
}
fun countWords(input : List<String>) : Int {
var wordCount = 0
for(i in input.indices) {
// val words = input[i].split(" ")
// println(words)
//
// wordCount += words.size
wordCount += input[i].split(" ").size
}
return wordCount
}
fun countHWords(input : List<String>) : Int {
// var hWordCount = 0
//
// for(i in input.indices) {
// val words = input[i].split(" ")
//
// for(j in words.indices) {
// if(words[j].lowercase().startsWith("h")) {hWordCount++}
// }
//
// }
//
// return hWordCount
var count = 0
for(line in input) {
count += line.split(" ").count {
it.startsWith("h", true)
}
}
return count
} | 0 | Kotlin | 0 | 0 | 0a5fa22b3653c4b44a716927e2293fc4b2ed9eb7 | 1,579 | AdventOfCode-2022 | Apache License 2.0 |
src/UsefulExample.kt | LucasDuBria | 574,598,208 | false | {"Kotlin": 2250} | fun main(){
val input = readInput("numbers")
println("Sum: ${sumAllNum(input)}")
println("Min: ${findMin(input)}")
println("Add2Smallest: ${addTwoSmallest(input)}")
val wordInput = readInput("sentences")
println("totalWords: ${countWords(wordInput)}")
println("totalHWords: ${countHWords(wordInput)}")
}
fun sumAllNum(input : List<String>) : Int {
// var total = 0
// for(num in input){
// total += num.toInt()
// }
// return total
return input.map { it.toInt() }.sum()
}
fun findMin(input : List<String>) : Int {
return input.map {it.toInt()}.min()
}
fun addTwoSmallest(input : List<String>) : Int {
val sorted = input.map { it.toInt() }.sorted()
println(sorted.take(2))
return input.map { it.toInt() }.sorted().take(2).sum()
}
fun countWords(input : List<String>) : Int {
var wordCount = 0
for (line in input) {
wordCount += line.split(" ").size
}
return wordCount
}
fun countHWords(input : List<String>) : Int {
var count = 0
for(line in input){
count += line.split(" ").count {
it.startsWith("h", true)
}
}
return count
} | 0 | Kotlin | 0 | 0 | d6d886fe589fb39f2b592851ae4c0a8fab728411 | 1,201 | LoginAndRegistration | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2022/Day08.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2022
import ru.timakden.aoc.util.Point
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 8: Treetop Tree House](https://adventofcode.com/2022/day/8).
*/
object Day08 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2022/Day08")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
var visibleTrees = 0
val treeGrid = input.map { row -> row.map { it.digitToInt() } }
val lastColumnIndex = treeGrid.first().lastIndex
val lastRowIndex = treeGrid.lastIndex
val heights = mutableMapOf<Point, Int>()
treeGrid.forEachIndexed { i, trees -> trees.forEachIndexed { j, tree -> heights[Point(i, j)] = tree } }
treeGrid.forEachIndexed { i, trees ->
for (j in trees.indices) {
val tree = trees[j]
if (i == 0 || j == 0 || i == lastRowIndex || j == lastColumnIndex) visibleTrees++
else {
if (heights.filterKeys { it.x == i && it.y in (0..<j) }.all { it.value < tree }) {
visibleTrees++
continue
}
if (heights.filterKeys { it.x == i && it.y in (j + 1..lastColumnIndex) }
.all { it.value < tree }
) {
visibleTrees++
continue
}
if (heights.filterKeys { it.x in (0..<i) && it.y == j }.all { it.value < tree }) {
visibleTrees++
continue
}
if (heights.filterKeys { it.x in (i + 1..lastRowIndex) && it.y == j }
.all { it.value < tree }
) {
visibleTrees++
continue
}
}
}
}
return visibleTrees
}
fun part2(input: List<String>): Int {
val treeGrid = input.map { row -> row.map { it.digitToInt() } }
val lastColumnIndex = treeGrid.first().lastIndex
val lastRowIndex = treeGrid.lastIndex
val heights = mutableMapOf<Point, Int>()
val scenicScores = mutableMapOf<Point, Int>()
treeGrid.forEachIndexed { i, trees -> trees.forEachIndexed { j, tree -> heights[Point(i, j)] = tree } }
treeGrid.forEachIndexed { i, trees ->
trees.forEachIndexed { j, tree ->
if (i == 0 || j == 0 || i == lastRowIndex || j == lastColumnIndex) scenicScores[Point(i, j)] = 0
else {
val scoreLeft = kotlin.run {
var count = 0
for (k in j - 1 downTo 0) {
if (checkNotNull(heights[Point(i, k)]) < tree) count++
else if (checkNotNull(heights[Point(i, k)]) >= tree) {
count++
break
} else break
}
count
}
val scoreRight = kotlin.run {
var count = 0
for (k in j + 1..lastColumnIndex) {
if (checkNotNull(heights[Point(i, k)]) < tree) count++
else if (checkNotNull(heights[Point(i, k)]) >= tree) {
count++
break
} else break
}
count
}
val scoreUp = kotlin.run {
var count = 0
for (k in i - 1 downTo 0) {
if (checkNotNull(heights[Point(k, j)]) < tree) count++
else if (checkNotNull(heights[Point(k, j)]) >= tree) {
count++
break
} else break
}
count
}
val scoreDown = kotlin.run {
var count = 0
for (k in i + 1..lastRowIndex) {
if (checkNotNull(heights[Point(k, j)]) < tree) count++
else if (checkNotNull(heights[Point(k, j)]) >= tree) {
count++
break
} else break
}
count
}
scenicScores[Point(i, j)] = scoreLeft * scoreRight * scoreUp * scoreDown
}
}
}
return scenicScores.maxOf { it.value }
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 4,996 | advent-of-code | MIT License |
year2018/src/main/kotlin/net/olegg/aoc/year2018/day7/Day7.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2018.day7
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2018.DayOf2018
import kotlin.math.max
/**
* See [Year 2018, Day 7](https://adventofcode.com/2018/day/7)
*/
object Day7 : DayOf2018(7) {
private val PATTERN = "Step (\\w) must be finished before step (\\w) can begin\\.".toRegex()
override fun first(): Any? {
val edges = lines
.mapNotNull { line ->
PATTERN.matchEntire(line)?.let { match ->
val (a, b) = match.destructured
return@mapNotNull a to b
}
}
val vertices = edges.flatMap { it.toList() }.toMutableSet()
val neighbors = edges
.groupBy { it.first }
.mapValuesTo(mutableMapOf()) { neighbors ->
neighbors.value.map { it.second }.toSet()
}
val answer = mutableListOf<String>()
while (vertices.isNotEmpty()) {
val next = vertices
.filter { v ->
neighbors.none { v in it.value }
}
.minOf { it }
answer += next
vertices.remove(next)
neighbors.remove(next)
}
return answer.joinToString(separator = "")
}
override fun second(): Any? {
val edges = lines
.mapNotNull { line ->
PATTERN.matchEntire(line)?.let { match ->
val (a, b) = match.destructured
return@mapNotNull a to b
}
}
val vertices = edges.flatMap { it.toList() }.toMutableSet()
val neighbors = edges
.groupBy { it.first }
.mapValuesTo(mutableMapOf()) { neighbors ->
neighbors.value.map { it.second }.toSet()
}
val start = vertices.associateWithTo(mutableMapOf()) { 0 }
val workers = IntArray(5) { 0 }
while (vertices.isNotEmpty()) {
val available = vertices
.filter { v ->
neighbors.none { v in it.value }
}
val soonest = start
.filter { it.key in available }
.minOfOrNull { it.value } ?: 0
val next = available
.sorted()
.first { start[it] == soonest }
val minWorker = workers.min()
val worker = workers.indexOfFirst { it == minWorker }
val time = max(workers[worker], soonest) + 61 + (next[0] - 'A')
workers[worker] = time
vertices.remove(next)
neighbors
.remove(next)
.orEmpty()
.filter { it in vertices }
.forEach { v ->
start[v] = max(start[v] ?: 0, time)
}
}
return workers.max()
}
}
fun main() = SomeDay.mainify(Day7)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,488 | adventofcode | MIT License |
src/main/kotlin/day02/Day02.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day02
import readInput
fun main() {
fun part1(input: List<String>): Int {
return input.fold(0) { acc, line ->
val p1 = line[0] - 'A' + 1
val p2 = line[2] - 'X' + 1
acc + p2 + if (p1 == p2) {
3
} else if (p2 - p1 == 1 || (p1 == 3 && p2 == 1)) {
6
} else {
0
}
}
}
fun part2(input: List<String>): Int {
return input.fold(0) { acc, line ->
val p1 = line[0] - 'A'
val p2 = when (line[2]) {
'X' -> (p1 + 3 - 1) % 3
'Y' -> p1
'Z' -> (p1 + 1) % 3
else -> error(line[2])
}
acc + p2 + 1 + when (line[2]) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> error(line[2])
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day02", "test")
val input = readInput("day02", "input")
check(part1(testInput) == 22)
println(part1(input))
check(part2(testInput) == 14)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 1,208 | aoc2022 | Apache License 2.0 |
src/day05/Day05.kt | tschens95 | 573,743,557 | false | {"Kotlin": 32775} | package day05
import readText
fun main() {
val crateMap = mutableMapOf<Int, MutableList<String>>()
fun initMap(length: Int) {
for(i in 0 until length) {
crateMap[i] = mutableListOf()
}
}
fun moveCrate(command: Command, reversePart2: Boolean) {
val cratesFrom = crateMap[command.crateFrom - 1] ?: throw RuntimeException("null")
val x = cratesFrom.size
val cratesList = cratesFrom.subList(x - command.number, x)
if (!reversePart2) cratesList.reverse()
crateMap[command.crateFrom - 1] = cratesFrom.subList(0, x - command.number)
crateMap[command.crateTo - 1] = crateMap[command.crateTo - 1]!!.plus(cratesList).toMutableList()
}
fun solvePuzzle(input: List<String>, reversePart2: Boolean): String {
val crates = input[0]
val commands = input[1]
val commandList = commands.split("\n").map {
val parts = it.split(" ")
val number = parts[1].toInt()
val from = parts[3].toInt()
val to = parts[5].trim().toInt()
Command(number, from, to)
}
val lines = crates.split("\n")
val length = lines[lines.size - 1].split(" ").map { it.trim().toInt() }.last()
initMap(length)
var rowCount = 0
while (rowCount < lines.size - 1) {
val s = lines[rowCount]
var i = 0
var column = 0
while (column < length) {
val element = s.substring(i + 1, i + 2)
if (element.isNotBlank()) {
crateMap[column]!!.add(element)
}
i += 4
column += 1
}
rowCount += 1
}
for (s in crateMap.values) {
s.reverse()
}
for (c in commandList) {
moveCrate(c, reversePart2)
}
var resultString = ""
for (a in crateMap.values) {
resultString += a.last()
}
return resultString
}
// the list contains (crates, rearrangement commands), the last line of crates are the numbers of the crate
fun part1(input: List<String>) : String {
return solvePuzzle(input, false)
}
fun part2(input: List<String>) : String {
return solvePuzzle(input, true)
}
val testInput =
" [D] \n" +
"[N] [C] \n" +
"[Z] [M] [P]\n" +
" 1 2 3 \n" +
"\n" +
"move 1 from 2 to 1\n" +
"move 3 from 1 to 3\n" +
"move 2 from 2 to 1\n" +
"move 1 from 1 to 2"
println(part1(testInput.split("\n\n")))
println(part2(testInput.split("\n\n")))
val input = readText("05").split("\r\n\r\n")
println("Part1:")
println(part1(input))
println("Part2:")
println(part2(input))
}
data class Command(val number: Int, val crateFrom: Int, val crateTo: Int) | 0 | Kotlin | 0 | 2 | 9d78a9bcd69abc9f025a6a0bde923f53c2d8b301 | 2,961 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/dp/LBS.kt | yx-z | 106,589,674 | false | null | package dp
// longest bitonic subsequence
// X[1..n] is bitonic if there exists i: 1 < i < n, X[1..i] is inscreasing and X[i..n] is decreasing
// find the length of lbs of A[1..n]
fun main(args: Array<String>) {
val a = intArrayOf(1, 11, 2, 10, 4, 5, 2, 1)
println(a.lbs())
}
fun IntArray.lbs(): Int {
val A = this
val n = A.size
// inc(i): length of LIS that ends @ A[i]
// 1d array inc[1..n] : inc[i] = inc(i)
val inc = IntArray(n)
// dec(i): length of LDS that starts @ A[i]
// 1d array dec[1..n] : dec[i] = dec(i)
val dec = IntArray(n)
// space complexity: O(n)
// base case:
// inc(1) = 1
// dec(n) = 1
inc[0] = 1
dec[n - 1] = 1
// recursive case:
// assume max{ } = 0
// inc(i) = max{ inc(k) } + 1 for k in 1 until i and A[k] < A[i]
// dec(i) = max{ dec(k) } + 1 for k in i + 1..n and A[k] < A[i]
// dependency: inc(i) depends on inc(k) where k < i, i.e. entries to the left
// dec(i) depends on dec(k) where k > i, i.e. entries to the right
// evaluation order: for inc(i), iterate i,k from 1 to n (left to right)
for (i in 1 until n) {
inc[i] = (inc.filterIndexed { k, _ -> k < i && A[k] < A[i] }.max() ?: 0) + 1
}
// for dec(i), iterate i, k from n down to 1 (right to left)
for (i in n - 2 downTo 0) {
dec[i] = (dec.filterIndexed { k, _ -> k > i && A[k] < A[i] }.max() ?: 0) + 1
}
// time complexity: O(n^2)
// we want max_i{ inc(i) + dec(i) } - 1 (- 1 since we count A[it] twice)
return (0 until n).map { inc[it] + dec[it] }.max()!! - 1
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,505 | AlgoKt | MIT License |
src/day04/src/main/kotlin/eu/gillespie/aoc2021/day04/Model.kt | TimothyGillespie | 433,972,043 | false | {"TypeScript": 8572, "Kotlin": 6335, "Dart": 4911, "JavaScript": 3018, "Shell": 1078} | package eu.gillespie.aoc2021.day04
import kotlin.math.roundToInt
import kotlin.math.sqrt
data class Game(
val boards: List<Board>,
) {
/**
* Marks a number in the board and returns a list of all boards
* which have now been won.
*/
fun drawNumber(number: Int): List<Int> {
val nowWinning = mutableListOf<Int>()
boards.forEachIndexed { index, singleBoard ->
if(singleBoard.markNumber(number)) {
nowWinning.add(index)
}
}
return nowWinning
}
}
data class Board(
val configuration: Map<Int, Field>,
var won: Boolean = false,
) {
fun markNumber(number: Int): Boolean {
val alreadyWon = won
val field = configuration[number]
if(field !== null) {
field.mark()
updateWon()
}
return won && !alreadyWon
}
private fun updateWon() {
val markedCoordinates = this.configuration.values
.filter { it.marked }
.map { it.coordinate }
val size = getSize()
// Checking rows and columns
for(i in 1..size) {
val markedRowI = markedCoordinates.filter { it.first == i }
val markedColI = markedCoordinates.filter { it.second == i }
if(markedRowI.size == size || markedColI.size == size) {
won = true
return
}
}
won = false
}
fun getSize(): Int {
return sqrt(this.configuration.entries.size.toDouble()).roundToInt()
}
fun deepCopy(): Board {
val configurationCopy = this.configuration.toMap()
.map { it.key to it.value.copy() }
.toMap()
return Board(configurationCopy, this.won)
}
override fun toString(): String {
val size = getSize()
val digitMaxCount = this.configuration
.maxOf { it.key }
.toString()
.length
val ordered = this.configuration.entries.sortedBy {
val coordinate = it.value.coordinate
coordinate.second + (coordinate.first - 1) * size
}
var result = ""
for(i in 0 until size) {
if(i > 0)
result += "\n"
for(j in 0 until size) {
if(j > 0)
result += " "
result += ordered.get(j + i * size).key
.toString().padStart(digitMaxCount)
}
}
return result
}
}
data class Field(
// First value is the row; Second value is the column
// Both starting at 1
val coordinate: Pair<Int, Int>,
var marked: Boolean = false,
) {
fun mark() {
this.marked = true
}
}
| 0 | TypeScript | 0 | 1 | 0357d97854699703e2628e315cec1b4c7f68a5e0 | 2,755 | AdventOfCode2021 | The Unlicense |
src/main/kotlin/cc/suffro/bpmanalyzer/Helpers.kt | xsoophx | 579,535,622 | false | {"Kotlin": 71055} | package cc.suffro.bpmanalyzer
import cc.suffro.bpmanalyzer.fft.data.FrequencyDomainWindow
import org.kotlinmath.Complex
import org.kotlinmath.sqrt
fun abs(n: Complex): Double = sqrt(n.re * n.re + n.im * n.im).re
fun getHighestPowerOfTwo(number: Int): Int {
var result = number
generateSequence(1) { (it * 2) }
.take(5)
.forEach { position -> result = result or (result shr position) }
return result xor (result shr 1)
}
fun List<FrequencyDomainWindow>.interpolate(): List<FrequencyDomainWindow> {
val interpolated = asSequence().zipWithNext().map { (current, next) ->
FrequencyDomainWindow(
getAverageMagnitude(current.magnitudes, next.magnitudes),
(next.startingTime + current.startingTime) / 2
)
}.toList()
return (interpolated + this).sortedBy { it.startingTime }
}
private fun getAverageMagnitude(current: List<Double>, next: List<Double>): List<Double> =
current.zip(next).map { (c, n) -> (c + n) / 2 }
fun List<FrequencyDomainWindow>.scaleMagnitudes(): List<FrequencyDomainWindow> {
val maximumMagnitudes = map { it.magnitudes.max() }
val maximum = maximumMagnitudes.max()
return map { window ->
val scaledMagnitudes = window.magnitudes.map { it / maximum }
FrequencyDomainWindow(scaledMagnitudes, window.startingTime)
}
}
data class Interval<T>(
val lowerBound: T,
val upperBound: T
)
| 0 | Kotlin | 0 | 0 | 85fbb14a2762b5051753de02fa3b796eeff7608c | 1,426 | BPM-Analyzer | MIT License |
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day08/Day08.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2022.day08
import nerok.aoc.utils.Direction
import nerok.aoc.utils.Input
import nerok.aoc.utils.Point
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun part1(input: List<String>): Long {
val grid = Grid()
input
.filter { it.isNotEmpty() }
.forEachIndexed { rowIndex, line ->
grid.rows.add(
line
.split("")
.filter { it.isNotBlank() }
.mapIndexed { colIndex, s ->
Point(s.toInt(), rowIndex, colIndex)
}.toMutableList()
)
}
return grid.findVisible().count().toLong()
}
fun part2(input: List<String>): Long {
val grid = Grid()
input
.filter { it.isNotEmpty() }
.forEachIndexed { rowIndex, line ->
grid.rows.add(
line
.split("")
.filter { it.isNotBlank() }
.mapIndexed { colIndex, s ->
Point(s.toInt(), rowIndex, colIndex)
}.toMutableList()
)
}
return grid.calculateScenicScore().max().toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day08_test")
check(part1(testInput) == 21L)
check(part2(testInput) == 8L)
val input = Input.readInput("Day08")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
class Grid(var rows: MutableList<MutableList<Point<Int>>> = emptyList<MutableList<Point<Int>>>().toMutableList()) {
fun findVisible(): Grid {
return Direction.entries
.map { direction -> this.skyline(direction) }
.reduce { acc, grid -> acc.merge(grid) }
}
private fun merge(grid: Grid): Grid {
this.rows.mapIndexed { rowIndex, columns ->
columns.mapIndexed { colIndex, point ->
if (point.content == -1 && grid[rowIndex, colIndex].content != -1) {
point.content = grid[rowIndex, colIndex].content
}
}
}
return this
}
private fun skyline(direction: Direction): Grid {
val tmpGrid = when (direction) {
Direction.NORTH -> {
this.copy()
}
Direction.EAST -> {
this.transpose().rowReversed()
}
Direction.SOUTH -> {
this.rowReversed()
}
Direction.WEST -> {
this.transpose()
}
}
val skyline = tmpGrid.copy()
val maxRow = tmpGrid.rows.first().toMutableList()
tmpGrid.rows
.drop(1)
.forEachIndexed { rowIndex, columns ->
columns
.forEachIndexed { colIndex, point ->
if (maxRow[colIndex].content < point.content) {
maxRow[colIndex] = point.copy()
} else {
skyline[rowIndex + 1, colIndex].content = -1
}
}
}
return when (direction) {
Direction.NORTH -> {
skyline.copy()
}
Direction.EAST -> {
skyline.rowReversed().transpose()
}
Direction.SOUTH -> {
skyline.rowReversed()
}
Direction.WEST -> {
skyline.transpose()
}
}
}
private fun copy(): Grid {
return Grid(
rows = rows
.map { cols ->
cols.map { point ->
point.copy()
}.toMutableList()
}
.toMutableList()
)
}
private fun rowReversed(): Grid {
val rowReversed = this.copy()
rowReversed.rows.reverse()
return rowReversed
}
private fun transpose(): Grid {
val transposed = this.copy()
this.rows.forEachIndexed { rowIndex, cols ->
cols.forEachIndexed { colsIndex, point ->
transposed[colsIndex, rowIndex] = point.copy()
}
}
return transposed
}
private operator fun set(row: Int, column: Int, value: Point<Int>) {
rows[row][column] = value
}
operator fun get(row: Int, column: Int): Point<Int> {
return rows[row][column]
}
override fun toString(): String {
return rows.joinToString("\n") { points -> points.joinToString("\t") { it.toString() } }
}
fun count(): Int {
return rows.sumOf { columns -> columns.count { point -> point.content >= 0 } }
}
fun calculateScenicScore(): Grid {
val scenicScoreGrid = this.copy()
this.rows.forEachIndexed { rowIndex, columns ->
columns.forEachIndexed { columnIndex, point ->
var score = 1
// South
var i = 1
if (rowIndex + i >= this.rows.size) {
i = 0
} else while (rowIndex + i < this.rows.size - 1 && this[rowIndex + i, columnIndex].content < point.content) {
i++
}
score *= i
// North
i = 1
if (rowIndex - i < 0) {
i = 0
} else while (rowIndex - i > 0 && this[rowIndex - i, columnIndex].content < point.content) {
i++
}
score *= i
// East
i = 1
if (columnIndex + i >= this.rows.first().size) {
i = 0
} else while (columnIndex + i < this.rows.first().size - 1 && this[rowIndex, columnIndex + i].content < point.content) {
i++
}
score *= i
// West
i = 1
if (columnIndex - i < 0) {
i = 0
} else while (columnIndex - i > 0 && this[rowIndex, columnIndex - i].content < point.content) {
i++
}
score *= i
scenicScoreGrid[rowIndex, columnIndex].content = score
}
}
return scenicScoreGrid
}
fun max(): Int = this.rows.maxOf { col -> col.maxOf { it.content } }
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 6,703 | AOC | Apache License 2.0 |
src/Day20.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | import kotlin.math.absoluteValue
fun main() {
data class Node(var number: Long) {
lateinit var prev: Node
lateinit var next: Node
fun remove() {
this.prev.next = this.next
this.next.prev = this.prev
}
fun insertAfter(a: Node) {
val b = a.next
prev = a
next = b
a.next = this
b.prev = this
}
fun get(diff: Int): Node {
var current = this
val forward = diff > 0
repeat(diff.absoluteValue) {
current = if (forward) current.next else current.prev
}
return current
}
fun toList(): List<Node> = buildList {
add(this@Node)
var current = next
while (current !== this@Node) {
add(current)
current = current.next
}
}
}
fun parse(input: List<String>): List<Node> {
val nodes = input.map { Node(it.toLong()) }
for ((a, b) in nodes.windowed(2, 1)) {
a.next = b
b.prev = a
}
nodes.first().prev = nodes.last()
nodes.last().next = nodes.first()
return nodes
}
fun part1(input: List<String>): Long {
val nodes = parse(input)
for (node in nodes) {
if (node.number == 0L) continue
val prev = node.prev
node.remove()
node.insertAfter(prev.get(node.number.toInt()))
}
val zero = nodes.first { it.number == 0L }
val a = zero.get(1000)
val b = a.get(1000)
val c = b.get(1000)
return a.number + b.number + c.number
}
fun part2(input: List<String>): Long {
val nodes = parse(input)
for (node in nodes) {
node.number *= 811589153
}
repeat(10) {
for (node in nodes) {
if (node.number == 0L) continue
val prev = node.prev
node.remove()
val list = prev.toList()
check(list.size == nodes.size - 1)
val insertAfter = list[Math.floorMod(node.number, list.size)]
node.insertAfter(insertAfter)
}
}
val list = nodes.first { it.number == 0L }.toList()
return list[1000 % list.size].number + list[2000 % list.size].number + list[3000 % list.size].number
}
// test if implementation meets criteria from the description, like:
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 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 2,765 | AdventOfCode2022 | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day226/day226.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day226
// day226.kt
// By <NAME>, 2019.
import java.util.LinkedList
/**
* Given a list of "words" sorted alphabetically (according to an arbitrary alphabet that does not necessarily
* correspond to a normal alphabet), find the underlying order of the alphabet.
*
* We want to find the rules governing the alphabet symbols. This can be done through the operation of leftwise
* elimination, which is, given two words, eliminating the leftmost portion of the two words that is identical to
* reduce to a relationship between two letters. For example:
* babies < babylon -> eliminate bab -> ies < ylon -> i < y in the alphabet
* We can do this pairwise through the list of words to get a sufficient set of rules to determine the alphabet.
* We represent this by a directed graph where a tree's children are the symbols that appear after it.
* In the example above, y will be a child of i.
*/
typealias SymbolList = List<Char>
// Information about the comparison
fun findAlphabet(words: List<String>): SymbolList {
// We want a set of all characters.
val symbols: SymbolList = words.flatMap { it.toList() }.toSet().toList()
// The topological graph.
val graph = mutableMapOf<Char,MutableSet<Char>>()
symbols.forEach { graph[it] = mutableSetOf() }
/**
* The result of comparing two distinct words: we left-eliminate all same characters and then return the first
* pair - providing it exists - of different characters, with the relationship between those characters based on
* the relationship between the initial two words.
*/
class Rule(word1: String, word2: String) {
val char1: Char?
val char2: Char?
init {
val (remain1, remain2) = word1.zip(word2).dropWhile { it.first == it.second }.unzip()
char1 = remain1.firstOrNull()
char2 = remain2.firstOrNull()
}
}
/**
* Compare words pairwise.
*/
words.zipWithNext { w1, w2 ->
/**
* w1 < w2 by virtue that it appears first in the dictionary, so Rule.char1 < Rule.char2 after left elimination
* if there is both a char1 and a char2 left.
*/
val result = Rule(w1, w2)
if (result.char2 != null)
graph[result.char1]?.add(result.char2)
}
/**
* Perform a topological sort to get the alphabet ordering.
* This depends on visiting the symbols in a coherent order and then adding them at depths that make sense.
*/
val alphabet = LinkedList<Char>()
val visited = mutableSetOf<Char>()
fun visit(char: Char) {
visited.add(char)
graph[char]?.forEach{
if (it !in visited)
visit(it)
}
alphabet.addFirst(char)
}
graph.keys.forEach {
if (it !in visited)
visit(it)
}
return alphabet
} | 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 2,890 | daily-coding-problem | MIT License |
src/main/kotlin/com/anahoret/aoc2022/day18/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day18
import java.io.File
import kotlin.system.measureTimeMillis
data class Point(val x: Long, val y: Long, val z: Long) {
fun neighbours(): List<Point> {
return listOf(
copy(x = x - 1),
copy(x = x + 1),
copy(y = y - 1),
copy(y = y + 1),
copy(z = z - 1),
copy(z = z + 1),
)
}
fun outside(boundingBox: BoundingBox): Boolean {
return x !in boundingBox.xRange || y !in boundingBox.yRange || z !in boundingBox.zRange
}
}
class BoundingBox(points: List<Point>) {
val xRange = points.minOf { it.x }..points.maxOf { it.x }
val yRange = points.minOf { it.y }..points.maxOf { it.y }
val zRange = points.minOf { it.z }..points.maxOf { it.z }
}
fun parsePoints(str: String): List<Point> {
return str.split("\n")
.map { it.split(",").map(String::toLong) }
.map { (x, y, z) -> Point(x, y, z) }
}
fun main() {
val points = File("src/main/kotlin/com/anahoret/aoc2022/day18/input.txt")
.readText()
.trim()
.let(::parsePoints)
// Part 1
part1(points).also { println("P1: ${it}ms") }
// Part 2
part2(points).also { println("P2: ${it}ms") }
}
private fun part1(points: List<Point>) = measureTimeMillis {
calculateSurface(points)
.also { println(it) }
}
private fun calculateSurface(
points: List<Point>,
): Int {
val lava = points.toSet()
return points.sumOf { p ->
6 - p.neighbours().count { it in lava }
}
}
private fun part2(points: List<Point>) = measureTimeMillis {
val boundingBox = BoundingBox(points)
val lava = points.toSet()
val neighbours = points.flatMap(Point::neighbours)
val surface = calculateSurface(points)
val internalCandidates = neighbours
.filterNot { it in lava || it.outside(boundingBox) }
.toMutableSet()
fun growBulb(start: Point): Pair<Boolean, Set<Point>> {
val acc = mutableSetOf(start)
val visited = mutableSetOf<Point>()
val queue = ArrayDeque<Point>()
queue.add(start)
var isAirPocket = true
while (queue.isNotEmpty()) {
val point = queue.removeFirst()
visited.add(point)
acc.add(point)
val airNeighbours = point.neighbours()
.filterNot { it in lava || it in visited }
if (isAirPocket && (point.outside(boundingBox) || airNeighbours.any { it.outside(boundingBox) })) {
isAirPocket = false
}
val airNeighboursInsideBorderBox = airNeighbours.filterNot { it.outside(boundingBox) }
visited.addAll(airNeighboursInsideBorderBox)
queue.addAll(airNeighboursInsideBorderBox)
}
return isAirPocket to acc
}
val airPocketPoints = mutableSetOf<Point>()
while (internalCandidates.isNotEmpty()) {
val candidate = internalCandidates.first()
val (isAirPocket, bulb) = growBulb(candidate)
internalCandidates.removeAll(bulb)
if (isAirPocket) {
airPocketPoints.addAll(bulb)
}
}
val excludedSurface = airPocketPoints
.flatMap(Point::neighbours)
.count { it in lava }
println(surface - excludedSurface)
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 3,309 | advent-of-code-2022 | Apache License 2.0 |
2021/src/main/kotlin/com/trikzon/aoc2021/Day8.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("/day8.txt")
benchmark(Part.One, ::day8Part1, input, 512, 50000)
benchmark(Part.Two, ::day8Part2, input, 1091165, 5000)
}
fun day8Part1(input: String): Int {
var instances = 0
input.lines().forEach { line ->
val outputValues = line.split(" | ")[1].split(' ').map { str -> str.trim() }
for (outputValue in outputValues) {
if (outputValue.length == 2 || outputValue.length == 4 || outputValue.length == 3 || outputValue.length == 7) {
instances++
}
}
}
return instances
}
fun day8Part2(input: String): Int {
var output = 0
input.lines().forEach { line ->
val inputValues = line.split(" | ")[0].split(' ')
val digits = Array(10) { "" }
val fiveSegments = ArrayList<String>()
val sixSegments = ArrayList<String>()
for (inputValue in inputValues) {
when (inputValue.length) {
2 -> digits[1] = inputValue
4 -> digits[4] = inputValue
3 -> digits[7] = inputValue
7 -> digits[8] = inputValue
5 -> fiveSegments.add(inputValue)
6 -> sixSegments.add(inputValue)
}
}
var c: Char? = null
var f: Char? = null
// Decode c and f
var occurrences = 0
for (sixSegment in sixSegments) {
if (sixSegment.contains(digits[1][0])) occurrences++
}
if (occurrences == 3) {
c = digits[1][1]
f = digits[1][0]
} else {
c = digits[1][0]
f = digits[1][1]
}
// Find 6
for (sixSegment in sixSegments) {
if (!sixSegment.contains(c)) {
digits[6] = sixSegment
}
}
// Find 2, 3, and 5
for (fiveSegment in fiveSegments) {
if (fiveSegment.contains(c)) {
if (fiveSegment.contains(f)) {
digits[3] = fiveSegment
} else {
digits[2] = fiveSegment
}
} else {
digits[5] = fiveSegment
}
}
val adg = digits[2].chars()
.filter { char -> digits[3].contains(char.toChar()) && digits[5].contains(char.toChar()) }
.toArray()
.map { i -> i.toChar() }
// Find 0 and 9
for (sixSegment in sixSegments) {
if (sixSegment != digits[6]) {
if (sixSegment.contains(adg[0]) && sixSegment.contains(adg[1]) && sixSegment.contains(adg[2])) {
digits[9] = sixSegment
} else {
digits[0] = sixSegment
}
}
}
val outputValues = line.split(" | ")[1].split(' ')
val outputDigits = Array(4) { 0 }
for (i in outputValues.indices) {
for (j in digits.indices) {
var numberMatching = 0
for (char in digits[j].chars()) {
if (outputValues[i].contains(char.toChar())) numberMatching++
}
if (numberMatching == outputValues[i].length && numberMatching == digits[j].length) {
outputDigits[i] = j
break
}
}
}
output += outputDigits[0] * 1000 + outputDigits[1] * 100 + outputDigits[2] * 10 + outputDigits[3]
}
return output
}
| 0 | Kotlin | 1 | 0 | d4dea9f0c1b56dc698b716bb03fc2ad62619ca08 | 3,536 | advent-of-code | MIT License |
src/main/kotlin/com/github/dangerground/aoc2020/Day21.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
fun main() {
val process = Day21(DayInput.asStringList(21))
println("result part 1: ${process.part1()}")
println("result part 2: ${process.part2()}")
}
class Day21(val input: List<String>) {
val ingredientsMap = input.map {
val tmp = it.split(" (contains ")
tmp[0].split(" ") to tmp[1].dropLast(1).split(", ").map { it.trim() }
}.toMap()
val alergenes = mutableMapOf<String, MutableSet<String>>()
val foods = mutableMapOf<String, MutableSet<String>>()
init {
ingredientsMap.forEach { entry ->
entry.value.forEach { alergene ->
if (!alergenes.containsKey(alergene)) {
alergenes[alergene] = entry.key.toMutableSet()
} else {
alergenes[alergene]!!.removeIf { !entry.key.contains(it) }
//alergenes[alergene]!!.addAll(entry.key)
}
}
}
ingredientsMap.forEach { entry ->
entry.key.forEach { food ->
if (!foods.containsKey(food)) {
foods[food] = entry.value.toMutableSet()
} else {
foods[food]!!.addAll(entry.value)
}
}
}
val single = mutableSetOf<String>()
var changed: Boolean
do {
changed = false
alergenes.forEach {
if (it.value.size == 1) {
single.add(it.value.first())
} else {
val before = it.value.size
it.value.removeIf { single.contains(it) }
if (before != it.value.size) {
changed = true
}
}
}
} while (changed)
val singleFood = mutableMapOf<String, String>()
do {
changed = false
foods.forEach {
if (it.value.size == 1) {
singleFood[it.value.first()] = it.key
} else {
val before = it.value.size
it.value.removeIf { singleFood.keys.contains(it) }
if (before != it.value.size) {
changed = true
}
}
}
} while (changed)
println("single: $foods")
}
fun part1(): Int {
val allFoods = ingredientsMap.keys.flatten().toSet()
val safeIngredients = allFoods.toMutableList()
alergenes.values.forEach { list ->
safeIngredients.removeIf { list.contains(it) }
}
return safeIngredients.map { ingr ->
ingredientsMap.keys.count { list -> list.contains(ingr) }
}.sum()
}
fun part2(): String {
val dangerous = alergenes.map { it.key to it.value.first() }.toMap()
println(alergenes)
// println(dangerous)
if (alergenes.map { it.value.size > 1 }.filter { it }.count() > 0) println("ERROR")
return dangerous.keys.sorted().map { dangerous[it]!! }.joinToString(separator = ",")
}
}
| 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 3,207 | adventofcode-2020 | MIT License |
src/main/kotlin/g0601_0700/s0630_course_schedule_iii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0601_0700.s0630_course_schedule_iii
// #Hard #Array #Greedy #Heap_Priority_Queue #2023_02_09_Time_536_ms_(100.00%)_Space_58_MB_(100.00%)
import java.util.PriorityQueue
class Solution {
fun scheduleCourse(courses: Array<IntArray>): Int {
// Sort the courses based on their deadline date.
courses.sortWith { a: IntArray, b: IntArray ->
a[1] - b[1]
}
// Only the duration is stored. We don't care which course
// is the longest, we only care about the total courses can
// be taken.
// If the question wants the course ids to be returned.
// Consider use a Pair<Duration, CourseId> int pair.
val pq = PriorityQueue { a: Int, b: Int -> b - a }
// Total time consumed.
var time = 0
// At the given time `course`, the overall "time limit" is
// course[1]. All courses in pq is already 'valid'. But
// adding this course[0] might exceed the course[1] limit.
for (course in courses) {
// If adding this course doesn't exceed. Let's add it
// for now. (Greedy algo). We might remove it later if
// we have a "better" solution at that time.
if (time + course[0] <= course[1]) {
time += course[0]
pq.offer(course[0])
} else {
// If adding this ecxeeds the limit. We can still add it
// if-and-only-if there are courses longer than current
// one. If so, by removing a longer course, current shorter
// course can fit in for sure. Although the total course
// count is the same, the overall time consumed is shorter.
// Which gives us more room for future courses.
// Remove any course that is longer than current course
// will work, but we remove the longest one with the help
// of heap (pq).
if (pq.isNotEmpty() && pq.peek() > course[0]) {
time -= pq.poll()
time += course[0]
pq.offer(course[0])
}
// If no course in consider (pq) is shorter than the
// current course. It is safe to discard it.
}
}
return pq.size
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,351 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/sep_challenge2021/ShortestPathGridWithObstacles.kt | yvelianyk | 405,919,452 | false | {"Kotlin": 147854, "Java": 610} | package sep_challenge2021
import java.util.*
fun main() {
val grid = arrayOf(
intArrayOf(0, 0, 0),
intArrayOf(1, 1, 0),
intArrayOf(0, 0, 0),
intArrayOf(0, 1, 1),
intArrayOf(0, 0, 0),
)
val result = shortestPath(grid, 1)
assert(result == 6)
println(result)
}
val directions = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(0, 1))
fun shortestPath(grid: Array<IntArray>, k: Int): Int {
val m = grid.size
val n = grid[0].size
val visited = Array(grid.size) { Array(grid[0].size) { IntArray(grid[0].size * grid.size + 1) } }
val queue: Queue<IntArray> = LinkedList()
queue.add(intArrayOf(0, 0, k, 0))
while (!queue.isEmpty()) {
val current = queue.poll()
val i = current[0]
val j = current[1]
val currentRemain = current[2]
val currentDist = current[3]
if (visited[i][j][currentRemain] == 1) continue
visited[i][j][currentRemain] = 1
if (i == m - 1 && j == n - 1) return currentDist
for (direction in directions) {
val newI = i + direction[0]
val newJ = j + direction[1]
if (newI in 0 until m && newJ in 0 until n) {
if (grid[newI][newJ] == 1 && currentRemain > 0) {
queue.add(intArrayOf(newI, newJ, currentRemain - 1, currentDist + 1))
} else if (grid[newI][newJ] == 0) {
queue.add(intArrayOf(newI, newJ, currentRemain, currentDist + 1))
}
}
}
}
return -1
}
| 0 | Kotlin | 0 | 0 | 780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd | 1,597 | leetcode-kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.