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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
leetcode2/src/leetcode/KthLargestElementInAStream.kt | hewking | 68,515,222 | false | null | package leetcode
import java.util.*
/**
* 数据流中的第k大的元素
* https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/
* Created by test
* Date 2019/5/18 15:07
* Description
* 设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。
你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。
示例:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
说明:
你可以假设 nums 的长度≥ k-1 且k ≥ 1。
*/
object KthLargestElementInAStream {
/**
* 思路:
* 1.第k大的问题都可以通过优先队列来解决
* 2.优先队列不需要自己构造,如果自己构造也需要几个方法
* deleteMin insert findMin 等
* 3.优先队列大小为k ,
* 4.如果元素小于k 则直接offer
* 5.如果元素大小已经达到k 则比较val 与 顶部元素大小相比较
* 6.如果小于 则废弃,因为是求第k大元素
*/
class KthLargest(k: Int, nums: IntArray) {
val q = PriorityQueue<Int>()
val k1 = k
fun add(`val`: Int): Int {
if (q.size < k1) {
q.offer(`val`)
} else {
if (`val` < q.peek()){
q.poll()
q.offer(`val`)
}
}
return q.peek()
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,752 | leetcode | MIT License |
P9735.kt | daily-boj | 253,815,781 | false | null | import kotlin.math.*
data class QuadraticEquation(val a: Long, val b: Long, val c: Long) {
fun solve(): Set<Double> {
val discriminant = b.toDouble() * b.toDouble() - 4.0 * a.toDouble() * c.toDouble()
if (discriminant < 0) {
return emptySet()
}
val sqrtedDiscriminant = sqrt(discriminant)
return setOf((-b + sqrtedDiscriminant) / 2 / a, (-b - sqrtedDiscriminant) / 2 / a)
}
}
fun syntheticDivision(a: Long, b: Long, c: Long, d: Long): Set<Double> {
if (d == 0L) {
return setOf(0.0) + QuadraticEquation(a, b, c).solve()
}
for (i in 1..sqrt(abs(d.toDouble())).toLong()) {
if (d % i != 0L) {
continue
}
for (e in listOf(i, -i, d / i, -d / i)) {
val newA = a
val newB = e * newA + b
val newC = e * newB + c
val newD = e * newC + d
if (newD == 0L) {
return setOf(e.toDouble()) + QuadraticEquation(newA, newB, newC).solve()
}
}
}
return emptySet()
}
fun gcd(a: Long, b: Long): Long =
if (b == 0L) a
else gcd(b, a % b)
fun main(args: Array<out String>) {
(0 until readLine()!!.toLong()).joinToString("\n") {
val (a, b, c, d) = readLine()!!.split(" ").map { it.toLong() }
syntheticDivision(a, b, c, d).toList().sorted().joinToString(" ") { String.format("%f", it) }
}.let(::println)
} | 0 | Rust | 0 | 12 | 74294a4628e96a64def885fdcdd9c1444224802c | 1,432 | RanolP | The Unlicense |
src/main/kotlin/day9.kt | tianyu | 574,561,581 | false | {"Kotlin": 49942} | import assertk.assertThat
import assertk.assertions.isEqualTo
import kotlin.math.absoluteValue
import kotlin.math.sign
private fun main() {
tests {
val example = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent()
"Reading head movements" {
val headMovements = example.lineSequence().headMovements().toList()
assertThat(headMovements.size).isEqualTo(24)
assertThat(headMovements.fold(Vec(0, 0), Vec::plus))
.isEqualTo(Vec(2, 2))
}
"Part 1 Example" {
assertThat(example.lineSequence().headMovements().tailPositions(rope(2)).toSet().size)
.isEqualTo(13)
}
"Part 2 Examples" {
assertThat(example.lineSequence().headMovements().tailPositions(rope(10)).toSet().size)
.isEqualTo(1)
assertThat("""
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent().lineSequence()
.headMovements()
.tailPositions(rope(10))
.toSet().size
).isEqualTo(36)
}
}
part1("The number of distinct tail positions for a 2-knot rope is:") {
headMovements().tailPositions(rope(2)).toSet().size
}
part2("The number of distinct tail positions for a 10-knot rope is:") {
headMovements().tailPositions(rope(10)).toSet().size
}
}
private fun rope(size: Int, origin: Vec = Vec(0, 0)) = Array(size) { origin }
private fun Sequence<Vec>.tailPositions(rope: Array<Vec>) = sequence {
yield(rope.last())
for (headMovement in this@tailPositions) {
rope[0] += headMovement
var previous = rope[0]
for (index in 1 until rope.size) {
val stretch = previous - rope[index]
if (stretch.magnitude <= 1) break
rope[index] += stretch.sign
previous = rope[index]
if (index == rope.lastIndex) yield(previous)
}
}
}
private data class Vec(val x: Int, val y: Int) {
operator fun plus(that: Vec): Vec = Vec(x + that.x, y + that.y)
operator fun minus(that: Vec): Vec = Vec(x - that.x, y - that.y)
val magnitude: Int = maxOf(x.absoluteValue, y.absoluteValue)
val sign: Vec get() = Vec(x.sign, y.sign)
}
private fun headMovements() = sequence {
withInputLines("day9.txt") {
yieldAll(headMovements())
}
}
private fun Sequence<String>.headMovements(): Sequence<Vec> {
val left = Vec(-1, 0)
val right = Vec(1, 0)
val up = Vec(0, 1)
val down = Vec(0, -1)
return flatMap {
sequence {
val direction = when (it[0]) {
'L' -> left
'R' -> right
'U' -> up
'D' -> down
else -> throw AssertionError("Unknown direction: ${it[0]}")
}
repeat(it.substring(2).toInt()) { yield(direction) }
}
}
} | 0 | Kotlin | 0 | 0 | 6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea | 2,730 | AdventOfCode2022 | MIT License |
src/main/kotlin/days/Day11Data.kt | yigitozgumus | 572,855,908 | false | {"Kotlin": 26037} | package days
import utils.SolutionData
import utils.Utils.createPart1Monkey
import utils.Utils.createPart2Monkey
fun main() = with(Day11Data()) {
println(" --- Part 1 --- ")
solvePart1()
println(" --- Part 2 --- ")
solvePart2()
}
data class Item(var worry: Long, val part1: Boolean = true) {
operator fun plus(value: Long) = this.apply {
worry += value
if (part1) worry /= 3
}
operator fun times(value: Long) = this.apply {
worry *= value
if (part1) worry /= 3
}
}
data class Monkey(
val index: Int,
val items: MutableList<Item>,
val inspect: (Item) -> Item,
val test: (target: Item) -> Int,
var inspectTimes: Long = 0L,
val testNumber: Long
)
class Day11Data : SolutionData(inputFile = "inputs/day11.txt") {
private val processedData = rawData.windowed(size = 6, step = 7)
val part1MonkeyList = processedData.map { createPart1Monkey(it) }
val part2MonkeyList = processedData.map { createPart2Monkey(it) }
}
fun Day11Data.solvePart1() {
repeat(20) {
part1MonkeyList.forEach { monkey ->
val sendList = mutableListOf<Pair<Item, Int>>()
monkey.items.forEach { item ->
monkey.inspect(item)
val monkeyToSend = monkey.test(item)
sendList.add(item to monkeyToSend)
}
monkey.inspectTimes += monkey.items.size
sendList.forEach { (item, monkeyIndex) ->
part1MonkeyList[monkeyIndex].items.add(item)
}
monkey.items.clear()
}
}
part1MonkeyList
.map { it.inspectTimes }.sortedDescending().take(2)
.also { println(it.first().times(it.last())) }
}
fun Day11Data.solvePart2() {
val totalModulo = part2MonkeyList.map { it.testNumber }.reduce { acc, l -> acc * l }
repeat(10_000) {
part2MonkeyList.forEach { monkey ->
val sendList = mutableListOf<Pair<Item, Int>>()
monkey.items.forEach { item ->
monkey.inspect(item)
val monkeyToSend = monkey.test(item)
val itemWithUpdatedWorry = item.copy(worry = item.worry % totalModulo)
sendList.add(itemWithUpdatedWorry to monkeyToSend)
}
monkey.inspectTimes += monkey.items.size
sendList.forEach { (item, monkeyIndex) ->
part2MonkeyList[monkeyIndex].items.add(item)
}
monkey.items.clear()
}
}
println(part2MonkeyList)
part2MonkeyList
.map { it.inspectTimes }
.sortedDescending().take(2)
.also { println(it.first().times(it.last())) }
} | 0 | Kotlin | 0 | 0 | 9a3654b6d1d455aed49d018d9aa02d37c57c8946 | 2,288 | AdventOfCode2022 | MIT License |
src/main/kotlin/com/staricka/adventofcode2023/days/Day8.kt | mathstar | 719,656,133 | false | {"Kotlin": 107115} | package com.staricka.adventofcode2023.days
import com.staricka.adventofcode2023.framework.Day
import com.staricka.adventofcode2023.util.lcm
class Day8: Day {
enum class Direction {
L, R
}
data class MapPath(val left: String, val right: String) {
companion object {
fun fromString(input: String): Pair<String, MapPath> {
val split = input.split(" = ")
val source = split[0]
val destSplit = split[1].split(", ")
val left = Regex("[A-Z0-9]+").find(destSplit[0])!!.value
val right = Regex("[A-Z0-9]+").find(destSplit[1])!!.value
return Pair(source, MapPath(left, right))
}
}
}
private fun getDirectionSequence(input: String): List<Direction> {
return input.toCharArray().map { Direction.valueOf(it.toString()) }
}
private fun getMapPaths(input: List<String>): Map<String, MapPath> {
return input.filter { it.isNotBlank() }
.associate { MapPath.fromString(it) }
}
override fun part1(input: String): Int {
val lines = input.lines()
val directionSequence = getDirectionSequence(lines[0])
val mapPaths = getMapPaths(lines.subList(2, lines.size))
var position = "AAA"
var steps = 0
var nextDirection = 0
while (position != "ZZZ") {
position = mapPaths[position]!!.let { when (directionSequence[nextDirection]) {
Direction.L -> it.left
Direction.R -> it.right
} }
steps++
nextDirection = (nextDirection + 1) % directionSequence.size
}
return steps
}
private fun zPosition(start: String, mapPaths: Map<String, MapPath>, directionSequence: List<Direction>): Int {
var position = start
var steps = 0
var nextDirection = 0
while (!position.endsWith("Z")) {
position = mapPaths[position]!!.let { when (directionSequence[nextDirection]) {
Direction.L -> it.left
Direction.R -> it.right
} }
steps++
nextDirection = (nextDirection + 1) % directionSequence.size
}
return steps
}
override fun part2(input: String): Long {
val lines = input.lines()
val directionSequence = getDirectionSequence(lines[0])
val mapPaths = getMapPaths(lines.subList(2, lines.size))
val position = mapPaths.keys.filter { it.endsWith("A") }
val zPosition = position.map { zPosition(it, mapPaths, directionSequence) }
return zPosition.map { it.toLong() }.reduce { acc, i -> lcm(acc, i) }
}
} | 0 | Kotlin | 0 | 0 | 8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa | 2,716 | adventOfCode2023 | MIT License |
src/main/kotlin/me/grison/aoc/y2020/Day20.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2020
import arrow.syntax.collections.tail
import me.grison.aoc.*
import java.util.*
class Day20 : Day(20, 2020) {
override fun title() = "Jurassic Jigsaw"
private fun tiles() =
inputGroups.map { it.lines() }
.map { t -> Tile(t.first().allLongs(includeNegative = false).first(), t.tail().map { s -> s.map { it == '#' } }) }
override fun partOne(): Long {
val tiles = tiles()
val edgeCount = mutableMapOf<List<Boolean>, Int>().withDefault { 0 }
tiles.forEach { tile ->
tile.minEdges().forEach { edge ->
edgeCount[edge] = edgeCount.getValue(edge) + 1
}
}
return tiles.filter { tile -> tile.minEdges().count { edgeCount.getValue(it) == 1 } == 2 }
.map { tile -> tile.id }.product()
}
override fun partTwo(): Int {
val tiles = tiles()
val globalTile = assembleCompleteTile(tiles)
var count = searchNessie(globalTile)?.let {
globalTile.pixels.sumOf { r -> r.count { it } } - it * 15
} ?: 0
var s = globalTile.mkString()
fun String.sharps() = withIndex().filter { (_, c) -> c == '#' }.map { (i, _) -> i }
var L = s.split("\n").map { it.stringList().toMutableList() }.toMutableList()
fun String.red() = red(this)
fun String.roughColor() = this
NESSIES.forEach { (y, x) ->
L[y - 1] = L[y - 1].mapIndexed { i, v -> if (i-x in nessie[0].sharps()) nessieR[0][i-x].toString().red() else v.roughColor() }.toMutableList()
L[y] = L[y].mapIndexed { i, v -> if (i-x in nessie[1].sharps()) nessieR[1][i-x].toString().red() else v.roughColor() }.toMutableList()
L[y + 1] = L[y + 1].mapIndexed { i, v -> if (i-x in nessie[2].sharps()) nessieR[2][i-x].toString().red() else v.roughColor() }.toMutableList()
}
L = L.map { l ->
l.map { if (it == "#") cyan(it) else if (it == ".") blue(it) else it}.toMutableList()
}.toMutableList()
//println("\n" + L.joinToString("\n") { it.joinToString("") })
return count
}
val NESSIES = mutableListOf<Pair<Int, Int>>()
private fun countNessies(tile: Tile) =
(1 until tile.size())
.flatMap { y -> (0..tile.size() - nessie[0].length).map { x -> p(x, y) } }
.count { (x, y) ->
val z = isNessie(tile, x, y)
if (z) NESSIES.add(p(y, x))
z
}
private val nessie = listOf(
" # ",
"# ## ## ###",
" # # # # # # "
)
private val nessieR = listOf(
""" _ """,
"""\ __ __ /O>""",
""" \ / \ / \ / """
)
private fun isNessie(tile: Tile, x: Int, y: Int): Boolean {
fun String.sharps() = withIndex().filter { (_, c) -> c == '#' }.map { (i, _) -> i }
return nessie[0].sharps().all { tile[x + it, y - 1] } // head
&& nessie[1].sharps().all { tile[x + it, y] } // middle
&& nessie[2].sharps().all { tile[x + it, y + 1] } // bottom
}
// search nessie in the big tile
private fun searchNessie(tile: Tile): Int? {
(0 until 4).forEach { _ ->
var count = countNessies(tile)
if (count != 0) return count
else tile.vFlip()
count = countNessies(tile)
if (count != 0) return count
else tile.hFlip()
count = countNessies(tile)
if (count != 0) return count
else tile.vFlip()
count = countNessies(tile)
if (count != 0) return count
else {
tile.hFlip()
tile.rotateRight()
}
}
return null
}
private fun assembleCompleteTile(tiles: List<Tile>): Tile {
val allTiles = tiles.associateBy { it.id }
val checkedTiles = mutableListOf<Tile>()
val remainingTiles = tiles.toMutableList()
val tilesToCheck = Stack<Tile>()
tilesToCheck += tiles.first()
while (tilesToCheck.isNotEmpty()) {
val currentTile = tilesToCheck.pop()
remainingTiles -= currentTile
val currentEdges = currentTile.edges()
remainingTiles.forEach { tile ->
tile.edges().forEachIndexed { num, edge ->
val reversed = edge.reversed() in currentEdges
val connected = edge in currentEdges || reversed
val currentEdge = currentEdges.indexOf(if (reversed) edge.reversed() else edge)
val amount = ((currentEdge + 4) - ((num + 2) % 4)) % 4
if (connected && currentEdge in (0..3)) {
allTiles[tile.id]!!.rotateRight(amount)
if (!reversed) {
if (currentEdge == 0 || currentEdge == 2) allTiles[tile.id]!!.hFlip()
else allTiles[tile.id]!!.vFlip()
}
currentTile.connectTiles(currentEdge, tile.id)
tile.connectTiles((currentEdge + 2) % 4, currentTile.id)
tilesToCheck += tile
}
}
}
checkedTiles += currentTile
}
val bigTile = Array(12) { arrayOfNulls<Tile>(12) }
var left: Tile? = allTiles.values.find { it.left == null && it.top == null }
bigTile.indices.forEach { y ->
var right: Tile? = left!!
bigTile[y].indices.forEach { x ->
bigTile[y][x] = right!!
right = allTiles[right!!.right]
}
left = allTiles[left!!.bottom]
}
return Tile(0, bigTile.map { row ->
row.map { tile -> tile!!.noBorders() }.flattenGrid()
}.reduce { acc, list -> acc + list })
}
class Tile(val id: Long, var pixels: List<List<Boolean>>) {
var top: Long? = null
var right: Long? = null
var bottom: Long? = null
var left: Long? = null
fun size() = pixels.size
fun noBorders() = pixels.tail().butLast().map { it.tail().butLast() }.let { pixels = it; pixels }
fun edges() = listOf(
pixels.first(), // top
pixels.map { it.last() }, // right
pixels.last().reversed(), // bottom
pixels.map { it.first() }.reversed() // left
)
fun minEdges(): List<List<Boolean>> {
return edges().map { e ->
var x = e.joinToString("") { b -> if (b) "1" else "0" }
x = if (x > x.reversed()) x.reversed() else x
x.split("").filter { b -> b != "" }.map { b -> b == "1" }
}
}
fun rotateRight(amount: Int = 1) {
repeat(amount) { pixels = pixels.swapRowCols() }
}
fun hFlip() = pixels.map { it.reversed() }.let { pixels = it }
fun vFlip() = pixels.reversed().let { pixels = it }
operator fun get(x: Int, y: Int) = pixels[y][x]
fun connectTiles(i: Int, tileID: Long) {
when (i) {
0 -> top = tileID
1 -> right = tileID
2 -> bottom = tileID
3 -> left = tileID
}
}
fun mkString() : String {
return pixels.joinToString("\n") { it.map { b -> if (b) '#' else '.' }.joinToString("") }
}
}
} | 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 7,554 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/g2601_2700/s2642_design_graph_with_shortest_path_calculator/Graph.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2601_2700.s2642_design_graph_with_shortest_path_calculator
// #Hard #Design #Heap_Priority_Queue #Graph #Shortest_Path
// #2023_07_18_Time_789_ms_(100.00%)_Space_69.8_MB_(25.00%)
import java.util.PriorityQueue
class Graph(n: Int, edges: Array<IntArray>) {
private val adj = HashMap<Int, ArrayList<Pair<Int, Int>>>().apply {
for (i in 0 until n)
this[i] = ArrayList<Pair<Int, Int>>()
for ((u, v, cost) in edges) {
this[u] = getOrDefault(u, ArrayList<Pair<Int, Int>>()).apply { this.add(v to cost) }
}
}
fun addEdge(edge: IntArray) {
val (u, v, cost) = edge
adj[u] = adj.getOrDefault(u, ArrayList<Pair<Int, Int>>()).apply { this.add(v to cost) }
}
fun shortestPath(node1: Int, node2: Int): Int {
val minHeap = PriorityQueue<Pair<Int, Int>> { a, b -> a.second - b.second }
val distance = IntArray(adj.size) { Integer.MAX_VALUE }
minHeap.add(node1 to 0)
distance[node1] = 0
while (minHeap.isNotEmpty()) {
val (node, cost) = minHeap.poll()
if (node == node2) return cost
if (cost > distance[node]) continue
adj[node]?.let {
for ((next, nextCost) in adj[node]!!) {
if (cost + nextCost < distance[next]) {
distance[next] = cost + nextCost
minHeap.add(next to cost + nextCost)
}
}
}
}
return -1
}
}
/*
* Your Graph object will be instantiated and called as such:
* var obj = Graph(n, edges)
* obj.addEdge(edge)
* var param_2 = obj.shortestPath(node1,node2)
*/
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,697 | LeetCode-in-Kotlin | MIT License |
2020/src/main/kotlin/de/skyrising/aoc2020/day22/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2020.day22
import de.skyrising.aoc.*
import java.util.*
private fun readInput(input: PuzzleInput): Map<Int, LinkedList<Int>> {
val map = mutableMapOf<Int, LinkedList<Int>>()
var current = LinkedList<Int>()
var id = -1
for (line in input.lines) {
when {
line.startsWith("Player ") -> {
id = line.substring(7, line.length - 1).toInt()
}
line.isNotEmpty() -> {
current.add(line.toInt())
}
else -> {
map[id] = current
current = LinkedList<Int>()
id = -1
}
}
}
if (id != -1) map[id] = current
return map
}
private fun round(a: LinkedList<Int>, b: LinkedList<Int>): Boolean {
if (a.isEmpty() || b.isEmpty()) return true
val a0 = a.poll()
val b0 = b.poll()
when {
a0 > b0 -> {
a.add(a0)
a.add(b0)
}
a0 < b0 -> {
b.add(b0)
b.add(a0)
}
else -> {
a.add(a0)
b.add(b0)
}
}
return a.isEmpty() || b.isEmpty()
}
private fun gameRecursive(p1: LinkedList<Int>, p2: LinkedList<Int>): Int {
val previous = mutableSetOf<Pair<List<Int>, List<Int>>>()
while (true) {
val result = roundRecursive(p1, p2, previous)
if (result != 0) return result
}
}
private fun roundRecursive(p1: LinkedList<Int>, p2: LinkedList<Int>, previous: MutableSet<Pair<List<Int>, List<Int>>>): Int {
if (previous.contains(Pair(p1, p2))) return 1
previous.add(Pair(ArrayList(p1), ArrayList(p2)))
val a = p1.poll()
val b = p2.poll()
val winner = if (a > p1.size || b > p2.size) {
if (a > b) 1 else 2
} else {
gameRecursive(LinkedList(p1.subList(0, a)), LinkedList(p2.subList(0, b)))
}
if (winner == 1) {
p1.add(a)
p1.add(b)
if (p2.isEmpty()) return 1
} else if (winner == 2) {
p2.add(b)
p2.add(a)
if (p1.isEmpty()) return 2
}
return 0
}
val test = TestInput("""
Player 1:
9
2
6
3
1
Player 2:
5
8
4
7
10
""")
val test2 = TestInput("""
Player 1:
43
19
Player 2:
2
29
14
""")
@PuzzleName("Crab Combat")
fun PuzzleInput.part1(): Any {
val (p1, p2) = ArrayList(readInput(this).values)
while (!round(p1, p2)) {}
var sum = 0
val winner = if (p1.isEmpty()) p2 else p1
for ((i, j) in winner.withIndex()) {
sum += (winner.size - i) * j
}
return sum
}
fun PuzzleInput.part2(): Any {
val (p1, p2) = ArrayList(readInput(this).values)
gameRecursive(p1, p2)
var sum = 0
val winner = if (p1.isEmpty()) p2 else p1
for ((i, j) in winner.withIndex()) {
sum += (winner.size - i) * j
}
return sum
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,887 | aoc | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year20/Day20.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year20
import com.grappenmaker.aoc.*
import com.grappenmaker.aoc.Direction.*
fun PuzzleSet.day20() = puzzle(day = 20) {
data class Tile(val id: Int, val grid: BooleanGrid)
val tiles = input.doubleLines().map(String::lines).map { l ->
Tile(l.first().splitInts().single(), l.drop(1).asGrid { it == '#' })
}
// Inefficient, doing double work I suppose...
val topLeft = tiles.first { curr ->
(tiles - curr).fold(listOf<Direction>()) { acc, otherTile ->
val poss = otherTile.grid.orientations().map { otherTile.copy(grid = it) }
acc + listOfNotNull(
poss.find { (_, a) -> a.rowValues(a.height - 1) == curr.grid.rowValues(0) }?.let { UP },
poss.find { (_, a) -> a.rowValues(0) == curr.grid.rowValues(curr.grid.height - 1) }?.let { DOWN },
poss.find { (_, a) -> a.columnValues(a.width - 1) == curr.grid.columnValues(0) }?.let { LEFT },
poss.find { (_, a) -> a.columnValues(0) == curr.grid.columnValues(curr.grid.width - 1) }?.let { RIGHT }
)
}.toSet() == setOf(DOWN, RIGHT)
}
fun seq(
start: Tile,
matchA: (Tile) -> List<Boolean>,
matchB: (Tile) -> List<Boolean>
) = generateSequence(start to tiles) { (curr, left) ->
val toMatch = matchA(curr)
val newLeft = left.filter { it.id != curr.id }
newLeft.flatMap { t -> t.grid.orientations().map { t.copy(grid = it) } }
.find { matchB(it) == toMatch }?.let { it to newLeft }
}.map { (a) -> a }
fun BooleanGrid.removeBorders() = rowsValues.drop(1).dropLast(1).map { it.drop(1).dropLast(1) }.asGrid()
val assembled = seq(
start = topLeft,
matchA = { it.grid.columnValues(it.grid.width - 1) },
matchB = { it.grid.columnValues(0) },
).map { top ->
seq(
start = top,
matchA = { it.grid.rowValues(it.grid.height - 1) },
matchB = { it.grid.rowValues(0) },
).toList()
}.toList()
partOne = (assembled.first().first().id.toLong() *
assembled.first().last().id.toLong() *
assembled.last().last().id.toLong() *
assembled.last().first().id.toLong()).s()
val result = assembled.map { col ->
col.map { it.grid.removeBorders().rowsValues }.reduce { acc, curr -> acc + curr }.swapOrder()
}.reduce { acc, curr -> acc + curr }.asGrid()
val monster = """
| #
|# ## ## ###
| # # # # # #
""".trimMargin().lines().asGrid { it == '#' }
val monsterPoints = monster.filterTrue()
val searchArea =
Rectangle(Point(0, 0), Point(result.width - monster.width - 1, result.height - monster.height - 1)).points
fun GridLike<Boolean>.monsterAt(at: Point) = monsterPoints.map { it + at }.takeIf { p -> p.all { this[it] } }
val correctOrientation = result.orientations().maxBy { poss -> searchArea.count { poss.monsterAt(it) != null } }
val answer = correctOrientation.filterTrue().toMutableSet()
searchArea.forEach { correctOrientation.monsterAt(it)?.let { set -> answer -= set.toSet() } }
partTwo = answer.size.s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 3,233 | advent-of-code | The Unlicense |
src/main/kotlin/dev/siller/aoc2023/Day03.kt | chearius | 725,594,554 | false | {"Kotlin": 50795, "Shell": 299} | package dev.siller.aoc2023
import dev.siller.aoc2023.util.Point
import dev.siller.aoc2023.util.Vector
data object Day03 : AocDayTask<UInt, UInt>(
day = 3,
exampleInput =
"""
|467..114..
|...*......
|..35..633.
|......#...
|617*......
|.....+.58.
|..592.....
|......755.
|...$.*....
|.664.598..
""".trimMargin(),
expectedExampleOutputPart1 = 4361u,
expectedExampleOutputPart2 = 467835u
) {
private data class Schematic(
val partNumbers: List<PartNumber>,
val symbols: List<Symbol>,
val width: UInt,
val height: UInt
)
private data class PartNumber(
val number: UInt,
val startPosition: Point
) {
val points: List<Point> =
(0..<number.toString().length).map { i -> startPosition + Vector(i, 0) }
}
private data class Symbol(
val symbol: Char,
val position: Point
)
override fun runPart1(input: List<String>): UInt =
parseSchematic(input).let { schematic ->
schematic.symbols.flatMap { symbol ->
val adjacentPoints =
symbol.position.getAdjacentPoints(
minX = 0,
maxX = schematic.width.toInt() - 1,
minY = 0,
maxY = schematic.height.toInt() - 1
)
schematic.partNumbers.filter { partNumber ->
partNumber.points.any { point ->
point in adjacentPoints
}
}
}.sumOf(PartNumber::number)
}
override fun runPart2(input: List<String>): UInt =
parseSchematic(input).let { schematic ->
schematic.symbols.sumOf { symbol ->
val adjacentPoints =
symbol.position.getAdjacentPoints(
minX = 0,
maxX = schematic.width.toInt() - 1,
minY = 0,
maxY = schematic.height.toInt() - 1
)
val adjacentPartNumbers =
schematic.partNumbers.filter { partNumber ->
partNumber.points.any { point ->
point in adjacentPoints
}
}
if (adjacentPartNumbers.size == 2) {
adjacentPartNumbers[0].number * adjacentPartNumbers[1].number
} else {
0u
}
}
}
private fun parseSchematic(input: List<String>): Schematic {
val partNumbers = mutableListOf<PartNumber>()
val symbols = mutableListOf<Symbol>()
input.forEachIndexed { y, line ->
var partNumber = ""
var startX = -1
line.forEachIndexed { x, character ->
when (character) {
in '0'..'9' -> {
if (partNumber.isBlank()) {
startX = x
}
partNumber += character
}
else -> {
if (partNumber.isNotBlank()) {
partNumbers += PartNumber(partNumber.toUInt(), Point(startX, y))
partNumber = ""
}
if (character != '.') {
symbols += Symbol(character, Point(x, y))
}
}
}
}
if (partNumber.isNotBlank()) {
partNumbers += PartNumber(partNumber.toUInt(), Point(startX, y))
}
}
return Schematic(partNumbers, symbols, input[0].length.toUInt(), input.size.toUInt())
}
}
| 0 | Kotlin | 0 | 0 | fab1dd509607eab3c66576e3459df0c4f0f2fd94 | 3,926 | advent-of-code-2023 | MIT License |
src/main/kotlin/dynamic_programming/PalindromePartitioning.kt | TheAlgorithms | 177,334,737 | false | {"Kotlin": 41212} | package dynamic_programming
/**
* Palindrome Partitioning Algorithm
*
* You are given a string as input, and task is to find the minimum number of partitions to be made,
* in the string sot that the resulting strings are all palindrome
* eg. s = "nitik"
* string s can be partitioned as n | iti | k into 3 palindromes, thus the number of partions are 2
* Time Complexity = O(n^2)
*
* */
/**
* @param String is the string to be checked
* @param Int is the starting index of the string in consideration
* @param Int is the ending index of the string in consideration
* @return whether string is a palindrome or not
**/
fun isPalindrome(string: String, i: Int, j: Int): Boolean {
for (l in 0..(j - i) / 2) {
if (string[l + i] != string[j - l]) {
return false
}
}
return true
}
/**
* @param String is the string to be checked
* @param Int is the starting index of the string in consideration
* @param Int is the ending index of the string in consideration
* @return minimum number of partitions required
**/
fun palindromePartition(string: String, i: Int, j: Int): Int {
if (i >= j) {
return 0
}
if (isPalindrome(string, i, j)) {
return 0
}
if (dp[i][j] != -1) {
return dp[i][j]
}
var mn = Int.MAX_VALUE
for (k in i until j) {
val temp: Int = palindromePartition(string, i, k) + palindromePartition(string, k + 1, j) + 1
if (temp < mn) {
mn = temp
}
}
dp[i][j] = mn
return dp[i][j]
}
/**
* memoization table
**/
lateinit var dp: Array<Array<Int>>
/**
* @param String the string on which algorithm is to be operated
*/
fun initialize(string: String): Int {
dp = Array(string.length) { Array(string.length) { -1 } }
return palindromePartition(string, 0, string.length - 1)
}
| 62 | Kotlin | 369 | 1,221 | e57a8888dec4454d39414082bbe6a672a9d27ad1 | 1,853 | Kotlin | MIT License |
src/main/kotlin/wordle.kt | rileynull | 448,412,739 | false | null | val solutions = java.io.File("""wordlist_solutions.txt""").readLines().map { it.toUpperCase() }
val guesses = java.io.File("""wordlist_guesses.txt""").readLines().map { it.toUpperCase() }
enum class Hint {
GREEN, YELLOW, GREY
}
/**
* Produce colored hints for a guess with respect to a solution, just like the game does.
*/
fun markGuess(guess: String, correct: String): List<Hint> {
val hints = MutableList(5) { _ -> Hint.GREY }
for (i in 0..4) {
if (guess[i] == correct[i]) {
hints[i] = Hint.GREEN
}
}
outer@for (i in 0..4) {
if (hints[i] != Hint.GREEN) {
for (j in 0..4) {
if (guess[i] == correct[j] && hints[j] != Hint.GREEN) {
hints[i] = Hint.YELLOW
continue@outer
}
}
hints[i] = Hint.GREY
}
}
return hints
}
/**
* Determines whether a word comports with a previous hint and checks against a blacklist of known bad letters.
*/
fun isWordValid(word: String, last: String, hint: List<Hint>, blacklist: Set<Char>): Boolean {
val yellows = mutableListOf<Char>()
val newBlacklist = blacklist.toMutableSet()
outer@for (i in 0..4) {
when (hint[i]) {
Hint.GREEN ->
if (word[i] != last[i]) return false
Hint.YELLOW -> {
if (word[i] == last[i]) return false
yellows += last[i]
for (j in 0..4) {
if (hint[j] != Hint.GREEN && word[j] == last[i]) continue@outer
}
return false
}
Hint.GREY ->
newBlacklist += last[i]
}
}
for (i in 0..4) {
// Technically I think we should be checking the exact number of yellows for each character but w/e.
if (hint[i] != Hint.GREEN && word[i] in blacklist && word[i] !in yellows) {
return false;
}
}
return true
}
| 0 | Kotlin | 0 | 0 | 9e92a16e9ad517b5afda7c70899bd0c67fd0e0a0 | 2,059 | wordle-kot | Apache License 2.0 |
src/main/kotlin/adventofcode/Day3.kt | geilsonfonte | 226,212,274 | false | null | package adventofcode
import kotlin.math.abs
typealias Point = Pair<Int, Int>
typealias Wire = List<Point>
val DIRECTIONS = mapOf('U' to Pair(0, 1), 'R' to Pair(1, 0), 'D' to Pair(0, -1), 'L' to Pair(-1, 0))
val ORIGIN = Pair(0, 0)
fun manhattan(a: Point, b: Point = ORIGIN): Int {
return abs(a.first - b.first) + abs(a.second - b.second)
}
fun closestIntersection(wire1: Wire, wire2: Wire, origin: Point = ORIGIN): Point? {
return wire1.intersect(wire2).minBy { manhattan(it, origin) }
}
fun firstIntersection(wire1: Wire, wire2: Wire): Int? {
return wire1.intersect(wire2).map { wire1.indexOf(it) + wire2.indexOf(it) + 2}.min()
}
fun wire(s: String): List<Point> {
val instructions: List<Pair<Char, Int>> = s.split(',').map { Pair(it.first(), it.substring(1).toInt())}
val path = mutableListOf<Point>()
var position = Pair(0, 0)
for ((dir, len) in instructions) {
for (step in 1..len) {
position = move(position, DIRECTIONS[dir] ?: error(""))
path.add(position)
}
}
return path
}
fun move(position: Pair<Int, Int>, direction: Pair<Int, Int>): Pair<Int, Int> {
return Pair(position.first + direction.first, position.second + direction.second)
}
class Day3 : Puzzle {
override val day = 3
private val input = input().lines()
private val wire1: Wire
private val wire2: Wire
init {
this.wire1 = wire(input.first())
this.wire2 = wire(input.last())
}
override fun answer1(): Int {
return manhattan(closestIntersection(wire1, wire2)!!)
}
override fun answer2(): Int {
return firstIntersection(wire1, wire2)!!
}
}
| 1 | Kotlin | 0 | 0 | e3fb51a61a9a38e2f5e093362d360a3d5a5abb1a | 1,672 | advent-of-code-2019 | The Unlicense |
src/main/kotlin/days/Day4.kt | mir47 | 433,536,325 | false | {"Kotlin": 31075} | package days
class Day4 : Day(4) {
override fun partOne(): Int {
return findWinner(getBoards()).second
}
override fun partTwo(): Int {
val boards = getBoards()
while (boards.size > 1) {
boards.remove(findWinner(boards).first)
}
return findWinner(boards).second
}
private fun findWinner(boards: MutableList<BingoBoard>): Pair<BingoBoard?, Int> {
inputList[0].split(",").forEach { draw ->
boards.forEach { board ->
board.numbers.forEach { number ->
if (draw.toInt() == number.number) {
number.marked = true
if (hasBingo(board, number.x, number.y)) {
return Pair(board, (sumUnmarked(board) * draw.toInt()))
}
}
}
}
}
return Pair(null, 0)
}
private fun getBoards(): MutableList<BingoBoard> {
val boards = mutableListOf<BingoBoard>()
for (i in 1 until inputList.size step 6) {
val items = mutableListOf<BingoItem>()
for (j in i+1..i+5) {
inputList[j].chunked(3).forEachIndexed { index, s ->
items.add(BingoItem(s.trim().toInt(), x = index, y = ((j-2)%5)))
}
}
boards.add(BingoBoard(items))
}
return boards
}
private fun hasBingo(board: BingoBoard, x: Int, y: Int): Boolean {
val hasX = board.numbers.firstOrNull { it.x == x && !it.marked } == null
val hasY = board.numbers.firstOrNull { it.y == y && !it.marked } == null
return (hasX || hasY)
}
private fun sumUnmarked(board: BingoBoard): Int {
return board.numbers.filter { !it.marked }.sumOf { it.number }
}
class BingoBoard(
val numbers: List<BingoItem> = emptyList()
)
class BingoItem(
val number: Int,
val x: Int,
val y: Int,
var marked: Boolean = false,
)
} | 0 | Kotlin | 0 | 0 | 686fa5388d712bfdf3c2cc9dd4bab063bac632ce | 2,057 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/Day01.kt | bigtlb | 573,081,626 | false | {"Kotlin": 38940} | fun main() {
fun part1(input: List<String>): Long {
var prevCalCount: Long = 0
val lastCalCount = input.fold(0L) { acc, cal ->
val cur = cal.toLongOrNull()
if (cur == null) {
if (prevCalCount < acc) {
prevCalCount = acc
}
0
} else {
acc + cur
}
}
return maxOf(prevCalCount, lastCalCount)
}
fun part2(input: List<String>): Long {
val elfCounts = mutableListOf<Long>()
elfCounts.add(
input.fold(0L) { acc, cal ->
val cur = cal.toLongOrNull()
if (cur == null) {
elfCounts.add(acc)
0
} else {
acc + cur
}
}
)
return elfCounts.sortedDescending().toList().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000L)
check(part2(testInput) == 45000L)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8f76d3c75a30ae00c563c997ed2fb54827ea94a | 1,211 | aoc-2022-demo | Apache License 2.0 |
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/sort/RadixSort.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1728251} | package dev.funkymuse.datastructuresandalgorithms.sort
import kotlin.math.pow
fun MutableList<Int>.radixSort() {
val base = 10
var done = false
var digits = 1
while (!done) {
done = true
val buckets = arrayListOf<MutableList<Int>>().apply {
for (i in 0..9) {
this.add(arrayListOf())
}
}
this.forEach { number ->
val remainingPart = number / digits
val digit = remainingPart % base
buckets[digit].add(number)
if (remainingPart > 0) {
done = false
}
}
digits *= base
this.clear()
this.addAll(buckets.flatten())
}
}
fun Int.digits(): Int {
var count = 0
var num = this
while (num != 0) {
count += 1
num /= 10
}
return count
}
fun Int.digit(atPosition: Int): Int? {
if (atPosition > digits()) return null
var num = this
val correctedPosition = (atPosition + 1).toDouble()
while (num / (10.0.pow(correctedPosition).toInt()) != 0) {
num /= 10
}
return num % 10
}
fun MutableList<Int>.lexicographicalSort() {
val newList = msdRadixSorted(this, 0)
this.clear()
this.addAll(newList)
}
private fun msdRadixSorted(list: MutableList<Int>, position: Int): MutableList<Int> {
if (position >= list.maxDigits()) return list
val buckets = arrayListOf<MutableList<Int>>().apply {
for (i in 0..9) {
this.add(arrayListOf())
}
}
val priorityBucket = arrayListOf<Int>()
list.forEach { number ->
val digit = number.digit(position)
if (digit == null) {
priorityBucket.add(number)
return@forEach
}
buckets[digit].add(number)
}
val newValues = buckets.reduce { result, bucket ->
if (bucket.isEmpty()) return@reduce result
result.addAll(msdRadixSorted(bucket, position + 1))
result
}
priorityBucket.addAll(newValues)
return priorityBucket
}
private fun List<Int>.maxDigits(): Int {
return this.maxOrNull()?.digits() ?: 0
} | 0 | Kotlin | 92 | 771 | e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1 | 2,139 | KAHelpers | MIT License |
src/main/kotlin/adventofcode/year2020/Day07HandyHaversacks.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2020
import adventofcode.Puzzle
import adventofcode.PuzzleInput
class Day07HandyHaversacks(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val bagRules by lazy {
input.lines().map { rule ->
val (color) = BAG_RULE_REGEX.find(rule)!!.destructured
val contents = BAG_CONTENTS_REGEX
.findAll(rule)
.map { it.destructured }
.associate { (amount, color) -> color to amount.toInt() }
Bag(color, contents)
}
}
override fun partOne() = bagRules
.count { it.contains(bagRules, "shiny gold") }
override fun partTwo() = bagRules
.get("shiny gold")
.size(bagRules)
.minus(1)
companion object {
val BAG_RULE_REGEX = """(\w+ \w+) bags contain (.*)""".toRegex()
val BAG_CONTENTS_REGEX = """(\d+) (\w+ \w+) bags?(, )?""".toRegex()
private data class Bag(
val color: String,
val contents: Map<String, Int>
) {
fun contains(bagRules: List<Bag>, searchPattern: String): Boolean {
if (contents.isEmpty()) return false
if (contents.containsKey(searchPattern)) return true
return contents
.map { bagRules.get(it.key).contains(bagRules, searchPattern) }
.contains(true)
}
fun size(bagRules: List<Bag>): Int {
if (contents.isEmpty()) return 1
return contents
.map { bagRules.get(it.key).size(bagRules) * it.value }
.sum()
.plus(1)
}
}
private fun List<Bag>.get(color: String) = this.first { it.color == color }
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 1,801 | AdventOfCode | MIT License |
untitled/src/main/kotlin/Day7.kt | jlacar | 572,845,298 | false | {"Kotlin": 41161} | class Day7(private val fileName: String) : AocSolution {
override val description: String get() = "Day 7 - No Space Left on Device ($fileName)"
private val root = parse(InputReader(fileName).lines)
override fun part1() = smallDirectories().sumOf { it.size() }
private fun smallDirectories() = findDirs { it.size() <= 100_000 }
override fun part2() = smallestDirectoryToDelete().size()
private fun smallestDirectoryToDelete() = spaceNeeded().let { minSize ->
findDirs { it.size() >= minSize }.minBy { it.size() } }
private fun spaceNeeded() = 30_000_000 - (70_000_000 - root.size())
private fun findDirs(predicate: (FileAoC7) -> Boolean): List<FileAoC7> = mutableListOf<FileAoC7>()
.also { matches -> root.walkDirectories { if (predicate.invoke(it)) matches.add(it) } }
private fun parse(input: List<String>): FileAoC7 {
val root = FileAoC7("/")
val dirStack = Stack<FileAoC7>()
fun dirName(line: String) = line.split(" ")[2]
fun directoryFrom(line: String) = FileAoC7(line.split(" ")[1])
fun fileFrom(line: String) = line.split(" ").let { (bytes, name) -> FileAoC7(name, bytes.toInt()) }
fun currentDir() = dirStack.peek()!!.contents
fun chdir(dir: String) = currentDir().first { it.name == dir }.also { dirStack.push(it) }
input.forEach { line ->
when {
line.startsWith("$ cd /") -> dirStack.push(root)
line.startsWith("$ cd ..") -> dirStack.pop()
line.startsWith("$ cd ") -> chdir(dirName(line))
line.startsWith("dir ") -> currentDir().add(directoryFrom(line))
line.first().isDigit() -> currentDir().add(fileFrom(line))
}
}
return root
}
}
data class FileAoC7 (val name: String, val bytes: Int, val isDirectory: Boolean = false) {
constructor(name: String) : this(name,0, true) {}
val contents: MutableList<FileAoC7> = mutableListOf()
fun size(): Int = if (isDirectory) contents.sumOf { it.size() } else bytes
fun walkDirectories(action: (FileAoC7) -> Unit) {
if (isDirectory) action.invoke(this).also { contents.forEach { it.walkDirectories(action) } }
}
}
fun main() {
Day7("Day7-sample.txt") solution {
part1() shouldBe 95437
part2() shouldBe 24933642
}
Day7("Day7.txt") solution {
part1() shouldBe 1118405
part2() shouldBe 12545514
}
Day7("Day7-alt.txt") solution {
part1() shouldBe 1886043
part2() shouldBe 3842121
}
} | 0 | Kotlin | 0 | 2 | dbdefda9a354589de31bc27e0690f7c61c1dc7c9 | 2,580 | adventofcode2022-kotlin | The Unlicense |
15/day-15.kt | nils-degroot | 433,879,737 | false | null | package some.test
import java.io.File
import java.util.PriorityQueue
data class Point(val x: Int, val y: Int)
data class PathCost(val point: Point, val cost: Int) : Comparable<PathCost> {
public override fun compareTo(other: PathCost): Int =
cost - other.cost
}
class Chiton(var relativePath: String) {
private var input = File(System.getProperty("user.dir") + "/../" + relativePath)
.readLines()
.map { it.map { Character.getNumericValue(it) } }
private fun getNeighbors(p: Point): List<Point> =
listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1))
.map { Point(p.x + it.first, p.y + it.second) }
.filter { it.x >= 0 && it.x < input.size && it.y >= 0 && it.y < input.size }
fun topLeft(): Point =
Point(0, 0)
fun bottomRight(): Point =
Point(input.size - 1, input.first().size - 1)
fun dijkstra(start: Point, end: Point): Int {
val costs = HashMap<Point, Int>()
val heap = PriorityQueue<PathCost>()
heap.add(PathCost(start, 0))
while (true) {
if (heap.peek() == null)
break
val pos = heap.poll()
if (pos.point == end)
break
if (pos.cost <= costs.getOrDefault(pos.point, Int.MAX_VALUE))
getNeighbors(pos.point)
.map { PathCost(it, input[it.x][it.y] + pos.cost) }
.filter { it.cost < costs.getOrDefault(it.point, Int.MAX_VALUE) }
.forEach {
heap.add(it)
costs.put(it.point, it.cost)
}
}
return costs.getOrDefault(end, Int.MAX_VALUE)
}
}
fun main(args: Array<String>) {
val chiton = Chiton(args[0])
println(chiton.dijkstra(chiton.topLeft(), chiton.bottomRight()))
}
| 0 | Rust | 0 | 0 | 8e291bacdbd85ce08eee3920586569a9c146c790 | 1,578 | advent-of-code-2021 | MIT License |
OddOccurrencesInArray.kt | getnahid | 267,415,396 | false | null | /*
OddOccurrencesInArray
Find value that occurs in odd number of elements.
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
Write a function:
fun solution(A: IntArray): Int
that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
For example, given array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the function should return 7, as explained in the example above.
Write an efficient algorithm for the following assumptions:
N is an odd integer within the range [1..1,000,000];
each element of array A is an integer within the range [1..1,000,000,000];
all but one of the values in A occur an even number of times.*/
fun solution(array: IntArray): Int {
array.sort()
val length = array.size
for (i in array.indices step 2) {
if (i + 1 < length && array[i] == array[i + 1]) continue
return array[i]
}
return 0
}
| 0 | Kotlin | 0 | 0 | 589c392237334f6c53513dc7b75bd8fa81ad3b79 | 1,451 | programing-problem-solves-kotlin | Apache License 2.0 |
src/Day01.kt | Miguel1235 | 726,260,839 | false | {"Kotlin": 21105} | val findFirstNumber = { word: String -> Regex("""\d""").find(word)!!.value }
private fun text2Numbers(word: String): String {
val regexNumbers = Regex("""(?=(one|two|three|four|five|six|seven|eight|nine))""")
val text2Number = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9"
)
return regexNumbers.replace(word) { r -> text2Number[r.groupValues[1]]!! }
}
private val part1 = { words: List<String> -> words.fold(0) { acc, word -> acc + (findFirstNumber(word) + findFirstNumber(word.reversed())).toInt() } }
private val part2 = { words: List<String> -> part1(words.map { word -> text2Numbers(word) }) }
fun main() {
val testInput = readInput("Day01_test")
check(part1(testInput) == 142)
val input = readInput("Day01")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | 69a80acdc8d7ba072e4789044ec2d84f84500e00 | 971 | advent-of-code-2023 | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day24.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2016
import se.saidaspen.aoc.util.*
fun main() = Day24.run()
object Day24 : Day(2016, 24) {
data class State(val pos : P<Int, Int>, val visited: Set<Int>)
override fun part1(): Any {
val map = toMap(input)
val goals = map.values.filter { it.digitToIntOrNull() != null && it != '0' }.toSet()
return bfs(
State(map.entries.firstOrNull { it.value == '0' }!!.key, setOf()),
{ it.visited.size == goals.size },
{
it.pos.neighborsSimple()
.filter { n -> map.containsKey(n) && map[n] != '#' }
.map { n ->
val newVisited = it.visited.toMutableSet()
if (map[n]!!.digitToIntOrNull() != null && map[n] != '0') {
newVisited.add(map[n]!!.digitToInt())
}
State(n, newVisited)
}
}
).second
}
override fun part2(): Any {
val map = toMap(input)
val goals = map.values.filter { it.digitToIntOrNull() != null && it != '0' }.toSet()
val startPos = map.entries.firstOrNull { it.value == '0' }!!.key
return bfs(
State(startPos, setOf()),
{ it.visited.size == goals.size && it.pos == startPos},
{
it.pos.neighborsSimple()
.filter { n -> map.containsKey(n) && map[n] != '#' }
.map { n ->
val newVisited = it.visited.toMutableSet()
if (map[n]!!.digitToIntOrNull() != null && map[n] != '0') {
newVisited.add(map[n]!!.digitToInt())
}
State(n, newVisited)
}
}
).second
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,866 | adventofkotlin | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day19/Day19.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day19
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputSplitOnBlank
import kotlin.math.abs
object Day19 : Day {
override val input = readInputSplitOnBlank(19).mapIndexed { i, l -> Scanner.from(i, l.lines().drop(1)) }
override fun part1() = resolve().flatMap { it.beacons }.toSet().count()
override fun part2() = resolve().mapNotNull { it.position }.run { flatMap { a -> map { a.dist(it) } } }.maxOrNull() ?: 0
private fun resolve(): List<Scanner> {
val scanners = input.toMutableList()
while (scanners.any { it.position == null }) {
for (i in scanners.indices)
for (j in scanners.indices)
if (scanners[i].position != null && scanners[j].position == null)
scanners[i].align(scanners[j])?.apply { scanners[j] = this }
}
return scanners.toList()
}
data class Point(val x: Int, val y: Int, val z: Int) {
companion object {
val ZERO = Point(0, 0, 0)
}
operator fun plus(other: Point) = Point(x + other.x, y + other.y, z + other.z)
operator fun minus(other: Point) = Point(x - other.x, y - other.y, z - other.z)
fun dist(other: Point) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z)
}
data class Scanner(val id: Int, val beacons: List<Point>, val position: Point?) {
companion object {
private val rotations = listOf<Point.() -> Point>(
{ Point(x, -z, y) },
{ Point(-y, -z, x) },
{ Point(z, -y, x) },
{ Point(y, z, x) },
{ Point(-z, y, x) },
{ Point(-x, -z, -y) },
{ Point(z, -x, -y) },
{ Point(x, z, -y) },
{ Point(-z, x, -y) },
{ Point(y, -z, -x) },
{ Point(z, y, -x) },
{ Point(-y, z, -x) },
{ Point(-z, -y, -x) },
{ Point(z, x, y) },
{ Point(-x, z, y) },
{ Point(-z, -x, y) },
{ Point(x, -y, -z) },
{ Point(-x, -y, z) },
{ Point(y, -x, z) },
{ Point(x, y, z) },
{ Point(-y, x, z) },
{ Point(y, x, -z) },
{ Point(-x, y, -z) },
{ Point(-y, -x, -z) },
)
fun from(id: Int, lines: List<String>) = Scanner(id, lines.map { it.point() }, Point.ZERO.takeIf { id == 0 })
private fun String.point() = split(',').map { it.toInt() }.let { (x, y, z) -> Point(x, y, z) }
}
fun align(other: Scanner): Scanner? {
repeat(24) { i ->
val rotated = other.rotate(i)
beacons.flatMap { b -> rotated.beacons.map { b to it } }.forEach { (b, r) ->
val diff = b - r
val aligned = rotated.beacons.map { it + diff }
if (overlap(aligned)) {
return other.copy(beacons = aligned, position = diff)
}
}
}
return null
}
private fun rotate(index: Int) = copy(beacons = beacons.map { rotations[index](it) })
private fun overlap(other: Iterable<Point>) = (beacons.toSet() intersect other.toSet()).size >= 12
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 3,443 | aoc2021 | MIT License |
advent-of-code-2023/src/test/kotlin/Day4Test.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class Day4Test {
data class Card(
val index: Int,
val left: List<Int>,
val right: List<Int>,
) {
val winning = left.intersect(right.toSet()).size
val score: Int = if (winning == 0) 0 else 1.shl(winning - 1)
val follow: Int = left.intersect(right.toSet()).size
override fun toString(): String {
return "$left | $right - $score"
}
}
@Test
fun `silver test (example)`() {
val input =
"""
Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
"""
.trimIndent()
val cards = parseCards(input)
cards.forEach { println(it) }
cards.sumOf { it.score } shouldBe 13
}
@Test
fun `silver test`() {
val cards = parseCards(loadResource("Day4"))
cards.sumOf { it.score } shouldBe 21213
}
@Test
fun `gold test (example)`() {
val input =
"""
Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
"""
.trimIndent()
val cards = parseCards(input)
countAll(cards) shouldBe 30
}
@Test
fun `gold test`() {
val cards = parseCards(loadResource("Day4"))
countAll(cards) shouldBe 8549735
}
private fun countAll(cards: List<Card>): Int {
val cache = mutableMapOf<Card, Int>()
fun expand(card: Card): Int {
if (card.follow == 0) return 1
return cache.getOrPut(card) {
// getOrOut allows local return!
1 + (card.index + 1..card.index + card.follow).sumOf { expand(cards[it]) }
}
}
return cards.sumOf { card -> expand(card) }
}
private fun parseCards(input: String) =
input
.lines()
.filter { it.isNotEmpty() }
.mapIndexed { index, line ->
val (left, right) =
line.substringAfter(":").split("|").map { half ->
half.split(" ").mapNotNull { it.trim().toIntOrNull() }
}
Card(index, left, right)
}
}
| 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 2,617 | advent-of-code | MIT License |
src/Day09.kt | dcbertelsen | 573,210,061 | false | {"Kotlin": 29052} | import java.io.File
import kotlin.math.abs
import kotlin.math.round
import kotlin.math.roundToInt
fun main() {
fun part1(input: List<String>): Int {
val rope = Rope()
input.forEach { moveData ->
val move = moveData.split(" ")
repeat(move[1].toInt()) {
rope.move(Direction.valueOf(move[0]))
}
}
return rope.tailPositions.size
}
fun part2(input: List<String>): Int {
val rope = Rope(10)
input.forEach { moveData ->
val move = moveData.split(" ")
repeat(move[1].toInt()) {
rope.move(Direction.valueOf(move[0]))
}
}
return rope.tailPositions.size
}
val testInput = listOf<String>(
"R 4",
"U 4",
"L 3",
"D 1",
"R 4",
"D 1",
"L 5",
"R 2",
)
val testInput2 = listOf(
"R 5",
"U 8",
"L 8",
"D 3",
"R 17",
"D 10",
"L 25",
"U 20",
)
// test if implementation meets criteria from the description, like:
println(part1(testInput))
check(part1(testInput) == 13)
println(part2(testInput2))
check(part2(testInput2) == 36)
val input = File("./src/resources/Day09.txt").readLines()
println(part1(input))
println(part2(input))
}
class Rope(val length: Int = 2) {
val knots = List(length) { _ -> Knot() }
val tailPositions = mutableSetOf("0,0")
private val head = knots[0]
private fun isTouchingPrevious(index: Int) = abs(knots[index].x-knots[index-1].x) < 2
&& abs(knots[index].y-knots[index-1].y) < 2
infix fun move(direction: Direction) {
when (direction) {
Direction.U -> head.y++
Direction.D -> head.y--
Direction.L -> head.x--
Direction.R -> head.x++
}
(1 until knots.size).forEach { i ->
if (!isTouchingPrevious(i)) {
if (knots[i-1].x == knots[i].x || knots[i-1].y == knots[i].y) {
knots[i].x = (knots[i-1].x + knots[i].x) / 2
knots[i].y = (knots[i-1].y + knots[i].y) / 2
} else {
knots[i].x += if (knots[i-1].x > knots[i].x) 1 else -1
knots[i].y += if (knots[i-1].y > knots[i].y) 1 else -1
}
}
}
tailPositions.add("${knots.last().x},${knots.last().y}")
// println ("H -> ($headX, $headY), T -> ($tailX, $tailY)")
// (0 .. 5).map { r ->
// (0 .. 5).joinToString("") { c ->
// if (headX == c && headY == r) "H" else if (tailX == c && tailY == r) "T" else "."
// }
// }.reversed().forEach { println(it) }
// println()
}
}
enum class Direction {
U,D,L,R
}
data class Knot(var x: Int = 0, var y: Int = 0) | 0 | Kotlin | 0 | 0 | 9d22341bd031ffbfb82e7349c5684bc461b3c5f7 | 2,913 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SmallestEquivalentString.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 dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
/**
* 1061. Lexicographically The Smallest Equivalent String
* @see <a href="https://leetcode.com/problems/lexicographically-smallest-equivalent-string/">Source</a>
*/
fun interface SmallestEquivalentString {
operator fun invoke(s1: String, s2: String, baseStr: String): String
}
class SmallestEquivalentStringUnion : SmallestEquivalentString {
override operator fun invoke(s1: String, s2: String, baseStr: String): String {
val graph = IntArray(ALPHABET_LETTERS_COUNT)
for (i in 0 until ALPHABET_LETTERS_COUNT) {
graph[i] = i
}
for (i in s1.indices) {
val a: Int = s1[i] - 'a'
val b: Int = s2[i] - 'a'
val end1 = find(graph, b)
val end2 = find(graph, a)
if (end1 < end2) {
graph[end2] = end1
} else {
graph[end1] = end2
}
}
val sb = StringBuilder()
for (i in baseStr.indices) {
val c: Char = baseStr[i]
sb.append(('a'.code + find(graph, c.code - 'a'.code)).toChar())
}
return sb.toString()
}
private fun find(graph: IntArray, idx: Int): Int {
var i = idx
while (graph[i] != i) {
i = graph[i]
}
return i
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,997 | kotlab | Apache License 2.0 |
src/y2022/day09.kt | sapuglha | 573,238,440 | false | {"Kotlin": 33695} | package y2022
import readFileAsLines
data class KnotPosition(
val name: String,
var x: Int = 0,
var y: Int = 0,
)
fun KnotPosition.move(direction: String) = when (direction) {
"U" -> y++
"D" -> y--
"L" -> x--
else /*RIGHT*/ -> x++
}
private fun KnotPosition.tailFollow(head: KnotPosition, visitedPositions: HashMap<String, Int>) {
val horizontalDistance = head.x - x
val verticalDistance = head.y - y
var moved = true
/*
E F 0 1 2
D - - - 3
C - I - 4
B - - - 5
A 9 8 7 6
*/
if (horizontalDistance == 0 && verticalDistance == 2) { // 0 - up
y++
} else if (horizontalDistance == 1 && verticalDistance == 2 || // 1 diagonal
horizontalDistance == 2 && verticalDistance == 2 || // 2 diagonal
horizontalDistance == 2 && verticalDistance == 1 // 3 diagonal
) {
x++
y++
} else if (horizontalDistance == 2 && verticalDistance == 0) { // 4 - right
x++
} else if (horizontalDistance == 2 && verticalDistance == -1 || // 5 diagonal
horizontalDistance == 2 && verticalDistance == -2 || // 6 diagonal
horizontalDistance == 1 && verticalDistance == -2 // 7 diagonal
) {
x++
y--
} else if (horizontalDistance == 0 && verticalDistance == -2) { // 8 - down
y--
} else if (horizontalDistance == -1 && verticalDistance == -2 || // 9 diagonal
horizontalDistance == -2 && verticalDistance == -2 || // A diagonal
horizontalDistance == -2 && verticalDistance == -1 // B diagonal
) {
x--
y--
} else if (horizontalDistance == -2 && verticalDistance == 0) { // C - left
x--
} else if (horizontalDistance == -2 && verticalDistance == 1 || // D diagonal
horizontalDistance == -2 && verticalDistance == 2 || // E diagonal
horizontalDistance == -1 && verticalDistance == 2 // F diagonal
) {
x--
y++
} else {
moved = false
}
if (this.name == "T" && moved) {
val position = "$x,$y"
val currentPosition = visitedPositions[position]
if (currentPosition == null) {
visitedPositions[position] = 1
} else {
visitedPositions[position] = currentPosition + 1
}
}
}
fun printMap(
headTailPosition: List<KnotPosition>,
xStart: Int = 0,
xEnd: Int = 5,
yStart: Int = 0,
yEnd: Int = 5
) {
val totalX = xEnd - xStart
for (countX in xStart..xEnd) {
headTailPosition
.filter { it.y == totalX - countX }
.sortedBy { it.x }
.also { list ->
for (countY in yStart..yEnd) {
val item = list.firstOrNull { it.x == countY }
print(item?.name ?: ".")
}
println()
}
}
println()
}
fun createRope(size: Int): List<KnotPosition> = mutableListOf<KnotPosition>()
.apply {
add(KnotPosition("H"))
repeat(size - 2) { index ->
add(KnotPosition("${index + 1}"))
}
add(KnotPosition("T"))
}
fun main() {
fun part1(input: List<String>): Int {
val rope = createRope(2)
val visitedPositions: HashMap<String, Int> = hashMapOf("0,0" to 1)
input.forEach { command ->
val (direction, count) = command.split(" ")
repeat(count.toInt()) {
rope.first().move(direction)
rope.last().tailFollow(rope.first(), visitedPositions)
printMap(rope)
}
}
return visitedPositions.count()
}
fun part2(input: List<String>): Int {
val rope = createRope(10)
val visitedPositions: HashMap<String, Int> = hashMapOf("0,0" to 1)
input.forEach { command ->
val (direction, count) = command.split(" ")
repeat(count.toInt()) {
rope.first().move(direction)
rope
.subList(1, rope.size)
.forEachIndexed { index, item ->
val newIndex = index + 1
item.tailFollow(rope[newIndex - 1], visitedPositions)
}
printMap(rope)
// printMap(headTailPosition, -5, 16, -11, 15)
}
}
return visitedPositions.count()
}
"y2022/data/day09_test1".readFileAsLines().let {
check(part1(it) == 13)
check(part2(it) == 1)
}
check(part2("y2022/data/day09_test2".readFileAsLines()) == 36)
"y2022/data/day09".readFileAsLines().let { input ->
println("part1: ${part1(input)}")
println("part2: ${part2(input)}")
}
}
| 0 | Kotlin | 0 | 0 | 82a96ccc8dcf38ae4974e6726e27ddcc164e4b54 | 4,730 | adventOfCode2022 | Apache License 2.0 |
src/Day13.kt | xNakero | 572,621,673 | false | {"Kotlin": 23869} | import Status.*
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
object Day13 {
fun part1(): Int =
parse()
.mapIndexed { index, (first, second) -> (index + 1) to compareElements(first, second) }
.filter { it.second == LESSER }
.sumOf { it.first }
fun part2(): Int =
parse()
.map { listOf(it.first, it.second) }
.flatten()
.let { it + "[[2]]".toPacket() + "[[6]]".toPacket() }
.sortedWith { first, second -> compareElements(first as JsonElement, second as JsonElement).representation }
.let { (it.indexOf("[2]".toPacket()) + 1) * (it.indexOf("[6]".toPacket()) + 1) }
private fun compareElements(first: JsonElement, second: JsonElement): Status =
when {
first is JsonArray && second is JsonArray -> {
compareArrays(first, second)
}
first is JsonPrimitive && second is JsonPrimitive -> {
compareValues(first, second)
}
first is JsonPrimitive && second is JsonArray -> {
compareElements(JsonArray(listOf(first)), second)
}
first is JsonArray && second is JsonPrimitive -> {
compareElements(first, JsonArray(listOf(second)))
}
else -> throw IllegalStateException("No such set of elements is allowed")
}
private fun compareValues(first: JsonPrimitive, second: JsonPrimitive): Status =
calculateOne(first.toString().toInt(), second.toString().toInt())
private fun compareArrays(first: JsonArray, second: JsonArray): Status {
repeat((0 until minOf(first.size, second.size)).count()) { index ->
val result = compareElements(first[index], second[index])
if (result != EQUAL) {
return result
}
}
return calculateOne(first.size, second.size)
}
private fun calculateOne(first: Int, second: Int): Status {
val result = first - second
return when {
result < 0 -> LESSER
result == 0 -> EQUAL
else -> BIGGER
}
}
private fun parse(): List<Pair<JsonArray, JsonArray>> = readInput("day13")
.windowed(2, 3)
.map { (first, second) -> Pair(first.toPacket(), second.toPacket()) }
}
private fun String.toPacket(): JsonArray = Json.decodeFromString(this)
enum class Status(val representation: Int) {
LESSER(-1), BIGGER(1), EQUAL(0)
}
fun main() {
println(Day13.part1())
println(Day13.part2())
} | 0 | Kotlin | 0 | 0 | c3eff4f4c52ded907f2af6352dd7b3532a2da8c5 | 2,765 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g1401_1500/s1463_cherry_pickup_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1401_1500.s1463_cherry_pickup_ii
// #Hard #Array #Dynamic_Programming #Matrix
// #2023_06_13_Time_198_ms_(100.00%)_Space_40.3_MB_(100.00%)
class Solution {
fun cherryPickup(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
val dp = Array(n) { Array(n) { IntArray(m) } }
dp[0][n - 1][0] = grid[0][0] + grid[0][n - 1]
for (k in 1 until m) {
for (i in 0..Math.min(n - 1, k)) {
for (j in n - 1 downTo Math.max(0, n - 1 - k)) {
dp[i][j][k] = maxOfLast(dp, i, j, k) + grid[k][i] + if (i == j) 0 else grid[k][j]
}
}
}
var result = 0
for (i in 0..Math.min(n - 1, m)) {
for (j in n - 1 downTo Math.max(0, n - 1 - m)) {
result = Math.max(result, dp[i][j][m - 1])
}
}
return result
}
private fun maxOfLast(dp: Array<Array<IntArray>>, i: Int, j: Int, k: Int): Int {
var result = 0
for (x in -1..1) {
for (y in -1..1) {
val r = i + x
val c = j + y
if (r >= 0 && r < dp[0].size && c >= 0 && c < dp[0].size) {
result = Math.max(result, dp[r][c][k - 1])
}
}
}
return result
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,345 | LeetCode-in-Kotlin | MIT License |
2022/src/main/kotlin/Day13.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import Day13.Data.DataList
import Day13.Data.DataValue
import kotlin.math.min
object Day13 {
fun part1(input: String): Int {
return input.split("\n\n")
.map { it.splitNewlines() }
.map { (left, right) -> compare(parse(left), parse(right)) }
.foldIndexed(0) { index, acc, result -> acc + if (result < 0) index + 1 else 0 }
}
fun part2(input: String): Int {
val dividers = listOf(parse("[[2]]"), parse("[[6]]"))
val data = input
.splitNewlines()
.filter { it.isNotEmpty() }
.map { parse(it) }
.plus(dividers)
.sortedWith(::compare)
return dividers.map { data.indexOf(it) + 1 }.reduce(Int::times)
}
private fun compare(left: Data, right: Data): Int {
return when (left) {
is DataValue -> when (right) {
is DataList -> compareLists(DataList(listOf(left)), right)
is DataValue -> left.value - right.value
}
is DataList -> when (right) {
is DataList -> compareLists(left, right)
is DataValue -> compareLists(left, DataList(listOf(right)))
}
}
}
private fun compareLists(left: DataList, right: DataList): Int {
for (index in 0 until min(left.list.size, right.list.size)) {
val result = compare(left.list[index], right.list[index])
if (result != 0) {
return result
}
}
return left.list.size - right.list.size
}
private fun parse(packet: String) = parse(packet, 1).first
private fun parse(data: String, start: Int): Pair<Data, Int> {
val list = mutableListOf<Data>()
val curr = StringBuilder()
fun appendValueIfPresent() {
if (curr.isNotEmpty()) {
list.add(DataValue(curr.toString().toInt()))
curr.clear()
}
}
var index = start
while (index < data.length) {
when (val char = data[index]) {
'[' -> {
val (innerData, newIndex) = parse(data, index + 1)
list.add(innerData)
index = newIndex
}
']' -> {
appendValueIfPresent()
return DataList(list) to index + 1
}
',' -> {
appendValueIfPresent()
index++
}
else -> {
curr.append(char)
index++
}
}
}
throw IllegalStateException("Unexpected parser failure!")
}
private sealed class Data {
data class DataList(val list: List<Data>) : Data()
data class DataValue(val value: Int) : Data()
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 2,466 | advent-of-code | MIT License |
src/day-8/part-1/solution-day-8-part-1.kts | d3ns0n | 572,960,768 | false | {"Kotlin": 31665} | import java.io.File
val treeGrid = mutableListOf<String>()
File("../input.txt").readLines()
.forEach { treeGrid.add(it) }
val treeGridWidth = treeGrid.first().length
val treeGridHeight = treeGrid.size
fun isAtEdge(x: Int, y: Int) = x == 0 || x == treeGridWidth - 1 || y == 0 || y == treeGridHeight - 1
fun isVisibleFromLeft(x: Int, y: Int): Boolean {
val height = treeGrid[y][x].code
return treeGrid[y].substring(0, x).all { it.code < height }
}
fun isVisibleFromRight(x: Int, y: Int): Boolean {
val height = treeGrid[y][x].code
return treeGrid[y].substring(x + 1, treeGrid[y].length).all { it.code < height }
}
fun isVisibleFromTop(x: Int, y: Int): Boolean {
val height = treeGrid[y][x].code
return (0 until y).all { treeGrid[it][x].code < height }
}
fun isVisibleFromBottom(x: Int, y: Int): Boolean {
val height = treeGrid[y][x].code
return (y + 1 until treeGridHeight).all { treeGrid[it][x].code < height }
}
fun findVisibleTrees(treeGrid: List<String>): Int {
var visibleTrees = 0
for (y in treeGrid.indices) {
for (x in 0 until treeGrid[y].length) {
if (
isAtEdge(x, y) ||
isVisibleFromLeft(x, y) ||
isVisibleFromRight(x, y) ||
isVisibleFromTop(x, y) ||
isVisibleFromBottom(x, y)
) {
visibleTrees++
}
}
}
return visibleTrees
}
val visibleTrees = findVisibleTrees(treeGrid)
println(visibleTrees)
assert(visibleTrees == 1736)
| 0 | Kotlin | 0 | 0 | 8e8851403a44af233d00a53b03cf45c72f252045 | 1,539 | advent-of-code-22 | MIT License |
src/2017Day10.kt | TheGreatJakester | 573,222,328 | false | {"Kotlin": 47612} | package day2017_10
import utils.runSolver
private typealias SolutionType = Int
private const val defaultSolution = 0
private const val dayNumber: String = "10"
private val testSolution1: SolutionType? = 88
private val testSolution2: SolutionType? = 36
class Node(val number: Int, var node: Node? = null) {
fun getNodeAt(index: Int): Node {
if (index == 0) return this
return node!!.getNodeAt(index - 1)
}
fun getCut(length: Int) = getCut(length, mutableListOf())
private fun getCut(
length: Int,
mutableList: MutableList<Node>
): List<Node> {
if (length > 0) {
mutableList.add(this)
return node!!.getCut(length - 1, mutableList)
}
return mutableList
}
fun reverse(previous: Node, newLast: Node, length: Int){
}
override fun toString(): String = number.toString()
private fun toRecursiveString(start: Node = this): String {
val n = node ?: return number.toString()
if (node == start) return number.toString()
return number.toString() + ", " + n.toRecursiveString(start)
}
}
private fun part1(input: String): SolutionType {
val firstNode = Node(0)
var curNode = firstNode
repeat(254) {
val next = Node(it + 1)
curNode.node = next
curNode = next
}
curNode.node = firstNode
curNode = firstNode
val cut = firstNode.getCut(4)
println(cut)
return defaultSolution
}
private fun part2(input: String): SolutionType {
return defaultSolution
}
fun main() {
val input = "97,167,54,178,2,11,209,174,119,248,254,0,255,1,64,190"
runSolver("Part 1", input, null, ::part1)
runSolver("Part 2", input, null, ::part2)
}
| 0 | Kotlin | 0 | 0 | c76c213006eb8dfb44b26822a44324b66600f933 | 1,740 | 2022-AOC-Kotlin | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day09.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode.days
import tr.emreone.adventofcode.manhattanDistanceTo
import tr.emreone.adventofcode.move
import tr.emreone.kotlin_utils.math.Point2D
object Day09 {
private val PATTERN = """(\w+) (\d+)""".toRegex()
private fun calcNewPositionOfKnot(me: Point2D, nextKnot: Point2D): Point2D {
val distance = nextKnot.manhattanDistanceTo(me)
var newPosition = me
/*
* if distance is greater than 1, then we have to move tail to new positions
*
* 3 2 3
* 3 2 1 2 3
* 2 1 M 1 2
* 3 2 1 2 3
* 3 2 3
*/
when (distance) {
0L, 1L -> {
// do nothing
}
else -> {
// distance 2: if share one axis then move tail to head
if (distance == 2L && !nextKnot.sharesAxisWith(me)) {
// head is direct diagonal to tail and do nothing
} else {
val xDirection = (nextKnot.x - me.x).coerceIn(-1, 1)
val yDirection = (nextKnot.y - me.y).coerceIn(-1, 1)
newPosition = Point2D(me.x + xDirection, me.y + yDirection)
}
}
}
return newPosition
}
private fun trackVisitedCoordsOfTail(input: List<String>, snakeLength: Int = 2): Set<Point2D> {
val snakeKnots = mutableListOf<Pair<Point2D, List<Point2D>>>()
for(i in 0 until snakeLength) {
snakeKnots.add(Point2D(0, 0) to listOf(Point2D(0, 0)))
}
input.forEach {
val (direction, distance) = PATTERN.matchEntire(it)!!.destructured
for (i in 1..distance.toInt()) {
val newHeadPosition = snakeKnots[0].first.move(direction, 1)
snakeKnots[0] = newHeadPosition to (snakeKnots[0].second + newHeadPosition)
for(k in 1 until snakeKnots.size) {
val prevKnot = snakeKnots[k - 1].first
val me = snakeKnots[k].first
val newTailPosition = calcNewPositionOfKnot(me, prevKnot)
snakeKnots[k] = newTailPosition to (snakeKnots[k].second + newTailPosition)
}
}
}
return snakeKnots.last().second.toSet()
}
fun part1(input: List<String>): Int {
return trackVisitedCoordsOfTail(input).size
}
fun part2(input: List<String>): Int {
return trackVisitedCoordsOfTail(input, 10).size
}
}
| 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 2,542 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/whac_a_mole/WhacMole.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.whac_a_mole
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/discuss/interview-question/350139/Google-or-Phone-Screen-or-Whac-A-Mole
*/
class WhacMoleTests {
@Test fun `hit max amount of moles`() {
hit(arrayOf(0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0), malletWidth = 4) shouldEqual Pair(1, 3)
hit(arrayOf(0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0), malletWidth = 5) shouldEqual Pair(1, 4)
hit(arrayOf(0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0), malletWidth = 6) shouldEqual Pair(0, 4)
}
@Test fun `hit max amount of moles with two mallets`() {
hit2(arrayOf(0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0), malledWidth = 5) shouldEqual Triple(1, 7, 6)
}
}
private fun hit(holes: Array<Int>, malletWidth: Int): Pair<Int, Int> {
var max = -1
var maxIndex = -1
holes.toList().windowed(size = malletWidth, step = 1).forEachIndexed { i, window ->
val sum = window.sum()
if (sum > max) {
max = sum
maxIndex = i
}
}
return Pair(maxIndex, max)
}
private fun hit2(holes: Array<Int>, malledWidth: Int): Triple<Int, Int, Int> {
var max = -1
var maxIndex1 = -1
var maxIndex2 = -1
holes.toList().windowed(size = malledWidth, step = 1).forEachIndexed { i1, window1 ->
val shift = i1 + malledWidth
holes.toList().drop(shift).windowed(size = malledWidth, step = 1).forEachIndexed { i2, window2 ->
val sum = window1.sum() + window2.sum()
if (sum > max) {
max = sum
maxIndex1 = i1
maxIndex2 = i2 + shift
}
}
}
return Triple(maxIndex1, maxIndex2, max)
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,707 | katas | The Unlicense |
src/main/kotlin/info/benjaminhill/stats/preprocess/Preprocessing.kt | salamanders | 184,444,482 | false | null | package info.benjaminhill.stats.preprocess
import org.nield.kotlinstatistics.percentile
/** Anything outside the bounds gets clamped to the bounds */
fun List<Double>.coercePercentile(pct: Double = 0.05): List<Double> {
require(isNotEmpty())
require(pct in 0.0..1.0)
// odd that it is pct of 100, not pct of 1
val min = this.percentile(pct * 100)
val max = this.percentile(100 - (pct * 100))
return map {
it.coerceIn(min, max)
}
}
/** Linear remap to range */
fun List<Double>.normalizeToRange(min: Double = 0.0, max: Double = 1.0): List<Double> {
require(isNotEmpty())
val currentMin = minOrNull()!!
val currentMax = maxOrNull()!!
if (currentMin == currentMax) {
return this.toList()
}
return map {
(it - currentMin) / (currentMax - currentMin) * max + min
}
}
/** All inputs must be positive */
fun List<Double>.histogram(buckets: Int = 11): IntArray {
require(isNotEmpty())
forEach { require(it >= 0.0) { "This histogram requires positive numbers: $it" } }
val max = maxOrNull()!!
val result = IntArray(buckets)
forEach {
result[(it / max * buckets).toInt().coerceAtMost(buckets - 1)]++
}
return result
}
fun List<Double>.smooth7(iterations: Int = 1): List<Double> {
require(iterations >= 1)
val kernel = mapOf(
-3 to .006,
-2 to .061,
-1 to .242,
0 to .382,
1 to .242,
2 to .061,
3 to .006
)
val source = if (iterations > 1) {
this.smooth7(iterations - 1)
} else {
this
}
return source.indices.map { idx ->
kernel.map { (k, v) ->
val offset = if (idx + k in source.indices) {
idx + k
} else {
idx + -k
}
source[offset] * v
}.sum()
}
}
| 0 | Kotlin | 0 | 0 | 3e3c246c18fa3009f7f54822a70202da3f1b65c5 | 1,863 | ezstats | MIT License |
src/Day11.kt | konclave | 573,548,763 | false | {"Kotlin": 21601} | import kotlin.collections.ArrayDeque
fun main() {
class Monkey(monkey: List<String>, var worryDivider: Int? = null) {
val id: Int
val items: ArrayDeque<Long> = ArrayDeque()
var actCount: Int = 0
private val operator: String
private val opArg: String
val testNum: Int
private val testTrueMonkeyId: Int
private val testFalseMonkeyId: Int
init {
val (idStr, itemsStr, operationStr) = monkey
val (testStr, testTrueStr, testFalseStr) = monkey.slice(3..5)
this.id = Regex("Monkey (\\d+):").find(idStr)!!.groupValues[1].toInt()
itemsStr
.trim()
.replace("Starting items: ", "")
.split(", ")
.forEach { this.items.addLast(it.toLong()) }
this.testNum = testStr.trim().replace("Test: divisible by ", "").toInt()
this.testTrueMonkeyId = testTrueStr.trim().replace("If true: throw to monkey ", "").toInt()
this.testFalseMonkeyId = testFalseStr.trim().replace("If false: throw to monkey ", "").toInt()
operationStr.trim().replace("Operation: new = ", "")
val (_, operator, arg2) = Regex("([+*])\\s(.+)")
.find(
operationStr
.trim()
.replace("Operation: new = old ", "")
)!!
.groupValues
this.operator = operator
this.opArg = arg2
}
fun act(): Pair<Long, Int> {
val worryLevel = this.inspect()
this.actCount += 1
val next = this.getNextMonkeyId(worryLevel)
return Pair(worryLevel, next)
}
private fun operation(old: Long): Long {
return when (this.operator) {
"+" -> {
if (this.opArg == "old") old + old else old + this.opArg.toInt()
}
"*" -> {
if (this.opArg == "old") old * old else old * this.opArg.toInt()
}
else -> throw Error("Unknown operator")
}
}
private fun getNextMonkeyId(worryLevel: Long): Int {
return if (worryLevel % this.testNum == 0L) this.testTrueMonkeyId else this.testFalseMonkeyId
}
private fun inspect(): Long {
return if (this.worryDivider != null) this.operation(this.items.removeFirst()) % this.worryDivider!! else this.operation(this.items.removeFirst()) / 3
}
fun catchItem(worryLevel: Long) {
this.items.addLast(worryLevel)
}
}
fun solve1(input: List<String>): Long {
val monkeys: List<Monkey> = input.chunked(7).map { Monkey(it) }
for (i in 1..20) {
monkeys.forEach { monkey ->
while (monkey.items.size > 0) {
val (item, monkeyId) = monkey.act()
val destMonkey = monkeys.find { it.id == monkeyId }!!
destMonkey.catchItem(item)
}
}
}
return monkeys
.sortedByDescending { it.actCount }
.take(2)
.fold(1) { acc, monkey -> acc * monkey.actCount }
}
fun solve2(input: List<String>): Long {
val monkeys: List<Monkey> = input.chunked(7).map { Monkey(it, 1) }
val divider = monkeys.map { it.testNum }.fold(1) { acc, it -> acc * it }
monkeys.forEach { it.worryDivider = divider}
repeat (10000) {
monkeys.forEach { monkey ->
while (monkey.items.size > 0) {
val (item, monkeyId) = monkey.act()
val destMonkey = monkeys.find { it.id == monkeyId }!!
destMonkey.catchItem(item)
}
}
}
return monkeys
.sortedByDescending { it.actCount }
.take(2)
.fold(1L) { acc, monkey -> acc * monkey.actCount }
}
val input = readInput("Day11")
println(solve1(input))
println(solve2(input))
}
| 0 | Kotlin | 0 | 0 | 337f8d60ed00007d3ace046eaed407df828dfc22 | 4,114 | advent-of-code-2022 | Apache License 2.0 |
src/Day24.kt | kipwoker | 572,884,607 | false | null | import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
class Day24 {
data class Valley(val blizzards: Map<Point, List<Direction>>, val maxY: Int, val maxX: Int)
data class Moment(val expedition: Point, val minutesSpent: Int)
fun parse(input: List<String>): Valley {
val blizzards = mutableMapOf<Point, List<Direction>>()
val walls = mutableSetOf<Point>()
for ((y, line) in input.withIndex()) {
for ((x, cell) in line.withIndex()) {
when (cell) {
'#' -> walls.add(Point(x, y))
'>' -> blizzards[Point(x, y)] = listOf(Direction.Right)
'<' -> blizzards[Point(x, y)] = listOf(Direction.Left)
'^' -> blizzards[Point(x, y)] = listOf(Direction.Up)
'v' -> blizzards[Point(x, y)] = listOf(Direction.Down)
}
}
}
return Valley(blizzards, input.size - 1, input[0].length - 1)
}
fun nextPosition(direction: Direction, position: Point, valley: Valley): Point {
val d = when (direction) {
Direction.Up -> Point(0, -1)
Direction.Down -> Point(0, 1)
Direction.Left -> Point(-1, 0)
Direction.Right -> Point(1, 0)
}
val newPosition = position.sum(d)
if (newPosition.x <= 0) {
return Point(valley.maxX - 1, newPosition.y)
}
if (newPosition.x >= valley.maxX) {
return Point(1, newPosition.y)
}
if (newPosition.y <= 0) {
return Point(newPosition.x, valley.maxY - 1)
}
if (newPosition.y >= valley.maxY) {
return Point(newPosition.x, 1)
}
return newPosition
}
fun print(valley: Valley) {
for (y in 0..valley.maxY) {
for (x in 0..valley.maxX) {
val point = Point(x, y)
if (x == 0 || x == valley.maxX || y == 0 || y == valley.maxY) {
print('#')
} else if (point !in valley.blizzards.keys) {
print('.')
} else {
val directions = valley.blizzards[point]!!
if (directions.size == 1) {
when (directions.first()) {
Direction.Up -> print('^')
Direction.Down -> print('v')
Direction.Left -> print('<')
Direction.Right -> print('>')
}
} else {
print(directions.size)
}
}
}
println()
}
println()
}
fun next(valley: Valley): Valley {
val blizzards = valley.blizzards.flatMap { blizzard ->
blizzard.value.map { direction -> nextPosition(direction, blizzard.key, valley) to direction }
}.groupBy({ x -> x.first }, { x -> x.second })
val newValley = Valley(blizzards, valley.maxY, valley.maxX)
return newValley
}
fun getAvailableMoves(current: Point, start: Point, target: Point, valley: Valley): Set<Point> {
return listOf(
Point(0, 0), // wait
Point(0, -1),
Point(0, 1),
Point(-1, 0),
Point(1, 0)
)
.map { p -> p.sum(current) }
.filter { p ->
(p.x > 0 && p.x < valley.maxX && p.y > 0 && p.y < valley.maxY) ||
p == target || p == start
}
.filter { p -> !valley.blizzards.containsKey(p) }
.toSet()
}
fun search(start: Point, target: Point, initValleyState: Valley): Pair<Int, Valley> {
val valleyStates = mutableListOf(initValleyState)
print(initValleyState)
val q = ArrayDeque<Moment>()
val visited = mutableSetOf<Moment>()
val initMoment = Moment(start, 0)
q.addLast(initMoment)
visited.add(initMoment)
while (q.isNotEmpty()) {
val moment = q.removeFirst()
val nextMinute = moment.minutesSpent + 1
val nextValleyState = if (valleyStates.size > nextMinute) {
valleyStates[nextMinute]
} else {
valleyStates.add(next(valleyStates.last()))
valleyStates.last()
}
val availableMoves = getAvailableMoves(moment.expedition, start, target, nextValleyState)
if (target in availableMoves) {
return nextMinute to nextValleyState
}
for (move in availableMoves) {
val nextMoment = Moment(move, nextMinute)
if (nextMoment !in visited) {
visited.add(nextMoment)
q.addLast(nextMoment)
}
}
}
return -1 to initValleyState
}
fun part1(input: List<String>): String {
val valley = parse(input)
val start = Point(1, 0)
val target = Point(valley.maxX - 1, valley.maxY)
val count = search(start, target, valley).first
return count.toString()
}
fun part2(input: List<String>): String {
val valley = parse(input)
val start = Point(1, 0)
val target = Point(valley.maxX - 1, valley.maxY)
val forward = search(start, target, valley)
val r1 = forward.first
println("R1 $r1")
val reward = search(target, start, forward.second)
val r2 = reward.first
println("R2 $r2")
val again = search(start, target, reward.second)
val r3 = again.first
println("R3 $r3")
return (r1 + r2 + r3).toString()
}
}
@OptIn(ExperimentalTime::class)
@Suppress("DuplicatedCode")
fun main() {
val solution = Day24()
val name = solution.javaClass.name
val execution = setOf(
ExecutionMode.Test1,
ExecutionMode.Test2,
ExecutionMode.Exec1,
ExecutionMode.Exec2
)
fun test() {
val expected1 = "18"
val expected2 = "54"
val testInput = readInput("${name}_test")
if (execution.contains(ExecutionMode.Test1)) {
println("Test part 1")
assert(solution.part1(testInput), expected1)
println("> Passed")
}
if (execution.contains(ExecutionMode.Test2)) {
println("Test part 2")
assert(solution.part2(testInput), expected2)
println("> Passed")
println()
}
println("=================================")
println()
}
fun run() {
val input = readInput(name)
if (execution.contains(ExecutionMode.Exec1)) {
val elapsed1 = measureTime {
println("Part 1: " + solution.part1(input))
}
println("Elapsed: $elapsed1")
println()
}
if (execution.contains(ExecutionMode.Exec2)) {
val elapsed2 = measureTime {
println("Part 2: " + solution.part2(input))
}
println("Elapsed: $elapsed2")
println()
}
}
test()
run()
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 7,236 | aoc2022 | Apache License 2.0 |
src/Day06.kt | coolcut69 | 572,865,721 | false | {"Kotlin": 36853} | fun main() {
fun check(input: String, size: Int): Int {
for (i in 0..input.length - size) {
val message = input.substring(i until i + size)
val groupBy: Map<String, List<String>> = message.chunked(1).groupBy { it.uppercase() }
if (groupBy.size == size) {
return i + size
}
}
return 0
}
fun part1(input: String): Int {
return check(input, 4)
}
fun part2(input: String): Int {
return check(input, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7)
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6)
check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10)
check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11)
check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19)
check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23)
check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23)
check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29)
check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26)
val input = readInput("Day06").first()
println(part1(input))
check(part1(input) == 1080)
println(part2(input))
check(part2(input) == 3645)
}
| 0 | Kotlin | 0 | 0 | 031301607c2e1c21a6d4658b1e96685c4135fd44 | 1,386 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/day17/Day17.kt | daniilsjb | 434,765,082 | false | {"Kotlin": 77544} | package day17
import java.io.File
import kotlin.math.abs
import kotlin.math.max
fun main() {
val data = parse("src/main/kotlin/day17/Day17.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 17 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Target(
val x1: Int,
val x2: Int,
val y1: Int,
val y2: Int,
)
private fun parse(path: String): Target {
val regex = """target area: x=(-?\d+)\.\.(-?\d+), y=(-?\d+)\.\.(-?\d+)""".toRegex()
val contents = File(path).readText()
val (x1, x2, y1, y2) = regex.find(contents)!!.destructured
return Target(x1.toInt(), x2.toInt(), y1.toInt(), y2.toInt())
}
// Frankly, this problem is very confusing to me, and I doubt this solution
// will work for any input that adheres to the description. But it worked for
// me, and I don't feel interested in making this any more flexible ¯\_(ツ)_/¯
private fun part1(target: Target): Int =
(abs(target.y1) - 1).let { n -> n * (n + 1) / 2 }
private fun Target.isReachedBy(vx: Int, vy: Int): Boolean {
var (x, y) = 0 to 0
var (dx, dy) = vx to vy
while (x <= x2 && y >= y1) {
x += dx
y += dy
if (x in x1..x2 && y in y1..y2) {
return true
}
dx = max(dx - 1, 0)
dy -= 1
}
return false
}
private fun part2(target: Target): Int {
val (vx0, vx1) = 1 to target.x2
val (vy0, vy1) = target.y1 to part1(target)
var counter = 0
for (vy in vy0..vy1) {
for (vx in vx0..vx1) {
if (target.isReachedBy(vx, vy)) {
++counter
}
}
}
return counter
}
| 0 | Kotlin | 0 | 1 | bcdd709899fd04ec09f5c96c4b9b197364758aea | 1,783 | advent-of-code-2021 | MIT License |
src/main/aoc2023/Day3.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2023
import AMap
import Pos
import increase
class Day3(input: List<String>) {
private val map = AMap.parse(input, listOf('.'))
private val numbers = findNumbers()
private val symbols = map.toMap().filterValues { it !in '0'..'9' }
// Map each number to the position of the first digit in the number
private fun findNumbers(): Map<Pos, String> {
val rawNumbers = map.toMap().filterValues { it in '0'..'9' }
var currentNumber = ""
var previousPos = Pos(-1, -1)
val numbers = mutableMapOf<Pos, String>()
rawNumbers.forEach { (pos, value) ->
if (pos != previousPos.move(Direction.Right) && currentNumber != "") {
numbers[previousPos.move(Direction.Left, currentNumber.length - 1)] = currentNumber
currentNumber = ""
}
currentNumber += value
previousPos = pos
}
numbers[previousPos.move(Direction.Left, currentNumber.length - 1)] = currentNumber
return numbers
}
// Number of neighbours (which are symbols) each number have
private val numNeighboursForNumbers = mutableMapOf<Pos, Int>()
// Map of symbols to all their neighbours (which are numbers)
private val neighboursOfSymbols = mutableMapOf<Pos, MutableList<String>>()
init {
numbers.forEach { (pos, number) ->
// All neighbouring positions to the current number
val neighbours = mutableSetOf<Pos>()
(number.indices).forEach {
neighbours.addAll(pos.move(Direction.Right, it).allNeighbours(true))
}
symbols.filterKeys { it in neighbours }.forEach { (symbolPos, _) ->
numNeighboursForNumbers.increase(pos)
if (neighboursOfSymbols[symbolPos] == null) {
neighboursOfSymbols[symbolPos] = mutableListOf()
}
neighboursOfSymbols[symbolPos]!!.add(number)
}
}
}
fun solvePart1(): Int {
return numbers
.filterKeys { numNeighboursForNumbers.getOrDefault(it, 0) > 0 }
.values
.sumOf { it.toInt() }
}
fun solvePart2(): Int {
return neighboursOfSymbols
.filter { symbols[it.key] == '*' && it.value.size == 2 }
.values
.sumOf { it.map { number -> number.toInt() }.reduce(Int::times) }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,425 | aoc | MIT License |
src/UsefulStuff.kt | AmandaLi0 | 574,592,026 | false | {"Kotlin": 5338} | fun main(){
val input = readInput("numbers")
println("Sum: ${countWords(input)}")
}
fun sumAllNums(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{
// var min = Integer.MAX_VALUE
// for(num in input){
// if(num.toInt()< min){
// min = num.toInt()
// }
// }
// return min
return input.map { it.toInt() }.min()
}
fun findTwoSmallest(input: List<String>):Int{
val sorted = input.map{it.toInt()}.sorted()
return sorted.take(2).sum()
}
//words separated by spaces
fun countWords(input: List<String>): Int{
var total = 0
for(i in input.indices){
val words = input[i].split(" ")
total+= words.size
}
return total
}
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 | 5ce0072f3095408688a7812bc3267834f2ee8cee | 1,034 | AdventOfCode | Apache License 2.0 |
solutions/aockt/y2023/Y2023D21.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.parse
import aockt.util.spacial.Area
import aockt.util.spacial.Direction
import aockt.util.spacial.Point
import aockt.util.spacial.move
import aockt.util.validation.assume
import io.github.jadarma.aockt.core.Solution
object Y2023D21 : Solution {
/**
* The map to an elven garden, showing only the finite version of the repeating tile.
* @property area The bounds of the tile.
* @property walls The coordinates of walls, which cannot be travelled on.
*/
private class Garden(val area: Area, val walls: Set<Point>) {
init {
require(walls.all { it in area }) { "Some walls are not within the area." }
}
/** Get the neighbours of the [point], within the same tile, and excluding walls. */
private fun neighborsOf(point: Point): List<Point> =
Direction.all
.map(point::move)
.filter { it in area && it !in walls }
/**
* From the [start]ing point, simulates walking an exact number of [steps] and returns all the points where
* you could end up.
*/
fun explore(start: Point, steps: Int): Set<Point> = buildSet {
val queue = ArrayDeque<Pair<Point, Int>>()
val alreadyQueued = mutableSetOf<Point>()
queue.add(start to steps)
while (queue.isNotEmpty()) {
val (point, stepsLeft) = queue.removeFirst()
if (stepsLeft % 2 == 0) add(point)
if (stepsLeft > 0) {
neighborsOf(point)
.filterNot { it in alreadyQueued }
.forEach {
queue.add(it to stepsLeft - 1)
alreadyQueued.add(it)
}
}
}
}
}
/** Parse the [input] and return the garden shape and the elf's starting point. */
private fun parseInput(input: String): Pair<Garden, Point> = parse {
lateinit var start: Point
lateinit var area: Area
val walls = input
.lines()
.asReversed()
.also { area = Area(it.first().length, it.size) }
.asSequence()
.flatMapIndexed { y, line -> line.mapIndexed { x, c -> Point(x, y) to c } }
.onEach { (point, element) -> if (element == 'S') start = point }
.filter { it.second == '#' }
.map { it.first }
.toSet()
Garden(area, walls) to start
}
override fun partOne(input: String) = parseInput(input).let { (garden, start) -> garden.explore(start, 64).count() }
override fun partTwo(input: String): Any {
val (garden, start) = parseInput(input)
val steps = 26501365
val tileSize: Int = with(garden.area) {
assume(width == height) { "The garden should be a square." }
assume(width % 2 == 1L) { "The garden should have an odd-size, in order to have true middles." }
assume(start.x == width / 2 && start.y == height / 2) { "The starting point should be in the middle." }
assume(steps.rem(width) == width / 2) { "Walking straight will always end in the center of a garden." }
val clearLines = (0L..start.x)
.asSequence()
.flatMap { i ->
listOf(
// Horizontal
Point(i, start.y),
Point(start.x + i, start.y),
// Vertical
Point(start.x, i),
Point(start.x, start.y + i),
// Rhombus
Point(i, start.y + i),
Point(start.x + i, height - 1 - i),
Point(width - 1 - i, start.y - i),
Point(start.x - i, i),
)
}
.none { it in garden.walls }
assume(clearLines) { "The horizontal and vertical columns, and their 'bounding rhombus' should be empty." }
width.toInt()
}
val gridSize: Int = steps / tileSize - 1
// Different starting points, from the edges of the garden tile.
val startTop = Point(start.x, tileSize - 1L)
val startRight = Point(tileSize - 1L, start.y)
val startBottom = Point(start.x, 0L)
val startLeft = Point(0L, start.y)
val startTopRight = Point(tileSize - 1L, tileSize - 1L)
val startTopLeft = Point(0L, tileSize - 1L)
val startBottomRight = Point(tileSize - 1L, 0L)
val startBottomLeft = Point(0L, 0L)
// Number of locations in tiles fully contained in the grid.
val oddTiles = garden.explore(start, tileSize * 2 + 1).count().toLong()
val evenTiles = garden.explore(start, tileSize * 2).count().toLong()
val fullyContained: Long =
oddTiles * (gridSize / 2 * 2 + 1L).let { it * it } +
evenTiles * (gridSize.inc() / 2 * 2L).let { it * it }
// Number of locations in the small corners of the grid.
val inCorners: Long = listOf(startTop, startRight, startBottom, startLeft)
.sumOf { garden.explore(it, tileSize - 1).count().toLong() }
// Number of locations in the smaller triangles along the grid edges.
val inSmallerTriangleEdges: Long = listOf(startTopRight, startBottomRight, startBottomLeft, startTopLeft)
.sumOf { garden.explore(it, tileSize / 2 - 1).count().toLong() }
.times(gridSize + 1)
// Number of locations in the larger triangles along the grid edges.
val inLargerTriangleEdges: Long = listOf(startTopRight, startBottomRight, startBottomLeft, startTopLeft)
.sumOf { garden.explore(it, tileSize * 3 / 2 - 1).count().toLong() }
.times(gridSize)
return fullyContained + inCorners + inSmallerTriangleEdges + inLargerTriangleEdges
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 6,009 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day08.kt | frango9000 | 573,098,370 | false | {"Kotlin": 73317} | fun main() {
val input = readInput("Day08")
println(Day08.part1(input))
println(Day08.part2(input))
}
class Day08 {
companion object {
fun part1(input: List<String>): Int {
val forest =
input.map { it.split("").filter { c -> c.isNotEmpty() }.map { character -> character.toInt() } }
val visibilityForest = input.map { it.map { false }.toMutableList() }
for (i in forest.indices) {
var currentTop = -1
for (j in forest[i].indices) {
if (forest[i][j] > currentTop) {
currentTop = forest[i][j]
visibilityForest[i][j] = true
}
}
currentTop = -1
for (j in forest[i].indices.reversed()) {
if (forest[i][j] > currentTop) {
currentTop = forest[i][j]
visibilityForest[i][j] = true
}
}
}
for (j in forest.first().indices) {
var currentTop = -1
for (i in forest.indices) {
if (forest[i][j] > currentTop) {
currentTop = forest[i][j]
visibilityForest[i][j] = true
}
}
currentTop = -1
for (i in forest.indices.reversed()) {
if (forest[i][j] > currentTop) {
currentTop = forest[i][j]
visibilityForest[i][j] = true
}
}
}
return visibilityForest.flatten().count { it }
}
fun part2(input: List<String>): Int {
val forest =
input.map { it.split("").filter { c -> c.isNotEmpty() }.map { character -> character.toInt() } }
val forestOfScores = input.map { it.map { 0 }.toMutableList() }
for (i in forest.indices) {
if (i == 0 || i == forest.size - 1) continue
for (j in forest[i].indices) {
if (j == 0 || j == forest[i].size - 1) continue
var leftDistance = 0
for (j2 in (j - 1 downTo 0)) {
leftDistance++
if (forest[i][j2] >= forest[i][j]) {
break
}
}
if (leftDistance == 0) continue
var rightDistance = 0
for (j2 in (j + 1 until forest[i].size)) {
rightDistance++
if (forest[i][j2] >= forest[i][j]) {
break
}
}
if (rightDistance == 0) continue
var topDistance = 0
for (i2 in (i - 1 downTo 0)) {
topDistance++
if (forest[i2][j] >= forest[i][j]) {
break
}
}
if (topDistance == 0) continue
var botDistance = 0
for (i2 in (i + 1 until forest.size)) {
botDistance++
if (forest[i2][j] >= forest[i][j]) {
break
}
}
if (botDistance == 0) continue
forestOfScores[i][j] = leftDistance * rightDistance * topDistance * botDistance
}
}
return forestOfScores.flatten().max()
}
}
}
| 0 | Kotlin | 0 | 0 | 62e91dd429554853564484d93575b607a2d137a3 | 3,744 | advent-of-code-22 | Apache License 2.0 |
src/Day09.kt | mr-cell | 575,589,839 | false | {"Kotlin": 17585} | import java.lang.IllegalArgumentException
import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
fun part1(input: List<String>): Int {
val moves = parseInput(input)
return followPath(moves, 2)
}
fun part2(input: List<String>): Int {
val moves = parseInput(input)
return followPath(moves, 10)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
val testInput2 = readInput("Day09_test_2")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
private fun parseInput(input: List<String>): String =
input.joinToString("") {
val direction = it.substringBefore(" ")
val numberOfMoves = it.substringAfter(" ").toInt()
direction.repeat(numberOfMoves)
}
private fun followPath(headPath: String, knots: Int): Int {
val rope = Array(knots) { Position(0, 0) }
val tailVisits = mutableSetOf(Position(0, 0))
headPath.forEach { direction ->
rope[0] = rope[0].move(direction)
rope.indices.windowed(2, 1) { (head, tail) ->
if (!rope[head].touches(rope[tail])) {
rope[tail] = rope[tail].moveTowards(rope[head])
}
}
tailVisits += rope.last()
}
return tailVisits.size
}
data class Position(val x: Int, val y: Int) {
fun touches(other: Position): Boolean =
(x - other.x).absoluteValue <= 1 && (y - other.y).absoluteValue <= 1
fun moveTowards(other: Position): Position =
Position(
x = (other.x - x).sign + x,
y = (other.y - y).sign + y
)
fun move(direction: Char): Position =
when (direction) {
'U' -> copy(y = y + 1)
'D' -> copy(y = y - 1)
'L' -> copy(x = x - 1)
'R' -> copy(x = x + 1)
else -> throw IllegalArgumentException("Unknown direction: $direction")
}
} | 0 | Kotlin | 0 | 0 | 2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9 | 2,084 | advent-of-code-2022 | Apache License 2.0 |
src/day04/Day04.kt | kerchen | 573,125,453 | false | {"Kotlin": 137233} | package day04
import readInput
class Section(sectionRange: String) {
var startID: Int = 0
var endID: Int = 0
init {
val idRange = sectionRange.split("-")
startID = idRange[0].toInt()
endID = idRange[1].toInt()
}
fun isFullyContainedIn(other: Section): Boolean = startID >= other.startID && endID <= other.endID
fun isOverlappingWith(other: Section): Boolean = startID >= other.startID && startID <= other.endID
}
fun main() {
fun part1(input: List<String>): Int {
var total = 0
for (elfPair in input) {
val sections = elfPair.split(",")
val leftSection = Section(sections[0])
val rightSection = Section(sections[1])
if (leftSection.isFullyContainedIn(rightSection) || rightSection.isFullyContainedIn(leftSection))
total += 1
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
for (elfPair in input) {
val sections = elfPair.split(",")
val leftSection = Section(sections[0])
val rightSection = Section(sections[1])
if (leftSection.isOverlappingWith(rightSection) || rightSection.isOverlappingWith(leftSection))
total += 1
}
return total
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dc15640ff29ec5f9dceb4046adaf860af892c1a9 | 1,525 | AdventOfCode2022 | Apache License 2.0 |
src/Day04.kt | shepard8 | 573,449,602 | false | {"Kotlin": 73637} | fun main() {
fun part1(pairs: List<Pair<IntRange, IntRange>>) = pairs.count { (range1, range2) ->
range1.contains(range2.first) && range1.contains(range2.last) || range2.contains(range1.first) && range2.contains(range1.last)
}
fun part2(pairs: List<Pair<IntRange, IntRange>>) = pairs.count { (range1, range2) ->
range1.contains(range2.first) || range2.contains(range1.first)
}
val input = readInput("Day04")
val pairs = sequence {
input.forEach { line ->
val ints = line.split(",", "-").map { it.toInt() }
yield(Pair(IntRange(ints[0], ints[1]), IntRange(ints[2], ints[3])))
}
}.toList()
println(part1(pairs))
println(part2(pairs))
}
| 0 | Kotlin | 0 | 1 | 81382d722718efcffdda9b76df1a4ea4e1491b3c | 728 | aoc2022-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2021/day7/CrabSubmarine.kt | arnab | 75,525,311 | false | null | package aoc2021.day7
import kotlin.math.abs
object CrabSubmarine {
fun parse(data: String) = data.split(",").map { it.toInt() }
fun findFuelCostForMedian(crabs: List<Int>): Int {
val sortedCrabs = crabs.sorted()
val midIndex = sortedCrabs.size / 2
return (midIndex - 1..midIndex + 1).map { i ->
calculateFuelCostToMoveTo(crabs, sortedCrabs[i])
}.minOf { it }
}
private fun calculateFuelCostToMoveTo(crabs: List<Int>, destination: Int) = crabs.sumOf { abs(it - destination) }
fun findFuelCostWithInflation(crabs: List<Int>): Int {
val memoryOfCost = HashMap<Int, Int>()
val positions = (crabs.min()!!..crabs.max()!!)
return positions.map { position ->
memoryOfCost[position] ?: calculateFuelCostWithInflation(crabs, position).also {
memoryOfCost[position] = it
}
}.minOf { it }
}
private fun calculateFuelCostWithInflation(crabs: List<Int>, crab: Int) = crabs.sumOf {
(1..(abs(it - crab))).sum()
}
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 1,062 | adventofcode | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2023/Day11.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2023
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.math.abs
import kotlin.test.assertEquals
class Day11 : AbstractDay() {
@Test
fun part1Test() {
assertEquals(374, compute1(testInput))
}
@Test
fun part1Puzzle() {
assertEquals(9974721, compute1(puzzleInput))
}
@Test
fun part2Test() {
assertEquals(1030, compute2(testInput, offSet = 10 - 1))
assertEquals(8410, compute2(testInput, offSet = 100 - 1))
}
@Test
fun part2Puzzle() {
assertEquals(702770569197, compute2(puzzleInput, offSet = 1000000 - 1))
}
private fun compute1(input: List<String>): Long {
val galaxyDistances = getGalaxyDistances(input, offSet = 1)
return galaxyDistances.values.sum()
}
private fun compute2(input: List<String>, offSet: Long): Long {
val galaxyDistances = getGalaxyDistances(input, offSet)
return galaxyDistances.values.sum()
}
private fun getGalaxyDistances(input: List<String>, offSet: Long): MutableMap<GalaxyPair, Long> {
var xShift = 0L
var yShift = 0L
val galaxies = mutableListOf<Galaxy>()
input.forEachIndexed { y, s ->
s.forEachIndexed { x, c ->
if (c == '#') galaxies.add(Galaxy(galaxies.size + 1, BigPoint(x + xShift, y + yShift)))
if (input.isColumnBlank(x)) xShift += offSet // empty column, shift to right
}
if (s.isEmptySpace()) yShift += offSet // empty line, shift down
xShift = 0 // new line reset x shift
}
val galaxyDistances = mutableMapOf<GalaxyPair, Long>()
for (galaxy in galaxies) {
val otherGalaxies = galaxies - galaxy
for (otherGalaxy in otherGalaxies) {
if (!galaxyDistances.contains(GalaxyPair(galaxy, otherGalaxy))) {
val dist = galaxy.pos.distanceTo(otherGalaxy.pos)
galaxyDistances[GalaxyPair(galaxy, otherGalaxy)] = dist
}
}
}
return galaxyDistances
}
private fun List<String>.isColumnBlank(x: Int): Boolean {
return this.map { it[x] }.none { it == '#' }
}
private fun String.isEmptySpace(): Boolean {
return this.none { it == '#' }
}
private data class Galaxy(
val num: Int,
val pos: BigPoint,
)
private data class GalaxyPair(
val galaxies: Set<Galaxy>,
) {
constructor(a: Galaxy, b: Galaxy) : this(setOf(a, b))
override fun toString(): String {
return galaxies.joinToString("<->") { it.num.toString() }
}
}
private data class BigPoint(val x: Long, val y: Long)
private fun BigPoint.distanceTo(other: BigPoint): Long {
return abs(other.x - x) + abs(other.y - y)
}
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 2,892 | aoc | Apache License 2.0 |
src/Day20.kt | er453r | 572,440,270 | false | {"Kotlin": 69456} | import kotlin.math.absoluteValue
fun main() {
class Wrapper(val value: Long)
fun mix(originalOrder:List<Wrapper>, mixed:MutableList<Wrapper>){
// println(mixed.map { it.value })
for (entry in originalOrder) {
val entryPositionInMixed = mixed.indexOf(entry)
mixed.remove(entry)
var newEntryPosition = entryPositionInMixed + entry.value
if(newEntryPosition < 0){
val n = (newEntryPosition.absoluteValue / mixed.size) + 1
newEntryPosition += n * mixed.size
}
newEntryPosition %= mixed.size
if(newEntryPosition == 0L)
newEntryPosition = mixed.size.toLong()
// println("Moving ${entry.value} between ${mixed[(newEntryPosition + mixed.size + - 1) % mixed.size].value} and ${mixed[(newEntryPosition) % mixed.size].value}")
mixed.add(newEntryPosition.toInt(), entry)
// println(mixed.map { it.value })
}
}
fun part1(input: List<String>): Long {
val originalOrder = input.map { Wrapper(it.toLong()) }
val mixed = originalOrder.toMutableList()
mix(originalOrder, mixed)
val zeroPosition = mixed.indexOfFirst { it.value == 0L }
return arrayOf(1000, 2000, 3000).map {
mixed[(zeroPosition + it) % mixed.size].value
}.sum()
}
fun part2(input: List<String>): Long {
val originalOrder = input.map { Wrapper(it.toLong() * 811589153) }
val mixed = originalOrder.toMutableList()
repeat(10){ mix(originalOrder, mixed) }
val zeroPosition = mixed.indexOfFirst { it.value == 0L }
return arrayOf(1000, 2000, 3000).map {
mixed[(zeroPosition + it) % mixed.size].value
}.sum()
}
test(
day = 20,
testTarget1 = 3,
testTarget2 = 1623178306,
part1 = ::part1,
part2 = ::part2,
)
}
| 0 | Kotlin | 0 | 0 | 9f98e24485cd7afda383c273ff2479ec4fa9c6dd | 1,955 | aoc2022 | Apache License 2.0 |
codeforces/globalround5/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.globalround5
fun main() {
val n = readInt()
val a = readInts()
val b = a.plus(a).plus(a)
val st = SegmentsTreeSimple(b)
val r = IntArray(b.size)
val ans = IntArray(b.size)
for (i in b.indices.reversed()) {
val v = b[i]
var low = i + 1
var high = b.size + 1
while (low + 1 < high) {
val mid = (low + high) / 2
if (st.getMin(i + 1, mid) * 2 < v) {
high = mid
} else {
low = mid
}
}
r[i] = high - 1
if (i + 1 < b.size) {
r[i] = minOf(r[i], r[i + 1])
}
ans[i] = r[i] - i
if (r[i] == b.size) ans[i] = -1
}
print(ans.take(n).joinToString(" "))
}
class SegmentsTreeSimple(data: List<Int>) {
internal val min: IntArray
internal var size: Int = 1
init {
while (size <= data.size) size *= 2
min = IntArray(2 * size)
System.arraycopy(data.toIntArray(), 0, min, size, data.size)
for (i in size - 1 downTo 1) {
min[i] = minOf(min[2 * i], min[2 * i + 1])
}
}
internal fun getMin(from: Int, to: Int): Int {
var f = from + size
var t = to + size
var res = Integer.MAX_VALUE
while (f < t) {
if (f % 2 == 1) {
res = minOf(res, min[f])
f++
}
if (t % 2 == 1) {
t--
res = minOf(res, min[t])
}
f /= 2
t /= 2
}
return res
}
}
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,427 | competitions | The Unlicense |
src/Day12.kt | MwBoesgaard | 572,857,083 | false | {"Kotlin": 40623} | import java.util.PriorityQueue
import kotlin.math.abs
fun main() {
class ElevationMap(inputMapData: List<String>) {
val height = inputMapData.size
val width = inputMapData[0].length
val map = MutableList(height) { MutableList(width) { "?" } }
val listOfPotentialStartingPoints: MutableList<Pair<Int, Int>> = mutableListOf()
lateinit var startPos: Pair<Int, Int>
lateinit var endPos: Pair<Int, Int>
val priorityByLetter = ('a'..'z')
.toList()
.map { it.toString() }
.zip((1..('a'..'z').toList().size))
.associate { it }
.toMutableMap()
init {
priorityByLetter["S"] = 1
priorityByLetter["E"] = 26
generateFromInput(inputMapData)
}
fun setStartingPos(pos: Pair<Int, Int>) {
this.startPos = pos
}
fun generateFromInput(input: List<String>) {
for ((rowIndex, line) in input.withIndex()) {
for ((colIndex, char) in line.chunked(1).withIndex()) {
if (char == "a") {
listOfPotentialStartingPoints.add(Pair(rowIndex, colIndex))
}
if (char == "S") {
startPos = Pair(rowIndex, colIndex)
}
if (char == "E") {
endPos = Pair(rowIndex, colIndex)
}
map[rowIndex][colIndex] = char
}
}
}
fun print() {
map.forEach { println(it.joinToString("")) }
println("Starting coordinates: $startPos, End coordinates $endPos")
}
fun printPath(path: List<Pair<Int, Int>>) {
val pathSet = path.toSet()
for ((rowIndex, row) in map.withIndex()) {
for ((colIndex, letter) in row.withIndex()) {
val letterToPrint = if (Pair(rowIndex, colIndex) == endPos) {
"E"
} else if (Pair(rowIndex, colIndex) in pathSet) {
"."
} else {
letter
}
print(letterToPrint)
}
print("\n")
}
println()
}
fun searchForExit(): MutableList<Pair<Int, Int>> {
val mapMapNodeComparator: Comparator<MapNode> = compareBy { it.combinedScore }
val openList = PriorityQueue(mapMapNodeComparator)
val closedSet = hashSetOf<Pair<Int, Int>>()
openList.add(MapNode("S", startPos, null))
while (openList.size > 0) {
val highestPriorityNode = openList.poll()
closedSet.add(highestPriorityNode.pos)
val neighbours = highestPriorityNode.getNeighbours()
for (neighbour in neighbours) {
if (neighbour.pos in closedSet) {
continue
}
if (priorityByLetter[neighbour.letter]!! > priorityByLetter[highestPriorityNode.letter]!! + 1) {
continue
}
if (neighbour.letter == "E") {
val path = mutableListOf<Pair<Int, Int>>()
var currentNode = neighbour
while (currentNode.parent != null) {
path.add(currentNode.pos)
currentNode = currentNode.parent!!
}
return path
}
openList.add(neighbour)
}
}
return mutableListOf()
}
inner class MapNode(val letter: String, val pos: Pair<Int, Int>, var parent: MapNode?) {
val distanceFromStartScore: Int = (parent?.distanceFromStartScore ?: 0) + 1
val distanceFromGoalScore: Int = abs(pos.first - endPos.first) + abs(pos.second - endPos.second) //Manhattan
val combinedScore: Int = distanceFromStartScore + distanceFromGoalScore
fun getNeighbours(): List<MapNode> {
val neighbours = mutableListOf<MapNode>()
if (pos.first > 0) { //North
val letter = map[pos.first - 1][pos.second]
val node = MapNode(letter, Pair(pos.first - 1, pos.second), this)
neighbours.add(node)
}
if (pos.first < height - 1) { //South
val letter = map[pos.first + 1][pos.second]
val node = MapNode(letter, Pair(pos.first + 1, pos.second), this)
neighbours.add(node)
}
if (pos.second > 0) { //West
val letter = map[pos.first][pos.second - 1]
val node = MapNode(letter, Pair(pos.first, pos.second - 1), this)
neighbours.add(node)
}
if (pos.second < width - 1) { //East
val letter = map[pos.first][pos.second + 1]
val node = MapNode(letter, Pair(pos.first, pos.second + 1), this)
neighbours.add(node)
}
return neighbours
}
}
}
fun part1(input: List<String>): Int {
val map = ElevationMap(input)
return map.searchForExit().size
}
fun part2(input: List<String>): Int {
val listOfResults = mutableListOf<Int>()
val map = ElevationMap(input)
// Elevation (a -> b) transitions, required to reach the end, can only be found on the far left of the map
// Therefore, only these positions are examined.
for (x in 0 until map.height) {
map.setStartingPos(Pair(x, 0))
val path = map.searchForExit()
listOfResults.add(path.size)
}
return listOfResults.min()
}
printSolutionFromInputLines("Day12", ::part1)
printSolutionFromInputLines("Day12", ::part2)
} | 0 | Kotlin | 0 | 0 | 3bfa51af6e5e2095600bdea74b4b7eba68dc5f83 | 6,150 | advent_of_code_2022 | Apache License 2.0 |
lib/src/main/kotlin/aoc/day15/Day15.kt | Denaun | 636,769,784 | false | null | @file:Suppress("UnstableApiUsage")
package aoc.day15
import com.google.common.collect.ContiguousSet
import com.google.common.collect.DiscreteDomain.longs
import com.google.common.collect.Range
import com.google.common.collect.RangeSet
import com.google.common.collect.TreeRangeSet
import kotlin.math.abs
fun part1(input: String): Int = surelyEmptyPositions(parse(input), 2_000_000L).asRanges()
.sumOf { ContiguousSet.create(it, longs()).size }
fun part2(input: String): Long {
val distressBeacon = findDistressBeacon(parse(input), 4_000_000L)!!
return distressBeacon.x * 4_000_000L + distressBeacon.y
}
fun surelyEmptyPositions(readings: List<Reading>, row: Long): RangeSet<Long> {
val result = scannedRanges(readings, row)
result.removeAll(readings.filter { it.beacon.y == row }.map { Range.singleton(it.beacon.x) })
return result
}
fun findDistressBeacon(readings: List<Reading>, maxCoordinate: Long): Position? {
val (row, possibleXs) = (0L..maxCoordinate).asSequence().map { row ->
val possibleXs = scannedRanges(readings, row).complement()
possibleXs.remove(Range.lessThan(0))
possibleXs.remove(Range.greaterThan(maxCoordinate))
row to possibleXs
}.find { !it.second.isEmpty } ?: return null
return Position(ContiguousSet.create(possibleXs.span(), longs()).single(), row)
}
fun scannedRanges(readings: List<Reading>, row: Long): RangeSet<Long> {
val result = TreeRangeSet.create<Long>()
result.addAll(readings.mapNotNull {
val emptyRadius = it.emptyRadius() - abs(row - it.sensor.y)
if (emptyRadius >= 0) {
Range.closed(it.sensor.x - emptyRadius, it.sensor.x + emptyRadius)
} else {
null
}
})
return result
}
data class Position(val x: Long, val y: Long) {
infix fun manhattanFrom(other: Position): Long = abs(x - other.x) + abs(y - other.y)
}
data class Reading(val sensor: Position, val beacon: Position) {
fun emptyRadius(): Long = sensor manhattanFrom beacon
}
| 0 | Kotlin | 0 | 0 | 560f6e33f8ca46e631879297fadc0bc884ac5620 | 2,027 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day25.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2022
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
import kotlin.math.absoluteValue
import kotlin.math.pow
import kotlin.math.sign
open class Part25A : PartSolution() {
private lateinit var snafu: List<String>
override fun parseInput(text: String) {
snafu = text.trimEnd().split("\n")
}
override fun compute(): String {
var sum = 0L
for (line in snafu) {
val dec = snafuToDecimal(line)
sum += dec
}
return decimalToSnafu(sum)
}
private fun snafuToDecimal(snafu: String): Long {
var dec = 0L
for ((i, char) in snafu.withIndex()) {
val mul = 5.0.pow(snafu.length - i - 1).toLong()
when (char) {
'0' -> continue
'1' -> dec += mul
'2' -> dec += 2 * mul
'-' -> dec -= mul
'=' -> dec -= 2 * mul
}
}
return dec
}
private fun decimalToSnafu(d: Long): String {
var decimal = d
val snafu = mutableListOf<Int>()
var div = decimal
var fac = 0
while (div.absoluteValue >= 5) {
div /= 5
fac += 1
}
while (true) {
div = decimal / 5.0.pow(fac).toLong()
snafu.add(div.toInt())
decimal -= div * 5.0.pow(fac).toLong()
var newFac = fac - 1
if (div.absoluteValue > 2) {
val lastIndex = snafu.size - 1
for (i in lastIndex downTo 0) {
if (snafu[i].absoluteValue > 2) {
decimal += snafu[i] * 5.0.pow(lastIndex - i + fac).toLong()
val sign = snafu[i].sign
snafu.removeLast()
newFac += 1
if (i > 0) {
snafu[i - 1] += sign
decimal -= sign * 5.0.pow(lastIndex - i + 1 + fac).toLong()
} else {
snafu.add(0, sign)
decimal -= sign * 5.0.pow(lastIndex + 1 + fac).toLong()
}
}
}
}
if (decimal == 0L && fac == 0) {
break
}
fac = newFac
}
return digitsToString(snafu)
}
private fun digitsToString(digits: List<Int>): String {
var result = ""
for (digit in digits) {
when (digit) {
0 -> result += "0"
1 -> result += "1"
2 -> result += "2"
-1 -> result += '-'
-2 -> result += "="
}
}
return result
}
override fun getExampleAnswer(): String {
return "2=-1=0"
}
}
fun main() {
Day(2022, 25, Part25A())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 2,947 | advent-of-code-kotlin | MIT License |
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day21.kt | clechasseur | 435,726,930 | false | {"Kotlin": 315943} | package io.github.clechasseur.adventofcode2021
import kotlin.math.max
object Day21 {
private const val player1StartingPos = 8
private const val player2StartingPos = 3
fun part1(): Int = playGame(DeterministicDice())
fun part2(): Long = playQuantumGame()
private interface Die {
fun roll(): Int
}
private class Player(var pos: Int) {
var score: Int = 0
fun move(die: Die): Int {
val moveBy = die.roll() + die.roll() + die.roll()
pos = (pos + moveBy - 1) % 10 + 1
score += pos
return 3
}
}
private fun playGame(die: Die): Int {
val player1 = Player(player1StartingPos)
val player2 = Player(player2StartingPos)
var rolls = 0
while (true) {
rolls += player1.move(die)
if (player1.score >= 1000) {
return rolls * player2.score
}
rolls += player2.move(die)
if (player2.score >= 1000) {
return rolls * player1.score
}
}
}
private class DeterministicDice : Die {
var next: Int = 1
override fun roll(): Int {
val rolled = next++
if (next > 100) {
next = 1
}
return rolled
}
}
private val diracDiceResults = listOf(
1 + 1 + 1, 1 + 1 + 2, 1 + 1 + 3, 1 + 2 + 1, 1 + 2 + 2, 1 + 2 + 3, 1 + 3 + 1, 1 + 3 + 2, 1 + 3 + 3,
2 + 1 + 1, 2 + 1 + 2, 2 + 1 + 3, 2 + 2 + 1, 2 + 2 + 2, 2 + 2 + 3, 2 + 3 + 1, 2 + 3 + 2, 2 + 3 + 3,
3 + 1 + 1, 3 + 1 + 2, 3 + 1 + 3, 3 + 2 + 1, 3 + 2 + 2, 3 + 2 + 3, 3 + 3 + 1, 3 + 3 + 2, 3 + 3 + 3,
)
private data class QuantumPlayer(val pos: Int, val score: Int) {
fun move(by: Int): QuantumPlayer {
val newPos = (pos + by - 1) % 10 + 1
return QuantumPlayer(newPos, score + newPos)
}
}
private data class QuantumGameState(val player1: QuantumPlayer, val player2: QuantumPlayer)
private fun playQuantumGame(): Long {
var states: Map<QuantumGameState, Long> = mapOf(QuantumGameState(
player1 = QuantumPlayer(player1StartingPos, 0),
player2 = QuantumPlayer(player2StartingPos, 0),
) to 1L)
var wins1 = 0L
var wins2 = 0L
while (states.isNotEmpty()) {
val newStates = mutableMapOf<QuantumGameState, Long>()
states.forEach { (state, universes) ->
diracDiceResults.forEach { rolls ->
val newPlayer1 = state.player1.move(rolls)
if (newPlayer1.score >= 21) {
wins1 += universes
} else {
val newState = QuantumGameState(newPlayer1, state.player2)
newStates[newState] = newStates.getOrDefault(newState, 0L) + universes
}
}
}
states = newStates.toMap()
newStates.clear()
states.forEach { (state, universes) ->
diracDiceResults.forEach { rolls ->
val newPlayer2 = state.player2.move(rolls)
if (newPlayer2.score >= 21) {
wins2 += universes
} else {
val newState = QuantumGameState(state.player1, newPlayer2)
newStates[newState] = newStates.getOrDefault(newState, 0L) + universes
}
}
}
states = newStates
}
return max(wins1, wins2)
}
}
| 0 | Kotlin | 0 | 0 | 4b893c001efec7d11a326888a9a98ec03241d331 | 3,639 | adventofcode2021 | MIT License |
src/main/kotlin/com/github/michaelbull/advent/day10/AsteroidMap.kt | michaelbull | 225,205,583 | false | null | package com.github.michaelbull.advent.day10
import com.github.michaelbull.advent.Position
import java.util.ArrayDeque
import java.util.SortedMap
data class AsteroidMap(
val asteroids: List<Position>
) {
fun detectableAsteroids(from: Position): Int {
return asteroids
.filter { it != from }
.map { from tangentTo it }
.distinct()
.size
}
fun vaporize(from: Position) = sequence {
val rays = ArrayDeque(raycast(from).map(List<Position>::iterator))
while (rays.isNotEmpty()) {
val ray = rays.removeFirst()
val vaporized = ray.next()
yield(vaporized)
if (ray.hasNext()) {
rays.addLast(ray)
}
}
}
private infix fun Position.tangentTo(other: Position): Tangent {
val adjacent = other.x - x
val opposite = other.y - y
return Tangent(adjacent, opposite).simplify()
}
private fun raycast(from: Position): List<List<Position>> {
return asteroidsByTangent(from).values.map {
it.sortedBy(from::distanceTo)
}
}
private fun asteroidsByTangent(from: Position): SortedMap<Tangent, List<Position>> {
return asteroids.asSequence()
.filter { it != from }
.groupBy { from tangentTo it }
.toSortedMap(TangentComparator)
}
}
fun String.toAsteroidMap(): AsteroidMap {
val asteroids = mutableListOf<Position>()
val lines = split("\n")
for ((y, line) in lines.withIndex()) {
for ((x, char) in line.withIndex()) {
val position = Position(x, y)
if (char == '#') {
asteroids += position
}
}
}
return AsteroidMap(asteroids)
}
| 0 | Kotlin | 0 | 2 | d271a7c43c863acd411bd1203a93fd10485eade6 | 1,795 | advent-2019 | ISC License |
src/Day15.kt | janbina | 112,736,606 | false | null | package day15
import getInput
import kotlin.coroutines.experimental.buildSequence
import kotlin.test.assertEquals
fun main(args: Array<String>) {
val (genA, genB) = getInput(15).readLines().map { it.split(" ").last().toLong() }
val factorA = 16807
val factorB = 48271
val module = 2147483647
assertEquals(577, part1(genA, genB, factorA, factorB, module))
assertEquals(316, part2(genA, genB, factorA, factorB, module))
}
fun generate(init: Long, factor: Int, module: Int, predicate: (Int) -> Boolean = { true }): Sequence<Int> = buildSequence {
var value = init
while (true) {
value = (value * factor) % module
value.toInt().let {
if (predicate(it)) yield(it)
}
}
}
fun part1(genAInit: Long, genBInit: Long, factorA: Int, factorB: Int, module: Int): Int {
val generatorA = generate(genAInit, factorA, module)
.map { it and 0xFFFF }
val generatorB = generate(genBInit, factorB, module)
.map { it and 0xFFFF }
return generatorA.zip(generatorB).take(40_000_000).count { it.first == it.second }
}
fun part2(genAInit: Long, genBInit: Long, factorA: Int, factorB: Int, module: Int): Int {
val generatorA = generate(genAInit, factorA, module, { it % 4 == 0 })
.map { it and 0xFFFF }
val generatorB = generate(genBInit, factorB, module, { it % 8 == 0 })
.map { it and 0xFFFF }
return generatorA.zip(generatorB).take(5_000_000).count { it.first == it.second }
}
| 0 | Kotlin | 0 | 0 | 71b34484825e1ec3f1b3174325c16fee33a13a65 | 1,507 | advent-of-code-2017 | MIT License |
src/Day19.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | import java.time.Duration
import java.time.Instant
import java.util.*
fun main() {
data class Blueprint(val robotToCosts: Array<IntArray>) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Blueprint) return false
if (!robotToCosts.contentDeepEquals(other.robotToCosts)) return false
return true
}
override fun hashCode(): Int {
return robotToCosts.contentDeepHashCode()
}
}
val allMaterials = arrayOf("ore", "clay", "obsidian", "geode")
fun readBlueprint(s: String): Blueprint {
val parts = s.dropLast(1).split(".")
require(allMaterials.size == parts.size)
val costs = Array(allMaterials.size) { intArrayOf() }
for (i in allMaterials.indices) {
val line = parts[i].split("costs ")[1]
val res = IntArray(allMaterials.size)
for (part in line.split(" and ")) {
val amount = part.split(' ')[0].toInt()
val type = allMaterials.indexOf(part.split(' ')[1])
require(type != -1)
res[type] = amount
}
costs[i] = res
}
return Blueprint(costs)
}
fun part1(input: List<String>): Int {
val blueprints = input.map(::readBlueprint)
fun solve(bIndex: Int, b: Blueprint): Int {
data class State(val robots: IntArray, val materials: IntArray, val robotBuilt: Boolean) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is State) return false
if (!robots.contentEquals(other.robots)) return false
if (!materials.contentEquals(other.materials)) return false
if (robotBuilt != other.robotBuilt) return false
return true
}
override fun hashCode(): Int {
var result = robots.contentHashCode()
result = 31 * result + materials.contentHashCode()
result = 31 * result + robotBuilt.hashCode()
return result
}
}
fun State.couldCreateRobot() = BooleanArray(allMaterials.size) { robot ->
val costs = b.robotToCosts[robot]
for (material in allMaterials.indices) {
if (costs[material] > materials[material] - robots[material]) {
return@BooleanArray false
}
}
true
}
val dp = HashSet<State>()
dp.add(
State(
robots = IntArray(allMaterials.size).also { it[0] = 1 },
materials = IntArray(allMaterials.size),
robotBuilt = false
)
)
repeat(24) {
println("BIndex $bIndex Time $it dpSize ${dp.size}")
val nextDP = HashSet<State>()
for (state in dp) {
val couldCreateRobot = state.couldCreateRobot()
val newMaterials = IntArray(allMaterials.size) { state.materials[it] + state.robots[it] }
for (robotName in allMaterials.indices) {
if (couldCreateRobot[3] && robotName != 3) continue
if (state.robotBuilt || !couldCreateRobot[robotName]) {
var enough = true
val curRobotCosts = b.robotToCosts[robotName]
for (material in allMaterials.indices) {
if (state.materials[material] < curRobotCosts[material]) {
enough = false
break
}
}
if (enough) {
nextDP.add(
State(
robots = IntArray(allMaterials.size) { state.robots[it] }.also { it[robotName]++ },
materials = IntArray(allMaterials.size) { newMaterials[it] - curRobotCosts[it] },
robotBuilt = true
)
)
}
}
}
if (!couldCreateRobot[3]) nextDP.add(State(state.robots, newMaterials, false))
}
dp.clear()
dp += nextDP
}
val result = dp.maxOf { it.materials.last() }
return result
}
var sum = 0
for ((i, b) in blueprints.withIndex()) {
sum += (i + 1) * solve(i, b)
}
return sum
}
fun part2(input: List<String>): Long {
val startTime = Instant.now()
fun String.prependTime() = "(${Duration.between(startTime, Instant.now())}) $this"
val blueprints = input.map(::readBlueprint)
fun solve(bIndex: Int, b: Blueprint): Int {
data class State(val robots: IntArray, val materials: IntArray, val robotBuilt: Boolean) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is State) return false
if (!robots.contentEquals(other.robots)) return false
if (!materials.contentEquals(other.materials)) return false
if (robotBuilt != other.robotBuilt) return false
return true
}
override fun hashCode(): Int {
var result = robots.contentHashCode()
result = 31 * result + materials.contentHashCode()
result = 31 * result + robotBuilt.hashCode()
return result
}
}
fun State.couldCreateRobot() = BooleanArray(allMaterials.size) { robot ->
val costs = b.robotToCosts[robot]
for (material in allMaterials.indices) {
if (costs[material] > materials[material] - robots[material]) {
return@BooleanArray false
}
}
true
}
val dp = HashSet<State>()
dp.add(
State(
robots = IntArray(allMaterials.size).also { it[0] = 1 },
materials = IntArray(allMaterials.size),
robotBuilt = false
)
)
repeat(32) {
println("BIndex $bIndex Time $it dpSize ${dp.size}".prependTime())
val nextDP = HashSet<State>()
for (state in dp) {
val couldCreateRobot = state.couldCreateRobot()
val newMaterials = IntArray(allMaterials.size) { state.materials[it] + state.robots[it] }
for (robotName in allMaterials.indices) {
if (couldCreateRobot[3] && robotName != 3) continue
if (state.robotBuilt || !couldCreateRobot[robotName]) {
var enough = true
val curRobotCosts = b.robotToCosts[robotName]
for (material in allMaterials.indices) {
if (state.materials[material] < curRobotCosts[material]) {
enough = false
break
}
}
if (enough) {
nextDP.add(
State(
robots = IntArray(allMaterials.size) { state.robots[it] }.also { it[robotName]++ },
materials = IntArray(allMaterials.size) { newMaterials[it] - curRobotCosts[it] },
robotBuilt = true
)
)
}
}
}
if (!couldCreateRobot[3]) nextDP.add(State(state.robots, newMaterials, false))
}
dp.clear()
dp += nextDP
.sortedByDescending { it.robots[3] }
.take(1_000_000)
}
val result = dp.maxOf { it.materials.last() }
println("BIndex $bIndex result $result".prependTime())
return result
}
var sum = 1L
for ((i, b) in blueprints.take(3).withIndex()) {
sum *= solve(i, b)
}
return sum
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 19)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 9,417 | advent-of-code-2022 | Apache License 2.0 |
code/data_structures/DisjointMinTable.kt | hakiobo | 397,069,173 | false | null | private class DisjointMinTable(input: IntArray) {
val n = ((input.size shl 1) - 1).takeHighestOneBit()
val levels = n.countTrailingZeroBits()
val nums = IntArray(n) { idx -> if (idx < input.size) input[idx] else 0 }
val table = Array(levels) { IntArray(n) }
init {
for (level in 0 until levels) {
for (block in 0 until (1 shl level)) {
val start = block shl (levels - level)
val end = (block + 1) shl (levels - level)
val mid = (start + end) shr 1
table[level][mid] = nums[mid]
for (x in mid + 1 until end) {
table[level][x] = min(table[level][x - 1], nums[x])
}
table[level][mid - 1] = nums[mid - 1]
for (x in mid - 2 downTo start) {
table[level][x] = min(table[level][x + 1], nums[x])
}
}
}
}
fun getMinRange(start: Int, end: Int): Int {
if (end < start) return getMinRange(end, start)
if (start == end) return nums[start]
val level = levels - 1 - (start xor end).takeHighestOneBit().countTrailingZeroBits()
return min(table[level][start], table[level][end])
}
}
| 0 | Kotlin | 1 | 2 | f862cc5e7fb6a81715d6ea8ccf7fb08833a58173 | 1,290 | Kotlinaughts | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day289/day289.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day289
// day289.kt
// By <NAME>, 2020.
// We can do this two ways:
// The first way is the more complicated minimax way, which entails calculating all moves and determining if the
// winning move is in the moves. If it is, it is possible for the first player to win Misere Nim.
fun nimMiniMax(heapList: List<Int>): Boolean {
if (heapList.all { it == 0 })
return false
require(heapList.all { it >= 0 })
// Memoize results.
val results: MutableMap<List<Int>, Int> = mutableMapOf()
fun getMoves(heaps: List<Int>): List<List<Int>> =
heaps.withIndex().flatMap { (heapIdx, heapHeight) ->
(1..heapHeight).map { remove -> heaps.withIndex().map { (idx2, h) -> if (heapIdx == idx2) h - remove else h } } }
fun aux(heaps: List<Int> = heapList): Int {
results[heaps]?.let { return it }
if (heaps.all { it == 0 })
return 1
val moves = getMoves(heaps)
val result = moves.map { 1 - aux(it) }.max() ?: 0
results[heaps] = result
return result
}
return aux() == 1
}
// The second method is to use the "nim-sum" method, which is taking the xor of the heaps.
// The goal is to make moves to put the num-sum back to zero, which will put the opponent
// in the losing position.
fun nimSum(heapList: List<Int>): Boolean {
if (heapList.all { it == 0 })
return false
require(heapList.all { it >= 0 })
// Special case: odd number of heaps of size 1. Players alternate taking an entire heap, and the first player
// is forced to take the last heap.
if (heapList.size % 2 == 1 && heapList.all { it == 1 })
return false
return heapList.fold(0){acc, heap -> acc.xor(heap)} != 0
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 1,750 | daily-coding-problem | MIT License |
src/main/kotlin/days/Day5.kt | sicruse | 434,002,213 | false | {"Kotlin": 29921} | package days
class Day5 : Day(5) {
private val vents: List<Line> by lazy { inputList.map { Line(it) } }
data class Point(val x: Int, val y: Int) {
constructor(point: Point) : this(x = point.x, y = point.y)
constructor(text: String) : this(fromText(text))
companion object {
private fun fromText(text: String): Point {
val (xText, yText) = text.split(",")
return Point(xText.toInt(), yText.toInt())
}
}
}
data class Line(val start: Point, val end: Point) {
constructor(line: Line) : this(start = line.start, end = line.end)
constructor(text: String) : this(fromText(text))
val xRange = if (start.x <= end.x) (start.x .. end.x) else (start.x downTo end.x)
val yRange = if (start.y <= end.y) (start.y .. end.y) else (start.y downTo end.y)
val xyRange = xRange.zip(yRange)
enum class Orientation {horizontal, vertical, diagonal}
val orientation by lazy {
when {
start.y == end.y -> Orientation.horizontal
start.x == end.x -> Orientation.vertical
else -> Orientation.diagonal
}
}
val points: Sequence<Point> = sequence {
when (orientation) {
Orientation.horizontal -> for (x in xRange) { yield( Point(x,start.y) ) }
Orientation.vertical -> for (y in yRange) { yield( Point(start.x,y) ) }
Orientation.diagonal -> for ((x,y) in xyRange) { yield( Point(x,y) ) }
}
}
companion object {
private fun fromText(text: String): Line {
val (startText, endText) = text.split(" -> ")
return Line(Point(startText), Point(endText))
}
}
}
class SeaFloor(vents: List<Line>) {
private val points by lazy { vents.flatMap { it.points } }
val danger by lazy { points.groupingBy { it }.eachCount().filter { it.value > 1 } }
}
override fun partOne(): Any {
val seafloor = SeaFloor( vents.filter { it.orientation != Line.Orientation.diagonal } )
return seafloor.danger.count()
}
override fun partTwo(): Any {
val seafloor = SeaFloor( vents )
return seafloor.danger.count()
}
}
| 0 | Kotlin | 0 | 0 | 172babe6ee67a86a7893f8c9c381c5ce8e61908e | 2,335 | aoc-kotlin-2021 | Creative Commons Zero v1.0 Universal |
solutions/src/solutions/y19/day 10.kt | Kroppeb | 225,582,260 | false | null | @file:Suppress("PackageDirectoryMismatch")
package solutions.solutions.y19.d10
import helpers.*
import kotlin.math.*
private fun ggd(a:Int, b:Int):Int = if(a == 0) b else ggd(b % a, a)
private fun part1(data: List<List<Boolean>>) {
(data.indices).map { x ->
(data[x].withIndex().filter { it.value }).map { (y,_) ->
val pp = data.mapIndexed { x2, l ->
l.withIndex().filter { it.value && (x != x2 || y != it.index) }.count { (y2, _) ->
val dx = x2 - x
val dy = y2 - y
val g = ggd(abs(dx), abs(dy))
val sx = dx / g
val sy = dy / g
val q = (1 until g).all {
!data[x + sx * it][y + sy * it]
}
q
}
}.sum() to y
pp
}.maxByOrNull{it.first}!! to x
}.maxByOrNull{it.first.first}!!.let{println("${it.second}, ${it.first.second}: ${it.first.first}")}
}
private fun fix(i:Double) = if(i < 0) i +100 else i
private fun part2(data: List<List<Boolean>>) {
val x = 22
val y = 17
data.mapIndexed { x2, l ->
l.withIndex().filter { it.value && (x2 != x || it.index != y) }.map { (y2, _) ->
val dx = x2 - x
val dy = y2 - y
val g = ggd(abs(dx), abs(dy))
val sx = dx / g
val sy = dy / g
val q = (1..g).count {
data[x + sx * it][y + sy * it]
}
(fix(atan2(sy.toDouble(), -sx.toDouble())) to q) to (x2 to y2)
}
}.flatten().sortedBy{it.first.first}.sortedBy { it.first.second }[199].let{println(it)}
}
fun main() {
val data: List<List<Boolean>> = getLines(2019_10).map{it.map{it!='.'}}
part1(data)
part2(data)
} | 0 | Kotlin | 0 | 1 | 744b02b4acd5c6799654be998a98c9baeaa25a79 | 1,500 | AdventOfCodeSolutions | MIT License |
src/com/zypus/genetic/Selections.kt | zypus | 213,665,750 | false | null | package com.zypus.SLIP.algorithms.genetic
import java.util.*
/**
* TODO Add description
*
* @author fabian <<EMAIL>>
*
* @created 03/03/16
*/
object Selections {
inline fun <G : Any, P : Any, B : Any, BC : Any> elitist(population: List<Entity<G, P, B, BC>>, count: Int, crossinline fitness: (Entity<G, P, B, BC>) -> Double): List<Entity<G, P, B, BC>> {
val sortedByFitness = population.sortedByDescending { fitness(it) }
return sortedByFitness.take(count)
}
inline fun <G : Any, P : Any, B : Any, BC : Any> rouletteWheel(population: List<Entity<G, P, B, BC>>, count: Int, crossinline fitness: (Entity<G, P, B, BC>) -> Double): List<Entity<G, P, B, BC>> {
val sortedByFitness = population.sortedByDescending { fitness(it) }
val min = fitness(sortedByFitness.last())
val fitnessSum = sortedByFitness.sumByDouble { fitness(it) } - population.size*min
var selected: List<Entity<G, P, B, BC>> = arrayListOf()
for (i in 1..count) {
var current = 1.0
val next = Math.random()
val lucky = sortedByFitness.first {
p ->
current -= (fitness(p)-min) / fitnessSum
next > current
}
selected += lucky
}
return selected
}
fun linear(populationSize: Int, bias: Double, random: Random): Int {
return (populationSize * (bias - Math.sqrt(bias * bias - 4.0 * (bias - 1) * random.nextDouble())) / 2.0 / (bias - 1)).toInt()
}
}
fun <T> Collection<T>.linearSelection(bias: Double, random: Random): T {
return elementAt(Selections.linear(size, bias,random))
}
| 0 | Kotlin | 0 | 0 | 418ee8837752143194fd769e86fac85e15136929 | 1,528 | SLIP | MIT License |
src/aoc23/Day11.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc23.day11
import kotlin.math.abs
import lib.Collections.cumulativeSum1
import lib.Grid
import lib.Point
import lib.Solution
data class Image(val galaxies: List<Point>, val maxBound: Point) {
fun expandRows(count: Int): Image {
val rowSizes = (0..maxBound.y).map { if (isEmptyRow(it)) count else 1 }
val lastRow = rowSizes.last()
val newRows = rowSizes.cumulativeSum1().dropLast(1)
val newGalaxies = galaxies.map { it.copy(y = newRows[it.y]) }
return Image(newGalaxies, maxBound.copy(y = lastRow))
}
fun expandCols(count: Int): Image = transpose().expandRows(count).transpose()
private fun isEmptyRow(row: Int) = galaxies.none { galaxy -> galaxy.y == row }
private fun transpose() = Image(galaxies.map { it.transpose() }, maxBound.transpose())
private fun Point.transpose() = Point(y, x)
companion object {
fun parse(input: String): Image {
val grid = Grid.parse(input)
val galaxies = grid.indicesOf('#')
val maxBound = Point(galaxies.maxOf { it.x }, galaxies.maxOf { it.y })
return Image(galaxies, maxBound)
}
}
}
typealias Input = Image
typealias Output = Long
private val solution = object : Solution<Input, Output>(2023, "Day11") {
override fun parse(input: String): Input = Image.parse(input)
override fun format(output: Output): String = "$output"
override fun solve(part: Part, input: Input): Output =
with(expand(part, input)) {
galaxies.sumOf { g1 ->
galaxies.sumOf { g2 ->
if (g1 < g2) g1.manhattanDistance(g2).toLong() else 0L
}
}
}
private fun expand(part: Part, input: Input): Input =
EXPANSION_FACTOR[part]!!.let { factor ->
input.expandRows(factor).expandCols(factor)
}
private fun distance(p1: Point, p2: Point): Long =
(abs(p1.x - p2.x) + abs(p1.y - p2.y)).toLong()
private val EXPANSION_FACTOR = mapOf(
Part.PART1 to 2,
Part.PART2 to 1000000
)
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 2,015 | aoc-kotlin | Apache License 2.0 |
src/main/day22/day22.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day22
import Point
import day22.Direction.DOWN
import day22.Direction.LEFT
import day22.Direction.RIGHT
import day22.Direction.UP
import readInput
typealias Board = Map<Point, Char>
const val WALL = '#'
const val OPEN = '.'
fun main() {
val input = readInput("main/day22/Day22")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val board = input.parseBoard()
val directions = input.readDirections()
var currentDirection = RIGHT
var position = board.filter { it.key.y == 1 }.minBy { it.key.x }.key
var index = 0
while (index < directions.length) {
var steps = ""
while (index < directions.length && directions[index].isDigit()) {
steps += directions[index]
index++
}
val numSteps = steps.toInt()
repeat(numSteps) {
position = board.nextTileFrom(position, currentDirection)
}
if (index < directions.length) {
currentDirection = if (directions[index] == 'L') currentDirection.left() else currentDirection.right()
index++
}
}
return position.y * 1000 + position.x * 4 + currentDirection.facing
}
fun part2(input: List<String>): Int {
val board = input.parseBoard()
val directions = input.readDirections()
var currentDirection = RIGHT
var position = board.filter { it.key.y == 1 }.minBy { it.key.x }.key
var index = 0
while (index < directions.length) {
var steps = ""
while (index < directions.length && directions[index].isDigit()) {
steps += directions[index]
index++
}
val numSteps = steps.toInt()
repeat(numSteps) {
val (pos, dir) = board.nextTileOnCubeFrom(position, currentDirection)
position = pos
currentDirection = dir
}
if (index < directions.length) {
currentDirection = if (directions[index] == 'L') currentDirection.left() else currentDirection.right()
index++
}
}
return position.y * 1000 + position.x * 4 + currentDirection.facing
}
fun List<String>.parseBoard(): Board {
val board = mutableMapOf<Point, Char>()
this.takeWhile { it.isNotBlank() }.mapIndexed { y, line ->
line.mapIndexed { x, c ->
if (c == OPEN || c == WALL) board[Point(x + 1, y + 1)] = c
}
}
return board
}
fun List<String>.readDirections() = this.dropLastWhile { it.isBlank() }.last()
fun Board.nextTileFrom(p: Point, direction: Direction): Point = when (direction) {
UP -> {
var next = Point(p.x, p.y - 1)
if (this[next] == WALL) next = p
if (this[next] == null) next = keys.filter { it.x == p.x }.maxBy { it.y }
if (this[next] == WALL) next = p
next
}
DOWN -> {
var next = Point(p.x, p.y + 1)
if (this[next] == WALL) next = p
if (this[next] == null) next = keys.filter { it.x == p.x }.minBy { it.y }
if (this[next] == WALL) next = p
next
}
RIGHT -> {
var next = Point(p.x + 1, p.y)
if (this[next] == WALL) next = p
if (this[next] == null) next = keys.filter { it.y == p.y }.minBy { it.x }
if (this[next] == WALL) next = p
next
}
LEFT -> {
var next = Point(p.x - 1, p.y)
if (this[next] == WALL) next = p
if (this[next] == null) next = keys.filter { it.y == p.y }.maxBy { it.x }
if (this[next] == WALL) next = p
next
}
}
fun Board.nextTileOnCubeFrom(p: Point, direction: Direction): Pair<Point, Direction> {
return when (direction) {
UP -> nextPositionAndDirection(Point(p.x, p.y - 1), p, direction)
DOWN -> nextPositionAndDirection(Point(p.x, p.y + 1), p, direction)
RIGHT -> nextPositionAndDirection(Point(p.x + 1, p.y), p, direction)
LEFT -> nextPositionAndDirection(Point(p.x - 1, p.y), p, direction)
}
}
private fun Board.nextPositionAndDirection(next: Point, p: Point, direction: Direction): Pair<Point, Direction> {
var next1 = next
var newDirection = direction
if (this[next1] == WALL) next1 = p
if (this[next1] == null) {
val (pos, dir) = gotoNextSide(p, direction)
next1 = pos
newDirection = dir
}
if (this[next1] == WALL) {
next1 = p
newDirection = direction
}
return next1 to newDirection
}
private fun sideOf(pos: Point): Char {
if (pos.x in 51..100 && pos.y in 1..50) return 'A'
if (pos.x in 101..150 && pos.y in 1..50) return 'B'
if (pos.x in 51..100 && pos.y in 51..100) return 'C'
if (pos.x in 51..100 && pos.y in 101..150) return 'D'
if (pos.x in 1..50 && pos.y in 101..150) return 'E'
if (pos.x in 1..50 && pos.y in 151..200) return 'F'
error("Side does not exist for $pos")
}
fun gotoNextSide(position: Point, direction: Direction): Pair<Point, Direction> {
var nextDir = direction
val side = sideOf(position)
var nextPos = position
val sideLength = 50
if (side == 'A' && direction == UP) {
nextDir = RIGHT
nextPos = Point(1, 3 * sideLength + position.x - sideLength) // nextSide = F
} else if (side == 'A' && direction == LEFT) {
nextDir = RIGHT
nextPos = Point(1, 2 * sideLength + (sideLength - position.y)) // nextSide = E
} else if (side == 'B' && direction == UP) {
nextDir = UP
nextPos = Point(position.x - 2 * sideLength, 201) // nextSide = F
} else if (side == 'B' && direction == RIGHT) {
nextDir = LEFT
nextPos = Point(101, (sideLength - position.y) + 2 * sideLength) // nextSide = D
} else if (side == 'B' && direction == DOWN) {
nextDir = LEFT
nextPos = Point(101, sideLength + (position.x - 2 * sideLength)) // nextSide = C
} else if (side == 'C' && direction == RIGHT) {
nextDir = UP
nextPos = Point((position.y - sideLength) + 2 * sideLength, sideLength) // nextSide = B
} else if (side == 'C' && direction == LEFT) {
nextDir = DOWN
nextPos = Point(position.y - sideLength, 101) // nextSide = E
} else if (side == 'E' && direction == LEFT) {
nextDir = RIGHT
nextPos = Point(51, sideLength - (position.y - 2 * sideLength)) // nextSide = 'A'
} else if (side == 'E' && direction == UP) {
nextDir = RIGHT
nextPos = Point(51, sideLength + position.x) // nextSide = C
} else if (side == 'D' && direction == DOWN) {
nextDir = LEFT
nextPos = Point(101, 3 * sideLength + (position.x - sideLength)) // nextSide = F
} else if (side == 'D' && direction == RIGHT) {
nextDir = LEFT
nextPos = Point(151, sideLength - (position.y - sideLength * 2)) // nextSide = B
} else if (side == 'F' && direction == RIGHT) {
nextDir = UP
nextPos = Point((position.y - 3 * sideLength) + sideLength, 151) // nextSide = D
} else if (side == 'F' && direction == LEFT) {
nextDir = DOWN
nextPos = Point(sideLength + (position.y - 3 * sideLength), 1) // nextSide = 'A'
} else if (side == 'F' && direction == DOWN) {
nextDir = DOWN
nextPos = Point(position.x + 2 * sideLength, 1) // nextSide = B
}
return nextPos to nextDir
}
enum class Direction(val facing: Int) {
UP(3), DOWN(1), RIGHT(0), LEFT(2);
fun right() = when (this) {
UP -> RIGHT
DOWN -> LEFT
RIGHT -> DOWN
LEFT -> UP
}
fun left() = when (this) {
UP -> LEFT
DOWN -> RIGHT
RIGHT -> UP
LEFT -> DOWN
}
}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 7,626 | aoc-2022 | Apache License 2.0 |
math/RomanToInteger/kotlin/Solution.kt | YaroslavHavrylovych | 78,222,218 | false | {"Java": 284373, "Kotlin": 35978, "Shell": 2994} | /**
* Roman numerals are represented by seven different symbols:
* I, V, X, L, C, D and M.
* Symbol Value
* I 1
* V 5
* X 10
* L 50
* C 100
* D 500
* M 1000
* For example, 2 is written as II in Roman numeral, just two one's
* added together. 12 is written as XII, which is simply X + II.
* The number 27 is written as XXVII, which is XX + V + II.
* Roman numerals are usually written largest to smallest from left to right.
* However, the numeral for four is not IIII. Instead,
* the number four is written as IV. Because the one is before
* the five we subtract it making four.
* The same principle applies to the number nine, which is written as IX.
* There are six instances where subtraction is used:
* I can be placed before V (5) and X (10) to make 4 and 9.
* X can be placed before L (50) and C (100) to make 40 and 90.
* C can be placed before D (500) and M (1000) to make 400 and 900.
* Given a roman numeral, convert it to an integer.
* <br/>
* https://leetcode.com/problems/roman-to-integer/
*/
class Solution {
val sing = hashMapOf(
Pair('I', 1), Pair('V', 5), Pair('X', 10), Pair('L', 50),
Pair('C', 100), Pair('D', 500), Pair('M', 1000)
)
fun romanToInt(s: String): Int {
var i = 0
var res = 0
while(i < s.length) {
val ch = s[i]
if(ch == 'I' && i < s.length - 1 && s[i+1] == 'V') {
i += 1
res += 4
} else if(ch == 'I' && i < s.length - 1 && s[i+1] == 'X') {
i += 1
res += 9
} else if(ch == 'X' && i < s.length - 1 && s[i+1] == 'L') {
i += 1
res += 40
} else if(ch == 'X' && i < s.length - 1 && s[i+1] == 'C') {
i += 1
res += 90
} else if(ch == 'C' && i < s.length - 1 && s[i+1] == 'D') {
i += 1
res += 400
} else if(ch == 'C' && i < s.length - 1 && s[i+1] == 'M') {
i += 1
res += 900
}
else {
res += sing[ch]!!
}
i += 1
}
return res
}
}
fun main() {
println("Roman to Integer: test is not implemented")
}
| 0 | Java | 0 | 2 | cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd | 2,413 | codility | MIT License |
src/main/kotlin/dev/tasso/adventofcode/_2021/day04/Day04.kt | AndrewTasso | 433,656,563 | false | {"Kotlin": 75030} | package dev.tasso.adventofcode._2021.day04
import dev.tasso.adventofcode.Solution
class Day04 : Solution<Int> {
override fun part1(input: List<String>): Int {
val calledNumbers = input[0].split(",")
val cards = input.asSequence()
.drop(2)
.filterNot { it == "" }
.map{it.trim().split(Regex("""\s+"""))}
.chunked(5)
.map{ BingoCard(it)}
.toList()
var winningCard: BingoCard? = null
for(number in calledNumbers) {
for(card in cards) {
card.numberCalled(number)
if(card.hasBingo()) {
winningCard = card
break
}
}
if(winningCard != null) {
break
}
}
return winningCard!!.getUnmarkedNumbers().map{ it.toInt() }.sum() * winningCard.lastCalledNumber.toInt()
}
override fun part2(input: List<String>): Int {
val calledNumbers = input[0].split(",")
val cards = input.asSequence()
.drop(2)
.filterNot { it == "" }
.map{it.trim().split(Regex("""\s+"""))}
.chunked(5)
.map{ BingoCard(it)}
.toList()
var lastWinningCard: BingoCard? = null
for(number in calledNumbers) {
cards.filter { !it.hasBingo() }.forEach { it.numberCalled(number) }
val nonWinningCards = cards.filter { !it.hasBingo() }
if(nonWinningCards.size == 1) {
lastWinningCard = nonWinningCards[0]
}
if(nonWinningCards.isEmpty()) {
break
}
}
return lastWinningCard!!.getUnmarkedNumbers().map{ it.toInt() }.sum() * lastWinningCard.lastCalledNumber.toInt()
}
}
| 0 | Kotlin | 0 | 0 | daee918ba3df94dc2a3d6dd55a69366363b4d46c | 1,840 | advent-of-code | MIT License |
src/main/kotlin/g1601_1700/s1671_minimum_number_of_removals_to_make_mountain_array/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1601_1700.s1671_minimum_number_of_removals_to_make_mountain_array
// #Hard #Array #Dynamic_Programming #Greedy #Binary_Search
// #2023_06_15_Time_264_ms_(100.00%)_Space_38.4_MB_(100.00%)
class Solution {
fun minimumMountainRemovals(nums: IntArray): Int {
val n = nums.size
// lbs -> longest bitomic subsequence
var lbs = 0
val dp = IntArray(n)
// dp[i] -> lis end at index i, dp2[i] -> lds end at index i
val dp2 = IntArray(n)
var lis: MutableList<Int> = ArrayList()
// calculate longest increasing subsequence
for (i in 0 until n - 1) {
if (lis.isEmpty() || lis[lis.size - 1] < nums[i]) {
lis.add(nums[i])
} else {
val idx = lis.binarySearch(nums[i])
if (idx < 0) {
lis[-idx - 1] = nums[i]
}
}
dp[i] = lis.size
}
lis = ArrayList()
// calculate longest decreasing subsequence
for (i in n - 1 downTo 1) {
if (lis.isEmpty() || lis[lis.size - 1] < nums[i]) {
lis.add(nums[i])
} else {
val idx = lis.binarySearch(nums[i])
if (idx < 0) {
lis[-idx - 1] = nums[i]
}
}
dp2[i] = lis.size
if (dp[i] > 1 && dp2[i] > 1) {
lbs = Math.max(lbs, dp[i] + dp2[i] - 1)
}
}
return n - lbs
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,516 | LeetCode-in-Kotlin | MIT License |
src/Day16.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | import kotlin.system.measureTimeMillis
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
.parseCave()
val part1TestInputResult = part1(testInput)
println("Part 1 (test input): $part1TestInputResult")
check(part1TestInputResult == 1651)
val input = readInput("Day16")
.parseCave()
val part1Result = part1(input)
println("Part 1: $part1Result")
check(part1Result == 1728)
val part2testInputResult = part2(testInput)
println("Part 2 (test input): $part2testInputResult")
check(part2testInputResult == 1707)
var part2Result: Int
val timeInMillis = measureTimeMillis {
part2Result = part2(input)
}
println("Part 2: $part2Result, time: ${timeInMillis / 1000.0}")
check(part2Result == 2304)
}
typealias ValveId = String
private data class Valve(
val rate: Int,
val id: ValveId,
val pipes: MutableList<ValveId>,
var isOpen: Boolean = false
)
private class Cave(
valves: List<Valve>
) {
val valves: Map<ValveId, Valve> = valves.associateBy(Valve::id)
fun getRateOf(openValves: Set<ValveId>): Int {
return openValves.sumOf { valves[it]!!.rate }
}
}
private fun part1(cave: Cave): Int {
return cave.getMaxPressure(30)
}
private fun part2(input: Cave): Int {
return input.getMaxPressurePart2(26)
}
private fun Cave.getMaxPressure(steps: Int): Int {
data class DequeItem(
val id: ValveId,
val minute: Int,
val openedValves: Set<ValveId>,
val maxRate: Int
) {
val isOpened: Boolean = id in openedValves
}
// Position, minute --> opened valves, max rate,
val cache: MutableMap<Pair<ValveId, Int>, DequeItem> = mutableMapOf()
val queue: ArrayDeque<DequeItem> = ArrayDeque()
val item2 = DequeItem(
"AA", 0, emptySet(), 0
)
cache["AA" to 0] = item2
queue.addLast(item2)
while (!queue.isEmpty()) {
val item = queue.removeLast()
if (item.minute > steps) continue
val currentRate = item.maxRate
if (!item.isOpened) {
val newOpenValves = item.openedValves + item.id
val newItem = DequeItem(
item.id,
item.minute + 1,
newOpenValves,
currentRate + getRateOf(newOpenValves)
)
if (!cache.containsKey(newItem.id to newItem.minute)
|| cache[newItem.id to newItem.minute]!!.maxRate < newItem.maxRate
) {
cache[newItem.id to newItem.minute] = newItem
queue.addLast(newItem)
}
}
this.valves[item.id]!!.pipes.map { p: String ->
DequeItem(
p,
item.minute + 1,
item.openedValves,
currentRate + getRateOf(item.openedValves)
)
}.forEach { newItem ->
if (!cache.containsKey(newItem.id to newItem.minute)
|| cache[newItem.id to newItem.minute]!!.maxRate < newItem.maxRate
) {
cache[newItem.id to newItem.minute] = newItem
queue.addLast(newItem)
}
}
}
return cache.maxOf { e ->
if (e.key.second == steps - 1) e.value.maxRate else 0
}
}
private fun Cave.getMaxPressurePart2(steps: Int): Int {
data class Position(val user: ValveId, val elephant: ValveId)
data class DequeItem(
val position: Position,
val minute: Int,
val openValves: Set<String>,
val maxRate: Int
)
// Position, Minute --> opened valves, max rate
val cache: MutableMap<Pair<Position, Int>, DequeItem> = mutableMapOf()
val queue: ArrayDeque<DequeItem> = ArrayDeque()
val startPosition = Position("AA", "AA")
val startItem = DequeItem(
startPosition, 0, emptySet(), 0
)
cache[startPosition to 0] = startItem
queue.addLast(startItem)
var maxRate = 0
fun addToCacheAndQueueIfRequired(newItem: DequeItem) {
if (newItem.minute >= steps) return
val positionNormalized = if (newItem.position.elephant < newItem.position.user) {
Position(newItem.position.elephant, newItem.position.user)
} else {
newItem.position
}
val newRate = newItem.maxRate
if (!cache.containsKey(positionNormalized to newItem.minute)
|| cache[positionNormalized to newItem.minute]!!.maxRate < newRate
) {
cache[positionNormalized to newItem.minute] = newItem
queue.addLast(newItem)
maxRate = maxOf(maxRate, newRate)
}
}
while (!queue.isEmpty()) {
val item = queue.removeLast()
if (item.minute > steps) continue
val currentRate = item.maxRate
if (item.position.user !in item.openValves) {
val openValvesUser = item.openValves + item.position.user
// Elephant move
if (item.position.elephant !in openValvesUser) {
val openValvesUserElephant = openValvesUser + item.position.elephant
val newItem = DequeItem(
item.position,
item.minute + 1,
openValvesUserElephant,
currentRate + getRateOf(openValvesUserElephant)
)
addToCacheAndQueueIfRequired(newItem)
}
this.valves[item.position.elephant]!!.pipes.map { p: String ->
DequeItem(
position = item.position.copy(elephant = p),
minute = item.minute + 1,
openValves = openValvesUser,
maxRate = currentRate + getRateOf(openValvesUser)
)
}.forEach { newItem ->
addToCacheAndQueueIfRequired(newItem)
}
}
this.valves[item.position.user]!!.pipes.forEach { p: String ->
if (item.position.elephant !in item.openValves
&& item.position.elephant != item.position.user
) {
val newOpenItems = item.openValves + item.position.elephant
DequeItem(
position = item.position.copy(user = p),
minute = item.minute + 1,
openValves = newOpenItems,
maxRate = currentRate + getRateOf(newOpenItems)
).let { addToCacheAndQueueIfRequired(it) }
}
this.valves[item.position.elephant]!!.pipes.map { ep: String ->
DequeItem(
position = Position(p, ep),
minute = item.minute + 1,
openValves = item.openValves,
maxRate = currentRate + getRateOf(item.openValves)
)
}.forEach { addToCacheAndQueueIfRequired(it) }
}
}
return maxRate
}
private val valveRegex = Regex("""Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? (.+)""")
private fun List<String>.parseCave(): Cave {
return Cave(this.map {
val (id, rate, pipes) = valveRegex.matchEntire(it)
?.groupValues
?.drop(1)
?: error("Can not parse valve `$it")
Valve(
id = id,
rate = rate.toInt(),
pipes = pipes.split(", ").toMutableList()
)
})
}
| 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 7,452 | aoc22-kotlin | Apache License 2.0 |
src/Day03.kt | jdappel | 575,879,747 | false | {"Kotlin": 10062} |
val lowercase = 'a'..'z'
val uppercase = 'A'..'Z'
fun main() {
fun logic(input: List<String>): Int {
return input.fold(0) { acc, line ->
val (first, second) = line.take(line.length.div(2)) to line.substring(line.length.div(2))
acc + first.toCharArray().intersect(second.toCharArray().toSet()).sumOf {
if (it in lowercase) {
lowercase.indexOf(it) + 1
} else if (it in uppercase) {
uppercase.indexOf(it) + 27
} else {
0
}
}
}
}
fun logic2(input: List<String>): Int {
return input.chunked(3).fold(0) { acc, lines ->
val (first, second, third) = lines
acc + first.toCharArray().intersect(second.toCharArray().toSet().intersect(third.toCharArray().toSet())).sumOf {
if (it in lowercase) {
lowercase.indexOf(it) + 1
} else if (it in uppercase) {
uppercase.indexOf(it) + 27
} else {
0
}
}
}
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("Day03_test")
println(logic2(input))
} | 0 | Kotlin | 0 | 0 | ddcf4f0be47ccbe4409605b37f43534125ee859d | 1,383 | AdventOfCodeKotlin | Apache License 2.0 |
aoc21/day_10/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
import java.util.ArrayDeque
fun match(c: Char): Char = when (c) {
'(' -> ')'
'[' -> ']'
'{' -> '}'
'<' -> '>'
else -> c
}
fun scoreErr(c: Char): Long = when (c) {
')' -> -3
']' -> -57
'}' -> -1197
'>' -> -25137
else -> 0
}
fun scoreMissing(c: Char): Long = when (c) {
')' -> 1
']' -> 2
'}' -> 3
'>' -> 4
else -> 0
}
fun analyse(line: String): Long {
val stack = ArrayDeque<Char>()
for (c in line) {
when (c) {
'(', '[', '<', '{' -> stack.push(c)
else -> if (match(stack.pop()) != c) return scoreErr(c)
}
}
return stack.fold(0) { res, c -> res * 5 + scoreMissing(match(c)) }
}
fun main() {
val lines = File("input").readLines()
val first = -lines.mapNotNull { analyse(it).takeIf { it < 0 } }.sum()
println("First: $first")
val scores = lines.mapNotNull { analyse(it).takeIf { it > 0 } }.sorted()
println("Second: ${scores[scores.size / 2]}")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,006 | advent-of-code | MIT License |
src/main/day02/day02.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day02
import readInput
import reverse
import second
const val ROCK = "A"
const val PAPER = "B"
const val SCISSORS = "C"
const val ROCK_ = "X"
const val PAPER_ = "Y"
const val SCISSORS_ = "Z"
const val LOSE = "X"
const val DRAW = "Y"
const val WIN = "Z"
fun part1(input: List<String>): Int {
return input.toPairs().sumOf {
when (it) {
ROCK to ROCK_ -> 1 + 3
ROCK to PAPER_ -> 2 + 6
ROCK to SCISSORS_ -> 3 + 0
PAPER to ROCK_ -> 1 + 0
PAPER to PAPER_ -> 2 + 3
PAPER to SCISSORS_ -> 3 + 6
SCISSORS to ROCK_ -> 1 + 6
SCISSORS to PAPER_ -> 2 + 0
SCISSORS to SCISSORS_ -> 3 + 3
else -> error("invalid pair")
}.toInt()
}
}
fun part2(input: List<String>): Int {
return input.toPairs().sumOf {
when (it.reverse()) {
LOSE to ROCK -> 0 + 3
DRAW to ROCK -> 3 + 1
WIN to ROCK -> 6 + 2
LOSE to PAPER -> 0 + 1
DRAW to PAPER -> 3 + 2
WIN to PAPER -> 6 + 3
LOSE to SCISSORS -> 0 + 2
DRAW to SCISSORS -> 3 + 3
WIN to SCISSORS -> 6 + 1
else -> error("invalid pair")
}.toInt()
}
}
fun main() {
val input = readInput("main/day02/Day02")
println(part1(input))
println(part2(input))
}
fun List<String>.toPairs() = map {
it.split(" ").let { pair ->
pair.first() to pair.second()
}
} | 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 1,492 | aoc-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/regex_matching/v5/RegexMatching.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.regex_matching.v5
import datsok.shouldEqual
import org.junit.jupiter.api.Test
class RegexMatching {
@Test fun `some examples`() {
"".matchesRegex("") shouldEqual true
"".matchesRegex("a") shouldEqual false
"a".matchesRegex("") shouldEqual false
"a".matchesRegex("a") shouldEqual true
"ab".matchesRegex("ab") shouldEqual true
"a".matchesRegex(".") shouldEqual true
"b".matchesRegex(".") shouldEqual true
"".matchesRegex(".") shouldEqual false
"ab".matchesRegex("a.") shouldEqual true
"ab".matchesRegex(".b") shouldEqual true
"ab".matchesRegex("c.") shouldEqual false
"".matchesRegex("a?") shouldEqual true
"a".matchesRegex("a?") shouldEqual true
"aa".matchesRegex("a?") shouldEqual false
"".matchesRegex(".?") shouldEqual true
"a".matchesRegex(".?") shouldEqual true
"ab".matchesRegex(".?") shouldEqual false
"".matchesRegex("a*") shouldEqual true
"a".matchesRegex("a*") shouldEqual true
"aa".matchesRegex("a*") shouldEqual true
"ba".matchesRegex("a*") shouldEqual false
"ab".matchesRegex("a*") shouldEqual false
"abc".matchesRegex(".*") shouldEqual true
}
}
typealias Matcher = (String) -> List<String>
fun char(c: Char): Matcher = { input ->
if (input.firstOrNull() == c) listOf(input.drop(1)) else emptyList()
}
fun anyChar(): Matcher = { input ->
if (input.isNotEmpty()) listOf(input.drop(1)) else emptyList()
}
fun zeroOrOne(matcher: Matcher): Matcher = { input ->
listOf(input) + matcher(input)
}
fun zeroOrMore(matcher: Matcher): Matcher = { input ->
listOf(input) + matcher(input).flatMap(zeroOrMore(matcher))
}
private fun String.matchesRegex(regex: String): Boolean {
val matchers = regex.fold(emptyList<Matcher>()) { matchers, c ->
when (c) {
'.' -> matchers + anyChar()
'?' -> matchers.dropLast(1) + zeroOrOne(matchers.last())
'*' -> matchers.dropLast(1) + zeroOrMore(matchers.last())
else -> matchers + char(c)
}
}
return matchers
.fold(listOf(this)) { inputs, matcher ->
inputs.flatMap(matcher).distinct()
}
.any { input -> input.isEmpty() }
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,322 | katas | The Unlicense |
kotlin/src/2022/Day22_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} | private data class P(val x: Int, val y: Int)
fun main() {
val input = readInput(22).lines()
val board = mutableMapOf<P, Int>() // wall = 2, empty field = 1, nothing = not in map
val N = input.indexOfFirst {it.isBlank()}
val M = input.take(N).maxOf {it.length}
input.take(N).withIndex().forEach {
it.value.withIndex().forEach {x ->
if (x.value != ' ') board[P(x.index + 1, it.index + 1)] = if (x.value == '#') 2 else 1
}
}
val moves = "(\\d+)([A-Z])?".toRegex().findAll(input[N + 1])
.flatMap {
it.groupValues.drop(1).filter {x -> x.isNotBlank()}
}.toList()
//////////////////// part1 ////////////////////
fun next(p: P, dx: Int, dy: Int, jump: (P, Int, Int) -> P?): P? {
val np = jump(p, dx, dy) ?: P(p.x + dx, p.y + dy)
return if (board[np] == 2) null else np
}
val faces = listOf('R', 'D', 'L', 'U')
val diff = mapOf('R' to P(1, 0), 'L' to P(-1, 0), 'U' to P(0, -1), 'D' to P(0, 1))
var p = P((1..M).first {P(it, 1) in board}, 1)
var face = 'R'
for (move in moves) {
if (move.first().isLetter()) {
face = faces[((faces.indexOf(face) + if (move.first() == 'R') 1 else -1) + 4) % 4]
continue
}
for (u in 0 until move.toInt()) {
val (dx, dy) = diff[face]!!
val np = next(p, dx, dy) { p, dx, dy ->
// if edge of the board, jump else, don't
if (P(p.x + dx, p.y + dy) in board) null
else {
var npp = P(
if (dx == 0) p.x else (if (dx > 0) 0 else M),
if (dy == 0) p.y else (if (dy > 0) 0 else N)
)
while (npp !in board) npp = P(npp.x + dx, npp.y + dy)
npp
}
} ?: break
p = np
}
}
println(p.y * 1000 + p.x * 4 + faces.indexOf(face))
//////////////////// part2 ////////////////////
p = P((1..M).first {P(it, 1) in board}, 1)
face = 'R'
// | AB|
// | C |
// |DE |
// |F |
fun jump(x: Int, y: Int, dx: Int, dy: Int): Pair<P, Char>? {
// A
if (x == 51 && y in 1..50 && dx < 0) return P(1, 151 - y) to 'R'
if (x in 51..100 && y == 1 && dy < 0) return P(1, 150+x-50) to 'R'
// B
if (x == 150 && y in 1..50 && dx > 0) return P(100, 100+(51-y)) to 'L'
if (x in 101..150 && y == 1 && dy < 0) return P(x - 100, 200) to 'U'
if (x in 101..150 && y == 50 && dy > 0) return P(100, 50+x-100) to 'L'
// C
if (x == 100 && y in 51..100 && dx > 0) return P(100 + y - 50, 50) to 'U'
if (x == 51 && y in 51..100 && dx < 0) return P(y - 50, 101) to 'D'
// D
if (y == 101 && x in 1..50 && dy < 0) return P(51, 50+x) to 'R'
if (y in 101..150 && x == 1 && dx < 0) return P(51, 151-y) to 'R'
// E
if (x == 100 && y in 101..150 && dx > 0) return P(150, 151-y) to 'L'
if (x in 51..100 && y == 150 && dy > 0) return P(50, 150+x-50) to 'L'
// F
if (x == 1 && y in 151..200 && dx < 0) return P(50 + y - 150, 1) to 'D'
if (x in 1..50 && y == 200 && dy > 0) return P(100 + x, 1) to 'D'
if (x == 50 && y in 151..200 && dx > 0) return P(50 + y - 150, 150) to 'U'
return null
}
for (move in moves) {
if (move.first().isLetter()) {
face = faces[((faces.indexOf(face) + if (move.first() == 'R') 1 else -1) + 4) % 4]
continue
}
for (u in 0 until move.toInt()) {
val (dx, dy) = diff[face]!!
var newface: Char? = face
val np = next(p, dx, dy) { p, dx, dy ->
val q = jump(p.x, p.y, dx, dy)
if (q != null) newface = q.second
q?.first
} ?: break
face = newface!!
p = np
}
}
println(p.y * 1000 + p.x * 4 + faces.indexOf(face))
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 4,019 | adventofcode | Apache License 2.0 |
src/Day02.kt | wlghdu97 | 573,333,153 | false | {"Kotlin": 50633} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val (opponent, ally) = it.split(" ")
fun map(sign: String): Int {
return when (sign) {
"A", "X" -> 1
"B", "Y" -> 2
"C", "Z" -> 3
else -> throw IllegalArgumentException()
}
}
fun selectedShape(): Int {
return map(ally)
}
fun roundOutcome(): Int {
val o = map(opponent)
val a = map(ally)
return when {
(o == a) -> 3
(o == 1 && a == 2) || (o == 2 && a == 3) || (o == 3 && a == 1) -> 6
else -> 0
}
}
selectedShape() + roundOutcome()
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val (opponent, ally) = it.split(" ")
fun selectedShape(): Int {
return when (opponent) {
"A" -> {
when (ally) {
"X" -> 3
"Y" -> 1
"Z" -> 2
else -> throw IllegalArgumentException()
}
}
"B" -> {
when (ally) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> throw IllegalArgumentException()
}
}
"C" -> {
when (ally) {
"X" -> 2
"Y" -> 3
"Z" -> 1
else -> throw IllegalArgumentException()
}
}
else -> throw IllegalArgumentException()
}
}
fun roundOutcome(): Int {
return when (ally) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> throw IllegalArgumentException()
}
}
selectedShape() + roundOutcome()
}
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2b95aaaa9075986fa5023d1bf0331db23cf2822b | 2,469 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day-03.kt | warriorzz | 728,357,548 | false | {"Kotlin": 15609, "PowerShell": 237} | package com.github.warriorzz.aoc
class Day3 : Day(3) {
var lines: List<ScematicLine> = listOf()
override fun init() {
lines = input.map { line ->
val numbers = "\\d+".toRegex().findAll(line).map { result ->
val int = result.value.toInt()
val range = result.range
val start = result.range.first
NumberSc(int, range, start)
}.toList()
val symbols = ArrayList<Gear>()
line.forEachIndexed { index, it ->
if (!it.isDigit() && it != '.')
symbols.add(Gear(index, it == '*'))
}
ScematicLine(symbols, numbers)
}
lines.forEachIndexed { indexLine, scematicLine ->
scematicLine.numbers.forEach { number ->
if (indexLine != 0) {
lines[indexLine - 1].symbols.forEach {
if (it.index in number.range) {
number.hasSymbol = true
it.increaseBy(number.int)
}
if (it.index == number.range.first - 1) {
number.hasSymbol = true
it.increaseBy(number.int)
}
if (it.index == number.range.last + 1) {
number.hasSymbol = true
it.increaseBy(number.int)
}
}
}
if (indexLine != lines.size - 1) {
lines[indexLine + 1].symbols.forEach {
if (it.index in number.range) {
number.hasSymbol = true
it.increaseBy(number.int)
}
if (it.index == number.startIndex - 1) {
number.hasSymbol = true
it.increaseBy(number.int)
}
if (it.index == number.range.last + 1) {
number.hasSymbol = true
it.increaseBy(number.int)
}
}
}
if (number.range.first != 0) {
scematicLine.symbols.forEach {
if (it.index == number.startIndex - 1) {
number.hasSymbol = true
it.increaseBy(number.int)
}
}
}
if (number.range.last != input.first().length - 1) {
scematicLine.symbols.forEach {
if (it.index == number.range.last + 1) {
number.hasSymbol = true
it.increaseBy(number.int)
}
}
}
}
}
lines.forEach { line ->
line.symbols.forEach {
println(it.index)
println(it.isGear)
println(it.gearRatio)
println(it.count)
}
}
}
override val partOne: (List<String>, Boolean) -> String = { _, _ ->
lines.map { it.numbers }.reduce { acc, numberScs ->
val list = ArrayList<NumberSc>()
list.addAll(acc)
list.addAll(numberScs)
list
}.filter { it.hasSymbol }.sumOf { it.int }.toString()
}
override val partTwo: (List<String>, Boolean) -> String = { _, _ ->
lines.map { it.symbols }.reduce { acc, symbol ->
val list = ArrayList<Gear>()
list.addAll(acc)
list.addAll(symbol)
list
}.filter { it.isGear && it.count == 2 }.sumOf { it.gearRatio }.toString()
}
}
data class ScematicLine(val symbols: List<Gear>, val numbers: List<NumberSc>)
data class NumberSc(val int: Int, val range: IntRange, val startIndex: Int, var hasSymbol: Boolean = false)
data class Gear(val index: Int, var isGear: Boolean, var gearRatio: Int = 1, var count: Int = 0) {
fun increaseBy(value: Int) {
if (isGear) {
if (count in 0..1) {
gearRatio *= value
count += 1
} else {
isGear = false
}
}
}
} | 0 | Kotlin | 0 | 1 | 502993c1cd414c0ecd97cda41475401e40ebb8c1 | 4,406 | aoc-23 | MIT License |
src/main/kotlin/solutions/Day12.kt | chutchinson | 573,586,343 | false | {"Kotlin": 21958} | class Day12 : Solver {
data class Vector2i(val x: Int, val y: Int)
data class Grid(val cells: List<Char>,
val width: Int, val height: Int)
override fun solve (input: Sequence<String>) {
val grid = parse(input)
println(first(grid))
println(second(grid))
}
fun first (grid: Grid): Int {
val start = grid.points().find { grid.get(it.x, it.y, false) == 'S' }
val end = grid.points().find { grid.get(it.x, it.y, false) == 'E' }
return grid.climb(start!!, end!!)
}
fun second (grid: Grid): Int {
val end = grid.points().find { grid.get(it.x, it.y, false) == 'E' }
return grid.points()
.filter { grid.get(it.x, it.y) == 'a' }
.map { grid.climb(it, end!!) }
.filter { it != 0 }
.min()
}
fun parse (input: Sequence<String>): Grid {
val cells = mutableListOf<Char>()
val lines = input.toList()
var width = 0
var height = 0
for (line in lines) {
for (ch in line) {
cells.add(ch)
}
width = line.length
height += 1
}
return Grid(cells, width, height)
}
fun Grid.get (x: Int, y: Int, reduce: Boolean = true): Char {
val value = cells[y * width + x]
if (reduce && value == 'S') return 'a'
if (reduce && value == 'E') return 'z'
return value
}
fun Grid.points () = sequence {
for (y in 0 until height) {
for (x in 0 until width) {
yield(Vector2i(x, y))
}
}
}
fun Grid.neighbors (x: Int, y: Int) = sequence {
fun valid (nx: Int, ny: Int): Boolean {
if (nx < 0 || nx >= width) return false
if (ny < 0 || ny >= height) return false
return get(nx, ny) <= get(x, y) + 1
}
if (valid(x - 1, y)) yield(Vector2i(x - 1, y))
if (valid(x + 1, y)) yield(Vector2i(x + 1, y))
if (valid(x, y - 1)) yield(Vector2i(x, y - 1))
if (valid(x, y + 1)) yield(Vector2i(x, y + 1))
}
fun Grid.climb (start: Vector2i, end: Vector2i): Int {
val queue = ArrayDeque<Vector2i>()
val scores = mutableMapOf<Vector2i, Int>()
val visited = mutableSetOf<Vector2i>() // no backtracking
fun visit (current: Vector2i, next: Vector2i) {
scores[next] = (scores[current] ?: -1) + 1
queue.addLast(next)
visited.add(next)
}
visit(start, start)
while (queue.isNotEmpty()) {
val current = queue.removeFirst()
if (current == end) {
return scores[end]!!
}
for (neighbor in neighbors(current.x, current.y)) {
if (!visited.contains(neighbor)) {
visit(current, neighbor)
}
}
}
return 0
}
} | 0 | Kotlin | 0 | 0 | 5076dcb5aab4adced40adbc64ab26b9b5fdd2a67 | 3,030 | advent-of-code-2022 | MIT License |
src/main/kotlin/g2801_2900/s2850_minimum_moves_to_spread_stones_over_grid/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2801_2900.s2850_minimum_moves_to_spread_stones_over_grid
// #Medium #Array #Dynamic_Programming #Breadth_First_Search #Matrix
// #2023_12_18_Time_133_ms_(100.00%)_Space_34.6_MB_(100.00%)
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Solution {
fun minimumMoves(grid: Array<IntArray>): Int {
val a = grid[0][0] - 1
val b = grid[0][1] - 1
val c = grid[0][2] - 1
val d = grid[1][0] - 1
val f = grid[1][2] - 1
val g = grid[2][0] - 1
val h = grid[2][1] - 1
val i = grid[2][2] - 1
var minCost = Int.MAX_VALUE
for (x in min(a, 0)..max(a, 0)) {
for (y in min(c, 0)..max(c, 0)) {
for (z in min(i, 0)..max(i, 0)) {
for (t in min(g, 0)..max(g, 0)) {
val cost: Int =
abs(x) + abs(y) + abs(z) + abs(t) + abs((x - a)) + abs(
(y - c)
) + abs((z - i)) + abs((t - g)) + abs((x - y + b + c)) + abs(
(y - z + i + f)
) + abs((z - t + g + h)) + abs((t - x + a + d))
if (cost < minCost) {
minCost = cost
}
}
}
}
}
return minCost
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,400 | LeetCode-in-Kotlin | MIT License |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day9/Day9.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day9
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.Companion.NEXT_4
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.get
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 9](https://adventofcode.com/2021/day/9)
*/
object Day9 : DayOf2021(9) {
override fun first(): Any? {
val points = lines.map { line -> line.toList().map { it.digitToInt() } }
return points.mapIndexed { y, line ->
line.filterIndexed { x, value ->
val point = Vector2D(x, y)
NEXT_4.map { point + it.step }.all { neighbor ->
points[neighbor]?.let { it > value } ?: true
}
}.sumOf { it + 1 }
}.sum()
}
override fun second(): Any? {
val points = lines.map { line -> line.toList().map { it.digitToInt() } }
val low = points.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, value ->
Vector2D(x, y).takeIf { point ->
NEXT_4.map { point + it.step }.all { neighbor ->
points[neighbor]?.let { it > value } ?: true
}
}
}
}
val basins = low.map { start ->
val startValue = points[start]!!
val seen = mutableMapOf<Vector2D, Int>()
val queue = ArrayDeque(listOf(start to startValue))
while (queue.isNotEmpty()) {
val (curr, value) = queue.removeFirst()
if (curr !in seen) {
seen[curr] = value
val next = NEXT_4.map { curr + it.step }
.mapNotNull { neighbor -> points[neighbor]?.let { neighbor to it } }
.filter { it.second > value && it.second != 9 }
queue += next
}
}
seen
}
return basins.map { it.size }
.sorted()
.takeLast(3)
.reduce { a, b -> a * b }
}
}
fun main() = SomeDay.mainify(Day9)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,841 | adventofcode | MIT License |
src/com/kingsleyadio/adventofcode/y2022/day02/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2022.day02
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val input = readInput(2022, 2).readLines()
part1(input)
part2(input)
}
fun part1(input: List<String>) {
val result = input.sumOf { line ->
when(line) {
"A X" -> 4
"A Y" -> 8
"A Z" -> 3
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 7
"C Y" -> 2
"C Z" -> 6
else -> 0u.toInt() // Hack around weird KT compile error
}
}
println(result)
}
fun part2(input: List<String>) {
val values = mapOf('A' to 1, 'B' to 2, 'C' to 3)
val result = input.sumOf { line ->
val (opponent, _, strategy) = line.toCharArray()
when(strategy) {
'X' -> (values.getValue(opponent) + 1) % 3 + 1
'Y' -> 3 + values.getValue(opponent)
'Z' -> 6 + values.getValue(opponent) % 3 + 1
else -> 0
}
}
println(result)
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,041 | adventofcode | Apache License 2.0 |
src/Day25.kt | fonglh | 573,269,990 | false | {"Kotlin": 48950, "Ruby": 1701} | fun main() {
// convert SNAFU digit (2, 1, 0, -, =) to Dec
fun snafuDigit(digit: Char): Int {
return when(digit) {
'2' -> 2
'1' -> 1
'0' -> 0
'-' -> -1
'=' -> -2
else -> 999
}
}
fun snafuToDec(snafuNum: String): Long {
var placeValue = 1.toLong()
var decimalNumber = 0.toLong()
snafuNum.reversed().forEach {
decimalNumber += snafuDigit(it) * placeValue
placeValue *= 5.toLong()
}
return decimalNumber
}
fun decToSnafu(input: Long): String {
var decNum = input
val snafuDigits = charArrayOf('=', '-', '0', '1', '2')
val snafuNum = StringBuilder()
while (decNum > 0) {
val currentDigit = (decNum+2.toLong()) % 5.toLong()
decNum = (decNum+2.toLong()) / 5.toLong()
snafuNum.append(snafuDigits[currentDigit.toInt()])
}
return snafuNum.toString().reversed()
}
fun part1(input: List<String>): String {
var fuelSum: Long = 0
input.forEach {
fuelSum += snafuToDec(it)
}
println(fuelSum)
return decToSnafu(fuelSum)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
check(part1(testInput) == "2=-1=0")
val input = readInput("Day25")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | ef41300d53c604fcd0f4d4c1783cc16916ef879b | 1,457 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/org/example/BiPartiteGraph.kt | jaypandya | 584,055,319 | false | null | package org.example
class Solution {
enum class Color {
Red, Blue, None;
}
fun isBipartite(graph: Array<IntArray>): Boolean {
val queue = ArrayDeque<Int>()
val colorArray = Array(graph.size) { Color.None }
for (index in colorArray.indices) {
if (colorArray[index] != Color.None) continue
colorArray[index] = Color.Red
queue.addLast(index)
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
val nodeColor = colorArray[node]
val neighborColor = if (nodeColor == Color.Red) Color.Blue else Color.Red
val neighbors = graph[node]
for (neighbor in neighbors) {
if (colorArray[neighbor] == Color.None) {
colorArray[neighbor] = neighborColor
queue.addLast(neighbor)
} else if (colorArray[neighbor] == nodeColor) {
return false
}
}
}
}
return true
}
}
fun parseGraph(s: String): Array<IntArray> {
var bracketCount = 0
val array = mutableListOf<IntArray>()
var innerList: MutableList<Int> = mutableListOf()
for (char in s.toCharArray()) {
if (char == '[') {
bracketCount++
if (bracketCount == 2) {
innerList = mutableListOf()
}
} else if (char == ']') {
bracketCount--
if (bracketCount == 1) {
array.add(innerList.toIntArray())
}
} else if (char == ',') {
continue
} else {
if (bracketCount == 2) {
innerList.add(char.digitToInt())
}
}
}
return array.toTypedArray()
}
fun main() {
val graph1 = arrayOf(
intArrayOf(1, 2, 3),
intArrayOf(0, 2),
intArrayOf(0, 1, 3),
intArrayOf(0, 2)
)
val graph2 = arrayOf(
intArrayOf(1, 3),
intArrayOf(0, 2),
intArrayOf(1, 3),
intArrayOf(0, 2)
)
val graph74 = parseGraph("[[],[3],[],[1],[]]")
val graph76 = parseGraph("[[],[2,4,6],[1,4,8,9],[7,8],[1,2,8,9],[6,9],[1,5,7,8,9],[3,6,9],[2,3,4,6,9],[2,4,5,6,7,8]]")
// [[1],[0,3],[3],[1,2]]
val graph78 = arrayOf(
intArrayOf(1),
intArrayOf(0, 3),
intArrayOf(3),
intArrayOf(1, 2)
)
val solution = Solution()
assert(!solution.isBipartite(graph1))
assert(solution.isBipartite(graph2))
assert(solution.isBipartite(graph74))
assert(!solution.isBipartite(graph76))
assert(solution.isBipartite(graph78))
}
| 0 | Kotlin | 0 | 0 | 5f94df91e07773239583c520682ed6505b0c186b | 2,711 | dsa | MIT License |
app/src/main/kotlin/day01/Day01.kt | W3D3 | 726,573,421 | false | {"Kotlin": 81242} | package day01
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 1
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay01Part1, ::solveDay01Part2)
}
val numbers = arrayOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
fun solveDay01Part1(input: List<String>): Int {
return input.map { s: String ->
val first = s.find { c -> c.isDigit() }
val last = s.findLast { c -> c.isDigit() }
val nr = "$first$last"
println(nr)
nr.toInt()
}.sum()
}
fun solveDay01Part2(input: List<String>): Int {
return input.map { s: String ->
// HACK replace this with a proper overlap solution
val line = s.replace("one", "on1e").replace("two", "tw2o").replace("three", "thre3e")
val regex = "(\\d|one|two|three|four|five|six|seven|eight|nine)".toRegex()
val matches = regex.findAll(line).sortedBy { it.range.first }
val first = matches.first().value
val last = matches.last().value
val matchesValues = matches.map { it.value }
println(matchesValues)
val firstDigit = if (first.length == 1) first.toInt() else numbers.indexOf(first) + 1
val lastDigit = if (last.length == 1) last.toInt() else numbers.indexOf(last) + 1
val nr = "$firstDigit$lastDigit"
nr.toInt()
}.sum()
}
| 0 | Kotlin | 0 | 0 | da174508f6341f85a1a92159bde3ecd5dcbd3c14 | 1,449 | AdventOfCode2023 | Apache License 2.0 |
calendar/day05/Day5.kt | polarene | 572,886,399 | false | {"Kotlin": 17947} | package day05
import Day
import Lines
class Day5 : Day() {
override fun part1(input: Lines): Any {
val crates = setupCrates(input)
val crane = Crane9000(crates)
input.asSequence()
.dropWhile { it.isNotEmpty() }
.drop(1)
.map(::readStep)
.forEach {
crane.rearrange(it.first, it.second, it.third)
}
return crates.top()
}
override fun part2(input: Lines): Any {
val crates = setupCrates(input)
println(crates)
val crane = Crane9001(crates)
input.asSequence()
.dropWhile { it.isNotEmpty() }
.drop(1)
.map(::readStep)
.forEach {
crane.rearrange(it.first, it.second, it.third)
}
return crates.top()
}
}
typealias Crate = Char
typealias Stack = MutableList<Crate>
fun setupCrates(input: Lines): Crates {
val cratesConfiguration = readConfiguration(input)
val stacksCount = countStacks(cratesConfiguration.removeFirst())
val stacks = initStacks(stacksCount)
val itemsDistance = 4
cratesConfiguration
.forEach { layer ->
(1 until layer.length step itemsDistance).forEach { i ->
layer[i].takeUnless { it.isWhitespace() }
?.run { stacks[i / itemsDistance] += this }
}
}
return Crates(stacks)
}
private fun readConfiguration(input: Lines) =
input.takeWhile { it.isNotEmpty() }
.reversed()
.toMutableList()
private fun countStacks(indicesLine: String) =
indicesLine[indicesLine.lastIndex - 1].digitToInt()
private fun initStacks(stacksCount: Int) = buildList<Stack>(stacksCount) {
repeat(stacksCount) { add(mutableListOf()) }
}
val STEP = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
fun readStep(line: String): Triple<Int, Int, Int> {
val (count, from, to) = STEP.matchEntire(line)!!.groupValues
.drop(1)
.map { it.toInt() }
return Triple(count, from - 1, to - 1)
}
class Crates(private val stacks: List<Stack>) {
fun top(): String = stacks.map { it.last() }.joinToString("")
fun move(from: Int, to: Int) {
stacks[to] += stacks[from].removeLast()
}
fun move(count: Int, from: Int, to: Int) {
stacks[to] += buildList {
repeat(count) { add(0, stacks[from].removeLast()) }
}
}
override fun toString(): String {
return buildString {
stacks.forEach { this.append(it).append('\n') }
}
}
}
class Crane9000(private val crates: Crates) {
fun rearrange(count: Int, from: Int, to: Int) {
repeat(count) { crates.move(from, to) }
}
}
class Crane9001(private val crates: Crates) {
fun rearrange(count: Int, from: Int, to: Int) {
crates.move(count, from, to)
}
} | 0 | Kotlin | 0 | 0 | 0b2c769174601b185227efbd5c0d47f3f78e95e7 | 2,867 | advent-of-code-2022 | Apache License 2.0 |
src/Lesson9MaximumSliceProblem/MaxProfit.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} | /**
* 100/100
* Check MaxSliceSum for explanation on Kadane's algorithm is applied here
* @param A
* @return
*/
fun solution(A: IntArray): Int {
if (A.size == 1 || A.size == 0) {
return 0
}
var maxSoFar = 0
var maxEndingHere = 0
var minPrice = A[0]
for (i in 1 until A.size) {
maxEndingHere = Math.max(0, A[i] - minPrice)
minPrice = Math.min(minPrice, A[i])
maxSoFar = Math.max(maxEndingHere, maxSoFar)
}
return maxSoFar
}
/**
* An array A consisting of N integers is given. It contains daily prices of a stock share for a period of N consecutive days. If a single share was bought on day P and sold on day Q, where 0 ≤ P ≤ Q < N, then the profit of such transaction is equal to A[Q] − A[P], provided that A[Q] ≥ A[P]. Otherwise, the transaction brings loss of A[P] − A[Q].
*
* For example, consider the following array A consisting of six elements such that:
*
* A[0] = 23171
* A[1] = 21011
* A[2] = 21123
* A[3] = 21366
* A[4] = 21013
* A[5] = 21367
* If a share was bought on day 0 and sold on day 2, a loss of 2048 would occur because A[2] − A[0] = 21123 − 23171 = −2048. If a share was bought on day 4 and sold on day 5, a profit of 354 would occur because A[5] − A[4] = 21367 − 21013 = 354. Maximum possible profit was 356. It would occur if a share was bought on day 1 and sold on day 5.
*
* Write a function,
*
* class Solution { public int solution(int[] A); }
*
* that, given an array A consisting of N integers containing daily prices of a stock share for a period of N consecutive days, returns the maximum possible profit from one transaction during this period. The function should return 0 if it was impossible to gain any profit.
*
* For example, given array A consisting of six elements such that:
*
* A[0] = 23171
* A[1] = 21011
* A[2] = 21123
* A[3] = 21366
* A[4] = 21013
* A[5] = 21367
* the function should return 356, as explained above.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [0..400,000];
* each element of array A is an integer within the range [0..200,000].
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 2,196 | Codility-Kotlin | Apache License 2.0 |
advent-of-code-2021/src/code/day2/Main.kt | Conor-Moran | 288,265,415 | false | {"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733} | package code.day2
import java.io.File
fun main() {
doIt("Day 2 Part 1: Test Input", "src/code/day2/test.input", part1);
doIt("Day 2 Part 1: Real Input", "src/code/day2/part1.input", part1);
doIt("Day 2 Part 2: Test Input", "src/code/day2/test.input", part2);
doIt("Day 2 Part 2: Real Input", "src/code/day2/part1.input", part2);
}
fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Int) {
val lines = arrayListOf<String>()
File(input).forEachLine { lines.add(it) };
println(String.format("%s: Ans: %d", msg , calc(lines)));
}
val part1: (List<String>) -> Int = { lines ->
val tots = mutableMapOf<String, Int>();
lines.forEach {
val cmd = parse(it);
val tot = tots.computeIfAbsent(cmd.first) { 0 };
tots[cmd.first] = tot + cmd.second;
};
val fwd = tots.getOrDefault("forward",0);
val depth = tots.getOrDefault("down", 0) - tots.getOrDefault("up", 0);
fwd * depth;
}
fun parse(line: String): Pair<String, Int> {
val tokens = line.split(" ");
return Pair<String, Int>(tokens[0], Integer.parseInt(tokens[1]));
}
val part2: (List<String>) -> Int = { lines ->
var aim = 0;
var horiz = 0;
var depth = 0;
lines.forEach {
val cmd = parse(it);
when(cmd.first) {
"forward" -> { horiz += cmd.second; depth += aim * cmd.second }
"up" -> { aim -= cmd.second; }
"down" -> { aim += cmd.second; }
}
};
depth * horiz;
}
| 0 | Kotlin | 0 | 0 | ec8bcc6257a171afb2ff3a732704b3e7768483be | 1,500 | misc-dev | MIT License |
src/Day10.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | private sealed interface Command
private sealed interface Assembly
private object Noop : Command, Assembly
private class AddX(val value: Int) : Command
private class Add(val value: Int) : Assembly
fun main() {
fun parseCommand(str: String): Command {
return when {
str == "noop" -> Noop
str.startsWith("addx ") -> AddX(str.removePrefix("addx ").toInt())
else -> error("Unexpected command '$str'")
}
}
fun parseAndConvertToAssembly(input: List<String>): List<Assembly> {
val initialCommands = input.map { parseCommand(it) }
val assembly = initialCommands
.flatMap {
when (it) {
is AddX -> listOf(Noop, Add(it.value))
is Noop -> listOf(it)
}
}
return assembly
}
class Executor(val assembly: List<Assembly>) {
var register = 1
private set
var cycle = 1
private set
fun nextStep() {
require(hasNext)
when (val cmd = assembly[cycle - 1]) {
is Add -> register += cmd.value
Noop -> {}
}
cycle += 1
}
val hasNext: Boolean
get() = cycle < assembly.size
}
fun part1(input: List<String>): Int {
val assembly = parseAndConvertToAssembly(input)
val recordedCycles =
listOf(20, 60, 100, 140, 180, 220)
.associateWith { 0 }
.toMutableMap()
val executor = Executor(assembly)
while (executor.hasNext) {
if (executor.cycle in recordedCycles) {
recordedCycles[executor.cycle] = executor.register
}
executor.nextStep()
}
return recordedCycles.toList().sumOf { (cycles, value) -> cycles * value }
}
fun part2(input: List<String>): String {
val assembly = parseAndConvertToAssembly(input)
val executor = Executor(assembly)
val width = 40
val height = 6
return (0 until height).joinToString(separator = System.lineSeparator()) { _ ->
(0 until width).joinToString("") { widthPos ->
val sprite = executor.register
val pixelColor: String =
if (widthPos in (sprite - 1)..(sprite + 1)) {
"#"
} else {
"."
}
executor.nextStep()
pixelColor
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val part2 = part2(testInput)
check(part2 == """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent()
)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 3,251 | aoc2022 | Apache License 2.0 |
src/Day12.kt | brigittb | 572,958,287 | false | {"Kotlin": 46744} | import java.util.Stack
fun main() {
fun prepareGrid(
input: List<String>,
x: Int,
y: Int,
): Triple<Array<Array<Vertex>>, Pair<Int, Int>, Pair<Int, Int>> {
val grid = Array(x) { Array(y) { Vertex() } }
var source = 0 to 0
var destination = 0 to 0
input
.filter { it.isNotEmpty() }
.map { it.asSequence() }
.forEachIndexed { row, columns ->
columns.forEachIndexed { column, height ->
when (height) {
'S' -> {
with(grid[row][column]) {
this.row = row
this.column = column
this.height = 'a'
this.distance = 0
}
source = row to column
}
'E' -> {
with(grid[row][column]) {
this.row = row
this.column = column
this.height = 'z'
this.distance = 0
}
destination = row to column
}
else ->
with(grid[row][column]) {
this.row = row
this.column = column
this.height = height
}
}
}
}
return Triple(grid, source, destination)
}
fun upOrNull(vertex: Vertex, grid: Array<Array<Vertex>>) =
if (vertex.row != 0) grid[vertex.row - 1][vertex.column] else null
fun rightOrNull(vertex: Vertex, y: Int, grid: Array<Array<Vertex>>) =
if (vertex.column != y - 1) grid[vertex.row][vertex.column + 1] else null
fun downOrNull(vertex: Vertex, x: Int, grid: Array<Array<Vertex>>) =
if (vertex.row != x - 1) grid[vertex.row + 1][vertex.column] else null
fun leftOrNull(vertex: Vertex, grid: Array<Array<Vertex>>) =
if (vertex.column != 0) grid[vertex.row][vertex.column - 1] else null
fun part1(input: List<String>): Int {
val x = input.size
val y = input.first().length
val (grid, source, destination) = prepareGrid(input, x, y)
val queue = ArrayDeque<Vertex>()
val visited = Stack<Vertex>()
queue.add(grid[source.first][source.second])
visited.add(grid[source.first][source.second])
while (queue.isNotEmpty()) {
val vertex = queue.removeFirst()
listOfNotNull(
upOrNull(vertex, grid),
rightOrNull(vertex, y, grid),
downOrNull(vertex, x, grid),
leftOrNull(vertex, grid)
)
.filter { vertex.height + 1 >= it.height }
.filter { !visited.contains(it) }
.forEach {
if (vertex.distance != null) {
it.distance = vertex.distance
?.plus(1)
?: error("previous vertex's distance not set")
}
queue.add(it)
visited.add(it)
}
}
return grid[destination.first][destination.second].distance ?: 0
}
fun part2(input: List<String>): Int {
val x = input.size
val y = input.first().length
val (grid, _, destination) = prepareGrid(input, x, y)
val queue = ArrayDeque<Vertex>()
val visited = Stack<Vertex>()
val possibleSources = mutableListOf<Vertex>()
queue.add(grid[destination.first][destination.second])
visited.add(grid[destination.first][destination.second])
while (queue.isNotEmpty()) {
val vertex = queue.removeFirst()
listOfNotNull(
upOrNull(vertex, grid),
rightOrNull(vertex, y, grid),
downOrNull(vertex, x, grid),
leftOrNull(vertex, grid)
)
.filter { vertex.height - 1 <= it.height }
.filter { !visited.contains(it) }
.forEach {
if (vertex.distance != null) {
it.distance = vertex.distance
?.plus(1)
?: error("previous vertex's distance not set")
}
queue.add(it)
visited.add(it)
if (it.height == 'a') {
possibleSources.add(it)
}
}
}
return possibleSources
.sortedBy { it.distance }
.first()
.distance
?: 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
data class Vertex(
var row: Int = 0,
var column: Int = 0,
var height: Char = 'a',
var distance: Int? = null,
)
| 0 | Kotlin | 0 | 0 | 470f026f2632d1a5147919c25dbd4eb4c08091d6 | 5,369 | aoc-2022 | Apache License 2.0 |
day03/part1.kts | bmatcuk | 726,103,418 | false | {"Kotlin": 214659} | // --- Day 3: Gear Ratios ---
// You and the Elf eventually reach a gondola lift station; he says the gondola
// lift will take you up to the water source, but this is as far as he can
// bring you. You go inside.
//
// It doesn't take long to find the gondolas, but there seems to be a problem:
// they're not moving.
//
// "Aaah!"
//
// You turn around to see a slightly-greasy Elf with a wrench and a look of
// surprise. "Sorry, I wasn't expecting anyone! The gondola lift isn't working
// right now; it'll still be a while before I can fix it." You offer to help.
//
// The engineer explains that an engine part seems to be missing from the
// engine, but nobody can figure out which one. If you can add up all the part
// numbers in the engine schematic, it should be easy to work out which part is
// missing.
//
// The engine schematic (your puzzle input) consists of a visual representation
// of the engine. There are lots of numbers and symbols you don't really
// understand, but apparently any number adjacent to a symbol, even diagonally,
// is a "part number" and should be included in your sum. (Periods (.) do not
// count as a symbol.)
//
// Here is an example engine schematic:
//
// 467..114..
// ...*......
// ..35..633.
// ......#...
// 617*......
// .....+.58.
// ..592.....
// ......755.
// ...$.*....
// .664.598..
//
// In this schematic, two numbers are not part numbers because they are not
// adjacent to a symbol: 114 (top right) and 58 (middle right). Every other
// number is adjacent to a symbol and so is a part number; their sum is 4361.
//
// Of course, the actual engine schematic is much larger. What is the sum of
// all of the part numbers in the engine schematic?
import java.io.*
import kotlin.io.*
import kotlin.math.*
fun isSymbol(chr: Char) = chr != '.' && !chr.isDigit()
fun hasAdjSymbol(lines: List<String>, lineIdx: Int, range: IntRange): Boolean {
val line = lines[lineIdx]
val expandedRange = max(range.start - 1, 0)..min(range.endInclusive + 1, line.length - 1)
if (lineIdx > 0 && lines[lineIdx - 1].subSequence(expandedRange).any(::isSymbol)) {
return true
}
if (lineIdx + 1 < lines.size && lines[lineIdx + 1].subSequence(expandedRange).any(::isSymbol)) {
return true
}
return isSymbol(line[expandedRange.start]) || isSymbol(line[expandedRange.endInclusive])
}
val RGX = Regex("(\\d+)")
val lines = File("input.txt").readLines()
val result = lines.withIndex().sumOf { (lineIdx, line) ->
RGX.findAll(line).sumOf {
val num = it.groupValues[1].toInt()
val range = it.range
if (hasAdjSymbol(lines, lineIdx, range)) num else 0
}
}
println(result)
| 0 | Kotlin | 0 | 0 | a01c9000fb4da1a0cd2ea1a225be28ab11849ee7 | 2,636 | adventofcode2023 | MIT License |
AdventOfCodeDay03/src/nativeMain/kotlin/Day03.kt | bdlepla | 451,510,571 | false | {"Kotlin": 165771} | class Day03(private val lines:List<String>) {
fun solvePart1():Long {
val linesCount = lines.count()
val halfCount = linesCount/2
val gammaString = lines[0].indices.map { idx ->
val onesCount = lines.count{it[idx] == '1'}
val onesGreater = onesCount > halfCount
if (onesGreater) '1' else '0'
}.joinToString("")
val epsilonString = gammaString
.map{ if (it == '1') '0' else '1'}
.joinToString("")
val gamma = gammaString.toLong(2)
val epsilon = epsilonString.toLong(2)
return gamma * epsilon
}
fun solvePart2(): Long {
val oxygen = findMost(lines, 0)
println("Oxygen = $oxygen")
val co2 = findLeast(lines, 0)
println("CO2 = $co2")
return oxygen * co2
}
private fun findMost(l:List<String>, idx:Int):Long {
if (l.count() == 1) return l.first().toLong(2)
val onesCount = l.count{it[idx] == '1'}
val zeroCount = l.count() - onesCount
val onesGreater = onesCount >= zeroCount
val which = if (onesGreater) '1' else '0'
val newList = l.filter{it[idx] == which}
//println(newList.joinToString(","))
return findMost(newList, idx+1)
}
private fun findLeast(l:List<String>, idx:Int):Long {
if (l.count() == 1) return l.first().toLong(2)
val onesCount = l.count{it[idx] == '1'}
val zeroCount = l.count() - onesCount
val zerosLesser = zeroCount <= onesCount
val which = if (zerosLesser) '0' else '1'
val newList = l.filter{it[idx] == which}
//println(newList.joinToString(","))
return findLeast(newList, idx+1)
}
} | 0 | Kotlin | 0 | 0 | 1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871 | 1,731 | AdventOfCode2021 | The Unlicense |
src/main/kotlin/de/jball/aoc2022/day10/Day10.kt | fibsifan | 573,189,295 | false | {"Kotlin": 43681} | package de.jball.aoc2022.day10
import de.jball.aoc2022.Day
class Day10(test: Boolean = false): Day<Int>(test, 13140, 1 /*cheating here...*/) {
private val program = input.map { parseCommand(it) }
private val spritePositions = program
.runningFold(listOf(Pair(0,1))) { state, operation -> operation.apply(state) }
.flatten()
.toMap()
private fun parseCommand(line: String): Operation {
return if (line == "noop") Noop else Add(line.split(" ")[1].toInt())
}
override fun part1(): Int {
return (20 until spritePositions.size step 40)
.sumOf {
// -1, because of "during"
spritePositions[it-1]!! * it
}
}
override fun part2(): Int {
for (i in (0 until 6)) {
for (j in (0 until 40)) {
print(pixel(i, j))
}
println()
}
return 1
}
private fun pixel(i: Int, j: Int): String {
val spritePosition = spritePositions[i * 40 + j]!!
return if (spritePosition >= j-1 && spritePosition <= j+1) "#" else "."
}
}
sealed class Operation {
abstract fun apply(previous: List<Pair<Int, Int>>): List<Pair<Int, Int>>
}
object Noop : Operation() {
override fun apply(previous: List<Pair<Int, Int>>) = listOf(Pair(previous.last().first+1, previous.last().second))
}
class Add(private val v: Int): Operation() {
override fun apply(previous: List<Pair<Int, Int>>) = listOf(
Pair(previous.last().first+1, previous.last().second),
Pair(previous.last().first+2, previous.last().second+v))
}
fun main() {
Day10().run()
}
| 0 | Kotlin | 0 | 3 | a6d01b73aca9b54add4546664831baf889e064fb | 1,646 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/Day1.kt | andilau | 544,512,578 | false | {"Kotlin": 29165} | package days
import days.Day1.Direction.*
import kotlin.math.abs
@AdventOfCodePuzzle(
name = "No Time for a Taxicab",
url = "https://adventofcode.com/2016/day/1",
date = Date(day = 1, year = 2016)
)
class Day1(input: String) : Puzzle {
private val instructions = input
.split(", ")
.map(Instruction::from)
override fun partOne(): Int = instructions.walk().last().manhattanDistance
override fun partTwo(): Int {
val visited = mutableSetOf<Point>()
for (point in instructions.walk()) {
if (point in visited)
return point.manhattanDistance
visited += point
}
error("Invalid Input")
}
private fun List<Instruction>.walk() = sequence {
var pos = Point.ORIGIN
var dir = NORTH
this@walk.forEach() { instruction ->
dir = dir.turn(instruction.turn)
(1..instruction.steps).forEach { _ ->
pos = pos.move(dir)
yield(pos)
}
}
}
data class Point(val x: Int, val y: Int) {
fun move(facing: Direction): Point = when (facing) {
NORTH -> copy(y = y + 1)
SOUTH -> copy(y = y - 1)
EAST -> copy(x = x + 1)
WEST -> copy(x = x - 1)
}
val manhattanDistance get() = abs(x) + abs(y)
companion object {
val ORIGIN: Point = Point(0, 0)
}
}
data class Instruction(val turn: Char, val steps: Int) {
companion object {
fun from(text: String): Instruction =
Instruction(text.first(), text.substring(1).toInt())
}
}
enum class Direction {
NORTH, EAST, SOUTH, WEST;
fun turn(turn: Char): Direction = when (this) {
NORTH -> if (turn == 'R') EAST else WEST
EAST -> if (turn == 'R') SOUTH else NORTH
SOUTH -> if (turn == 'R') WEST else EAST
WEST -> if (turn == 'R') NORTH else SOUTH
}
}
}
| 3 | Kotlin | 0 | 0 | b2a836bd3f1c5eaec32b89a6ab5fcccc91b665dc | 2,029 | advent-of-code-2016 | Creative Commons Zero v1.0 Universal |
src/Day07.kt | psy667 | 571,468,780 | false | {"Kotlin": 23245} | enum class Type {
DIR,
FILE,
}
data class Node(val type: Type, val name: String, var size: Int, val children: MutableList<Node>)
fun main() {
val id = "07"
fun Node.addChildDir(name: String) {
this.children.add(Node(Type.DIR, name, 0, mutableListOf()))
}
fun Node.addChildFile(name: String, size: Int) {
this.children.add(Node(Type.FILE, name, size, mutableListOf()))
}
fun printTree(node: Node, depth: Int = 0) {
println("${" ".repeat(depth)} - ${node.name} ${node.type} ${node.size}")
if(node.type == Type.DIR) {
node.children.forEach{it -> printTree(it, depth + 1)}
}
}
fun calcSize(node: Node): Int {
if(node.type == Type.FILE) {
return node.size
}
node.size = node.children.map{ calcSize(it) }.sum()
return node.size
}
fun flatTree(node: Node): MutableList<Node> {
val list = mutableListOf(node)
list.addAll(node.children.flatMap { flatTree(it) })
return list
}
fun part1(input: List<String>): Int {
val path = mutableListOf<String>()
val tree = Node(Type.DIR, "/", 0, mutableListOf())
fun Node.getByPath(path: List<String>): Node {
var res = tree
path.drop(1).forEach { name ->
res = res.children.find{ it.name == name }!!
}
return res
}
input.forEach {
if (it.startsWith("$")) {
val (_, cmd) = it.split(" ")
if (cmd == "cd") {
val name = it.split(" ")[2]
if (name == "..") {
path.removeLast()
} else {
path.add(name)
}
}
} else {
val (dirOrSize, name) = it.split(" ")
if (dirOrSize == "dir") {
tree.getByPath(path).addChildDir(name)
} else {
tree.getByPath(path).addChildFile(name, dirOrSize.toInt())
}
}
}
calcSize(tree)
return flatTree(tree)
.filter {it.type != Type.FILE}
.filter{ it.size <= 100000 }
.map{ it.size }
.sum()
}
fun part2(input: List<String>): Int {
val path = mutableListOf<String>()
val tree = Node(Type.DIR, "/", 0, mutableListOf())
fun Node.getByPath(path: List<String>): Node {
var res = tree
path.drop(1).forEach { name ->
res = res.children.find{ it.name == name }!!
}
return res
}
input.forEach {
if (it.startsWith("$")) {
val (_, cmd) = it.split(" ")
if (cmd == "cd") {
val name = it.split(" ")[2]
if (name == "..") {
path.removeLast()
} else {
path.add(name)
}
}
} else {
val (dirOrSize, name) = it.split(" ")
if (dirOrSize == "dir") {
tree.getByPath(path).addChildDir(name)
} else {
tree.getByPath(path).addChildFile(name, dirOrSize.toInt())
}
}
}
calcSize(tree)
val used = tree.size
val remain = 70000000L - used
return flatTree(tree)
.filter {it.type != Type.FILE}
.sortedBy { it.size }
.first { it.size + remain >= 30000000 }
.size
}
val testInput = readInput("Day${id}_test")
check(part2(testInput) == 24933642)
val input = readInput("Day${id}")
println("==== DAY $id ====")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 73a795ed5e25bf99593c577cb77f3fcc31883d71 | 3,932 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/AsFarFromLandAsPossible.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
import kotlin.math.min
/**
* 1162. As Far from Land as Possible
* @see <a href="https://leetcode.com/problems/as-far-from-land-as-possible/">Source</a>
*/
fun interface AsFarFromLandAsPossible {
fun maxDistance(grid: Array<IntArray>): Int
}
class AsFarFromLandAsPossibleDP : AsFarFromLandAsPossible {
override fun maxDistance(grid: Array<IntArray>): Int {
val n: Int = grid.size
val m: Int = grid[0].size
var res = 0
for (i in 0 until n) {
for (j in 0 until m) {
if (grid[i][j] == 1) continue
grid[i][j] = LIMIT
if (i > 0) grid[i][j] = min(grid[i][j], grid[i - 1][j] + 1)
if (j > 0) grid[i][j] = min(grid[i][j], grid[i][j - 1] + 1)
}
}
for (i in n - 1 downTo -1 + 1) {
for (j in m - 1 downTo -1 + 1) {
if (grid[i][j] == 1) continue
if (i < n - 1) grid[i][j] = min(grid[i][j], grid[i + 1][j] + 1)
if (j < m - 1) grid[i][j] = min(grid[i][j], grid[i][j + 1] + 1)
res = max(res, grid[i][j]) // update the maximum
}
}
return if (res == LIMIT) -1 else res - 1
}
companion object {
// 201 here cuz as the description, the size won't exceed 100.
private const val LIMIT = 201
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,021 | kotlab | Apache License 2.0 |
src/Day01.kt | hoppjan | 573,053,610 | false | {"Kotlin": 9256} | fun main() {
val testLines = readInput("Day01_test")
val testResult1 = part1(testLines)
check(testResult1 == 24_000)
println("test part 1: $testResult1")
val testResult2 = part2(testLines)
check(testResult2 == 45_000)
println("test part 2: $testResult2")
val lines = readInput("Day01")
println("part 1: ${part1(lines)}")
println("part 2: ${part2(lines)}")
}
private fun part1(input: List<String>) = parseCalories(input)
.maxOf { list ->
list.sumOf { it.toInt() }
}
private fun part2(input: List<String>) = parseCalories(input)
.map { list -> list.sumOf { it.toInt() } }
.sorted()
.takeLast(3)
.sumOf { it }
private fun parseCalories(input: List<String>) =
input.joinToString(separator = "\n")
.trim()
.split("\n\n")
.map { lines -> lines.split("\n").filter { it.isNotBlank() } }
| 0 | Kotlin | 0 | 0 | f83564f50ced1658b811139498d7d64ae8a44f7e | 887 | advent-of-code-2022 | Apache License 2.0 |
src/Day01.kt | freszu | 573,122,040 | false | {"Kotlin": 32507} | fun main() {
fun part1(input: List<String>) = input.map { it.toIntOrNull() }
.fold(0 to 0) { (max, current), value ->
if (value != null) {
Pair(max, current + value)
} else {
Pair(if (current > max) current else max, 0)
}
}.first
fun part2(inputFileName: String): Int = readInputAsString(inputFileName)
.split("\n\n")
.map { it.split("\n") }
.map { elf -> elf.map { it.toIntOrNull() ?: 0 }.sum() }
.sortedDescending()
.take(3)
.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
println(part1(readInput("Day01")))
check(part2("Day01_test") == 45000)
println(part2("Day01"))
}
| 0 | Kotlin | 0 | 0 | 2f50262ce2dc5024c6da5e470c0214c584992ddb | 840 | aoc2022 | Apache License 2.0 |
day3/kt3/src/main/kotlin/Main.kt | smjackson | 470,351,294 | false | {"Kotlin": 6920, "C++": 1618} | import com.adhara.readFile
import kotlin.math.pow
fun main(args: Array<String>) {
println("--- Day 3 ---")
val input = readFile(args[0])
val numBits = input[0].trim().length
val intData = inputToInt(input, numBits)
partOne(intData, numBits)
partTwo(intData, numBits)
}
fun inputToInt(input: List<String>, numBits: Int): List<Int> {
val bins = input.map {
it.trim().toInt(2)
}
return bins
}
fun countOnes(input: List<Int>, numBits: Int, pos: Int): Int {
var total = 0;
input.forEach() { hex ->
for (i in 0..(numBits - 1)) {
if ((hex and (1 shl i)) != 0) {
total += 1
}
}
}
return total
}
fun partOne(input: List<Int>, numBits: Int) {
println(" ** Part One **")
val totals = IntArray(numBits)
input.forEach() { hex ->
for (i in 0..(numBits - 1)) {
if ((hex and (1 shl i)) != 0) {
totals[i] += 1
}
}
}
println("Number of bits: ${numBits}")
println("Number of values: ${input.size}")
println("Totals are: ${totals.contentToString()}")
var gamma: UInt = 0U
var max: UInt = (2.0).pow(numBits).toUInt() - 1U
for (i in 0..(numBits - 1)) {
if (totals[i] > (input.size / 2)) {
gamma = gamma or ((1 shl i).toUInt())
}
}
val epsilon: UInt = gamma.inv() and max
println("Gamma: ${gamma}")
println("Epsilon: ${epsilon}")
println("Power: ${gamma * epsilon}\n")
}
fun partTwo(input: List<Int>, numBits: Int) {
println(" ** Part Two **")
val o2 = findOxygen(input.toMutableList(), numBits, numBits - 7)
val co2 = findCO2(input.toMutableList(), numBits, numBits - 7)
println("O2: ${o2}")
println("CO2: ${co2}")
println("Product: ${o2 * co2}")
}
fun findOxygen(input: MutableList<Int>, numBits: Int, pos: Int): Int {
if(input.size == 1) {
return input[0]
}
var count = countOnes(input, numBits, pos)
if(count >= numBits / 2) {
// Keep values with 1 in pos
} else {
// Keep values with 0 in pos
}
return findOxygen(input, numBits, pos - 1)
}
fun findCO2(input: MutableList<Int>, numBits: Int, pos: Int): Int {
} | 0 | Kotlin | 0 | 0 | 275c278829e4374061895a4ffc27dbb2b2d7891c | 2,253 | adventofcode2021 | MIT License |
AoC2021day09-SmokeBasin/src/main/kotlin/Main.kt | mcrispim | 533,770,397 | false | {"Kotlin": 29888} | import java.io.File
class Basin(val points: MutableSet<Pair<Int, Int>> = mutableSetOf())
fun main() {
val input = File("data.txt")
val gridChar = input.readLines()
val grid = readInts(gridChar)
val lowPoints: List<Pair<Int, Int>> = getLowPoints(grid)
println ("The sum of the risk levels of all low points is ${riskLevel(lowPoints, grid)}")
val basins: List<Basin> = getBasins(lowPoints, grid)
val basinsSizes = basins.map { it.points.size }
val product = basins.map { it.points.size }.sorted().takeLast(3).fold(1) { acc, n -> acc * n}
println("The product of the size of the 3 biggest basins is $product")
}
fun getBasins(lowPoints: List<Pair<Int, Int>>, grid: MutableList<IntArray>): MutableList<Basin> {
val basins = mutableListOf<Basin>()
for ((line, col) in lowPoints) {
val basin = Basin(mutableSetOf(Pair(line, col)))
val pointsToCheck: MutableList<Pair<Int, Int>> = getNextPoints(line, col, grid).toMutableList()
while (pointsToCheck.isNotEmpty()) {
val point = pointsToCheck.removeFirst()
if (grid[point.first][point.second] != 9 && point !in basin.points) {
basin.points.add(point)
pointsToCheck.addAll(getNextPoints(point.first, point.second, grid))
}
}
basins.add(basin)
}
return basins
}
fun getNextPoints(line: Int, col: Int, grid: MutableList<IntArray>): List<Pair<Int, Int>> {
val points = mutableListOf<Pair<Int, Int>>()
if (line > 0) {
points.add(Pair(line - 1, col))
}
if (line < grid.lastIndex) {
points.add(Pair(line + 1, col))
}
if (col > 0) {
points.add(Pair(line, col - 1))
}
if (col < grid[line].lastIndex) {
points.add(Pair(line, col + 1))
}
return points
}
private fun getLowPoints(grid: MutableList<IntArray>): List<Pair<Int, Int>> {
val result = mutableListOf<Pair<Int, Int>>()
for (line in grid.indices) {
for (col in grid[line].indices) {
if (isLowPoint(grid, line, col)) {
result.add(Pair(line, col))
}
}
}
return result
}
private fun readInts(gridChar: List<String>): MutableList<IntArray> {
val grid = mutableListOf<IntArray>()
for (line in gridChar) {
val myLine = mutableListOf<Int>()
for (c in line) {
myLine.add(c.digitToInt())
}
grid.add(myLine.toIntArray())
}
return grid
}
private fun riskLevel(lowPoints: List<Pair<Int, Int>>, grid: List<IntArray>): Int {
var result = 0
for ((line, col) in lowPoints) {
val value = grid[line][col]
result += (value + 1)
}
return result
}
private fun isLowPoint(board: List<IntArray>, line: Int, col: Int): Boolean {
val value = board[line][col]
if (line > 0 && value >= board[line - 1][col]) {
return false
}
if (line < board.lastIndex && value >= board[line + 1][col]) {
return false
}
if (col > 0 && value >= board[line][col - 1]) {
return false
}
if (col < board[line].lastIndex && value >= board[line][col + 1]) {
return false
}
return true
} | 0 | Kotlin | 0 | 0 | ac4aa71c9b5955fa4077ae40fc7e3fc3d5242523 | 3,199 | AoC2021 | MIT License |
src/pl/shockah/aoc/y2021/Day12.kt | Shockah | 159,919,224 | false | null | package pl.shockah.aoc.y2021
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import pl.shockah.aoc.AdventTask
import pl.shockah.aoc.UnorderedPair
class Day12: AdventTask<Day12.Graph, Int, Int>(2021, 12) {
data class Graph(
val start: Cave,
val end: Cave,
val caves: Set<Cave>
)
data class Cave(
val name: String
) {
var connections: Set<Cave> = emptySet()
val isBig = name.uppercase() == name
}
override fun parseInput(rawInput: String): Graph {
val edges = rawInput.trim().lines().map {
val split = it.split('-')
return@map UnorderedPair(split[0].trim(), split[1].trim())
}
val caves = edges.flatMap { listOf(it.first, it.second) }.map { Cave(it) }.associateBy { it.name }
edges.forEach {
val cave1 = caves[it.first]!!
val cave2 = caves[it.second]!!
cave1.connections += cave2
cave2.connections += cave1
}
return Graph(caves["start"]!!, caves["end"]!!, caves.values.toSet())
}
private fun countPossiblePaths(end: Cave, current: Cave, caveAllowedTwice: Cave?, currentPath: List<Cave>): Int {
if (current == end)
return if (caveAllowedTwice == null) 1 else currentPath.count { it == caveAllowedTwice } / 2
return current.connections.filter { cave ->
val allowedCount = if (caveAllowedTwice == cave) 2 else 1
return@filter cave.isBig || currentPath.count { it == cave } <= allowedCount - 1
}.sumOf { countPossiblePaths(end, it, caveAllowedTwice, if (it.isBig) currentPath else currentPath + it) }
}
override fun part1(input: Graph): Int {
return countPossiblePaths(input.end, input.start, null, listOf(input.start))
}
override fun part2(input: Graph): Int {
val noRepeatCount = countPossiblePaths(input.end, input.start, null, listOf(input.start))
val withRepeatCount = input.caves
.filter { it != input.start && it != input.end && !it.isBig }
.sumOf { countPossiblePaths(input.end, input.start, it, listOf(input.start)) }
return noRepeatCount + withRepeatCount
}
class Tests {
private val task = Day12()
private val rawInput = """
start-A
start-b
A-c
A-b
b-d
A-end
b-end
""".trimIndent()
@Test
fun part1() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(10, task.part1(input))
}
@Test
fun part2() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(36, task.part2(input))
}
}
} | 0 | Kotlin | 0 | 0 | 9abb1e3db1cad329cfe1e3d6deae2d6b7456c785 | 2,379 | Advent-of-Code | Apache License 2.0 |
facebook/y2020/qual/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package facebook.y2020.qual
private fun solve(): Int {
val n = readInt()
val growsHere = mutableMapOf<Int, Int>()
val fallsHere = mutableMapOf<Int, MutableList<Int>>()
repeat(n) {
val (p, h) = readInts()
growsHere[p] = h
fallsHere.computeIfAbsent(p - h) { mutableListOf() }.add(h)
}
val best = mutableMapOf<Int, Int>()
val bestWithoutThis = mutableMapOf<Int, Int>()
for (x in (growsHere.keys + fallsHere.keys).sorted()) {
val b = best.getOrDefault(x, 0)
val bw = bestWithoutThis.getOrDefault(x, 0)
for (h in fallsHere.getOrElse(x) { mutableListOf() }) {
best[x + h] = maxOf(best.getOrDefault(x + h, 0), maxOf(b, bw) + h)
}
val h = growsHere[x] ?: continue
bestWithoutThis[x + h] = maxOf(bestWithoutThis.getOrDefault(x + h, 0), bw + h)
}
return (best.values + bestWithoutThis.values).maxOrNull()!!
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${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,090 | competitions | The Unlicense |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[104]二叉树的最大深度.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.util.*
import kotlin.math.max
//给定一个二叉树,找出其最大深度。
//
// 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
//
// 说明: 叶子节点是指没有子节点的节点。
//
// 示例:
//给定二叉树 [3,9,20,null,null,15,7],
//
// 3
// / \
// 9 20
// / \
// 15 7
//
// 返回它的最大深度 3 。
// Related Topics 树 深度优先搜索 递归
// 👍 756 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun maxDepth(root: TreeNode?): Int {
//DFS 时间复杂度 O(n)
if (root == null) return 0
return Math.max(maxDepth(root.left),maxDepth(root.right)) +1
//BFS 时间复杂度 O(n)
//遍历一层深度加一
if (root == null) return 0
val queue :LinkedList<TreeNode> = LinkedList<TreeNode>()
queue.addFirst(root)
var res = 0
while (!queue.isEmpty()){
val size = queue.size
for (i in 0 until size){
val node = queue.removeLast()
if (node.left != null) queue.addFirst(node.left)
if (node.right != null) queue.addFirst(node.right)
}
//每遍历一层加一
res++
}
return res
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,624 | MyLeetCode | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.