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/Day24.kt | clechasseur | 264,758,910 | false | null | object Day24 {
private val input = """
31/13
34/4
49/49
23/37
47/45
32/4
12/35
37/30
41/48
0/47
32/30
12/5
37/31
7/41
10/28
35/4
28/35
20/29
32/20
31/43
48/14
10/11
27/6
9/24
8/28
45/48
8/1
16/19
45/45
0/4
29/33
2/5
33/9
11/7
32/10
44/1
40/32
2/45
16/16
1/18
38/36
34/24
39/44
32/37
26/46
25/33
9/10
0/29
38/8
33/33
49/19
18/20
49/39
18/39
26/13
19/32
""".trimIndent()
private val parts = input.lineSequence().map { it.toPart() }.toList()
fun part1() = buildBridges(parts, listOf(Part(0, 0))).map { it.strength() }.max()!!
fun part2(): Int {
val bridges = buildBridges(parts, listOf(Part(0, 0))).sortedByDescending { it.size }
val longestBridges = bridges.filter { it.size == bridges.first().size }
return longestBridges.map { it.strength() }.max()!!
}
private fun buildBridges(partsLeft: List<Part>, soFar: List<Part>): List<List<Part>> {
val matchingParts = partsLeft.filter { part ->
part.leftPort == soFar.last().rightPort || part.rightPort == soFar.last().rightPort
}
if (matchingParts.isEmpty()) {
return listOf(soFar)
}
return matchingParts.flatMap { nextPart ->
val newPartsLeft = partsLeft - nextPart
val newSoFar = soFar + if (nextPart.leftPort == soFar.last().rightPort) {
nextPart
} else {
nextPart.reverse
}
buildBridges(newPartsLeft, newSoFar)
}
}
private data class Part(val leftPort: Int, val rightPort: Int) {
val strength: Int
get() = leftPort + rightPort
val reverse: Part
get() = Part(rightPort, leftPort)
override fun toString(): String = "$leftPort/$rightPort"
}
private fun String.toPart(): Part {
val (leftPort, rightPort) = split('/')
return Part(leftPort.toInt(), rightPort.toInt())
}
private fun List<Part>.strength() = sumBy { it.strength }
}
| 0 | Kotlin | 0 | 0 | f3e8840700e4c71e59d34fb22850f152f4e6e739 | 2,432 | adventofcode2017 | MIT License |
src/day2/Day02.kt | JoeSkedulo | 573,328,678 | false | {"Kotlin": 69788} | package day2
import day2.Move.*
import day2.Part.PartOne
import day2.Part.PartTwo
import day2.RoundResult.*
import readInput
fun main() {
fun rounds(input: List<String>) : List<Round> {
return input.map { line -> Round(
opponentInput = Move.values().first { it.v == line.first() },
input = Input.values().first { it.v == line.last() },
) }
}
fun part1(input: List<String>): Int {
return rounds(input).sumOf { round -> round.toScore(PartOne) }
}
fun part2(input: List<String>): Int {
return rounds(input).sumOf { round -> round.toScore(PartTwo) }
}
val input = readInput("day2/Day02")
println(part1(input))
println(part2(input))
}
enum class Move(val v: Char, val score: Int) {
Rock('A', 1),
Paper('B', 2),
Scissors('C', 3)
}
enum class Input(
val v: Char,
val partOne: Move,
val partTwo: RoundResult
) {
X('X', Rock, Loss),
Y('Y', Paper, Draw),
Z('Z', Scissors, Win)
}
enum class RoundResult(val score: Int) {
Win(6), Loss(0), Draw(3)
}
enum class Part {
PartOne, PartTwo
}
data class Round(
val opponentInput: Move,
val input: Input
)
fun Round.toMove(part: Part) = when(part) {
PartOne -> input.partOne
PartTwo -> when(input.partTwo) {
Loss -> opponentInput.toLoss()
Draw -> opponentInput.toDraw()
Win -> opponentInput.toWin()
}
}
fun Move.toWin() = when (this) {
Rock -> Paper
Paper -> Scissors
Scissors -> Rock
}
fun Move.toLoss() = when (this) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
fun Move.toDraw() = this
fun Round.toResultScore(f : (Round) -> Move) = when {
opponentInput == f(this) -> Draw
opponentInput == Rock && f(this) == Paper -> Win
opponentInput == Paper && f(this) == Scissors -> Win
opponentInput == Scissors && f(this) == Rock -> Win
else -> Loss
}.score
fun Round.toScore(part: Part) = toMove(part).let { move -> move.score + toResultScore { move } } | 0 | Kotlin | 0 | 0 | bd8f4058cef195804c7a057473998bf80b88b781 | 2,026 | advent-of-code | Apache License 2.0 |
src/Day03.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | fun main() {
val priorities = ('a'..'z').zip((1..26)).toMap() +
('A'..'Z').zip((27..52)).toMap()
fun part1(input: List<String>): Int {
var totalSum = 0
for (line in input) {
val halfLen = line.length / 2
val head = line.take(halfLen).asIterable()
val tail = line.substring(halfLen).asIterable().toSet()
totalSum += priorities[head.intersect(tail).single()]!!
}
return totalSum
}
fun part2(input: List<String>): Int {
var intermediate = emptySet<Char>()
var totalSum = 0
for ((i, line) in input.withIndex()) {
if (i > 0 && i % 3 == 0) {
totalSum += priorities[intermediate.single()]!!
intermediate = emptySet()
}
intermediate = if (intermediate.isEmpty()) {
intermediate.union(line.asIterable())
} else {
intermediate.intersect(line.asIterable().toSet())
}
}
totalSum += priorities[intermediate.single()]!!
return totalSum
}
// 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 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 1,403 | aoc2022 | Apache License 2.0 |
kotlin/0128-longest-consecutive-sequence.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} | import kotlin.math.max
class Solution {
fun longestConsecutive(nums: IntArray): Int {
if (nums.isEmpty()) return 0
if (nums.size == 1) return 1
val hashSet = HashSet<Int>()
nums.forEach { hashSet.add(it) }
var longestSize = 0
var isNumberStartOfSequence: Boolean
for (num in nums) {
isNumberStartOfSequence = !hashSet.contains(num - 1)
if (isNumberStartOfSequence) {
var nextConsecutiveNumber = num + 1
var currentSize = 1
while (hashSet.contains(nextConsecutiveNumber)) {
nextConsecutiveNumber++
currentSize++
}
longestSize = max(longestSize, currentSize)
}
}
return longestSize
}
}
// Alternative solution using Union Find
class Solution {
class DSU(val n: Int) {
val parent = IntArray(n) { it }
val size = IntArray(n) { 1 }
fun find(x: Int): Int {
if (parent[x] != x)
parent[x] = find(parent[x])
return parent[x]
}
fun union(x: Int, y: Int) {
val px = find(x)
val py = find(y)
if (px != py) {
parent[py] = px
size[px] += size[py]
}
}
fun getLongest(): Int {
var res = 0
for (i in parent.indices) {
if (parent[i] == i)
res = maxOf(res, size[i])
}
return res
}
}
fun longestConsecutive(nums: IntArray): Int {
val hm = HashMap<Int, Int>()
val dsu = DSU(nums.size)
for ((i,n) in nums.withIndex()) {
if (n in hm) continue
hm[n - 1]?.let { dsu.union(i, it) }
hm[n + 1]?.let { dsu.union(i, it) }
hm[n] = i
}
return dsu.getLongest()
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,956 | leetcode | MIT License |
src/Day06.kt | akijowski | 574,262,746 | false | {"Kotlin": 56887, "Shell": 101} | fun main() {
// TODO: Clean this up
fun part1(input: String): Int {
input.windowed(4).indexOfFirst { it.toCharArray().distinct().size == it.length }
val seen = mutableSetOf<Char>()
for (idx in input.indices) {
val c = input[idx]
if (c in seen) {
seen.clear()
}
seen += c
if (seen.size >= 4) {
return idx + 1
}
}
return 0
}
fun part2(input: String): Int {
val seen = mutableMapOf<Char, Int>()
var low = 0
for (high in input.indices) {
val c = input[high]
if (c in seen.keys) {
low = low.coerceAtLeast(seen[c]!!)
seen.filterValues { it < low }.keys.forEach { seen.remove(it) }
}
seen[c] = high
val window = high - low
if (window >= 14) {
return high + 1
}
}
return 0
}
fun foo(input: String): Int {
val seen = mutableMapOf<Char, Int>()
var low = 0
for (high in input.indices) {
val c = input[high]
if (c in seen.keys) {
low = low.coerceAtLeast(seen[c]!!)
seen.filterValues { it < low }.keys.forEach { seen.remove(it) }
}
seen[c] = high
val window = high - low
if (window >= 4) {
return high + 1
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsText("Day06_test")
check(part1(testInput) == 7)
check(foo(testInput) == 7)
buildMap {
put("bvwbjplbgvbhsrlpgdmjqwftvncz", 5)
put("nppdvjthqldpwncqszvftbrmjlhg", 6)
put("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 10)
put("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 11)
}.forEach { (s, c) ->
check(foo(s) == c) { "expected $s to equal $c" }
}
buildMap {
put("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 19)
put("bvwbjplbgvbhsrlpgdmjqwftvncz", 23)
put("nppdvjthqldpwncqszvftbrmjlhg", 23)
put("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 29)
put("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 26)
}.forEach { (s, c) ->
check(part2(s) == c) { "expected $s to equal $c"}
}
val input = readInputAsText("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 84d86a4bbaee40de72243c25b57e8eaf1d88e6d1 | 2,465 | advent-of-code-2022 | Apache License 2.0 |
src/day12/Day12.kt | commanderpepper | 574,647,779 | false | {"Kotlin": 44999} | package day12
import readInput
import kotlin.math.abs
/**
* My solution was able to find the correct shortest path for the smaller puzzle input (the solution is 31).
* My solution fails to make a proper tree for the actual puzzle input. I believe this is caused from the way I add visited positions to the set.
* My hunch is that I would have to tell a Set of the point added but also the origin or direction in which a point was visited from. This way a point can be inspected from more than one direction.
*/
fun main(){
val day12Input = readInput("day12")
day12Input.forEach(::println)
val elevationMap = generateElevationMap(day12Input)
elevationMap.forEach(::println)
val startPosition = day12Input.findPositionOf('S')
val endPosition = day12Input.findPositionOf('E')
println(startPosition)
println(endPosition)
val rootPosition = PositionTree(rootPosition = startPosition!!)
// Track if position tree was already checked
val visitedPositions = mutableSetOf<Position>()
val positionsToCheck = mutableListOf<PositionTree>()
positionsToCheck.add(rootPosition)
// While there are more positions to check, generate children
while(positionsToCheck.isNotEmpty()){
val positionTreeToGenerateFrom = positionsToCheck.removeFirst()
// If the next item in the list is not in the set then generate away
if(visitedPositions.contains(positionTreeToGenerateFrom.rootPosition).not()){
generateChildren(positionTreeToGenerateFrom, elevationMap)
visitedPositions.add(positionTreeToGenerateFrom.rootPosition)
// If a child is not null then add it to the list of positions to check against
positionTreeToGenerateFrom.leftChild?.let { positionsToCheck.add(it) }
positionTreeToGenerateFrom.rightChild?.let { positionsToCheck.add(it) }
positionTreeToGenerateFrom.upChild?.let { positionsToCheck.add(it) }
positionTreeToGenerateFrom.downChild?.let { positionsToCheck.add(it) }
}
}
println(rootPosition)
val answer = findShortestPathTo(rootPosition, endPosition!!)
println(answer)
}
fun generateChildren(positionTree: PositionTree?, elevationMap: List<List<Int>>){
if(positionTree != null){
val leftPosition: Position = positionTree.rootPosition.copy(x = positionTree.rootPosition.x - 1 , y = positionTree.rootPosition.y )
val rightPosition: Position = positionTree.rootPosition.copy(x = positionTree.rootPosition.x + 1 , y = positionTree.rootPosition.y)
val upPosition: Position = positionTree.rootPosition.copy(x = positionTree.rootPosition.x , y = positionTree.rootPosition.y - 1)
val downPosition: Position = positionTree.rootPosition.copy(x = positionTree.rootPosition.x , y = positionTree.rootPosition.y + 1)
val currentPositionElevationValue = elevationMap[positionTree.rootPosition.y][positionTree.rootPosition.x]
// Left
addChildPosition(leftPosition, elevationMap, currentPositionElevationValue,leftPosition.x >= 0){ positionToAdd ->
positionTree.leftChild = PositionTree(positionToAdd)
}
// Right
addChildPosition(rightPosition, elevationMap, currentPositionElevationValue,rightPosition.x < elevationMap.first().size){ positionToAdd ->
positionTree.rightChild = PositionTree(positionToAdd)
}
// Up
addChildPosition(upPosition, elevationMap, currentPositionElevationValue,upPosition.y >= 0){ positionToAdd ->
positionTree.upChild = PositionTree(positionToAdd)
}
// Down
addChildPosition(downPosition, elevationMap, currentPositionElevationValue,downPosition.y < elevationMap.size){ positionToAdd ->
positionTree.downChild = PositionTree(positionToAdd)
}
}
}
private fun addChildPosition(
positionToInspect: Position,
elevationMap: List<List<Int>>,
currentPositionElevationValue: Int,
positionCheck: Boolean,
positionAdd: (Position) -> Unit
) {
if (positionCheck) {
val candidateElevationValue = elevationMap[positionToInspect.y][positionToInspect.x]
if (candidateElevationValue == currentPositionElevationValue || abs(candidateElevationValue - currentPositionElevationValue) == 1) {
positionAdd(positionToInspect)
}
}
}
fun findShortestPathTo(root: PositionTree, targetPosition: Position, steps: Int = 0): Int {
if(root.rootPosition == targetPosition){
return steps
}
val leftSteps = root.leftChild?.let { findShortestPathTo(it, targetPosition, steps + 1) } ?: -1
val rightSteps = root.rightChild?.let { findShortestPathTo(it, targetPosition, steps + 1) } ?: -1
val downSteps = root.downChild?.let { findShortestPathTo(it, targetPosition, steps + 1) } ?: -1
val upSteps = root.upChild?.let { findShortestPathTo(it, targetPosition, steps + 1) } ?: -1
val stepLists = listOf(leftSteps, rightSteps, downSteps, upSteps)
val answer = stepLists.filter { it != -1 }
return if(answer.isNotEmpty()) answer.min() else -1
}
fun generateElevationMap(heightMap: List<String>, startChar: Char = 'S', endChar: Char = 'E'): List<List<Int>> {
val elevationMap = mutableListOf<List<Int>>()
heightMap.forEach { row ->
val list = mutableListOf<Int>()
row.forEach { elevation ->
list.add(
when (elevation) {
startChar -> 'a'.calculateElevation()
endChar -> 'z'.calculateElevation()
else -> elevation.calculateElevation()
}
)
}
elevationMap.add(list)
}
return elevationMap.toList()
}
fun List<String>.findPositionOf(targetChar: Char): Position? {
var position: Position? = null
this.forEachIndexed { y, row ->
row.forEachIndexed { x, elevation ->
if(elevation == targetChar){
position = Position(x = x, y = y)
}
}
}
return position
}
fun Char.calculateElevation(): Int {
return this.toInt() - 96
}
data class Position(val x: Int, val y: Int)
data class PositionTree(
val rootPosition: Position,
var leftChild: PositionTree? = null,
var rightChild: PositionTree? = null,
var upChild: PositionTree? = null,
var downChild: PositionTree? = null
) | 0 | Kotlin | 0 | 0 | fef291c511408c1a6f34a24ed7070ceabc0894a1 | 6,393 | advent-of-code-kotlin-2022 | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year15/Day15.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year15
import com.grappenmaker.aoc.PuzzleSet
fun PuzzleSet.day15() = puzzle {
val ingredients = inputLines.map { l ->
val (_, propertyList) = l.split(": ")
val (capacity, durability, flavor, texture, calories) =
propertyList.split(", ").map { it.split(" ")[1].toInt() }
Ingredient(capacity, durability, flavor, texture, calories)
}
val cookieSize = 100
// Idea: Start with a cookie with equal proportions per ingredient
// (this is sort of the average cookie and statistically a good starter?)
// Then "BFS through neighbours" until we find the best one
// I assume this can be done a lot better, since it took 5001ms the first time
// I tried to run part 2. Fun puzzle though.g
fun solve(requireCalories: Boolean, starterCookie: Cookie): Cookie {
val seen = hashSetOf(starterCookie.hash)
val queue = ArrayDeque(listOf(starterCookie))
var highestScore = Cookie(ingredients.associateWith { 0 })
while (queue.isNotEmpty()) {
val next = queue.removeFirst()
if (
next.score > highestScore.score &&
(next.calories == 500 || !requireCalories)
) highestScore = next
queue.addAll(next.adjacent().filter { seen.add(it.hash) })
}
return highestScore
}
val cookie = Cookie(ingredients.associateWith { cookieSize / ingredients.size })
val partOneCookie = solve(false, cookie)
partOne = partOneCookie.score.s()
partTwo = solve(true, partOneCookie).score.s()
}
data class Cookie(val ingredients: Map<Ingredient, Int>) {
// Utility to keep track of what cookies we have had
// Since every ingredient has a smaller size than 100,
// we can store every ingredient as 7 bits of a long
// (assuming we have no more than 64/7=9 ingredients)
val hash = ingredients.values.reduceIndexed { idx, acc, curr -> acc or (curr and 0x7F shl (idx * 7)) }
val singleIngredient by lazy {
ingredients.toList().fold(emptyCookie) { acc, curr ->
val (ingredient, amount) = curr
acc.copy(
capacity = acc.capacity + ingredient.capacity * amount,
durability = acc.durability + ingredient.durability * amount,
flavor = acc.flavor + ingredient.flavor * amount,
texture = acc.texture + ingredient.texture * amount,
calories = acc.calories + ingredient.calories * amount
)
}
}
val calories get() = singleIngredient.calories
// Basically selects every combo of 2 ingredients and varies them by one
fun adjacent() = ingredients.flatMap { (ingredientA, amountA) ->
(ingredients - ingredientA).flatMap { (ingredientB, amountB) ->
val aPlus = ingredientA to amountA + 1
val aMinus = ingredientA to amountA - 1
val bPlus = ingredientB to amountB + 1
val bMinus = ingredientB to amountB - 1
listOf(
ingredients + aPlus + bMinus,
ingredients + aMinus + bPlus
).filter { it.isValid() }.map { Cookie(it) }
}
}
val score get() = singleIngredient.score
operator fun compareTo(other: Cookie) = singleIngredient.compareTo(other.singleIngredient)
}
fun Map<Ingredient, Int>.isValid() = values.none { it <= 0 }
val emptyCookie = Ingredient(0, 0, 0, 0, 0)
// This can also represent a whole cookie
data class Ingredient(
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
)
operator fun Ingredient.compareTo(other: Ingredient) = score - other.score
val Ingredient.score: Int
get() {
val allProps = listOf(capacity, durability, flavor, texture)
return if (allProps.any { it <= 0 }) 0
else allProps.reduce { acc, curr -> acc * curr }
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 3,942 | advent-of-code | The Unlicense |
src/Day04.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 13
private const val EXPECTED_2 = 30L
private class Day04(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
var sum = 0
for (line in readAsLines()) {
val parts = line.split(" | ")
val winning = parts[0].substringAfter(": ").splitInts().toSet()
val myNumbers = parts[1].splitInts().toSet()
val winCount = winning.intersect(myNumbers).count()
if (winCount > 0) {
sum += 1 shl (winCount - 1)
}
}
return sum
}
fun part2(): Any {
val lines = readAsLines()
val wins = LongArray(lines.size) { 1 }
for ((index, line) in lines.withIndex()) {
val current = wins[index]
val parts = line.split(" | ")
val winning = parts[0].substringAfter(": ").splitInts().toSet()
val myNumbers = parts[1].splitInts().toSet()
val winCount = winning.intersect(myNumbers).count()
for (i in 0 until winCount) {
wins[index + i + 1] += current
}
}
return wins.sum()
}
}
fun main() {
val testInstance = Day04(true)
val instance = Day04(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 1,529 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/me/circuitrcay/euler/utils/Extensions.kt | adamint | 134,989,381 | false | null | package me.circuitrcay.euler.utils
import org.apache.commons.collections4.iterators.PermutationIterator
import org.jsoup.Jsoup
import java.math.BigInteger
fun <T : Number> bigInt(n: T) = BigInteger(n.toString())
private fun Long.isEven() = (this % 2) == 0L
private fun Long.isPrime() = this > 1 && smallestPrimeFactor() == null
fun Int.smallestPrimeFactor() = toLong().smallestPrimeFactor()?.toInt()
private fun Long.smallestPrimeFactor() = (2..Math.sqrt(toDouble()).toLong()).find { this % it == 0.toLong() }
fun primes() = generateSequence(2L) { previous ->
var number = previous + if (previous.isEven()) 1 else 2
while (!number.isPrime()) number += 2
number
}
fun String.generatePermutations(): List<String> {
val permutations = mutableListOf<String>()
val chars = toCharArray()
val iterator = PermutationIterator(chars.toList())
while (iterator.hasNext()) permutations.add(iterator.next().joinToString(""))
return permutations
}
fun String.generateRotationalPermutations(): List<String> {
val list = mutableListOf<String>()
val chars = toCharArray()
(1..(chars.size)).forEach {
list.add(chars.joinToString(""))
val tempFirst = chars[0]
for (i in 1..(chars.size - 1) step 1) chars[i - 1] = chars[i]
chars[chars.size - 1] = tempFirst
}
return list
}
fun sieveOf(num: Int): Array<Boolean> {
val primes = Array(num + 1, { true })
primes[0] = false
primes[1] = false
for (i in 2..(num / 2) step 1) for (multiplier in (i * 2)..num step i) primes[multiplier] = false
return primes
}
fun Array<Boolean>.convertSieveToPlaces() = mapIndexed { index, b -> if (!b) -1 else index }.filter { it != -1 }
fun String.isPalindrome(): Boolean = this == reversed()
fun isPanDigital(x: Int, y: Int): Boolean {
val str = x.toString() + y.toString() + (x * y).toString()
if (str.length != 9) return false;
val nums = Array(9, { false })
(1..9).forEach { if (str.contains(it.toString())) nums[it - 1] = true }
return nums.filter { it }.count() == 9
}
fun String.isPanDigital(n: Int? = null) = length == n ?: 9 && contains(1, n ?: 9)
fun Long.isPanDigital(n: Int? = null) = toString().length == n ?: 9 && toString().contains(0, n ?: 9)
fun String.contains(start: Int, end: Int): Boolean {
for (i in start..end step 1) if (!contains(i.toString())) return false
return true
}
fun Int.permutationOf(vararg ints: Int) = toLong().permutationOf(*ints.map { it.toLong() }.toLongArray())
fun Long.permutationOf(vararg longs: Long): Boolean {
if (longs.map { it.toString().length }.filter { it != toString().length }.count() > 0) return false
longs.map { it.toString() }.forEach { long ->
toString().forEach { if (!long.contains(it)) return false }
long.map { it.toString() }.forEach { against ->
against.forEach { if (!long.contains(it)) return false }
}
}
return true
}
fun Char.alphabeticalPosition(): Int {
return when (this) {
'a' -> 1
'b' -> 2
'c' -> 3
'd' -> 4
'e' -> 5
'f' -> 6
'g' -> 7
'h' -> 8
'i' -> 9
'j' -> 10
'k' -> 11
'l' -> 12
'm' -> 13
'n' -> 14
'o' -> 15
'p' -> 16
'q' -> 17
'r' -> 18
's' -> 19
't' -> 20
'u' -> 21
'v' -> 22
'w' -> 23
'x' -> 24
'y' -> 25
'z' -> 26
else -> -9999999
}
}
fun triangleNumbersOf(num: Int): List<Int> {
val triangleNumbers = mutableListOf<Int>()
(1..num).forEach { triangleNumbers.add((0.5f * it.toFloat() * (it + 1).toFloat()).toInt()) }
return triangleNumbers
}
fun String.getResource(): String = Jsoup.connect(this).get().body().text()
fun print(arr: Array<Array<Int>>) {
val sb = StringBuilder()
arr.forEach { row -> row.forEach { sb.append("$it ") }; sb.append("\n") }
println(sb)
}
fun generateCounterClockwiseSpiral(size: Int, prev: Array<Array<Int>>? = null): Array<Array<Int>> {
if (size % 2 == 0) throw IllegalArgumentException("Size must be odd")
var spiral = Array(size, { Array(size, { 1 }) })
if (prev != null) {
val list = mutableListOf<Array<Int>>()
list.add(Array(size, { 0 }))
list.addAll(prev.toMutableList())
list.add(Array(size, { 0 }))
for (i in 1..(list.size - 2)) {
val temp = mutableListOf(0)
temp.addAll(list[i].toMutableList())
temp.add(0)
list[i] = temp.toTypedArray()
}
spiral = list.toTypedArray()
}
var current = if (prev == null) Pair(size / 2, size / 2)
else Pair(size - 2, 1)
var displacement = if (prev == null) 1 else prev.size
for (currSize in 2..size) {
val startValue = spiral[current.first][current.second]
var count = 1
for (right in 1..displacement) {
spiral[current.first][current.second + right] = startValue + count
count++
}
current = Pair(current.first, current.second + displacement)
for (up in 1..displacement) {
spiral[current.first - up][current.second] = startValue + count
count++
}
current = Pair(current.first - displacement, current.second)
for (left in 1..(displacement + 1)) {
spiral[current.first][current.second - left] = startValue + count
count++
}
current = Pair(current.first, current.second - displacement - 1)
for (down in 1..(displacement + 1)) {
spiral[current.first + down][current.second] = startValue + count
count++
}
if (displacement + 2 >= size) {
var right = 1
while (right < size) {
spiral[size - 1][right] = startValue + count
right++
count++
}
return spiral
}
current = Pair(current.first + displacement + 1, current.second)
displacement += 2
}
return spiral
}
fun generateClockwiseSpiral(size: Int) = generateCounterClockwiseSpiral(size).reversedArray()
fun <T> getDiagonals(arr: Array<Array<T>>): List<T> {
val list = mutableListOf<T>()
for (x in 0..(arr.size - 1)) {
list.add(arr[x][x])
if (x != arr.size / 2) list.add(arr[arr.size - 1 - x][x])
}
return list
} | 0 | Kotlin | 0 | 0 | cebe96422207000718dbee46dce92fb332118665 | 6,413 | project-euler-kotlin | Apache License 2.0 |
src/Day22.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
data class Point3(val x: Int, val y: Int, var z: Int)
val input = readInput("Day22").map { brick ->
brick.split('~').map { point ->
val (x,y,z) = point.split(',').map { it.toInt() }
Point3(x,y,z)
}
}.sortedBy { minOf(it[0].z, it[1].z) }
fun getBrickIndex(p: Point3) = input.withIndex().find { (_, brick) ->
val (p1,p2) = brick
minOf(p1.x, p2.x) <= p.x && p.x <= maxOf(p1.x, p2.x) &&
minOf(p1.y, p2.y) <= p.y && p.y <= maxOf(p1.y, p2.y) &&
minOf(p1.z, p2.z) <= p.z && p.z <= maxOf(p1.z, p2.z)
}?.index
val ground = setOf(-1)
fun getDependsOn(p1: Point3, p2: Point3): Set<Int> {
val z = minOf(p1.z, p2.z)
if (z == 1) return ground
assert(z > 1)
val res = HashSet<Int>()
for (x in minOf(p1.x, p2.x)..maxOf(p1.x, p2.x)) {
for (y in minOf(p1.y, p2.y)..maxOf(p1.y, p2.y)) {
val sup = getBrickIndex(Point3(x,y,z-1))
if (sup != null) res.add(sup)
}
}
return res
}
for ((p1,p2) in input) {
while (getDependsOn(p1,p2).isEmpty()) {
p1.z --
p2.z --
}
}
val dependsOn = input.map { (p1, p2) ->
getDependsOn(p1, p2)
}
val singleSupport = dependsOn.mapNotNull {
it.singleOrNull()
}.toSet()
println(input.indices.count { it !in singleSupport })
var res2 = 0
for (i in input.indices) {
val remove = mutableSetOf(i)
do {
var changed = false
for (j in input.indices) {
if (j !in remove && (dependsOn[j] - remove).isEmpty()) {
remove.add(j)
changed = true
}
}
} while (changed)
res2 += remove.size-1
}
println(res2)
} | 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,883 | advent-of-code-kotlin | Apache License 2.0 |
src/Day07.kt | ds411 | 573,543,582 | false | {"Kotlin": 16415} | fun main() {
fun part1(input: List<String>): Int {
val dirByPath = buildFilesystem(input)
return dirByPath.values.filter { it.getSize() <= 100000 }.sumOf { it.getSize() }
}
fun part2(input: List<String>): Int {
val dirByPath = buildFilesystem(input)
val spaceAvailable = 70000000
val spaceNeeded = 30000000
val spaceUsed = dirByPath["/"]!!.getSize()
val spaceUnused = spaceAvailable - spaceUsed
val spaceToFree = spaceNeeded - spaceUnused
return dirByPath.values.map { it.getSize() }.filter { it >= spaceToFree }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private fun buildFilesystem(input: List<String>): Map<String, Directory> {
val dirByPath = mutableMapOf<String, Directory>()
val fs = Directory("/")
dirByPath["/"] = fs
var cwd = fs
var ptr = 0
while (ptr < input.size) {
val line = input[ptr]
if (line.startsWith('$')) {
val parts = line.split(' ')
val command = parts[1]
if (command == "cd") {
val dir = parts[2]
when (dir) {
"/" -> cwd = fs
".." -> {
val path = cwd.absolutePath.substringBeforeLast('/')
cwd = dirByPath[path]!!
}
else -> {
val node = cwd.nodes[dir]
if (node == null) {
val path = "${cwd.absolutePath}/${dir}"
val directory = Directory(path)
dirByPath[path] = directory
cwd.nodes[dir] = directory
cwd = directory
}
else {
cwd = node as Directory
}
}
}
}
ptr += 1
}
else {
val parts = line.split(' ')
val size = parts[0]
val name = parts[1]
if (size == "dir") {
if (!cwd.nodes.containsKey(name)) {
val path = "${cwd.absolutePath}/${name}"
val directory = Directory(path)
dirByPath[path] = directory
cwd.nodes[name] = directory
}
}
else {
val size = size.toInt()
cwd.nodes[name] = File(size)
}
ptr += 1
}
}
return dirByPath
}
private interface FSNode {
fun getSize(): Int
}
private class Directory(val absolutePath: String): FSNode {
val nodes: MutableMap<String, FSNode> = mutableMapOf()
override fun getSize(): Int {
return nodes.values.sumOf { it.getSize() }
}
}
private class File(private val size: Int): FSNode {
override fun getSize(): Int {
return size
}
} | 0 | Kotlin | 0 | 0 | 6f60b8e23ee80b46e7e1262723960af14670d482 | 3,230 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | wellithy | 571,903,945 | false | null | package day05
import util.*
@JvmInline
value class Crate(val mark: Char)
@JvmInline
value class Stack(private val crates: ArrayDeque<Crate> = ArrayDeque()) {
fun addLast(crate: Crate) = crates.addLast(crate)
fun move(other: Stack, count: Int, order: Boolean) =
other.crates.addFirst(crates.removeFirst(count), order)
fun top(): Crate = crates.first()
}
@JvmInline
value class Supplies(private val stacks: Map<Int, Stack>) {
fun execute(count: Int, from: Int, to: Int, order: Boolean) =
stacks.getValue(from).move(stacks.getValue(to), count, order)
fun top(): String =
generateSequence(1) { it + 1 }.take(stacks.size).map { stacks.getValue(it).top().mark }.joinToString("")
}
class Solver(private val order: Boolean) {
private companion object {
const val CRATE_DELIMITER: Char = '['
val MOVE_COMMAND: Regex = Regex("""move (\d+) from (\d+) to (\d+)""")
const val CRATE_WIDTH: Int = "[X] ".length
fun String.crate(id: Int): Crate? =
if (get(id * CRATE_WIDTH) != CRATE_DELIMITER) null
else Crate(get(id * CRATE_WIDTH + 1))
fun MutableMap<Int, Stack>.addCrates(line: String) {
val max = line.length + 1
require(max % CRATE_WIDTH == 0)
repeat(max / CRATE_WIDTH) { id ->
line.crate(id)?.let {
computeIfAbsent(id + 1) { _ -> Stack() }.addLast(it)
}
}
}
}
fun solve(lines: Sequence<String>): String {
val map = mutableMapOf<Int, Stack>()// this is kind of cheating :-)
val supplies = Supplies(map)
lines.forEach {
if (CRATE_DELIMITER in it) map.addCrates(it)
else MOVE_COMMAND.matchEntire(it)?.run {
destructured.toList().map(String::toInt).let { (count, from, to) ->
supplies.execute(count, from, to, order)
}
}
}
return supplies.top()
}
}
fun part1(input: Sequence<String>): String = Solver(false).solve(input)
fun part2(input: Sequence<String>): String = Solver(true).solve(input)
fun main() {
test(::part1, "CMZ")
go(::part1, "JDTMRWCQJ")
test(::part2, "MCD")
go(::part2, "VHJDDCWRD")
}
| 0 | Kotlin | 0 | 0 | 6d5fd4f0d361e4d483f7ddd2c6ef10224f6a9dec | 2,278 | aoc2022 | Apache License 2.0 |
src/Day25.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 54
private const val EXPECTED_2 = 0
private class Day25(isTest: Boolean) : Solver(isTest) {
fun flowCount(
conn: MutableMap<String, MutableSet<String>>,
src: String,
dest: String
): Pair<Int, List<Pair<String, String>>?> {
val allEdges = conn.flatMap { (src, dests) -> dests.map { src to it } }
val cap = allEdges.associateWith { 1 }.toMutableMap()
var n = 0
val seen = mutableSetOf<String>()
fun augmentFlow(p: String): Boolean {
if (p == dest) {
return true
}
seen.add(p)
for (d in conn[p]!!) {
if (d in seen) {
continue
}
val e = p to d
if (cap[e]!! > 0) {
cap.merge(e, -1) { a, b -> a + b }
cap.merge(d to p, 1) { a, b -> a + b }
if (augmentFlow(d)) {
return true
}
cap.merge(e, 1) { a, b -> a + b }
cap.merge(d to p, -1) { a, b -> a + b }
}
}
return false
}
while (augmentFlow(src)) {
seen.clear()
n++
}
// Return fully saturated edges
return n to allEdges.filter { cap[it] == 0 }
}
fun minCutEdges(conn: MutableMap<String, MutableSet<String>>): List<Pair<String, String>> {
val nodes = conn.keys.toList()
for (i in nodes.indices) {
for (j in i + 1..<nodes.size) {
val (cut, edges) = flowCount(conn, nodes[i], nodes[j])
if (cut == 3) {
println("Cut between ${nodes[i]} and ${nodes[j]} -- $edges")
return edges!!
}
}
}
error("no min cut 3")
}
fun part1(): Any {
val conn = readAsLines().map {
val parts = it.split(": ")
parts[0] to parts[1].split(" ").toMutableSet()
}.toMap().toMutableMap()
for ((a, b) in conn.entries.toList()) {
for (d in b) {
conn.getOrPut(d) { mutableSetOf() }.add(a)
}
}
for ((src, dest) in minCutEdges(conn)) {
conn[src]!!.remove(dest)
}
val seen = mutableSetOf<String>()
fun visit(n: String) {
for (d in conn[n]!!) {
if (d !in seen) {
seen.add(d)
visit(d)
}
}
}
visit(conn.keys.first())
return (conn.size - seen.size) * seen.size
}
fun part2(): Any {
return 0
}
}
fun main() {
val testInstance = Day25(true)
val instance = Day25(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 3,120 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | armandmgt | 573,595,523 | false | {"Kotlin": 47774} | fun main() {
fun compartments(rucksack: String): Pair<CharArray, CharArray> {
return Pair(
rucksack.substring(0, rucksack.length / 2).toCharArray(),
rucksack.substring(rucksack.length / 2).toCharArray()
)
}
fun toPriority(char: Char): Int {
return if (char <= 'Z') char.code - 64 + 26 else char.code - 96
}
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val pair = compartments(rucksack)
val intersection = pair.first.toSet().intersect(pair.second.toSet())
intersection.sumOf(::toPriority)
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { group ->
val intersection = group[0].toSet().intersect(group[1].toSet().intersect(group[2].toSet()))
intersection.sumOf(::toPriority)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("resources/Day03_test")
check(part1(testInput) == 157)
val input = readInput("resources/Day03")
println(part1(input))
check(part2(testInput) == 70)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 0d63a5974dd65a88e99a70e04243512a8f286145 | 1,200 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/kt/kotlinalgs/app/searching/MissingInt.ws.kts | sjaindl | 384,471,324 | false | null | package kt.kotlinalgs.app.searching
println("test")
val array = IntArray(1000) {
if (it == 900) 1001 // missing is 900!
else it
}
println(Solution().missingInt(array))
/*
follow up: 1 bil. ints, 10 MB memory
1 billion ints
10MB = ~10.000KB = ~10.000.000 bytes = ~ 80 million bits .. ~ < 2^23 bytes -> 2^23 / 4 (int = 4 byte for count!) = ~ 2^21
rangeSize >= 2^32 / 2^21 -> rangeSize >= 2^10 = 1024
ranges = min ranges of around 1024 elements
1. build rangeCount -> should be 1024!!
MutableMap<Int, Int>, mapping from rangeId to count, where rangeId = num / 1024
for each num: add or incr. range count
2. iterate over ranges from 0 to x, find first missing or with count < 1024
now we know missing int is in that range
3. BooleanArray of size 1024 .. mapping from range start to end
iterate again over input, just check ints within range and set to true
4. iterate over BooleanArray and return first element, where array[num-1] == false
*/
// assume file with 4 billion ints, return first missing one
// 1GB memory = ~1.000MB = ~1.000.000KB = ~1.000.000.000 bytes = ~8.000.000.000 bits
class Solution {
fun missingInt(array: IntArray): Int {
val bitVector = BitVector(array.size + 1)
array.forEach {
bitVector.setBit(it)
}
for (num in array.indices) {
if (!bitVector.isBitSet(num)) return num
}
return array.size
}
}
class BitVector(val size: Int) {
val bits = IntArray(arraySize)
val arraySize: Int
get() = when {
size % 32 == 0 -> size / 32
else -> size / 32 + 1
}
fun isBitSet(bit: Int): Boolean {
val index = bit / 32
val elementIndex = bit % 32
val mask = 1 shl elementIndex
// val bin = toBinary(bits[index])
// != 0 instead of > 0, as bit 32 is sign bit, which is < 0!!
return bits[index] and mask != 0
}
// 31, index = 0, elIndex = 31
// 32, index = 1, elIndex = 0
// 33, index = 1, elIndex = 1
fun setBit(bit: Int) {
val index = bit / 32
val elementIndex = bit % 32
val mask = 1 shl elementIndex
// val bin = toBinary(bits[index])
bits[index] = bits[index] or mask
// val bin2 = toBinary(bits[index])
}
fun toBinary(x: Int, len: Int = 32): String {
return String.format(
"%" + len + "s",
Integer.toBinaryString(x)
).replace(" ".toRegex(), "0")
}
}
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 2,492 | KotlinAlgs | MIT License |
src/y2023/Day03.kt | a3nv | 574,208,224 | false | {"Kotlin": 34115, "Java": 1914} | package y2023
import utils.readInput
fun main() {
fun isSymbol(c: Char): Boolean {
return !c.isLetterOrDigit() && '.' != c
}
fun getNeighbours(row: Int, col: Int, size: Int, length: Int): List<Pair<Int, Int>> {
val neighbours = mutableListOf<Pair<Int, Int>>();
val directions = listOf(
-1 to -1, -1 to 0, -1 to 1,
0 to -1, 0 to 1,
1 to -1, 1 to 0, 1 to 1
)
for (dir in directions) {
val newRow = row + dir.first
val newCol = col + dir.second
if (newRow in 0 until size && newCol >= 0 && newCol < length) {
neighbours.add(newRow to newCol)
}
}
return neighbours
}
fun isNumber(c: Char): Boolean {
return c.isDigit()
}
fun collectCompleteNumber(
grid: List<String>,
startRow: Int,
startCol: Int,
visited: HashSet<Pair<Int, Int>>
): String {
val numberQueue = ArrayDeque<Pair<Int, Int>>()
numberQueue.addLast(startRow to startCol)
val sb = StringBuilder()
visited.add(startRow to startCol)
val currentLine = grid[startRow]
val (row, col) = numberQueue.removeFirst()
sb.append(grid[row][col])
var left = startCol
var right = startCol
while (left > 0 && currentLine[left - 1].isDigit()) {
left--
visited.add(startRow to left)
}
while (right < currentLine.length - 1 && currentLine[right + 1].isDigit()) {
right++
visited.add(startRow to right)
}
return currentLine.substring(left..right)
}
fun part1(input: List<String>): Int {
val visited = HashSet<Pair<Int, Int>>()
val queue = ArrayDeque<Pair<Int, Int>>()
var sum = 0
for (i in input.indices) {
for (j in input[0].indices) {
if (isSymbol(input[i][j])) {
queue.addLast(i to j)
// println("Found: ${input[i][j]}")
}
}
}
while (queue.isNotEmpty()) {
val (row, col) = queue.removeFirst()
// println("Searching around: ${input[row][col]}")
for ((adjRow, adjCol) in getNeighbours(row, col, input.size, input[0].length)) {
// println("Checking $adjRow to $adjCol found ${input[adjRow][adjCol]}")
if (isNumber(input[adjRow][adjCol])) {
if (!visited.contains(adjRow to adjCol)) {
val completeNumber = collectCompleteNumber(input, adjRow, adjCol, visited)
sum += completeNumber.toInt()
}
}
}
}
return sum
}
fun part2(input: List<String>): Int {
val visited = HashSet<Pair<Int, Int>>()
val queue = ArrayDeque<Pair<Int, Int>>()
var sum = 0
for (i in input.indices) {
for (j in input[0].indices) {
if (input[i][j] == '*') {
queue.addLast(i to j)
// println("Found: ${input[i][j]}")
}
}
}
while (queue.isNotEmpty()) {
val (row, col) = queue.removeFirst()
// println("Searching around: ${input[row][col]}")
var list = mutableListOf<Int>();
for ((adjRow, adjCol) in getNeighbours(row, col, input.size, input[0].length)) {
// println("Checking $adjRow to $adjCol found ${input[adjRow][adjCol]}")
if (isNumber(input[adjRow][adjCol])) {
if (!visited.contains(adjRow to adjCol)) {
val completeNumber = collectCompleteNumber(input, adjRow, adjCol, visited)
list.add(completeNumber.toInt())
}
}
}
if (list.size == 2) {
sum += list.reduce { acc, i -> acc * i }
}
}
return sum
}
// test if implementation meets criteria from the description, like:
var testInput = readInput("y2023", "Day03_test_part1")
println("Test input: ${part1(testInput)}")
check(part1(testInput) == 4361)
println("Test input, part 2: ${part2(testInput)}")
// check(part2(testInput) == 2286)
val input = readInput("y2023", "Day03")
println("User input: ${part1(input)}")
check(part1(input) == 532331)
println("User input, part 2: ${part2(input)}")
check(part2(input) == 82301120)
}
| 0 | Kotlin | 0 | 0 | ab2206ab5030ace967e08c7051becb4ae44aea39 | 4,577 | advent-of-code-kotlin | Apache License 2.0 |
src/Day02.kt | JCampbell8 | 572,669,444 | false | {"Kotlin": 10115} | fun main() {
val ROCK_SCORE = 1
val PAPER_SCORE = 2
val SCISSORS_SCORE = 3
val ROCK = "AX"
val PAPER = "BY"
val SCISSORS = "CZ"
val LOSS = 0
val DRAW = 3
val WIN = 6
fun didIWin(me: String, them: String): Int {
return if (ROCK.contains(me) && PAPER.contains(them) || PAPER.contains(me) && SCISSORS.contains(them) ||
SCISSORS.contains(me) && ROCK.contains(them)
) {
//we lost
-1
} else if (ROCK.contains(me) && SCISSORS.contains(them) || PAPER.contains(me) && ROCK.contains(them) ||
SCISSORS.contains(me) && PAPER.contains(them)
) {
//we win!
1
} else {
//we draw
0
}
}
fun part1(input: List<String>): Int {
val totals = input.map { it.split(" ") }.map {
val myRPSScore = when (it[1]) {
"X" -> ROCK_SCORE
"Y" -> PAPER_SCORE
"Z" -> SCISSORS_SCORE
else -> {
0
}
}
val winScore = when (didIWin(it[1], it[0])) {
1 -> WIN
0 -> DRAW
-1 -> LOSS
else -> {
0
}
}
myRPSScore + winScore
}
return totals.sum()
}
fun part2(input: List<String>): Int {
val totals = input.map { it.split(" ") }.map {
val myRPSScore = when (it[1]) {
"X" -> when (it[0]) {
"A" -> SCISSORS_SCORE
"B" -> ROCK_SCORE
"C" -> PAPER_SCORE
else -> {0}
}
"Y" -> when (it[0]) {
"A" -> ROCK_SCORE
"B" -> PAPER_SCORE
"C" -> SCISSORS_SCORE
else -> {0}
}
"Z" -> when (it[0]) {
"A" -> PAPER_SCORE
"B" -> SCISSORS_SCORE
"C" -> ROCK_SCORE
else -> {0}
}
else -> {
0
}
}
val winScore = when (it[1]) {
"X" -> LOSS
"Y" -> DRAW
"Z" -> WIN
else -> {
0
}
}
myRPSScore + winScore
}
return totals.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
//check(part2(testInput) == 45000)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 0bac6b866e769d0ac6906456aefc58d4dd9688ad | 2,796 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | WhatDo | 572,393,865 | false | {"Kotlin": 24776} | fun main() {
val input = readInput("Day05")
val crates = parseCrates(input)
println(crates)
val instructions = parseInstructions(input)
println(instructions)
instructions.forEach { instr ->
when (instr) {
is Move -> move9001(crates, instr)
}
}
val sortedStacks = crates.stacks.entries.sortedBy { it.key }
println("Top crates are ${sortedStacks.joinToString(separator = "") { it.value.lastOrNull()?.toString() ?: " " }}")
}
private fun move(inv: Inventory, move: Move) {
repeat(move.amount) {
inv.stacks[move.to]!!.addLast(inv.stacks[move.from]!!.removeLast())
}
}
private fun move9001(inv: Inventory, move: Move) {
val from = inv.stacks[move.from]!!
val to = inv.stacks[move.to]!!
val moveIdx = from.size - move.amount
repeat(move.amount) {
to.addLast(from.removeAt(moveIdx))
}
}
sealed class Instr
data class Move(val amount: Int, val from: Int, val to: Int) : Instr()
data class Inventory(
val stacks: Map<Int, ArrayDeque<Char>>
)
private fun parseInstructions(input: List<String>): List<Instr> {
return input.subList(input.indexOf("") + 1, toIndex = input.size)
.map { instr -> instr.split(" ") }
.map { instrList -> Move(instrList[1].toInt(), instrList[3].toInt(), instrList[5].toInt()) }
}
private fun parseCrates(input: List<String>): Inventory {
val stacks = input.takeWhile { !numberRowRegex.matches(it) }.map { row ->
row.windowed(3, 4, partialWindows = true) { crate ->
if (crateRegex.matches(crate)) {
crate[1]
} else {
null
}
}
}.fold(mutableMapOf<Int, ArrayDeque<Char>>()) { map, chars ->
chars.forEachIndexed { index, c ->
if (c != null) {
map.getOrPut(index + 1) { ArrayDeque() }.addFirst(c)
}
}
map
}
return Inventory(stacks)
}
val crateRegex = "^\\[[A-Z]\\]$".toRegex()
val numberRowRegex = "^[1-9\\s]+$".toRegex() | 0 | Kotlin | 0 | 0 | 94abea885a59d0aa3873645d4c5cefc2d36d27cf | 2,039 | aoc-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | vladislav-og | 573,326,483 | false | {"Kotlin": 27072} | fun main() {
fun part1(input: List<String>): Int {
var fullyContainsPairsCount = 0
for (row in input) {
val (x1, x2, y1, y2) = row.split(",").map {
pair -> pair.split("-")
}.flatten().map { i -> i.toInt() }
if ((y1 in x1..x2 && y2 in x1..x2) || (x1 in y1..y2 && x2 in y1..y2)) {
fullyContainsPairsCount++
}
}
return fullyContainsPairsCount
}
fun part2(input: List<String>): Int {
var fullyContainsPairsCount = 0
for (row in input) {
val (x1, x2, y1, y2) = row.split(",").map {
pair -> pair.split("-")
}.flatten().map { i -> i.toInt() }
if (y1 in x1..x2 || y2 in x1..x2 || x1 in y1..y2 || x2 in y1..y2) {
fullyContainsPairsCount++
}
}
return fullyContainsPairsCount
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
println(part1(testInput))
check(part1(testInput) == 2)
println(part2(testInput))
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b230ebcb5705786af4c7867ef5f09ab2262297b6 | 1,247 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/anahoret/aoc2022/day20/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day20
import com.anahoret.aoc2022.calculateEndIndex
import java.io.File
import kotlin.system.measureTimeMillis
data class NumberContainer(val initialIndex: Int, val value: Long)
fun parse(str: String): Array<NumberContainer> {
return str.split("\n")
.mapIndexed { idx, s -> NumberContainer(idx, s.toLong()) }
.toTypedArray()
}
fun main() {
val input = File("src/main/kotlin/com/anahoret/aoc2022/day20/input.txt")
.readText()
.trim()
val numbers = parse(input)
// Part 1
part1(numbers.copyOf()).also { println("P1: ${it}ms") }
// Part 2
part2(numbers.copyOf()).also { println("P2: ${it}ms") }
}
private fun part1(numbers: Array<NumberContainer>) = measureTimeMillis {
mix(numbers)
calcResult(numbers)
.also(::println)
}
private fun part2(numbers: Array<NumberContainer>) = measureTimeMillis {
val decryptionKey = 811589153
val multipliedNumbers = numbers.map { it.copy(value = it.value * decryptionKey) }.toTypedArray()
repeat(10) {
mix(multipliedNumbers)
}
calcResult(multipliedNumbers)
.also(::println)
}
private fun calcResult(numbers: Array<NumberContainer>): Long {
val zeroIdx = numbers.indexOfFirst { it.value == 0L }
return listOf(1000, 2000, 3000)
.sumOf { numbers[calculateEndIndex(zeroIdx, it.toLong(), numbers.size)].value }
}
private fun mix(numbers: Array<NumberContainer>) {
numbers.indices.forEach { idx ->
val currentIndex = numbers.indexOfFirst { it.initialIndex == idx }
numbers.shift(currentIndex, numbers[currentIndex].value)
}
}
private fun <T> Array<T>.shift(idx: Int, amount: Long) {
val endIndex = calculateEndIndex(idx, amount, size - 1)
val tmp = this[idx]
when {
endIndex > idx -> (idx until endIndex).forEach { i -> this[i] = this[i + 1] }
else -> (idx downTo endIndex.inc()).forEach { i -> this[i] = this[i - 1] }
}
this[endIndex] = tmp
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 2,000 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/kotlin/day15/Day15.kt | W3D3 | 572,447,546 | false | {"Kotlin": 159335} | package day15
import common.InputRepo
import common.readSessionCookie
import common.solve
import util.Coord
import kotlin.math.abs
fun main(args: Array<String>) {
val day = 15
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay15Part1, ::solveDay15Part2)
}
fun solveDay15Part1(input: List<String>, row: Int = 2_000_000): Int {
val sensorInfoList = input.map { parseInstruction(it) }
val sensorRangesForRow = sensorInfoList.map { it.getRangeForRow(row) }
val coveredXCorrdsOnRow = sensorRangesForRow.flatMap { it.toSet() }.toSet()
val beaconsForRow =
sensorInfoList.filter { sensorInfo -> sensorInfo.beacon.y == row && coveredXCorrdsOnRow.contains(sensorInfo.beacon.x) }
.map { it.beacon }.toSet().count()
return sensorRangesForRow.flatMap { it.toSet() }.toSet().count() - beaconsForRow
}
fun solveDay15Part2(input: List<String>, upperBound: Int = 4_000_000): Long {
val sensorInfoList = input.map { parseInstruction(it) }
val uncovered = findUncovered(upperBound, sensorInfoList)
return uncovered.x * 4_000_000L + uncovered.y
}
private fun findUncovered(upperBound: Int, sensorInfoList: List<SensorInfo>): Coord {
val outOfReachCoords = sensorInfoList.flatMap { sensorInfo ->
sensorInfo.getFirstUnreachable()
.filter { it.x in 0..upperBound && it.y in 0..upperBound }
}.toSet()
val uncoveredCoords = outOfReachCoords
.filter { candidateCoord -> sensorInfoList.none { it.isCovered(candidateCoord) } }
return uncoveredCoords.first()
}
fun printGrid(n: Int, m: Int, marker: Set<Coord>) {
for (y in -2..m) {
for (x in -2..n) {
val coord = Coord(x, y)
if (marker.contains(coord)) {
print("#")
} else {
print(".")
}
}
println()
}
println()
}
data class SensorInfo(val sensor: Coord, val beacon: Coord) {
private val distance = sensor.manhattanDistance(beacon)
fun isCovered(testCoord: Coord): Boolean {
return getRangeForRow(testCoord.y).contains(testCoord.x)
}
fun getRangeForRow(row: Int): IntRange {
val distLeft = distance - abs(this.sensor.y - row)
if (distLeft < 1) {
return IntRange.EMPTY
}
return IntRange(this.sensor.x - distLeft, this.sensor.x + distLeft)
}
fun getFirstUnreachable(): Set<Coord> {
return this.sensor.getCoordsInExactDistance(distance + 1)
}
}
private fun parseInstruction(line: String): SensorInfo {
val moveRegex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex()
return moveRegex.matchEntire(line)
?.destructured
?.let { (xSensor, ySensor, xBeacon, yBeacon) ->
SensorInfo(Coord(xSensor.toInt(), ySensor.toInt()), Coord(xBeacon.toInt(), yBeacon.toInt()))
}
?: throw IllegalArgumentException("Bad sensor reading: '$line'")
} | 0 | Kotlin | 0 | 0 | 34437876bf5c391aa064e42f5c984c7014a9f46d | 3,008 | AdventOfCode2022 | Apache License 2.0 |
src/Day13.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | import Signal.Scalar
import Signal.Seq
import java.lang.IllegalArgumentException
sealed class Signal {
fun scalar(): Int = if (this is Scalar) this.value else throw IllegalArgumentException("Can't cast Seq to Scalar")
fun seq(): Seq = if (this is Seq) this else Seq(listOf(this))
data class Scalar(val value: Int) : Signal() {
override fun toString(): String = value.toString()
}
data class Seq(val value: List<Signal>) : Signal(), List<Signal> by value {
override fun toString(): String = value.toString()
}
}
class PairsIterator(private val input: List<String>) : Iterator<Pair<Seq, Seq>> {
private var index: Int = 0
override fun hasNext(): Boolean = index < input.size
private fun parse(s: String): Seq {
val result = mutableListOf<Signal>()
val stack: MutableList<MutableList<Signal>> = mutableListOf(result)
var lastNum = ""
for (ch in s.removePrefix("[")) {
when (ch) {
'[' -> {
val newList = ArrayList<Signal>()
stack.last().add(Seq(newList))
stack.add(newList)
}
']' -> {
if (lastNum.isNotEmpty()) {
stack.last().add(Scalar(lastNum.toInt()))
lastNum = ""
}
stack.removeLast()
}
' ' -> {}
',' -> {
if (lastNum.isNotEmpty()) {
stack.last().add(Scalar(lastNum.toInt()))
lastNum = ""
}
}
else -> lastNum += ch
}
}
return Seq(result)
}
override fun next(): Pair<Seq, Seq> {
val result = Pair(parse(input[index++]), parse(input[index++]))
index++
return result
}
}
fun main() {
fun compare(left: Seq, right: Seq): Int {
for (index in left.indices) {
if (right.size <= index) {
return 1
}
val leftItem = left[index]
val rightItem = right[index]
val someIsList = (leftItem is Seq) || (rightItem is Seq)
val compared = if (someIsList) {
compare(leftItem.seq(), rightItem.seq())
} else {
leftItem.scalar() - rightItem.scalar()
}
if (compared != 0) {
return compared
}
}
return if (left.size == right.size) 0 else -1
}
fun part1(input: List<String>): Int {
var indexes = 0
var index = 1
for ((left, right) in Iterable { PairsIterator(input) }) {
val compared = compare(left, right)
if (compared < 0) indexes += index
index++
}
return indexes
}
fun part2(input: List<String>): Int {
val toAdd2 = Seq(listOf(Seq(listOf(Scalar(2)))))
val toAdd6 = Seq(listOf(Seq(listOf(Scalar(6)))))
val seqList: List<Seq> = Iterable { PairsIterator(input) }
.flatMap { (l, r) -> listOf(l, r) } + listOf(toAdd2, toAdd6)
val sorted = seqList.sortedWith { l, r -> compare(l, r) }
return (sorted.indexOf(toAdd2) + 1) * (sorted.indexOf(toAdd6) + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
check(part1(input) == 5806)
check(part2(input) == 23600)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 3,689 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | adrianforsius | 573,044,406 | false | {"Kotlin": 68131} | import org.assertj.core.api.Assertions.assertThat
fun main() {
fun part1(input: List<String>): Int {
data class Point(var x: Int, var y: Int)
var visited = listOf(Point(0,0))
fun visit(x: Int, y: Int): Point {
val p = Point(x, y)
visited += p
return p
}
var head = Point(0,0)
var tail = Point(0,0)
input.map{
val part = it.split(" ")
val step = part.last().toInt()
var start = tail.copy()
when (part.first()) {
"R" -> head.x = step + head.x
"L"-> head.x = (step*-1) + head.x
"U"-> head.y = step + head.y
"D"-> head.y = (step*-1) + head.y
}
while (true) {
var deltaX = head.x - start.x
var deltaY = head.y - start.y
var delta = Point(deltaX, deltaY)
when {
delta.y > 1 -> start.x = head.x
delta.y < -1 -> start.x = head.x
delta.x > 1 -> start.y = head.y
delta.x < -1 -> start.y = head.y
}
when {
delta.y > 1 -> tail = visit(start.x, start.y + 1)
delta.y < -1 -> tail = visit(start.x, start.y - 1)
delta.x > 1 -> tail = visit(start.x + 1, start.y)
delta.x < -1 -> tail = visit(start.x - 1, start.y)
else -> break
}
when {
delta.y > 1 -> start.y++
delta.y < -1 -> start.y--
delta.x > 1 -> start.x++
delta.x < -1 -> start.x--
}
}
}
return visited.toSet().count()
}
fun part2(input: List<String>): Int {
data class Point(var x: Int, var y: Int, val visited: List<Point> = emptyList())
var rope: MutableList<Point> = MutableList(10) { Point(0, 0) }
fun visit(p: Point, x: Int, y: Int): Point {
return Point(x, y, p.visited+Point(x, y))
}
input.map {
val part = it.split(" ")
val step = part.last().toInt()
val direction = part.first()
repeat(step) {
rope.windowed(2).withIndex().forEach {(index, _) ->
var head = rope[index]
var tail = rope[index+1]
if (index == 0 ) {
when (direction) {
"R" -> head.x++
"L" -> head.x--
"U" -> head.y++
"D" -> head.y--
}
}
var deltaX = head.x - tail.x
var deltaY = head.y - tail.y
when {
deltaY > 1 -> tail = visit(tail, head.x, tail.y + 1)
deltaY < -1 -> tail = visit(tail, head.x, tail.y - 1)
deltaX > 1 -> tail = visit(tail, tail.x + 1, head.y)
deltaX < -1 -> tail = visit(tail, tail.x - 1, head.y)
}
rope[index+1] = tail
}
}
}
val out = rope.last().visited.toSet().toList().sortedBy { it.x }
return out.count() // center
}
// test if implementation meets criteria from the description, like:
// Test
val testInput = readInput("Day09_test")
// val output1 = part1(testInput)
// assertThat(output1).isEqualTo(13)
// // Answer
val input = readInput("Day09")
// val outputAnswer1 = part1(input)
// assertThat(outputAnswer1).isEqualTo(5874)
// Test
val output2 = part2(testInput)
assertThat(output2).isEqualTo(0)
// Test 1
val testInput1 = readInput("Day09_test_1")
assertThat(part2(testInput1)+1).isEqualTo(36)
// Answer
val outputAnswer2 = part2(input)
assertThat(outputAnswer2+1).isEqualTo(2467)
}
| 0 | Kotlin | 0 | 0 | f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb | 4,095 | kotlin-2022 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions60.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
fun test60() {
printlnResult(1)
printlnResult(2)
printlnResult(3)
}
/**
* Questions 60: Find the probabilities of all situations of sums of n dices
*/
private fun getProbabilityOfDices(n: Int): Map<Int, Double> {
val map = getProbabilityOfDicesRecursion(n)
val amount = map.values.sum()
return map.mapValues { (_, value) ->
value.toDouble() / amount
}
}
private fun getProbabilityOfDicesRecursion(n: Int): HashMap<Int, Int> {
val result = HashMap<Int, Int>(6 * n - n + 1)
if (n == 1) {
for (i in 1..6)
result[i] = 1
return result
} else {
val preResult = getProbabilityOfDicesRecursion(n - 1)
for (i in 1..6)
preResult.forEach {
val sum = i + it.key
result[sum] = if (result.containsKey(sum))
result[sum]!! + it.value
else
it.value
}
}
return result
}
private fun getProbabilitiesOfDicesLoop(n: Int): Map<Int, Double> {
require(n > 0) { "The n must greater than 0" }
var map = HashMap<Int, Int>(6)
for (i in 1..6)
map[i] = 1
for (i in 2..n) {
val newMap = HashMap<Int, Int>(6 * i - i + 1)
for (j in 1..6) {
map.forEach {
val sum = j + it.key
newMap[sum] = if (newMap.containsKey(sum))
newMap[sum]!! + it.value
else
it.value
}
}
map = newMap
}
val amount = map.values.sum()
return map.mapValues { (_, value) ->
value.toDouble() / amount
}
}
private fun printlnResult(n: Int) {
val result = getProbabilityOfDices(n) == getProbabilitiesOfDicesLoop(n)
println("When we have n dices, we find the probabilities of sun of all dices is $result")
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,897 | Algorithm | Apache License 2.0 |
src/Day20.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | fun main() {
fun part1(input: List<String>): Int {
val values = input.map { it.toInt() }
val indexed = values.mapIndexed { idx, value -> idx to value }
val result = indexed.toMutableList()
for (toMove in indexed) {
val oldIndex = result.indexOf(toMove)
val steps = toMove.second
val newIndex = ((oldIndex + steps) % result.lastIndex + result.lastIndex) % (result.lastIndex)
result.removeAt(oldIndex)
result.add(newIndex, toMove)
}
val resultingList = result.map { it.second }
val zeroIndex = resultingList.indexOf(0)
var sum = 0
for (idx in listOf(1, 2, 3).map { it * 1000 }) {
sum += resultingList[((idx % result.size) + zeroIndex) % result.size]
}
return sum
}
fun part2(input: List<String>): Long {
val descriptionKey = 811589153
val values = input.map { it.toLong() }.map { it * descriptionKey }
val indexed = values.mapIndexed { idx, value -> idx to value }
val result = indexed.toMutableList()
repeat(10) {
for (toMove in indexed) {
val oldIndex = result.indexOf(toMove)
val steps = toMove.second
val newIndex = ((oldIndex + steps) % result.lastIndex + result.lastIndex) % (result.lastIndex)
result.removeAt(oldIndex)
result.add(newIndex.toInt(), toMove)
}
}
val resultingList = result.map { it.second }
val zeroIndex = resultingList.indexOf(0)
var sum = 0L
for (idx in listOf(1L, 2L, 3L).map { it * 1000 }) {
val correctedIdx = ((idx % result.size) + zeroIndex) % result.size
sum += resultingList[correctedIdx.toInt()]
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
check(part1(testInput) == 3)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 2,138 | aoc2022 | Apache License 2.0 |
src/Day02.kt | xuejingao | 573,076,407 | false | null | import Outcome.*
private val selectedScoreMap = hashMapOf<String, Int>(
"X" to 1, // rock
"Y" to 2, // paper
"Z" to 3, // scissor
)
private enum class Outcome {
WIN, LOSE, DRAW
}
private val winScoreMap = hashMapOf<Outcome, Int>(
WIN to 6,
LOSE to 0,
DRAW to 3,
)
fun main() {
fun determineResult(opp: String, you: String): Outcome {
return if(opp[0].plus(23).compareTo(you[0]) == 0) DRAW
else if(opp == "A" && you == "Z" ||
opp == "B" && you == "X" ||
opp == "C" && you == "Y") LOSE
else WIN
}
fun calculateScore(opponentChoice: String, yourChoice: String): Int {
val result = determineResult(opponentChoice.toString(), yourChoice)
var yourScore = selectedScoreMap[yourChoice]?.plus(winScoreMap[result]!!)
return yourScore!!
}
fun part1(input: List<String>): Int {
var scoreFromFollowing = 0
for( round in input ) {
val opponent = round[0].toString()
val yours = round[2].toString()
scoreFromFollowing += calculateScore(opponent, yours)
}
return scoreFromFollowing
}
fun calculateYourSelection(opponentSelection: String, result: Outcome): String {
return if(result == DRAW) {
when(opponentSelection) {
"A" -> "X"
"B" -> "Y"
"C" -> "Z"
else -> throw error("invalid mapping")
}
} else if(result == WIN) {
when(opponentSelection) {
"A" -> "Y"
"B" -> "Z"
"C" -> "X"
else -> throw error("invalid mapping")
}
} else {
when(opponentSelection) {
"A" -> "Z"
"B" -> "X"
"C" -> "Y"
else -> throw error("invalid mapping")
}
}
}
fun part2(input: List<String>): Int {
// X = lose
// Y = Draw
// Z = WIN
// Calculate the points
var totalPoints = 0
for (round in input) {
val opponentsChoice = round[0].toString()
val endRoundResult = round[2].toString().let {
when(it) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw error("Not Valid Input")
}
}
val yourChoice = calculateYourSelection(opponentsChoice, endRoundResult)
totalPoints += calculateScore(opponentsChoice, yourChoice)
}
return totalPoints
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e438c3527ff7c69c13985dcd7c55145336d4f9ca | 2,955 | aoc-kotlin-2022 | Apache License 2.0 |
src/Day02.kt | mcrispim | 573,449,109 | false | {"Kotlin": 46488} | fun main() {
// Part 1
// First Column (adversary move) A = Rock, B = Paper, C = Scissor
// Second column (your move) X = Rock, Y = Paper, Z = Scissor
fun part1(input: List<String>): Int {
val handPoints = mapOf(
"A X" to 4, "A Y" to 8, "A Z" to 3,
"B X" to 1, "B Y" to 5, "B Z" to 9,
"C X" to 7, "C Y" to 2, "C Z" to 6
)
return input.sumOf { handPoints[it]!!}
}
// Part 2
// First Column (adversary move) A = Rock, B = Paper, C = Scissor
// Second column (result) X = lose, Y = draw, Z = win
fun part2(input: List<String>): Int {
val handPoints = mapOf(
"A X" to 3, "A Y" to 4, "A Z" to 8,
"B X" to 1, "B Y" to 5, "B Z" to 9,
"C X" to 2, "C Y" to 6, "C Z" to 7
)
return input.sumOf { handPoints[it]!! }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5fcacc6316e1576a172a46ba5fc9f70bcb41f532 | 1,147 | AoC2022 | Apache License 2.0 |
2020/src/year2020/day07/Day07.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2020.day07
import util.readAllLines
import java.util.regex.Pattern
private fun getRules(filename: String): Map<String, Map<String, Int>> {
val input = readAllLines(filename)
val contentsPattern = Pattern.compile("([0-9])+ (.*)? bag.*")
val map = mutableMapOf<String, MutableMap<String, Int>>()
input.forEach { line ->
val parts = line.split(" contain ")
val target = parts[0].replace(" bags", "")
if (!map.containsKey(target)) {
map[target] = mutableMapOf()
}
val targetMap = checkNotNull(map[target])
val contents = parts[1].split(", ")
contents.forEach {
val matcher = contentsPattern.matcher(it)
val matches = matcher.matches()
if (matches) {
val number = matcher.group(1).toInt()
val type = matcher.group(2)
targetMap[type] = number
}
}
}
return map
}
private fun findBagType(parentMap: Map<String, Map<String, Int>>, parentType: String, type: String) : Boolean {
parentMap[parentType]?.entries?.forEach { entry ->
if (entry.key == type) {
return true
} else {
if (findBagType(parentMap, entry.key, type)) {
return true
}
}
}
return false
}
private fun recursiveCountBagType(total: Int, parentMap: Map<String, Map<String, Int>>, type: String) : Int {
var nextTotal = total
parentMap[type]?.entries?.forEach { entry ->
val childTotal = recursiveCountBagType(total, parentMap, entry.key)
nextTotal += entry.value * (1 + childTotal)
}
return nextTotal
}
fun main() {
val map = getRules("input.txt")
val count = map.entries.count {
findBagType(map, it.key, "shiny gold")
}
println(count)
val total = recursiveCountBagType(0, map, "shiny gold")
println(total)
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 1,931 | adventofcode | MIT License |
src/Day15.kt | zirman | 572,627,598 | false | {"Kotlin": 89030} | import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
import kotlin.system.measureTimeMillis
data class Pos(val x: Int, val y: Int)
data class Sensor(val x: Int, val y: Int)
data class Beacon(val x: Int, val y: Int)
sealed interface SensorGrid {
object Air : SensorGrid
object Sensor : SensorGrid
object Beacon : SensorGrid
object Scanned : SensorGrid
}
data class Range(val start: Int, val end: Int)
fun Range.contains(x: Int): Boolean {
return x in start..end
}
fun Range.contains(range: Range): Boolean {
return start <= range.start && end >= range.end
}
// combines two ranges if into a single continuous range
fun tryMerge(r1: Range, r2: Range): Range? {
return when {
r1.contains(r2.start - 1) -> Range(r1.start, max(r1.end, r2.end))
r1.contains(r2.end + 1) -> Range(min(r1.start, r2.start), r1.end)
r2.contains(r1.start - 1) -> Range(r2.start, max(r1.end, r2.end))
r2.contains(r1.end + 1) -> Range(min(r1.start, r2.start), r2.end)
else -> null
}
}
fun merge(rs: List<Range>, r: Range): List<Range> {
return buildList {
var m = r
rs.forEach { r2 ->
val q = tryMerge(r2, m)
if (q != null) {
m = q
} else {
add(r2)
}
}
add(m)
}
}
operator fun Range.minus(range: Range): List<Range> {
return if (start < range.start) {
if (end > range.end) {
listOf(Range(start, range.start - 1), Range(range.end + 1, end))
} else {
listOf(Range(start, range.start - 1))
}
} else if (start <= range.end) {
if (end > range.end) {
listOf(Range(range.end + 1, end))
} else {
listOf()
}
} else {
listOf(this)
}
}
operator fun List<Range>.minus(range: Range): List<Range> {
return this.fold(emptyList()) { acc, r ->
acc + (r - range)
}
}
val Range.size: Int
get() {
return end - start + 1
}
@ExperimentalStdlibApi
fun main() {
fun part1(input: List<String>, searchRow: Int): Int {
val sensors = input.map { line ->
val (a, b, c, d) = """^Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)$"""
.toRegex()
.matchEntire(line)!!
.destructured
val sensor = Sensor(a.toInt(), b.toInt())
val beacon = Beacon(c.toInt(), d.toInt())
val manhattanDistance = (sensor.x - beacon.x).absoluteValue + (sensor.y - beacon.y).absoluteValue
Triple(sensor, beacon, manhattanDistance)
}
val minX = sensors.minOf { (s, _, m) -> s.x - m }
val maxX = sensors.maxOf { (s, _, m) -> s.x + m }
val minY = sensors.minOf { (s, _, m) -> s.y - m }
val maxY = sensors.maxOf { (s, _, m) -> s.y + m }
// val width = maxX - minX + 1
// val height = maxY - minY + 1
val xRange = minX..maxX
val yRange = minY..maxY
// operator fun List<List<SensorGrid>>.get(p: Pos): SensorGrid {
// return if (p.x in xRange && p.y in yRange) this[p.y - minY][p.x - minX]
// else SensorGrid.Air
// }
//
// operator fun List<MutableList<SensorGrid>>.set(p: Pos, t: SensorGrid) {
// when (this[p.y - minY][p.x - minX]) {
// SensorGrid.Air, SensorGrid.Scanned -> {
// this[p.y - minY][p.x - minX] = t
// }
//
// else -> {}
// }
// }
// println(width)
// println(height)
// println(width * height)
val grid: MutableMap<Pos, SensorGrid> = mutableMapOf()
// fun Array<SensorGrid>.toString(width: Int): String {
// return toList().chunked(width).joinToString("\n") { row ->
// row.joinToString("") {
// when (it) {
// SensorGrid.Air -> "."
// SensorGrid.Beacon -> "B"
// SensorGrid.Scanned -> "#"
// SensorGrid.Sensor -> "S"
// }
// }
// }
// }
sensors.forEach { (s, b, m) ->
grid[Pos(s.x, s.y)] = SensorGrid.Sensor
grid[Pos(b.x, b.y)] = SensorGrid.Beacon
val visited = mutableSetOf<Pos>()
val fillScanned = DeepRecursiveFunction { p: Pos ->
if (visited.contains(p) || (p.x - s.x).absoluteValue + (p.y - s.y).absoluteValue > m) return@DeepRecursiveFunction
visited.add(p)
when (grid[p]) {
SensorGrid.Air, SensorGrid.Scanned, null -> {
grid[p] = SensorGrid.Scanned
}
else -> {}
}
callRecursive(Pos(p.x - 1, p.y))
callRecursive(Pos(p.x + 1, p.y))
callRecursive(Pos(p.x, p.y - 1))
callRecursive(Pos(p.x, p.y + 1))
}
// fun fillScanned(p: Pos) {
// if (visited.contains(p) || (p.x - s.x).absoluteValue + (p.y - s.y).absoluteValue > m) return
// visited.add(p)
// when (grid[p]) {
// SensorGrid.Air, SensorGrid.Scanned, null -> {
// grid[p] = SensorGrid.Scanned
// }
//
// else -> {}
// }
// fillScanned(Pos(p.x - 1, p.y))
// fillScanned(Pos(p.x + 1, p.y))
// fillScanned(Pos(p.x, p.y - 1))
// fillScanned(Pos(p.x, p.y + 1))
// }
fillScanned(Pos(s.x, s.y))
// yRange.joinToString("\n") { y ->
// xRange.joinToString("") { x ->
// when (grid[Pos(x, y)]) {
// SensorGrid.Air -> "."
// SensorGrid.Beacon -> "B"
// SensorGrid.Scanned -> "#"
// SensorGrid.Sensor -> "S"
// null -> "."
// }
// }
// }.also { println(it) }
// println(grid.toString())
// println()
}
yRange.joinToString("\n") { y ->
y.toString().last() + xRange.joinToString("") { x ->
when (grid[Pos(x, y)]) {
SensorGrid.Air -> "."
SensorGrid.Beacon -> "B"
SensorGrid.Scanned -> "#"
SensorGrid.Sensor -> "S"
null -> "."
}
}
}.also { println(it) }
return xRange.count { x -> grid[Pos(x, searchRow)] == SensorGrid.Scanned }
}
fun part2(input: List<String>, maxXY: Int): Long {
val sensors = input.map { line ->
val (a, b, c, d) = """^Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)$"""
.toRegex()
.matchEntire(line)!!
.destructured
val sensor = Sensor(a.toInt(), b.toInt())
val beacon = Beacon(c.toInt(), d.toInt())
val manhattanDistance = (sensor.x - beacon.x).absoluteValue + (sensor.y - beacon.y).absoluteValue
Pair(sensor, manhattanDistance)
}
//maxXY / 20
return buildList {
(0..maxXY).map { y ->
val xRange = Range(0, maxXY)
var ranges = listOf<Range>()
sensors.forEach { (s, m) ->
val dif = m - (s.y - y).absoluteValue
if (dif >= 0) {
ranges = merge(ranges, Range(s.x - dif, s.x + dif))
}
}
ranges
.fold(listOf(xRange)) { acc, range -> acc - range }
.ifEmpty { null }
?.let { add(Pair(y, it)) }
}
}
.let {
check(it.size == 1)
val (y, rs) = it.first()
check(rs.size == 1)
val (q) = rs
check(q.size == 1)
q.start.toLong() * 4_000_000L + y.toLong()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
val input = readInput("Day15")
check(
part2(
testInput,
20
) == 56000011L
)
println(
measureTimeMillis {
part2(
input,
4_000_000
)
}
)
}
| 0 | Kotlin | 0 | 1 | 2ec1c664f6d6c6e3da2641ff5769faa368fafa0f | 8,717 | aoc2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumDeleteSum.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* 712. Minimum ASCII Delete Sum for Two Strings
* @see <a href="https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/">Source</a>
*/
fun interface MinimumDeleteSum {
operator fun invoke(s1: String, s2: String): Int
}
/**
* Approach 1: Recursion
*/
class MinimumDeleteSumRecursion : MinimumDeleteSum {
override operator fun invoke(s1: String, s2: String): Int {
return computeCost(s1, s2, s1.length - 1, s2.length - 1)
}
// Return minimum cost to make s1[0...i] and s2[0...j] equal
private fun computeCost(s1: String, s2: String, i: Int, j: Int): Int {
// If s1 is empty, then we need to delete all characters of s2
if (i < 0) {
var deleteCost = 0
for (pointer in 0..j) {
deleteCost += s2[pointer].code
}
return deleteCost
}
// If s2 is empty, then we need to delete all characters of s1
if (j < 0) {
var deleteCost = 0
for (pointer in 0..i) {
deleteCost += s1[pointer].code
}
return deleteCost
}
// Check s1[i] and s2[j]
return if (s1[i] == s2[j]) {
computeCost(s1, s2, i - 1, j - 1) // Characters match, no cost, move to the next characters
} else {
// Calculate the minimum cost to make s1[0...i] and s2[0...j] equal by considering three operations:
// 1. Delete s1[i] and move to the next character in s1.
// 2. Delete s2[j] and move to the next character in s2.
// 3. Replace s1[i] with s2[j] and move to the next characters in both s1 and s2.
min(
(s1[i].code + computeCost(s1, s2, i - 1, j)).toDouble(),
min(
(s2[j].code + computeCost(s1, s2, i, j - 1)).toDouble(),
(s1[i].code + s2[j].code + computeCost(s1, s2, i - 1, j - 1)).toDouble(),
),
).toInt()
}
}
}
class MinimumDeleteSumTopDown : MinimumDeleteSum {
// Hash Map to store the result of each sub-problem.
private val savedResult: MutableMap<Pair<Int, Int>, Int> = HashMap()
override operator fun invoke(s1: String, s2: String): Int {
// Return minimum cost to make s1[0...i] and s2[0...j] equal
return computeCost(s1, s2, s1.length - 1, s2.length - 1)
}
// Return minimum cost to make s1[0...i] and s2[0...j] equal
private fun computeCost(s1: String, s2: String, i: Int, j: Int): Int {
// If both strings are empty, then no deletion is required
if (i < 0 && j < 0) {
return 0
}
// If already computed, then return the result from the hash map
val key = Pair(i, j)
if (savedResult.containsKey(key)) {
return savedResult[key]!!
}
// If any one string is empty, delete all characters of the other string
if (i < 0) {
savedResult[key] = s2[j].code + computeCost(s1, s2, i, j - 1)
return savedResult[key]!!
}
if (j < 0) {
savedResult[key] = s1[i].code + computeCost(s1, s2, i - 1, j)
return savedResult[key]!!
}
// Call sub-problem depending on s1[i] and s2[j]
// Save the computed result.
if (s1[i] == s2[j]) {
savedResult[key] =
computeCost(s1, s2, i - 1, j - 1) // Characters match, no cost, move to the next characters
} else {
// Calculate the minimum cost to make s1[0...i] and s2[0...j] equal by considering two operations:
// 1. Delete s1[i] and move to the next character in s1.
// 2. Delete s2[j] and move to the next character in s2.
savedResult[key] = min(
(s1[i].code + computeCost(s1, s2, i - 1, j)).toDouble(),
(s2[j].code + computeCost(s1, s2, i, j - 1)).toDouble(),
).toInt()
}
return savedResult[key]!!
}
}
/**
* Approach 3: Bottom-up Dynamic Programming
*/
class MinimumDeleteSumBottomUp : MinimumDeleteSum {
override operator fun invoke(s1: String, s2: String): Int {
// Prepare the two-dimensional array
val m: Int = s1.length
val n: Int = s2.length
val computeCost = Array(m + 1) { IntArray(n + 1) }
// Fill in the base case values
for (i in 1..m) {
computeCost[i][0] = computeCost[i - 1][0] + s1[i - 1].code
}
for (j in 1..n) {
computeCost[0][j] = computeCost[0][j - 1] + s2[j - 1].code
}
// Fill the remaining cells using the Bellman Equation
for (i in 1..m) {
for (j in 1..n) {
if (s1[i - 1] == s2[j - 1]) {
computeCost[i][j] = computeCost[i - 1][j - 1]
} else {
computeCost[i][j] = min(
s1[i - 1].code + computeCost[i - 1][j],
s2[j - 1].code + computeCost[i][j - 1],
)
}
}
}
// Return the answer for entire input strings
return computeCost[m][n]
}
}
/**
* Approach 4: Space-Optimized Bottom-up Dynamic Programming
*/
class MinimumDeleteSumBottomUpOtp : MinimumDeleteSum {
override operator fun invoke(s1: String, s2: String): Int {
// Make sure s2 is smaller string
if (s1.length < s2.length) {
return invoke(s2, s1)
}
// Case for empty s1
val m = s1.length
val n = s2.length
val currRow = IntArray(n + 1)
for (j in 1..n) {
currRow[j] = currRow[j - 1] + s2[j - 1].code
}
// Compute answer row-by-row
for (i in 1..m) {
var diag = currRow[0]
currRow[0] += s1[i - 1].code
for (j in 1..n) {
// If characters are the same, the answer is top-left-diagonal value
val answer: Int = if (s1[i - 1] == s2[j - 1]) {
diag
}
// Otherwise, the answer is minimum of top and left values with
// deleted character's ASCII value
else {
min(
s1[i - 1].code + currRow[j],
s2[j - 1].code + currRow[j - 1],
)
}
// Before overwriting currRow[j] with answer, save it in diag
// for the next column
diag = currRow[j]
currRow[j] = answer
}
}
// Return the answer
return currRow[n]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 7,353 | kotlab | Apache License 2.0 |
kotlin/2020/round-1a/pattern-matching/src/main/kotlin/Solution.kt | ShreckYe | 345,946,821 | false | null | fun main() {
val T = readLine()!!.toInt()
repeat(T) { t ->
val N = readLine()!!.toInt()
val P = (0 until N).map { readLine()!! }
println("Case #${t + 1}: ${case(N, P)}")
}
}
fun case(N: Int, P: List<String>): String? =
getName(P.map { it.toList() })
fun getName(patterns: List<List<Char>>): String? =
getNameSequence(patterns)?.joinToString("") ?: "*"
fun getNameSequence(patterns: List<List<Char>>): Sequence<Char>? {
if (patterns.any { it.isEmpty() })
return if (patterns.asSequence().filter { it.isNotEmpty() }.all { it.all { it == '*' } }) "".asSequence() else null
// All are not empty
val heads = patterns.map { it[0] }
if (heads.zipWithNext().all { it.first == it.second }) {
val head = heads[0]
if (head != '*') return getNameSequence(patterns.map { it.subList(1, it.size) })?.let { sequenceOf(head) + it }
} else {
val distinctLetters = heads.asSequence().filter { it != '*' }.distinct().toList()
val nDistinctLetters = distinctLetters.count()
if (nDistinctLetters == 1)
return getNameSequence(patterns.map { if (it[0] != '*') it.subList(1, it.size) else it })
?.let { sequenceOf(distinctLetters[0]) + it }
else if (nDistinctLetters > 1) return null
}
// All heads are asterisks
if (patterns.any { it.last() != '*' })
return getNameSequence(patterns.map { it.reversed() })?.run { toList().asReversed().asSequence() }
// All patterns start and end with asterisks
val patternStrings = patterns.map { it.subList(1, it.size).asSequence().filter { it != '*' } }
return patternStrings.asSequence().flatten()
} | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 1,698 | google-code-jam | MIT License |
melif/src/main/kotlin/ru/ifmo/ctddev/isaev/measure.kt | siviae | 53,358,845 | false | {"Kotlin": 152748, "Java": 152582} | package ru.ifmo.ctddev.isaev
/**
* @author iisaev
*/
abstract class RelevanceMeasure(val minValue: Double, val maxValue: Double) {
abstract fun evaluate(feature: Feature, classes: List<Int>): Double
fun evaluate(original: FeatureDataSet): DoubleArray {
return original.features.map { evaluate(it, original.classes) }
.toDoubleArray()
}
override fun toString(): String {
return javaClass.simpleName
}
}
private fun toDoubleArray(values: List<Int>): DoubleArray {
val featureValues = DoubleArray(values.size)
values.forEachIndexed { index, value ->
featureValues[index] = value.toDouble()
}
return featureValues
}
class SpearmanRankCorrelation : RelevanceMeasure(-1.0, 1.0) {
override fun evaluate(feature: Feature, classes: List<Int>): Double {
val featureValues = toDoubleArray(feature.values)
val doubleClasses = toDoubleArray(classes)
return evaluate(
featureValues,
doubleClasses
)
}
fun evaluate(values: DoubleArray, classes: DoubleArray): Double {
val xMean = values.average()
val yMean = classes.average()
val sumDeviationsXY = values.indices
.map { i ->
val devX = values[i] - xMean
val devY = classes[i] - yMean
devX * devY
}
.sum()
val squaredDeviationX = values.asSequence()
.map { it - xMean }
.map { it * it }
.sum()
val squaredDeviationY = classes.asSequence()
.map { it - yMean }
.map { it * it }
.sum()
return sumDeviationsXY / Math.sqrt(squaredDeviationX * squaredDeviationY)
}
}
class FitCriterion : RelevanceMeasure(0.0, 1.0) {
override fun evaluate(feature: Feature, classes: List<Int>): Double {
val values = feature.values
val mean0 = calculateMean(0, values, classes)
val mean1 = calculateMean(1, values, classes)
val var0 = calculateVariance(0, mean0, values, classes)
val var1 = calculateVariance(1, mean1, values, classes)
val fcpSum = values.indices
.filter { i ->
val fcp = calculateFCP(values[i], mean0, mean1, var0, var1)
val clazz = classes[i]
fcp == clazz
}
.count()
return fcpSum.toDouble() / classes.size
}
private fun calculateVariance(clazz: Int, mean0: Double, values: List<Int>, classes: List<Int>): Double {
return classes.indices
.filter { i -> classes[i] == clazz }
.map { index -> Math.pow(values[index] - mean0, 2.0) }
.average()
}
private fun calculateMean(clazz: Int, values: List<Int>, classes: List<Int>): Double {
return classes.indices
.filter { classes[it] == clazz }
.map({ values[it] })
.average()
}
private fun calculateFCP(value: Int, mean0: Double, mean1: Double, var0: Double, var1: Double): Int {
val val0 = Math.abs(value - mean0) / var0
val val1 = Math.abs(value - mean1) / var1
return if (val0 < val1) 0 else 1
}
}
| 0 | Kotlin | 0 | 1 | 2a3300ea32dda160d400258f2400c03ad84cb713 | 3,333 | parallel-feature-selection | MIT License |
src/day05/Day05.kt | TimberBro | 572,681,059 | false | {"Kotlin": 20536} | package day05
import readInput
data class Instruction(val quantity: Int, val source: Int, val destination: Int)
fun main() {
fun part1(input: List<String>): String {
val crates = parseCrates(input)
val instructions = parseInstructions(input)
for (instruction in instructions) {
for (i in 1..instruction.quantity)
crates[instruction.destination].addLast(crates[instruction.source].removeLast())
}
val result = StringBuilder()
for (crate in crates) {
result.append(crate.removeLast())
}
return result.toString()
}
fun part2(input: List<String>): String {
val crates = parseCrates(input)
val instructions = parseInstructions(input)
for (instruction in instructions) {
if (instruction.quantity == 1) {
crates[instruction.destination].addLast(crates[instruction.source].removeLast())
} else {
val buffer = ArrayList<Char>()
for (i in 1..instruction.quantity) {
buffer.add(crates[instruction.source].removeLast())
}
crates[instruction.destination].addAll(buffer.reversed())
}
}
val result = StringBuilder()
for (crate in crates) {
result.append(crate.removeLast())
}
return result.toString()
}
val testInput = readInput("day05/Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("day05/Day05")
println(part1(input))
println(part2(input))
}
private fun parseCrates(input: List<String>): ArrayList<ArrayDeque<Char>> {
val cratesMap = input.asSequence()
.flatMap { "\\[(\\w+)\\]".toRegex().findAll(it) }
.groupBy { it.range.first + 1 }
.toMap()
// Parse second time to work with indexes as usual
val crates = ArrayList<ArrayDeque<Char>>()
for (entry in cratesMap.entries.sortedBy { it.key }) {
val line = ArrayDeque<Char>()
for (result in entry.value) {
line.addFirst(result.groupValues[1].toCharArray()[0])
}
crates.add(line)
}
return crates
}
private fun parseInstructions(input: List<String>): List<Instruction> {
val instructions = input.asSequence()
.flatMap { "move (\\d+) from (\\d+) to (\\d+)".toRegex().findAll(it) }
.map { x ->
Instruction(
x.groupValues[1].toInt(),
x.groupValues[2].toInt() - 1,
x.groupValues[3].toInt() - 1
)
}
.toList()
return instructions
} | 0 | Kotlin | 0 | 0 | 516a98e5067d11f0e6ff73ae19f256d8c1bfa905 | 2,771 | AoC2022 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2023/Day11.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2023
import se.saidaspen.aoc.util.*
import kotlin.math.abs
fun main() = Day11.run()
object Day11 : Day(2023, 11) {
private val map = toMap(input)
private val emptyRows = input.lines().indices.filter { r -> map.filter { it.key.second == r }.all { it.value == '.' } }.toList()
private val emptyCols = input.lines()[0].indices.filter { c -> map.filter { it.key.first == c }.all { it.value == '.' } }.toList()
private val galaxies = map.filter { it.value == '#' }.keys.toList()
private val pairs = combinations(galaxies.toTypedArray(), 2).toList()
private fun dist(a: P<Int, Int>, b: P<Int, Int>, exp: Long): Long {
val timesY = emptyRows.count { it < b.second && it > a.second }.toLong()
val timesX = emptyCols.count { it < b.first && it > a.first || it > b.first && it < a.first }.toLong()
return abs(a.x - b.x).toLong() + timesX * exp + abs(a.y - b.y).toLong() + timesY * exp
}
override fun part1() = pairs.sumOf { dist(it[0], it[1], 1) }
override fun part2() = pairs.sumOf { dist(it[0], it[1], 999999) }
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,107 | adventofkotlin | MIT License |
src/Day05.kt | dominik003 | 573,083,805 | false | {"Kotlin": 9376} | import java.util.*
fun main() {
fun part1(input: Pair<Map<Int, ArrayDeque<Char>>, List<Triple<Int, Int, Int>>>): String {
val stackMap = input.first
val commands = input.second
commands.forEach {
for (i in 0 until it.first) {
val firstEl = stackMap[it.second - 1]?.pop()
if (firstEl != null) {
stackMap[it.third - 1]?.push(firstEl)
}
}
}
return stackMap.map { it.value.pop() }.joinToString("")
}
fun part2(input: Pair<Map<Int, ArrayDeque<Char>>, List<Triple<Int, Int, Int>>>): String {
val stackMap = input.first
val commands = input.second
commands.forEach { trip ->
val tempStack = ArrayDeque<Char>()
for (i in 0 until trip.first) {
val curEl = stackMap[trip.second - 1]?.pop()
if (curEl != null) {
tempStack.push(curEl)
}
}
tempStack.forEach { el ->
stackMap[trip.third - 1]?.push(el)
}
}
return stackMap.map { it.value.pop() }.joinToString("")
}
fun preprocess(input: List<String>): Pair<Map<Int, ArrayDeque<Char>>, List<Triple<Int, Int, Int>>> {
val stackSize = input.indexOfFirst { it.startsWith(" 1") }
val bucketCount = (input[stackSize].length + 2) / 4
val stackMap = (0 until bucketCount).associateWith { ArrayDeque<Char>() }
((stackSize - 1) downTo 0).forEach { stackPos ->
(0 until bucketCount).forEach { bucketPos ->
val curLine = input[stackPos]
val curPos = (bucketPos * 4) + 1
if (curPos <= curLine.length && curLine[curPos] != ' ') {
stackMap[bucketPos]?.push(curLine[curPos])
}
}
}
val commands = mutableListOf<Triple<Int, Int, Int>>()
(stackSize + 2 until input.size).forEach {
val split = input[it].split(" ")
commands.add(
Triple(
split[1].toInt(), split[3].toInt(), split[5].toInt()
)
)
}
return Pair(stackMap, commands)
}
// test if implementation meets criteria from the description, like:
check(part1(preprocess(readInput(5, true))) == "CMZ")
check(part2(preprocess(readInput(5, true))) == "MCD")
println(part1(preprocess(readInput(5))))
println(part2(preprocess(readInput(5))))
} | 0 | Kotlin | 0 | 0 | b64d1d4c96c3dd95235f604807030970a3f52bfa | 2,542 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2018/Day07.kt | tginsberg | 155,878,142 | false | null | /*
* Copyright (c) 2018 by <NAME>
*/
/**
* Advent of Code 2018, Day 7 - The Sum of Its Parts
*
* Problem Description: http://adventofcode.com/2018/day/7
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day7/
*/
package com.ginsberg.advent2018
class Day07(input: List<String>) {
private val allPairs = parseInput(input)
private val childrenOf: Map<Char, Set<Char>> = generateDependencies(allPairs)
private val parentsOf: Map<Char, Set<Char>> = generateDependencies(allPairs.map { it.second to it.first })
private val allKeys = childrenOf.keys.union(parentsOf.keys)
fun solvePart1(): String {
val ready = allKeys.filterNot { it in parentsOf }.toMutableList()
val done = mutableListOf<Char>()
while (ready.isNotEmpty()) {
val next = ready.sorted().first().also { ready.remove(it) }
done.add(next)
childrenOf[next]?.let { maybeReadySet ->
ready.addAll(maybeReadySet.filter { maybeReady ->
parentsOf.getValue(maybeReady).all { it in done }
})
}
}
return done.joinToString(separator = "")
}
fun solvePart2(workers: Int, costFunction: (Char) -> Int): Int {
val ready = allKeys.filterNot { it in parentsOf }.map { it to costFunction(it) }.toMutableList()
val done = mutableListOf<Char>()
var time = 0
while (ready.isNotEmpty()) {
// Work on things that are ready.
// Do one unit of work per worker, per item at the head of the queue.
ready.take(workers).forEachIndexed { idx, work ->
ready[idx] = Pair(work.first, work.second - 1)
}
// These are done
ready.filter { it.second == 0 }.forEach { workItem ->
done.add(workItem.first)
// Now that we are done, add some to ready that have become unblocked
childrenOf[workItem.first]?.let { maybeReadySet ->
ready.addAll(
maybeReadySet.filter { maybeReady ->
parentsOf.getValue(maybeReady).all { it in done }
}
.map { it to costFunction(it) }
.sortedBy { it.first }
)
}
}
// Remove anything that we don't need to look at anymore.
ready.removeIf { it.second == 0 }
time++
}
return time
}
private fun parseInput(input: List<String>): List<Pair<Char, Char>> =
input.map { row ->
row.split(" ").run { this[1].first() to this[7].first() }
}
private fun generateDependencies(input: List<Pair<Char, Char>>): Map<Char, Set<Char>> =
input
.groupBy { it.first }
.mapValues { (_, value) -> value.map { it.second }.toSet() }
companion object {
fun exampleCostFunction(c: Char): Int = actualCostFunction(c) - 60
fun actualCostFunction(c: Char): Int = 60 + (c - 'A' + 1)
}
} | 0 | Kotlin | 1 | 18 | f33ff59cff3d5895ee8c4de8b9e2f470647af714 | 3,133 | advent-2018-kotlin | MIT License |
src/main/kotlin/g2401_2500/s2435_paths_in_matrix_whose_sum_is_divisible_by_k/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2401_2500.s2435_paths_in_matrix_whose_sum_is_divisible_by_k
// #Hard #Array #Dynamic_Programming #Matrix
// #2023_07_05_Time_752_ms_(100.00%)_Space_76.1_MB_(100.00%)
class Solution {
private val mod = (1e9 + 7).toInt()
private var row = 0
private var col = 0
private lateinit var cache: Array<Array<IntArray>>
fun numberOfPaths(grid: Array<IntArray>, k: Int): Int {
row = grid.size
col = grid[0].size
cache = Array(row) { Array(col) { IntArray(k) { -1 } } }
return numberOfPaths(grid, 0, 0, k, 0)
}
// return the number of path with <Sum([r][c] ~ [ROW][COL]) % k == remainder>
private fun numberOfPaths(grid: Array<IntArray>, r: Int, c: Int, k: Int, remainder: Int): Int {
if (r to c !in grid) return 0
if (cache[r][c][remainder] != -1) return cache[r][c][remainder]
if (r == row - 1 && c == col - 1)
return if (grid[r][c] % k == remainder) 1 else 0
return ((remainder - grid[r][c] + 100 * k) % k).let {
(numberOfPaths(grid, r + 1, c, k, it) + numberOfPaths(grid, r, c + 1, k, it)) % mod
}.also {
cache[r][c][remainder] = it
}
}
private operator fun Array<IntArray>.contains(pair: Pair<Int, Int>): Boolean {
return (0 <= pair.first && pair.first < this.size) &&
(0 <= pair.second && pair.second < this[0].size)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,411 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/day13/Day13.kt | alxgarcia | 435,549,527 | false | {"Kotlin": 91398} | package day13
import java.io.File
/* Syntax sugar */
typealias Dot = Pair<Int, Int>
typealias PaperFold = Pair<Char, Int>
private val Dot.x: Int
get() = this.first
private val Dot.y: Int
get() = this.second
/* end */
fun parseInput(lines: List<String>): Pair<List<Dot>, List<PaperFold>> {
val dots =
lines
.takeWhile { it.isNotEmpty() && it.first().isDigit() }
.map {
val (x, y) = it.split(",").map(String::toInt)
x to y
}
fun extractAxisAndValue(string: String): Pair<Char, Int> {
val (sentence, value) = string.split("=")
return (sentence.last() to value.toInt())
}
val paperFolds = lines
.drop(dots.size + 1) // removing also the empty line separator
.map(::extractAxisAndValue)
return Pair(dots, paperFolds)
}
fun fold(dots: List<Dot>, paperFold: PaperFold): List<Dot> {
val (axis, value) = paperFold
return when (axis) {
'x' -> {
val (base, foldingSide) = dots
.filterNot { it.x == value }
.partition { it.x < value }
(base + foldingSide.map { (value - (it.x - value)) to it.y }).distinct()
}
'y' -> {
val (base, foldingSide) = dots
.filterNot { it.y == value }
.partition { it.y < value }
(base + foldingSide.map { it.x to (value - (it.y - value)) }).distinct()
}
else -> TODO("Not supported axis :)")
}
}
// Actually not needed
fun countVisibleDotsAfterFolding(dots: List<Dot>, paperFolds: List<PaperFold>): Int =
paperFolds.fold(dots, ::fold).size
fun countVisibleDotsAfterFirstFolding(dots: List<Dot>, paperFolds: List<PaperFold>): Int =
fold(dots, paperFolds.first()).size
fun printAfterAllFolds(dots: List<Dot>, paperFolds: List<PaperFold>) {
fun print(dots: List<Dot>) {
val rowMax = dots.maxOf { it.y }
val columnMax = dots.maxOf { it.x }
(0..rowMax).forEach { y ->
(0..columnMax).forEach { x ->
if (dots.contains(x to y)) print('#')
else print('.')
}
println()
}
}
print(paperFolds.fold(dots, ::fold))
}
fun main() {
File("./input/day13.txt").useLines { lines ->
val (dots, folds) = parseInput(lines.toList())
println(countVisibleDotsAfterFirstFolding(dots, folds))
printAfterAllFolds(dots, folds)
}
}
// ARHZPCUH | 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 2,272 | advent-of-code-2021 | MIT License |
src/2021-Day03.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | fun main() {
fun part1(input: List<String>): Pair<Int,Int> {
val size = input[0].trim().length
val counts = MutableList(size) { 0 }
var total = 0
for (line in input) {
++total
var ix = 0
for (digit in line.trim()) {
if (digit == '1') {
++counts[ix]
}
++ix
}
}
var gamma = 0
val threshold = total.toFloat()/2
for (count in counts) {
gamma = gamma shl 1
if (count > threshold) {
gamma++
}
}
var epsilon = (1 shl counts.size) - 1 - gamma
return Pair(gamma, epsilon)
}
fun filterBitPosition(input: List<String>, bitPosition: Int): Pair<List<String>, List<String>> {
val sorted = input.fold(mutableListOf(mutableListOf<String>(),mutableListOf<String>())) { acc, s ->
acc[s[bitPosition] - '0'].add(s)
acc
}
return Pair(sorted[0].toList(), sorted[1].toList())
}
fun part2(input: List<String>): Pair<Int,Int> {
var o2GenInput = input
var bitPosition = 0
while (o2GenInput.size > 1) {
val (list0, list1) = filterBitPosition(o2GenInput, bitPosition)
o2GenInput = if (list1.size >= list0.size) list1 else list0
++bitPosition
}
val o2GenValue = o2GenInput.first().trim().toInt(2)
var co2ScrubInput = input
bitPosition = 0
while (co2ScrubInput.size > 1) {
val (list0, list1) = filterBitPosition(co2ScrubInput, bitPosition)
co2ScrubInput = if (list1.size >= list0.size) list0 else list1
++bitPosition
}
val co2ScrubValue = co2ScrubInput.first().trim().toInt(2)
return Pair(o2GenValue, co2ScrubValue)
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"00100\n",
"11110\n",
"10110\n",
"10111\n",
"10101\n",
"01111\n",
"00111\n",
"11100\n",
"10000\n",
"11001\n",
"00010\n",
"01010\n"
)
val (gamma, epsilon) = part1(testInput)
println("gamma:${gamma}, epsilon:${epsilon}, product:${gamma * epsilon}")
check(gamma == 22)
check(epsilon == 9)
//
// check(part1(testInput) == 7)
// check(part2(testInput) == 5)
//
val input = readInput("2021-day3")
val (gamma2, epsilon2) = part1(input)
println("gamma:${gamma2}, epsilon:${epsilon2}, product:${gamma2 * epsilon2}")
val (o2, co2) = part2(testInput)
println("o2:${o2}, co2:${co2}, product:${o2 * co2}")
check(o2 == 23)
check(co2 == 10)
val (o2Real, co2Real) = part2(input)
println("o2:${o2Real}, co2:${co2Real}, product:${o2Real * co2Real}")
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 2,882 | 2022-aoc-kotlin | Apache License 2.0 |
leetcode/src/offer/middle/Offer13.kt | zhangweizhe | 387,808,774 | false | null | package offer.middle
fun main() {
// 剑指 Offer 13. 机器人的运动范围
// https://leetcode.cn/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/
println(movingCount(16,16,2))
}
fun movingCount(m: Int, n: Int, k: Int): Int {
val visited = ArrayList<RobotPair>()
help1(visited, m, n, k, 0, 0)
return visited.size
}
private fun help1(visited: MutableList<RobotPair>, m: Int, n: Int, k: Int, i: Int, j: Int) {
if (i < 0 || i >= m) {
return
}
if (j < 0 || j >= n) {
return
}
val find = visited.find {
it.x == i && it.y == j
}
if (find != null) {
// 已经遍历过了
return
}
val sumI = sum(i)
if (sumI > k) {
// i 的数位和已经大于 k 了,不能进入
return
}
if (sumI + sum(j) > k) {
return
}
// 添加到访问集合中
visited.add(RobotPair(i, j))
// 向下、向右遍历
help1(visited, m, n, k, i, j+1)
help1(visited, m, n, k, i+1, j)
}
private fun help(visited: MutableSet<RobotPair>, m: Int, n: Int, k: Int, i: Int, j: Int) {
if (i < 0 || i >= m) {
// 横坐标越界
return
}
if (j < 0 || j >= n) {
return
}
val sumI = sum(i)
if (sumI > k || sumI + sum(j) > k) {
// 数位和大于0
return
}
// 已经遍历过
val robotPair = RobotPair(i, j)
if (visited.contains(robotPair)) {
return
}
// 当前格子是可以移动到的
visited.add(robotPair)
// 只需向右和向下查找
// 参考题解动画,可运动范围,会随着 k 的增大,逐渐向右、向下扩展
// https://leetcode.cn/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/solution/ji-qi-ren-de-yun-dong-fan-wei-by-leetcode-solution/
help(visited, m, n, k, i+1, j)
help(visited, m, n, k, i, j+1)
}
class RobotPair(val x:Int, val y:Int) {
override fun equals(other: Any?): Boolean {
if (other !is RobotPair) {
return false
}
return other.x == x && other.y == y
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
}
private fun sum(x: Int): Int {
var ret = 0
var tmp = x
while (tmp != 0) {
ret += tmp % 10
tmp /= 10
}
return ret
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,348 | kotlin-study | MIT License |
src/day4/Day04.kt | kongminghan | 573,466,303 | false | {"Kotlin": 7118} | package day4
import readInput
import java.lang.Integer.max
import java.lang.Integer.min
fun main() {
fun String.toIntRange(): IntRange {
val (first, second) = this.split("-")
return first.toInt()..second.toInt()
}
fun ClosedRange<Int>.containedIn(other: ClosedRange<Int>) =
other.contains(this.start) && other.contains(this.endInclusive)
fun List<String>.findContainedRange(transform: (IntRange, IntRange) -> Pair<IntRange, IntRange>?): List<Pair<IntRange, IntRange>> {
return this.mapNotNull {
val (first, second) = it.split(",")
val firstRange = first.toIntRange()
val secondRange = second.toIntRange()
transform(firstRange, secondRange)
}
}
fun part1(input: List<String>): Int {
return input.findContainedRange { firstRange, secondRange ->
if (firstRange.containedIn(secondRange) || secondRange.containedIn(firstRange)) {
firstRange to secondRange
} else {
null
}
}.size
}
fun part2(input: List<String>): Int {
return input.findContainedRange { firstRange, secondRange ->
if ((firstRange.toSet() intersect secondRange.toSet()).isNotEmpty()) {
firstRange to secondRange
} else {
null
}
}.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(day = 4, name = "Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput(day = 4, name = "Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f602900209712090778c161d407ded8c013ae581 | 1,702 | advent-of-code-kotlin | Apache License 2.0 |
archive/2022/Day03.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | package aoc2022
private const val EXPECTED_1 = 157
private const val EXPECTED_2 = 70
private fun Set<Char>.score(): Int {
check(size == 1)
val value = first()
return if (value in 'a'..'z')
value - 'a' + 1
else
value - 'A' + 27
}
private class Day03(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
return readAsLines().sumOf { line ->
val left = line.subSequence(0, line.length / 2).toSet()
val right = line.subSequence(line.length / 2, line.length).toSet()
left.intersect(right).score()
}
}
fun part2(): Any {
return readAsLines().chunked(3).sumOf { group ->
check(group.size == 3)
val sets = group.map { it.toSet() }
sets[0].intersect(sets[1]).intersect(sets[2]).score()
}
}
}
fun main() {
val testInstance = Day03(true)
val instance = Day03(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println(instance.part1())
testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } }
println(instance.part2())
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 1,166 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dp/MaxSum.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
// given an array of arbitrary numbers
// find the largest sum of elements in a contiguous subarray
fun main(args: Array<String>) {
val arr = intArrayOf(-6, 12, -7, 0, 14, -7, 5)
// println(arr.maxSumN2())
// println(arr.maxSumNLogN())
// println(arr.maxSumN())
// println(arr.maxSumKadane())
println(arr.toOneArray().maxSumRedo())
}
// brute force DP: O(N^2)
fun IntArray.maxSumN2(): Int {
// dp[i, j] = sum of this[i..j]
// dp[i, j] = 0, if (i > j || i, j !in 0 until size)
// = this[i], if (i == j)
// = dp[i, j - 1] + this[j], o/w
// we want max(dp[i, j])
val dp = Array(size) { IntArray(size) }
var max = Int.MIN_VALUE
for (i in 0 until size) {
for (j in i until size) {
dp[i, j] = if (i == j) {
this[i]
} else {
if (j == 0) {
this[j]
} else {
dp[i, j - 1] + this[j]
}
}
max = max(max, dp[i][j])
}
}
return max
}
// better: O(n log n)
fun IntArray.maxSumNLogN(s: Int = 0, e: Int = size - 1): Int {
// the basic idea here is:
// there are three cases of the resulting subarray A[i..j]
// 1. j < n / 2 left of the middle line
// 2. i > n / 2 right of the middle line
// 3. i < n / 2 < j crossing the middle line
// we may recursively solve 1 and 2
// and do O(n) to find 3: max prefix sum of A[n / 2 + 1..n] + max suffix sum of A[1..n / 2 - 1]
// finally compare 1, 2, and 3 and get the biggest one as solution
// runtime analysis
// T(n) <= O(n) + 2T(n / 2) -> T ~ O(n log n)
if (s > e) {
return 0
}
if (s == e) {
return max(0, this[s])
}
if (s == e - 1) {
return max(this[s], this[e], this[s] + this[e], 0)
}
val midIdx = s + (e - s) / 2
val left = maxSumNLogN(s, midIdx - 1)
val right = maxSumNLogN(midIdx + 1, e)
var mid = this[midIdx]
mid += prefixSum(midIdx + 1, e)
mid += suffixSum(s, midIdx - 1)
return max(left, right, mid)
}
fun IntArray.prefixSum(s: Int = 0, e: Int = size - 1): Int {
// dp(i): sum for this[s..s + i]
// memoization structure: 1d array dp[0..size - 1 - s] : dp[i] = dp(i)
val dp = IntArray(e - s + 1)
// space complexity: O(n)
// base case:
// dp(i) = this[s] if i = 0
dp[0] = this[s]
// we want max_i{ dp(i) } >= 0
var max = max(dp[0], 0)
// recursive case:
// dp(i) = dp(i - 1) + this[s + i] o/w
// dependency: dp(i) depends on dp(i - 1), that is the entry to the left
// evaluation order: loop for i from 1 until size - s (left to right)
for (i in 1..e - s) {
dp[i] = dp[i - 1] + this[s + i]
max = max(max, dp[i])
}
// time complexity: O(n)
return max
}
// similarly we have suffixSum and I won't do analysis here
fun IntArray.suffixSum(s: Int = 0, e: Int = size - 1): Int {
// dp(i): sum for this[s + i..e]
val dp = IntArray(e - s + 1)
dp[e - s] = this[e]
var max = max(dp[e - s], 0)
for (i in e - s - 1 downTo 0) {
dp[i] = dp[i + 1] + this[s + i]
max = max(max, dp[i])
}
return max
}
// optimized: O(n)
fun IntArray.maxSumN(): Int {
// dp[i] = max sum for this[i until size]
// dp[i] = 0, if i !in 0 until size
// = dp[i + 1], if this[i] < 0
// = this[i] + max(0, tmpSum + dp[nex]), o/w
// , where nex is the next positive number
val dp = IntArray(size + 1)
dp[size] = 0
var nex = size
var tmpSum = 0
for (i in size - 1 downTo 0) {
if (this[i] <= 0) {
dp[i] = dp[i + 1]
tmpSum += this[i]
} else {
dp[i] = this[i]
if (tmpSum + dp[nex] > 0) {
dp[i] += tmpSum + dp[nex]
}
tmpSum = 0
nex = i
}
}
return dp.max() ?: 0
}
// Kadane's algorithm
fun IntArray.maxSumKadane(): Int {
var maxEndingHere = 0
var maxSoFar = 0
forEach {
maxEndingHere += it
maxEndingHere = max(maxEndingHere, 0)
maxSoFar = max(maxSoFar, maxEndingHere)
}
return maxSoFar
}
// a variation of kadane's algorithm
fun OneArray<Int>.maxSumRedo(): Int {
// dp[i]: max sum subarray for this[i..n] that MUST include this[i]
val dp = OneArray(size) { this[it] }
for (i in size - 1 downTo 1)
dp[i] += max(0, dp[i + 1])
return dp.max()!!
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 3,988 | AlgoKt | MIT License |
kotlin/037.kts | daithiocrualaoich | 12,319,597 | false | {"Scala": 55137, "CoffeeScript": 17629, "Python": 10689, "Rust": 5395, "Kotlin": 2121, "Shell": 924} | /*
* Truncatable Primes
* ==================
* The number 3797 has an interesting property. Being prime itself, it is
* possible to continuously remove digits from left to right, and remain prime
* at each stage: 3797, 797, 97, and 7. Similarly we can work from right to
* left: 3797, 379, 37, and 3.
*
* Find the sum of the only eleven primes that are both truncatable from left to
* right and right to left.
*
* NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
*/
import kotlin.math.sqrt
/**
* Returns the prefixes of the receiving List.
*/
fun <T> List<T>.prefixes(): List<List<T>> {
return indices.map { i -> slice(0..i) }
}
/**
* Returns the suffixes of the receiving List.
*/
fun <T> List<T>.suffixes(): List<List<T>> {
return indices.map { i -> slice(i..lastIndex) }
}
/**
* Get the closest integer below the square root of [n].
*
* @retur n floor(sqrt(n))
*/
fun isqrt(n: Int): Int {
return sqrt(n.toFloat()).toInt()
}
/**
* Determine if [n] is prime by trial division.
*/
fun isPrime(n: Int): Boolean {
return n > 1 && (2..isqrt(n)).all { d -> n % d != 0 }
}
/**
* Expand [n] into a list of single digit integers.
*/
fun digitExpansion(n: Int): List<Int> {
return if (n < 10) {
listOf(n)
} else {
digitExpansion(n / 10) + (n % 10)
}
}
/**
* Determine if [n] is a left- and right-truncatable prime.
*/
fun isTruncatablePrime(n: Int): Boolean {
// Single digit primes cannot be truncatable.
if (n < 10) {
return false
}
// Calculate left and right truncations.
val digits = digitExpansion(n)
val expansions: List<List<Int>> = digits.prefixes() + digits.suffixes()
val truncations: List<Int> = expansions.map { expansion: List<Int> ->
expansion.joinToString("").toInt()
}
// And test truncations are primes.
return truncations.all { t -> isPrime(t) }
}
val integers = generateSequence(1) { it + 1 }
val truncatablePrimes = integers.filter { isTruncatablePrime(it) }
// The question tells us there are only 11 truncatable primes.
val answer = truncatablePrimes.take(11).sumBy { it } // = 748,317
println(answer)
| 0 | Scala | 0 | 1 | 5bb0ab16bf9bc622b94f4c66a18fa6fac070fc48 | 2,121 | euler | Apache License 2.0 |
src/main/kotlin/aoc23/day03.kt | asmundh | 573,096,020 | false | {"Kotlin": 56155} | package aoc23
import datastructures.Coordinate
import datastructures.getAllAdjacentCoordinates
import runTask
import utils.InputReader
import java.util.UUID
fun day3part1(input: List<String>): Int =
with(getNumbersAndSymbols(input)) {
symbols.flatMap { symbol ->
symbol.coordinate.getAllAdjacentCoordinates()
.mapNotNull { coordinate ->
parts[coordinate]
}
}.distinctBy { it.id }.sumOf { it.size }
}
fun day3part2(input: List<String>): Int =
with(getNumbersAndSymbols(input)) {
symbols
.filter { it.char == '*' }
.sumOf { symbol ->
symbol.coordinate.getAllAdjacentCoordinates().mapNotNull { coordinate ->
parts[coordinate]
}.distinctBy { it.id }
.takeIf { it.size == 2 }
?.let { it.first().size * it.last().size } ?: 0
}
}
fun getNumbersAndSymbols(input: List<String>): SymbolsAndParts {
val parts: MutableMap<Coordinate, Part> = mutableMapOf()
val symbols: MutableList<Symbol> = mutableListOf()
input.forEachIndexed { indexY, row ->
var candidate = ""
row.forEachIndexed { indexX, char ->
if (char.isDigit()) {
candidate += char
} else if (char != '.') {
symbols.add(Symbol(Coordinate(indexX + 1, indexY), char))
}
if (indexX == row.lastIndex || !char.isDigit()) {
if (candidate.isNotEmpty()) {
val uuid = UUID.randomUUID().toString()
candidate.indices.forEach {
val coordinate = Coordinate(indexX - it, indexY)
parts[coordinate] = Part(coordinate, uuid, candidate.toInt())
}
}
candidate = ""
}
}
}
return SymbolsAndParts(symbols, parts)
}
data class Part(
val coordinate: Coordinate,
val id: String,
val size: Int
)
data class Symbol(
val coordinate: Coordinate,
val char: Char
)
data class SymbolsAndParts(
val symbols: List<Symbol>,
val parts: Map<Coordinate, Part>
)
fun main() {
val input: List<String> = InputReader.getInputAsList(3)
runTask("D3p1") { day3part1(input) }
runTask("D3p2") { day3part2(input) }
}
| 0 | Kotlin | 0 | 0 | 7d0803d9b1d6b92212ee4cecb7b824514f597d09 | 2,389 | advent-of-code | Apache License 2.0 |
src/Day10.kt | AxelUser | 572,845,434 | false | {"Kotlin": 29744} | import java.util.*
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
var cmd = 0
var x = 1
val ops: Queue<Triple<Int, String, Int>> = LinkedList()
for (cycle in 1..220) {
if (ops.isNotEmpty() && ops.peek().first == cycle) {
x += ops.poll().third
}
if (cmd < input.size && ops.isEmpty()) {
val parts = input[cmd++].split(' ')
when (parts[0]) {
"addx" -> ops.offer(Triple(cycle + 2, parts[0], parts[1].toInt()))
}
}
if (cycle >= 20 && (cycle == 20 || (cycle - 20) % 40 == 0)) {
sum += x * cycle
}
}
return sum
}
fun part2(input: List<String>): String {
val screen = Array(6) { BooleanArray(40) }
var cmd = 0
var x = 1
val ops: Queue<Triple<Int, String, Int>> = LinkedList()
for (cycle in 0 until 240) {
if (cmd < input.size && ops.isEmpty()) {
val parts = input[cmd++].split(' ')
when (parts[0]) {
"addx" -> ops.offer(Triple(cycle + 1, parts[0], parts[1].toInt()))
}
}
with(cycle % 40) {
if (this in x - 1..x + 1) {
screen[cycle / 40][this] = true
}
}
if (ops.isNotEmpty() && ops.peek().first == cycle) {
x += ops.poll().third
}
}
return screen.joinToString("\n") { it.joinToString("") { b -> if (b) "#" else " " } }
}
check(part1(readInput("Day10_test")) == 13140)
println(part2(readInput("Day10_test")))
println(part1(readInput("Day10")))
println(part2(readInput("Day10")))
}
| 0 | Kotlin | 0 | 1 | 042e559f80b33694afba08b8de320a7072e18c4e | 1,825 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day03.kt | SimonMarquis | 724,825,757 | false | {"Kotlin": 30983} | import Day03.Object.Part
import Day03.Object.Symbol
import kotlin.math.max
import kotlin.math.min
class Day03(private val input: List<String>) {
sealed class Object {
data class Part(val x: IntRange, val y: Int, val value: Int) : Object()
data class Symbol(val x: Int, val y: Int, val value: Char) : Object() {
val aoe = x.dec()..x.inc()
}
}
private fun List<String>.schematic(regex: Regex = """(\d+|[^.])""".toRegex()): List<List<Object>> = mapIndexed { y, it ->
regex.findAll(it).map {
if (it.value.all(Char::isDigit)) Part(x = it.range, y = y, value = it.value.toInt())
else Symbol(x = it.range.first, y = y, value = it.value.single())
}.toList()
}
private fun <T> Iterable<T>.padded(padding: Iterable<T>) = padding + this + padding
private fun <T> Iterable<T>.symbols(value: Char? = null) = filterIsInstance<Symbol>().filter { value == null || value == it.value }
private fun MutableList<Object>.removePartsInRangeOf(symbol: Symbol): List<Part> = findPartsInRangeOf(symbol).also(::removeAll)
private fun Iterable<Object>.findPartsInRangeOf(symbol: Symbol) = filterIsInstance<Part>().filter { symbol.aoe overlaps it.x }
private infix fun IntRange.overlaps(other: IntRange) = max(first, other.first) <= min(last, other.last)
fun part1() = input.schematic().map { it.toMutableList() }
.padded(mutableListOf())
.windowed(3) { (above, middle, below) ->
listOf(above, middle, below).flatMap { line ->
middle.symbols().flatMap { symbol -> line.removePartsInRangeOf(symbol) }
}
}.flatten()
.sumOf(Part::value)
fun part2() = input.schematic()
.padded(emptyList())
.windowed(3) { (above, middle, below) ->
middle.symbols('*').mapNotNull { symbol ->
listOf(above, middle, below).flatMap { it.findPartsInRangeOf(symbol) }
.takeIf { it.size == 2 }
?.let { (a, b) -> a to b }
}
}.flatten()
.sumOf { it.first.value * it.second.value }
}
| 0 | Kotlin | 0 | 1 | 043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e | 2,138 | advent-of-code-2023 | MIT License |
ceria/16/src/main/kotlin/Solution.kt | VisionistInc | 317,503,410 | false | null | import java.io.File
import java.util.Collections
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
private fun solution1(input :List<String>) :Int {
val rules = input.subList(0, input.indexOf("") )
val nearbyTickets = input.subList(input.lastIndexOf("nearby tickets:") + 1, input.size).map{ it.split(',').map{ it.toInt() }}
var rulesMap = mutableMapOf<String, Pair<IntRange, IntRange>>()
for (r in rules) {
val name = r.substring(0, r.indexOf(':'))
val firstRange = r.substring(r.indexOf(":") + 2, r.indexOf(" or ")).split('-')
val secondRange = r.substring(r.lastIndexOf(" ") + 1).split('-')
rulesMap.put(name, Pair(IntRange(firstRange[0].toInt(), firstRange[1].toInt()), IntRange(secondRange[0].toInt(), secondRange[1].toInt())))
}
var invalidValues = mutableListOf<Int>()
for (ticket in nearbyTickets) {
for (num in ticket) {
var valid = false
for (pair in rulesMap.values) {
if (pair.first.contains(num) || pair.second.contains(num)) {
valid = true
break
}
}
if (!valid) invalidValues.add(num)
}
}
return invalidValues.sum()
}
private fun solution2(input :List<String>) :Long {
val rules = input.subList(0, input.indexOf("") )
val yourTicket = input.get(input.indexOf("your ticket:") + 1).split(',').map{ it.toInt() }
val nearbyTickets = input.subList(input.lastIndexOf("nearby tickets:") + 1, input.size).map{ it.split(',').map{ it.toInt() }}
var rulesMap = mutableMapOf<String, Pair<IntRange, IntRange>>()
for (r in rules) {
val name = r.substring(0, r.indexOf(':'))
val firstRange = r.substring(r.indexOf(":") + 2, r.indexOf(" or ")).split('-')
val secondRange = r.substring(r.lastIndexOf(" ") + 1).split('-')
rulesMap.put(name, Pair(IntRange(firstRange[0].toInt(), firstRange[1].toInt()), IntRange(secondRange[0].toInt(), secondRange[1].toInt())))
}
var invalidTickets = mutableListOf<List<Int>>()
for (ticket in nearbyTickets) {
for (num in ticket) {
var valid = false
for (pair in rulesMap.values) {
if (pair.first.contains(num) || pair.second.contains(num)) {
valid = true
break
}
}
if (!valid) {
invalidTickets.add(ticket)
break
}
}
}
val validTickets = nearbyTickets.minus(invalidTickets)
var validPositionsMap = mutableMapOf<String, List<Int>>()
rulesMap.forEach {rule, valuePair ->
validPositionsMap.put(rule, (0..rules.size - 1).toList() )
for (ticket in validTickets) {
for (i in ticket.indices) {
if ( !valuePair.first.contains(ticket[i]) && !valuePair.second.contains(ticket[i])) {
if (validPositionsMap.get(rule)!!.contains(i)) {
var pos = validPositionsMap.get(rule)!!.toMutableList()
pos.remove(i)
validPositionsMap.put(rule, pos)
}
}
}
}
}
var ruleToPosition = mutableMapOf<String, Int>()
while (ruleToPosition.size != validPositionsMap.size) {
var rulesToRemove = mutableListOf<String>()
validPositionsMap.forEach {rule, indexes ->
if (indexes.size == 1) {
ruleToPosition.put(rule, indexes.get(0))
rulesToRemove.add(rule)
}
}
for (rule in rulesToRemove) {
val indexToRemove = validPositionsMap.get(rule)!!.get(0)
validPositionsMap.forEach {r, indexes ->
if (indexes.contains(indexToRemove)) {
val newIndexes = indexes.toMutableList()
newIndexes.remove(indexToRemove)
validPositionsMap.put(r, newIndexes)
}
}
}
}
var product = 1L
ruleToPosition.forEach {rule, pos ->
if (rule.startsWith("departure")) {
product *= yourTicket.get(pos)
}
}
return product
} | 0 | Rust | 0 | 0 | 002734670384aa02ca122086035f45dfb2ea9949 | 3,909 | advent-of-code-2020 | MIT License |
KotlinAdvent2018/week1/src/main/kotlin/net/twisterrob/challenges/adventOfKotlin2018/week1/MarkingWayOnMap.kt | TWiStErRob | 136,539,340 | false | {"Kotlin": 104880, "Java": 11319} | package net.twisterrob.challenges.adventOfKotlin2018.week1
import net.twisterrob.challenges.adventOfKotlin2018.week1.AStar.Pos
import net.twisterrob.challenges.adventOfKotlin2018.week1.Map.Cell
import java.lang.Math.sqrt
fun addPath(inputMap: String): String {
val map = Map.parse(inputMap)
AStar(map).run(::heuristicBetween, Map::distanceBetween)
return map.toString()
}
private fun heuristicBetween(a: Pos, b: Pos): Double {
fun Int.squared() = (this * this).toDouble()
return sqrt((a.row - b.row).squared() + (a.col - b.col).squared())
}
private const val selfPositionRow = 1
private const val selfPositionCol = 1
private val distancesForNeighbors = arrayOf(
arrayOf(1.5, 1.0, 1.5),
arrayOf(1.0, 0.0, 1.0),
arrayOf(1.5, 1.0, 1.5)
)
private fun Map.distanceBetween(a: Pos, b: Pos): Double {
if (this[a.row, a.col] == Cell.Obstacle || this[b.row, b.col] == Cell.Obstacle) {
return Double.POSITIVE_INFINITY
}
val rowD = a.row - b.row
val colD = a.col - b.col
require(rowD in -1..1) { "not neighboring cells" }
require(colD in -1..1) { "not neighboring cells" }
require(!(rowD == 0 && colD == 0)) { "distance to self shouldn't be asked" }
return distancesForNeighbors[selfPositionRow - rowD][selfPositionCol - colD]
}
| 1 | Kotlin | 1 | 2 | 5cf062322ddecd72d29f7682c3a104d687bd5cfc | 1,240 | TWiStErRob | The Unlicense |
kotlin/src/main/kotlin/be/swsb/aoc2023/day7/Day7.kt | Sch3lp | 724,797,927 | false | {"Kotlin": 44815, "Rust": 14075} | package be.swsb.aoc2023.day7
import be.swsb.aoc2023.day7.Card.*
object HandComparator : Comparator<Pair<Hand, Bid>> {
override fun compare(hand1: Pair<Hand, Bid>, hand2: Pair<Hand, Bid>): Int {
val typeComparison = hand1.first.type.ordinal.compareTo(hand2.first.type.ordinal)
return if (typeComparison == 0) {
compareCardsToTheirRespectivePositions(hand1, hand2)
} else typeComparison
}
private fun compareCardsToTheirRespectivePositions(hand1: Pair<Hand, Bid>, hand2: Pair<Hand, Bid>): Int {
var index = 0
var handComparison = hand1.first.cards[index].ordinal.compareTo(hand2.first.cards[index].ordinal) * -1
while (handComparison == 0 && index < 5) {
index++
handComparison = hand1.first.cards[index].ordinal.compareTo(hand2.first.cards[index].ordinal) * -1
}
return handComparison
}
}
typealias Bid = Int
enum class HandType {
HighCard,
OnePair,
TwoPair,
ThreeOfAKind,
FullHouse,
FourOfAKind,
FiveOfAKind,
}
data class Hand(val cards: List<Card>) {
val type: HandType = cards.determineType()
private fun List<Card>.determineType(): HandType {
val amountsPerCard = this.groupBy { it }.mapValues { (_, v) -> v.count() }
return when {
amountsPerCard.size == 1 -> HandType.FiveOfAKind
amountsPerCard.any { (_, amount) -> amount == 4 } -> HandType.FourOfAKind
amountsPerCard.any { (_, amount) -> amount == 3 } && amountsPerCard.any { (_, amount) -> amount == 2 } -> HandType.FullHouse
amountsPerCard.any { (_, amount) -> amount == 3 } -> HandType.ThreeOfAKind
amountsPerCard.filterValues { amount -> amount == 2 }.size == 2 -> HandType.TwoPair
amountsPerCard.filterValues { amount -> amount == 2 }.size == 1 -> HandType.OnePair
else -> HandType.HighCard
}
}
}
fun Hand(cards: String): Hand = Hand(cards.map { Card(it) })
enum class Card {
A, K, Q, J, T, `9`, `8`, `7`, `6`, `5`, `4`, `3`, `2`
}
fun parse(string: String): List<Pair<Hand, Int>> =
string.lines().map { line -> line.split(" ").let { (first, second) -> first.toHand() to second.toInt() } }
private fun String.toHand() = Hand(this)
fun parse2(string: String): Int = 0
fun Card(c: Char) =
Card.valueOf("$c")
fun Card0(c: Char): Card = when (c) {
'A' -> A
'K' -> K
'Q' -> Q
'J' -> J
'T' -> T
'9' -> `9`
'8' -> `8`
'7' -> `7`
'6' -> `6`
'5' -> `5`
'4' -> `4`
'3' -> `3`
'2' -> `2`
else -> error("Could not parse $c into a Card")
}
fun Card2(c: Char) =
listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2').zip(Card.values().toList())
.toMap()[c]
?: error("Could not parse $c into a Card")
fun Card3(c: Char) =
values().associateBy { it.name }["$c"] ?: error("Could not parse $c into a Card") | 0 | Kotlin | 0 | 1 | dec9331d3c0976b4de09ce16fb8f3462e6f54f6e | 2,933 | Advent-of-Code-2023 | MIT License |
2022/24/24.kt | LiquidFun | 435,683,748 | false | {"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191} | typealias Point = Pair<Int, Int>
val dirs = listOf(0 to 1, 1 to 0, 0 to -1, -1 to 0)
val dirsChars: Map<Char, Point> = mapOf('>' to dirs[0], 'v' to dirs[1], '<' to dirs[2], '^' to dirs[3])
fun lcmOf(a: Int, b: Int) = (1..100000).first { it % a == 0 && it % b == 0 }
fun main() {
val input = generateSequence(::readlnOrNull).toList()
val (height, width) = (input.size - 2) to (input[0].length - 2)
val lcm = lcmOf(height, width)
val blizzards = List<MutableSet<Point>>(lcm+1) { mutableSetOf() }
for ((y, row) in input.withIndex()) {
for ((x, v) in row.withIndex()) {
if (v in dirsChars)
for (t in 0..lcm)
blizzards[t].add(
(y + dirsChars[v]!!.first * t - 1).mod(height)+1 to
(x + dirsChars[v]!!.second * t - 1).mod(width)+1
)
}
}
// Blizzard repeats every 700 steps
assert(blizzards[0] == blizzards[lcm])
assert(blizzards[1] != blizzards[lcm])
fun isInside(p: Point): Boolean = p.first in input.indices && p.second in input[0].indices
fun minTimeToMoveFromTo(atTime: Int, from: Point, to: Point): Int {
val queue = ArrayDeque<Pair<Int, Point>>()
queue.add(atTime to from)
val visited: MutableSet<Pair<Int, Point>> = mutableSetOf()
while (queue.isNotEmpty()) {
val (t, yx) = queue.removeFirst()
val (y, x) = yx
if (y == to.first && x == to.second)
return t
val vis = t % lcm to (y to x)
if (visited.contains(vis))
continue
visited.add(vis)
for ((ya, xa) in dirs.map { y+it.first to x+it.second }.filter(::isInside)) {
if (input[ya][xa] != '#' && !blizzards[(t+1).mod(lcm)].contains(ya to xa))
queue.add(t+1 to (ya to xa))
}
if (!blizzards[(t+1).mod(lcm)].contains(y to x))
queue.add(t+1 to (y to x))
}
return -1
}
val start = 0 to 1
val end = height+1 to width
val t1 = minTimeToMoveFromTo(0, start, end)
println(t1)
val t2 = minTimeToMoveFromTo(t1, end, start)
val t3 = minTimeToMoveFromTo(t2, start, end)
println(t3)
}
| 0 | Kotlin | 7 | 43 | 7cd5a97d142780b8b33b93ef2bc0d9e54536c99f | 2,282 | adventofcode | Apache License 2.0 |
src/Day04.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | fun main() {
fun fullyIn(range1: IntRange, range2: IntRange): Boolean {
return (range1.first in range2 && range1.last in range2)
}
fun overlap(range1: IntRange, range2: IntRange): Boolean {
return (range1.first in range2 || range1.last in range2)
}
fun withRangesParsed(input: List<String>, function: (IntRange, IntRange) -> Boolean): Int {
return input.count {
it.isNotBlank() && it.split(",").map { it2 -> it2.split('-').let { (a, b) -> a.toInt()..b.toInt() } }
.let { (r1, r2) -> function(r1, r2) || function(r2, r1) }
}
}
fun part1(input: List<String>): Int {
return withRangesParsed(input, ::fullyIn)
}
fun part2(input: List<String>): Int {
return withRangesParsed(input, ::overlap)
}
// 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 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 1,084 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day15.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.Point
import shared.XYMap
import shared.getLines
import kotlin.math.abs
class CavernRisk(input: List<String>): XYMap<Int>(input, { c: Char -> c.digitToInt() }) {
private val start = Point(0,0)
private val goal = Point(width-1, height-1)
private fun heuristic(a: Point, b: Point) = (abs(a.x - b.x) + abs(a.y - b.y)) * 5
private fun reconstructPath(cameFrom: Map<Point, Point>, end: Point): Int {
var totalPath = 0
var current = end
while (cameFrom.containsKey(current)){
totalPath += getValue(current)
current = cameFrom[current]!!
}
return totalPath
}
fun aStar(): Int{
val openSet = mutableSetOf(start)
val cameFrom = mutableMapOf<Point, Point>()
val gScore = mutableMapOf(Pair(start, 0))
val fScore = mutableMapOf(Pair(start, heuristic(start, goal)))
while (openSet.isNotEmpty()){
val current = openSet.minByOrNull { fScore[it]!! }!!
if(current == goal) return reconstructPath(cameFrom, current)
openSet.remove(current)
for(neighbour in findAdjacentPoints(current)){
val tentativeGScore = gScore[current]!! + getValue(neighbour)
if(tentativeGScore < gScore[neighbour] ?: Int.MAX_VALUE){
cameFrom[neighbour] = current
gScore[neighbour] = tentativeGScore
fScore[neighbour] = tentativeGScore + heuristic(neighbour, goal)
if(!openSet.contains(neighbour)) openSet.add(neighbour)
}
}
}
throw Exception("should have found goal by now")
}
}
fun toFullMap(input: List<String>): List<String>{
fun repeat(line: String, nr: Int): String{
return line.map {
val increased = it.digitToInt() + nr
if(increased > 9) increased % 9 else increased
}.joinToString("")
}
val horizontalScaled = input.map {
repeat(it, 0) + repeat(it, 1) + repeat(it, 2) + repeat(it, 3) + repeat(it, 4)
}
val fullMap = mutableListOf<String>()
repeat(5){ i ->
horizontalScaled.forEach { line ->
fullMap.add(repeat(line, i))
}
}
return fullMap
}
fun main(){
val input = getLines("day15.txt")
val cavern = CavernRisk(input)
val task1 = cavern.aStar()
println(task1)
val fullMap = toFullMap(input)
val fullCavern = CavernRisk(fullMap)
val task2 = fullCavern.aStar()
println(task2)
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 2,536 | AdventOfCode2021 | MIT License |
src/Day02.kt | jaldhar | 573,188,501 | false | {"Kotlin": 14191} |
class RockPaperScissors {
companion object {
val shape = mapOf<String, Int>(
"X" to 1,
"Y" to 2,
"Z" to 3,
)
val transform = mapOf<String, String>(
"AX" to "Z",
"AY" to "X",
"AZ" to "Y",
"BX" to "X",
"BY" to "Y",
"BZ" to "Z",
"CX" to "Y",
"CY" to "Z",
"CZ" to "X",
)
val outcome = mapOf<String, Int>(
"AX" to 3,
"AY" to 6,
"AZ" to 0,
"BX" to 0,
"BY" to 3,
"BZ" to 6,
"CX" to 6,
"CY" to 0,
"CZ" to 3,
)
fun play1(line: String): Int {
var (his, mine) = line.split(" ")
return RockPaperScissors.shape[mine]!! + RockPaperScissors.outcome["${his}${mine}"]!!
}
fun play2(line: String): Int {
var (his, mine) = line.split(' ');
mine = RockPaperScissors.transform["${his}${mine}"]!!;
return RockPaperScissors.shape[mine]!! + RockPaperScissors.outcome["${his}${mine}"]!!
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.map { RockPaperScissors.play1(it) }.sumOf { it }
}
fun part2(input: List<String>): Int {
return input.map { RockPaperScissors.play2(it) }.sumOf { it }
}
// 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 | 0 | b193df75071022cfb5e7172cc044dd6cff0f6fdf | 1,727 | aoc2022-kotlin | Apache License 2.0 |
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2015/day09/Day09.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2015.day09
import nl.sanderp.aoc.common.readResource
data class Distance(val from: String, val to: String, val distance: Int)
fun parse(line: String): List<Distance> {
val segments = line.split(" to ", " = ")
val distance = Distance(from = segments[0], to = segments[1], distance = segments[2].toInt())
return listOf(distance, distance.copy(from = distance.to, to = distance.from))
}
fun <T> List<T>.permutations(): List<List<T>> {
if (this.size == 1) return listOf(this)
val perms = mutableListOf<List<T>>()
val toInsert = this[0]
for (perm in this.drop(1).permutations()) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
fun main() {
val distances = readResource("Day09.txt").lines().flatMap { parse(it) }
val locations = distances.map { it.from }.distinct()
val routes = locations
.permutations()
.map { it.zipWithNext { a, b -> distances.first { d -> d.from == a && d.to == b } } }
.map { it to it.sumOf { route -> route.distance }}
println("Part one: ${routes.minOf { it.second }}")
println("Part two: ${routes.maxOf { it.second }}")
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,283 | advent-of-code | MIT License |
src/main/kotlin/day21/Day21.kt | dustinconrad | 572,737,903 | false | {"Kotlin": 100547} | package day21
import readResourceAsBufferedReader
fun main() {
println("part 1: ${part1(readResourceAsBufferedReader("21_1.txt").readLines())}")
println("part 2: ${part2(readResourceAsBufferedReader("21_2.txt").readLines())}")
}
fun part1(input: List<String>): Long {
val nodes = input.map { Node.parse(it) }
val monkeyGraph = MonkeyGraph(nodes)
val result = monkeyGraph.nodeValue()
return result
}
fun part2(input: List<String>): Long {
val nodes = input.map { Node.parse(it) }
val monkeyGraph = MonkeyGraph(nodes)
val result = monkeyGraph.process()
return 0
}
sealed interface Node {
fun evaluate(lookup: Map<String, Long>): Long
fun ancestors(): Collection<String>
var inDegree: Int
val name: String
companion object {
private val constRegex = Regex("""[a-z]+:\s\d+""")
fun parse(line: String): Node {
val constant = constRegex.matchEntire(line)
return if (constant != null) {
val (name, rest) = line.split(":")
ConstantNode(name, rest.trim().toLong())
} else {
val (name, rest) = line.split(":")
val (left, op, right) = rest.trim().split(" ")
MonkeyNode(name, left, op, right)
}
}
}
}
data class ConstantNode(override val name: String, val const: Long) : Node {
override var inDegree = 0
override fun evaluate(lookup: Map<String, Long>): Long {
return const
}
override fun ancestors() = emptySet<String>()
}
data class MonkeyNode(override val name: String, val left: String, val op: String, val right: String) : Node {
override var inDegree = 2
override fun evaluate(lookup: Map<String, Long>): Long {
require(inDegree == 0) { "inDegree not zero" }
val leftVal = lookup[left]!!
val rightVal = lookup[right]!!
return when (op) {
"+" -> leftVal + rightVal
"*" -> leftVal * rightVal
"-" -> leftVal - rightVal
"/" -> leftVal / rightVal
else -> throw IllegalArgumentException("Unknown op $op")
}
}
override fun ancestors(): Set<String> {
return setOf(left, right)
}
}
class MonkeyGraph(nodes: Collection<Node>) {
private val _values: MutableMap<String, Long> = mutableMapOf()
private val graph = nodes.associateBy { it.name }
fun nodeValue(target: String = "root"): Long {
process()
return _values[target]!!
}
fun process() {
val reverseGraph = reverseGraph()
val zeroIn = graph.values.filter { it.inDegree == 0 }
val q = ArrayDeque<Node>()
q.addAll(zeroIn)
while(q.isNotEmpty()) {
val curr = q.removeFirst()
_values[curr.name] = curr.evaluate(_values)
reverseGraph[curr.name]?.forEach {
it.inDegree--
if (it.inDegree == 0) {
q.add(it)
}
}
}
}
private fun reverseGraph(): MutableMap<String, MutableList<Node>> {
val reverseGraph = mutableMapOf<String, MutableList<Node>>()
graph.forEach { (_, v) ->
v.ancestors().forEach { ancestor ->
val siblings = reverseGraph.getOrPut(ancestor) { mutableListOf() }
siblings.add(v)
}
}
return reverseGraph
}
}
| 0 | Kotlin | 0 | 0 | 1dae6d2790d7605ac3643356b207b36a34ad38be | 3,445 | aoc-2022 | Apache License 2.0 |
src/twentytwentythree/day08/Day08.kt | colinmarsch | 571,723,956 | false | {"Kotlin": 65403, "Python": 6148} | package twentytwentythree.day08
import readInput
fun main() {
fun Set<String>.allZ(): Boolean {
return this.all { it.last() == 'Z' }
}
fun part1(input: List<String>): Int {
val directions = input[0].toList()
val nodeMap = mutableMapOf<String, Pair<String, String>>()
input.subList(2, input.size).forEach { line ->
val splits = line.split(" = ")
val nodeName = splits[0]
val nodeLeft = splits[1].split(",")[0].substring(1)
val nodeRight =
splits[1].split(",")[1].substring(0, splits[1].split(",")[1].length - 1).trim()
nodeMap[nodeName] = Pair(nodeLeft, nodeRight)
}
var currentNode = "AAA"
var stepCount = 0
while (currentNode != "ZZZ") {
val currentValue = nodeMap[currentNode]!!
val currentDirection = directions[stepCount++ % directions.size]
currentNode = if (currentDirection == 'L') {
currentValue.first
} else {
currentValue.second
}
}
return stepCount
}
fun part2(input: List<String>): Long {
val directions = input[0].toList()
val nodeMap = mutableMapOf<String, Pair<String, String>>()
val startingNodes = mutableSetOf<String>()
input.subList(2, input.size).forEach { line ->
val splits = line.split(" = ")
val nodeName = splits[0]
val nodeLeft = splits[1].split(",")[0].substring(1)
val nodeRight =
splits[1].split(",")[1].substring(0, splits[1].split(",")[1].length - 1).trim()
nodeMap[nodeName] = Pair(nodeLeft, nodeRight)
if (nodeName.last() == 'A') {
startingNodes.add(nodeName)
}
}
var currentNodes = startingNodes
var stepCount = 0L
while (!currentNodes.allZ()) {
val newNodes = mutableSetOf<String>()
currentNodes.forEach { currentNode ->
val currentValue = nodeMap[currentNode]!!
val currentDirection = directions[(stepCount % directions.size).toInt()]
newNodes.add(
if (currentDirection == 'L') {
currentValue.first
} else {
currentValue.second
}
)
}
currentNodes = newNodes
stepCount++
}
return stepCount
}
val input = readInput("twentytwentythree/day08", "Day08_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bcd7a08494e6db8140478b5f0a5f26ac1585ad76 | 2,300 | advent-of-code | Apache License 2.0 |
src/main/kotlin/io/matrix/RangeSumQuery2DMatrix.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.matrix
import io.utils.runTests
// https://leetcode.com/problems/range-sum-query-2d-immutable/
class RangeSumQuery2DMatrix(private val matrix: Array<IntArray>) {
private val dp = Array(matrix.size) { IntArray(matrix.firstOrNull()?.size ?: 0) }.apply {
if (matrix.isNotEmpty() && matrix.first().isNotEmpty()) {
for (row in matrix.indices) {
var accum = 0
for (col in matrix.first().indices) {
val up = if (row == 0) 0 else this[row - 1][col]
accum += matrix[row][col]
this[row][col] = accum + up
}
}
}
}
// Time O(1) Space O(NM)
fun executeConstant(topRow: Int, topCol: Int, bottomRow: Int, bottomCol: Int): Int = when {
topRow > 0 && topCol > 0 -> {
val up = dp[topRow - 1][bottomCol]
val left = dp[bottomRow][topCol - 1]
val sum = dp[topRow - 1][topCol - 1]
dp[bottomRow][bottomCol] - up - left + sum
}
topRow > 0 -> {
val up = dp[topRow - 1][bottomCol]
dp[bottomRow][bottomCol] - up
}
topCol > 0 -> {
val left = dp[bottomRow][topCol - 1]
dp[bottomRow][bottomCol] - left
}
else -> dp[bottomRow][bottomCol]
}
// Time O(NM) Space O(1)
fun execute(topRow: Int, topCol: Int, bottomRow: Int, bottomCol: Int): Int {
var result = 0
for (row in topRow..bottomRow) {
if (row in matrix.indices) {
for (col in topCol..bottomCol) {
if (col in 0 until (matrix.firstOrNull()?.size ?: 0))
result += matrix[row][col]
}
}
}
return result
}
}
fun main() {
runTests(listOf(
Triple(arrayOf(intArrayOf(3, 0, 1, 4, 2), intArrayOf(5, 6, 3, 2, 1), intArrayOf(1, 2, 0, 1, 5), intArrayOf(4, 1, 0, 1, 7), intArrayOf(1, 0, 3, 0, 5)),
listOf(2, 1, 4, 3), 8)
)) { (input, points, value) -> value to RangeSumQuery2DMatrix(input).executeConstant(points.first(), points[1], points[2], points[3]) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,936 | coding | MIT License |
src/Day05.kt | haraldsperre | 572,671,018 | false | {"Kotlin": 17302} | typealias CrateStack = ArrayDeque<Char>
fun CrateStack.pop(): Char = removeLast()
fun CrateStack.pop(count: Int): CrateStack {
val a = CrateStack()
repeat(count) { a.addFirst(pop()) }
return a
}
fun CrateStack.push(crate: Char) = addLast(crate)
fun CrateStack.push(crates: CrateStack) {
while (crates.isNotEmpty()) push(crates.removeFirst())
}
fun main() {
fun createStacks(stackVisualization: List<String>): List<CrateStack> {
val stacks = stackVisualization
.last()
.chunked(4)
.map { ArrayDeque<Char>() }
for (line in stackVisualization.reversed().listIterator(1)) {
line
.replace(" ", " ")
.split(" ")
.forEachIndexed { index, card ->
if (card.isNotEmpty()) stacks.get(index = index).push(card[1])
}
}
return stacks
}
fun getInstruction(instruction: String): Triple<Int, Int, Int> {
val pattern = Regex("move (\\d+) from (\\d+) to (\\d+)")
val (number, from, to) = pattern.find(instruction)!!.destructured
return Triple(number.toInt(), from.toInt(), to.toInt())
}
fun part1(input: List<String>): String {
val (stackDescription, instructions) = input.chunkedBy(String::isEmpty)
val stacks = createStacks(stackDescription)
for (instruction in instructions) {
val (number, from, to) = getInstruction(instruction)
repeat(number) {
stacks[to - 1].push(stacks[from - 1].pop())
}
}
return stacks
.map { it.pop() }
.joinToString("")
}
fun part2(input: List<String>): String {
val (stackDescription, instructions) = input.chunkedBy(String::isEmpty)
val stacks = createStacks(stackDescription)
for (instruction in instructions) {
val (number, from, to) = getInstruction(instruction)
stacks[to - 1].push(stacks[from - 1].pop(number))
}
return stacks
.map { it.pop() }
.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c4224fd73a52a2c9b218556c169c129cf21ea415 | 2,414 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | import kotlin.math.abs
fun main() {
fun part1(coords: List<Pair<Coords, Coords>>, lineY: Int): Int {
val rangePointList = getRangePointListForLine(coords, lineY)
var result = 0
var beginCount = 0
var currentBegin: Int? = null
rangePointList.forEach {
when(it.pointType) {
RangePointType.BEGIN -> {
if (beginCount == 0) {
currentBegin = it.x
}
beginCount++
}
RangePointType.END -> {
beginCount--
if (beginCount == 0) {
result += (it.x - currentBegin!! + 1)
}
}
RangePointType.BEACON -> {
if (beginCount > 0)
result--
}
}
}
return result
}
fun part2(coords: List<Pair<Coords, Coords>>, range: IntRange): Long {
var resultX: Int? = null
var resultY: Int? = null
for (y in range) {
val rangePointList = getRangePointListForLine(coords, y)
var lastEndOrBeacon: Int? = null
var beginCount = 0
run rangePointList@{
rangePointList.forEach {
if (it.x > range.last)
return@rangePointList
when (it.pointType) {
RangePointType.BEGIN -> {
if (beginCount == 0 && it.x > 0 && lastEndOrBeacon != it.x - 1) {
resultX = it.x - 1
return@rangePointList
}
beginCount++
}
RangePointType.END -> {
beginCount--
lastEndOrBeacon = it.x
}
RangePointType.BEACON -> {
lastEndOrBeacon = it.x
}
}
}
}
if (resultX != null) {
resultY = y
break
}
}
return 4000000L * resultX!!.toLong() + resultY!!
}
val testInput = readInput("Day15_test")
val testCoords: List<Pair<Coords, Coords>> = readCoords(testInput)
check(part1(testCoords, 10) == 26)
check(part2(testCoords, 1..20) == 56000011L)
val input = readInput("Day15")
val coords = readCoords(input)
println(part1(coords, 2000000))
println(part2(coords, 1 .. 4000000))
}
private val REGEX = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""")
private fun readCoords(input: List<String>): List<Pair<Coords, Coords>> {
val result = mutableListOf<Pair<Coords, Coords>>()
input.forEach {
val matchResult = REGEX.matchEntire(it) ?: return@forEach
result.add(
Pair(
Coords(matchResult.groupValues[1].toInt(), matchResult.groupValues[2].toInt()),
Coords(matchResult.groupValues[3].toInt(), matchResult.groupValues[4].toInt())
)
)
}
return result
}
private enum class RangePointType { BEGIN, BEACON, END }
private data class RangePoint(val x: Int, val pointType: RangePointType)
private fun getRangePointListForLine(
coords: List<Pair<Coords, Coords>>,
lineY: Int
): List<RangePoint> {
val rangePointList = mutableListOf<RangePoint>()
val beaconSet = mutableSetOf<Int>()
coords.forEach {
val distance = abs(it.first.x - it.second.x) + abs(it.first.y - it.second.y)
val deltaY = abs(it.first.y - lineY)
if (deltaY > distance)
return@forEach
val deltaX = distance - deltaY
rangePointList.add(RangePoint(it.first.x - deltaX, RangePointType.BEGIN))
rangePointList.add(RangePoint(it.first.x + deltaX, RangePointType.END))
if (it.second.y == lineY) {
beaconSet.add(it.second.x)
}
}
beaconSet.forEach {
rangePointList.add(RangePoint(it, RangePointType.BEACON))
}
rangePointList.sortWith(
Comparator.comparingInt<RangePoint> { rp -> rp.x }
.thenComparing { rp -> rp.pointType.ordinal }
)
return rangePointList
} | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 4,406 | AdventOfCode2022 | Apache License 2.0 |
src/Day15.kt | anilkishore | 573,688,256 | false | {"Kotlin": 27023} | import java.util.regex.Pattern
import kotlin.math.abs
import kotlin.streams.toList
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
class Segment(var start: Int, var end: Int) : Comparable<Segment> {
fun overlap(other: Segment): Int {
if (other.end < other.start)
return 0
val maxStart = maxOf(start, other.start)
val minEnd = minOf(end, other.end)
return maxOf(0, minEnd - maxStart + 1)
}
override fun compareTo(other: Segment): Int =
if (start != other.start) start - other.start
else end - other.end
}
@OptIn(ExperimentalTime::class)
fun main() {
val lim = 4000000
fun part1(input: List<List<Int>>, yLimit: Int = 2000000): Int {
val beaconXs = mutableSetOf<Int>()
val segments = input.map { s ->
val (sx, sy, bx, by) = s
if (by == yLimit) beaconXs.add(bx)
val dx = abs(sx - bx) + abs(sy - by) - abs(sy - yLimit)
if (dx < 0) Segment(0, -1)
else Segment(sx - dx, sx + dx)
}.filter { it.start <= it.end }.toTypedArray()
segments.sort()
var merged = mutableListOf(segments[0])
for (s in segments) {
val curEnd = merged.last().end
if (s.start <= curEnd)
merged.last().end = maxOf(curEnd, s.end)
else
merged.add(s)
}
// Part-2
val xLimit = Segment(0, lim)
for (i in 0 until merged.size - 1) {
val gap = Segment(merged[i].end + 1, merged[i + 1].start - 1)
if (gap.overlap(xLimit) == 1) {
println("Part 2 answer = ${gap.start.toLong() * lim + yLimit}")
}
}
return merged.sumOf { it.end - it.start + 1 } - beaconXs.size
}
fun part2(input: List<List<Int>>) {
for (y in 0..lim)
part1(input, y)
}
val input = readInput("Day15")
val numPattern = Pattern.compile("-?\\d+")
val numsList = input.map { s ->
val matcher = numPattern.matcher(s)
matcher.results().mapToInt { r -> r.group().toInt() }.toList()
}
println(part1(numsList))
println("Runtime (ms) = ${measureTime { part2(numsList) }.inWholeMilliseconds}") // 1.5-1.7s
} | 0 | Kotlin | 0 | 0 | f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9 | 2,272 | AOC-2022 | Apache License 2.0 |
src/Day03.kt | olezhabobrov | 572,687,414 | false | {"Kotlin": 27363} | fun main() {
fun Char.priority(): Int {
return if (isLowerCase())
code - 'a'.code + 1
else
code - 'A'.code + 27
}
fun part1(input: List<String>): Int =
input.sumOf { rucksack ->
val (first, second) =
rucksack.map { item -> item.priority() }
.chunked(rucksack.length / 2)
.map { compartment -> compartment.toSet() }
first.sumOf { if (second.contains(it)) it else 0 }
}
fun part2(input: List<String>): Int =
input.chunked(3).sumOf { team ->
val sets = team.map { elf -> elf.map { item -> item.priority() }.toSet() }
(sets[0] intersect sets[1] intersect sets[2]).random()
}
// 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 | 31f2419230c42f72137c6cd2c9a627492313d8fb | 1,043 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/day24_arithmetic_logic_unit/ArithmeticLogicUnit.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day24_arithmetic_logic_unit
/**
* At first blush, this looks like a "build an interpreter/VM" sort of problem
* in the style of Intcode. However, 9^14 numbers to check... This is another
* "find the optimal path" (like Chiton #15), but the thing you need to find a
* path through is expressed by the input program's _behavior_, not a map you
* are provided. The only info you know is that the final Z must be zero, so
* pruning the "paths" has to be done backwards. You don't necessarily need an
* interpreter either; manually disassembling to identify the algorithm, and
* then re-coding in your solution language will work just as well.
*
* Part two is just inverting the fitness function: find min vs find max.
*/
fun main() {
util.solve(51983999947999, ::partOne) // 51993999947999 is too high
util.solve(11211791111365, ::partTwo)
}
private typealias Round = List<Op>
private fun Round.execute(z: Long, w: Long) =
Machine().let { m ->
m.z = z
m.execute(this, listOf(w))
m.z
}
private fun Round.searchIn(targets: Set<Long>): Set<Long> =
mutableSetOf<Long>().let { next ->
for (z in -10_000..10_000L)
for (w in 1..9L)
if (targets.contains(execute(z, w)))
next.add(z)
next
}
private typealias Slices = List<Round>
private fun Slices.buildInputZByRound(): Map<Int, Set<Long>> =
mutableMapOf<Int, Set<Long>>().also { byRound ->
((size - 1) downTo 0).fold(setOf(0L)) { targets, r ->
if (targets.isEmpty()) {
throw IllegalStateException("no targets for round $r")
}
byRound[r] = this[r].searchIn(targets)
byRound[r]!!
}
}
fun partOne(input: String) =
solve(input, 9 downTo 1L)
fun solve(input: String, digitPriority: Iterable<Long>): Long {
// break the problem into per-digit rounds
val m = Machine()
val slices = m.parse(input)
.chunked(18)
// back-track and find all the per-round output Z that might work
val inputZByRound = slices.buildInputZByRound()
// go forward and find the largest per-round W that passes the check
fun walk(r: Int, z: Long, digits: List<Long>): Long {
if (digits.size == 14) {
return digits.fold(0L) { agg, n ->
agg * 10 + n
}
}
val targets = if (r == 13) setOf(0L)
else inputZByRound[r + 1]!!
for (w in digitPriority) {
val v = slices[r].execute(z, w)
if (targets.contains(v)) {
val answer = walk(r + 1, v, digits + w)
if (answer > 0) {
return answer
}
}
}
return -1
}
return walk(0, 0, emptyList())
}
fun partTwo(input: String) =
solve(input, 1..9L)
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 2,860 | aoc-2021 | MIT License |
src/Day07.kt | paul-matthews | 433,857,586 | false | {"Kotlin": 18652} | import java.lang.Math.abs
typealias CrabMultiplier = (Int) -> Int
val constantInt: CrabMultiplier = {i -> i}
val incrementalInt: CrabMultiplier = {i -> (1..i).toList().sum()}
fun List<String>.toCrabs(): Crabs = fold(mutableListOf()) { acc, s ->
acc.addAll(s.split(",").toInts())
acc
}
typealias Crabs = List<Int>
fun Crabs.getDistanceFrom(point: Int, multiplier: CrabMultiplier) = fold(0) {acc, crab->
acc + multiplier(abs(point - crab))
}
fun Crabs.getDistanceFrom(points: List<Int>, multiplier: CrabMultiplier) = points.map { getDistanceFrom(it, multiplier) }
fun Crabs.getMinMaxRange() = minOf { it }..maxOf { it }
fun main() {
fun part1(input: List<String>) = with(input.toCrabs()) {
getDistanceFrom((getMinMaxRange()).toList(), constantInt).minOf { it }
}
fun part2(input: List<String>) = with(input.toCrabs()) {
getDistanceFrom((getMinMaxRange()).toList(), incrementalInt).minOf { it }
}
val testInput = readFileContents("Day07_test")
val part1Result = part1(testInput)
println(part1Result)
check(part1Result == 37) { "Expected: 37 but found $part1Result" }
val part2Result = part2(testInput)
check((part2Result) == 168) { "Expected 168 but is: $part2Result" }
val input = readFileContents("Day07")
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 2f90856b9b03294bc279db81c00b4801cce08e0e | 1,363 | advent-of-code-kotlin-template | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch2/Problem23.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch2
import dev.bogwalk.util.maths.sumProperDivisors
/**
* Problem 23: Non-Abundant Sums
*
* https://projecteuler.net/problem=23
*
* Goal: Return whether N can be expressed as the sum of 2 abundant numbers.
*
* Constraints: 0 <= N <= 1e5
*
* Perfect Number: The sum of its proper divisors equals itself.
* e.g. properD(6) = sum{1,2,3} = 6
*
* Deficient Number: The sum of its proper divisors is less than itself.
* e.g. properD(4) = sum{1, 2} = 3
*
* Abundant Number: The sum of its proper divisors exceeds itself.
* e.g. properD(12) = sum{1,2,3,4,6} = 16
*
* By mathematical analysis, all integers > 28123 can be expressed as the sum of 2 abundant
* numbers. This upper limit cannot, however, be reduced further even though it is known that the
* largest number that cannot be expressed as the sum of 2 abundant numbers is less than this
* upper limit.
*
* e.g.: N = 24
* smallest abundant number = 12,
* so smallest integer that can be expressed = 12 + 12 = 24
* result = True
*/
class NonAbundantSums {
/**
* Project Euler specific implementation meant to find the sum of all positive integers that
* cannot be written as the sum of 2 abundant numbers.
*
* N.B. The final test case shows that 20161 is the largest integer that cannot be expressed
* as such, even though 28123 is provided as the upper limit.
*/
fun sumOfAllNonAbundants(): Int {
return (0..20161).sumOf { if (isSumOfAbundants(it)) 0 else it }
}
/**
* Solution is optimised based on:
*
* - 12 being the smallest abundant number to exist, so the smallest integer expressed as a
* sum of abundants is 24.
*
* - 945 being the smallest odd abundant number.
*
* - An odd number has to be the sum of an even & odd number, so all odd numbers under
* 957 (945 + 12) cannot be the sum of abundants, since all other abundants below 945
* are even.
*
* - All integers > 20161 can be expressed as the sum of 2 abundant numbers, as shown in the
* final test case.
*
* - xMax of x + y = N would be N / 2, to avoid duplicate checks.
*/
fun isSumOfAbundants(n: Int): Boolean {
if (n < 24 || (n < 957 && n % 2 != 0)) return false
if (n > 20161) return true
val xMax = n / 2
val range = if (xMax < 945) {
12..xMax step 2
} else {
// could consider removing prime numbers > 944 from loop as primes cannot be abundant
// numbers, but the speed difference is negligible
(12..944 step 2) + (945..xMax)
}
for (x in range) {
if (isAbundant(x) && isAbundant(n - x)) {
return true
}
}
return false
}
fun isAbundant(n: Int) = sumProperDivisors(n) > n
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,879 | project-euler-kotlin | MIT License |
src/Day05.kt | mr-cell | 575,589,839 | false | {"Kotlin": 17585} | fun main() {
fun performInstructions(instructions: List<Instruction>, stacks: Stacks, reverse: Boolean) {
instructions.forEach { (howMany, from, to) ->
val crates = stacks[from].take(howMany)
repeat(howMany) { stacks[from].removeFirst() }
stacks[to].addAll(0, if (reverse) crates.reversed() else crates)
}
}
fun part1(input: List<String>): String {
val stacks = readStacks(input)
val instructions = readInstructions(input)
performInstructions(instructions, stacks, true)
return stacks.tops()
}
fun part2(input: List<String>): String {
val stacks = readStacks(input)
val instructions = readInstructions(input)
performInstructions(instructions, stacks, false)
return stacks.tops()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
private fun List<MutableList<Char>>.tops(): String = this.map { it.first() }.joinToString("")
private fun readStacks(input: List<String>): Stacks {
val stackRows = input.takeWhile { it.contains("[") }
return (1..stackRows.last().length step 4).map { index ->
stackRows.mapNotNull { it.getOrNull(index) }
.filter { it.isUpperCase() }
.toMutableList()
}
}
private fun readInstructions(input: List<String>): List<Instruction> {
return input.dropWhile { !it.startsWith("move") }
.map { it.split(" ") }
.map { Instruction(it.get(1).toInt(), it.get(3).toInt() - 1, it.get(5).toInt() - 1) }
}
private data class Instruction(val howMany: Int, val from: Int, val to: Int)
typealias Stacks = List<MutableList<Char>> | 0 | Kotlin | 0 | 0 | 2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9 | 1,892 | advent-of-code-2022 | Apache License 2.0 |
src/Day11/Day11.kt | lukeqwas | 573,403,156 | false | null | package Day11
import readInput
import java.lang.IllegalArgumentException
import java.math.BigDecimal
import java.math.BigInteger
fun main() {
val testInput = readInput("Day11/Day11")
val monkeyList = mutableListOf<Monkey>()
var startingItems = mutableListOf<Item>()
var operation = { x:BigDecimal -> BigDecimal.ZERO}
var testAction = { x:BigDecimal -> false}
var monkeyThrowTrue = 0
var divisor = BigDecimal.ONE
for(input in testInput) {
// create a monkey here
if(input.contains("Starting items")) {
// List of numbers
val startingItemsString = input.split(":")[1].trim().split(",")
startingItems = startingItemsString.map { Item(it.trim().toBigDecimal()) }.toMutableList()
} else if( input.contains("Operation:")) {
val x = input.split("= old ")[1].trim()
operation = parseFunction(x)
} else if(input.contains("Test: ")) {
divisor = parseDivisor(input)
testAction = parseTestAction(input, divisor)
} else if(input.contains("If true: throw to monkey")) {
monkeyThrowTrue = parseMonkeyThrow(input)
} else if(input.contains("If false: throw to monkey")) {
val monkeyThrowFalse = parseMonkeyThrow(input)
monkeyList.add(Monkey(startingItems, operation, testAction, monkeyThrowTrue, monkeyThrowFalse, divisor))
}
}
val modulo = monkeyList
.map {it.divisor}
.distinct()
.fold(BigDecimal.ONE) { acc, div -> acc * div }
calculateMonkeyBusiness(10_000, monkeyList, modulo)
// find the top two monkeys
monkeyList.sortByDescending { it.monkeyBusiness }
for(monkey in monkeyList){
println(monkey.monkeyBusiness)
}
println(BigInteger.valueOf(monkeyList[0].monkeyBusiness).multiply(BigInteger.valueOf(monkeyList[1].monkeyBusiness)))
}
fun parseMonkeyThrow(input: String): Int {
return "\\d+".toRegex().find(input, 0)?.value?.toInt()!!
}
fun calculateMonkeyBusiness(rounds: Int, monkeys: MutableList<Monkey>, modulo: BigDecimal) {
for(i in 0 until rounds) {
for (monkey in monkeys) {
for (item in monkey.items) {
monkey.inspect()
val worryLevel = monkey.operation(item.worryLevel) % modulo
// println(worryLevel)
val isTest = monkey.testAction(worryLevel)
if (isTest) {
monkeys[monkey.monkeyThrowTrue].items.add(Item(worryLevel))
} else {
monkeys[monkey.monkeyThrowFalse].items.add(Item(worryLevel))
}
}
monkey.clearItems()
}
}
}
data class Monkey(var items: MutableList<Item>,
val operation:(scalar: BigDecimal)-> BigDecimal,
val testAction:(value: BigDecimal) -> Boolean,
val monkeyThrowTrue: Int,
val monkeyThrowFalse: Int, val divisor: BigDecimal) {
var monkeyBusiness: Long = 0
fun inspect() {
this.monkeyBusiness++
}
fun clearItems() {
items = mutableListOf()
}
}
data class Item(val worryLevel: BigDecimal)
// input looks like <math_symbol> <number>
fun parseFunction(input: String): (x: BigDecimal) -> BigDecimal {
// get the number first
val scalar = "\\d+".toRegex().find(input, 0)?.value?.toBigDecimal() ?: return {y: BigDecimal -> y.pow(2)}
when(input[0]) {
'*' -> return {y: BigDecimal -> y.multiply(scalar) }
'+' -> return {y: BigDecimal -> y.plus(scalar)}
else -> throw IllegalArgumentException(input)
}
}
fun parseTestAction(input: String, divisor: BigDecimal): (x: BigDecimal) -> Boolean {
// val divisor = "\\d+".toRegex().find(input, 0)?.value?.toBigDecimal()
// ?: throw IllegalArgumentException("$input has no divisor")
return {x: BigDecimal -> (x.remainder(divisor)).equals(BigDecimal.ZERO)}
}
fun parseDivisor (input: String): BigDecimal {
return "\\d+".toRegex().find(input, 0)?.value?.toBigDecimal()
?: throw IllegalArgumentException("$input has no divisor")
} | 0 | Kotlin | 0 | 0 | 6174a8215f8d4dc6d33fce6f8300a4a8999d5431 | 4,153 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/aoc2020/day02_password_philosophy/PasswordPhilosophy.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package aoc2020.day02_password_philosophy
fun main() {
util.solve(424, ::partOne)
util.solve(747, ::partTwo)
}
data class Policy(val a: Int, val b: Int, val char: Char)
data class Record(val policy: Policy, val password: String)
object parseRecord {
private val RE_RECORD = Regex("""(\d+)-(\d+) ([a-z]): *([a-z]+)""")
operator fun invoke(it: String): Record = RE_RECORD
.find(it)
?.let { m ->
Record(
Policy(
m.groups[1]!!.value.toInt(),
m.groups[2]!!.value.toInt(),
m.groups[3]!!.value.first(),
),
m.groups[4]!!.value
)
}
?: throw IllegalStateException("Unrecognized record: '$it'")
}
private fun String.toRecords() = lines()
.map { parseRecord(it) }
fun partOne(input: String): Int {
// adding an early-exit when max is exceeded to skip processing
// the rest of the password makes it slower.
fun Policy.conforms(password: String) =
password.count { it == char } in a..b
return input
.toRecords()
.count {
it.policy.conforms(it.password)
}
}
fun partTwo(input: String): Int {
fun Policy.conforms(password: String): Boolean {
val atA = password[a - 1] == char
val atB = password[b - 1] == char
return if (atA) !atB else atB
}
return input
.toRecords()
.count {
it.policy.conforms(it.password)
}
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 1,525 | aoc-2021 | MIT License |
2017/src/main/java/p3/Problem3.kt | ununhexium | 113,359,669 | false | null | package p3
import more.format
import more.next
import p3.Position.x
import p3.Position.y
import kotlin.math.ceil
import kotlin.math.log10
// https://adventofcode.com/2017/day/3
val inputs = listOf(
1,
1024,
289326
)
fun main(args: Array<String>)
{
inputs.forEach {
println(buildSpiral(it))
}
}
private fun distance(input: Int): Int
{
if (input == 1) return 0
val MAX = 1000
/**
* ring / max value
* 0 / 1
* 1 / 9
* 2 / 25
* ... / ...
*/
val ring =
(0..MAX)
.asSequence()
.first { it -> ringToSquare(it) >= input }
// ring 2 has length 2, ring 3 has length 4
val ringSideLength = ringToSide(ring)
// the surface of the previous ring
val previousSquareRing = ringToSquare(ring - 1)
// 1, 9, 25, 49, 81 etc. have index 0
// then it goes +1 in the same direction as the original spiral
val ringIndex = input - previousSquareRing - ring
val edgeIndex = ringIndex % (ringSideLength - 1)
return ring + edgeIndex
}
fun square(i: Int) = i * i
fun ringToSide(i: Int) = i * 2 + 1
fun ringToSquare(i: Int) = square(ringToSide(i))
object Position
{
var x: Int = 0
var y: Int = 0
}
enum class Direction
{
UP,
LEFT,
DOWN,
RIGHT
}
fun moveThere(direction: Direction, distance: Int)
{
when (direction)
{
Direction.UP -> Position.y += distance
Direction.DOWN -> Position.y -= distance
Direction.LEFT -> Position.x -= distance
Direction.RIGHT -> Position.x += distance
}
}
fun buildSpiral(stopAfter: Int): Int
{
val side = 20
val grid = Array(side, { Array(side, { 0 }) })
Position.x = side / 2
Position.y = side / 2
grid[x][y] = 1
// 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, ....
var direction = Direction.RIGHT
val increments = (1..side).map { listOf(it, it) }.flatten()
val increment = increments.iterator()
while (x > 0
&& x < side - 1
&& y > 0
&& y < side - 1
)
{
(0 until increment.next()).forEach {
/**
* a b c
* d e f
* g h i
*
* sum a to i, screen coordinates
*/
grid[x][y] = (-1..1).map { yOffset ->
(-1..1).map { xOffset ->
grid[x + xOffset][y + yOffset]
}.sum()
}.sum()
println("[$x;$y] = " + grid[x][y])
if (grid[x][y] > stopAfter)
{
printFormatedGrid(grid)
return grid[x][y]
}
moveThere(direction, 1)
}
direction = direction.next()
}
printFormatedGrid(grid)
return -1
}
private fun printFormatedGrid(grid: Array<Array<Int>>)
{
val length = ceil(log10(grid.flatten().max()!!.toDouble() + 1.0)).toInt()
println(
grid.joinToString(separator = "") {
"\n" + it.joinToString(separator = " ") {
it.format(length)
}
}
)
} | 6 | Kotlin | 0 | 0 | d5c38e55b9574137ed6b351a64f80d764e7e61a9 | 2,791 | adventofcode | The Unlicense |
src/Day05.kt | lukewalker128 | 573,611,809 | false | {"Kotlin": 14077} | fun main() {
val testInput = readInput("Day05_test")
checkEquals("CMZ", part1(testInput))
checkEquals("MCD", part2(testInput))
val input = readInput("Day05")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
/**
* Execute commands from the given input on the initial stacks and output a combined string of the top crate on each
* stack.
*/
private fun part1(input: List<String>): String {
val (stacks, commands) = input.process()
// execute the list of commands
commands.forEach { command ->
val src = stacks[command.srcStack - 1]
val dest = stacks[command.destStack - 1]
require(command.numCrates <= src.size)
repeat(command.numCrates) {
dest.add(src.removeLast())
}
}
return stacks.map { it.last() }.joinToString(separator = "")
}
private fun List<String>.process(): Pair<List<MutableList<Char>>, List<Command>> {
val partitionIndex = indexOfFirst { it.isBlank() }
val stackLines = subList(0, partitionIndex)
val commandLines = subList(partitionIndex + 1, size)
// determine the number of stacks
val numStacks = stackLines.last().split(" ").last().toInt()
// initialize stacks from the input
val stacks = List(numStacks) { mutableListOf<Char>() }
for (i in stackLines.lastIndex - 1 downTo 0) {
val line = stackLines[i]
for (stackNum in 0 until numStacks) {
val charIndex = stackNum * 4 + 1
// need the bounds check since IJ removes trailing blank space from the input files
if (charIndex < line.length && line[charIndex].isLetter()) {
stacks[stackNum].add(line[charIndex])
}
}
}
// parse commands from the input
val commands = commandLines.map { Command(it) }
return Pair(stacks, commands)
}
private class Command(input: String) {
val numCrates: Int
val srcStack: Int
val destStack: Int
init {
val match = requireNotNull(commandRegex.matchEntire(input))
// first group is the entire substring matched
match.groupValues.let {
numCrates = it[1].toInt()
srcStack = it[2].toInt()
destStack = it[3].toInt()
}
}
override fun toString(): String {
return "num=$numCrates, src=$srcStack, dest=$destStack"
}
private companion object {
val commandRegex = Regex("^move (\\d+) from (\\d+) to (\\d+)$")
}
}
/**
* Same as Part 1, but moves entire groups of crates instead of one at a time.
*/
private fun part2(input: List<String>): String {
val (stacks, commands) = input.process()
commands.forEach { command ->
val src = stacks[command.srcStack - 1]
val dest = stacks[command.destStack - 1]
require(command.numCrates <= src.size)
// NOTE: slice is used here instead of subList since the latter has undefined behavior when structural changes
// are made to the base list.
dest.addAll(src.slice(src.size - command.numCrates .. src.lastIndex))
repeat(command.numCrates) {
src.removeLast()
}
}
return stacks.map { it.last() }.joinToString(separator = "")
}
| 0 | Kotlin | 0 | 0 | c1aa17de335bd5c2f5f555ecbdf39874c1fb2854 | 3,234 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | romainbsl | 572,718,344 | false | {"Kotlin": 17019} | fun main() {
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): String {
val (stacks, moves) = parse(input)
moves.forEach { move ->
repeat(move.count) {
stacks[move.to]?.addLast(
stacks[move.from]?.removeLast() ?: return@repeat
)
}
}
return stacks.values.map { it.last() }.joinToString("") { it.mark }
}
private fun part2(input: List<String>): String {
val (stacks, moves) = parse(input)
moves.forEach { move ->
val cratesToMove = buildList<Crate> {
repeat(move.count) {
stacks[move.from]?.removeLast()?.let { it1 -> add(it1) }
}
}
stacks[move.to]?.addAll(cratesToMove.reversed())
}
return stacks.values.map { it.last() }.joinToString("") { it.mark }
}
@JvmInline
value class Crate(val mark: String) {
companion object {
fun fromMark(charSequence: CharSequence) = Crate(charSequence.toString())
}
}
data class Move(val count: Int, val from: Int, val to: Int) {
companion object {
fun fromInput(line: String): Move {
val (count, from, to) = line
.remove("move ", "from ", " to")
.split(" ")
.map { it.toInt() }
return Move(count, from, to)
}
}
}
fun parse(input: List<String>): Pair<MutableMap<Int, ArrayDeque<Crate>>, List<Move>> {
val stacks = mutableMapOf<Int, ArrayDeque<Crate>>().apply {
input
.subList(0, input.indexOf(""))
.reversed()
.drop(1)
.forEach { line ->
line
.chunked(4) { it.trim().removePrefix("[").removeSuffix("]") }
.forEachIndexed { index, mark ->
if (mark.isEmpty()) return@forEachIndexed
val key = index + 1
val stack = getOrPut(key) { ArrayDeque() }.also {
it.addLast(Crate.fromMark(mark))
}
set(key, stack)
}
}
}
val moves = input
.subList(input.indexOf("") + 1, input.lastIndex + 1)
.map { Move.fromInput(it) }
return stacks to moves
} | 0 | Kotlin | 0 | 0 | b72036968769fc67c222a66b97a11abfd610f6ce | 2,487 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1011/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1011
/**
* LeetCode page: [1011. Capacity To Ship Packages Within D Days](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/);
*/
class Solution {
/* Complexity:
* Time O(N+K(LogM)(LogN)) and Space O(N) where N is the size of weights, K is days, and M is
* the total weight;
*/
fun shipWithinDays(weights: IntArray, days: Int): Int {
val weightsPrefixSum = buildPrefixSum(weights)
return findLeastCapacity(weightsPrefixSum, days)
}
private fun buildPrefixSum(weights: IntArray): IntArray {
val result = weights.clone()
for (i in 1 until result.size) {
result[i] += result[i - 1]
}
return result
}
private fun findLeastCapacity(weightsPrefixSum: IntArray, days: Int): Int {
val totalWeight = weightsPrefixSum.last()
var lowerBound = maxOf(totalWeight / days, weightsPrefixSum.first())
var upperBound = totalWeight
while (lowerBound < upperBound) {
val guess = (lowerBound + upperBound) ushr 1
val canShipInDays = verifyCapacity(guess, weightsPrefixSum, days)
if (canShipInDays) upperBound = guess else lowerBound = guess + 1
}
return lowerBound
}
private fun verifyCapacity(capacity: Int, weightsPrefixSum: IntArray, days: Int): Boolean {
val totalWeight = weightsPrefixSum.last()
var shippedWeight = 0
repeat(days) {
val maxShippedWeight = shippedWeight + capacity
if (maxShippedWeight >= totalWeight) return true
shippedWeight = findShippedWeight(maxShippedWeight, weightsPrefixSum)
if (shippedWeight == 0) return false
}
return false
}
private fun findShippedWeight(maxShippedWeight: Int, weightsPrefixSum: IntArray): Int {
val bsIndex = weightsPrefixSum.binarySearch(maxShippedWeight)
val shippedWeightIndex = if (bsIndex >= 0) bsIndex else -(bsIndex + 1) - 1
return if (shippedWeightIndex < 0) 0 else weightsPrefixSum[shippedWeightIndex]
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,125 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day08.kt | MisterTeatime | 561,848,263 | false | {"Kotlin": 20300} | fun main() {
fun part1(input: List<String>): Int {
val regexEscapeSequences = """\\x[0-9a-fA-F]{2}|\\\\|\\\"""".toRegex()
val codeLength = input.sumOf { it.length }
val memoryLength = input
.map { it.drop(1)} //Erstes Gänsefüßchen verwerfen
.map { it.dropLast(1) } //Letztes Gänsefüßchen verwerfen
.map { it.replace(regexEscapeSequences, "A")} //Escapesequenzen austauschen
.sumOf { it.length } //Durchzählen
return codeLength - memoryLength
}
fun part2(input: List<String>): Int {
val codeLength = input.sumOf { it.length }
val encodedCodeLength = input
.map { it.replace("""\""", """\\""") } //Escape \
.map { it.replace(""""""","""\"""") } // Escape "
.map { s -> "\"$s\""}
return encodedCodeLength.sumOf { it.length } - codeLength
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 12)
check(part2(testInput) == 19)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d684bd252a9c6e93106bdd8b6f95a45c9924aed6 | 1,182 | AoC2015 | Apache License 2.0 |
src/Day07.kt | zt64 | 572,594,597 | false | null | fun main() {
val input = readInput("Day07")
val log = input.lines()
val rootDirectory = Dir(null, "/")
var currentDirectory = rootDirectory
val fs = mutableListOf<FsEntity>()
fs.add(rootDirectory)
fun flatten(list: List<FsEntity>): List<FsEntity> = buildList {
list.forEach { entity ->
add(entity)
if (entity is Dir) addAll(flatten(entity.contents))
}
}
fun part1(): Long {
log.forEachIndexed { index, line ->
if (line.startsWith("$")) {
val commandArgs = line.removePrefix("$ ").split(" ")
val command = commandArgs.first()
val args = commandArgs.drop(1)
when (command) {
"cd" -> {
val directory = args.first()
currentDirectory = when {
directory == ".." -> currentDirectory.parent!!
directory.startsWith("/") -> rootDirectory
else -> {
currentDirectory.contents
.filterIsInstance<Dir>()
.first { it.name == directory }
}
}
}
"ls" -> {
val contents = log.drop(index + 1).takeWhile { !it.startsWith("$") }
currentDirectory.contents.addAll(
contents.map { entity ->
when {
entity.startsWith("dir") -> {
val name = entity.substringAfter("dir ")
Dir(currentDirectory, name)
}
else -> {
val (size, name) = entity.split(" ")
File(currentDirectory, name, size.toLong())
}
}
}
)
}
}
}
}
val flattened = flatten(rootDirectory.contents)
return flattened.filterIsInstance<Dir>()
.filter { it.size <= 100000 }
.sumOf { it.size }
}
fun part2(): Long {
val min = 30000000 - (70000000 - rootDirectory.size)
val flattened = flatten(rootDirectory.contents)
return flattened.filterIsInstance<Dir>()
.filter { it.size > min }
.minBy { it.size }.size
}
println(part1())
println(part2())
}
sealed interface FsEntity {
val parent: Dir?
val size: Long
}
data class File(
override val parent: Dir?,
val name: String,
override val size: Long,
) : FsEntity
data class Dir(
override val parent: Dir?,
val name: String,
val contents: MutableList<FsEntity> = mutableListOf()
) : FsEntity {
override fun toString(): String = name
override val size get() = contents.sumOf(FsEntity::size)
} | 0 | Kotlin | 0 | 0 | 4e4e7ed23d665b33eb10be59670b38d6a5af485d | 3,188 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day17.kt | dlew | 75,886,947 | false | null | class Day17 {
enum class Direction(val c: Char, val x: Int, val y: Int) {
UP('U', 0, -1),
DOWN('D', 0, 1),
LEFT('L', -1, 0),
RIGHT('R', 1, 0)
}
data class State(val x: Int, val y: Int, val moves: String)
companion object {
private val INDEX_TO_DIRECTION = arrayOf(Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT)
fun isOpen(c: Char) = when (c) {
'b', 'c', 'd', 'e', 'f' -> true
else -> false
}
fun openDoors(md5: String) = md5.take(4)
.mapIndexedNotNull { i, c -> if (isOpen(c)) INDEX_TO_DIRECTION[i] else null }
fun solveMaze(passcode: String) = solveMaze(passcode, State(0, 0, ""))
fun longestSolution(passcode: String) = longestSolution(passcode, State(0, 0, ""))
private fun solveMaze(passcode: String, initial: State): String {
val queue = mutableListOf(initial)
while (queue.isNotEmpty()) {
val state = queue.removeAt(0)
if (state.x < 0 || state.x > 3 || state.y < 0 || state.y > 3) {
continue
}
if (state.x == 3 && state.y == 3) {
return state.moves
}
val nextMoves = openDoors("$passcode${state.moves}".md5(true))
.mapNotNull { State(state.x + it.x, state.y + it.y, state.moves + it.c) }
queue.addAll(nextMoves)
}
throw IllegalStateException("Impossible maze!")
}
// A sloppy copy and paste job, but it'll do
private fun longestSolution(passcode: String, initial: State): Int {
val queue = mutableListOf(initial)
var longest: Int = 0
while (queue.isNotEmpty()) {
val state = queue.removeAt(0)
if (state.x < 0 || state.x > 3 || state.y < 0 || state.y > 3) {
continue
}
if (state.x == 3 && state.y == 3) {
longest = Math.max(state.moves.length, longest)
continue
}
val nextMoves = openDoors("$passcode${state.moves}".md5(true))
.mapNotNull { State(state.x + it.x, state.y + it.y, state.moves + it.c) }
queue.addAll(nextMoves)
}
return longest
}
}
} | 0 | Kotlin | 2 | 12 | 527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd | 2,119 | aoc-2016 | MIT License |
src/main/kotlin/de/consuli/aoc/year2022/days/Day08.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2022.days
import de.consuli.aoc.common.Day
class Day08 : Day(8, 2022) {
private val treesTestInput: List<Tree>
private val trees: List<Tree>
init {
trees = readTrees(false)
treesTestInput = readTrees(true)
}
override fun partOne(testInput: Boolean): Any {
return getTrees(testInput).count { it.isVisible() }
}
override fun partTwo(testInput: Boolean): Any {
return getTrees(testInput).maxOf { it.scenicScore }
}
private fun readTrees(testInput: Boolean): List<Tree> {
val treesInput = getInput(testInput).withIndex()
return treesInput.map { indexedTreeRow ->
val treeRowIndexed = indexedTreeRow.value.toCharArray().withIndex()
treeRowIndexed.map { treeRowIndex ->
Tree(
treeRowIndex.value.code,
getMaxTreeSizeForRowPart(treeRowIndexed.filter { it.index < treeRowIndex.index }
.map { it.value }),
getMaxTreeSizeForRowPart(treeRowIndexed.filter { it.index > treeRowIndex.index }
.map { it.value }),
getMaxTreeSizeForColumn(
treesInput.filter { it.index > indexedTreeRow.index },
treeRowIndex.index
),
getMaxTreeSizeForColumn(
treesInput.filter { it.index < indexedTreeRow.index },
treeRowIndex.index
),
calculateScenicScore(
indexedTreeRow.index,
treeRowIndex.index,
treeRowIndex.value.code,
testInput
)
)
}
}.flatten()
}
private fun getColumn(testInput: Boolean, column: Int): String {
return getInput(testInput).joinToString("") { it.toCharArray()[column].toString() }
}
private fun calculateScenicScore(rowIndex: Int, columnIndex: Int, treeSize: Int, testInput: Boolean): Int {
val column = getColumn(testInput, columnIndex)
val row = getInput(testInput)[rowIndex]
val scoreUp = calculateScoreForDirection(column.substring(0, rowIndex).reversed().toCharArray(), treeSize)
val scoreLeft = calculateScoreForDirection(row.substring(0, columnIndex).reversed().toCharArray(), treeSize)
val scoreDown = calculateScoreForDirection(column.substring(rowIndex + 1).toCharArray(), treeSize)
val scoreRight = calculateScoreForDirection(row.substring(columnIndex + 1).toCharArray(), treeSize)
return scoreUp * scoreDown * scoreLeft * scoreRight
}
private fun calculateScoreForDirection(remainingDirectionChars: CharArray, size: Int): Int {
return (remainingDirectionChars
.indexOfFirst { it.code >= size } + 1).addRemainingVisibleTreesToEdge(remainingDirectionChars.size)
}
private fun getTrees(testInput: Boolean): List<Tree> {
return when (testInput) {
true -> treesTestInput
false -> trees
}
}
private fun Int.addRemainingVisibleTreesToEdge(reaminingTreesInSight: Int) =
if (toInt() == 0) reaminingTreesInSight else toInt()
private fun getMaxTreeSizeForColumn(rows: List<IndexedValue<String>>?, columnIndex: Int): Int {
return rows?.maxOfOrNull { it.value.toCharArray()[columnIndex].code } ?: 0
}
private fun getMaxTreeSizeForRowPart(treeRow: Iterable<Char>): Int {
return treeRow.maxOfOrNull { it.code } ?: 0
}
}
class Tree(
private val size: Int,
private val maxSizeTreeLeft: Int,
private val maxSizeTreeRight: Int,
private val maxSizeTreesBottom: Int,
private val maxSizeTreesTop: Int,
val scenicScore: Int
) {
fun isVisible(): Boolean {
return size > sequenceOf(
this.maxSizeTreesBottom,
this.maxSizeTreeLeft,
this.maxSizeTreeRight,
this.maxSizeTreesTop
).min()
}
}
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 4,086 | advent-of-code | Apache License 2.0 |
aoc/src/main/kotlin/com/bloidonia/aoc2023/graph/Graph.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.graph
import java.util.PriorityQueue
typealias Neighbours<Vertex> = (Vertex) -> List<Vertex>
typealias End<Vertex> = (Vertex) -> Boolean
typealias Cost<Vertex> = (Vertex, Vertex) -> Long
typealias Fudge<Vertex> = (Vertex) -> Long
data class Seen<Vertex>(val cost: Long, val prev: Vertex?)
private data class Score<Vertex>(
val vertex: Vertex,
val score: Long,
val fudge: Long
) : Comparable<Score<Vertex>> {
override fun compareTo(other: Score<Vertex>): Int =
(score + fudge).compareTo(other.score + other.fudge)
}
class Result<Vertex>(
val start: Vertex,
private val end: Vertex?,
private val result: Map<Vertex, Seen<Vertex>>
) {
private fun getScore(vertex: Vertex) = result[vertex]?.cost
fun getScore() = end?.let { getScore(it) }
}
fun <Vertex> shortestPath(
start: Vertex,
endFunction: End<Vertex>,
neighbours: Neighbours<Vertex>,
cost: Cost<Vertex> = { _, _ -> 1 },
fudge: Fudge<Vertex> = { 0 }
): Result<Vertex> {
val toVisit = PriorityQueue(listOf(Score(start, 0, fudge(start))))
val seenPoints: MutableMap<Vertex, Seen<Vertex>> = mutableMapOf(start to Seen(0, null))
var last: Vertex? = null
while (last == null) {
if (toVisit.isEmpty()) {
// No path
return Result(start, null, seenPoints)
}
val (current, currentScore) = toVisit.remove()
last = if (endFunction(current)) current else null
val nextPoints = neighbours(current)
.filter { it !in seenPoints }
.map { next -> Score(next, currentScore + cost(current, next), fudge(next)) }
toVisit.addAll(nextPoints)
seenPoints.putAll(nextPoints.associate { it.vertex to Seen(it.score, current) })
}
return Result(start, last, seenPoints)
}
| 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 1,828 | aoc-2023 | MIT License |
app/src/main/kotlin/day04/Day04.kt | meli-w | 433,710,859 | false | {"Kotlin": 52501} | package day04
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 4
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay04Part1, ::solveDay04Part2)
}
fun solveDay04Part1(input: List<String>): Int {
val bingoNumbers: List<Int> = getBingoNumber(input)
val bingoFields = getBingoField(input)
return checkWinning(bingoNumbers, bingoFields)
}
fun solveDay04Part2(input: List<String>): Int {
val bingoNumbers: List<Int> = getBingoNumber(input)
val bingoFields = getBingoField(input)
return checkWinningPart2(bingoNumbers, bingoFields)
}
private fun checkWinning(
bingoNumbers: List<Int>,
bingoFields: List<Board>
): Int {
bingoNumbers.forEach { number ->
bingoFields.forEach { board ->
board.checkNumber(number)
if (board.hasBingo()) {
return number * board.sumUnmarkedNumbers()
}
}
}
return 0
}
private fun checkWinningPart2(
bingoNumbers: List<Int>,
bingoFields: List<Board>
): Int {
val mutableBingoFields: MutableList<Board> = bingoFields.toMutableList()
var winningCheckSum = 0
bingoNumbers.forEach { number ->
val winningBoards = mutableBingoFields.checkNumber(number)
if (winningBoards.isNotEmpty()) {
winningBoards
.reversed()
.forEach {
mutableBingoFields.removeAt(it.boardIndex)
}
winningCheckSum = winningBoards.last().winningCheckSum
}
}
return winningCheckSum
}
private fun List<Board>.checkNumber(number: Int): List<WinningBoard> {
val winningBoards = mutableListOf<WinningBoard>()
forEachIndexed { index, board ->
board.checkNumber(number)
if (board.hasBingo()) {
winningBoards.add(
WinningBoard(
winningCheckSum = number * board.sumUnmarkedNumbers(),
boardIndex = index
)
)
}
}
return winningBoards
}
data class WinningBoard(val winningCheckSum: Int, val boardIndex: Int)
class Board(val board: List<List<BingoNumber>>) {
fun checkNumber(number: Int) {
board.forEach { row: List<BingoNumber> ->
row.forEach { bingoNumber ->
if (number == bingoNumber.value) {
bingoNumber.isChecked = true
}
}
}
}
fun hasBingo(): Boolean = bingoRow() || bingoColumn()
fun sumUnmarkedNumbers(): Int = board
.flatten()
.filter { !it.isChecked }
.sumOf { it.value }
private fun bingoColumn(): Boolean {
repeat(board.size) { columnIndex ->
board
.map { it[columnIndex] }
.let { column ->
if (bingo(column)) {
return true
}
}
}
return false
}
private fun bingoRow(): Boolean {
board.forEach { row ->
if (bingo(row)) {
return true
}
}
return false
}
private fun bingo(bingoNumbers: List<BingoNumber>): Boolean = bingoNumbers.all(BingoNumber::isChecked)
}
data class BingoNumber(val value: Int, var isChecked: Boolean = false)
fun getBingoNumber(input: List<String>): List<Int> = input
.first()
.split(",")
.map { it.toInt() }
fun getBingoField(input: List<String>): List<Board> = input
.let { it.subList(2, it.size) }
.filterNot { it.isEmpty() }
.chunked(5)
.map { bingoField: List<String> ->
Board(
bingoField
.map { row ->
row
.replace("(\\s+)?(\\d+)".toRegex(), "$2,")
.split(",")
.filterNot { it.isEmpty() }
.map { BingoNumber(it.toInt()) }
}
)
} | 0 | Kotlin | 0 | 1 | f3b96c831d6c8e21de1ac866cf9c64aaae2e5ea1 | 4,041 | AoC-2021 | Apache License 2.0 |
src/main/kotlin/Day8_2.kt | vincent-mercier | 726,287,758 | false | {"Kotlin": 37963} | import java.io.File
import java.io.InputStream
private fun gcd(x: Long, y: Long): Long {
return if ((y == 0L)) x else gcd(y, x % y)
}
private fun lcm(numbers: Sequence<Long>): Long {
return numbers
.fold(1) { x: Long, y: Long ->
x * (y / gcd(x, y))
}
}
fun firstZ(
directions:Sequence<Char>,
directionMap: Map<String, Map<Char, String>>,
starting: String
): Long {
var current = starting
var steps = 0L
for (direction in directions) {
steps++
current = directionMap[current]!![direction]!!
if (current.last() == 'Z') return steps
}
return -1L
}
fun main() {
val directionRegex = "(?<key>[A-Z]{3}) = \\((?<left>[A-Z]{3}), (?<right>[A-Z]{3})\\)".toRegex()
val inputStream: InputStream = File("./src/main/resources/day8.txt").inputStream()
val inputText = inputStream.bufferedReader().readLines()
val directions = inputText.removeFirst()
val directionMap = inputText.mapNotNull { directionRegex.find(it) }
.map {
it.groups["key"]!!.value to mapOf(
'L' to it.groups["left"]!!.value,
'R' to it.groups["right"]!!.value
)
}
.toMap()
var aNodes = directionMap.keys.filter { it.last() == 'A' }
val firstZs = aNodes.asSequence().map { firstZ(directionsSequence(directions), directionMap, it) }
var steps: Long = lcm(firstZs)
println(steps)
}
fun containAllSame(aNodes: List<String>, startingToLastAndZs: Map<String, Pair<String, Set<Int>>>): Int? {
val lists = aNodes.map { startingToLastAndZs[it]!!.second }
return lists.removeFirst().firstOrNull {value -> lists.all { it.contains(value) } }
}
| 0 | Kotlin | 0 | 0 | 53b5d0a0bb65a77deb5153c8a912d292c628e048 | 1,712 | advent-of-code-2023 | MIT License |
src/Day02.kt | m0r0 | 576,999,741 | false | null | fun main() {
fun part1(input: List<String>): Int {
return solvePart1(input)
}
fun part2(input: List<String>): Int {
return solvePart2(input)
}
val input = readInput("Day02")
part1(input).println()
part2(input).println()
}
fun solvePart1(input: List<String>): Int {
return input.sumOf { singleGame ->
getOutcome(singleGame).score + getScoreForPlay(singleGame.split(" ").last())
}
}
fun solvePart2(input: List<String>): Int {
return input.sumOf { singleGame ->
val desiredOutcome = getDesiredOutcome(singleGame)
desiredOutcome.score + getScoreForOutcome(singleGame.split(" ").first(), desiredOutcome)
}
}
private fun getOutcome(input: String): Outcome {
return when (input) {
"$ROCK_1 $ROCK_2", "$PAPER_1 $PAPER_2", "$SCISSORS_1 $SCISSORS_2" -> Outcome.Draw
"$ROCK_1 $PAPER_2", "$PAPER_1 $SCISSORS_2", "$SCISSORS_1 $ROCK_2" -> Outcome.Win
"$ROCK_1 $SCISSORS_2", "$PAPER_1 $ROCK_2", "$SCISSORS_1 $PAPER_2" -> Outcome.Loss
else -> throw IllegalStateException("Invalid input $input")
}
}
private fun getDesiredOutcome(input: String): Outcome {
return when (input.split(" ").last()) {
DRAW -> Outcome.Draw
WIN -> Outcome.Win
LOSS -> Outcome.Loss
else -> throw IllegalStateException("Invalid input $input")
}
}
private fun getScoreForOutcome(opponentsPlay: String, outcome: Outcome): Int {
return when (opponentsPlay) {
ROCK_1 -> when (outcome) {
Outcome.Loss -> getScoreForPlay(SCISSORS_2)
Outcome.Win -> getScoreForPlay(PAPER_2)
Outcome.Draw -> getScoreForPlay(ROCK_2)
}
PAPER_1 -> when (outcome) {
Outcome.Win -> getScoreForPlay(SCISSORS_2)
Outcome.Draw -> getScoreForPlay(PAPER_2)
Outcome.Loss -> getScoreForPlay(ROCK_2)
}
SCISSORS_1 -> when (outcome) {
Outcome.Draw -> getScoreForPlay(SCISSORS_2)
Outcome.Loss -> getScoreForPlay(PAPER_2)
Outcome.Win -> getScoreForPlay(ROCK_2)
}
else -> throw IllegalStateException("Invalid play $opponentsPlay")
}
}
private fun getScoreForPlay(play: String): Int {
return play.first().code - 'W'.code
}
sealed class Outcome(val score: Int) {
object Loss : Outcome(0)
object Draw : Outcome(3)
object Win : Outcome(6)
}
private const val ROCK_1 = "A"
private const val PAPER_1 = "B"
private const val SCISSORS_1 = "C"
private const val ROCK_2 = "X"
private const val LOSS = "X"
private const val PAPER_2 = "Y"
private const val DRAW = "Y"
private const val SCISSORS_2 = "Z"
private const val WIN = "Z"
| 0 | Kotlin | 0 | 0 | b6f3c5229ad758f61f219040f8db61f654d7fc00 | 2,699 | kotlin-AoC-2022 | Apache License 2.0 |
src/day05/Day05.kt | iliascholl | 572,982,464 | false | {"Kotlin": 8373} | package day05
import day05.Instruction.Companion.toInstruction
import readInput
private typealias Stack = MutableMap.MutableEntry<Int, ArrayDeque<Char>>
private typealias Stacks = MutableMap<Int, ArrayDeque<Char>>
private data class Instruction(
val amount: Int,
val from: Int,
val to: Int,
) {
companion object {
private operator fun MatchResult?.get(key: String): Int = this
?.groups
?.get(key)
?.value
?.toInt()
?: throw IllegalArgumentException("Cannot parse '$this'")
fun String.toInstruction() =
Regex("^move (?<amount>\\d+) from (?<from>\\d+) to (?<to>\\d+)$")
.matchEntire(this)
.let {
Instruction(
amount = it["amount"],
from = it["from"],
to = it["to"],
)
}
}
}
private fun List<String>.readInitialState(): Pair<Stacks, List<Instruction>> {
val separator = indexOfFirst(String::isBlank)
val stacks = subList(0, separator)
val instructions = subList(separator + 1, size)
return stacks.readStacks() to instructions.readInstructions()
}
private fun List<String>.readInstructions() = map { instruction ->
instruction.toInstruction()
}
private fun List<String>.readStacks(): Stacks = ArrayDeque(reversed()).let { deque ->
val columns = deque.removeFirst()
.withIndex()
.filter { it.value.isDigit() }
.map { IndexedValue(it.index, it.value.digitToInt()) }
val stacks = mutableMapOf<Int, ArrayDeque<Char>>()
columns.forEach { stacks[it.value] = ArrayDeque() }
deque.forEach { line ->
columns.forEach { (index, value) ->
line[index]
.takeIf(Char::isLetter)
?.let { stacks[value]?.addFirst(line[index]) }
}
}
return stacks
}
private fun processInstruction(stacks: Stacks, instruction: Instruction) = stacks.also {
val (amount, from, to) = instruction
repeat(amount) {
stacks[from]?.removeFirst()
?.let { stacks[to]?.addFirst(it) }
}
}
private fun processInstructionMultiContainer(stacks: Stacks, instruction: Instruction) = stacks.also {
val (amount, from, to) = instruction
List(amount) {
stacks[from]?.removeFirst()
}.reversed().forEach {
it?.let { stacks[to]?.addFirst(it) }
}
}
private fun Stacks.output() =
entries.sortedBy(Stack::key).joinToString("") { it.value.removeFirst().toString() }
fun main() {
fun part1(input: List<String>) = input
.readInitialState()
.let { (stacks, instructions) -> instructions.fold(stacks, ::processInstruction) }
.output()
fun part2(input: List<String>) = input
.readInitialState()
.let { (stacks, instructions) -> instructions.fold(stacks, ::processInstructionMultiContainer) }
.output()
check(part1(readInput("day05/test")) == "CMZ")
println(part1(readInput("day05/input")))
check(part2(readInput("day05/test")) == "MCD")
println(part2(readInput("day05/input")))
}
| 0 | Kotlin | 0 | 1 | 26db12ddf4731e4ee84f45e1dc4385707f9e1d05 | 3,159 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2021/Day19.kt | colinodell | 433,864,377 | true | {"Kotlin": 111114} | package com.colinodell.advent2021
// I really struggled with this one, so I ended up adapting the solution from the following:
// - https://bit.ly/3Ei8rOw
// - https://github.com/ThomasBollmeier/advent-of-code-kotlin-2021
class Day19(input: String) {
private val scanners = input.split("\n\n").map { s ->
Scanner(s.split("\n").filter { !it.startsWith("---") }.map { line ->
line.split(",").map { it.toInt() }.let {
Vector3(it[0], it[1], it[2])
}
})
}
fun solvePart1() = solution.flatMap { it.first.beacons }.distinct().size
fun solvePart2() = solution.permutationPairs().maxOf { (a, b) -> a.second.manhattanDistance(b.second) }
private val solution: List<Pair<Scanner, Vector3>> by lazy {
val located = mutableListOf<Pair<Scanner, Vector3>>()
val locatedIndices = mutableSetOf<Int>()
located.add(Pair(scanners[0], Vector3(0, 0, 0)))
locatedIndices.add(0)
var locatedIdx = 0
while (locatedIdx < located.size) {
val (a, _) = located[locatedIdx]
for ((i, b) in scanners.withIndex()) {
if (i in locatedIndices) {
continue
}
a.findOverlap(b).ifNotNull {
locatedIndices.add(i)
located.add(Pair(it.partner, it.relativePosition))
}
}
locatedIdx++
}
located
}
private data class Overlap(val partner: Scanner, val relativePosition: Vector3, val commonBeacons: Set<Vector3>)
private inner class Scanner(val beacons: List<Vector3>) {
fun findOverlap(other: Scanner): Overlap? {
for (t in transforms) {
for (i in beacons.indices) {
for (j in other.beacons.indices) {
val overlap = calcOverlap(other, t, i, j)
if (overlap.commonBeacons.size >= 12) {
return overlap
}
}
}
}
return null
}
private fun calcOverlap(other: Scanner, t: (Vector3) -> Vector3, i: Int, j: Int): Overlap {
// Transform and move the beacons
var s = other.transform(t)
val dr = beacons[i] - s.beacons[j]
s = s.move(dr)
val overlapPositions = beacons.toSet() intersect s.beacons.toSet()
return Overlap(s, dr, overlapPositions)
}
private fun transform(t: (Vector3) -> Vector3) = Scanner(beacons.map(t))
private fun move(dr: Vector3) = Scanner(beacons.map { it + dr })
}
private val transforms by lazy {
val vectors = listOf(
Vector3(1, 0, 0),
Vector3(-1, 0 , 0),
Vector3(0, 1, 0),
Vector3(0, -1, 0),
Vector3(0, 0, 1),
Vector3(0, 0, -1)
)
val result = mutableListOf<(Vector3) -> Vector3>()
for (vi in vectors) {
for (vj in vectors) {
if (vi.dot(vj) == 0) {
val vk = vi.cross(vj)
val t = arrayOf(vi.toArray(), vj.toArray(), vk.toArray())
result.add { v ->
val r = arrayOf(v.x, v.y, v.z)
val x = (0..2).fold(0) { acc, i ->
acc + t[0][i] * r[i]
}
val y = (0..2).fold(0) { acc, i ->
acc + t[1][i] * r[i]
}
val z = (0..2).fold(0) { acc, i ->
acc + t[2][i] * r[i]
}
Vector3(x, y, z)
}
}
}
}
result
}
}
| 0 | Kotlin | 0 | 1 | a1e04207c53adfcc194c85894765195bf147be7a | 3,873 | advent-2021 | Apache License 2.0 |
advent2022/src/main/kotlin/year2022/Day07.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2022
import AdventDay
sealed interface Node {
val name: String
val parent: Node?
val fileSize: Int
}
class File(override val fileSize: Int, override val name: String, override val parent: Node?): Node
class Directory(
override val name: String,
override val parent: Node?,
val children: MutableList<Node> = mutableListOf()
): Node {
override val fileSize: Int
get() = children.sumOf { it.fileSize }
fun filterInTree(pre: (Directory) -> Boolean): List<Directory> =
children.filterIsInstance<Directory>()
.flatMap { it.filterInTree(pre) } +
if (pre(this))
listOf(this)
else
emptyList()
}
fun List<String>.computeFolderContent(parent: Node): List<Node> = drop(1).map {
val (a, b) = it.split(" ")
when (a) {
"dir" -> Directory(b, parent)
else -> File(a.toInt(), b, parent)
}
}
fun List<String>.parseInput(): Directory {
val realInput = drop(1).joinToString("\n").split("$ ")
var cur = Directory("/", null)
val root = cur
for (i in realInput.drop(1).map { it.lines().filter { l -> l.isNotBlank() } }) {
when {
i.first().startsWith("ls") -> {
val children = i.computeFolderContent(cur)
cur.children.addAll(children)
}
else -> {
val (_, dir) = i.first().split(" ")
cur = when (dir) {
".." -> cur.parent as Directory
"/" -> root
else -> cur.children.find { it.name == dir } as? Directory ?: error(dir)
}
}
}
}
return root
}
class Day07 : AdventDay(2022, 7) {
override fun part1(input: List<String>): Int {
val root = input.parseInput()
return root.filterInTree { it.fileSize <= 100_000 }.sumOf { it.fileSize }
}
override fun part2(input: List<String>): Int {
val root = input.parseInput()
val currentSize = root.fileSize
return root.filterInTree {
70_000_000 - (currentSize - it.fileSize) >= 30_000_000
}.minOf { it.fileSize }
}
}
fun main() = Day07().run() | 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 2,235 | advent-of-code | Apache License 2.0 |
src/Day12/Day12.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day12
import readInput
import java.util.PriorityQueue
import kotlin.math.*
class Node(val elevation: Int): Comparable<Node> {
var distance = Int.MAX_VALUE - 1
var prev: Node? = null
var neighbors = mutableListOf<Node>()
fun isReachable(other: Node): Boolean {
return other.elevation <= elevation + 1
}
fun reset() {
distance = Int.MAX_VALUE - 1
prev = null
}
override fun compareTo(other: Node) = compareValuesBy(this, other, {it.distance}, {it.distance})
}
class Maze() {
var nodesPriorityQueue = PriorityQueue<Node>()
var allNodes = mutableListOf<Node>()
var targetNode: Node? = null
var smallestStartNodeDist = Int.MAX_VALUE
fun processInput(input: List<String>, multipleStarts: Boolean) {
val matrix = mutableListOf<MutableList<Node>>()
for (row in input) {
var matrixRow = mutableListOf<Node>()
matrix.add(matrixRow)
for (nodeChar in row) {
if (nodeChar == 'S') {
val node = Node('a'.code)
node.distance = 0
matrixRow.add(node)
nodesPriorityQueue.add(node)
} else if (nodeChar == 'E') {
val node = Node('z'.code)
targetNode = node
matrixRow.add(node)
nodesPriorityQueue.add(node)
} else {
val node = Node(nodeChar.code)
if(multipleStarts && nodeChar == 'a') {
node.distance = 0
}
matrixRow.add(node)
nodesPriorityQueue.add(node)
}
}
}
allNodes = nodesPriorityQueue.toMutableList()
for (rowIndex in matrix.indices) {
val row = matrix[rowIndex]
for (nodeIndex in row.indices) {
val node = row[nodeIndex]
//N
if(rowIndex > 0 && node.isReachable(matrix[rowIndex - 1][nodeIndex])) {
node.neighbors.add(matrix[rowIndex - 1][nodeIndex])
}
//S
if(rowIndex < matrix.size - 1 && node.isReachable(matrix[rowIndex + 1][nodeIndex])) {
node.neighbors.add(matrix[rowIndex + 1][nodeIndex])
}
//E
if(nodeIndex < row.size - 1 && node.isReachable(matrix[rowIndex][nodeIndex + 1])) {
node.neighbors.add(matrix[rowIndex][nodeIndex + 1])
}
//W
if(nodeIndex > 0 && node.isReachable(matrix[rowIndex][nodeIndex - 1])) {
node.neighbors.add(matrix[rowIndex][nodeIndex - 1])
}
}
}
}
fun runDjikstras() {
while (nodesPriorityQueue.isNotEmpty()) {
val node = nodesPriorityQueue.remove()
for (neighbor in node.neighbors) {
val dist = node.distance + 1
if(dist < neighbor.distance) {
neighbor.distance = dist
neighbor.prev = node
nodesPriorityQueue.remove(neighbor)
nodesPriorityQueue.add(neighbor)
}
}
}
}
fun getShortsDist(): Int {
return targetNode!!.distance
}
}
fun main() {
fun part1(input: List<String>): Int {
val maze = Maze()
maze.processInput(input, false)
maze.runDjikstras()
return maze.getShortsDist()
}
fun part2(input: List<String>): Int {
val maze = Maze()
maze.processInput(input, true)
maze.runDjikstras()
return maze.getShortsDist()
}
val testInput = readInput("Day12","Day12_test")
println(part1(testInput))
check(part1(testInput) == 31)
println(part2(testInput))
check(part2(testInput) == 29)
val input = readInput("Day12","Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 4,070 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | freszu | 573,122,040 | false | {"Kotlin": 32507} | import kotlin.math.abs
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
fun Position.manhattanDistance(other: Position) = abs(this.x - other.x) + abs(this.y - other.y)
@OptIn(ExperimentalTime::class)
fun main() {
val inputLineRegex = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""")
data class SensorBeaconArea(val sensor: Position, val beacon: Position) {
val range = sensor.manhattanDistance(beacon)
operator fun contains(position: Position) = position != beacon && sensor.manhattanDistance(position) <= range
}
fun parse(lines: List<String>): List<SensorBeaconArea> = lines.map { line ->
val (sx, sy, bx, by) = inputLineRegex.matchEntire(line)!!.destructured
SensorBeaconArea(
(sx.toInt() to sy.toInt()),
(bx.toInt() to by.toInt())
)
}
fun yWithNoBeaconSpaceCount(y: Int, sensorsToBeacons: List<SensorBeaconArea>): Int {
val xMin = sensorsToBeacons.minOf { sb -> sb.sensor.x - sb.range }
val xMax = sensorsToBeacons.maxOf { sb -> sb.sensor.x + sb.range }
return (xMin..xMax).count { x ->
sensorsToBeacons.any { sensorBeaconArea ->
val testedPosition = (x to y)
testedPosition in sensorBeaconArea
}
}
}
fun part2(maxRange: Int, sensorsToBeacons: List<SensorBeaconArea>): Long {
fun positionWithNoBeacon(maxRange: Int, sensorsToBeacons: List<SensorBeaconArea>): Position? {
for (x in 0..maxRange) {
var y = 0
while (y <= maxRange) {
val testedPosition = (x to y)
val sensorBeaconArea = sensorsToBeacons.find { testedPosition in it } ?: return testedPosition
y = sensorBeaconArea.sensor.y + sensorBeaconArea.range - abs(x - sensorBeaconArea.sensor.x) + 1
}
}
return null
}
val distressBeacon = requireNotNull(positionWithNoBeacon(maxRange, sensorsToBeacons))
return distressBeacon.x.toLong() * 4000000L + distressBeacon.y.toLong()
}
val testInput = readInput("Day15_test")
val input = readInput("Day15")
val testSensorsToBeacons = parse(testInput)
val sensorsToBeacons = parse(input)
check(yWithNoBeaconSpaceCount(10, testSensorsToBeacons) == 26)
measureTime {
println(yWithNoBeaconSpaceCount(2000000, sensorsToBeacons))
}.also { println("Time part1: $it") }
check(part2(20, testSensorsToBeacons) == 56000011L)
measureTime {
println(part2(4000000, sensorsToBeacons))
}.also { println("Time part2: $it") }
}
| 0 | Kotlin | 0 | 0 | 2f50262ce2dc5024c6da5e470c0214c584992ddb | 2,696 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day9.kt | nerok | 572,862,875 | false | {"Kotlin": 32118} | import java.io.File
fun main(args: Array<String>) {
day9part2()
}
fun day9part1() {
var coordinates = mutableListOf<List<Int>>()
val input = File("day9input.txt").bufferedReader().readLines()
input.mapIndexed { index, line ->
line.split("")
.filterNot { it == "" }
.map { it.toInt() }
.let { coordinates.add(index, it) }
}
findLocalMinimas(coordinates).map { coordinates[it.first][it.second]+1 }.sum().also { println(it) }
}
fun day9part2() {
var coordinates = mutableListOf<List<Int>>()
val input = File("day9input.txt").bufferedReader().readLines()
input.mapIndexed { index, line ->
line.split("")
.filterNot { it == "" }
.map { it.toInt() }
.let { coordinates.add(index, it) }
}
val limits = findBasinLimits(coordinates)
println("Total size: ${coordinates.size * coordinates.first().size}")
println("Nines: ${limits.size}")
val score = clusterBaisins(coordinates, limits)
.map { it.value.size }
.sorted()
.also { "Non-nines: ${println(it.sum())}" }
.takeLast(3)
.reduce { acc: Int, i: Int ->
acc * i
}
println("Score $score")
}
fun clusterBaisins(map: MutableList<List<Int>>, basinLimits: Set<Pair<Int,Int>>): Map<Int, Set<Pair<Int,Int>>> {
var nextCluster = 0
val clusterMap = mutableMapOf<Int, Set<Pair<Int,Int>>>()
val clusterIndex = mutableMapOf<Pair<Int,Int>, Int>()
map.forEachIndexed { rowIndex, row ->
row.forEachIndexed { index, point ->
if (point == 9) return@forEachIndexed
val columnNeighbours = when (rowIndex) {
0 -> {
listOf(rowIndex+1 to index to clusterIndex.getOrDefault(rowIndex+1 to index, -1))
}
map.size - 1 -> {
listOf(rowIndex-1 to index to clusterIndex.getOrDefault(rowIndex-1 to index, -1))
}
else -> {
listOf(
rowIndex-1 to index to clusterIndex.getOrDefault(rowIndex-1 to index, -1),
rowIndex+1 to index to clusterIndex.getOrDefault(rowIndex+1 to index, -1)
)
}
}
val rowNeighbours = when(index) {
0 -> {
listOf(rowIndex to index + 1 to clusterIndex.getOrDefault(rowIndex to index + 1, -1))
}
row.size - 1 -> {
listOf(rowIndex to index - 1 to clusterIndex.getOrDefault(rowIndex to index - 1, -1))
}
else -> {
listOf(
rowIndex to index-1 to clusterIndex.getOrDefault(rowIndex to index-1, -1),
rowIndex to index+1 to clusterIndex.getOrDefault(rowIndex to index+1, -1)
)
}
}
val neighbours = columnNeighbours + rowNeighbours
if (neighbours.none { it.second != -1 }) {
val neighbourhood = (neighbours.map { it.first } + (rowIndex to index))
.filter { map[it.first][it.second] != 9 }
.toSet()
clusterMap[nextCluster] = neighbourhood
neighbourhood.forEach {
clusterIndex[it] = nextCluster
}
nextCluster = nextCluster.inc()
}
else {
val neighbourhood = (neighbours.map { it.first } + (rowIndex to index))
.filter { map[it.first][it.second] != 9 }
.toMutableSet()
var cluster = -1
neighbourhood.map {
if (cluster == -1) {
cluster = clusterIndex.getOrDefault(it, -1)
}
else {
val neighbourIndex = clusterIndex[it]
if (neighbourIndex != null && cluster != neighbourIndex) {
println("Cluster: $cluster, neighbour: ${neighbourIndex}, it: $it")
val newCluster = minOf(cluster, neighbourIndex)
val neighbourhood1 = clusterMap.getOrDefault(neighbourIndex, emptySet())
clusterMap.remove(neighbourIndex)
val neighbourhood2 = clusterMap.getOrDefault(cluster, emptySet())
clusterMap.remove(cluster)
val newNeighbourhood = neighbourhood1 + neighbourhood2
newNeighbourhood.forEach { clusterIndex[it] = newCluster }
clusterMap[newCluster] = newNeighbourhood
}
}
}
neighbourhood.forEach {
clusterIndex[it] = cluster
}
clusterMap[cluster]?.let { neighbourhood.addAll(it) }
clusterMap[cluster] = neighbourhood
}
}
}
return clusterMap
}
fun findBasinLimits(map: MutableList<List<Int>>): Set<Pair<Int,Int>> {
val limits = mutableSetOf<Pair<Int,Int>>()
map.forEachIndexed { rowIndex, row ->
row.forEachIndexed { index, point ->
if (point == 9) limits.add(rowIndex to index)
}
}
return limits
}
fun findLocalMinimas(map: MutableList<List<Int>>): List<Pair<Int,Int>> {
val minimas = mutableListOf<Pair<Int,Int>>()
map.forEachIndexed { rowIndex, row ->
row.forEachIndexed { index, point ->
val possibleMinima = when (index) {
0 -> {
point < row[index+1]
}
row.size-1 -> {
point < row[index-1]
}
else -> {
(point < row[index-1]) && (point < row[index+1])
}
}
//println("Row $rowIndex, column $index: $possibleMinima")
if (!possibleMinima) {
return@forEachIndexed
}
val localMinima = when (rowIndex) {
0 -> {
point < map[rowIndex+1][index]
}
map.size-1 -> {
point < map[rowIndex-1][index]
}
else -> {
(point < map[rowIndex-1][index]) && (point < map[rowIndex+1][index])
}
}
if (localMinima) {
minimas.add(rowIndex to index)
}
}
}
return minimas
} | 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 6,650 | Advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/solutions/year2022/Day2.kt | neewrobert | 573,028,531 | false | {"Kotlin": 7605} | package solutions.year2022
import readInputLines
private val lose = mapOf(1 to 0, 2 to 1, 0 to 2)
private val won = mapOf(0 to 1, 1 to 2, 2 to 0)
fun main() {
fun getResultScore(elfCode: Int, villainCode: Int) =
3 * elfCode to when (elfCode) {
0 -> lose[villainCode]!!
1 -> villainCode
else -> won[villainCode]!!
} + 1
fun getResultScoreWithPlay(elfCode: Int, villainCode: Int) = when {
villainCode == elfCode -> 3
won[villainCode]!! == elfCode -> 6
else -> 0
} to (elfCode + 1)
fun calculateScore(input: List<String>, withPlay: Boolean = true): Int {
return input.sumOf { round ->
val (op, result) = round.split(" ").map { it[0].code }
val villainCode = op - 'A'.code
val elfCode = result - 'X'.code
val (resultScore, playScore) = if (withPlay) {
getResultScoreWithPlay(villainCode, elfCode)
} else {
getResultScore(elfCode, villainCode)
}
resultScore + playScore
}
}
fun part1(input: List<String>): Int {
return calculateScore(input)
}
fun part2(input: List<String>): Int {
return calculateScore(input, false)
}
val testInput = readInputLines("2022", "Day2_test")
val testResult = part1(testInput)
println(testResult)
check(testResult != 0)
check(testResult == 17)
val testResultPart2 = part2(testInput)
println(testResultPart2)
check(testResultPart2 != 0)
check(testResultPart2 == 27)
val input = readInputLines("2022", "Day2")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 7ecf680845af9d22ef1b9038c05d72724e3914f1 | 1,701 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | lassebe | 573,423,378 | false | {"Kotlin": 33148} | fun main() {
val scores = mapOf(
"Rock" to 1,
"Paper" to 2,
"Scissor" to 3,
"Win" to 6,
"Draw" to 3,
"Loss" to 0
)
fun part1(input: List<String>): Int = input.sumOf {
val plays = it.split(" ").map {
mapOf(
"A" to "Rock",
"X" to "Rock",
"B" to "Paper",
"Y" to "Paper",
"C" to "Scissor",
"Z" to "Scissor",
)[it]
}
val theyPlay = plays.first()
val youPlay = plays.last()
val resultScore = scores[if (theyPlay == "Rock" && youPlay == "Paper"
|| theyPlay == "Paper" && youPlay == "Scissor"
|| theyPlay == "Scissor" && youPlay == "Rock"
) {
"Win"
} else if (theyPlay == youPlay) {
"Draw"
} else {
"Loss"
}]!!
val playScore = scores[plays.last()!!]!!
resultScore + playScore
}
fun part2(input: List<String>): Int {
return input.map {
val plays = it.split(" ").map { decode ->
mapOf(
"A" to "Rock",
"X" to "Loss",
"B" to "Paper",
"Y" to "Draw",
"C" to "Scissor",
"Z" to "Win",
)[decode]!!
}
val theyPlay = plays.first()
val expectedResult = plays.last()
val youPlay = when (expectedResult) {
"Win" -> {
mapOf(
"Scissor" to "Rock",
"Rock" to "Paper",
"Paper" to "Scissor",
)[theyPlay]!!
}
"Loss" -> {
mapOf(
"Rock" to "Scissor",
"Paper" to "Rock",
"Scissor" to "Paper",
)[theyPlay]!!
}
else -> {
theyPlay
}
}
val resultScore = scores[expectedResult]!!
val playScore = scores[youPlay]!!
resultScore + playScore
}.sum()
}
val testInput = readInput("Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
check(part2(testInput) == 12)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c3157c2d66a098598a6b19fd3a2b18a6bae95f0c | 2,506 | advent_of_code_2022 | Apache License 2.0 |
src/Day03.kt | befrvnk | 574,229,637 | false | {"Kotlin": 15788} | fun Char.priority() = if (this.code <= 'Z'.code) this.code - 'A'.code + 27 else this.code - 'a'.code + 1
fun main() {
fun part1(input: List<String>): Int {
var totalPriority = 0
input.forEach { rucksack ->
val leftCompartment = rucksack.substring(0 until rucksack.length / 2)
val rightCompartment = rucksack.substring((rucksack.length / 2) until rucksack.length)
check(leftCompartment + rightCompartment == rucksack)
val doubleItems = mutableListOf<Char>()
leftCompartment.toCharArray().forEach { item ->
if (rightCompartment.contains(item)) {
doubleItems += item
}
}
doubleItems.distinct().forEach { item ->
totalPriority += item.priority()
}
}
return totalPriority
}
fun part2(input: List<String>): Int {
return input.chunked(3).map { (elf1, elf2, elf3) ->
elf1.first { it in elf2 && it in elf3 }
}.sumOf { it.priority() }
}
// 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 | 68e5dd5656c052d8c8a2ea9e03c62f4cd2438dd7 | 1,347 | aoc-2022-kotlin | Apache License 2.0 |
src/day04/Day04.kt | scottpeterson | 573,109,888 | false | {"Kotlin": 15611} | private class CleaningAssignment(start: Int, end: Int) {
val range = start..end
infix fun containsAll(other: CleaningAssignment) = range.intersect(other.range).size == other.range.count()
infix fun containsAny(other: CleaningAssignment) = range.intersect(other.range).isNotEmpty()
companion object {
fun parse(input: String) =
input.split("-").map { id -> id.toInt() }.let { (start, end) -> CleaningAssignment(start, end) }
}
}
private class CleaningAssignmentPair(val first: CleaningAssignment, val second: CleaningAssignment) {
fun hasFullOverlap() = first containsAll second || second containsAll first
fun hasAnyOverlap() = first containsAny second || second containsAny first
companion object {
fun parse(input: String) = input.split(",").map(CleaningAssignment::parse).let { (first, second) -> CleaningAssignmentPair(first, second) }
}
}
fun main() {
fun partOne(input: List<CleaningAssignmentPair>): Int = input.count { it.hasFullOverlap() }
fun partTwo(input: List<CleaningAssignmentPair>): Int = input.count { it.hasAnyOverlap() }
val input = readInput("day04/Day04_Input").map(CleaningAssignmentPair::parse)
println(partOne(input))
println(partTwo(input))
} | 0 | Kotlin | 0 | 0 | 0d86213c5e0cd5403349366d0f71e0c09588ca70 | 1,261 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | private fun ranges(): List<Pair<IntRange, IntRange>> {
return readInput("Day04").map { it.split(",") }.map { it[0].split("-") + it[1].split("-") }
.map { Pair(IntRange(it[0].toInt(), it[1].toInt()), IntRange(it[2].toInt(), it[3].toInt())) }
}
private fun part1(ranges: List<Pair<IntRange, IntRange>>): Int {
return ranges.count { it.first.contains(it.second) || it.second.contains(it.first) }
}
private fun part2(ranges: List<Pair<IntRange, IntRange>>): Int {
return ranges.count { it.first.intersect(it.second) }
}
fun main() {
println(part1(ranges()))
println(part2(ranges()))
}
| 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 612 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code-2022/src/main/kotlin/year_2022/Day14.kt | rudii1410 | 575,662,325 | false | {"Kotlin": 37749} | package year_2022
import util.Pos2
import util.Runner
import util.wrap
fun main() {
fun drawStone(map: List<MutableList<Char>>, h: Pos2, v: Pos2) {
for (i in h.x .. h.y) {
for (j in v.x .. v.y) map[i][j] = '#'
}
}
fun scanAndNormalizeMap(
input: List<String>
): Triple<List<MutableList<Char>>, Pos2, Pos2> {
val map: List<MutableList<Char>>
var rangeV = Pos2(Int.MAX_VALUE, Int.MIN_VALUE)
var rangeH = Pos2(Int.MAX_VALUE, Int.MIN_VALUE)
fun getBump(): Int = (rangeV.y + 2) - (500 - rangeH.x)
input.map { row ->
row.split(" -> ").windowed(2).map {
val start = it[0].split(",").map { s -> s.toInt() }
val end = it[1].split(",").map { e -> e.toInt() }
wrap(
listOf(start[0], end[0]).sorted().let { x -> Pos2(x[0], x[1]) },
listOf(start[1], end[1]).sorted().let { x -> Pos2(x[0], x[1]) }
) { hVal, vVal ->
rangeV = Pos2(rangeV.x.coerceAtMost(vVal.x), rangeV.y.coerceAtLeast(vVal.y))
rangeH = Pos2(rangeH.x.coerceAtMost(hVal.x), rangeH.y.coerceAtLeast(hVal.y))
listOf(vVal, hVal)
}
}
}.apply {
val newVRange = rangeV.y + 2
map = List(1 + newVRange) {
MutableList(1 + (2 * (newVRange))) { '.' }
}
drawStone(map, Pos2(newVRange, newVRange), Pos2(0, (2 * newVRange)))
}.map { row ->
row.map { hv ->
wrap(getBump(), rangeH.x) { a, b ->
listOf(hv[0], Pos2(a + hv[1].x - b, a + hv[1].y - b))
}
}
}.forEach { row ->
row.forEach { hv ->
drawStone(map, hv[0], hv[1])
}
}
return Triple(map, rangeV, Pos2(getBump(), getBump() + (rangeH.y - rangeH.x)))
}
fun printMap(map: List<MutableList<Char>>, it: Int, sandDrop: Int? = null) {
println("iteration : $it")
sandDrop?.let { map[0][it] = '+' }
map.forEach { r ->
r.forEach { print(if (it == '#') '█' else if (it == '.') ' ' else it) }
println()
}
println()
}
/* Part 1 */
fun part1(input: List<String>): Int {
var result = 0
val (map, vRange, hRange) = scanAndNormalizeMap(input)
val start = Pos2(0, 2 + vRange.y)
var sandPos = start
while (true) {
val bot = sandPos.getBottom()
if (bot.x > vRange.y) break
sandPos = if (map[bot.x][bot.y] == '.') {
bot
} else {
val left = bot.getLeft()
val right = bot.getRight()
if (left.y < hRange.x || right.y >= hRange.y) break
if (map[left.x][left.y] == '.') left
else if (map[right.x][right.y] == '.') right
else {
result++
map[sandPos.x][sandPos.y] = 'o'
start
}
}
}
return result
}
Runner.run(::part1, 24)
/* Part 2 */
fun part2(input: List<String>): Int {
var result = 0
val (map, vRange, _) = scanAndNormalizeMap(input)
val start = Pos2(0, 2 + vRange.y)
var sandPos = start
while (true) {
val bot = sandPos.getBottom()
sandPos = if (map[bot.x][bot.y] == '.') {
bot
} else {
val left = bot.getLeft()
val right = bot.getRight()
if (map[left.x][left.y] == '.') left
else if (map[right.x][right.y] == '.') right
else {
if (map[sandPos.x][sandPos.y] == 'o') break
result++
map[sandPos.x][sandPos.y] = 'o'
start
}
}
}
return result
}
Runner.run(::part2, 93)
}
| 1 | Kotlin | 0 | 0 | ab63e6cd53746e68713ddfffd65dd25408d5d488 | 4,073 | advent-of-code | Apache License 2.0 |
src/Year2022Day02.kt | zhangt2333 | 575,260,256 | false | {"Kotlin": 34993} | enum class HandShape {
ROCK, PAPER, SCISSOR;
companion object {
fun of(char: Char): HandShape = when (char) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSOR
else -> throw IllegalArgumentException()
}
fun of(myResult: Result, opponentHand: HandShape): HandShape = when (opponentHand) {
ROCK -> when (myResult) {
Result.LOST -> SCISSOR
Result.DRAW -> ROCK
Result.WON -> PAPER
}
PAPER -> when (myResult) {
Result.LOST -> ROCK
Result.DRAW -> PAPER
Result.WON -> SCISSOR
}
SCISSOR -> when (myResult) {
Result.LOST -> PAPER
Result.DRAW -> SCISSOR
Result.WON -> ROCK
}
}
}
fun score(): Int = when (this) {
ROCK -> 1
PAPER -> 2
SCISSOR -> 3
}
}
enum class Result {
LOST, DRAW, WON;
companion object {
fun of(char: Char): Result = when (char) {
'X' -> LOST
'Y' -> DRAW
'Z' -> WON
else -> throw IllegalArgumentException()
}
fun of(myHand: HandShape, opponentHand: HandShape): Result = when (myHand to opponentHand) {
HandShape.ROCK to HandShape.SCISSOR, HandShape.PAPER to HandShape.ROCK, HandShape.SCISSOR to HandShape.PAPER -> WON
HandShape.ROCK to HandShape.ROCK, HandShape.PAPER to HandShape.PAPER, HandShape.SCISSOR to HandShape.SCISSOR -> DRAW
HandShape.ROCK to HandShape.PAPER, HandShape.PAPER to HandShape.SCISSOR, HandShape.SCISSOR to HandShape.ROCK -> LOST
else -> throw java.lang.IllegalArgumentException()
}
}
fun score(): Int = when (this) {
LOST -> 0
DRAW -> 3
WON -> 6
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val opponentHand = HandShape.of(it[0])
val myHand = HandShape.of(it[2])
Result.of(myHand, opponentHand).score() + myHand.score()
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val opponentHand = HandShape.of(it[0])
val myResult = Result.of(it[2])
HandShape.of(myResult, opponentHand).score() + myResult.score()
}
}
val testLines = readLines(true)
check(part1(testLines) == 15)
check(part2(testLines) == 12)
val lines = readLines()
println(part1(lines))
println(part2(lines))
}
| 0 | Kotlin | 0 | 0 | cdba887c4df3a63c224d5a80073bcad12786ac71 | 2,621 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day2.kt | hughjdavey | 572,954,098 | false | {"Kotlin": 61752} | package days
import days.Day2.Outcome.LOSE
import days.Day2.Outcome.DRAW
import days.Day2.Outcome.WIN
import days.Day2.Shape.ROCK
import days.Day2.Shape.PAPER
import days.Day2.Shape.SCISSORS
class Day2 : Day(2) {
private val mappings = mapOf("A" to 1, "X" to 1, "B" to 2, "Y" to 2, "C" to 3, "Z" to 3)
private val game = inputList.map { it.split(" ").map { mappings[it]!! } }
override fun partOne(): Any {
return game.map { Game(Shape.values()[it[0] - 1], Shape.values()[it[1] - 1], null) }
.sumOf { it.getValue() }
}
override fun partTwo(): Any {
return game.map { Game(Shape.values()[it[0] - 1], null, Outcome.values()[it[1] - 1]) }
.sumOf { it.getValue() }
}
class Game(private val them: Shape, private val us: Shape?, private val outcome: Outcome?) {
fun getValue(): Int {
return if (us != null) getOutcome(them, us).value + us.value else getUs(them, outcome!!).value + outcome.value
}
private fun getOutcome(them: Shape, us: Shape): Outcome {
return if ((us == ROCK && them == SCISSORS) || (us == SCISSORS && them == PAPER) || (us == PAPER && them == ROCK)) WIN
else if (us == them) DRAW
else LOSE
}
private fun getUs(them: Shape, outcome: Outcome): Shape {
return when (outcome) {
LOSE -> when (them) { ROCK -> SCISSORS; PAPER -> ROCK; SCISSORS -> PAPER }
WIN -> when (them) { ROCK -> PAPER; PAPER -> SCISSORS; SCISSORS -> ROCK }
DRAW -> them
}
}
}
enum class Shape(val value: Int) { ROCK(1), PAPER(2), SCISSORS(3) }
enum class Outcome(val value: Int) { LOSE(0), DRAW(3), WIN(6) }
}
| 0 | Kotlin | 0 | 2 | 65014f2872e5eb84a15df8e80284e43795e4c700 | 1,749 | aoc-2022 | Creative Commons Zero v1.0 Universal |
kotlin/2018/src/main/kotlin/2018/Lib06.kt | nathanjent | 48,783,324 | false | {"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966} | package aoc.kt.y2018;
import kotlin.math.absoluteValue
/**
* Day 6.
*/
/** Part 1 */
fun processAreas1(input: String): String {
val coordinateMap = coordinateMap(input)
val (width, height) = borderDimensions(coordinateMap)
val distanceMap = distanceMap(coordinateMap, width, height)
val areaMap = mutableMapOf<Point, Int>()
for ((point, dMap) in distanceMap) {
val minCoordinate = dMap.minBy { it.value }
if (minCoordinate != null) {
val mapWithoutMin = dMap.minus(minCoordinate.key)
val nextMinCoordinate = mapWithoutMin.minBy { it.value }
areaMap.put(point, if (nextMinCoordinate == null || minCoordinate.value == nextMinCoordinate.value) {
-1
} else {
minCoordinate.key
})
}
}
// Remove areas touching border as these are infinite
val infiniteAreaCoordinates = areaMap.filter {
val pt = it.key
pt.x == 0 || pt.y == 0 || pt.x == width || pt.y == height
}
.map { it.value }
val finiteAreaCoordinates = areaMap.filter { point ->
!infiniteAreaCoordinates.any { infiniteCoordinate ->
point.value == infiniteCoordinate
}
}
val countMap = mutableMapOf<Int, Int>()
for ((_, id) in finiteAreaCoordinates) {
val count = countMap.getOrDefault(id, 0)
countMap.put(id, count + 1)
}
//var visualMap = ""
//for (y in 0..height + 1) {
// for (x in 0..width + 1) {
// if (x == 0) {
// visualMap += '\n'
// }
// val mapPoint = Point(x, y)
// visualMap += "|" + areaMap.get(mapPoint)?:""
// }
//}
val maxFiniteAreaSize = countMap.maxBy { it.value }?.value
return maxFiniteAreaSize
//visualMap
.toString()
}
/** Part 2 */
fun processAreas2(input: String, maxDistanceTotal: Int): String {
val coordinateMap = coordinateMap(input)
val (width, height) = borderDimensions(coordinateMap)
val distanceMap = distanceMap(coordinateMap, width, height)
val areas = mutableListOf<Point>()
for ((point, dMap) in distanceMap) {
if (dMap.values.sum() < maxDistanceTotal) {
areas.add(point)
}
}
return areas
.count()
.toString()
}
fun manhattanDistance(p1: Int, p2: Int, q1: Int, q2: Int): Int {
return (p1 - q1).absoluteValue + (p2 - q2).absoluteValue
}
fun manhattanDistance(p1: Point, p2: Point): Int {
return manhattanDistance(p1.x, p1.y, p2.x, p2.y)
}
private fun coordinateMap(input: String): Map<Int, Point> {
return input.lines()
.filter { !it.isEmpty() }
.mapIndexed { i, line ->
val (xStr, yStr) = line.split(", ")
Pair(i, Point(xStr.toInt(), yStr.toInt()))
}
.toMap()
}
private fun borderDimensions(coordinateMap: Map<Int, Point>): Pair<Int, Int> {
return coordinateMap.values.fold(Pair(-1, -1), { acc, n ->
Pair(if (n.x > acc.first) { n.x } else { acc.first },
if (n.y > acc.second) { n.y } else { acc.second })
})
}
private fun distanceMap(coordinateMap: Map<Int, Point>, width: Int, height: Int): Map<Point, Map<Int, Int>> {
val distanceMap = mutableMapOf<Point, MutableMap<Int, Int>>()
for (y in 0..height + 1) {
for (x in 0..width + 1) {
val mapPoint = Point(x, y)
for ((id, coordinatePoint) in coordinateMap) {
val distance = manhattanDistance(coordinatePoint, mapPoint)
val distances = distanceMap.getOrDefault(mapPoint, mutableMapOf())
distances.put(id, distance)
distanceMap.put(mapPoint, distances)
}
}
}
return distanceMap
}
| 0 | Rust | 0 | 0 | 7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf | 3,768 | adventofcode | MIT License |
kotlin/src/katas/kotlin/leetcode/jump_game_ii/JumpGame.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.jump_game_ii
import datsok.shouldEqual
import org.junit.jupiter.api.Test
//
// https://leetcode.com/problems/jump-game-ii ✅
//
// Given an array of non-negative integers, you are initially positioned at the first index of the array.
// Each element in the array represents your maximum jump length at that position.
// Your goal is to reach the last index in the minimum number of jumps.
// Note: You can assume that you can always reach the last index.
// Constraints:
// 1 <= nums.length <= 3 * 10^4
// 0 <= nums[i] <= 10^5
//
// Example:
// Input: [2,3,1,1,4]
// Output: 2
// Explanation: The minimum number of jumps to reach the last index is 2.
// Jump 1 step from index 0 to 1, then 3 steps to the last index.
//
// Example 2:
// Input: nums = [2,3,0,1,4]
// Output: 2
//
fun jump(nums: IntArray): Int {
return if (nums.size <= 1) 0
else findMinJumps(nums.toList()).size
}
private fun findMinJumps(nums: List<Int>): List<Int> =
generateSequence(seed = 0) { i ->
if (i + nums[i] >= nums.lastIndex) null
else {
val nextIndices = (i + 1)..(i + nums[i])
nextIndices.maxByOrNull { it: Int -> it + nums[it] }!!
}
}.toList()
fun jump_(nums: IntArray): Int {
require(nums.all { it > 0 })
if (nums.size <= 1) return 0
var jumpCount = 1
var reachableIndices = 1..nums[0]
while (nums.lastIndex !in reachableIndices) {
var maxSteps = Int.MIN_VALUE
reachableIndices.forEach { index ->
val steps = nums[index]
if (steps >= maxSteps) {
maxSteps = steps
reachableIndices = (index + 1)..(index + steps)
}
}
jumpCount++
}
return jumpCount
}
class JumpGameTests {
@Test fun `some examples`() {
findMinJumps(listOf(0)) shouldEqual listOf(0)
findMinJumps(listOf(1)) shouldEqual listOf(0)
findMinJumps(listOf(1, 1, 1)) shouldEqual listOf(0, 1)
findMinJumps(listOf(2, 3, 1, 1, 4)) shouldEqual listOf(0, 1)
findMinJumps(listOf(2, 3, 0, 1, 4)) shouldEqual listOf(0, 1)
findMinJumps(listOf(2, 3, 3, 1, 4)) shouldEqual listOf(0, 2)
findMinJumps(listOf(2, 3, 3, 1, 4, 0)) shouldEqual listOf(0, 2)
findMinJumps(listOf(2, 3, 3, 1, 4, 0, 0)) shouldEqual listOf(0, 2, 4)
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,371 | katas | The Unlicense |
src/Lesson6Sorting/MaxProductOfThree.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} |
import java.util.Arrays
/**
* 100/100
* @param A
* @return
*/
fun solution(A: IntArray): Int {
val N = A.size
Arrays.sort(A)
/**
* When we sort an array there are two possible options for the largest product
* 1) The largest (the last) three elements
* 2) Combination of two smallest and the largest elements
* Logic of (1): Obvious
* Logic of (2): A pair of negatives multiplied returns a positive, which in combination with
* the largest positive element of the array can give the max outcome.
* Therefore we return the max of options (1) and (2)
*/
return Math.max(A[0] * A[1] * A[N - 1], A[N - 1] * A[N - 2] * A[N - 3])
}
/**
* A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).
*
* For example, array A such that:
*
* A[0] = -3
* A[1] = 1
* A[2] = 2
* A[3] = -2
* A[4] = 5
* A[5] = 6
* contains the following example triplets:
*
* (0, 1, 2), product is −3 * 1 * 2 = −6
* (1, 2, 4), product is 1 * 2 * 5 = 10
* (2, 4, 5), product is 2 * 5 * 6 = 60
* Your goal is to find the maximal product of any triplet.
*
* Write a function:
*
* class Solution { public int solution(int[] A); }
*
* that, given a non-empty array A, returns the value of the maximal product of any triplet.
*
* For example, given array A such that:
*
* A[0] = -3
* A[1] = 1
* A[2] = 2
* A[3] = -2
* A[4] = 5
* A[5] = 6
* the function should return 60, as the product of triplet (2, 4, 5) is maximal.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [3..100,000];
* each element of array A is an integer within the range [−1,000..1,000].
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 1,786 | Codility-Kotlin | Apache License 2.0 |
src/Day02.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | fun main() {
fun String.toNumber(): Int = when (this) {
"X" -> 1
"Y" -> 2
"Z" -> 3
"A" -> 1
"B" -> 2
"C" -> 3
else -> 0
}
fun win(players: List<Int>): Int = ((players[1] - players[0] + 4) % 3) * 3
fun calcMyPrice(players: List<Int>): Int = win(players) + players[1]
fun part1(input: List<String>): Int = input.sumOf { calcMyPrice(it.split(" ").map { it.toNumber() }) }
fun calcWinningsWithHelp(players: List<Int>): Int = (players[0] + players[1]) % 3 + 1 + (players[1] - 1) * 3
fun part2(input: List<String>): Int = input.sumOf { calcWinningsWithHelp(it.split(" ").map { it.toNumber() }) }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 955 | advent-of-code-kotlin-2022 | Apache License 2.0 |
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day18Part2.kt | Guruth | 328,467,380 | false | {"Kotlin": 188298, "Rust": 13289, "Elixir": 1833} | package sh.weller.adventofcode.twentytwenty
fun List<String>.day18Part2(): Long =
this.map { it.split(" ").filter { it.isNotBlank() } }
.map { it.calculateAdvanced() }
.map { it.toLong() }
.sum()
private fun List<String>.calculateAdvanced(): String {
when {
this.size == 1 -> {
return this[0]
}
this.size == 3 -> {
return calculateNumbers(this[0], this[1], this[2])
}
this[0].startsWith("(") -> {
val subExpression = this.getSubExpression()
val subExpressionResult = subExpression.calculateAdvanced()
val restExpression = this.drop(this.getSubExpression().size)
return (listOf(subExpressionResult) + restExpression).calculateAdvanced()
}
this[2].startsWith("(") -> {
val subExpression = this.drop(2).getSubExpression()
val subExpressionResult = subExpression.calculateAdvanced()
val restExpression = this.drop(subExpression.size + 2)
return (listOf(this[0], this[1], subExpressionResult) + restExpression).calculateAdvanced()
}
else -> {
return when {
this[1] == "+" -> {
val tmpResult = calculateNumbers(this[0], this[1], this[2])
(listOf(tmpResult) + this.drop(3)).calculateAdvanced()
}
else -> {
(listOf(this[0], this[1]) + this.drop(2).calculateAdvanced()).calculateAdvanced()
}
}
}
}
}
private fun List<String>.getSubExpression(): List<String> {
val closingIndex = this.indexOfClosingParenthesis()
val firstValue = this[0].drop(1)
val lastValue = this[closingIndex].dropLast(1)
return listOf(firstValue) + this.subList(1, closingIndex) + listOf(lastValue)
}
private fun List<String>.indexOfClosingParenthesis(): Int {
var index = 0
var openParenthesis = 0
do {
if (this[index].contains("(")) {
openParenthesis += this[index].count { it == '(' }
} else if (this[index].contains(")")) {
openParenthesis -= this[index].count { it == ')' }
}
index++
} while (openParenthesis != 0)
return index - 1
}
private fun calculateNumbers(firstValue: String, operator: String, secondValue: String): String =
when (operator) {
"+" -> firstValue.toLong() + secondValue.toLong()
"*" -> firstValue.toLong() * secondValue.toLong()
else -> throw IllegalArgumentException("Unknown Operator")
}.toString()
| 0 | Kotlin | 0 | 0 | 69ac07025ce520cdf285b0faa5131ee5962bd69b | 2,607 | AdventOfCode | MIT License |
src/Day25.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | import kotlin.math.pow
object Day25 {
const val EXPECTED_PART1_CHECK_ANSWER = "2=-1=0"
const val EXPECTED_PART2_CHECK_ANSWER = 1
}
fun main() {
fun fivesValueForDigit(char: Char) = when (char) {
'2' -> 2
'1' -> 1
'0' -> 0
'-' -> -1
'=' -> -2
else -> error("Unknown char $char")
}
fun digitForFivesValue(value: Long) = when (value) {
0L -> '0'
1L -> '1'
2L -> '2'
3L -> '='
4L -> '-'
else -> error("Unsupported value $value")
}
fun convertFivePowerNumberToDecimalNumber(fivePowerNumber: String): Long {
return fivePowerNumber.reversed().foldIndexed(0L) { idx, total, curFive ->
total + fivesValueForDigit(curFive) * (5.toDouble().pow(idx).toLong())
}
}
fun convertDecimalNumberToFivePowerNumber(decimalNumber: Long): String {
if (decimalNumber == 0L) return "0"
return generateSequence(decimalNumber to "") { (rest, totalNumber) ->
val low = rest % 5
(rest + 2) / 5 to digitForFivesValue(low) + totalNumber
}.first { it.first <= 0L }.second
}
fun part1(input: List<String>): String {
val sumInDecimal = input.sumOf { convertFivePowerNumberToDecimalNumber(it) }
val snafuValue = convertDecimalNumberToFivePowerNumber(sumInDecimal)
return snafuValue
}
fun part2(input: List<String>): Int {
return 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
val input = readInput("Day25")
val part1TestResult = part1(testInput)
println("Part 1 test: $part1TestResult")
check(part1TestResult == Day25.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
println(part1(input))
val part2TestResult = part2(testInput)
println("Part 2 test: $part2TestResult")
check(part2TestResult == Day25.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 2,022 | aoc-2022-in-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.