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/leetcode/kotlin/array/easy/973. K Closest Points to Origin.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package leetcode.kotlin.array.easy
import java.util.Arrays
import kotlin.random.Random
// O(nlogn),O(n)
private fun kClosest1(points: Array<IntArray>, K: Int): Array<IntArray>? {
fun distance(point: IntArray) = point[0] * point[0] + point[1] * point[1]
val N = points.size
val dists = IntArray(N)
for (i in 0 until N) dists[i] = distance(points[i])
Arrays.sort(dists)
val distK = dists[K - 1]
val ans = Array(K) { IntArray(2) }
var t = 0
for (i in 0 until N) if (distance(points[i]) <= distK) ans[t++] = points[i]
return ans
}
// O(nlogn),O(n)
private fun kClosest2(points: Array<IntArray>, K: Int): Array<IntArray> {
return points.sortedWith(kotlin.Comparator { t1, t2 -> (t1[0] * t1[0] + t1[1] * t1[1]) - (t2[0] * t2[0] + t2[1] * t2[1]) })
.take(K)
.toTypedArray()
}
private fun kClosest3(points: Array<IntArray>, K: Int): Array<IntArray> {
return points.sortedWith(compareBy<IntArray> { it[0] * it[0] + it[1] * it[1] }).take(K)
.toTypedArray()
}
// todo: need to verify this solution
private fun kClosest4(points: Array<IntArray?>, K: Int): Array<IntArray?>? {
if (points.isEmpty()) return null
// gives distance of ith point from origin
fun distance(i: Int) = points[i]?.let { it[0] * it[0] + it[1] * it[1] } ?: Int.MAX_VALUE
// swap two points (i.e. two rows on Array)
fun swap(i: Int, j: Int) {
points[i] = points[j].also { points[j] = points[i] }
}
/**
* Partition process of quick-sort. O(n)
* Function return pivot element position j, who is correct position in sorted array.
* All element greater than pivot will be on right side of j index and small on left side of it.
*/
fun partition(i: Int, j: Int): Int {
var i = i
var j = j
val oi = i // save pivot original position
// we need to sort based on distance
// get distance of ith point from origin; each row is a point
val pivot = distance(i)
i++
while (true) {
while (i < j && distance(i) < pivot) i++
while (i <= j && distance(j) > pivot) j--
if (i >= j) break
swap(i, j)
}
swap(oi, j) // place pivot in its right position
return j // return pivot position
}
fun sort(i: Int, j: Int, K: Int) {
if (i >= j) return
val k = Random.nextInt(i, j)
swap(i, k)
val mid = partition(i, j)
val leftLength = mid - i + 1
if (K < leftLength)
sort(i, mid - 1, K)
else if (K > leftLength)
sort(mid + 1, j, K - leftLength)
}
sort(0, points.size - 1, K)
return points.copyOfRange(0, K)
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,714 | leetcode-kotlin | Apache License 2.0 |
src/day12/Code.kt | fcolasuonno | 225,219,560 | false | null | package day12
import isDebug
import java.io.File
import kotlin.math.abs
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed)}")
println("Part 2 = ${part2(parsed)}")
}
data class Moon(
val x: Int, val y: Int, val z: Int,
val vx: Int = 0, val vy: Int = 0, val vz: Int = 0
) {
fun updateVelocity(set: List<Moon>) = copy(
vx = vx - set.count { it.x < x } + set.count { it.x > x },
vy = vy - set.count { it.y < y } + set.count { it.y > y },
vz = vz - set.count { it.z < z } + set.count { it.z > z })
fun updatePosition() = copy(x = x + vx, y = y + vy, z = z + vz)
}
private val lineStructure = """<x=(-?\d+), y=(-?\d+), z=(-?\d+)>""".toRegex()
fun parse(input: List<String>) = input.map {
lineStructure.matchEntire(it)?.destructured?.let {
val (x, y, z) = it.toList().map { it.toInt() }
Moon(x, y, z)
}
}.requireNoNulls()
fun part1(input: List<Moon>, steps: Int = 1000) = generateSequence(input) { moons ->
moons.map {
it.updateVelocity(moons - it)
}.map {
it.updatePosition()
}
}.take(steps + 1).last().sumBy {
(abs(it.x) + abs(it.y) + abs(it.z)) *
(abs(it.vx) + abs(it.vy) + abs(it.vz))
}
fun part2(input: List<Moon>) = generateSequence(input) { moons ->
moons.map {
it.updateVelocity(moons - it)
}.map {
it.updatePosition()
}
}.drop(1).let { sequence ->
lcm(
1L + sequence.indexOfFirst { it.all { it.vx == 0 } && it.map { it.x } == input.map { it.x } },
lcm(1L + sequence.indexOfFirst { it.all { it.vy == 0 } && it.map { it.y } == input.map { it.y } },
1L + sequence.indexOfFirst { it.all { it.vz == 0 } && it.map { it.z } == input.map { it.z } }
)
)
}
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b | 0 | Kotlin | 0 | 0 | d1a5bfbbc85716d0a331792b59cdd75389cf379f | 2,077 | AOC2019 | MIT License |
src/Day03.kt | bendh | 573,833,833 | false | {"Kotlin": 11618} | fun main() {
fun charToValue(char: Char) = if (char.code >= 97) char.code - 96 else char.code - 38
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val chunks = rucksack.chunked(rucksack.length / 2).map { it.toCharArray() }.toTypedArray()
val compartment1 = chunks[0].toSet()
val compartment2 = chunks[1].toSet()
(compartment1 intersect compartment2).sumOf {
charToValue(it)
}
}
}
fun part2(input: List<String>): Int {
var totalPrio = 0
input.map { it.toCharArray().toSet() }.chunked(3).forEach { group ->
totalPrio += (group[0] intersect group[1] intersect group[2]).sumOf {
char -> charToValue(char)
}
}
return totalPrio
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
//
val input = readLines("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e3ef574441b63a99a99a095086a0bf025b8fc475 | 1,121 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day14.kt | eo | 574,058,285 | false | {"Kotlin": 45178} | // https://adventofcode.com/2022/day/14
fun main() {
fun part1(input: List<String>): Int {
val sandSourcePoint = Point(500, 0)
val blockedPoints = input.map(Path::fromString)
.flatMap(Path::points)
.toMutableSet()
val maxOfPointY = blockedPoints.maxOf(Point::y)
var sandsRested = 0
while (true) {
var currentSandPoint = sandSourcePoint
while (currentSandPoint !in blockedPoints) {
val nextSandPoint = listOf(
currentSandPoint.belowPoint,
currentSandPoint.belowLeftPoint,
currentSandPoint.belowRightPoint
).firstOrNull { it !in blockedPoints }
if (nextSandPoint == null) {
blockedPoints += currentSandPoint
sandsRested++
} else if (nextSandPoint.y < maxOfPointY) {
currentSandPoint = nextSandPoint
} else {
return sandsRested
}
}
}
}
fun part2(input: List<String>): Int {
val sandSourcePoint = Point(500, 0)
val blockedPoints = input.map(Path::fromString)
.flatMap(Path::points)
.toMutableSet()
val floorY = blockedPoints.maxOf(Point::y) + 2
var sandsRested = 0
while (sandSourcePoint !in blockedPoints) {
var currentSandPoint = sandSourcePoint
while (currentSandPoint !in blockedPoints) {
val nextSandPoint = listOf(
currentSandPoint.belowPoint,
currentSandPoint.belowLeftPoint,
currentSandPoint.belowRightPoint
).firstOrNull { it !in blockedPoints }
if (nextSandPoint == null) {
blockedPoints += currentSandPoint
sandsRested++
} else if (nextSandPoint.y < floorY) {
currentSandPoint = nextSandPoint
} else {
blockedPoints += currentSandPoint
sandsRested++
break
}
}
}
return sandsRested
}
val input = readLines("Input14")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
private data class Point(val x: Int, val y: Int) {
val belowLeftPoint get() = copy(x = x - 1, y = y + 1)
val belowPoint get() = copy(y = y + 1)
val belowRightPoint get() = copy(x = x + 1, y = y + 1)
companion object {
fun fromString(str: String): Point =
str.split(",")
.let { (x, y) ->
Point(x.toInt(), y.toInt())
}
}
}
private class Path(points: List<Point>) {
val points: Set<Point> =
points
.windowed(size = 2, step = 1)
.flatMap { (point1, point2) ->
pointsInLine(point1, point2)
}
.toSet()
private fun pointsInLine(point1: Point, point2: Point): List<Point> = when {
point1.x == point2.x -> {
if (point1.y < point2.y) {
point1.y..point2.y
} else {
point1.y downTo point2.y
}.map { Point(point1.x, it) }
}
point1.y == point2.y -> {
if (point1.x < point2.x) {
point1.x..point2.x
} else {
point1.x downTo point2.x
}.map { Point(it, point1.y) }
}
else -> error("Either x or y positions of points on a line should be the same!")
}
companion object {
fun fromString(str: String) = Path(
str.split(" -> ")
.map(Point::fromString)
)
}
} | 0 | Kotlin | 0 | 0 | 8661e4c380b45c19e6ecd590d657c9c396f72a05 | 3,810 | aoc-2022-in-kotlin | Apache License 2.0 |
aoc/src/main/kotlin/com/bloidonia/aoc2023/day08/Main.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.day08
import com.bloidonia.aoc2023.lcm
import com.bloidonia.aoc2023.lines
import com.bloidonia.aoc2023.repeat
private const val example = """RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)"""
private const val example2 = """LLR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)"""
private const val example3 = """LR
11A = (11B, XXX)
11B = (XXX, 11Z)
11Z = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)"""
private fun moves(input: String) = input.map { if (it == 'R') 1 else 0 }.asSequence()
private data class Node(val next: List<String>) {
constructor(input: String) : this(Regex(""".+ = \(([^,]+), ([^)]+)\)""").matchEntire(input).let {
val (a, b) = it!!.destructured
listOf(a, b)
})
}
private fun parse(input: List<String>) = input
.drop(2)
.associate { i ->
i.split(Regex("\\s+"))[0] to Node(i)
}
private fun part1(input: List<String>): Int {
val moves = moves(input[0])
val network = parse(input)
return solve("AAA", moves, network) { it == "ZZZ" }
}
private fun solve(start: String, moves: Sequence<Int>, network: Map<String, Node>, success: (String) -> Boolean) = moves
.repeat()
.runningFold(start) { acc, move ->
network[acc]!!.next[move]
}
.withIndex()
.find { success(it.value) }!!.index
private fun part2(input: List<String>): Long {
val moves = moves(input[0])
val network = parse(input)
// Each node has a cyclic path to itself, so we can just find the LCM of the cycle lengths
val numbers = network.keys.filter { it.endsWith("A") }
.map { startNode ->
val stepsRequired = solve(startNode, moves, network) { it.endsWith("Z") }.toLong()
println("$startNode requires $stepsRequired steps")
stepsRequired
}
.toLongArray()
return lcm(*numbers)
}
fun main() {
println("Example 1: ${part1(example.lines())}")
println("Example 2: ${part1(example2.lines())}")
println("Part 1: ${part1(lines("/day08.input"))}")
println("Example 3: ${part2(example3.lines())}")
println("Part 2: ${part2(lines("/day08.input"))}")
} | 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 2,271 | aoc-2023 | MIT License |
src/Day21.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | fun main() {
class Monkey(val children: List<String>, val operation: (List<Long>) -> Long) {
fun getValue(tree: Map<String, Monkey>): Long {
return operation(children.map { x -> tree[x]!!.getValue(tree) })
}
}
val operations: Map<String, (List<Long>) -> Long> = mapOf(
"+" to { x -> x[0] + x[1] },
"-" to { x -> x[0] - x[1] },
"*" to { x -> x[0] * x[1] },
"/" to { x ->
if (x[0] % x[1] == 0L) {
x[0] / x[1]
} else {
throw Exception()
}
})
fun parseMonkey(input: String): Pair<String, Monkey> {
val (name, formula) = input.split(":")
if (formula.trim().split(" ").size == 1) {
val value = formula.trim().toLong()
val operationFunction =
if (name == "humn") {
fun(_: List<Long>): Long {
println("humn called")
return value
}
} else {
fun(_: List<Long>): Long {
return value
}
}
return (name to Monkey(listOf(), operationFunction))
}
val (left, operation, right) = formula.trim().split(" ")
return name to Monkey(listOf(left, right), operations[operation]!!)
}
fun parseInput(input: List<String>): Map<String, Monkey> {
return input.associate { s -> parseMonkey(s) }
}
fun part1(monkeys: Map<String, Monkey>): Long {
return monkeys["root"]!!.getValue(monkeys)
}
println("Day 21")
val testInput = readInput("Day21-test")
val realInput = readInput("Day21")
val testMonkeys = parseInput(testInput)
val realMonkeys = parseInput(realInput)
println("Part1 test: ${part1(testMonkeys)}")
println("Part1 real: ${part1(realMonkeys)}")
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 1,920 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2015/ScienceForHungryPeople.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2015
fun scienceForHungryPeople1(ingredients: List<Ingredient>) =
recipes(ingredients).maxOf { it.score() }
fun scienceForHungryPeople2(ingredients: List<Ingredient>): Int =
recipes(ingredients).filter { it.calories == 500 }.maxOf { it.score() }
private fun recipes(ingredients: List<Ingredient>) = sequence {
for (weights in weights(sum = 100))
yield((weights * ingredients).sum())
}
private fun weights(sum: Int) = sequence {
for (i in 0..sum)
for (j in 0..sum - i)
for (k in 0..sum - i - j)
yield(listOf(i, j, k, sum - i - j - k))
}
data class Ingredient(
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
) {
fun score() = capacity * durability * flavor * texture
}
private fun List<Ingredient>.sum() = Ingredient(
capacity = sumOf { it.capacity }.coerceAtLeast(0),
durability = sumOf { it.durability }.coerceAtLeast(0),
flavor = sumOf { it.flavor }.coerceAtLeast(0),
texture = sumOf { it.texture }.coerceAtLeast(0),
calories = sumOf { it.calories }.coerceAtLeast(0),
)
private operator fun List<Int>.times(ingredients: List<Ingredient>) =
zip(ingredients) { w, i -> w * i }
private operator fun Int.times(i: Ingredient) = Ingredient(
capacity = this * i.capacity,
durability = this * i.durability,
flavor = this * i.flavor,
texture = this * i.texture,
calories = this * i.calories
)
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,497 | advent-of-code | MIT License |
src/main/kotlin/Day05.kt | Vampire | 572,990,104 | false | {"Kotlin": 57326} | fun main() {
val movePattern = """move (?<amount>\d++) from (?<source>\d) to (?<target>\d)""".toPattern()
fun part1(input: List<String>, rearrange: Boolean = true): String {
val stackLines = input.takeWhile(String::isNotBlank).asReversed()
val stackNumbersLine = stackLines[0]
val stackNumbers = stackNumbersLine.trim().split(" ++".toPattern())
val stacks = stackNumbers.associateWith { stackNumber ->
val stackIndex = stackNumbersLine.indexOf(stackNumber)
stackLines
.drop(1)
.map { if (stackIndex < it.length) it[stackIndex] else ' ' }
.filter { it != ' ' }
.toMutableList()
}
input
.dropWhile(String::isNotBlank)
.drop(1)
.filter(String::isNotBlank)
.forEach {
val matchResult = movePattern.matcher(it).apply { check(matches()) }
val amount = matchResult.group("amount").toInt()
val source = matchResult.group("source")
val target = matchResult.group("target")
if (rearrange) {
amount.downTo(1).forEach {
stacks[target]!!.add(stacks[source]!!.removeLast())
}
} else {
stacks[target]!!.addAll(amount.downTo(1).map {
stacks[source]!!.removeLast()
}.asReversed())
}
}
return stackNumbers
.map { stacks[it] }
.joinToString(separator = "") {
it!!.last().toString()
}
}
fun part2(input: List<String>) = part1(input, rearrange = false)
val testInput = readStrings("Day05_test", trim = false)
check(part1(testInput) == "CMZ")
val input = readStrings("Day05", trim = false)
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
check(part1(input) == "VWLCWGSDQ")
}
| 0 | Kotlin | 0 | 0 | 16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f | 2,029 | aoc-2022 | Apache License 2.0 |
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day12/Day12.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2021.day12
import eu.janvdb.aocutil.kotlin.readLines
import java.util.*
const val FILENAME = "input12.txt"
fun main() {
val connections = readLines(2021, FILENAME)
.map { it.split('-').map(::Room) }
.flatMap { rooms -> listOf(Connection(rooms[0], rooms[1]), Connection(rooms[1], rooms[0])) }
val paths1 = enumeratePaths(connections, ::canVisit1)
println(paths1.size)
val paths2 = enumeratePaths(connections, ::canVisit2)
println(paths2.size)
}
fun canVisit1(currentPath: Path, room: Room): Boolean {
return room.isLarge() || !currentPath.contains(room)
}
fun canVisit2(currentPath: Path, room: Room): Boolean {
if (!currentPath.contains(room)) return true
if (room.isLarge()) return true
if (room == Room.START || room == Room.END) return false
return currentPath.containsSmallRoomTwice()
}
fun enumeratePaths(connections: Collection<Connection>, canVisitFunction: (Path, Room) -> Boolean): List<Path> {
val result = mutableListOf<Path>()
val pathsToVisit: Deque<Path> = LinkedList()
pathsToVisit.addFirst(Path(Room.START))
while (!pathsToVisit.isEmpty()) {
val pathToVisit = pathsToVisit.removeFirst()
val endPoint = pathToVisit.last()
if (endPoint == Room.END) {
result.add(pathToVisit)
} else {
connections.asSequence()
.filter { it.from == endPoint }
.filter { canVisitFunction(pathToVisit, it.to) }
.forEach {
val newPath = pathToVisit.add(it.to)
pathsToVisit.addFirst(newPath)
}
}
}
return result
}
data class Room(val name: String) {
fun isLarge() = name.uppercase() == name
fun isSmall() = name.uppercase() != name
companion object {
val START = Room("start")
val END = Room("end")
}
}
data class Connection(val from: Room, val to: Room)
data class Path(val rooms: List<Room>) {
constructor(room: Room) : this(listOf(room))
fun last(): Room = rooms.last()
fun add(room: Room) = Path(rooms + room)
fun contains(room: Room) = rooms.contains(room)
fun containsSmallRoomTwice() = rooms
.filter { it.isSmall() }
.groupBy { it }
.none { it.value.size > 1 }
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,079 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day23.kt | gijs-pennings | 573,023,936 | false | {"Kotlin": 20319} | import java.util.*
private const val N_ROUNDS = 1000 // use N_ROUNDS=10 for part 1
private val NEIGHBORS_DELTA = listOf(
Pos( 0, 1),
Pos( 1, 1),
Pos( 1, 0),
Pos( 1, -1),
Pos( 0, -1),
Pos(-1, -1),
Pos(-1, 0),
Pos(-1, 1)
)
fun main() {
val lines = readInput(23)
val w = lines[0].length
val h = lines.size
val elves = mutableListOf<Elf>()
for (x in 0 until w)
for (y in 0 until h)
if (lines[h - y - 1][x] == '#')
elves += Elf(Pos(x + N_ROUNDS, y + N_ROUNDS))
val nOccupying = Array(w + 2 * N_ROUNDS) { IntArray(h + 2 * N_ROUNDS) }
nOccupying.fill(elves.map { it.pos })
val dirs = ArrayDeque(Dir.values().toList())
repeat(N_ROUNDS) { round ->
// first half: determine proposed directions
for (e in elves)
if (NEIGHBORS_DELTA.any { nOccupying[e.pos + it] > 0 })
e.propDir = dirs.firstOrNull { d ->
d.checkEmptyDelta.all { nOccupying[e.pos + it] == 0 }
}
// second half: move each elf with no conflicts
nOccupying.fill(elves.map { it.propPos })
var moved = 0
for (e in elves)
if (e.propDir != null) {
if (nOccupying[e.propPos] == 1) { e.pos = e.propPos; moved++ }
e.propDir = null
}
if (N_ROUNDS != 10 && moved == 0) {
println("round ${round + 1}") // part 2
return
}
nOccupying.fill(elves.map { it.pos })
// prepare for next round
dirs.addLast(dirs.removeFirst())
}
val (x0, x1) = nOccupying.getFirstAndLastColumns()
val (y0, y1) = nOccupying.transposed().getFirstAndLastColumns()
println("${(x1 - x0) * (y1 - y0) - elves.size} empty tiles") // part 1
}
private fun Array<IntArray>.fill(ps: Iterable<Pos>) {
for (col in this) col.fill(0)
for (p in ps) this[p.x][p.y]++
}
private fun Array<IntArray>.getFirstAndLastColumns() = Pair(
indexOfFirst { it.any { v -> v > 0 } },
indexOfLast { it.any { v -> v > 0 } } + 1
)
private fun Array<IntArray>.transposed() = Array(this[0].size) { y ->
IntArray(this.size) { x -> this[x][y] }
}
private operator fun Array<IntArray>.get(i: Pos) = this[i.x][i.y]
private data class Elf(var pos: Pos) {
var propDir: Dir? = null
val propPos get() = if (propDir == null) pos else pos + propDir!!.delta
}
private enum class Dir(
val delta: Pos,
val checkEmptyDelta: List<Pos>
) {
NORTH(y = +1),
SOUTH(y = -1),
WEST(x = -1),
EAST(x = +1);
constructor(x: Int = 0, y: Int = 0) : this(Pos(x, y), listOf(
if (x == 0) Pos(-1, y) else Pos(x, -1),
Pos(x, y),
if (x == 0) Pos(+1, y) else Pos(x, +1)
))
}
| 0 | Kotlin | 0 | 0 | 8ffbcae744b62e36150af7ea9115e351f10e71c1 | 2,778 | aoc-2022 | ISC License |
2022/src/main/kotlin/com/github/akowal/aoc/Day17.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
import kotlin.math.min
class Day17 {
private val wind = inputFile("day17").readLines().single().map {
when (it) {
'>' -> 1
else -> -1
}
}
private val shapes = listOf(
intArrayOf(
0b0011110,
),
intArrayOf(
0b0001000,
0b0011100,
0b0001000,
),
intArrayOf(
0b0011100,
0b0000100,
0b0000100,
),
intArrayOf(
0b0010000,
0b0010000,
0b0010000,
0b0010000,
),
intArrayOf(
0b0011000,
0b0011000,
),
)
fun solvePart1(): Int {
val chamber = mutableListOf<Int>()
repeat(2022) { n ->
val windShift = calcWindShift(n)
val shape = shapes[n % shapes.size].shifted(windShift)
// println(">>>>> $n")
// println(shape.render())
// println("---<")
chamber.asReversed().forEach { println(it.render())}
val stopDepth = (chamber.lastIndex downTo 0).firstOrNull {
collides(it, chamber, shape)
}?.inc() ?: 0
if (stopDepth + shape.size >= chamber.size) {
repeat(stopDepth + shape.size - chamber.size) { chamber.add(0) }
}
shape.forEachIndexed { i, layer ->
chamber[stopDepth + i] = chamber[stopDepth + i] or layer
}
println("--->")
chamber.asReversed().forEach { println(it.render())}
}
return chamber.size - 1
}
private fun collides(depth: Int, chamber: List<Int>, shape: IntArray): Boolean {
if (chamber.isEmpty() || depth < 0) {
return true
}
for (i in depth until min(depth + shape.size, chamber.size)) {
if (chamber[i] and shape[i - depth] != 0) {
return true
}
}
return false
}
private fun calcWindShift(i: Int): Int {
var offset = 0
repeat(3) { j ->
offset += wind[(i + j) % wind.size]
}
return offset
}
fun solvePart2(): Int {
return 0
}
fun IntArray.render() = joinToString("\n") { it.render() }
fun Int.render() = "%7s".format(Integer.toBinaryString(this)).replace(' ', '.').replace('0', '.').replace('1', '#')
private fun IntArray.shifted(n: Int): IntArray {
val rightSpace = minOf(Int::countTrailingZeroBits)
val leftSpace = 7 - maxOf(Int::takeHighestOneBit).shl(1).countTrailingZeroBits()
return when {
n > 0 -> map { layer -> layer shr min(n, rightSpace) }.toIntArray()
n < 0 -> map { layer -> layer shl min(-n, leftSpace) }.toIntArray()
else -> this
}
}
}
fun main() {
val solution = Day17()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 3,004 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day12/Day12.kt | dustinconrad | 572,737,903 | false | {"Kotlin": 100547} | package day12
import geometry.Coord
import geometry.plus
import geometry.x
import geometry.y
import readResourceAsBufferedReader
import java.util.function.Predicate
fun main() {
println("part 1: ${part1(readResourceAsBufferedReader("12_1.txt").readLines())}")
println("part 2: ${part2(readResourceAsBufferedReader("12_1.txt").readLines())}")
}
fun part1(input: List<String>): Int {
val start = input.find('S')
val end = Predicate<Char> { 'E' == it }
return bfs(input, start, end) { curr, neighbor -> neighbor.code - curr.code <= 1}
}
fun part2(input: List<String>): Int {
val start = input.find('E')
val end = Predicate<Char> { 'a' == it || 'S' == it }
return bfs(input, start, end) { curr, neighbor -> curr.code - neighbor.code <= 1}
}
typealias Hills = List<String>
fun Hills.elevation(c: Coord): Char {
return when(val char = this[c.y()][c.x()]) {
'S' -> 'a'
'E' -> 'z'
else -> char
}
}
fun Array<IntArray>.at(c: Coord): Int = this[c.y()][c.x()]
fun Hills.neighbors(c: Coord): List<Coord> {
return listOf(
1 to 0, -1 to 0, 0 to 1, 0 to -1
).map(c::plus)
.filter { this.indices.contains(it.y()) && this[c.y()].indices.contains(it.x()) }
}
fun Hills.find(c: Char): Coord {
return this.mapIndexed { index, s -> index to s.indexOf(c) }
.first { it.x() != -1 }
}
fun bfs(hills: Hills, start: Coord, end: Predicate<Char>, nFn: (Char, Char) -> Boolean): Int {
val shortestPaths = Array(hills.size) { IntArray(hills[0].length) }
shortestPaths[start.y()][start.x()] = 0
val seen = mutableSetOf<Coord>()
val q = ArrayDeque<Coord>()
q.add(start)
while(q.isNotEmpty()) {
val curr = q.removeFirst()
if (end.test(hills[curr.y()][curr.x()])) {
return shortestPaths.at(curr)
}
if (!seen.add(curr)) {
continue
}
val currShortest = shortestPaths.at(curr)
val neighbors = hills.neighbors(curr)
.filterNot { seen.contains(it) }
.filter { nFn.invoke(hills.elevation(curr), hills.elevation(it)) }
neighbors.forEach {
shortestPaths[it.y()][it.x()] = currShortest + 1
}
q.addAll(neighbors)
}
throw IllegalArgumentException("No end")
} | 0 | Kotlin | 0 | 0 | 1dae6d2790d7605ac3643356b207b36a34ad38be | 2,304 | aoc-2022 | Apache License 2.0 |
advent7/src/main/kotlin/Main.kt | thastreet | 574,294,123 | false | {"Kotlin": 29380} | import java.io.File
interface IFile {
val name: String
val size: Int
val parent: Directory?
}
data class SingleFile(
override val name: String,
override val size: Int,
override val parent: Directory?
) : IFile
data class Directory(
override val name: String,
override var parent: Directory?
) : IFile {
var files: MutableMap<String, IFile> = mutableMapOf()
override val size: Int
get() = files.values.sumOf { it.size }
fun flatten(output: MutableList<Directory>) {
files.values.filterIsInstance<Directory>().forEach {
output.add(it)
it.flatten(output)
}
}
}
fun main(args: Array<String>) {
val lines = File("input.txt").readLines()
val root = parseTree(lines)
val part1Answer = part1(root)
println("part1Answer: $part1Answer")
val part2Answer = part2(root)
println("part2Answer: $part2Answer")
}
fun part1(root: Directory): Int {
val candidates = mutableListOf<Directory>()
findPart1Candidates(root, candidates)
return candidates.sumOf { it.size }
}
fun part2(root: Directory): Int {
val directories = mutableListOf<Directory>()
root.flatten(directories)
directories.sortBy { it.size }
val unused = 70000000 - root.size
val needed = 30000000 - unused
return directories.first { it.size >= needed }.size
}
fun findPart1Candidates(directory: Directory, candidates: MutableList<Directory>) {
directory.files.values.filterIsInstance<Directory>().forEach {
if (it.size <= 100000) {
candidates.add(it)
}
findPart1Candidates(it, candidates)
}
}
fun parseTree(lines: List<String>): Directory {
var index = 0
var directory: Directory? = null
var root: Directory? = null
do {
val line = lines[index]
val parts = line.split(" ")
when (parts[0]) {
"$" -> {
when (parts[1]) {
"cd" -> {
directory = if (parts[2] == "..") {
directory?.parent
} else {
directory?.files?.values
?.firstOrNull { it is Directory && it.name == parts[2] } as? Directory
?: Directory(parts[0], directory).also {
if (root == null) {
root = it
}
}
}
}
"ls" -> {
var tempIndex = index
var tempParts: List<String> = emptyList()
do {
++tempIndex
if (tempIndex in lines.indices) {
val tempLine = lines[tempIndex]
tempParts = tempLine.split(" ")
when (tempParts[0]) {
"$" -> index = tempIndex - 1
"dir" -> directory?.files?.set(tempParts[1], Directory(tempParts[1], directory))
else -> directory?.files?.set(
tempParts[1],
SingleFile(tempParts[1], tempParts[0].toInt(), directory)
)
}
}
} while (tempIndex in lines.indices && tempParts[0] != "$")
}
}
}
}
++index
} while (index in lines.indices)
return root!!
} | 0 | Kotlin | 0 | 0 | e296de7db91dba0b44453601fa2b1696af9dbb15 | 3,752 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | fasfsfgs | 573,562,215 | false | {"Kotlin": 52546} | fun main() {
fun part1(input: List<String>): Int {
val verticalSlice = input.toLines().toVerticalSlice()
return releaseSand(verticalSlice)
}
fun part2(input: List<String>): Int {
val verticalSlice = input.toLines().toVerticalSlice()
verticalSlice.addFloor()
return releaseSand(verticalSlice)
}
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
data class LineCoords(val start: Pair<Int, Int>, val end: Pair<Int, Int>)
fun List<String>.toLines() = flatMap { it.toLines() }
fun String.toLines() = split(" -> ")
.map {
val (xLine, yLine) = it.split(",")
Pair(xLine.toInt(), yLine.toInt())
}
.windowed(2)
.map { LineCoords(it[0], it[1]) }
data class VerticalSlice(val scan: MutableMap<Pair<Int, Int>, Structure>, var floorY: Int? = null) {
fun addFloor() {
floorY = scan.keys.map { it.second }.max() + 2
}
}
fun List<LineCoords>.toVerticalSlice(): VerticalSlice {
val scan = mutableMapOf<Pair<Int, Int>, Structure>()
forEach {
if (it.start.first == it.end.first) {
val x = it.start.first
val minY = it.start.second.coerceAtMost(it.end.second)
val maxY = it.start.second.coerceAtLeast(it.end.second)
for (y in minY..maxY) scan[Pair(x, y)] = Structure.ROCK
} else {
val y = it.start.second
val minX = it.start.first.coerceAtMost(it.end.first)
val maxX = it.start.first.coerceAtLeast(it.end.first)
for (x in minX..maxX) scan[Pair(x, y)] = Structure.ROCK
}
}
return VerticalSlice(scan)
}
enum class Structure(val representation: Char) {
SAND('o'),
ROCK('#'),
AIR('.')
}
fun releaseSand(verticalSlice: VerticalSlice): Int {
var restedSand = 0
var sandOverflown = false
while (!sandOverflown) {
val newSand = dropNewSand(verticalSlice) ?: return restedSand
verticalSlice.scan[newSand] = Structure.SAND
restedSand++
if (newSand == Pair(500, 0)) return restedSand
}
return restedSand
}
fun dropNewSand(verticalSlice: VerticalSlice): Pair<Int, Int>? {
var sand = Pair(500, 0)
val maxY = verticalSlice.scan.keys.map { it.second }.max()
var sandRested = false
while (!sandRested) {
if (verticalSlice.floorY == null && sand.second == maxY) return null
if (sand.second + 1 == verticalSlice.floorY) {
sandRested = true
continue
}
if (verticalSlice.scan[Pair(sand.first, sand.second + 1)] == null) {
sand = sand.copy(second = sand.second + 1)
continue
}
if (verticalSlice.scan[Pair(sand.first - 1, sand.second + 1)] == null) {
sand = sand.copy(sand.first - 1, sand.second + 1)
continue
}
if (verticalSlice.scan[Pair(sand.first + 1, sand.second + 1)] == null) {
sand = sand.copy(sand.first + 1, sand.second + 1)
continue
}
sandRested = true
}
return sand
}
| 0 | Kotlin | 0 | 0 | 17cfd7ff4c1c48295021213e5a53cf09607b7144 | 3,217 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g1001_1100/s1031_maximum_sum_of_two_non_overlapping_subarrays/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1001_1100.s1031_maximum_sum_of_two_non_overlapping_subarrays
// #Medium #Array #Dynamic_Programming #Sliding_Window
// #2023_05_24_Time_172_ms_(100.00%)_Space_36.7_MB_(100.00%)
class Solution {
fun maxSumTwoNoOverlap(nums: IntArray, firstLen: Int, secondLen: Int): Int {
val firstLenSum = getFirstLenSums(nums, firstLen)
return getMaxLenSum(nums, secondLen, firstLenSum)
}
private fun getMaxLenSum(nums: IntArray, secondLen: Int, firstLenSum: Array<IntArray>): Int {
var maxSum = 0
var currentSum = 0
var onRight: Int
for (i in 0 until secondLen) {
currentSum += nums[i]
}
onRight = firstLenSum[1][secondLen]
maxSum = maxSum.coerceAtLeast(currentSum + onRight)
var i = 1
var j = secondLen
while (j < nums.size) {
currentSum = currentSum - nums[i - 1] + nums[j]
onRight = if (j < nums.size - 1) firstLenSum[1][j + 1] else 0
maxSum = maxSum.coerceAtLeast(currentSum + firstLenSum[0][i - 1].coerceAtLeast(onRight))
i++
j++
}
return maxSum
}
private fun getFirstLenSums(nums: IntArray, windowSize: Int): Array<IntArray> {
// sum[0] - maximum from left to right, sum[1] - max from right to left.
val sum = Array(2) { IntArray(nums.size) }
var currentLeftSum = 0
var currentRightSum = 0
run {
var i = 0
var j = nums.size - 1
while (i < windowSize) {
currentLeftSum += nums[i]
currentRightSum += nums[j]
i++
j--
}
}
sum[0][windowSize - 1] = currentLeftSum
sum[1][nums.size - windowSize] = currentRightSum
var i = windowSize
var j = nums.size - windowSize - 1
while (i < nums.size) {
currentLeftSum = currentLeftSum - nums[i - windowSize] + nums[i]
currentRightSum = currentRightSum - nums[j + windowSize] + nums[j]
sum[0][i] = sum[0][i - 1].coerceAtLeast(currentLeftSum)
sum[1][j] = sum[1][j + 1].coerceAtLeast(currentRightSum)
i++
j--
}
return sum
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,255 | LeetCode-in-Kotlin | MIT License |
src/Day10.kt | xabgesagtx | 572,139,500 | false | {"Kotlin": 23192} | fun main() {
val day = "Day10"
fun calcCycleValues(input: List<String>): List<Pair<Int, Int>> {
var x = 1
var cycle = 1
val cycleValues = input.flatMap {
if (it == "noop") {
listOf(++cycle to x)
} else {
val firstCycleValue = ++cycle to x
x += it.incValue()
listOf(firstCycleValue, ++cycle to x)
}
}
return listOf(1 to 1) + cycleValues
}
fun combinedSignalStrengthAt(input: List<String>, cycles: Set<Int>): Int {
return calcCycleValues(input).filter { it.first in cycles }
.sumOf { it.first * it.second }
}
fun part1(input: List<String>): Int {
return combinedSignalStrengthAt(input, setOf(20, 60, 100, 140, 180, 220))
}
fun part2(input: List<String>): List<String> {
return calcCycleValues(input)
.dropLast(1)
.chunked(40)
.map { line ->
line.map { it.second }
.mapIndexed { index, cycleValue -> calcSpriteAt(index, cycleValue) }
.joinToString("")
}
}
println(
calcCycleValues(
listOf(
"noop",
"addx 3",
"addx -5"
)
)
)
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
check(part1(testInput) == 13140)
part2(testInput).forEach { println(it) }
check(
part2(testInput) == listOf(
"##..##..##..##..##..##..##..##..##..##..",
"###...###...###...###...###...###...###.",
"####....####....####....####....####....",
"#####.....#####.....#####.....#####.....",
"######......######......######......####",
"#######.......#######.......#######....."
)
)
val input = readInput(day)
println(part1(input))
println()
println()
println("RESULT:")
println()
part2(input).forEach { println(it) }
}
private fun calcSpriteAt(pos: Int, cycleValue: Int): Char {
return spriteFor(cycleValue)[pos]
}
private fun spriteFor(cycleValue: Int): List<Char> {
val spritePos = (cycleValue .. cycleValue + 2).toSet()
return (1..40).map { if (it in spritePos) '#' else '.' }
}
private fun String.incValue() = split(" ").firstNotNullOf { it.toIntOrNull() } | 0 | Kotlin | 0 | 0 | 976d56bd723a7fc712074066949e03a770219b10 | 2,459 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2021/d04/Day04.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2021.d04
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
typealias Board = MutableList<List<Int>>
// if winningBoard = false, we want to find the board that wins last
fun scoreBoard(nums: List<Int>, boards: List<Board>, winningBoard: Boolean): Int {
val markers = boards.map { board ->
board.map { row ->
row.map { false }.toMutableList()
}
}
fun isWinner(boardMarkers: List<List<Boolean>>) =
boardMarkers.any { row -> row.all { it } } || // won along a row
boardMarkers.indices.any { x -> boardMarkers.all { it[x] } } // won along a column
var i = 0
var lastWinner: Int? = null
val winners = mutableSetOf<Int>()
while ((winningBoard && winners.isEmpty()) || (!winningBoard && winners.size < boards.size)) {
val num = nums[i]
boards.forEachIndexed { boardNum, board ->
board.forEachIndexed { y, row ->
row.forEachIndexed { x, entry ->
if (entry == num) {
markers[boardNum][y][x] = true
}
}
}
if (boardNum !in winners && isWinner(markers[boardNum])) {
winners.add(boardNum)
lastWinner = boardNum
}
}
i++
}
val unmarkedSum = boards[lastWinner!!].flatMapIndexed { y, row ->
row.filterIndexed { x, _ ->
!markers[lastWinner!!][y][x]
}
}.sum()
return unmarkedSum * nums[i-1]
}
fun main() = timed {
val (nums, boards) = (DATAPATH / "2021/day04.txt")
.useLines { it.toList() }
.let { lines ->
val nums = lines.first()
.split(",")
.map { it.toInt() }
val boards = mutableListOf<Board>()
lines.drop(1).forEach { line ->
if (line.isBlank()) {
boards.add(mutableListOf())
} else {
boards.last().add(
line.split(Regex("\\s+"))
.mapNotNull { it.toIntOrNull() }
)
}
}
nums to boards
}
println("Part one: ${scoreBoard(nums, boards, true)}")
println("Part two: ${scoreBoard(nums, boards, false)}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,421 | advent-of-code | MIT License |
y2019/src/main/kotlin/adventofcode/y2019/Day15.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2019
import adventofcode.io.AdventSolution
import adventofcode.language.intcode.IntCodeProgram
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
import adventofcode.util.vector.neighbors
import java.util.*
fun main() = Day15.solve()
object Day15 : AdventSolution(2019, 15, "Oxygen System") {
override fun solvePartOne(input: String) =
IntCodeProgram.fromData(input).let(::exploreMaze).first
override fun solvePartTwo(input: String): Int {
val map: Map<Vec2, Int> = IntCodeProgram.fromData(input).let(::exploreMaze).second
val source: List<Vec2> = map.asSequence().first { it.value == 2 }.key.let { listOf(it) }
val open: MutableSet<Vec2> = map.asSequence().filter { it.value == 1 }.map { it.key }.toMutableSet()
return generateSequence(source) { candidates ->
candidates.flatMap { p -> p.neighbors().filter { it in open } }
}
.onEach { open -= it.toSet() }
.indexOfFirst { it.isEmpty() } - 1
}
private fun exploreMaze(droidcontrol: IntCodeProgram): Pair<Int, Map<Vec2, Int>> {
val map = mutableMapOf(Vec2.origin to 1)
var position = Vec2.origin
val pathToPosition = Stack<Direction>()
var score = 0
while (true) {
val forwardDirection = Direction.values().find { position + it.vector !in map }
val backtrackingDirection = pathToPosition.lastOrNull()?.reverse
val dir = forwardDirection ?: backtrackingDirection ?: return score to map
droidcontrol.input(dir.toInput())
droidcontrol.execute()
val status = droidcontrol.output()!!.toInt()
position += dir.vector
map[position] = status
when {
status == 0 -> position -= dir.vector
forwardDirection != null -> pathToPosition.push(dir)
else -> pathToPosition.pop()
}
if (status == 2) score = pathToPosition.size
}
}
private fun Direction.toInput() = when (this) {
Direction.UP -> 1L
Direction.RIGHT -> 4L
Direction.DOWN -> 2L
Direction.LEFT -> 3L
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,270 | advent-of-code | MIT License |
src/Day12.kt | HaydenMeloche | 572,788,925 | false | {"Kotlin": 25699} | fun main() {
val lines = readInput("Day12")
val graph = Graph(lines.mapIndexed { y, line -> line.mapIndexed { x, code -> Vertex(x, y, code) } })
println("answer one: ${graph.findShortestPath('S')}")
println("answer two: ${graph.findShortestPath('a')}")
}
class Vertex(val x: Int, val y: Int, val code: Char) {
val height: Int
get() = when(code) {
'S' -> 0
'E' -> 26
else -> code - 'a'
}
}
class Graph(private val vertexes: List<List<Vertex>>) {
private val xMax = vertexes[0].lastIndex
private val yMax = vertexes.lastIndex
fun findShortestPath(target: Char): Int? {
val end = vertexes.flatten().single { it.code == 'E' }
val exploringVertex = ArrayDeque(listOf(end to 0))
val visited = mutableSetOf(end)
while (!exploringVertex.isEmpty()) {
val (vertex, distance) = exploringVertex.removeFirst()
if (vertex.code == target) return distance
vertex.reachableNeighbors(vertex.height).forEach {
if (visited.add(it)) exploringVertex.add(it to distance + 1)
}
}
return null
}
private fun Vertex.neighbors() = listOfNotNull(
vertexAt(x - 1, y), vertexAt(x + 1, y),
vertexAt(x, y - 1), vertexAt(x, y + 1)
)
private fun Vertex.reachableNeighbors(height: Int) = neighbors().filter { it.height + 1 >= height}
private fun vertexAt(x: Int, y: Int) =
if (x < 0 || x > xMax || y < 0 || y > yMax) null else vertexes[y][x]
} | 0 | Kotlin | 0 | 1 | 1a7e13cb525bb19cc9ff4eba40d03669dc301fb9 | 1,554 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | cjosan | 573,106,026 | false | {"Kotlin": 5721} | fun main() {
fun Char.toPriority() = (if (isLowerCase()) this - 'a' else this - 'A' + 26) + 1
fun String.splitToSets() = Pair(
this.substring(0, this.length / 2).toSet(),
this.substring(this.length / 2).toSet()
)
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
rucksack
.splitToSets()
.let { (first, second) -> first intersect second }
.single()
.toPriority()
}
}
fun part2(input: List<String>): Int {
return input
.chunked(3) {
it.map { elf ->
elf.toSet()
}.let { (first, second, third) ->
first intersect second intersect third
}.single().toPriority()
}
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a81f7fb9597361d45ff73ad2a705524cbc64008b | 1,135 | advent-of-code2022 | Apache License 2.0 |
src/Day02.kt | dmdrummond | 573,289,191 | false | {"Kotlin": 9084} | fun main() {
fun part1(input: List<String>): Int {
fun calculateScore(input: String): Int {
val choiceScore = when(input[2]) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> throw Error("Unable to process $input")
}
val winScore = when (input) {
"A X", "B Y", "C Z" -> 3
"A Y", "B Z", "C X" -> 6
"A Z", "B X", "C Y" -> 0
else -> throw Error ("Not sure what $input means")
}
return choiceScore + winScore
}
return input.sumOf { calculateScore(it) }
}
fun part2(input: List<String>): Int {
fun calculateScore(input: String): Int {
val winScore = when (input[2]) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> throw Error("Not sure what $input means")
}
val choiceScore = when (input) {
"A X", "C Y", "B Z" -> 3
"C X", "B Y", "A Z" -> 2
"B X", "A Y", "C Z" -> 1
else -> throw Error("Unable to process $input")
}
return winScore + choiceScore
}
return input.sumOf { calculateScore(it) }
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 2493256124c341e9d4a5e3edfb688584e32f95ec | 1,536 | AoC2022 | Apache License 2.0 |
2021/src/Day13.kt | Bajena | 433,856,664 | false | {"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454} | import java.util.*
// https://adventofcode.com/2021/day/13
fun main() {
class Table(dots: List<Pair<Int, Int>>) {
var dots = dots
fun fold(direction: String, at: Int) {
var newDots = mutableListOf<Pair<Int, Int>>()
when (direction) {
"x" -> {
dots.forEach {
if (it.first > at) {
newDots.add(Pair(it.first - 2 * (it.first - at), it.second))
} else {
newDots.add(it)
}
}
}
"y" -> {
dots.forEach {
if (it.second > at) {
newDots.add(Pair(it.first, it.second - 2 * (it.second - at)))
} else {
newDots.add(it)
}
}
}
else -> println("OOOPS")
}
dots = newDots.distinct()
}
fun pointToIndex(x : Int, y : Int) : Int {
return y * cols() + x
}
fun indexToPoint(index : Int) : Pair<Int, Int> {
return Pair(index % cols(), index / cols())
}
fun cols() : Int {
return dots.maxOf { it.first } + 1
}
fun rows() : Int {
return dots.maxOf { it.second } + 1
}
fun printMe() {
val dotIndices = dots.map { pointToIndex(it.first, it.second) }.sorted()
(0..(cols() * rows() - 1)).forEach { index ->
if (index % cols() == 0) {
println("")
// print("${index / rows() }: ")
}
if (dotIndices.contains(index)) {
print("#")
} else print(".")
}
println()
}
}
fun part1() {
val dots = mutableListOf<Pair<Int, Int>>()
val folds = mutableListOf<Pair<String, Int>>()
for (line in readInput("Day13")) {
if (line.isEmpty()) continue
if (line.startsWith("fold")) {
val command = line.replace("fold along ", "").split("=")
folds.add(Pair(command.first(), command.last().toInt()))
continue
}
val dot = line.split(",").map { it.toInt() }
dots.add(Pair(dot.first(), dot.last()))
}
println(dots)
println(folds)
val t = Table(dots)
t.printMe()
t.fold(folds.first().first, folds.first().second)
t.printMe()
println(t.dots.size)
}
fun part2() {
val dots = mutableListOf<Pair<Int, Int>>()
val folds = mutableListOf<Pair<String, Int>>()
for (line in readInput("Day13")) {
if (line.isEmpty()) continue
if (line.startsWith("fold")) {
val command = line.replace("fold along ", "").split("=")
folds.add(Pair(command.first(), command.last().toInt()))
continue
}
val dot = line.split(",").map { it.toInt() }
dots.add(Pair(dot.first(), dot.last()))
}
println(dots)
println(folds)
val t = Table(dots)
for (fold in folds) {
t.fold(fold.first, fold.second)
}
t.printMe()
println(t.dots.size)
}
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a | 2,896 | advent-of-code | Apache License 2.0 |
src/main/algorithms/sorting/QuickSort.kt | vamsitallapudi | 119,534,182 | false | {"Java": 24691, "Kotlin": 20452} | package main.algorithms.sorting
fun main(args: Array<String>) {
val array = readLine()!!.split(" ").map { it.toInt() }.toIntArray() // 1) Read the input and split into array
quickSort(array, 0, array.size-1)
for(i in array) println(i)
}
fun quickSort(array: IntArray, left: Int, right: Int) {
val index = partition (array, left, right)
if(left < index-1) { // 2) Sorting left half
quickSort(array, left, index-1)
}
if(index < right) { // 3) Sorting right half
quickSort(array,index, right)
}
}
fun partition(array: IntArray, l: Int, r: Int): Int {
var left = l
var right = r
val pivot = array[(left + right)/2] // 4) Pivot Point
while (left <= right) {
while (array[left] < pivot) left++ // 5) Find the elements on left that should be on right
while (array[right] > pivot) right-- // 6) Find the elements on right that should be on left
// 7) Swap elements, and move left and right indices
if (left <= right) {
swapArray(array, left,right)
left++
right--
}
}
return left
}
fun swapArray(a: IntArray, b: Int, c: Int) {
val temp = a[b]
a[b] = a[c]
a[c] = temp
}
| 0 | Java | 1 | 1 | 9349fa7488fcabcb9c58ce5852d97996a9c4efd3 | 1,229 | HackerEarth | Apache License 2.0 |
src/Day03.kt | euphonie | 571,665,044 | false | {"Kotlin": 23344} | fun main() {
fun getCharValue(c: Char) : Int {
return (if (c.isLowerCase()) c.code -'a'.code else c.code -'A'.code+26)+1
}
fun countMatchingTypes(rucksack: String) : Int {
val halfIndex = (rucksack.length/2)
val firstCompartment = rucksack.substring(0, halfIndex)
val secondCompartment = rucksack.substring(halfIndex)
val matchingTypes = firstCompartment.filter{
it in secondCompartment
}.toSet()
return matchingTypes.sumOf { c -> getCharValue(c) }
}
fun part1(input: List<String>) : Int {
return input.sumOf { rucksack -> countMatchingTypes(rucksack) }
}
fun getBadgePriority(group: List<String>) : Int {
val matchingType = group[0].filter {
it in group[1] && it in group[2]
}.toSet()
return matchingType.sumOf { c -> getCharValue(c) }
}
fun part2(input: List<String>) : Int {
var badgePriorities = 0
for (i in input.indices step 3) {
badgePriorities += getBadgePriority(input.slice(i..i+2))
}
return badgePriorities
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
check(part1(input) == 7763)
check(part2(input) == 2569)
} | 0 | Kotlin | 0 | 0 | 82e167e5a7e9f4b17f0fbdfd01854c071d3fd105 | 1,336 | advent-of-code-kotlin | Apache License 2.0 |
solutions/aockt/y2015/Y2015D16.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2015
import io.github.jadarma.aockt.core.Solution
object Y2015D16 : Solution {
private val propertyRegex = Regex("""([a-z]+): (\d+)""")
private val sueIdRegex = Regex("""^Sue (\d+):.*$""")
/** Parses a single line of input and returns what information you know about any [AuntSue]. */
private fun parseInput(input: String) = AuntSue(
id = sueIdRegex.matchEntire(input)!!.groups[1]!!.value.toInt(),
properties = propertyRegex.findAll(input).associate {
val (name, value) = it.destructured
name to value.toInt()
}
)
/** All you know about one of your many aunts. */
private data class AuntSue(val id: Int, val properties: Map<String, Int>)
/**
* Tests these properties against the [mfcsamRules] and returns whether they meet all criteria.
* If there is a rule for a key that is not present in this map, it is ignored.
*/
private fun Map<String, Int>.consistentWith(mfcsamRules: Map<String, (Int) -> Boolean>): Boolean =
mfcsamRules.all { (key, predicate) -> this[key]?.let { value -> predicate(value) } ?: true }
override fun partOne(input: String) =
input
.lineSequence()
.map(this::parseInput)
.first { aunt ->
aunt.properties.consistentWith(
mapOf(
"children" to { it == 3 },
"cats" to { it == 7 },
"samoyeds" to { it == 2 },
"pomeranians" to { it == 3 },
"akitas" to { it == 0 },
"vizslas" to { it == 0 },
"goldfish" to { it == 5 },
"trees" to { it == 3 },
"cars" to { it == 2 },
"perfumes" to { it == 1 },
)
)
}
.id
override fun partTwo(input: String) =
input
.lineSequence()
.map(this::parseInput)
.first { aunt ->
aunt.properties.consistentWith(
mapOf(
"children" to { it == 3 },
"cats" to { it > 7 },
"samoyeds" to { it == 2 },
"pomeranians" to { it < 3 },
"akitas" to { it == 0 },
"vizslas" to { it == 0 },
"goldfish" to { it < 5 },
"trees" to { it > 3 },
"cars" to { it == 2 },
"perfumes" to { it == 1 },
)
)
}
.id
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 2,723 | advent-of-code-kotlin-solutions | The Unlicense |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions51.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round0
import kotlin.math.*
/**
* 数组中的逆序对
*/
fun test51() {
val array = intArrayOf(7, 5, 6, 4)
println("数组中的逆序对共有:${inversePairs1(array)}对")
println("数组中的逆序对共有:${inversePairs2(array)}对")
}
//自顶向下的归并
fun inversePairs1(array: IntArray): Int {
if (array.isEmpty()) return 0
val substitute = IntArray(array.size)
val aux = IntArray(array.size)
for (i in array.indices) {
substitute[i] = array[i]
aux[i] = array[i]
}
return sort(substitute, aux, 0, array.size - 1)
}
private fun sort(a: IntArray, aux: IntArray, lo: Int, hi: Int): Int {
if (hi <= lo) return 0
val mid = lo + (hi - lo) / 2
val myCount = sort(a, aux, lo, mid) + sort(a, aux, mid + 1, hi)
return merge(a, aux, lo ,mid, hi, myCount)
}
//自底向上的归并
fun inversePairs2(array: IntArray): Int {
val substitute = IntArray(array.size)
val aux = IntArray(array.size)
for (i in array.indices) {
substitute[i] = array[i]
aux[i] = array[i]
}
var sz = 1
var count = 0
while (sz < array.size) {
var lo = 0
while (lo < array.size - sz) {
count = merge(substitute, aux, lo, lo + sz - 1, min(lo + (sz shl 1) - 1, array.size - 1), count)
lo += sz shl 1
}
sz += sz
}
return count
}
private fun merge(a: IntArray, aux: IntArray, lo: Int, mid: Int, hi: Int, count: Int): Int {
var i = lo
var j = mid + 1
var myCount = count
for (k in lo..hi)
aux[k] = a[k]
for (k in lo..hi)
when {
i > mid -> a[k] = aux[j++]
j > hi ->a[k] = aux[i++]
aux[j] < aux[i] -> {
a[k] = aux[j++]
myCount += mid + 1 - i
}
else -> a[k] = aux[i++]
}
return myCount
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,677 | Algorithm | Apache License 2.0 |
app/src/main/kotlin/day13/Day13.kt | W3D3 | 433,748,408 | false | {"Kotlin": 72893} | package day13
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 13
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay13Part1, ::solveDay13Part2)
}
data class Coord(val x: Int, val y: Int)
data class Fold(val axis: Char, val value: Int)
data class Input(val dots: Set<Coord>, val folds: List<Fold>)
private fun parseInput(input: List<String>): Input {
val coordRegex = """(\d+),(\d+)""".toRegex()
val foldRegex = """fold along (\w)=(\d+)""".toRegex()
val (coordinatesRaw, foldsRaw) = input.partition { (it != "\n") and it.contains(",") }
val dots = coordinatesRaw.filter { it.isNotEmpty() }.map {
val (x, y) = coordRegex.find(it)!!.destructured
Coord(x.toInt(), y.toInt())
}.toSet()
val folds = foldsRaw.filter { it.isNotEmpty() }.map {
println(it)
val (axis, value) = foldRegex.find(it)!!.destructured
Fold(axis.toCharArray().first(), value.toInt())
}
return Input(dots, folds)
}
private fun foldDot(location: Coord, fold: Fold): Coord {
when (fold.axis) {
'x' -> {
if (location.x < fold.value) return location
return Coord(fold.value - (location.x - fold.value), location.y)
}
'y' -> {
if (location.y < fold.value) return location
return Coord(location.x, fold.value - (location.y - fold.value))
}
else -> throw UnsupportedOperationException("Does not support folding on axis ${fold.axis}")
}
}
private fun printDots(dots: Set<Coord>) {
val maxX = dots.maxOf { it.x }
val maxY = dots.maxOf { it.y }
for (y in 0..maxY) {
for (x in 0..maxX) {
if (dots.contains(Coord(x, y))) print("#") else print(" ")
}
println()
}
}
fun solveDay13Part1(input: List<String>): Int {
val puzzle = parseInput(input)
var dots = puzzle.dots
for (fold in puzzle.folds) {
dots = dots.map { foldDot(it, fold) }.toSet()
}
printDots(dots)
return dots.size
}
fun solveDay13Part2(input: List<String>): Int {
val puzzle = parseInput(input)
val firstFold = puzzle.folds.first()
val dots = puzzle.dots.map { foldDot(it, firstFold) }.toSet()
return dots.size
} | 0 | Kotlin | 0 | 0 | df4f21cd99838150e703bcd0ffa4f8b5532c7b8c | 2,334 | AdventOfCode2021 | Apache License 2.0 |
src/main/aoc2020/Day21.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2020
class Day21(input: List<String>) {
private val products = input.map { line ->
val ingredients = line.substringBefore(" (contains ").split(" ")
val allergens = line.substringAfter("(contains ").dropLast(1).split(", ")
ingredients to allergens
}
private fun examineIngredients(): Map<String, Set<String>> {
val ingredientCanBe = products.flatMap { it.first }.toSet().associateWith { mutableSetOf<String>() }
products.forEach { product ->
val allOther = products - product
val possibleAllergens = product.second
product.first.forEach { ingredient ->
for (allergen in possibleAllergens) {
val productsWithSameAllergens = allOther.filter { it.second.contains(allergen) }
if (productsWithSameAllergens.all { otherProduct -> ingredient in otherProduct.first }) {
// if this ingredient contains this allergen it must be listed in
// all products that lists the allergen
ingredientCanBe[ingredient]!!.add(allergen)
}
}
}
}
return ingredientCanBe
}
fun solvePart1(): Int {
val safe = examineIngredients().filterValues { it.isEmpty() }.keys
return products.flatMap { it.first }.count { it in safe }
}
fun solve(dangerous: Map<String, Set<String>>): MutableMap<String, String> {
val left: MutableMap<String, MutableSet<String>> = dangerous.map { it.key to it.value.toMutableSet() }.toMap().toMutableMap()
val known = mutableMapOf<String, String>()
while (left.isNotEmpty()) {
val current = left.minByOrNull { it.value.size }!!
val ingredient = current.key
val allergen = current.value.single()
known[ingredient] = allergen
left.remove(ingredient)
left.forEach { (_, value) -> value.remove(allergen) }
}
return known
}
fun solvePart2(): String {
val dangerousIngredients = examineIngredients().filterValues { it.isNotEmpty() }
val solved = solve(dangerousIngredients)
return solved.toList().sortedBy { it.second }.joinToString(",") { it.first }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,317 | aoc | MIT License |
src/Day20.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
fun normalise(size: Int, num: Long): Int {
var number = num
if (number >= size) {
number %= size
}
while (number < 0) {
number += size
}
return number.toInt()
}
fun calculateValues(numbers: List<Pair<Int, Long>>, zeroIdx: Int, position: Int): Long {
return numbers[(zeroIdx + position) % numbers.size].second
}
fun decrypt(numbers: MutableList<Pair<Int, Long>>): Long {
for (i in numbers.indices) {
val idx = numbers.indexOfFirst { it.first == i }
val num = numbers.removeAt(idx)
val putAt = normalise(numbers.size, idx + num.second)
if (putAt == 0) {
numbers.add(num)
} else {
numbers.add(putAt, num)
}
}
val zeroIdx = numbers.indexOfFirst { it.second == 0L }
val a = calculateValues(numbers, zeroIdx, 1000)
val b = calculateValues(numbers, zeroIdx, 2000)
val c = calculateValues(numbers, zeroIdx, 3000)
return a + b + c
}
fun calculateValues2(
original: List<Pair<Int, Long>>,
mix: Long,
numbers: List<Pair<Int, Long>>,
zeroIdx: Int,
position: Int
): Long {
return original[numbers[(zeroIdx + position) % numbers.size].first].second
}
fun decrypt2(original: List<Pair<Int, Long>>, mix: Long): Long {
val numbers = original.map { it.first to it.second * mix % (original.size - 1) }.toMutableList()
repeat(10) {
for (i in numbers.indices) {
val idx = numbers.indexOfFirst { it.first == i }
val num = numbers.removeAt(idx)
val putAt = normalise(numbers.size, idx + num.second)
if (putAt == 0) {
numbers.add(num)
} else {
numbers.add(putAt, num)
}
}
}
val zeroIdx = numbers.indexOfFirst { it.second == 0L }
val a = calculateValues2(original, mix, numbers, zeroIdx, 1000)
val b = calculateValues2(original, mix, numbers, zeroIdx, 2000)
val c = calculateValues2(original, mix, numbers, zeroIdx, 3000)
return (a + b + c) * mix
}
fun part1(input: List<String>): Long {
val numbers = input.mapIndexed { index, s -> index to s.toLong() }
return decrypt(numbers.toMutableList())
}
fun part2(input: List<String>): Long {
val numbers = input.mapIndexed { index, s -> index to s.toLong() }
return decrypt2(numbers.toMutableList(), 811589153)
}
val testInput = readInput("Day20_test")
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 2,867 | advent-of-code-2022 | Apache License 2.0 |
src/d08/Main.kt | cweckerl | 572,838,803 | false | {"Kotlin": 12921} | package d08
import java.io.File
fun main() {
fun part1(input: List<String>) {
var trees = 0
val visited = mutableMapOf<Int, Char>()
for (i in input.indices) {
for (j in input[0].indices) {
if (i == 0 || i == input.size - 1 || j == 0 || j == input[0].length - 1) {
if (i == 0) visited[j] = input[i][j]
trees++
} else {
val tree = input[i][j]
val left = input[i].substring(0, j)
val right = input[i].substring(j + 1)
if (tree > visited[j]!!) {
trees++
visited[j] = tree
} else if (tree > left.max() || tree > right.max() || tree > input.drop(i + 1).maxOf { it[j] }) {
trees++
}
}
}
}
println(trees)
}
fun part2(input: List<String>) {
var score = 0
for (i in input.indices) {
for (j in input[0].indices) {
if (!(i == 0 || i == input.size - 1 || j == 0 || j == input[0].length - 1)) {
val tree = input[i][j]
val left = input[i].substring(0, j).reversed().toList()
val right = input[i].substring(j + 1).toList()
val up = input.subList(0, i).reversed().map { it[j] }
val down = input.drop(i + 1).map { it[j] }
val paths = arrayOf(up, down, left, right)
val tmp = paths.map {
var count = 0
for (t in it) {
count++
if (tree <= t) break
}
count
}.reduce(Int::times)
if (tmp > score) score = tmp
}
}
}
println(score)
}
val input = File("src/d08/input").readLines()
part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | 612badffbc42c3b4524f5d539c5cbbfe5abc15d3 | 2,087 | aoc | Apache License 2.0 |
src/Day10.kt | f1qwase | 572,888,869 | false | {"Kotlin": 33268} | import kotlin.math.abs
private sealed interface Command {
object Noop : Command
class Add(val value: Int) : Command
}
private fun parseCommand(input: String): Command = when (input.substringBefore(' ')) {
"noop" -> Command.Noop
"addx" -> Command.Add(input.substringAfter(' ').toInt())
else -> throw IllegalArgumentException("Unknown command: $input")
}
fun getCpuRegisterValues(input: List<String>) = input
.map(::parseCommand)
.flatMap {
when (it) {
Command.Noop -> listOf(it)
is Command.Add -> {
listOf(Command.Noop, it)
}
}
}
.runningFold(1) { value, command ->
when (command) {
Command.Noop -> value
is Command.Add -> value + command.value
}
}
fun main() {
fun part1(input: List<String>): Int = getCpuRegisterValues(input)
.foldIndexed(0) { index, strengthSum, registerValue ->
val cycle = index + 1 // cast to 1-based cycle
if (cycle % 40 == 20) {
strengthSum + cycle * registerValue
} else {
strengthSum
}
}
fun part2(input: List<String>): String {
return getCpuRegisterValues(input)
.mapIndexed { cycle, spritePosition ->
if (abs(cycle % 40 - spritePosition) <= 1) {
'#'
} else {
'.'
}
}
.chunked(40)
.joinToString("\n") { it.joinToString("") }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
part1(testInput).let { check(it == 13140) { it } }
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3fc7b74df8b6595d7cd48915c717905c4d124729 | 1,826 | aoc-2022 | Apache License 2.0 |
src/Day08.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} | fun main() {
fun part1(input: List<String>): Int {
val trees = input.map { it.map { it.digitToInt() }.toIntArray() }.toTypedArray()
val visible = Array(input.size) {BooleanArray(input.size)}
for(i in 0 until input.size) {
var max = -1
for (j in 0 .. input.size - 1) {
if (trees[i][j] > max) {
max = trees[i][j]
visible[i][j] = true
}
}
max = -1
for(j in input.size - 1 downTo 0) {
if (trees[i][j] > max) {
max = trees[i][j]
visible[i][j] = true
}
}
}
for(j in 0 until input.size) {
var max = -1
for (i in 0 .. input.size - 1) {
if (trees[i][j] > max) {
max = trees[i][j]
visible[i][j] = true
}
}
max = -1
for(i in input.size - 1 downTo 0) {
if (trees[i][j] > max) {
max = trees[i][j]
visible[i][j] = true
}
}
}
var counter = 0
for(i in 0 .. visible.size - 1) {
for(j in 0 .. visible[i].size - 1) {
if (visible[i][j]) {
counter++
}
}
}
return counter
}
fun part2(input: List<String>): Int {
val trees = input.map { it.map { it.digitToInt() }.toIntArray() }.toTypedArray()
fun analyze(i0 : Int, j0 : Int) : Int {
var scenic = 1
var counter = 1
for(j in j0 + 1 .. trees[i0].size - 2) {
if (trees[i0][j0] <= trees[i0][j]) {
break;
}
counter++
}
scenic *= counter
counter = 1
for(j in j0 - 1 downTo 1) {
if (trees[i0][j0] <= trees[i0][j]) {
break;
}
counter++
}
scenic *= counter
counter = 1
for(i in i0 + 1 .. trees.size - 2) {
if (trees[i0][j0] <= trees[i][j0]) {
break;
}
counter++
}
scenic *= counter
counter = 1
for(i in i0 - 1 downTo 1) {
if (trees[i0][j0] <= trees[i][j0]) {
break;
}
counter++
}
scenic *= counter
return scenic;
}
var max = 0
for(i in 1 .. trees.size - 2) {
for(j in 1 .. trees[i].size - 2) {
val scenic = analyze(i, j)
if (scenic > max) {
max = scenic
}
}
}
return max
}
// test if implementation meets criteria from the description, like:
val testInputExample = readInput("Day08_example")
check(part1(testInputExample) == 21)
check(part2(testInputExample) == 8)
val testInput = readInput("Day08_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 3,265 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day13.kt | ivancordonm | 572,816,777 | false | {"Kotlin": 36235} | import java.util.*
fun main() {
fun String.parse(): Item.Values {
val stack = Stack<Item.Values>()
var s = this
val root = Item.Values(mutableListOf())
var current = root
var num = ""
while (s.isNotEmpty()) {
when (s.first()) {
'[' -> {
val inner = Item.Values(mutableListOf())
current.values.add(inner)
stack.push(current)
current = inner
}
']' -> {
if (num.isNotEmpty()) {
current.values.add(Item.Value(num.toInt()))
num = ""
}
current = stack.pop()
}
',' -> {
if (num.isNotEmpty()) {
current.values.add(Item.Value(num.toInt()))
num = ""
}
}
else -> {
num += s.first()
}
}
s = s.drop(1)
}
return root
}
fun part1(input: List<String>) = input
.chunked(3)
.mapIndexed { index, lines -> Pair(index + 1, lines[0].parse() < lines[1].parse()) }
.filter { it.second }
.sumOf { it.first }
fun part2(input: List<String>): Int {
val sortedList =input.filter { it.isNotEmpty() }.map { it.parse() }.sorted().toMutableList()
val positions = mutableListOf<Int>()
for (elem in listOf("[[2]]".parse(), "[[6]]".parse())) {
for((idx, l) in sortedList.withIndex())
if(elem < l) {
positions.add(idx+1)
sortedList.add(idx+1, elem)
break
}
}
return positions.reduce { acc, i -> acc * i}
}
val testInput = readInput("Day13_test")
val input = readInput("Day13")
check(part1(testInput) == 13)
println(part1(testInput))
println(part1(input))
println(part2(testInput))
check(part2(testInput) == 140)
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | dc9522fd509cb582d46d2d1021e9f0f291b2e6ce | 2,167 | AoC-2022 | Apache License 2.0 |
src/main/aoc2018/Day24.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
import kotlin.math.min
class Day24(input: List<String>) {
data class Group(val team: String, val id: Int, val units: Int, val hp: Int, val attack: Int, val attackType: String, val initiative: Int,
val weaknesses: Set<String>, val immunities: Set<String>) {
var liveUnits = units
var boost = 0
val isAlive: Boolean
get() = liveUnits > 0
val effectivePower: Int
get() = liveUnits * (attack + if (team == "Immune System") boost else 0)
fun damageToTake(damage: Int, type: String) = when {
immunities.contains(type) -> 0
weaknesses.contains(type) -> 2 * damage
else -> damage
}
fun takeDamage(damage: Int, type: String): Int {
val killedUnits = min(liveUnits, damageToTake(damage, type) / hp)
liveUnits -= killedUnits
return killedUnits
}
}
private val groups = parseInput(input)
private fun parseInput(input: List<String>): List<Group> {
var i = 0
var id = 1
val groups = mutableListOf<Group>()
while (i < input.size) {
val team = input[i++].dropLast(1)
while (i < input.size && input[i].isNotEmpty()) {
groups.add(parseGroup(team, id++, input[i++]))
}
i++ // skip blank line between the two teams
id = 1
}
return groups
}
// 18 units each with 729 hit points (weak to fire; immune to cold, slashing)
// with an attack that does 8 radiation damage at initiative 10
fun parseGroup(team: String, id: Int, rawGroup: String): Group {
val parts = rawGroup.split(" ")
val units = parts.first().toInt()
val hp = parts[4].toInt()
val attackPart = rawGroup.substringAfter("attack that does ").split(" ")
val attack = attackPart.first().toInt()
val attackType = attackPart[1]
val initiative = attackPart.last().toInt()
val immunities = mutableSetOf<String>()
val weaknesses = mutableSetOf<String>()
val statusPart = rawGroup.substringAfter("(", "").substringBefore(")")
if (statusPart.isNotEmpty()) {
statusPart.split("; ").forEach {
when {
it.startsWith("weak to") -> {
it.substringAfter("weak to ").split(", ").forEach { weak -> weaknesses.add(weak) }
}
it.startsWith("immune to") -> {
it.substringAfter("immune to ").split(", ").forEach { weak -> immunities.add(weak) }
}
}
}
}
return Group(team, id, units, hp, attack, attackType, initiative, weaknesses, immunities)
}
private fun selectTargets(): Map<Group, Group> {
val selectedTargets = mutableMapOf<Group, Group>()
val toSelect = groups.filter { it.isAlive }
.sortedWith(compareBy({ -it.effectivePower }, { -it.initiative })).toMutableList()
val availableTargets = groups.filter { it.isAlive }.toMutableList()
while (toSelect.isNotEmpty()) {
val attacker = toSelect.removeAt(0)
val target = availableTargets.asSequence()
.filter { attacker.team != it.team }
.filter { it.damageToTake(attacker.effectivePower, attacker.attackType) > 0 }
.sortedWith(compareBy(
{ -it.damageToTake(attacker.effectivePower, attacker.attackType) },
{ -it.effectivePower },
{ -it.initiative }
))
.firstOrNull()
if (target != null) {
selectedTargets[attacker] = target
availableTargets.remove(target)
}
}
return selectedTargets
}
private fun attackTargets(targets: Map<Group, Group>): Int {
val toAttack = groups.filter { it.isAlive }.sortedBy { -it.initiative }.toMutableList()
var totalKills = 0
while (toAttack.isNotEmpty()) {
val attacker = toAttack.removeAt(0)
if (attacker.isAlive && targets.containsKey(attacker)) {
totalKills += targets.getValue(attacker).takeDamage(attacker.effectivePower, attacker.attackType)
}
}
return totalKills
}
@Suppress("unused")
private fun printTeamInfo() {
println("Immune System:")
groups.filter { it.team == "Immune System" && it.isAlive }.sortedWith(compareBy { it.id }).forEach {
println("Group ${it.id} contains ${it.liveUnits} units")
}
println("Infection:")
groups.filter { it.team == "Infection" && it.isAlive }.sortedWith(compareBy { it.id }).forEach {
println("Group ${it.id} contains ${it.liveUnits} units")
}
println()
}
private fun fight() {
while (groups.groupBy { it.team }.values.all { teamGroups -> teamGroups.any { it.isAlive } }) {
// While all (both) teams have any group that is still alive, continue fighting
val targets = selectTargets()
val killed = attackTargets(targets)
if (killed == 0) {
// None of the teams manages to kill anyone so abort and call it a draw.
return
}
}
}
private fun reset(boost: Int) {
groups.forEach {
it.liveUnits = it.units
it.boost = boost
}
}
private fun fightWithBoost(boost: Int): Boolean {
reset(boost)
fight()
return groups.filter { it.isAlive }.all { it.team == "Immune System" }
}
fun solvePart1(): Int {
fight()
return groups.filter { it.isAlive }.sumOf { it.liveUnits }
}
fun solvePart2(): Int {
// Fight with increasing boost until immune system wins.
generateSequence(1) { it + 1 }.map { fightWithBoost(it) }.first { it }
return groups.filter { it.isAlive }.sumOf { it.liveUnits }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 6,148 | aoc | MIT License |
src/main/kotlin/aoc2023/Day14.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2023
import print
import readInput
import to2dCharArray
import kotlin.math.max
private enum class Direction { NORTH, SOUTH, EAST, WEST }
private class MirrorMap(private val input: List<String>) {
private var currentMap = input.to2dCharArray()
private val maxY = input.size
private val maxX = currentMap.size
val northLoad: Int
get() {
var northLoad = 0
currentMap.withIndex().forEach { (x, column) ->
column.withIndex().forEach { (y, char) ->
if (char == 'O') northLoad += maxY - y
}
}
return northLoad
}
private fun findCycle(): Pair<Int, Int>? {
var str = currentMap.map { it.toList() }
val cache = mutableMapOf(str to 0)
// north, then west, then south, then east
repeat(Int.MAX_VALUE) { round ->
tilt(Direction.NORTH)
tilt(Direction.WEST)
tilt(Direction.SOUTH)
tilt(Direction.EAST)
str = currentMap.map { it.toList() }
if (cache.contains(str)) {
return cache[str]!! to round
} else {
cache[str] = round
}
}
return null
}
fun cycle(times: Int) {
val initial = input.to2dCharArray()
val cycle = findCycle() ?: throw IllegalArgumentException("No cycle found")
val cycleLength = cycle.second - cycle.first
val remaining = times - cycle.second
val remainingAfterCycling = remaining % cycleLength
currentMap = initial
// walk into the cycle, then at least once + remaining steps until 'times'
repeat(cycle.first + cycleLength + remainingAfterCycling) {
tilt(Direction.NORTH)
tilt(Direction.WEST)
tilt(Direction.SOUTH)
tilt(Direction.EAST)
}
}
fun tilt(direction: Direction) {
val tiltedMap = Array(currentMap.size) { CharArray(currentMap.first().size) { '.' } }
currentMap.withIndex().forEach { (x, column) ->
column.withIndex().forEach { (y, char) ->
if (char == '#') tiltedMap[x][y] = char
}
}
val deltaY = when (direction) {
Direction.NORTH -> -1
Direction.SOUTH -> 1
else -> 0
}
val deltaX = when (direction) {
Direction.EAST -> 1
Direction.WEST -> -1
else -> 0
}
currentMap.withIndex().forEach { (x, column) ->
column.withIndex().forEach { (y, char) ->
if (char == 'O') {
var currentY = y
var currentX = x
while (currentY + deltaY in 0..<maxY && currentX + deltaX in 0..<maxX
&& tiltedMap[currentX + deltaX][currentY + deltaY] == '.'
) {
currentY += deltaY
currentX += deltaX
}
// position already taken -> move backward again
while (tiltedMap[currentX][currentY] == char) {
currentY -= deltaY
currentX -= deltaX
}
tiltedMap[currentX][currentY] = char
}
}
}
currentMap = tiltedMap
}
}
object Day14 {
fun part1(input: List<String>): Int {
val map = MirrorMap(input)
map.tilt(Direction.NORTH)
return map.northLoad
}
fun part2(input: List<String>): Int {
val map = MirrorMap(input)
map.cycle(1_000_000_000)
return map.northLoad
}
}
fun main() {
val testInput = readInput("Day14_test", 2023)
check(Day14.part1(testInput) == 136)
check(Day14.part2(testInput) == 64)
val input = readInput("Day14", 2023)
println(Day14.part1(input))
println(Day14.part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,974 | adventOfCode | Apache License 2.0 |
Advent-of-Code-2023/src/Day14.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day14"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
/**
* Calculates the load caused by the rounded rocks in the platform.
* The load is calculated by multiplying the number of rounded rocks in a column by the distance from the bottom.
* Since we want to know the total load on the north beam, by transposing the platform we only need to move the
* rounded rocks to the left.
* First, we split the platform by the cube-shaped rocks, then we sort the rounded rocks in each column and join them
* back together. This way the cube-shaped rocks won't interfere with the sorting. In the end, we transpose the
* platform back to its original state.
*/
private fun part1(input: List<String>): Int {
val tiltedPlatform = input
.transpose()
.map { row -> row.split("#") }
.map { row ->
row.joinToString("#") { str ->
str.toCharArray().sortedDescending().joinToString("")
}
}.transpose()
.foldIndexed(0) { index, sum, row ->
sum + row.count { it == 'O' } * (input.size - index)
}
return tiltedPlatform
}
/**
* Calculates the cycle, and moves the rocks to their positions.
* A cycle is composed by four 90 degree rotations.
*/
private fun cycle(platform: List<String>): List<String> {
var newPlatform = platform
repeat(4) {
newPlatform = newPlatform
.transpose()
.map { row -> row.split("#") }
.map { row ->
row.joinToString("#") { str ->
str.toCharArray().sortedDescending().joinToString("")
}
}.map { row -> row.reversed() }
}
return newPlatform
}
/**
* Finds the final platform after 1 billion rotations. Since the platform is cyclic, we can find the final platform
* by finding the offset of the first cycle and then finding the offset of the final platform in the cycle.
*/
private fun part2(input: List<String>): Int {
var lastPlatform = input
val seenPlatforms = mutableSetOf<List<String>>()
val orderedCycles = mutableListOf<List<String>>()
while (true) {
lastPlatform = cycle(lastPlatform)
if (lastPlatform in seenPlatforms) {
break
}
seenPlatforms.add(lastPlatform)
orderedCycles.add(lastPlatform)
}
val firstCycleIdx = orderedCycles.indexOf(lastPlatform)
// (number of cycles left) % (offset of a cycle) = initial platform + (offset of a cycle) = idx of the final plat
val finalPlatform = orderedCycles[(1_000_000_000 - firstCycleIdx) % (orderedCycles.size - firstCycleIdx) + firstCycleIdx - 1]
return finalPlatform.foldIndexed(0) { index, sum, row ->
sum + row.count { it == 'O' } * (input.size - index)
}
}
fun main() {
createTestFiles(AOC_DAY)
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 136
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 64
println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 108889" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 104671" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 3,435 | Advent-of-Code-2023 | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/MinimumWindowSubstring.kt | faniabdullah | 382,893,751 | false | null | //Given two strings s and t of lengths m and n respectively, return the minimum
//window substring of s such that every character in t (including duplicates) is
//included in the window. If there is no such substring, return the empty string
//"".
//
// The testcases will be generated such that the answer is unique.
//
// A substring is a contiguous sequence of characters within the string.
//
//
// Example 1:
//
//
//Input: s = "ADOBECODEBANC", t = "ABC"
//Output: "BANC"
//Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C'
//from string t.
//
//
// Example 2:
//
//
//Input: s = "a", t = "a"
//Output: "a"
//Explanation: The entire string s is the minimum window.
//
//
// Example 3:
//
//
//Input: s = "a", t = "aa"
//Output: ""
//Explanation: Both 'a's from t must be included in the window.
//Since the largest window of s only has one 'a', return empty string.
//
//
//
// Constraints:
//
//
// m == s.length
// n == t.length
// 1 <= m, n <= 10⁵
// s and t consist of uppercase and lowercase English letters.
//
//
//
//Follow up: Could you find an algorithm that runs in O(m + n) time? Related
//Topics Hash Table String Sliding Window 👍 8292 👎 493
package leetcodeProblem.leetcode.editor.en
class MinimumWindowSubstring {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun minWindow(s: String, t: String): String {
if (s.isEmpty() || t.isEmpty()) {
return ""
}
val dictT: MutableMap<Char, Int> = HashMap()
for (i in t.indices) {
val count = dictT.getOrDefault(t[i], 0)
dictT[t[i]] = count + 1
}
val required = dictT.size
var l = 0
var r = 0
var formed = 0
val windowCounts: MutableMap<Char, Int> = HashMap()
val ans = intArrayOf(-1, 0, 0)
while (r < s.length) {
var c = s[r]
val count = windowCounts.getOrDefault(c, 0)
windowCounts[c] = count + 1
if (dictT.containsKey(c) && windowCounts[c]!!.toInt() == dictT[c]!!.toInt()) {
formed++
}
while (l <= r && formed == required) {
c = s[l]
if (ans[0] == -1 || r - l + 1 < ans[0]) {
ans[0] = r - l + 1
ans[1] = l
ans[2] = r
}
windowCounts[c] = windowCounts[c]!! - 1
if (dictT.containsKey(c) && windowCounts[c]!!.toInt() < dictT[c]!!.toInt()) {
formed--
}
l++
}
r++
}
return if (ans[0] == -1) "" else s.substring(ans[1], ans[2] + 1)
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {
println(MinimumWindowSubstring.Solution().minWindow("acbbaca", "aba"))
}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 3,213 | dsa-kotlin | MIT License |
src/year2023/day12/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2023.day12
import arrow.core.nonEmptyListOf
import utils.ProblemPart
import utils.findAllWithOverlap
import utils.readInputs
import utils.runAlgorithm
import utils.withMemoization
fun main() {
val (realInput, testInputs) = readInputs(2023, 12, transform = ::parse)
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(21),
algorithm = ::part1,
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(525152),
algorithm = ::part2,
),
)
}
private fun parse(input: List<String>): List<Input> = input.map { line ->
val (record, groups) = line.split(' ')
Input(
record = record,
groups = groups.splitToSequence(',').map { it.toInt() }.toList()
)
}
private fun part1(input: List<Input>): Long = input.sumOf(possibilityCounter::invoke)
private val possibilityCounter: DeepRecursiveFunction<Input, Long> = withMemoization { currentState ->
val firstGroupSize = currentState.groups.firstOrNull()
when {
firstGroupSize == null -> if (currentState.record.any { it == '#' }) 0 else 1
currentState.unknownIndexes.isEmpty() -> if (currentState.missingDamaged == 0) {
currentState.groups
.joinToString(separator = "\\.+", prefix = "\\.*", postfix = "\\.*") { "#{$it}" }
.toRegex()
.matches(currentState.record)
.let { if (it) 1 else 0 }
} else 0
else -> "[?#]{$firstGroupSize}(?!#)".toRegex()
.findAllWithOverlap(currentState.record)
.filterNot {
!currentState.record.matches("[^#]{${it.range.first}}.*".toRegex())
}
.map { matchResult ->
val nextChar = currentState.record.getOrNull(matchResult.range.last + 1)
Input(
currentState.record.drop(matchResult.range.last + 1).let {
if (nextChar == null) it else it.drop(1)
},
currentState.groups.drop(1),
)
}
.sumOf { callRecursive(it) }
}
}
private fun part2(input: List<Input>): Long {
return input.asSequence()
.map { currentInput ->
Input(
generateSequence { currentInput.record }
.take(5)
.joinToString(separator = "?"),
buildList {
repeat(5) { addAll(currentInput.groups) }
}
)
}
.sumOf(possibilityCounter::invoke)
}
private data class Input(
val record: String,
val groups: List<Int>,
) {
val unknownIndexes = record.asSequence().withIndex()
.mapNotNull { (index, char) -> if (char == '?') index else null }
.toSet()
val missingDamaged = groups.sum() - record.count { it == '#' }
}
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 2,989 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/d19_BeaconScanner/BeaconScanner.kt | aormsby | 425,644,961 | false | {"Kotlin": 68415} | package d19_BeaconScanner
import util.Coord3d
import util.Input
import util.Output
fun main() {
val startTime = Output.startTime()
Output.day(19, "Beacon Scanner")
val scannerList = Input.parseLines(filename = "/input/d19_scanner_beacon_map.txt")
.toScannerList()
scannerList[0].hasShifted = true
val shiftedScanners = scannerList.take(1).toMutableList()
val unshiftedScanners = scannerList.drop(1).toMutableList()
while (unshiftedScanners.isNotEmpty()) {
unshiftedScanners.forEach shifted@{ s ->
shiftedScanners.forEach { s2 ->
if (s != s2) {
s.findOverlapsWith(s2)
if (s.hasShifted) return@shifted
}
}
}
val newShifts = unshiftedScanners.filter { it.hasShifted }
shiftedScanners.addAll(newShifts)
newShifts.forEach { unshiftedScanners.remove(it) }
}
Output.part(1, "Unique Beacons", scannerList.flatMap { it.allBeacons }.toSet().size)
Output.part(2, "Largest Scanner Distance", getLargestScannerDistance(scannerList))
Output.executionTime(startTime)
}
fun getLargestScannerDistance(scanners: List<Scanner>): Int {
val distMap = mutableMapOf<String, Int>()
scanners.forEachIndexed { i, s1 ->
scanners.forEachIndexed { j, s2 ->
val k = listOf(i, j).sorted().joinToString("_")
if (i != j && k !in distMap) distMap[k] = s1.position.manhattanDistanceTo(s2.position)
}
}
return distMap.maxOf { it.value }
}
fun List<String>.toScannerList(): List<Scanner> {
val scanners = mutableListOf<Scanner>()
var curScanner = Scanner(0)
forEach { line ->
when {
line.startsWith("---") -> {
curScanner = Scanner(which = line.substringAfter("r ").substringBefore(" -").toInt())
scanners.add(curScanner)
}
line.isNotBlank() -> {
with(line.split(',').map { it.toInt() }) {
curScanner.allBeacons.add(Coord3d(this[0], this[1], this[2]))
}
}
line.isBlank() -> curScanner.calculateBeaconDistances()
}
if (line == this.last()) curScanner.calculateBeaconDistances()
}
return scanners
}
data class Scanner(
var which: Int,
) {
var position: Coord3d = Coord3d(0, 0, 0)
var allBeacons: MutableList<Coord3d> = mutableListOf()
var orientation: Coord3d = Coord3d(0, 0, 0)
var hasShifted: Boolean = false
val beaconDistances: MutableMap<String, Float> = mutableMapOf()
fun calculateBeaconDistances() {
allBeacons.forEachIndexed { i, c1 ->
allBeacons.forEachIndexed { j, c2 ->
val k = listOf(i, j).sorted().joinToString("_")
if (i != j && k !in beaconDistances) beaconDistances[k] = c1.distanceTo(c2)
}
}
}
fun findOverlapsWith(other: Scanner) {
val allMyMatches = beaconDistances.filterValues { it in other.beaconDistances.values }
val uniqueMatches = allMyMatches.keys.flatMap { k ->
k.split('_').map { s -> s.toInt() }
}.toSet()
if (uniqueMatches.size >= 12) {
val otherMatches = other.beaconDistances.filterValues { it in allMyMatches.values }
orientScanner(
allMyMatches.entries.sortedBy { it.value },
otherMatches.entries.sortedBy { it.value },
other
)
}
}
fun orientScanner(
myMatches: List<Map.Entry<String, Float>>,
otherMatches: List<Map.Entry<String, Float>>,
other: Scanner
) {
// region key setup
val myKeyIndexList = mutableListOf(myMatches.first())
myKeyIndexList.add(myMatches.first {
it.key.contains(myKeyIndexList.first().key.substringAfter('_')) &&
it.key.substringAfter('_').length == myKeyIndexList.first().key.substringAfter('_').length &&
it != myKeyIndexList[0]
})
val myFirstKeys = myKeyIndexList.map { it.key }
val otherKeyIndexList = mutableListOf(otherMatches.first())
otherKeyIndexList.add(otherMatches.first { it.value == myKeyIndexList.last().value })
val otherFirstKeys = otherKeyIndexList.map { it.key }
// endregion
// region coord setup
val myCoordPair = findMatchingCoord(myFirstKeys, allBeacons)
val myCoord = myCoordPair.second
val mySecondCoord = allBeacons[myFirstKeys.first()
.split('_').map { it.toInt() }.first { it != myCoordPair.first }]
val otherCoordPair = findMatchingCoord(otherFirstKeys, other.allBeacons)
val otherCoord = otherCoordPair.second
val otherSecondCoord = other.allBeacons[otherFirstKeys.first()
.split('_').map { it.toInt() }.first { it != otherCoordPair.first }]
// endregion
// region orient and match
val myDupe = Coord3d(myCoord.x, myCoord.y, myCoord.z)
val mySecondDupe = Coord3d(mySecondCoord.x, mySecondCoord.y, mySecondCoord.z)
position = otherCoord + myDupe.opposite()
while (position + mySecondDupe != otherSecondCoord && orientation.x < 4) {
listOf(myDupe, mySecondDupe).orientToNext()
position = otherCoord + myDupe.opposite()
}
// endregion
// position current scanner and beacons based on coord match
if (orientation.x < 4) {
allBeacons = allBeacons.map { it.reorient() + position }.toMutableList()
hasShifted = true
} else {
position = Coord3d(0, 0, 0)
orientation = Coord3d(0, 0, 0)
}
}
fun List<Coord3d>.orientToNext() {
var nextRot = Coord3d(orientation.x, orientation.y, orientation.z)
updateScannerOrientation()
nextRot = nextRot.diffWith(orientation)
if (nextRot.x == -3) nextRot.x = 1
if (nextRot.y == -3) nextRot.y = 1
if (nextRot.z == -3) nextRot.z = 1
forEach { it.rotate(nextRot) }
}
fun updateScannerOrientation() {
orientation.z += 1
if (orientation.z > 3) {
orientation.y += 1
orientation.z = 0
}
if (orientation.y > 3) {
orientation.x += 1
orientation.y = 0
}
}
fun Coord3d.reorient(): Coord3d {
val o = Coord3d(orientation.x, orientation.y, orientation.z)
while (o.x > 0) {
o.x--
this.rotate(Coord3d(1, 0, 0))
}
while (o.y > 0) {
o.y--
this.rotate(Coord3d(0, 1, 0))
}
while (o.z > 0) {
o.z--
this.rotate(Coord3d(0, 0, 1))
}
return this
}
fun Coord3d.rotate(rotation: Coord3d) {
if (rotation.z == 1) {
val temp = y
y = x
x = temp
y *= -1
}
if (rotation.y == 1) {
val temp = x
x = z
z = temp
x *= -1
}
if (rotation.x == 1) {
val temp = z
z = y
y = temp
z *= -1
}
}
fun findMatchingCoord(keys: List<String>, beaconList: List<Coord3d>): Pair<Int, Coord3d> {
val indices = keys.flatMap { it.split('_') }.map { it.toInt() }
val coords = indices.map { beaconList[it] }
return Pair(
indices.groupingBy { it }.eachCount().filter { it.value > 1 }.keys.first(),
coords.groupingBy { it }.eachCount().filter { it.value > 1 }.keys.first(),
)
}
} | 0 | Kotlin | 1 | 1 | 193d7b47085c3e84a1f24b11177206e82110bfad | 7,688 | advent-of-code-2021 | MIT License |
src/main/kotlin/EvaluateReversePolishNotation.kt | Codextor | 453,514,033 | false | {"Kotlin": 26975} | /**
* You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
*
* Evaluate the expression. Return an integer that represents the value of the expression.
*
* Note that:
*
* The valid operators are '+', '-', '*', and '/'.
* Each operand may be an integer or another expression.
* The division between two integers always truncates toward zero.
* There will not be any division by zero.
* The input represents a valid arithmetic expression in a reverse polish notation.
* The answer and all the intermediate calculations can be represented in a 32-bit integer.
*
*
* Example 1:
*
* Input: tokens = ["2","1","+","3","*"]
* Output: 9
* Explanation: ((2 + 1) * 3) = 9
* Example 2:
*
* Input: tokens = ["4","13","5","/","+"]
* Output: 6
* Explanation: (4 + (13 / 5)) = 6
* Example 3:
*
* Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
* Output: 22
* Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
* = ((10 * (6 / (12 * -11))) + 17) + 5
* = ((10 * (6 / -132)) + 17) + 5
* = ((10 * 0) + 17) + 5
* = (0 + 17) + 5
* = 17 + 5
* = 22
*
*
* Constraints:
*
* 1 <= tokens.length <= 104
* tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
* @see <a href="https://leetcode.com/problems/evaluate-reverse-polish-notation/">LeetCode</a>
*/
fun evalRPN(tokens: Array<String>): Int {
val listOfOperators = listOf("+", "-", "*", "/")
val stack = ArrayDeque<Int>()
tokens.forEach { token ->
if (token in listOfOperators) {
val operand2 = stack.removeLast()
val operand1 = stack.removeLast()
val result = operate(operand1, operand2, token)
stack.addLast(result)
} else {
stack.addLast(token.toInt())
}
}
return stack.last()
}
private fun operate(operand1: Int, operand2: Int, operator: String) = when (operator) {
"+" -> operand1 + operand2
"-" -> operand1 - operand2
"*" -> operand1 * operand2
"/" -> operand1 / operand2
else -> 0
}
| 0 | Kotlin | 1 | 0 | 68b75a7ef8338c805824dfc24d666ac204c5931f | 2,113 | kotlin-codes | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day08.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2022
import com.dvdmunckhof.aoc.toGrid
class Day08(input: List<List<Int>>) {
private val grid = input.map { row -> row.map(::Tree) }.toGrid()
fun solvePart1(): Int {
val visibleTrees = mutableSetOf<Tree>()
for (row in grid.rows) {
visibleTrees += visibleTreesPart1(row)
visibleTrees += visibleTreesPart1(row.asReversed())
}
for (col in grid.columns) {
visibleTrees += visibleTreesPart1(col)
visibleTrees += visibleTreesPart1(col.asReversed())
}
return visibleTrees.size
}
fun solvePart2(): Int {
return grid.points().maxOf { point ->
val height = grid[point].height
val row = grid.rows[point.r]
val col = grid.columns[point.c]
val directions = listOf(
row.subList(0, point.c).asReversed(),
row.subList(point.c + 1, row.size),
col.subList(0, point.r).asReversed(),
col.subList(point.r + 1, col.size),
)
if (directions.any(List<Tree>::isEmpty)) {
0
} else {
directions.fold(1) { scenicScore, trees ->
val distance = (trees.takeWhile { it.height < height }.count() + 1).coerceAtMost(trees.size)
scenicScore * distance
}
}
}
}
private fun visibleTreesPart1(trees: List<Tree>): List<Tree> {
val visibleTrees = mutableListOf(trees.first())
for (tree in trees) {
if (tree.height > visibleTrees.last().height) {
visibleTrees += tree
if (tree.height == 9) {
break
}
}
}
return visibleTrees
}
private class Tree(val height: Int)
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,881 | advent-of-code | Apache License 2.0 |
src/main/kotlin/SortCharactersByFrequency.kt | Codextor | 453,514,033 | false | {"Kotlin": 26975} | /**
* Given a string s, sort it in decreasing order based on the frequency of the characters.
* The frequency of a character is the number of times it appears in the string.
*
* Return the sorted string. If there are multiple answers, return any of them.
*
*
*
* Example 1:
*
* Input: s = "tree"
* Output: "eert"
* Explanation: 'e' appears twice while 'r' and 't' both appear once.
* So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
* Example 2:
*
* Input: s = "cccaaa"
* Output: "aaaccc"
* Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
* Note that "cacaca" is incorrect, as the same characters must be together.
* Example 3:
*
* Input: s = "Aabb"
* Output: "bbAa"
* Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
* Note that 'A' and 'a' are treated as two different characters.
*
*
* Constraints:
*
* 1 <= s.length <= 5 * 10^5
* s consists of uppercase and lowercase English letters and digits.
* @see <a href="https://leetcode.com/problems/sort-characters-by-frequency/">LeetCode</a>
*/
fun frequencySort(s: String): String {
val frequencyMap = mutableMapOf<Char, Int>()
s.forEach { char ->
frequencyMap[char] = 1 + frequencyMap.getOrDefault(char, 0)
}
val charsByFrequencyMap = mutableMapOf<Int, MutableList<Char>>()
frequencyMap.forEach { char, frequency ->
if (!charsByFrequencyMap.contains(frequency)) {
charsByFrequencyMap[frequency] = mutableListOf(char)
} else {
charsByFrequencyMap[frequency]?.add(char)
}
}
val result = StringBuilder()
for (frequency in s.length downTo 1) {
charsByFrequencyMap[frequency]?.forEach { char ->
repeat(frequency) {
result.append(char)
}
}
}
return result.toString()
}
| 0 | Kotlin | 1 | 0 | 68b75a7ef8338c805824dfc24d666ac204c5931f | 1,905 | kotlin-codes | Apache License 2.0 |
src/Day12.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | import java.util.*
fun main() {
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>, ): Int = solve(input, startMarkers = setOf('S'))
private fun part2(input: List<String>, ): Int = solve(input, startMarkers = setOf('S', 'a'))
private fun solve(input: List<String>, startMarkers: Set<Char>): Int {
val area = input.toMatrix()
val starts = input.findAllChars(startMarkers)
val end = input.findChar('E')
val visited = mutableSetOf<IJ>()
val queue = PriorityQueue<Item>()
starts.forEach {
queue.offer(Item(0, it))
}
while (queue.isNotEmpty()) {
val (steps, ij) = queue.poll()
if (ij in visited) {
continue
}
if (ij == end) {
return steps
}
val (i, j) = ij
if (i > 0 && (area[i - 1][j] - area[i][j]) <= 1) {
queue.offer(Item(steps + 1, IJ(i - 1, j)))
}
if (j > 0 && (area[i][j - 1] - area[i][j]) <= 1) {
queue.offer(Item(steps + 1, IJ(i, j - 1)))
}
if (i < area.lastIndex && (area[i + 1][j] - area[i][j]) <= 1) {
queue.offer(Item(steps + 1, IJ(i + 1, j)))
}
if (j < area[i].lastIndex && (area[i][j + 1] - area[i][j]) <= 1) {
queue.offer(Item(steps + 1, IJ(i, j + 1)))
}
visited.add(ij)
}
error("Path not found")
}
private fun List<String>.toMatrix(): Matrix {
return Array(this.size) { i ->
IntArray(this[i].length) { j ->
when (this[i][j]) {
'S' -> 0
'E' -> 'z'.code - 'a'.code
else -> this[i][j].code - 'a'.code
}
}
}
}
private fun List<String>.findChar(target: Char): IJ {
this.forEachIndexed { i, row ->
row.forEachIndexed { j, ch ->
if (ch == target) {
return IJ(i, j)
}
}
}
error("$target not found")
}
private fun List<String>.findAllChars(targets: Set<Char>): List<IJ> {
val result = mutableListOf<IJ>()
this.forEachIndexed { i, row ->
row.forEachIndexed { j, ch ->
if (ch in targets) {
result.add(IJ(i, j))
}
}
}
return result
} | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 2,415 | AOC2022 | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year22/Day16.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year22
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.splitInts
import kotlin.math.max
fun PuzzleSet.day16() = puzzle {
val valves = inputLines.map { l ->
val conns = l.substringAfter("valves ").substringAfter("valve ").split(", ")
Valve(l.split(" ")[1], l.splitInts().single(), conns)
}.sortedByDescending { it.rate }
val initial = valves.indexOfFirst { it.name == "AA" }
val connections = valves.map { v -> valves.filter { it.name in v.connections }.map(valves::indexOf) }
val rates = valves.map { it.rate }
// 134217728 = 2^27
val seen = MutableList(134217728) { -1 }
require(valves.size <= 60) { "Input input (too many valves)" }
require(valves.count { it.rate > 0 } <= 15) { "Invalid input (too many valves output something)" }
fun solve(valveIndex: Int = initial, opened: Int = 0, timeLeft: Int = 30, partTwo: Boolean = false): Int {
if (timeLeft <= 0) return if (partTwo) solve(initial, opened, 26, false) else 0
// valve index - 6 bits -> max 0x3F, shift 27-6=21
// opened - 15 bits -> max 0x7FFF, shift 21-15=6
// time left - 5 bits -> max 0x1F, shift 6-5=1
// part two - 1 bit -> max 0x1, shift 1-1=0
// total = 6+15+5+1=27 (fits in int)
val indexed = (valveIndex and 0x3F shl 21) or (opened and 0x7FFF shl 6) or
(timeLeft and 0x1F shl 1) or (if (partTwo) 1 else 0)
val seenValue = seen[indexed]
if (seenValue != -1) return seenValue
var result = 0
connections[valveIndex].forEach { new -> result = max(solve(new, opened, timeLeft - 1, partTwo), result) }
val shift = 1 shl valveIndex
val rate = rates[valveIndex]
if (rate > 0 && opened and shift == 0) {
result = max(solve(valveIndex, opened or shift, timeLeft - 1, partTwo) + (timeLeft - 1) * rate, result)
}
seen[indexed] = result
return result
}
partOne = solve(initial).s()
partTwo = solve(initial, timeLeft = 26, partTwo = true).s()
}
data class Valve(val name: String, val rate: Int, val connections: List<String>) | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,173 | advent-of-code | The Unlicense |
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day21/Day21.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2022.day21
import eu.janvdb.aocutil.kotlin.readLines
//const val FILENAME = "input21-test.txt"
const val FILENAME = "input21.txt"
val PATTERN_VARIABLE = Regex("[a-z]+")
val PATTERN_OPERATION = Regex("\\((\\d+) ([+*/-]) (\\d+)\\)")
val PATTERN_EQUATION_1 = Regex("\\((.*) ([+*/-]) (\\d+)\\) = (\\d+)")
val PATTERN_EQUATION_2 = Regex("\\((\\d+) ([+*/-]) (.*)\\) = (\\d+)")
fun main() {
val puzzles = readLines(2022, FILENAME).associate {
val parts = it.split(": ")
Pair(parts[0], parts[1])
}
solvePuzzles(puzzles)
val puzzles2 = puzzles.toMutableMap()
puzzles2["humn"] = "X"
puzzles2["root"] = puzzles2["root"]!!.replace('+', '=')
solvePuzzles(puzzles2)
}
fun solvePuzzles(puzzles: Map<String, String>) {
val puzzleString = buildLargeEquation(puzzles)
val puzzleString2 = simplifyEquation(puzzleString)
val puzzleString3 = solveEquation(puzzleString2)
println(puzzleString3)
}
private fun buildLargeEquation(puzzles2: Map<String, String>): String {
var puzzleString = puzzles2["root"]!!
if (!puzzleString.contains("=")) puzzleString = "($puzzleString)"
while (true) {
val matchResult = PATTERN_VARIABLE.find(puzzleString) ?: break
val replacement = puzzles2[matchResult.value]!!
val replacementBraces = if (replacement.contains(PATTERN_VARIABLE)) "($replacement)" else replacement
puzzleString = puzzleString.replaceRange(matchResult.range, replacementBraces)
}
return puzzleString
}
fun simplifyEquation(puzzle: String): String {
var current = puzzle
while (true) {
val matchResult = PATTERN_OPERATION.find(current) ?: break
val value1 = matchResult.groupValues[1].toBigInteger()
val operator = matchResult.groupValues[2]
val value2 = matchResult.groupValues[3].toBigInteger()
val solution = when (operator) {
"+" -> value1 + value2
"-" -> value1 - value2
"*" -> value1 * value2
"/" -> value1 / value2
else -> throw IllegalArgumentException(operator)
}
current = current.replaceRange(matchResult.range, solution.toString())
}
return current
}
fun solveEquation(puzzle: String): String {
var current = puzzle
while (true) {
if (current[0] == '(' && current[current.length - 1] == ')')
current = current.substring(2, current.length - 1)
val matchResult1 = PATTERN_EQUATION_1.matchEntire(current)
if (matchResult1 != null) {
val largePart = matchResult1.groupValues[1]
val operator = matchResult1.groupValues[2]
val number = matchResult1.groupValues[3].toBigInteger()
val otherNumber = matchResult1.groupValues[4].toBigInteger()
val result = when (operator) {
"+" -> otherNumber - number
"-" -> otherNumber + number
"*" -> otherNumber / number
"/" -> otherNumber * number
else -> throw IllegalArgumentException(operator)
}
current = "$largePart = $result"
continue
}
val matchResult2 = PATTERN_EQUATION_2.matchEntire(current)
if (matchResult2 != null) {
val number = matchResult2.groupValues[1].toBigInteger()
val operator = matchResult2.groupValues[2]
val largePart = matchResult2.groupValues[3]
val otherNumber = matchResult2.groupValues[4].toBigInteger()
val result = when (operator) {
"+" -> otherNumber - number
"-" -> number - otherNumber
"*" -> otherNumber / number
"/" -> number / otherNumber
else -> throw IllegalArgumentException(operator)
}
current = "$largePart = $result"
continue
}
break
}
return current
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 3,426 | advent-of-code | Apache License 2.0 |
src/com/ajithkumar/aoc2022/Day08.kt | ajithkumar | 574,372,025 | false | {"Kotlin": 21950} | package com.ajithkumar.aoc2022
import com.ajithkumar.utils.*
fun main() {
fun inputTo2DArray(inputList: List<String>): Array<IntArray> {
// Create a mutable list to hold the converted values
val convertedValues = mutableListOf<IntArray>()
// Loop through the input list
for (input in inputList) {
// Split the input string by empty string
val splitValues = input.split("").slice(1 until inputList.size+1)
// Convert the split values to integers and add them to the converted values list
convertedValues.add(splitValues.map { it.toInt() }.toIntArray())
}
// Convert the list of converted values to a 2D IntArray and assign it to the resultArray variable
return convertedValues.toTypedArray()
}
fun part1(input: List<String>): Int {
// convert input: List<String> into a 2D IntArray with empty string as delimiter
val trees = inputTo2DArray(input)
// Create a mutable list to hold the visible trees
val visibleTrees = mutableListOf<Pair<Int, Int>>()
for (row in trees.indices) {
for (col in trees[row].indices) {
// Check if the current tree is visible from the edge of the grid
val treeVisible = isTreeVisible(row, col, trees)
// println("$row, $col, $treeVisible")
if (treeVisible) {
// If the tree is visible, add it to the list of visible trees
visibleTrees.add(Pair(row, col))
}
}
}
// Find number of elements in the 2D IntArray whose value is
return visibleTrees.size
}
fun scenicScore(trees: Array<IntArray>, row: Int, col: Int): Int {
val height = trees[row][col]
//iterate top
var topCount = 0
for(r in (0 until row).reversed()) {
topCount++
if(trees[r][col] >= height) {break}
}
var bottomCount = 0
for(r in row+1 until trees.size) {
bottomCount++
if(trees[r][col] >= height) {break}
}
var leftCount = 0
for(c in (0 until col).reversed()) {
leftCount++
if(trees[row][c] >= height) {break}
}
var rightCount = 0
for(c in col+1 until trees.size) {
rightCount++
if(trees[row][c] >= height) {break}
}
return topCount*bottomCount*leftCount*rightCount
}
fun part2(input: List<String>): Int {
val trees = inputTo2DArray(input)
val result = Array(input.size) {IntArray(input.size) {1} }
for (row in trees.indices) {
for (col in trees[row].indices) {
result[row][col] = scenicScore(trees, row, col)
}
}
println(result.contentDeepToString())
return result.map { rows -> rows.max() }.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
// Iterate over the rows and columns of the 2D array
// Define the isTreeVisible() function
fun isTreeVisible(row: Int, col: Int, trees: Array<IntArray>): Boolean {
// Get the height of the current tree
val height = trees[row][col]
// Check if the current tree is located on the edge of the grid
if (row == 0 || row == trees.size - 1 || col == 0 || col == trees[row].size - 1) {
return true
}
// Check if the current tree is visible from the top edge of the grid
var topVisible = true
if (row > 0) {
for (r in 0 until row) {
if (trees[r][col] >= height) {
topVisible = false
break
}
}
}
// Check if the current tree is visible from the bottom edge of the grid
var bottomVisible = true
if (row < trees.size - 1) {
for (r in row + 1 until trees.size) {
if (trees[r][col] >= height) {
bottomVisible = false
break
}
}
}
// Check if the current tree is visible from the left edge of the grid
var leftVisible = true
if (col > 0) {
for (c in 0 until col) {
if (trees[row][c] >= height) {
leftVisible = false
break
}
}
}
// Check if the current tree is visible from the right edge of the grid
var rightVisible = true
if (col < trees[row].size - 1) {
for (c in col + 1 until trees[row].size) {
if (trees[row][c] >= height) {
rightVisible = false
break
}
}
}
return (topVisible || bottomVisible || rightVisible || leftVisible)
}
| 0 | Kotlin | 0 | 0 | f95b8d1c3c8a67576eb76058a1df5b78af47a29c | 4,923 | advent-of-code-kotlin-template | Apache License 2.0 |
leetcode/src/bytedance/Q53.kt | zhangweizhe | 387,808,774 | false | null | package bytedance
fun main() {
// 53. 最大子数组和
// https://leetcode.cn/problems/maximum-subarray/
println(maxSubArray1(intArrayOf(1)))
}
fun maxSubArray(nums: IntArray): Int {
// 动态规划数组,dp[i] 表示以 nums[i] 结尾的子数组的和
val dp = IntArray(nums.size)
dp[0] = nums[0]
var max = dp[0]
for (i in 1 until nums.size) {
if (dp[i-1] > 0) {
dp[i] = dp[i-1] + nums[i]
}else {
dp[i] = nums[i]
}
if (max < dp[i]) {
max = dp[i]
}
}
return max
}
fun maxSubArray1(nums: IntArray): Int {
// 优化版本,dp[i] 只和 dp[i-1] 有关,可以用一个变量替换 dp 数组,优化空间复杂度
// 可以理解为:前面数组的和 prevSum 如果是正数的,对 nums[i] 来说是正贡献,可以累加到以 nums[i] 结尾的子数组的和上
// 如果前面数组的和 prevSum 是负数的,对 nums[i] 来说是负贡献,那么以 nums[i] 结尾的子数组的和,就没必要加上 prevSum,
// nums[i] 自己作为以 nums[i] 结尾的子数组的和就可以了
var prevSum = nums[0]
var max = prevSum
for (i in 1 until nums.size) {
if (prevSum > 0) {
prevSum += nums[i]
}else {
prevSum = nums[i]
}
if (max < prevSum) {
max = prevSum
}
}
return max
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,427 | kotlin-study | MIT License |
2015/src/main/kotlin/day19.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Graph
import utils.Parse
import utils.Parser
import utils.Solution
import utils.findAll
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
fun main() {
Day19.run()
}
object Day19 : Solution<Day19.Input>() {
override val name = "day19"
override val parser = Parser { parseInput(it) }
@Parse("{r '\n' rules}\n\n{molecule}")
data class Input(
val rules: List<Rule>,
val molecule: Molecule,
)
class Molecule(
val atoms: List<String>,
) {
val key get() = atoms.joinToString("")
override fun equals(other: Any?) = (other is Molecule) && key == other.key
override fun hashCode() = key.hashCode()
override fun toString() = key
}
fun parseMolecule(input: String) = Molecule(buildList {
val sb = StringBuilder()
for (char in input) {
if (char.isUpperCase()) {
if (sb.isNotEmpty()) {
add(sb.toString())
sb.clear()
}
}
sb.append(char)
}
add(sb.toString())
})
@Parse("{input} => {output}")
data class Rule(
val input: String,
val output: String,
)
private fun generate(molecule: Molecule, ruleMap: Map<String, List<Rule>>): List<Pair<Rule, Molecule>> {
return molecule.atoms.flatMapIndexed { index, atom ->
val rules = ruleMap[atom] ?: emptyList()
rules.map { rule ->
val list = (molecule.atoms.subList(0, index) + parseMolecule(rule.output).atoms + molecule.atoms.subList(index + 1, molecule.atoms.size))
Molecule(list) to rule
}
}.toMap().entries.map { (k, v) -> v to k }
}
override fun part1(input: Input): Int {
val ruleMap = input.rules.groupBy { it.input }
return generate(input.molecule, ruleMap).size
}
/*
* may or may not finish in a reasonable amount of time, depending on how we luck out with the random shuffle
*/
override fun part2(input: Input): Int {
val rules = input.rules.shuffled()
val g = Graph<String, Rule>(
edgeFn = { molecule ->
// try applying each rule
rules.flatMap { rule ->
molecule.findAll(rule.output).map { atom ->
rule to molecule.substring(0, atom) + rule.input + molecule.substring(atom + rule.output.length)
}
}
}
)
return g.dfs(input.molecule.toString()) { it == "e" }.size - 1
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,363 | aoc_kotlin | MIT License |
src/main/kotlin/Day20.kt | clechasseur | 318,029,920 | false | null | import org.clechasseur.adventofcode2020.Day20Data
import org.clechasseur.adventofcode2020.Direction
import org.clechasseur.adventofcode2020.Pt
import org.clechasseur.adventofcode2020.move
object Day20 {
private val input = Day20Data.input
private val idRegex = """^Tile (\d+):$""".toRegex()
private val seaMonster = """
#
# ## ## ###
# # # # # #
""".trimIndent().lines()
fun part1(): Long {
val tiles = input.toTiles()
val corners = tiles.map { tile ->
tile to Direction.values().mapNotNull { direction ->
tiles.asSequence().filter {
it != tile
}.flatMap {
it.orientationSequence()
}.firstOrNull {
tile.canConnect(it, direction)
}
}.count()
}.filter { (_, neighbours) ->
neighbours == 2
}.map { (tile, _) ->
tile
}
require(corners.size == 4) { "There's ${corners.size} corners?!?" }
return corners.fold(1L) { acc, tile -> acc * tile.id }
}
fun part2(): Int {
val tiles = input.toTiles()
val firstTile = tiles.first()
val quilt = buildQuilt(Quilt(firstTile), tiles - firstTile) ?: error("Could not build quilt")
require(quilt.square) { "Final quilt is not a square" }
val bigTile = quilt.cropAll().toTile(id = 0L)
val numMonsters = countSeaMonsters(bigTile)
return bigTile.lines.sumBy { line ->
line.count { it == '#' }
} - seaMonster.sumBy { line ->
line.count { it == '#' }
} * numMonsters
}
private fun buildQuilt(quilt: Quilt, tiles: Set<Tile>): Quilt? = if (tiles.isEmpty()) {
quilt
} else {
sequence {
tiles.asSequence().forEach { tile ->
quilt.edges.asSequence().forEach { edgePt ->
tile.orientationSequence().mapNotNull { orientedTile ->
val sewnQuilt = quilt.trySew(edgePt, orientedTile)
if (sewnQuilt != null) buildQuilt(sewnQuilt, tiles - tile) else null
}.forEach { builtQuilt ->
yield(builtQuilt)
}
}
}
}.firstOrNull()
}
private fun countSeaMonsters(bigTile: Tile): Int = bigTile.orientationSequence().map { tile ->
(tile.lines.indices.first..tile.lines.indices.last - seaMonster.size + 1).flatMap { y ->
(tile.lines.first().indices.first..tile.lines.first().indices.last - seaMonster.first().length + 1).map { x ->
val picture = tile.lines.subList(y, y + seaMonster.size).map { line ->
line.substring(x, x + seaMonster.first().length)
}
picture.zip(seaMonster).all { (fromPic, fromMonster) ->
fromPic.zip(fromMonster).all { (cFromPic, cFromMonster) ->
cFromMonster == ' ' || cFromPic == cFromMonster
}
}
}
}.count { it }
}.max()!!
private data class Tile(val id: Long, val data: List<String>) {
val lines: List<String>
get() = data
val columns: List<String> by lazy {
data.indices.map { x -> data.joinToString("") { it[x].toString() } }
}
fun flipVertically(): Tile = copy(data = lines.reversed())
fun rotateClockwise(): Tile = copy(data = lines.indices.map { x ->
lines.indices.reversed().joinToString("") { y -> data[y][x].toString() }
})
fun orientationSequence(): Sequence<Tile> = generateSequence(this) { tile ->
tile.rotateClockwise()
}.take(4).flatMap { tile ->
sequenceOf(tile, tile.flipVertically())
}
fun canConnect(tile: Tile, direction: Direction): Boolean = when (direction) {
Direction.UP -> lines.first() == tile.lines.last()
Direction.DOWN -> lines.last() == tile.lines.first()
Direction.LEFT -> columns.first() == tile.columns.last()
Direction.RIGHT -> columns.last() == tile.columns.first()
}
fun crop(): Tile = copy(data = lines.drop(1).dropLast(1).map {
it.substring(1 until it.length - 1)
})
override fun toString(): String = lines.joinToString("\n")
}
private data class Quilt(val tiles: Map<Pt, Tile>) {
constructor(firstTile: Tile) : this(mapOf(Pt.ZERO to firstTile))
val edges: List<Pt>
get() = tiles.keys.flatMap { pt ->
Direction.values().map { pt.move(it) }
}.filter {
it !in tiles
}
val xIndices: IntRange
get() = tiles.keys.minBy { it.x }!!.x..tiles.keys.maxBy { it.x }!!.x
val yIndices: IntRange
get() = tiles.keys.minBy { it.y }!!.y..tiles.keys.maxBy { it.y }!!.y
val square: Boolean
get() = (xIndices.last - xIndices.first) == (yIndices.last - yIndices.first)
fun trySew(pt: Pt, tile: Tile): Quilt? {
val fits = Direction.values().map { direction ->
pt.move(direction) to direction
}.filter { (existingPt, _) ->
existingPt in tiles
}.all { (existingPt, direction) ->
tile.canConnect(tiles[existingPt]!!, direction)
}
return if (fits) Quilt(tiles + (pt to tile)) else null
}
fun cropAll(): Quilt = Quilt(tiles.mapValues { (_, tile) -> tile.crop() })
fun toTile(id: Long): Tile = Tile(id, yIndices.flatMap { y ->
val tile = tiles[Pt(xIndices.first, y)]!!
tile.lines.indices.map { tileY ->
xIndices.joinToString("") { x ->
tiles[Pt(x, y)]!!.lines[tileY]
}
}
})
}
private fun String.toTiles(): Set<Tile> {
val tiles = mutableSetOf<Tile>()
val toParse = lines()
var i = 0
while (i < toParse.size) {
val match = idRegex.matchEntire(toParse[i]) ?: error("Wrong tile ID: ${toParse[i]}")
val id = match.groupValues[1].toLong()
var j = i + 1
while (j < toParse.size && toParse[j].isNotEmpty()) {
j++
}
val data = toParse.subList(i + 1, j)
tiles.add(Tile(id, data))
i = j + 1
}
return tiles
}
}
| 0 | Kotlin | 0 | 0 | 6173c9da58e3118803ff6ec5b1f1fc1c134516cb | 6,583 | adventofcode2020 | MIT License |
src/Day04.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | import kotlin.math.max
import kotlin.math.min
fun main() {
class Range(val begin: Int, val end: Int) {
override operator fun equals(other: Any?): Boolean {
if (other !is Range) {
return false
}
return begin == other.begin && end == other.end
}
override fun hashCode(): Int {
return Pair(begin, end).hashCode()
}
}
fun parseRange(description: String): Range {
val data = description.split('-').map { x -> x.toInt() }
return Range(data[0], data[1])
}
fun parsePair(description: String): List<Range> {
return description.split(',').map(::parseRange)
}
fun oneIsInsideOther(range1: Range, range2: Range): Boolean {
val totalRange = Range(min(range1.begin, range2.begin), max(range1.end, range2.end))
return totalRange == range1 || totalRange == range2
}
fun part1scorePair(description: String): Int {
val data = parsePair(description)
return if (oneIsInsideOther(data[0], data[1])) 1 else 0
}
fun part1(input: List<String>): Int {
return input.map(::part1scorePair).sum()
}
fun isOverlap(range1: Range, range2: Range): Boolean {
val intersectRange = Range(max(range1.begin, range2.begin), min(range1.end, range2.end))
return intersectRange.begin <= intersectRange.end
}
fun part2scorePair(description: String): Int {
val data = parsePair(description)
return if (isOverlap(data[0], data[1])) 1 else 0
}
fun part2(input: List<String>): Int {
return input.map(::part2scorePair).sum()
}
val input = readInput("Day04")
println("Day 4")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 1,771 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day9.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.Point
import shared.XYMap
import shared.getLines
fun findRiskLevelsSum(input: List<String>): Int{
val map = LavaTubes(input)
return map.getLowPoints().sumOf { map.getValue(it) + 1 }
}
fun findLargestBasinsMultiplied(input: List<String>): Int{
val map = LavaTubes(input)
val basinSizes = map.findBasins()
return basinSizes.sortedDescending().take(3).reduce { acc, i -> acc * i }
}
fun main(){
val input = getLines("day9.txt")
val task1 = findRiskLevelsSum(input)
println(task1)
val task2 = findLargestBasinsMultiplied(input)
println(task2)
}
private class LavaTubes(input: List<String>): XYMap<Int>(input, { c: Char -> c.digitToInt() }) {
private fun lowPoint(point: Point) = findAdjacentPoints(point).all { getValue(point) < getValue(it) }
fun getLowPoints() = allPoints().filter { lowPoint(it) }
fun findBasins() = getLowPoints().map { findBasinSize(it) }
private fun findBasinSize(lowPoint: Point): Int{
val hasChecked = mutableListOf(lowPoint)
var toCheck = findAdjacentPoints(lowPoint).filter { getValue(it) != 9 }
var size = 1
while(toCheck.isNotEmpty()){
size += toCheck.size
hasChecked.addAll(toCheck)
toCheck = toCheck.flatMap { point -> findAdjacentPoints(point) }.toSet().filter { !hasChecked.contains(it) && getValue(it) != 9 }
}
return size
}
}
| 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 1,423 | AdventOfCode2021 | MIT License |
src/main/kotlin/advent/day14/ExtendedPolymerization.kt | hofiisek | 434,171,205 | false | {"Kotlin": 51627} | package advent.day14
import advent.loadInput
import java.io.File
/**
* @author <NAME>
*/
typealias PairInsertionRules = Map<String, String>
fun <K> MutableMap<K, Long>.putOrSumValue(key: K, count: Long) =
compute(key) { _, currCount -> (currCount ?: 0) + count }
fun <T, K> Grouping<T, K>.eachCountLong(): Map<K, Long> = eachCount().map { (k, v) -> k to v.toLong() }.toMap()
fun String.toChar() = single()
fun part1(input: File) = input.readLines()
.filter(String::isNotBlank)
.let { it.first() to it.drop(1) }
.let { (polymerTemplate, insertionRules) ->
val rules: PairInsertionRules = insertionRules
.map { it.split(" -> ") }
.associate { (pair, charToInsert) -> pair to charToInsert }
runPolymerizationNaive(polymerTemplate, rules, 10)
.groupingBy { it }
.eachCount()
.let { charsToCount ->
charsToCount.maxOf { it.value } - charsToCount.minOf { it.value }
}
}
fun runPolymerizationNaive(
currentPolymer: String,
rules: PairInsertionRules,
maxSteps: Int,
step: Int = 1
): String = when {
step > maxSteps -> currentPolymer
else -> currentPolymer
.windowed(size = 2)
.map { pair ->
when (val charToInsert = rules[pair]) {
null -> pair.first()
else -> pair.first() + charToInsert
}
}
.joinToString("")
.let { polymer -> runPolymerizationNaive(polymer + currentPolymer.last(), rules, maxSteps, step + 1) }
}
fun part2(input: File) = input.readLines()
.filter(String::isNotBlank)
.let { it.first() to it.drop(1) }
.let { (polymerTemplate, insertionRules) ->
val rules: PairInsertionRules = insertionRules
.map { it.split(" -> ") }
.associate { (pair, charToInsert) -> pair to charToInsert }
var pairsCount: Map<String, Long> = polymerTemplate
.windowed(size = 2)
.groupingBy { it }
.eachCountLong()
.toMap()
val charsCount: MutableMap<Char, Long> = polymerTemplate
.groupingBy { it }
.eachCountLong()
.toMutableMap()
val steps = 40
// literally no idea how to do this functionally and immutable :(
repeat(steps) { step ->
println("step: ${step + 1}, pairs: $pairsCount, chars: $charsCount")
val updatedPairsCount = mutableMapOf<String, Long>()
pairsCount.forEach { (pair, count) ->
when (val charToInsert = rules[pair]) {
null -> updatedPairsCount.putOrSumValue(pair, count)
else -> {
listOf(pair[0] + charToInsert, charToInsert + pair[1])
.forEach { updatedPairsCount.putOrSumValue(it, count) }
charsCount.putOrSumValue(charToInsert.toChar(), count)
}
}
}
pairsCount = updatedPairsCount
}
charsCount
}
.let { it.maxOf { it.value } - it.minOf { it.value } }
fun main() {
with(loadInput(day = 14)) {
// with(loadInput(day = 14, filename = "input_example.txt")) {
println(part1(this))
println(part2(this))
}
} | 0 | Kotlin | 0 | 2 | 3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb | 3,327 | Advent-of-code-2021 | MIT License |
src/y2016/Day20.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2016
import util.readInput
enum class Indicator {
START, STOP
}
object Day20 {
private fun parse(input: List<String>): List<Pair<Long, Indicator>> {
return input.flatMap { line ->
val (start, stop) = line.split("-").map { it.toLong() }
listOf(start to Indicator.START, stop to Indicator.STOP)
}.sortedBy { it.first }
}
fun part1(input: List<String>) {
val parsed = parse(input)
val stackDepth = parsed.scan(0) { acc, pair ->
if (pair.second == Indicator.START) {
acc + 1
} else {
acc - 1
}
}.drop(1)
println(parsed)
println(stackDepth)
val idx = stackDepth.indexOf(0)
println("stop: ${parsed[idx]}")
println("next: ${parsed[idx + 1]}")
part2(parsed, stackDepth)
}
fun part2(parsed: List<Pair<Long, Indicator>>, stackDepth: List<Int>) {
val gaps = stackDepth.dropLast(1)
.mapIndexedNotNull { idx, depth ->
if (depth != 0) {
null
} else {
parsed[idx + 1].first - parsed[idx].first - 1
}
}
println("gaps: $gaps")
println("total: ${gaps.sum()}")
}
}
fun main() {
val testInput = """
5-8
0-2
4-7
""".trimIndent().split("\n")
println("------Tests------")
println(Day20.part1(testInput))
println("------Real------")
val input = readInput("resources/2016/day20")
println(Day20.part1(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,573 | advent-of-code | Apache License 2.0 |
src/Day02/Solution.kt | cweinberger | 572,873,688 | false | {"Kotlin": 42814} | package Day02
import readInput
/**
* Col 1
* A = Rock
* B = Paper
* C = Scissors
*
* Col 2
* X = Rock | Lose
* Y = Paper | Draw
* Z = Scissors | Win
*
* Lose = 0 pts
* Draw = 3 pts
* Win = 6 pts
* Rock = 1 pts
* Paper = 2 pts
* Scissors = 3 pts
*/
enum class Hand(val value: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
companion object {
@Throws(IllegalArgumentException::class)
fun withInput(input: String) : Hand {
return when (input) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException("Unexpected input: '$input'")
}
}
}
fun resultAgainst(other: Hand) : Result {
return when (other) {
this.getLosingHand() -> Result.WIN
this.getWinningHand() -> Result.LOSE
else -> Result.DRAW
}
}
fun getLosingHand() : Hand {
return when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
fun getWinningHand() : Hand {
return when (this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
}
enum class Result(val value: Int) {
WIN(6),
DRAW(3),
LOSE(0);
companion object {
@Throws(IllegalArgumentException::class)
fun withInput(input: String) : Result {
return when (input) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException("Unexpected input: '$input'")
}
}
}
}
fun main() {
fun parseMatchLineAsHands(input: String) : Pair<Hand, Hand> {
return input
.split(" ")
.map { Hand.withInput(it) }
.let { Pair(it.first(), it.last()) }
}
fun parseMatchLineAsHandAndResult(input: String) : Pair<Hand, Result> {
return input
.split(" ")
.let { Pair(
Hand.withInput(it.first()),
Result.withInput(it.last())
) }
}
fun evaluateMatch(yourHand: Hand, otherHand: Hand): Int {
return yourHand.value + yourHand.resultAgainst(otherHand).value
}
fun evaluateMatches(input: List<String>): List<Int> {
println("Evaluating ${input.count()} matches")
return input
.map { matchStr ->
parseMatchLineAsHands(matchStr)
.let { hands ->
evaluateMatch(hands.second, hands.first)
}
}
}
fun part1(input: List<String>): Int {
return evaluateMatches(input).sum()
}
fun part2(input: List<String>): Int {
println("Evaluating ${input.count()} matches")
return input
.map { matchStr ->
parseMatchLineAsHandAndResult(matchStr)
.let {
when (it.second) {
Result.WIN -> Pair(it.first, it.first.getWinningHand())
Result.DRAW -> Pair(it.first, it.first)
Result.LOSE -> Pair(it.first, it.first.getLosingHand())
}
}
.let { hands ->
evaluateMatch(hands.second, hands.first)
}
}.sum()
}
val testInput = readInput("Day02/TestInput")
val input = readInput("Day02/Input")
println("=== Part 1 - Test Input ===")
println(part1(testInput))
println("=== Part 1 - Final Input ===")
println(part1(input))
println("=== Part 2 - Test Input ===")
println(part2(testInput))
println("=== Part 2 - Final Input ===")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 883785d661d4886d8c9e43b7706e6a70935fb4f1 | 3,871 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DistinctSubseq2.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
import dev.shtanko.algorithms.MOD
/**
* 940. Distinct Subsequences II
* @see <a href="https://leetcode.com/problems/distinct-subsequences-ii/">Source</a>
*/
fun interface DistinctSubseq2 {
fun distinctSubseqII(s: String): Int
}
/**
* Approach 1: Dynamic Programming
*/
class DistinctSubseq2DP : DistinctSubseq2 {
override fun distinctSubseqII(s: String): Int {
val n: Int = s.length
val dp = IntArray(n + 1)
dp[0] = 1
val last = IntArray(ALPHABET_LETTERS_COUNT) { -1 }
for (i in 0 until n) {
val x: Int = s[i] - 'a'
dp[i + 1] = dp[i] * 2 % MOD
if (last[x] >= 0) dp[i + 1] -= dp[last[x]]
dp[i + 1] %= MOD
last[x] = i
}
dp[n]--
if (dp[n] < 0) dp[n] += MOD
return dp[n]
}
}
class DistinctSubseq2DPConstSpace : DistinctSubseq2 {
override fun distinctSubseqII(s: String): Int {
var pre = 1 // The number of subsequences till previous-location. Include empty string: ""
var cur = 1 // The number of subsequences till now. Include empty string: ""
// The number of subsequences that end with a character till now. Not include empty string: ""
val lastCount = IntArray(ALPHABET_LETTERS_COUNT)
for (element in s) {
val charIndex: Int = element - 'a'
cur = pre * 2 % MOD // include-current-character + not-include-current-character
// Remove duplicated characters: previous subsequences that end with current character.
cur -= lastCount[charIndex]
cur = if (cur >= 0) cur % MOD else cur + MOD
lastCount[charIndex] = pre // The number of subsequences that end with current character.
pre = cur
}
--cur // remove the empty string: ""
return cur
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,549 | kotlab | Apache License 2.0 |
src/main/kotlin/co/csadev/advent2022/Day11.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2022 by <NAME>
* Advent of Code 2022, Day 11
* Problem Description: http://adventofcode.com/2021/day/11
*/
package co.csadev.advent2022
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Resources.resourceAsText
class Day11(override val input: String = resourceAsText("22day11.txt")) :
BaseDay<String, Long, Long> {
data class Monkey(
var items: MutableList<Long>,
val operation: (Long) -> Long,
val divBy: Int,
val trueMonkey: Int,
val falseMonkey: Int,
var inspectCount: Int = 0
)
private fun List<String>.toOperation(): (Long) -> Long {
val op: (Long) -> Long = { old ->
val part1 = if (this[0] == "old") old else this[0].toLong()
val part2 = if (this[2] == "old") old else this[2].toLong()
if (this[1] == "+") (part1 + part2) else (part1 * part2)
}
return op
}
override fun solvePart1() = solver(20, 3)
override fun solvePart2() = solver(10_000)
private fun solver(rounds: Int, worryResolver: Int = 1): Long {
val monkeys = input.split("\n\n").map {
val monkeyLines = it.lines()
Monkey(
monkeyLines[1].substringAfter(": ").split(", ").map { i -> i.toLong() }.toMutableList(),
monkeyLines[2].substringAfter("new = ").split(" ").toOperation(),
monkeyLines[3].substringAfter("divisible by ").toInt(),
monkeyLines[4].substringAfter("monkey ").toInt(),
monkeyLines[5].substringAfter("monkey ").toInt()
)
}
val monkeyCount = monkeys.size
val gcd = monkeys.map { e -> e.divBy.toLong() }.reduce { a, b -> a * b }
repeat(rounds) {
(0 until monkeyCount).forEach { i ->
val m = monkeys[i]
val itemCount = m.items.size
repeat(itemCount) {
val item = m.items.removeAt(0)
val newWorry = m.operation(item) / worryResolver
val newMonkey = if (newWorry % m.divBy == 0L) m.trueMonkey else m.falseMonkey
m.inspectCount++
monkeys[newMonkey].items.add(if (worryResolver == 1) newWorry % gcd else newWorry)
}
}
}
return monkeys.sortedByDescending { it.inspectCount }.take(2)
.run { this[0].inspectCount.toLong() * this[1].inspectCount.toLong() }
}
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 2,508 | advent-of-kotlin | Apache License 2.0 |
src/Day04.kt | lsimeonov | 572,929,910 | false | {"Kotlin": 66434} |
fun main() {
fun part1(input: List<String>): Int {
var c = 0
input.forEach {
val row = it.split(',')
val input1 = row[0].split('-').map { s -> s.toInt() }
val input2 = row[1].split('-').map { s -> s.toInt() }
val r1 = input1[0]..input1[1]
val r2 = input2[0]..input2[1]
val diff1 = r1 - r2
val diff2 = r2 - r1
if (diff1.isEmpty() || diff2.isEmpty()) {
c++
}
}
return c
}
fun part2(input: List<String>): Int {
var c = 0
input.forEach {
val row = it.split(',')
val input1 = row[0].split('-').map { s -> s.toInt() }
val input2 = row[1].split('-').map { s -> s.toInt() }
val r1 = input1[0]..input1[1]
val r2 = input2[0]..input2[1]
if (r1.toSet().intersect(r2.toSet()).isNotEmpty()) {
c++
}
}
return c
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9d41342f355b8ed05c56c3d7faf20f54adaa92f1 | 1,286 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | hoppjan | 573,053,610 | false | {"Kotlin": 9256} | fun main() {
val testLines = readInput("Day04_test")
val testResult1 = part1(testLines)
println("test part 1: $testResult1")
check(testResult1 == 2)
val testResult2 = part2(testLines)
println("test part 2: $testResult2")
check(testResult2 == 4)
val lines = readInput("Day04")
println("part 1: ${part1(lines)}")
println("part 2: ${part2(lines)}")
}
private fun part1(input: List<String>) = parseSections(input)
.count { (first, second) -> first contains second }
private infix fun IntRange.contains(range: IntRange) =
first in range && last in range || range.first in this && range.last in this
private fun part2(input: List<String>) = parseSections(input)
.count { (first, second) -> first overlaps second }
private infix fun IntRange.overlaps(range: IntRange) =
first in range || last in range || range.first in this || range.last in this
private fun parseSections(input: List<String>) =
input.map { line ->
line.split(",").let { (first, second) -> first.toRange() to second.toRange() }
}
private fun String.toRange() = split("-").let { (first, second) -> first.toInt()..second.toInt() }
| 0 | Kotlin | 0 | 0 | f83564f50ced1658b811139498d7d64ae8a44f7e | 1,173 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day2/Day2.kt | jksolbakken | 317,995,724 | false | null | package day2
import java.io.File
fun main() {
val input = File(object {}.javaClass.getResource("/day2/input.txt").toURI()).readLines()
println("char count: ${matchingNrOfChars(input)}")
println("char position: ${matchingPosition(input)}")
}
fun matchingNrOfChars(lines: List<String>) = prepare(lines)
.map { (ruleAsString, password) -> Pair(charCountRule(ruleAsString), password) }
.count { (rule, password) -> rule(password) }
fun matchingPosition(lines: List<String>) = prepare(lines)
.map { (ruleAsString, password) -> Pair(charPositionRule(ruleAsString), password) }
.count { (rule, password) -> rule(password) }
private fun charCountRule(asText: String): (String) -> Boolean =
asText.split(" ").let { (charCounts, character) ->
val (min, max) = charCounts.split("-").map { it.toInt() }
val range = IntRange(min, max)
val char = character.first()
return { password -> password.filter { it == char }.count() in range }
}
private fun charPositionRule(asText: String): (String) -> Boolean =
asText.split(" ").let { (positions, character) ->
val (firstPos, secondPos) = positions.split("-").map { it.toInt() }
val char = character.first()
return { password ->
password.withIndex().count {
indexMatches(it.index, firstPos, secondPos) && it.value == char
} == 1
}
}
private fun prepare(input: List<String>) =
input.filter { it.isNotEmpty() }.map { it.split(": ") }
private fun indexMatches(actualIndex: Int, vararg desiredIndices: Int) =
actualIndex + 1 in desiredIndices
| 0 | Kotlin | 0 | 0 | 4c5e7a46c010c0155e930617a57cd6711f872edb | 1,601 | aoc_2020 | MIT License |
src/Day07.kt | Venkat-juju | 572,834,602 | false | {"Kotlin": 27944} | import kotlin.system.measureNanoTime
fun main() {
fun solve(input: List<String>, isPart1: Boolean): Long {
val currentDirectoryTree = mutableListOf<String>()
val directorySizes = hashMapOf<List<String>, Long>()
input.forEach {
val commandSplit = it.split(" ")
val isCommand = commandSplit.first() == "$"
if (isCommand) {
// this is command
when(commandSplit[1]) {
"cd" -> {
when(val directory = commandSplit[2]) {
"/" -> {
currentDirectoryTree.clear()
currentDirectoryTree.add("/")
}
".." -> currentDirectoryTree.removeLast()
else -> currentDirectoryTree.add(directory)
}
}
"ls" -> Unit
}
} else {
// this is not command
commandSplit[0].toIntOrNull()?.let { fileSize ->
currentDirectoryTree.reversed().windowed(currentDirectoryTree.size, partialWindows = true).forEach { directory ->
directorySizes[directory] = (directorySizes[directory] ?: 0) + fileSize
}
}
}
}
return if (isPart1) {
directorySizes.filter { it.value <= 100000 }.values.sum()
} else {
val unUsedSpace = 70000000 - directorySizes[listOf("/")]!!
val requiredSpace = 30000000 - unUsedSpace
directorySizes.filter { it.value >= requiredSpace }.values.min()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(solve(testInput, true) == 95437L)
check(solve(testInput, false) == 24933642L)
val input = readInput("Day07")
val timeTaken = measureNanoTime {
println(solve(input, true))
println(solve(input, false))
}
println("Time taken: $timeTaken")
}
| 0 | Kotlin | 0 | 0 | 785a737b3dd0d2259ccdcc7de1bb705e302b298f | 2,149 | aoc-2022 | Apache License 2.0 |
src/kotlin2023/Day03.kt | egnbjork | 571,981,366 | false | {"Kotlin": 18156} | package kotlin2023
import readInput
fun main() {
val lines = readInput("kotlin2023/Day03_test")
println(sumNotPartNumbers(lines))
}
fun sumNotPartNumbers(lines: List<String>): Int {
return lines.mapIndexed { i, e ->
extractNumbers(e).filter {
isPartNumber(it, i, lines)
}.sum()
}.sum()
}
fun isPartNumber(number: Int, lineNumber: Int, lines: List<String>): Boolean {
val lineWithNumber = lines[lineNumber]
val numberLength = number.toString().length
val firstPosition = lineWithNumber.indexOf(number.toString())
val secondPosition = firstPosition + numberLength
for (i in firstPosition..secondPosition) {
//check at the top
if (lineNumber != 0) {
for (n in firstPosition - 1..secondPosition) {
if (isSymbolAdjacent(lines[lineNumber - 1], n)) {
println("number $number is part at the top")
return true
}
}
}
//check left
if (isSymbolAdjacent(lineWithNumber, firstPosition - 1)) {
println("number $number is part on the left")
return true
}
//check right
if (isSymbolAdjacent(lineWithNumber, secondPosition)) {
println("number $number is part on the right")
return true
}
//check at the bottom
if (lineNumber != lines.lastIndex) {
for (n in firstPosition - 1..secondPosition) {
if (isSymbolAdjacent(lines[lineNumber + 1], n)) {
println("number $number is part at the bottom")
return true
}
}
}
}
return false
}
fun isSymbolAdjacent(line: String, position: Int): Boolean {
if (position < 0 || position > line.length - 1) {
return false
}
return !line[position].isDigit() &&
line[position] != '.'
}
fun extractNumbers(line: String): List<Int> {
return line
.replace(Regex("[^0-9]"), " ")
.trim()
.split(" ")
.filter {
it.toIntOrNull() != null
}.map {
it.toInt()
}
}
| 0 | Kotlin | 0 | 0 | 1294afde171a64b1a2dfad2d30ff495d52f227f5 | 2,185 | advent-of-code-kotlin | Apache License 2.0 |
src/Day12.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | data class Spring(
val data: String,
val broken: List<Int>
)
fun String.initSpring(factor: Int = 1): Spring {
return this.split(" ").let {
val data = it[0]
val broken = it[1]
Spring(
data = (0..<factor).joinToString("?") { data },
broken = (0..<factor).joinToString(",") { broken }
.split(",")
.map { it.toInt() }
)
}
}
fun Spring.countHash() = data.countHash()
fun String.countHash() = this.count { it == '#' }
fun Spring.startsWith(c: Char) = data.startsWith(c)
fun Spring.isImpossibleState(lastEndedWithHash: Boolean): Boolean {
// If broken pipes remain, this is not possible path
if (broken.isEmpty() && countHash() > 0)
return true
// There must be enough chars remaining to satisfy the remaining match
if (broken.sum() + (broken.size - 1) > data.length)
return true
// If previously ended with #
if (lastEndedWithHash && startsWith('#'))
return true
return false
}
// Advance "data" by 1 char
fun Spring.advanceByData() = this.copy(data = this.data.drop(1))
// Advance by first broken size
fun Spring.advanceByBroken() = Spring(data = data.drop(broken.first()), broken = broken.drop(1))
// Memoize this recursion.
val cache = mutableMapOf<Pair<Spring, Boolean>, Long>()
fun Spring.countPossible(lastEndedWithHash: Boolean = false): Long = cache.getOrPut(this to lastEndedWithHash) {
if (this.isImpossibleState(lastEndedWithHash))
return@getOrPut 0
if (this.broken.isEmpty() && (this.data.isEmpty() || this.countHash() == 0))
return@getOrPut 1
if (!lastEndedWithHash && !this.startsWith('.')) {
// Take a peek at head of the data
val head = this.data.take(this.broken.first())
// If head is all #####, then we must take this
if (head.countHash() == head.length) {
return@getOrPut this.advanceByBroken().countPossible(true)
} else {
// If head is combination of ? and #
val a = if (head.count { it != '.' } == head.length)
this.advanceByBroken().countPossible(true)
else 0
// If head doesn't start with a definitive broken,
// then assume it is not broken then move forward
val b = if (!head.startsWith('#'))
this.advanceByData().countPossible(false)
else 0
return@getOrPut a + b
}
}
// Advance by 1 char and move on
return@getOrPut this.advanceByData().countPossible(false)
}
fun main() {
fun part1(input: List<String>): Long {
return input.sumOf {
it.initSpring()
.also { println("Processing $it") }
.countPossible()
.also { println("Possible: $it") }
}
}
fun part2(input: List<String>): Long {
return input.sumOf {
it.initSpring(5)
.also { println("Processing $it") }
.countPossible()
.also { println("Possible: $it") }
}
}
val input = readInput("Day12")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 3,191 | aoc-2023 | Apache License 2.0 |
src/Day25.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | import kotlin.math.abs
import kotlin.math.ln
import kotlin.math.pow
fun main() {
val digits = mapOf(
'2' to 2,
'1' to 1,
'0' to 0,
'-' to -1,
'=' to -2,
)
fun snafuToInt(snafu: String) = snafu
.reversed()
.mapIndexed { i, c ->
5.0.pow(i.toDouble()).toLong() * digits.getValue(c)
}
.sum()
val chars = charArrayOf('=', '-', '0', '1', '2')
val multipliers = listOf(-2, -1, 0, 1, 2)
fun intToSnafu(x: Long): String {
var remainder = x
val exponent = (ln(x.toDouble()) / ln(5.0)).toInt() + 1
val result = mutableListOf<Char>()
for (e in exponent downTo 0) {
val factor = 5.0.pow(e).toLong()
val multiplier = multipliers.minBy { abs(remainder - it * factor) }
remainder -= multiplier * factor
result.add(chars[multiplier + 2])
}
check(remainder == 0L)
while (result.first() == '0') result.removeAt(0)
val snafu = String(result.toCharArray())
check(snafuToInt(snafu) == x)
return snafu
}
fun part1(input: List<String>): String {
val value = input.sumOf(::snafuToInt)
return intToSnafu(value)
}
check(intToSnafu(1) == "1")
check(intToSnafu(2) == "2")
check(intToSnafu(3) == "1=")
check(intToSnafu(4) == "1-")
check(intToSnafu(5) == "10")
check(intToSnafu(6) == "11")
check(intToSnafu(7) == "12")
check(intToSnafu(8) == "2=")
check(intToSnafu(9) == "2-")
check(intToSnafu(10) == "20")
check(intToSnafu(15) == "1=0")
check(intToSnafu(20) == "1-0")
check(intToSnafu(2022) == "1=11-2")
check(intToSnafu(12345) == "1-0---0")
check(intToSnafu(314159265) == "1121-1110-1=0")
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
check(part1(testInput) == "2=-1=0")
val input = readInput("Day25")
println(part1(input))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 2,018 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/hopkins/aoc/day15/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day15
import java.io.File
const val debug = true
const val part = 2
val map: Map<Int, MutableList<Lens>> =
(0 until 256).associateBy({ it }, { mutableListOf()})
/** Advent of Code 2023: Day 15 */
fun main() {
// Read the file input
val lines: List<String> = File("input/input15.txt").readLines()
val numLines = lines.size
if (debug) {
println("Num lines: $numLines")
}
// Split into items
val items = lines[0].split(",")
if (debug) {
println("Num items: ${items.size}")
}
val sum = items.sumOf { item ->
val result = calculateHash(item)
if (debug) {
println("item=$item hash=$result")
}
result
}
println("Part 1 Sum: $sum")
println()
if (part == 1) {
return
}
items.forEach { item ->
val label = item.dropLast(if (item.endsWith("-")) 1 else 2)
val boxNumber = calculateHash(label)
println("Item: $item Label: $label Box: $boxNumber")
val box = map[boxNumber]!!
if (item.endsWith("-")) {
// Remove the item
box.removeAll { lens -> lens.label == label }
println("Remove $label")
} else {
// Add the item
val (_, focalLength) = item.split("=")
val focalLengthInt = focalLength.toInt()
val lens = box.firstOrNull { lens -> lens.label == label }
if (lens == null) {
box.add(Lens(label, focalLengthInt))
} else {
lens.focalLength = focalLengthInt
}
}
}
val p2sum = map.entries
.filter { (_, lensList) -> lensList.isNotEmpty() }
.map { (boxNumber, lensList) ->
val lensValues =
lensList.mapIndexed { index, lens ->
(boxNumber + 1) * (index + 1) * lens.focalLength
}.sum()
println("Box $boxNumber: lenses=$lensList value=$lensValues")
lensValues
}.sum()
println("Part 2 Sum: $p2sum")
}
fun calculateHash(input: String): Int {
if (input.isEmpty()) {
return 0;
}
var acc = 0
for (c in input.chars()) {
acc += c
acc *= 17
acc %= 256
}
return acc
}
class Lens(val label: String, var focalLength: Int) {
override fun toString(): String = "[$label $focalLength]"
} | 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 2,416 | aoc2023 | MIT License |
src/main/kotlin/com/ginsberg/advent2023/Day14.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 14 - Parabolic Reflector Dish
* Problem Description: http://adventofcode.com/2023/day/14
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day14/
*/
package com.ginsberg.advent2023
class Day14(input: List<String>) {
private val grid: Array<CharArray> = input.map { it.toCharArray() }.toTypedArray()
private val progressions: Map<Point2D, List<Point2D>> = mapOf(
Point2D.NORTH to grid.indices.flatMap { y ->
grid.first().indices.map { x ->
Point2D(x, y)
}
},
Point2D.WEST to grid.first().indices.flatMap { x ->
grid.indices.map { y ->
Point2D(x, y)
}
},
Point2D.SOUTH to grid.indices.reversed().flatMap { y ->
grid.first().indices.map { x ->
Point2D(x, y)
}
},
Point2D.EAST to grid.first().indices.reversed().flatMap { x ->
grid.indices.map { y ->
Point2D(x, y)
}
}
)
fun solvePart1(): Int {
grid.tilt(Point2D.NORTH)
return grid.score()
}
fun solvePart2(goal: Int = 1_000_000_000): Int {
val seen = mutableMapOf<Int, Int>()
var cycleNumber = 1
while (cycleNumber <= goal) {
grid.cycle()
when (val state = grid.sumOf { it.joinToString("").hashCode() }) {
!in seen -> seen[state] = cycleNumber++
else -> {
val cycleLength = cycleNumber - seen.getValue(state)
val cyclesRemaining = (goal - cycleNumber) % cycleLength
repeat(cyclesRemaining) {
grid.cycle()
}
return grid.score()
}
}
}
return grid.score()
}
private fun Array<CharArray>.cycle() {
tilt(Point2D.NORTH)
tilt(Point2D.WEST)
tilt(Point2D.SOUTH)
tilt(Point2D.EAST)
}
private fun Array<CharArray>.tilt(direction: Point2D) {
progressions
.getValue(direction)
.filter { this[it] == 'O' }
.forEach { doTilt(it, direction) }
}
private fun Array<CharArray>.doTilt(place: Point2D, direction: Point2D) {
var current = place
while (isSafe(current + direction) && this[current + direction] == '.') {
swap(current, current + direction)
current += direction
}
}
private fun Array<CharArray>.score(): Int =
mapIndexed { y, row ->
row.sumOf { c ->
if (c == 'O') size - y
else 0
}
}.sum()
}
| 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 2,786 | advent-2023-kotlin | Apache License 2.0 |
src/main/kotlin/days/y2019/Day03/Day03.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2019
import days.Day
import kotlin.math.abs
public class Day03 : Day(2019, 3) {
override fun partOne(input: String): Any {
val (wireA, wireB) = input.split("\n").map { it.parseWire() }
val pointsA = wireA.points()
val pointsB = wireB.points()
return pointsA.intersect(pointsB).minOfOrNull { it.manhattanDistance(Point(0, 0)) }
?: error("No intersections found")
}
override fun partTwo(input: String): Any {
val (wireA, wireB) = input.split("\n").map { it.parseWire() }
val pointsAndStepsA = wireA.pointsAndSteps()
val pointsAndStepsB = wireB.pointsAndSteps()
return pointsAndStepsA.keys.intersect(pointsAndStepsB.keys).minOfOrNull { point ->
val distA = pointsAndStepsA[point]!!
val distB = pointsAndStepsB[point]!!
distA + distB
}!!
}
}
private fun Point.manhattanDistance(point: Point): Int = abs(x - point.x) + abs(y - point.y)
data class Point(val x: Int, val y: Int)
private fun List<WireSegment>.points(): Set<Point> {
val result = mutableSetOf<Point>()
var x = 0
var y = 0
forEach { segment ->
repeat(segment.distance) {
when (segment.direction) {
Direction.UP -> y++
Direction.DOWN -> y--
Direction.LEFT -> x--
Direction.RIGHT -> x++
}
result.add(Point(x, y))
}
}
return result
}
private fun List<WireSegment>.pointsAndSteps(): Map<Point, Int> {
val result = mutableMapOf<Point, Int>()
var x = 0
var y = 0
var stepsTaken = 0
forEach { segment ->
repeat(segment.distance) {
when (segment.direction) {
Direction.UP -> y++
Direction.DOWN -> y--
Direction.LEFT -> x--
Direction.RIGHT -> x++
}
stepsTaken++
result[Point(x, y)] = stepsTaken
}
}
return result
}
private fun String.parseWire(): List<WireSegment> = split(",").map {
val direction = Direction.from(it[0])
val distance = it.substring(1).toInt()
WireSegment(direction, distance)
}
data class WireSegment(val direction: Direction, val distance: Int)
enum class Direction(val char: Char) {
UP('U'),
DOWN('D'),
LEFT('L'),
RIGHT('R');
companion object {
fun from(c: Char): Direction = values().first { it.char == c }
}
} | 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 2,484 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/MinimumWindowSubstring.kt | Codextor | 453,514,033 | false | {"Kotlin": 26975} | /**
* Given two strings s and t of lengths m and n respectively, return the minimum window
* substring
* of s such that every character in t (including duplicates) is included in the window.
* If there is no such substring, return the empty string "".
*
* The testcases will be generated such that the answer is unique.
*
*
*
* Example 1:
*
* Input: s = "ADOBECODEBANC", t = "ABC"
* Output: "BANC"
* Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
* Example 2:
*
* Input: s = "a", t = "a"
* Output: "a"
* Explanation: The entire string s is the minimum window.
* Example 3:
*
* Input: s = "a", t = "aa"
* Output: ""
* Explanation: Both 'a's from t must be included in the window.
* Since the largest window of s only has one 'a', return empty string.
*
*
* Constraints:
*
* m == s.length
* n == t.length
* 1 <= m, n <= 10^5
* s and t consist of uppercase and lowercase English letters.
*
*
* Follow up: Could you find an algorithm that runs in O(m + n) time?
* @see <a https://leetcode.com/problems/minimum-window-substring/">LeetCode</a>
*/
fun minWindow(s: String, t: String): String {
val sFrequencyMap = mutableMapOf<Char, Int>()
val tFrequencyMap = mutableMapOf<Char, Int>()
t.forEach { char ->
tFrequencyMap[char] = 1 + tFrequencyMap.getOrDefault(char, 0)
}
var start = 0
var end = 0
var minWindowStart = 0
var minWindowLength = Int.MAX_VALUE
var requiredChars = tFrequencyMap.size
while (start < s.length && end < s.length) {
while (end < s.length && requiredChars > 0) {
val endChar = s[end]
sFrequencyMap[endChar] = 1 + sFrequencyMap.getOrDefault(endChar, 0)
if (sFrequencyMap[endChar] == tFrequencyMap[endChar]) {
requiredChars--
}
end++
}
if (requiredChars > 0) {
break
}
var startChar = s[start]
while (!tFrequencyMap.containsKey(startChar) || sFrequencyMap[startChar]!! > tFrequencyMap[startChar]!!) {
sFrequencyMap[startChar] = sFrequencyMap[startChar]!! - 1
start++
startChar = s[start]
}
if (end - start < minWindowLength) {
minWindowLength = end - start
minWindowStart = start
}
sFrequencyMap[startChar] = sFrequencyMap[startChar]!! - 1
requiredChars++
start++
}
return if (minWindowLength == Int.MAX_VALUE) {
""
} else {
s.substring(minWindowStart until minWindowStart + minWindowLength)
}
}
| 0 | Kotlin | 1 | 0 | 68b75a7ef8338c805824dfc24d666ac204c5931f | 2,619 | kotlin-codes | Apache License 2.0 |
src/Day02.kt | greg-burgoon | 573,074,283 | false | {"Kotlin": 120556} | import java.util.*
fun main() {
val conclusionMap = mapOf(
"A X" to 3,
"A Y" to 6,
"A Z" to 0,
"B X" to 0,
"B Y" to 3,
"B Z" to 6,
"C X" to 6,
"C Y" to 0,
"C Z" to 3
)
val winLoseDrawMap = mapOf(
"A X" to "A Z",
"A Y" to "A X",
"A Z" to "A Y",
"B X" to "B X",
"B Y" to "B Y",
"B Z" to "B Z",
"C X" to "C Y",
"C Y" to "C Z",
"C Z" to "C X"
)
val moveMap = mapOf(
"X" to 1,
"Y" to 2,
"Z" to 3
)
fun part1(input: String): Int {
val lines = input.split("\n")
val winValues = lines.stream().map {
val move = it.split(" ").get(1)
conclusionMap.getOrDefault(it, 0).plus(moveMap.getOrDefault(move, 0))
}.toList().sum()
return winValues
}
fun part2(input: String): Int {
val lines = input.split("\n")
val winValues = lines.stream().map {
winLoseDrawMap.getOrDefault(it, "")
}.map {
val move = it.split(" ").get(1)
conclusionMap.getOrDefault(it, 0).plus(moveMap.getOrDefault(move, 0))
}.toList().sum()
return winValues
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 74f10b93d3bad72fa0fc276b503bfa9f01ac0e35 | 1,499 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-12.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2015
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputText
fun main() {
val input = readInputText(2015, "12-input")
val test1 = readInputText(2015, "12-test1")
val test2 = readInputText(2015, "12-test2")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test2).println()
part2(input).println()
}
private fun part1(input: String): Int {
val (json, rest) = parseJson(input)
assert(rest == input.length)
return json.sum()
}
private fun part2(input: String): Int {
val (json, rest) = parseJson(input)
assert(rest == input.length)
return json.sumWithoutRed()
}
private sealed class Json {
abstract fun sum(): Int
abstract fun sumWithoutRed(): Int
class Array(val array: List<Json>) : Json() {
override fun sum() = array.sumOf { it.sum() }
override fun sumWithoutRed() = array.sumOf { it.sumWithoutRed() }
}
class Object(val map: Map<String, Json>) : Json() {
override fun sum() = map.values.sumOf { it.sum() }
override fun sumWithoutRed(): Int {
val hasRed = map.values.any { it is String && it.value == "red" }
return if (hasRed) 0 else map.values.sumOf { it.sumWithoutRed() }
}
}
class Number(val value: Int) : Json() {
override fun sum() = value
override fun sumWithoutRed() = value
}
class String(val value: kotlin.String) : Json() {
override fun sum() = 0
override fun sumWithoutRed() = 0
}
}
private fun parseJson(input: String, from: Int = 0): Pair<Json, Int> {
val numRegex = """-?\d+""".toRegex()
var position = from
when (input[position]) {
'"' -> {
val endIndex = input.indexOf('"', position + 1)
return Json.String(input.substring(from + 1 until endIndex)) to endIndex + 1
}
'[' -> {
val list = mutableListOf<Json>()
position++
while (input[position] != ']') {
val (item, rest) = parseJson(input, position)
list += item
position = if (input[rest] == ',') rest + 1 else rest
}
return Json.Array(list) to position + 1
}
'{' -> {
val map = mutableMapOf<Json.String, Json>()
position++
while (input[position] != '}') {
val (key, rest1) = parseJson(input, position)
val (value, rest2) = parseJson(input, rest1 + 1)
map[key as Json.String] = value
position = if (input[rest2] == ',') rest2 + 1 else rest2
}
return Json.Object(map) to position + 1
}
else -> {
val match = numRegex.matchAt(input, position)!!
return Json.Number(match.value.toInt()) to position + match.value.length
}
}
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 3,003 | advent-of-code | MIT License |
jvm/src/main/kotlin/io/prfxn/aoc2021/day20.kt | prfxn | 435,386,161 | false | {"Kotlin": 72820, "Python": 362} | // Trench Map (https://adventofcode.com/2021/day/20)
package io.prfxn.aoc2021
fun main() {
val lines = textResourceReader("input/20.txt").readLines()
val ieAlgo = lines.take(1).first()
val litMap =
lines.drop(2).flatMapIndexed { r, line ->
line.mapIndexed { c, char ->
Triple(0, r, c) to (char == '#')
}
}.toMap().toMutableMap()
fun isLit(step: Int, r: Int, c: Int): Boolean =
Triple(step, r, c).let { key ->
if (step == 0) litMap[key] ?: false
else
litMap.getOrPut(Triple(step, r, c)) {
ieAlgo[
Integer.parseInt(
(r - 1..r + 1).flatMap { r1 ->
(c - 1..c + 1).map { c1 ->
if (isLit(step - 1, r1, c1)) "1"
else "0"
}
}.joinToString(""),
2
)
] == '#'
}
}
fun count(step: Int, rows: IntRange, cols: IntRange) =
rows.flatMap { r -> cols.map { c -> isLit(step, r, c) } }.count { it }
fun Int.toRange() = (this..this)
fun countLitPixels(numEnhancements: Int): Int {
fun count(rows: IntRange, cols: IntRange) = count(numEnhancements, rows, cols)
val rows0 = (-numEnhancements until lines.drop(2).size + numEnhancements)
val cols0 = (-numEnhancements until lines.drop(2).first().length + numEnhancements)
return generateSequence(Triple(rows0, cols0, count(rows0, cols0))) { (rows, cols, count) ->
val rows1 = (rows.first - 1 .. rows.last + 1)
val cols1 = (cols.first - 1 .. cols.last + 1)
Triple(rows1, cols1, count +
count(rows1.first.toRange(), cols1) + // top row
count(rows1.last.toRange(), cols1) + // bottom row
count(rows, cols1.first.toRange()) + // left col (minus top & bottom rows)
count(rows, cols1.last.toRange())) // right col (minus top & bottom rows)
}.map { it.third }.windowed(2).find { (c1, c2) -> c1 == c2 }!!.first()
}
println(countLitPixels(2)) // answer1
println(countLitPixels(50)) // answer2
}
| 0 | Kotlin | 0 | 0 | 148938cab8656d3fbfdfe6c68256fa5ba3b47b90 | 2,365 | aoc2021 | MIT License |
src/pl/shockah/aoc/y2015/Day15.kt | Shockah | 159,919,224 | false | null | package pl.shockah.aoc.y2015
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import pl.shockah.aoc.AdventTask
import pl.shockah.aoc.parse6
import java.util.regex.Pattern
import kotlin.math.max
class Day15: AdventTask<List<Day15.Ingredient>, Int, Int>(2015, 15) {
private val inputPattern: Pattern = Pattern.compile("(.*): capacity (-?\\d+), durability (-?\\d+), flavor (-?\\d+), texture (-?\\d+), calories (-?\\d+)")
data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
)
override fun parseInput(rawInput: String): List<Ingredient> {
return rawInput.lines().map {
val (name, capacity, durability, flavor, texture, calories) = inputPattern.parse6<String, Int, Int, Int, Int, Int>(it)
return@map Ingredient(name, capacity, durability, flavor, texture, calories)
}.sortedByDescending { it.capacity + it.durability + it.flavor + it.texture }
}
private fun getTotalCost(ingredients: Map<Ingredient, Int>): Int {
val capacity = ingredients.entries.sumOf { (ingredient, amount) -> ingredient.capacity * amount }
val durability = ingredients.entries.sumOf { (ingredient, amount) -> ingredient.durability * amount }
val flavor = ingredients.entries.sumOf { (ingredient, amount) -> ingredient.flavor * amount }
val texture = ingredients.entries.sumOf { (ingredient, amount) -> ingredient.texture * amount }
return max(capacity, 0) * max(durability, 0) * max(flavor, 0) * max(texture, 0)
}
private fun getCalories(ingredients: Map<Ingredient, Int>): Int {
return ingredients.entries.sumOf { (ingredient, amount) -> ingredient.calories * amount }
}
private fun findBestIngredients(input: List<Ingredient>, current: Map<Ingredient, Int>, spoonsLeft: Int, calories: Int?): Map<Ingredient, Int>? {
if (input.isEmpty())
return current
val ingredient = input.first()
val newInput = input.subList(1, input.size)
val range = if (input.size == 1) (spoonsLeft..spoonsLeft) else (0..spoonsLeft)
var results = range.mapNotNull { findBestIngredients(newInput, current + (ingredient to it), spoonsLeft - it, calories) }
if (calories != null)
results = results.filter { getCalories(it) == calories }
return results.maxByOrNull { getTotalCost(it) }
}
override fun part1(input: List<Ingredient>): Int {
return getTotalCost(findBestIngredients(input, mapOf(), 100, null)!!)
}
override fun part2(input: List<Ingredient>): Int {
return getTotalCost(findBestIngredients(input, mapOf(), 100, 500)!!)
}
class Tests {
private val task = Day15()
private val rawInput = """
Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3
""".trimIndent()
@Test
fun part1() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(62842880, task.part1(input))
}
@Test
fun part2() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(57600000, task.part2(input))
}
}
} | 0 | Kotlin | 0 | 0 | 9abb1e3db1cad329cfe1e3d6deae2d6b7456c785 | 3,061 | Advent-of-Code | Apache License 2.0 |
src/Day07_alt2.kt | zodiia | 573,067,225 | false | {"Kotlin": 11268} | package day07alt2
import readInput
fun main() {
fun parseFiles(input: List<String>): List<Long> {
val dirs = HashMap<String, Long>().also { it["/"] = 0L }
var cwd = "/"
input.forEach { line ->
if (line.startsWith("$ cd ")) {
cwd = when (line.substring(5)) {
"/" -> "/"
".." -> "${cwd.split('/').dropLast(2).joinToString("/")}/"
else -> "${cwd}${line.substring(5)}/"
}
} else if (!line.startsWith("$")) {
val parts = line.split(' ')
if (parts[0] == "dir") {
dirs["${cwd}${parts[1]}/"] = 0L
} else {
val cwdParts = cwd.split('/')
for (i in 1 until cwdParts.size) {
val path = "${cwdParts.take(i).joinToString("/")}/"
dirs[path] = (dirs[path] ?: 0L) + parts[0].toLong()
}
}
}
}
return dirs.map { it.value }
}
fun part1(input: List<String>) = parseFiles(input).filter { it <= 100000 }.sum()
fun part2(input: List<String>): Long {
val dirs = parseFiles(input)
return dirs.fold(Long.MAX_VALUE) { cur, it -> if (it >= dirs.max() - 40000000 && it < cur) it else cur }
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 4f978c50bb7603adb9ff8a2f0280f8fdbc652bf2 | 1,454 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day9.kt | Gitvert | 725,292,325 | false | {"Kotlin": 97000} | fun day9 (lines: List<String>) {
val valueHistories = parseOasisInput(lines)
var sum = 0L
var sum2 = 0L
valueHistories.forEach {
sum += findExtrapolatedValue(it)
sum2 += findBackwardsExtrapolatedValue(it)
}
println("Day 9 part 1: $sum")
println("Day 9 part 2: $sum2")
println()
}
fun findBackwardsExtrapolatedValue(numbers: List<Long>): Long {
val sequences = buildExtrapolatedTree(numbers)
val reversedSequences = sequences.map { it.reversed().toMutableList() }
for (i in 0..<reversedSequences.size-1) {
reversedSequences[i + 1].add(reversedSequences[i + 1].last() - reversedSequences[i].last())
}
return reversedSequences.last().last()
}
fun findExtrapolatedValue(numbers: List<Long>): Long {
val sequences = buildExtrapolatedTree(numbers)
for (i in 0..<sequences.size-1) {
sequences[i + 1].add(sequences[i + 1].last() + sequences[i].last())
}
return sequences.last().last()
}
fun buildExtrapolatedTree(numbers: List<Long>): List<MutableList<Long>> {
val sequences = mutableListOf<MutableList<Long>>()
sequences.add(numbers.toMutableList())
while (!sequences.last().all { it == 0L }) {
val nextSequence = mutableListOf<Long>()
for (i in 0..<sequences.last().size-1) {
nextSequence.add(sequences.last()[i+1] - sequences.last()[i])
}
sequences.add(nextSequence)
}
sequences.removeLast()
return sequences.reversed()
}
fun parseOasisInput(lines: List<String>): List<List<Long>> {
return lines.map { line -> line.split(" ").map { it.toLong() } }
} | 0 | Kotlin | 0 | 0 | f204f09c94528f5cd83ce0149a254c4b0ca3bc91 | 1,655 | advent_of_code_2023 | MIT License |
src/Day01.kt | martintomac | 726,272,603 | false | {"Kotlin": 19489} | fun main() {
val valueToWords = mapOf(
1 to listOf("1", "one"),
2 to listOf("2", "two"),
3 to listOf("3", "three"),
4 to listOf("4", "four"),
5 to listOf("5", "five"),
6 to listOf("6", "six"),
7 to listOf("7", "seven"),
8 to listOf("8", "eight"),
9 to listOf("9", "nine"),
)
val wordToValue = valueToWords.invert()
fun String.extractCalibrationValue(): Int {
val first = findAnyOf(wordToValue.keys)!!.second.let { wordToValue[it]!! }
val last = findLastAnyOf(wordToValue.keys)!!.second.let { wordToValue[it]!! }
return first * 10 + last
}
fun machine(input: List<String>): Int {
return input.sumOf { it.extractCalibrationValue() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
machine(testInput).println()
val input = readInput("Day01")
machine(input).println()
}
private fun <K, V> Map<K, Collection<V>>.invert(): Map<V, K> =
asSequence()
.flatMap { (key, values) -> values.map { it to key } }
.toMap()
| 0 | Kotlin | 0 | 0 | dc97b23f8461ceb9eb5a53d33986fb1e26469964 | 1,148 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2018/Day07.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2018
import se.saidaspen.aoc.util.*
fun main() {
Day07.run()
}
object Day07 : Day(2018, 7) {
override fun part1(): Any {
val dependencies = input.lines().filter { it.isNotBlank() }.map { P(it.split(" ")[1], it.split(" ")[7]) }.toList()
val map = dependencies.map { mutableListOf(it.first, it.second) }.flatten().distinct().map { P(it, mutableListOf<String>()) }.toMap().toMutableMap()
val visited = mutableListOf<String>()
for (d in dependencies) {
val children = map.getOrPut(d.first) {mutableListOf()}
children.add(d.second)
}
while(map.isNotEmpty()) {
val available = map.keys.filter { !map.values.flatten().contains(it) }.sorted()
val visit = available.first()
visited.add(visit)
map.remove(visit)
}
return visited.joinToString("")
}
override fun part2(): Any {
val dependencies = input.lines().filter { it.isNotBlank() }.map { P(it.split(" ")[1], it.split(" ")[7]) }.toList()
val map = dependencies.map { mutableListOf(it.first, it.second) }.flatten().distinct().map { P(it, mutableListOf<String>()) }.toMap().toMutableMap()
for (d in dependencies) {
val children = map.getOrPut(d.first) {mutableListOf()}
children.add(d.second)
}
var t = -1
val workers = mutableMapOf<String, Int>()
while(map.isNotEmpty() || workers.isNotEmpty()) {
t++
val finished = workers.toList().filter { it.second == t }.map { it.first }
finished.forEach{
workers.remove(it)
map.remove(it)
}
val available = map.keys.filter { !map.values.flatten().contains(it) }.sorted().toMutableList()
workers.toList().map { it.first }.forEach{available.remove(it)}
val availableWorkers = 5 - workers.size
val visit = available.take(availableWorkers)
for (n in visit) {
workers[n] = t + (n.toCharArray().first() - 'A') + 1 + 60
}
}
return t
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,166 | adventofkotlin | MIT License |
src/main/kotlin/dp/MaxWeightUnrootedTree.kt | yx-z | 106,589,674 | false | null | package dp
import graph.core.*
import util.max
// given an unrooted tree T, that is, connected acyclic undirected graphs,
// 1. let the edges in T be weighed (either > 0, 0, or < 0)
// find a path with largest weight
fun WeightedGraph<Int, Int>.maxWeight() =
vertices.map { maxWeight(it, init()) }.max() ?: 0
fun WeightedGraph<Int, Int>.init(): HashMap<Vertex<Int>, Boolean> {
val map = HashMap<Vertex<Int>, Boolean>()
vertices.forEach { map[it] = false }
return map
}
fun WeightedGraph<Int, Int>.maxWeight(v: Vertex<Int>,
map: HashMap<Vertex<Int>, Boolean>): Int {
map[v] = true
var max = 0
getEdgesOf(v).forEach { (s, e, _, data) ->
val u = if (s === v) e else s
if (map[u] == false) {
max = max(max, this.maxWeight(u, map) + (data ?: 0))
}
}
return max
}
// 2. let the weight be in vertices (unweighted edges)
// find a path with max weight
fun Graph<Int>.maxWeight() =
vertices.map { maxWeight(it, init()) }.max() ?: 0
fun Graph<Int>.init(): HashMap<Vertex<Int>, Boolean> {
val map = HashMap<Vertex<Int>, Boolean>()
vertices.forEach { map[it] = false }
return map
}
fun Graph<Int>.maxWeight(v: Vertex<Int>, map: HashMap<Vertex<Int>, Boolean>): Int {
map[v] = true
var max = 0
getEdgesOf(v).forEach { (s, e) ->
val u = if (s === v) e else s
if (map[u] == false) {
max = max(max, this.maxWeight(u, map))
}
}
return max + v.data
}
fun main(args: Array<String>) {
val vertices = (1..6).map { Vertex(it) }
val edges = setOf(
WeightedEdge(vertices[0], vertices[1], weight = -1),
WeightedEdge(vertices[1], vertices[2], weight = 3),
WeightedEdge(vertices[2], vertices[3], weight = -2),
WeightedEdge(vertices[3], vertices[4], weight = 3),
WeightedEdge(vertices[3], vertices[5], weight = 0))
val T = WeightedGraph(vertices, edges)
// println(T.maxWeight())
val v = (1..3).map { Vertex(it - 2) }
val e = setOf(
Edge(v[0], v[1])
)
val g = Graph(v, e)
println(g.maxWeight())
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,985 | AlgoKt | MIT License |
src/main/kotlin/com/ginsberg/advent2020/Day11.kt | tginsberg | 315,060,137 | false | null | /*
* Copyright (c) 2020 by <NAME>
*/
/**
* Advent of Code 2020, Day 11 - Seating System
* Problem Description: http://adventofcode.com/2020/day/11
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day11/
*/
package com.ginsberg.advent2020
typealias Seats = Array<CharArray>
typealias Seat = Pair<Int, Int>
class Day11(input: List<String>) {
private val seats: Seats = input.map { it.toCharArray() }.toTypedArray()
fun solvePart1(): Int =
findStableMap(4, this::countImmediateNeighbors)
fun solvePart2(): Int =
findStableMap(5, this::countFarNeighbors)
private fun findStableMap(tolerance: Int, countFunction: (Seats, Seat) -> Int): Int =
generateSequence(seats) { it.next(tolerance, countFunction) }
.zipWithNext()
.first { it.first.contentDeepEquals(it.second) }
.first
.occupied()
private fun Seats.next(tolerance: Int, countFunction: (Seats, Seat) -> Int): Seats =
this.mapIndexed { x, row ->
row.mapIndexed { y, spot ->
val occupied = countFunction(this, Seat(x, y))
when {
spot == 'L' && occupied == 0 -> '#'
spot == '#' && occupied >= tolerance -> 'L'
else -> spot
}
}.toCharArray()
}.toTypedArray()
private fun countImmediateNeighbors(seats: Seats, seat: Seat): Int =
neighbors
.map { it + seat }
.filter { it in seats }
.count { seats[it.first][it.second] == '#' }
private fun countFarNeighbors(seats: Seats, seat: Seat): Int =
neighbors
.mapNotNull { findSeatOnVector(seats, seat, it) }
.count { it == '#' }
private fun findSeatOnVector(seats: Seats, seat: Seat, vector: Seat): Char? =
generateSequence(seat + vector) { it + vector }
.map { if (it in seats) seats[it.first][it.second] else null }
.first { it == null || it != '.' }
private fun Seats.occupied(): Int =
this.sumBy { it.count { row -> row == '#' } }
private operator fun Seats.contains(seat: Seat): Boolean =
seat.first in this.indices && seat.second in this.first().indices
private operator fun Seat.plus(that: Seat): Seat =
Seat(this.first + that.first, this.second + that.second)
companion object {
// @formatter:off
private val neighbors = sequenceOf(
-1 to -1, -1 to 0, -1 to 1,
0 to -1, 0 to 1,
1 to -1, 1 to 0, 1 to 1
)
// @formatter:on
}
}
| 0 | Kotlin | 2 | 38 | 75766e961f3c18c5e392b4c32bc9a935c3e6862b | 2,660 | advent-2020-kotlin | Apache License 2.0 |
src/Day12.kt | wlghdu97 | 573,333,153 | false | {"Kotlin": 50633} | import java.util.*
private class Graph constructor(
private val width: Int,
private val height: Int,
private val startPos: Position,
private val endPos: Position,
private val heightArray: Array<IntArray>
) : Iterable<Int> {
private val edges = hashMapOf<Int, MutableSet<Int>>()
init {
require(heightArray.size == height && heightArray.all { it.size == width })
calculateEdges()
}
fun calculateEdges() {
heightArray.forEachIndexed { y, row ->
row.forEachIndexed { x, h ->
val source = nodeIndexFor(x, y)
val edges = edges[source] ?: mutableSetOf()
if ((y - 1) >= 0 && heightArray[y - 1][x] - 1 <= h) {
edges += nodeIndexFor(x, y - 1)
}
if ((y + 1) < height && heightArray[y + 1][x] - 1 <= h) {
edges += nodeIndexFor(x, y + 1)
}
if ((x - 1) >= 0 && heightArray[y][x - 1] - 1 <= h) {
edges += nodeIndexFor(x - 1, y)
}
if ((x + 1) < width && heightArray[y][x + 1] - 1 <= h) {
edges += nodeIndexFor(x + 1, y)
}
this.edges[source] = edges
}
}
}
fun dijkstra(start: Int, end: Int = nodeIndexFor(endPos.x, endPos.y)): Int {
return dijkstra(Position(start % width, start / width), Position(end % width, end / width))
}
fun dijkstra(start: Position = startPos, end: Position = endPos): Int {
val size = width * height
val dist = IntArray(size) { INFINITY }
val prev = IntArray(size) { UNDEFINED }
val queue: Queue<Int> = LinkedList((0 until size).toList())
dist[nodeIndexFor(start.x, start.y)] = 0
while (queue.isNotEmpty()) {
val u = queue.minBy { dist[it] }
queue.remove(u)
for (neighbor in edges[u] ?: emptySet()) {
if (!queue.contains(neighbor)) {
continue
}
val alt = dist[u] + 1
if (alt < dist[neighbor]) {
dist[neighbor] = alt
prev[neighbor] = u
}
}
}
return dist[nodeIndexFor(end.x, end.y)]
}
override fun iterator(): Iterator<Int> {
return heightArray.flatMap { it.asIterable() }.iterator()
}
private fun nodeIndexFor(x: Int, y: Int): Int {
return x + (y * width)
}
data class Position(val x: Int, val y: Int)
companion object {
private const val INFINITY = Int.MAX_VALUE
private const val UNDEFINED = -1
}
}
/**
* a : 0, z :25
*/
private fun parseGraph(input: List<String>): Graph {
require(input.isNotEmpty())
val width = input.first().length
val height = input.size
val heightArray = Array(height) { IntArray(width) { -1 } }
var startPos: Graph.Position? = null
var endPos: Graph.Position? = null
input.forEachIndexed { y, str ->
str.toCharArray().forEachIndexed { x, c ->
when (c) {
'S' -> {
startPos = Graph.Position(x, y)
heightArray[y][x] = 0
}
'E' -> {
endPos = Graph.Position(x, y)
heightArray[y][x] = 25
}
in 'a'..'z' -> {
heightArray[y][x] = c.code - 97
}
}
}
}
return Graph(width, height, startPos!!, endPos!!, heightArray)
}
fun main() {
fun part1(input: List<String>): Int {
return parseGraph(input).dijkstra()
}
fun part2(input: List<String>): Int {
val graph = parseGraph(input)
val startingPointCandidateIndices = graph.mapIndexedNotNull { index, height ->
if (height == 0) {
index
} else {
null
}
}
return startingPointCandidateIndices.map { graph.dijkstra(it) }
.filter { it > 0 }
.min()
}
val testInput = readInput("Day12-Test01")
val input = readInput("Day12")
println(part1(testInput))
println(part1(input))
println(part2(testInput))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2b95aaaa9075986fa5023d1bf0331db23cf2822b | 4,335 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day3/Day3.kt | Jessevanbekkum | 112,612,571 | false | null | package day3
import java.lang.Math.abs
import java.lang.Math.sqrt
fun ringSize(ring: Int): Int {
if (ring == 0) {
return 1;
}
return ((ring - 1) * 2 + 1) * 4 + 4
}
fun middles(ring: Int): List<Int> {
var diff = 2 * ring;
val first = squareSize(ring - 1) + ring
return listOf(first, first + diff, first + 2 * diff, first + 3 * diff)
}
fun squareSize(ring: Int): Int {
return (ring * 2 + 1) * (ring * 2 + 1)
}
fun path(input: Int): Int {
var i = myRing(input)
return middles(i).map { v -> abs(input - v) }.min()!! + i
}
private fun myRing(input: Int): Int {
var i = 0;
while (squareSize(i) <= input) {
i++;
}
return i
}
fun getCoordinates(input: Int): Pair<Int, Int> {
val biggerSquare = (0..1000).map { i -> i * 2 + 1 }.map { i -> i * i }.first { sq -> sq >= input }
val r = (sqrt(biggerSquare.toDouble()).toInt() - 1) / 2;
var x: Int = r
var y = -1 * x;
var current = biggerSquare;
while (current != input) {
current--;
if (y == -r && x==r) {
x--;
continue
}
if (x == r) {
y--
continue
}
if (y == r) {
x++;
continue
}
if (x == -r) {
y++
continue
}
if (y == -r) {
x--;
continue
}
}
return Pair(x, y);
}
fun neighbours(input: Int): List<Pair<Int, Int>> {
if (input == 0) {
return emptyList()
}
val coor = getCoordinates(input);
return listOf(
Pair(coor.first-1, coor.second),
Pair(coor.first-1, coor.second-1),
Pair(coor.first, coor.second-1),
Pair(coor.first+1, coor.second-1),
Pair(coor.first+1, coor.second),
Pair(coor.first+1, coor.second+1),
Pair(coor.first, coor.second+1),
Pair(coor.first-1, coor.second+1)
)
}
fun firstLarger(input: Int) :Int {
val grid = mutableMapOf< Pair<Int, Int>, Int>()
(1..input).forEach { grid.put( getCoordinates(it), it) }
val mem = mutableListOf<Int>(1)
var i = 2;
while (mem.last() < input) {
val neigh = neighbours(i);
val sum = neigh
.map { s -> grid.get(s) }
.filterNotNull()
.map {j -> mem.getOrElse(j-1){0} }
.sum()
mem.add(sum)
i++
}
return mem.last()
} | 0 | Kotlin | 0 | 0 | 1340efd354c61cd070c621cdf1eadecfc23a7cc5 | 2,430 | aoc-2017 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2021/day16/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2021.day16
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
readInput(2021, 16).forEachLine { line ->
val input = line.map { it.digitToInt(16).toString(2).padStart(4, '0') }.joinToString("")
val packet = parse(input)
println(packet.versionSum())
println(packet.evaluate())
}
}
sealed interface Packet {
val version: Int
fun versionSum(): Int
fun evaluate(): Long
class Literal(
override val version: Int,
private val value: Long
) : Packet {
override fun versionSum() = version
override fun evaluate() = value
}
class Expression(
override val version: Int,
private val operator: (List<Packet>) -> Long,
private val subPackets: List<Packet>
) : Packet {
override fun versionSum() = version + subPackets.sumOf(Packet::versionSum)
override fun evaluate() = operator.invoke(subPackets)
}
}
fun parse(input: String): Packet {
fun parse(reader: StringReader): Packet {
val version = reader.readBinary(3)
when (val typeId = reader.readBinary(3)) {
4 -> {
val number = buildString {
while (true) {
val sub = reader.read(5)
append(sub.substring(1))
if (sub[0] == '0') break
}
}.toLong(2)
return Packet.Literal(version, number)
}
else -> {
val subPackets = arrayListOf<Packet>()
if (reader.readBinary(1) == 0) {
val subPacketLength = reader.readBinary(15)
val start = reader.index
while (reader.index - start < subPacketLength) subPackets.add(parse(reader))
} else {
val subPacketCount = reader.readBinary(11)
repeat(subPacketCount) { subPackets.add(parse(reader)) }
}
val operator: (List<Packet>) -> Long = { packets ->
when (typeId) {
0 -> packets.sumOf { it.evaluate() }
1 -> packets.fold(1L) { acc, packet -> acc * packet.evaluate() }
2 -> packets.minOf { it.evaluate() }
3 -> packets.maxOf { it.evaluate() }
5 -> if (packets[0].evaluate() > packets[1].evaluate()) 1 else 0
6 -> if (packets[0].evaluate() < packets[1].evaluate()) 1 else 0
7 -> if (packets[0].evaluate() == packets[1].evaluate()) 1 else 0
else -> error("Invalid operator")
}
}
return Packet.Expression(version, operator, subPackets)
}
}
}
return parse(StringReader(input))
}
class StringReader(private val string: String) {
var index = 0
fun read(size: Int): String {
val result = string.substring(index, index + size)
index += size
return result
}
}
fun StringReader.readBinary(size: Int): Int = read(size).toInt(2)
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 3,212 | adventofcode | Apache License 2.0 |
day-17/src/main/kotlin/TrickShot.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | import kotlin.system.measureTimeMillis
fun main() {
val partOneMillis = measureTimeMillis {
println("Part One Solution: ${partOne()}")
}
println("Part One Solved in: $partOneMillis ms")
val partTwoMillis = measureTimeMillis {
println("Part Two Solution: ${partTwo()}")
}
println("Part Two Solved in: $partTwoMillis ms")
}
typealias Point = Pair<Int, Int>
typealias Velocity = Pair<Int, Int>
private fun partOne(): Int {
val (xRange, yRange) = readRanges()
var highest = Point(Int.MIN_VALUE, Int.MIN_VALUE)
val start = Point(0, 0)
for (x in 0..xRange.last) {
for (y in yRange.first..200) {
val initial = Velocity(x, y)
findHighestPointOfHittingTrajectory(start, initial, xRange, yRange, highest)?.let {
if (it.second > highest.second) highest = it
}
}
}
return highest.second
}
private fun partTwo(): Int {
val (xRange, yRange) = readRanges()
var count = 0
val start = Point(0, 0)
for (x in 0..xRange.last) {
for (y in yRange.first..200) {
val initial = Velocity(x, y)
if (isHittingTrajectory(start, initial, xRange, yRange)) {
count++
}
}
}
return count
}
private tailrec fun findHighestPointOfHittingTrajectory(
point: Point,
velocity: Velocity,
xRange: IntRange,
yRange: IntRange,
high: Point
): Point? {
val highest = if (point.second > high.second) point else high
if (point.first in xRange && point.second in yRange) {
return highest
}
// Out of horizontal range: will never be able to get back in it since horizontal velocity is always >= 0
if (point.first > xRange.last) {
return null
}
// Stopped on horizontal axis and out of range
if (velocity.first == 0 && point.first !in xRange) {
return null
}
// Out of vertical range and with velocity in opposite direction of range
if (point.second < yRange.first && velocity.second < 1) {
return null
}
val nextPoint = Point(point.first + velocity.first, point.second + velocity.second)
val nextVelocity = Velocity(if (velocity.first == 0) 0 else velocity.first - 1, velocity.second - 1)
return findHighestPointOfHittingTrajectory(nextPoint, nextVelocity, xRange, yRange, highest)
}
private fun isHittingTrajectory(point: Point, velocity: Velocity, xRange: IntRange, yRange: IntRange): Boolean {
return findHighestPointOfHittingTrajectory(point, velocity, xRange, yRange, point) != null
}
private fun readRanges(): Pair<IntRange, IntRange> {
val regex = Regex(".*(x=[0-9/.]+).*(y=[0-9/.-]+)")
val input = readInputLines()[0]
val groups = regex.matchEntire(input)!!.groups
val (x0, x1) = groups[1]!!.value.substring(2).split("..").map { it.toInt() }
val (y0, y1) = groups[2]!!.value.substring(2).split("..").map { it.toInt() }
val xRange = x0..x1
val yRange = if (y0 > y1) y1..y0 else y0..y1
return Pair(xRange, yRange)
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 3,256 | aoc-2021 | MIT License |
Advent-of-Code-2023/src/Day15.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day15"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
/**
* Hash function.
*/
private fun hash(message: String): Int {
return message.fold(0) { acc, c -> ((acc + c.code) * 17) % 256 }
}
/**
* Calculates the hash of each step and sums them up.
*/
private fun part1(input: List<String>): Int {
val steps = input.flatMap { it.split(",") }
return steps.sumOf { step -> hash(step) }
}
private typealias Label = String
private typealias FocalLength = Int
/**
* Places each label inside the box corresponding to its hash. And calculates the focusing power.
*/
private fun part2(input: List<String>): Int {
val steps = input.flatMap { it.split(",") }
val boxes = ArrayList<MutableList<Label>>().apply { repeat(256) { add(mutableListOf()) } }
val focalLengths = hashMapOf<Label, FocalLength>()
for (step in steps) {
if ("=" in step) {
val (label, focalLength) = step.split("=")
val index = hash(label)
if (label !in boxes[index]) {
boxes[index].add(label)
}
focalLengths[label] = focalLength.toInt()
} else {
val label = step.removeSuffix("-")
val index = hash(label)
if (label in boxes[index]) {
boxes[index].remove(label)
}
}
}
var sum = 0
for ((boxNum, box) in boxes.withIndex()) {
for ((slot, label) in box.withIndex()) {
sum += (boxNum + 1) * (slot + 1) * focalLengths[label]!!
}
}
return sum
}
fun main() {
createTestFiles(AOC_DAY)
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 1320
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 145
println("* PART 2: ${part2(testInput)}\t\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 504449" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 262044" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 2,218 | Advent-of-Code-2023 | Apache License 2.0 |
src/Day02.kt | vladislav-og | 573,326,483 | false | {"Kotlin": 27072} | fun main() {
// key value match from left to right: lose, draw, win
val winMapping = mapOf(
Pair("A", "ZXY"), // rock -> scissors, rock, paper
Pair("B", "XYZ"), // paper -> scissors
Pair("C", "YZX"), // scissors -> rock
)
val myMoveScoreMapping = mapOf(
Pair("X", 1), Pair("Y", 2), Pair("Z", 3),
)
fun calculateGamePoints(opponentsMove: String, myMove: String) = winMapping[opponentsMove]!!.indexOf(myMove) * 3
fun extractData(row: String) = row.split(" ")
fun part1(input: List<String>): Int {
var score = 0
for (row in input) {
val (opponentsMove, myMove) = extractData(row)
score += myMoveScoreMapping[myMove]!!
score += calculateGamePoints(opponentsMove, myMove)
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (row in input) {
val (opponentsMove, outcome) = extractData(row)
val myMove = winMapping[opponentsMove]!![myMoveScoreMapping[outcome]!! - 1].toString()
score += myMoveScoreMapping[myMove]!!
score += calculateGamePoints(opponentsMove, myMove)
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
println(part2(testInput))
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b230ebcb5705786af4c7867ef5f09ab2262297b6 | 1,434 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | msernheim | 573,937,826 | false | {"Kotlin": 32820} | import kotlin.math.floor
fun main() {
fun getOperation(operation: String): (ULong) -> ULong {
val parts = operation.split(" ")
if (parts.size == 3) {
if (parts[2] == "old") {
return when (parts[1]) {
"*" -> { x: ULong -> x * x }
"+" -> { x: ULong -> x + x }
else -> { x: ULong -> x }
}
}
return when (parts[1]) {
"*" -> { x: ULong -> x * parts[2].toULong() }
"+" -> { x: ULong -> x + parts[2].toULong() }
else -> { x: ULong -> x }
}
}
return { x: ULong -> x }
}
fun parseMonkeys(input: String): Map<Int, Monkey> {
val monkeys = mutableMapOf<Int, Monkey>()
input.split("Monkey ").forEach { stringMonkey ->
var items = mutableListOf<ULong>()
var operation = { x: ULong -> x }
var test = 1
var targetSuccess = 0
var targetFail = 1
var key = -1
stringMonkey.split("\n").forEach { row ->
when {
row.trim().replace(":", "").toIntOrNull() != null -> {
key = row.trim().replace(":", "").toInt()
}
row.trimStart().startsWith("Starting items: ") -> {
items = row.trimStart().removePrefix("Starting items: ")
.split(", ").map { item -> item.toULong() }.toMutableList()
}
row.trimStart().startsWith("Operation: ") -> {
operation = getOperation(row.trimStart().removePrefix("Operation: new = "))
}
row.trimStart().startsWith("Test: divisible by ") -> {
test = row.trimStart().removePrefix("Test: divisible by ").toInt()
}
row.trimStart().startsWith("If true: ") -> {
targetSuccess = row.trimStart().removePrefix("If true: throw to monkey ").toInt()
}
row.trimStart().startsWith("If false: ") -> {
targetFail = row.trimStart().removePrefix("If false: throw to monkey ").toInt()
}
}
}
if (key != -1) monkeys[key] = Monkey(items, operation, test.toULong(), targetSuccess, targetFail)
}
return monkeys
}
fun part1(input: String): Long {
val monkeys = parseMonkeys(input)
for (i in 1..20) {
for (key in 0 until monkeys.size) {
val currentMonkey = monkeys[key]
currentMonkey!!.items.forEach { item: ULong ->
val newWorry = floor(currentMonkey.inspect(item).toDouble() / 3.0).toULong()
when {
newWorry.mod(currentMonkey.testDivisor)
.toInt() == 0 -> monkeys[currentMonkey.targetSuccess]!!.items.add(newWorry)
else -> monkeys[currentMonkey.targetFail]!!.items.add(newWorry)
}
monkeys[key]!!.nInspections++
}
monkeys[key]!!.items.clear()
}
}
val highest = monkeys.values.maxOfOrNull { monkey -> monkey.nInspections }
val secondHighest = monkeys.values.map { monkey -> monkey.nInspections }.sortedDescending()[1]
return highest!! * secondHighest
}
fun part2(input: String, rounds: Int): Long {
val monkeys = parseMonkeys(input)
val commonD = monkeys.values.map { monk -> monk.testDivisor }.reduce { acc, next -> acc * next }
for (i in 1..rounds) {
for (key in 0 until monkeys.size) {
val currentMonkey = monkeys[key]
currentMonkey!!.items.forEach { item: ULong ->
val newWorry = currentMonkey.inspect(item) % commonD
when {
newWorry.mod(currentMonkey.testDivisor)
.toInt() == 0 -> monkeys[currentMonkey.targetSuccess]!!.items.add(newWorry)
else -> monkeys[currentMonkey.targetFail]!!.items.add(newWorry)
}
monkeys[key]!!.nInspections++
}
monkeys[key]!!.items.clear()
}
}
val highest = monkeys.values.maxOfOrNull { monkey -> monkey.nInspections }
val secondHighest = monkeys.values.map { monkey -> monkey.nInspections }.sortedDescending()[1]
return highest!! * secondHighest
}
val input = readInputAsString("Day11")
val part1 = part1(input)
val part2 = part2(input, 10000)
println("Result part1: $part1")
println("Result part2: $part2")
}
class Monkey(
var items: MutableList<ULong>,
val inspect: (worry: ULong) -> ULong,
val testDivisor: ULong,
val targetSuccess: Int,
val targetFail: Int,
var nInspections: Long = 0L
) {
override fun toString(): String {
return "Monkey(items=$items, inspections=$nInspections)"
}
}
| 0 | Kotlin | 0 | 3 | 54cfa08a65cc039a45a51696e11b22e94293cc5b | 5,200 | AoC2022 | Apache License 2.0 |
src/Day11.kt | Reivax47 | 572,984,467 | false | {"Kotlin": 32685} | import java.math.BigInteger
import kotlin.math.floor
fun main() {
fun createMonkeys(input: List<String>): List<monkeys> {
val reponse = mutableListOf<monkeys>()
var index = 0
while (index < input.size) {
val listsDescription = mutableListOf<String>()
for (i in 0..5) {
listsDescription.add(input[index + i])
}
index += 7
reponse.add(monkeys(listsDescription.toList()))
}
return reponse.toList()
}
fun part1(input: List<String>): Int {
val lesmonkeys = createMonkeys(input)
for (round in 1..20) {
lesmonkeys.forEach { unMonkey ->
while (unMonkey.startingItems.size > 0) {
var items = unMonkey.startingItems[0]
unMonkey.startingItems.removeAt(0)
val operande = if (unMonkey.selfOperande) items else unMonkey.operande
when (unMonkey.operateur) {
"+" -> {
items += operande.toLong()
}
"*" -> {
items *= operande.toLong()
}
}
items = floor(items / 3.0).toLong()
if ((items % unMonkey.modulo).toInt() == 0) {
val leMonkey = lesmonkeys.find { it.numero == unMonkey.monkeyIfTrue }
leMonkey?.startingItems?.add(items)
} else {
val leMonkey = lesmonkeys.find { it.numero == unMonkey.monkeyIfFalse }
leMonkey?.startingItems?.add(items)
}
unMonkey.inspectedItems++
}
}
}
val lesSingesTries = lesmonkeys.sortedByDescending { it.inspectedItems }
return (lesSingesTries[0].inspectedItems * lesSingesTries[1].inspectedItems)
}
fun part2(input: List<String>): BigInteger {
val lesmonkeys = createMonkeys(input)
val plusPetitCommunMultiple = lesmonkeys.map { it.modulo }.reduce { acc, i -> acc * i }
for (round in 1..10000) {
lesmonkeys.forEach { unMonkey ->
while (unMonkey.startingItems.size > 0) {
var items = unMonkey.startingItems[0]
unMonkey.startingItems.removeAt(0)
val operande = if (unMonkey.selfOperande) items else unMonkey.operande
when (unMonkey.operateur) {
"+" -> {
items += operande.toLong()
}
"*" -> {
items *= operande.toLong()
}
}
items %= plusPetitCommunMultiple
if ((items % unMonkey.modulo).toInt() == 0) {
val leMonkey = lesmonkeys.find { it.numero == unMonkey.monkeyIfTrue }
leMonkey?.startingItems?.add(items)
} else {
val leMonkey = lesmonkeys.find { it.numero == unMonkey.monkeyIfFalse }
leMonkey?.startingItems?.add(items)
}
unMonkey.inspectedItems++
}
}
}
val lesSingesTries = lesmonkeys.sortedByDescending { it.inspectedItems }
val prem = lesSingesTries[0].inspectedItems.toBigInteger()
val second = lesSingesTries[1].inspectedItems.toBigInteger()
return prem.multiply(second)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605)
check(part2(testInput) == "2713310158".toBigInteger())
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
class monkeys(description: List<String>) {
var startingItems = mutableListOf<Long>()
var operateur: String = ""
var modulo: Int = 0
var selfOperande: Boolean = false
var operande: Int = 0
var numero = 0
var monkeyIfTrue = 0
var monkeyIfFalse = 0
var inspectedItems: Int = 0
init {
this.numero = description[0].split(" ")[1].split(":")[0].toInt()
val lesItems = description[1].split(":")[1].split(",")
lesItems.forEach { unItem ->
this.startingItems.add(unItem.trim().toLong())
}
val operation = description[2].split(" = ")[1]
this.operateur = operation.substring(4, 5)
val lafin = operation.substring(6)
if (lafin == "old") {
this.selfOperande = true
} else {
this.operande = lafin.toInt()
}
this.modulo = description[3].split("by ")[1].toInt()
this.monkeyIfTrue = description[4].split("to monkey ")[1].toInt()
this.monkeyIfFalse = description[5].split("to monkey ")[1].toInt()
}
}
| 0 | Kotlin | 0 | 0 | 0affd02997046d72f15d493a148f99f58f3b2fb9 | 5,033 | AD2022-01 | Apache License 2.0 |
src/year_2023/day_01/Day01.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2023.day_01
import readInput
object Day01 {
/**
* Calculate the sum of all the calibration values
*/
fun solutionOne(calibrationValues: List<String>): Int {
val values = calibrationValues.map { calibration ->
var first = '0'
var last = '0'
for (i in calibration.indices) {
if (calibration[i].isDigit()) {
first = calibration[i]
break
}
}
for (i in calibration.length - 1 downTo 0) {
if (calibration[i].isDigit()) {
last = calibration[i]
break
}
}
"$first$last".toInt()
}
return values.sum()
}
/**
* Now strings of the words count
*/
fun solutionTwo(calibrationValues: List<String>): Int {
val cleaned = calibrationValues.map { calibration ->
calibration.replace("one", "on1e")
.replace("two", "tw2o")
.replace("three", "thr3ee")
.replace("four", "fou4r")
.replace("five", "fiv5e")
.replace("six", "si6x")
.replace("seven", "se7ven")
.replace("eight", "eig8ht")
.replace("nine", "nin9e")
}
return solutionOne(cleaned)
}
}
fun main() {
val calibrationValues = readInput("year_2023/day_01/Day01.txt")
val solutionOne = Day01.solutionOne(calibrationValues)
println("Solution 1: Sum of all calibration: $solutionOne")
val solutionTwo = Day01.solutionTwo(calibrationValues)
println("Solution 2: Sum of all calibration: $solutionTwo")
}
| 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 1,732 | advent_of_code | Apache License 2.0 |
src/main/kotlin/days/Day12.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
import kotlin.collections.ArrayDeque
class Day12 : Day(12) {
override fun partOne(): Any {
val input = parseInput()
val height = input.height
val (s, e) = input.start to input.end
return findClosestPath(s, e, height) ?: throw IllegalStateException("Couldn't find a way from $s to $e")
}
override fun partTwo(): Any {
val input = parseInput()
val height = input.height
val e = input.end
return height.findAll('a').mapNotNull { findClosestPath(it, e, height) }.minOf { it }
}
private fun Array<CharArray>.findAll(c: Char): List<Point> {
return this.withIndex().flatMap { (row, line) ->
line.withIndex().mapNotNull{ (col, charAt) ->
if (charAt == c) Point(row, col) else null
}
}
}
private fun findClosestPath(from: Point, to: Point, height: Array<CharArray>): Int? {
val (rows, cols) = height.size to height.first().size
val queue = ArrayDeque<Pair<Point, Int>>().apply { add(from to 0) }
val visited = mutableSetOf<Point>().apply { add(from) }
while (queue.isNotEmpty()) {
val (cur, dist) = queue.removeFirst()
if (cur == to) {
return dist
} else {
cur.safeNeighbours(rows, cols).forEach { next ->
if (isClimbable((height at cur) to (height at next)) && next !in visited) {
queue.add(next to dist + 1)
visited.add(next)
}
}
}
}
return null
}
private fun parseInput(): Input {
lateinit var s: Point
lateinit var e: Point
val height = inputList.mapIndexed { row, line ->
line.toCharArray().also {
line.withIndex().find { (_, c) -> c == 'S' }?.let { s = Point(row, it.index) }
line.withIndex().find { (_, c) -> c == 'E' }?.let { e = Point(row, it.index) }
}
}.toTypedArray().also {
it[s.row][s.col] = 'a'
it[e.row][e.col] = 'z'
}
return Input(s, e, height)
}
private fun isClimbable(fromTo: Pair<Char, Char>) = fromTo.let { (from, to) -> from >= to || from + 1 == to }
data class Point(val row: Int, val col: Int) {
fun safeNeighbours(rows: Int, cols: Int): List<Point> {
val dr = listOf(-1, 0, 1 ,0)
val dc = listOf(0, 1, 0 ,-1)
return dr.zip(dc).mapNotNull { (dr, dc) ->
if (row + dr in 0 until rows && col + dc in 0 until cols) Point(row + dr, col + dc)
else null
}
}
}
class Input(val start: Point, val end: Point, val height: Array<CharArray>)
private infix fun Array<CharArray>.at(point: Point) = this[point.row][point.col]
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 2,893 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/Day03.kt | marosseleng | 573,498,695 | false | {"Kotlin": 32754} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { getDuplicateSum(it) }
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { findBadgePriority(it) }
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
fun getPriority(char: Char): Int {
return when (char) {
in 'a'..'z' -> char.code - 96
in 'A'..'Z' -> char.code - 38
else -> 0
}
}
fun findBadgePriority(input: List<String>): Int {
val first = input[0]
val second = input[1]
val third = input[2]
var index = 0
for (candidate in first) {
if (candidate in second && candidate in third) {
return getPriority(candidate)
}
}
return 0
}
fun getDuplicateSum(line: String): Int {
val maxIndex = line.length / 2
var prioritySum = 0
val secondHalf = line.substring(maxIndex)
val firstHalf = line.dropLast(maxIndex)
val alreadyUsedDuplicates = mutableSetOf<Char>()
secondHalf.forEach {
if (it in firstHalf && alreadyUsedDuplicates.add(it)) {
prioritySum += getPriority(it)
}
}
return prioritySum
} | 0 | Kotlin | 0 | 0 | f13773d349b65ae2305029017490405ed5111814 | 1,318 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/year2022/day10/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2022.day10
import io.kotest.matchers.shouldBe
import utils.plusOrMinus
import utils.readInput
fun main() {
val testInput = readInput("10", "test_input")
val realInput = readInput("10", "input")
val cycleEnds = 20..220 step 40
val testRuntime = testInput.asSequence()
.map(::toInstruction)
.fold(
mutableListOf(Register(0, 1, 1)),
::computeRegisterHistory
)
testRuntime.filter { it.cycle in cycleEnds }
.sumOf { it.cycle * it.valueDuringCycle }
.also(::println) shouldBe 13140
val realRuntime = realInput.asSequence()
.map(::toInstruction)
.fold(
mutableListOf(Register(0, 1, 1)),
::computeRegisterHistory
)
realRuntime.filter { it.cycle in cycleEnds }
.sumOf { it.cycle * it.valueDuringCycle }
.let(::println)
testRuntime.asSequence()
.drop(1)
.chunked(40, ::cycleConsoleLine)
.forEach(::println)
println()
realRuntime.asSequence()
.drop(1)
.chunked(40, ::cycleConsoleLine)
.forEach(::println)
}
private sealed interface Instruction {
object Noop : Instruction {
override fun toString() = "Noop"
}
data class Add(val quantity: Int) : Instruction {
override fun toString() = quantity.toString()
}
}
private fun toInstruction(value: String): Instruction = when (value) {
"noop" -> Instruction.Noop
else -> value.takeLastWhile { it != ' ' }.toInt().let(Instruction::Add)
}
data class Register(
val cycle: Int,
val valueDuringCycle: Int,
val valueAfterCycle: Int,
)
private fun computeRegisterHistory(registerHistory: MutableList<Register>, instruction: Instruction) = registerHistory.apply {
val lastState = last()
add(
lastState.copy(
cycle = lastState.cycle + 1,
valueDuringCycle = lastState.valueAfterCycle,
)
)
if (instruction is Instruction.Add) add(
lastState.copy(
cycle = lastState.cycle + 2,
valueDuringCycle = lastState.valueAfterCycle,
valueAfterCycle = lastState.valueAfterCycle + instruction.quantity,
)
)
}
private fun cycleConsoleLine(cycle: List<Register>): String {
return cycle.joinToString(separator = "") {
if ((it.cycle - 1) % 40 in it.valueDuringCycle.plusOrMinus(1)) "█" else " "
}
}
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 2,427 | Advent-of-Code | Apache License 2.0 |
app/src/y2021/day08/Day08SevenSegmentSearch.kt | henningBunk | 432,858,990 | false | {"Kotlin": 124495} | package y2021.day08
import common.Answers
import common.AocSolution
import common.annotations.AoCPuzzle
fun main(args: Array<String>) {
Day08SevenSegmentSearch().solveThem()
Day08WithoutAnalyzingIndividualSegments().solveThem()
}
@AoCPuzzle(2021, 8)
class Day08SevenSegmentSearch : AocSolution {
override val answers = Answers(samplePart1 = 26, samplePart2 = 61229, part1 = 512, part2 = 1091165)
override fun solvePart1(input: List<String>): Any = input
.parseToDisplays()
.flatMap { it.fourDigitOutputValue }
.count {
when (it.length) {
2, 3, 4, 7 -> true
else -> false
}
}
override fun solvePart2(input: List<String>): Any = input
.parseToDisplays()
.sumOf { display -> display.read() }
}
fun List<String>.parseToDisplays(): List<Display> = map { line ->
line.split("|")
.let { (tenUniqueSignalPatterns, fourDigitOutputValue) ->
Display(
tenUniqueSignalPatterns.trim().split(" "),
fourDigitOutputValue.trim().split(" ")
)
}
}
data class Display(
val tenUniqueSignalPatterns: List<String>,
val fourDigitOutputValue: List<String>
) {
private val wiring: Array<Char> = decode(tenUniqueSignalPatterns + fourDigitOutputValue)
fun read(): Int = fourDigitOutputValue
.map { it.getDigit(wiring) }
.joinToString("")
.toInt()
/**
* Decode the wiring by using an array of length 7.
* Each item of the array represents on segment of the 7 segment display
* Each item holds an array of chars, starting with abcdefg, representing all possibilities which code could be decoding this segment
* With few steps one after another we can reduce these possibilities until each item in the array will only contain one code.
* This is the correct wiring.
*
* The indices in the array represent the following segments:
*
* 0
* ┏━━━━━━━┓
* ┃ ┃
* 1 ┃ ┃ 2
* ┃ 3 ┃
* ┣━━━━━━━┫
* ┃ ┃
* 4 ┃ ┃ 5
* ┃ ┃
* ┗━━━━━━━┛
* 6
*
*/
private fun decode(numbers: List<String>): Array<Char> {
val data: List<Array<Char>> = numbers
.map { it.toCharArray().toTypedArray() }
val possibleCandidates: Array<Array<Char>> = Array(7) { arrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g') }
// Distinct Numbers 1, 4 or 7
data.forEach { numberCode: Array<Char> ->
when (numberCode.size) {
2 -> possibleCandidates.narrowDownCandidates(numberCode, 2, 5) // 1
3 -> possibleCandidates.narrowDownCandidates(numberCode, 0, 2, 5) // 7
4 -> possibleCandidates.narrowDownCandidates(numberCode, 1, 3, 2, 5) // 4
}
}
// Five segment numbers 2, 3, or 5
val sharedByFiveSegmentNumbers = data
.filter { it.size == 5 }
.fold(setOf('a', 'b', 'c', 'd', 'e', 'f', 'g')) { rest, next ->
rest.intersect(next.toSet())
}.toTypedArray()
// The shared ones must be the horizontal ones
possibleCandidates.narrowDownCandidates(sharedByFiveSegmentNumbers, 0, 3, 6)
// Six segment numbers 0, 6, 9
val sharedBySixSegmentNumbers: Array<Char> = data
.filter { it.size == 6 }
.map { it.toSet() }
.let { sixSegmentNumbers ->
arrayOf(
sixSegmentNumbers[1].union(sixSegmentNumbers[2]).minus(sixSegmentNumbers[0]).first(),
sixSegmentNumbers[0].union(sixSegmentNumbers[2]).minus(sixSegmentNumbers[1]).first(),
sixSegmentNumbers[0].union(sixSegmentNumbers[1]).minus(sixSegmentNumbers[2]).first(),
)
}
val middleHorizontal: Array<Char> = sharedByFiveSegmentNumbers
.toSet()
.intersect(sharedBySixSegmentNumbers.toSet())
.toTypedArray()
possibleCandidates.narrowDownCandidates(middleHorizontal, 3)
val sharedBySixSegmentNumbersWithoutHorizontal =
sharedBySixSegmentNumbers.filter { it != middleHorizontal.first() }
if (possibleCandidates[2].contains(sharedBySixSegmentNumbersWithoutHorizontal[0]) &&
possibleCandidates[5].contains(sharedBySixSegmentNumbersWithoutHorizontal[0])
) {
// sharedBySixSegmentNumbersWithoutHorizontal[0] must be a 9 because it shares both segments with one
possibleCandidates.narrowDownCandidates(arrayOf(sharedBySixSegmentNumbersWithoutHorizontal[0]), 2)
// sharedBySixSegmentNumbersWithoutHorizontal[1] must be a 6
possibleCandidates.narrowDownCandidates(arrayOf(sharedBySixSegmentNumbersWithoutHorizontal[1]), 4)
} else {
// sharedBySixSegmentNumbersWithoutHorizontal[0] must be a 6 because it shares both segments with one
possibleCandidates.narrowDownCandidates(arrayOf(sharedBySixSegmentNumbersWithoutHorizontal[0]), 4)
// sharedBySixSegmentNumbersWithoutHorizontal[1] must be a 9
possibleCandidates.narrowDownCandidates(arrayOf(sharedBySixSegmentNumbersWithoutHorizontal[1]), 2)
}
// Bottom horizontal is the last one we didn't address, it should be unique though by this time.
return possibleCandidates.map { it.first() }.toCharArray().toTypedArray()
}
private fun String.getDigit(wiring: Array<Char>): Int = when (length) {
2 -> 1
3 -> 7
4 -> 4
7 -> 8
5 -> when { // 2, 3, 5
contains(wiring[1]) -> 5
contains(wiring[4]) -> 2
else -> 3
}
else -> when { // 0, 6, 9
!contains(wiring[3]) -> 0
contains(wiring[2]) -> 9
else -> 6
}
}
/**
* Called on our array for the candidates. Two things happen:
* 1. Only the chars which are given as candidates parameter remain for the given segments.
* 2. The given chars are removed from all other segments
*/
private fun Array<Array<Char>>.narrowDownCandidates(
candidates: Array<Char>,
vararg segments: Int
) {
removeCandidate(candidates.opposite, *segments.toTypedArray().toIntArray())
removeCandidate(candidates, *segments.toList().opposite.toTypedArray().toIntArray())
}
private val Array<Char>.opposite: Array<Char>
get() = "abcdefg".filterNot(::contains).toCharArray().toTypedArray()
private val List<Int>.opposite: List<Int>
get() = (0..6).filterNot { contains(it) }
private fun Array<Array<Char>>.removeCandidate(number: Array<Char>, vararg segments: Int) {
segments.forEach { segment ->
this[segment] = this[segment].filterNot(number::contains).toTypedArray()
}
}
}
| 0 | Kotlin | 0 | 0 | 94235f97c436f434561a09272642911c5588560d | 7,054 | advent-of-code-2021 | Apache License 2.0 |
src/main/java/com/ncorti/aoc2021/Exercise12.kt | cortinico | 433,486,684 | false | {"Kotlin": 36975} | package com.ncorti.aoc2021
import java.util.Stack
object Exercise12 {
private fun getInput(): HashMap<String, MutableList<String>> {
val input =
getInputAsTest("12") { split("\n") }.map { line ->
line.split("-").let { it[0] to it[1] }
}
val world =
hashMapOf(
*input
.flatMap { listOf(it.first, it.second) }
.distinct()
.map { it to mutableListOf<String>() }
.toTypedArray())
input.forEach { (start, end) ->
world[start]?.add(end)
world[end]?.add(start)
}
return world
}
private fun visit(
world: HashMap<String, MutableList<String>>,
visitCriteria: (String, List<String>) -> Boolean
): List<String> {
val next = Stack<List<String>>().apply { push(listOf("start")) }
val visit = mutableListOf<String>()
while (next.isNotEmpty()) {
val curr = next.pop()
val edge = curr.last()
if (edge == "end") {
visit.add(curr.joinToString(","))
} else {
world[edge]?.forEach {
if (visitCriteria(it, curr) || it == "end") {
next.add(curr + it)
}
}
}
}
return visit
}
private fun List<String>.hasASmallCave(): Boolean = this.count { it.isASmallCave() } >= 1
private fun List<String>.hasDuplicatedSmallCave(): Boolean =
this.count { it.isASmallCave() } != this.distinct().count { it.isASmallCave() }
private fun String.isASmallCave(): Boolean =
this != "start" && this != "end" && this.uppercase() != this
private fun String.isABigCave(): Boolean =
this != "start" && this != "end" && this.uppercase() == this
fun part1(): Int =
visit(getInput()) { cave, currentSeen ->
(cave.isASmallCave() && cave !in currentSeen) ||
(cave.isASmallCave() && !currentSeen.hasASmallCave()) ||
cave.isABigCave()
}
.size
fun part2(): Int =
visit(getInput()) { cave, currentSeen ->
(cave.isASmallCave() && cave !in currentSeen) ||
(cave.isASmallCave() && !currentSeen.hasDuplicatedSmallCave()) ||
cave.isABigCave()
}
.size
}
fun main() {
println(Exercise12.part1())
println(Exercise12.part2())
}
| 0 | Kotlin | 0 | 4 | af3df72d31b74857201c85f923a96f563c450996 | 2,562 | adventofcode-2021 | MIT License |
src/org/aoc2021/Day22.kt | jsgroth | 439,763,933 | false | {"Kotlin": 86732} | package org.aoc2021
import java.nio.file.Files
import java.nio.file.Path
import kotlin.math.max
import kotlin.math.min
private fun IntRange.size(): Int {
return if (this.last >= this.first) {
this.last - this.first + 1
} else {
0
}
}
object Day22 {
data class Cube(val x: IntRange, val y: IntRange, val z: IntRange) {
fun volume(): Long {
return x.size().toLong() * y.size() * z.size()
}
fun intersect(other: Cube): Cube {
if (x.first > other.x.last ||
x.last < other.x.first ||
y.first > other.y.last ||
y.last < other.y.first ||
z.first > other.z.last ||
z.last < other.z.first) {
return Cube(IntRange.EMPTY, IntRange.EMPTY, IntRange.EMPTY)
}
val minX = max(x.first, other.x.first)
val maxX = min(x.last, other.x.last)
val minY = max(y.first, other.y.first)
val maxY = min(y.last, other.y.last)
val minZ = max(z.first, other.z.first)
val maxZ = min(z.last, other.z.last)
return Cube(minX..maxX, minY..maxY, minZ..maxZ)
}
}
data class Step(val on: Boolean, val cube: Cube)
private fun solve(lines: List<String>, shouldBound: Boolean): Long {
val steps = parseSteps(lines).let { if (shouldBound) boundCubes(it) else it }
val cubes = steps.map(Step::cube)
var totalVolume = 0L
steps.forEachIndexed { i, step ->
val flippedVolume = computeFlippedVolume(steps.subList(0, i), step)
if (step.on) {
totalVolume += flippedVolume
totalVolume += computeNonIntersectingVolume(cubes.subList(0, i), step.cube)
} else {
totalVolume -= flippedVolume
}
}
return totalVolume
}
private fun parseSteps(lines: List<String>): List<Step> {
return lines.map { line ->
val (onString, rest) = line.split(" ")
val (xRange, yRange, zRange) = rest.split(",").map { rangeString ->
rangeString.substring(2).split("..").let { it[0].toInt()..it[1].toInt() }
}
Step(onString == "on", Cube(xRange, yRange, zRange))
}
}
private fun boundCubes(steps: List<Step>): List<Step> {
return steps.map { step ->
val (x, y, z) = step.cube
Step(step.on, Cube(
max(x.first, -50)..min(x.last, 50),
max(y.first, -50)..min(y.last, 50),
max(z.first, -50)..min(z.last, 50),
))
}
}
private fun computeFlippedVolume(previousSteps: List<Step>, step: Step): Long {
val overlappingSteps = previousSteps.filter { it.cube.intersect(step.cube).volume() > 0 }
var totalFlippedVolume = 0L
overlappingSteps.indices.filter { j -> overlappingSteps[j].on != step.on }.forEach { j ->
val otherStep = overlappingSteps[j]
val laterCubes = overlappingSteps.subList(j + 1, overlappingSteps.size).map(Step::cube)
val offOnIntersect = step.cube.intersect(otherStep.cube)
totalFlippedVolume += computeNonIntersectingVolume(laterCubes, offOnIntersect)
}
return totalFlippedVolume
}
private fun computeNonIntersectingVolume(previousCubes: List<Cube>, cube: Cube): Long {
val overlappingCubes = previousCubes.filter { it.intersect(cube).volume() > 0 }
var newVolume = cube.volume()
var sign = -1
for (cubeCount in 1..overlappingCubes.size) {
val cubeCombinations = combinations(overlappingCubes, cubeCount)
cubeCombinations.forEach { cubeCombination ->
newVolume += sign * cubeCombination.fold(cube) { a, b -> a.intersect(b) }.volume()
}
sign *= -1
}
return newVolume
}
private fun <T> combinations(list: List<T>, count: Int): List<List<T>> {
if (count == 1) {
return list.map { listOf(it) }
}
return list.flatMapIndexed { i, elem ->
val subCombinations = combinations(list.subList(i + 1, list.size), count - 1)
subCombinations.map { listOf(elem).plus(it) }
}
}
@JvmStatic
fun main(args: Array<String>) {
val lines = Files.readAllLines(Path.of("input22.txt"), Charsets.UTF_8)
val solution1 = solve(lines, true)
println(solution1)
val solution2 = solve(lines, false)
println(solution2)
}
} | 0 | Kotlin | 0 | 0 | ba81fadf2a8106fae3e16ed825cc25bbb7a95409 | 4,636 | advent-of-code-2021 | The Unlicense |
src/year2022/day11/Solution.kt | LewsTherinTelescope | 573,240,975 | false | {"Kotlin": 33565} | package year2022.day11
import utils.bigint
import utils.extractTrailingInt
import utils.isDivisibleBy
import utils.productOf
import utils.removeEach
import utils.runIt
import utils.splitOnBlankLines
import utils.toLinkedList
import utils.toLongList
import java.math.BigInteger
fun main() = runIt(
testInput = """
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
""".trimIndent(),
::part1,
testAnswerPart1 = bigint(10605),
::part2,
testAnswerPart2 = bigint(2713310158),
)
fun part1(input: String): BigInteger = input.execMonkeyBusiness(rounds = 20)
fun part2(input: String): BigInteger = input.execMonkeyBusiness(rounds = 10_000, canChill = false)
fun String.execMonkeyBusiness(
rounds: Int,
canChill: Boolean = true,
) = splitOnBlankLines()
.map(Monke::from)
.calculateInspectionCounts(rounds, canChill)
.apply { sortDescending() }
.take(2)
.productOf(Int::toBigInteger)
typealias WorryLevel = Long
data class Monke(
val startingItems: List<WorryLevel>,
val increaseGivenWorry: (WorryLevel) -> WorryLevel,
val testDivisor: Int,
val targetIfTrue: Int,
val targetIfFalse: Int,
) {
companion object {
fun from(input: String): Monke = input.lines().let { lines ->
Monke(
startingItems = lines[1].split(": ").last().trim().toLongList(),
increaseGivenWorry = lines[2].toAperation(),
testDivisor = lines[3].extractTrailingInt(),
targetIfTrue = lines[4].extractTrailingInt(),
targetIfFalse = lines[5].extractTrailingInt(),
)
}
}
fun test(worryLevel: WorryLevel): Boolean = worryLevel isDivisibleBy testDivisor
}
fun List<Monke>.calculateInspectionCounts(
rounds: Int,
canChillax: Boolean = true,
): IntArray {
val lcm = productOf { it.testDivisor }
val monkeInspectionCounts = IntArray(size)
val monkeItems = Array(size) { get(it).startingItems.toLinkedList() }
val monkesWithItems = zip(monkeItems)
fun Monke.yeet(worryLevel: WorryLevel) {
val target = if (test(worryLevel)) targetIfTrue else targetIfFalse
monkeItems[target] += worryLevel
}
repeat(rounds) {
monkesWithItems.forEachIndexed { i, (monke, itemWorries) ->
itemWorries.removeEach { initialWorry ->
monke.increaseGivenWorry(initialWorry)
.let { (if (canChillax) it / 3 else it) % lcm }
.let(monke::yeet)
monkeInspectionCounts[i]++
}
}
}
return monkeInspectionCounts
}
fun String.toAperation(): (WorryLevel) -> WorryLevel = split(" ")
.takeLast(2)
.let { (op, modifier) ->
when (op) {
"+" -> { old: WorryLevel -> old + (modifier.toLongOrNull() ?: old) }
"*" -> { old: WorryLevel -> old * (modifier.toLongOrNull() ?: old) }
else -> error("Unrecognized operation: $op")
}
}
| 0 | Kotlin | 0 | 0 | ee18157a24765cb129f9fe3f2644994f61bb1365 | 3,261 | advent-of-code-kotlin | Do What The F*ck You Want To Public License |
kotlin/1675-minimize-deviation-in-array.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | //another solution using a max Heap and a min Heap.
class Solution {
fun minimumDeviation(nums: IntArray): Int {
val minHeap = PriorityQueue<Int>()
var maxHeap = PriorityQueue<Int>(Collections.reverseOrder())
var res = Integer.MAX_VALUE
// O(N)
// For each number, we are adding the largest number it can become
// Even numbers can't get bigger, so we add it
// Odd Numbers can get to twice it size, so we add that
for(num in nums) {
minHeap.add( if(num % 2 == 0) num else num * 2)
maxHeap.add( if(num % 2 == 0) num else num * 2)
}
var maxDiff = maxHeap.peek() - minHeap.peek()
var max = maxHeap.poll()
// O(nlogM * logN)
// We are halving each even number in our max, adding it to min and max, and getting the new possible min each time
// Loop until maxHeap top reached an odd number, then we are checked all possible mins
while(max % 2 == 0) {
max /= 2
minHeap.add(max)
maxHeap.add(max)
max = maxHeap.poll()
maxDiff = minOf(maxDiff, max - minHeap.peek())
}
return maxDiff
}
}
class Solution {
fun minimumDeviation(nums: IntArray): Int {
// minHeap with pair of N to it's maximum value X that N can get to.
// For odd Numbers, N = N and X = 2 * N
// For even numbers, N = N/2 until it's odd, X = N
val minHeap = PriorityQueue<Pair<Int, Int>> {a,b -> a.first - b.first}
var heapMax = 0
var res = Integer.MAX_VALUE
// O(nlogm)
for(_num in nums) {
var num = _num
while(num % 2 == 0) {
num /= 2
}
minHeap.add(num to maxOf(_num, 2 * num))
heapMax = maxOf(heapMax, num)
}
// O(nlogm * logn)
while(minHeap.size == nums.size) {
val (n, nMax) = minHeap.poll()
res = minOf(res, heapMax - n)
if(n < nMax) {
minHeap.add(n * 2 to nMax)
heapMax = maxOf(heapMax, n * 2)
}
}
return res
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 2,184 | leetcode | MIT License |
src/main/kotlin/year2023/Day05.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2023
class Day05 {
data class RangeMap(val destStart: Long, val sourceStart: Long, val size: Long) {
private val sourceRange = sourceStart..<sourceStart + size
companion object {
fun parse(input: String): RangeMap {
val (destStart, sourceStart, size) = input.split(' ').map { it.toLong() }
return RangeMap(destStart, sourceStart, size)
}
}
fun getDestination(source: Long): Long? {
return if (source in sourceRange) {
destStart + (source - sourceStart)
} else {
null
}
}
}
fun part1(input: String): Long {
val lines = input.lines()
val seeds = lines[0]
.substringAfter("seeds: ")
.split(' ')
.map { it.toLong() }
.map { it..it }
return findMinLocation(lines, seeds)
}
fun part2(input: String): Long {
val lines = input.lines()
val seeds = lines[0]
.substringAfter("seeds: ")
.split(' ')
.map { it.toLong() }
.chunked(2)
.map { chunk ->
val (start, size) = chunk
start..<start + size
}
return findMinLocation(lines, seeds)
}
fun findMinLocation(lines: List<String>, seedRanges: List<LongRange>): Long {
val mappings = buildList {
var currentList: MutableList<RangeMap>? = null
for (line in lines.drop(1)) {
if (line.isBlank()) {
currentList = mutableListOf<RangeMap>()
add(currentList as List<RangeMap>)
} else if (line[0].isDigit()) {
currentList!!.add(RangeMap.parse(line))
}
}
}
return seedRanges.map { seedRange ->
seedRange.minOf { seed ->
mappings.fold(seed) { acc, rangeMaps ->
rangeMaps.forEach { rangeMap ->
val destination = rangeMap.getDestination(acc)
if (destination != null) {
return@fold destination
}
}
acc
}
}
}.min()
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 2,348 | aoc-2022 | Apache License 2.0 |
src/adventofcode/blueschu/y2017/day12/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day12
import java.io.File
import kotlin.test.assertEquals
val input: List<String> by lazy {
File("resources/y2017/day12.txt")
.bufferedReader()
.use { it.readLines() }
}
fun main(args: Array<String>) {
val exampleNetwork = listOf(
"0 <-> 2",
"1 <-> 1",
"2 <-> 0, 3, 4",
"3 <-> 2, 4",
"4 <-> 2, 3, 6",
"5 <-> 6",
"6 <-> 4, 5"
)
assertEquals(6, part1(exampleNetwork))
println("Part 1: ${part1(input)}")
assertEquals(2, part2(exampleNetwork))
println("Part 2: ${part2(input)}")
}
data class NetworkNode(val id: Int) {
val connections = mutableSetOf<NetworkNode>()
fun connectWith(other: NetworkNode) {
if (other === this) return
other.connections.add(this)
connections.add(other)
}
}
fun NetworkNode.findAllNodes(): List<NetworkNode> {
val indexedNodes = mutableListOf<NetworkNode>(this)
fun findNewNodes(node: NetworkNode) {
if (node in indexedNodes) return
val connectedNodes = node.connections.filterNot { it in indexedNodes }
indexedNodes.add(node)
if (connectedNodes.isNotEmpty()) {
connectedNodes.forEach { findNewNodes(it) }
}
}
connections.forEach {
findNewNodes(it)
}
return indexedNodes
}
fun parseNetwork(description: List<String>): Array<NetworkNode> {
val pattern = "^(?:\\d{1,4}) <-> ((?:(?:, )?\\d{1,4})+)$".toRegex()
// node descriptions assumed to start at node 0 and increment
val parsedDescriptions: List<List<Int>> = description.map {
val connections = pattern.matchEntire(it)?.groups?.get(1)?.value
?: throw IllegalArgumentException("Node description could not be parsed: $it")
connections.split(", ").map(String::toInt)
}
// create a node for each id
val nodes = Array(parsedDescriptions.size, { NetworkNode(it) })
// connect the nodes
for ((id, connections) in parsedDescriptions.withIndex()) {
connections.forEach { otherId ->
nodes[id].connectWith(nodes[otherId])
}
}
return nodes
}
fun findDistinctNetworks(nodes: Array<NetworkNode>): List<List<NetworkNode>> {
val nodePool = nodes.associateBy { it.id }.toMutableMap()
val networks = mutableListOf<List<NetworkNode>>()
while (nodePool.isNotEmpty()) {
val networkNodes = nodePool.values.first().findAllNodes()
networks.add(networkNodes)
networkNodes.map(NetworkNode::id).forEach { nodePool.remove(it) }
}
return networks
}
fun part1(networkDescription: List<String>): Int =
parseNetwork(networkDescription).first().findAllNodes().size
fun part2(networkDescription: List<String>): Int =
findDistinctNetworks(parseNetwork(networkDescription)).size
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 2,846 | Advent-Of-Code | MIT License |
day14/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | fun main() {
val input = "236021"
val inputAsInt = input.toInt()
val inputAsList = input
.toList()
.map { (it - 48).toInt() }
println("Part I: the solution is ${solvePartI(inputAsInt)}.")
println("Part II: the solution is ${solvePartII(inputAsList)}.")
}
fun solvePartI(numberOfRecipes: Int): String {
val scoreboard = mutableListOf(3, 7)
var elf1Index = 0
var elf2Index = 1
var scoreboardLength = 2
while (scoreboardLength < numberOfRecipes + 10) {
val sumOfScoresAsString = (scoreboard[elf1Index] + scoreboard[elf2Index]).toString()
sumOfScoresAsString.forEach { char ->
scoreboard.add(char.toInt() - 48)
}
elf1Index = (elf1Index + 1 + scoreboard[elf1Index]) % scoreboard.size
elf2Index = (elf2Index + 1 + scoreboard[elf2Index]) % scoreboard.size
scoreboardLength = scoreboard.size
}
return (numberOfRecipes..numberOfRecipes + 9)
.map { recipe -> scoreboard[recipe] }
.joinToString("")
}
fun solvePartII(pattern: List<Int>): Int {
val scoreboard = mutableListOf(3, 7)
var elf1Index = 0
var elf2Index = 1
while (true) {
val sumOfScoresAsString = (scoreboard[elf1Index] + scoreboard[elf2Index]).toString()
sumOfScoresAsString.forEach { char ->
scoreboard.add(char.toInt() - 48)
}
val tailMatchIndex = scoreboard
.takeLast(pattern.size + 1)
.windowed(pattern.size)
.indexOfFirst { window -> window == pattern }
if (tailMatchIndex != -1) {
return scoreboard.size - (pattern.size + 1) + tailMatchIndex
}
elf1Index = (elf1Index + 1 + scoreboard[elf1Index]) % scoreboard.size
elf2Index = (elf2Index + 1 + scoreboard[elf2Index]) % scoreboard.size
}
}
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 1,873 | AdventOfCode2018 | MIT License |
src/main/kotlin/com/ginsberg/advent2023/Day22.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 22 - Sand Slabs
* Problem Description: http://adventofcode.com/2023/day/22
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day22/
*/
package com.ginsberg.advent2023
import com.ginsberg.advent2023.Day22.Brick.Companion.GROUND
class Day22(input: List<String>) {
private val bricks: List<Brick> = input
.mapIndexed { index, row -> Brick.of(index, row) }
.sorted()
.settle()
fun solvePart1(): Int =
bricks.size - bricks.structurallySignificant().size
fun solvePart2(): Int =
bricks.structurallySignificant().sumOf { it.topple().size - 1 }
private fun List<Brick>.structurallySignificant(): List<Brick> =
filter { brick -> brick.supporting.any { it.supportedBy.size == 1 } }
private fun List<Brick>.settle(): List<Brick> = buildList {
this@settle.forEach { brick ->
var current = brick
do {
var settled = false
val supporters = filter { below -> below.canSupport(current) }
if (supporters.isEmpty() && !current.onGround()) {
val restingPlace = filter { it.z.last < current.z.first - 1 }
.maxOfOrNull { it.z.last }?.let { it + 1 } ?: GROUND
current = current.fall(restingPlace)
} else {
settled = true
supporters.forEach { below -> below.supports(current) }
add(current)
}
} while (!settled)
}
}
private fun Brick.topple(): Set<Brick> = buildSet {
add(this@topple)
val untoppled = (bricks - this).toMutableSet()
do {
val willFall = untoppled
.filter { it.supportedBy.isNotEmpty() }
.filter { it.supportedBy.all { brick -> brick in this } }
.also {
untoppled.removeAll(it)
addAll(it)
}
} while (willFall.isNotEmpty())
}
private data class Brick(val id: Int, val x: IntRange, val y: IntRange, val z: IntRange) : Comparable<Brick> {
val supporting = mutableSetOf<Brick>()
val supportedBy = mutableSetOf<Brick>()
override fun compareTo(other: Brick): Int =
z.first - other.z.first
fun supports(other: Brick) {
supporting += other
other.supportedBy += this
}
fun canSupport(other: Brick): Boolean =
x intersects other.x && y intersects other.y && z.last + 1 == other.z.first
fun onGround(): Boolean =
z.first == GROUND
fun fall(restingPlace: Int): Brick =
copy(
z = restingPlace..(restingPlace + (z.last - z.first))
)
companion object {
const val GROUND = 1
fun of(index: Int, input: String): Brick =
input.split("~")
.map { side -> side.split(",").map { it.toInt() } }
.let { lists ->
val left = lists.first()
val right = lists.last()
Brick(
index,
left[0]..right[0],
left[1]..right[1],
left[2]..right[2]
)
}
}
}
} | 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 3,508 | advent-2023-kotlin | Apache License 2.0 |
src/day21/Day21.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day21
import readInput
import java.lang.IllegalStateException
enum class Operator(val repr: Char) {
ADD('+'),
SUB('-'),
MULT('*'),
DIV('/');
fun apply(fst: Long, snd: Long): Long = when (this) {
ADD -> fst + snd
SUB -> fst - snd
MULT -> fst * snd
DIV -> fst / snd
}
fun reverseFst(fst: Long, res: Long): Long = when (this) {
ADD -> res - fst
SUB -> fst - res
MULT -> res / fst
DIV -> fst / res
}
fun reverseSnd(snd: Long, res: Long): Long = when (this) {
ADD -> res - snd
SUB -> snd + res
MULT -> res / snd
DIV -> res * snd
}
companion object {
fun fromRepr(repr: Char): Operator = values().first { it.repr == repr }
}
}
abstract class Monkey
data class Literal(val literal: Long) : Monkey()
data class Instruction(val fst: String, val operator: Operator, val snd: String) : Monkey()
class Me : Monkey()
fun main() {
fun solveMap(input: MutableMap<String, Monkey>) {
var changed = true
while (changed) {
changed = false
for ((name, monkey) in input) {
if (monkey is Instruction) {
val fst = input[monkey.fst]
val snd = input[monkey.snd]
if (fst is Literal && snd is Literal) {
input[name] = Literal(monkey.operator.apply(fst.literal, snd.literal))
changed = true
}
}
}
}
}
fun part1(input: MutableMap<String, Monkey>): Long = solveMap(input).let { (input["root"] as Literal).literal }
fun part2(input: MutableMap<String, Monkey>): Long {
input["humn"] = Me()
solveMap(input)
fun getValueOfRev(monkey: Monkey, target: Long): Long {
if (monkey is Me) {
return target
}
if (monkey is Instruction) {
val fst = input[monkey.fst]
val snd = input[monkey.snd]
if (fst is Literal) {
return getValueOfRev(snd!!, monkey.operator.reverseFst(fst.literal, target))
}
if (snd is Literal) {
return getValueOfRev(fst!!, monkey.operator.reverseSnd(snd.literal, target))
}
}
throw IllegalStateException()
}
val root = input["root"] as Instruction
val searchable = if(input[root.fst] is Literal) input[root.snd] else input[root.fst]
val target = (if(input[root.fst] is Literal) input[root.fst] else input[root.snd]) as Literal
return getValueOfRev(searchable as Instruction, target.literal)
}
fun preprocess(input: List<String>): MutableMap<String, Monkey> = input.associate {
val split = it.split(" ")
val literal = split[1].toLongOrNull()
split[0].substring(0..3) to if (literal != null) Literal(literal) else Instruction(
split[1],
Operator.fromRepr(split[2][0]),
split[3]
)
}.toMutableMap()
// test if implementation meets criteria from the description, like:
val testInput = readInput(21, true)
check(part1(preprocess(testInput)) == 152L)
val input = readInput(21)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) == 301L)
println(part2(preprocess(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 3,467 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day24.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getLines
class Alu(private val monad: List<String>){
private val variables = mutableMapOf(
Pair('w', 0),
Pair('x', 0),
Pair('y', 0),
Pair('z', 0),
)
fun checkModelNumber(modelNumber: String): Boolean{
variables.keys.forEach { variables[it] = 0 }
var readIndex = 0
try{
for(instruction in monad){
val command = instruction.split(" ")[0]
val a = instruction.split(" ")[1].first()
val b = instruction.split(" ").getOrNull(2)
variables[a] = when(command){
"inp" -> {
val value = modelNumber[readIndex].digitToInt()
readIndex++
value
}
"add" -> variables[a]!! + getBValue(b!!)
"mul" -> variables[a]!! * getBValue(b!!)
"div" -> variables[a]!! / getBValue(b!!)
"mod" -> variables[a]!! % getBValue(b!!)
"eql" -> if(variables[a]!! == getBValue(b!!)) 1 else 0
else -> throw Exception("Should always find")
}
}
//println(variables['z'])
return variables['z'] == 0
}catch(e: Exception) {
return false
}
}
private fun getBValue(b: String): Int {
return try{
b.toInt()
}catch (e: Exception){
variables[b.first()]!!
}
}
}
fun main(){
val input = getLines("day24.txt")
val alu = Alu(input)
/*
inp w
mul x 0
add x z
mod x 26
div z {DIV}
add x {CHECK}
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y {OFFSET}
mul y x
add z y
*/
val relations = mutableListOf<Relation>()
val stack = mutableListOf<StackElement>()
getSections(input).forEachIndexed { index, section ->
if(section.div == 1){
stack.add(StackElement(index, section.offset))
}else{
val popped = stack.removeLast()
println("model_nr[$index] == model_nr[${popped.nr}] + ${popped.value + section.check}")
relations.add(Relation(index, popped.nr, popped.value + section.check))
}
}
val max = getModelNumber(relations, 9 downTo 1)
val maxValid = alu.checkModelNumber(max)
println("max model number $max is $maxValid")
val min = getModelNumber(relations, 1..9)
val minValid = alu.checkModelNumber(min)
println("min model number $min is $minValid")
}
data class Section(val div: Int, val check: Int, val offset: Int)
data class StackElement(val nr: Int, val value: Int)
data class Relation(val nrA: Int, val nrB: Int, val diff: Int)
fun getSections(input: List<String>): List<Section>{
return input.chunked(18).map {
val div = it[4].split(" ")[2].toInt()
val check = it[5].split(" ")[2].toInt()
val offset = it[15].split(" ")[2].toInt()
Section(div, check, offset)
}
}
fun getModelNumber(relations: List<Relation>, intProgression: IntProgression): String{
var modelNumber = ""
for(i in 0 until 14){
val pair = relations.find { it.nrA == i || it.nrB == i }!!
val chose = if(pair.nrA == i){
intProgression.toList().first { IntRange(1,9).contains(it - pair.diff) }
}else{
intProgression.toList().first { IntRange(1,9).contains(it + pair.diff) }
}
modelNumber += chose
}
return modelNumber
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 3,615 | AdventOfCode2021 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.