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/Day02.kt
Yasenia
575,276,480
false
{"Kotlin": 15232}
fun main() { fun part1(input: List<String>): Int { var totalScore = 0 for (line in input) { val columns = line.split(" ") val opponentValue = "ABC".indexOf(columns[0]) val myValue = "XYZ".indexOf(columns[1]) val shapeScore = listOf(1, 2, 3)[myValue] val outcomeScore = listOf( listOf(3, 0, 6), listOf(6, 3, 0), listOf(0, 6, 3), )[myValue][opponentValue] totalScore += shapeScore + outcomeScore } return totalScore } fun part2(input: List<String>): Int { var totalScore = 0 for (line in input) { val columns = line.split(" ") val opponentValue = "ABC".indexOf(columns[0]) val outcome = "XYZ".indexOf(columns[1]) val shapeScore = listOf( listOf(3, 1, 2), listOf(1, 2, 3), listOf(2, 3, 1), )[opponentValue][outcome] val outcomeScore = listOf(0, 3, 6)[outcome] totalScore += shapeScore + outcomeScore } return totalScore } 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
9300236fa8697530a3c234e9cb39acfb81f913ba
1,367
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/TotalCost.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 java.util.PriorityQueue import kotlin.math.max /** * 2462. Total Cost to Hire K Workers * @see <a href="https://leetcode.com/problems/total-cost-to-hire-k-workers/">Source</a> */ fun interface TotalCost { operator fun invoke(costs: IntArray, k: Int, candidates: Int): Long } /** * Approach 1: 2 Priority Queues */ class TotalCostPriorityQueues : TotalCost { override operator fun invoke(costs: IntArray, k: Int, candidates: Int): Long { val headWorkers: PriorityQueue<Int> = PriorityQueue() val tailWorkers: PriorityQueue<Int> = PriorityQueue() // headWorkers stores the first k workers. // tailWorkers stores at most last k workers without any workers from the first k workers. for (i in 0 until candidates) { headWorkers.add(costs[i]) } for (i in max(candidates, costs.size - candidates) until costs.size) { tailWorkers.add(costs[i]) } var answer: Long = 0 var nextHead = candidates var nextTail: Int = costs.size - 1 - candidates for (i in 0 until k) { if (tailWorkers.isEmpty() || headWorkers.isNotEmpty() && headWorkers.peek() <= tailWorkers.peek()) { answer += headWorkers.poll() // Only refill the queue if there are workers outside the two queues. if (nextHead <= nextTail) { headWorkers.add(costs[nextHead]) nextHead++ } } else { answer += tailWorkers.poll() // Only refill the queue if there are workers outside the two queues. if (nextHead <= nextTail) { tailWorkers.add(costs[nextTail]) nextTail-- } } } return answer } } /** * Approach 2: 1 Priority Queue */ class TotalCostPriorityQueue : TotalCost { override operator fun invoke(costs: IntArray, k: Int, candidates: Int): Long { // The worker with the lowest cost has the highest priority, if two players has the // same cost, break the tie by their indices (0 or 1). val pq = PriorityQueue( java.util.Comparator { a: IntArray, b: IntArray -> if (a[0] == b[0]) { return@Comparator a[1] - b[1] } a[0] - b[0] }, ) // Add the first k workers with section id of 0 and // the last k workers with section id of 1 (without duplication) to pq. for (i in 0 until candidates) { pq.offer(intArrayOf(costs[i], 0)) } for (i in max(candidates, costs.size - candidates) until costs.size) { pq.offer(intArrayOf(costs[i], 1)) } var answer: Long = 0 var nextHead = candidates var nextTail: Int = costs.size - 1 - candidates for (i in 0 until k) { val curWorker = pq.poll() val curCost = curWorker[0] val curSectionId = curWorker[1] answer += curCost.toLong() // Only refill pq if there are workers outside. if (nextHead <= nextTail) { if (curSectionId == 0) { pq.offer(intArrayOf(costs[nextHead], 0)) nextHead++ } else { pq.offer(intArrayOf(costs[nextTail], 1)) nextTail-- } } } return answer } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,168
kotlab
Apache License 2.0
src/main/kotlin/com/marcdenning/adventofcode/day11/Day11a.kt
marcdenning
317,730,735
false
{"Kotlin": 87536}
package com.marcdenning.adventofcode.day11 import java.io.File import java.lang.Integer.max import java.lang.Integer.min private const val FLOOR = '.' private const val EMPTY = 'L' private const val OCCUPIED = '#' fun main(args: Array<String>) { val floorPlanMatrix = File(args[0]).readLines().map { it.toCharArray() }.toTypedArray() println("Number of occupied seats: ${countSeats(findSteadyFloorPlan(floorPlanMatrix), OCCUPIED)}") } fun fillSeats(floorPlanMatrix: Array<CharArray>): Array<CharArray> { val outputFloorPlanMatrix = floorPlanMatrix.map { it.copyOf() }.toTypedArray() for ((rowIndex, row) in floorPlanMatrix.withIndex()) { for ((columnIndex, seat) in row.withIndex()) { if (seat == EMPTY && countSeats(getAdjascentSeats(floorPlanMatrix, rowIndex, columnIndex), OCCUPIED) == 0) { outputFloorPlanMatrix[rowIndex][columnIndex] = OCCUPIED } } } return outputFloorPlanMatrix } fun emptySeats(floorPlanMatrix: Array<CharArray>): Array<CharArray> { val outputFloorPlanMatrix = floorPlanMatrix.map { it.copyOf() }.toTypedArray() for ((rowIndex, row) in floorPlanMatrix.withIndex()) { for ((columnIndex, seat) in row.withIndex()) { if (seat == OCCUPIED && countSeats(getAdjascentSeats(floorPlanMatrix, rowIndex, columnIndex), OCCUPIED) >= 4) { outputFloorPlanMatrix[rowIndex][columnIndex] = EMPTY } } } return outputFloorPlanMatrix } fun getAdjascentSeats(floorPlanMatrix: Array<CharArray>, rowIndex: Int, columnIndex: Int): Array<CharArray> { val startRow = max(0, rowIndex - 1) val startColumn = max(0, columnIndex - 1) val endRow = min(floorPlanMatrix.size - 1, rowIndex + 1) val endColumn = min(floorPlanMatrix[0].size - 1, columnIndex + 1) val adjascentSeatMatrix = floorPlanMatrix.copyOfRange(startRow, endRow + 1) .map { row -> row.copyOfRange(startColumn, endColumn + 1) } .toTypedArray() adjascentSeatMatrix[rowIndex - startRow][columnIndex - startColumn] = ' ' return adjascentSeatMatrix } fun findSteadyFloorPlan(floorPlanMatrix: Array<CharArray>): Array<CharArray> { var lastFloorPlan = Array(floorPlanMatrix.size) { CharArray(floorPlanMatrix[0].size) } var currentFloorPlan = floorPlanMatrix.copyOf() var isFillTurn = true while (!lastFloorPlan.contentDeepEquals(currentFloorPlan)) { lastFloorPlan = currentFloorPlan if (isFillTurn) { currentFloorPlan = fillSeats(currentFloorPlan) isFillTurn = false } else { currentFloorPlan = emptySeats(currentFloorPlan) isFillTurn = true } } return currentFloorPlan } fun countSeats(floorPlanMatrix: Array<CharArray>, seatType: Char): Int = floorPlanMatrix.map { row -> row.map { seat -> if (seat == seatType) 1 else 0 }.sum() }.sum()
0
Kotlin
0
0
b227acb3876726e5eed3dcdbf6c73475cc86cbc1
2,909
advent-of-code-2020
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem106/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem106 import com.hj.leetcode.kotlin.common.model.TreeNode /** * LeetCode page: [106. Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the size of inorder; */ fun buildTree(inorder: IntArray, postorder: IntArray): TreeNode? { val inorderValueToIndex = inorder.valueToIndex() require(inorderValueToIndex.size == inorder.size) { "All node values should be distinct by problem constraints." } return buildTree(SubArray(inorder), inorderValueToIndex, SubArray(postorder)) } private fun IntArray.valueToIndex(): Map<Int, Int> { return foldIndexed(hashMapOf()) { index, acc, i -> acc[i] = index acc } } private class SubArray( val fullArray: IntArray, val from: Int = 0, val to: Int = fullArray.lastIndex ) { val size = to - from + 1 } private fun buildTree( inorder: SubArray, inorderValueToIndex: Map<Int, Int>, postorder: SubArray ): TreeNode? { val isEmpty = with(inorder) { from > to } if (isEmpty) return null val rootValue = with(postorder) { fullArray[to] } val leftSize = checkNotNull(inorderValueToIndex[rootValue]) - inorder.from val rightSize = inorder.size - leftSize - 1 return TreeNode(rootValue).apply { left = buildTree( with(inorder) { SubArray(fullArray, from, from + leftSize - 1) }, inorderValueToIndex, with(postorder) { SubArray(fullArray, from, from + leftSize - 1) } ) right = buildTree( with(inorder) { SubArray(fullArray, to - rightSize + 1, to) }, inorderValueToIndex, with(postorder) { SubArray(fullArray, to - rightSize , to -1) } ) } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,080
hj-leetcode-kotlin
Apache License 2.0
src/Day23.kt
er453r
572,440,270
false
{"Kotlin": 69456}
fun main() { val directionsToConsider = arrayOf( arrayOf( Vector2d.UP, Vector2d.UP + Vector2d.LEFT, Vector2d.UP + Vector2d.RIGHT, ), arrayOf( Vector2d.DOWN, Vector2d.DOWN + Vector2d.LEFT, Vector2d.DOWN + Vector2d.RIGHT, ), arrayOf( Vector2d.LEFT, Vector2d.LEFT + Vector2d.UP, Vector2d.LEFT + Vector2d.DOWN, ), arrayOf( Vector2d.RIGHT, Vector2d.RIGHT + Vector2d.UP, Vector2d.RIGHT + Vector2d.DOWN, ), ) fun diffuseElves(elves: MutableSet<Vector2d>, stopAfterRound: Int = -1): Int { var rounds = 1 var directionsToConsiderIndex = 0 while (true) { val moveProposals = mutableMapOf<Vector2d, Vector2d>() val moveProposalsDuplicates = mutableSetOf<Vector2d>() val moveProposalsElves = mutableSetOf<Vector2d>() // first half for (elf in elves) { val neighbours = elf.neighbours8().intersect(elves) if (neighbours.isEmpty()) continue for (n in directionsToConsider.indices) { val directionToConsiderIndex = (directionsToConsiderIndex + n) % directionsToConsider.size val directionNeighbours = directionsToConsider[directionToConsiderIndex].map { elf + it }.toSet() if (directionNeighbours.intersect(neighbours).isEmpty()) { val moveProposal = directionNeighbours.first() if (moveProposal in moveProposalsDuplicates) break if (moveProposal in moveProposals) { moveProposalsDuplicates += moveProposal moveProposalsElves -= moveProposals[moveProposal]!! moveProposals -= moveProposal break } moveProposals[moveProposal] = elf moveProposalsElves += elf break } } } if (stopAfterRound == -1 && moveProposals.isEmpty()) break // second half elves -= moveProposalsElves // elves -= moveProposals.values.toSet() elves += moveProposals.keys directionsToConsiderIndex = (directionsToConsiderIndex + 1) % directionsToConsider.size if (rounds++ == stopAfterRound) break } return rounds } fun part1(input: List<String>): Int { val elves = Grid(input.map { line -> line.toCharArray().toList() }).data.flatten().filter { it.value == '#' }.map { it.position }.toMutableSet() diffuseElves(elves, stopAfterRound = 10) val minX = elves.minOf { it.x } val maxX = elves.maxOf { it.x } val minY = elves.minOf { it.y } val maxY = elves.maxOf { it.y } return (maxX - minX + 1) * (maxY - minY + 1) - elves.size } fun part2(input: List<String>): Int { val elves = Grid(input.map { line -> line.toCharArray().toList() }).data.flatten().filter { it.value == '#' }.map { it.position }.toMutableSet() return diffuseElves(elves) } test( day = 23, testTarget1 = 110, testTarget2 = 20, part1 = ::part1, part2 = ::part2, ) }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
3,566
aoc2022
Apache License 2.0
2022/kotlin/app/src/main/kotlin/day03/App.kt
jghoman
726,228,039
false
{"Kotlin": 15309, "Rust": 14555, "Scala": 1804, "Shell": 737}
package day03 fun readFileUsingGetResource(fileName: String): String = ClassLoader.getSystemClassLoader().getResource(fileName).readText(Charsets.UTF_8) fun day03Part1(lines: String): Int { return lines .split("\n") .map { l -> Triple(l, l.substring(0, l.length / 2), l.substring(l.length / 2)) } .map { Triple(it.first, it.second.toList(), it.third.toList()) } .map { Triple(it.first, HashSet(it.second), HashSet(it.third)) } .map { Pair(it.first, it.second.intersect(it.third)) } .map { Pair(it.first, it.second.first())} .map { Triple(it.first, it.second, if(it.second.isLowerCase()) it.second.code - 96 else it.second.code - 38)} .map { it.third } .sum() //.forEach { println(it) } // 7831 } fun day03Part2(lines: String):Int { return lines.split("\n") .map { it -> it.toSet() } .chunked(3) .map { it.get(0).intersect(it.get(1)).intersect(it.get(2))} .map { it.first() } .map { if(it.isLowerCase()) it.code - 96 else it.code - 38} .sum() //.forEach { println(it) } // 2683 } fun main() { val input = readFileUsingGetResource("day-3-input.txt"); //val result = day03Part1(input) //println("Answer = $result") val result2 = day03Part2(input) println("Answer = $result2") }
0
Kotlin
0
0
2eb856af5d696505742f7c77e6292bb83a6c126c
1,436
aoc
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2018/Day04.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 4 - Repose Record * * Problem Description: http://adventofcode.com/2018/day/4 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day4/ */ package com.ginsberg.advent2018 class Day04(rawInput: List<String>) { private val sleepMinutesPerGuard: Map<Int, List<Int>> = parseInput(rawInput) fun solvePart1(): Int = sleepMinutesPerGuard .maxBy { it.value.size }!! .run { key * value.mostFrequent()!! } fun solvePart2(): Int = sleepMinutesPerGuard.flatMap { entry -> entry.value.map { minute -> entry.key to minute // Guard to Minute } } .mostFrequent()!! // Which guard slept the most in a minute? .run { first * second } private fun parseInput(input: List<String>): Map<Int, List<Int>> { val sleeps = mutableMapOf<Int, List<Int>>() var guard = 0 var sleepStart = 0 input.sorted().forEach { row -> when { row.contains("Guard") -> guard = guardPattern.single(row).toInt() row.contains("asleep") -> sleepStart = timePattern.single(row).toInt() else -> { val sleepMins = (sleepStart until timePattern.single(row).toInt()).toList() sleeps.merge(guard, sleepMins) { a, b -> a + b } } } } return sleeps } companion object { private val guardPattern = """^.+ #(\d+) .+$""".toRegex() private val timePattern = """^\[.+:(\d\d)] .+$""".toRegex() } private fun Regex.single(from: String): String = this.find(from)!!.destructured.component1() }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
1,785
advent-2018-kotlin
MIT License
src/Day02.kt
strindberg
572,685,170
false
{"Kotlin": 15804}
import Result.DRAW import Result.LOSS import Result.WIN sealed interface Move { val points: Int fun beats(other: Move): Result fun askedFor(result: Result): Move } enum class Result { WIN, DRAW, LOSS } object Rock : Move { override val points = 1 override fun beats(other: Move) = when (other) { is Scissor -> WIN is Rock -> DRAW else -> LOSS } override fun askedFor(result: Result) = when (result) { WIN -> Paper DRAW -> Rock LOSS -> Scissor } } object Paper : Move { override val points = 2 override fun beats(other: Move) = when (other) { is Rock -> WIN is Paper -> DRAW else -> LOSS } override fun askedFor(result: Result) = when (result) { WIN -> Scissor DRAW -> Paper LOSS -> Rock } } object Scissor : Move { override val points = 3 override fun beats(other: Move) = when (other) { is Paper -> WIN is Scissor -> DRAW else -> LOSS } override fun askedFor(result: Result) = when (result) { WIN -> Rock DRAW -> Scissor LOSS -> Paper } } fun getFirstMove(first: Char) = if (first == 'A') Rock else if (first == 'B') Paper else if (first == 'C') Scissor else throw RuntimeException() fun getSecondMove(b: Char) = if (b == 'X') Rock else if (b == 'Y') Paper else if (b == 'Z') Scissor else throw RuntimeException() fun getSecondResult(second: Char) = if (second == 'X') LOSS else if (second == 'Y') DRAW else if (second == 'Z') WIN else throw RuntimeException() fun main() { fun part1(input: List<String>): Int = input.sumOf { line -> val first = getFirstMove(line[0]) val second = getSecondMove(line[2]) when (second.beats(first)) { WIN -> second.points + 6 DRAW -> second.points + 3 LOSS -> second.points } } fun part2(input: List<String>): Int = input.sumOf { line -> val first = getFirstMove(line[0]) val result = getSecondResult(line[2]) val second = first.askedFor(result) when (result) { WIN -> second.points + 6 DRAW -> second.points + 3 LOSS -> second.points } } val input = readInput("Day02") val part1 = part1(input) println(part1) check(part1 == 8933) val part2 = part2(input) println(part2) check(part2 == 11998) }
0
Kotlin
0
0
c5d26b5bdc320ca2aeb39eba8c776fcfc50ea6c8
2,899
aoc-2022
Apache License 2.0
2021/src/main/kotlin/alternative/Day20.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
package alternative class Day20(val input: List<String>) { private val algorithm = input[0].map { if (it == '#') '1' else '0' }.toTypedArray() private val originalImage = input[1].split("\n").map { row -> row.map { if (it == '#') '1' else '0' }.toTypedArray() }.toTypedArray() private fun enhance(steps: Int): Int { val processed = (0 until steps).fold(originalImage) { image, step -> val outside = when (algorithm.first() == '1') { true -> if (step % 2 == 0) algorithm.last() else algorithm.first() false -> '0' } (-1..image.size).map { y -> (-1..image.first().size).map { x -> (-1..1).flatMap { dy -> (-1..1).map { dx -> dy to dx } } .map { (dy, dx) -> y + dy to x + dx } .joinToString("") { (y, x) -> (image.getOrNull(y)?.getOrNull(x) ?: outside).toString() } .toInt(2).let { algorithm[it] } }.toTypedArray() }.toTypedArray() } return processed.sumOf { row -> row.count { it == '1' } } } fun solve1(): Int { return enhance(2) } fun solve2(): Int { return enhance(50) } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
1,268
adventofcode-2021-2025
MIT License
src/2021-Day05.kt
frozbiz
573,457,870
false
{"Kotlin": 124645}
import kotlin.math.absoluteValue fun main() { fun part1(input: List<String>): Int { val board = Grid() for (line in input) { val (pt1, pt2) = line.split("->").map { Point.fromString(it) } when (pt1.relationshipTo(pt2)) { Point.Relationship.EQUAL -> ++board[pt1] Point.Relationship.VERTICAL, Point.Relationship.HORIZONTAL -> { (pt1 to pt2).forEach { ++board[it] } } else -> {} } } return board.allPoints().count { it.second > 1 } } fun part2(input: List<String>): Int { val board = Grid() for (line in input) { val (pt1, pt2) = line.split("->").map { Point.fromString(it) } (pt1 to pt2).forEach { ++board[it] } } return board.allPoints().count { it.second > 1 } } // test if implementation meets criteria from the description, like: val testInput = listOf( "0,9 -> 5,9\n", "8,0 -> 0,8\n", "9,4 -> 3,4\n", "2,2 -> 2,1\n", "7,0 -> 7,4\n", "6,4 -> 2,0\n", "0,9 -> 2,9\n", "3,4 -> 1,4\n", "0,0 -> 8,8\n", "5,5 -> 8,2\n" ) check(part1(testInput) == 5) check(part2(testInput) == 12) val input = readInput("2021-day5") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388
1,416
2022-aoc-kotlin
Apache License 2.0
src/main/kotlin/year2021/day-08.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2021 import lib.aoc.Day import lib.aoc.Part fun main() { Day(8, 2021, PartA8(), PartB8()).run() } open class PartA8 : Part() { data class Entry(val signal: List<String>, val output: List<String>) { companion object { fun parse(line: String): Entry { val (signalText, outputText) = line.split(" | ") return Entry(signalText.split(" "), outputText.split(" ")) } } } protected lateinit var entries: List<Entry> override fun parse(text: String) { entries = text.split("\n").map(Entry::parse) } override fun compute(): String { return entries.sumOf { entry -> entry.output.count { it.length in listOf(2, 3, 4, 7) } }.toString() } override val exampleAnswer: String get() = "26" override val customExampleData: String? get() = """ be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce """.trimIndent() } class PartB8 : PartA8() { override fun compute(): String { return entries.sumOf { entry -> val (signal, output) = entry val sortedSignal = signal.map { it.toCharArray().sorted().joinToString("") } val sortedOutput = output.map { it.toCharArray().sorted().joinToString("") } val tmp = mutableMapOf<String, String>() findUniques(sortedSignal, tmp) find6(sortedSignal, tmp) find0(sortedSignal, tmp) find9(sortedSignal, tmp) find5(sortedSignal, tmp) find3(sortedSignal, tmp) find2(sortedSignal, tmp) val code = tmp.map { (k, v) -> v to k }.associate { it } sortedOutput.map { code[it] }.joinToString("").toInt() }.toString() } private fun findUniques(signal: List<String>, tmp: MutableMap<String, String>) { val lengthMap = mapOf(2 to "1", 3 to "7", 4 to "4", 7 to "8") for (word in signal) { if (word.length in lengthMap) { tmp[lengthMap.getValue(word.length)] = word } } } private fun find6(signal: List<String>, tmp: MutableMap<String, String>) { for (word in signal) { if (word.length == 6 && tmp.getValue("1").any { it !in word }) { tmp["6"] = word break } } } private fun find0(signal: List<String>, tmp: MutableMap<String, String>) { for (word in signal) { if (word.length == 6 && tmp.getValue("4").any { it !in word } && word !in tmp.values) { tmp["0"] = word break } } } private fun find9(signal: List<String>, tmp: MutableMap<String, String>) { for (word in signal) { if (word.length == 6 && word !in tmp.values) { tmp["9"] = word break } } } private fun find5(signal: List<String>, tmp: MutableMap<String, String>) { for (word in signal) { if (word.length == 5 && word.all { it in tmp.getValue("6") }) { tmp["5"] = word break } } } private fun find3(signal: List<String>, tmp: MutableMap<String, String>) { for (word in signal) { if (word.length == 5 && word.all { it in tmp.getValue("9") } && word !in tmp.values) { tmp["3"] = word break } } } private fun find2(signal: List<String>, tmp: MutableMap<String, String>) { for (word in signal) { if (word.length == 5 && word !in tmp.values) { tmp["2"] = word break } } } override val exampleAnswer: String get() = "61229" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
4,855
Advent-Of-Code-Kotlin
MIT License
src/Day04.kt
freszu
573,122,040
false
{"Kotlin": 32507}
fun main() { fun part1(input: List<String>) = input.map { it.split('-', ',') } .map { it.map(String::toInt) } .map { (range1start, range1end, range2start, range2end) -> val range1 = range1start..range1end val range2 = range2start..range2end range1.contains(range2) || range2.contains(range1) } .count(true::equals) fun part2(input: List<String>) = input.map { it.split('-', ',') } .map { it.map(String::toInt) } .map { (range1start, range1end, range2start, range2end) -> val range1 = range1start..range1end val range2 = range2start..range2end range1.overlaps(range2) } .count(true::equals) // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") val dayInput = readInput("Day04") part1(testInput) check(part1(testInput) == 2) println(part1(dayInput)) check(part2(testInput) == 4) println(part2(dayInput)) }
0
Kotlin
0
0
2f50262ce2dc5024c6da5e470c0214c584992ddb
1,035
aoc2022
Apache License 2.0
src/main/kotlin/betman/PointCalculator.kt
ration
129,735,439
false
null
package betman import betman.pojos.Bet import betman.pojos.Game import betman.pojos.Group import betman.pojos.Match object PointCalculator { enum class Winner { HOME, TIE, AWAY; companion object { fun fromScore(home: Int, away: Int): Winner { val result = home - away return when { result > 0 -> HOME result == 0 -> TIE else -> AWAY } } } } fun calculate(group: Group, game: Game, winnerId: Int?, goalKing: String?, bet: Bet): Int { return game.matches.map { toPoints(it, bet, group) }.sum() + winnerPoints(group, bet, winnerId) + goalKing(group, bet, goalKing) } /** * Accumulation of points per game */ fun pointsPerGame(group: Group, game: Game, bet: Bet): Map<Int, Int> { var sum = 0 val ans: MutableMap<Int, Int> = mutableMapOf() for (match in game.matches) { if (match.homeGoals == null) { continue } sum += toPoints(match, bet, group) ans[match.id] = sum } return ans} private fun toPoints(match: Match, bet: Bet, group: Group): Int { if (match.homeGoals != null) { return if (exactScoreMatch(bet, match)) { group.exactScorePoints } else { oneTeamScorePoints(bet, match, group) + matchWinnerPoints(bet, match, group) } } return 0 } private fun matchWinnerPoints(bet: Bet, match: Match, group: Group): Int { val scoreBet = bet.scores.find { it.matchId == match.id } if (scoreBet != null) { return (match.homeGoals to match.awayGoals).biLet { homeGoals, awayGoals -> val result = Winner.fromScore(homeGoals, awayGoals) val betResult = Winner.fromScore(scoreBet.home, scoreBet.away) if (result == betResult) group.correctWinnerPoints else 0 } ?: 0 } return 0 } fun <T, U, R> Pair<T?, U?>.biLet(body: (T, U) -> R): R? { return first?.let { f -> second?.let { s -> body(f, s) } } } private fun winnerPoints(group: Group, bet: Bet, winnerId: Int?): Int = if (winnerId != null && bet.winner == winnerId) group.winnerPoints else 0 private fun goalKing(group: Group, bet: Bet, goalKing: String?): Int = if (goalKing != null && bet.goalKing == goalKing) group.goalKingPoints else 0 private fun oneTeamScorePoints(bet: Bet, match: Match, group: Group): Int { return if (bet.scores.find { it.matchId == match.id }?.home == match.homeGoals || bet.scores.find { it.matchId == match.id }?.away == match.awayGoals) group.teamGoalPoints else 0 } private fun exactScoreMatch(bet: Bet, match: Match) = bet.scores.find { it.matchId == match.id }?.home == match.homeGoals && bet.scores.find { it.matchId == match.id }?.away == match.awayGoals }
2
Kotlin
0
1
140fae3b6623c6c57a8a9478fa88df41db9bd906
3,182
betman
MIT License
src/Day04/Day04.kt
emillourens
572,599,575
false
{"Kotlin": 32933}
fun main() { fun part1(input: List<String>): Int { var counter = 0 for (assignments in input) { val assignment1Lower = assignments.split(",")[0].split("-")[0].toInt() val assignment1Upper = assignments.split(",")[0].split("-")[1].toInt() val assignment2Lower = assignments.split(",")[1].split("-")[0].toInt() val assignment2Upper = assignments.split(",")[1].split("-")[1].toInt() if((assignment1Lower in assignment2Lower..assignment2Upper && assignment1Upper in assignment2Lower..assignment2Upper) || (assignment2Lower in assignment1Lower..assignment1Upper && assignment2Upper in assignment1Lower..assignment1Upper)) { counter++ } } return counter } fun part2(input: List<String>): Int { var counter = 0 for (assignments in input) { val assignment1Lower = assignments.split(",")[0].split("-")[0].toInt() val assignment1Upper = assignments.split(",")[0].split("-")[1].toInt() val assignment2Lower = assignments.split(",")[1].split("-")[0].toInt() val assignment2Upper = assignments.split(",")[1].split("-")[1].toInt() if((assignment1Lower in assignment2Lower..assignment2Upper || assignment1Upper in assignment2Lower..assignment2Upper) || (assignment2Lower in assignment1Lower..assignment1Upper || assignment2Upper in assignment1Lower..assignment1Upper)) { counter++ } } return counter } // 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
1f9739b73ef080b012e505e0a4dfe88f928e893d
1,979
AoC2022
Apache License 2.0
modules/fathom/src/main/kotlin/silentorb/mythic/fathom/surfacing/old/TraceSurfaceOld.kt
silentorb
227,508,449
false
null
package silentorb.mythic.fathom.surfacing.old import silentorb.mythic.spatial.Quaternion import silentorb.mythic.spatial.Vector2 import silentorb.mythic.spatial.Vector3 data class LongestLineCandidate( val distance: Float, val position: Vector3 ) // Used to precalculate the first half of the normal projection algorithm fun getNormalRotation(normal: Vector3): Quaternion = Quaternion().rotationTo(Vector3(0f, 0f, 1f), normal) // Used to execute the second half of the normal projection algorithm fun projectFromNormalRotation(normalRotation: Quaternion, point: Vector2) = normalRotation.transform(Vector3(point.x, point.y, 0f)) /* // Casts a ray along the surface of a volumetric shape and stops when the ray gets too far away from the surface // If the origin of the ray is along a sharp edge or point, it is possible there to be no valid edge in this direction tailrec fun castSurfaceRay(config: SurfacingConfig, origin: Vector3, direction: Vector3, distance: Float, candidate: Vector3): Vector3 { val newDistance = distance + config.stride val position = origin + direction * newDistance val sample = config.getDistance(position) return if (sample > config.tolerance || sample < -config.tolerance) { candidate } else { castSurfaceRay(config, origin, direction, newDistance, position) } } tailrec fun tracePolygonBounds(config: SurfacingConfig, origin: Vector3, normalRotation: Quaternion, directions: List<Vector2>, candidates: List<Vector3>): List<Vector3> { return if (directions.none()) { candidates } else { val direction = projectFromNormalRotation(normalRotation, directions.first()) val candidate = castSurfaceRay(config, origin, direction, 0f, origin) val newCandidates = candidates.plus(candidate) tracePolygonBounds(config, origin, normalRotation, directions.drop(1), newCandidates) } } // Following shape contours, finds the longest possible edge within a specified tolerance along any orthogonal direction fun tracePolygonBounds(config: SurfacingConfig, origin: Vector3): List<Vector3> { val initialDirections = listOf( Vector2(1f, 0f), Vector2(0f, 1f), Vector2(-1f, 0f), Vector2(0f, -1f), Vector2(1f, 1f), Vector2(1f, -1f), Vector2(-1f, -1f), Vector2(-1f, 1f) ) val normal = calculateNormal(config.getDistance, origin) val normalRotation = getNormalRotation(normal) return tracePolygonBounds(config, origin, normalRotation, initialDirections, listOf()) } fun createStartingPolygon(config: SurfacingConfig, origin: Vector3): Mesh { } fun traceSurface(config: SurfacingConfig, origin: Vector3) { var mesh = createStartingPolygon(config, origin) val incompleteEdgeCount = 1 while(incompleteEdgeCount > 0) { // Get next edge // Get concave connected edges // Get approximately orthoganal vertices filtering out already connected vertices } } */
0
Kotlin
0
2
74462fcba9e7805dddec1bfcb3431665df7d0dee
3,066
mythic-kotlin
MIT License
src/Day07.kt
TinusHeystek
574,474,118
false
{"Kotlin": 53071}
class Day07 : Day(7) { data class FileInfo(val size: Long, val name: String) data class Directory(val parent: Directory?, val name: String) { val directories = mutableListOf<Directory>() private val files = mutableListOf<FileInfo>() fun addDirectory(directoryName: String) { val directory = Directory(this, directoryName) directories.add(directory) } fun getDirectory(directoryName: String) : Directory { return directories.single { it.name == directoryName } } fun addFile(fileSize: String, fileName: String) { val file = FileInfo(fileSize.toLong(), fileName) files.add(file) } fun getDirectorySize() : Long { var size: Long = 0 size += files.sumOf { it.size } size += directories.sumOf { it.getDirectorySize() } return size } } private fun parseFileSystem(input: String) : Directory { val root = Directory(null, "/") var currentDirectory = root val lines = input.lines() for (line in lines) { val split = line.split(" ") when (split[0]) { "\$" -> when (split[1]) { "cd" -> when (split[2]) { "/" -> currentDirectory = root ".." -> { if (currentDirectory.parent != null) currentDirectory = currentDirectory.parent!! } else -> currentDirectory = currentDirectory.getDirectory(split[2]) } "ls" -> { /*list*/ } } "dir" -> currentDirectory.addDirectory(split[1]) else -> { currentDirectory.addFile(split[0], split[1]) } } } return root } // --- Part 1 --- private fun getDirectoryWithSizeLessThan(directory: Directory, limit: Long) : Long { var totalSize : Long = 0 val size = directory.getDirectorySize() if (size <= limit) totalSize += size for (childDir in directory.directories) { totalSize += getDirectoryWithSizeLessThan(childDir, limit) } return totalSize } override fun part1ToString(input: String): String { val root = parseFileSystem(input) val totalSize = getDirectoryWithSizeLessThan(root, 100_000) return totalSize.toString() } private fun getDirectoryWithSizeLargerThan(directory: Directory, required: Long) : MutableList<Long> { val validSizes = mutableListOf<Long>() val size = directory.getDirectorySize() if (size >= required) validSizes.add(size) for (childDir in directory.directories) { validSizes.addAll(getDirectoryWithSizeLargerThan(childDir, required)) } return validSizes } // --- Part 2 --- override fun part2ToString(input: String): String { val root = parseFileSystem(input) val deviceTotalSize = 70_000_000 val requiredFreeSpace = 30_000_000 val currentFreeSpace = deviceTotalSize - root.getDirectorySize() val spaceToCleanUp = requiredFreeSpace - currentFreeSpace val sizes = getDirectoryWithSizeLargerThan(root, spaceToCleanUp) return sizes.min().toString() } } fun main() { val day = Day07() day.printToStringResults("95437", "24933642") }
0
Kotlin
0
0
80b9ea6b25869a8267432c3a6f794fcaed2cf28b
3,519
aoc-2022-in-kotlin
Apache License 2.0
2021/src/day16/Solution.kt
vadimsemenov
437,677,116
false
{"Kotlin": 56211, "Rust": 37295}
package day16 import java.nio.file.Files import java.nio.file.Paths fun main() { fun part1(input: Input): Int { fun dfs(packet: Packet): Int { var sum = packet.version if (packet is Operation) { for (subPacket in packet.subPackets) { sum += dfs(subPacket) } } return sum } Parser(input).use { parser -> return dfs(parser.parsePacket()) } } fun part2(input: Input): Long { fun evaluate(packet: Packet): Long = when(packet) { is Literal -> packet.value is Operation -> when(packet.typeId) { 0 -> packet.subPackets.sumOf { evaluate(it) } 1 -> packet.subPackets.fold(1L) { acc, subPacket -> acc * evaluate(subPacket) } 2 -> packet.subPackets.minOf { evaluate(it) } 3 -> packet.subPackets.maxOf { evaluate(it) } 5, 6, 7 -> { check(packet.subPackets.size == 2) val (lhs, rhs) = packet.subPackets.map { evaluate(it) } when (packet.typeId) { 5 -> if (lhs > rhs) 1 else 0 6 -> if (lhs < rhs) 1 else 0 7 -> if (lhs == rhs) 1 else 0 else -> error("unexpected packet type ID: ${packet.typeId}") } } else -> error("unexpected packet type ID: ${packet.typeId}") } } Parser(input).use { parser -> return evaluate(parser.parsePacket()) } } check(part1("D2FE28".toBinaryString()) == 6) check(part1("38006F45291200".toBinaryString()) == 9) check(part1("EE00D40C823060".toBinaryString()) == 14) check(part1("8A004A801A8002F478".toBinaryString()) == 16) check(part1("620080001611562C8802118E34".toBinaryString()) == 12) check(part1("C0015000016115A2E0802F182340".toBinaryString()) == 23) check(part1("A0016C880162017C3686B18A3D4780".toBinaryString()) == 31) check(part2("C200B40A82".toBinaryString()) == 3L) check(part2("04005AC33890".toBinaryString()) == 54L) check(part2("880086C3E88112".toBinaryString()) == 7L) check(part2("CE00C43D881120".toBinaryString()) == 9L) check(part2("D8005AC2A8F0".toBinaryString()) == 1L) check(part2("F600BC2D8F".toBinaryString()) == 0L) check(part2("9C005AC2F8F0".toBinaryString()) == 0L) check(part2("9C0141080250320F1802104A08".toBinaryString()) == 1L) println(part1(readInput("input.txt"))) println(part2(readInput("input.txt"))) } private sealed interface Packet { val version: Int val typeId: Int } private data class Literal( override val version: Int, override val typeId: Int, val value: Long ) : Packet private data class Operation( override val version: Int, override val typeId: Int, val subPackets: List<Packet> ) : Packet private class Parser(val string: String): AutoCloseable { private var ptr = 0 fun parsePacket(): Packet { val version = parseNum(3) val typeId = parseNum(3) return if (typeId == 4) { Literal(version, typeId, parseLiteralValue()) } else { Operation(version, typeId, parseSubPackets()) } } private fun parseSubPackets(): List<Packet> { val lengthType = parseNum(1) val length = parseNum(if (lengthType == 0) 15 else 11) val subPacketsStart = ptr val subPackets = mutableListOf<Packet>() fun parseNext(): Boolean = when (lengthType) { 0 -> ptr - subPacketsStart < length 1 -> subPackets.size < length else -> error("unexpected length type: $lengthType") } while (parseNext()) { subPackets.add(parsePacket()) } when (lengthType) { 0 -> check(ptr - subPacketsStart == length) 1 -> check(subPackets.size == length) } return subPackets } private fun parseLiteralValue(): Long { var value = 0L do { val last = parseNum(1) == 0 value = (value shl 4) + parseNum(4) } while (!last) return value } private fun parseNum(len: Int): Int { return string.substring(ptr, ptr + len).toInt(2).also { ptr += len } } override fun close() { while (ptr < string.length) { check(string[ptr++] == '0') } } } private fun String.toBinaryString() = map { it.toString() .toInt(16) .toString(2) .padStart(4, '0') }.joinToString("") { it } private fun readInput(s: String): Input { return Files.newBufferedReader(Paths.get("src/day16/$s")).readLines().first().toBinaryString() } private typealias Input = String
0
Kotlin
0
0
8f31d39d1a94c862f88278f22430e620b424bd68
4,378
advent-of-code
Apache License 2.0
src/Day05.kt
lmoustak
573,003,221
false
{"Kotlin": 25890}
import java.util.* fun main() { val labelRegex = Regex("""\s+\d+""") val moveRegex = Regex("""move (\d+) from (\d+) to (\d+)""") fun part1(input: List<String>): String { val stacks = mutableListOf<Stack<Char>>() for (i in input.indices) { val line = input[i] val numberOfStacks = labelRegex.findAll(line).count() if (numberOfStacks > 0 && stacks.isEmpty()) { for (j in 1..numberOfStacks) stacks.add(Stack<Char>()) for (j in i - 1 downTo 0) { val row = input[j] for (k in row.indices step 4) { val crate = row[k + 1] if (crate in 'A'..'Z') { stacks[k / 4].push(crate) } } } } else if (moveRegex.matches(line)) { val groups = moveRegex.find(line)!!.groups val cratesToMove = groups[1]!!.value.toInt() val fromStack = groups[2]!!.value.toInt() val toStack = groups[3]!!.value.toInt() for (i in 1..cratesToMove) { stacks[toStack - 1].push(stacks[fromStack - 1].pop()) } } } return stacks.map { it.last() }.joinToString(separator = "") } fun part2(input: List<String>): String { val stacks = mutableListOf<Stack<Char>>() for (i in input.indices) { val line = input[i] val numberOfStacks = labelRegex.findAll(line).count() if (numberOfStacks > 0 && stacks.isEmpty()) { for (j in 1..numberOfStacks) stacks.add(Stack<Char>()) for (j in i - 1 downTo 0) { val row = input[j] for (k in row.indices step 4) { val crate = row[k + 1] if (crate in 'A'..'Z') { stacks[k / 4].push(crate) } } } } else if (moveRegex.matches(line)) { val groups = moveRegex.find(line)!!.groups val cratesToMove = groups[1]!!.value.toInt() val fromStack = groups[2]!!.value.toInt() val toStack = groups[3]!!.value.toInt() val tempStack = Stack<Char>() for (i in 1..cratesToMove) { tempStack.push(stacks[fromStack - 1].pop()) } for (i in tempStack.indices) { stacks[toStack - 1].push(tempStack.pop()) } } } return stacks.map { it.last() }.joinToString(separator = "") } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bd259af405b557ab7e6c27e55d3c419c54d9d867
2,862
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/me/giacomozama/adventofcode2022/days/Day08.kt
giacomozama
572,965,253
false
{"Kotlin": 75671}
package me.giacomozama.adventofcode2022.days import java.io.File class Day08 : Day() { private lateinit var input: List<IntArray> override fun parseInput(inputFile: File) { input = inputFile.useLines { lines -> lines.map { line -> IntArray(line.length) { line[it].digitToInt() } }.toList() } } // n = number of trees // time: O(n), space: O(n) override fun solveFirstPuzzle(): Int { val m = input.size val n = input[0].size val isVisible = Array(m) { BooleanArray(n) } for (x in 0 until n) { isVisible[0][x] = true var tallest = input[0][x] for (y in 1 until m) { if (input[y][x] > tallest) { isVisible[y][x] = true tallest = input[y][x] } } isVisible[m - 1][x] = true tallest = input[m - 1][x] for (y in m - 2 downTo 0) { if (input[y][x] > tallest) { isVisible[y][x] = true tallest = input[y][x] } } } for (y in 0 until m) { isVisible[y][0] = true var tallest = input[y][0] for (x in 1 until n) { if (input[y][x] > tallest) { isVisible[y][x] = true tallest = input[y][x] } } isVisible[y][n - 1] = true tallest = input[y][n - 1] for (x in n - 2 downTo 0) { if (input[y][x] > tallest) { isVisible[y][x] = true tallest = input[y][x] } } } return isVisible.sumOf { r -> r.count { it } } } // n = number of trees, d = number of possible tree heights // time: O(nd), space: O(n + d) override fun solveSecondPuzzle(): Int { val m = input.size val n = input[0].size val scores = Array(m) { IntArray(n) { 1 } } var result = 0 for (x in 0 until n) { val dp = IntArray(10) for (y in 1 until m) { var closest = Int.MIN_VALUE for (i in input[y][x]..9) closest = maxOf(closest, dp[i]) scores[y][x] *= y - closest dp[input[y][x]] = y } dp.fill(m - 1) for (y in m - 2 downTo 0) { var closest = Int.MAX_VALUE for (i in input[y][x]..9) closest = minOf(closest, dp[i]) scores[y][x] *= closest - y dp[input[y][x]] = y } } for (y in 0 until m) { val dp = IntArray(10) for (x in 1 until n) { var closest = Int.MIN_VALUE for (i in input[y][x]..9) closest = maxOf(closest, dp[i]) scores[y][x] *= x - closest dp[input[y][x]] = x } dp.fill(n - 1) for (x in n - 2 downTo 0) { var closest = Int.MAX_VALUE for (i in input[y][x]..9) closest = minOf(closest, dp[i]) result = maxOf(result, scores[y][x] * (closest - x)) dp[input[y][x]] = x } } return result } }
0
Kotlin
0
0
c30f4a37dc9911f3e42bbf5088fe246aabbee239
3,324
aoc2022
MIT License
src/main/kotlin/Excercise18.kt
underwindfall
433,989,850
false
{"Kotlin": 55774}
sealed class SNum { class Reg(val x: Int) : SNum() { override fun toString(): String = x.toString() } class Pair(val l: SNum, val r: SNum) : SNum() { override fun toString(): String = "[$l,$r]" } } fun parseSNum(s: String): SNum { var i = 0 fun parse(): SNum { if (s[i] == '[') { i++ val l = parse() check(s[i++] == ',') val r = parse() check(s[i++] == ']') return SNum.Pair(l, r) } val start = i while (s[i] in '0'..'9') i++ return SNum.Reg(s.substring(start, i).toInt()) } return parse().also { check(i == s.length) } } fun SNum.findPair(n: Int): SNum.Pair? { if (n == 0) return this as? SNum.Pair? if (this is SNum.Pair) { l.findPair(n - 1)?.let { return it } r.findPair(n - 1)?.let { return it } } return null } fun SNum.findReg(lim: Int): SNum.Reg? = when (this) { is SNum.Reg -> if (x >= lim) this else null is SNum.Pair -> { l.findReg(lim)?.let { return it } r.findReg(lim)?.let { return it } null } } fun SNum.traverse(keep: SNum.Pair): List<SNum> = when (this) { is SNum.Reg -> listOf(this) is SNum.Pair -> if (this == keep) listOf(this) else l.traverse(keep) + r.traverse(keep) } fun SNum.replace(op: Map<SNum, SNum>): SNum { op[this]?.let { return it } return when (this) { is SNum.Reg -> this is SNum.Pair -> SNum.Pair(l.replace(op), r.replace(op)) } } fun SNum.reduceOp(): Map<SNum, SNum>? { val n = findPair(4) if (n != null) { check(n.l is SNum.Reg) check(n.r is SNum.Reg) val op = mutableMapOf<SNum, SNum>(n to SNum.Reg(0)) val f = traverse(n) val i = f.indexOf(n) (f.getOrNull(i - 1) as? SNum.Reg)?.let { op[it] = SNum.Reg(it.x + n.l.x) } (f.getOrNull(i + 1) as? SNum.Reg)?.let { op[it] = SNum.Reg(it.x + n.r.x) } return op } val r = findReg(10) if (r != null) return mapOf(r to SNum.Pair(SNum.Reg(r.x / 2), SNum.Reg((r.x + 1) / 2))) return null } fun add(a: SNum, b: SNum): SNum = generateSequence<SNum>(SNum.Pair(a, b)) { s -> s.reduceOp()?.let { s.replace(it) } }.last() fun SNum.magnitude(): Int = when (this) { is SNum.Reg -> x is SNum.Pair -> 3 * l.magnitude() + 2 * r.magnitude() } private fun part1() { val input = getInputAsTest("18") { split("\n") } val a = input.map(::parseSNum) val part1 = a.reduce(::add).magnitude() println("part1 = $part1") } private fun part2() { val input = getInputAsTest("18") { split("\n") } val a = input.map(::parseSNum) val part2 = buildList { for (i in a.indices) for (j in a.indices) if (i != j) add(add(a[i], a[j]).magnitude()) } .maxOrNull()!! println("part2 = $part2") } fun main() { part1() part2() }
0
Kotlin
0
0
4fbee48352577f3356e9b9b57d215298cdfca1ed
2,789
advent-of-code-2021
MIT License
tree_data_structure/PseudoPalindromicPathsInABinaryTree/kotlin/Solution.kt
YaroslavHavrylovych
78,222,218
false
{"Java": 284373, "Kotlin": 35978, "Shell": 2994}
/** * Given a binary tree where node values are digits from 1 to 9. * A path in the binary tree is said to be pseudo-palindromic * if at least one permutation of the node values in the path is a palindrome. * Return the number of pseudo-palindromic paths going * from the root node to leaf nodes. * <br/> * https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/ * <br/> * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. */ class Solution { var res = 0 lateinit var mp: MutableMap<Int, Int> fun pseudoPalindromicPaths(root: TreeNode?): Int { res = 0 if (root == null) return 0 mp = HashMap<Int, Int>() if (root.left == null && root.right == null) return 1 help(root) return res } private fun help(n: TreeNode) { mp.put(n.`val`, mp.getOrDefault(n.`val`, 0) + 1) if (n.left != null) { help(n.left!!) } if (n.right != null) { help(n.right!!) } if (n.left == null && n.right == null) { //check if pseudo pal if (isPal()) res += 1 } //remove from the map, we are going home val amount = mp.get(n.`val`)!! - 1 if (amount == 0) mp.remove(n.`val`) else mp.put(n.`val`, amount) } private fun isPal(): Boolean { var nonDiv = true for (v in mp.values) { if (v % 2 != 0) { if (nonDiv) { nonDiv = false continue } return false } } return true } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null } fun main() { println("Pseudo-Palindromic Paths in a Binary Tree" + ": test is not implemented") }
0
Java
0
2
cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd
1,807
codility
MIT License
src/main/kotlin/be/tabs_spaces/advent2021/days/Day11.kt
janvryck
433,393,768
false
{"Kotlin": 58803}
package be.tabs_spaces.advent2021.days import kotlin.also as and import kotlin.let as then class Day11 : Day(11) { override fun partOne() = Cavern(inputList).iterate(100) override fun partTwo() = Cavern(inputList).optimalStep() class Cavern(rawInput: List<String>) { private val octopuses = rawInput.indices.flatMap { y -> rawInput[y].indices.map { x -> Octopus(Point(x, y), rawInput[y][x].digitToInt()) } } private val xMax = octopuses.maxOf { it.position.x } private val yMax = octopuses.maxOf { it.position.y } fun iterate(times: Int) = (1..times).sumOf { step() } fun optimalStep() = generateSequence { step() }.takeWhile { it < 100 }.count().inc() private fun step(): Int = octopuses .forEach { it.increaseEnergyLevel() } .then { countFlashes().and { expendEnergy() } } private fun countFlashes() = generateSequence { octopuses.count { it.willFlash() }.and { propagateFlashes() } } .takeWhile { it > 0 } .sum() private fun propagateFlashes() = octopuses.filter { it.willFlash() }.forEach { it.flash(neighbours(it.position)) } private fun neighbours(position: Point) = octopuses.filter { it.position in position.neighbours(xMax, yMax) } private fun expendEnergy() = octopuses.filter { it.hasFlashed() }.forEach { it.energyExpended() } } private data class Octopus(val position: Point, private var energyLevel: Int) { fun increaseEnergyLevel() { energyLevel++ } fun energyExpended() { energyLevel = 0 } fun willFlash() = energyLevel == 10 fun hasFlashed() = energyLevel > 10 fun flash(neighbours: List<Octopus>) { increaseEnergyLevel() neighbours .filterNot { it.willFlash() } .forEach { it.increaseEnergyLevel() } } } private data class Point(val x: Int, val y: Int) { fun neighbours(xMax: Int, yMax: Int) = listOf(x - 1, x, x + 1) .filter { it in 0..xMax } .flatMap { x -> listOf(y - 1, y, y + 1) .filter { it in 0..yMax } .map { y -> Point(x, y) } }.filter { neighbour -> neighbour != this } } }
0
Kotlin
0
0
f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9
2,361
advent-2021
Creative Commons Zero v1.0 Universal
src/Day08.kt
pavlo-dh
572,882,309
false
{"Kotlin": 39999}
fun main() { fun part1(input: List<String>): Int { val visibleGrid = input.map { BooleanArray(it.length) } for (i in 1 until input.size - 1) { var highest = input[i][0] for (j in 1 until input.size - 1) { if (input[i][j] > highest && input[i][j] > input[i][j - 1]) { visibleGrid[i][j] = true highest = input[i][j] } } highest = input[i][input.lastIndex] for (j in input.size - 2 downTo 1) { if (input[i][j] > highest && input[i][j] > input[i][j + 1]) { visibleGrid[i][j] = true highest = input[i][j] } } } for (j in 1 until input.size - 1) { var highest = input[0][j] for (i in 1 until input.size - 1) { if (input[i][j] > highest && input[i][j] > input[i - 1][j]) { visibleGrid[i][j] = true highest = input[i][j] } } highest = input[input.lastIndex][j] for (i in input.size - 2 downTo 1) { if (input[i][j] > highest && input[i][j] > input[i + 1][j]) { visibleGrid[i][j] = true highest = input[i][j] } } } var visibleCount = 0 for (i in input.indices) { for (j in input.indices) { if (i == 0 || i == input.size - 1 || j == 0 || j == input.size - 1) visibleGrid[i][j] = true if (visibleGrid[i][j]) visibleCount++ } } return visibleCount } fun part2(input: List<String>): Int { fun findScore(i: Int, j: Int): Int { if (i == 0 || i == input.size || j == 0 || j == input.size) return 0 var down = 0 for (k in i + 1..input.lastIndex) { down++ if (input[k][j] >= input[i][j]) break } var up = 0 for (k in i - 1 downTo 0) { up++ if (input[k][j] >= input[i][j]) break } var right = 0 for (k in j + 1..input.lastIndex) { right++ if (input[i][k] >= input[i][j]) break } var left = 0 for (k in j - 1 downTo 0) { left++ if (input[i][k] >= input[i][j]) break } return down * up * right * left } var highestScore = 0 for (i in input.indices) { for (j in input.indices) { val score = findScore(i, j) if (score > highestScore) highestScore = score } } return highestScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992
3,116
aoc-2022-in-kotlin
Apache License 2.0
src/aoc23/Day08.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc23.day08 import lib.Maths.lcm import lib.Solution enum class Step(val symbol: Char) { LEFT('L'), RIGHT('R'); companion object { fun parse(symbol: Char): Step = values().find { it.symbol == symbol }!! } } data class Node(val label: String, val left: String, val right: String) { fun isSource(): Boolean = label == "AAA" fun isGhostSource(): Boolean = label.endsWith("A") fun isSink(): Boolean = label == "ZZZ" fun isGhostSink(): Boolean = label.endsWith("Z") companion object { fun parse(nodeStr: String): Node { val (label, left, right) = NODE_REGEX.matchEntire(nodeStr)!!.destructured return Node(label, left, right) } private val NODE_REGEX = Regex("""(\w+) = \((\w+), (\w+)\)""") } } data class Network(val nodes: Map<String, Node>) { fun source(): Node = nodes.values.find { it.isSource() }!! fun ghostSources(): List<Node> = nodes.values.filter { it.isGhostSource() } fun step(node: Node, step: Step): Node = when (step) { Step.LEFT -> nodes[node.left] Step.RIGHT -> nodes[node.right] } ?: error("Invalid step $step for node $node") companion object { fun parse(networkStr: String): Network = networkStr.lines().map(Node::parse).associateBy { it.label }.let { Network(it) } } } data class Input(val steps: List<Step>, val network: Network) { fun countStepsToSink(source: Node): Long { var node = source var stepIndex = 0L while (!node.isGhostSink()) { val step = getStep(stepIndex) node = network.step(node, step) stepIndex++ } return stepIndex } private fun getStep(stepIndex: Long): Step = steps[(stepIndex % steps.size).toInt()]!! companion object { fun parse(inputStr: String): Input { val (stepsPart, networkPart) = inputStr.split("\n\n") return Input(stepsPart.map { Step.parse(it) }, Network.parse(networkPart)) } } } typealias Output = Long private val solution = object : Solution<Input, Output>(2023, "Day08") { override fun parse(input: String) = Input.parse(input) override fun format(output: Output): String = "$output" override fun part1(input: Input): Output = input.countStepsToSink(input.network.source()) override fun part2(input: Input): Output = input .network .ghostSources() .map(input::countStepsToSink) .reduce { acc, cnt -> acc lcm cnt } } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
2,473
aoc-kotlin
Apache License 2.0
src/main/kotlin/g1301_1400/s1320_minimum_distance_to_type_a_word_using_two_fingers/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1320_minimum_distance_to_type_a_word_using_two_fingers // #Hard #String #Dynamic_Programming #2023_06_05_Time_181_ms_(100.00%)_Space_37.7_MB_(100.00%) class Solution { private var word: String? = null private lateinit var dp: Array<Array<Array<Int?>>> fun minimumDistance(word: String): Int { this.word = word dp = Array(27) { Array(27) { arrayOfNulls(word.length) } } return find(null, null, 0) } private fun find(f1: Char?, f2: Char?, index: Int): Int { if (index == word!!.length) { return 0 } val result = dp[if (f1 == null) 0 else f1.code - 'A'.code + 1][ if (f2 == null) 0 else f2.code - 'A'.code + 1 ][index] if (result != null) { return result } val ic = word!![index] var move = move(f1, ic) + find(ic, f2, index + 1) move = Math.min(move, move(f2, ic) + find(f1, ic, index + 1)) dp[if (f1 == null) 0 else f1.code - 'A'.code + 1][if (f2 == null) 0 else f2.code - 'A'.code + 1][index] = move return move } private fun move(c1: Char?, c2: Char): Int { if (c1 == null) { return 0 } val c1x = (c1.code - 'A'.code) % 6 val c1y = (c1.code - 'A'.code) / 6 val c2x = (c2.code - 'A'.code) % 6 val c2y = (c2.code - 'A'.code) / 6 return Math.abs(c1x - c2x) + Math.abs(c1y - c2y) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,454
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/claudio/adventofcode2022/Day11Part2.kt
ClaudioConsolmagno
572,915,041
false
{"Kotlin": 41573}
package dev.claudio.adventofcode2022 fun main() { Day11Part2().main() } private class Day11Part2 { fun main() { // val input = Support.readFileAsListString("2022/day11-input.txt") // val monkeysSample = listOf( // Monkey(0, mutableListOf(79, 98), { it:Long -> it * 19}, 23, 2, 3), // Monkey(1, mutableListOf(54, 65, 75, 74), { it:Long -> it + 6}, 19, 2, 0), // Monkey(2, mutableListOf(79, 60, 97), { it:Long -> it * it}, 13, 1, 3), // Monkey(3, mutableListOf(74), { it:Long -> it + 3}, 17, 0, 1), // ) val monkeys = listOf( Monkey(0, mutableListOf(99, 63, 76, 93, 54, 73), { it:Long -> it * 11}, 2, 7, 1), Monkey(1, mutableListOf(91, 60, 97, 54), { it:Long -> it + 1}, 17, 3, 2), Monkey(2, mutableListOf(65), { it:Long -> it + 7}, 7, 6, 5), Monkey(3, mutableListOf(84, 55), { it:Long -> it + 3}, 11, 2, 6), Monkey(4, mutableListOf(86, 63, 79, 54, 83), { it:Long -> it * it}, 19, 7, 0), Monkey(5, mutableListOf(96, 67, 56, 95, 64, 69, 96), { it:Long -> it + 4}, 5, 4, 0), Monkey(6, mutableListOf(66, 94, 70, 93, 72, 67, 88, 51), { it:Long -> it * 5}, 13, 4, 5), Monkey(7, mutableListOf(59, 59, 74), { it:Long -> it + 8}, 3, 1, 3), ) val leastCommonMultiple = monkeys.map { it.testDiv }.distinct().reduce { acc, it -> acc * it } for (i in 1..10000) { monkeys.forEach { it.items.toList().forEach{ item -> it.inspectionCount++ val newWorry = it.operation(item).mod(leastCommonMultiple) monkeys[it.test(newWorry)].items.add(newWorry) it.items.removeFirst() } } } // println(monkeys) // println(monkeys.map { it.inspectionCount }) println(monkeys.map { it.inspectionCount }.sortedDescending().take(2).reduce {acc, it -> acc * it}) } private data class Monkey( val number: Long, var items: MutableList<Long>, val operation: (Long) -> Long, val testDiv: Long, val testTrue: Int, val testFalse: Int, var inspectionCount: Long = 0L ) { fun test(worry: Long): Int { return if (worry % testDiv == 0L) { testTrue } else { testFalse } } } }
0
Kotlin
0
0
43e3f1395073f579137441f41cd5a63316aa0df8
2,398
adventofcode-2022
Apache License 2.0
src/DigitsRecognizer.kt
lasp91
70,458,490
false
null
import java.io.File import java.util.stream.IntStream import java.util.concurrent.atomic.AtomicInteger data class Observation (val label: String , val Pixels: IntArray) typealias Distance = (IntArray, IntArray) -> Int typealias Classifier = (IntArray) -> String typealias Observations = Array<Observation> fun observationData(csvData: String) : Observation { val columns = csvData.split(',') val label = columns[0] val pixels = columns.subList(1, columns.lastIndex).map(String::toInt) return Observation(label, pixels.toIntArray()) } fun reader(path: String) : Array<Observation> { val observations = File(path).useLines { lines -> lines.drop(1).map(::observationData).toList().toTypedArray() } return observations } val manhattanDistance = { pixels1: IntArray, pixels2: IntArray -> // Using zip and map val dist = pixels1.zip(pixels2) .map { p -> Math.abs(p.first - p.second) } .sum() dist } val manhattanDistanceImperative = fun(pixels1: IntArray, pixels2: IntArray) : Int { var dist = 0 for (i in 0 until pixels1.size) dist += Math.abs(pixels1[i] - pixels2[i]) return dist } val euclideanDistance = { pixels1: IntArray, pixels2: IntArray -> val dist = pixels1.zip(pixels2) // .map { p -> Math.pow((p.first - p.second).toDouble(), 2.0) } .map({ p -> val dist = (p.first - p.second); dist * dist }) .sum() dist } val euclideanDistanceImperative = fun(pixels1: IntArray, pixels2: IntArray) : Int { var dist = 0 for (i in 0 until pixels1.size) { val dif = Math.abs(pixels1[i] - pixels2[i]) dist += dif * dif } return dist } fun classify(trainingSet: Array<Observation>, dist: Distance, pixels: IntArray) : String { val observation = trainingSet.minBy { (_, Pixels) -> dist(Pixels, pixels) } return observation!!.label } fun evaluate(validationSet: Array<Observation>, classifier: (IntArray) -> String) : Unit { // val average = validationSet // .map({ (label, Pixels) -> if (classifier(Pixels) == label) 1.0 else 0.0 }) // .average() // println("Correct: $average") //} val count = validationSet.size val sum = AtomicInteger(0) IntStream.range(0, validationSet.size).parallel().forEach { i -> if (classifier(validationSet[i].Pixels) == validationSet[i].label) sum.addAndGet(1) } println("Correct: ${sum.toDouble() / count}") } //----------------------------------------------------------------------------------------- fun main(args: Array<String>) { val trainingPath = "./Data/trainingsample.csv" val trainingData = reader(trainingPath) val validationPath = "./Data/validationsample.csv" val validationData = reader(validationPath) val manhattanClassifier = fun(pixels: IntArray) : String { return classify(trainingData, manhattanDistanceImperative, pixels) } val euclideanClassifier = fun(pixels: IntArray) : String { return classify(trainingData, euclideanDistanceImperative, pixels) } run { val startTime = System.currentTimeMillis() println(" Manhattan Kotlin") evaluate(validationData, manhattanClassifier) val endTime = System.currentTimeMillis() val elapsedTime = (endTime - startTime) / 1000.0 println(">>> Elapsed time is: $elapsedTime sec") } run { val startTime = System.currentTimeMillis() println(" Euclidean Kotlin") evaluate(validationData, euclideanClassifier) val endTime = System.currentTimeMillis() val elapsedTime = (endTime - startTime) / 1000.0 println(">>> Elapsed time is: $elapsedTime sec") } }
0
Kotlin
0
0
4907cbb2c656c344f5c0a5175909e6cc3bedd67d
3,579
DigitsRecognizer_using_Kotlin
Apache License 2.0
src/Day22.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
import com.github.h0tk3y.betterParse.combinators.or import com.github.h0tk3y.betterParse.combinators.use import com.github.h0tk3y.betterParse.combinators.zeroOrMore import com.github.h0tk3y.betterParse.grammar.Grammar import com.github.h0tk3y.betterParse.grammar.parseToEnd import com.github.h0tk3y.betterParse.lexer.literalToken import com.github.h0tk3y.betterParse.lexer.regexToken import com.github.h0tk3y.betterParse.parser.Parser private enum class Spot { OPEN, WALL } private enum class Facing(val score: Int) { RIGHT(0), DOWN(1), LEFT(2), UP(3) } private sealed interface Direction { object Left : Direction object Right : Direction data class Move(val amount: Int) : Direction } private val pathGrammar = object : Grammar<List<Direction>>() { val number by regexToken("\\d+") val l by literalToken("L") val r by literalToken("R") val move by number use { Direction.Move(text.toInt()) } val left by l use { Direction.Left } val right by r use { Direction.Right } val term by move or left or right val terms: Parser<List<Direction>> = zeroOrMore(term) override val rootParser by terms } fun main() { fun part1(input: String): Int { val (boardInput, directionInput) = input.split("\n\n") val board = boardInput.lines().flatMapIndexed { row, line -> line.mapIndexedNotNull { column, char -> when (char) { '.' -> ((row + 1) to (column + 1)) to Spot.OPEN '#' -> ((row + 1) to (column + 1)) to Spot.WALL else -> null } } }.toMap() val minRow = board.minOf { it.key.first } val maxRow = board.maxOf { it.key.first } val minColumn = board.minOf { it.key.second } val maxColumn = board.maxOf { it.key.second } var position = board .minWith(compareBy<Map.Entry<Pair<Int, Int>, Spot?>> { it.key.first }.thenBy { it.key.second }) .key var facing = Facing.RIGHT fun move() { position = when (facing) { Facing.UP -> sequence { yield(position.copy(first = position.first - 1)) yieldAll(generateSequence(position.copy(first = maxRow)) { it.copy(first = it.first - 1) }) } Facing.DOWN -> sequence { yield(position.copy(first = position.first + 1)) yieldAll(generateSequence(position.copy(first = minRow)) { it.copy(first = it.first + 1) }) } Facing.LEFT -> sequence { yield(position.copy(second = position.second - 1)) yieldAll(generateSequence(position.copy(second = maxColumn)) { it.copy(second = it.second - 1) }) } Facing.RIGHT -> sequence { yield(position.copy(second = position.second + 1)) yieldAll(generateSequence(position.copy(second = minColumn)) { it.copy(second = it.second + 1) }) } }.first { board[it] != null } .takeIf { board[it] == Spot.OPEN } ?: position } fun turnLeft() { facing = when (facing) { Facing.RIGHT -> Facing.UP Facing.DOWN -> Facing.RIGHT Facing.LEFT -> Facing.DOWN Facing.UP -> Facing.LEFT } } fun turnRight() { facing = when (facing) { Facing.RIGHT -> Facing.DOWN Facing.DOWN -> Facing.LEFT Facing.LEFT -> Facing.UP Facing.UP -> Facing.RIGHT } } pathGrammar.parseToEnd(directionInput).forEach { when (it) { is Direction.Move -> repeat(it.amount) { move() } Direction.Left -> turnLeft() Direction.Right -> turnRight() } } return (1000 * position.first) + (4 * position.second) + facing.score } fun part2(input: String): Int { val (boardInput, directionInput) = input.split("\n\n") return 0 } // test if implementation meets criteria from the description, like: val testInput = readText("Day22_test") check(part1(testInput) == 6032) check(part2(testInput) == 5031) val input = readText("Day22") with(part1(input)) { check(this == 1428) println(this) } with(part2(input)) { // check(this == 569) println(this) } }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
4,575
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/pl/jpodeszwik/aoc2023/Day09.kt
jpodeszwik
729,812,099
false
{"Kotlin": 55101}
package pl.jpodeszwik.aoc2023 private fun solve(line: String): Long { val numbers = line.split(" ").map { java.lang.Long.parseLong(it) } val diffs = ArrayList<List<Long>>() diffs.add(numbers) var currentNumbers = numbers while (!currentNumbers.all { it == 0L }) { val newDiffs = ArrayList<Long>() for (i in 0..<currentNumbers.size - 1) { newDiffs.add(currentNumbers[i + 1] - currentNumbers[i]) } diffs.add(newDiffs) currentNumbers = newDiffs } var ret = 0L diffs.reversed().forEach { val last = it.lastOrNull() if (last != null) { ret += last } } return ret } private fun part1(lines: List<String>) { val result = lines.sumOf { solve(it) } println(result) } private fun solve2(line: String): Long { val numbers = line.split(" ").map { java.lang.Long.parseLong(it) } val diffs = ArrayList<List<Long>>() diffs.add(numbers) var currentNumbers = numbers while (!currentNumbers.all { it == 0L }) { val newDiffs = ArrayList<Long>() for (i in 0..<currentNumbers.size - 1) { newDiffs.add(currentNumbers[i + 1] - currentNumbers[i]) } diffs.add(newDiffs) currentNumbers = newDiffs } var ret = 0L diffs.reversed().forEach { val first = it.firstOrNull() if (first != null) { ret = first - ret } } return ret } private fun part2(lines: List<String>) { val result = lines.sumOf { solve2(it) } println(result) } fun main() { val lines = loadFile("/aoc2023/input9") part1(lines) part2(lines) }
0
Kotlin
0
0
2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63
1,669
advent-of-code
MIT License
src/Day08.kt
wlghdu97
573,333,153
false
{"Kotlin": 50633}
class Forest constructor(private val input: Array<IntArray>) { val size = input.size init { // check input is square assert(input.all { it.size == size }) } operator fun get(x: Int, y: Int): Int { return input[x][y] } } fun Forest.visibleTreeFromOutsideCount(): Int { fun isVisible(targetX: Int, targetY: Int): Boolean { val height = this[targetX, targetY] val north = (0 until targetY).none { this[targetX, it] >= height } val south = (targetY + 1 until size).none { this[targetX, it] >= height } val west = (0 until targetX).none { this[it, targetY] >= height } val east = (targetX + 1 until size).none { this[it, targetY] >= height } return (north || south || west || east) } var innerVisible = 0 for (x in 1 until size - 1) { for (y in 1 until size - 1) { if (isVisible(x, y)) { innerVisible += 1 } } } return (size * 4 - 4) + innerVisible } fun Forest.highestScenicScore(): Int { fun scenicScoreFor(targetX: Int, targetY: Int): Int { val height = this[targetX, targetY] var north = 0 for (y in (targetY - 1) downTo 0) { if (this[targetX, y] >= height) { north += 1 break } north += 1 } var south = 0 for (y in (targetY + 1) until size) { if (this[targetX, y] >= height) { south += 1 break } south += 1 } var west = 0 for (x in (targetX - 1) downTo 0) { if (this[x, targetY] >= height) { west += 1 break } west += 1 } var east = 0 for (x in (targetX + 1) until size) { if (this[x, targetY] >= height) { east += 1 break } east += 1 } return (north * south * west * east) } var max = 0 for (x in 1 until size - 1) { for (y in 1 until size - 1) { val score = scenicScoreFor(x, y) if (score > max) { max = score } } } return max } fun makeTestForest(): Forest { return Forest( arrayOf( intArrayOf(3, 0, 3, 7, 3), intArrayOf(2, 5, 5, 1, 2), intArrayOf(6, 5, 3, 3, 2), intArrayOf(3, 3, 5, 4, 9), intArrayOf(3, 5, 3, 9, 0) ) ) } fun parseForest(input: List<String>): Forest { val array = input.map { it.toCharArray().map { char -> char.digitToInt() }.toIntArray() }.toTypedArray() return Forest(array) } fun main() { fun test1(forest: Forest): Int { return forest.visibleTreeFromOutsideCount() } fun part1(input: List<String>): Int { return parseForest(input).visibleTreeFromOutsideCount() } fun test2(forest: Forest): Int { return forest.highestScenicScore() } fun part2(input: List<String>): Int { return parseForest(input).highestScenicScore() } val input = readInput("Day08") println(test1(makeTestForest())) println(part1(input)) println(test2(makeTestForest())) println(part2(input)) }
0
Kotlin
0
0
2b95aaaa9075986fa5023d1bf0331db23cf2822b
3,349
aoc-2022
Apache License 2.0
Problems/Algorithms/79. Word Search/WordSearch.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun exist(board: Array<CharArray>, word: String): Boolean { val n = board.size val m = board[0].size val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)) val visited = Array(n) { BooleanArray(m) { false } } for (i in 0..n-1) { for (j in 0..m-1) { if (aux(board, neighbors, visited, i, j, word)) return true } } return false } private fun aux(board: Array<CharArray>, neighbors: Array<IntArray>, visited: Array<BooleanArray>, i: Int, j: Int, word: String): Boolean { if (word.length == 1) return board[i][j] == word.get(0) visited[i][j] = true var ans = false if (board[i][j] == word.get(0)) { ans = neighbors.filter { isValid(board, visited, i+it[0], j+it[1]) } .any { aux(board, neighbors, visited, i+it[0], j+it[1], word.substring(1)) } } visited[i][j] = false return ans } private fun isValid(board: Array<CharArray>, visited: Array<BooleanArray>, i: Int, j: Int): Boolean { val n = board.size val m = board[0].size return i >= 0 && i < n && j >= 0 && j < m && !visited[i][j] } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,312
leet-code
MIT License
parserkt-util/src/commonMain/kotlin/org/parserkt/util/Trie.kt
ParserKt
242,278,819
false
null
package org.parserkt.util //// == Trie Tree == open class Trie<K, V>(var value: V?) { constructor(): this(null) val routes: MutableMap<K, Trie<K, V>> by lazy(::mutableMapOf) operator fun get(key: Iterable<K>): V? = getPath(key).value open operator fun set(key: Iterable<K>, value: V) { getOrCreatePath(key).value = value } operator fun contains(key: Iterable<K>) = try { this[key] != null } catch (_: NoSuchElementException) { false } fun getPath(key: Iterable<K>): Trie<K, V> { return key.fold(initial = this) { point, k -> point.routes[k] ?: errorNoPath(key, k) } } fun getOrCreatePath(key: Iterable<K>): Trie<K, V> { return key.fold(initial = this) { point, k -> point.routes.getOrPut(k, ::Trie) } } fun collectKeys(): Set<List<K>> { if (routes.isEmpty() && value == null) return emptySet() val routeSet = routes.flatMapTo(mutableSetOf()) { kr -> val (pathKey, nextRoute) = kr return@flatMapTo nextRoute.collectKeys().map { listOf(pathKey)+it } } if (value != null) routeSet.add(emptyList()) return routeSet } private fun errorNoPath(key: Iterable<K>, k: K): Nothing { val msg = "${key.joinToString("/")} @$k" throw NoSuchElementException(msg) } override fun equals(other: Any?) = compareUsing(other) { routes == it.routes && value == it.value } override fun hashCode() = hash(routes, value) override fun toString(): String = when { value == null -> "Path$routes" value != null && routes.isNotEmpty() -> "Bin[$value]$routes" value != null && routes.isEmpty() -> "Term($value)" else -> impossible() } } //// == Abstract == fun <K, V> Trie<K, V>.toMap() = collectKeys().associate { it to this[it]!! } operator fun <V> Trie<Char, V>.get(key: CharSequence) = this[key.asIterable()] operator fun <V> Trie<Char, V>.set(key: CharSequence, value: V) { this[key.asIterable()] = value } operator fun <V> Trie<Char, V>.contains(key: CharSequence) = key.asIterable() in this fun <K, V> Trie<K, V>.merge(vararg kvs: Pair<Iterable<K>, V>) { for ((k, v) in kvs) this[k] = v } fun <V> Trie<Char, V>.mergeStrings(vararg kvs: Pair<CharSequence, V>) { for ((k, v) in kvs) this[k] = v } /** Create multiply route in path to [key], helper for functions like `setNocase` */ fun <K, V> Trie<K, V>.getOrCreatePaths(key: Iterable<K>, layer: (K) -> Iterable<K>): List<Trie<K, V>> = key.fold(listOf(this)) { points, k -> points.flatMap { point -> layer(k).map { point.routes.getOrPut(it, ::Trie) } } }
1
Kotlin
0
11
37599098dc9aafef7b509536e6d17ceca370d6cf
2,504
ParserKt
MIT License
src/aoc23/Day10.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc23.day10 import lib.Direction import lib.Direction.* import lib.Grid import lib.Point import lib.Solution enum class Tile(val symbol: Char, val connections: Set<Direction>) { GROUND('.', emptySet()), VERTICAL('|', setOf(UP, DOWN)), HORIZONTAL('-', setOf(LEFT, RIGHT)), NORTH_EAST('L', setOf(UP, RIGHT)), NORTH_WEST('J', setOf(UP, LEFT)), SOUTH_WEST('7', setOf(DOWN, LEFT)), SOUTH_EAST('F', setOf(DOWN, RIGHT)), START('S', setOf(UP, DOWN, LEFT, RIGHT)); companion object { fun parse(symbol: Char): Tile { return values().find { it.symbol == symbol } ?: error("Unknown symbol: $symbol") } } } data class Connection(val from: Point, val to: Point, val direction: Direction) { fun reversed(): Connection = Connection(to, from, direction.turnAround()) } enum class Orientation { CW, CCW } /** * A closed pipe is a sequence of connections that starts and ends at the same point. We use * connections instead of points to represent the pipe as we need to know the direction of the pipe. * The original tiles are not important to keep track of. However, if needed, we can always get the * original tiles from the grid. */ data class Pipe(val connections: List<Connection>) { val length: Int = connections.size /** * Fix the orientation of the pipe. The pipe is either clockwise or counter-clockwise. */ fun fixOrientation(orientation: Orientation): Pipe = if (orientation == this.checkOrientation()) this else reversed() /** * Reverse the pipe by traversing the connections in reverse order and also by reversing each * individual connection. */ private fun reversed() = Pipe(connections.reversed().map(Connection::reversed)) /** * Check the orientation of the pipe. The pipe is either clockwise or counter-clockwise. * We start with the left most connection on the top most row. Then the connection must be either * RIGHT or DOWN as otherwise the connection is not left-most connection in top-most row. If the * connection is RIGHT, then the pipe orientation is clockwise, otherwise it is counter-clockwise. */ private fun checkOrientation(): Orientation = if (findTopLeftConnection().direction == RIGHT) Orientation.CW else Orientation.CCW /** * Find the left most connection on the top most row. The connection must be either RIGHT or DOWN. * Also, the connection must start with a tile of type START or SOUTH_EAST as otherwise there is * another tile either on the left or on top making it not the left most connection on the top * most row. */ private fun findTopLeftConnection() = connections.minWith(compareBy({ it.from.y }, { it.from.x })) } data class Field(val grid: Grid<Tile>) { private val start: Point by lazy { grid.indexOf(Tile.START) } fun findPipe(): Pipe = Pipe(buildList { var curr = connections(start).first() add(curr) while (curr.to != start) { val next = connections(curr.to).first { it.to != curr.from } curr = next add(curr) } }) private fun connections(from: Point): List<Connection> = possibleConnections(from).filter { connection -> connection.to in grid && connection.direction.turnAround() in grid[connection.to].connections } private fun possibleConnections(from: Point): List<Connection> = grid[from].connections.map { Connection(from, from.move(it), it) } companion object { fun parse(input: String): Field = Field(Grid.parse(input).map { Tile.parse(it) }) } } typealias Input = Field typealias Output = Int private val solution = object : Solution<Input, Output>(2023, "Day10") { override fun parse(input: String): Input = Field.parse(input) override fun format(output: Output): String = "$output" override fun part1(input: Input): Output = input.findPipe().length / 2 override fun part2(input: Input): Output { // Traverse the pipe clockwise while looking on the right side of the pipe. If there is a tile // on the right side of the pipe, then we are inside the pipe. Otherwise, we are outside the // pipe. Then we run a BFS from the inside of the pipe to find all the points inside the pipe. val pipe = input.findPipe().fixOrientation(Orientation.CW) val pointsOnPipe = pipe.connections.map { it.from }.toSet() // Find all the points adjacent to the pipe on the right side. These are the points that are // inside the pipe. val innerPoints = pipe.connections.flatMap { connection -> listOf(connection.from, connection.to).mapNotNull { pointOnPipe -> val rightDir = connection.direction.turnRight() val innerPoint = pointOnPipe.move(rightDir) innerPoint.takeIf { it in input.grid && it !in pointsOnPipe } } } // Run a BFS from the inside of the pipe to find all the points inside the pipe. val queue = ArrayDeque(innerPoints) val visited = pointsOnPipe.toMutableSet() while (queue.isNotEmpty()) { val point = queue.removeFirst() if (point in input.grid && point !in visited) { visited.add(point) queue.addAll(input.grid.adjacents(point)) } } // The number of points inside the pipe is the number of visited points minus the number of // points on the pipe. return visited.size - pointsOnPipe.size } } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
5,397
aoc-kotlin
Apache License 2.0
src/Day05.kt
li-xin-yi
573,617,763
false
{"Kotlin": 23422}
import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap fun main() { fun solvePart1(input: List<String>): String { val stacks = HashMap<Int, Deque<Char>>() var start = 0 for (idx in input.indices) { if (input[idx] == "") { start = idx + 1 break } for (i in 0 until input[idx].length step 4) { if (input[idx][i] == '[' && input[idx][i + 2] == ']') { stacks.getOrPut(i / 4 + 1) { ArrayDeque() }.addFirst(input[idx][i + 1]) } } } for (idx in start until input.size) { val (k, from, to) = input[idx].split(" ").slice(setOf(1, 3, 5)).map(String::toInt) for (t in 0 until k) { val tmp = stacks[from]!!.removeLast() stacks[to]!!.addLast(tmp) } } return stacks.map { it.value.last() }.joinToString("") } fun solvePart2(input: List<String>): String { val stacks = HashMap<Int, MutableList<Char>>() var start = 0 for (idx in input.indices) { if (input[idx] == "") { start = idx + 1 break } for (i in 0 until input[idx].length step 4) { if (input[idx][i] == '[' && input[idx][i + 2] == ']') { stacks.getOrPut(i / 4 + 1) { ArrayList() }.add(input[idx][i + 1]) } } } stacks.forEach { it.value.reverse() } for (idx in start until input.size) { val (k, from, to) = input[idx].split(" ").slice(setOf(1, 3, 5)).map(String::toInt) stacks[to]!!.addAll(stacks[from]!!.takeLast(k)) for (t in 0 until k) { stacks[from]!!.removeLast() } } return stacks.map { it.value.last() }.joinToString("") } val testInput = readInput("input/Day05_test") check(solvePart1(testInput) == "CMZ") check(solvePart2(testInput) == "MCD") val input = readInput("input/Day05_input") println(solvePart1(input)) println(solvePart2(input)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
2,191
AoC-2022-kotlin
Apache License 2.0
src/main/kotlin/g2501_2600/s2547_minimum_cost_to_split_an_array/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2501_2600.s2547_minimum_cost_to_split_an_array // #Hard #Array #Hash_Table #Dynamic_Programming #Counting // #2023_07_06_Time_400_ms_(100.00%)_Space_50.3_MB_(100.00%) class Solution { fun minCost(nums: IntArray, k: Int): Int { val n = nums.size val dp = IntArray(n) dp.fill(-1) val len = Array(n) { IntArray(n) } for (r in len) r.fill(0) for (i in 0 until n) { val count = IntArray(n) count.fill(0) var c = 0 for (j in i until n) { count[nums[j]] += 1 if (count[nums[j]] == 2) c += 2 else if (count[nums[j]] > 2) c += 1 len[i][j] = c } } return f(0, nums, k, len, dp) } private fun f(ind: Int, nums: IntArray, k: Int, len: Array<IntArray>, dp: IntArray): Int { if (ind >= nums.size) return 0 if (dp[ind] != -1) return dp[ind] dp[ind] = Int.MAX_VALUE for (i in ind until nums.size) { val current = len[ind][i] + k val next = f(i + 1, nums, k, len, dp) dp[ind] = dp[ind].coerceAtMost(current + next) } return dp[ind] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,203
LeetCode-in-Kotlin
MIT License
src/algorithms.kt
BenjaminEarley
151,190,621
false
null
import ConsList.Cons import ConsList.Nil import ZipperList.Cell import ZipperList.Empty fun binarySearch(a: Array<Int>, target: Int): Int { tailrec fun loop(min: Int, max: Int): Int = if (max < min) -1 else { val guess = listOf(min, max).average().toInt() when { a[guess] < target -> loop(guess + 1, max) a[guess] > target -> loop(min, guess - 1) else -> guess } } return loop(0, a.size - 1) } fun selectionSort(a: Array<Int>): Array<Int> { fun getSmallestIndex(b: Array<Int>): Int { var index = 0 var x = b[0] for (i in 1 until b.size) { if (x > b[i]) { x = b[i] index = i } } return index } fun Array<Int>.swap(index1: Int, index2: Int): Array<Int> = let { val temp = it[index1]; it[index1] = it[index2]; it[index2] = temp; it } var ordered: Array<Int> = a for (i in 0 until ordered.size - 1) { val value = ordered[i] val potential = getSmallestIndex(ordered.sliceArray(i + 1 until ordered.size)) if (ordered[potential + i + 1] < value) ordered = ordered.swap(i, potential + i + 1) } return ordered } fun insertionSort(a: Array<Int>): Array<Int> { for (j in 1 until a.size) { var i = j - 1 val processedValue = a[j] while ((i >= 0) && (a[i] > processedValue)) { a[i + 1] = a[i] i-- } a[i + 1] = processedValue } return a } fun insertionSort2(a: Iterator<Int>): Iterator<Int> { fun insert(left: ZipperList<Int>, focus: Int): ZipperList<Int> = when (left) { is Empty -> Cell(focus, Empty) is Cell -> { if (left.head > focus) Cell(left.head, insert(left.tail, focus)) else Cell(focus, left) } } tailrec fun loop(c: ZipperCursor<Int>): ZipperList<Int> = when (c.right) { is Empty -> insert(c.left, c.focus) is Cell -> loop(ZipperCursor(insert(c.left, c.focus), c.right.head, c.right.tail)) } return loop(a.toZipper() ?: return emptyArray<Int>().iterator()) .toIterator().asSequence().toList().asReversed().iterator() } fun mergeSort(list: List<Int>): List<Int> { fun merge(left: ConsList<Int>, right: ConsList<Int>): ConsList<Int> = when { left is Nil -> right right is Nil -> left else -> { val leftHead = (left as Cons).head val rightHead = (right as Cons).head if (leftHead < rightHead) Cons(leftHead, merge(left.tail, right)) else Cons(rightHead, merge(left, right.tail)) } } fun sort(l: ConsList<Int>): ConsList<Int> { val n = l.size() / 2 return if (n == 0) l else { val (left, right) = l.split(n) merge(sort(left), sort(right)) } } return sort(list.toConsList()).toList() }
0
Kotlin
0
0
1a4278273f3d79d4e5bb7054d0e5fb91274e871c
3,082
Functional_Kotlin
MIT License
src/main/kotlin/com/rtarita/days/Day6.kt
RaphaelTarita
724,581,070
false
{"Kotlin": 64943}
package com.rtarita.days import com.rtarita.structure.AoCDay import com.rtarita.util.day import com.rtarita.util.sqr import kotlinx.datetime.LocalDate import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToInt import kotlin.math.sqrt /** * The distances resulting in holding down the button for n milliseconds follow a parabola defined as * `-square(n) + time * n`. The current record distance in this mathematical representation is a * line that is parallel to the n-Axis. The equation `-square(n) + time * n == recordDist` yields * two solutions, which are precisely the lower and upper bound of the possible solutions. The equation * can be solved using the quadratic formula. */ object Day6 : AoCDay { private val SPACE_REGEX = Regex("\\s+") override val day: LocalDate = day(6) private fun parseInput(input: String): List<Pair<Long, Long>> { val (time, distance) = input.lines() .map { line -> line.trimStart { !it.isDigit() } .split(SPACE_REGEX) .map { it.toLong() } } return time.zip(distance) } private fun solveQuadratic(a: Long, b: Long, c: Long): Pair<Double, Double>? { val discriminant = sqr(b) - 4 * a * c return if (discriminant < 0) { null } else { val root = sqrt(discriminant.toDouble()) ((-b + root) / 2 * a) to ((-b - root) / 2 * a) } } private fun rangeSize(lower: Double, upper: Double) = (ceil(upper).roundToInt() - 1) - (floor(lower).roundToInt() + 1) + 1 override fun executePart1(input: String) = parseInput(input).map { (time, recordDist) -> val (lower, upper) = solveQuadratic(-1, time, -recordDist) ?: error("unsolvable") rangeSize(lower, upper) } .reduce { a, b -> a * b } override fun executePart2(input: String): Any { val (time, recordDist) = input.lines() .map { line -> line.filter { it.isDigit() } .toLong() } val (lower, upper) = solveQuadratic(-1, time, -recordDist) ?: error("unsolvable") return rangeSize(lower, upper) } }
0
Kotlin
0
0
4691126d970ab0d5034239949bd399c8692f3bb1
2,225
AoC-2023
Apache License 2.0
src/commonMain/kotlin/io/github/offlinebrain/khexagon/algorythm/Pathfinding.kt
OfflineBrain
663,452,814
false
null
package io.github.offlinebrain.khexagon.algorythm import io.github.offlinebrain.khexagon.coordinates.AxisPoint /** * Represents a path tile with generic type `T`. * * @param T the type of objects that can be used for movement cost and heuristic calculations. */ interface PathTile<T> : AxisPoint, Walkable, MovementCost<T>, Heuristic<T> /** * Provides an interface to calculate the movement cost to a certain location. * * Supposed to be used on adjacent locations. * * @param T the type of the destination location. */ interface MovementCost<T> { infix fun moveCostTo(to: T): Double } /** * Provides an interface to determine if a path is walkable. */ interface Walkable { fun isWalkable(): Boolean } /** * Provides an interface to calculate the heuristic value to a certain location. * * @param T the type of the destination location. */ interface Heuristic<T> { infix fun heuristicTo(to: T): Int } /** * Applies the A* pathfinding algorithm on a given graph to find the shortest path from the start point [from] to the destination [to]. * * @param [from] The starting point in the graph. * @param [to] The destination point in the graph. * @param [neighbors] A function that takes a point and returns a list of its neighboring points. * @param [isWalkable] A function that takes a point and returns whether the point can be traversed or not. * @param [heuristic] A function that estimates the distance between two points. * @param [movementCost] A function that calculates the exact movement cost between two points. By default, it returns a constant cost of 1.0 for any pair of points or 0.0 if points are equal. * @return a list of points representing the shortest path from [from] to [to] based on the provided functions. Returns an empty list if no path is found. */ fun <T> aStar( from: T, to: T, neighbors: (T) -> List<T>, isWalkable: (T) -> Boolean, heuristic: (T, T) -> Int, movementCost: (T, T) -> Double ): List<T> where T : AxisPoint { if (!isWalkable(from) || !isWalkable(to)) return emptyList() if (from.q == to.q && from.r == to.r) return listOf(from) val moveCost = movementCost(from, from) val openSet = mutableListOf(from to moveCost) val costs = mutableMapOf(from to moveCost) val path = mutableMapOf<T, T>() while (openSet.isNotEmpty()) { val current = openSet.removeLast() if (current.first == to) { break } neighbors(current.first).filter { isWalkable(it) }.forEach { neighbor -> val previousCost = costs[neighbor] val newCost = (costs[current.first] ?: 0.0) + movementCost(current.first, neighbor) if (previousCost == null || newCost < previousCost) { costs[neighbor] = newCost val priority = newCost + heuristic(current.first, neighbor) openSet.apply { add(neighbor to priority) sortByDescending { it.second } } path[neighbor] = current.first } } } var backward: T? = path[to] ?: return emptyList() val result = mutableListOf(to) while (backward != null) { result.add(backward) backward = path[backward] } return result.reversed() } fun <T> aStar( from: T, to: T, neighbors: (T) -> List<T>, ): List<T> where T : PathTile<T> = aStar(from, to, neighbors, { it.isWalkable() }, { a, b -> a heuristicTo b }) { a, b -> a moveCostTo b } /** * A data class that implements a pathfinding algorithm on a graph represented by points of type `T` extending [AxisPoint]. * * @property origin The initial point or node. * @property maxMoveCost The maximum allowed movement cost. * @property neighbors A function that takes a point and returns a list of its neighboring points. * @property isWalkable A function that takes a point and returns whether it's traversable. * @property heuristic A heuristic function to estimate the distance between two points. * @property movementCost A function that calculates the exact movement cost between two points. By default, it returns a constant cost of 1.0 for any pair of points or 0.0 if points are equal. */ data class AccessibilityTrie<T>( val origin: T, val maxMoveCost: Int, val neighbors: (T) -> List<T>, val isWalkable: (T) -> Boolean, val heuristic: (T, T) -> Int, val movementCost: (T, T) -> Double ) where T : AxisPoint { private val accessMap: MutableMap<T, T> = mutableMapOf() /** * The set of all points accessible from the origin within [maxMoveCost]. */ val accessible: Set<T> get() = accessMap.keys init { build() } /** * Builds the accessMap considering the walkable nodes, neighbors, and costs. * Called automatically on initialization. */ fun build() { accessMap.clear() if (!isWalkable(origin)) return val moveCost = movementCost(origin, origin) val openSet = mutableListOf(origin to moveCost) val costs = mutableMapOf(origin to moveCost) while (openSet.isNotEmpty()) { val current = openSet.removeLast() if (current.second > maxMoveCost) { continue } neighbors(current.first).filter { isWalkable(it) }.forEach { neighbor -> val previousCost = costs[neighbor] val newCost = (costs[current.first] ?: 0.0) + movementCost(current.first, neighbor) if (previousCost == null || newCost < previousCost) { costs[neighbor] = newCost val priority = newCost + heuristic(current.first, neighbor) openSet.apply { add(neighbor to priority) sortByDescending { it.second } } accessMap[neighbor] = current.first } } } } /** * Retrieves a list representing the path from the origin to the specified point using the predecessors stored in the access map. * * @param point The point to which you need the path from the origin. * @return a list of points forming the path from the origin to the specified point. * An empty list is returned if no path exists. */ operator fun get(point: T): List<T> { if (!isWalkable(point)) return emptyList() if (point == origin) return listOf(origin) val result = mutableListOf<T>() var backward: T? = accessMap[point] ?: return result result.add(point) while (backward != null) { result.add(backward) backward = accessMap[backward] } return result.reversed() } companion object { operator fun <T> invoke( origin: T, maxMoveCost: Int, neighbors: (T) -> List<T>, ): AccessibilityTrie<T> where T : PathTile<T> = AccessibilityTrie( origin, maxMoveCost, neighbors, isWalkable = { it.isWalkable() }, heuristic = { a, b -> a heuristicTo b }, movementCost = { a, b -> a moveCostTo b } ) } }
0
Kotlin
0
1
1bf3b6f073fbad98eeb10ea83730e883cf8ed7d5
7,319
khexagon
MIT License
src/aoc2022/Day03.kt
miknatr
576,275,740
false
{"Kotlin": 413403}
package aoc2022 fun main() { println('A'.code) println('Z'.code) println('a'.code) println('z'.code) fun Char.getPriority(): Int = if (this.code >= 97) this.code - 96 else this.code - 65 + 27 fun part1(input: List<String>) = input .filter { it != "" } .map { line -> Pair( line .slice(0 until line.length / 2) .toSet(), line .slice(line.length / 2 until line.length) .toSet() ) } .map { backpack -> backpack.first .intersect(backpack.second) .first() } .sumOf { onlyItem -> onlyItem.getPriority() } fun part2(input: List<String>) = input .filter { it != "" } .chunked(3) .map { elvesTrio -> elvesTrio[0].toSet() .intersect(elvesTrio[1].toSet()) .intersect(elvesTrio[2].toSet()) .first() } .sumOf { onlyItem -> onlyItem.getPriority() } val testInput = readInput("Day03_test") part1(testInput).println() part2(testInput).println() val input = readInput("Day03") part1(input).println() part2(input).println() }
0
Kotlin
0
0
400038ce53ff46dc1ff72c92765ed4afdf860e52
1,295
aoc-in-kotlin
Apache License 2.0
src/Day03.kt
nordberg
573,769,081
false
{"Kotlin": 47470}
fun main() { fun prio(c: Char): Int { val priority = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" return priority.indexOf(c) + 1 } fun part1(input: List<String>): Int { return input.sumOf { val (firstHalf, secondHalf) = it.chunked(it.length / 2) println("$firstHalf $secondHalf") val intersection = firstHalf.toCharArray().intersect(secondHalf.toHashSet()) prio(intersection.first()) } } fun part2(input: List<String>): Int { val groupsOfThree = input.chunked(3) return groupsOfThree.sumOf { val firstIntersection = it[0].toCharArray().toHashSet() intersect it[1].toCharArray().toHashSet() val secondIntersection = it[2].toCharArray().toHashSet() intersect firstIntersection prio(secondIntersection.first()) } } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") //check(part1(testInput) == 1) val input = readInput("Day03") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3de1e2b0d54dcf34a35279ba47d848319e99ab6b
1,137
aoc-2022
Apache License 2.0
src/main/kotlin/g2401_2500/s2471_minimum_number_of_operations_to_sort_a_binary_tree_by_level/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2471_minimum_number_of_operations_to_sort_a_binary_tree_by_level // #Medium #Breadth_First_Search #Tree #Binary_Tree // #2023_07_05_Time_789_ms_(100.00%)_Space_63.6_MB_(100.00%) import com_github_leetcode.TreeNode import java.util.ArrayDeque /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun minimumOperations(root: TreeNode): Int { val q = ArrayDeque<TreeNode?>() var count = 0 if (root.left != null && root.right != null && root.left!!.`val` > root.right!!.`val`) { count++ } if (root.left != null) { q.add(root.left) } if (root.right != null) { q.add(root.right) } while (q.isNotEmpty()) { var size = q.size val al: MutableList<Int> = ArrayList() while (size-- > 0) { val node = q.poll()!! if (node.left != null) { al.add(node.left!!.`val`) q.add(node.left) } if (node.right != null) { al.add(node.right!!.`val`) q.add(node.right) } } count += helper(al) } return count } private fun helper(list: MutableList<Int>): Int { var swaps = 0 val sorted = IntArray(list.size) for (i in sorted.indices) { sorted[i] = list[i] } sorted.sort() val ind: MutableMap<Int, Int?> = HashMap() for (i in list.indices) { ind[list[i]] = i } for (i in list.indices) { if (list[i] != sorted[i]) { swaps++ ind[list[i]] = ind[sorted[i]] list[ind[sorted[i]]!!] = list[i] } } return swaps } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,020
LeetCode-in-Kotlin
MIT License
src/Day01.kt
mhuerster
572,728,068
false
{"Kotlin": 24302}
fun main() { fun getElvesFromInput(input: List<String>): List<List<Int>> { val groupSeparator = ",\\s,\\s".toRegex() val itemSeparator = ",\\s+".toRegex() val groups = input.joinToString() val elves = groups.split(groupSeparator).map { it.split(itemSeparator).map { it.toInt() } }// return(elves) } fun part1(input: List<String>): Int { val elves = getElvesFromInput(input) val calories = elves.map { it.sum() } val result = calories.max() return(result) } fun part2(input: List<String>): Int { val elves = getElvesFromInput(input) val calories = elves.map { it.sum() } return(calories.sortedDescending().take(3).sum()) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_sample") val input = readInput("Day01") check(part1(testInput) == 24000) check(part2(testInput) == 45000) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f333beaafb8fe17ff7b9d69bac87d368fe6c7b6
1,030
2022-advent-of-code
Apache License 2.0
src/Day04.kt
li-xin-yi
573,617,763
false
{"Kotlin": 23422}
fun main() { fun solvePart1(input: List<String>): Int { var res = 0 for (line in input) { val (interval1, interval2) = line.split(",") val (a, b) = interval1.split("-").map(String::toInt) val (c, d) = interval2.split("-").map(String::toInt) if ((a <= c && b >= d) || (a >= c && b <= d)) { res += 1 } } return res } fun solvePart2(input: List<String>): Int { var res = input.size for (line in input) { val (interval1, interval2) = line.split(",") val (a, b) = interval1.split("-").map(String::toInt) val (c, d) = interval2.split("-").map(String::toInt) if ((b < c) || (a > d)) { res -= 1 } } return res } val testInput = readInput("input/Day04_test") check(solvePart1(testInput) == 2) check(solvePart2(testInput) == 4) val input = readInput("input/Day04_input") println(solvePart1(input)) println(solvePart2(input)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
1,074
AoC-2022-kotlin
Apache License 2.0
app/src/y2021/day06/Day06Lanternfish.kt
henningBunk
432,858,990
false
{"Kotlin": 124495}
package y2021.day06 import common.Answers import common.AocSolution import common.annotations.AoCPuzzle fun main(args: Array<String>) { Day06Lanternfish().solveThem() } @AoCPuzzle(year = 2021, day = 6) class Day06Lanternfish : AocSolution { override val answers = Answers(samplePart1 = 5934, samplePart2 = 26984457539, part1 = 355386, part2 = 1613415325809) override fun solvePart1(input: List<String>): Any = Population(input.first()) .apply { ageBy(days = 80) } .size override fun solvePart2(input: List<String>): Any = Population(input.first()) .apply { ageBy(days = 256) } .size } class Population(initial: String) { var population: MutableMap<Int, Long> = mutableMapOf() val size: Long get() = population.toList().sumOf { (_, amount) -> amount } init { initial.split(',').map { it.toInt() }.forEach { population[it] = population.getOrDefault(it, 0L) + 1L } } fun ageBy(days: Int) { repeat(days) { ageOneDay() } } private fun ageOneDay() { var populationOnNextDay: MutableMap<Int, Long> = mutableMapOf() population.forEach { (daysUntilBirth, amountOfFish) -> val nextDaysUntilBirth = when (daysUntilBirth) { 0 -> { populationOnNextDay.birth(amountOfFish) 6 } else -> daysUntilBirth - 1 } populationOnNextDay.addFish(daysUntilBirth = nextDaysUntilBirth, amountOfFish) } population = populationOnNextDay } private fun MutableMap<Int, Long>.addFish(daysUntilBirth: Int, amountOfFish: Long) { this[daysUntilBirth] = getOrDefault(daysUntilBirth, 0L) + amountOfFish } private fun MutableMap<Int, Long>.birth(amount: Long) { this[8] = amount } }
0
Kotlin
0
0
94235f97c436f434561a09272642911c5588560d
1,899
advent-of-code-2021
Apache License 2.0
src/main/kotlin/ctci/chaptereight/PermutationsWithoutDups.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package ctci.chaptereight // 8.7 - page 135 // Write a method in Kotlin to compute all the permutations of a string of unique characters. fun main() { val permutations = permutations("abc") for (permutation in permutations) { println(permutation) } } //This implementation uses a recursive approach to compute all the permutations of the input string. The base case is // when the input string has only one character, in which case there is only one possible permutation. For longer // strings, the method iterates through each character in the string, and for each character, it computes all the // permutations of the remaining characters by recursively calling the method. Then, it concatenates the current // character with each of the permutations of the remaining characters, and adds the result to the list of // permutations. Finally, the method returns the list of permutations. fun permutations(str: String): List<String> { val permutations = mutableListOf<String>() if (str.length == 1) { permutations.add(str) return permutations } for (i in 0 until str.length) { val c = str[i] val remaining = str.substring(0, i) + str.substring(i + 1) val subPermutations = permutations(remaining) for (subPerm in subPermutations) { permutations.add(c + subPerm) } } return permutations } //The space complexity of the permutations method is O(n!) since it generates all possible permutations of a string, // which is a total of n! permutations for a string of length n. The time complexity of the method is also O(n!) as // it uses a backtracking algorithm to generate all permutations, which takes O(n!) time. // Time complexity of generating all permutations of a string is always O(n!) for any algorithm, as the number of // permutations is n! and generating each one takes O(n) time.
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
1,903
dsa-kotlin
MIT License
src/y2017/3.kt
chesterm8
123,070,176
false
null
package y2017 import kotlin.math.* fun main(args: Array<String>) { val base = ceil(sqrt(input3.toDouble())).toInt() //Level of the loop we are on val stepsToThisLoop = base / 2 val total = (base + 1).toDouble().pow(2) //Highest number in this loop val offset = total - input3 //Distance of current number from max in this loop val stepsToCorner = offset % base //Number of steps required to get from our number to corner val stepsToCentre = abs(((base + 1) / 2) - stepsToCorner) //Number of steps to get from our number to centre val result1 = floor(stepsToThisLoop + stepsToCentre).toInt() println("Result 1: $result1") println("Result 2: " + calcPart2(base)) } private fun calcPart2(base: Int): Int { val loop = MutableList(base, { MutableList(base, { 0 }) }) var x = base / 2 var y = base / 2 loop[x][y] = 1 var squareSize = 2 while (loop[x][y] < input3) { x++ //Go up var guard = y + squareSize while (y < guard) { loop[x][y] = sumSurroundingCells(loop, x, y) y++ if (loop[x][y] > input3) { return loop[x][y] } } y-- //Go left guard = x - squareSize while (x > guard) { x-- loop[x][y] = sumSurroundingCells(loop, x, y) if (loop[x][y] > input3) { return loop[x][y] } } //Go down guard = y - squareSize while (y > guard) { y-- loop[x][y] = sumSurroundingCells(loop, x, y) if (loop[x][y] > input3) { return loop[x][y] } } //Go right guard = x + squareSize while (x < guard) { x++ loop[x][y] = sumSurroundingCells(loop, x, y) if (loop[x][y] > input3) { return loop[x][y] } } squareSize += 2 } return -1 } fun sumSurroundingCells(loop: MutableList<MutableList<Int>>, x: Int, y: Int): Int { return loop[x + 1][y] + loop[x + 1][y + 1] + loop[x][y + 1] + loop[x - 1][y + 1] + loop[x - 1][y] + loop[x - 1][y - 1] + loop[x][y - 1] + loop[x + 1][y - 1] }
0
Kotlin
0
0
bed839efa608f83cd32c52a95fc0f5634d64aa2b
2,239
advent
MIT License
src/main/kotlin/aoc2023/day1.kt
sodaplayer
726,524,478
false
{"Kotlin": 4129}
package aoc2023 import utils.loadInput fun main() { val lines = loadInput("/2023/day1") .bufferedReader() .readLines() // Part 1 val numerals = lines.map { line -> line.filter { it.isDigit() } } val pairs = numerals .map { "${it.first()}${it.last()}" } .map(String::toInt) val sum = pairs.sum() println(sum) lines.sumOf { line -> val singles = line.windowed(1).mapIndexed { i, s -> i to if (s[0].isDigit()) s.toInt() else null }.filter { it.second != null } val threes = line.windowed(3).mapIndexed { i, s -> i to when (s) { "one" -> 1 "two" -> 2 "six" -> 6 else -> null } }.filter { it.second != null } val fours = line.windowed(4).mapIndexed { i, s -> i to when (s) { "four" -> 4 "five" -> 5 "nine" -> 9 else -> null } }.filter { it.second != null } val fives = line.windowed(5).mapIndexed { i, s -> i to when (s) { "three" -> 3 "seven" -> 7 "eight" -> 8 else -> null } }.filter { it.second != null } (singles + threes + fours + fives) .sortedBy { it.first } .let { (it.first().second!! * 10) + it.last().second!! } }.also { println(it) } }
0
Kotlin
0
0
c0937a8288f8466a28932c8cf8e3ba454ac8c4ac
1,490
aoc2023-kotlin
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2019/Day10.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2019 import com.s13g.aoc.Result import com.s13g.aoc.Solver import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.sqrt /** https://adventofcode.com/2019/day/10 */ class Day10 : Solver { override fun solve(lines: List<String>): Result { // Parse Input val field = hashSetOf<XY>() for ((y, line) in lines.withIndex()) { for ((x, c) in line.withIndex()) { if (c == '#') { field.add(XY(x, y)) } } } // Find the asteroid with the best visibility. var mostSeen = 0 var bestAsteroid = XY(0, 0) for (a in field) { val count = countVisible(a, field) if (count > mostSeen) { mostSeen = count bestAsteroid = a } } // Create a set without the selected asteroid. val fieldB = field.toMutableSet() fieldB.remove(bestAsteroid) // Add angle and dinstanceof every asteroid to selected one. addAuxData(bestAsteroid, fieldB) // Sort according to Part B rules. val twoHundred = sortB(fieldB.sortedWith(partBComparator))[199] // Select 200th to be destroyed. val solutionB = twoHundred.x * 100 + twoHundred.y return Result("$mostSeen", "$solutionB") } /** Sort primarily by angle, but then ensure same-angle items get sorted next-round. */ private fun sortB(sorted: List<XY>): List<XY> { val angled = mutableListOf<Angled>() angled.add(Angled(sorted[0].angle, mutableListOf(sorted[0]))) for (i in 1 until sorted.size) { if (sorted[i - 1].angle == sorted[i].angle) { angled.last().items.add(sorted[i]) } else { angled.add(Angled(sorted[i].angle, mutableListOf(sorted[i]))) } } val result = mutableListOf<XY>() while (result.size < sorted.size) { for (a in angled) { if (a.items.isNotEmpty()) { result.add(a.items.removeAt(0)) } } } return result } private fun addAuxData(a: XY, field: Set<XY>) { for (b in field) { val dX = b.x - a.x val dY = b.y - a.y b.angle = angle(dX, dY) val adX = abs(dX) val adY = abs(dY) b.distance = sqrt((adX * adX + adY * adY).toDouble()) } } private fun angle(dX: Int, dY: Int) = Math.PI - atan2(dX.toDouble(), dY.toDouble()) /** Count all asteroids directly visible from 'a'. */ private fun countVisible(a: XY, field: Set<XY>): Int { // Asteroids with the same angle only count as one (the others will be // hidden behind) val anglesFound = mutableSetOf<Double>() for (b in field) { if (a == b) continue anglesFound.add(angle(b.x - a.x, b.y - a.y)) } return anglesFound.size } private data class Angled(val angle: Double, val items: MutableList<XY>) private data class XY(val x: Int, val y: Int, var angle: Double = 0.0, var distance: Double = 0.0) private val partBComparator = Comparator<XY> { a, b -> when { a.angle < b.angle -> -1 a.angle > b.angle -> 1 else -> when { a.distance < b.distance -> -1 a.distance > b.distance -> 1 else -> 0 } } } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
3,140
euler
Apache License 2.0
solutions/src/PacificAtlanticWaterFlow.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/pacific-atlantic-water-flow/ */ class PacificAtlanticWaterFlow { fun pacificAtlantic(matrix: Array<IntArray>): List<List<Int>> { if (matrix.isEmpty()) { return listOf() } var pathToAtlanticFromPacific = mutableSetOf<Pair<Int,Int>>() var pathToPacificFromAtlantic = mutableSetOf<Pair<Int,Int>>() val pathToFromBoth = mutableSetOf<Pair<Int,Int>>() val m = matrix.size val n = matrix[0].size //Pacific for (i in matrix.indices) { val currentPoint = Pair(i,0) dfs(pathToAtlanticFromPacific,currentPoint,matrix,Int.MIN_VALUE) } for (i in matrix[0].indices) { val currentPoint = Pair(0,i) dfs(pathToAtlanticFromPacific,currentPoint,matrix,Int.MIN_VALUE) } for (i in matrix.indices) { val currentPoint = Pair(i,matrix[0].lastIndex) dfs(pathToPacificFromAtlantic,currentPoint,matrix,Int.MIN_VALUE) } for (i in matrix[0].indices) { val currentPoint = Pair(matrix.lastIndex,i) dfs(pathToPacificFromAtlantic,currentPoint,matrix,Int.MIN_VALUE) } for (i in matrix.indices) { for (j in matrix[0].indices) { val currentPoint = Pair(i,j) if (pathToAtlanticFromPacific.contains(currentPoint) && pathToPacificFromAtlantic.contains(currentPoint)) { pathToFromBoth.add(currentPoint) } } } return pathToFromBoth.map { listOf(it.first,it.second) } } private fun dfs(visited: MutableSet<Pair<Int,Int>>, currentPoint: Pair<Int, Int>, matrix: Array<IntArray>, height: Int) { if (currentPoint.first < 0 || currentPoint.second < 0 || currentPoint.first >= matrix.size || currentPoint.second >= matrix[0].size || matrix[currentPoint.first][currentPoint.second] < height) { return } visited.add(currentPoint) listOf( Pair(currentPoint.first+1,currentPoint.second), Pair(currentPoint.first-1,currentPoint.second), Pair(currentPoint.first,currentPoint.second+1), Pair(currentPoint.first,currentPoint.second-1) ) .filter { !visited.contains(it) } .forEach { dfs(visited,it,matrix,matrix[currentPoint.first][currentPoint.second]) } } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
2,469
leetcode-solutions
MIT License
src/jvmMain/kotlin/day01/initial/Day01.kt
liusbl
726,218,737
false
{"Kotlin": 109684}
package day01.initial // Took 48 minutes to solve fun main() { // day1part1() // Solution: 55816 day1part2() // Solution: 54980 } fun day1part1() { val input = inputDay1 // val input = """ // 1abc2 // pqr3stu8vwx // a1b2c3d4e5f // treb7uchet // """.trimIndent() val lines = input.lines() val result = lines.sumOf { line -> val firstDigit = line.first { it.isDigit() } val lastDigit = line.last { it.isDigit() } "${firstDigit.digitToInt()}${lastDigit.digitToInt()}".toInt() } println(result) } // 47857 is not right answer! // 49247 is not right answer! // 49209 is not right answer! // 54961 is not right fun day1part2() { val input = inputDay1 // val input = "6hznsq5qjcjsvgnl" // val input = "twohznsqfiveqjcjsvgnl" //val input = "nineseven2sixnineqd" // val input = """ // two1nine // eightwothree // abcone2threexyz // xtwone3four // 4nineeightseven2 // zoneight234 // 7pqrstsixteen // """.trimIndent() val lines = input.lines() val map = mapOf( // "zero" to 0, "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9 ) val fakeNumbers = map.keys val result = lines.sumOf { line -> val closestNumber = if (fakeNumbers.any { line.contains(it) }) { fakeNumbers.minBy { number -> var index = line.indexOf(number) if (index == -1) { index = Int.MAX_VALUE } index } } else { null } val closestIndex = closestNumber?.let { line.indexOf(it) } ?: Int.MAX_VALUE var firstDigitIndex = line.indexOfFirst { it.isDigit() } if (firstDigitIndex == -1) { firstDigitIndex = Int.MAX_VALUE } val firstValue = if (closestIndex <= firstDigitIndex) { map[closestNumber]!! } else { line[firstDigitIndex].digitToInt() } val farthestNumber = fakeNumbers.maxBy { number -> line.lastIndexOf(number) } val farthestIndex = line.lastIndexOf(farthestNumber) val lastDigitIndex = line.indexOfLast { it.isDigit() } val lastValue = if (farthestIndex >= lastDigitIndex) { map[farthestNumber]!! } else { line[lastDigitIndex].digitToInt() } "${firstValue}${lastValue}".toInt() } println(result) } // 6hznsq5qjcjsvgnl is wrong // Check what happens when there are no numbers as text! Or vce versa! val inputDay1 = """ hcpjssql4kjhbcqzkvr2fivebpllzqbkhg 4threethreegctxg3dmbm1 1lxk2hfmcgxtmps89mdvkl sixbfjblhsjr3 soneighttwo39ktl132 sqd1fivenfsmpsmjtscfivedzxfhnbbj8six 9oneonetwofiveseven42 7mhpslddjtwo9sixkzdvqzvggvfoursdvd onetwothreextbtpkrcphhp4kfplhqdvp9 89l991eightttxtj3 7znvzpdnnnfsevennrvlhseven16b 5eight8579 6twotwo18eightthreeeight 5fourthreesbgsix6two nineoneh841dxnrvcmtwo 9one7three9kbrdcdeighttqmgg vsrsixfiveninestndvtfqmr7 six5eight prvdoneqmsnstjgq7bdshdninenine9 3715nineeighthxnqxhg4ch zvdhmnvnineqjghs93bmmxrtxhrvsksqgfive 6hznsq5qjcjsvgnl 51gzmkn5 2rscfiveonetwoonexndftfive 5gkxjcskc89eight onethreeoneeightqskd4zhr 8dnkzpsfzrqljhkx6one threenine41tczlqlsjjrkhsjm3jqhgscgspx sevennine4dkkqrrjcpfourckzxj71one nineseven2sixnineqd eight72threefivefour9onefive gprffive3kksp qcl27four4 sfdreight4ninesix5 1756gvjdggpchc9 threerzcxhlvdjkhtlxlg6ninetwonine1 thnine5 twoninejxxm1one nc73threetwoeight s2sixbnsmngsclg 6tplzllbthreecljqhtgqlkxnl 4four4 ntxmgvkm9 5fourslt8gqdrdsseven6six fourfour26 263eightfivefthkfxfxnfms2 716 twodgksqsdtrsrpeight8five1 jdhtxp1nine8jrxrrkc12six3 2gmmtgzstg1rbsix threemhmfivevg6sixlppbjmmninej 9eighthvxnlvthqjtpsjnleightwokq three8threeeightmcnvlmj7 sixmn5 8jctlksix fkrxrsseven6dcxzhdmvtg sixxgrnqk8qvgrqbs skprzqrt3h65eighteightdlpljhnjdp onelpfdt669hrzninethree 3ninehgveightzppzljfourfour4 838onejonehznckplj5nine lrdtwo61 niner5kqzqg 4eight8seventwo3 fvbrtpbcfive24 twoczldjcsix1six 9fourklmzjmnlgtvh five7nine2nvjbprppthnine8 tmht6mfjnnpznrv6jscqfjxkvtgklmprsix svpqzpj9sixsixxnvbprh1 eight8two47g11 7qxbfj5c 2hzcmzl7 4gbkshmmksfseven 8sevenone oneseven1three 9three2fjldqmdhv 3vfsqqzrpzq38twotwondxrc sixbgz1four trzvzjzeight7sixdgq41 94rj2 twofour3tkjjvjsfourz3 cxtgfmqddm9five61f ninesfvfmrk7vrgddhzvh11onethree zhdbmjhsfv5nkkllpthree88seven 69zlsvkk2six 576dqcspgvd 7flqjn9 eightqxsix4fiveeightfive oneeight9onemll8ccgrrqvrp 7qdscnine5two eightfive5threekkrb741xgnndtvzd 6xpdgng622cplsixone ninesix4jxxgjppthree9six 87sixtwotcjlss njlfxvcxbpmk6ttdng sevenzcprvz4eightnk6ninefourtwo 2twomvdjvrhrsgrqhp eightonehtmvfvxeight2onettnkt ngbtlr8five5fourtwotwojsdl 39sixthree9 4ntgdsbshd32 ninetwo5htqnmctjkxrttgtdfone bckgxxpreight4eightbpchtxv8seven twoeight2sxnxsfkxqkbsix one8kjtgoneeightsdcmrllcfiveqxsj7 gsfmgl4one43 zthm8cmmb83twotwothree seventgd6 sixphptdkzcqsixlgztbffhs5 2onenine9sevenonefourfvd 1djkqqd slfldflseven6five85tvxbzvmjvjhpbnqtfxtvcfc six2kseven seven7464 zcslbttpgk3foureightone5 4oneone4453 fivex6lz zceightwobvhfqqzngtctgsq3rjzmtnmbx7xtc zxrxseven7ncr5m4 7ninelzrrzmlfourpssbjpkckj9 6vbrpprjfive3twovfklfh7 9cgkqfgccl5fivezlhcfgvm bttvvjkgp6clntnrksthreeeight7 threesix8eight4foureightkjxjfgxlcfqnh three5foursevenlhlmrzrdvxthreeglfvksgmxlrz c48seventhree sevenddgcqkgkr9fourppxqzpqxpkzjpcc51rh 3rn2zhhth 628nine seven86four 7bdqmrbdnzbnine nine621rlqzseven 73two rnbchhfk6884fivejtr5twonet qpjlhpnxpnszsrgglpnlclml5qone 3threeninesixdsdsjvz vmeightbtzkbvdjbcqsx5mfqft8sevensl jzvqqfzxrbfbhonetwo2knrhfl 1hjkmdchmone2twotwosix sixseven9 9two8zlkph 7twoz ninergqldrlxvn148zdpvgdrptvpg9nbbhgk szcspm5sixtwovtrmvrthreefour7oneightqqj foursixthreetwo7vjjdgcqrbh7 qgqhpnkzgrfivenine7foursixlgqcxzkcjr phhljpb4zsixpxt22four3 twogjbhrdrnl9six znbkscjpxnjzninesevenjnkdvckhgtwo5five xfkgbhrrpckrftonenxghthree2mz fivefdgxmb894ztnrljrr7kxzrvlxjcq2 nqblpkxmzcnhplrhcpv4 tq3nine9 bqxh6nine57 nine5fgvfmthreethree2 2bqvhb79rrczpptxbb4lmcdgkqm6 seven1eightnine3seventhreeeightlcsspsb one7llljbvzngchlnineoneeight dcztsfgsix8sixjlghbxslpd 4v365 5fiveqsgkf63fivefmp9seven 2gpnfjrnmcvjfninelmdzkvrmkjqvcp 2lznfour1threerqjtphnine nzvvxdbb8cpxjdlqxxfour joneight9nlqrzbthreeonenine four5hhnbcc8eight4eightbvhsfktmk sixfpnzsixgksix2s 9onefmkkgvzlzqpl7eight5 p8vceight1 dnkzmnvffthreefive7sevenxthdvzxxg nine4seven38mbhpcdfour 4seventwo7nine tqxhpxmgllzvbxlfvrmvsgkk3four6 xgvvninensvnjhglfng8ninefive threecqccjxnfournineeight7 fkone9bstvjhmrzh9qfhnxdld1 72gxqrns94 8xkqjdvone1339dgdzj 61zvcqrbdlgfivefourdcvpfpspbgxsmjbmblkz 4ninethreelbjtv89xnrt honeightfivegjbghjfbvlv78vcg sixjg5dbhkr2sevenjsbrvfv 6onenineone 688ninetwo 7tworbz jthreesixsixfive7fiveseven slnsnqn1glrhtrltdlvqmmgfrvckhkbxtsixxjlzqh msj8 pqz759rdgv2fourfjvdqvtn3 gscbthreethree3five7five68 3seven2 5llpcgxpcv85d39qqkxltchpc 2vflrsvfive7hnkmgfvnnsqz 7lfdthreegbkqsevenninefive5nj 3dsddfournine 2gghdftbmm9three jnfxg762 pgrzbonenine3eight959nine 4phpncp2six hvdvhprnsplknvdqlx9eightgcxvphpv4687 5ninembmxsppthreefour3 tworgvxntpjhr7xftlhponehzqdggmbhp62 sseven5two rhtzskrlvtmzgkszone1eightone 1tjrchtrxknstbmxh2zdpglqsxpdbnx4 8vvpsixbjxxkxclxchjvlvvqqdspqrgh 2six1gfzlrvxgfntqhjqd 8onenineeightsevendfhgbbmc1 six12three81vfive four153one 1dfbkfpnqvthreemqzlvcvdnsxgfourtwovhmf tll5xhqgfvq1hsphkgclrzhmlsqeight8 2three9sixkprzkzrdzjndjtptbmbsfjzplss 36onepntjtvpjfour4eightnine 8t2ninefour6sixjx gpnfthree16xj8fqx8n seven42eight5pzxvx 6ninefour zrmgttjv3vtnlmrkdtjgsdhc 8plhvcl8sblzgsd one77phjchvd5six 6gfour8bvgcxsrslrqf 36jllpvdrzqkdjvcts1fjkbfttbeightseven 4nine663mjtdlmqqrvsxnlhcz3six ftzqhxjvstrz18threepzrjkkqxrd4 mtbvkvsq38rzk xtldnjzthree7 3eightfive83nine32 3qpdkkdfxgvlktkkbtptnzqnzxl7four5 nine97eight212 mcvj6 sixninefkgntpsboneskphgqmvfq81 six7mdntzshzr6two81bklxmvcv qs7ft fiveqzpcskcrlninebnkvgthreengfbfhln3sevenfour spjqtwo4seventwo 8fqq 4eightgltkrzs64spgdrhf35 ffckrhfjb9 lv128sixninefive 6th sevenfive19eightninenine9seven jhmfcj6foursevenmszfjthree8gkpdpnnxbhj 8gvjzvvthreeseven33 threexnfjlnkmkt9seven949sixgsfdkzzk eightvfdjxhcvonebnzhrrqpvxdmnqxtzf7tzl fivesjkthreem6twokhdrsk1hz 641pqhdbzk99onetwofour sevenxsskzhcppdthree48 2two49qcnine sevenseventhreemqcgvbr8onernnone rkclvq4seven446dkjfpgtseightwobc two11pzzzxlqqqnfxxqg 5911four4three6six 7jsvdgx dvdffj2 8fourfourdbrbbnsjrzhj7 pzkckdkmfonefivetwozmdxrdmztwo6xd 48sevenninexqglbmcnbgsdtjtkcp nine4rbbnhlbmfseventwobqbrpvqssxcxqsmcg 7lgzfznxpspthreedgreightwopmf zmlhnk9bhtdqmxzvgdssixtvvrkpznvjpn 11five16snqbrtqbx gnvmgninenine83 onehnmbqdhtpmone29vhhxsxzkrnsix 9dpcdfxp3qtcktbbxglrfp2dsjdhbdncbtxj fouronezh9ninethreenine 6lrbthreemplnineseven five6onefourthree 3twoseven 8sixxtmqfxnp234twohsfr 6seven5ninenine3 sevenfivectsglsqstxjmgdsjrzfveight7 four9sevensixs7onergssqzfmbvbspmr jjeightwosix9fklkfxrfhjxksznine 39six ndbbqgqf3gvzczcdkpzxlxfjshr9 fourxmnjvrbkln8mnzvpthree5 foureight94 ztjplxlksevenseven8ktlb 94ngctc1hnvkpgxnmxxsp1 qchqnmstcsevenmkkmkxltzjtfsc798 97zkqgmsfive8 nqkjxjvvb7nqbgtr45sixsixgczfive pvrjzqpfoureightfivetwo4zcmmcffnlthree xktoneighttwoqljrsctbzxxqjtwo1ftsjczrsevenzqcdxtnktwo eightjbxnnhscg5seven gpjxfmgpdcmbc6 six1two9 g8fivethree kv5nine9fzkvznlfive 1ts86 75five6 threepbhr81 ninek2xhmcmtnrf eightkntlndvjskzfour5c threehpg7kgnjkgqzs87 4bnnpbgqpmfour2rjpthreeqmjrb9four four24three 2chsixsixqfcksfpqbt 2ztjdqjr4kpbxmcdpd xfive79two775eightwohm cpcjzmltqbtljgqqvnine78three 5sevenl 6tqsvxbbqx two9zkvfcllbpmmsscvn2fivecndc4 zqmz46fivejfljvptwosix 4zmhnjftwo1qmtqnhbtt sixsevenlknss2gzcvfshvfpkfcq9four6 81mjbktphdjfv6glzl five6cpctwofiveccsvlshnj three8lninexhlqmrhm 225onecrjvgckdbk6 nine154fivemtgvpfnlgx rtmpvkpdtgtm67five seventmcrfpsfpx9seven9five1seven9 rpftkjkhfive858mgjjgcpcsevenxrjfsxrr kvcthrfkcjvq3659 kxnbtm5 three7mmqmcpkz7sixhpzsxpknszbdr nine92csvcxhcr7 7fouronefive6qfml9eight5 489hdvzxfsgjngkzkdvfiveone3 6sgnbhjqqxqeightgmvtqdcfivesix dfphtx3 four8mcrszfpbbsjdmqpkjdgftqhskp9 7763tqbgpfltbrcgm6 9onevrnmrhtb5onethree3zbpdfznxbkbscjtjb pninethreetwo76tclssnpz 9fournine 63nxvsmhbngseventwosix djnine3jzghptvbpbseven9 2six16one 4eight2 four85nzfour69one 6625lbssixkrxsfshjp 2133eightzmfxcrlhngthree four7fcszmcs gtfqrjqxkxjkblfstrcszcrz3one1mjhbv vbpseven2four 2bngj8rdxvdcxdvj7four 2pqnineeighttworps twoszzrbzlqb8sixq six54bgrpn 17five 8threefrvhj19fivethree42 eightltpcssixtwoxms5ghf sevenonefive57mdpqbsdttdxxzctcqonethree threersqkhmgbsnlszskhslp57oneightlm six9threerzdsfkzj rskvrvxrxntspzstworpxfxqjrvnmhgsvcdthree21zvjlxd 3gdkcg vvvxkxhzeight295seven 1hqzbfzdzrbnz3x6 9fiveeightpvjpvdrl 7jcgbkthree3pqxlsixfour rxeightwonineqntwocpstsl3rtfbzzf5 trlsqtls9nxstgtnthree89 glxnkkssflcttone73 3drvbgb8eight 4937fouronemnqb 63vjtwo1fourcmvkmzpcsh four8119sixonedjmsqnxtwo 296544 ninefj3 three4ninefour8two fiveninethreethree3jss8lzlk gsjfrnhggktwobcnxfp96bt 27onerbtz4fourfour1 88three6five ffckjftkbrxfvzphmx4 2nqbxnqhxonesevengsxfspghjnglnl2 7hqtrhpdtnrhjx1sixeightknhzpmt five29xb1xhdf6bxbxptxfnrmmvn 2sixmmdkrzkgmvjvp1six9four 414fournine2kcjss 7kgb5twonine 66five3threerhx qzh9 ninexsdkngnzffourljrhrsrkx9sevenseven five6eightninetnonesix 6prgtmxjlztstbkcfour th9 jmtgprnslgn5 7twoeightgngmcqnpd 92eight8 twolvxlvg57 3ninethreeeightvgvbnk2f nsmeightwo8vjbgfhhrsixoneclzeight 9sixeight3nrbxqhtgskeightvmh8 threelsqvpd99chmlmtj xeightwo8 5pjjjkxxkfourjvgshnffjfjzd4 1px three8twoneh sevenfivephvqsqrzl524 2seven3 five45pktjrjnckjsixninezrcjxdrsmdc rxgxctwobtwo9ngbrhfjhqc six153bq 2qltqxkzeightonevxhsbglxk hjpltpcf1blmcfourtwonine467 42five9eight sixxhlfqh1ttp threetwosgbvsprq7j5threelcbx npgrkbnhbsmpbnshg46 ninenine9five8m pjdxpnddndfiveqjlsp5dtlstrlz tvc57krtsmhqqvfqxfpjkfbbddpg3five 1jkcfxpgmeight4qmhxrxjlghjsgnjptltvtwones eightkpgvbmlpfmrpfncnlb6rtltdbk4 3fxcmvxfivemntgvphgsspeightzsdjdrpxnlxs shsdpncrxhlxsevenmkjpznnkdjr5fournine four8qdrjtt1eightnineonefour3 three82gnpljsnbcn5 1ggfivethreefour75 one6vhx 5fivetwo2529 six2b2 fourninefiveseven9 fourfvrglnpdqfhsnine6zpsccbone1h 1eight8mzdtwofour 8eightwoq ninesixfivecpmlvqkk9three kgcmvpjvjbmnqbstwo45fiveoneightqhn xjrcgdblffour5onefive hqtxjnineqngjvsfour4gbt2 9sevenlxzlrvzln brcptklplkfj1vqdpbvbdsix96 four9oneldsvbfivesix 145tdpvphfbqknine ljflbdvxqhvmtsevensix4eight 6onefive8zlplrvfour 6mzhddbtg8sevennine48rnc fivesix3fivehtpdghxhm62 87123 fivethree43seven5pztchmt onegzqbbzm6vpm5 952eight 6four2srtnppsttwoninegvhctmqftp 5threethreeqxvspthn612phhseven 73four35pgtvz 5four29 79fiveeightone1 bgblfdstmvbsgsjgn281sevenzlrpmtxbeightwohcq 9sixpqttnvjmlscone5 6threesfourfivebkkx fivesixsevendlmldl3 bqvpfzghfoursxbndvlxzgbs5eighteight fbmcgpz83pztlsevenmjbxbpcxx three61rrthjdzs 8mx57sevennines7 3rmcfbldjhtcfhfnqsixkkpclcb5z ttsm16gzcqninetzkjzcrmcbkrn qkvonetwoseven486 lnqnbkpsix84 5sixrzl1hlgjcnzxsevenone7 99hcznvbnbnhssk 2cccbmqtzkfivenine7gnhjvcg5 8gxkkrgnpsx38kbxeightwonzm 8kdv pmxninecqeightfour1bgpqrrkjnhjfhtn nineseventwo6nine fpftlgd33sevenseven417 fourt3fivethree tfive8jzbjf5nkvttwonzpbplthc 41nineninethreeone8two 31mdlfvreightwotr 6twosixsixjlmcdqrpjthree4four g2 eightjjzh3ntlglxxpmcdrfnvkone ht6 eight9threehmbfnsjtpl5threergldqjfjheightdhbz vssqqrmvpnpjthreetwo8bhbbrfckmzvbc4 klgl8nntkkvhsixsixfour47fivetwonel ttwospnvbcr2ktkzcmftpfqxbbrfjxpxthree six7jcfjpjt6lgclnzonebzlbfsdbgbpzdkhx six824czjxvvkghdvzbzql6 vfivecjlm8seven fiveeightcrn6ldxqdqxkvntwo4 lzcqrfkct4ninesixfour5onenjqx ninenine1ttjjjmvrbs 4xcmqggjhts 8nkd1six mldzcxznine4seight eighthdthqc56 zhjffivefshkbqttwo5 lgngmclkjjvhncffivetwo5stcjnzlfjb2 glpflvjx6 one863sixfivenineninejrbvqlz 9fttbspxxtgbeight sglfjndn8mcfcftwotwo fxzsrvxhpvkseven3fivejmtjlpmb 9kphnine31ddxztph s39lffour3lkdbrks 3fhhth5hgsmh8vqspmmqcteight 6sevenhtclc 26njgdfive7onejtglghzlj kktgkzfcpd6nlfcvxvvfnine 8ccnhdd4czfgsevennineqszfqd onefour194xkj9eight8 onesixkvjr52 eightfive1rnrqjbfdck9hp8klq five69bcg threefivet136pfivefive seven7mhdhlhnmghklbbjcbseven93mgltsvnbx 9762threefive ctdssd25qnrztptmr 13fxdptkcgmxjfdccgcrj545gfzdlmcrpp sixjrlmbcfournrsvjltwo5sbbvsfxsr5 grkkhhpmx9 vbvmkmxnmvdxfive8jd 41141722 91xngpn3sfjkkfmjnthree zxsix17brp7twotwo nine39six6 llq7 83threethreeeightninethree svdbjstvsix6zqbppsfour two76fxzdss3sevenzg9htmnflgq fourtwotwo2ptb cbrv9 vrvdvq1psq2fourgvmqk 42sevendmdsonetwom75 fourhxr4ntppb 14btwo18 vzx8two 3sdmnlqsqkb9324xfdhptnine 6n4 5twoltmoneseven xmqdjlz5seveneightonetwoseven9 7three4eightzxlgpxhnrb4667 5nine39eight one1twojxjnb eightkmlhjvhhgd5pqkblcr jddsgdgdf16231sixmzfnpgvnqp hgkss234five691 kxzvnbnnine3n438xrt lhnfour9 fourrqktqhglbh3sevensevenfive89 xdrtgjlstwothreeqdhnpxhqtjkldfcbkqgxmlktfour7 fqoneightftbxksztshxssevensq1 3rtsnzspqrrqsfive 213 nine6three53bzrhpg6nine t3sxccdtzvhvfive 7762 7gxvmb 644eight5448two 8hxnqrqknththree3 3sevenfive9six fiveseven3threemkppbkpxhqgn czseven6418mqkjdlftcjfbjsd4 971ponenckqqv1 ninesevenmqqtcnl151seven2 7cmrgqbzfour 3six6fourdxbxngjonelzhjl txtfxpsmmlninefour8q8 pqhpzfive3four 7bggjsjrsv 49ninefive1fivenstnfcm5 seven2lrkhzgkj5fourtwo eightone7717eight9 fld3threetwo1three 1fourfive34onetszfour mxfdscrkbr8nine53seven onethree4fivemxlchhzqbzpvszj7 cjzhpqseven1fivetwofour78 9vsnhq22ksrrjmkhvdtwo 2lzkxtvseventhreeseventwo three8fourfivetwozgcrbrxdjk 87vqrqfvxrkdsix3 two3ccsix spjtwo5four 53gvzvzrnr29mrxljz onefourone1ninethreeeight66 6kbt 3nc5eight sevennkbjttdjv216m9djcrntqxx jzs333tjlhhroneklmmhflgvb two9seven2eight834five fivetwo4two3five five76 9sevenljjrrrrvfg tlttwonermnfrl94 xpbjpfzbkcgseven36fiveseven 7fivefourhvjf6seven 5three765nkj eight8nine8eighttwonine3 2fivesixvfhninehbsfklrhgzfourjdjgb cdthree6vbntwo9 sevenfpnmvftmpn8 qcbhgzqtrbcc6 ntvtxbdkcvtxdkzdz5kvkvdbxhdj5twojxfivekxvdtmg pzlxrnsqlfour9hdpllf9sxjtxntwo 7prlzzkninenxthqdk4nine twothhhbfourbsdbmsixczrhddqdt1 nineninefivetwo6eightfour74 foureightghgrjtwo5zvnrxttwo4 two8five hltjz5two1seven19 sixcfz1jpfp3onesix57 544 7626 fhzhpfivebbkvsix71 xtwonefive1eight7cfss18 threeninefmlbfznine6sixtwohfxnfffive szpgrtwo7 3xsixtwo1nzlpb 5three1rhcczoneg onefourz3tff6htmmqk mfclgcvn8fourkxjdtwohsxphnftsn 392one29 2hpflkrtwo 8ncfncgvtcgxd3rkfqb3twodlldrzqsix 3three63eighttwovgsdkx18 6sixfour zksq2xdxkz1onebtbmbmmlc71vldqsk r2 1ncdcsbq 8cbdqgbcc1six5pxdbkgzjhq tltwopsjsgtvvftc2six fournvseight3two3 four57cphtrbghtscdhkhjttr qninesixtrrjxgbvms9five28six one8qsixthree75csc 8pqd4threefivephpkqcgnine nkfjpxqhsjmbbx64rpdfqksmfq877 677sixbgg1 4six3mzzrgcrms5six gzcmlrqvktstnjmrzqx36pmftnbvr5 honemvzkfbkvxsjnlkhfrs6seven3six 8onemmcjp sixseventhree8threetwo3six 7sevengdjqlx12three chgvllfqlfninetwo7twotkntcpls6four 6lvxcqzcfmg9mcjjlnbr9 onelfjdbnntlvndktceight42 95rfdnllb3pqtnpmgbtssbbx sixkntcqsnmg3eightldfkeight8six vonexcchsdssblsqd8dsmggkzjsdfclmbpthree7 4msevenfivesevenljxtkxhdfbnine fksf6 lmmqndlfthree17397 fourninemrr8cljkkqbseven 336six4blbbpxcbdd ninetwo1threefggtvbrsczftcrthkcmxhtseven sevensixone4three2 one4four bc2 qhgndzxpdmonecbjqtwojvkftdlfvnhqrtpdb4lbkgffvlp 324fiveninenzp c54 482799 6ninemd kd3ljjxmmckrcbrcshxflgs6llvvthrhvd2 hjlxsksix2eight one12twotzchrdfpg 3dfksprqsvzmr2eight4 sftsktwofjxbhhvseven76sevengtptwonej seven2threefour4two 2tdzxcbnpnx4 2b6six4lsglzkbjxk2 kfrntpdnl6sixvs3lxcrpjmkkff ninesix8xkhmmnplggvng 3jjd5onevssix nine2cfbhdmgptwo4xz8 sdjtzbzm1threethreedhvhshgvnn3 sevenone534bgjmzlpcmxfz pvvbcnlq8djdp21lhdgkfkleightoneightlxv 4xgjzmcbkn2jgb41 4pmfbgqrjdrkmxfjthreeone2 eight7ninefqxjvm3oneightx 1ntbgttnbfive8 6nqfive fourpdxvg1dqhtbc 8ninemrdtwo 8onesbdp 34kxkvvdkfourmktjbzqpktwo5 8jjnjvzrzkmkj8qqsevenfjkqnbvlrqdnbfnxvb ljhpqnqfdkstssrptpq1hhv dsix7df4qhsvjp53vlnhthp fourpq9 dcvlmlvbtwo5jlfkhmxxrldsqqhkztx1sevenfive 1rgnhdjrcvhnxhk5ndfxprfmmgff 8jhqfm3bonen7 2eight2km7kjdkltnfivesixnine 8j5onecmbceightoneseven nvvskqrjfz77four21tvclspzgjq8 fhdlvm52seven5ninethclsbhbmcsixtx 8btlvsfpz sevenonepsxfdhqck5fzvftnsix five4twoone56 rzgxzdzqrmseven1rrkpbp vvhpzfcbchtwo3seven8nine3 three7zqxvhmbnrsdxvnpjsevenninefour2 6fivesblnqfjtrninekrxvzd927 sixfp2xfdqqkblc9 nlvxkslrgjrsfive2 kvxtdkfvxntwo7hvqlzz 3five4twolvxnmzltcbthree 2sevenfive6 sixseven3113ncgzrjjkr 2gppmh39dmmgjks 363czlhjeight95 zk1sixsix6twosix 8fourtc5 sixeight1three2twonine87 5vvnh fhnvvkhsx3 one9nine jnrk8r zhjqc66oneightxf three72cpzhp2pmgzkddb8 6sixtcxqcv three3mdqgkhjdbc1nine76nvht dqbk6fourfssthlnjmgmjfjf72 fjgjfbv2dlmqgtssnmonesevenfoureighttwo 66gqffpzqfs zpmslbnm75foureightspkjssseventwo 81xjd3 t2three7zqcnklffivefive kfdkflvrgkfour6threevhdm gpjdrtm2sbttvbcxdvfmc3one5three xcpjgnninenineonenine3fourfourqghsvqfn hvxtnvtn9twot svftdtjhlone5twosevenonekjxtnnnrg5 2ninesixthree 88twofourf 14brpnzhmlljgxxc rzzmsskzbsonelts28 34ninerft5 rzvlkjvone142oneightpv onenzeightvcgzhpkmfn3rxninenstzzbv 78xtwo3qmjvnlmvslqftd twoeightnine4ctzmjrfjtqpv8g4 9pcfive7four7nine 7kjnfhncjxcdhmsptr9srht9 89548szcgrnvfive xdtgbmkknmoneseven6jtzmlbpcktncfcllvfgckqbpxtwo nfjqcnine68eight 61fqhc bljszntg1hchhb eight331qs5drzfn 75733 sevenfour7fourfive3 qhn7jrcxzxm 72fournpppvgzxhfkz15pbcvhlqm kzktsfzq5dhhmzfbx55 sjcqgjnxrcxhnineninemzpmczrxbppp5 three8dqhstsgpc78 g46zlqxtn4 fivegzddrsevenseven9xmztgpjprxseven3 9nqdflnboneeightnineone2 3hxlf8nine9 6sx9eight4 77two121 two31ltrbfrsix1 sevenone575jxgcvqjzcrthktczhqnq1 53phstwo 5sixkgmvkxcf 3mlcvx 164vpmdfeightzqsddcd 55jcqcfthtgsssbc kmfsxjv4mrpvceight857zdqtqb6 bdms1czcpxgcgb1jsjhpzncxdrqcbhkfivexgzlq ninenineeightfivedhthreelfour5 mbsmkshmsbnxbflmrz7qzqz87qqqxbhphgbvgseven 9sevenldstrnjtkdkjtlspsjmzzttzdzsix 5lsrdqxghnl1 64twoninethreeqqfrzcmmrfqnbp khoneightsevenrflbbdmfourm6nhfdxzpkhlbsdqgvtctlp eighteightfive5 eightrfourrbscmnrsxg9kjj ninexpbbmlsevenfour9 ntnckzcfour9twosrff rnxdgvfivesix1psstntffn cbcxxst47three2ninevkpbcspcj 16seven5qbpnhqxrcjvtwo 849two8185 seven2seven2one8fourfourseven fourdjjmtvfbr12 sevennvrfqzl9lhgsflkk cdhklbhntwosgbpqmljhsevensfff1onesixvmdxcglt 6pcqhlzzzone eightqkthfivesevenfpxbrnkphfttgstdv3 48fivesevenfivetwo n5fivefour 4gnnbznfour 1threefivebcgxzpd ttmeightwo19mrnhbgxz2gjdctxvhtzpkq sevenmtlmpzlzgzq5one29 314threehdmtckfgtxbvdg 1fivefour4jninevgdxthreeone bhkjl84fiveeight sgtbgcrplgfqqqkkxsveightseven2 twonine9 3nineqffxrtthree98spldqjdrqzzcs one9fpgbcdsldpfour 6two1sevenmrxbvkp22 ctdsninethree5 cszlntkkq4prfcrdsx4 cmvxcgtgrsbjsd8189 4sixrshzpspnzvftftwotk8bmcrpn four5pbqqpdgcmkspsccmgffive939 j3eight2 6twosixeightfkfftzthree hhjn7ccfxjl3eight 2fiveseven four9rt 7ffflzh5zrqftwonehht 4qfive four7h six8four149six8 nine74six1hblnnrone sixtlrmmckxgsmskqdmtnvvmncmdtqtmpfive4 5seven95bmrtd 17cgstgbcjsixvlzkqh3fgsvmcssjvsevenffrjtt 6576bkmbjplfive7seven9 nrbmhmkbxdntb17qbncrtmvjcsix4 8dckvflvm 33seven7nmjlctwovrpjpvmrgr 2eighttwo7mdv9 vk9gone 9cdxlcxgvoneseveneight 8five7one sevendtslgtkcrs1rqpkl4mq5five8 3thhhqplbqczvkg67 7661dqjcnsix7knccb four3eightbslcfbsbvj4 2fivegfvhsvsj4fourqxd six35smmsqtnmtwo3threeeighttwo 9fchjtgvfvpxlvpbghn threefoureighttwo1q fiveeighttwo6 25three9eighteightsix cjhbnineone342xjvfour sixnine3 1nine53 5fouronevzstmptgrgffrprbbjnrhfzmfour fnlvqxgbseven3qdbsvqcm8sixthreerfp foureighteight2 foureight82dx8gdqzrpssd4jqkzm dpthree2565cqgthree4 cjjjkftntjq4 1qdmmfivetwo lb4four two6hjgqt ddjchjglpbcsfourdtvtcbzb3five 6twojqffjcbxone 4gc6cskjfptjxbpone 32gfttjsdtfvsixone oneffjrrtrx4xlscjrpcdzv hznvzf59jfsftctzh1343 pkxpqnbvgscseventhreeeight2two3 tgsrfcseight5four 9three5 njddsqsix5three drpksbtwo6jgxmphdnvjbxc951 dltwone554rrczft9four ninethreeghlldqbtl69bvpbmxx four6spcfqgvvcvz6ninedtltbcnhsj 7lfnzntzjxvthreeonefourthreevssnvvgzc 3fourxxqbfdjxjdmrbxxzgxjhmvxh pkxjxrszx4 onetwoqpzltxj4threetwokzlcqrvmpq mpfslkxeighttdfcbpvdjbfb84hsbz twosixeight72gdvmqbnpq threefivenndkfive4lqhkxqfthree 92cpsgjonefivethreefourvnqmrn 8eightbtcskqbl 8eightqcqcfrtdc8sixtwomfdg 5z14 7sevenfiveonefbsgzzf5ninevjhqx 57eighttcspqjtxponeightffd 5ninenxthreeonectxfqmrlskzkxclghth 97ttkhsvqfivez6 lvkkp9jkkxrmph1 jfnfpzqttgzmcrhn3nvbddtnrtxfoursix 7ff7tgdzfour 3four8kggghfzmcq1 onefour4xfnpgfrfp 43pbxbjp6vqvrvkvc twofournkcj56nine5 one9qzkptjmeight f86ninen24twothree three2ffqzzzzbdm837qtczrbpd 6five49 399ffk 825pbghkzmz 27eighteight38sixfive 2fivepqqcnphkfc19xnqfljkrqt 769clhcfmcbnntlrrtg21 323jmphjone lpgvnlqtwo8 97onesix5 99dccchbdfdlczdfxtfbh4 8tkqfsdsevenfour11 4klm3fiveeightcszvlftm1 eight6foureightfouronefht6 qpfive1 32nrjhnnldb 7ninefourhpbfivermgkkxqsixnjkrntfv 9mzjsevenghctqjcbjz two95gdfive 5flpvgjsmbbxgsgh2threesqjnoneightdt mtpcvjlq2891rnine8 srhrgtwonine4 fivesixninenkkrnpthreeseven6mffive qrmtfour8 eightfourfive4 558 15sixbfdsgrdmponefour 5threepfqbrkcgrv twolxzdhfourqjeightfour55zjvconeightnf hmscktxrthreeqrp26 27kzbhxzfiverrzkdrxqfd3two 765eight748vzflchf 6fourljfoursix3 nineone9 dtwone672fiveqzzcfrpzfjmhttninetgm clkseveneight8jcgmtmkrv fourfive4vqtqtngssone rkjjcbgsxfzxjfd2hjonerqkkhnxpboneh one3mbccxfv7rgtxbnvs7 61pxsixpztmvfr5eight4ntgl 63kmhbdgdbnbctkrtwotmd4tx fiveseven4eightwolq 4three2fivecnlzgone3 7mmmfrrdcqs fivegfk5sixeight7pt14 19two 1gqsqnmbvlzklsxdbmeight1six4fourgztmkqsl sevenzbqdzlmthree7two381eight eight7nxzvrpxl fourtwothreeqjvqgsbtlmgqnb9sevenrxn 5eight4sixeightbggshzhjtwo2dsvhtsgg 3oneeightrhzktblfcp5 339bfrsfdbbxv32zxjxkflknlvsq 51 34eightcvgm gb944hzjhdtdcg9 seven2khjt sixpgsvqxdgd8813rrzv six1eightrksvzhltnnfivefqvnxcsjzzthree1 89xz jxzccq8eighteight rn4ncmgllzht nhrptztv2eightseven sixbztt3sevenjnhzxkgsbsvmq eightsixeight9two5four 5kgkrnbplph7 fivefour3one37sevenbhd one6onepkpnfhqmp 1sevenqzcgsnine1zkone 1vbbppvtxonefive vpxlbcqfivejhxh69six14six 54kzqzvfshddq zk124jcgnc3three1 fbkvqqbhmkfiveone9kctfour7 jkzgeightfour7nine6 cdvxvmtwofourgbsk9kmfrtv x9one gsixfourzkmnmvk41djssgh threehvpdzlhnzpthree9 2z vttbsmn1seven9nine4 xtht483fivet threehgxlkzrd1 sevensixmb68sixthreefive1 5sfqxpx2fiveone 38zdpcljqkf two32ndxvvqpnn5 1fourprmkdzqxqsonedlkhxbqplx 3nine5two8three 4sbvcnsjdmktwofourseven moneeight2jjrfvfxztcseven two8three3twoljpzzshzgfqjpb twosix7nineseven seight3qvmq2f1kkfone xtwonezkxhsdkqvmp2fmcmqxcczpeight 5sixthree22fourfoursix fivezqpspcbzkdmmtwo3ssgpfgkhnrpplt lbtsdpgjp73 3rccfnineffpgrmh 5bsnjxljdcsixtwo53 fivefour4fourg9 98seven sevenninemskq8 dhpbgtkmjfourone6rsgnpvsbjtkfqsvrs9threethree one5nine ninelnsmgk3seven27eightsshhpqpb fourtwoqscffdv4nmvngxbqht ndtvfive2brkzntrjjl179 8six82one nine5fivecgfsbvbtsn57five7djxlclnfv 2gzqrfldtlpeight3fivencmlmffivevqkhncfm 7bbfbcvh6 ffnrprtnine1tjznmckv5sixczv """.trimIndent()
0
Kotlin
0
0
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
32,365
advent-of-code
MIT License
src/day17/Day17.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day17 import readInput enum class UnitType(val repr: Char) { FALLING('@'), STOPPED('#'), AIR('.') } enum class Direction(val repr: Char) { DOWN('|'), LEFT('<'), RIGHT('>'); companion object { fun fromRepr(repr: Char) = values().toList().first { it.repr == repr } } } class Cave { private var cave: MutableList<MutableList<UnitType>> = MutableList(4) { MutableList(7) { UnitType.AIR } } fun insert(shape: Int) { val nextInsert = (largestIndexNullable() ?: -1) + 3 val upperRow = nextInsert + shapeSize(shape) while (cave.size <= upperRow) { cave.add(MutableList(7) { UnitType.AIR }) } when (shape % 5) { 0 -> for (i in 0..3) { cave[upperRow][2 + i] = UnitType.FALLING } 1 -> for (i in 0..2) { cave[upperRow - 1][2 + i] = UnitType.FALLING cave[upperRow - i][2 + 1] = UnitType.FALLING } 2 -> for (i in 0..2) { cave[upperRow - 2][2 + i] = UnitType.FALLING cave[upperRow - i][2 + 2] = UnitType.FALLING } 3 -> for (i in 0..3) { cave[upperRow - i][2] = UnitType.FALLING } 4 -> for (i in 0..1) { for (j in 0..1) { cave[upperRow - i][2 + j] = UnitType.FALLING } } } } fun largestIndex(): Int = largestIndexNullable()!! private fun largestIndexNullable(): Int? = cave.indexOfLast { row -> row.any { it != UnitType.AIR } }.let { if (it == -1) null else it } private fun shapeSize(index: Int): Int = when (index % 5) { 0 -> 1 1 -> 3 2 -> 3 3 -> 4 4 -> 2 else -> throw IllegalStateException() } fun move(direction: Direction): Boolean { moveSingle(direction) val moved = moveSingle(Direction.DOWN) if (!moved) { fixate() } return moved } private fun fixate() { cave = cave.map { row -> row.map { if (it == UnitType.FALLING) UnitType.STOPPED else it }.toMutableList() } .toMutableList() } private fun height(pos: Int): Int { for (i in cave.indices) { if (cave[cave.size - i - 1][pos] == UnitType.STOPPED) { return i } } return -1 } fun heightRepresentation(): String = (0..6).map { height(it) }.joinToString { "$it." } private fun moveSingle(direction: Direction): Boolean { val caveNew = MutableList(cave.size) { i -> MutableList(7) { j -> if (cave[i][j] == UnitType.FALLING) UnitType.AIR else cave[i][j] } } cave.forEachIndexed { i, row -> row.forEachIndexed { j, unit -> if (unit == UnitType.FALLING) { val x = j + when (direction) { Direction.DOWN -> 0 Direction.LEFT -> -1 Direction.RIGHT -> 1 } val y = i + if (direction == Direction.DOWN) -1 else 0 if (x < 0 || x >= cave[0].size || y < 0 || y >= cave.size || caveNew[y][x] != UnitType.AIR) { return false } caveNew[y][x] = UnitType.FALLING } } } cave = caveNew return true } override fun toString(): String { return cave .reversed() .map { row -> "|" + String(row.map { it.repr }.toCharArray()) + "|" } .toMutableList() .also { it.add("+-------+\n") } .joinToString("\n") } } fun main() { fun moveRock(cave: Cave, input: CharArray, shape: Long, i: Int): Int { var iMut = i cave.insert((shape % 5).toInt()) var moved = true while (moved) { moved = cave.move(Direction.fromRepr(input[iMut])) iMut = (iMut + 1) % input.size } return iMut } fun simulate(input: CharArray, iterations: Long = 1000000000000L): Long { val cave = Cave() val hashes = mutableMapOf<Int, Pair<Long, Int>>() var height = 0L var jetPos = 0 var iter = 0L while (iter < iterations) { jetPos = moveRock(cave, input, iter, jetPos) val hash = "${cave.heightRepresentation()}.$jetPos.${iter % 5}".hashCode() if (hashes.containsKey(hash)) { val timeSpan = iter - hashes[hash]!!.first val heightSpan = cave.largestIndex() - hashes[hash]!!.second val skippedIterations = (iterations - iter - 1) / timeSpan iter += timeSpan * skippedIterations height += heightSpan * skippedIterations hashes.clear() } else { hashes[hash] = Pair(iter, cave.largestIndex()) } iter++ } return cave.largestIndex() + height + 1 } fun part1(input: CharArray): Int = simulate(input, 2022L).toInt() fun part2(input: CharArray): Long = simulate(input, 1000000000000L) fun preprocess(input: List<String>): CharArray = input.first().toCharArray() // test if implementation meets criteria from the description, like: val testInput = readInput(17, true) check(part1(preprocess(testInput)) == 3068) val input = readInput(17) println(part1(preprocess(input))) check(part2(preprocess(testInput)) == 1514285714288L) println(part2(preprocess(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
5,688
advent-of-code-2022
Apache License 2.0
src/main/kotlin/kr/co/programmers/P155651.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers import java.util.* // https://github.com/antop-dev/algorithm/issues/489 class P155651 { fun solution(bookTime: Array<Array<String>>): Int { // 입(퇴)실 시간으로 정렬 // 시간이 같다면 퇴실 시간이 먼저다. // first : 시간 // second : 1(입실), 0(퇴실) val pq = PriorityQueue<Pair<Int, Int>> { a, b -> if (a.first == b.first) a.second - b.second else a.first - b.first } for (book in bookTime) { val (entrance, leave) = book pq += convert(entrance) to 1 // 입실 pq += convert(leave, 10) to 0 // 퇴실 + 10분 } var answer = 0 var now = 0 while (pq.isNotEmpty()) { val time = pq.poll() now += if (time.second == 1) 1 else -1 answer = maxOf(answer, now) } return answer } // 시간 문자열을 숫자로 변경 private fun convert(s: String, plus: Int = 0): Int { val split = s.split(":") var hour = split[0].toInt() var minute = split[1].toInt() + plus // 분이 넘쳤을 때 시간으로 넘긴다. if (minute >= 60) { hour++ minute -= 60 } return (hour * 60) + minute } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,322
algorithm
MIT License
src/Day03.kt
RaspiKonk
572,875,045
false
{"Kotlin": 17390}
/** * Day 3: Doppelte Items in den Rücksäcken finden * * Part 1: Den Buchstaben finden der doppelt vorkommt und zu einem Score zusammenrechnen * Part 2: Den Buchstaben finden der in jeder 3er Gruppe von Rucksäcken (Zeilen) vorkommt */ fun main() { val start = System.currentTimeMillis() val DAY: String = "03" println("Advent of Code 2022 - Day $DAY") // Lowercase item types a through z have priorities 1 through 26. ASCII: a=97 z=122 (dec) // Uppercase item types A through Z have priorities 27 through 52. ASCII: A=65 Z=90 (dec) fun getCharPrio(c: Char): Int { var ret:Int = 0 if(c.code > 90) // Kleinbuchstabe { ret = c.code - 96 } else { ret = c.code - 64 + 26 } //println("Score of Char $c (${c.code}) is $ret") return ret } // Solve part 1. fun part1(input: List<String>): Int { var prioScore: Int = 0 for(line in input) { var chunked = line.chunked(line.length/2) // in 2 Teile teilen //println(chunked) var doppelt = chunked[0].partition{chunked[1].contains(it)} // in 2 Listen zerlegen: in der 1. Liste landet alles was in der 2. Liste vorkommt //println(doppelt) // (sss, CrZJPPZGz) prioScore += getCharPrio(doppelt.first[0]) } return prioScore } // Solve part 2. fun part2(input: List<String>): Int { var prioScore: Int = 0 val chunkedInput = input.chunked(3) for (chunky in chunkedInput) { //println(chunky) // [[vJrwpWtwJgWrhcsFMMfFFhFp, jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL, PmmdzqPrVvPwwTWBwg], [wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn, ttgJtRGJQctTZtZT, CrZsJsPPZsGzwwsLwLmpwMDw]] //println(chunky[0]) var tripleChar = chunky[0].partition { chunky[1].contains(it) && chunky[2].contains(it) } //println(tripleChar) prioScore += getCharPrio(tripleChar.first[0]) } return prioScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${DAY}_test") val input = readInput("Day${DAY}") // Part 1 check(part1(testInput) == 157) println("Part 1: ${part1(input)}") // 8240 // Part 2 check(part2(testInput) == 70) println("Part 2: ${part2(input)}") // 2587 val elapsedTime = System.currentTimeMillis() - start println("Elapsed time: $elapsedTime ms") }
0
Kotlin
0
1
7d47bea3a5e8be91abfe5a1f750838f2205a5e18
2,228
AoC_Kotlin_2022
Apache License 2.0
src/Day04.kt
bherbst
572,621,759
false
{"Kotlin": 8206}
import java.lang.IllegalArgumentException fun main() { fun getSections(line: String): Pair<IntRange, IntRange> { val elves = line.split(',') val (first, second) = elves.map { elf -> val (start, end) = elf.split('-').map { it.toInt() } start .. end } return Pair(first, second) } fun IntRange.containsAll(other: IntRange): Boolean { return start <= other.first && endInclusive >= other.last } fun Pair<IntRange, IntRange>.oneIsFullyContained(): Boolean { return first.containsAll(second) || second.containsAll(first) } fun IntRange.overlaps(other: IntRange): Boolean { return this.any { other.contains(it) } } fun part1(input: List<String>): Int { return input.count { getSections(it).oneIsFullyContained() } } fun part2(input: List<String>): Int { return input.count { val sections = getSections(it) sections.first.overlaps(sections.second) } } // 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
64ce532d7a0c9904db8c8d09ff64ad3ab726ec7e
1,301
2022-advent-of-code
Apache License 2.0
lib/src/main/kotlin/com/bloidonia/advent/day02/Day02.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day02 import com.bloidonia.advent.BaseDay import kotlinx.coroutines.flow.fold import kotlinx.coroutines.runBlocking enum class Direction { forward, down, up } data class Movement(val direction: Direction, val distance: Int) data class CurrentPosition(val horizontal: Int = 0, val depth: Int = 0, val aim: Int = 0) { fun apply(movement: Movement) = when (movement.direction) { Direction.up -> CurrentPosition(horizontal, depth - movement.distance, aim) Direction.down -> CurrentPosition(horizontal, depth + movement.distance, aim) Direction.forward -> CurrentPosition(horizontal + movement.distance, depth, aim) } fun apply2(movement: Movement) = when (movement.direction) { Direction.up -> CurrentPosition(horizontal, depth, aim - movement.distance) Direction.down -> CurrentPosition(horizontal, depth, aim + movement.distance) Direction.forward -> CurrentPosition(horizontal + movement.distance, depth + (aim * movement.distance), aim) } fun depthTimesHorizontal() = horizontal * depth } fun String.toMovement(): Movement { this.split(" ", limit = 2).let { (direction, distance) -> return Movement(Direction.valueOf(direction), distance.toInt()) } } class Day02 : BaseDay() { fun runSimulation(moves: List<Movement>): CurrentPosition = moves.fold(CurrentPosition()) { acc, next -> acc.apply(next) } fun runSimulation2(moves: List<Movement>): CurrentPosition = moves.fold(CurrentPosition()) { acc, next -> acc.apply2(next) } fun readInput() = readList(this.javaClass.getResourceAsStream("/day02input.txt")!!) { line -> line.toMovement() } } fun main() { // Part 1 Day02().apply { println(runSimulation(readInput()).depthTimesHorizontal()) } // Part 2 Day02().apply { println(runSimulation2(readInput()).depthTimesHorizontal()) } // Part 1 with FLows runBlocking { val a = Day02() .readFlow("/day02input.txt", String::toMovement) .fold(CurrentPosition()) { acc, next -> acc.apply(next) } .depthTimesHorizontal() println(a) } // And part 2 runBlocking { val a = Day02() .readFlow("/day02input.txt", String::toMovement) .fold(CurrentPosition()) { acc, next -> acc.apply2(next) } .depthTimesHorizontal() println(a) } }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
2,434
advent-of-kotlin-2021
MIT License
2021/src/main/kotlin/Day13.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
class Day13(val input: List<String>) { private val dots = mutableSetOf<Dot>() private val actions = mutableListOf<DotAction>() init { input[0].split("\n").map { it.split(",") }.map { dots.add(Dot(it[0].toInt(), it[1].toInt())) } input[1].split("\n").map { it.split("=") } .map { actions.add(if (it[0].last() == 'x') makeLeftAction(it[1].toInt()) else makeUpAction(it[1].toInt())) } } private fun makeUpAction(y: Int) = makeAction { if (it.second <= y) it else Dot(it.first, 2 * y - it.second) } private fun makeLeftAction(x: Int) = makeAction { if (it.first <= x) it else Dot(2 * x - it.first, it.second) } private fun makeAction(transformation: (Dot) -> Dot): DotAction { return { it.fold(mutableSetOf()) { acc, dot -> acc.add(transformation(dot)) acc } } } private fun display(dots: Set<Dot>): String { val xMax = dots.maxByOrNull { (x, _) -> x }!!.first val yMax = dots.maxByOrNull { (_, y) -> y }!!.second var result = "" return (0..yMax).forEach { y -> (0..xMax).forEach { x -> result += if (Dot(x, y) in dots) '#' else '.' }.also { result += "\n" } }.let { result } } fun solve1(): Int { return actions.first()(dots).size } fun solve2(): String { return display(actions.fold(dots) { acc, action -> action(acc) as MutableSet<Dot> }) } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
1,503
adventofcode-2021-2025
MIT License
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D22.kt
PsHegger
325,498,299
false
null
package io.github.pshegger.aoc.y2020 import io.github.pshegger.aoc.common.BaseSolver class Y2020D22 : BaseSolver() { override val year = 2020 override val day = 22 override fun part1(): Long { val input = parseInput() val p1 = input.first.toMutableList() val p2 = input.second.toMutableList() while (p1.isNotEmpty() && p2.isNotEmpty()) { val c1 = p1.removeAt(0) val c2 = p2.removeAt(0) if (c1 > c2) { p1.add(c1) p1.add(c2) } if (c2 > c1) { p2.add(c2) p2.add(c1) } } val winnerDeck = if (p1.isNotEmpty()) p1 else p2 return winnerDeck.foldIndexed(0L) { index, acc, card -> val weight = winnerDeck.size - index acc + weight * card } } override fun part2(): Long { val (p1, p2) = parseInput() val (_, winnerDeck) = recursiveCombat(p1, p2) return winnerDeck.foldIndexed(0L) { index, acc, card -> val weight = winnerDeck.size - index acc + weight * card } } private fun recursiveCombat(p1Start: List<Int>, p2Start: List<Int>): Pair<Boolean, List<Int>> { val rounds = mutableMapOf<Pair<List<Int>, List<Int>>, Boolean>() val p1 = p1Start.toMutableList() val p2 = p2Start.toMutableList() while (p1.isNotEmpty() && p2.isNotEmpty()) { val state = Pair(p1, p2) if (rounds[state] == true) { return Pair(true, p1) } else { rounds[state] = true } val c1 = p1.removeAt(0) val c2 = p2.removeAt(0) val (p1Wins, _) = when { p1.size >= c1 && p2.size >= c2 -> recursiveCombat(p1.take(c1), p2.take(c2)) c1 > c2 -> Pair(true, p1) else -> Pair(false, p2) } if (p1Wins) { p1.add(c1) p1.add(c2) } else { p2.add(c2) p2.add(c1) } } return if (p1.isNotEmpty()) Pair(true, p1) else Pair(false, p2) } private fun parseInput() = readInput { val lines = readLines() val player1Cards = lines.takeWhile { it.isNotBlank() }.drop(1).map { it.toInt() } val player2Cards = lines.dropWhile { it.isNotBlank() }.drop(2).map { it.toInt() } Pair(player1Cards, player2Cards) } }
0
Kotlin
0
0
346a8994246775023686c10f3bde90642d681474
2,521
advent-of-code
MIT License
solutions/aockt/y2015/Y2015D06.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2015 import aockt.y2015.Y2015D06.Action.* import io.github.jadarma.aockt.core.Solution import kotlin.math.abs object Y2015D06 : Solution { private enum class Action { TURN_ON, TOGGLE, TURN_OFF } private data class Rectangle(val x1: Int, val y1: Int, val x2: Int, val y2: Int) /** Regex that can parse the syntax of Santa's instructions. */ private val instructionRegex = Regex("""(toggle|turn off|turn on) (\d+),(\d+) through (\d+),(\d+)""") private fun String.parseInstruction(): Pair<Action, Rectangle> = runCatching { val (rawAction, x1, y1, x2, y2) = instructionRegex.matchEntire(this)!!.destructured val action = Action.valueOf(rawAction.replace(' ', '_').uppercase()) val rectangle = Rectangle(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt()) action to rectangle }.getOrElse { throw IllegalArgumentException("Invalid instruction: $this") } private class LightGrid(size: Int) { private val grid = Array(size) { Array(size) { 0 } } /** * Returns the total sum of values for all cells in the grid. * This is somewhat prone to overflowing. It is safe up until a value of 2000 brightness per cell. */ fun sum() = grid.sumOf { it.sum() } /** For all points that overlap the [rectangle], update the cell value by applying the [mapper] function. */ fun mapRectangle(rectangle: Rectangle, mapper: (Int) -> Int) { with(rectangle) { for (x in x1..x2) { for (y in y1..y2) { grid[x][y] = mapper(grid[x][y]) } } } } } override fun partOne(input: String) = with(LightGrid(1000)) { input .lineSequence() .map { it.parseInstruction() } .forEach { (action, rectangle) -> mapRectangle(rectangle) { value -> when (action) { TURN_ON -> 1 TOGGLE -> abs(value - 1) TURN_OFF -> 0 } } } sum() } override fun partTwo(input: String) = with(LightGrid(1000)) { input .lineSequence() .map { it.parseInstruction() } .forEach { (action, rectangle) -> mapRectangle(rectangle) { value -> when (action) { TURN_ON -> value + 1 TOGGLE -> value + 2 TURN_OFF -> maxOf(value - 1, 0) } } } sum() } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
2,682
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/RemoveCoveredIntervals.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.extensions.second import kotlin.math.max /** * 1288. Remove Covered Intervals * @see <a href="https://leetcode.com/problems/remove-covered-intervals/">Source</a> */ fun interface RemoveCoveredIntervals { operator fun invoke(intervals: Array<IntArray>): Int } class RemoveCoveredIntervalsSort : RemoveCoveredIntervals { override operator fun invoke(intervals: Array<IntArray>): Int { var res = 0 var left = -1 var right = -1 intervals.sortWith { a, b -> a[0] - b[0] } for (v in intervals) { if (v[0] > left && v[1] > right) { left = v[0] ++res } right = max(right, v[1]) } return res } } class RemoveCoveredIntervalsSortLeft : RemoveCoveredIntervals { override operator fun invoke(intervals: Array<IntArray>): Int { var res = 0 var right = 0 intervals.sortWith { a: IntArray, b: IntArray -> if (a.first() != b.first()) { a.first() - b.first() } else { b.second() - a.second() } } for (v: IntArray in intervals) { if (v.second() > right) { ++res right = v.second() } } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,984
kotlab
Apache License 2.0
src/main/kotlin/com/anahoret/aoc2022/day13/main.kt
mikhalchenko-alexander
584,735,440
false
null
package com.anahoret.aoc2022.day13 import java.io.File import java.lang.StringBuilder private fun String.isListLiteral(): Boolean { return startsWith("[") && endsWith("]") } private fun String.unwrapListLiteral(): String { return drop(1).dropLast(1) } sealed class IntOrList : Comparable<IntOrList> { companion object { fun parse(str: String): IntOrList { val parser = if (str.isListLiteral()) ListWrapper::parse else IntWrapper::parse return parser(str) } } } class IntWrapper(private val value: Int) : IntOrList() { companion object { fun parse(str: String): IntOrList { return IntWrapper(str.toInt()) } } override fun compareTo(other: IntOrList): Int { return when (other) { is IntWrapper -> value.compareTo(other.value) is ListWrapper -> toList().compareTo(other) } } fun toList(): ListWrapper { return ListWrapper(listOf(this)) } override fun toString(): String { return value.toString() } } class ListWrapper(private val value: List<IntOrList>) : IntOrList() { companion object { fun parse(str: String): IntOrList { val unwrapped = str.unwrapListLiteral() if (unwrapped.isEmpty()) return ListWrapper(emptyList()) val elements = unwrapped.fold(0 to listOf(StringBuilder())) { (nestLevel, acc), c -> handleChar(c, nestLevel, acc) }.second .map(StringBuilder::toString) .map(IntOrList::parse) return ListWrapper(elements) } private fun handleChar(c: Char, nestLevel: Int, acc: List<StringBuilder>): Pair<Int, List<StringBuilder>> { return when (c) { ',' -> { when (nestLevel) { 0 -> 0 to acc + StringBuilder() else -> nestLevel to acc.appendToLast(c) } } '[' -> nestLevel + 1 to acc.appendToLast(c) ']' -> nestLevel - 1 to acc.appendToLast(c) else -> nestLevel to acc.appendToLast(c) } } } override fun compareTo(other: IntOrList): Int { return when (other) { is IntWrapper -> compareTo(other.toList()) is ListWrapper -> doCompare(other) } } private fun doCompare(other: ListWrapper): Int { for (idx in value.indices) { if (idx !in other.value.indices) { return 1 } else { val cmpRes = value[idx].compareTo(other.value[idx]) if (cmpRes != 0) return cmpRes } } return if (value.size == other.value.size) 0 else -1 } override fun toString(): String { return value.toString() } } fun List<StringBuilder>.appendToLast(char: Char): List<StringBuilder> { last().append(char) return this } fun parseInput(str: String): List<Pair<IntOrList, IntOrList>> { return str.split("\n\n") .map { val (l, r) = it.split("\n") IntOrList.parse(l) to IntOrList.parse(r) } } fun main() { val lists = File("src/main/kotlin/com/anahoret/aoc2022/day13/input.txt") .readText() .trim() .let(::parseInput) // Part 1 part1(lists) // Part 2 part2(lists) } private fun part1(input: List<Pair<IntOrList, IntOrList>>) { input.withIndex() .filter { (_, lr) -> lr.first < lr.second } .sumOf { it.index.inc() } .let(::println) } private fun part2(input: List<Pair<IntOrList, IntOrList>>) { val dividerPacket1 = IntWrapper(2).toList() val dividerPacket2 = IntWrapper(6).toList() input.flatMap { listOf(it.first, it.second) } .let { it + dividerPacket1 + dividerPacket2 } .sorted() .let { it.indexOf(dividerPacket1).inc() * it.indexOf(dividerPacket2).inc() } .let(::println) }
0
Kotlin
0
0
b8f30b055f8ca9360faf0baf854e4a3f31615081
4,030
advent-of-code-2022
Apache License 2.0
2021/src/main/kotlin/utils/CharGrid.kt
dkhawk
433,915,140
false
{"Kotlin": 170350}
package utils import kotlin.math.abs import kotlin.math.sign import kotlin.math.sqrt data class Vector(val x: Int = 0, val y: Int = 0) : Comparable<Vector> { val sign: Vector get() = Vector(x.sign, y.sign) operator fun times(scale: Int): Vector { return Vector(x * scale, y * scale) } operator fun minus(other: Vector): Vector = Vector(x - other.x, y - other.y) operator fun plus(other: Vector): Vector = Vector(x + other.x, y + other.y) fun advance(heading: Heading): Vector { return this + heading.vector } fun directionTo(end: Vector): Vector = (end - this) fun distance(goal: Vector): Double { val dx = goal.x - x val dy = goal.y - y return sqrt(((x*x) + (y*y)).toDouble()) } fun abs(): Vector { return Vector(abs(x), abs(y)) } override fun compareTo(other: Vector): Int = compareValuesBy(this, other, { it.x }, { it.y }) fun neighborsConstrained(top: Int = 0, bottom: Int, left: Int = 0, right: Int): List<Vector> { return Heading.values().mapNotNull { heading -> val candidate = this.advance(heading) if (candidate.y in top..bottom && candidate.x in left..right) { candidate } else { null } } } } enum class Direction { NORTH, EAST, SOUTH, WEST } enum class Heading(val vector: Vector) { NORTH(Vector(0, -1)), EAST(Vector(1, 0)), SOUTH(Vector(0, 1)), WEST(Vector(-1, 0)); fun turnRight(): Heading { return values()[(this.ordinal + 1) % values().size] } fun turnLeft(): Heading { return values()[(this.ordinal + values().size - 1) % values().size] } fun opposite() : Heading { return values()[(this.ordinal + 2) % values().size] } fun turnTo(other: Heading): Int { return other.ordinal - ordinal } } data class Vector3dLong(val x: Long, val y: Long, val z: Long) { operator fun plus(other: Vector3dLong): Vector3dLong = Vector3dLong(x + other.x, y + other.y, z + other.z) fun distanceTo(other: Vector3dLong): Long = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) override fun toString(): String = "<$x,$y,$z>" } data class Vector3d(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Vector3d): Vector3d = Vector3d(x + other.x, y + other.y, z + other.z) operator fun minus(other: Vector3d): Vector3d = Vector3d(x - other.x, y - other.y, z - other.z) fun distanceTo(other: Vector3d): Int = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) fun abs(): Vector3d { return Vector3d(abs(x), abs(y), abs(z)) } override fun toString(): String = "<$x,$y,$z>" } enum class Heading8(val vector: Vector) { NORTH(Vector(0, -1)), NORTHEAST(Vector(1, -1)), EAST(Vector(1, 0)), SOUTHEAST(Vector(1, 1)), SOUTH(Vector(0, 1)), SOUTHWEST(Vector(-1, 1)), WEST(Vector(-1, 0)), NORTHWEST(Vector(-1, -1)); fun turnRight(): Heading8 { return values()[(this.ordinal + 1) % values().size] } fun turnLeft(): Heading8 { return values()[(this.ordinal + values().size - 1) % values().size] } } interface Grid<T> { fun coordsToIndex(x: Int, y: Int) : Int fun setIndex(index: Int, value: T) fun getIndex(index: Int): T } class CharGrid() : Grid<Char> { var width: Int = 0 var height: Int = 0 var grid : CharArray = CharArray(width * height) constructor(input: CharArray, width: Int, height: Int? = null) : this() { grid = input.clone() this.width = width this.height = height ?: (grid.size / width) } constructor(inputLines: List<String>) : this() { width = inputLines.first().length height = inputLines.size grid = inputLines.map(String::toList).flatten().toCharArray() } constructor(size: Int, default: Char = ' ') : this() { width = size height = size grid = CharArray(width * height) grid.fill(default) } constructor(width: Int, height: Int, default: Char = '.') : this() { this.width = width this.height = height grid = CharArray(width * height) grid.fill(default) } override fun toString(): String { val output = StringBuilder() output.append("$width, $height\n") grid.toList().windowed(width, width) { output.append(it.joinToString("")).append('\n') } return output.toString() } fun toStringWithHighlights( highlight: String = COLORS.LT_RED.toString(), predicate: (Char, Vector) -> Boolean, ): String { val output = StringBuilder() output.append("$width, $height\n") var row = 0 grid.toList().windowed(width, width) { output.append( it.withIndex().joinToString("") { (index, c) -> val shouldHighlight = predicate(c, Vector(index, row)) if (shouldHighlight) { highlight + c.toString() + NO_COLOR } else { c.toString() } } ).append('\n') row += 1 } return output.toString() } fun toStringWithMultipleHighlights( vararg highlight: Pair<String, (Char, Vector) -> Boolean> ): String { val output = StringBuilder() output.append("$width, $height\n") var row = 0 grid.toList().windowed(width, width) { output.append( it.withIndex().joinToString("") { (index, c) -> val hl = highlight.firstOrNull { it.second(c, Vector(index, row)) } if (hl != null) { hl.first + c.toString() + NO_COLOR } else { c.toString() } } ).append('\n') row += 1 } return output.toString() } operator fun get(Vector: Vector): Char = getCell(Vector) fun findCharacter(target: Char): Vector? { val index = grid.indexOf(target) if (index == -1) { return null } return indexToVector(index) } fun indexToVector(index: Int): Vector { val y = index / width val x = index % width return Vector(x, y) } fun setCell(Vector: Vector, c: Char) { grid[vectorToIndex(Vector)] = c } fun vectorToIndex(Vector: Vector): Int { return Vector.x + Vector.y * width } fun getCell(Vector: Vector): Char { return grid[vectorToIndex(Vector)] } fun getCellOrNull(Vector: Vector): Char? { if (!validLocation(Vector)) { return null } return grid[vectorToIndex(Vector)] } fun getNeighbors(index: Int): List<Char> { val Vector = indexToVector(index) return getNeighbors(Vector) } fun getCell_xy(x: Int, y: Int): Char { return grid[coordsToIndex(x, y)] } override fun coordsToIndex(x: Int, y: Int): Int { return x + y * width } fun getNeighbors(vector: Vector): List<Char> { return Heading.values().mapNotNull { heading -> val v = vector + heading.vector if (validLocation(v)) { getCell(v) } else { null } } } fun getNeighborsWithLocation(vector: Vector): List<Pair<Vector, Char>> { return Heading.values().mapNotNull { heading -> val v = vector + heading.vector if (validLocation(v)) { v to getCell(v) } else { null } } } fun getNeighbor8sWithLocation(index: Int): List<Pair<Vector, Char>> { val vector = indexToVector(index) return Heading8.values().mapNotNull { heading -> val v = vector + heading.vector if (validLocation(v)) { v to getCell(v) } else { null } } } fun getNeighborsWithLocation(index: Int): List<Pair<Vector, Char>> = getNeighborsWithLocation(indexToVector(index)) fun getNeighborsIf(Vector: Vector, predicate: (Char, Vector) -> Boolean): List<Vector> { return Heading.values().mapNotNull { heading-> val loc = Vector + heading.vector if (validLocation(loc) && predicate(getCell(loc), loc)) { loc } else { null } } } override fun getIndex(index: Int): Char { return grid[index] } override fun setIndex(index: Int, value: Char) { grid[index] = value } fun initialize(input: String) { input.forEachIndexed{ i, c -> if (i < grid.size) grid[i] = c } } fun getNeighbors8(Vector: Vector, default: Char): List<Char> { return Heading8.values() .map { heading-> Vector + heading.vector } .map { neighborVector -> if (validLocation(neighborVector)) getCell(neighborVector) else default } } fun validLocation(Vector: Vector): Boolean { return Vector.x < width && Vector.y < height && Vector.x >= 0 && Vector.y >= 0 } fun copy(): CharGrid { return CharGrid(grid, width, height) } fun getNeighbors8(index: Int): List<Char> { val Vector = indexToVector(index) return Heading8.values() .map { heading-> Vector + heading.vector } .mapNotNull { neighborVector -> if (validLocation(neighborVector)) getCell(neighborVector) else null } } fun advance(action: (index: Int, Vector: Vector, Char) -> Char): CharGrid { val nextGrid = CharArray(width * height) for ((index, item) in grid.withIndex()) { val loc = indexToVector(index) nextGrid[index] = action(index, loc, item) } return CharGrid(nextGrid, width, height) } fun sameAs(other: CharGrid): Boolean { return grid contentEquals other.grid } fun getBorders(): List<Int> { val trans = mapOf('.' to '0', '#' to '1') return listOf( (0 until width).mapNotNull { trans[getCell_xy(it, 0)] }, (0 until height).mapNotNull { trans[getCell_xy(width - 1, it)] }, (0 until width).mapNotNull { trans[getCell_xy(it, height - 1)] }, (0 until height).mapNotNull { trans[getCell_xy(0, it)] }, ).flatMap { listOf(it, it.reversed()) }.map { it.joinToString("") } .map { it.toInt(2) } } fun rotate(rotation: Int): CharGrid { var r = rotation var src = this if (r < 0) { while (r < 0) { val nextGrid = CharGrid(CharArray(width * height), width, height) (0 until height).forEach { row -> val rowContent = src.getRow(row).reversedArray() nextGrid.setColumn(row, rowContent) } r += 1 src = nextGrid } } else { while (r > 0) { val nextGrid = CharGrid(CharArray(width * height), width, height) (0 until height).forEach { row -> val rowContent = src.getRow(row) nextGrid.setColumn((width - 1) - row, rowContent) } r -= 1 src = nextGrid } } return src } private fun setColumn(col: Int, content: CharArray) { var index = col repeat(height) { grid[index] = content[it] index += width } } fun getRow(row: Int): CharArray { val start = row * width return grid.sliceArray(start until (start + width)) } private fun setRow(row: Int, content: CharArray) { val start = row * width val end = start + width (start until end).forEachIndexed { index, it -> grid[it] = content[index] } } fun getBorder(heading: Heading) { val trans = mapOf('.' to '0', '#' to '1') val thing = when (heading) { Heading.NORTH -> (0 until width).mapNotNull { trans[getCell_xy(it, 0)] } Heading.EAST -> (0 until height).mapNotNull { trans[getCell_xy(width - 1, it)] } Heading.SOUTH -> (0 until width).mapNotNull { trans[getCell_xy(it, height - 1)] } Heading.WEST -> (0 until height).mapNotNull { trans[getCell_xy(0, it)] } }.joinToString("") println(thing) // .map { it.toInt(2) } } fun flipAlongVerticalAxis(): CharGrid { var i = 0 var j = width - 1 val nextGrid = CharGrid(CharArray(width * height), width, height) while (i < j) { nextGrid.setColumn(j, getColumn(i)) nextGrid.setColumn(i, getColumn(j)) i++ j-- } if (i == j) { nextGrid.setColumn(i, getColumn(i)) } return nextGrid } fun flipAlongHorizontalAxis(): CharGrid { var i = 0 var j = height - 1 val nextGrid = CharGrid(CharArray(width * height), width, height) while (i < j) { nextGrid.setRow(j, getRow(i)) nextGrid.setRow(i, getRow(j)) i++ j-- } if (i == j) { nextGrid.setRow(i, getRow(j)) } return nextGrid } fun getColumn(col: Int): CharArray { val result = CharArray(height) var index = col repeat(height) { result[it] = grid[index] index += width } return result } fun stripBorder(): CharGrid { val nextWidth = width - 2 val nextHeight = height - 2 val nextGrid = CharGrid(CharArray(nextWidth * nextHeight), nextWidth, nextHeight) (1 .. nextHeight).forEach { row -> (1 .. nextHeight).forEach { col -> nextGrid.setCell_xy(col - 1, row - 1, getCell_xy(col, row)) } } return nextGrid } fun setCell_xy(x: Int, y: Int, ch: Char) { grid[coordsToIndex(x, y)] = ch } fun getPermutations(): List<CharGrid> { return getFlips().flatMap { it.getRotations() } } private fun getFlips(): List<CharGrid> { return listOf( this, this.flipAlongHorizontalAxis(), this.flipAlongVerticalAxis(), this.flipAlongHorizontalAxis().flipAlongVerticalAxis() ) } private fun getRotations(): List<CharGrid> { return (0..3).map { rotate(it) } } fun insertAt_xy(xOffset: Int, yOffset: Int, other: CharGrid) { repeat(other.height) { row -> val y = row + yOffset repeat(other.width) { col -> val x = col + xOffset setCell_xy(x, y, other.getCell_xy(col, row)) } } } fun findAll(predicate: (Int, Char) -> Boolean): List<Pair<Int, Char>> { return grid.withIndex().filter { (index, value) -> predicate(index, value) }.map { (index, value) -> index to value } } fun pivot(): CharGrid { val outGrid = CharGrid(CharArray(width * height), height, width) repeat(height) { row -> repeat(width) { col -> outGrid.setCell_xy(row, col, getCell_xy(col, row)) } } return outGrid } fun rotateClockwise(): CharGrid { val outGrid = CharGrid(CharArray(width * height), height, width) repeat(height) { row -> repeat(width) { col -> val outY = col val outX = (height - 1) - row val src = getCell_xy(col, row) outGrid.setCell_xy(outX, outY, src) } } return outGrid } fun rotateCounterClockwise(): CharGrid { val outGrid = CharGrid(CharArray(width * height), height, width) repeat(height) { row -> repeat(width) { col -> val outX = row val outY = (width - 1) - col val src = getCell_xy(col, row) outGrid.setCell_xy(outX, outY, src) } } return outGrid } operator fun set(it: Vector, value: Char) { this.setCell(it, value) } }
0
Kotlin
0
0
64870a6a42038acc777bee375110d2374e35d567
14,695
advent-of-code
MIT License
src/test/kotlin/Common.kt
christof-vollrath
317,635,262
false
null
import java.lang.IllegalArgumentException import kotlin.math.* fun readResource(name: String) = ClassLoader.getSystemClassLoader().getResource(name)?.readText() fun <T> List<List<T>>.transpose(): List<List<T>> { val result = mutableListOf<List<T>>() val n = get(0).size for (i in 0 until n) { val col = mutableListOf<T>() for (row in this) { col.add(row[i]) } result.add(col) } return result } fun <E> List<List<E>>.turnRight(): List<List<E>> { val result = mutableListOf<List<E>>() val n = this[0].size for (x in 0 until n) { val col = mutableListOf<E>() for (y in (n-1) downTo 0) { col.add(this[y][x]) } result.add(col) } return result } fun <E> List<E>.permute():List<List<E>> { if (size == 1) return listOf(this) val perms = mutableListOf<List<E>>() val sub = get(0) for(perm in drop(1).permute()) for (i in 0..perm.size){ val newPerm=perm.toMutableList() newPerm.add(i, sub) perms.add(newPerm) } return perms } fun <E> combine(e: Collection<Collection<E>>): Collection<Collection<E>> = if (e.isEmpty()) listOf(emptyList()) else { e.first().flatMap { firstVariant -> combine(e.drop(1)).map { listOf(firstVariant) + it } } } tailrec fun gcd(a: Int, b: Int): Int = // Greatest Common Divisor (Euclid, see: https://en.wikipedia.org/wiki/Greatest_common_divisor) when { a == 0 -> b b == 0 -> a a > b -> gcd(a-b, b) else -> gcd(a, b-a) } tailrec fun gcd(a: Long, b: Long): Long = when { a == 0L -> b b == 0L -> a a > b -> gcd(a-b, b) else -> gcd(a, b-a) } fun lcm(a: Int, b: Int) = abs(a * b) / gcd(a, b) // less common multiple (see: https://en.wikipedia.org/wiki/Least_common_multiple) fun lcm(numbers: List<Int>) = numbers.drop(1).fold(numbers[0]) { acc, curr -> lcm(acc, curr) } fun lcm(a: Long, b: Long) = abs(a * b) / gcd(a, b) fun lcm(numbers: List<Long>) = numbers.drop(1).fold(numbers[0]) { acc, curr -> lcm(acc, curr) } // see https://www.mathsisfun.com/polar-cartesian-coordinates.html data class PolarCoordinate(val dist: Double, val angle: Double) data class CartesianCoordinate(val x: Double, val y: Double) { fun toPolar(): PolarCoordinate { val dist = sqrt(x.pow(2) + y.pow(2)) val h = atan(y / x) val angle = when { x >= 0 && y >= 0 -> h // Quadrant I x < 0 && y >= 0 -> h + PI // Quadrant II x < 0 && y < 0 -> h + PI // Quadrant III x >= 0 && y < 0 -> h + PI * 2 // Quadrant IIII else -> throw IllegalArgumentException("Unkown quadrant for x=$x y=$y") } return PolarCoordinate(dist, angle) } } data class Coord2(val x: Int, val y: Int) { infix fun manhattanDistance(other: Coord2): Int = abs(x - other.x) + abs(y - other.y) operator fun plus(direction: Coord2) = Coord2(x + direction.x, y + direction.y) operator fun minus(direction: Coord2) = Coord2(x - direction.x, y - direction.y) operator fun times(n: Int) = Coord2(x * n, y * n) operator fun times(matrix: List<List<Int>>) = Coord2(x * matrix[0][0] + y * matrix[0][1], x * matrix[1][0] + y * matrix[1][1]) fun neighbors() = neighborOffsets.map { neighborOffset -> this + neighborOffset } fun neighbors8() = neighbor8Offsets.map { neighborOffset -> this + neighborOffset } companion object { val neighborOffsets = listOf(Coord2(-1, 0), Coord2(1, 0), Coord2(0, -1), Coord2(0, 1)) val neighbor8Offsets = (-1..1).flatMap { y -> (-1..1).mapNotNull { x -> if (x != 0 || y != 0) Coord2(x, y) else null } } val turnMatrixLeft = listOf( listOf(0, 1), listOf(-1, 0) ) val turnMatrixRight = listOf( listOf(0, -1), listOf(1, 0) ) } } typealias Plane<E> = List<List<E>> fun <E> Plane<E>.getOrNull(coord: Coord2): E? { return if (coord.y !in 0 until size) null else { val row = get(coord.y) if ( ! (0 <= coord.x && coord.x < row.size)) null else row[coord.x] } } data class Coord3(val x: Int, val y: Int, val z: Int) { operator fun plus(direction: Coord3) = Coord3(x + direction.x, y + direction.y, z + direction.z) operator fun minus(direction: Coord3) = Coord3(x - direction.x, y - direction.y, z - direction.z) operator fun times(n: Int) = Coord3(x * n, y * n, z * n) fun neighbors() = neighborOffsets.map { neighborOffset -> this + neighborOffset } fun neighbors26() = neighbor26Offsets.map { neighborOffset -> this + neighborOffset } companion object { val neighborOffsets = listOf(Coord3(-1, 0, 0), Coord3(1, 0, 0), Coord3(0, -1, 0), Coord3(0, 0, 1), Coord3(0, 0, -1), Coord3(0, 0, 1)) val neighbor26Offsets = (-1..1).flatMap { z -> (-1..1).flatMap { y -> (-1..1).mapNotNull { x -> if (x != 0 || y != 0 || z != 0) Coord3(x, y, z) else null } } } } } typealias Cube<E> = List<List<List<E>>> fun <E> Cube<E>.getOrNull(coord: Coord3): E? { return if (coord.z !in this.indices) null else { val layer = this[coord.z] if (coord.y !in layer.indices) null else { val row = layer[coord.y] if (!(0 <= coord.x && coord.x < row.size)) null else row[coord.x] } } } data class Coord4(val x: Int, val y: Int, val z: Int, val w: Int) { operator fun plus(direction: Coord4) = Coord4(x + direction.x, y + direction.y, z + direction.z, w + direction.w) fun neighbors80() = neighbor80Offsets.map { neighborOffset -> this + neighborOffset } companion object { val neighbor80Offsets = (-1..1).flatMap { w -> (-1..1).flatMap { z -> (-1..1).flatMap { y -> (-1..1).mapNotNull { x -> if (x != 0 || y != 0 || z != 0 || w != 0) Coord4(x, y, z, w) else null } } } } } }
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
6,413
advent_of_code_2020
Apache License 2.0
strings/RegularExpressionMatching/kotlin/Solution.kt
YaroslavHavrylovych
78,222,218
false
{"Java": 284373, "Kotlin": 35978, "Shell": 2994}
/** * Given an input string (s) and a pattern (p), implement * regular expression matching with support for '.' and '*' where: * '.' Matches any single character.​​​​ * '*' Matches zero or more of the preceding element. * The matching should cover the entire input string (not partial). * <br> * https://leetcode.com/problems/regular-expression-matching/ */ class Solution { fun isMatch(s: String, p: String): Boolean = isMatch(s, p, 0, 0) fun isMatch(s: String, p: String, si: Int, pi: Int): Boolean { if(pi >= p.length) { if(si >= s.length) return true return false } val ch = p[pi] val mult = if(pi + 1 >= p.length) false else p[pi + 1] == '*' if(!mult) { if(si >= s.length) return false else return (s[si] == ch || ch == '.') && isMatch(s, p, si + 1, pi + 1) } //we have a multi-match if(si >= s.length) return isMatch(s, p, si, pi + 2) //si < s.length val chs = s[si] var i = si if(ch == '.') { while(i < s.length) { if(isMatch(s, p, i++, pi + 2)) return true } } else if(ch == chs) { while(i < s.length && chs == s[i]) { if(isMatch(s, p, i++, pi + 2)) return true } } return isMatch(s, p, i, pi + 2) } } fun main() { println("Regular Expression Matching: test is not implemented") }
0
Java
0
2
cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd
1,356
codility
MIT License
src/Day11.kt
cagriyildirimR
572,811,424
false
{"Kotlin": 34697}
data class Monkey( val id: Int, var items: MutableList<Long> = mutableListOf(), var op: Operation = Operation("", 0), var test: Long = 0, var ifTrue: Int = 0, var ifFalse: Int = 0, var inspection: Long = 0 ) data class Operation(val type: String, val y: Long) { fun calculate(x: Long): Long { return when (type) { "*" -> x * y "+" -> x + y else -> x * x } } } fun day11Part1() { val ms = parseInput() calculate(ms, 20) { it / 3 } } fun day11Part2() { val ms = parseInput() calculate(ms, 10_000) { it % ms.map { it.test }.reduce(Long::times) } } fun calculate(ms: MutableList<Monkey>, n: Int, f: (Long) -> Long) { repeat(n) { for (monke in ms) { for (i in monke.items) { val w = f(monke.op.calculate(i)) monke.inspection++ if (w % monke.test == 0L) { with(ms[monke.ifTrue]) { items.add(w) } } else { with(ms[monke.ifFalse]) { items.add(w) } } } monke.items = mutableListOf() } } val x = ms.map { it.inspection }.sortedDescending() (x[0] * x[1]).print() } fun parseInput(): MutableList<Monkey> { val input = readInput("Day11") val ms = mutableListOf<Monkey>() var m = 0 // parsing input for (i in input) { when { i.take(6) == "Monkey" -> { ms.add(Monkey(m)) m++ } i.trim().take(5) == "Start" -> { i.takeLastWhile { it != ':' }.split(",").forEach { ms[m - 1].items.add(it.trim().toLong()) } } i.trim().take(9) == "Operation" -> { val p = i.takeLastWhile { it != '=' }.trim().split(" ") ms[m - 1].op = if (p[2] == "old") Operation("", 0) else Operation(p[1], p[2].toLong()) } i.trim().take(4) == "Test" -> { ms[m - 1].test = i.split(" ").last().toLong() } i.trim().take(7) == "If true" -> { ms[m - 1].ifTrue = i.split(" ").last().toInt() } i.trim().take(8) == "If false" -> { ms[m - 1].ifFalse = i.split(" ").last().toInt() } } } return ms }
0
Kotlin
0
0
343efa0fb8ee76b7b2530269bd986e6171d8bb68
2,471
AoC
Apache License 2.0
src/Day05.kt
simonitor
572,972,937
false
{"Kotlin": 8461}
fun main() { // first val (startBoard, movelist) = readFile("inputDay5").split("\n\n").map { it.split("\n") } val boardState = setupBoard(startBoard.toMutableList()) val parsedMoveList = parseMoveList(movelist) applyMoves(boardState, parsedMoveList) println(getTopOfStacks(boardState)) val boardState2 = setupBoard(startBoard.toMutableList()) applyMovesWithNewCrane(boardState2, parsedMoveList) println(getTopOfStacks(boardState2)) } fun setupBoard(startBoard: MutableList<String>): MutableMap<String, MutableList<Char>> { val coordinate = startBoard.removeLast() val boardState = emptyMap<String, MutableList<Char>>().toMutableMap() coordinate.filter { it != ' ' }.forEach { boardState[it.toString()] = emptyList<Char>().toMutableList() } for (i in startBoard.size - 1 downTo 0) { for (e in 0 until startBoard[i].length) { if (startBoard[i][e] !in " []".toSet()) { boardState[coordinate[e].toString()]?.add(startBoard[i][e]) } } } return boardState } fun parseMoveList(moves :List<String>): List<List<String>>{ return moves.map { moveInstruction -> moveInstruction.split(" ").filter { it.contains( Regex("[0-9]") ) } } } fun getTopOfStacks(boardState: MutableMap<String, MutableList<Char>>): String { return buildString { for (i in 1..boardState.size) { this.append(boardState[i.toString()]?.last()) } } } fun applyMoves(boardState: MutableMap<String, MutableList<Char>>, moveList: List<List<String>>) { moveList.forEach { val (amount, from, to) = it for (i in 0 until amount.toInt()) { val char = boardState[from]?.removeLast() ?: return boardState[to]?.add(char) } } } fun applyMovesWithNewCrane(boardState: MutableMap<String, MutableList<Char>>, moveList: List<List<String>>) { moveList.forEach { val (amount, from, to) = it val stack = boardState[from]?.takeLast(amount.toInt()) ?: return repeat(amount.toInt()) { boardState[from]?.removeLast() ?: return } boardState[to]?.addAll(stack) } }
0
Kotlin
0
0
11d567712dd3aaf3c7dee424a3442d0d0344e1fa
2,235
AOC2022
Apache License 2.0
src/Day10.kt
laricchia
434,141,174
false
{"Kotlin": 38143}
import kotlin.math.floor import kotlin.text.StringBuilder val openingChars = setOf('(', '[', '{', '<') val closingChars = setOf(')', ']', '}', '>') fun firstPart10(list : List<String>) { val errorsCount = mutableMapOf<Char, Int>() closingChars.map { errorsCount[it] = 0 } // val scopes = mutableListOf<Scope>() for (line in list) { val root = Scope('*', false, null) var currentScope = root lineCheck@ for (it in line.toCharArray()) { if (it in openingChars) { val newScope = Scope(it, false, currentScope) currentScope.child.add(newScope) currentScope = newScope } if (it in closingChars) { if (it == currentScope.openingChar.expectedClosing()) { currentScope.isClosed = true if (currentScope.parent != null) { val nextSibling = currentScope.parent!!.child.filterNot { it.isClosed }.lastOrNull() currentScope = nextSibling ?: currentScope.parent!! } else break@lineCheck } else { errorsCount[it] = errorsCount[it]!! + 1 break@lineCheck } } } } println(errorsCount.map { it.key.errorScore() * it.value }.sum()) } fun secondPart10(list : List<String>) { val incompleteLines = mutableListOf<Scope>() for (line in list) { val root = Scope('*', false, null) var currentScope = root incompleteLines.add(root) lineCheck@ for (it in line.toCharArray()) { if (it in openingChars) { val newScope = Scope(it, false, currentScope) currentScope.child.add(newScope) currentScope = newScope } if (it in closingChars) { if (it == currentScope.openingChar.expectedClosing()) { currentScope.isClosed = true if (currentScope.parent != null) { val nextSibling = currentScope.parent!!.child.filterNot { it.isClosed }.lastOrNull() currentScope = nextSibling ?: currentScope.parent!! } else break@lineCheck } else { incompleteLines.removeLast() break@lineCheck } } } } // println(incompleteLines.size) val completitionStrings = incompleteLines.map { val builder = StringBuilder() it.close(builder) builder.toString() } // println(completitionStrings) val scores = completitionStrings.map { it.removeSuffix("*").fold(0L) { acc, c -> (acc * 5) + c.completionScore() } } // println(scores.sorted()) println(scores.sorted()[floor(scores.size / 2.0).toInt()]) } fun main() { val input : List<String> = readInput("Day10") val list = input.filter { it.isNotBlank() } firstPart10(list) secondPart10(list) } data class Scope( val openingChar : Char, var isClosed : Boolean, val parent : Scope?, val child : MutableList<Scope> = mutableListOf(), ) fun Char.expectedClosing() : Char { return when (this) { '(' -> ')' '[' -> ']' '{' -> '}' '<' -> '>' else -> '*' } } fun Char.errorScore() : Int { return when (this) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 } } fun Char.completionScore() : Long { return when (this) { ')' -> 1 ']' -> 2 '}' -> 3 '>' -> 4 else -> 0 } } fun Scope.close(stringBuilder: StringBuilder) { val openChildren = child.filterNot { it.isClosed } openChildren.asReversed().map { it.close(stringBuilder) } if (!isClosed) stringBuilder.append(openingChar.expectedClosing()) }
0
Kotlin
0
0
7041d15fafa7256628df5c52fea2a137bdc60727
3,956
Advent_of_Code_2021_Kotlin
Apache License 2.0
src/main/kotlin/ru/glukhov/aoc/Day7.kt
cobaku
576,736,856
false
{"Kotlin": 25268}
package ru.glukhov.aoc fun main() { val shell = Problem.forDay("day7").use { val shell = Shell() it.forEachLine { val cmd = it.parseCommand() if (cmd != null) { shell.execute(cmd) } else { shell.appendOutput(it) } } return@use shell } println("Result of the first problem is ${shell.getFirstProblemOutput()}") println("Result of the second problem is ${shell.getSecondProblemOutput()}") } private fun String.parseCommand(): ShellCommand? { if (!this.startsWith("$")) { return null } val plain = this.substring(1).trim() return if (plain.startsWith("cd")) { ShellCommand(plain.replace("cd", "").trim(), ShellCommand.Type.CD) } else { ShellCommand("", ShellCommand.Type.LS) } } private fun String.parseFile(): Pair<String, Int> = this.split(" ").let { Pair(it[1].trim(), it[0].toInt()) } private class Shell { private var currentItem = Folder("/", 0, null, mutableListOf()) fun execute(cmd: ShellCommand) { if (cmd.cmd == ShellCommand.Type.CD) { currentItem = if (cmd.path == "/") { currentItem.toRoot() } else { currentItem.cd(cmd.path.trim()) } } } fun appendOutput(line: String) { if (line.startsWith("dir")) { val folderName = line.replace("dir", "") currentItem.addFolder(folderName.trim()) } val first = line.first() if (first.isDigit()) { val (name, size) = line.parseFile() currentItem.addFile(name, size) } } fun getFirstProblemOutput(): Int { return count(currentItem.toRoot()) } fun getSecondProblemOutput(): Int { val toRoot = currentItem.toRoot() val rootSize = toRoot.items.stream().mapToInt { it.size }.sum() val free = 70000000 - rootSize val required = 30000000 - free val target = mutableListOf<Folder>() findLessThan(required, toRoot, target) target.sortBy { it.size } return target.first().size } private fun count(root: Folder): Int { val selfSize = if (root.size > 100_000) 0 else root.size val entrySize = root.items.stream().filter { it.type == Item.Type.FOLDER } .mapToInt { count(it as Folder) } .sum() return selfSize + entrySize } private fun findLessThan(required: Int, root: Folder, target: MutableList<Folder>) { if (root.size >= required) { target.add(root) } root.items.stream() .filter { it.type == Item.Type.FOLDER } .map { it as Folder } .forEach { findLessThan(required, it, target) } } } private class ShellCommand(val path: String, val cmd: Type) { enum class Type { CD, LS; } } private open class Item(val name: String, val type: Type, var size: Int) { enum class Type { FOLDER, FILE } } private class Folder(name: String, size: Int, val root: Folder?, val items: MutableList<Item>) : Item(name, Type.FOLDER, size) { fun addFolder(name: String): Folder { val folder = Folder(name, 0, this, mutableListOf()) items.add(folder) return folder } fun addFile(name: String, size: Int) { this.size += size items.add(File(name, size)) incrementRootFolderSize(size) } fun cd(name: String): Folder { if (name == "..") { return this.root!! } return (items.find { it.name == name && it.type == Type.FOLDER } ?: addFolder(name)) as Folder } fun toRoot(): Folder { if (root == null) { return this } var fold = this while (fold.root != null) { fold = fold.root!! } return fold } fun incrementRootFolderSize(size: Int) { if (root == null) { return } var r = root while (r!!.root != null) { r.size += size r = r.root } } override fun toString(): String { return "${super.name} dir ($size)" } } private class File(name: String, size: Int) : Item(name, Type.FILE, size) { override fun toString(): String { return "${super.name} (file) $size" } }
0
Kotlin
0
0
a40975c1852db83a193c173067aba36b6fe11e7b
4,419
aoc2022
MIT License
src/Day03.kt
ochim
579,680,353
false
{"Kotlin": 3652}
fun main() { fun getScore(c: Char) = if (c.isLowerCase()) { c.code - 'a'.code + 1 } else { c.code - 'A'.code + 27 } fun part1(input: List<String>): Int { return input.sumOf { line -> val comp1 = line.substring(0, line.length / 2) val comp2 = line.substring(line.length / 2) getScore(comp1.first { it in comp2 }) } } fun part2(input: List<String>): Int { val groups = input.chunked(3) return groups.sumOf { (a, b, c) -> getScore(a.first { it in b && it in c }) } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") part1(input).println() part2(input).println() }
0
Kotlin
0
0
b5d34a8f0f3000c8ad4afd7726dd93171baee76e
804
advent-of-code-kotlin-2022
Apache License 2.0
21/part_two.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File fun readInput() : Game { val input = File("input.txt") .readLines() val posRegex = """Player (\d+) starting position: (\d+)""".toRegex() val (_, player1Pos) = posRegex.find(input[0])?.destructured!! val (_, player2Pos) = posRegex.find(input[1])?.destructured!! return Game(player1Pos.toInt(), player2Pos.toInt()) } @JvmName("plusLongLong") operator fun Pair<Long, Long>.plus(rhs : Pair<Long, Long>): Pair<Long, Long> { return Pair(first + rhs.first, second + rhs.second) } operator fun Pair<Int, Int>.plus(rhs : Pair<Int, Int>): Pair<Int, Int> { return Pair(first + rhs.first, second + rhs.second) } data class GameState(val playersPos : Pair<Int, Int>, val scores : Pair<Int, Int>, val playerToMove : Int) class Game(player1Pos : Int, player2Pos : Int) { companion object { const val DIE_MAX_VAL = 3 const val MIN_SCORE_TO_WIN = 21 const val MAX_POS = 10 const val ROLLS_PER_TURN = 3 const val PLAYER_1 = 0 const val FIRST_PLAYER_TO_MOVE = PLAYER_1 } private val playersPos = mutableListOf(player1Pos, player2Pos) private val allPossibleRolls = mutableListOf<Int>() init { calcPossibleDiceSum(0, ROLLS_PER_TURN) } fun calcUniverses() : Pair<Long, Long> { val dp = mutableMapOf<GameState, Pair<Long, Long>>() val initialGameState = GameState(Pair(playersPos[0], playersPos[1]), Pair(0, 0), FIRST_PLAYER_TO_MOVE) return solve(initialGameState, dp) } private fun calcPossibleDiceSum(curSum : Int, remainingRolls : Int) { if (remainingRolls == 0) { allPossibleRolls.add(curSum) } else { for (value in 1..DIE_MAX_VAL) { calcPossibleDiceSum(curSum + value, remainingRolls - 1) } } } private fun solve(gameState : GameState, dp : MutableMap<GameState, Pair<Long, Long>>) : Pair<Long, Long> { if (gameState.scores.first >= MIN_SCORE_TO_WIN) return Pair(1, 0) if (gameState.scores.second >= MIN_SCORE_TO_WIN) return Pair(0, 1) if (gameState in dp) return dp[gameState]!! var result = Pair(0L, 0L) for (roll in allPossibleRolls) { val newPlayersPos = calcPlayersPos(gameState.playersPos, gameState.playerToMove, roll) val newScore = calcScore(newPlayersPos, gameState.playerToMove, gameState.scores) val newPlayerToMove = nextPlayerToMove(gameState.playerToMove) val newGameState = GameState(newPlayersPos, newScore, newPlayerToMove) result += solve(newGameState, dp) } dp[gameState] = result return result } private fun calcPlayersPos(playersPos : Pair<Int, Int>, playerToMove : Int, diceSum : Int) : Pair<Int, Int> { var result = if (playerToMove == PLAYER_1) { Pair((playersPos.first + diceSum) % MAX_POS, playersPos.second) } else { Pair(playersPos.first, (playersPos.second + diceSum) % MAX_POS) } if (result.first == 0) { result = Pair(MAX_POS, result.second) } else if (result.second == 0) { result = Pair(result.first, MAX_POS) } return result } private fun calcScore(playersPos : Pair<Int, Int>, playerToMove : Int, scores: Pair<Int, Int>) : Pair<Int, Int> { return if (playerToMove == PLAYER_1) { scores + Pair(playersPos.first, 0) } else { scores + Pair(0, playersPos.second) } } private fun nextPlayerToMove(playerToMove: Int) : Int { return 1 - playerToMove } } fun solve(game : Game) : Long { val (player1Wins, player2Wins) = game.calcUniverses() return maxOf(player1Wins, player2Wins) } fun main() { val game = readInput() val ans = solve(game) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
3,882
advent-of-code-2021
MIT License
Kotlin/src/UniqueBinarySearchTrees.kt
TonnyL
106,459,115
false
null
/** * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? * * For example, * Given n = 3, there are a total of 5 unique BST's. * * 1 3 3 2 1 * \ / / / \ \ * 3 2 1 1 3 2 * / / \ \ * 2 1 2 3 * * Two solutions are all accepted. */ class UniqueBinarySearchTrees { // Recursive solution. Accepted. /*fun numTrees(n: Int): Int { if (n == 0 || n == 1) return 1 return (1..n).sumBy { numTrees(it - 1) * numTrees(n - it) } }*/ // Dynamic programming. fun numTrees(n: Int): Int { val array = IntArray(n + 2, { 0 }) array[0] = 1 array[1] = 1 for (i in 2..n) { for (j in 0 until i) { array[i] += array[j] * array[i - j - 1] } } return array[n] } }
1
Swift
22
189
39f85cdedaaf5b85f7ce842ecef975301fc974cf
954
Windary
MIT License
src/Day02.kt
allwise
574,465,192
false
null
import RockPaperScissors.Play.* import RockPaperScissors.Result.* import java.io.File fun main() { fun part1(input: List<String>): Int { val rpc = RockPaperScissors(input) return rpc.quick1() println(rpc.quick1()) } fun part2(input: List<String>): Int { val rpc = RockPaperScissors(input) return rpc.quick2() println(rpc.quick2()) } // 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)) } class RockPaperScissors(val input:List<String>) { var count = 0 var sum = 0 fun quick1(): Int { val mapit = 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 ) val sum = input.map { mapit[it] ?: 1 }.sum() return sum } fun quick2(): Int { val mapit = 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 ) val sum = input.map { mapit[it] ?: 1 }.sum() return sum } fun sumrounds() { val res = input.map { getGame(it) } .map { (calculateRound(it)) }.sum() val res2 = input.map { getGame2(it) } .map { (calculateRound(it)) }.sum() println("res is " + res) println("res 2 is " + res2) } fun calculateRound(round: Pair<Play, Play>): Int { count++ val shapeValue = shapeValue(round.second) val winnings = gameResult(round) //println("""$count [opponent: ${round.first}, mine:${round.second}]($shapeValue,$winnings)""") return shapeValue + winnings } fun gameResult(round: Pair<Play, Play>): Int { if (round.first == round.second) return 3 if (round.first == ROCK) { if (round.second == PAPER) return 6 else return 0 } else if (round.first == PAPER) { if (round.second == SCISSORS) return 6 else return 0 } else if (round.first == SCISSORS) { if (round.second == ROCK) return 6 else return 0 } return 0 } fun convert(action: String): Play { return when (action) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> ROCK } } fun convertRes(action: String): Result { return when (action) { "X" -> LOSE "Y" -> DRAW "Z" -> WIN else -> LOSE } } fun getGame(game: String): Pair<Play, Play> { //println("game " + game) val opponenet: Play = convert(game.split(" ").first()) val mine: Play = convert(game.split(" ").last()) //println("""[opponent: $opponenet, mine:$mine]""") return opponenet to mine } fun getGame2(game: String): Pair<Play, Play> { //println("game " + game) val opponenet: Play = convert(game.split(" ").first()) val result: Result = convertRes(game.split(" ").last()) val mine = getPlay(opponenet, result) //println("""[opponent: $opponenet, mine:$mine]""") return opponenet to mine } fun getPlay(opponent: Play, result: Result): Play { return when (result) { DRAW -> opponent WIN -> { when (opponent) { SCISSORS -> ROCK ROCK -> PAPER PAPER -> SCISSORS } } LOSE -> when (opponent) { SCISSORS -> PAPER ROCK -> SCISSORS PAPER -> ROCK } } } fun shapeValue(mine: Play): Int { // X - Rock 1 // Y - Paper 2 // Z - Scissors 3 return when (mine) { ROCK -> 1 PAPER -> 2 SCISSORS -> 3 else -> 0 } } enum class Play{ ROCK, PAPER, SCISSORS } enum class Result{ WIN, DRAW, LOSE } }
0
Kotlin
0
0
400fe1b693bc186d6f510236f121167f7cc1ab76
4,641
advent-of-code-2022
Apache License 2.0
src/Day11.kt
ostersc
572,991,552
false
{"Kotlin": 46059}
import java.util.function.Predicate data class Throw(val toMonkey: Int, val item: Long) class Monkey(instructions: List<String>) { var items = mutableListOf<Long>() var operation: (Long) -> Long = { old -> old } var test: Predicate<Long> = Predicate { item -> true } var trueTestMonkeyIndex = -1 var falseTestMonkeyIndex = -1 var inspectionCount = 0L var divisor = 1L init { check(instructions.size == 5) //starting items 0 items += instructions[0].substringAfter(':').split(',').toMutableList().map { it.trim().toLong() } //operation 1 val opsSplit = instructions[1].substringAfter('=').trim().split(' ') operation = { old -> val left = if (opsSplit.first() == "old") old else opsSplit.first().trim().toLong() val operation = opsSplit[1] val right = if (opsSplit.last() == "old") old else opsSplit.last().trim().toLong() when (operation) { "+" -> left + right "*" -> left * right else -> throw IllegalStateException("Unsupported operation ${opsSplit[1]}") } } divisor = instructions[2].substringAfterLast(' ').toLong() //test 2 test = Predicate { item -> //println(" comparing ${item} with divisor ${divisor}, returning ${item%divisor==0L}") item % divisor == 0L } // if true 3 trueTestMonkeyIndex = instructions[3].substringAfterLast(' ').toInt() // if false 4 falseTestMonkeyIndex = instructions[4].substringAfterLast(' ').toInt() } fun takeTurn(shouldDivide: Boolean, productOfDivisors: Long = 1L): List<Throw> { val throwList = mutableListOf<Throw>() // On a single monkey's turn, it inspects and throws // all of the items it is holding one at a time and in the order listed. for (i in 0..items.lastIndex) { inspectionCount++ //println(" Monkey inspects an item with a worry level of ${items.first()}.") //After each monkey inspects an item var newWorry = operation(items.first()) //println(" Worry level is now $newWorry") //before it tests your worry level, your worry level to be // divided by three and rounded down to the nearest integer if (shouldDivide) { newWorry = newWorry / 3 } else { newWorry = newWorry % productOfDivisors } //println(" Monkey gets bored with item. Worry level is divided by 3 to $newWorry.") var toMonkey = falseTestMonkeyIndex if (test.test(newWorry)) { toMonkey = trueTestMonkeyIndex } items.removeFirst() //println(" Item with worry level $newWorry is thrown to monkey $toMonkey.") throwList.add(Throw(toMonkey, newWorry)) } return throwList } } fun main() { fun part1(input: List<String>): Long { val monkeys = mutableListOf<Monkey>() input.windowed(7, 7, true) { monkeys += Monkey(it.subList(1, 6)) } for (round in 1..20) { for (m in monkeys) { //println("Monkey ") m.takeTurn(true).forEach { t -> monkeys[t.toMonkey].items.add(t.item) } //println() } } //sort by inspection count take(2).multiply return monkeys.sortedByDescending { it.inspectionCount }.let { it[0].inspectionCount * it[1].inspectionCount } } fun part2(input: List<String>): Long { val monkeys = mutableListOf<Monkey>() input.windowed(7, 7, true) { monkeys += Monkey(it.subList(1, 6)) } val productOfDivisors = monkeys.fold(1L) { result, m -> result * m.divisor } for (round in 1..10_000) { for (m in monkeys) { //println("Monkey ") m.takeTurn(false, productOfDivisors).forEach { t -> monkeys[t.toMonkey].items.add(t.item) } //println() //println("Monkey inspected ${m.inspectionCount} times") } } //sort by inspection count take(2).multiply return monkeys.sortedByDescending { it.inspectionCount }.let { it[0].inspectionCount * it[1].inspectionCount } } val testInput = readInput("Day11_test") var testResult = part1(testInput) check(testResult == 10605L) testResult = part2(testInput) check(testResult == 2713310158) val input = readInput("Day11") val part1 = part1(input) println(part1) check(part1 == 50172L) val part2 = part2(input) println(part2) check(part2 == 11614682178) }
0
Kotlin
0
1
3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9
4,789
advent-of-code-2022
Apache License 2.0
src/Day09.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
import kotlin.math.abs fun main() { fun getNumTailVisitedPositions(input: List<String>, ropeLength: Int): Int { val rope = MutableList(ropeLength) { Coordinates(0, 0) } val tailVisited = mutableSetOf<Coordinates>() tailVisited.add(rope.last()) for(line in input) { val split = line.split(' ') val direction = split[0] val amount = split[1].toInt() val vector = when(direction) { "U" -> Coordinates(-1, 0) "D" -> Coordinates(1, 0) "L" -> Coordinates(0, -1) "R" -> Coordinates(0, 1) else -> throw IllegalArgumentException("Unexpected direction: $direction") } repeat(amount) { rope[0] = rope[0].add(vector) for(i in 1 until rope.size) { val head = rope[i-1] val tail = rope[i] // Check distance if ((abs(head.col - tail.col) > 1) || (abs(head.row - tail.row) > 1)) { // Snap tail val moveCol = if (head.col == tail.col) 0 else (head.col - tail.col) / abs(head.col - tail.col) val moveRow = if (head.row == tail.row) 0 else (head.row - tail.row) / abs(head.row - tail.row) val tailVector = Coordinates(moveRow, moveCol) rope[i] = tail.add(tailVector) } } tailVisited.add(rope.last()) } } return tailVisited.size } val testInput = readInput("Day09_test") check(getNumTailVisitedPositions(testInput, 2) == 13) check(getNumTailVisitedPositions(testInput, 10) == 1) val testInput2 = readInput("Day09_test2") check(getNumTailVisitedPositions(testInput2, 10) == 36) val input = readInput("Day09") check(getNumTailVisitedPositions(input, 2) == 6030) println(getNumTailVisitedPositions(input, 2)) println(getNumTailVisitedPositions(input, 10)) }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
2,085
aoc2022
Apache License 2.0
dcp_kotlin/src/main/kotlin/dcp/day278/day278.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day278 data class BinaryTree(val left: BinaryTree?, val right: BinaryTree?) { companion object { // Memoize for efficiency. private val cache: MutableMap<Int, List<BinaryTree>> = mutableMapOf() fun constructAllTrees(numNodes: Int): List<BinaryTree> { // Boundary cases: there are 0 trees of size 0. if (numNodes == 0) return emptyList() // There is one node of size 1. if (numNodes == 1) return listOf(BinaryTree(null, null)) // Create a node and then append all combinations of i in [0, x-1] trees on the left and // j = x - 1 - i trees on the right. return (0 until numNodes).flatMap { leftNodes -> val rightNodes = numNodes - 1 - leftNodes val leftSubtrees = cache[leftNodes] ?: run { val trees = constructAllTrees(leftNodes) cache[leftNodes] = trees trees } val rightSubtrees = cache[rightNodes] ?: run { val trees = constructAllTrees(rightNodes) cache[rightNodes] = trees trees } // We need special cases when the left or right subtrees contain 0 nodes, as they must be null. // We have handled the corner when { leftNodes == 0 -> rightSubtrees.map { rightSubtree -> BinaryTree(null, rightSubtree) } rightNodes == 0 -> leftSubtrees.map { leftSubtree -> BinaryTree(leftSubtree, null) } else -> leftSubtrees.flatMap { leftSubtree -> rightSubtrees.map { rightSubtree -> BinaryTree(leftSubtree, rightSubtree) } } } } } // The number of BSTs over n nodes should equal the nth Catalan number. // We calculate it using dynamic programming. fun catalanNumber(n: Int): Int { if (n <= 1) return n val catalan: MutableList<Int> = MutableList(n + 1){0} catalan[0] = 1 catalan[1] = 1 (2..n).forEach { i -> (0 until i).forEach {j -> catalan[i] += catalan[j] * catalan[i - j - 1] } } return catalan[n] } } }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
2,493
daily-coding-problem
MIT License
src/Day08.kt
coolcut69
572,865,721
false
{"Kotlin": 36853}
fun main() { fun visibleFromTop(tree: Tree, trees: MutableList<Tree>): Boolean { val filter = trees.filter { tree.x > it.x && tree.y == it.y } val maxOf = filter.maxOf { it.height } return tree.height > maxOf } fun visibleFromBottom(tree: Tree, trees: MutableList<Tree>): Boolean { val filter = trees.filter { tree.x < it.x && tree.y == it.y } val maxOf = filter.maxOf { it.height } return tree.height > maxOf } fun visibleFromLeft(tree: Tree, trees: MutableList<Tree>): Boolean { val filter = trees.filter { tree.x == it.x && tree.y > it.y } val maxOf = filter.maxOf { it.height } return tree.height > maxOf } fun visibleFromRight(tree: Tree, trees: MutableList<Tree>): Boolean { val filter = trees.filter { tree.x == it.x && tree.y < it.y } val maxOf = filter.maxOf { it.height } return tree.height > maxOf } fun scenicScoreLeft(tree: Tree, trees: MutableList<Tree>): Int { val filter = trees.filter { right -> tree.x == right.x && tree.y > right.y } if (filter[0].height == tree.height) return 1 var i = 0 for (t in filter.reversed()) { if (t.height < tree.height) { i++ } if (t.height >= tree.height) { i++ return i } } return i } fun scenicScoreRight(tree: Tree, trees: MutableList<Tree>): Int { val filter = trees.filter { right -> tree.x == right.x && tree.y < right.y } if (filter[0].height == tree.height) return 1 var i = 0 for (t in filter) { if (t.height < tree.height) { i++ } if (t.height >= tree.height) { i++ return i } } return i } fun scenicScoreTop(tree: Tree, trees: MutableList<Tree>): Int { val filter = trees.filter { right -> tree.y == right.y && tree.x > right.x } if (filter[0].height == tree.height) return 1 var i = 0 for (t in filter.reversed()) { if (t.height < tree.height) { i++ } if (t.height >= tree.height) { i++ return i } } return i } fun scenicScoreBottom(tree: Tree, trees: MutableList<Tree>): Int { val filter = trees.filter { right -> tree.y == right.y && tree.x < right.x } if (filter[0].height == tree.height) return 1 var i = 0 for (t in filter) { if (t.height < tree.height) { i++ } if (t.height >= tree.height) { i++ return i } } return i } fun createForest(inputs: List<String>): MutableList<Tree> { val trees: MutableList<Tree> = ArrayList() for ((i, row) in inputs.withIndex()) { for ((j, char) in row.toList().withIndex()) { trees.add(Tree(i, j, char.toString().toInt())) } } return trees } fun part1(inputs: List<String>): Int { val forest: MutableList<Tree> = createForest(inputs) val maxX = forest.maxOf { tree -> tree.x } - 1 val maxY = forest.maxOf { tree -> tree.y } - 1 val visibleTrees: MutableSet<Tree> = HashSet() // check left to right and right to left for (i in (1..maxX)) { val leftToRight = forest.filter { tree -> tree.x == i && tree.y != 0 && tree.y != inputs.size - 1 } for (tree in leftToRight) { if (visibleFromLeft(tree, forest)) { visibleTrees.add(tree) } if (visibleFromRight(tree, forest)) { visibleTrees.add(tree) } } } for (i in (1..maxY)) { val topToBottom = forest.filter { tree -> tree.y == i && tree.x != 0 && tree.x != inputs.size - 1 } for (tree in topToBottom) { if (visibleFromTop(tree, forest)) { visibleTrees.add(tree) } if (visibleFromBottom(tree, forest)) { visibleTrees.add(tree) } } } return visibleTrees.size + forest.size - (maxX * maxY) } fun part2(inputs: List<String>): Int { val forest: MutableList<Tree> = createForest(inputs) val maxX = forest.maxOf { tree -> tree.x } - 1 val maxY = forest.maxOf { tree -> tree.y } - 1 val scenicScores: MutableSet<Int> = HashSet() // check left to right and right to left for (i in (1..maxX)) { val leftToRight = forest.filter { tree -> tree.x == i && tree.y != 0 && tree.y != inputs.size - 1 } for (tree in leftToRight) { val scenicScore = scenicScoreTop(tree, forest) * scenicScoreLeft(tree, forest) * scenicScoreBottom(tree, forest) * scenicScoreRight(tree, forest) scenicScores.add(scenicScore) } } return scenicScores.max() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") // println(part1(input)) check(part1(input) == 1538) // println(part2(input)) check(part2(input) == 496125) } data class Tree( val x: Int, val y: Int, val height: Int )
0
Kotlin
0
0
031301607c2e1c21a6d4658b1e96685c4135fd44
5,696
aoc-2022-in-kotlin
Apache License 2.0
src/DayThree.kt
P-ter
572,781,029
false
{"Kotlin": 18422}
import kotlin.math.roundToInt fun main() { fun partOne(input: List<String>): Int { var total = 0 input.forEach { line -> val middle = (line.length / 2.0).roundToInt() val firstHalf = line.substring(0, middle) val secondHalf = line.substring(middle) val intersection = firstHalf.toCharArray().toList().intersect(secondHalf.toCharArray().toList()) if (intersection.isNotEmpty()) { intersection.forEach { if(it.isLowerCase()) { total += it.code - 96 } else if (it.isUpperCase()) { total += it.code - 64 + 26 } } } } return total } fun partTwo(input: List<String>): Int { var total = 0 input.chunked(3).forEach { group -> val first = group[0] val second = group[1] val third = group[2] val firstSecond = first.toCharArray().toList().intersect(second.toCharArray().toList()) val secondThird = second.toCharArray().toList().intersect(third.toCharArray().toList()) val firstThird = first.toCharArray().toList().intersect(third.toCharArray().toList()) val intersection = firstSecond.intersect(secondThird).intersect(firstThird) if (intersection.isNotEmpty()) { intersection.forEach { if(it.isLowerCase()) { total += it.code - 96 } else if (it.isUpperCase()) { total += it.code - 64 + 26 } } } } return total } val input = readInput("daythree") println(partOne(input)) println(partTwo(input)) }
0
Kotlin
0
1
e28851ee38d6de5600b54fb884ad7199b44e8373
1,847
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/d3/d3.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d3 import readInput fun part1(input: List<String>): Int { var sum = 0 for (line in input) { val comp1 = line.substring(0, line.length/2) val comp2 = line.substring(line.length/2) val set1 = comp1.toSet() for (elt in comp2) if (elt in set1) { println("${elt} - ${prio(elt)}") sum += prio(elt) break } } return sum } fun prio(elt: Char): Int { if (elt in 'a'..'z') return 1 + (elt - 'a') return 27 + (elt -'A') } fun part2(input: List<String>): Int { var sum = 0 for (group in 0 until input.size step 3) { val set1 = input[group].toSet() val set2 = input[group+1].toSet() val set3 = input[group+2].toSet() val common = set1.intersect(set2).intersect(set3) println("${common} - ${prio(common.first())}") sum += prio(common.first()) } return sum } fun main() { //val input = readInput("d3/test") val input = readInput("d3/input1") println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
1,079
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/de/niemeyer/aoc2022/Day03.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
/** * Advent of Code 2022, Day 3: Rucksack Reorganization * Problem Description: https://adventofcode.com/2022/day/3 */ package de.niemeyer.aoc2022 import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName fun main() { fun part1(input: List<String>): Int = input.map { rucksack -> val compartmentItems = rucksack.chunked(rucksack.length / 2).map { it.toCharArray().toSet() } val inter = compartmentItems[0].intersect(compartmentItems[1]) inter.first().priority() }.sum() fun part2(input: List<String>): Int = input.windowed(3, 3).map { rucksacks -> val rucksackItems = rucksacks.map { it.toCharArray().toSet() } val inter = rucksackItems.reduce { acc, set -> acc.intersect(set) } inter.first().priority() }.sum() val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt") val puzzleInput = resourceAsList(fileName = "${name}.txt") check(part1(testInput) == 157) println(part1(puzzleInput)) check(part1(puzzleInput) == 7_817) check(part2(testInput) == 70) println(part2(puzzleInput)) check(part2(puzzleInput) == 2_444) } fun Char.priority(): Int = when (this) { in 'a'..'z' -> this - 'a' + 1 else -> this - 'A' + 27 }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
1,351
AoC-2022
Apache License 2.0
src/Day02.kt
semanticer
577,822,514
false
{"Kotlin": 9812}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val roundInputs = it.split(" ") val opponent = roundInputs[0].toOpponentWeapon() val me = roundInputs[1].toMyWeapon() clashOfWeapons(opponent, me) } } fun part2(input: List<String>): Int { return input.sumOf { val roundInputs = it.split(" ") val opponent = roundInputs[0].toOpponentWeapon() val desiredOutcome = roundInputs[1].toDesiredRoundOutcome() clashOfWeaponsWithDesiredOutcome(opponent, desiredOutcome) } } // 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") part1(input).println() part2(input).println() } sealed class Weapon(val value: Int) { object Rock : Weapon(1) object Paper : Weapon(2) object Scissors : Weapon(3) } sealed class Outcome(val value: Int) { object Lose : Outcome(0) object Draw : Outcome(3) object Win : Outcome(6) } fun String.toOpponentWeapon() = when (this) { "A" -> Weapon.Rock "B" -> Weapon.Paper "C" -> Weapon.Scissors else -> throw IllegalArgumentException("Unknown opponent weapon: $this") } fun String.toMyWeapon() = when (this) { "X" -> Weapon.Rock "Y" -> Weapon.Paper "Z" -> Weapon.Scissors else -> throw IllegalArgumentException("Unknown opponent weapon: $this") } fun String.toDesiredRoundOutcome() = when (this) { "X" -> Outcome.Lose "Y" -> Outcome.Draw "Z" -> Outcome.Win else -> throw IllegalArgumentException("Unknown opponent weapon: $this") } fun clashOfWeapons(opponent: Weapon, me: Weapon): Int { val result = when (opponent) { Weapon.Rock -> when (me) { Weapon.Rock -> Outcome.Draw Weapon.Paper -> Outcome.Win Weapon.Scissors -> Outcome.Lose } Weapon.Paper -> when (me) { Weapon.Rock -> Outcome.Lose Weapon.Paper -> Outcome.Draw Weapon.Scissors -> Outcome.Win } Weapon.Scissors -> when (me) { Weapon.Rock -> Outcome.Win Weapon.Paper -> Outcome.Lose Weapon.Scissors -> Outcome.Draw } } return result.value + me.value } fun clashOfWeaponsWithDesiredOutcome(opponent: Weapon, outcome: Outcome): Int { val weapon = when (opponent) { Weapon.Rock -> when (outcome) { Outcome.Draw -> Weapon.Rock Outcome.Win -> Weapon.Paper Outcome.Lose -> Weapon.Scissors } Weapon.Paper -> when (outcome) { Outcome.Lose -> Weapon.Rock Outcome.Draw -> Weapon.Paper Outcome.Win -> Weapon.Scissors } Weapon.Scissors -> when (outcome) { Outcome.Win -> Weapon.Rock Outcome.Lose -> Weapon.Paper Outcome.Draw -> Weapon.Scissors } } return weapon.value + outcome.value }
0
Kotlin
0
0
9013cb13f0489a5c77d4392f284191cceed75b92
3,103
Kotlin-Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2023/day16/Day16.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day16 import com.jacobhyphenated.advent2023.Day /** * Day 16: The Floor Will Be Lava * * A beam of light gets reflected and split throughout the puzzle input. * The beam travels one space at a time in a specific direction. * '.' does nothing, the beam continues onward * '-' if the beam is traveling north/south, split the beam into two heading west+east * '|' if the beam is traveling east/west, split the beam into two heading north+south * '/' reflect the beam 90 degrees * '\' reflect the beam the opposite 90 degrees */ class Day16: Day<List<List<Char>>> { override fun getInput(): List<List<Char>> { return readInputFile("16").lines().map { it.toCharArray().toList() } } /** * Part 1: The beam starts in the top left corner heading east. * If the beam passes through a space, then that space is energized. * How many spaces does this beam energize? */ override fun part1(input: List<List<Char>>): Int { // start just off the edge of the grid, so we properly interact with the first space val startBeam = Beam(Pair(0,-1), Direction.EAST) return energizedSpacesFromStartingEdge(startBeam, input) } /** * Part 2: The beam can enter from any edge (top down, bottom up, left to right, right to left) * What is the maximum number of spaces that can become energized? */ override fun part2(input: List<List<Char>>): Any { val startTop = input[0].indices.map { col -> Beam(Pair(-1, col), Direction.SOUTH) } val startBottom = input[0].indices.map { col -> Beam(Pair(input.size, col), Direction.NORTH) } val startLeft = input.indices.map { row -> Beam(Pair(row, -1), Direction.EAST) } val startRight = input.indices.map { row -> Beam(Pair(row, input[0].size), Direction.WEST) } return (startTop + startBottom + startLeft + startRight).maxOf { energizedSpacesFromStartingEdge(it, input) } } /** * Count the number of spaces the beam passes through */ private fun energizedSpacesFromStartingEdge(startBeam: Beam, input: List<List<Char>>): Int { // keep track of both position and direction. If a beam repeats this, we can ignore it val visited = mutableSetOf<Beam>() var beams = listOf(startBeam) visited.add(startBeam) // go until we have no more beams to follow while (beams.isNotEmpty()) { beams = beams.flatMap { moveBeam(it, input) } .filter { it !in visited } visited.addAll(beams) } // reduce the visited set to just locations, and count them // note: subtract 1 because the first location is always off the edge of the grid return visited.map { it.location }.toSet().size - 1 } /** * Determine the next location and direction of the given beam. * @return a list as the splitters can create multiple beams from a single beam */ private fun moveBeam(beam: Beam, grid: List<List<Char>>): List<Beam> { val (currentRow, currentCol) = beam.location val newLocation = when(beam.direction) { Direction.EAST -> Pair(currentRow, currentCol + 1) Direction.WEST -> Pair(currentRow, currentCol - 1) Direction.NORTH -> Pair(currentRow - 1, currentCol) Direction.SOUTH -> Pair(currentRow + 1, currentCol) } val (row, col) = newLocation if (row < 0 || row >= grid.size || col < 0 || col >= grid[0].size) { return emptyList() } return when (grid[row][col]) { '.' -> listOf(Beam(newLocation, beam.direction)) '-' -> when (beam.direction) { Direction.WEST, Direction.EAST -> listOf(Beam(newLocation, beam.direction)) Direction.NORTH, Direction.SOUTH -> listOf(Beam(newLocation, Direction.EAST), Beam(newLocation, Direction.WEST)) } '|' -> when (beam.direction) { Direction.NORTH, Direction.SOUTH -> listOf(Beam(newLocation, beam.direction)) Direction.EAST, Direction.WEST -> listOf(Beam(newLocation, Direction.NORTH), Beam(newLocation, Direction.SOUTH)) } '/' -> when (beam.direction) { Direction.NORTH -> listOf(Beam(newLocation, Direction.EAST)) Direction.SOUTH -> listOf(Beam(newLocation, Direction.WEST)) Direction.EAST -> listOf(Beam(newLocation, Direction.NORTH)) Direction.WEST -> listOf(Beam(newLocation, Direction.SOUTH)) } '\\' -> when (beam.direction) { Direction.NORTH -> listOf(Beam(newLocation, Direction.WEST)) Direction.SOUTH -> listOf(Beam(newLocation, Direction.EAST)) Direction.EAST -> listOf(Beam(newLocation, Direction.SOUTH)) Direction.WEST -> listOf(Beam(newLocation, Direction.NORTH)) } else -> throw IllegalArgumentException("Invalid character ${grid[row][col]}") } } override fun warmup(input: List<List<Char>>) { part1(input) } } data class Beam(val location: Pair<Int,Int>, val direction: Direction) enum class Direction { NORTH, EAST, SOUTH, WEST } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day16().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
4,996
advent2023
The Unlicense
src/Day18.kt
rosyish
573,297,490
false
{"Kotlin": 51693}
typealias Cube = Triple<Int, Int, Int> fun main() { val cubes = readInput("Day18_input").map { val (x, y, z) = it.split(",").map { it.toInt() } Cube(x, y, z) }.toSet() val minDim = cubes.flatMap { it.toList() }.min() val maxDim = cubes.flatMap { it.toList() }.max() fun Cube.getAdjacent(): List<Cube> { return listOf( Cube(0, 0, 1), Cube(0, 0, -1), Cube(0, 1, 0), Cube(0, -1, 0), Cube(-1, 0, 0), Cube(1, 0, 0)) .map { Cube(it.first + this.first, it.second + this.second, it.third + this.third) } .toList() } // Part 1 var adj = 0 for (cube in cubes) { for (adjCube in cube.getAdjacent()) { if (cubes.contains(adjCube)) { adj++ } } } println(cubes.size * 6 - adj) // Part 2 fun outsideBounds(cube: Cube): Boolean { return cube.toList().firstOrNull { it < minDim - 1 || it > maxDim + 1 } != null } val visited = mutableSetOf<Cube>() fun bfs(startCube: Cube) { val queue = ArrayDeque<Cube>() queue.add(startCube) while (queue.isNotEmpty()) { val airCube = queue.removeFirst() if (visited.contains(airCube)) { continue } visited.add(airCube) for (newAirCube in airCube.getAdjacent()) { if (!cubes.contains(newAirCube) && !visited.contains(newAirCube) && !outsideBounds(newAirCube) ) { queue += newAirCube } } } } // recursion stack overflows, so do BFS bfs(Cube(minDim - 1, minDim - 1, minDim - 1)) var result = 0 for (cube in cubes) { for (adjCube in cube.getAdjacent()) { if (visited.contains(adjCube)) result++ } } println(result) }
0
Kotlin
0
2
43560f3e6a814bfd52ebadb939594290cd43549f
1,961
aoc-2022
Apache License 2.0
advent-of-code-2023/src/Day10.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import lib.matrix.* private typealias Maze = Matrix<Pipe> private typealias MazeRow = List<Pipe> private const val DAY = "Day10" fun main() { fun testInput(id: Int) = readInput("${DAY}_test$id") fun input() = readInput(DAY) "Part 1" { part1(testInput(0)) shouldBe 4 part1(testInput(1)) shouldBe 8 measureAnswer { part1(input()) } } "Part 2" { part2(testInput(2)) shouldBe 4 part2(testInput(3)) shouldBe 4 part2(testInput(4)) shouldBe 8 part2(testInput(5)) shouldBe 10 measureAnswer { part2(input()) } } } private fun part1(maze: Maze): Int = findLoop(maze).size / 2 private fun part2(maze: Maze): Int { val loop = findLoop(maze) // Ignore first and last row as it cannot contain tiles lying inside loop return (1..<maze.lastRowIndex).sumOf { row -> countInnerTilesInRow( row = maze.row(row), isPartOfLoop = { col -> Position(row, col) in loop }, ) } } // Idea is to track flag "if we are inside loop". Initially we are outside, // but if we face ║, ╔╝ or ╚╗ - we change the flag to the opposite. // Combinations ╔╗ and ╚╝ doesn't affect the flag. Horizontal pipes just ignored. private fun countInnerTilesInRow(row: MazeRow, isPartOfLoop: (col: Int) -> Boolean): Int { var tilesInsideLoop = 0 var insideLoop = false var savedTile: Pipe? = null for ((col, tile) in row.withIndex()) { if (isPartOfLoop(col)) { when (tile) { Pipe.LEFT_RIGHT -> Unit // skip Pipe.TOP_BOTTOM -> insideLoop = !insideLoop else -> { if (tile == savedTile?.opposite) insideLoop = !insideLoop savedTile = if (savedTile == null) tile else null } } } else if (insideLoop) { tilesInsideLoop++ } } return tilesInsideLoop } private fun readInput(name: String) = readMatrix(name) { it.map(Pipe::bySymbol) } /** Returns set of positions making loop. Replaces start tile with pipe. */ private fun findLoop(maze: Maze): Set<Position> { val startPosition = findStartPosition(maze) var (comeFromSide, position) = sequenceOf(SIDE_TOP, SIDE_BOTTOM, SIDE_LEFT, SIDE_RIGHT) .map { side -> side to startPosition.nextBySide(side) } .filter { (_, position) -> position in maze } .first { (comeFromSide, position) -> maze[position].canBeReachedFrom(comeFromSide) } val startSide = comeFromSide return buildSet { add(position) while (position != startPosition) { val pipe = maze[position] val sideToGo = pipe.nextSideToGo(comeFromSide) position = position.nextBySide(sideToGo) comeFromSide = sideToGo add(position) } }.also { // Replace start tile with derived pipe tile maze[startPosition] = Pipe.bySides(startSide or sideOppositeTo(comeFromSide)) } } private fun findStartPosition(maze: Maze): Position { for (row in maze.rowIndices) { for (col in maze.columnIndices) { if (maze[row, col] == Pipe.START) { return Position(row, col) } } } error("Start position not found") } private enum class Pipe(val symbol: Char, val sides: Int) { TOP_LEFT(symbol = 'J', sides = SIDE_TOP or SIDE_LEFT), TOP_BOTTOM(symbol = '|', sides = SIDE_TOP or SIDE_BOTTOM), TOP_RIGHT(symbol = 'L', sides = SIDE_TOP or SIDE_RIGHT), LEFT_RIGHT(symbol = '-', sides = SIDE_LEFT or SIDE_RIGHT), LEFT_BOTTOM(symbol = '7', sides = SIDE_LEFT or SIDE_BOTTOM), RIGHT_BOTTOM(symbol = 'F', sides = SIDE_RIGHT or SIDE_BOTTOM), START(symbol = 'S', sides = MASK_NONE), EMPTY(symbol = '.', sides = MASK_NONE); val opposite: Pipe get() = Pipe.bySides(sides xor MASK_ALL) fun nextSideToGo(comeFromSide: Int): Int = sides xor sideOppositeTo(comeFromSide) fun canBeReachedFrom(side: Int): Boolean = sideOppositeTo(side) or sides == sides companion object { fun bySymbol(symbol: Char): Pipe = entries.first { it.symbol == symbol } fun bySides(sides: Int): Pipe = entries.first { it.sides == sides } } } private fun Position.nextBySide(side: Int): Position { return when (side) { SIDE_TOP -> offsetBy(row = -1) SIDE_BOTTOM -> offsetBy(row = +1) SIDE_LEFT -> offsetBy(column = -1) SIDE_RIGHT -> offsetBy(column = +1) else -> error("Unexpected side: $side") } } private fun sideOppositeTo(side: Int): Int = when (side) { SIDE_TOP, SIDE_BOTTOM -> MASK_HORIZONTAL xor side SIDE_LEFT, SIDE_RIGHT -> MASK_VERTICAL xor side else -> error("Unexpected side: $side") } private const val MASK_ALL = 0b1111 private const val MASK_HORIZONTAL = 0b1100 private const val MASK_VERTICAL = 0b0011 private const val MASK_NONE = 0b0000 private const val SIDE_TOP = 0b1000 private const val SIDE_BOTTOM = 0b0100 private const val SIDE_LEFT = 0b0010 private const val SIDE_RIGHT = 0b0001
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
5,097
advent-of-code
Apache License 2.0
src/Day04.kt
aemson
577,677,183
false
{"Kotlin": 7385}
fun main() { val inputData = readInput("Day04_input") val campOrder: List<Pair<List<Int>, List<Int>>> = inputData.map { input -> val sectionsMap = input.split(",").map { val split = it.split("-") val start = split[0].toInt() val end = split[1].toInt() var numbs = mutableListOf<Int>() for (i in start..end) { numbs.add(i) } numbs.toList() } val firstList = sectionsMap[0] val secondList = sectionsMap[1] firstList to secondList } println("Camp Cleanup (Part 1) -> ${partOneSolution(campOrder)}") println("Camp Cleanup (Part 2) -> ${partTwoSolution(campOrder)}") } fun partOneSolution(campOrder: List<Pair<List<Int>, List<Int>>>) = campOrder.map { (firstList, secondList) -> if (firstList.containsAll(secondList) || secondList.containsAll(firstList)) 1 else 0 }.sum() fun partTwoSolution(campOrder: List<Pair<List<Int>, List<Int>>>) = campOrder.map { (firstList, secondList) -> if (firstList.intersect(secondList.toSet()).isNotEmpty() || secondList.intersect(firstList.toSet()) .isNotEmpty() ) 1 else 0 }.sum()
0
Kotlin
0
0
ffec4b848ed5c2ba9b2f2bfc5b991a2019c8b3d4
1,291
advent-of-code-22
Apache License 2.0
src/Day02.kt
tstellfe
575,291,176
false
{"Kotlin": 8536}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val opponent = it.split(" ")[0] val mine = it.split(" ")[1] RockPaperScissor.from(opponent)!!.score(mine) } } fun part2(input: List<String>): Int { return input.sumOf { val opponent = it.split(" ")[0] val mine = it.split(" ")[1] RockPaperScissor.from(opponent)!!.roundResult(mine) } } val testInput = readInput("Day02_test") val input = readInput("Day02") println(part2(testInput)) println(part2(input)) } enum class RockPaperScissor(val input: String) { ROCK("A") { override fun score(input: String): Int = when (input) { "X" -> 1 + 3 "Y" -> 2 + 6 "Z" -> 3 + 0 else -> throw Exception() } override fun roundResult(input: String): Int = when (input) { "X" -> score("Z") "Y" -> score("X") "Z" -> score("Y") else -> throw Exception() } }, PAPER("B") { override fun score(input: String): Int = when (input) { "X" -> 1 + 0 "Y" -> 2 + 3 "Z" -> 3 + 6 else -> throw Exception() } override fun roundResult(input: String): Int = when (input) { "X" -> score("X") "Y" -> score("Y") "Z" -> score("Z") else -> throw Exception() } }, SCISSOR("C") { override fun score(input: String): Int = when (input) { "X" -> 1 + 6 "Y" -> 2 + 0 "Z" -> 3 + 3 else -> throw Exception() } override fun roundResult(input: String): Int = when (input) { "X" -> score("Y") "Y" -> score("Z") "Z" -> score("X") else -> throw Exception() } }; abstract fun score(input: String): Int abstract fun roundResult(input: String): Int companion object { fun from(input: String): RockPaperScissor? = values().firstOrNull { it.input == input } } }
0
Kotlin
0
0
e100ba705c8e2b83646b172d6407475c27f02eff
1,866
adventofcode-2022
Apache License 2.0
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/Subsets.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* Use this technique when the problem asks to deal with permutations or combinations of a set of elements. The "Subsets" coding pattern is different from the "Two Heaps" pattern. The "Subsets" pattern is commonly used to generate all possible subsets of a set, while the "Two Heaps" pattern is used for efficiently solving problems involving two heaps, typically to find medians, intervals, or other order statistics. */ //1. String Permutations by changing case fun letterCasePermutation(S: String): List<String> { val result = mutableListOf<String>() generatePermutations(S.toCharArray(), 0, result) return result } fun generatePermutations(chars: CharArray, index: Int, result: MutableList<String>) { if (index == chars.size) { result.add(String(chars)) return } if (chars[index].isLetter()) { chars[index] = chars[index].toLowerCase() generatePermutations(chars, index + 1, result) chars[index] = chars[index].toUpperCase() generatePermutations(chars, index + 1, result) } else { generatePermutations(chars, index + 1, result) } } fun main() { val input = "a1b2" val result = letterCasePermutation(input) println("String Permutations by changing case: $result") } //2. Unique Generalized Abbreviations fun generateAbbreviations(word: String): List<String> { val result = mutableListOf<String>() generateAbbreviationsRecursive(word.toCharArray(), 0, 0, StringBuilder(), result) return result } fun generateAbbreviationsRecursive( chars: CharArray, index: Int, count: Int, current: StringBuilder, result: MutableList<String> ) { if (index == chars.size) { if (count > 0) { current.append(count) } result.add(current.toString()) return } // Abbreviate the current character generateAbbreviationsRecursive(chars, index + 1, count + 1, current, result) // Include the current character without abbreviation if (count > 0) { current.append(count) } current.append(chars[index]) generateAbbreviationsRecursive(chars, index + 1, 0, current, result) // Backtrack current.setLength(current.length - (count + 1)) } fun main() { val word = "word" val result = generateAbbreviations(word) println("Unique Generalized Abbreviations: $result") }
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
2,391
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/Day02.kt
AxelUser
572,845,434
false
{"Kotlin": 29744}
fun main() { val wins = hashMapOf( 1 to 3, 2 to 1, 3 to 2 ) fun List<String>.solve1(): Int { var score = 0 for (round in this) { val opponent = round[0] - 'A' + 1 val player = round[2] - 'X' + 1 if (opponent == player) { score += 3 // draw } else if (wins[player] == opponent) { score += 6 // win } score += player } return score } fun List<String>.solve2(): Int { val loses = wins.map { (w,l) -> l to w }.toMap() var score = 0 for (round in this) { val opponent = round[0] - 'A' + 1 val player = when(round[2]) { 'X' -> wins[opponent]!! 'Y' -> opponent 'Z' -> loses[opponent]!! else -> error("invalid option ${round[2]}") } score += player + (round[2] - 'X') * 3 } return score } fun part1(input: List<String>): Int { return input.solve1() } fun part2(input: List<String>): Int { return input.solve2() } check(part1(readInput("Day02_test")) == 15) check(part2(readInput("Day02_test")) == 12) println(part1(readInput("Day02"))) println(part2(readInput("Day02"))) }
0
Kotlin
0
1
042e559f80b33694afba08b8de320a7072e18c4e
1,358
aoc-2022
Apache License 2.0
src/Day05.kt
szymon-kaczorowski
572,839,642
false
{"Kotlin": 45324}
fun main() { fun part1(input: List<String>): String { var i = 0 while (input[i].isNotBlank()) { i++ } var totalStacks = input[i - 1].last().toString().toInt() var crane = (1..totalStacks).map { mutableListOf<Char>() }.toMutableList() for (j in 0.until(i)) { var stacks = input[j] for (k in 0.until(totalStacks)) { if (stacks.length > k * 4 + 1) { val c = stacks[k * 4 + 1] if (c.isWhitespace()) { } else { if (!c.isDigit()) { crane[k].add(0, c) println(crane) } } } } } for (command in (i + 1).until(input.size)) { var commandText = input[command] var commandPieces = commandText.split(" ") var amount = commandPieces[1].toInt() var from = commandPieces[3].toInt() var into = commandPieces[5].toInt() for (calc in 1..amount) { crane[into - 1].add(crane[from - 1].last()) crane[from - 1].removeLast() } } return crane.map { it.last() }.joinToString(separator = "") { it.toString() } } fun part2(input: List<String>): String { var i = 0 while (input[i].isNotBlank()) { i++ } println(input[i - 1]) var totalStacks = input[i - 1].last().toString().toInt() var crane = (1..totalStacks).map { mutableListOf<Char>() }.toMutableList() for (j in 0.until(i)) { var stacks = input[j] for (k in 0.until(totalStacks)) { if (stacks.length > k * 4 + 1) { val c = stacks[k * 4 + 1] if (c.isWhitespace()) { } else { if (!c.isDigit()) { crane[k].add(0, c) } } } } } for (command in (i + 1).until(input.size)) { var commandText = input[command] var commandPieces = commandText.split(" ") var amount = commandPieces[1].toInt() var from = commandPieces[3].toInt() var into = commandPieces[5].toInt() var temp = mutableListOf<Char>() for (calc in 1..amount) { temp += crane[from - 1].removeLast() } crane[into-1].addAll(temp.reversed()) } return crane.map { it.last() }.joinToString(separator = "") { it.toString() }.also { println(it) } } // 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
1d7ab334f38a9e260c72725d3f583228acb6aa0e
3,075
advent-2022
Apache License 2.0
src/main/kotlin/days/Day14.kt
hughjdavey
225,440,374
false
null
package days import kotlin.math.ceil class Day14 : Day(14) { override fun partOne(): Any { return NanoFactory(inputList).minimumOreForOneFuel() } override fun partTwo(): Any { return NanoFactory(inputList).maxFuelForOre(ONE_TRILLION) } data class ChemicalQuantity(val chemical: String, var quantity: Long) data class Reaction(val output: ChemicalQuantity, val inputs: List<ChemicalQuantity>) class NanoFactory(reactionsList: List<String>) { val reactions = reactionsList.map { parseReaction(it) } fun minimumOreForOneFuel(): Long { return getFuel(1) } fun maxFuelForOre(maxOre: Long): Long { var lo = maxOre / minimumOreForOneFuel() var hi = maxOre while (lo < hi - 1) { val fuelAmount = (lo + hi) / 2 val ore = getFuel(fuelAmount) when { ore < maxOre -> lo = fuelAmount ore == maxOre -> return fuelAmount else -> hi = fuelAmount } } return lo } private fun getFuel(quantity: Long): Long { val have = mutableMapOf<String, Long>() var ore = 0L fun makeChemical(chemicalQuantity: ChemicalQuantity) { if (chemicalQuantity.chemical == "ORE") { ore += chemicalQuantity.quantity return } val required = chemicalQuantity.quantity - have.getOrDefault(chemicalQuantity.chemical, 0) if (required > 0) { val reaction = reactions.find { it.output.chemical == chemicalQuantity.chemical }!! val multiplier = ceil(required.toDouble() / reaction.output.quantity).toInt() for (input in reaction.inputs) { makeChemical(ChemicalQuantity(input.chemical, input.quantity * multiplier)) } have[chemicalQuantity.chemical] = have.getOrDefault(chemicalQuantity.chemical, 0) + multiplier * reaction.output.quantity } have[chemicalQuantity.chemical] = have.getOrDefault(chemicalQuantity.chemical, 0) - chemicalQuantity.quantity } makeChemical(ChemicalQuantity("FUEL", quantity)) return ore } companion object { fun parseReaction(str: String): Reaction { val (ins, out) = str.split("=>").map { it.trim() } return Reaction(parseChemicalQuantity(out), ins.split(',').map { it.trim() }.map { parseChemicalQuantity(it) }) } private fun parseChemicalQuantity(str: String): ChemicalQuantity { val (quan, chem) = str.split(' ') return ChemicalQuantity(chem, quan.toLong()) } } } companion object { const val ONE_TRILLION = 1_000_000_000_000 } }
0
Kotlin
0
1
84db818b023668c2bf701cebe7c07f30bc08def0
3,007
aoc-2019
Creative Commons Zero v1.0 Universal
src/Day18.kt
zfz7
573,100,794
false
{"Kotlin": 53499}
fun main() { println(day18A(readFile("Day18"))) println(day18B(readFile("Day18"))) } fun day18A(input: String): Int { var count = 0 cords.forEach { cord -> if (!cords.contains(listOf(cord[0] + 1, cord[1], cord[2]))) { count++ } if (!cords.contains(listOf(cord[0] - 1, cord[1], cord[2]))) { count++ } if (!cords.contains(listOf(cord[0], cord[1] + 1, cord[2]))) { count++ } if (!cords.contains(listOf(cord[0], cord[1] - 1, cord[2]))) { count++ } if (!cords.contains(listOf(cord[0], cord[1], cord[2] + 1))) { count++ } if (!cords.contains(listOf(cord[0], cord[1], cord[2] - 1))) { count++ } } return count } val cords = readFile("Day18").trim().split("\n") .map { line -> line.split(",").map { it.toInt() } } .toSet() val cordCache: MutableMap<List<Int>, Boolean> = mutableMapOf() val maxX = cords.maxBy { it[0] }[0] val maxY = cords.maxBy { it[1] }[1] val maxZ = cords.maxBy { it[2] }[2] fun day18B(input: String): Int { var count = 0 cords.forEach { cord -> println(cord) if (!cords.contains(listOf(cord[0] + 1, cord[1], cord[2])) && canReachOutside(listOf(cord[0] + 1, cord[1], cord[2])) ) { count++ } if (!cords.contains(listOf(cord[0] - 1, cord[1], cord[2])) && canReachOutside(listOf(cord[0] - 1, cord[1], cord[2])) ) { count++ } if (!cords.contains(listOf(cord[0], cord[1] + 1, cord[2])) && canReachOutside(listOf(cord[0], cord[1] + 1, cord[2])) ) { count++ } if (!cords.contains(listOf(cord[0], cord[1] - 1, cord[2])) && canReachOutside(listOf(cord[0], cord[1] - 1, cord[2])) ) { count++ } if (!cords.contains(listOf(cord[0], cord[1], cord[2] + 1)) && canReachOutside(listOf(cord[0], cord[1], cord[2] + 1)) ) { count++ } if (!cords.contains(listOf(cord[0], cord[1], cord[2] - 1)) && canReachOutside(listOf(cord[0], cord[1], cord[2] - 1)) ) { count++ } } return count } fun canReachOutside(cord: List<Int>): Boolean { val list = mutableSetOf(cord) val visited = mutableSetOf<List<Int>>() while (list.isNotEmpty()) { val current = list.first().also{ list.remove(it) } if(visited.contains(current)){ continue } visited.add(current) if (cordCache.contains(current)) { cordCache[cord] = cordCache[current]!! if (cordCache[current]!!) return true else continue } if (cords.contains(current)) { cordCache[current] = false continue } if (current[0] !in 0..maxX || current[1] !in 0..maxY || current[2] !in 0..maxZ) { cordCache[cord] = true cordCache[current] = true return true } list.add(listOf(current[0] - 1, current[1], current[2])) list.add(listOf(current[0], current[1] - 1, current[2])) list.add(listOf(current[0], current[1], current[2] - 1)) list.add(listOf(current[0] + 1, current[1], current[2])) list.add(listOf(current[0], current[1] + 1, current[2])) list.add(listOf(current[0], current[1], current[2] + 1)) } return false }
0
Kotlin
0
0
c50a12b52127eba3f5706de775a350b1568127ae
3,543
AdventOfCode22
Apache License 2.0
src/Day04.kt
rdbatch02
575,174,840
false
{"Kotlin": 18925}
fun main() { fun parseInput(input: List<String>): List<List<IntRange>> { return input.map { inputLine -> val assignmentStrings = inputLine.split(",") assignmentStrings.map { val assignmentSections = it.split("-") IntRange(assignmentSections.first().toInt(), assignmentSections.last().toInt()) } } } fun part1(input: List<String>): Int { val ranges = parseInput(input) return ranges.count {rangePair -> rangePair.first() in rangePair.last() || rangePair.last() in rangePair.first() } } fun part2(input: List<String>): Int { val ranges = parseInput(input) return ranges.count {rangePair -> rangePair.first().partiallyOverlaps(rangePair.last()) || rangePair.last().partiallyOverlaps(rangePair.first()) } } val input = readInput("Day04") println("Part 1 - " + part1(input)) println("Part 2 - " + part2(input)) }
0
Kotlin
0
1
330a112806536910bafe6b7083aa5de50165f017
1,003
advent-of-code-kt-22
Apache License 2.0
src/Day03.kt
andydenk
573,909,669
false
{"Kotlin": 24096}
import java.lang.IllegalStateException fun main() { // 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("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<String>): Int { return input .sumOf { calculatePriorityOfDuplicate(it) } } private fun part2(input: List<String>): Int { return input .chunked(3) .sumOf { calculatePriorityOfBadge(it) } } private fun calculatePriorityOfBadge(elfGroup: List<String>): Int { if (elfGroup.size != 3) throw IllegalStateException("ElfGroup Size is not valid") return elfGroup .map { it.toSet() } .reduce { acc, element -> acc.toSet() intersect element.toSet() } .single() .priority() } private fun calculatePriorityOfDuplicate(input: String): Int { if (input.length % 2 != 0) throw IllegalStateException("Compartment Size is not equal") val firstCompartment = input.take(input.length / 2).associateBy { it } val secondCompartment = input.takeLast(input.length / 2) return secondCompartment.first { firstCompartment.contains(it) }.priority() } private typealias Item = Char private fun Item.priority(): Int = code - (('a'.code - 1).takeIf { isLowerCase() } ?: ('A'.code - 27))
0
Kotlin
0
0
1b547d59b1dc55d515fe8ca8e88df05ea4c4ded1
1,434
advent-of-code-2022
Apache License 2.0
ctci/arrays_and_strings/_02_check_permutation/CheckPermutation.kt
vishal-sehgal
730,172,606
false
{"Kotlin": 8936}
package ctci.arrays_and_strings._02_check_permutation /** * #1.2 * * Check Permutation: Given two strings, write a method to decide if one is a permutation * of the other. */ class CheckPermutation { /** * Determines whether two given strings are permutations of each other. * * Time Complexity: O(n), where n is the length of the input strings. * * @param string1 The first string to be checked for permutation. * @param string2 The second string to be checked for permutation. * @return `true` if the strings are permutations, `false` otherwise. */ fun arePermutationsSolutionOne(string1: String, string2: String): Boolean { if ((string1.length != string2.length)) return false val charCount = mutableMapOf<Char, Int>() string1.forEach { charCount[it] = charCount.getOrDefault(it, 0) + 1 } return string2.all { charCount[it]?.let { count -> count > 0 && charCount.put(it, count - 1) != null } ?: false } } /** * Time Complexity: O(n), where n is the length of the input strings. */ fun arePermutationsSolutionTwo(string1: String, string2: String): Boolean { if (string1.length != string2.length) return false return stringToCountMap(string1) == stringToCountMap(string2) } /** * Converts a string into a character count map. * * This function takes a string as input and creates a mutable map where each character * in the string is a key, and the corresponding value is the count of occurrences of that character. * It iterates through the characters of the string, updating the count in the map accordingly. * * @param string The input string to be converted into a character count map. * @return A mutable map with characters as keys and their counts as values. */ private fun stringToCountMap(string: String): MutableMap<Char, Int> { val charCount = mutableMapOf<Char, Int>() string.forEach { charCount[it] = charCount.getOrDefault(it, 0) + 1 } return charCount } } fun main() { val string1 = "abc" val string2 = "cab" val string3 = "bca" println("Are $string1 & $string2 Permutations? ${CheckPermutation().arePermutationsSolutionOne(string1, string2)}") println("Are $string1 & $string2 Permutations? ${CheckPermutation().arePermutationsSolutionTwo(string1, string2)}") println("Are $string2 & $string3 Permutations? ${CheckPermutation().arePermutationsSolutionOne(string2, string3)}") println("Are $string2 & $string3 Permutations? ${CheckPermutation().arePermutationsSolutionTwo(string2, string3)}") }
0
Kotlin
0
0
f83e929dfef941fbd8150c3ebc7c7c6fee60148b
2,757
kotlin-coding-interview
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxPoints.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.math.gcd /** * 149. Max Points on a Line * @see <a href="https://leetcode.com/problems/max-points-on-a-line/">Source</a> */ fun interface MaxPoints { operator fun invoke(points: Array<IntArray>): Int } class MaxPointsMap : MaxPoints { override operator fun invoke(points: Array<IntArray>): Int { if (points.size < SAME_LINE) return points.size var maxRes = 0 for (i in points.indices) { var same = 0 var tempMax = 0 val map = HashMap<String, Int>() for (j in points.indices) { if (i != j) { val dx = points[i][0] - points[j][0] val dy = points[i][1] - points[j][1] if (dx == 0 && dy == 0) { same++ continue } val gcd = (dx to dy).gcd() val key = dx.div(gcd).toString().plus("/").plus(dy / gcd) map[key] = map.getOrDefault(key, 0).plus(1) tempMax = tempMax.coerceAtLeast(map[key]!!) } } maxRes = maxRes.coerceAtLeast(tempMax + same + 1) } return maxRes } private companion object { private const val SAME_LINE = 3 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,975
kotlab
Apache License 2.0
src/main/kotlin/day03/Day03.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day03 import readInput fun main() { fun value(item: Char) = if (item in 'a'..'z') { item - 'a' + 1 } else { item - 'A' + 27 } fun part1(input: List<String>): Int { return input.sumOf {line -> val cmp1 = line.substring(0, line.length / 2) val cmp2 = line.substring(line.length / 2) val failedItems = cmp1.toSet().intersect(cmp2.toSet()) check(failedItems.size == 1) val item = failedItems.first() value(item) } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf {group -> val badges = group.map { it.toSet() }.reduce { v1, v2 -> v1.intersect(v2) } check(badges.size == 1) val badge = badges.first() value(badge) } } val testInput = readInput("day03", "test") val input = readInput("day03", "input") check(part1(testInput) == 157) println(part1(input)) check(part2(testInput) == 70) println(part2(input)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
1,058
aoc2022
Apache License 2.0
src/main/kotlin/io/intervals/MeetingRoomII.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.intervals import io.utils.runTests import java.util.* import kotlin.Comparator // https://leetcode.com/problems/meeting-rooms-ii/ class MeetingRoomII { fun execute(input: Array<IntArray>): Int { if (input.isEmpty()) return 0 val allocator = PriorityQueue(input.size, Comparator<Int> { a, b -> a - b }) input.sortBy { it.first() } // Add the first meeting allocator.add(input.first().last()) // Iterate over remaining intervals for (index in 1 until input.size) { // If the room due to free up the earliest is free, assign that room to this meeting. if (input[index].first() >= allocator.peek()) { allocator.poll() } // If a new room is to be assigned, then also we add to the heap, // If an old room is allocated, then also we have to add to the heap with updated end time. allocator.add(input[index].last()) } // The size of the heap tells us the minimum rooms required for all the meetings. return allocator.size } fun execute1(input: Array<IntArray>): Int { if (input.isEmpty()) return 0 var result = 1 input.sortBy { it[0] } for (index in input.indices) { result = maxOf( checkPrevious(input, index, input[index].first()) + checkNext(input, index, input[index].first()) + 1, checkPrevious(input, index, input[index].last(), 1) + checkNext(input, index, input[index].last(), 1) + 1, result) if (result == input.size) break } return result } private fun checkNext(input: Array<IntArray>, currentIndex: Int, value: Int, extra: Int = 0): Int { var index = currentIndex + 1 var result = 0 while (index in input.indices) { if (value in input[index].first() + extra until input[index].last()) result++ index++ } return result } private fun checkPrevious(input: Array<IntArray>, currentIndex: Int, value: Int, extra: Int = 0): Int { var index = currentIndex - 1 var result = 0 while (index in input.indices) { if (value in input[index].first() + extra until input[index].last()) result++ index-- } return result } } fun main() { runTests(listOf( arrayOf(intArrayOf(0, 30), intArrayOf(5, 10), intArrayOf(15, 20)) to 2, arrayOf(intArrayOf(13, 15), intArrayOf(1, 13)) to 1, arrayOf(intArrayOf(4, 18), intArrayOf(1, 35), intArrayOf(12, 45), intArrayOf(25, 46), intArrayOf(22, 27)) to 4 )) { (input, value) -> value to MeetingRoomII().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
2,535
coding
MIT License
src/Day11.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
data class Monkey( val startingItems: List<Long>, val opExpr: String, val divisor: Long, val testTrueMonkey: Int, val testFalseMonkey: Int, ) { // do not count starting items var count = 0 val items = startingItems.toMutableList() fun round(item: Long, gcd: Long? = null): Pair<Int, Long> { var worry = calcWorry(item) worry = if (gcd != null) { worry % gcd } else { worry / 3 } val monkey = if (worry % divisor == 0L) testTrueMonkey else testFalseMonkey return monkey to worry } private fun calcWorry(item: Long): Long { count++ return if (opExpr == "* old") { item * item } else { val (op, v) = opExpr.split(" ") when (op) { "*" -> item * v.toInt() else -> item + v.toInt() } } } } fun List<Monkey>.calcHighestProduct(num: Int) = map { it.count.toLong() }.sorted().takeLast(num).reduce { a, b -> a * b } fun main() { val startItemsRegex = """^Starting items: (.+)$""".toRegex() val opRegex = """^Operation: new = old (.+)$""".toRegex() val divisorRegex = """^Test: divisible by (\d+)$""".toRegex() val trueRegex = """^If true: throw to monkey (\d+)$""".toRegex() val falseRegex = """^If false: throw to monkey (\d+)$""".toRegex() fun toMonkey(inputs: List<String>): Monkey { val startItems = startItemsRegex .matchEntire(inputs[1])?.groups?.last()?.value?.split(",") ?.map { s -> s.trim() } ?.map { s -> s.toLong() } ?: throw IllegalArgumentException("incorrect input: ${inputs[1]}") val opExpr = opRegex.matchEntire(inputs[2])?.groups?.last()?.value?.trim() ?: throw IllegalArgumentException("incorrect input: ${inputs[2]}") val divisorExpr = divisorRegex.matchEntire(inputs[3])?.groups?.last()?.value?.toLong() ?: throw IllegalArgumentException("incorrect input: ${inputs[3]}") val trueMonkey = trueRegex.matchEntire(inputs[4])?.groups?.last()?.value?.toInt() ?: throw IllegalArgumentException("incorrect input: ${inputs[4]}") val falseMonkey = falseRegex.matchEntire(inputs[5])?.groups?.last()?.value?.toInt() ?: throw IllegalArgumentException("incorrect input: ${inputs[5]}") return Monkey(startItems, opExpr, divisorExpr, trueMonkey, falseMonkey) } fun getMonkeys(input: List<String>): List<Monkey> { return input .filter { it.isNotBlank() } .map { it.trim() } .chunked(6) .map { toMonkey(it) } } fun part1(input: List<String>): Long { val monkeys = getMonkeys(input) repeat(20) { monkeys.forEach { monkey -> while (monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() val (nextMonkey, output) = monkey.round(item) monkeys[nextMonkey].items.add(output) } } } return monkeys.calcHighestProduct(2) } fun part2(input: List<String>): Long { val monkeys = getMonkeys(input) val gcd = monkeys.map { it.divisor }.reduce { a, b -> a * b } repeat(10_000) { monkeys.forEach { monkey -> while (monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() val (nextMonkey, output) = monkey.round(item, gcd) monkeys[nextMonkey].items.add(output) } } } return monkeys.calcHighestProduct(2) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
3,995
advent-of-code-2022
Apache License 2.0
2023/5/solve-1.kts
gugod
48,180,404
false
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
import java.io.File import kotlin.text.Regex class CategoryToCategoryMapper ( val name: String, val source: String, val destination: String, val howTo: List<Triple<Long,Long,Long>> ) { fun convert(src: Long): Long { val rule = howTo.firstOrNull { it.second <= src && src < (it.second + it.third) } return if (rule == null) src else rule.first + (src - rule.second) } } private fun String.findAllNumbers() = Regex("[0-9]+").findAll(this).map { it.value.toLong() } val input = File(if (args.size == 0) "input" else args[0]).readText() val paragraphs = input.split("\n\n") val seeds = paragraphs[0].findAllNumbers().toList() val mappers = (1..paragraphs.lastIndex).map { i -> val lines = paragraphs[i].split("\n") val (src, _, dst, _) = lines[0].split( '-', ' ', limit = 4 ) val howTo = (1..lines.lastIndex).flatMap { val nums = lines[it].findAllNumbers().toList() if (nums.size == 3) listOf(Triple(nums[0]!!, nums[1]!!, nums[2]!!)) else listOf() } CategoryToCategoryMapper("$src-to-$dst", src, dst, howTo) } val mapper = mappers.first { it.source == "seed" } var seedToLocationChain = mutableListOf<CategoryToCategoryMapper>(mapper) while (seedToLocationChain.last().destination != "location") { seedToLocationChain.add(mappers.first { it.source == seedToLocationChain.last().destination }) } val ans = seeds.map { var n = it seedToLocationChain.forEach { mapper -> n = mapper.convert(n) } n }.min() println(ans.toString())
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
1,568
advent-of-code
Creative Commons Zero v1.0 Universal
src/main/kotlin/aoc2023/day14/day14Solver.kt
Advent-of-Code-Netcompany-Unions
726,531,711
false
{"Kotlin": 94973}
package aoc2023.day14 import lib.* suspend fun main() { setupChallenge().solveChallenge() } fun setupChallenge(): Challenge<Array<Array<Char>>> { return setup { day(14) year(2023) //input("example.txt") parser { it.readLines().get2DArrayOfColumns() } partOne { val tilted = it.tilt(CardinalDirection.North) tilted.calculateLoad().toString() } partTwo { var tilted = it val history = mutableMapOf<String, Pair<Int, Array<Array<Char>>>>() val limit = 1000000000 var i = 0 while(i < limit) { val key = tilted.asString() if(history.containsKey(key)) { val rep = history[key]!! val repLength = i - rep.first val ff = (limit - i) / (repLength) println("Fast-forwarding from $i for $ff * $repLength reps") i += (ff * repLength) tilted = rep.second } tilted = tilted.spin() history[key] = i to tilted i++ } tilted.calculateLoad().toString() } } } fun Array<Array<Char>>.tilt(direction: CardinalDirection): Array<Array<Char>> { val tilted = this.clone() val ranges = when(direction) { CardinalDirection.North -> this.indices to this.first().indices CardinalDirection.South -> this.indices to this.first().indices.reversed() CardinalDirection.West -> this.indices to this.first().indices CardinalDirection.East -> this.indices.reversed() to this.first().indices } ranges.first.forEach { i -> ranges.second.forEach { j -> if (this[i][j] == 'O') { var pos = i to j var blocked = false while (!blocked) { val newPos = pos.adjacent(direction) if (isValidCoord(newPos.x(), newPos.y()) && tilted[newPos.x()][newPos.y()] == '.') { pos = newPos } else { blocked = true } } tilted[i][j] = '.' tilted[pos.x()][pos.y()] = 'O' } } } return tilted } fun Array<Array<Char>>.calculateLoad(): Long { return this.first().indices.map { i -> this.map { it[i] } .count { it == 'O' } * (this.size - i) } .sumOf { it.toLong() } } fun Array<Array<Char>>.asString(): String { return this.fold("") {s, r -> s + r.fold("") {s2, c -> s2 + c } } } fun Array<Array<Char>>.spin(): Array<Array<Char>> { var tilted = this tilted = tilted.tilt(CardinalDirection.North) tilted = tilted.tilt(CardinalDirection.West) tilted = tilted.tilt(CardinalDirection.South) tilted = tilted.tilt(CardinalDirection.East) return tilted }
0
Kotlin
0
0
a77584ee012d5b1b0d28501ae42d7b10d28bf070
3,026
AoC-2023-DDJ
MIT License
src/Day14.kt
juliantoledo
570,579,626
false
{"Kotlin": 34375}
fun main() { val start = Pair(500,0) var maxX = 0 var maxY = 0 var minX = Int.MAX_VALUE var minY = Int.MAX_VALUE val widerForPart = 1000 fun printMatrix(matrix: MutableList<MutableList<String>>) { matrix.forEachIndexed{i, item -> println("$i ${item.subList(minX-200,maxX+200).joinToString(separator = "")}") } } fun sand(matrix: MutableList<MutableList<String>>, part2:Boolean = false): Int { var totalSand = 0 val xRange = (minX until maxX) var sandFinal = false while(!sandFinal) { var sandX = start.first var sandY = start.second var sandRested = false while(!sandRested) { // Final for Part1/Endless if (!part2 && (sandX !in xRange || sandY >= maxY)) { sandRested = true sandFinal = true } else { if (matrix[sandY + 1][sandX] == ".") { sandY++ } else if (matrix[sandY + 1][sandX - 1] == ".") { sandY++; sandX-- } else if (matrix[sandY + 1][sandX + 1] == ".") { sandY++; sandX++ } else { sandRested = true; totalSand++ matrix[sandY][sandX] = "o" // Final for Part2/Floor if (part2 && sandY == start.second && sandX == start.first) { sandFinal = true } } } } } return totalSand } fun solve(input: List<String>, part2:Boolean = false): Int { var paths: MutableList<List<Pair<Int,Int>>> = mutableListOf() input.forEach { line -> val path: List<Pair<Int,Int>> = line.split(" -> ").map { val a = it.split(",") Pair(a[0].toInt(), a[1].toInt()) } path.forEach{point -> if (point.first > maxX) maxX = point.first if (point.second > maxY) maxY = point.second if (point.first < minX) minX = point.first if (point.second < minY) minY = point.second } paths.add(path) } var matrix = MutableList(maxY+3) { MutableList<String>(maxX+widerForPart) { "." }} matrix[start.second][start.first] = "+" paths.forEach{path -> path.forEachIndexed{index, point -> matrix[point.second][point.first] = "#" if (index < path.size-1) { val postPoint = path[index+1] if (point.first == postPoint.first) { for (new in point.second + 1 until postPoint.second) matrix[new][point.first] = "#" } if (point.second == postPoint.second) { for (new in point.first + 1 until postPoint.first) matrix[point.second][new] = "#" } } if (index > 1) { val prePoint = path[index-1] if (point.first == prePoint.first) { for (new in point.second + 1 until prePoint.second) matrix[new][point.first] = "#" } if (point.second == prePoint.second) { for (new in point.first + 1 until prePoint.first) matrix[point.second][new] = "#" } } } } // New Floor for Part2 if (part2) for (i in 0 until maxX + widerForPart) matrix[maxY + 2][i] = "#" return sand(matrix, part2) } val test = solve(readInput("Day14_test")) println("Test1: $test") check(test == 24) println("Test2: " + solve(readInput("Day14_test"), true)) println("Part1: " + solve(readInput("Day14_input"))) println("Part2: " + solve(readInput("Day14_input"), true)) }
0
Kotlin
0
0
0b9af1c79b4ef14c64e9a949508af53358335f43
4,059
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/day23.kt
gautemo
433,582,833
false
{"Kotlin": 91784}
import shared.Point import shared.getText import kotlin.math.abs class AmphipodAStar(val input: String){ private fun heuristic(map: String) = AmphipodCave(map).heurestic() fun aStar(): Int{ val openSet = mutableSetOf(input) val cameFrom = mutableMapOf<String, String>() val gScore = mutableMapOf(Pair(input, 0)) val fScore = mutableMapOf(Pair(input, heuristic(input))) while (openSet.isNotEmpty()){ val current = openSet.minByOrNull { fScore[it]!! }!! val currentMap = AmphipodCave(current) if(currentMap.goalReached()) return gScore[current]!! openSet.remove(current) for((neighbour, energy) in currentMap.possibleMoves()){ val tentativeGScore = gScore[current]!! + energy if(tentativeGScore < (gScore[neighbour] ?: Int.MAX_VALUE)){ cameFrom[neighbour] = current gScore[neighbour] = tentativeGScore fScore[neighbour] = tentativeGScore + heuristic(neighbour) if(!openSet.contains(neighbour)) openSet.add(neighbour) } } } throw Exception("should have found goal by now") } } class AmphipodCave(val input: String){ private val points: List<CavePoint> private val width = input.lines().first().length private val height = input.lines().size private val goalDepth = if(height == 5) 2 else 4 init { val list = mutableListOf<CavePoint>() for(y in 0 until height){ for(x in 0 until width){ val p = when(input.lines().getOrNull(y)?.getOrNull(x)){ '.' -> Open(Point(x,y)) 'A' -> Amber(Point(x,y)) 'B' -> Bronze(Point(x,y)) 'C' -> Copper(Point(x,y)) 'D' -> Desert(Point(x,y)) else -> Wall(Point(x,y)) } list.add(p) } } points = list } private fun get(point: Point) = points.find { it.point == point } fun possibleMoves(): List<Pair<String, Int>> { return points.filterIsInstance<Amphipod>().flatMap { amphipod -> val goTo = if(amphipod.inHallway()){ nextInGoal(amphipod)?.let { listOf(it) } ?: listOf() }else{ if(amphipod.inGoal() && allUnderIsValid(amphipod)) return@flatMap listOf() points.filter { it is Open && it.inHallway() } }.filter { canGoToPoint(amphipod, it) } goTo.map { val steps = abs(amphipod.point.x - it.point.x) + abs(amphipod.point.y - it.point.y) Pair(printSwap(amphipod, it), amphipod.energy * steps) } } } private fun canGoToPoint(amphipod: Amphipod, open: CavePoint): Boolean{ if(open.inHallway() && listOf(3,5,7,9).contains(open.point.x)) return false for(x in minOf(amphipod.point.x, open.point.x)+1 until maxOf(amphipod.point.x, open.point.x)){ if(get(Point(x, 1)) !is Open) return false } fun validY(x: Int, range: IntRange): Boolean{ for(y in range){ if(get(Point(x, y)) !is Open) return false } return true } return if(amphipod.inHallway()){ validY(open.point.x, amphipod.point.y until open.point.y) }else{ validY(amphipod.point.x, open.point.y until amphipod.point.y) } } private fun printSwap(p1: CavePoint, p2: CavePoint): String{ var map = "" for(y in 0 until height){ for(x in 0 until width){ map += when(Point(x,y)){ p1.point -> p2.symbol p2.point -> p1.symbol else -> points.find { it.point.x == x && it.point.y == y }!!.symbol } } if(y != height - 1) map += "\n" } return map } fun heurestic(): Int{ return points.filterIsInstance<Amphipod>().sumOf { amphipod -> val ySteps = if(amphipod.inHallway()) 2 else 5 (abs(amphipod.goalX - amphipod.point.x) + ySteps) * amphipod.energy } } fun goalReached() = points.filterIsInstance<Amphipod>().all { it.inGoal() } private fun nextInGoal(amphipod: Amphipod): Open?{ for(y in height-2 downTo height-1-goalDepth){ val p = get(Point(amphipod.goalX, y)) if(p is Amphipod && p.symbol != amphipod.symbol) return null if(p is Open) return p } return null } private fun allUnderIsValid(amphipod: Amphipod): Boolean{ for(y in height-2 downTo amphipod.point.y){ if(get(Point(amphipod.goalX, y))?.symbol != amphipod.symbol) return false } return true } } sealed class CavePoint(val symbol: Char, val point: Point){ fun inHallway() = point.y == 1 } sealed class Amphipod(symbol: Char, point: Point, val energy: Int, val goalX: Int): CavePoint(symbol, point){ fun inGoal() = point.x == goalX } class Wall(point: Point): CavePoint('#', point) class Open(point: Point): CavePoint('.', point) class Amber(point: Point): Amphipod('A', point, 1, 3) class Bronze(point: Point): Amphipod('B', point,10, 5) class Copper(point: Point): Amphipod('C', point,100, 7) class Desert(point: Point): Amphipod('D', point,1000, 9) fun main(){ val input = getText("day23.txt") val map = AmphipodAStar(input) val task1 = map.aStar() println(task1) val foldedMap = AmphipodAStar(withFoldInput(input)) val task2 = foldedMap.aStar() println(task2) } fun withFoldInput(input: String): String{ val lines = input.lines().toMutableList() lines.add(3, " #D#C#B#A#") lines.add(4, " #D#B#A#C#") return lines.joinToString("\n") }
0
Kotlin
0
0
c50d872601ba52474fcf9451a78e3e1bcfa476f7
5,899
AdventOfCode2021
MIT License