path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/tr/emreone/adventofcode/days/Day14.kt | EmRe-One | 434,793,519 | false | {"Kotlin": 44202} | package tr.emreone.adventofcode.days
object Day14 {
class Reindeer(val name: String, val speed: Int, val flyTime: Int, val restTime: Int) {
/**
* |__fly__|______________rest______________||__fly__|______________rest______________|
* |-----------------------seconds---------------------------|
* |-----diff------|
*
* numberOfCycles = seconds / (flyTime + restTime)
* diff = seconds - numberOfCycles * (flyTime + restTime)
*
* totalFlyTime = numberOfCycles * flyTime + (diff < flyTime ? diff : flyTime)
*/
fun totalFlyTimeAt(seconds: Int): Int {
val timeOfOnePeriod = this.flyTime + this.restTime
val numberOfCycles = seconds / timeOfOnePeriod
val diff = seconds - numberOfCycles * timeOfOnePeriod
return numberOfCycles * this.flyTime + (if (diff < this.flyTime) diff else this.flyTime)
}
companion object {
fun parse(line: String): Reindeer {
val pattern = """^(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.""".toRegex()
val (n, s, f, r) = pattern.matchEntire(line)!!.destructured
return Reindeer(n, s.toInt(), f.toInt(), r.toInt())
}
}
}
fun part1(input: List<String>, seconds: Int = 2503): Int {
val reindeers = input.map { Reindeer.parse(it) }
return reindeers.maxOf { it.totalFlyTimeAt(seconds) * it.speed }
}
fun part2(input: List<String>, seconds: Int = 2503): Int {
val reindeers = input.map { Reindeer.parse(it) }
val scoreMap = reindeers.associate { it.name to 0 }.toMutableMap()
for (second in 1..seconds) {
val distances = reindeers.associate { it.name to (it.totalFlyTimeAt(second) * it.speed) }
val leadingDistance = distances.maxOf { it.value }
distances.filter {
it.value == leadingDistance
}.forEach { (name, _) ->
scoreMap[name] = scoreMap[name]!! + 1
}
}
return scoreMap.maxOf { it.value }
}
}
| 0 | Kotlin | 0 | 0 | 57f6dea222f4f3e97b697b3b0c7af58f01fc4f53 | 2,215 | advent-of-code-2015 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem16/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem16
/**
* LeetCode page: [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/);
*/
class Solution {
/* Complexity:
* Time O(N^2) and Space O(N) where N is the size of nums;
*/
fun threeSumClosest(nums: IntArray, target: Int): Int {
val sorted = nums.clone().apply { sort() }
val maxSum = sorted.lastIndex.let { sorted[it] + sorted[it - 1] + sorted[it - 2] }
val numsTooSmall = target >= maxSum
if (numsTooSmall) return maxSum
var closestSum = maxSum
var minDistance = Math.abs(target - closestSum)
for (firstIndex in 0..sorted.size - 3) {
val minSum = sorted[firstIndex] + sorted[firstIndex + 1] + sorted[firstIndex + 2]
val canEndSearch = minSum >= target
if (canEndSearch) {
val distance = minSum - target
closestSum = if (distance < minDistance) minSum else closestSum
return closestSum
}
var secondIndex = firstIndex + 1
var thirdIndex = getThirdIndex(sorted, firstIndex, secondIndex, target)
while (secondIndex < thirdIndex) {
val sum = sorted[firstIndex] + sorted[secondIndex] + sorted[thirdIndex]
val distance = Math.abs(target - sum)
if (distance < minDistance) {
minDistance = distance
closestSum = sum
}
when {
sum > target -> thirdIndex--
sum < target -> secondIndex++
else -> return closestSum
}
}
}
return closestSum
}
private fun getThirdIndex(sorted: IntArray, firstIndex: Int, secondIndex: Int, targetSum: Int): Int {
val targetThird = targetSum - sorted[firstIndex] - sorted[secondIndex]
return sorted
.binarySearch(targetThird, secondIndex + 1)
.let { bsIndex -> if (bsIndex < 0) -(bsIndex + 1) else bsIndex }
.coerceAtMost(sorted.lastIndex)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,115 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day15.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | import java.math.BigInteger
import java.util.LinkedList
import kotlin.math.abs
data class Sensor(val x: Int, val y: Int, val bx: Int, val by: Int, val dis: Int)
fun main() {
val dx = listOf(-1, -1, -1, 0, 0, 1, 1, 1)
val dy = listOf(-1, 0, 1, -1, 1, -1, 0, 1)
fun toKey(x: Int, y: Int) = "${x}_${y}"
fun toPair(key: String) = key.split("_").let { Pair(it[0].toInt(), it[1].toInt()) }
fun getDis(ax: Int, ay: Int, bx: Int, by: Int) = abs(ax - bx) + abs(ay - by)
fun String.toSensor(): Sensor {
val x = split(":")[0].split(",")[0].split("=")[1].toInt()
val y = split(":")[0].split(",")[1].split("=")[1].toInt()
val bx = split(":")[1].split(",")[0].split("=")[1].toInt()
val by = split(":")[1].split(",")[1].split("=")[1].toInt()
return Sensor(x, y, bx, by, getDis(x, y, bx, by))
}
fun part1(input: List<String>, y: Int): Int {
val sensors = input.map { it.toSensor() }
val beaconSet = sensors.map { toKey(it.bx, it.by) }.toSet()
return (-5000000 .. 5000000).count { x ->
(toKey(x, y) !in beaconSet) && sensors.any { sen -> getDis(x, y, sen.x, sen.y) <= sen.dis }
}
}
fun part2(input: List<String>, limit: Int): String {
val sensors = input.map { it.toSensor() }
val beaconSet = sensors.map { toKey(it.bx, it.by) }.toSet()
fun okay(zx: Int, zy: Int) = sensors.all { sen -> getDis(zx, zy, sen.x, sen.y) > sen.dis }
var ansX = -1
var ansY = -1
for (sensor in sensors) {
val visited = mutableSetOf<String>()
val Q = LinkedList<String>()
val key = toKey(sensor.bx, sensor.by)
Q += key
visited += key
while (Q.isNotEmpty()) {
val top = Q.poll()
val (x, y) = toPair(top)
for (k in dx.indices) {
val zx = x + dx[k]
val zy = y + dy[k]
val zKey = toKey(zx, zy)
if (zx < 0 || zx > limit) continue
if (zy < 0 || zy > limit) continue
if (zKey in visited) continue
if (zKey in beaconSet) continue
if (getDis(sensor.x, sensor.y, zx, zy) == sensor.dis + 1) {
if (okay(zx, zy)) {
ansX = zx
ansY = zy
break
}
Q += zKey
visited += zKey
}
}
if (ansX != -1) break
}
if (ansX != -1) break
}
val result = ansX.toBigInteger() * BigInteger.valueOf(4000000) + ansY.toBigInteger()
return result.toString()
}
println(part1(readInput("data/Day15_test"), 10))
println(part1(readInput("data/Day15"), 2000000))
println(part2(readInput("data/Day15_test"), 20))
println(part2(readInput("data/Day15"), 4000000))
} | 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 2,674 | aoc-2022-in-kotlin | Apache License 2.0 |
2021/src/main/kotlin/Day22.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | class Day22(val input: List<String>) {
private var instructions = input.map { Instruction(it) }
fun solve1(): Long {
val reactor = Reactor()
return with(-50..50) {
instructions.mapNotNull { it.limit(this, this, this) }
.forEach { reactor.execute(it) }
}.let { reactor.count }
}
fun solve2(): Long {
val reactor = Reactor()
return instructions.forEach { reactor.execute(it) }.let { reactor.count }
}
private data class Instruction(var x: IntRange, var y: IntRange, var z: IntRange, var mode: InstructionMode) {
constructor(input: String) : this(0..0, 0..0, 0..0, InstructionMode.OFF) {
this.mode = if (input.startsWith("on")) InstructionMode.ON else InstructionMode.OFF
val tempInput = input.substringAfter(' ').split(',')
val (xStart, xEnd) = tempInput[0].substringAfter('=').split("..").map { it.toInt() }
val (yStart, yEnd) = tempInput[1].substringAfter('=').split("..").map { it.toInt() }
val (zStart, zEnd) = tempInput[2].substringAfter('=').split("..").map { it.toInt() }
this.x = minOf(xStart, xEnd)..maxOf(xStart, xEnd)
this.y = minOf(yStart, yEnd)..maxOf(yStart, yEnd)
this.z = minOf(zStart, zEnd)..maxOf(zStart, zEnd)
}
fun limit(x: IntRange, y: IntRange, z: IntRange): Instruction? {
val newX = this.x.center(x)
val newY = this.y.center(y)
val newZ = this.z.center(z)
if (newX.isEmpty() || newY.isEmpty() || newZ.isEmpty()) {
return null
}
val xRange = IntRange(newX.first(), newX.last())
val yRange = IntRange(newY.first(), newY.last())
val zRange = IntRange(newZ.first(), newZ.last())
return Instruction(xRange, yRange, zRange, mode)
}
fun cube(): Cube {
return Cube(x, y, z)
}
}
private enum class InstructionMode { ON, OFF }
private data class Cube(var x: IntRange, var y: IntRange, var z: IntRange) {
val volume: Long
get() = x.count().toLong() * y.count().toLong() * z.count().toLong()
fun contains(other: Cube): Boolean {
return x.containsAll(other.x) && y.containsAll(other.y) && z.containsAll(other.z)
}
fun intersects(other: Cube): Boolean {
return x.intersects(other.x) && y.intersects(other.y) && z.intersects(other.z)
}
operator fun minus(other: Cube): List<Cube> {
val xSteps = x.split(other.x)
val ySteps = y.split(other.y)
val zSteps = z.split(other.z)
val result = mutableListOf<Cube>()
xSteps.forEach { newX ->
ySteps.forEach { newY ->
zSteps.forEach { newZ ->
val newCube = Cube(newX, newY, newZ)
if (this.contains(newCube) && !newCube.intersects(other)) {
result.add(newCube)
}
}
}
}
return result
}
}
private class Reactor {
private val cubes: HashSet<Cube> = hashSetOf()
val count: Long get() = cubes.sumOf { it.volume }
fun execute(instruction: Instruction) {
if (instruction.mode == InstructionMode.ON) {
add(instruction.cube())
} else {
remove(instruction.cube())
}
}
private fun add(cube: Cube) {
if (cubes.any { it.contains(cube) }) {
return
}
cubes.filter { it.intersects(cube) }.forEach { existingCube ->
val newCubes = existingCube - cube
cubes.remove(existingCube)
cubes.addAll(newCubes)
}
cubes.add(cube)
}
private fun remove(cube: Cube) {
cubes.filter { it.intersects(cube) }.forEach { existingCube ->
val newCubes = existingCube - cube
cubes.remove(existingCube)
cubes.addAll(newCubes)
}
}
}
} | 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 4,232 | adventofcode-2021-2025 | MIT License |
common/graph/src/main/kotlin/com/curtislb/adventofcode/common/graph/WeightedGraph.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.common.graph
import com.curtislb.adventofcode.common.heap.MinimumHeap
/**
* A graph consisting of unique nodes of type [V], connected by directed edges with integer weights.
*/
abstract class WeightedGraph<V> {
/**
* An edge from one node to another in a weighted graph.
*
* @property node The destination node.
* @property weight The cost incurred by traversing this edge to the given [node].
*/
data class Edge<out T>(val node: T, val weight: Long)
/**
* Returns all weighted edges from [node] to adjacent nodes in the graph.
*/
protected abstract fun getEdges(node: V): Iterable<Edge<V>>
/**
* Returns the minimal path cost from [source] to any node in the graph for which [isGoal]
* returns `true`, using the A* path search algorithm with the given [heuristic] function.
*
* If there is no path from [source] to any goal node, this function instead returns `null`.
*
* The [heuristic] function should return an estimate of the minimal path cost from a node to
* any goal node. It *must not* return a negative value or a value that is greater than the
* minimal path cost. Otherwise, the behavior of this function is undefined.
*/
fun aStarDistance(
source: V,
heuristic: (node: V) -> Long,
isGoal: (node: V) -> Boolean
): Long? {
val distanceMap = mutableMapOf(source to 0L)
val nodeHeap = MinimumHeap<V>().apply { addOrDecreaseKey(source, heuristic(source)) }
while (!nodeHeap.isEmpty()) {
// Check the next node with the lowest f-score
val (node, _) = nodeHeap.popMinimum()
val distance = distanceMap[node]!!
if (isGoal(node)) {
return distance
}
// Update the f-score of each neighboring node
for (edge in getEdges(node)) {
val oldDistance = distanceMap[edge.node]
val newDistance = distance + edge.weight
if (oldDistance == null || oldDistance > newDistance) {
distanceMap[edge.node] = newDistance
nodeHeap.addOrDecreaseKey(edge.node, newDistance + heuristic(edge.node))
}
}
}
// Search ended without finding a goal node
return null
}
/**
* Returns the minimal path cost from [source] to any node in the graph for which [isGoal]
* returns `true`, using Dijkstra's shortest path algorithm.
*
* If there is no path from [source] to any goal node, this function instead returns `null`.
*/
fun dijkstraDistance(source: V, isGoal: (node: V) -> Boolean): Long? {
val visited = mutableSetOf<V>()
val nodeHeap = MinimumHeap<V>().apply { addOrDecreaseKey(source, 0L) }
while (!nodeHeap.isEmpty()) {
// Check the next node with the shortest distance
val (node, distance) = nodeHeap.popMinimum()
if (isGoal(node)) {
return distance
}
visited.add(node)
// Update the shortest known distance to each unvisited neighbor
for (edge in getEdges(node)) {
if (edge.node !in visited) {
val oldDistance = nodeHeap[edge.node]
val newDistance = distance + edge.weight
if (oldDistance == null || oldDistance > newDistance) {
nodeHeap.addOrDecreaseKey(edge.node, newDistance)
}
}
}
}
// Search ended without finding a goal node
return null
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 3,706 | AdventOfCode | MIT License |
src/Day16.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} | // I hate this code. Please don't look at it.
fun main() {
fun calcDistance(valveSource: String, valveDestination: String, valves: Map<String, Valve>): Int {
val active = mutableSetOf(TunnelPath(valves[valveSource]!!, 0))
val visited = mutableSetOf<Valve>()
while (active.isNotEmpty()) {
val current = active.minByOrNull { it.cost }!!
if (current.valve.name == valveDestination) {
return current.cost
}
visited.add(current.valve)
active.remove(current)
val possibilities = current.valve.tunnels.map{ valves[it]!! }.filter { !visited.contains(it) }
for(possibility in possibilities) {
val alreadyActive = active.find { it.valve == possibility }
if (alreadyActive != null) {
if (alreadyActive.cost > current.cost+1) {
active.remove(alreadyActive)
active.add(TunnelPath(possibility, current.cost+1))
}
} else {
active.add(TunnelPath(possibility, current.cost+1))
}
}
}
throw IllegalStateException("Didn't find result")
}
fun part1(input: List<String>, maxTime: Int): Int {
// Parse input
val valves = input.map {
// Remove excess words in input
it.substring(6)
.replace(" has flow rate=", ";")
.replace(" tunnels lead to valves ", "")
.replace(" tunnel leads to valve ", "")
.replace(", ", ",")
}.map {
// Parse useful input
val split = it.split(';')
Valve(split[0], split[1].toInt(), split[2].split(','))
}.associateBy { it.name }
val usefulValves = valves.filterValues { it.flow > 0 || it.name == "AA" }.values
val flowValves = usefulValves.filter { it.flow > 0 }
// println("All valves: $valves")
// println("Useful valves: $usefulValves")
// Get distance between all valves
val valveDistances = mutableMapOf<Valve, MutableMap<Valve, Int>>()
for(valveSource in usefulValves) {
valveDistances[valveSource] = mutableMapOf()
for(valveDestination in usefulValves) {
if (valveSource != valveDestination) {
//println("Calculating distance between ${valveSource.name} and ${valveDestination.name}")
val distance = calcDistance(valveSource.name, valveDestination.name, valves)
//println("Distance between ${valveSource.name} and ${valveDestination.name}: $distance")
valveDistances[valveSource]!![valveDestination] = distance + 1
}
}
}
// Build all possible paths
var valvePaths = mutableMapOf<List<Valve>, Int>()
val limitedPaths = mutableMapOf<List<Valve>, Int>()
for((valve, distances) in valveDistances.filter { (key, _) -> key.name == "AA" }) {
for((destination, distance) in distances) {
valvePaths[listOf(valve, destination)] = distance
}
}
//println(valvePaths.keys.map { it.map { v -> v.name} })
repeat(flowValves.size-1) {
val nextPaths = mutableMapOf<List<Valve>, Int>()
for((path, cost) in valvePaths) {
for(valve in flowValves) {
if (!path.contains(valve)) {
//println("Path: ${path.map {it.name}} -> ${valve.name}")
val newCost = cost + valveDistances[path.last()]!![valve]!!
if (newCost < maxTime) {
nextPaths[path + valve] = newCost
} else {
limitedPaths[path] = cost
}
}
}
}
valvePaths = nextPaths
}
val allPaths = valvePaths + limitedPaths
//println("Num possible paths: ${allPaths.size}")
// Walk paths
var maxFlow = 0
for((path, _) in allPaths) {
var currentFlow = 0
var time = 1
for(i in 0 until path.size-1) {
time += valveDistances[path[i]]!![path[i+1]]!!
val flow = path[i+1].flow
val fullTimeFlow = (maxTime-time+1) * flow
currentFlow += fullTimeFlow
//println("t=$time: Turn on ${path[i+1].name} for $flow (full time = $fullTimeFlow)")
}
maxFlow = maxOf(maxFlow, currentFlow)
}
return maxFlow
}
fun part2(input: List<String>, maxTime: Int): Int {
// Parse input
val valves = input.map {
// Remove excess words in input
it.substring(6)
.replace(" has flow rate=", ";")
.replace(" tunnels lead to valves ", "")
.replace(" tunnel leads to valve ", "")
.replace(", ", ",")
}.map {
// Parse useful input
val split = it.split(';')
Valve(split[0], split[1].toInt(), split[2].split(','))
}.associateBy { it.name }
val usefulValves = valves.filterValues { it.flow > 0 || it.name == "AA" }.values
val flowValves = usefulValves.filter { it.flow > 0 }
// println("All valves: $valves")
// println("Useful valves: $usefulValves")
// Get distance between all valves
val valveDistances = mutableMapOf<Valve, MutableMap<Valve, Int>>()
for(valveSource in usefulValves) {
valveDistances[valveSource] = mutableMapOf()
for(valveDestination in usefulValves) {
if (valveSource != valveDestination) {
//println("Calculating distance between ${valveSource.name} and ${valveDestination.name}")
val distance = calcDistance(valveSource.name, valveDestination.name, valves)
//println("Distance between ${valveSource.name} and ${valveDestination.name}: $distance")
valveDistances[valveSource]!![valveDestination] = distance + 1
}
}
}
// Build all possible paths
var valvePaths = mutableMapOf<List<Valve>, Int>()
val limitedPaths = mutableMapOf<List<Valve>, Int>()
for((valve, distances) in valveDistances.filter { (key, _) -> key.name == "AA" }) {
for((destination, distance) in distances) {
valvePaths[listOf(valve, destination)] = distance
}
}
//println(valvePaths.keys.map { it.map { v -> v.name} })
repeat(flowValves.size-1) {
val nextPaths = mutableMapOf<List<Valve>, Int>()
for((path, cost) in valvePaths) {
for(valve in flowValves) {
if (!path.contains(valve)) {
//println("Path: ${path.map {it.name}} -> ${valve.name}")
val newCost = cost + valveDistances[path.last()]!![valve]!!
if (newCost < maxTime) {
nextPaths[path + valve] = newCost
} else {
limitedPaths[path] = cost
}
}
}
}
limitedPaths += valvePaths
valvePaths = nextPaths
}
val allPaths = valvePaths + limitedPaths
val blah = allPaths.keys.map { it.map {v -> v.name} }.toSet()
//println("Num possible paths: ${allPaths.size}")
// Walk paths
var pathFlows = mutableMapOf<List<Valve>, Int>()
for((path, _) in allPaths) {
var currentFlow = 0
var time = 1
for(i in 0 until path.size-1) {
time += valveDistances[path[i]]!![path[i+1]]!!
val flow = path[i+1].flow
val fullTimeFlow = (maxTime-time+1) * flow
currentFlow += fullTimeFlow
//println("t=$time: Turn on ${path[i+1].name} for $flow (full time = $fullTimeFlow)")
}
pathFlows[path] = currentFlow
}
// Find non-overlapping path pairs, and take max
val pathsWithoutStart = pathFlows.mapKeys { (key, _) -> key.subList(1, key.size) }
val pathList = pathsWithoutStart.keys.toList()
var pairMax = 0
//println("Num to compare: ${pathList.size}")
// for(path1 in pathsWithoutStart.keys) {
// for(path2 in pathsWithoutStart.keys.filter { it.intersect(path1.toSet()).isEmpty() }) {
// pairMax = maxOf(pairMax, pathsWithoutStart[path1]!! + pathsWithoutStart[path2]!!)
// }
// }
for(i in pathList.indices) {
val path1 = pathList[i]
//if(i % 1000 == 0) println(i)
for(path2 in pathsWithoutStart.keys.filter { it.intersect(path1.toSet()).isEmpty() }) {
pairMax = maxOf(pairMax, pathsWithoutStart[path1]!! + pathsWithoutStart[path2]!!)
}
}
//println("PairMax: $pairMax")
return pairMax
}
val testInput = readInput("Day16_test")
check(part1(testInput, 30) == 1651)
check(part2(testInput, 26) == 1707)
val input = readInput("Day16")
//val time = java.util.Date().time
println(part1(input, 30))
//println("Time: ${java.util.Date().time - time}ms")
println(part2(input, 26))
}
data class Valve(
val name: String,
val flow: Int,
val tunnels: List<String>
)
data class TunnelPath(
val valve: Valve,
val cost: Int
)
| 0 | Kotlin | 0 | 0 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 9,751 | aoc2022 | Apache License 2.0 |
src/Day02.kt | diesieben07 | 572,879,498 | false | {"Kotlin": 44432} | private val file = "Day02"
private enum class RoundResult(val char: Char, val score: Int) {
LOOSE('X', 0),
DRAW('Y', 3),
WIN('Z', 6);
companion object {
fun of(char: Char): RoundResult {
return values().singleOrNull { it.char == char } ?: throw NoSuchElementException("No element for $char")
}
}
}
private enum class Hand(val charOp: Char, val charMe: Char, val score: Int) {
ROCK('A', 'X', 1),
PAPER('B', 'Y', 2),
SCISSORS('C', 'Z', 3);
fun result(op: Hand): RoundResult {
return when (ordinal - op.ordinal) {
0 -> RoundResult.DRAW
-1, 2 -> RoundResult.LOOSE
1, -2 -> RoundResult.WIN
else -> throw AssertionError()
}
}
fun myHandFor(desiredResult: RoundResult): Hand {
return values()[(ordinal + desiredResult.ordinal - 1 + 3) % 3]
}
companion object {
fun of(char: Char): Hand {
return values().singleOrNull { it.charOp == char || it.charMe == char } ?: throw NoSuchElementException("No element for $char")
}
}
}
private data class RoundData(val op: Hand, val me: Hand, val desiredResult: RoundResult) {
fun getScore(): Int {
return me.result(op).score + me.score
}
fun getScore2(): Int {
val myHand = op.myHandFor(desiredResult)
return desiredResult.score + myHand.score
}
}
private fun Sequence<String>.parseInput(): Sequence<RoundData> = map { RoundData(Hand.of(it[0]), Hand.of(it[2]), RoundResult.of(it[2])) }
private fun part1() {
streamInput(file) { input ->
println(input.parseInput().map { it.getScore() }.sum())
}
}
private fun part2() {
streamInput(file) { input ->
println(input.parseInput().map { it.getScore2() }.sum())
}
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6 | 1,845 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | hottendo | 572,708,982 | false | {"Kotlin": 41152} |
fun main() {
fun doCompleteSectionsOverlap(a: String, b: String): Boolean {
val firstElvesSections = a.split('-').map { it.toInt() }
val secondElvesSections = b.split('-').map { it.toInt() }
// Test: first elve's sections completely in second elves sections
if(firstElvesSections.first() >= secondElvesSections.first() &&
firstElvesSections.last() <= secondElvesSections.last()) {
return true
}
// Test: second elve's sections completely in first elve's sections
if(secondElvesSections.first() >= firstElvesSections.first() &&
secondElvesSections.last() <= firstElvesSections.last()) {
return true
}
return false
}
fun doPartialSectionsOverlap(a: String, b: String): Boolean {
val firstElvesSections = a.split('-').map { it.toInt() }
val secondElvesSections = b.split('-').map { it.toInt() }
// Test: first elve's sections completely in second elves sections
if(firstElvesSections.last() >= secondElvesSections.first() &&
firstElvesSections.first() <= secondElvesSections.last()) {
return true
}
return false
}
fun part1(input: List<String>): Int {
var score = 0
for(item in input) {
val sections = item.split(',')
if (doCompleteSectionsOverlap(sections.first(), sections.last())) {
score += 1
}
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for(item in input) {
val sections = item.split(',')
if (doPartialSectionsOverlap(sections.first(), sections.last())) {
score += 1
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
println("Part 1 (Test): ${part1(testInput)}")
println("Part 2 (Test): ${part2(testInput)}")
// check(part1(testInput) == 1)
val input = readInput("Day04")
println("Part 1 : ${part1(input)}")
println("Part 2 : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | a166014be8bf379dcb4012e1904e25610617c550 | 2,200 | advent-of-code-2022 | Apache License 2.0 |
src/y2022/Day25.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2022
import util.readInput
object Day25 {
private fun powersOf(n: Int) = sequence {
var p = 1L
while (true) {
yield(p)
p *= n
}
}
private val breaks = powersOf(5).runningFold(0L) { acc, p -> acc + p * 2 }.takeWhile { it < 33078355623611 }.toList()
private fun snafuToDecimal(input: String): Long {
return input.reversed().map {
when (it) {
'-' -> -1
'=' -> -2
else -> it.digitToInt()
}
}.asSequence().zip(powersOf(5)).sumOf { (digit, power) ->
digit * power
}
}
fun part1(input: List<String>): String {
val total = input.sumOf { snafuToDecimal(it) }
println("total: $total")
println("breaks: $breaks")
repeat(30) {
println("$it ->\t\t${decimalToSnafu(it.toLong())}")
}
return decimalToSnafu(total)
}
private fun decimalToSnafu(n: Long): String {
val normal = n.toString(5).reversed().map { it.digitToInt() } + 0
var carryOver = 0
return normal.map {
val new = it + carryOver
if (new > 2) {
carryOver = 1
new - 5
} else {
carryOver = 0
new
}
}.joinToString("") {
when (it) {
-2 -> "="
-1 -> "-"
else -> it.toString()
}
}.reversed()
}
}
fun main() {
val testInput = """
1=-0-2
12111
2=0=
21
2=01
111
20012
112
1=-1=
1-12
12
1=
122
""".trimIndent().split("\n")
println("------Tests------")
println(Day25.part1(testInput))
println("------Real------")
val input = readInput("resources/2022/day25")
println(Day25.part1(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,948 | advent-of-code | Apache License 2.0 |
kotlin/problems/src/solution/LeetCodeKt.kt | lunabox | 86,097,633 | false | {"Kotlin": 146671, "Python": 38767, "JavaScript": 19188, "Java": 13966} | package solution
import kotlin.math.abs
class LeetCodeKt {
fun licenseKeyFormatting(S: String, K: Int): String {
val chars = S.filter {
it != '-'
}
val buffer = StringBuilder(chars)
val step = (chars.length - K).downTo(1).step(K)
for (i in step) {
buffer.insert(i, "-")
}
return buffer.toString().toUpperCase()
}
fun fib(N: Int): Int {
var a = 0
var b = 1
repeat(N - 1) {
val c = a + b
a = b
b = c
}
return if (N == 0) 0 else b
}
fun distributeCandies(candies: IntArray): Int {
val set = HashSet<Int>()
candies.forEach {
if (it !in set) {
set.add(it)
}
}
return if (set.size >= candies.size / 2) {
candies.size / 2
} else {
set.size
}
}
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val result = ArrayList<List<Int>>()
nums.sort()
for (i in 0 until nums.size - 3) {
for (j in i + 1 until nums.size - 2) {
for (k in j + 1 until nums.size - 1) {
for (l in k + 1 until nums.size) {
if (nums[i] + nums[j] + nums[k] + nums[l] == target) {
val array = arrayListOf(nums[i], nums[j], nums[k], nums[l])
var add = true
result.forEach {
if (it[0] == nums[i] && it[1] == nums[j] && it[2] == nums[k] && it[3] == nums[l]) {
add = false
return@forEach
}
}
if (add) {
result.add(array)
}
}
}
}
}
}
return result
}
fun threeSum(nums: IntArray): List<List<Int>> {
val result = ArrayList<List<Int>>()
nums.sort()
for (i in nums.indices) {
if (i == 0 || nums[i] > nums[i - 1]) {
var l = i + 1
var r = nums.size - 1
while (l < r) {
val s = nums[i] + nums[l] + nums[r]
when {
s == 0 -> {
result.add(arrayListOf(nums[i], nums[l], nums[r]))
l++
r--
while (l < r && nums[l - 1] == nums[l]) l++
while (l < r && nums[r + 1] == nums[r]) r--
}
s > 0 -> r--
else -> l++
}
}
}
}
return result
}
/**
* https://leetcode-cn.com/problems/3sum-closest/
* 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案
*/
fun threeSumClosest(nums: IntArray, target: Int): Int {
nums.sort()
var result = nums[0] + nums[1] + nums[2]
for (i in 0 until nums.size - 2) {
for (j in i + 1 until nums.size - 1) {
for (k in j + 1 until nums.size) {
val s = nums[i] + nums[j] + nums[k]
if (abs(s - target) < abs(result - target)) {
result = s
}
}
}
}
return result
}
} | 0 | Kotlin | 0 | 0 | cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9 | 3,762 | leetcode | Apache License 2.0 |
src/Day14.kt | MatthiasDruwe | 571,730,990 | false | {"Kotlin": 47864} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
val rocks = mutableSetOf<Pair<Int, Int>>()
input.forEach { row ->
row.split(" -> ").map { point ->
val x = point.split(",")
Pair(x[0].toInt(), x[1].toInt())
}.windowed(2, 1) {
if (it[0].first == it[1].first) {
val min = min(it[0].second, it[1].second)
val max = max(it[0].second, it[1].second)
for (i in min..max) {
rocks.add(Pair(it[0].first, i))
}
}
if (it[0].second == it[1].second) {
val min = min(it[0].first, it[1].first)
val max = max(it[0].first, it[1].first)
for (i in min..max) {
rocks.add(Pair(i, it[0].second))
}
}
}
}
val maxdepth = rocks.maxOf { it.second }
var currentSand = Pair(500, 0)
var count = 0
while (currentSand.second < maxdepth) {
if (rocks.firstOrNull { it == Pair(currentSand.first, currentSand.second + 1) } == null) {
currentSand = Pair(currentSand.first, currentSand.second + 1)
} else if (rocks.firstOrNull { it == Pair(currentSand.first - 1, currentSand.second + 1) } == null) {
currentSand = Pair(currentSand.first - 1, currentSand.second + 1)
} else if (rocks.firstOrNull { it == Pair(currentSand.first + 1, currentSand.second + 1) } == null) {
currentSand = Pair(currentSand.first + 1, currentSand.second + 1)
} else {
count++
rocks.add(currentSand)
currentSand = Pair(500, 0)
}
}
return count
}
fun part2(input: List<String>): Long {
val rocks = mutableSetOf<Pair<Int, Int>>()
input.forEach { row ->
row.split(" -> ").map { point ->
val x = point.split(",")
Pair(x[0].toInt(), x[1].toInt())
}.windowed(2, 1) {
if (it[0].first == it[1].first) {
val min = min(it[0].second, it[1].second)
val max = max(it[0].second, it[1].second)
for (i in min..max) {
rocks.add(Pair(it[0].first, i))
}
}
if (it[0].second == it[1].second) {
val min = min(it[0].first, it[1].first)
val max = max(it[0].first, it[1].first)
for (i in min..max) {
rocks.add(Pair(i, it[0].second))
}
}
}
}
val maxdepth = rocks.maxOf { it.second }
var currentSand = Pair(500, 0)
var count = 0L
val indexRocks =
rocks.groupBy { it.first }.mapValues { it.value.sortedBy { it.second }.toMutableList() }.toMutableMap()
while (!rocks.contains(Pair(500, 0))) {
if (indexRocks[currentSand.first]?.contains(Pair(currentSand.first, currentSand.second + 1)) != true) {
val temp = indexRocks[currentSand.first]?.firstOrNull { it.second > currentSand.second }
currentSand = temp?.copy(second = temp.second - 1) ?: Pair(currentSand.first, maxdepth + 1)
} else if (indexRocks[currentSand.first - 1]?.contains(
Pair(
currentSand.first - 1,
currentSand.second + 1
)
) != true
) {
val temp = indexRocks[currentSand.first - 1]?.firstOrNull { it.second > currentSand.second }
currentSand = temp?.copy(second = temp.second - 1) ?: Pair(currentSand.first - 1, maxdepth + 1)
} else if (indexRocks[currentSand.first + 1]?.contains(
Pair(
currentSand.first + 1,
currentSand.second + 1
)
) != true
) {
val temp = indexRocks[currentSand.first + 1]?.firstOrNull { it.second > currentSand.second }
currentSand = temp?.copy(second = temp.second - 1) ?: Pair(currentSand.first + 1, maxdepth + 1)
} else {
count++
rocks.add(currentSand)
if (indexRocks[currentSand.first] != null) {
indexRocks[currentSand.first]?.add(currentSand)
indexRocks[currentSand.first]?.sortBy { it.second }
} else {
indexRocks[currentSand.first] = mutableListOf(currentSand)
}
currentSand = Pair(500, 0)
}
if (currentSand.second == maxdepth + 1) {
count++
rocks.add(currentSand)
if (indexRocks[currentSand.first] != null) {
indexRocks[currentSand.first]?.add(currentSand)
indexRocks[currentSand.first]?.sortBy { it.second }
} else {
indexRocks[currentSand.first] = mutableListOf(currentSand)
}
currentSand = Pair(500, 0)
}
}
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_example")
check(part1(testInput) == 24)
check(part2(testInput) == 93L)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f35f01cea5075cfe7b4a1ead9b6480ffa57b4989 | 5,717 | Advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day19.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.InputParser
enum class XMAS { X, M, A, S }
data class WorkFlowStart(val start: WorkFlow, val accepted: WorkFlow, val rejected: WorkFlow)
data class WorkFlow(val name: String, val rules: MutableList<Rule> = mutableListOf())
class Rule(val value: XMAS, val range: IntRange, val target: WorkFlow)
data class Part(val x: Int, val m: Int, val a: Int, val s: Int)
object WorkFlowParser : InputParser<Pair<WorkFlowStart, List<Part>>> {
override fun parse(input: String): Pair<WorkFlowStart, List<Part>> {
val (workflows, parts) = input.split("\n\n")
val workflowMap = mutableMapOf("A" to WorkFlow("A"), "R" to WorkFlow("R"))
workflows.split("\n").forEach { workflow ->
val name = workflow.split("{")[0]
val rules = workflow.split("{")[1].split("}")[0].split(",")
.map {
if (":" !in it) {
Rule(XMAS.X, 1..4000, workflowMap.getOrPut(it) { WorkFlow(it) })
} else {
val number = it.split(":").first().substring(2).toInt()
Rule(
value = XMAS.valueOf("${it[0]}".uppercase()),
range = if (it.contains("<")) 1 until number else number + 1..4000,
target = workflowMap.getOrPut(it.split(":").last()) { WorkFlow(it.split(":").last()) })
}
}
workflowMap.getOrPut(name) { WorkFlow(name) }.rules.addAll(rules)
}
val parsedParts = parts.split("\n").map { part ->
"(\\d+)".toRegex().findAll(part).map { it.groupValues[1] }.toList().let {
Part(it[0].toInt(), it[1].toInt(), it[2].toInt(), it[3].toInt())
}
}
return WorkFlowStart(workflowMap["in"]!!, workflowMap["A"]!!, workflowMap["R"]!!) to parsedParts
}
}
fun main() {
aoc(WorkFlowParser) {
puzzle { 2023 day 19 }
part1 { (workflow, parts) ->
parts.sumOf { part ->
var w = workflow.start
while (w.name !in listOf("A", "R")) {
w = w.rules.first { rule ->
when (rule.value) {
XMAS.X -> part.x in rule.range
XMAS.M -> part.m in rule.range
XMAS.A -> part.a in rule.range
XMAS.S -> part.s in rule.range
}
}.target
}
if (w.name == "A") part.x.toLong() + part.m + part.a + part.s else 0L
}
}
part2(submit = true) { (workflow, _) ->
data class RangedXmas(
val x: IntRange = 1..4000,
val m: IntRange = 1..4000,
val a: IntRange = 1..4000,
val s: IntRange = 1..4000,
)
val queue = ArrayDeque<Pair<RangedXmas, WorkFlow>>()
queue.add(RangedXmas() to workflow.start)
val acceptedRanges = mutableListOf<RangedXmas>()
val rejectedRanges = mutableListOf<RangedXmas>()
while (queue.isNotEmpty()) {
val (range, w) = queue.removeFirst()
if (w.name == "A") {
acceptedRanges.add(range)
continue
} else if (w.name == "R") {
rejectedRanges.add(range)
continue
}
var remainingRange = range
w.rules.forEach { rule ->
var split = if (rule.range.first == 1) rule.range.last else rule.range.first
split += (if (rule.range.last == 4000) 0 else 1)
var a: RangedXmas? = null
var b: RangedXmas? = null
when (rule.value) {
XMAS.X -> {
if (split != 4000 && split in remainingRange.x) {
a = remainingRange.copy(x = remainingRange.x.first until split)
b = remainingRange.copy(x = split..remainingRange.x.last)
}
}
XMAS.M -> {
if (split != 4000 && split in remainingRange.m) {
a = remainingRange.copy(m = remainingRange.m.first until split)
b = remainingRange.copy(m = split..remainingRange.m.last)
}
}
XMAS.A -> {
if (split != 4000 && split in remainingRange.a) {
a = remainingRange.copy(a = remainingRange.a.first until split)
b = remainingRange.copy(a = split..remainingRange.a.last)
}
}
XMAS.S -> {
if (split != 4000 && split in remainingRange.s) {
a = remainingRange.copy(s = remainingRange.s.first until split)
b = remainingRange.copy(s = split..remainingRange.s.last)
}
}
}
if (a != null && rule.range.first == 1) {
queue.add(a to rule.target)
remainingRange = b!!
} else if (b != null) {
queue.add(b to rule.target)
remainingRange = a!!
} else {
queue.add(remainingRange to rule.target)
}
}
}
val result = acceptedRanges.sumOf {
it.x.count().toLong() * it.m.count().toLong() * it.a.count().toLong() * it.s.count().toLong()
}
result
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 6,129 | aoc-2023 | The Unlicense |
src/main/kotlin/roundC2021/rockpaperscissors-testset3-solution.kt | kristofersokk | 422,727,227 | false | null | package roundC2021
fun main() {
val days = readLine()!!.toInt()
readLine()
(1..days).forEach { dayIndex ->
val (W, E) = readLine()!!.split(" ").map { it.toInt() }
println("Case #$dayIndex: ${getSequence(W, E)}")
}
}
const val SEQUENCE_LENGTH = 60
private fun getSequence(w: Int, e: Int): String {
val v = Array(SEQUENCE_LENGTH + 1) { Array(SEQUENCE_LENGTH + 1) { DoubleArray(SEQUENCE_LENGTH + 1) } }
val steps =
Array(SEQUENCE_LENGTH + 1) { Array(SEQUENCE_LENGTH + 1) { Array(SEQUENCE_LENGTH + 1) { intArrayOf(0, 0, 0) } } }
v[1][0][0] = 1.0 / 3 * (w + e)
v[0][1][0] = 1.0 / 3 * (w + e)
v[0][0][1] = 1.0 / 3 * (w + e)
steps[1][0][0] = intArrayOf(-1, 0, 0)
steps[0][1][0] = intArrayOf(0, -1, 0)
steps[0][0][1] = intArrayOf(0, 0, -1)
var bestCombination = intArrayOf(0, 0, 1)
var bestCombinationValue = v[0][0][1]
(0..SEQUENCE_LENGTH).forEach { r ->
(0..SEQUENCE_LENGTH - r).forEach { p ->
(0..SEQUENCE_LENGTH - r - p).forEach { s ->
val n = r + p + s
if (n >= 2) {
val (newValue, step) = calculateNewValue(v, r, p, s, w, e)
v[r][p][s] = newValue
steps[r][p][s] = step
if (n == SEQUENCE_LENGTH && newValue > bestCombinationValue) {
bestCombination = intArrayOf(r, p, s)
bestCombinationValue = newValue
}
}
}
}
}
return findPath(bestCombination, steps)
}
private fun calculateNewValue(
v: Array<Array<DoubleArray>>,
r: Int,
p: Int,
s: Int,
w: Int,
e: Int
): Pair<Double, IntArray> {
val n = r + p + s
return arrayOf(
(if (r > 0) v[r - 1][p][s] + p.toDouble() * w / (n - 1) + s.toDouble() * e / (n - 1) else -1.0) to intArrayOf(
-1,
0,
0
),
(if (p > 0) v[r][p - 1][s] + s.toDouble() * w / (n - 1) + r.toDouble() * e / (n - 1) else -1.0) to intArrayOf(
0,
-1,
0
),
(if (s > 0) v[r][p][s - 1] + r.toDouble() * w / (n - 1) + p.toDouble() * e / (n - 1) else -1.0) to intArrayOf(
0,
0,
-1
),
).maxByOrNull { pair -> pair.first } ?: (-1.0 to intArrayOf(0, 0, 0))
}
private fun findPath(bestCombination: IntArray, steps: Array<Array<Array<IntArray>>>): String {
var currentStep = bestCombination
val resultString = StringBuilder()
while (!currentStep.contentEquals(intArrayOf(0, 0, 0))) {
val (r, p, s) = currentStep
val (dr, dp, ds) = steps[r][p][s]
resultString.append(
when {
dr == -1 -> "R"
dp == -1 -> "P"
ds == -1 -> "S"
else -> ""
}
)
currentStep = intArrayOf(r + dr, p + dp, s + ds)
}
return resultString.toString().reversed()
}
| 0 | Kotlin | 0 | 0 | 3ebd59df60ee425b7af86a147f49361dc56ee38d | 3,000 | Google-coding-competitions | MIT License |
src/main/kotlin/day05/Day05.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day05
import readInput
fun main() {
class State(val stacks: Array<MutableList<Char>>, val allAtOnce: Boolean) {
fun move(num: Int, from: Int, to: Int) {
val buffer = ArrayDeque<Char>()
repeat(num) {
val c = stacks[from].removeLast()
if (allAtOnce) {
buffer.addFirst(c)
} else {
buffer.addLast(c)
}
}
stacks[to].addAll(buffer)
}
}
fun parse(input: List<String>, allAtOnce: Boolean): State {
val numsIndex = input.indexOfFirst { it.startsWith(" 1 ") }
val size = input[numsIndex].trim().split("\\s+".toRegex()).size
val stacks = Array<MutableList<Char>>(size) { mutableListOf() }
(0 until numsIndex)
.reversed()
.map { input[it] }
.forEach { level ->
for (i in 0 until size) {
val shift = 1 + i * 4
if (shift < level.length && level[shift] != ' ') {
stacks[i].add(level[shift])
}
}
}
return State(stacks, allAtOnce)
}
fun solve(input: List<String>, allAtOnce: Boolean): String {
val state = parse(input, allAtOnce)
val regex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
input.forEach { line ->
val match = regex.matchEntire(line)
if (match != null) {
val num = match.groups[1]!!.value.toInt()
val from = match.groups[2]!!.value.toInt() - 1
val to = match.groups[3]!!.value.toInt() - 1
state.move(num, from, to)
}
}
return state.stacks.joinToString(separator = "") { it.last().toString() }
}
fun part1(input: List<String>): String {
return solve(input, false)
}
fun part2(input: List<String>): String {
return solve(input, true)
}
val testInput = readInput("day05", "test")
val input = readInput("day05", "input")
check(part1(testInput) == "CMZ")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 2,237 | aoc2022 | Apache License 2.0 |
src/day19/Day19.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | @file:Suppress("MagicNumber")
package day19
import readInput
fun main() {
fun parse(input: List<String>): List<BluePrint> =
input.map { line ->
val sentences = line.split("""[\.:]""".toRegex()).filter { it.isNotEmpty() }.map { it.trim() }
val id = sentences[0].split(" ").last().toInt()
val oreCostOre = sentences[1].split(" ")[4].toInt()
val clayCostOre = sentences[2].split(" ")[4].toInt()
val obsidianCostOre = sentences[3].split(" ")[4].toInt()
val obsidianCostClay = sentences[3].split(" ")[7].toInt()
val geodeCostOre = sentences[4].split(" ")[4].toInt()
val geodeCostObsidian = sentences[4].split(" ")[7].toInt()
BluePrint(
id = id,
robots = mapOf(
GeodeType.ORE to listOf(Cost(GeodeType.ORE, oreCostOre)),
GeodeType.CLAY to listOf(Cost(GeodeType.ORE, clayCostOre)),
GeodeType.OBSIDIAN to
listOf(Cost(GeodeType.ORE, obsidianCostOre), Cost(GeodeType.CLAY, obsidianCostClay)),
GeodeType.GEODE to listOf(
Cost(GeodeType.ORE, geodeCostOre),
Cost(GeodeType.OBSIDIAN, geodeCostObsidian)
)
),
)
}
fun part1(input: List<String>): Int {
val bluePrints = parse(input)
val minutes = 24
val startingRobots = listOf(Robot(GeodeType.ORE))
val allQualityLevels = bluePrints.mapIndexed { i, bluePrint ->
println("check: $i")
BluePrint.currentMax = 0
val qualityLevel = bluePrint.calculateQualityLevel(startingRobots, minutes)
qualityLevel * bluePrint.id
}
.also { println(it) }.sum()
return allQualityLevels
}
fun part2(input: List<String>): Int {
val bluePrints = parse(input)
val minutes = 32
val startingRobots = listOf(Robot(GeodeType.ORE))
val allQualityLevels = bluePrints.take(3).mapIndexed { i, bluePrint ->
println("check: $i")
BluePrint.currentMax = 0
val qualityLevel = bluePrint.calculateQualityLevel(startingRobots, minutes)
qualityLevel
}
.also { println(it) }.reduce(Int::times)
return allQualityLevels
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day19/Day19_test")
val input = readInput("day19/Day19")
check((part1(testInput)).also { println(it) } == 33)
println(part1(input))
check(part2(testInput).also { println(it) } == 1)
println(part2(input))
}
data class BluePrint(
val id: Int,
val robots: Map<GeodeType, List<Cost>>
) {
private val maxTypes: Map<GeodeType, Int> = mapOf(
GeodeType.ORE to (robots.values.flatten().filter { it.type == GeodeType.ORE }.maxOfOrNull { it.cost } ?: 0),
GeodeType.CLAY to (robots.values.flatten().filter { it.type == GeodeType.CLAY }.maxOfOrNull { it.cost } ?: 0),
GeodeType.OBSIDIAN to (robots.values.flatten().filter { it.type == GeodeType.OBSIDIAN }.maxOfOrNull { it.cost }
?: 0),
)
fun calculateQualityLevel(
currentRobots: List<Robot>,
minutes: Int,
collectedGeodes: Map<GeodeType, Int> = startingCollection()
): Int {
if (minutes <= 0 || !checkCanBeBetter(minutes, currentRobots, collectedGeodes)) {
val geodeCount = collectedGeodes[GeodeType.GEODE] ?: 0
if ((geodeCount > currentMax)) {
currentMax = geodeCount
println(currentMax)
}
return geodeCount
}
val geodeCount = mutableListOf<Int>()
// buy robot
if (checkType(collectedGeodes, GeodeType.GEODE)) {
geodeCount.add(buyRobot(collectedGeodes, GeodeType.GEODE, currentRobots, minutes))
} else {
listOf(GeodeType.OBSIDIAN, GeodeType.CLAY, GeodeType.ORE).forEach { type ->
if (checkType(collectedGeodes, type) && !checkMax(type, currentRobots)) {
geodeCount.add(buyRobot(collectedGeodes, type, currentRobots, minutes))
}
}
// produce
val currentGeodes = collectedGeodes.toMutableMap()
produceGeodes(currentRobots, currentGeodes)
geodeCount.add(calculateQualityLevel(currentRobots, minutes - 1, currentGeodes))
}
return geodeCount.max()
}
private fun checkCanBeBetter(
minutes: Int,
currentRobots: List<Robot>,
collectedGeodes: Map<GeodeType, Int>
): Boolean {
val geodeRobotCount = currentRobots.count { it.type == GeodeType.GEODE }
val geodeCount = collectedGeodes[GeodeType.GEODE]!!
val generatedCount = (0 until minutes).map {
geodeRobotCount + it
}.sum()
return geodeCount + generatedCount > currentMax
}
private fun checkMax(type: GeodeType, currentRobots: List<Robot>): Boolean {
return currentRobots.count { it.type == type } >= maxTypes[type]!!
}
private fun checkType(collectedGeodes: Map<GeodeType, Int>, type: GeodeType) =
robots[type]!!.all {
it.cost <= collectedGeodes[it.type]!!
}
private fun buyRobot(
collectedGeodes: Map<GeodeType, Int>,
geode: GeodeType,
currentRobots: List<Robot>,
minutes: Int
): Int {
val currentGeodes = collectedGeodes.toMutableMap()
buyRobot(geode, currentGeodes)
produceGeodes(currentRobots, currentGeodes)
return calculateQualityLevel(
currentRobots + listOf(Robot(geode)),
minutes - 1,
currentGeodes
)
}
private fun buyRobot(geode: GeodeType, collectedGeodes: MutableMap<GeodeType, Int>) {
robots[geode]!!.forEach {
collectedGeodes[it.type] = collectedGeodes[it.type]!! - it.cost
}
}
private fun produceGeodes(
currentRobots: List<Robot>,
collectedGeodes: MutableMap<GeodeType, Int>
) {
currentRobots.forEach { robot ->
collectedGeodes[robot.type]?.let { collectedGeodes[robot.type] = it + 1 }
}
}
private fun startingCollection(): MutableMap<GeodeType, Int> =
mutableMapOf(
GeodeType.ORE to 0,
GeodeType.CLAY to 0,
GeodeType.OBSIDIAN to 0,
GeodeType.GEODE to 0,
)
companion object {
var currentMax = 0
}
}
data class Robot(
val type: GeodeType,
)
data class Cost(
val type: GeodeType,
val cost: Int,
)
enum class GeodeType {
ORE, CLAY, OBSIDIAN, GEODE
}
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 6,815 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day02.kt | Akhunzaada | 573,119,655 | false | {"Kotlin": 23755} | fun main() {
/**
A = X = Rock
B = Y = Paper
C = Z = Scissors
Score:
1 for Rock, 2 for Paper, and 3 for Scissors
0 if you lost, 3 if the round was a draw, and 6 if you won
S: Selection, R: Result
Permutations:
S R
A X = 1 + 3 = 4
A Y = 2 + 6 = 8
A Z = 3 + 0 = 3
B X = 1 + 0 = 1
B Y = 2 + 3 = 5
B Z = 3 + 6 = 9
C X = 1 + 6 = 7
C Y = 2 + 0 = 2
C Z = 3 + 3 = 6
*/
val part1Hands = mapOf(
"A X" to 4,
"A Y" to 8,
"A Z" to 3,
"B X" to 1,
"B Y" to 5,
"B Z" to 9,
"C X" to 7,
"C Y" to 2,
"C Z" to 6
)
/**
X = Lose
Y = Draw
Z = Win
S: Selection, R: Result
Permutations:
R S
A X = 0 + 3 = 3
A Y = 3 + 1 = 4
A Z = 6 + 2 = 8
B X = 0 + 1 = 1
B Y = 3 + 2 = 5
B Z = 6 + 3 = 9
C X = 0 + 2 = 2
C Y = 3 + 3 = 6
C Z = 6 + 1 = 7
*/
val part2Hands = mapOf(
"A X" to 3,
"A Y" to 4,
"A Z" to 8,
"B X" to 1,
"B Y" to 5,
"B Z" to 9,
"C X" to 2,
"C Y" to 6,
"C Z" to 7
)
fun part1(input: List<String>): Int {
return input.sumOf { part1Hands[it] ?: 0 }
}
fun part2(input: List<String>): Int {
return input.sumOf { part2Hands[it] ?: 0 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b2754454080989d9579ab39782fd1d18552394f0 | 1,880 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | orirabi | 574,124,632 | false | {"Kotlin": 14153} | data class Order(val from: Int, val to: Int, val amount: Int)
class Crates() {
/*
*
[J] [B] [T]
[M] [L] [Q] [L] [R]
[G] [Q] [W] [S] [B] [L]
[D] [D] [T] [M] [G] [V] [P]
[T] [N] [N] [N] [D] [J] [G] [N]
[W] [H] [H] [S] [C] [N] [R] [W] [D]
[N] [P] [P] [W] [H] [H] [B] [N] [G]
[L] [C] [W] [C] [P] [T] [M] [Z] [W]
1 2 3 4 5 6 7 8 9
*
* */
val crates: Map<Int, ArrayDeque<String>> = mapOf(
1 to ArrayDeque(listOf("D", "T", "W", "N", "L")),
2 to ArrayDeque(listOf("H", "P", "C")),
3 to ArrayDeque(listOf("J", "M", "G", "D", "N", "H", "P", "W")),
4 to ArrayDeque(listOf("L", "Q", "T", "N", "S", "W", "C")),
5 to ArrayDeque(listOf("N", "C", "H", "P")),
6 to ArrayDeque(listOf("B", "Q", "W", "M", "D", "N", "H", "T")),
7 to ArrayDeque(listOf("L", "S", "G", "J", "R", "B", "M")),
8 to ArrayDeque(listOf("T", "R", "B", "V", "G", "W", "N", "Z")),
9 to ArrayDeque(listOf("L", "P", "N", "D", "G", "W")),
)
fun getTops(): String {
return crates.entries.sortedBy { it.key }.map { it.value.first() }.joinToString("")
}
fun runOrder(order: Order) {
val from = crates[order.from]!!
val to = crates[order.to]!!
for (i in 1..order.amount) {
to.addFirst(from.removeFirst())
}
}
fun runBulkOrder(order: Order) {
val from = crates[order.from]!!
val to = crates[order.to]!!
val temp = ArrayDeque<String>()
for (i in 1..order.amount) {
temp.addLast(from.removeFirst())
}
to.addAll(0, temp)
}
}
fun main() {
fun parseOrder(str: String): Order {
//move 6 from 6 to 5
val split = str.split(" ")
return Order(
amount = split[1].toInt(),
from = split[3].toInt(),
to = split[5].toInt(),
)
}
fun getTopCrates(orders: List<String>): String {
val crates = Crates()
orders.asSequence()
.map(::parseOrder)
.forEach(crates::runOrder)
return crates.getTops()
}
fun getTopCratesByBulkOrder(orders: List<String>): String {
val crates = Crates()
orders.asSequence()
.map(::parseOrder)
.forEach(crates::runBulkOrder)
return crates.getTops()
}
val orders = readInput("Day05")
println(getTopCrates(orders))
println(getTopCratesByBulkOrder(orders))
}
| 0 | Kotlin | 0 | 0 | 41cb10eac3234ae77ed7f3c7a1f39c2f9d8c777a | 2,518 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/Day05.kt | ripla | 573,901,460 | false | {"Kotlin": 19599} | object Day5 {
class Command(val amount: Int, val from: Int, val to: Int)
private val commandRegex = Regex("""\d+""")
fun part1(input: List<String>): String {
val (commandLines, rest) = input.partition { it.startsWith("move") }
val stackLines = rest.dropLast(2);
val numberOfStacks = stackLines.last().length
val maxStackHeight = stackLines.size
val transposedEmptyStacks = List(numberOfStacks) { CharArray(maxStackHeight) }
val transposedStacks = stackLines
.foldIndexed(transposedEmptyStacks) { index, acc, value ->
value.toCharArray().withIndex().forEach { (stringIndex, charValue) ->
acc[stringIndex][index] = charValue
}
return@foldIndexed acc
}
.filter { !it.contains('[') && !it.contains(']') }
.filter { !it.all { char -> char == ' ' } }
.map { it -> it.filterNot { it.isWhitespace() } }
.map { it.reversed() }
.map { it.toMutableList() }
return commandLines.map { commandLine ->
val commandSplit = commandRegex.findAll(commandLine).map { it.value }.map { it.toInt() }.toList()
Command(commandSplit[0], commandSplit[1] - 1, commandSplit[2] - 1)
}.fold(transposedStacks) { stacks, command ->
(1..command.amount).forEach { _ -> stacks[command.to].add(stacks[command.from].removeLast()) }
stacks
}.map { it.last() }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val (commandLines, rest) = input.partition { it.startsWith("move") }
val stackLines = rest.dropLast(2);
val numberOfStacks = stackLines.last().length
val maxStackHeight = stackLines.size
val transposedEmptyStacks = List(numberOfStacks) { CharArray(maxStackHeight) }
val transposedStacks = stackLines
.foldIndexed(transposedEmptyStacks) { index, acc, value ->
value.toCharArray().withIndex().forEach { (stringIndex, charValue) ->
acc[stringIndex][index] = charValue
}
return@foldIndexed acc
}
.filter { !it.contains('[') && !it.contains(']') }
.filter { !it.all { char -> char == ' ' } }
.map { it -> it.filterNot { it.isWhitespace() } }
.map { it.reversed() }
.map { it.toMutableList() }
.toList()
return commandLines.map { commandLine ->
val commandSplit = commandRegex.findAll(commandLine).map { it.value }.map { it.toInt() }.toList()
Command(commandSplit[0], commandSplit[1] - 1, commandSplit[2] - 1)
}.fold(transposedStacks) { stacks, command ->
stacks[command.to].addAll(stacks[command.from].takeLast(command.amount))
(1..command.amount).forEach { _ -> stacks[command.from].removeLast() }
stacks
}.map { it.last() }.joinToString(separator = "")
}
}
| 0 | Kotlin | 0 | 0 | e5e6c0bc7a9c6eaee1a69abca051601ccd0257c8 | 3,052 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/sk/todo-revise/1531. String Compression II.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.`todo-revise`
class Solution1531 {
fun getLengthOfOptimalCompression(str: String, k: Int): Int {
fun calcLen(len: Int): Int {
return when {
len == 0 -> 0
len == 1 -> 1
len < 10 -> 2
len < 100 -> 3
else -> 4
}
}
val N = str.length
val dp = Array(N) {
Array(26) {
Array(N + 1) {
IntArray(
k + 1
) { Int.MAX_VALUE }
}
}
}
fun solve(i: Int, ch: Int, len: Int, k: Int): Int {
val space = StringBuilder()
repeat(i) {space.append(" ")}
println("$space -> i=$i, ch=${'a' + ch} , len=$len, k=$k, dp= ${dp.println(i,ch,len,k)}")
if (i == str.length) return calcLen(len)
if (dp[i][ch][len][k] == Int.MAX_VALUE) {
if (k > 0) dp[i][ch][len][k] = solve(i + 1, ch, len, k - 1)
val c = str[i] - 'a'
if (c == ch) {
dp[i][ch][len][k] = minOf(dp[i][ch][len][k], solve(i + 1, ch, len + 1, k))
} else {
dp[i][ch][len][k] = minOf(dp[i][ch][len][k], calcLen(len) + solve(i + 1, c, 1, k))
}
}
println("$space <- i=$i, ch=${'a' + ch} , len=$len, k=$k, dp= ${dp.println(i,ch,len,k)}")
return dp[i][ch][len][k]
}
return solve(0, 0, 0, k)
}
}
fun main() {
val s = Solution1531()
println(s.getLengthOfOptimalCompression("aaabbaa", 2))
}
private fun Array<Array<Array<IntArray>>>.println(i: Int, ch: Int, len: Int, k: Int): String {
return if (i== this.size) "${calcLen(len)}" else "${this[i][ch][len][k]}"
}
fun calcLen(len: Int): Int {
return when {
len == 0 -> 0
len == 1 -> 1
len < 10 -> 2
len < 100 -> 3
else -> 4
}
}
class Solution1531_2 {
private fun xs(x: Int): Int {
return when {
x == 1 -> 0
x < 10 -> 1
x < 100 -> 2
else -> 3
}
}
fun getLengthOfOptimalCompression(s: String, k: Int): Int {
val N = 127
val dp = Array(N) { IntArray(N) { -1 } }
val str = s
val n = s.length
fun solve(left: Int, k: Int): Int {
if (k < 0) return N
if (left >= n || n - left <= k) return 0
var res = dp[left][k]
if (res != -1) return res
res = N
val cnt = IntArray(26)
for (j in left until n) {
var most = 0
cnt[str[j] - 'a']++
most = cnt[str[j] - 'a']
res = minOf(res, 1 + xs(most) + solve(j + 1, k - (j - left + 1 - most)))
}
return res
}
return solve(0, k)
}
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,934 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day4.kt | hughjdavey | 433,597,582 | false | {"Kotlin": 53042} | package days
class Day4 : Day(4) {
private val numbers = inputList.first().split(",").map { it.toInt() }
override fun partOne(): Any {
return winningBoardSet(true).find { it.winningNumber != null }?.score() ?: 0
}
override fun partTwo(): Any {
return winningBoardSet(false).maxByOrNull { numbers.indexOf(it.winningNumber) }?.score() ?: 0
}
private fun winningBoardSet(firstWinner: Boolean): List<BingoCard> {
val boards = inputList.drop(2).filter { it != "" }.chunked(5).map { BingoCard(it) }
return numbers.asSequence()
.map { n -> boards.map { board -> board.check(n) } }
.takeWhile { if (firstWinner) it.all { it.winningNumber == null } else it.any { it.winningNumber == null } }
.last()
}
data class BingoCard(val grid: List<String>) {
private val rows = grid.map { it.replace(Regex("\\s+"), " ").trim().split(" ").map { BingoNumber(it.toInt()) } }
private val columns = (0..(rows.first().lastIndex)).map { rows.map { row -> row[it] } }
var winningNumber: Int? = null
fun check(n: Int): BingoCard {
rows.flatten().find { it.number == n }?.marked = true
val wins = rows.any { row -> row.all { it.marked } } || columns.any { col -> col.all { it.marked } }
if (wins && winningNumber == null) {
winningNumber = n
}
return this
}
fun score(): Int {
return rows.flatten().filterNot { it.marked }.sumOf { it.number } * winningNumber!!
}
override fun toString(): String {
return rows.map { row -> row.map { if (it.marked) "(${it.number})" else it.number } }
.joinToString("\n").plus("\n")
}
}
data class BingoNumber(val number: Int, var marked: Boolean = false)
}
| 0 | Kotlin | 0 | 0 | a3c2fe866f6b1811782d774a4317457f0882f5ef | 1,869 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/main/java/com/booknara/problem/graph/EvaluateDivisionKt.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.graph
/**
* 399. Evaluate Division (Medium)
* https://leetcode.com/problems/evaluate-division/
*/
class EvaluateDivisionKt {
// T:O(v+e), S:O(v+e)
fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray {
// build a graph for the equations
val res = DoubleArray(queries.size)
val graph = HashMap<String, ArrayList<Pair<String, Double>>>()
for (i in equations.indices) {
val first = equations[i][0]
val second = equations[i][1]
val value = values[i]
graph.putIfAbsent(first, ArrayList())
graph.putIfAbsent(second, ArrayList())
graph[first]?.add(Pair(second, value))
graph[second]?.add(Pair(first, 1.0 / value))
}
for (i in 0..queries.size - 1) {
val start = queries[i][0]
val end = queries[i][1]
res[i] = dfs(start, end, graph, HashSet())
}
return res
}
fun dfs(start: String, end: String, graph: HashMap<String, ArrayList<Pair<String, Double>>>, visited: HashSet<String>): Double {
if (!graph.containsKey(start) && !graph.containsKey(end)) {
return -1.0
}
if (start == end) {
return 1.0
}
visited.add(start)
if (graph.containsKey(start)) {
val list = graph.getValue(start)
for (i in 0..list.size - 1) {
val pair = list.get(i)
if (!visited.contains(pair.first)) {
val res = dfs(pair.first, end, graph, visited)
if (res != -1.0) {
return res * pair.second;
}
}
}
}
return -1.0
}
}
fun main(args: Array<String>) {
val equations = listOf(listOf("a", "b"), listOf("b", "c"))
val values = doubleArrayOf(2.0,3.0)
val queries = listOf(listOf("a", "c"), listOf("b", "a"), listOf("a", "e"), listOf("a", "a"), listOf("x", "x"))
val result = EvaluateDivisionKt().calcEquation(equations, values, queries)
for (r in result) {
println(r)
}
}
| 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 1,969 | playground | MIT License |
src/adventofcode/blueschu/y2017/day24/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day24
import java.io.File
import kotlin.test.assertEquals
val input: List<String> by lazy {
File("resources/y2017/day24.txt")
.bufferedReader()
.use { it.readLines() }
}
fun main(args: Array<String>) {
val exampleSegments = listOf(
"0/2",
"2/2",
"2/3",
"3/4",
"3/5",
"0/1",
"10/1",
"9/10"
)
assertEquals(31, part1(exampleSegments))
println("Part 1: ${part1(input)}")
assertEquals(19, part2(exampleSegments))
println("Part 2: ${part2(input)}")
}
typealias BridgeSegment = Pair<Int, Int>
typealias Bridge = List<BridgeSegment>
val BridgeSegment.strength get() = first + second
fun BridgeSegment.hasEnd(pins: Int): Boolean = first == pins || second == pins
fun BridgeSegment.flipped() = BridgeSegment(second, first)
infix fun BridgeSegment.matches(other: BridgeSegment): Boolean {
return first == other.first && second == other.second
|| first == other.second && second == other.first
}
fun Bridge.strength() = sumBy(BridgeSegment::strength)
fun parseBridgeSegment(token: String): BridgeSegment {
val (first, second) = token.split('/').map(String::toInt)
return BridgeSegment(first, second)
}
// RAM thirsty devil
fun findNextBridges(bridge: Bridge, segmentPool: List<BridgeSegment>): List<Bridge> {
val endPins = bridge.last().second
val validSegments = segmentPool.filter { it.hasEnd(endPins) }
.map { if (it.first == endPins) it else it.flipped() }
return if (validSegments.isEmpty()) listOf(bridge) else {
listOf(bridge) + validSegments.flatMap { next ->
findNextBridges(
bridge.plus(next),
segmentPool.filterNot { it matches next }
)
}
}
}
fun part1(segmentDesc: List<String>): Int {
val segments = segmentDesc.map { parseBridgeSegment(it) }
val bridges = findNextBridges(listOf(BridgeSegment(0,0)), segments)
return bridges.map(Bridge::strength).max()
?: throw IllegalArgumentException("No possible bridges for the specified segments")
}
fun part2(segmentDesc: List<String>): Int {
val segments = segmentDesc.map { parseBridgeSegment(it) }
val bridges: List<Bridge> = findNextBridges(
listOf(BridgeSegment(0, 0)),
segments
)
val maxLength = bridges.map(Bridge::size).max()
?: throw IllegalArgumentException("No possible bridges for the specified segments")
return bridges.filter { it.size == maxLength }.map(Bridge::strength).max()!!
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 2,586 | Advent-Of-Code | MIT License |
src/Day07.kt | flexable777 | 571,712,576 | false | {"Kotlin": 38005} | import java.util.*
fun main() {
data class File(
val name: String,
val size: Long,
)
data class Folder(
val name: String,
val folders: MutableSet<Folder> = mutableSetOf(),
val files: MutableSet<File> = mutableSetOf(),
)
fun Folder.size(): Long {
var totalSize = folders.sumOf { it.size() }
totalSize += files.sumOf { file ->
file.size
}
return totalSize
}
fun getAllFolders(folder: Folder): MutableSet<Folder> {
val folders = mutableSetOf<Folder>()
folders.addAll(folder.folders.map {
getAllFolders(it)
}.flatten())
folders += folder.folders
return folders
}
fun readFileSystem(input: List<String>): Stack<Folder> {
val folderStack = Stack<Folder>()
input.forEach { line ->
when {
//listing of folder contents
!line.startsWith("$") -> {
val (filename, filesize) = line.split(" ")
if (filename != "dir") {
folderStack.peek().files += File(name = filesize, size = filename.toLong())
}
}
//Change directory
line.startsWith("$ cd") -> {
val (_, _, folderName) = line.split(" ")
if (folderName == "..") {
folderStack.pop()
} else {
if (folderStack.isEmpty()) {
folderStack += Folder(name = folderName)
} else {
if (!folderStack.peek().folders.any { it.name == folderName }) {
with(Folder(name = folderName)) {
folderStack.peek().folders += this
folderStack.push(this)
}
} else {
folderStack.push(folderStack.peek().folders.first { it.name == folderName })
}
}
}
}
}
}
return folderStack
}
fun part1(input: List<String>): Long =
getAllFolders(readFileSystem(input).first()).filter { folder ->
folder.size() <= 100_000
}.sumOf { f ->
f.size()
}
fun part2(input: List<String>): Long {
val folderStack = readFileSystem(input)
val free = 70000000 - folderStack.first().size()
val missing = 30000000 - free
val sortedFoldersBySize = getAllFolders(folderStack.first()).filter { folder ->
folder.size() >= missing
}.sortedBy { f ->
f.size()
}
return sortedFoldersBySize.first().size()
}
val testInput = readInputAsLines("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInputAsLines("Day07")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
} | 0 | Kotlin | 0 | 0 | d9a739eb203c535a3d83bc5da1b6a6a90a0c7bd6 | 3,152 | advent-of-code-2022 | Apache License 2.0 |
Array/cuijilin/Array0604.kt | JessonYue | 268,215,243 | false | null | package luge
/*
2020.06.4
面试题 10.01. 合并排序的数组 //https://leetcode-cn.com/problems/sorted-merge-lcci/
给定两个排序后的数组 A 和 B,其中 A 的末端有足够的缓冲空间容纳 B。 编写一个方法,将 B 合并入 A 并排序。
初始化 A 和 B 的元素数量分别为 m 和 n。
示例:
输入:
A = [1,2,3,0,0,0], m = 3
B = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
说明:
A.length == n + m*/
fun main() {
var arrayA = intArrayOf(4, 6, 8, 0, 0, 0, 0, 0)
var arrayB = intArrayOf(2, 3, 4, 5, 6)
merge(arrayA, 3, arrayB, arrayB.size)?.forEachIndexed { index, i ->
print("$i,")
}
}
// 最直观的方法是先将数组 B 放进数组 A 的尾部,然后直接对整个数组进行排序。不考虑
// 双指针法:利用了数组有序的特性
fun merge(A: IntArray, m: Int, B: IntArray, n: Int): IntArray {
var indexA = m - 1
var indexB = n - 1
var cur = m + n - 1
while (indexA > -1 && indexB > -1) {
if (A[indexA] > B[indexB]) {
A[cur--] = A[indexA--]
} else {
A[cur--] = B[indexB--]
}
}
while (indexB > -1) {
A[indexB] = B[indexB]
indexB--
}
return A
}
| 0 | C | 19 | 39 | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | 1,240 | LeetCodeLearning | MIT License |
src/Day18.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} | @file:Suppress("PackageDirectoryMismatch")
package day18
import readInput
data class Cube(val x: Int, val y: Int, val z: Int)
fun Cube.connected(c: Cube) =
x == c.x && y == c.y && (z == c.z-1 || z == c.z+1) ||
y == c.y && z == c.z && (x == c.x-1 || x == c.x+1) ||
z == c.z && x == c.x && (y == c.y-1 || y == c.y+1)
fun String.toCube(): Cube {
val (x,y,z) = split(',').map{ it.toInt() }
return Cube(x,y,z)
}
fun part1(lines: List<String>): Int {
val cubes = lines.map { it.toCube() }
var faces = cubes.size * 6
cubes.forEachIndexed { i, cube ->
for (j in i+1 .. cubes.lastIndex)
if (cube.connected(cubes[j])) faces-=2
}
return faces
}
enum class Face(val dx: Int=0, val dy: Int=0, val dz: Int=0) {
LEFT(dx=-1), RIGHT(dx=+1), UP(dy=-1), DOWN(dy=+1), FRONT(dz=+1), BACK(dz=-1)
}
fun Cube.connectedBy(f: Face) = Cube(x+f.dx, y+f.dy, z+f.dz)
fun Cube.around() = Face.values().map{ connectedBy(it) }
class Cubes(lines: List<String>) {
val list = lines.map { it.toCube() }
val all = list.toSet()
val minX = list.minOf { it.x }
val maxX = list.maxOf { it.x }
val minY = list.minOf { it.y }
val maxY = list.maxOf { it.y }
val minZ = list.minOf { it.z }
val maxZ = list.maxOf { it.z }
fun Cube.isValid() = x in minX-1 .. maxX+1 && y in minY-1 .. maxY+1 && z in minZ-1 .. maxZ+1
}
fun part2(lines: List<String>): Int = with( Cubes(lines) ) {
val outside = mutableSetOf<Cube>()
val open = mutableListOf( Cube(minX-1,minY-1,minZ-1) ) // Assume is outside
var faces = 0
while (open.isNotEmpty()) {
val c = open.removeFirst()
outside.add(c)
c.around().forEach { a ->
if ( a in all ) faces++
else
if (a.isValid() && a !in outside && a !in open)
open.add(a)
}
}
faces
}
fun main() {
val testInput = readInput("Day18_test")
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18")
println(part1(input)) // 3526
println(part2(input)) // 2090
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 2,114 | aoc2022 | Apache License 2.0 |
src/main/year_2017/day23/day23.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package year_2017.day23
import readInput
import second
val registers = mutableMapOf(
'a' to 0,
'b' to 0,
'c' to 0,
'd' to 0,
'e' to 0,
'f' to 0,
'g' to 0,
'h' to 0,
)
fun part1(input: List<String>): Int {
val instructions = input.map(String::toInstruction)
return runInstructions(instructions)
}
private fun runInstructions(instructions: List<Instruction>): Int {
var counter = 0
var index = 0
while (index in instructions.indices) {
print("index $index, counter $counter \r")
val instruction = instructions[index]
when (instruction.command) {
"set" -> {
registers[instruction.x] = if (instruction.yIsNumber()) instruction.y.toInt() else registers[instruction.y.first()]!!
index++
}
"sub" -> {
registers[instruction.x] =
registers[instruction.x]!! - if (instruction.yIsNumber()) instruction.y.toInt() else registers[instruction.y.first()]!!
index++
}
"mul" -> {
registers[instruction.x] =
registers[instruction.x]!! * if (instruction.yIsNumber()) instruction.y.toInt() else registers[instruction.y.first()]!!
counter++
index++
}
"jnz" -> {
val v = if (instruction.x.isDigit()) instruction.x.digitToInt() else registers[instruction.x]!!
if (v != 0) index += instruction.y.toInt()
else index++
}
else -> error("unknown instruction ${instruction.command}")
}
}
return counter
}
fun part2(input: List<String>): Int {
val start = input.first().split(" ")[2].toInt() * 100 + 100000
return (start..start + 17000 step 17).count {
!it.toBigInteger().isProbablePrime(5)
}
}
fun main() {
val input = readInput("main/year_2017/day23/Day23")
println(part1(input))
println(part2(input))
}
fun String.toInstruction(): Instruction {
return this.split(" ").let {
Instruction(command = it.first(), x = it.second().first(), y = it[2])
}
}
data class Instruction(val command: String, val x: Char, val y: String) {
fun yIsNumber() = y.first().isDigit() || y.first() == '-'
}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 2,318 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day12.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2021
import se.saidaspen.aoc.util.Day
fun main() = Day12.run()
private const val VST = "visitedSmallCaveOnce"
object Day12 : Day(2021, 12) {
override fun part1(): Any {
val paths = input.lines()
.flatMap { listOf(it.split("-")[0] to it.split("-")[1], it.split("-")[1] to it.split("-")[0]) }
.groupBy { it.first }
.mapValues { it.value.map { li -> li.second } }
.toMap()
val queue = mutableListOf<List<String>>()
queue.add(listOf("start"))
var fullPaths = 0
while (queue.isNotEmpty()) {
val curr = queue.removeAt(0)
if (curr.last() == "end") {
fullPaths++
continue
}
val candidates =
paths[curr.last()]!!.filter { it == it.toUpperCase() || !curr.contains(it) }.toMutableList()
queue.addAll(candidates.map {
val neighbour = curr.toMutableList()
neighbour.add(it)
neighbour
})
}
return fullPaths
}
override fun part2(): Any {
val paths = input.lines()
.flatMap { listOf(it.split("-")[0] to it.split("-")[1], it.split("-")[1] to it.split("-")[0]) }
.groupBy { it.first }
.mapValues { it.value.map { li -> li.second } }
.toMap()
val queue = mutableListOf<List<String>>()
queue.add(listOf("start"))
var fullPaths = 0
while (queue.isNotEmpty()) {
val curr = queue.removeAt(0)
if (curr.last() == "end") {
fullPaths++
continue
}
val candidates = paths[curr.last()]!!.filter { it != "start" }.filter {
it == it.toUpperCase()
|| (!curr.contains(it))
|| (curr.count { n -> n == it } == 1 && curr[0] == "start")
}
val neighbours = candidates.map {
val neighbour = curr.toMutableList()
neighbour.add(it)
if (neighbour[0] == "start" && neighbour.filter { n -> n != n.toUpperCase() }.groupingBy { n -> n }
.eachCount()
.map { n -> n.value }.any { n -> n == 2 }) {
neighbour.add(0, VST)
}
neighbour
}
queue.addAll(neighbours)
}
return fullPaths
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,514 | adventofkotlin | MIT License |
src/Day08/Solution.kt | cweinberger | 572,873,688 | false | {"Kotlin": 42814} | package Day08
import readInput
fun main() {
fun parseInput(input: List<String>) : List<List<Int>> {
return input.map { line ->
line.map { it.digitToInt() }
}
}
fun isVisible1D(input: List<Int>, targetIndex: Int) : Boolean {
if(targetIndex == 0 || targetIndex == input.size-1) return true
val value = input[targetIndex]
val listBefore = input.subList(0, targetIndex)
val listAfter = input.subList(targetIndex+1, input.size)
return listBefore.all { it < value } || listAfter.all { it < value }
}
fun isVisible2D(input: List<List<Int>>, targetRow: Int, targetCol: Int) : Boolean {
val row = input[targetRow]
val col = input.map { it[targetCol] }
return isVisible1D(row, targetCol) || isVisible1D(col, targetRow)
}
fun Boolean.toInt() = if (this) 1 else 0
fun getViewingDistance1D(input: List<Int>, targetIndex: Int) : Int {
val value = input[targetIndex]
val listBefore = input.subList(0, targetIndex)
val listAfter = input.subList(targetIndex+1, input.size)
val listBeforeClearView = listBefore.reversed().toMutableList().dropWhile { it < value }
val listAfterClearView = listAfter.toMutableList().dropWhile { it < value }
val distanceBefore = listBefore.count() - listBeforeClearView.count() + listBeforeClearView.isNotEmpty().toInt()
val distanceAfter = listAfter.count() - listAfterClearView.count() + listAfterClearView.isNotEmpty().toInt()
return distanceBefore * distanceAfter
}
fun getViewingDistance2D(input: List<List<Int>>, targetRow: Int, targetCol: Int) : Int {
val row = input[targetRow]
val col = input.map { it[targetCol] }
return getViewingDistance1D(row, targetCol) * getViewingDistance1D(col, targetRow)
}
fun part1(input: List<String>): Int {
val parsedInput = parseInput(input)
return parsedInput
.mapIndexed { rowIndex, row ->
row.mapIndexed { colIndex, col ->
isVisible2D(parsedInput, rowIndex, colIndex)
}
}
.flatten()
.count { it }
}
fun part2(input: List<String>): Int {
val parsedInput = parseInput(input)
return parsedInput
.mapIndexed { rowIndex, row ->
row.mapIndexed { colIndex, col ->
getViewingDistance2D(parsedInput, rowIndex, colIndex)
}
}
.flatten().maxOf { it }
}
val testInput = readInput("Day08/TestInput")
val input = readInput("Day08/Input")
println("\n=== Part 1 - Test Input ===")
println(part1(testInput))
println("\n=== Part 1 - Final Input ===")
println(part1(input))
println("\n=== Part 2 - Test Input ===")
println(part2(testInput))
println("\n=== Part 2 - Final Input ===")
println(part2(input))
// println("1,2: ${getViewingDistance2D(parseInput(testInput), 1, 2)}")
// println("3,2: ${getViewingDistance2D(parseInput(testInput), 3, 2)}")
}
| 0 | Kotlin | 0 | 0 | 883785d661d4886d8c9e43b7706e6a70935fb4f1 | 3,109 | aoc-2022 | Apache License 2.0 |
kotlin/15.kt | NeonMika | 433,743,141 | false | {"Kotlin": 68645} | class Day15 : Day<Graph<Pair<Int, Int>>>("15") {
override fun dataStar1(lines: List<String>): Graph<Pair<Int, Int>> {
val arr = TwoDimensionalArray(lines.ints(""))
val edges = arr.map2DIndexed { row, col, _ ->
arr.getHorizontalAndVerticalNeighbors(row, col)
.map { neighbor -> Edge(row to col, neighbor.row to neighbor.col, arr[neighbor.row, neighbor.col]) }
}.flatMap { it }
val g = Graph(edges)
return g
}
override fun dataStar2(lines: List<String>): Graph<Pair<Int, Int>> {
val firstList = lines.map { line ->
line.ints("") +
line.ints("").map { it + 1 } +
line.ints("").map { it + 2 } +
line.ints("").map { it + 3 } +
line.ints("").map { it + 4 }
}.map { line -> line.map { if (it >= 10) it - 9 else it } }
val list = (firstList +
firstList.map { it.map { it + 1 } } +
firstList.map { it.map { it + 2 } } +
firstList.map { it.map { it + 3 } } +
firstList.map { it.map { it + 4 } })
.map { line -> line.map { if (it >= 10) it - 9 else it } }
val arr = TwoDimensionalArray(list)
val edges = arr.map2DIndexed { row, col, _ ->
arr.getHorizontalAndVerticalNeighbors(row, col)
.map { neighbor -> Edge(row to col, neighbor.row to neighbor.col, arr[neighbor.row, neighbor.col]) }
}.flatMap { it }
val g = Graph(edges)
return g
}
override fun star1(data: Graph<Pair<Int, Int>>): Int {
val path =
data.dijkstra(data.nodes[0 to 0]!!).paths[data.nodes.values.maxByOrNull { it.data.first * 10 + it.data.second }!!]!!
return path.sumOf { e -> e.weight }
}
override fun star2(data: Graph<Pair<Int, Int>>): Int {
return star1(data)
}
}
fun main() {
Day15()()
} | 0 | Kotlin | 0 | 0 | c625d684147395fc2b347f5bc82476668da98b31 | 1,952 | advent-of-code-2021 | MIT License |
src/Day02.kt | riFaulkner | 576,298,647 | false | {"Kotlin": 9466} | fun main() {
fun part1(input: List<String>): Int {
val scorePerRound = input.map {round ->
val opponentChoice = getChoiceValue(round.subSequence(0, 1).toString())
val myChoice = getChoiceValue(round.subSequence(2,3).toString())
scoreRound(opponentChoice, myChoice)
}
return scorePerRound.sum()
}
fun part2(input: List<String>): Int {
val scorePerRound = input.map {round ->
val opponentChoice = getChoiceValue(round.subSequence(0, 1).toString())
val myChoice = generateMyChoice(opponentChoice, round.subSequence(2,3).toString())
scoreRound(opponentChoice, myChoice)
}
return scorePerRound.sum()
}
runTests()
val testInput = readInput("inputs/Day02-example")
part1(testInput).println()
part2(testInput).println()
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("inputs/Day02")
part1(input).println()
part2(input).println()
}
fun runTests() {
readInput("inputs/Day02-tests").forEach {round ->
val opponentChoice = getChoiceValue(round.subSequence(0, 1).toString())
val myChoice = getChoiceValue(round.subSequence(2,3).toString())
val expectedScore = round.subSequence(4, 5).toString().toInt()
check(scoreRound(opponentChoice, myChoice) == expectedScore)
}
}
fun getChoiceValue(choice: String): Int {
return when (choice) {
"A", "X" -> {
1
}
"B", "Y" -> {
2
}
"C", "Z" -> {
3
}
else -> throw IllegalArgumentException("Invalid entry")
}
}
fun generateMyChoice(oppChoiceValue: Int, outcomeRequired: String): Int {
/**
* X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win.
*
* X = -1
* Y = 0
* Z = +1
*/
val choice = when(outcomeRequired) {
"X" -> oppChoiceValue-1
"Y" -> oppChoiceValue
"Z" -> oppChoiceValue + 1
else -> throw IllegalArgumentException("Invalid input")
}
if (choice == 0) {
return 3
}
if (choice == 4) {
return 1
}
return choice
}
fun scoreRound(oppChoiceValue: Int, myChoiceValue: Int): Int {
/**
* The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors)
* plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won).
*/
var roundScoring = myChoiceValue
if (oppChoiceValue == myChoiceValue) {
roundScoring += 3
}
if ((oppChoiceValue + 1) % 3 == myChoiceValue % 3) {
roundScoring += 6
}
return roundScoring
} | 0 | Kotlin | 0 | 0 | 33ca7468e17c47079fe2e922a3b74fd0887e1b62 | 2,797 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2020/Day16.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2020
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
class Day16 : AdventDay(2020, 16) {
val rangesReg = """(\d+)-(\d+)""".toRegex()
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day16()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun findValidRanges(input: List<String>): Map<String, Sequence<IntRange>> {
return input.map {
val key = it.substringBefore(":")
val ranges = rangesReg.findAll(it).map {
IntRange(it.groupValues[1].toInt(), it.groupValues[2].toInt())
}
key to ranges
}.toMap()
}
fun parseRanges(input: String): Map<String, Sequence<IntRange>> {
val ranges = input.substringBefore("your ticket").trim().lines()
return findValidRanges(ranges)
}
fun parseTickets(input: String): List<Ticket> {
return input.substringAfter("nearby tickets:").trim().lines().map { Ticket(it) }
}
fun solvePart1(input: String): Int {
val rules = parseRanges(input).values.asSequence().flatten()
val tickets = parseTickets(input)
return tickets.flatMap { it.invalidNumbers(rules) }.sum()
}
fun findProductOfDepartureCols(placements: Map<String, Int>, ticket: Ticket): Long {
return placements.entries.filter { it.key.startsWith("departure") }.map { (_k, v) ->
ticket.numbers[v]
}.product()
}
fun solvePart2(input: String): Long {
val rules = parseRanges(input)
val myTicket = Ticket(input.substringAfter("your ticket:").lines().drop(1).first())
val tickets = parseTickets(input).filter { it.isValid(rules.values.asSequence().flatten()) }
val rulesToPlace = performIntersection(rules, myTicket, tickets)
val placements = findMinima(rulesToPlace)
return findProductOfDepartureCols(placements, myTicket)
}
fun findMinima(rulesToPlace: List<Set<String>>): Map<String, Int> {
val map = rulesToPlace.mapIndexed { idx, e -> idx to e }.toMap()
return map.entries.sortedBy { it.value.size }.fold(emptyMap<String, Int>()) { r, rule ->
val remainingKeys = rule.value - r.keys
r.plus(remainingKeys.first() to rule.key)
}
}
fun performIntersection(
rules: Map<String, Sequence<IntRange>>,
myTicket: Ticket,
tickets: List<Ticket>
): List<Set<String>> {
return tickets.fold(myTicket.validRules(rules)) { ruleSet, ticket ->
ticket.validRules(rules).mapIndexed { idx, otherRuleset ->
otherRuleset.intersect(ruleSet[idx])
}
}
}
fun part1(): Int {
return solvePart1(inputAsString)
}
fun part2(): Long {
return solvePart2(inputAsString)
}
data class Ticket(val numbers: List<Int>) {
constructor(ticketString: String) : this(
numbers = ticketString.split(",").map { it.toInt() }
)
fun invalidNumbers(validRanges: Sequence<IntRange>): List<Int> {
return numbers.filter { ticketNumber -> validRanges.none { ticketNumber in it } }
}
fun isValid(validRanges: Sequence<IntRange>): Boolean {
return numbers.all { ticketNumber -> validRanges.any { ticketNumber in it } }
}
fun validRules(rules: Map<String, Sequence<IntRange>>): List<Set<String>> {
return numbers.map { number ->
rules.entries.filter {
it.value.any { number in it }
}.map { it.key }.toSet()
}
}
}
}
fun List<Int>.product(): Long = this.fold(1) { acc, e -> acc * e }
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 3,838 | adventofcode | MIT License |
src/Day14.kt | karloti | 573,006,513 | false | {"Kotlin": 25606} | import kotlin.math.absoluteValue
import kotlin.math.sign
class Day14(private val input: Sequence<String>) {
private val String.numbers get() = Regex("(\\d+)").findAll(this).map { it.groupValues[1].toInt() }
private val directions = listOf(Point(0, 1), Point(-1, 1), Point(1, 1))
val yLine by lazy { initCoordinates.maxOf { it.y } }
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
operator fun minus(other: Point) = Point(x - other.x, y - other.y)
}
private fun Point.drawTo(other: Point): Sequence<Point> {
val vector = other - this
val direction = Point(vector.x.sign, vector.y.sign)
val length = maxOf(vector.x.absoluteValue, vector.y.absoluteValue)
return List(length) { direction }.runningFold(this, Point::plus).asSequence()
}
val initCoordinates: Set<Point> = input
.map { it.numbers.chunked(2) { (x, y) -> Point(x, y) }.zipWithNext { a, b -> a.drawTo(b) }.flatten() }
.flatten()
.toSet()
fun solution(maxLine: Int, failure: Boolean): Int {
val coordinates = initCoordinates.toMutableSet()
val wallSize = coordinates.size
val start = Point(500, 0)
while (true) {
val nextPoint: Point = generateSequence(start) { p: Point ->
directions.firstOrNull { (p + it) !in coordinates }?.plus(p)
}.takeWhile { it.y <= maxLine }.last()
when {
nextPoint == start -> { coordinates += nextPoint; break }
nextPoint.y == maxLine && failure -> break
}
coordinates += nextPoint
}
return coordinates.size - wallSize
}
}
fun main() = Day14(readInputAsSequence("Day14")).run {
check(solution(maxLine = yLine, failure = true).also(::println) == 994)
check(solution(maxLine = yLine + 1, failure = false).also(::println) == 26283)
} | 0 | Kotlin | 1 | 2 | 39ac1df5542d9cb07a2f2d3448066e6e8896fdc1 | 1,956 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day11.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2022
import com.dvdmunckhof.aoc.toDeque
class Day11(private val input: List<String>) {
fun solvePart1() = solve(20, false)
fun solvePart2() = solve(10_000, true)
fun solve(rounds: Long, alternativeLevelManagement: Boolean): Long {
val monkeys = input.windowed(6, 7)
.map { lines ->
val operationParts = lines[2].substringAfter("= ").split(" ")
val operationValue1 = operationParts[0].toLongOrNull()
val operationValue2 = operationParts[2].toLongOrNull()
val operation = when (operationParts[1]) {
"*" -> OperationMultiply(operationValue1, operationValue2)
"+" -> OperationAddition(operationValue1, operationValue2)
else -> error("Unknown operator")
}
val startingItems = lines[1].substringAfter(": ").split(", ").map(String::toLong).toDeque()
val test = lines[3].substringAfterLast(" ").toLong()
val testTrue = lines[4].substringAfterLast(" ").toInt()
val testFalse = lines[5].substringAfterLast(" ").toInt()
Monkey(startingItems, operation, test, testTrue, testFalse)
}
val commonDenominator = monkeys.fold(1L) { acc, monkey -> acc * monkey.testDivider }
for (round in 1..rounds) {
for (monkey in monkeys) {
while (monkey.items.isNotEmpty()) {
val currentLevel = monkey.items.removeFirst()
val tmpLevel = monkey.operation.apply(currentLevel)
val newLevel = if (alternativeLevelManagement) tmpLevel % commonDenominator else tmpLevel / 3
val monkeyIndex = if (newLevel % monkey.testDivider == 0L) monkey.indexTrue else monkey.indexFalse
monkeys[monkeyIndex].items += newLevel
monkey.handledItemCount++
}
}
}
return monkeys.sortedBy { it.handledItemCount }
.takeLast(2)
.fold(1L) { acc, monkey -> acc * monkey.handledItemCount }
}
private data class Monkey(
val items: ArrayDeque<Long>,
val operation: Operation,
val testDivider: Long,
val indexTrue: Int,
val indexFalse: Int,
) {
var handledItemCount: Long = 0
}
private sealed class Operation(private val a: Long?, private val b: Long?) {
fun apply(old: Long): Long = apply(a ?: old, b ?: old)
abstract fun apply(a: Long, b: Long): Long
}
private class OperationAddition(a: Long?, b: Long?) : Operation(a, b) {
override fun apply(a: Long, b: Long) = a + b
}
private class OperationMultiply(a: Long?, b: Long?) : Operation(a, b) {
override fun apply(a: Long, b: Long) = a * b
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 2,891 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day4.kt | i-redbyte | 433,743,675 | false | {"Kotlin": 49932} | const val SIZE = 5
typealias BingoGame = Pair<List<Int>, MutableList<Board>>
private fun make(lines: List<String>): BingoGame {
val numbers = lines[0].split(",").map { it.toInt() }
val boards = mutableListOf<Board>()
var line = 2
while (line < lines.size) {
boards.add(
Board.create(
lines[line],
lines[line + 1],
lines[line + 2],
lines[line + 3],
lines[line + 4]
)
)
line += 6 // space
}
return numbers to boards
}
fun main() {
val data = readInputFile("day4")
fun part1(): Int {
val (calls, boards) = make(data)
var result = 0
for (num in calls) {
val victor = boards.find { it.suchMeaning(num) }
if (victor != null) {
result = victor.getScores(num)
break
}
}
return result
}
fun part2(): Int {
val (calls, boards) = make(data)
var result = 0
for ((i, num) in calls.withIndex()) {
val victors = boards.filter { it.suchMeaning(num) }
victors.forEach { boards.remove(it) }
if (boards.size == 0 || i == calls.size - 1) {
result = victors.last().getScores(num)
break
}
}
return result
}
println("Part1 ${part1()}")
println("Part2 ${part2()}")
}
class Board(numbers: List<Int>) {
private val rows = Array(SIZE) {
mutableSetOf(
numbers[SIZE * it],
numbers[SIZE * it + 1],
numbers[SIZE * it + 2],
numbers[SIZE * it + 3],
numbers[SIZE * it + 4]
)
}
private val cols = Array(SIZE) {
mutableSetOf(
numbers[it],
numbers[it + SIZE],
numbers[it + 10],
numbers[it + 15],
numbers[it + 20]
)
}
fun suchMeaning(value: Int): Boolean {
rows.forEach { it.remove(value) }
cols.forEach { it.remove(value) }
return rows.any { it.isEmpty() } || cols.any { it.isEmpty() }
}
fun getScores(num: Int): Int {
return rows.flatMap { it.toList() }.sum() * num
}
companion object {
fun create(vararg raw: String): Board =
Board(raw.joinToString(" ").trim().split("\\s+".toRegex()).map { it.toInt() })
}
}
| 0 | Kotlin | 0 | 0 | 6d4f19df3b7cb1906052b80a4058fa394a12740f | 2,442 | AOC2021 | Apache License 2.0 |
src/Day07.kt | rdbatch02 | 575,174,840 | false | {"Kotlin": 18925} | import java.util.*
interface FileSystemObject {
val name: String
}
fun main() {
data class File(
override val name: String,
val size: Int
): FileSystemObject
data class Directory(
override val name: String,
val contents: MutableMap<String, FileSystemObject> = mutableMapOf(),
val parentDir: Directory? = null
): FileSystemObject {
fun getSize(): Int {
return contents.map {
if (it.value is Directory) {
(it.value as Directory).getSize()
} else {
(it.value as File).size
}
}.sum() ?: 0
}
}
fun parseFileSystem(input: List<String>): Directory {
val dirStack: Stack<String> = Stack()
// val fileSystem: MutableMap<String, FileSystemObject> = mutableMapOf("/" to Directory("/", mutableMapOf()))
val rootDirectory = Directory("/")
var currentDirectory: Directory = rootDirectory
input.subList(1, input.size).forEach {terminalOutput -> // Skip the first command which cd's into root
val outputArray = terminalOutput.split(" ")
if (outputArray.first() == "$") { // Parsing a command
if (outputArray[1] == "cd") { // change dir
if (outputArray.last() == "..") { // Up dir
dirStack.pop()
currentDirectory = currentDirectory.parentDir ?: currentDirectory // Don't go up if we're at the root
}
else { // Down dir
val newDirName = outputArray.last()
dirStack.push(newDirName)
currentDirectory = currentDirectory.contents?.get(newDirName) as Directory
}
}
// else would be ls which is effectively a no-op for state
}
else { // Parsing a file or directory
val objectName = outputArray.last()
if (outputArray.first() == "dir") { // Parsing a directory
val newDir = Directory(objectName, parentDir = currentDirectory)
currentDirectory.contents[objectName] = newDir
}
else { // Parsing a file
val newFile = File(objectName, outputArray.first().toInt())
currentDirectory.contents[objectName] = File(objectName, outputArray.first().toInt())
}
}
}
return rootDirectory
}
fun sumDirSizesUnderThreshold(threshold: Int, dir: Directory): Int {
var sizeUnderThreshold = 0
if (dir.getSize() <= threshold) {
sizeUnderThreshold += dir.getSize()
}
dir.contents.values.filterIsInstance<Directory>().forEach {
sizeUnderThreshold += sumDirSizesUnderThreshold(threshold, it)
}
return sizeUnderThreshold
}
fun part1(input: List<String>): Int {
val rootDirectory = parseFileSystem(input)
return sumDirSizesUnderThreshold(100000, rootDirectory)
}
fun findSmallestDirectoryAboveThreshold(threshold: Int, dir: Directory): Directory {
var smallestDirSeen = dir
dir.contents.values.filterIsInstance<Directory>().forEach {
val smallestChildDir = findSmallestDirectoryAboveThreshold(threshold, it)
if (smallestChildDir.getSize() > threshold && smallestChildDir.getSize() < smallestDirSeen.getSize()) {
smallestDirSeen = smallestChildDir
}
}
return smallestDirSeen
}
fun part2(input: List<String>): Int {
// Delete at least 30000000 in a single directory
val totalSpace = 70000000
val updateSize = 30000000
val rootDirectory = parseFileSystem(input)
val freeSpace = totalSpace - rootDirectory.getSize()
println("Free space - " + freeSpace)
val neededSpace = updateSize - freeSpace
println("Need - " + neededSpace)
return findSmallestDirectoryAboveThreshold(neededSpace, rootDirectory).getSize()
}
val input = readInput("Day07")
println("Part 1 - " + part1(input))
println("Part 2 - " + part2(input))
}
| 0 | Kotlin | 0 | 1 | 330a112806536910bafe6b7083aa5de50165f017 | 4,278 | advent-of-code-kt-22 | Apache License 2.0 |
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day21/Day21.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2020.day21
import eu.janvdb.aocutil.kotlin.MatchFinder
import eu.janvdb.aocutil.kotlin.readLines
val INGREDIENT_LIST_REGEX = Regex("([^()]+) \\(contains ([^()]+)\\)")
fun main() {
val recipes = readRecipes()
val ingredients = recipes.getIngredients().toList()
val allergens = recipes.getAllergens().toList()
val ingredientByAllergen =
MatchFinder.findMatch(allergens, ingredients) { allergen, ingredient -> recipes.matches(ingredient, allergen) }
val ingredientsWithoutAllergen = ingredients.minus(ingredientByAllergen.values)
val occurrencesOfIngredientsWithoutAllergen = ingredientsWithoutAllergen.map { ingredient ->
recipes.recipes.count { recipe -> recipe.ingredients.contains(ingredient) }
}.sum()
println(occurrencesOfIngredientsWithoutAllergen)
val ingredientsWithAllergenSorted = allergens.sorted().map { ingredientByAllergen[it] }.joinToString(separator = ",")
println(ingredientsWithAllergenSorted)
}
fun readRecipes(): Recipes {
return Recipes(
readLines(2020, "input21.txt")
.map { INGREDIENT_LIST_REGEX.matchEntire(it)!! }
.map { Recipe(it.groupValues[1].split(" ").toSet(), it.groupValues[2].split(", ").toSet()) }
)
}
data class Recipe(val ingredients: Set<String>, val allergens: Set<String>)
data class Recipes(val recipes: List<Recipe>) {
fun getIngredients(): Set<String> = recipes.flatMap { it.ingredients }.toSet()
fun getAllergens(): Set<String> = recipes.flatMap { it.allergens }.toSet()
fun matches(ingredient: String, allergen: String): Boolean {
for (recipe in recipes) {
if (recipe.allergens.contains(allergen) && !recipe.ingredients.contains(ingredient)) return false
}
return true
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 1,682 | advent-of-code | Apache License 2.0 |
src/main/kotlin/algo/expert/solutions/medium/MinCoinsForChange.kt | swstack | 329,129,910 | false | null | package algo.expert.solutions.medium
import java.lang.Integer.min
// Solution: Dynamic programming
fun minNumberOfCoinsForChange(n: Int, denoms: List<Int>): Int {
val coins = IntArray(n + 1) { -1 }
coins[0] = 0
for (d in denoms.sorted()) {
for (i in 1 until coins.size) {
if (d <= i) {
val remaining = i - d
val remainingCoins = coins[remaining]
if (remainingCoins != -1) {
if (coins[i] == -1) {
coins[i] = 1 + remainingCoins
} else {
coins[i] = min(coins[i], 1 + remainingCoins)
}
}
}
}
}
return coins[n]
}
// Solution: Build a tree of all possible combinations -- very inefficient
class TreeNode(var value: Int) {
var children: MutableList<TreeNode> = mutableListOf()
}
fun minNumberOfCoinsForChangeTreeNaive(n: Int, denoms: List<Int>): Int {
val root = buildTree(TreeNode(n), denoms)
val shortest = findShortestBranchEqualToZero(root, 0)
return shortest
}
fun buildTree(node: TreeNode, denoms: List<Int>): TreeNode {
for (d in denoms) {
if (node.value - d >= 0) {
node.children.add(TreeNode(node.value - d))
}
}
for (c in node.children) {
buildTree(c, denoms)
}
return node
}
fun findShortestBranchEqualToZero(node: TreeNode, depth: Int): Int {
if (node.value == 0) {
return depth
}
if (node.children.isEmpty()) {
return Integer.MAX_VALUE
}
val lengths = mutableListOf<Int>()
for (c in node.children) {
lengths.add(findShortestBranchEqualToZero(c, depth + 1))
}
return lengths.min()!!
}
// Solution: Build optimized tree (without using actual tree data structure)
// - Build out the tree breadth-first
// - Stop on the first branch to equal 0 instead of building out the entire tree
// - Stop building branches < 0
fun minNumberOfCoinsForChangeTreeOptimized(n: Int, denoms: List<Int>): Int {
return treeOptimizedHelper(listOf(n), denoms, 1)
}
fun treeOptimizedHelper(row: List<Int>, denoms: List<Int>, depth: Int): Int {
if (row.isEmpty()) {
return Integer.MAX_VALUE
}
val nextRow = mutableListOf<Int>()
for (node in row) {
for (d in denoms) {
if (node - d == 0) {
return depth
}
if (node - d > 0) {
nextRow.add(node - d)
}
}
}
return treeOptimizedHelper(nextRow, denoms, depth + 1)
} | 0 | Kotlin | 0 | 0 | 3ddad9724ed022d87a47a664b4c87f37cac0b61f | 2,599 | algo-expert-solutions | MIT License |
src/main/kotlin/day18.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.getText
fun main() {
val input = getText("day18.txt")
println(day18A(input))
println(day18B(input))
}
fun day18A(input: String): Int {
val grid = input.lines().map { line ->
line.split(",").map { it.toInt() }.let { XYZ(it[0], it[1], it[2]) }
}
return grid.sumOf {
it.sides().count { side -> !grid.contains(side) }
}
}
fun day18B(input: String): Int {
val lava = input.lines().map { line ->
line.split(",").map { it.toInt() }.let { XYZ(it[0], it[1], it[2]) }
}
val minX = lava.minOf { it.x }
val maxX = lava.maxOf { it.x }
val minY = lava.minOf { it.y }
val maxY = lava.maxOf { it.y }
val minZ = lava.minOf { it.z }
val maxZ = lava.maxOf { it.z }
return lava.sumOf { cube ->
cube.sides().count { side ->
!lava.contains(side) && dfsSearchWater(side, lava,minX..maxX, minY..maxY, minZ..maxZ)
}
}
}
fun dfsSearchWater(start: XYZ, lava: List<XYZ>, x: IntRange, y: IntRange, z: IntRange): Boolean {
val explored = mutableListOf<XYZ>()
val queue = mutableSetOf(start)
while (queue.isNotEmpty()) {
val check = queue.last()
queue.remove(check)
if(!x.contains(check.x) || !y.contains(check.y) || !z.contains(check.z)) return true
explored.add(check)
queue.addAll(check.sides().filter { !explored.contains(it) && !lava.contains(it) })
}
return false
}
data class XYZ(val x: Int, val y: Int, val z: Int) {
fun sides(): List<XYZ> {
return listOf(
XYZ(x - 1, y, z),
XYZ(x, y - 1, z),
XYZ(x, y, z - 1),
XYZ(x + 1, y, z),
XYZ(x, y + 1, z),
XYZ(x, y, z + 1),
)
}
} | 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 1,744 | AdventOfCode2022 | MIT License |
gcj/y2022/round3/c_small.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2022.round3
private fun solve(letters: String = "ACDEHIJKMORST"): String {
val n = readInt()
val exits = List(2) { readInts().map { it - 1 } }
val dist1 = List(n) { v -> listOf(exits[0][v], exits[1][v]) }
val dist2 = List(n) { v -> val d1 = dist1[v]; dist1[d1[0]] + dist1[d1[1]] }
val dist12 = List(n) { v -> dist1[v] + dist2[v] }
for (i in 0 until n) {
if (i in dist2[i]) return "IMPOSSIBLE"
}
val ans = IntArray(n) { -1 }
val forbid = List(n) { mutableSetOf<Int>() }
for (i in 0 until n) {
val fi = forbid[i]
for (j in dist12[i]) fi.add(ans[j])
ans[i] = letters.indices.first { it !in fi }
for (j in dist12[i]) forbid[j].add(ans[i])
}
return ans.map { letters[it] }.joinToString("")
}
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 | 982 | competitions | The Unlicense |
puzzles/kotlin/src/tan-network/tan-network.kt | charlesfranciscodev | 179,561,845 | false | {"Python": 141140, "Java": 34848, "Kotlin": 33981, "C++": 27526, "TypeScript": 22844, "C#": 22075, "Go": 12617, "JavaScript": 11282, "Ruby": 6255, "Swift": 3911, "Shell": 3090, "Haskell": 1375, "PHP": 1126, "Perl": 667, "C": 493} | import java.util.Scanner
import java.util.Stack
fun main(args : Array<String>) {
val network = Network()
network.readGameInput()
network.solve()
}
class Stop(val id: String, val fullName: String, val latitude: Double, val longitude: Double) {
val routes = ArrayList<String>()
fun distance(other: Stop): Double {
val x = (other.longitude - longitude) * Math.cos((latitude + other.latitude) / 2)
val y = other.latitude - latitude
return Math.hypot(x, y) * 6371
}
}
class Network {
var start: String = ""
var end: String = ""
val stops = HashMap<String, Stop>()
fun readGameInput() {
val input = Scanner(System.`in`)
start = input.next() // start id
end = input.next() // end id
val nbStops = input.nextInt()
if (input.hasNextLine()) {
input.nextLine()
}
for (i in 0 until nbStops) {
val line = input.nextLine().split(",")
val id = line[0]
val fullName = line[1].replace("\"", "")
val latitude = Math.toRadians(line[3].toDouble())
val longitude = Math.toRadians(line[4].toDouble())
val stop = Stop(id, fullName, latitude, longitude)
stops[id] = stop
}
val nbRoutes = input.nextInt()
if (input.hasNextLine()) {
input.nextLine()
}
for (i in 0 until nbRoutes) {
val route = input.nextLine().split(" ")
val id1 = route[0]
val id2 = route[1]
stops[id1]?.routes?.add(id2)
}
}
// Compute the shortest path between start and end using A*
// Reference: https://en.wikipedia.org/wiki/A*_search_algorithm
fun search(startId: String, endId: String): Map<String, String>? {
val startStop = stops[startId]
val endStop = stops[endId]
val closedSet = HashSet<String>() // set of ids already evaluated
val openSet = HashSet<String>() // set of discovered ids that are not evaluated yet
val parents = HashMap<String, String>()
val gScores = HashMap<String, Double>()
val fScores = HashMap<String, Double>()
openSet.add(startId)
gScores[startId] = 0.0
if (startStop != null && endStop != null) fScores[startId] = hCost(startStop, endStop)
while (openSet.isNotEmpty()) {
val minId = min(openSet, fScores)
if (minId == endId) return parents // search is done
val minStop = stops[minId] ?: break
openSet.remove(minId)
closedSet.add(minId)
for (neighborId in minStop.routes) {
if (!closedSet.contains(neighborId)) {
if (!openSet.contains(neighborId)) openSet.add(neighborId)
val neighborStop = stops[neighborId]
var gScore = gScores.getOrDefault(minId, Double.MAX_VALUE)
if (neighborStop != null) gScore += minStop.distance(neighborStop)
if (gScore < gScores.getOrDefault(neighborId, Double.MAX_VALUE)) {
parents[neighborId] = minId
gScores[neighborId] = gScore
if (neighborStop != null && endStop != null) fScores[neighborId] = gScore + hCost(neighborStop, endStop)
}
}
}
}
return null
}
fun min(openSet: Set<String>, fScores: Map<String, Double>): String {
var minId = openSet.first()
var minFScore = Double.MAX_VALUE
for (id in openSet) {
val fScore = fScores.getOrDefault(id, Double.MAX_VALUE)
if (fScore < minFScore) {
minId = id
minFScore = fScore
}
}
return minId
}
fun hCost(currentStop: Stop, endStop: Stop): Double {
return currentStop.distance(endStop)
}
fun solve() {
if (start == end) {
println(stops[start]?.fullName)
return
}
val parents = search(start, end)
var currentId = end
val stack = Stack<String>()
if (parents == null) {
println("IMPOSSIBLE")
return
}
while (parents.containsKey(currentId)) {
stack.push(currentId)
currentId = parents.getOrDefault(currentId, "")
}
stack.push(currentId)
while (stack.isNotEmpty()) {
println(stops[stack.pop()]?.fullName)
}
}
}
| 0 | Python | 19 | 45 | 3ec80602e58572a0b7baf3a2829a97e24ca3460c | 4,013 | codingame | MIT License |
src/com/github/crunchynomnom/aoc2022/puzzles/Day08.kt | CrunchyNomNom | 573,394,553 | false | {"Kotlin": 14290, "Shell": 518} | package com.github.crunchynomnom.aoc2022.puzzles
import Puzzle
import java.io.File
import java.lang.Integer.max
class Day08 : Puzzle() {
private lateinit var forest: List<List<Tree>>
override fun part1(input: File) {
forest = input.readLines().map { x -> x.map { Tree(it.code) }.toList()}
for (y in 0 until forest.size) {
traverseEast(0, y, 0)
}
for (x in 0 until forest[0].size) {
traverseSouth(x, 0, 0)
}
println(forest.sumOf { it.count { it.exposed } })
}
override fun part2(input: File) {
forest = input.readLines().map { x -> x.map { Tree(it.code) }.toList()}
for (y in 1 until forest.size-1) {
for (x in 1 until forest[0].size-1) {
forest[x][y].uVision = getVision(x, y, y-1 downTo 0, true).also { print("$it ") }
forest[x][y].dVision = getVision(x, y, y+1 until forest.size, true).also { print("$it ") }
forest[x][y].lVision = getVision(x, y, x-1 downTo 0, false).also { print("$it ") }
forest[x][y].rVision = getVision(x, y, x+1 until forest[0].size, false).also { print("$it ") }
}
}
println(forest.maxOf { it.maxOf { tree -> tree.dVision * tree.uVision * tree.rVision * tree.lVision } })
}
private fun traverseSouth(x: Int, y: Int, highestSoFar: Int): Int = traverse(x, y, highestSoFar, true)
private fun traverseEast(x: Int, y: Int, highestSoFar: Int): Int = traverse(x, y, highestSoFar, false)
// returns highest from the direction towards the traversing is conducted
private fun traverse(x: Int, y: Int, highestSoFar: Int, goesDown: Boolean): Int {
if (forest[x][y].height > highestSoFar) {
forest[x][y].exposed = true
}
var returned = 0
if (goesDown) {
if (y + 1 == forest[0].size) {
forest[x][y].exposed = true
return forest[x][y].height
}
returned = traverseSouth(x, y + 1, max(highestSoFar, forest[x][y].height))
} else {
if (x + 1 == forest[0].size) {
forest[x][y].exposed = true
return forest[x][y].height
}
returned = traverseEast(x + 1, y, max(highestSoFar, forest[x][y].height))
}
forest[x][y].exposed = x == 0 || y == 0 || forest[x][y].exposed || returned < forest[x][y].height
return max(forest[x][y].height, returned)
}
private fun getVision(x: Int, y: Int, range: IntProgression, vertical: Boolean): Int {
var count = 0
for (i in range) {
count++
if (vertical && (forest[x][i].height >= forest[x][y].height)) break
if (!vertical && (forest[i][y].height >= forest[x][y].height)) break
}
return count
}
data class Tree(
val height: Int,
var dVision: Int = 0,
var uVision: Int = 0,
var rVision: Int = 0,
var lVision: Int = 0,
var exposed: Boolean = false
) {
override fun toString(): String = "${height - '0'.code} ${if (exposed) "." else "H"}"
}
}
| 0 | Kotlin | 0 | 0 | 88bae9c0ce7f66a78f672b419e247cdd7374cdc1 | 3,171 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | Totwart123 | 573,119,178 | false | null | fun main() {
data class Node(
var visited:Boolean = false,
val height:Int = -1,
var distance: Int = Int.MAX_VALUE,
val neighbors: MutableList<Node> = mutableListOf()
)
fun visitNext(nodeList: List<List<Node>>){
val node = nodeList.flatten().filter { !it.visited && it.distance != Int.MAX_VALUE }.minByOrNull { it.distance }
if(node != null){
node.neighbors.filter { !it.visited && it.height <= node.height + 1 }.forEach {
if(it.distance > node.distance + 1){
it.distance = node.distance + 1
}
}
node.visited = true
visitNext(nodeList)
}
}
fun addNeigbours(nodes: List<List<Node>>){
for(i in nodes.indices){
for(j in nodes[i].indices){
if(i > 0){
nodes[i][j].neighbors.add(nodes[i-1][j])
}
if(j < nodes[i].size - 1){
nodes[i][j].neighbors.add(nodes[i][j + 1])
}
if(i < nodes.size - 1){
nodes[i][j].neighbors.add(nodes[i+1][j])
}
if(j > 0){
nodes[i][j].neighbors.add(nodes[i][j-1])
}
}
}
}
fun part1(input: List<String>): Int {
val nodes = input.map { line ->
line.map {
val height = if(it == 'S') 0 else if (it == 'E') 25 else it.code - 97
Node(height = height)
}
}
var start: Pair<Int, Int> = Pair(-1, -1)
var end: Pair<Int, Int> = Pair(-1, -1)
input.forEachIndexed { i, line ->
line.forEachIndexed { j, c ->
if(c == 'S'){
start = Pair(i,j)
}
if( c == 'E'){
end = Pair(i, j)
}
}
}
addNeigbours(nodes)
nodes[start.first][start.second].distance = 0
visitNext(nodes)
return nodes[end.first][end.second].distance
}
fun part2(input: List<String>): Int {
val nodes = input.map { line ->
line.map {
val height = if(it == 'S') 0 else if (it == 'E') 25 else it.code - 97
Node(height = height)
}
}
val possibleStarts: MutableList<Pair<Int, Int>> = mutableListOf()
var end: Pair<Int, Int> = Pair(-1, -1)
input.forEachIndexed { i, line ->
line.forEachIndexed { j, c ->
if(c == 'S'){
possibleStarts.add(Pair(i,j))
}
if( c == 'E'){
end = Pair(i, j)
}
if(c == 'a'){
possibleStarts.add(Pair(i,j))
}
}
}
addNeigbours(nodes)
var minSteps = Int.MAX_VALUE
possibleStarts.forEach {start ->
nodes.flatten().forEach {
it.distance = Int.MAX_VALUE
it.visited = false
}
nodes[start.first][start.second].distance = 0
visitNext(nodes)
val steps = nodes[end.first][end.second].distance
minSteps = if(minSteps > steps) steps else minSteps
}
return minSteps
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 33e912156d3dd4244c0a3dc9c328c26f1455b6fb | 3,594 | AoC | Apache License 2.0 |
src/Day05.kt | MT-Jacobs | 574,577,538 | false | {"Kotlin": 19905} | import java.util.Queue
fun main() {
fun part1(input: List<String>): String {
return getJob(input).run {
instructions.map { it.run {
repeat(count) {
stacks[destIndex].addFirst(stacks[sourceIndex].removeFirst())
}
} }
stacks.map { it.first() }.toCharArray().concatToString()
}
}
fun part2(input: List<String>): String {
return getJob(input).run {
instructions.map { it.run {
val liftedStack: List<Char> = sequence {
repeat(count) {
yield(stacks[sourceIndex].removeFirst())
}
}.toList().reversed()
liftedStack.forEach { box ->
stacks[destIndex].addFirst(box)
}
} }
stacks.map { it.first() }.toCharArray().concatToString()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
val part1Result = part1(testInput)
check(part1Result == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
fun getJob(input: List<String>): JobSetup {
val cratesInput: List<String> = input.takeWhile { it != "" }
val instructionsInput: List<String> = input.subList(cratesInput.size+1, input.size)
val stacks: List<ArrayDeque<Char>> = cratesInput.toCrateStacks()
val instructions: List<Instruction> = instructionsInput.map {
val words = it.split(' ')
Instruction(
count = words[1].toInt(),
// Converting number to 0-indexing
sourceIndex = words[3].toInt() - 1,
destIndex = words[5].toInt() - 1,
)
}
return JobSetup(stacks, instructions)
}
data class JobSetup(
val stacks: List<ArrayDeque<Char>>,
val instructions: List<Instruction>,
)
data class Instruction(
val count: Int,
val sourceIndex: Int,
val destIndex: Int,
)
fun List<String>.toCrateStacks(): List<ArrayDeque<Char>> {
val cratesOnly: List<String> = this.dropLast(1)
return this.last()
.toList()
.mapIndexed { index, c -> index to c }
.mapNotNull { (index, c) ->
c.digitToIntOrNull()?.let { index }
}.map { crateColumPosition ->
cratesOnly.mapNotNull {
crateRow -> crateRow.getOrNull(crateColumPosition).takeUnless { it == ' ' }
}.toCollection(ArrayDeque())
}
} | 0 | Kotlin | 0 | 0 | 2f41a665760efc56d531e56eaa08c9afb185277c | 2,598 | advent-of-code-2022 | Apache License 2.0 |
src/day23/Day23.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | package day23
import containsAny
import readInput
enum class Direction(val vec: Position) {
N(Position(-1, 0)),
NE(Position(-1, 1)),
E(Position(0, 1)),
SE(Position(1, 1)),
S(Position(1, 0)),
SW(Position(1, -1)),
W(Position(0, -1)),
NW(Position(-1, -1));
companion object {
// steps are counted from 1
fun considerationSequence(step: Int): List<Direction> {
return when (step % 4) {
1 -> listOf(N, S, W, E)
2 -> listOf(S, W, E, N)
3 -> listOf(W, E, N, S)
0 -> listOf(E, N, S, W)
else -> {
throw Exception("Kek, step % 4 is ${step % 4}")
}
}
}
fun directionsToCheckWhenLookingAt(direction: Direction): List<Direction> {
return when (direction) {
N -> listOf(NW, N, NE)
S -> listOf(SW, S, SE)
W -> listOf(NW, W, SW)
E -> listOf(NE, E, SE)
else -> throw Exception("Requesting direction check for $direction")
}
}
}
}
data class Position(val row: Int, val column: Int) {
operator fun plus(other: Position): Position {
return Position(row + other.row, column + other.column)
}
operator fun minus(other: Position): Position {
return Position(row - other.row, column - other.column)
}
fun area(): Int {
return row * column
}
fun neigbours(): List<Position> {
return Direction.values().map { x -> x.vec + this }
}
fun neigbours(direction: Direction): List<Position> {
return Direction.directionsToCheckWhenLookingAt(direction).map { x -> x.vec + this }
}
}
typealias State = Set<Position>
fun State.part1Answer(): Int {
return (bottomRight() - topLeft() + Position(1, 1)).area() - this.size
}
fun State.topLeft(): Position {
return Position(this.minOf { x -> x.row }, this.minOf { x -> x.column })
}
fun State.bottomRight(): Position {
return Position(this.maxOf { x -> x.row }, this.maxOf { x -> x.column })
}
fun State.normalized(): State {
return this.map { x -> x - this.topLeft() }.toSet()
}
fun State.proposition(elf: Position, considerationSequence: List<Direction>): Position? {
if (!this.containsAny(elf.neigbours())) {
return null
}
for (direction in considerationSequence) {
if (!this.containsAny(elf.neigbours(direction))) {
return elf + direction.vec
}
}
return null
}
fun State.nextWith(considerationSequence: List<Direction>): State? {
val movingElves = this
.asSequence()
.map { x -> x to proposition(x, considerationSequence) }
.filter { x -> x.second != null }
.groupBy { x -> x.second }
.filter { x -> x.value.size == 1 }
.map { x -> x.value[0]}
.toList().toMap()
// println("Number of moving elves: ${movingElves.size}")
if (movingElves.isEmpty()) {
return null
}
val nextState = mutableSetOf<Position>()
for (elf in this) {
if (elf in movingElves) {
nextState.add(movingElves[elf]!!)
} else {
nextState.add(elf)
}
}
return nextState
}
fun readState(input: List<String>): State {
val state = mutableSetOf<Position>()
for (row in input.indices) {
for (column in input[row].indices) {
if (input[row][column] == '#') {
state.add(Position(row, column))
}
}
}
return state
}
fun simulate(startState: State, startStep: Int, numberOfSteps: Int): State {
var state = startState
for (step in startStep until startStep + numberOfSteps) {
// print("step $step: ")
state = state.nextWith(Direction.considerationSequence(step)) ?: state
}
return state
}
fun simulateUntilEnd(startState: State): Int {
var current = startState
var stepOfNextState = 1
var next = current.nextWith(Direction.considerationSequence(stepOfNextState))
while (next != null) {
current = next
stepOfNextState += 1
next = current.nextWith(Direction.considerationSequence(stepOfNextState))
}
return stepOfNextState
}
fun prettyPrintState(state: State) {
for (row in 0..5) {
for (column in 0..4) {
if (state.contains(Position(row, column))) {
print("#")
} else {
print(".")
}
}
println()
}
}
fun testSimulation(testData: List<Pair<Int, State>>) {
for (i in 0 until testData.size - 1) {
val (startStep, startState) = testData[i]
val (endStep, endState) = testData[i + 1]
val simulatedState = simulate(startState, startStep + 1, endStep - startStep)
if (endState != simulatedState) {
println("Simulating $startStep to $endStep starting with")
prettyPrintState(startState)
println("Expected state")
prettyPrintState(endState)
println("Simulated State")
prettyPrintState(simulatedState)
throw Exception("Simulation is wrong")
}
}
}
fun parseTestData(input: List<String>): List<Pair<Int, State>> {
var stateMap = mutableListOf<String>()
val testData = mutableListOf<Pair<Int, State>>()
for (line in input) {
if (line.toIntOrNull() == null) {
stateMap.add(line)
} else {
testData.add(line.toInt() to readState(stateMap))
stateMap = mutableListOf()
}
}
return testData
}
fun testSimulationToEnd(startState: State, steps: Int) {
val simulatedSteps = simulateUntilEnd(startState)
if (simulatedSteps != steps) {
throw Exception("Simulation took $simulatedSteps instead of $steps")
}
}
fun countStepsBetween(startState: State, endState: State, threshold: Int): Int {
var state = startState
var step = 1
while (step < threshold && state.normalized() != endState.normalized()) {
state = state.nextWith(Direction.considerationSequence(step))!!
step += 1
}
return step - 1
}
fun testCountSteps(startState: State, endState: State, expectedSteps: Int, threshold: Int) {
val steps = countStepsBetween(startState, endState, threshold)
if (steps != expectedSteps) {
throw Exception("Steps is $steps instead of $expectedSteps")
}
}
fun main() {
val smallTestData = parseTestData(readInput("Day23-test"))
val bigTestData = parseTestData(readInput("Day23-test2"))
val extraTestState = readState(readInput("Day23-extratest"))
// println("test small simulation")
testSimulation(smallTestData)
// println("test big simulation")
testSimulation(bigTestData)
// println("Simulationg small test data")
simulate(smallTestData[0].second, 1, 10)
// println("Simulating big test Data")
simulate(bigTestData[0].second, 1, 25)
testCountSteps(smallTestData[0].second, smallTestData[3].second, 3, 100)
testCountSteps(bigTestData[0].second, extraTestState, 19, 100)
testSimulationToEnd(smallTestData[0].second, 4)
testSimulationToEnd(bigTestData[0].second, 20)
println("Day 23")
val input = readInput("Day23")
val ans = simulate(readState(input), 1, 10).part1Answer()
println("Answer part1: $ans")
val ans2 = simulateUntilEnd(readState(input))
println("Answer part2: $ans2")
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 7,471 | aoc-2022 | Apache License 2.0 |
src/Day08.kt | VadimB95 | 574,449,732 | false | {"Kotlin": 19743} | fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val inputMatrix = parseInput(input)
var visibleTreesCount = 0
for (i in input.indices) {
for (j in input.indices) {
val isVisibleLeft = isVisible(inputMatrix[i].sliceArray(0..j))
val isVisibleRight = isVisible(inputMatrix[i].sliceArray(j..input.lastIndex).reversedArray())
val topHeights = mutableListOf<Int>()
for (k in 0..i) {
topHeights.add(inputMatrix[k][j])
}
val isVisibleTop = isVisible(topHeights.toIntArray())
val bottomHeights = mutableListOf<Int>()
for (k in i..input.lastIndex) {
bottomHeights.add(inputMatrix[k][j])
}
val isVisibleBottom = isVisible(bottomHeights.toIntArray().reversedArray())
val isTreeVisible = isVisibleLeft || isVisibleRight || isVisibleTop || isVisibleBottom
if (isTreeVisible) visibleTreesCount++
}
}
return visibleTreesCount
}
private fun parseInput(input: List<String>): List<IntArray> =
input.map { it.split("").filter(String::isNotBlank).map(String::toInt).toIntArray() }
private fun isVisible(heights: IntArray): Boolean {
if (heights.size <= 1) return true
var topHeight = 0
val currentTreeHeight = heights.last()
for (i in 0 until heights.lastIndex) {
val height = heights[i]
if (height > topHeight) {
topHeight = height
}
}
return topHeight < currentTreeHeight
}
private fun part2(input: List<String>): Int {
val inputMatrix = parseInput(input)
var highestScenicScore = 0
for (i in input.indices) {
for (j in input.indices) {
val visibilityLeft = getVisibilityDistance(inputMatrix[i].sliceArray(0..j).reversedArray())
val visibilityRight = getVisibilityDistance(inputMatrix[i].sliceArray(j..input.lastIndex))
val topHeights = mutableListOf<Int>()
for (k in i downTo 0) {
topHeights.add(inputMatrix[k][j])
}
val visibilityTop = getVisibilityDistance(topHeights.toIntArray())
val bottomHeights = mutableListOf<Int>()
for (k in i..input.lastIndex) {
bottomHeights.add(inputMatrix[k][j])
}
val visibilityBottom = getVisibilityDistance(bottomHeights.toIntArray())
val scenicScore = visibilityLeft * visibilityRight * visibilityTop * visibilityBottom
if (scenicScore > highestScenicScore) {
highestScenicScore = scenicScore
}
}
}
return highestScenicScore
}
private fun getVisibilityDistance(input: IntArray): Int {
if (input.size <= 1) return 0
val currentTreeHeight = input.first()
var visibilityDistance = 0
for (i in 1..input.lastIndex) {
visibilityDistance++
if (input[i] >= currentTreeHeight) break
}
return visibilityDistance
}
| 0 | Kotlin | 0 | 0 | 3634d1d95acd62b8688b20a74d0b19d516336629 | 3,267 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | kent10000 | 573,114,356 | false | {"Kotlin": 11288} | import java.lang.Exception
import kotlin.math.abs
fun main() {
//rock //paper
fun determineWinner(player1: Hand, player2: Hand): Int {
//Paper Beats Rock Beats Scissors Beats Paper
if (player1 == player2) { return 0 } //Draw
if (player1.ordinal + 1 == player2.ordinal || (player1.ordinal == 2 && player2 == Hand.Paper)) {
return 1
}
return 2
//paper 1 and rock 0 p
//rock 1 paper 0
//scissors 2 paper
}
fun parseChoice(letter: String): Hand {
return when (letter.uppercase()) {
"A" , "X" -> Hand.Rock
"B", "Y" -> Hand.Paper
"C", "Z" -> Hand.Scissors
else -> throw Exception("Invalid Gesture")
}
}
fun part1(input: List<String>): Int {
//Oponent
//A - Rock, B - Paper, C - Scissors
//Self
//X - Rock 1, Y - Paper 2, Z - Scissors 3
//Win is 6 Draw is 3 Loss is 0
var score = 0
input.forEach {
val choices = it.split(" ")
val opponentChoice = parseChoice(choices[0])
val selfChoice = parseChoice(choices[1])
val winner = determineWinner(opponentChoice, selfChoice)
//0 Draw, 1 Opponent, 2 Self
score += selfChoice.score + ((winner + 2 * abs(winner - 1)) / 2) * 3
//score += selfChoice.score + (3 * (winner + 2 * (abs(winner-1)))) / 2
} // 2/2 1 4/2 2
return score
}
fun part2(input: List<String>): Int {
var score = 0
input.forEach {
val choices = it.split(" ")
val opponentChoice = parseChoice(choices[0])
val selfChoice = when (choices[1].uppercase()) {
"X" -> Hand.values().elementAtOrNull(opponentChoice.ordinal + 1) ?: Hand.Paper //loss
"Y" -> opponentChoice
"Z" -> Hand.values().elementAtOrNull(opponentChoice.ordinal - 1) ?: Hand.Scissors //Win
else -> throw Exception("Invalid Gesture")
}
val winner = determineWinner(opponentChoice, selfChoice)
//0 Draw, 1 Opponent, 2 Self
score += selfChoice.score + ((winner + 2 * abs(winner - 1)) / 2) * 3
//score += selfChoice.score + (3 * (winner + 2 * (abs(winner-1)))) / 2
}
return score
}
/* test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
*/
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class Hand(val score: Int){
Paper(2),
Rock(1),
Scissors(3)
}
| 0 | Kotlin | 0 | 0 | c128d05ab06ecb2cb56206e22988c7ca688886ad | 2,748 | advent-of-code-2022 | Apache License 2.0 |
src/day5/Day05.kt | Johnett | 572,834,907 | false | {"Kotlin": 9781} | package day5
import readInput
fun main() {
fun rearrangeCrates(isCrateMover9001: Boolean, values: List<String>): String {
val crateValues = values.takeWhile { createValue ->
createValue.contains("[")
}.map {
it.replace("[", "")
.replace("]", "")
.replace(" ", " ")
.split(" ")
}
val instructions = values.dropWhile {value->
!value.contains("from")
}.map {rawInstruction->
rawInstruction.replace("move", "")
.replace("from", "")
.replace("to", "")
.replace(" ", " ")
.trim()
.split(" ").map { instruction ->
instruction.toInt()
}
}
val crateStacks: MutableMap<Int, List<String>> = mutableMapOf()
crateValues.forEach { createValue ->
createValue.forEachIndexed { index, crate ->
if (crate.isEmpty()) return@forEachIndexed
crateStacks[index + 1] = (crateStacks[index + 1] ?: listOf()) + crate
}
}
instructions.forEach { instruction ->
val (move, from, to) = instruction
if (!isCrateMover9001) crateStacks[to] =
crateStacks[from]!!.take(move).reversed() + crateStacks[to]!! else crateStacks[to] =
crateStacks[from]!!.take(move) + crateStacks[to]!!
crateStacks[from] = crateStacks[from]!!.drop(move)
}
return crateStacks.toSortedMap().map {crateStack->
crateStack.value.first()
}.joinToString("")
}
fun part1(input: List<String>): String {
return rearrangeCrates(false, input)
}
fun part2(input: List<String>): String {
return rearrangeCrates(true, input)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day5/Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("day5/Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | c8b0ac2184bdad65db7d2f185806b9bb2071f159 | 2,150 | AOC-2022-in-Kotlin | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec21.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2020
import org.elwaxoro.advent.PuzzleDayTester
class Dec21 : PuzzleDayTester(21, 2020) {
override fun part1(): Any = parse().let { inputLines ->
foodPoisioningMap(inputLines).let { poisoning ->
val badIngredients = poisoning.values
// remove all the bad ingredients, count up what's left (leave in dupes)
inputLines.map { it.second.filterNot { badIngredients.contains(it) } }.flatten().size
}
}
// sort by allergen, then print list of ingredients
override fun part2(): Any =
foodPoisioningMap(parse()).toList().sortedBy { it.first }.joinToString(",") { it.second }
// parse input into a list of pairs: first is the set of allergens, second is the set of ingredients
private fun parse(): List<Pair<Set<String>, Set<String>>> = load().map { line ->
line.split(" (contains ").let { split ->
split[1].replace(')', ' ').split(", ").map { it.trim() }.toSet() to split[0].split(" ").toSet()
}
}
// returns map of 1 allergen to 1 ingredient
private fun foodPoisioningMap(inputLines: List<Pair<Set<String>, Set<String>>>): Map<String, String> {
// set of all the allergens exactly once
val uniqueAllergens = inputLines.map { it.first }.flatten().toSet()
// map allergen to the set of common ingredients across all lines
val allergenMap: Map<String, Set<String>> = uniqueAllergens.map { allergen ->
// for just lines with the allergen, intersect their ingredient sets together, so only common ingredients remain
allergen to inputLines.filter { it.first.contains(allergen) }.map { it.second }
.reduce { acc, set -> acc.intersect(set) }
}.toMap()
// split the allergens into known (1 allergen to 1 ingredient) and unknown (1 allergen to multiple ingredients)
val partition = allergenMap.toList().partition { it.second.size == 1 }
val known = partition.first.map { it.first to it.second.single() }.toMap(mutableMapOf())
val unknown: MutableMap<String, Set<String>> = partition.second.toMap(mutableMapOf())
// INTO THE UNKNOOOOOWWWWWWNNNNNNNN
while (unknown.isNotEmpty()) {
// for every unknown allergen, subtract out all the known ingredients, then see if anything is down to ingredient size 1
unknown.map { it.key to it.value - known.values }.filter { it.second.size == 1 }.let { freshFinds ->
// TODO this turned out nasty. better way?
known.putAll(freshFinds.map { it.first to it.second.single() }.toMap())
freshFinds.forEach { unknown.remove(it.first) }
}
}
return known
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,762 | advent-of-code | MIT License |
src/Day12.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | private class Highmap(
val area: List<List<Int>>,
val startPosition: Position,
val endPosition: Position
) {
val width: Int
get() = area[0].size
val height: Int
get() = area.size
fun elevationAt(pos: Position): Int {
return area[pos.y][pos.x]
}
fun hasPathBetween(from: Position, to: Position): Boolean {
return from.isInArea()
&& to.isInArea()
&& elevationAt(from) + 1 >= elevationAt(to)
}
private fun Position.isInArea(): Boolean {
return this.x in (0 until width)
&& this.y in (0 until height)
}
}
private data class Position(val x: Int, val y: Int) {
override fun toString(): String {
return "[$x,$y]"
}
}
fun main() {
fun part1(input: Highmap): Int {
return calculateMinStepsMatrix(input)[input.startPosition]
}
fun part2(input: Highmap): Int {
val minStepsMatrix = calculateMinStepsMatrix(input)
return input.area.flatMapIndexed { y, ints ->
ints.indices.filter { x -> ints[x] == 0 }
.map { x -> minStepsMatrix[y][x] }
}.min()
}
val testInput = readInput("Day12_test")
.parseHighmap()
val testResult = part1(testInput)
check(testResult == 31)
val input = readInput("Day12")
.parseHighmap()
val part1Result = part1(input)
println(part1Result)
//check(part1Result == 462)
val part2Result = part2(input)
println(part2Result)
//check(part2Result == 451)
}
private fun calculateMinStepsMatrix(input: Highmap): List<List<Int>> {
val dequeue: ArrayDeque<Pair<Position, Int>> = ArrayDeque()
val minStepsMatrix: List<MutableList<Int>> = MutableList(input.height) { MutableList(input.width) { Int.MAX_VALUE } }
dequeue.addLast(input.endPosition to 0);
while (!dequeue.isEmpty()) {
val (to, depth) = dequeue.removeFirst()
if (minStepsMatrix[to] <= depth) {
continue
} else {
minStepsMatrix[to] = depth
}
listOf(
to.copy(x = to.x - 1),
to.copy(x = to.x + 1),
to.copy(y = to.y - 1),
to.copy(y = to.y + 1)
).forEach { fromPos ->
if (input.hasPathBetween(fromPos, to)) {
dequeue.addLast(fromPos to (depth + 1))
}
}
}
return minStepsMatrix
}
private operator fun List<List<Int>>.get(from: Position): Int {
return this[from.y][from.x]
}
private operator fun List<MutableList<Int>>.set(from: Position, value: Int) {
this[from.y][from.x] = value
}
private fun List<String>.parseHighmap(): Highmap {
var startPos: Position? = null
var endPos: Position? = null
val highMap: List<List<Int>> = this.mapIndexed { y, s ->
s.mapIndexed i@{ x, c ->
when (c) {
'S' -> {
startPos = Position(x, y)
return@i 0
}
'E' -> {
endPos = Position(x, y)
return@i 'z' - 'a'
}
else -> {
return@i c - 'a'
}
}
}
}
return Highmap(highMap, startPos!!, endPos!!)
} | 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 3,276 | aoc22-kotlin | Apache License 2.0 |
src/year_2022/day_11/Day11.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_11
import readInput
import java.math.BigInteger
data class Monkey(
val id: Int,
val items: MutableList<Int>,
val operation: List<String>,
val divisibleBy: Int,
val whenTrue: Int,
val whenFalse: Int
) {
var inspectionCount: Long = 0
/**
* @return pair of worry level to monkey tossed to
*/
fun test(worryLevel: Int, modulo: Int, decreaseWorry: Boolean = true): Pair<Int, Int> {
inspectionCount += 1
val formula = operation.map { value ->
if (value == "old") {
worryLevel.toString()
} else {
value
}
}
var bigResult = when (formula[1]) {
"+" -> BigInteger(formula[0]) + BigInteger(formula[2])
"-" -> BigInteger(formula[0]) - BigInteger(formula[2])
"*" -> BigInteger(formula[0]) * BigInteger(formula[2])
"/" -> BigInteger(formula[0]) / BigInteger(formula[2])
else -> {
println("UNKNOWN OPERATION: ${formula[1]}")
0.toBigInteger()
}
}
if (bigResult > modulo.toBigInteger()) {
bigResult %= modulo.toBigInteger()
}
var result = bigResult.toInt()
if (decreaseWorry) {
result /= 3
}
return if (result % divisibleBy == 0) {
result to whenTrue
} else {
result to whenFalse
}
}
}
object Day11 {
/**
* @return
*/
fun solutionOne(text: List<String>): Long {
val monkeys = parseText(text)
var modulo = monkeys.first().divisibleBy
for (i in 1 until monkeys.size) {
modulo *= monkeys[i].divisibleBy
}
for (round in 1..20) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val itemWorryLevel = monkey.items.removeFirst()
val (newWorry, nextMonkey) = monkey.test(itemWorryLevel, modulo)
monkeys.first { it.id == nextMonkey }.items.add(newWorry)
}
}
}
val inspections = monkeys
.map { monkey -> monkey.inspectionCount }
.sortedByDescending { it }
return inspections[0] * inspections[1]
}
/**
* @return
*/
fun solutionTwo(text: List<String>): Long {
val monkeys = parseText(text)
var modulo = monkeys.first().divisibleBy
for (i in 1 until monkeys.size) {
modulo *= monkeys[i].divisibleBy
}
for (round in 1..10_000) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val itemWorryLevel = monkey.items.removeFirst()
val (newWorry, nextMonkey) = monkey.test(itemWorryLevel, modulo, false)
monkeys.first { it.id == nextMonkey }.items.add(newWorry)
}
}
// if (round in listOf(1, 20) || round % 1000 == 0) {
// println("\n== After round $round ==")
// monkeys.forEach { monkey ->
// println("Monkey ${monkey.id} inspected items ${monkey.inspectionCount} times.")
// }
// }
}
val inspections = monkeys
.map { monkey -> monkey.id to monkey.inspectionCount }
.sortedByDescending { it.second }
return inspections[0].second * inspections[1].second
}
private fun parseText(text: List<String>): List<Monkey> {
return text.filter { it.isNotEmpty() }.windowed(6, 6).map { monkey ->
val monkeyId = monkey[0].split(" ")[1].split(":").first()
val items = monkey[1].substring(18).split(", ").map { Integer.parseInt(it) }
val operation = monkey[2].split(": ")[1].split(" ").subList(2, 5)
val testDivisibleBy = monkey[3].split(" ").last()
val testTrue = monkey[4].split(" ").last()
val testFalse = monkey[5].split(" ").last()
Monkey(
id = Integer.parseInt(monkeyId),
items = items.toMutableList(),
operation = operation,
divisibleBy = Integer.parseInt(testDivisibleBy),
whenTrue = Integer.parseInt(testTrue),
whenFalse = Integer.parseInt(testFalse)
)
}
}
}
fun main() {
val inputText = readInput("year_2022/day_11/Day11.txt")
val solutionOne = Day11.solutionOne(inputText)
println("Solution 1: $solutionOne")
val solutionTwo = Day11.solutionTwo(inputText)
println("Solution 2: $solutionTwo")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 4,704 | advent_of_code | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2019/Day12.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2019
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import kotlin.math.abs
/** https://adventofcode.com/2019/day/12 */
class Day12 : Solver {
override fun solve(lines: List<String>): Result {
val planetsA = lines.map { parse(it) }
(1..1000).forEach { _ -> step(planetsA) }
val energyA = planetsA.map { it.energy() }.sum()
val planetsB = lines.map { parse(it) }
val loopX = findLoop(planetsB) { Pair(it.pos.x, it.vel.x) }
val loopY = findLoop(planetsB) { Pair(it.pos.y, it.vel.y) }
val loopZ = findLoop(planetsB) { Pair(it.pos.z, it.vel.z) }
val resultB = lcm(loopX.toLong(), lcm(loopY.toLong(), loopZ.toLong()))
return Result("$energyA", "$resultB")
}
/** Find the first loop on the given axis. */
private fun findLoop(planets: List<Planet>, get: (Planet) -> Pair<Int, Int>): Int {
val history = hashSetOf<String>()
while (true) {
step(planets)
val stateXStr = "${planets.map { get(it) }.toList()}"
if (stateXStr in history) {
return history.size
}
history.add(stateXStr)
}
}
/** Lowest common multiple. */
private fun lcm(a: Long, b: Long): Long {
return abs(a * b) / gcd(a, b)
}
/** Greatest common denominator using Euclid's method. */
private fun gcd(a: Long, b: Long): Long {
var t: Long;
var aa = a
var bb = b
while (bb != 0L) {
t = bb;
bb = aa % bb;
aa = t;
}
return aa;
}
private fun step(planets: List<Planet>) {
for (planet in planets) {
for (other in planets) {
if (other == planet) continue
planet.vel.x += comp(other.pos.x, planet.pos.x)
planet.vel.y += comp(other.pos.y, planet.pos.y)
planet.vel.z += comp(other.pos.z, planet.pos.z)
}
}
planets.forEach { it.applyVelocity() }
}
private fun comp(a: Int, b: Int) = if (a > b) 1 else if (a < b) -1 else 0
private fun parse(line: String): Planet {
val split = line.split(", ")
val x = split[0].split("=")[1].toInt()
val y = split[1].split("=")[1].toInt()
val z = split[2].split("=")[1].split(">")[0].toInt()
return Planet(XYZ(x, y, z), XYZ(0, 0, 0))
}
private data class Planet(val pos: XYZ, val vel: XYZ) {
fun energy() = pos.energy() * vel.energy()
fun applyVelocity() {
pos.x += vel.x
pos.y += vel.y
pos.z += vel.z
}
}
private data class XYZ(var x: Int, var y: Int, var z: Int) {
fun energy() = abs(x) + abs(y) + abs(z)
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,511 | euler | Apache License 2.0 |
src/Day02.kt | buczebar | 572,864,830 | false | {"Kotlin": 39213} | fun main() {
fun gameResult(yourMove: HandShape, opponentMove: HandShape) =
when (yourMove) {
opponentMove.greater() -> GameResult.WIN
opponentMove.lower() -> GameResult.LOSS
else -> GameResult.DRAW
}
fun part1(input: List<Pair<HandShape, HandShape>>): Int {
return input.sumOf { (opponentMove, yourMove) ->
yourMove.score + gameResult(yourMove, opponentMove).score
}
}
fun getMoveForExpectedResult(opponentMove: HandShape, expectedResult: GameResult) =
when (expectedResult) {
GameResult.LOSS -> opponentMove.lower()
GameResult.DRAW -> opponentMove
GameResult.WIN -> opponentMove.greater()
}
fun part2(input: List<Pair<HandShape, GameResult>>) =
input.sumOf {
val (opponentMove, gameResult) = it
gameResult.score + getMoveForExpectedResult(opponentMove, gameResult).score
}
val testInputPart1 = parseInput("Day02_test", String::toHandShape, String::toHandShape)
check(part1(testInputPart1) == 15)
val testInputPart2 = parseInput("Day02_test", String::toHandShape, String::toGameResult)
check(part2(testInputPart2) == 12)
val inputForPart1 = parseInput("Day02", String::toHandShape, String::toHandShape)
println(part1(inputForPart1))
val inputForPart2 = parseInput("Day02", String::toHandShape, String::toGameResult)
println(part2(inputForPart2))
}
private fun <T, U> parseInput(name: String, firstArgParser: (String) -> T, secondArgParser: (String) -> U) =
readInput(name).map { round ->
round.split(" ").let {
Pair(firstArgParser.invoke(it[0]), secondArgParser.invoke(it[1]))
}
}
private fun String.toHandShape(): HandShape {
return when (this) {
"A", "X" -> HandShape.ROCK
"B", "Y" -> HandShape.PAPER
"C", "Z" -> HandShape.SCISSORS
else -> throw IllegalArgumentException()
}
}
private fun String.toGameResult(): GameResult {
return when (this) {
"X" -> GameResult.LOSS
"Y" -> GameResult.DRAW
"Z" -> GameResult.WIN
else -> throw IllegalArgumentException()
}
}
private enum class HandShape(val score: Int) {
ROCK(1) {
override fun greater() = PAPER
override fun lower() = SCISSORS
},
PAPER(2) {
override fun greater() = SCISSORS
override fun lower() = ROCK
},
SCISSORS(3) {
override fun greater() = ROCK
override fun lower() = PAPER
};
abstract fun greater(): HandShape
abstract fun lower(): HandShape
}
private enum class GameResult(val score: Int) {
LOSS(0),
DRAW(3),
WIN(6)
}
| 0 | Kotlin | 0 | 0 | cdb6fe3996ab8216e7a005e766490a2181cd4101 | 2,725 | advent-of-code | Apache License 2.0 |
src/aoc2023/Day2.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2023
import utils.checkEquals
import utils.readInput
fun main(): Unit = with(Day2) {
part1(testInput).checkEquals(8)
part1(input)
.checkEquals(2176)
// .sendAnswer(part = 1, day = "2", year = 2023)
part2(testInput).checkEquals(2286)
part2(input)
.checkEquals(63700)
// .sendAnswer(part = 2, day = "2", year = 2023)
}
object Day2 {
data class GameSet(
val id: Int,
val red: Int,
val green: Int,
val blue: Int,
)
fun part1(input: List<String>): Int = input.sumOf { line ->
val gameSets = line.parseGameSets()
if (
gameSets.any {
it.red > 12 || it.green > 13 || it.blue > 14
}
)
return@sumOf 0
return@sumOf gameSets.random().id
}
fun part2(input: List<String>): Int = input.sumOf { line ->
val gameSets = line.parseGameSets()
val r = gameSets.maxOf { it.red }
val g = gameSets.maxOf { it.green }
val b = gameSets.maxOf { it.blue }
return@sumOf r * g * b
}
fun String.parseGameSets(): List<GameSet> {
val line = this
val id = line.substringBefore(':').drop(5).toInt()
val sets = line.substringAfter(':').split(';')
val gameSets = sets.map {
val colors = it.split(',').map { it.trim() }
val red = colors.singleOrNull { it.endsWith("red") }?.takeWhile { it.isDigit() }
val green = colors.singleOrNull { it.endsWith("green") }?.takeWhile { it.isDigit() }
val blue = colors.singleOrNull { it.endsWith("blue") }?.takeWhile { it.isDigit() }
GameSet(
id,
red = red?.toInt() ?: 0,
green = green?.toInt() ?: 0,
blue = blue?.toInt() ?: 0
)
}
return gameSets
}
val input
get() = readInput("Day2", "aoc2023")
val testInput
get() = readInput("Day2_test", "aoc2023")
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 2,030 | Kotlin-AOC-2023 | Apache License 2.0 |
src/main/java/com/ncorti/aoc2021/Exercise09.kt | cortinico | 433,486,684 | false | {"Kotlin": 36975} | package com.ncorti.aoc2021
object Exercise09 {
private fun getInput(): List<List<Int>> =
getInputAsTest("09") { split("\n") }.map { line ->
line.toCharArray().map { it.digitToInt() }
}
private fun List<List<Int>>.isALowerPoint(i: Int, j: Int): Boolean =
(i == 0 || this[i][j] < this[i - 1][j]) &&
(j == 0 || this[i][j] < this[i][j - 1]) &&
(i == this.size - 1 || this[i][j] < this[i + 1][j]) &&
(j == this[i].size - 1 || this[i][j] < this[i][j + 1])
private fun discoverBasin(world: List<List<Int>>, starti: Int, startj: Int): Int {
val seen = mutableSetOf<Pair<Int, Int>>()
val next = mutableListOf(starti to startj)
while (next.isNotEmpty()) {
val (i, j) = next.removeFirst()
seen.add(i to j)
if (i != 0 && world[i - 1][j] != 9 && (i - 1 to j) !in seen) {
next.add(i - 1 to j)
}
if (j != 0 && world[i][j - 1] != 9 && (i to j - 1) !in seen) {
next.add(i to j - 1)
}
if (i != world.size - 1 && world[i + 1][j] != 9 && (i + 1 to j) !in seen) {
next.add(i + 1 to j)
}
if (j != world[0].size - 1 && world[i][j + 1] != 9 && (i to j + 1) !in seen) {
next.add(i to j + 1)
}
}
return seen.size
}
fun part1(): Int =
getInput().let { world ->
world
.mapIndexed { i, line ->
line.filterIndexed { j, _ -> world.isALowerPoint(i, j) }.sumOf { it + 1 }
}
.sum()
}
fun part2(): Int =
getInput()
.let { world ->
world.flatMapIndexed { i, line ->
List(line.size) { j ->
if (world.isALowerPoint(i, j)) {
discoverBasin(world, i, j)
} else {
0
}
}
}
}
.sortedDescending()
.take(3)
.reduce { acc, next -> acc * next }
}
fun main() {
println(Exercise09.part1())
println(Exercise09.part2())
}
| 0 | Kotlin | 0 | 4 | af3df72d31b74857201c85f923a96f563c450996 | 2,269 | adventofcode-2021 | MIT License |
src/main/java/dev/haenara/mailprogramming/solution/y2020/m02/d23/Solution200223.kt | HaenaraShin | 226,032,186 | false | null | package dev.haenara.mailprogramming.solution.y2020.m02.d23
import dev.haenara.mailprogramming.solution.Solution
/**
* 매일프로그래밍 2020. 02. 23
*
* M x N 크기의 양의 정수 매트릭스와 비용(cost)가 주어졌을 때,
* 주어진 비용으로 매트릭스의 시작 위치 (0, 0)에서 마지막 위치 (M-1, N-1)까지 도달하는 경로의 수를 구하시오.
* 매트릭스에서 이동한 경로의 비용은 거쳐간 셀 값의 합이다.
* 매트릭스에서는 오직 오른쪽 한 칸 또는 아래쪽 한 칸으로만 이동할 수 있다.
* 즉, 셀 (i, j)에서는 (i, j+1) 또는 (i+1, j)로 이동할 수 있다.
*
* Input
* [[4, 7, 1, 6],
* [5, 7, 3, 9],
* [3, 2, 1, 2],
* [7, 1, 6, 3]]
* cost = 25
*
* Output
* 2 (두 가지 경로는 4-7-1-3-1-6-3, 4-5-7-3-1-2-3)
*
* 풀이
*
*/
class Solution200223 : Solution<Solution200223.Input, Int>{
private var count = 0
private lateinit var map : Array<Array<Int>>
private var cost = 0
override fun solution(input : Input) : Int {
map = input.map
cost = input.cost
return goRightOrDown(0, 0)
}
private fun goRightOrDown(x : Int, y : Int, costSum : Int = 0) : Int {
val sum = costSum + map[y][x]
if (x == map[y].lastIndex && y == map.lastIndex) {
return if (sum == cost) {
1
} else {
0
}
} else if (x == map[y].lastIndex) {
// move down
return goRightOrDown(x, y + 1, sum)
} else if (y == map.lastIndex) {
// move right
return goRightOrDown(x + 1, y, sum)
} else {
// move right and down
return goRightOrDown(x + 1, y, sum) + goRightOrDown(x, y + 1, sum)
}
}
class Input(val map : Array<Array<Int>>, val cost : Int)
}
| 0 | Kotlin | 0 | 7 | b5e50907b8a7af5db2055a99461bff9cc0268293 | 1,891 | MailProgramming | MIT License |
src/main/kotlin/Day2.kt | corentinnormand | 725,992,109 | false | {"Kotlin": 40576} | class Day2 : Aoc("day2.txt") {
override fun one() {
val input = readFile("day2.txt").lines()
val result = input.asSequence().map { it.split(":") }
.map { s ->
val second = s[1].split(';')
.map { str -> str.split(",") }
.map { str -> str.map { it.trim() } }
.map { str -> str.map { it.split(" "); } }
.map { str -> str.map { s -> Pair(s[1], s[0].toInt()) } }
.map { it.toMap() }
.flatMap { it.entries }
.groupBy { it.key }
.mapValues { it.value.maxOf { v -> v.value } }
Pair(s[0].split(" ")[1].toInt(), second)
}
.filter { it.second.all { e -> (e.key == "blue" && e.value <= 14) || (e.key == "green" && e.value <= 13) || (e.key == "red" && e.value <= 12) } }
.sumOf { it.first }
println(result)
}
override fun two() {
val input = readFile("day2.txt").lines()
val result = input.asSequence().map { it.split(":") }
.map { s ->
val second = s[1].split(';')
.map { str -> str.split(",") }
.map { str -> str.map { it.trim() } }
.map { str -> str.map { it.split(" "); } }
.map { str -> str.map { s -> Pair(s[1], s[0].toInt()) } }
.map { it.toMap() }
.flatMap { it.entries }
.groupBy { it.key }
.mapValues { it.value.maxOf { v -> v.value } }
Pair(s[0].split(" ")[1].toInt(), second)
}
.map { it.second }
.map { it.values.reduce { acc, value -> acc * value } }
.sum()
println(result)
}
}
| 0 | Kotlin | 0 | 0 | 2b177a98ab112850b0f985c5926d15493a9a1373 | 1,838 | aoc_2023 | Apache License 2.0 |
src/Day05.kt | frungl | 573,598,286 | false | {"Kotlin": 86423} | fun main() {
fun parseStacks(i: List<String>): MutableList<MutableList<String>> {
val tmp = i.map {
it.padEnd(i.last().length, ' ')
.chunked(1)
.filterIndexed { index, _ -> index % 4 == 1 }
}.dropLast(1)
val res = MutableList<MutableList<String>>(tmp[0].size) { mutableListOf() }
tmp.asReversed().fold(res) { set, el ->
set.mapIndexed { index, chars ->
if(el[index].isNotBlank())
chars.add(el[index])
chars
}.toMutableList()
}
return res
}
fun parseQuery(q: List<String>): List<List<Int>> {
return q.fold(mutableListOf<List<Int>>()) { acc, s ->
acc.add(s.split(' ').filter { it.toIntOrNull() != null }.map { it.toInt() })
acc
}.toList()
}
fun part1(input: List<String>): String {
val (q, i) = input.filter { it.isNotBlank() }.partition { it.contains("move") }
val stacks = parseStacks(i)
val queries = parseQuery(q)
queries.forEach {
val (cnt, from, to) = it
stacks[to - 1].addAll(stacks[from - 1].takeLast(cnt).asReversed())
stacks[from - 1] = stacks[from - 1].dropLast(cnt).toMutableList()
}
return stacks.fold("") { str, it ->
str + it.last()
}
}
fun part2(input: List<String>): String {
val (q, i) = input.filter { it.isNotBlank() }.partition { it.contains("move") }
val stacks = parseStacks(i)
val queries = parseQuery(q)
queries.forEach {
val (cnt, from, to) = it
stacks[to - 1].addAll(stacks[from - 1].takeLast(cnt))
stacks[from - 1] = stacks[from - 1].dropLast(cnt).toMutableList()
}
return stacks.fold("") { str, it ->
str + it.last()
}
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d4cecfd5ee13de95f143407735e00c02baac7d5c | 2,107 | aoc2022 | Apache License 2.0 |
2021/src/main/kotlin/day5_fast.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Segment
import kotlin.math.abs
import kotlin.math.roundToInt
import utils.Parser
import utils.Solution
import utils.mapItems
fun main() {
Day5Fast.run()
}
object Day5All {
@JvmStatic fun main(args: Array<String>) {
mapOf("func" to Day5Func, "imp" to Day5Imp, "fast" to Day5Fast).forEach { (header, solution) ->
solution.run(
header = header,
printParseTime = false
)
}
}
}
object Day5Fast: Solution<List<Segment>>() {
override val name = "day5"
override val parser = Parser.lines
.mapItems(Segment::parse)
.mapItems { if (it.start.x > it.end.x) Segment(it.end, it.start) else it }
override fun part1(input: List<Segment>): Int {
return solve(input.filter { it.isVertical || it.isHorizontal })
}
override fun part2(input: List<Segment>): Int {
return solve(input)
}
private fun solve(segments: List<Segment>): Int {
val intersections = Array(1000) { IntArray(1000) { 0 } }
var count = 0
segments.forEachIndexed { i, line ->
for (j in (i + 1 until segments.size)) {
val other = segments[j]
if (other.start.x > line.end.x || other.end.x < line.start.x)
continue
if (minOf(other.start.y, other.end.y) > maxOf(line.start.y, line.end.y) ||
maxOf(other.start.y, other.end.y) < minOf(line.start.y, line.end.y))
continue
if (line.isVertical) {
count = verticalIntersections(other, line, intersections, count)
} else if (other.isVertical) {
count = verticalIntersections(line, other, intersections, count)
} else if (line.slope != other.slope) {
val y1 = line.start.y
val y2 = other.start.y
val x1 = line.start.x
val x2 = other.start.x
val s1 = line.slope
val s2 = other.slope
val fx = (y2 - y1 - x2 * s2 + x1 * s1) / (s1 - s2).toDouble()
// bit of a hack, check whether the lines overlap when quantized
if (abs(fx.roundToInt().toFloat() - fx) > 0.001) {
continue
}
val x = fx.roundToInt()
if (x in line.start.x .. line.end.x && x in other.start.x .. other.end.x) {
val p = line[x]
if (intersections[p.x][p.y]++ == 0) {
count++
}
}
} else if (line[0].y == other[0].y) {
val start = maxOf(line.start.x, other.start.x)
val end = minOf(line.end.x, other.end.x)
for (x in start .. end) {
val p = line[x]
// if new intersection found, add to count
if (intersections[p.x][p.y]++ == 0) {
count++
}
}
}
}
}
return count
}
private fun verticalIntersections(
other: Segment,
segment: Segment,
intersections: Array<IntArray>,
count: Int
): Int {
var count1 = count
if (!other.isVertical) {
val p = other[segment.start.x]
if (p.y in (minOf(segment.start.y, segment.end.y)..maxOf(segment.start.y, segment.end.y)) && p in other) {
if (intersections[p.x][p.y]++ == 0) {
count1++
}
}
} else {
if (segment.start.x == other.start.x) {
val x = segment.start.x
val l1sy = minOf(segment.start.y, segment.end.y)
val l1ey = maxOf(segment.start.y, segment.end.y)
val l2sy = minOf(other.start.y, other.end.y)
val l2ey = maxOf(other.start.y, other.end.y)
val start = maxOf(l1sy, l2sy)
val end = minOf(l1ey, l2ey)
for (y in start..end) {
if (intersections[x][y]++ == 0) {
count1++
}
}
}
}
return count1
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 3,716 | aoc_kotlin | MIT License |
aoc2022/day7.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2022
import utils.InputRetrieval
import java.lang.Integer.min
fun main() {
Day7.execute()
}
object Day7 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: Dir): Int = calcCumulativeDirSize(input)
private fun part2(input: Dir): Int = calcMinDirSizeAbove(input, (30000000 - (70000000 - input.size)))
private fun readInput(): Dir {
val input: List<String> = InputRetrieval.getFile(2022, 7).readLines()
// Create Dir Tree
val topDir = Dir("/")
var currentDir = topDir
for (i in input) {
if (i.startsWith("$ cd ")) {
val dirName = i.removePrefix("$ cd ")
currentDir = when (dirName) {
".." -> currentDir.parentDir!! // Go up
"/" -> topDir // Go root
else -> currentDir.nodes.filterIsInstance<Dir>().first { it.name == dirName } // Go to child dir
}
} else if (!i.startsWith('$')) {
// We only have a command output, so we can just skip the '$ ls' entry and just assume anything that doesn't start with '$' is the list output of the current dir
val (size, fileName) = i.split(' ')
val item = when (size) {
"dir" -> currentDir.nodes.filterIsInstance<Dir>().firstOrNull { it.name == fileName } ?: Dir(fileName, parentDir = currentDir)
else -> currentDir.nodes.filterIsInstance<File>().firstOrNull { it.name == fileName } ?: File(fileName, size.toInt())
}
currentDir.nodes.add(item)
}
}
return topDir
}
/**
* This solution is not perfect because it iterates the tree multiple times go get the dir sizes, but it is good enough for the input size
*/
private fun calcCumulativeDirSize(node: Node, maxSize: Int = 100000): Int = when (node) {
is File -> 0
is Dir -> {
val nodeSize = node.size
val childrenCumulativeSize = node.nodes.sumOf { calcCumulativeDirSize(it) }
if (nodeSize > maxSize) {
childrenCumulativeSize
} else {
nodeSize + childrenCumulativeSize
}
}
}
/**
* This solution is not perfect because it iterates the tree multiple times go get the dir sizes, but it is good enough for the input size
*/
private fun calcMinDirSizeAbove(node: Node, minSize: Int): Int = when (node) {
is File -> 0
is Dir -> {
val itemSize = node.size
if (itemSize >= minSize) {
val childSizes = node.nodes.map { calcMinDirSizeAbove(it, minSize) }.filter { it >= minSize }.minOrNull() ?: Int.MAX_VALUE
min(itemSize, childSizes)
} else 0
}
}
sealed interface Node {
val name: String
val size: Int
}
data class File(override val name: String, override val size: Int) : Node
data class Dir(override val name: String, val nodes: MutableSet<Node> = mutableSetOf(), val parentDir: Dir? = null) : Node {
override val size: Int
get() = nodes.sumOf { it.size }
override fun hashCode() = name.hashCode()
override fun toString() = name
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return name == (other as Dir).name
}
}
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 3,627 | Advent-Of-Code | MIT License |
src/Day08.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | typealias MyPair = Pair<Boolean, Int>
class Field(val f: (MyPair, MyPair, MyPair, MyPair) -> Int): Iterable<Int> {
val field: MutableList<List<Int>> = mutableListOf()
override fun iterator(): Iterator<Int> {
return object : Iterator<Int> {
var col = -1
var row = 0
override fun hasNext(): Boolean = col*row < (field.size-1)*(field[0].size-1)
override fun next(): Int {
if (col == field[0].size-1) {
row++
col = 0
} else {
col++
}
return f(lookDown(row, col),
lookUp(row, col),
lookLeft(row, col),
lookRight(row, col)
)
}
}
}
fun addRow(row: List<Int>) {
this.field.add(row)
}
fun lookRight(row: Int, col: Int): MyPair {
var dist = 0
for (j in col+1 until this.field[row].size) {
dist++
if (this.field[row][j] >= this.field[row][col]) {
return Pair(false, dist)
}
}
return Pair(true, dist)
}
fun lookLeft(row: Int, col: Int): MyPair {
var dist = 0
for (j in col-1 downTo 0) {
dist++
if (this.field[row][j] >= this.field[row][col]) {
return Pair(false, dist)
}
}
return Pair(true, dist)
}
fun lookUp(row: Int, col: Int): MyPair {
var dist = 0
for (j in row-1 downTo 0) {
dist++
if (this.field[j][col] >= this.field[row][col]) {
return Pair(false, dist)
}
}
return Pair(true, dist)
}
fun lookDown(row: Int, col: Int): MyPair {
var dist = 0
for (j in row+1 until this.field.size) {
dist++
if (this.field[j][col] >= this.field[row][col]) {
return Pair(false, dist)
}
}
return Pair(true, dist)
}
}
fun main() {
fun part1(input: List<String>): Int {
val field = Field { down: MyPair, up: MyPair, left: MyPair, right: MyPair ->
(down.first || up.first || left.first || right.first).compareTo(false)
}
for (line in input) {
field.addRow(line.map{it.toString().toInt()})
}
return field.sum()
}
fun part2(input: List<String>): Int {
val field = Field { down: MyPair, up: MyPair, left: MyPair, right: MyPair ->
down.second * up.second * left.second * right.second
}
for (line in input) {
field.addRow(line.map{it.toString().toInt()})
}
return field.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 3,061 | aoc2022 | Apache License 2.0 |
2023/src/main/kotlin/Day02.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import Color.BLUE
import Color.GREEN
import Color.RED
private enum class Color {
RED, GREEN, BLUE
}
private typealias Cubes = Map<Color, Int>
private data class Game(val num: Int, val draws: List<Cubes>)
object Day02 {
fun part1(input: String): Int {
return input.splitNewlines()
.map { parseGame(it) }
.filter { it.isPossible() }
.sumOf { it.num }
}
fun part2(input: String): Int {
return input.splitNewlines()
.map { parseGame(it) }
.map { it.calculateMinimumCubes() }
.sumOf { it.power() }
}
private fun Game.isPossible() = this.draws.all {
it.getOrDefault(RED, 0) <= 12
&& it.getOrDefault(GREEN, 0) <= 13
&& it.getOrDefault(BLUE, 0) <= 14
}
private fun Game.calculateMinimumCubes(): Cubes {
val minCubes = mutableMapOf<Color, Int>()
this.draws.forEach { draw ->
Color.entries.forEach { color ->
minCubes[color] = maxOf(minCubes.getOrDefault(color, 0), draw.getOrDefault(color, 0))
}
}
return minCubes
}
private fun Cubes.power() = this.values.reduce(Int::times)
// Parsing
private val GAME_REGEX = Regex("Game (\\d+): (.*)")
private val DRAW_REGEX = Regex("(\\d+) (red|green|blue)")
private fun parseGame(game: String): Game {
val match = GAME_REGEX.matchEntire(game)!!
val number = match.groups[1]!!.value.toInt()
val draws = match.groups[2]!!.value.trim().split("; ")
val parsedDraws = draws.map { draw ->
DRAW_REGEX.findAll(draw)
.associate { Color.valueOf(it.groups[2]!!.value.uppercase()) to it.groups[1]!!.value.toInt() }
}
return Game(number, parsedDraws)
}
}
| 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,652 | advent-of-code | MIT License |
aoc2023/day4.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2023
import utils.InputRetrieval
import kotlin.math.pow
fun main() {
Day4.execute()
}
private object Day4 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<ScratchCard>): Int = input.sumOf { it.value() }
// We could improve the performance of this, so we could cache data, but it's good enough... And this way I can use the PC as a heat source
private fun part2(input: List<ScratchCard>): Int {
val ticketCount: MutableMap<Int, Int> = input.associate { it.cardId to 1 }.toMutableMap()
val winningTickets = input.filter { it.winningTicket() }.associateBy { it.cardId }
winningTickets.values.forEach {
it.increaseCardCount(ticketCount, winningTickets)
}
return ticketCount.values.sum()
}
private fun readInput(): List<ScratchCard> = InputRetrieval.getFile(2023, 4).readLines().map { ScratchCard.parse(it) }
private fun ScratchCard.increaseCardCount(ticketCount: MutableMap<Int, Int>, winningTickets: Map<Int, ScratchCard>) {
(1..this.matchingNumberCount).map { this.cardId + it }.forEach {
ticketCount[it] = ticketCount[it]!! + 1
winningTickets[it]?.increaseCardCount(ticketCount, winningTickets)
}
}
private data class ScratchCard(
val cardId: Int,
val winningNumbers: List<Int>,
val numbers: List<Int>,
val matchingNumberCount: Int = numbers.filter { number -> winningNumbers.contains(number) }.size,
) {
fun winningTicket(): Boolean = this.matchingNumberCount > 0
fun value(): Int = if (winningTicket()) (2.0).pow(this.matchingNumberCount - 1).toInt() else 0
companion object {
fun parse(input: String): ScratchCard {
val (cardId, rawNumbers) = input.split(':')
val (winningNumbers, numbers) = rawNumbers.split('|')
return ScratchCard(
cardId = cardId.removePrefix("Card").trim().toInt(),
winningNumbers = winningNumbers.split(' ').filter { it.isNotBlank() }.map { it.toInt() },
numbers = numbers.split(' ').filter { it.isNotBlank() }.map { it.toInt() })
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 2,343 | Advent-Of-Code | MIT License |
kotlin/src/katas/kotlin/leetcode/magic_square/MagicSquare.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.magic_square
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/discuss/interview-question/341295/Google-or-Online-Assessment-2019-or-Fill-Matrix
*/
class MagicSquareTests {
@Test fun `find magic square of size n`() {
magicSquare(size = 2) shouldEqual emptyList()
magicSquare(size = 3) shouldEqual listOf(
listOf(8, 3, 4),
listOf(1, 5, 9),
listOf(6, 7, 2)
)
/*
magicSquare(size = 4) shouldEqual listOf(
listOf(8, 3, 4),
listOf(1, 5, 9),
listOf(6, 7, 2)
)
*/
}
}
private fun magicSquare(size: Int): List<List<Int>> {
return magicSquare(emptySolution(size)).firstOrNull()?.rows() ?: emptyList()
}
private fun magicSquare(s: Solution): Sequence<Solution> {
if (s.isComplete()) return sequenceOf(s)
return s.nextSteps()
.filter { it.isValid() }
.flatMap { magicSquare(it) }
}
private fun emptySolution(size: Int) = Solution(list = emptyList(), size = size)
private data class Solution(val list: List<Int>, val size: Int) {
private val targetSum = (1..(size * size)).sum() / 3
fun isComplete() = list.size == size * size
fun nextSteps() =
((size * size).downTo(1) - list).asSequence()
.map { step -> copy(list = list + step) }
fun isValid() =
(rows() + columns() + diagonals())
.filterNot { it.contains(0) }
.all { it.sum() == targetSum }
fun rows() =
(0 until size).map { row ->
(0 until size).map { column ->
this[row * size + column]
}
}
fun columns() =
(0 until size).map { column ->
(0 until size).map { row ->
this[row * size + column]
}
}
fun diagonals() =
listOf(
(0 until size).map { i -> this[i * size + i] },
(0 until size).map { i -> this[i * size + (size - i - 1)] }
)
private operator fun get(i: Int) = if (i < list.size) list[i] else 0
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,101 | katas | The Unlicense |
untitled/src/main/kotlin/Day2.kt | jlacar | 572,845,298 | false | {"Kotlin": 41161} | class Day2(private val fileName: String) : AocSolution {
override val description: String get() = "Day 2 - Rock Paper Scissors ($fileName)"
private val input = InputReader(fileName).lines
override fun part1() = input.sumOf { rpsScore(it) }
override fun part2() = input.sumOf { rpsStrategicScore(it) }
}
fun rpsScore(round: String): Int {
val (opponentMove, yourMove) = round.split(" ")
return roundScore(rpsPoint(yourMove), rpsPoint(opponentMove))
}
fun rpsStrategicScore(round: String): Int {
val (opponentMove, strategy) = round.split(" ")
val oppPt = rpsPoint(opponentMove)
val youPt = strategicPoint(oppPt, resultWanted(strategy))
return roundScore(youPt, oppPt)
}
fun rpsPoint(move: String) = pointsFor[move] ?: 0
private val pointsFor = mapOf("A" to 1, "X" to 1, "B" to 2, "Y" to 2, "C" to 3, "Z" to 3)
private fun roundScore(you: Int, opp: Int) = you + score[result(you, opp)]
private val score = arrayOf(3, 6, 0)
/*
you 1 1 2 2 3 3 1 - rock
opp 2 3 1 3 1 2 2 - paper
dif -1 -2 1 -1 2 1 3 - scissors
+3%3 2 1 1 2 2 1
L W W L L W
*/
private fun result(you: Int, opp: Int) = (you - opp + 3) % 3
private const val DRAW = 0
private const val WIN = 1
private const val LOSE = 2
private val defeat = arrayOf(0, 2, 3, 1)
private val loseTo = arrayOf(0, 3, 1, 2)
fun strategicPoint(opponent: Int, resultWanted: Int) =
when (resultWanted) {
DRAW -> opponent
WIN -> defeat[opponent]
else -> loseTo[opponent]
}
private fun resultWanted(strategy: String) =
when (strategy) {
"X" -> LOSE
"Y" -> DRAW
else -> WIN
}
fun main() {
Day2("Day2-sample.txt") solution {
part1() shouldBe 15
part2() shouldBe 12
}
Day2("Day2.txt") solution {
part1() shouldBe 14264
part2() shouldBe 12382
}
Day2("Day2-alt.txt") solution {
part1() shouldBe 13268
part2() shouldBe 15508
}
} | 0 | Kotlin | 0 | 2 | dbdefda9a354589de31bc27e0690f7c61c1dc7c9 | 1,990 | adventofcode2022-kotlin | The Unlicense |
src/2022/Day04.kt | bartee | 575,357,037 | false | {"Kotlin": 26727} | fun main () {
fun createRangeFromDelimiters(it: String) : List<Int> {
val borders = it.split("-")
val list = mutableListOf<Int>()
for (i in borders[0].toInt().rangeTo(borders[1].toInt())) {
list.add(i)
}
return list
}
fun isOverlapping(list1: List<Int>, list2: List<Int>): Boolean {
// Check if list1 exists in list2
println("Verifying (${list1.first()}-${list1.last()} and ${list2.first()}-${list2.last()})")
if (list1.last() < list2.first() || list1.first() > list2.last()){
println("Lists are way out of range (${list1.first()}-${list1.last()} and ${list2.first()}-${list2.last()})")
return false
}
if (list1.first() >= list2.first() && list1.last() <= list2.last()){
println("The second list contains the first one")
return true
} else if (list2.first() >= list1.first() && list2.last() <= list1.last()) {
println("The first list contains the second one")
return true
}
println("NO - list1 and list2 do not overlap")
return false
}
fun isPartiallyOverlapping(list1: List<Int>, list2: List<Int>): Boolean {
val res1 = list1.intersect(list2)
val res2 = list2.intersect(list1)
if (res1.size > 0 || res2.size > 0){
println("${res1.size} items from list1 overlap list2, or ${res2.size} items from list 2 overlap list 1")
return true
}
return false
}
fun findFullyOverlappingSectionSequences(input:List<String>): Int {
var sequencesFound = 0
input.map {
val lists = it.split(",").map {
createRangeFromDelimiters(it)
}
val list1 = lists.first()
val list2 = lists.last()
if(isOverlapping(list1, list2)){
sequencesFound +=1
}
}
println("$sequencesFound overlaps found")
return sequencesFound
}
fun findPartiallyOverlappingSectionSequences(input:List<String>): Int {
var sequencesFound = 0
input.map {
val lists = it.split(",").map {
createRangeFromDelimiters(it)
}
val list1 = lists.first()
val list2 = lists.last()
if(isPartiallyOverlapping(list1, list2)){
sequencesFound +=1
}
}
println("$sequencesFound overlaps found")
return sequencesFound
}
// test if implementation meets criteria from the description, like:
val test_input = readInput("resources/day04_example")
check(findFullyOverlappingSectionSequences(test_input) == 2)
check(findPartiallyOverlappingSectionSequences(test_input) == 4)
// check(part2(test_input) == 12)
// Calculate the results from the input:
val input = readInput("resources/day04_dataset")
findFullyOverlappingSectionSequences(input)
findPartiallyOverlappingSectionSequences(input)
} | 0 | Kotlin | 0 | 0 | c7141d10deffe35675a8ca43297460a4cc16abba | 2,733 | adventofcode2022 | Apache License 2.0 |
src/Day11.kt | mvanderblom | 573,009,984 | false | {"Kotlin": 25405} | val operations = mapOf(
"+" to {a: Long, b: Long -> a + b},
"*" to {a: Long, b: Long -> a * b}
)
data class ItemForMonkey(val item: Long, val monkey: Int)
class Monkey(
val items: MutableList<Long>,
val operation: String,
val divisibleBy: Long,
val trueMonkeyIndex: Int,
val falseMonkeyIndex: Int,
var inspectedItems: Long = 0) {
private fun inspectItem(old: Long): Long {
inspectedItems++
val (first, operator , second) = operation.replace("old", old.toString()).split(" ")
return operations.getValue(operator)(first.toLong(), second.toLong())
}
fun executeRound(divideFunction: (Long) -> Long): List<ItemForMonkey> {
val itemsForMonkey = items.map {
var newVal = divideFunction(inspectItem(it))
if (newVal % divisibleBy == 0L)
ItemForMonkey(newVal, trueMonkeyIndex)
else
ItemForMonkey(newVal, falseMonkeyIndex)
}
items.clear()
return itemsForMonkey
}
override fun toString(): String {
return "Monkey(items=$items, $inspectedItems)"
}
companion object {
fun parse(input: List<String>): Monkey {
println(input)
val items = input[1].substring(18).split(", ").map { it.toLong() }
val operation = input[2].substring(19)
val divisibleBy = input[3].substring(21).toLong()
val trueMonkeyIndex = input[4].substring(29).toInt()
val falseMonkeyIndex = input[5].substring(30).toInt()
return Monkey(items.toMutableList(), operation, divisibleBy, trueMonkeyIndex, falseMonkeyIndex)
}
}
}
fun main() {
val dayName = 11.toDayName()
fun executeRound(monkeys: List<Monkey>, divider: (Long) -> Long) {
monkeys.forEach { monkey ->
val itemsForMonkey = monkey.executeRound(divider)
itemsForMonkey.forEach { (item, monkeyIndex) ->
monkeys[monkeyIndex].items.add(item)
}
}
}
fun calculateMonkeyBusiness(monkeys: List<Monkey>): Long {
val (first, second) = monkeys
.map { it.inspectedItems }
.sortedDescending()
.take(2)
return first * second
}
fun part1(input: List<String>): Long {
val monkeys = input.chunked(7)
.map(Monkey.Companion::parse)
repeat(20) { i ->
executeRound(monkeys) { it / 3 }
println("Round $i")
}
return calculateMonkeyBusiness(monkeys)
}
fun part2(input: List<String>): Long {
val magicNumber = input
.filter { it.contains("divisible by") }
.map { it.substring(21).toInt() }
.reduce(Int::times)
val monkeys = input.chunked(7)
.map(Monkey.Companion::parse)
repeat(10_000) {i ->
executeRound(monkeys) { it % magicNumber }
println("Round $i")
}
return calculateMonkeyBusiness(monkeys)
};
val testInput = readInput("${dayName}_test")
val input = readInput(dayName)
// Part 1
val testOutputPart1 = part1(testInput)
testOutputPart1 isEqualTo 10605L
val outputPart1 = part1(input)
outputPart1 isEqualTo 112815L
// Part 2
val testOutputPart2 = part2(testInput)
testOutputPart2 isEqualTo 2713310158L
val outputPart2 = part2(input)
outputPart2 isEqualTo null
}
| 0 | Kotlin | 0 | 0 | ba36f31112ba3b49a45e080dfd6d1d0a2e2cd690 | 3,522 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/l_sieve/CountSemiprimes.kts | HungUnicorn | 219,005,946 | false | null | package l_sieve
import kotlin.math.pow
import kotlin.math.sqrt
fun solution(N: Int, P: IntArray, Q: IntArray): IntArray {
if (P.size != Q.size || P.isEmpty() || Q.isEmpty()) {
return emptyList<Int>().toIntArray()
}
if (N <= 3) {
val zeros = Array(P.size) { 0 }
return zeros.toIntArray()
}
val result = arrayListOf<Int>()
val limit = getLimit(N, Q)
val cumulativeNumSemiPrimes = getCumulativeNumSemiPrimes(limit)
for (i in P.indices) {
val numSemiPrimes = cumulativeNumSemiPrimes[Q[i]] - cumulativeNumSemiPrimes[P[i]-1]
result.add(numSemiPrimes)
}
return result.toIntArray()
}
fun getLimit(N: Int, Q: IntArray): Int {
var limit: Int = Q.max()!!
if (limit > N) {
limit = N
}
return limit
}
fun sieveSimple(n: Int): Array<Boolean> {
val indices = Array(n + 1) { true }
indices[0] = false
indices[1] = false
val limit = sqrt(n.toDouble()).toInt()
val range = 2..limit
for (i in range) {
if (indices[i]) {
var j = i.toDouble().pow(2).toInt()
while (j <= n) {
indices[j] = false
j += i
}
}
}
return indices
}
fun getPrimes(sieved: Array<Boolean>): IntArray {
val result = arrayListOf<Int>()
for (i in sieved.indices) {
if (sieved[i]) {
result.add(i)
}
}
return result.toIntArray()
}
fun getCumulativeNumSemiPrimes(n: Int): List<Int> {
val sieved = sieveSimple(n / 2)
val primes = getPrimes(sieved)
val cumulativeNumSemiPrimes = Array(n + 1) { 0 }
for (p1 in primes) {
for (p2 in primes) {
if (p1 * p2 > n || p2 > p1) {
break
}
cumulativeNumSemiPrimes[p1 * p2] = 1
}
}
for (i in 1 .. n) {
cumulativeNumSemiPrimes[i] += cumulativeNumSemiPrimes[i - 1]
}
return cumulativeNumSemiPrimes.toList()
}
check(
listOf(10, 4, 0).toIntArray().contentEquals(
solution(
26,
listOf(1, 4, 16).toIntArray(),
listOf(26, 10, 20).toIntArray()
)
)
)
| 0 | Kotlin | 1 | 10 | e53167d4db538a963af8de1be7038380577ea2e6 | 2,170 | Kotlin-Solution-for-Codility-Lesson | MIT License |
src/day08/Day08.kt | iulianpopescu | 572,832,973 | false | {"Kotlin": 30777} | package day08
import readInput
import kotlin.math.max
private const val DAY = "08"
private const val DAY_TEST = "day${DAY}/Day${DAY}_test"
private const val DAY_INPUT = "day${DAY}/Day${DAY}"
fun main() {
fun isTreeVisible(i: Int, j: Int, input: List<String>): Boolean {
if (i == 0 || j == 0 || i == input.lastIndex || j == input[i].lastIndex) return true
val tree = input[i][j].digitToInt()
val visibleHLeft = input[i].substring(0 until j).all { it.digitToInt() < tree }
val visibleHRight = input[i].substring(j + 1..input[i].lastIndex).all { it.digitToInt() < tree }
val visibleVTop = input.subList(0, i).map { it[j] }.all { it.digitToInt() < tree }
val visibleVBottom = input.subList(i + 1, input.size).map { it[j] }.all { it.digitToInt() < tree }
return visibleHLeft || visibleHRight || visibleVTop || visibleVBottom
}
var lastVisibleTree = 0
fun shouldCountTree(viewingTree: Int, currentTree: Int): Boolean {
return if (currentTree in lastVisibleTree until viewingTree) {
lastVisibleTree = currentTree
true
} else if (currentTree > lastVisibleTree) {
lastVisibleTree = currentTree
true
} else false
}
fun countTreeVisibleScore(i: Int, j: Int, input: List<String>): Int {
val tree = input[i][j].digitToInt()
var counting = true
val hLeftCount = input[i]
.substring(0 until j)
.reversed()
.map { it.digitToInt() }
.takeWhile { currTree ->
val shouldCount = counting
if (currTree >= tree) counting = false
shouldCount
}
.size
lastVisibleTree = 0
counting = true
val hRightCount = input[i]
.substring(j + 1..input[i].lastIndex)
.map { it.digitToInt() }
.takeWhile { currTree ->
val shouldCount = counting
if (currTree >= tree) counting = false
shouldCount
}
.size
lastVisibleTree = 0
counting = true
val vTopCount = input.subList(0, i).reversed().map { it[j].digitToInt() }
.takeWhile { currTree ->
val shouldCount = counting
if (currTree >= tree) counting = false
shouldCount
}
.size
lastVisibleTree = 0
counting = true
val vBottomCount = input.subList(i + 1, input.size).map { it[j].digitToInt() }
.takeWhile { currTree ->
val shouldCount = counting
if (currTree >= tree) counting = false
shouldCount
}
.size
// println("$i:$j -> $hLeftCount $hRightCount $vTopCount $vBottomCount")
return hLeftCount * hRightCount * vTopCount * vBottomCount
}
fun part1(input: List<String>): Int {
var total = 0
for (i in input.indices) {
for (j in input[i].indices) {
if (isTreeVisible(i, j, input)) {
total += 1
}
}
}
return total
}
fun part2(input: List<String>): Int {
var maxim = 0
for (i in input.indices) {
for (j in input[i].indices) {
val treeScore = countTreeVisibleScore(i, j, input)
maxim = max(maxim, treeScore)
}
}
return maxim
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(DAY_TEST)
check(part1(testInput) == 21)
println(part2(testInput))
check(part2(testInput) == 8)
val input = readInput(DAY_INPUT)
println(part1(input))
println(part2(input))
// 2156 too low
} | 0 | Kotlin | 0 | 0 | 4ff5afb730d8bc074eb57650521a03961f86bc95 | 3,840 | AOC2022 | Apache License 2.0 |
src/Day20/Day20.kt | martin3398 | 436,014,815 | false | {"Kotlin": 63436, "Python": 5921} | fun Array<Array<Boolean>>.print() {
for (row in this) {
row.print()
}
}
fun Array<Boolean>.print() {
for (e in this) {
print(if (e) "#" else ".")
}
println()
}
fun Boolean.toInt() = if (this) 1 else 0
fun main() {
val paddingSize = 200
fun preprocess(input: List<String>): Pair<Array<Array<Boolean>>, Array<Boolean>> {
val algorithm = input[0].map { it == '#' }.toTypedArray()
val ySize = input.size - 2 + 2 * paddingSize
val xSize = input[2].length + 2 * paddingSize
val res = Array<Array<Boolean>>(ySize) { Array(xSize) { false } }
for (i in 0 until paddingSize) {
res[i] = Array(xSize) { false }
res[ySize - 1 - i] = Array(xSize) { false }
}
for ((i, e) in input.drop(2).withIndex()) {
res[i + paddingSize] =
Array(paddingSize) { false } + e.map { it == '#' }.toTypedArray() + Array(paddingSize) { false }
}
return Pair(res, algorithm)
}
fun applyAlgorithm(input: Array<Array<Boolean>>, algorithm: Array<Boolean>): Array<Array<Boolean>> {
val res = Array(input.size) { Array(input[0].size) { false } }
for (y in 1 until input.size - 1) {
for (x in 1 until input[0].size - 1) {
val bits = input[y - 1].sliceArray(x - 1..x + 1) +
input[y].sliceArray(x - 1..x + 1) +
input[y + 1].sliceArray(x - 1..x + 1)
val index = bits.joinToString("") { it.toInt().toString() }.toInt(2)
res[y][x] = algorithm[index]
}
}
return res
}
fun iterate(input: Array<Array<Boolean>>, algorithm: Array<Boolean>, num: Int): Int {
var intermediate = input
for (i in 0 until num) {
intermediate = applyAlgorithm(intermediate, algorithm)
}
intermediate = intermediate.map { it.sliceArray(num until it.size - num) }
.slice(num until intermediate.size - num).toTypedArray()
return intermediate.sumOf { it.count { x -> x } }
}
fun part1(input: Array<Array<Boolean>>, algorithm: Array<Boolean>): Int {
return iterate(input, algorithm, 2)
}
fun part2(input: Array<Array<Boolean>>, algorithm: Array<Boolean>): Int {
return iterate(input, algorithm, 50)
}
val (testInput, testAlgorithm) = preprocess(readInput(20, true))
val (input, algorithm) = preprocess(readInput(20))
check(part1(testInput, testAlgorithm) == 35)
println(part1(input, algorithm))
check(part2(testInput, testAlgorithm) == 3351)
println(part2(input, algorithm))
}
| 0 | Kotlin | 0 | 0 | 085b1f2995e13233ade9cbde9cd506cafe64e1b5 | 2,670 | advent-of-code-2021 | Apache License 2.0 |
src/problems/day7/part1/part1.kt | klnusbaum | 733,782,662 | false | {"Kotlin": 43060} | package problems.day7.part1
import java.io.File
private const val inputFile = "input/day7/input.txt"
//private const val testFile = "input/day7/test.txt"
fun main() {
val scoreSum = File(inputFile).bufferedReader().useLines { sumScores(it) }
println("Sum of scores is $scoreSum")
}
private fun sumScores(lines: Sequence<String>): Int {
return lines.map { it.toHand() }
.sorted()
.foldIndexed(0) { index, acc, hand -> acc + ((index + 1) * hand.bid) }
}
private data class Hand(val cards: List<Card>, val bid: Int, val handType: HandType) : Comparable<Hand> {
override fun compareTo(other: Hand): Int {
if (this.handType == other.handType) {
return this.cards.compareTo(other.cards)
}
return this.handType.compareTo(other.handType)
}
}
private fun List<Card>.compareTo(other: List<Card>): Int {
for (pair in this.asSequence().zip(other.asSequence())) {
if (pair.first != pair.second) {
return pair.first.compareTo(pair.second)
}
}
return 0
}
private fun String.toHand(): Hand {
val cards = this.substringBefore(" ").map { it.toCard() }
val bid = this.substringAfter(" ").toInt()
val handType = cards.toHandType()
return Hand(cards, bid, handType)
}
private enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND,
}
private fun List<Card>.toHandType(): HandType {
val typeHistogram = mutableMapOf<Card, UInt>()
for (card in this) {
typeHistogram[card] = typeHistogram.getOrDefault(card, 0u) + 1u
}
return when {
typeHistogram.any { it.value == 5u } -> HandType.FIVE_OF_A_KIND
typeHistogram.any { it.value == 4u } -> HandType.FOUR_OF_A_KIND
typeHistogram.any { it.value == 3u } and typeHistogram.any { it.value == 2u } -> HandType.FULL_HOUSE
typeHistogram.any { it.value == 3u } -> HandType.THREE_OF_A_KIND
typeHistogram.filter { it.value == 2u }.count() == 2 -> HandType.TWO_PAIR
typeHistogram.any { it.value == 2u } -> HandType.ONE_PAIR
else -> HandType.HIGH_CARD
}
}
private enum class Card {
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE,
}
private fun Char.toCard() = when (this) {
'2' -> Card.TWO
'3' -> Card.THREE
'4' -> Card.FOUR
'5' -> Card.FIVE
'6' -> Card.SIX
'7' -> Card.SEVEN
'8' -> Card.EIGHT
'9' -> Card.NINE
'T' -> Card.TEN
'J' -> Card.JACK
'Q' -> Card.QUEEN
'K' -> Card.KING
'A' -> Card.ACE
else -> throw IllegalArgumentException("Char $this does not have a corresponding card")
} | 0 | Kotlin | 0 | 0 | d30db2441acfc5b12b52b4d56f6dee9247a6f3ed | 2,743 | aoc2023 | MIT License |
src/Day09.kt | wlghdu97 | 573,333,153 | false | {"Kotlin": 50633} | import kotlin.math.abs
import kotlin.math.sign
enum class Direction {
U, D, L, R;
}
class Instruction(val direction: Direction, val distance: Int)
data class Position(val x: Int, val y: Int)
fun List<Instruction>.calculateTailVisitedPositionCount(ropeLength: Int = 2): Int {
assert(ropeLength > 1)
val tailVisited = hashSetOf<Position>()
val rope = Array(ropeLength) { Position(0, 0) }
this.forEach { inst ->
repeat(inst.distance) {
for (headIndex in 0 until (ropeLength - 1)) {
val oldHead = rope[headIndex]
val head = if (headIndex == 0) {
when (inst.direction) {
Direction.U -> oldHead.copy(y = oldHead.y - 1)
Direction.D -> oldHead.copy(y = oldHead.y + 1)
Direction.L -> oldHead.copy(x = oldHead.x - 1)
Direction.R -> oldHead.copy(x = oldHead.x + 1)
}.apply {
rope[headIndex] = this
}
} else {
oldHead
}
val tailIndex = headIndex + 1
val tail = rope[tailIndex]
var nextTailX = tail.x
var nextTailY = tail.y
if (abs(head.x - nextTailX) > 1) {
nextTailX += (head.x - nextTailX).sign
if (head.y != nextTailY) {
nextTailY += (head.y - nextTailY).sign
}
}
if (abs(head.y - nextTailY) > 1) {
nextTailY += (head.y - nextTailY).sign
if (head.x != nextTailX) {
nextTailX += (head.x - nextTailX).sign
}
}
if (tail.x != nextTailX || tail.y != nextTailY) {
if (tailIndex == (ropeLength - 1)) {
tailVisited.add(tail)
}
rope[tailIndex] = Position(nextTailX, nextTailY)
}
}
}
}
tailVisited.add(rope[ropeLength - 1])
return tailVisited.count()
}
fun makeTestInstructions(): List<Instruction> {
return listOf(
"R 4", "U 4", "L 3", "D 1",
"R 4", "D 1", "L 5", "R 2"
).map { parseInstruction(it) }
}
fun makeTestInstructions2(): List<Instruction> {
return listOf(
"R 5", "U 8", "L 8", "D 3",
"R 17", "D 10", "L 25", "U 20"
).map { parseInstruction(it) }
}
fun parseInstruction(raw: String): Instruction {
val (dir, dist) = raw.split(" ")
val direction = Direction.valueOf(dir)
val distance = dist.toInt()
return Instruction(direction, distance)
}
fun main() {
fun test1(): Int {
return makeTestInstructions().calculateTailVisitedPositionCount()
}
fun part1(input: List<String>): Int {
return input.map { parseInstruction(it) }.calculateTailVisitedPositionCount()
}
fun test2(): Int {
return makeTestInstructions().calculateTailVisitedPositionCount(10)
}
fun test3(): Int {
return makeTestInstructions2().calculateTailVisitedPositionCount(10)
}
fun part2(input: List<String>): Int {
return input.map { parseInstruction(it) }.calculateTailVisitedPositionCount(10)
}
val input = readInput("Day09")
println(test1())
println(part1(input))
println(test2())
println(test3())
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2b95aaaa9075986fa5023d1bf0331db23cf2822b | 3,512 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/pub/edholm/aoc2017/day2/Checksum.kt | Edholm | 112,762,269 | false | null | package pub.edholm.aoc2017.day2
import pub.edholm.aoc2017.utils.getInputForDay
fun main(args: Array<String>) {
val inputForDay2 = getInputForDay(2)
val matrix = buildMatrix(inputForDay2)
val checksum = Checksum()
println("Day 2:")
println(" Part I: ${checksum.calculatePartOne(matrix)}")
println(" Part II: ${checksum.calculatePartTwo(matrix)}")
}
private fun buildMatrix(input: String): List<List<Int>> {
return input
.trim()
.split("\n")
.map {
it.split("\t")
.map(String::toInt)
}
}
internal class Checksum {
fun calculatePartOne(matrix: List<List<Int>>): Int {
return matrix
.map { it.getMinAndMax() }
.map { it.diff() }
.sum()
}
fun calculatePartTwo(matrix: List<List<Int>>): Int {
return matrix
.map { it.findDivisible() }
.map { it.divide() }
.sum()
}
private fun MinMax.diff(): Int {
return this.max - this.min
}
private fun List<Int>.getMinAndMax(): MinMax {
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
this.forEach {
if (it > max) {
max = it
}
if (it < min) {
min = it
}
}
return MinMax(min, max)
}
private fun List<Int>.findDivisible(): Pair<Int, Int> {
this.forEachIndexed { index, value ->
this.subList(index + 1, this.size).forEach { nxtValue ->
if (value % nxtValue == 0) {
return Pair(value, nxtValue)
} else if (nxtValue % value == 0) {
return Pair(nxtValue, value)
}
}
}
throw IllegalStateException("No divisible numbers found in $this")
}
private fun Pair<Int, Int>.divide() = this.first / this.second
}
private data class MinMax(val min: Int, val max: Int)
| 0 | Kotlin | 0 | 3 | 1a087fa3dff79f7da293852a59b9a3daec38a6fb | 1,737 | aoc2017 | The Unlicense |
src/Day03.kt | hoppjan | 573,053,610 | false | {"Kotlin": 9256} | fun main() {
val testLines = readInput("Day03_test")
val testResult1 = part1(testLines)
println("test part 1: $testResult1")
check(testResult1 == 157)
val testResult2 = part2(testLines)
println("test part 2: $testResult2")
check(testResult2 == 70)
val lines = readInput("Day03")
println("part 1: ${part1(lines)}")
println("part 2: ${part2(lines)}")
}
private fun part1(input: List<String>) = input.sumOf { line ->
line.toCompartments().findCommon().toPriority()
}
private fun String.toCompartments() = substring(0, length / 2) to substring(length / 2)
private fun Pair<String, String>.findCommon() = first.first { char -> second.contains(char) }
private fun Triple<String, String, String>.findCommon() =
first.first { char -> second.contains(char) && third.contains(char) }
private fun Char.toPriority() = (('a'..'z') + ('A'..'Z')).indexOf(this) + 1
private fun part2(input: List<String>) = input
.windowed(size = 3, step = 3) { (first, second, third) ->
Triple(first, second, third).findCommon().toPriority()
}.sum()
private fun Iterable<Int>.sum() = sumOf { it }
| 0 | Kotlin | 0 | 0 | f83564f50ced1658b811139498d7d64ae8a44f7e | 1,140 | advent-of-code-2022 | Apache License 2.0 |
gcj/y2020/round1b/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2020.round1b
private fun greedy(init: List<Int>): String {
var a = init
val moves = mutableListOf<String>()
while (a.zipWithNext().any { it.first > it.second }) {
val pairs = mutableMapOf<Int, Pair<Int, Int>>()
loop@for (i in 1 until a.size) for (j in i + 1 until a.size) {
val score = sequenceOf(a[0] != a[j - 1], a[i - 1] == a[i], a[i - 1] != a[j], a[j - 1] == a[j]).count { it }
pairs[score] = i to j
if (score == 0) break@loop
}
val (i, j) = pairs[pairs.keys.minOrNull()]!!
a = a.subList(i, j) + a.take(i) + a.drop(j)
moves.add("$i ${j - i}")
}
return "${moves.size}\n${moves.joinToString("\n")}"
}
private fun solve(): String {
val (r, s) = readInts()
val a = List(s) { List(r) { it } }.flatten()
return greedy(a)
}
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,024 | competitions | The Unlicense |
src/main/kotlin/io/github/aarjavp/aoc/day03/Day03.kt | AarjavP | 433,672,017 | false | {"Kotlin": 73104} | package io.github.aarjavp.aoc.day03
import io.github.aarjavp.aoc.readFromClasspath
class Day03 {
data class PowerConsumption(val gammaRate: Int, val epsilonRate: Int) {
val value = gammaRate * epsilonRate
}
fun calculatePowerConsumption(diagnostic: Sequence<String>, bits: Int): PowerConsumption {
val counts = IntArray(bits)
var lineCount = 0
for (line in diagnostic) {
lineCount++
for (i in counts.indices) {
if (line[i] == '1') counts[i]++
}
}
val gamma = counts.map { if (it > lineCount / 2) 1 else 0 }.joinToString(separator = "").toInt(2)
val epsilon = gamma.inv() and ("1".repeat(counts.size).toInt(2))
return PowerConsumption(gamma, epsilon)
}
data class LifeSupportRating(val oxygenGeneratorRating: Int, val co2ScrubberRating: Int) {
val value = oxygenGeneratorRating * co2ScrubberRating
}
fun calculateLifeSupportRating(diagnostic: Sequence<String>, bits: Int): LifeSupportRating {
fun List<String>.partitionMostAndLeastCommon(position: Int): Pair<List<String>, List<String>> {
val (ones, zeroes) = partition { it[position] == '1' }
return if (ones.size >= zeroes.size) ones to zeroes else zeroes to ones
}
var oxygenCandidates: List<String>
var co2ScrubberCandidates: List<String>
diagnostic.toList().partitionMostAndLeastCommon(0).run {
oxygenCandidates = first
co2ScrubberCandidates = second
}
for (i in 1 until bits) {
if (oxygenCandidates.size > 1) {
oxygenCandidates = oxygenCandidates.partitionMostAndLeastCommon(i).first
}
if (co2ScrubberCandidates.size > 1) {
co2ScrubberCandidates = co2ScrubberCandidates.partitionMostAndLeastCommon(i).second
}
if (oxygenCandidates.size == 1 && co2ScrubberCandidates.size == 1) {
break
}
}
if (oxygenCandidates.size != 1 && co2ScrubberCandidates.size != 1) {
error("expected only one value for oxygen and co2 but got oxygen: $oxygenCandidates, co2: $co2ScrubberCandidates")
}
return LifeSupportRating(oxygenCandidates.first().toInt(2), co2ScrubberCandidates.first().toInt(2))
}
}
fun main() {
val solution = Day03()
println(readFromClasspath("Day03.txt").useLines { solution.calculatePowerConsumption(it, 12).value })
println(readFromClasspath("Day03.txt").useLines { solution.calculateLifeSupportRating(it, 12).value })
}
| 0 | Kotlin | 0 | 0 | 3f5908fa4991f9b21bb7e3428a359b218fad2a35 | 2,620 | advent-of-code-2021 | MIT License |
src/day02/day02.kt | PS-MS | 572,890,533 | false | null | package day02
import readInput
sealed class RockPaperScissors(val value: Int) {
abstract infix fun beats(other: RockPaperScissors): Boolean
abstract fun fixResult(x: String): RockPaperScissors?
class Rock : RockPaperScissors(1) {
override fun beats(other: RockPaperScissors): Boolean {
return other is Scissors
}
override fun fixResult(x: String): RockPaperScissors? {
return when (x) {
"Y" -> Rock() // draw
"X" -> Scissors()
"Z" -> Paper()
else -> null
}
}
}
class Paper : RockPaperScissors(2) {
override fun beats(other: RockPaperScissors): Boolean {
return other is Rock
}
override fun fixResult(x: String): RockPaperScissors? {
return when (x) {
"Y" -> Paper()
"X" -> Rock()
"Z" -> Scissors()
else -> null
}
}
}
class Scissors : RockPaperScissors(3) {
override fun beats(other: RockPaperScissors): Boolean {
return other is Paper
}
override fun fixResult(x: String): RockPaperScissors? {
return when (x) {
"Y" -> Scissors() // draw
"X" -> Paper() // lose
"Z" -> Rock() // win
else -> null
}
}
}
}
fun main() {
infix fun RockPaperScissors.versus(other: RockPaperScissors): Int {
val result = when {
this beats other -> 6
other beats this -> 0
else -> 3
}
return result + this.value
}
fun String.toRockPaperScissors(): RockPaperScissors? {
return when (this) {
"A","X" -> RockPaperScissors.Rock()
"B","Y" -> RockPaperScissors.Paper()
"C","Z" -> RockPaperScissors.Scissors()
else -> null
}
}
fun calculateScore(a: String, b: String): Int {
val them = a.toRockPaperScissors()
val us = them?.fixResult(b)
return if(them != null && us != null) {
return us versus them
} else 0
}
fun parseRows(input: List<String>): List<List<String>> {
return input.map { rounds -> rounds.split(" ")}
}
fun part1(input: List<String>): Int {
val rounds = parseRows(input).map { it.mapNotNull { it.toRockPaperScissors() } }
return rounds.sumOf { val (a,b) = it; b versus a }
}
fun part2(input: List<String>): Int {
val rounds = parseRows(input)
return rounds.sumOf { val (a,b) = it; calculateScore(a, b) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day02/test")
check(part1(testInput) == 15)
val input = readInput("day02/real")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 24f280a1d8ad69e83755391121f6107f12ffebc0 | 2,933 | AOC2022 | Apache License 2.0 |
src/main/kotlin/adventofcode/day2/Day2.kt | SanderSmee | 160,828,336 | false | null | package adventofcode.day2
import java.io.File
/**
*
*/
fun main(args: Array<String>) {
val input = File(ClassLoader.getSystemResource("day-02-input.txt").file).readLines()
// part 1
val (twos, threes, checksum) = calculateChecksum(input)
println("$twos x $threes = $checksum")
// part 2
val firstDiff = findCloseIds(input).first()
val result = firstDiff.first.removeRange(firstDiff.indices.first()..firstDiff.indices.first())
println("${result}")
}
private fun calculateChecksum(input: List<String>): Triple<Int, Int, Int> {
val countedBoxIds = input.map { toLetterCount(it) }
val twosCount = countedBoxIds.filter { it.countsForTwo() }.size
val threesCount = countedBoxIds.filter { it.countsForThree() }.size
return Triple(twosCount, threesCount, twosCount * threesCount)
}
private fun toLetterCount(boxId: String): BoxIdLetterCount {
val letterCounts = boxId.toList()
.groupingBy { it }
.eachCount()
.map { LetterCount(it.key, it.value) }
return BoxIdLetterCount(boxId, letterCounts)
}
data class BoxIdLetterCount(val boxId: String, val letters: List<LetterCount>) {
fun countsForTwo() = letters.find { it.count == 2 } != null
fun countsForThree() = letters.find { it.count == 3 } != null
}
class LetterCount(val letter: Char, val count: Int) {
}
private fun findCloseIds(boxIds: List<String>): MutableList<Diff> {
val boxIdsDifferentBy1 = mutableListOf<Diff>()
for (first in boxIds) {
for (second in boxIds) {
val diff = first.diff(second)
if (diff.indices.size == 1) {
boxIdsDifferentBy1.add(diff)
}
}
}
return boxIdsDifferentBy1
}
fun String.diff(other: String): Diff {
val indices = mutableListOf<Int>()
for (i in 0 until Math.min(this.length, other.length)) {
if (this[i] != other[i]) {
indices.add(i)
}
}
return Diff(this, other, indices)
}
data class Diff(val first:String, val second:String, val indices:List<Int>)
| 0 | Kotlin | 0 | 0 | e5fc4aef3b4fc635d04335062585da5c1e810555 | 2,061 | adventofcode-2018 | The Unlicense |
src/day08/Day08.kt | taer | 573,051,280 | false | {"Kotlin": 26121} | package day08
import readInput
class Cell(val value: Int, var visible: Boolean = false){
override fun toString(): String {
return "$value $visible"
}
}
fun main() {
fun mySeq(
rows: Iterable<Int>,
columns: Iterable<Int>
) = sequence {
rows.forEach { r ->
columns.forEach { c ->
yield(r to c)
}
}
}
fun part1(input: List<String>): Int {
val forest = input.map { it.map { Cell(it.digitToInt()) }.toTypedArray() }.toTypedArray()
val rows = forest.indices
val columns = forest.first().indices
rows.forEach { r ->
var max = -1
columns.forEach { c ->
val cell = forest[r][c]
if (cell.value > max) {
max = cell.value
cell.visible = true
}
}
max = -1
columns.reversed().forEach { c ->
val cell = forest[r][c]
if (cell.value > max) {
max = cell.value
cell.visible = true
}
}
}
columns.forEach { c ->
var max = -1
rows.forEach { r ->
val cell = forest[r][c]
if (cell.value > max) {
max = cell.value
cell.visible = true
}
}
max = -1
rows.reversed().forEach { r ->
val cell = forest[r][c]
if (cell.value > max) {
max = cell.value
cell.visible = true
}
}
}
return forest.sumOf { it.count { it.visible } }
}
fun getValue(forest: Array<Array<Cell>>, row: Int, col: Int): Int {
val columns = forest.first().indices
val rows = forest.indices
val ourHeight = forest[row][col].value
var scoreUp = 0
var scoreDown = 0
var scoreL = 0
var scoreR = 0
for (x in row - 1 downTo 0) {
scoreUp++
if (ourHeight <= forest[x][col].value) {
break;
}
}
for (x in row + 1..rows.last) {
scoreDown++
if (ourHeight <= forest[x][col].value) {
break;
}
}
for (y in col + 1..columns.last) {
scoreR++
if (ourHeight <= forest[row][y].value) {
break;
}
}
for (y in col - 1 downTo 0) {
scoreL++
if (ourHeight <= forest[row][y].value) {
break;
}
}
return scoreUp * scoreDown * scoreL * scoreR
}
fun part2(input: List<String>): Int {
val forest = input.map { it.map { Cell(it.digitToInt()) }.toTypedArray() }.toTypedArray()
val rows = forest.indices
val columns = forest.first().indices
return rows.maxOf { row ->
columns.maxOf { col->
getValue(forest, row, col)
}
}
}
val testInput = readInput("day08", true)
val input = readInput("day08")
check(part1(testInput) == 21){}
check(part2(testInput) == 8)
println(part1(input))
println(part2(input))
check(part1(input) == 1835)
check(part2(input) == 263670)
}
| 0 | Kotlin | 0 | 0 | 1bd19df8949d4a56b881af28af21a2b35d800b22 | 3,409 | aoc2022 | Apache License 2.0 |
src/main/kotlin/solutions/day19/Day19.kt | Dr-Horv | 570,666,285 | false | {"Kotlin": 115643} | package solutions.day19
import solutions.Solver
import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.max
enum class RobotType {
ORE,
CLAY,
OBSIDIAN,
GEODE
}
data class RobotCost(val ore: Int, val clay: Int = 0, val obsidian: Int = 0)
data class Blueprint(
val nbr: Int,
val costs: Map<RobotType, RobotCost>
)
data class State(
val blueprint: Blueprint,
val minute: Int,
val ores: Int,
val oreRobots: Int,
val clay: Int,
val clayRobots: Int,
val obsidian: Int,
val obsidianRobots: Int,
val geodes: Int,
val geodeRobots: Int,
val nextRobotToBuild: RobotType
)
fun State.canAffordToBuild(): Boolean {
val cost = blueprint.costs.getValue(nextRobotToBuild)
return ores >= cost.ore &&
clay >= cost.clay &&
obsidian >= cost.obsidian
}
fun State.build(next: RobotType = this.nextRobotToBuild): State {
val cost = blueprint.costs.getValue(nextRobotToBuild)
var oreRobotsNext = oreRobots
var clayRobotsNext = clayRobots
var obsidianRobotsNext = obsidianRobots
var geodeRobotsNext = geodeRobots
when (nextRobotToBuild) {
RobotType.ORE -> oreRobotsNext++
RobotType.CLAY -> clayRobotsNext++
RobotType.OBSIDIAN -> obsidianRobotsNext++
RobotType.GEODE -> geodeRobotsNext++
}
return this.copy(
ores = ores - cost.ore,
clay = clay - cost.clay,
obsidian = obsidian - cost.obsidian,
oreRobots = oreRobotsNext,
clayRobots = clayRobotsNext,
obsidianRobots = obsidianRobotsNext,
geodeRobots = geodeRobotsNext,
nextRobotToBuild = next
)
}
fun State.gather(n: Int = 1): State = this.copy(
minute = minute + n,
ores = ores + (oreRobots * n),
clay = clay + (clayRobots * n),
obsidian = obsidian + (obsidianRobots * n),
geodes = geodes + (geodeRobots * n)
)
class Day19 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val regex =
"Blueprint (\\d+): Each ore robot costs (\\d+) ore\\. Each clay robot costs (\\d+) ore\\. Each obsidian robot costs (\\d+) ore and (\\d+) clay\\. Each geode robot costs (\\d+) ore and (\\d+) obsidian\\.".toRegex()
val blueprints = mutableListOf<Blueprint>()
for (line in input) {
val result = regex.find(line)
if (result != null) {
val (nbrS, orcs, crcs, orocs, orccs, grocs, grobcs) = result.destructured
val oreRobotCost = RobotCost(orcs.toInt())
val clayRobotCost = RobotCost(crcs.toInt())
val obsidianRobotCost = RobotCost(orocs.toInt(), orccs.toInt())
val geodeRobotCost = RobotCost(ore = grocs.toInt(), obsidian = grobcs.toInt())
val costs = mapOf(
Pair(RobotType.ORE, oreRobotCost),
Pair(RobotType.CLAY, clayRobotCost),
Pair(RobotType.OBSIDIAN, obsidianRobotCost),
Pair(RobotType.GEODE, geodeRobotCost)
)
blueprints.add(
Blueprint(
nbrS.toInt(),
costs
)
)
}
if (partTwo && blueprints.size == 3) {
break
}
}
val end = if (!partTwo) {
24
} else {
32
}
val blueprintOutcome = mutableListOf<Pair<Blueprint, Int>>()
for (b in blueprints) {
val max = findOutcomes(b, end)
blueprintOutcome += Pair(b, max)
}
return if (!partTwo) {
blueprintOutcome.sumOf { it.first.nbr * it.second }.toString()
} else {
blueprintOutcome.fold(1) { acc, pair -> pair.second * acc }.toString()
}
}
private fun findOutcomes(blueprint: Blueprint, end: Int): Int {
val start1 = State(blueprint, 0, 0, 1, 0, 0, 0, 0, 0, 0, RobotType.ORE)
val start2 = State(blueprint, 0, 0, 1, 0, 0, 0, 0, 0, 0, RobotType.CLAY)
val inMemoryCache = mutableMapOf(Pair(end, 0))
return max(
findOutcomesFromState(start1, end, inMemoryCache),
findOutcomesFromState(start2, end, inMemoryCache)
)
}
private fun findOutcomesFromState(state: State, end: Int, cache: MutableMap<Int, Int>): Int {
val timeLeft = end - state.minute
if (timeLeft == 0) {
if (cache.getValue(end) < state.geodes) {
cache[end] = state.geodes
}
return state.geodes
}
val estimatedBest = state.geodes + state.geodeRobots * timeLeft + (timeLeft * (timeLeft + 1)) / 2
if (estimatedBest < cache.getValue(end)) {
return -1
}
if (state.canAffordToBuild()) {
val potentialRobotsToBuild = RobotType.values().filter { shouldBuildMore(state.build(), it) }
return potentialRobotsToBuild.maxOf {
findOutcomesFromState(
state.gather().build(it),
end,
cache
)
}
} else {
val minutesUntilCanAfford = calculateMinutesUntilCanAfford(state)
return if (minutesUntilCanAfford < timeLeft) {
findOutcomesFromState(state.gather(minutesUntilCanAfford), end, cache)
} else {
findOutcomesFromState(state.gather(timeLeft), end, cache)
}
}
}
private fun shouldBuildMore(state: State, type: RobotType): Boolean = when (type) {
RobotType.ORE -> state.oreRobots < state.blueprint.costs.values.maxOf { it.ore }
RobotType.CLAY -> state.clayRobots < state.blueprint.costs.values.maxOf { it.clay }
RobotType.OBSIDIAN -> state.clayRobots > 0 && state.obsidianRobots < state.blueprint.costs.values.maxOf { it.obsidian }
RobotType.GEODE -> state.obsidianRobots > 0
}
fun calculateMinutesUntilCanAfford(state: State): Int {
val cost = state.blueprint.costs.getValue(state.nextRobotToBuild)
val oreMinutes = if (state.ores < cost.ore) {
ceil(abs(state.ores - cost.ore) / state.oreRobots.toDouble()).toInt()
} else {
0
}
val clayMinutes = if (state.clay < cost.clay) {
ceil(abs(state.clay - cost.clay) / state.clayRobots.toDouble()).toInt()
} else {
0
}
val obsidianMinutes = if (state.obsidian < cost.obsidian) {
ceil(abs(state.obsidian - cost.obsidian) / state.obsidianRobots.toDouble()).toInt()
} else {
0
}
return listOf(oreMinutes, clayMinutes, obsidianMinutes).max()
}
}
| 0 | Kotlin | 0 | 2 | 6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e | 6,809 | Advent-of-Code-2022 | MIT License |
src/main/kotlin/com/dambra/adventofcode2018/day11/Grid.kt | pauldambra | 159,939,178 | false | null | package com.dambra.adventofcode2018.day11
class Grid(private val gridSerial: Int) {
//ugh topleft to gridsize to power
private val powersAt: MutableMap<Cell, MutableMap<Int, Int>> = mutableMapOf()
fun seekLargestThreeByThreeSquare(): Triple<Int, Cell, Int> {
return seekLargestCellSquareOfAnySize(3..3)
}
fun seekLargestCellSquareOfAnySize(gridSizes: IntRange = 1..300): Triple<Int, Cell, Int> {
val x = gridSizes.map { gridSize ->
gridSize to largestPowerLevelAtGridSize(gridSize)
}
.filterNot { it.second == null }
.maxBy { it.second!!.second }!!
//grid size, topLeft, power
return Triple(x.first, x.second!!.first, x.second!!.second)
}
private fun largestPowerLevelAtGridSize(
gridSize: Int
): Pair<Cell, Int>? {
val gridSides = 1..300
return gridSides
.map { x -> gridSides.map { y -> Cell(x, y) } }
.asSequence()
.flatten()
.filter { cell -> squareFitsInGrid(cell, gridSize) }
.map { cell ->
Pair(cell, powerForSquare(cell, gridSize))
}
.maxBy { it.second }
}
fun powerForSquare(topLeft: Cell, gridSize: Int): Int {
if (gridSize == 1) {
val powerAtFirstCell = powerLevelOf(Cell(topLeft.x, topLeft.y), gridSerial)
powersAt[topLeft] = mutableMapOf()
powersAt[topLeft]!![1] = powerAtFirstCell
return powerAtFirstCell
}
// if they run one at a time there's always the one smallest below from gridSize 2 and up
// so you only need to calculate for each x where new max y
// and for each y where new max x
var largestCalculated: Int = 0
if (powersAt.containsKey(topLeft)) {
val seenPowers = powersAt[topLeft]!!
largestCalculated = seenPowers[gridSize - 1] ?: 0
}
var sum = largestCalculated
if (largestCalculated == 0) {
for (x in (topLeft.x until topLeft.x + gridSize).asSequence()) {
for (y in (topLeft.y until topLeft.y + gridSize).asSequence()) {
sum += powerLevelOf(Cell(x, y), gridSerial)
}
}
} else {
sum += gridExpander(topLeft, gridSize)
.map { powerLevelOf(it, gridSerial) }
.sum()
powersAt[topLeft]!![gridSize] = sum
}
if (topLeft == Cell(90, 269) && gridSize == 16) println("gridsize: $gridSize with topleft $topLeft sum is $sum")
return sum
}
private fun squareFitsInGrid(cell: Cell, gridSize: Int) = cell.x + gridSize <= 301 && cell.y + gridSize <= 301
}
fun gridExpander(topLeft: Cell, nextGridSize: Int): List<Cell> {
val maxX = topLeft.x + nextGridSize - 1
val maxY = topLeft.y + nextGridSize - 1
val acrossBottom = (topLeft.x until topLeft.x + nextGridSize).map { x ->
Cell(x, maxY)
}
val downSide = (topLeft.y until topLeft.y + nextGridSize).map { y ->
Cell(maxX, y)
}
return acrossBottom + downSide
} | 0 | Kotlin | 0 | 1 | 7d11bb8a07fb156dc92322e06e76e4ecf8402d1d | 3,149 | adventofcode2018 | The Unlicense |
2022/kotlin-lang/src/main/kotlin/mmxxii/days/Day8.kt | Delni | 317,500,911 | false | {"Kotlin": 66017, "Dart": 53066, "Go": 28200, "TypeScript": 7238, "Rust": 7104, "JavaScript": 2873} | package mmxxii.days
import mmxxii.entities.canSeeFarWithTrees
import mmxxii.entities.toTrees
class Day8 : Abstract2022<Int>("08", "Treetop Tree House") {
override fun part1(input: List<String>) = input
.toTrees()
.flatMapIndexed { i, trees ->
trees.mapIndexed { j, tree ->
(i to j).withDirections(trees, input) { left, right, top, bottom ->
listOf(
left.takeWhile { it < tree }.size == j,
right.takeLastWhile { it < tree }.size == trees.size - j - 1,
top.takeWhile { it < tree }.size == i,
bottom.takeLastWhile { it < tree }.size == input.size - i - 1,
).takeIf { it.any { visible -> visible } }?.let { (i to j) }
}
}.filterNotNull()
}
.size
override fun part2(input: List<String>) = input
.toTrees()
.flatMapIndexed { i, trees ->
trees.mapIndexed { j, tree ->
(i to j).withDirections(trees, input) { left, right, top, bottom ->
listOf(
tree canSeeFarWithTrees left.reversed(),
tree canSeeFarWithTrees right,
tree canSeeFarWithTrees top.reversed(),
tree canSeeFarWithTrees bottom
).fold(1, Int::times)
}
}
}
.max()
private fun <T> Pair<Int, Int>.withDirections(
row: List<Int>,
columns: List<String>,
transform: (left: List<Int>, right: List<Int>, top: List<Int>, bottom: List<Int>) -> T
): T {
val column = columns.map { it.toCharArray()[second].toString().toInt() }
return transform(
row.subList(0, second),
row.subList(second + 1, row.size),
column.subList(0, first),
column.subList(first + 1, columns.size)
)
}
}
| 0 | Kotlin | 0 | 1 | d8cce76d15117777740c839d2ac2e74a38b0cb58 | 1,988 | advent-of-code | MIT License |
advent23-kt/app/src/main/kotlin/dev/rockyj/advent_kt/Day4.kt | rocky-jaiswal | 726,062,069 | false | {"Kotlin": 41834, "Ruby": 2966, "TypeScript": 2848, "JavaScript": 830, "Shell": 455, "Dockerfile": 387} | package dev.rockyj.advent_kt
private data class ScratchCard(val id: Int, val wins: List<Int>, val nums: List<Int>)
private fun toCards(input: List<String>): List<Pair<List<Int>, List<Int>>> {
val cards = mutableListOf<Pair<List<Int>, List<Int>>>()
input.forEachIndexed { _idx, line ->
val card = line.split(":")
val play = card.get(1).trim().split("|")
val winningNumbers = play.get(0).trim().split(Regex("\\s+")).map { Integer.parseInt(it) }
val myNumbers = play.get(1).trim().split(Regex("\\s+")).map { Integer.parseInt(it) }
cards.add(Pair(winningNumbers, myNumbers))
}
return cards.toList()
}
private fun foobar(cardPack: List<ScratchCard>, copies: MutableMap<Int, Int>, from: Int = 0) {
if (from >= cardPack.size) {
val s = (1..cardPack.size).map {
copies[it] ?: 1
}
println(s.sum())
return
}
val card = cardPack.get(from)
val wins = card.wins
val myNums = card.nums
val currCardCopies = copies[card.id] ?: 1
val winCount = myNums.filter { wins.contains(it) }.size
val copyIds = (1..winCount).map { card.id + it }
copyIds
.mapNotNull { cardPack.find { card -> card.id == it } }
.forEach { copy ->
repeat((1..currCardCopies).count()) {
copies[copy.id] = (copies[copy.id] ?: 1) + 1
}
}
foobar(cardPack, copies, from + 1)
}
private fun part2(input: List<String>) {
val cardPack = toCards(input).mapIndexed { idx, cardLine ->
ScratchCard(idx + 1, cardLine.first, cardLine.second)
}
foobar(cardPack, cardPack.fold(mutableMapOf()) { agg, card ->
agg[card.id] = 1
agg
})
}
private fun part1(input: List<String>) {
val res = toCards(input).toList().map { card ->
val wins = card.first
val myNums = card.second
val winCount = myNums.filter { wins.contains(it) }.size
if (winCount == 0) {
0.0
} else {
Math.pow(2.0, winCount.toDouble() - 1)
}
}
println(res.sum())
}
fun main() {
val lines = fileToArr("day4_2.txt")
part1(lines)
part2(lines)
} | 0 | Kotlin | 0 | 0 | a7bc1dfad8fb784868150d7cf32f35f606a8dafe | 2,196 | advent-2023 | MIT License |
src/day07/Day07.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day07
import readInput
fun main() {
val testInput = readInput("day07/Day07_test")
println(part1(testInput))
println(part2(testInput))
}
private fun createDirMap(input: List<String>): Map<String, Int> {
val dirMap = hashMapOf("/" to 0)
var currentDirName = "/"
input.forEach {
if (it.startsWith("$ cd /")) return@forEach
if (it.startsWith("$ ls")) return@forEach
if (it.startsWith("$ cd ..")) {
currentDirName = currentDirName.replace("""/[a-z.]*$""".toRegex(), "")
return@forEach
}
if (it.startsWith("$ cd ")) {
currentDirName += '/' + it.replace("$ cd ", "")
return@forEach
}
if (it.startsWith("dir ")) {
val dirName = it.replace("dir ", "")
dirMap["${currentDirName}/$dirName"] = 0
} else {
val size = it.replaceFirst(""" .*""".toRegex(), "").toInt()
var dirName = currentDirName
while (dirName != "/") {
dirMap[dirName] = dirMap.getOrDefault(dirName, 0) + size
dirName = dirName.replace("""/[a-z.]*$""".toRegex(), "")
}
dirMap["/"] = dirMap.getOrDefault("/", 0) + size
}
}
return dirMap
}
private fun part1(input: List<String>): Int {
val dirMap = createDirMap(input)
println(dirMap)
return dirMap.values.filter { it < 100000 }.sum()
}
private fun part2(input: List<String>): Int {
val dirMap = createDirMap(input)
val totalSize = dirMap["/"] ?: return 0
val remaining = totalSize - 40000000
if (remaining <= 0) {
return 0
}
return dirMap.values.sorted().first { it > remaining }
}
| 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 1,713 | advent-of-code-2022 | Apache License 2.0 |
aoc2023/day2.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2023
import utils.InputRetrieval
fun main() {
Day2.execute()
}
private object Day2 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<Game>): Int {
// Only 12 red cubes, 13 green cubes, and 14 blue cubes are allowed
return input.filter { it.rounds.none { round -> round.red > 12 || round.green > 13 || round.blue > 14 } }.sumOf { it.number }
}
private fun part2(input: List<Game>): Int {
// The power of a set of cubes is equal to the numbers of red, green, and blue cubes multiplied together
return input.sumOf { game -> game.rounds.maxOf { it.red } * game.rounds.maxOf { it.green } * game.rounds.maxOf { it.blue } }
}
private fun readInput(): List<Game> = InputRetrieval.getFile(2023, 2).readLines().map { Game.parse(it) }
private data class Game(val number: Int, val rounds: List<Round>) {
companion object {
fun parse(input: String): Game {
val (gameNumberStr, gamesStr) = input.split(':')
val gameNumber: Int = gameNumberStr.removePrefix("Game ").toInt()
val rounds = gamesStr.split(';').map { round -> Round.parse(round) }
return Game(gameNumber, rounds)
}
}
}
private data class Round(val red: Int, val green: Int, val blue: Int) {
companion object {
fun parse(input: String): Round {
val colours = input.split(',').associate { s ->
val (value, colour) = s.trim().split(' ')
colour to value.toInt()
}
return Round(colours["red"] ?: 0, colours["green"] ?: 0, colours["blue"] ?: 0)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 1,844 | Advent-Of-Code | MIT License |
src/main/kotlin/LongestCommonSubsequence.kt | Codextor | 453,514,033 | false | {"Kotlin": 26975} | /**
* Given two strings text1 and text2, return the length of their longest common subsequence.
* If there is no common subsequence, return 0.
*
* A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
*
* For example, "ace" is a subsequence of "abcde".
* A common subsequence of two strings is a subsequence that is common to both strings.
*
*
*
* Example 1:
*
* Input: text1 = "abcde", text2 = "ace"
* Output: 3
* Explanation: The longest common subsequence is "ace" and its length is 3.
* Example 2:
*
* Input: text1 = "abc", text2 = "abc"
* Output: 3
* Explanation: The longest common subsequence is "abc" and its length is 3.
* Example 3:
*
* Input: text1 = "abc", text2 = "def"
* Output: 0
* Explanation: There is no such common subsequence, so the result is 0.
*
*
* Constraints:
*
* 1 <= text1.length, text2.length <= 1000
* text1 and text2 consist of only lowercase English characters.
* @see <a https://leetcode.com/problems/longest-common-subsequence/">LeetCode</a>
*/
fun longestCommonSubsequence(text1: String, text2: String): Int {
if (text1.isEmpty() || text2.isEmpty()) {
return 0
}
val memoryArray = Array<IntArray>(text1.length + 1) { IntArray(text2.length + 1) }
for (index1 in (0 until text1.length).reversed()) {
for (index2 in (0 until text2.length).reversed()) {
val length = if (text1[index1] == text2[index2]) {
1 + memoryArray[index1 + 1][index2 + 1]
} else {
maxOf(memoryArray[index1 + 1][index2], memoryArray[index1][index2 + 1])
}
memoryArray[index1][index2] = length
}
}
return memoryArray[0][0]
}
| 0 | Kotlin | 1 | 0 | 68b75a7ef8338c805824dfc24d666ac204c5931f | 1,821 | kotlin-codes | Apache License 2.0 |
src/com/wd/algorithm/leetcode/ALGO0004.kt | WalkerDenial | 327,944,547 | false | null | package com.wd.algorithm.leetcode
import com.wd.algorithm.test
/**
* 4. 寻找两个正序数组的中位数
*
* 给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
*
*/
class ALGO0004 {
/**
* 方式一:暴力解法
* 将 2 个数组合并,然后取中位数
* 时间复杂度 T(m + n)
*/
fun findMedianSortedArrays1(nums1: IntArray, nums2: IntArray): Double {
val nums = nums1.plus(nums2)
nums.sort()
val index = nums.size / 2
return when {
nums.size % 2 != 0 -> nums[index].toDouble()
else -> (nums[index - 1] + nums[index]) / 2.0
}
}
/**
* 方式二:二分查找
* 通过二分查找找出分割位置,然后比较左上、右下 和 左下、右上数据信息,符合条件即为对接点
* 时间复杂度 T(min(m, n))
*/
fun findMedianSortedArrays2(nums1: IntArray, nums2: IntArray): Double {
val num1Size = nums1.size
val num2Size = nums2.size
val totalNum = num1Size + num2Size
val isEven = totalNum % 2 == 0
val halfIndex = totalNum / 2
var left = 0
var right = 0
var prev = 0
var curr = 0
for (i in 0..halfIndex) {
prev = curr
curr = when {
left >= num1Size -> nums2[right++]
right >= num2Size -> nums1[left++]
nums1[left] > nums2[right] -> nums2[right++]
else -> nums1[left++]
}
}
return if (isEven) (prev + curr) / 2.0 else curr.toDouble()
}
}
fun main() {
val clazz = ALGO0004()
val num1 = intArrayOf(1, 2, 3)
val num2 = intArrayOf(4, 5, 6)
(clazz::findMedianSortedArrays1).test(num1, num2)
(clazz::findMedianSortedArrays2).test(num1, num2)
} | 0 | Kotlin | 0 | 0 | 245ab89bd8bf467625901034dc1139f0a626887b | 1,908 | AlgorithmAnalyze | Apache License 2.0 |
src/y2015/Day16.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2015
import util.readInput
object Day16 {
private fun parse(input: List<String>): List<Map<String, Int>> {
return input.map {
val els = it.replace(Regex("[:,]"), "").split(" ")
mapOf(
els[2] to els[3].toInt(),
els[4] to els[5].toInt(),
els[6] to els[7].toInt()
)
}
}
fun part1(): Long {
return 373L
}
fun part2(input: List<String>): Int {
val parsed = parse(input)
return parsed.indexOfFirst {
isMatch(it)
} + 1
}
private fun isMatch(sue: Map<String, Int>): Boolean {
return listOfNotNull(
sue["children"]?.let { it == 3 },
sue["cats"]?.let { it > 7 },
sue["samoyeds"]?.let { it == 2 },
sue["pomeranians"]?.let { it < 3 },
sue["akitas"]?.let { it == 0 },
sue["vizslas"]?.let { it == 0 },
sue["goldfish"]?.let { it < 5 },
sue["trees"]?.let { it > 3 },
sue["cars"]?.let { it == 2 },
sue["perfumes"]?.let { it == 1 })
.all { it }
}
}
/*
children: 3
cats: 7
samoyeds: 2
pomeranians: 3
akitas: 0
vizslas: 0
goldfish: 5
trees: 3
cars: 2
perfumes: 1
Sue 13: cats: 4, samoyeds: 7, pomeranians: 8
*/
fun main() {
println("------Real------")
val input = readInput("resources/2015/day16")
println(Day16.part1())
println(Day16.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,482 | advent-of-code | Apache License 2.0 |
src/year_2022/day_16/Day16.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_16
import readInput
import kotlin.math.max
data class Valve(
val name: String,
val flowRate: Int,
val toValves: List<String>
)
object Day16 {
var score = 0
/**
* @return
*/
fun solutionOne(text: List<String>): Int {
score = 0
val valvesMap = parseText(text)
val shortestPaths = floydWarshall(
shortestPaths = valvesMap.values.associate { it.name to it.toValves.associateWith { 1 }.toMutableMap() }.toMutableMap(),
valves = valvesMap
)
depthFirstSearch(
currScore = 0,
currentValve = "AA",
visited = emptySet(),
time = 0,
totalTime = 30,
valves = valvesMap,
shortestPaths = shortestPaths
)
return score
}
/**
* @return
*/
fun solutionTwo(text: List<String>): Int {
score = 0
val valvesMap = parseText(text)
val shortestPaths = floydWarshall(
shortestPaths = valvesMap.values.associate { it.name to it.toValves.associateWith { 1 }.toMutableMap() }.toMutableMap(),
valves = valvesMap
)
depthFirstSearch(
currScore = 0,
currentValve = "AA",
visited = emptySet(),
time = 0,
totalTime = 26,
valves = valvesMap,
shortestPaths = shortestPaths,
hasElephantHelper = true
)
return score
}
private fun depthFirstSearch(
currScore: Int,
currentValve: String,
visited: Set<String>,
time: Int,
totalTime: Int,
valves: Map<String, Valve>,
shortestPaths: MutableMap<String, MutableMap<String, Int>>,
hasElephantHelper: Boolean = false
) {
score = max(score, currScore)
for ((valve, dist) in shortestPaths[currentValve]!!) {
if (!visited.contains(valve) && time + dist + 1 < totalTime) {
depthFirstSearch(
currScore + (totalTime - time - dist - 1) * valves[valve]?.flowRate!!,
valve,
visited.union(listOf(valve)),
time + dist + 1,
totalTime,
valves,
shortestPaths
)
}
}
if (hasElephantHelper) {
depthFirstSearch(
currScore = currScore,
currentValve = "AA",
visited = visited,
time = 0,
totalTime = totalTime,
valves = valves,
shortestPaths = shortestPaths,
hasElephantHelper = false
)
}
}
private fun floydWarshall(
shortestPaths: MutableMap<String, MutableMap<String, Int>>,
valves: Map<String, Valve>
): MutableMap<String, MutableMap<String, Int>> {
for (k in shortestPaths.keys) {
for (i in shortestPaths.keys) {
for (j in shortestPaths.keys) {
val ik = shortestPaths[i]?.get(k) ?: 9999
val kj = shortestPaths[k]?.get(j) ?: 9999
val ij = shortestPaths[i]?.get(j) ?: 9999
if (ik + kj < ij)
shortestPaths[i]?.set(j, ik + kj)
}
}
}
//remove all paths that lead to a valve with rate 0
shortestPaths.values.forEach {
it.keys.map { key -> if (valves[key]?.flowRate == 0) key else "" }
.forEach { toRemove -> if (toRemove != "") it.remove(toRemove) }
}
return shortestPaths
}
//Valve AA has flow rate=0; tunnels lead to valves DD, II, BB
private fun parseText(text: List<String>): Map<String, Valve> {
return text.map { line ->
var toValves = line.split("to val")[1].split(" ")
toValves = toValves.subList(1, toValves.size)
toValves = toValves.flatMap { it.split(",") }.filter { it.isNotEmpty() }
Valve(
name = line.split(" ")[1],
flowRate = Integer.parseInt(line.split(" ")[4].split("=")[1].split(";")[0]),
toValves = toValves
)
}.associateBy { valve -> valve.name }
}
}
fun main() {
val inputText = readInput("year_2022/day_16/Day16.txt")
val solutionOne = Day16.solutionOne(inputText)
println("Solution 1: $solutionOne")
val solutionTwo = Day16.solutionTwo(inputText)
println("Solution 2: $solutionTwo")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 4,616 | advent_of_code | Apache License 2.0 |
src/Day02.kt | mandoway | 573,027,658 | false | {"Kotlin": 22353} | enum class Outcome(val points: Int) {
LOSE(0),
DRAW(3),
WIN(6)
}
fun String.decrypt() = when (this) {
"X" -> "A"
"Y" -> "B"
"Z" -> "C"
else -> throw IllegalArgumentException("char must be in X, Y, Z")
}
val shapes = listOf("A", "B", "C")
fun String.pointsByShape() = shapes.indexOf(this) + 1
fun outcome(opponent: String, me: String): Outcome {
val opponentIndex = shapes.indexOf(opponent)
val myIndex = shapes.indexOf(me.decrypt())
return when {
(opponentIndex + 1) % shapes.size == myIndex -> Outcome.WIN
(myIndex + 1) % shapes.size == opponentIndex -> Outcome.LOSE
else -> Outcome.DRAW
}
}
fun String.points(): Int {
val (opponent, me) = split(" ")
return outcome(opponent, me).points + me.decrypt().pointsByShape()
}
fun String.outcomeSecond() = when (this) {
"X" -> Outcome.LOSE
"Y" -> Outcome.DRAW
"Z" -> Outcome.WIN
else -> throw IllegalArgumentException()
}
fun String.points2(): Int {
val (opponent, me) = split(" ")
val outcome = me.outcomeSecond()
val indexOfOpponent = shapes.indexOf(opponent)
val myShape = when (outcome) {
Outcome.LOSE -> indexOfOpponent - 1
Outcome.DRAW -> indexOfOpponent
Outcome.WIN -> indexOfOpponent + 1
}
.mod(shapes.size)
.let { shapes[it] }
return outcome.points + myShape.pointsByShape()
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { it.points() }
}
fun part2(input: List<String>): Int {
return input.sumOf { it.points2() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0393a4a25ae4bbdb3a2e968e2b1a13795a31bfe2 | 1,873 | advent-of-code-22 | Apache License 2.0 |
src/day02/Code.kt | fcolasuonno | 572,734,674 | false | {"Kotlin": 63451, "Dockerfile": 1340} | package day02
import readInput
private enum class Outcome(val score: Int) {
Lost(0), Draw(3), Win(6);
}
private enum class HandShape(val value: Int) {
Rock(1), Paper(2), Scissor(3)
}
fun <E> Iterable<E>.cartesian() = flatMap { left -> map { right -> left to right } }
fun main() {
val game = HandShape.values().toList().cartesian().associateWith { (hand1, hand2) ->
when {
hand1.value == hand2.value -> Outcome.Draw
hand1.value % 3 == (hand2.value - 1) -> Outcome.Win
else -> Outcome.Lost
}
}
fun parse(input: List<String>) = input.map {
val (other, mine) = it.split(' ')
other.single() to mine.single()
}
fun part1(input: List<String>) = parse(input).sumOf { (other, mine) ->
val otherHand = HandShape.values()[other - 'A']
val myHand = HandShape.values()[mine - 'X']
game.getValue(otherHand to myHand).score + myHand.value
}
fun part2(input: List<String>) = parse(input).sumOf { (other, mine) ->
val otherHand = HandShape.values()[other - 'A']
val myOutcome = Outcome.values()[mine - 'X']
val (_, myHand) = game
.filterKeys { it.first == otherHand }
.filterValues { it == myOutcome }
.keys.single()
myOutcome.score + myHand.value
}
val input = readInput(::main.javaClass.packageName)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9cb653bd6a5abb214a9310f7cac3d0a5a478a71a | 1,453 | AOC2022 | Apache License 2.0 |
src/Day10.kt | Reivax47 | 572,984,467 | false | {"Kotlin": 32685} | import kotlin.math.floor
fun main() {
fun rempliCycle(input: List<String>): Array<Int> {
val nombreAdd = input.filter { it.contains("addx") }.size
val nombreNoop = input.filter { it.contains("noop") }.size
val nombreCycles = nombreAdd * 2 + nombreNoop
var cycles = Array(nombreCycles + 1) { 1 }
var indexCycle = 0
input.forEach { ligne ->
val instruction = ligne.split(" ")
when (instruction[0]) {
"noop" -> {
indexCycle++
cycles[indexCycle] = cycles[indexCycle - 1]
}
"addx" -> {
indexCycle += 2
cycles[indexCycle - 1] = cycles[indexCycle - 2]
cycles[indexCycle] = cycles[indexCycle - 1] + instruction[1].toInt()
}
}
}
return cycles
}
fun part1(input: List<String>): Int {
val cycles = rempliCycle(input)
return cycles[19] * 20 + cycles[59] * 60 + cycles[99] * 100 + cycles[139] * 140 + cycles[179] * 180 + cycles[219] * 220
}
fun part2(input: List<String>) {
val cycles = rempliCycle(input)
var crt = Array(6) { "" }
for (cycle in 1..240) {
var ligne = floor(cycle / 40.0).toInt()
var position = cycle % 40
val X = cycles[cycle - 1]
if (position == 0) {
position = 40
ligne--
}
if (position - 1 >= X - 1 && position - 1 <= X + 1) {
crt[ligne] += "#"
} else {
crt[ligne] += "."
}
}
for (j in 0..5) {
println(crt[j])
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
part2(testInput)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | 0affd02997046d72f15d493a148f99f58f3b2fb9 | 2,016 | AD2022-01 | Apache License 2.0 |
src/Day05.kt | AndreiShilov | 572,661,317 | false | {"Kotlin": 25181} | import java.io.File
import java.util.Stack
fun main() {
data class Move(
val amount: Int,
val from: Int,
val to: Int,
)
fun readInput(name: String) = File("src", "$name.txt").readText().split("\n\n")
fun getMoves(moves: String) = moves
.split("\n")
.filter { it.isNotBlank() }
.map { it.split(" ") }
.map { moveArray -> Move(moveArray[1].toInt(), moveArray[3].toInt(), moveArray[5].toInt()) }
.toList()
fun setUpInitialCrates(crates: String): List<Stack<Char>> {
val cratesLines = crates.split("\n").reversed()
val stacksNumbersArray = cratesLines.first().split(Regex(" \\D "))
val cratesStacks = List(stacksNumbersArray.size) { Stack<Char>() }
cratesLines.subList(1, cratesLines.size).forEach { it ->
it.toCharArray()
.toList()
.chunked(4)
.forEachIndexed { index, it ->
val char = it[1]
if (char != ' ') cratesStacks[index].push(char)
}
}
return cratesStacks
}
fun solve(name: String, action: Function2<Move, List<Stack<Char>>, Unit>): String {
val readInput = readInput(name)
val crates = readInput[0]
val moves = readInput[1]
println(crates)
println(moves)
val cratesStacks = setUpInitialCrates(crates)
println(cratesStacks)
val movesList = getMoves(moves)
movesList.forEach { move -> action(move, cratesStacks) }
println(cratesStacks)
return cratesStacks
.filter { it.isNotEmpty() }
.map { it.peek() }
.joinToString("")
}
fun part1(name: String): String {
return solve(name) { move, cratesStacks ->
for (time in 1..move.amount) {
cratesStacks[move.to - 1].push(cratesStacks[move.from - 1].pop())
}
}
}
fun part2(name: String): String {
return solve(name) { move, cratesStacks ->
val tmpList = mutableListOf<Char>()
for (time in 1..move.amount) {
tmpList.add(cratesStacks[move.from - 1].pop())
}
tmpList.reversed().forEach { cratesStacks[move.to - 1].push(it) }
}
}
// test if implementation meets criteria from the description, like:
check(part1(name = "Day05_test") == "CMZ")
check(part2(name = "Day05_test") == "MCD")
val input = readInput("Day05")
println(part1(name = "Day05"))
println(part2(name = "Day05"))
}
| 0 | Kotlin | 0 | 0 | 852b38ab236ddf0b40a531f7e0cdb402450ffb9a | 2,602 | aoc-2022 | Apache License 2.0 |
2023/src/main/kotlin/de/skyrising/aoc2023/day19/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day19
import de.skyrising.aoc.*
enum class Operator {
LT, GT;
companion object {
inline operator fun get(c: Char) = entries[(c.code - '<'.code) / 2]
}
}
enum class Category {
X, M, A, S;
companion object {
val HASHED = arrayOf(X, A, S, M)
inline operator fun get(c: Char) = HASHED[(c.code xor (c.code shr 1)) and 3]
}
}
@JvmInline
value class Categories<T>(private val value: Array<T>) {
val x get() = value[0]
val m get() = value[1]
val a get() = value[2]
val s get() = value[3]
operator fun get(category: Category) = value[category.ordinal]
fun copy(category: Category, value: T): Categories<T> {
val newValue = this.value.copyOf()
newValue[category.ordinal] = value
return Categories(newValue)
}
companion object {
inline fun <reified T> of(x: T, m: T, a: T, s: T) = Categories(arrayOf(x, m, a, s))
}
}
fun Categories<IntRange>.combinations() = x.count().toLong() * m.count() * a.count() * s.count()
data class Rule(val key: Category?, val predicateOp: Operator, val predicateValue: Int, val next: String) {
fun matches(ratings: Categories<Int>): Boolean {
if (key == null) return true
return when (predicateOp) {
Operator.LT -> ratings[key] < predicateValue
Operator.GT -> ratings[key] > predicateValue
}
}
override fun toString(): String {
if (key == null) return next
return "$key${"<>"[predicateOp.ordinal]}$predicateValue:$next"
}
}
data class Workflow(val rules: List<Rule>) {
override fun toString() = rules.joinToString(", ", "Workflow{", "}")
}
fun parse(input: PuzzleInput, parseRatings: Boolean = true): Pair<Map<String, Workflow>, List<Categories<Int>>> {
val (workflowLines, ratingLines) = input.lines.splitOnEmpty(2)
val workflows = HashMap.newHashMap<String, Workflow>(workflowLines.size)
for (line in workflowLines) {
val brace = line.indexOf('{')
val name = line.substring(0, brace)
val rulesSubstr = line.substring(brace + 1, line.length - 1)
val rules = mutableListOf<Rule>()
rulesSubstr.splitToRanges(',') { from, to ->
rules.add(if (to != rulesSubstr.length) {
val key = Category[rulesSubstr[from]]
val op = Operator[rulesSubstr[from + 1]]
val colon = rulesSubstr.indexOf(':', from)
Rule(key, op, rulesSubstr.toInt(from + 2, colon), rulesSubstr.substring(colon + 1, to))
} else {
Rule(null, Operator.GT, 0, rulesSubstr.substring(from))
})
}
workflows[name] = Workflow(rules)
}
val ratings = if (parseRatings) ratingLines.map {
Categories(it.ints().toTypedArray())
} else emptyList()
return workflows to ratings
}
data class QueueEntry(val state: String, val ruleIndex: Int, val ranges: Categories<IntRange>)
inline fun allAccepted(workflows: Map<String, Workflow>): MutableList<Categories<IntRange>> {
val unprocessed = ArrayDeque<QueueEntry>()
unprocessed.add(QueueEntry("in", 0, Categories.of(1..4000, 1..4000, 1..4000, 1..4000)))
val accepted = mutableListOf<Categories<IntRange>>()
while (unprocessed.isNotEmpty()) {
val (state, ruleIndex, ranges) = unprocessed.removeLast()
val workflow = workflows[state]!!
if (ruleIndex >= workflow.rules.size) continue
val rule = workflow.rules[ruleIndex]
val next = rule.next
val key = rule.key
if (key == null) {
if (next == "A") accepted.add(ranges)
else if (next != "R") unprocessed.add(QueueEntry(next, 0, ranges))
continue
}
val range = ranges[key]
val matching = if (rule.predicateOp == Operator.LT) range.first until rule.predicateValue else rule.predicateValue + 1..range.last
val nextRanges = if (!matching.isEmpty()) ranges.copy(key, matching) else null
if (nextRanges != null) {
if (next == "A") accepted.add(nextRanges)
else if (next != "R") unprocessed.add(QueueEntry(next, 0, nextRanges))
}
val nonMatching = if (rule.predicateOp == Operator.LT) rule.predicateValue..range.last else range.first..rule.predicateValue
val otherRanges = if (!nonMatching.isEmpty()) ranges.copy(key, nonMatching) else null
if (otherRanges != null) unprocessed.add(QueueEntry(state, ruleIndex + 1, otherRanges))
}
return accepted
}
val test = TestInput("""
px{a<2006:qkq,m>2090:A,rfg}
pv{a>1716:R,A}
lnx{m>1548:A,A}
rfg{s<537:gd,x>2440:R,A}
qs{s>3448:A,lnx}
qkq{x<1416:A,crn}
crn{x>2662:A,R}
in{s<1351:px,qqz}
qqz{s>2770:qs,m<1801:hdj,R}
gd{a>3333:R,R}
hdj{m>838:A,pv}
{x=787,m=2655,a=1222,s=2876}
{x=1679,m=44,a=2067,s=496}
{x=2036,m=264,a=79,s=2244}
{x=2461,m=1339,a=466,s=291}
{x=2127,m=1623,a=2188,s=1013}
""")
@PuzzleName("Aplenty")
fun PuzzleInput.part1(): Any {
val (workflows, ratings) = parse(this)
var result = 0
for (rating in ratings) {
var state = "in"
while (state != "R" && state != "A") {
val workflow = workflows[state]!!
state = workflow.rules.first { it.matches(rating) }.next
}
if (state == "A") {
result += rating.x + rating.m + rating.a + rating.s
}
}
return result
}
fun PuzzleInput.part2(): Any {
val (workflows, _) = parse(this, false)
return allAccepted(workflows).sumOf(Categories<IntRange>::combinations)
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 5,624 | aoc | MIT License |
src/main/kotlin/advent2019/day15/day15.kt | davidpricedev | 225,621,794 | false | null | package advent2019.day15
import advent2019.IntCode.ICComp
import advent2019.IntCode.startComputer
import java.util.ArrayDeque
/**
* 1 = North, 2 = S, 3 = W, 4 = E
* 0 = no change (wall), 1 = confirm movement, 2 = confirm movement + on location
*/
fun main() {
// part1
println(walkTheDronePart1(getProgram()))
}
fun walkTheDronePart1(program: List<Long>): Int {
val comp = startComputer(program)
val startingPoint = Point(0,0)
val distances = mutableMapOf(startingPoint to RouteInfo(listOf(startingPoint)))
val work = ArrayDeque(listOf(StackItem(listOf(startingPoint), comp)))
while (work.isNotEmpty()) {
val workItem = work.removeFirst()
listOf(1L, 2, 3, 4).map { runCommand(workItem, it) }.filter { it.resultCode != 0L }.forEach {
val point = it.path.last()
if (it.resultCode == 2L) {
visualize(distances, point)
return it.path.count() - 1 // off by one since the path includes starting point
}
if (it.path.count() < (distances[point]?.path?.count() ?: Int.MAX_VALUE)) {
// Set/Update the min distance to the point
distances[point] = RouteInfo(it.path)
work.addLast(StackItem(it.path, it.comp))
}
}
}
return -1
}
fun runCommand(workItem: StackItem, direction: Long): CommandResult {
val (priorPath, comp) = workItem
val (nextComp, results) = comp.runInput(listOf(direction))
return CommandResult(
path = priorPath + getNextPoint(priorPath.last(), direction),
comp = nextComp,
resultCode = results.first()
)
}
// 1 = North, 2 = S, 3 = W, 4 = E
fun getNextPoint(current: Point, direction: Long) =
when (direction) {
1L -> Point(current.x, current.y + 1)
2L -> Point(current.x, current.y - 1)
3L -> Point(current.x - 1, current.y)
4L -> Point(current.x + 1, current.y)
else -> throw Exception("(╯°□°)╯︵ ┻━┻ direction $direction is unknown")
}
data class Point(val x: Int, val y: Int) {}
data class RouteInfo(val path: List<Point>) {}
data class StackItem(val path: List<Point>, val comp: ICComp)
data class CommandResult(val path: List<Point>, val comp: ICComp, val resultCode: Long)
fun visualize(map: Map<Point, RouteInfo>, oxyPoint: Point) {
val startingPoint = Point(0,0)
val rightBound = map.keys.maxBy { it.x }?.x ?: 0
val leftBound = map.keys.minBy { it.x }?.x ?: 0
val upperBound = map.keys.maxBy { it.y }?.y ?: 0
val lowerBound = map.keys.minBy { it.y }?.y ?: 0
fun viz(point: Point) = when (point) {
startingPoint -> { " S " }
oxyPoint -> { " O " }
in map -> { " . " }
else -> { "###" }
}
fun printRow(row: Int) {
println((leftBound..rightBound).joinToString("") { col -> viz(Point(col, row)) })
}
(lowerBound..upperBound).forEach { row -> printRow(row) }
}
fun getProgram() =
"3,1033,1008,1033,1,1032,1005,1032,31,1008,1033,2,1032,1005,1032,58,1008,1033,3,1032,1005,1032,81,1008,1033,4,1032,1005,1032,104,99,101,0,1034,1039,1002,1036,1,1041,1001,1035,-1,1040,1008,1038,0,1043,102,-1,1043,1032,1,1037,1032,1042,1105,1,124,1002,1034,1,1039,101,0,1036,1041,1001,1035,1,1040,1008,1038,0,1043,1,1037,1038,1042,1106,0,124,1001,1034,-1,1039,1008,1036,0,1041,101,0,1035,1040,102,1,1038,1043,1001,1037,0,1042,1105,1,124,1001,1034,1,1039,1008,1036,0,1041,1002,1035,1,1040,1001,1038,0,1043,102,1,1037,1042,1006,1039,217,1006,1040,217,1008,1039,40,1032,1005,1032,217,1008,1040,40,1032,1005,1032,217,1008,1039,5,1032,1006,1032,165,1008,1040,7,1032,1006,1032,165,1101,2,0,1044,1106,0,224,2,1041,1043,1032,1006,1032,179,1102,1,1,1044,1105,1,224,1,1041,1043,1032,1006,1032,217,1,1042,1043,1032,1001,1032,-1,1032,1002,1032,39,1032,1,1032,1039,1032,101,-1,1032,1032,101,252,1032,211,1007,0,31,1044,1106,0,224,1101,0,0,1044,1106,0,224,1006,1044,247,1002,1039,1,1034,101,0,1040,1035,1001,1041,0,1036,102,1,1043,1038,1002,1042,1,1037,4,1044,1105,1,0,9,21,83,15,75,17,11,9,80,22,37,23,19,89,6,29,79,24,75,3,39,3,98,13,20,53,24,30,59,26,13,19,63,84,10,2,57,7,22,43,28,72,11,25,67,17,90,6,10,24,93,76,36,21,34,18,19,15,72,53,18,19,82,8,57,40,18,2,48,71,19,46,26,32,69,29,27,42,8,58,25,17,44,39,47,24,54,32,48,6,26,43,91,4,16,47,45,19,73,3,52,43,25,5,22,73,58,12,56,23,44,7,46,96,48,25,8,16,56,20,48,72,28,44,26,14,23,28,61,29,15,69,86,28,97,6,4,77,4,1,37,55,70,69,22,19,23,78,21,41,2,1,48,29,20,30,22,91,36,15,46,16,83,5,95,38,9,42,84,25,45,3,81,38,79,8,1,78,42,25,58,15,29,48,52,19,36,4,27,43,24,62,6,56,60,22,22,48,23,70,8,83,17,13,63,85,25,13,14,85,79,18,13,63,3,48,94,22,73,18,26,40,68,12,25,10,56,90,59,19,68,25,27,20,20,65,1,22,55,20,1,20,88,24,69,65,13,49,8,5,78,77,1,3,93,9,13,34,17,75,28,13,92,66,35,7,98,3,63,78,59,87,2,80,83,56,15,28,96,25,32,3,27,47,5,73,56,9,59,19,16,60,2,21,50,92,44,19,73,64,7,21,39,19,20,20,63,5,12,6,14,34,12,8,48,12,68,33,14,99,9,85,20,76,18,29,99,52,11,5,98,65,83,15,30,97,35,21,96,4,53,44,23,39,25,53,60,78,85,11,7,4,39,23,84,22,29,56,37,88,18,19,84,4,65,86,8,27,66,24,26,19,95,13,19,61,19,42,85,14,19,29,90,22,15,78,18,90,8,24,21,97,86,15,40,21,61,21,49,61,6,88,40,9,2,38,13,85,16,50,55,93,83,16,77,25,27,91,8,95,15,60,70,63,13,24,24,96,30,8,22,27,74,17,14,92,18,49,4,38,9,33,88,12,62,28,35,77,29,59,3,18,45,5,10,42,58,23,78,72,15,79,2,48,47,14,65,24,5,83,41,11,89,4,57,36,19,12,2,40,21,16,44,36,13,69,70,1,11,51,16,68,30,24,83,26,40,14,82,48,10,5,83,1,76,90,15,44,24,10,88,30,24,78,1,54,97,83,27,46,87,5,19,86,19,48,19,9,50,20,69,17,10,80,34,23,24,18,75,19,20,21,73,11,32,5,15,35,2,77,22,53,18,22,86,6,9,37,30,64,28,77,17,28,12,41,62,59,2,92,97,77,14,3,76,85,11,47,14,85,6,53,2,18,52,29,23,54,35,75,5,97,40,6,45,4,75,64,5,13,86,7,84,84,1,38,23,81,72,5,26,97,70,14,40,9,41,63,41,26,80,57,14,69,90,2,28,95,24,21,80,18,26,33,39,29,11,70,73,69,17,79,13,7,73,6,21,11,75,35,10,23,30,78,75,1,1,73,4,62,30,11,21,6,38,8,40,9,56,3,24,92,66,3,86,61,28,40,17,81,74,58,92,19,4,48,34,39,30,14,36,35,73,12,15,60,49,77,13,53,77,12,20,78,18,34,17,36,17,53,64,7,63,26,20,19,94,16,26,84,13,18,60,47,17,11,56,2,48,53,11,8,79,94,22,14,8,95,7,12,21,77,16,44,4,89,70,96,11,81,8,72,5,35,79,45,1,47,10,86,75,82,5,47,5,65,4,50,22,34,12,84,13,62,80,63,23,45,39,36,0,0,21,21,1,10,1,0,0,0,0,0,0".split(",").map { it.toLong() }
| 0 | Kotlin | 0 | 0 | 2283647e5b4ed15ced27dcf2a5cf552c7bd49ae9 | 6,371 | adventOfCode2019 | Apache License 2.0 |
src/Day01.kt | CrazyBene | 573,111,401 | false | {"Kotlin": 50149} | fun main() {
fun part1(input: List<String>): Int {
val elves = inputToElves(input)
return getElvesWithMostCalories(elves).sumOf { elf -> elf.sum() }
}
fun part2(input: List<String>): Int {
val elves = inputToElves(input)
return getElvesWithMostCalories(elves, 3).sumOf { elf -> elf.sum() }
}
val testInput = readInput("Day01Test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println("Question 1 - Answer: ${part1(input)}")
println("Question 2 - Answer: ${part2(input)}")
}
fun getElvesWithMostCalories(elves: List<List<Int>>, n: Int = 1): List<List<Int>> {
if (n <= 0) error("The count of elves with most calories must be greater than 0")
val elvesToCheck = elves.toMutableList()
val elvesWithMostCalories = mutableListOf<List<Int>>()
for (i in 0 until n) {
val index = elvesToCheck.indices.maxByOrNull { elvesToCheck.map { elf -> elf.sum() }[it] } ?: break
elvesWithMostCalories.add(elvesToCheck[index])
elvesToCheck.removeAt(index)
}
return elvesWithMostCalories
}
fun inputToElves(input: List<String>): MutableList<List<Int>> {
val elves = mutableListOf<List<Int>>()
var restInputLines = input.toMutableList()
while (restInputLines.isNotEmpty()) {
elves.add(restInputLines.takeWhile { it.isNotEmpty() }.map { it.toInt() })
restInputLines = restInputLines.dropWhile { it.isNotEmpty() }.drop(1).toMutableList()
}
return elves
}
| 0 | Kotlin | 0 | 0 | dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26 | 1,545 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/day16/main.kt | janneri | 572,969,955 | false | {"Kotlin": 99028} | package day16
import util.readTestInput
import kotlin.math.min
private typealias ValveId = String
private data class Valve(val valveId: ValveId) {
var flowrate: Int = 0
var neighbors: List<String> = listOf()
private constructor(valveId: ValveId, flowrate: Int, neighbors: List<ValveId>): this(valveId) {
this.flowrate = flowrate
this.neighbors = neighbors
}
override fun toString(): String = valveId
companion object {
// Parses input lines, such as:
// Valve AA has flow rate=0; tunnels lead to valves DD, II, BB
// Valve JJ has flow rate=21; tunnel leads to valve II
fun parse(str: String): Valve {
val valveId = str.substring(6, 8)
val neighbors = when {
str.contains("valves") -> str.substringAfter("to valves ").split(", ")
else -> str.substringAfter("to valve ").split(", ")
}
val flowrate = str.substringAfter("flow rate=").takeWhile { it != ';' }.toInt()
return Valve(valveId, flowrate, neighbors)
}
}
}
private data class GameState(var totalPressureReleased : Int = 0, val currentValve: Valve,
val currentElephantValve: Valve?, val openValves: Set<Valve>) {
fun withNewTotalPressure(): GameState {
totalPressureReleased += openValves.sumOf { it.flowrate }
return this
}
fun currentValveOpenable(): Boolean =
!openValves.contains(currentValve) && currentValve.flowrate > 0
fun currentElephantValveOpenable(): Boolean =
!openValves.contains(currentElephantValve) && currentElephantValve!!.flowrate > 0
fun currentPressure(): Int = openValves.sumOf { it.flowrate }
}
private class Tunnels(valves: List<Valve>, initialValveId: ValveId, elephantValveId: ValveId?) {
val valvesById: Map<ValveId, Valve> = valves.fold(mutableMapOf()) { acc, valve ->
acc[valve.valveId] = valve
acc
}
val openableValves = valves.filter { it.flowrate > 0 }
val openableValveCount = openableValves.size
// Distances from all nodes to any other node. In the sample, distances["AA"]["BB"] would be 2
val distances: Map<ValveId, Map<ValveId, Int>> = valves.associate { it.valveId to getDistances(it) }
val initialState = GameState(
currentValve = valvesById[initialValveId]!!,
currentElephantValve = valvesById[elephantValveId],
openValves = mutableSetOf()
)
fun getDistances(fromValve: Valve): Map<ValveId, Int> {
val visited = mutableSetOf<Valve>()
val distances = mutableMapOf(fromValve.valveId to 0)
val queue = mutableListOf(fromValve)
while (queue.isNotEmpty()) {
val current = queue.removeAt(0)
if (!visited.contains(current)) {
visited.add(current)
current.neighbors.forEach{neighbor ->
val newDistance = distances[current.valveId]!! + 1
if (distances[neighbor] == null) distances[neighbor] = newDistance
queue.add(valvesById[neighbor]!!)
}
}
}
return distances
}
fun theoreticalMax(gameState: GameState, timeLeft: Int): Int {
var closedValveSum = 0
if (timeLeft > 1) {
closedValveSum = openableValves.filter { !gameState.openValves.contains(it) }
.fold(0) { acc, valve ->
val moveTime = distances[gameState.currentValve.valveId]?.get(valve.valveId)!!
val minMoveTime = when (gameState.currentElephantValve) {
null -> moveTime
else -> min(moveTime, distances[gameState.currentElephantValve.valveId]?.get(valve.valveId)!!)
}
acc + (timeLeft - minMoveTime - 1) * valve.flowrate
}
}
val openValveSum = timeLeft * gameState.currentPressure()
return gameState.totalPressureReleased + closedValveSum + openValveSum
}
fun nextStatesFromState(state: GameState): Set<GameState> {
val newStates = mutableSetOf<GameState>()
if (state.currentElephantValve == null) {
// open current
if (state.currentValveOpenable()) {
val newState = state.copy(
totalPressureReleased = state.totalPressureReleased + state.currentPressure(),
openValves = state.openValves + state.currentValve
)
newStates.add(newState)
}
// move to neighbors
newStates.addAll(state.currentValve.neighbors.map {
val nextValve = valvesById[it]!!
val newState = state.copy(currentValve = nextValve).withNewTotalPressure()
newState
})
}
else {
// I move, the elephant moves
newStates.addAll(state.currentValve.neighbors.flatMap {
val nextValve = valvesById[it]!!
state.currentElephantValve.neighbors
.map { ev -> valvesById[ev]!! }
.map { eValve ->
state.copy(currentValve = nextValve,
currentElephantValve = eValve,
totalPressureReleased = state.totalPressureReleased + state.currentPressure())
}.toSet()
})
// I move, the elephant opens
if (state.currentElephantValveOpenable()) {
newStates.addAll(state.currentValve.neighbors.map {
val nextValve = valvesById[it]!!
state.copy(currentValve = nextValve,
openValves = state.openValves + state.currentElephantValve,
totalPressureReleased = state.totalPressureReleased + state.currentPressure())
})
}
// I open, the elephant moves
if (state.currentValveOpenable()) {
newStates.addAll(state.currentElephantValve.neighbors.map {
val nextValve = valvesById[it]!!
state.copy(currentElephantValve = nextValve,
openValves = state.openValves + state.currentValve,
totalPressureReleased = state.totalPressureReleased + state.currentPressure())
})
}
// I open, the elephant opens
if (state.currentValveOpenable() && state.currentElephantValveOpenable()) {
val newState = state.copy(
totalPressureReleased = state.totalPressureReleased + state.currentPressure(),
openValves = state.openValves + state.currentValve + state.currentElephantValve
)
newStates.add(newState)
}
}
return newStates
}
fun nextStates(fromStates: Set<GameState>, timeLeft: Int): Set<GameState> {
val nextStates = fromStates.flatMap { state ->
val newStates = mutableSetOf<GameState>()
// just wait because all valves are open
if (state.openValves.size == openableValveCount) {
val newState = state.copy().withNewTotalPressure()
newStates.add(newState)
}
else {
// add all possible states, where we open valves or move
newStates.addAll(nextStatesFromState(state))
}
newStates
}
return nextStates
.sortedBy { state -> theoreticalMax(state, timeLeft) }
.reversed()
.take(1000)
.toSet()
}
}
fun playRounds(inputLines: List<String>, minutes: Int, elephantValveId: ValveId?): Int {
val tunnels = Tunnels(inputLines.map { Valve.parse(it) }, "AA", elephantValveId)
var currentStates = setOf(tunnels.initialState)
for (i in 1 .. minutes) {
println("== Minute $i (${currentStates.size} states)==")
currentStates = tunnels.nextStates(currentStates, minutes - i)
}
return currentStates.maxBy { it.totalPressureReleased }.totalPressureReleased
}
fun main() {
val inputLines = readTestInput("day16")
println(playRounds(inputLines, 30, null))
println(playRounds(inputLines, 26, "AA"))
}
| 0 | Kotlin | 0 | 0 | 1de6781b4d48852f4a6c44943cc25f9c864a4906 | 8,382 | advent-of-code-2022 | MIT License |
src/main/kotlin/aoc2018/ExperimentalEmergencyTeleportation.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2018
import komu.adventofcode.utils.nonEmptyLines
import kotlin.math.abs
fun experimentalEmergencyTeleportation1(input: String): Int {
val bots = input.nonEmptyLines().map { Nanobot.parse(it) }
val strongest = bots.maxBy { it.range }
return bots.count { strongest.pos.manhattanDistance(it.pos) <= strongest.range }
}
fun experimentalEmergencyTeleportation2(input: String): Int {
val bots = input.nonEmptyLines().map { Nanobot.parse(it) }
var bestConfirmedScore = Int.MIN_VALUE
var bestPoint = Point3.ORIGIN
fun recurse(cube: Cube) {
val divisions = cube.divide()
if (divisions.isEmpty()) {
// If cube can't be divided, it's just a single point
val point = cube.toPoint()
val score = bots.count { point.manhattanDistance(it.pos) <= it.range }
if (score > bestConfirmedScore) {
bestConfirmedScore = score
bestPoint = point
}
} else {
recurse(divisions.maxBy { it.upperBoundForScore(bots) })
}
}
recurse(Cube(bots.map { it.pos }))
return bestPoint.manhattanDistance(Point3.ORIGIN)
}
private data class Cube(val xRange: IntRange, val yRange: IntRange, val zRange: IntRange) {
constructor(bots: Iterable<Point3>) : this(
xRange = bots.minOf { it.x }..bots.maxOf { it.x },
yRange = bots.minOf { it.y }..bots.maxOf { it.y },
zRange = bots.minOf { it.z }..bots.maxOf { it.z },
)
fun toPoint() = Point3(xRange.first, yRange.first, zRange.first)
fun divide(): List<Cube> = buildList {
if (xRange.splittable || yRange.splittable || zRange.splittable)
for (x in xRange.split())
for (y in yRange.split())
for (z in zRange.split())
add(Cube(x, y, z))
}
fun closestPoint(p: Point3) = Point3(xRange.closest(p.x), yRange.closest(p.y), zRange.closest(p.z))
fun upperBoundForScore(bots: List<Nanobot>): Int =
bots.count { closestPoint(it.pos).manhattanDistance(it.pos) <= it.range }
}
private fun IntRange.closest(x: Int): Int = when {
x < first -> first
x > last -> last
else -> x
}
private val IntRange.splittable: Boolean
get() = first != last
private fun IntRange.split(): List<IntRange> {
if (first >= last)
return listOf(this)
val mid = (last + first) / 2
return listOf(first..mid, mid + 1..last)
}
private data class Nanobot(val pos: Point3, val range: Int) {
companion object {
private val regex = Regex("""pos=<(-?\d+),(-?\d+),(-?\d+)>, r=(\d+)""")
fun parse(s: String): Nanobot {
val (x, y, z, r) = regex.matchEntire(s)?.destructured ?: error("no match '$s'")
return Nanobot(Point3(x.toInt(), y.toInt(), z.toInt()), r.toInt())
}
}
}
private data class Point3(val x: Int, val y: Int, val z: Int) {
override fun toString() = "<$x,$y,$z>"
fun manhattanDistance(p: Point3): Int =
abs(x - p.x) + abs(y - p.y) + abs(z - p.z)
companion object {
val ORIGIN = Point3(0, 0, 0)
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 3,155 | advent-of-code | MIT License |
src/main/kotlin/ai/hypergraph/kaliningraph/types/TypeSystem.kt | ileasile | 424,362,465 | true | {"Kotlin": 121295} | package ai.hypergraph.kaliningraph.types
import ai.hypergraph.kaliningraph.times
/** Corecursive Fibonacci sequence of [Nat]s **/
tailrec fun <T, R: Nat<T, R>> Nat<T, R>.fibonacci(
n: T,
seed: Pair<T, T> = nil to one,
fib: (Pair<T, T>) -> Pair<T, T> = { (a, b) -> b to a + b },
i: T = nil,
): T =
if (i == n) fib(seed).first
else fibonacci(n = n, seed = fib(seed), i = i.next())
/** Returns [n]! **/
fun <T, R: Nat<T, R>> Nat<T, R>.factorial(n: T): T = prod(seq(to = n.next()))
/** Returns a sequence of [Nat]s starting from [from] until [to] **/
tailrec fun <T, R: Nat<T, R>> Nat<T, R>.seq(
from: T = one, to: T,
acc: Set<T> = emptySet()
): Set<T> = if (from == to) acc else seq(from.next(), to, acc + from)
/** Returns true iff [t] is prime **/
fun <T, R: Nat<T, R>> Nat<T, R>.isPrime(t: T, kps: Set<T> = emptySet()): Boolean =
// Take Cartesian product, filter distinct pairs due to commutativity
(if (kps.isNotEmpty()) kps * kps else seq(to = t) * seq(to = t))
.distinctBy { (l, r) -> setOf(l, r) }
.all { (i, j) -> if (i == one || j == one) true else i * j != t }
/** Returns [total] prime [Nat]s **/
tailrec fun <T, R: Nat<T, R>> Nat<T, R>.primes(
total: T, // total number of primes
i: T = nil, // counter
c: T = one.next(), // prime candidate
kps: Set<T> = emptySet() // known primes
): Set<T> =
when {
i == total -> kps
isPrime(c) -> primes(total, i.next(), c.next(), kps + c)
else -> primes(total, i, c.next(), kps)
}
/** Returns the sum of two [Nat]s **/
tailrec fun <T, R: Nat<T, R>> Nat<T, R>.plus(l: T, r: T, acc: T = l, i: T = nil): T =
if (i == r) acc else plus(l, r, acc.next(), i.next())
/** Returns the product of two [Nat]s **/
tailrec fun <T, R: Nat<T, R>> Nat<T, R>.times(l: T, r: T, acc: T = nil, i: T = nil): T =
if (i == r) acc else times(l, r, acc + l, i.next())
tailrec fun <T, R: Nat<T, R>> Nat<T, R>.pow(base: T, exp: T, acc: T = one, i: T = one): T =
if (i == exp) acc else pow(base, exp, acc * base, i.next())
fun <T, R: Nat<T, R>> Nat<T, R>.sum(list: Iterable<T>): T = list.reduce { acc, t -> acc + t }
fun <T, R: Nat<T, R>> Nat<T, R>.prod(list: Iterable<T>): T = list.reduce { acc, t -> (acc * t) }
interface Nat<T, R: Nat<T, R>> {
val nil: T
val one: T get() = nil.next()
fun T.next(): T
// TODO: implement pred, minus?
// https://en.wikipedia.org/wiki/Church_encoding#Derivation_of_predecessor_function
operator fun T.plus(t: T) = plus(this, t)
operator fun T.times(t: T) = times(this, t)
infix fun T.pow(t: T) = pow(this, t)
class of<T>(override val nil: T, val vnext: T.() -> T): Nat<T, of<T>> {
override fun T.next(): T = vnext()
}
}
interface Group<T, R: Group<T, R>>: Nat<T, R> {
override fun T.next(): T = this + one
override fun T.plus(t: T): T
class of<T>(
override val nil: T, override val one: T,
val plus: (T, T) -> T
): Group<T, of<T>> {
override fun T.plus(t: T) = plus(this, t)
}
}
interface Ring<T, R: Ring<T, R>>: Group<T, R> {
override fun T.plus(t: T): T
override fun T.times(t: T): T
class of<T>(
override val nil: T, override val one: T,
val plus: (T, T) -> T,
val times: (T, T) -> T
): Ring<T, of<T>> {
override fun T.plus(t: T) = plus(this, t)
override fun T.times(t: T) = times(this, t)
}
}
@Suppress("NO_TAIL_CALLS_FOUND")
/** Returns the result of subtracting two [Field]s **/
tailrec fun <T, R: Field<T, R>> Field<T, R>.minus(l: T, r: T, acc: T = nil, i: T = nil): T = TODO()
@Suppress("NO_TAIL_CALLS_FOUND")
/** Returns the result of dividing of two [Field]s **/
tailrec fun <T, R: Field<T, R>> Field<T, R>.div(l: T, r: T, acc: T = l, i: T = nil): T = TODO()
interface Field<T, R: Field<T, R>>: Ring<T, R> {
operator fun T.minus(t: T): T = minus(this, t)
operator fun T.div(t: T): T = div(this, t)
class of<T>(
override val nil: T, override val one: T,
val plus: (T, T) -> T,
val times: (T, T) -> T,
val minus: (T, T) -> T,
val div: (T, T) -> T
): Field<T, of<T>> {
override fun T.plus(t: T) = plus(this, t)
override fun T.times(t: T) = times(this, t)
override fun T.minus(t: T) = minus(this, t)
override fun T.div(t: T) = div(this, t)
}
}
interface Vector<T> {
val ts: List<T>
fun vmap(map: (T) -> T) = of(ts.map { map(it) })
fun zip(other: Vector<T>, merge: (T, T) -> T) =
of(ts.zip(other.ts).map { (a, b) -> merge(a, b) })
class of<T>(override val ts: List<T>): Vector<T> {
constructor(vararg ts: T): this(ts.toList())
override fun toString() =
ts.joinToString(",", "${ts.javaClass.simpleName}[", "]")
}
}
interface VectorField<T, F: Field<T, F>> {
val f: F
operator fun Vector<T>.plus(vec: Vector<T>): Vector<T> = zip(vec) { a, b -> with(f) { a + b } }
infix fun T.dot(p: Vector<T>): Vector<T> = p.vmap { f.times(it, this) }
class of<T, F: Field<T, F>>(override val f: F): VectorField<T, F>
}
// TODO: Clifford algebra?
// http://www.math.ucsd.edu/~alina/oldcourses/2012/104b/zi.pdf
data class GaussInt(val a: Int, val b: Int) {
operator fun plus(o: GaussInt): GaussInt = GaussInt(a + o.a, b + o.b)
operator fun times(o: GaussInt): GaussInt =
GaussInt(a * o.a - b * o.b, a * o.b + b * o.a)
}
class Rational {
constructor(i: Int, j: Int = 1) {
if (j == 0) throw ArithmeticException("Denominator must not be zero!")
canonicalRatio = reduce(i, j)
a = canonicalRatio.first
b = canonicalRatio.second
}
private val canonicalRatio: Pair<Int, Int>
/**
* TODO: Use [Nat] instead?
*/
val a: Int
val b: Int
operator fun times(r: Rational) = Rational(a * r.a, b * r.b)
operator fun plus(r: Rational) = Rational(a * r.b + r.a * b, b * r.b)
operator fun minus(r: Rational) = Rational(a * r.b - r.a * b, b * r.b)
operator fun div(r: Rational) = Rational(a * r.b, b * r.a)
override fun toString() = "$a/$b"
override fun equals(other: Any?) =
(other as? Rational).let { a == it!!.a && b == it.b }
override fun hashCode() = toString().hashCode()
companion object {
val ZERO = Rational(0, 1)
val ONE = Rational(1, 1)
fun reduce(a: Int, b: Int) = Pair(a / a.gcd(b), b / a.gcd(b))
// https://github.com/binkley/kotlin-rational/blob/61be6f7df2d579ad83c6810a5f9426a4478b99a2/src/main/kotlin/hm/binkley/math/math-functions.kt#L93
private tailrec fun Int.gcd(that: Int): Int = when {
this == that -> this
this in 0..1 || that in 0..1 -> 1
this > that -> (this - that).gcd(that)
else -> gcd(that - this)
}
}
} | 0 | null | 0 | 0 | 4b6aadf379ec40fe0c7d5de0ee25fa64520e31b3 | 6,517 | kaliningraph | Apache License 2.0 |
src/Day11.kt | xabgesagtx | 572,139,500 | false | {"Kotlin": 23192} | import Operator.PLUS
import Operator.TIMES
fun main() {
val day = "Day11"
fun readMonkeys(input: List<String>): Map<Int, Monkey> {
return input.filter { it.isNotBlank() }
.chunked(6)
.mapIndexed { index, lines -> lines.toMonkey(index) }
.associateBy { it.number }
}
fun Map<Int,Monkey>.simulateRound(worryLevelDivider: Long) {
for(i in 0 until size) {
val monkey = getValue(i)
while (monkey.items.isNotEmpty()) {
monkey.inspectedItems++
var item = monkey.items.removeFirst()
item = monkey.operation.perform(item)
item /= worryLevelDivider
if (item % monkey.testDivider == 0L) {
getValue(monkey.firstTarget).items.add(item)
} else {
getValue(monkey.secondTarget).items.add(item)
}
}
}
}
fun part1(input: List<String>): Long {
val monkeys = readMonkeys(input)
repeat(20) {
monkeys.simulateRound(3L)
}
val (firstHighest, secondHighest) = monkeys.values.map { it.inspectedItems }.sortedDescending().take(2)
return firstHighest * secondHighest
}
fun part2(input: List<String>): Long {
val monkeys = readMonkeys(input)
repeat(10000) {
monkeys.simulateRound(1L)
}
val (firstHighest, secondHighest) = monkeys.values.map { it.inspectedItems }.sortedDescending().take(2)
return firstHighest * secondHighest
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
readMonkeys(testInput).values.forEach { println(it) }
println("Test part 1:")
println(part1(testInput))
check(part1(testInput) == 10605L)
println()
println("Test part 2:")
println(part2(testInput))
check(part2(testInput) == 2713310158L)
val input = readInput(day)
println()
println("Part 1")
println(part1(input))
println()
println("Part 2")
println(part2(input))
}
private fun List<String>.toMonkey(index: Int): Monkey {
val (startingItemsLine, operationLine, testLine, trueCaseLine, falseCaseLine) = this.drop(1)
val startingItems =
startingItemsLine.substringAfter("Starting items:").split(",").mapNotNull { it.trim().toLongOrNull() }
val (operatorString, operandString) = operationLine.substringAfter("Operation: new = old ").split(" ")
val operator = when (operatorString) {
"*" -> TIMES
"+" -> PLUS
else -> error("Unexpected operator: $operatorString")
}
val fixedOperand = operandString.toLongOrNull()
val operation = Operation(operator, fixedOperand)
val testDivider = testLine.substringAfter("Test: divisible by ").toLong()
val firstTarget = trueCaseLine.substringAfter("If true: throw to monkey ").toInt()
val secondTarget = falseCaseLine.substringAfter("If false: throw to monkey ").toInt()
return Monkey(index, ArrayDeque(startingItems), operation, testDivider, firstTarget, secondTarget)
}
private enum class Operator {
PLUS, TIMES
}
private data class Operation(val operator: Operator, val fixedOperand: Long?) {
fun perform(oldValue: Long): Long {
val operand = fixedOperand ?: oldValue
return when (operator) {
PLUS -> oldValue + operand
TIMES -> oldValue * operand
}
}
}
private data class Monkey(
val number: Int,
val items: ArrayDeque<Long>,
val operation: Operation,
val testDivider: Long,
val firstTarget: Int,
val secondTarget: Int,
var inspectedItems: Long = 0
)
| 0 | Kotlin | 0 | 0 | 976d56bd723a7fc712074066949e03a770219b10 | 3,730 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-14.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.CharGrid
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import com.github.ferinagy.adventOfCode.toCharGrid
fun main() {
val input = readInputLines(2023, "14-input")
val test1 = readInputLines(2023, "14-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val grid = input.toCharGrid()
val (cubes, round) = parse(grid)
return tilt(round, cubes, grid.width, grid.height, Coord2D(0, -1)).sumOf { grid.height - it.y }
}
private fun part2(input: List<String>): Int {
val grid = input.toCharGrid()
val (cubes, round) = parse(grid)
var newRounds = round
val cycles = mutableMapOf(newRounds to 0)
var cycle = 0
while (true) {
newRounds = loop(newRounds, cubes, grid)
cycle++
if (newRounds in cycles) {
break
}
cycles[newRounds] = cycle
}
val cycleStart = cycles[newRounds]!!
val loopLength = cycle - cycleStart
repeat((1000000000 - cycleStart) % loopLength) {
newRounds = loop(newRounds, cubes, grid)
}
return newRounds.sumOf { grid.height - it.y }
}
private fun loop(rounds: Set<Coord2D>, cubes: Set<Coord2D>, grid: CharGrid) = directions.fold(rounds) { acc, dir ->
tilt(acc, cubes, grid.width, grid.height, dir)
}
private fun parse(grid: CharGrid): Pair<Set<Coord2D>, Set<Coord2D>> {
val cubes = mutableSetOf<Coord2D>()
val round = mutableSetOf<Coord2D>()
grid.yRange.forEach { y ->
grid.xRange.forEach { x ->
val c = grid[x, y]
when (c) {
'#' -> cubes += Coord2D(x, y)
'O' -> round += Coord2D(x, y)
}
}
}
return cubes to round
}
private val directions = listOf(Coord2D(0, -1), Coord2D(-1, 0), Coord2D(0, 1), Coord2D(1, 0))
private fun Coord2D.selector(coord: Coord2D) = -(x * coord.x + y * coord.y)
private fun tilt(round: Set<Coord2D>, cubes: Set<Coord2D>, width: Int, height: Int, dir: Coord2D): Set<Coord2D> {
val newRounds = mutableSetOf<Coord2D>()
round.sortedBy(dir::selector).forEach {
var coord = it
while ((coord + dir).isIn(width, height) && coord + dir !in cubes && coord + dir !in newRounds) coord += dir
newRounds += coord
}
return newRounds
}
private fun Coord2D.isIn(width: Int, height: Int) = x in 0..<width && y in 0..<height
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,696 | advent-of-code | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.