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
advent-of-code-2023/src/test/kotlin/Day7Test.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test /** --- Day 7: Camel Cards --- */ class Day7Test { private val testInput = """ 32T3K 765 T55J5 684 KK677 28 KTJJT 220 QQQJA 483 """ .trimIndent() private val silverComparator = compareBy<CardAndBet> { (card, bet) -> card.handType() } .thenByDescending { (card, bet) -> card.secondary() } private val comparatorWithJokers = compareBy<CardAndBet> { (card, bet) -> card.handTypeWithJoker() } .thenByDescending { (card, bet) -> card.secondaryWithJoker() } data class CardAndBet(val card: String, val bet: Int, val rank: Int = 0) @Test fun `silver test (example)`() { val rankCards = rankCards(testInput) "32T3K".handType() shouldBe 2 rankCards.shouldBe( listOf( CardAndBet(card = "32T3K", bet = 765, rank = 1), CardAndBet(card = "KTJJT", bet = 220, rank = 2), CardAndBet(card = "KK677", bet = 28, rank = 3), CardAndBet(card = "T55J5", bet = 684, rank = 4), CardAndBet(card = "QQQJA", bet = 483, rank = 5), )) rankCards.sumOf { it.bet * it.rank } shouldBe 6440 } @Test fun `silver test`() { val cards = rankCards(loadResource("Day7")) cards.sumOf { it.bet * it.rank } shouldBe 250951660 } @Test fun `gold test (example)`() { val rankCards = rankCards(testInput, comparatorWithJokers) rankCards.shouldBe( listOf( CardAndBet(card = "32T3K", bet = 765, rank = 1), CardAndBet(card = "KK677", bet = 28, rank = 2), CardAndBet(card = "T55J5", bet = 684, rank = 3), CardAndBet(card = "QQQJA", bet = 483, rank = 4), CardAndBet(card = "KTJJT", bet = 220, rank = 5), )) rankCards.sumOf { it.bet * it.rank } shouldBe 5905 } @Test fun `gold test`() { val cards = rankCards(loadResource("Day7"), comparatorWithJokers) cards.sumOf { it.bet * it.rank } shouldBe 251481660 } private fun rankCards(input: String, comparator: Comparator<CardAndBet> = silverComparator) = parse(input) .sortedWith(comparator) .mapIndexed { index, cardAndBet -> cardAndBet.copy(rank = index + 1) } .toList() private fun parse(input: String): Sequence<CardAndBet> = input .lines() .asSequence() .filter { it.isNotEmpty() } .map { it.trim().split(" ") } .map { (card, bet) -> CardAndBet(card, bet.toInt()) } private fun String.handType(): Int { val sizes: List<Int> = toCharArray().groupBy { it }.map { it.value.size }.sortedDescending() return when (sizes) { // Five of a kind listOf(5) -> 7 // Four of a kind listOf(4, 1) -> 6 // Full house listOf(3, 2) -> 5 // Three of a kind listOf(3, 1, 1) -> 4 // Two pair listOf(2, 2, 1) -> 3 // One pair listOf(2, 1, 1, 1) -> 2 // High card else -> 1 } } private fun String.secondary(): String { return toCharArray().joinToString("") { char -> when (char) { 'A' -> "a" 'K' -> "b" 'Q' -> "c" 'J' -> "d" 'T' -> "e" '9' -> "f" '8' -> "g" '7' -> "h" '6' -> "i" '5' -> "j" '4' -> "k" '3' -> "l" '2' -> "m" else -> error("Unexpected char: $char") } } } enum class HandType(val rank: Int) { FiveOfAKind(7), FourOfAKind(6), FullHouse(5), ThreeOfAKind(4), TwoPair(3), OnePair(2), HighCard(1), ; fun adjustForJokers(jokers: Int): HandType { return when (this) { FiveOfAKind -> FiveOfAKind FourOfAKind -> when (jokers) { 0 -> FourOfAKind 1 -> FiveOfAKind else -> error("Unexpected jokers: $jokers") } FullHouse -> when (jokers) { 0 -> FullHouse 1 -> FourOfAKind 2 -> FiveOfAKind else -> error("Unexpected jokers: $jokers") } ThreeOfAKind -> when (jokers) { 0 -> ThreeOfAKind 1 -> FourOfAKind 2 -> FiveOfAKind else -> error("Unexpected jokers: $jokers") } TwoPair -> when (jokers) { 0 -> TwoPair 1 -> FullHouse 2 -> FourOfAKind 3 -> FiveOfAKind else -> error("Unexpected jokers: $jokers") } OnePair -> when (jokers) { 0 -> OnePair 1 -> ThreeOfAKind 2 -> FourOfAKind 3 -> FiveOfAKind else -> error("Unexpected jokers: $jokers") } HighCard -> when (jokers) { 0 -> HighCard 1 -> OnePair 2 -> ThreeOfAKind 3 -> FourOfAKind 4 -> FiveOfAKind 5 -> FiveOfAKind else -> error("Unexpected jokers: $jokers") } } } } private fun String.handTypeWithJoker(): Int { val toCharArray = toCharArray() val jokers = toCharArray.count { it == 'J' } val sizes: List<Int> = toCharArray .filterNot { it == 'J' } .groupBy { it } .map { it.value.size } .filter { it > 1 } .sortedDescending() return when (sizes) { listOf(5) -> HandType.FiveOfAKind listOf(4) -> HandType.FourOfAKind listOf(3, 2) -> HandType.FullHouse listOf(3) -> HandType.ThreeOfAKind listOf(2, 2) -> HandType.TwoPair listOf(2) -> HandType.OnePair else -> HandType.HighCard } .adjustForJokers(jokers) .rank } private fun String.secondaryWithJoker(): String { return toCharArray().joinToString("") { char -> when (char) { 'A' -> "a" 'K' -> "b" 'Q' -> "c" 'T' -> "e" '9' -> "f" '8' -> "g" '7' -> "h" '6' -> "i" '5' -> "j" '4' -> "k" '3' -> "l" '2' -> "m" 'J' -> "o" else -> error("Unexpected char: $char") } } } }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
6,346
advent-of-code
MIT License
src/day02/Day02.kt
Regiva
573,089,637
false
{"Kotlin": 29453}
package day02 import readText fun main() { fun readGuide(fileName: String): Sequence<List<String>> { return readText(fileName) .splitToSequence("\n") .map { it.split(" ") } } val scoresMatrix = arrayOf( intArrayOf(4, 8, 3), intArrayOf(1, 5, 9), intArrayOf(7, 2, 6), ) fun String.simplify() = when (this) { "A", "X" -> 0 "B", "Y" -> 1 "C", "Z" -> 2 else -> -1 } // Time — O(n), Memory — O(n) fun part1(input: Sequence<List<String>>): Int { return input.sumOf { list -> scoresMatrix[list[0].simplify()][list[1].simplify()] } } val part2ScoresMatrix = arrayOf( intArrayOf(3, 4, 8), intArrayOf(1, 5, 9), intArrayOf(2, 6, 7), ) // Time — O(n), Memory — O(n) fun part2(input: Sequence<List<String>>): Int { return input.sumOf { list -> part2ScoresMatrix[list[0].simplify()][list[1].simplify()] } } val testInput = readGuide("day02/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readGuide("day02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2d9de95ee18916327f28a3565e68999c061ba810
1,206
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/tonnoz/adventofcode23/day18/Day18.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day18 import com.tonnoz.adventofcode23.utils.println import com.tonnoz.adventofcode23.utils.readInput import kotlin.math.abs import kotlin.system.measureTimeMillis object Day18 { @JvmStatic fun main(args: Array<String>) { val input = "input18.txt".readInput() println("time part1: ${measureTimeMillis { calculateArea(input) { it.toDrillInstroPt1() }.println() }}ms") println("time part2: ${measureTimeMillis { calculateArea(input) { it.toDrillInstroPt2() }.println() }}ms") } private fun calculateArea(input: List<String>, transformF: (String) -> DrillingInstruction): Long { val (trenchPerimeter, trench) = input.map(transformF).toTrenchVertices() return trench.shoelaceArea(trenchPerimeter) } data class DrillingInstruction(val direction: Direction, val distance: Long, val color: String) enum class Direction(val char: Char) { UP('U'), DOWN('D'), LEFT('L'), RIGHT('R'); companion object { private val map = entries.associateBy(Direction::char) fun fromChar(char: Char): Direction = map[char]!! fun fromChar2(char: Char) = when (char) { '0' -> RIGHT '1' -> DOWN '2' -> LEFT '3' -> UP else -> throw IllegalArgumentException("Unknown Direction") } } } private fun String.toDrillInstroPt1(): DrillingInstruction { val direction = Direction.fromChar(this.first()) val distance = this.substring(2,4).trim().toLong() val color = this.takeLast(8).take(7) return DrillingInstruction(direction, distance, color) } private fun String.toDrillInstroPt2(): DrillingInstruction { val color = this.takeLast(8).take(7) val distance = color.substring(1, color.length-1).toLong(radix = 16) val direction = Direction.fromChar2(color.last()) return DrillingInstruction(direction, distance, color) } private fun List<DrillingInstruction>.toTrenchVertices(): Pair<Long, List<Pair<Long, Long>>> { var curRow = 0L var curCol = 0L var perimeter = 0L this.map { when (it.direction) { Direction.UP -> curRow -= it.distance Direction.DOWN -> curRow += it.distance Direction.LEFT -> curCol -= it.distance Direction.RIGHT -> curCol += it.distance } perimeter += it.distance Pair(curRow, curCol) }.let { return Pair(perimeter, it) } } /** * Calculate the area of the trench polygon using the shoelace formula. * This is a modified version that includes the perimeter of the polygon. * https://en.wikipedia.org/wiki/Shoelace_formula * https://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area#:~:text=x%2C%20y)%20%3D%2030.0-,Kotlin,-//%20version%201.1.3%0A%0Aclass */ private fun List<Pair<Long,Long>>.shoelaceArea(perimeter: Long): Long { val n = this.size var result = 0.0 for (i in 0 until n - 1) { result += this[i].first * this[i + 1].second - this[i + 1].first * this[i].second } return (((abs(result + this[n - 1].first * this[0].second - this[0].first * this[n -1].second) + perimeter) / 2) + 1).toLong() } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
3,116
adventofcode23
MIT License
src/Day15.kt
robinpokorny
572,434,148
false
{"Kotlin": 38009}
import kotlin.math.* private data class Sensor( val position: Point, val minBeacon: Point, val distance: Int ) private val lineRe = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)") private fun parse(input: List<String>): List<Sensor> = input .map { line -> val (sx, sy, bx, by) = lineRe .matchEntire(line)!! .destructured .toList() .map { it.toInt() } Sensor( Point(sx, sy), Point(bx, by), abs(sx - bx) + abs(sy - by) ) } private fun seenRangesOnRow(sensors: List<Sensor>, row: Int) = sensors .mapNotNull { (position, _, distance) -> val side = distance - abs(position.y - row) if (side > 0) (position.x - side).rangeTo(position.x + side) else null } private fun seenOnRow(sensors: List<Sensor>, row: Int): Int { val seen = seenRangesOnRow(sensors, row) // For some reason this is quite fast val visibleOnRow = seen.fold(mutableSetOf<Int>()) { prev, next -> prev.addAll(next) prev }.size val beaconsOnRow = sensors .map { it.minBeacon } .distinct() .count { it.y == row } return visibleOnRow - beaconsOnRow } private fun unseenPoint(sensors: List<Sensor>, limit: Int): Long = (0..limit) .firstNotNullOf(fun(row: Int): Point? { val seen = seenRangesOnRow(sensors, row).sortedBy { it.start } if (seen.first().start > 0) { return Point(0, row) } var lastSeen = seen.first().endInclusive return seen.firstNotNullOfOrNull { if (it.start > lastSeen + 1) Point(lastSeen + 1, row) else { lastSeen = max(lastSeen, it.endInclusive) null } } }) .let { it.x.toLong() * 4_000_000 + it.y } fun main() { val input = parse(readDayInput(15)) val testInput = parse(rawTestInput) // PART 1 assertEquals(seenOnRow(testInput, 10), 26) println("Part1: ${seenOnRow(input, 2_000_000)}") // PART 2 assertEquals(unseenPoint(testInput, 20), 56000011) println("Part2: ${unseenPoint(input, 4_000_000)}") } private val rawTestInput = """ Sensor at x=2, y=18: closest beacon is at x=-2, y=15 Sensor at x=9, y=16: closest beacon is at x=10, y=16 Sensor at x=13, y=2: closest beacon is at x=15, y=3 Sensor at x=12, y=14: closest beacon is at x=10, y=16 Sensor at x=10, y=20: closest beacon is at x=10, y=16 Sensor at x=14, y=17: closest beacon is at x=10, y=16 Sensor at x=8, y=7: closest beacon is at x=2, y=10 Sensor at x=2, y=0: closest beacon is at x=2, y=10 Sensor at x=0, y=11: closest beacon is at x=2, y=10 Sensor at x=20, y=14: closest beacon is at x=25, y=17 Sensor at x=17, y=20: closest beacon is at x=21, y=22 Sensor at x=16, y=7: closest beacon is at x=15, y=3 Sensor at x=14, y=3: closest beacon is at x=15, y=3 Sensor at x=20, y=1: closest beacon is at x=15, y=3 """.trimIndent().lines()
0
Kotlin
0
2
56a108aaf90b98030a7d7165d55d74d2aff22ecc
3,190
advent-of-code-2022
MIT License
src/main/kotlin/TrenchMap_20.kt
Flame239
433,046,232
false
{"Kotlin": 64209}
fun getTrenchMap(): TrenchMapInput { val lines = readFile("TrenchMap").split("\n") val enhancer = lines[0].map { if (it == '#') '1' else '0' } val image = Array(lines.size - 2) { CharArray(lines[2].length) { '0' } } lines.drop(2).forEachIndexed { index, line -> line.forEachIndexed { sIndex, char -> image[index][sIndex] = if (char == '#') '1' else '0' } } return TrenchMapInput(enhancer, image) } fun enhanceImage(enhancer: List<Char>, image: Array<CharArray>, defaultChar: Char): Pair<Char, Array<CharArray>> { val enhancedImage = Array(image.size + 2) { CharArray(image[0].size + 2) { defaultChar } } for (i in enhancedImage.indices) { for (j in enhancedImage[0].indices) { val binaryIndex = listOf( image.getOrNull(i - 2)?.getOrNull(j - 2) ?: defaultChar, image.getOrNull(i - 2)?.getOrNull(j - 1) ?: defaultChar, image.getOrNull(i - 2)?.getOrNull(j) ?: defaultChar, image.getOrNull(i - 1)?.getOrNull(j - 2) ?: defaultChar, image.getOrNull(i - 1)?.getOrNull(j - 1) ?: defaultChar, image.getOrNull(i - 1)?.getOrNull(j) ?: defaultChar, image.getOrNull(i)?.getOrNull(j - 2) ?: defaultChar, image.getOrNull(i)?.getOrNull(j - 1) ?: defaultChar, image.getOrNull(i)?.getOrNull(j) ?: defaultChar ).joinToString("").toInt(2) enhancedImage[i][j] = enhancer[binaryIndex] } } val newDefaultChar = enhancer[defaultChar.toString().repeat(9).toInt(2)] return Pair(newDefaultChar, enhancedImage) } fun lightUpCount(enhancementsCount: Int): Int { var (enhancer, image) = getTrenchMap() var defaultChar = '0' repeat(enhancementsCount) { val (newDefaultChar, enhancedImage) = enhanceImage(enhancer, image, defaultChar) defaultChar = newDefaultChar image = enhancedImage } return image.sumOf { it.count { c -> c == '1' } } } fun main() { println(lightUpCount(2)) println(lightUpCount(50)) } data class TrenchMapInput(val enhancer: List<Char>, val image: Array<CharArray>)
0
Kotlin
0
0
ef4b05d39d70a204be2433d203e11c7ebed04cec
2,178
advent-of-code-2021
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/AdajacenyList.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.graph import java.util.* fun main() { // val adjL = AdajacenyList(7) // adjL.accept(Scanner(System.`in`)) // adjL.display() val visited: BooleanArray = BooleanArray(7) { false } val adjacencyList = AdjacencyList() val graph = adjacencyList.buildGraph() // adjacencyList.dfs(graph, 0, visited) // adjacencyList.dfs(graph, 0, 7) adjacencyList.breadthFirstSearch(graph, 0, 7) } data class Edge(val src: Int, val dst: Int, val weight: Int) { override fun toString(): String { return "src: $src to dest: $dst weight: $weight" } } class AdajacenyList(vertCount: Int) { private var vertList = MutableList(vertCount) { mutableListOf<Edge>() } fun accept(sc: Scanner) { println("Enter edge count: ") val edgeCount = sc.nextInt() for (i in 0 until edgeCount) { val src = sc.nextInt() val dst = sc.nextInt() val srcEdge = Edge(src, dst, 1) val dstEdge = Edge(dst, src, 1) vertList[src].add(dstEdge) vertList[dst].add(srcEdge) } } fun display() { // for (i in 0 until vertList.size) { // println() // for (j in 0 until vertList[i].size) { // println("\t${vertList[i][j]}") // } // } for (i in vertList.indices) { print("v$i\t") for (e in vertList[i]) print("$e --> ") println() } } } class AdjacencyList() { fun buildGraph(): MutableMap<Int, List<Edge>> { val graph = mutableMapOf<Int, List<Edge>>() val edge1 = Edge(1, 0, 1) val edge2 = Edge(2, 0, 1) val edge3 = Edge(6, 0, 1) val edge4 = Edge(1, 2, 1) val edge5 = Edge(1, 4, 1) val edge6 = Edge(3, 4, 1) val edge7 = Edge(3, 5, 1) val edge8 = Edge(6, 5, 1) val edge9 = Edge(4, 6, 1) graph[0] = listOf(edge1, edge2, edge3) graph[2] = listOf(edge4) graph[4] = listOf(edge5, edge6) graph[5] = listOf(edge7, edge8) graph[6] = listOf(edge9) return graph } data class Edge(val to: Int, val from: Int, val id: Int) fun dfs(graph: MutableMap<Int, List<Edge>>, at: Int, visited: BooleanArray) { if (visited[at]) return visited[at] = true val listOfNeighbours = graph[at] println("Recursive visit $at") listOfNeighbours?.let { for (neighbour in listOfNeighbours) { dfs(graph, neighbour.to, visited) } } } fun dfs(graph: MutableMap<Int, List<Edge>>, rootId: Int, numberOfVertex: Int) { val visited = BooleanArray(numberOfVertex) { false } val stack = ArrayDeque<Int>() stack.push(rootId) println("Iterative Visit $rootId") while (!stack.isEmpty()) { val current = stack.pop() val list = graph[current] list?.let { for (edge in list) { if (!visited[edge.to]) { stack.push(edge.to) visited[edge.to] = true println("Iterative Visit ${edge.to}") } } } } stack.pollLast() } fun breadthFirstSearch(graph: MutableMap<Int, List<Edge>>, rootId: Int, numberOfVertex: Int) { val visited = BooleanArray(numberOfVertex) { false } val queue = ArrayDeque<Int>() queue.offer(rootId) println("Visited $rootId") visited[rootId] = true while (queue.isNotEmpty()) { val current = queue.poll() val list = graph[current] list?.let { for (edge in list) { if (!visited[edge.to]) { queue.offer(edge.to) println("Visited ${edge.to}") visited[edge.to] = true } } } } } } //9 //0 1 //0 2 //0 6 //1 2 //1 4 //3 4 //3 5 //6 5 //4 6
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
4,140
DS_Algo_Kotlin
MIT License
src/year2021/17/Day17.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
private data class TargetPoint( val x: Int, val y: Int ) { fun applySpeed(speed: TargetPoint): TargetPoint { return TargetPoint( x + speed.x, y + speed.y, ) } fun correctSpeed(): TargetPoint { return TargetPoint( x = (x - 1).coerceAtLeast(0), y = y - 1, ) } fun isInside(area: TargetArea): Boolean { return x in area.xRange && y in area.yRange } } private data class TargetArea( val xRange: IntRange, val yRange: IntRange, ) { fun leftArea( currentPosition: TargetPoint, ): Boolean { return currentPosition.x > xRange.last || currentPosition.y < yRange.first } } private val initialPoint = TargetPoint(0, 0) private val inputTest = TargetArea( xRange = 20..30, yRange = -10..-5, ) private val inputReal = TargetArea( xRange = 79..137, yRange = -176..-117, ) private fun calculateAllVariantsForInput( targetArea: TargetArea, calculateAnswer: (Map<TargetPoint, Set<TargetPoint>>) -> Int, ): Int { // Speed To Positions for correct items val mutableSet = mutableMapOf<TargetPoint, Set<TargetPoint>>() val xRange = targetArea.xRange val yRange = targetArea.yRange /** * THIS IS HARDCODED VALUES - Instead of calculating it just put large values for x and y that works for both inputs. */ val hardcodedXRange = 0..xRange.last val hardcodedYRange = yRange.first..200 for (x in hardcodedXRange) { for (y in hardcodedYRange) { val initialSpeed = TargetPoint( x = x, y = y, ) val result = checkIsInTargetAreaWithInitialPosition( targetArea = targetArea, initialPoint = initialPoint, initialSpeed = initialSpeed, ) if (result.any { it.isInside(targetArea) }) { mutableSet[initialSpeed] = result } } } return calculateAnswer(mutableSet) } private fun checkIsInTargetAreaWithInitialPosition( targetArea: TargetArea, initialPoint: TargetPoint, initialSpeed: TargetPoint, ): Set<TargetPoint> { val allPositions = mutableSetOf(initialPoint) var currentSpeed = initialSpeed var currentPosition = initialPoint while (targetArea.leftArea(currentPosition).not()) { currentPosition = currentPosition.applySpeed(currentSpeed) currentSpeed = currentSpeed.correctSpeed() allPositions.add(currentPosition) } return allPositions } fun main() { fun part1(input: TargetArea): Int { return calculateAllVariantsForInput(input) { mutableSet -> mutableSet.mapValues { it.value.maxOf { it.y } } .filter { it.value != 0 } .maxOf { it.value } } } fun part2(input: TargetArea): Int { return calculateAllVariantsForInput(input) { mutableSet -> mutableSet.keys.size } } // test if implementation meets criteria from the description, like: val part1Test = part1(inputTest) check(part1Test == 45) val part1 = part1(inputReal) println("Part 1: $part1") check(part1 == 15400) val part2 = part2(inputReal) println("Part 2: $part2") check(part2 == 5844) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
3,373
KotlinAdventOfCode
Apache License 2.0
src/Day18.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
fun main() { Day18.printSolutionIfTest(64, 58) } object Day18 : Day<Int, Int>(18) { override fun part1(lines: List<String>): Int { val cubes = build(lines).values.filter { !it.air } return cubes.flatMap { c -> c.faces.values }.count { it } } override fun part2(lines: List<String>): Int { val cubes = build(lines) val solidCubes = cubes.values.filter { !it.air } while(addAir(cubes)){} while(removeAir(cubes)){} val airFaces = cubes.filter { it.value.air }.values.flatMap { c -> c.faces.values }.count { !it } val faces = solidCubes.flatMap { c -> c.faces.values }.count { it } //val bubbles = air.filter { it.faces.values.all { t -> !t } } //cubes.forEach { point, c -> println("$point ${c.faces} Air: ${c.air}") } return faces - airFaces //3376 too high } private fun addAir(cubes: MutableMap<Day18.Point, Day18.Cube>): Boolean { val air = cubes.filter { it.value.air }.toMap() var added = 0 air.keys.forEach{ point -> if (isSurroundedBy(point, cubes, 5)){ addMissing(point, cubes) added++ } } println("Added $added") return added > 0 } private fun addMissing(point: Point, cubes: MutableMap<Point, Cube>) { val points = listOf( Point(point.x - 1, point.y, point.z), Point(point.x + 1, point.y, point.z), Point(point.x, point.y - 1, point.z), Point(point.x, point.y + 1, point.z), Point(point.x, point.y, point.z - 1), Point(point.x, point.y, point.z + 1) ) //println("$point surrounded: $surrounded") points.filter { p -> cubes[p] == null }.forEach { cubes[it] = Cube(air=true) } } private fun removeAir(cubes: MutableMap<Point, Cube>): Boolean { val air = cubes.filter { it.value.air }.toMap() var removed = 0 air.keys.forEach{ point -> if (!isSurroundedBy(point, cubes, 6)){ cubes.remove(point) removed++ } } println("Removed $removed") return removed > 0 } private fun isSurroundedBy(point: Point, cubes: MutableMap<Point, Cube>, numPoints:Int): Boolean { val points = listOf( Point(point.x - 1, point.y, point.z), Point(point.x + 1, point.y, point.z), Point(point.x, point.y - 1, point.z), Point(point.x, point.y + 1, point.z), Point(point.x, point.y, point.z - 1), Point(point.x, point.y, point.z + 1) ) //println("$point surrounded: $surrounded") return points.mapNotNull { p -> cubes[p] }.count() == numPoints } private fun processFace(cubes: MutableMap<Point, Cube>, cube: Cube, face: String, otherFace: String, point: Point) { var otherCube = cubes[point] if (otherCube == null){ otherCube = Cube(air=true) cubes[point] = otherCube } otherCube.faces[otherFace] = false if (!otherCube.air) cube.faces[face] = false } /* ###### #OOO## #O O## #OOO## */ private fun build(lines: List<String>): MutableMap<Point, Cube> { val cubes = lines.map { it.split(",").map { c -> c.toInt() } } .map { (x, y, z) -> Point(x, y, z) }.associateWith { Cube() }.toMutableMap() cubes.toMap().forEach { (point, cube) -> cube.faces.forEach { (face, value) -> if (value) { when (face) { "xm" -> processFace(cubes, cube, face, "xp", Point(point.x - 1, point.y, point.z)) "xp" -> processFace(cubes, cube, face, "xm", Point(point.x + 1, point.y, point.z)) "ym" -> processFace(cubes, cube, face, "yp", Point(point.x, point.y - 1, point.z)) "yp" -> processFace(cubes, cube, face, "ym", Point(point.x, point.y + 1, point.z)) "zm" -> processFace(cubes, cube, face, "zp", Point(point.x, point.y, point.z - 1)) "zp" -> processFace(cubes, cube, face, "zm", Point(point.x, point.y, point.z + 1)) } } } } return cubes } data class Point(val x: Int, val y: Int, val z: Int) class Cube(val air:Boolean = false) { val faces = mutableMapOf( "xm" to true, "xp" to true, "ym" to true, "yp" to true, "zm" to true, "zp" to true, ) } }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
4,688
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/Coord2D.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode import kotlin.math.abs data class Coord2D(val x: Int, val y: Int) { companion object { fun parse(input: String) = input.split(",").let { (x, y) -> Coord2D(x.toInt(), y.toInt()) } } override fun toString() = "[$x, $y]" val manhattanDist: Int get() = abs(x) + abs(y) fun adjacent(includeDiagonals: Boolean): List<Coord2D> = buildList { setOf(-1 to 0, 0 to -1, 1 to 0, 0 to 1).forEach { this += copy(x = x + it.first, y = y + it.second) } if (includeDiagonals) { setOf(-1 to -1, -1 to 1, 1 to -1, 1 to 1).forEach { this += copy(x = x + it.first, y = y + it.second) } } } operator fun plus(other: Coord2D) = copy(x = x + other.x, y = y + other.y) operator fun minus(other: Coord2D) = copy(x = x - other.x, y = y - other.y) operator fun times(n: Int) = Coord2D(x * n, y * n) fun distanceTo(other: Coord2D) = abs(x - other.x) + abs(y - other.y) } fun Coord2D.rotateCw() = Coord2D(y, -x) fun Coord2D.rotateCcw() = Coord2D(-y, x) fun Coord2D.isIn(xRange: IntRange, yRange: IntRange) = x in xRange && y in yRange fun List<Coord2D>.filterIn(xRange: IntRange, yRange: IntRange) = filter { it.isIn(xRange, yRange) } data class Coord3D(val x: Int, val y: Int, val z: Int) { companion object { fun parse(input: String) = input.split(",").let { (x, y, z) -> Coord3D(x.toInt(), y.toInt(), z.toInt()) } } operator fun plus(other: Coord3D) = copy(x = x + other.x, y = y + other.y, z = z + other.z) val manhattanDist: Int get() = abs(x) + abs(y) + abs(z) }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,669
advent-of-code
MIT License
y2015/src/main/kotlin/adventofcode/y2015/Day17.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2015 import adventofcode.io.AdventSolution object Day17 : AdventSolution(2015, 17, "No Such Thing as Too Much") { override fun solvePartOne(input: String) = input.lines() .map { it.toInt() } .let { partitions(it, 150) } override fun solvePartTwo(input: String) = input.lines() .map { it.toInt() } .let { partitions2(it, 0, 150) } .groupingBy { it }.eachCount() .minByOrNull { (k, _) -> k } ?.value private fun partitions(parts: List<Int>, total: Int): Int = when { total == 0 -> 1 total < 0 -> 0 parts.isEmpty() -> 0 else -> partitions(parts.drop(1), total) + partitions(parts.drop(1), total - parts[0]) } private fun partitions2(parts: List<Int>, used: Int, total: Int): List<Int> = when { total == 0 -> listOf(used) total < 0 -> emptyList() parts.isEmpty() -> emptyList() else -> partitions2(parts.drop(1), used, total) + partitions2(parts.drop(1), used + 1, total - parts[0]) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
964
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CriticalConnections.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <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.LinkedList import kotlin.math.max import kotlin.math.min /** * 1192. Critical Connections in a Network * @see <a href="https://leetcode.com/problems/critical-connections-in-a-network">Source</a> */ fun interface CriticalConnections { operator fun invoke(n: Int, connections: List<List<Int>>): List<List<Int>> } /** * Approach: Depth First Search for Cycle Detection */ class CycleDetection : CriticalConnections { private var graph: MutableMap<Int, MutableList<Int>> = HashMap() private var rank: MutableMap<Int, Int?> = HashMap() private var connDict: MutableMap<Pair<Int, Int>, Boolean> = HashMap() override operator fun invoke(n: Int, connections: List<List<Int>>): List<List<Int>> { formGraph(n, connections) this.dfs(0, 0) val result: MutableList<List<Int>> = ArrayList() for (criticalConnection in connDict.keys) { result.add(listOf(criticalConnection.first, criticalConnection.second)) } return result } private fun dfs(node: Int, discoveryRank: Int): Int { // That means this node is already visited. We simply return the rank. if (rank[node] != null) { return rank.getOrDefault(node, 0) ?: 0 } // Update the rank of this node. rank[node] = discoveryRank // This is the max we have seen till now. So we start with this instead of INT_MAX or something. var minRank = discoveryRank + 1 for (neighbor in graph.getOrDefault(node, ArrayList())) { // Skip the parent. val neighRank = rank[neighbor] if (neighRank != null && neighRank == discoveryRank - 1) { continue } // Recurse on the neighbor. val recursiveRank = this.dfs(neighbor, discoveryRank + 1) // Step 1, check if this edge needs to be discarded. if (recursiveRank <= discoveryRank) { val sortedU = min(node, neighbor) val sortedV = max(node, neighbor) connDict.remove(Pair(sortedU, sortedV)) } // Step 2, update the minRank if needed. minRank = min(minRank, recursiveRank) } return minRank } private fun formGraph(n: Int, connections: List<List<Int>>) { // Default rank for unvisited nodes is "null" for (i in 0 until n) { graph[i] = ArrayList() rank[i] = null } for (edge in connections) { // Bidirectional edges val u = edge[0] val v = edge[1] graph[u]?.add(v) graph[v]?.add(u) val sortedU = min(u, v) val sortedV = max(u, v) connDict[Pair(sortedU, sortedV)] = true } } } class CriticalConnectionsGraph : CriticalConnections { var time = 0 private val bridges = ArrayList<List<Int>>() override operator fun invoke(n: Int, connections: List<List<Int>>): List<List<Int>> { val graph = buildGraph(n, connections) graph.vertices.forEach { if (it.visited.not()) dfs(it, graph) } return bridges } private fun dfs(u: Vertex, graph: Graph) { time++ u.d = time u.low = time u.visited = true var child = 0 for (v in graph.adjList[u.id]) { if (v.visited.not()) { child++ v.parent = u.id dfs(v, graph) u.low = minOf(u.low, v.low) if (u.parent == -1 && child > 1) { u.articulationPoint = true } else if (u.parent != -1 && v.low >= u.d) { u.articulationPoint = true } if (v.low > u.d) bridges.add(listOf(u.id, v.id)) } else if (u.parent != v.id) { u.low = minOf(u.low, v.d) } } } private fun buildGraph(n: Int, connections: List<List<Int>>): Graph { val graph = Graph(n) connections.forEach { path -> val (from, to) = path[0] to path[1] graph.addEdge(from, to) } return graph } private data class Vertex( val id: Int, var d: Int = 0, var low: Int = Int.MAX_VALUE, var parent: Int = -1, var visited: Boolean = false, var articulationPoint: Boolean = false, ) private class Graph(n: Int) { val vertices = Array(n) { i -> Vertex(i) } val adjList = Array(n) { LinkedList<Vertex>() } fun addEdge(from: Int, to: Int) { val (f, t) = vertices[from] to vertices[to] adjList[from].add(t) adjList[to].add(f) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,429
kotlab
Apache License 2.0
src/day1/Code.kt
fcolasuonno
221,697,249
false
null
package day1 import java.io.File import kotlin.math.abs fun main() { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } fun parse(input: List<String>) = input.map { it.split(", ") }.requireNoNulls() fun rotate(dir: Char, lr: Char) = when (dir) { 'N' -> if (lr == 'R') 'E' else 'W' 'S' -> if (lr == 'R') 'W' else 'E' 'W' -> if (lr == 'R') 'N' else 'S' 'E' -> if (lr == 'R') 'S' else 'N' else -> throw IllegalArgumentException() } fun part1(input: List<List<String>>): Any? = input.map { it.fold(mutableListOf("NO")) { list, next -> list.apply { add(rotate(list.last().first(), next.first()) + next.drop(1)) } }.drop(1).groupBy { it.first() }.mapValues { it.value.sumBy { it.drop(1).toInt() } }.let { abs(it.getOrDefault('E', 0) - it.getOrDefault('W', 0)) + abs(it.getOrDefault('N', 0) - it.getOrDefault('S', 0)) } } fun part2(input: List<List<String>>): Any? = input.map { val visited = mutableSetOf<Pair<Int, Int>>() it.fold(mutableListOf("NO")) { list, next -> list.apply { add(rotate(list.last().first(), next.first()) + next.drop(1)) } }.drop(1).fold(mutableListOf(0 to 0)) { currentPos, steps -> currentPos.apply { val last = last() currentPos += (1..steps.drop(1).toInt()).map { movement -> last.copy( first = last.first + when (steps.first()) { 'E' -> movement 'W' -> -movement else -> 0 }, second = last.second + when (steps.first()) { 'N' -> movement 'S' -> -movement else -> 0 }) } } }.first { !visited.add(it) }.let { abs(it.first) + abs(it.second) } }
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
2,228
AOC2016
MIT License
2019/day3/part_b.kt
sergeknystautas
226,467,020
false
null
package aoc2019.day3; import kotlin.math.abs; /* Takes a sequence like U7,R6,D4,L4 and creates a sequence of spots this goes thru like... []"1,0","2,0","3,0", etc...] */ fun followWire(instructions: String): List<String> { // Assume we start at 0,0 var pos = Pair(0,0); var path = mutableListOf<String>(); var commands = instructions.split(","); for (command in commands) { // println(command); var delta = Direction(command.substring(0, 1).toUpperCase()); var counter:Int = command.substring(1).toInt(); while (counter > 0) { pos = Pair(pos.first + delta.first, pos.second + delta.second); var label = "${pos.first},${pos.second}"; // println(label); path.add(label); counter--; } } // path.remove("0,0"); // println(path.size); return path; } fun Direction(letter: String): Pair<Int,Int> { when (letter) { "R" -> return Pair(1,0); "L" -> return Pair(-1,0); "U" -> return Pair(0,1); "D" -> return Pair(0,-1); } return Pair(0,0); } fun Distance(pair: String): Int { var coords: List<Int> = pair.split(",").map{ abs(it.toInt()) }; return coords[0] + coords[1]; } fun Steps(pair: String, wire1: List<String>, wire2: List<String>): Int { // Find the indices of both and add them up. var index1 = wire1.indexOf(pair) + 1; var index2 = wire2.indexOf(pair) + 1; return index1 + index2; } fun main(args: Array<String>) { if (args.size != 2) { println("You done messed up a-a-ron"); return; } var red = args[0]; var blue = args[1]; var redPath = followWire(red); var bluePath = followWire(blue); var crosses = redPath.intersect(bluePath); // println(crosses); var distances = crosses.map{ Steps(it, redPath, bluePath); } // println(distances); println(distances.min()); }
0
Kotlin
0
0
38966bc742f70122681a8885e986ed69dd505243
1,940
adventofkotlin2019
Apache License 2.0
src/day03/Day03.kt
S-Flavius
573,063,719
false
{"Kotlin": 6843}
package day03 import readInput import kotlin.concurrent.fixedRateTimer fun main() { fun part1(input: List<String>): Int { var prioSum = 0 for (line in input) { var common = ' ' val compOne = line.substring(0, line.length / 2) val compTwo = line.substring(line.length / 2) for (letter in compOne) { for (letterTwo in compTwo) { if (letter == letterTwo) common = letter } } prioSum += if (common.isUpperCase()) common.code - 38 else common.code - 96 } return prioSum } fun part2(input: List<String>): Int { var currentLines = 0 var prioSum = 0 val lines = arrayOf("", "", "") for (line in input) { var common = ' ' lines[currentLines++] = line if (currentLines == 3) { for (letter in lines[0]) { for (letterOne in lines[1]) { for (letterTwo in lines[2]) { if (letter == letterOne && letter == letterTwo) { common = letter } } } } currentLines = 0 prioSum += if (common.isUpperCase()) common.code - 38 else common.code - 96 } } return prioSum } // test if implementation meets criteria from the description, like: val testInput = readInput("day03/Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("day03/Day03") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
47ce29125ff6071edbb07ae725ac0b9d672c5356
1,799
AoC-Kotlin-2022
Apache License 2.0
src/Day12.kt
a-glapinski
572,880,091
false
{"Kotlin": 26602}
import utils.Coordinate2D import utils.readInputAsLines fun main() { val input = readInputAsLines("day12_input") val heightmap = input.flatMapIndexed { i, row -> row.mapIndexed { j, height -> Coordinate2D(i, j) to height } }.toMap() fun reach(startElevation: Char, destinationElevation: Char): Int { val (start, _) = heightmap.entries.first { (_, h) -> h == startElevation } val distances = heightmap.keys.associateWith { Int.MAX_VALUE }.toMutableMap() .apply { this[start] = 0 } val possibleMoves = mutableListOf(start) while (possibleMoves.isNotEmpty()) { val curr = possibleMoves.removeFirst() curr.neighbours() .filter { n -> n in heightmap && heightmap.getElevation(n) - heightmap.getElevation(curr) <= 1 } // change to >= -1 for second part .forEach { neighbour -> val distance = distances.getValue(curr) + 1 if (heightmap[neighbour] == destinationElevation) return distance if (distance < distances.getValue(neighbour)) { distances[neighbour] = distance possibleMoves.add(neighbour) } } } error("Couldn't reach destination.") } val result1 = reach(startElevation = 'S', destinationElevation = 'E') println(result1) // val result2 = reach(startElevation = 'E', destinationElevation = 'a') // println(result2) } private fun Map<Coordinate2D, Char>.getElevation(coordinate: Coordinate2D) = when (val c = getValue(coordinate)) { 'S' -> 'a' 'E' -> 'z' else -> c }
0
Kotlin
0
0
c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8
1,729
advent-of-code-2022
Apache License 2.0
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day18.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2020 import nl.dirkgroot.adventofcode.util.Input import nl.dirkgroot.adventofcode.util.Puzzle class Day18(input: Input) : Puzzle() { private val tokenRegex = "\\s*(\\d+|\\+|\\*|\\(|\\))".toRegex() abstract class Token object Plus : Token() object Star : Token() object Open : Token() object Close : Token() data class Number(val value: Long) : Token() interface Term { fun evaluate(): Long } abstract class Operation(val term: Term) { abstract fun evaluate(input: Long): Long } class Add(term: Term) : Operation(term) { override fun evaluate(input: Long) = input + term.evaluate() } class Multiply(term: Term) : Operation(term) { override fun evaluate(input: Long) = input * term.evaluate() } data class Constant(val value: Long) : Term { override fun evaluate() = value } data class Expression(val term: Term, val ops: List<Operation>) : Term { override fun evaluate() = ops .fold(term.evaluate()) { acc, operation -> operation.evaluate(acc) } } private val expressions by lazy { input.lines() } override fun part1() = solve(Part.One) override fun part2() = solve(Part.Two) private fun solve(part: Part) = expressions .map { tokenize(it) } .map { Parser(part).parse(it) } .sumOf { it.evaluate() } private fun tokenize(expression: String) = tokenRegex.findAll(expression).map { when (val token = it.groupValues[1]) { "+" -> Plus "*" -> Star "(" -> Open ")" -> Close else -> Number(token.toLong()) } } enum class Part { One, Two } private class Parser(val part: Part) { fun parse(tokens: Sequence<Token>) = parseExpression(tokens).first private fun parseExpression(tokens: Sequence<Token>): Pair<Expression, Sequence<Token>> = parseTerm(tokens).let { (term, operations) -> val (ops, remaining) = parseOperations(operations) Expression(term, ops) to remaining } private fun parseTerm(tokens: Sequence<Token>) = tokens.first().let { first -> when (first) { is Open -> { val (expression, remaining) = parseExpression(tokens.drop(1)) if (remaining.first() != Close) throw IllegalStateException("Expected closing bracket") expression to remaining.drop(1) } is Number -> Constant(first.value) to tokens.drop(1) else -> throw IllegalStateException("Unexpected token $first") } } private tailrec fun parseOperations( remaining: Sequence<Token>, operations: MutableList<Operation> = mutableListOf() ): Pair<List<Operation>, Sequence<Token>> = when { remaining.none() -> operations to remaining remaining.first() is Close -> operations to remaining else -> { val (operation, rest) = when (part) { Part.One -> parseOperation1(remaining) Part.Two -> parseOperation2(remaining) } operations.add(operation) parseOperations(rest, operations) } } private fun parseOperation1(tokens: Sequence<Token>): Pair<Operation, Sequence<Token>> { val operation = tokens.first() val (term, remaining) = parseTerm(tokens.drop(1)) return when (operation) { is Plus -> Add(term) to remaining is Star -> Multiply(term) to remaining else -> throw IllegalStateException("Unexpected token: $operation") } } private fun parseOperation2(tokens: Sequence<Token>) = when (val operation = tokens.first()) { is Plus -> { val (term, remaining) = parseTerm(tokens.drop(1)) Add(term) to remaining } is Star -> { val (expr, remaining) = parseExpression(tokens.drop(1)) Multiply(expr) to remaining } else -> throw IllegalStateException("Unexpected token: $operation") } } }
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
4,495
adventofcode-kotlin
MIT License
src/main/kotlin/solutions/Day07.kt
chutchinson
573,586,343
false
{"Kotlin": 21958}
class Day07 : Solver { open class Node (val parent: Node?, val children: MutableList<Node>) { open val size: Int get() = 0 fun iterator (): Sequence<Node> { val stack = ArrayDeque<Node>() stack.addLast(this) return sequence { while (stack.size > 0) { val node = stack.removeFirst() for (child in node.children) stack.addLast(child) yield (node) } } } } class Directory (parent: Node?, val name: String) : Node(parent, mutableListOf()) { override val size: Int get() = this.iterator() .filter { it is File } .map { it.size } .sum() } class File (parent: Node?, val name: String, val fileSize: Int): Node(parent, mutableListOf()) { override val size : Int get() = fileSize } override fun solve (input: Sequence<String>) { val tree = parse(input) println(first(tree)) println(second(tree)) } fun first (tree: Directory): Int { return tree.iterator() .filter { it is Directory && it.size < 100000 } .sumOf { it.size } } fun second (tree: Directory): Int { val totalUnused = 70000000 - tree.iterator() .filter { it is File } .sumOf { it.size } return tree.iterator() .filter { it is Directory && totalUnused + it.size >= 30000000 } .minOf { it.size } } fun parse (input: Sequence<String>) : Directory { val root = Directory(null, "/") var current: Node? = root for (line in input) { val cmd = line.substring(0, 4) val arg = if (line.length >= 5) line.substring(5) else "" when { cmd == "dir " -> continue cmd == "$ ls" -> continue cmd == "$ cd" && arg == "/" -> current = root cmd == "$ cd" && arg == ".." -> current = current?.parent cmd == "$ cd" -> { val parent = current current = Directory(current, arg) parent?.children?.add(current) } else -> { val parts = line.split(" ") val size = parts[0].toInt() val name = parts[1] current?.children?.add(File(current, name, size)) } } } return root } }
0
Kotlin
0
0
5076dcb5aab4adced40adbc64ab26b9b5fdd2a67
2,589
advent-of-code-2022
MIT License
ceria/04/src/main/kotlin/Solution.kt
VisionistInc
317,503,410
false
null
import java.io.File val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid") val optionalField = "cid" val validUnits = mapOf<String, IntRange>("cm" to IntRange(150, 193), "in" to IntRange(59, 76)) val validEyeColors = listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") fun main(args : Array<String>) { val input = File(args.first()).readLines() println("Solution 1: ${solution1(detectPassports(input))}") println("Solution 2: ${solution2(detectPassports(input))}") } private fun solution1(input: List<String>) :Int { var validPassportCount = 0 for ( p in input ) { val fieldsNotInPassport = requiredFields.minus(p.split(" ").map{field -> field.split(":").get(0) }) if (fieldsNotInPassport.isEmpty() || (fieldsNotInPassport.size == 1 && fieldsNotInPassport.contains(optionalField)) ) { validPassportCount++ } } return validPassportCount } private fun solution2(input: List<String>) :Int { var validPassportCount = 0 for ( p in input ) { val fieldsInPassport = p.split(" ").map{field -> field.split(":").get(0) } val fieldsNotInPassport = requiredFields.minus( fieldsInPassport ) if (fieldsNotInPassport.isEmpty() || (fieldsNotInPassport.size == 1 && fieldsNotInPassport.contains(optionalField)) ) { val fieldValues = p.split(" ").associate { val (left, right) = it.split(":") left to right } var valid = true for (f in requiredFields) { val value = fieldValues.get(f) when (f) { "byr" -> { if (value?.length != 4 || value.filter{ it.isDigit() }.length != 4 || !IntRange(1920, 2002).contains(value.toInt())) { valid = false } } "iyr" -> { if (value?.length != 4 || value.filter{ it.isDigit() }.length != 4 || !IntRange(2010, 2020).contains(value.toInt())) { valid = false } } "eyr" -> { if (value?.length != 4 || value.filter{ it.isDigit() }.length != 4 || !IntRange(2020, 2030).contains(value.toInt())) { valid = false } } "hgt" -> { if ( !validUnits.containsKey(value?.takeLast(2)) || validUnits.get(value?.takeLast(2))?.contains(value?.dropLast(2)?.toInt()) == false ) { valid = false } } "hcl" -> { if (value?.length != 7 || value.first() != '#' || value.takeLast(6).filter{ it in 'a'..'f' || it in '0'..'9' }.length != 6) { valid = false } } "ecl" -> { if (value?.length != 3 || !validEyeColors.contains(value)) { valid = false } } "pid" -> { if (value?.length != 9 || value.filter{ it.isDigit() }.length != 9) { valid = false } } } if (!valid) { break } } if (valid) { validPassportCount++ } } } return validPassportCount } private fun detectPassports(input :List<String>) :List<String> { var passports = mutableListOf<String>() var completePassport = "" for (line in input) { if (line.isNullOrBlank()) { passports.add(completePassport.trim()) completePassport = "" continue } completePassport = completePassport.plus(line).plus(" ") } passports.add(completePassport.trim()) return passports }
0
Rust
0
0
002734670384aa02ca122086035f45dfb2ea9949
4,126
advent-of-code-2020
MIT License
src/Lesson6Sorting/NumberOfDiscIntersections.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
import java.util.Arrays /** * 100/100 * @param A * @return */ fun solution(A: IntArray): Int { val N = A.size val higherEdges = LongArray(N) val lowerEdges = LongArray(N) for (i in 0 until N) { higherEdges[i] = i + A[i].toLong() lowerEdges[i] = i - A[i].toLong() } Arrays.sort(higherEdges) Arrays.sort(lowerEdges) var counter: Long = 0 for (i in N - 1 downTo 0) { val position: Int = Arrays.binarySearch(lowerEdges, higherEdges[i]) if (position >= 0) { var intersects = position for (j in position until N) { if (lowerEdges[j] == higherEdges[i]) { intersects++ } else { break } } counter += intersects.toLong() } else { counter -= (position + 1).toLong() } } val duplicates = N.toLong() * (N.toLong() + 1) / 2 // ova dva u prvom ranu preskoci pa dodaj pre slanja kao setio si se duplikata counter -= duplicates return if (counter > 10000000) -1 else counter.toInt() } // Inspiration: https://rafal.io/posts/codility-intersecting-discs.html /** * We draw N discs on a plane. The discs are numbered from 0 to N − 1. An array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J]. * * We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders). * * The figure below shows discs drawn for N = 6 and A as follows: * * A[0] = 1 * A[1] = 5 * A[2] = 2 * A[3] = 1 * A[4] = 4 * A[5] = 0 * * * There are eleven (unordered) pairs of discs that intersect, namely: * * discs 1 and 4 intersect, and both intersect with all the other discs; * disc 2 also intersects with discs 0 and 3. * Write a function: * * class Solution { public int solution(int[] A); } * * that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000. * * Given array A shown above, the function should return 11, as explained above. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [0..100,000]; * each element of array A is an integer within the range [0..2,147,483,647]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
2,544
Codility-Kotlin
Apache License 2.0
src/Day06.kt
jfiorato
573,233,200
false
null
fun main() { fun part1(input: List<String>): Array<Int> { var results: Array<Int> = arrayOf() input.forEach charLoop@{ val marker: ArrayList<Char> = arrayListOf() it.forEachIndexed { idx, char -> if (marker.size == 4) { marker.removeAt(0) marker += char if (marker.distinct().size == 4) { results += (idx + 1) return@charLoop } } else { marker += char } } } return results } fun part2(input: List<String>): Array<Int> { var results: Array<Int> = arrayOf() input.forEach charLoop@{ val marker: ArrayList<Char> = arrayListOf() it.forEachIndexed { idx, char -> if (marker.size == 14) { marker.removeAt(0) marker += char if (marker.distinct().size == 14) { results += (idx + 1) return@charLoop } } else { marker += char } } } return results } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput).contentEquals(arrayOf(7, 5, 6, 10, 11))) check(part2(testInput).contentEquals(arrayOf(19, 23, 23, 29, 26))) val input = readInput("Day06") println(part1(input).joinToString(separator = ",")) println(part2(input).joinToString(separator = ",")) }
0
Kotlin
0
0
4455a5e9c15cd067d2661438c680b3d7b5879a56
1,691
kotlin-aoc-2022
Apache License 2.0
src/kickstart2022/c/AntsOnStick.kt
vubogovich
256,984,714
false
null
package kickstart2022.c // TODO test set 2 fun main() { val inputFileName = "src/kickstart2022/c/AntsOnStick.in" java.io.File(inputFileName).takeIf { it.exists() }?.also { System.setIn(it.inputStream()) } for (case in 1..readLine()!!.toInt()) { val (n, len) = readLine()!!.split(' ').map { it.toInt() } val ants = Array(n) { val (p, d) = readLine()!!.split(' ').map { it.toInt() } Ant(it + 1, p, if (d == 1) Direction.RIGHT else Direction.LEFT) } .sortedBy { it.pos } .toMutableList() var time = 0L val drops = mutableListOf<Drop>() while (ants.size > 0) { while (ants.size > 0 && ants[0].dir == Direction.LEFT) { drops.add(Drop(ants[0].num, time + ants[0].pos)) ants.removeAt(0) } while (ants.size > 0 && ants.last().dir == Direction.RIGHT) { drops.add(Drop(ants.last().num, time + len - ants.last().pos)) ants.removeLast() } var minLen = Int.MAX_VALUE for (i in 0 until ants.size - 1) { if (ants[i].dir == Direction.RIGHT && ants[i + 1].dir == Direction.LEFT && ants[i + 1].pos - ants[i].pos < minLen ) { minLen = ants[i + 1].pos - ants[i].pos } } if (minLen < Int.MAX_VALUE) { val move = (minLen + 1) / 2 for (k in ants.indices) { ants[k].pos += if (ants[k].dir == Direction.RIGHT) move else -move } for (k in 0 until ants.size - 1) { if (ants[k].pos > ants[k + 1].pos && ants[k].dir == Direction.RIGHT && ants[k + 1].dir == Direction.LEFT ) { ants[k].pos-- ants[k].dir = Direction.LEFT ants[k + 1].pos++ ants[k + 1].dir = Direction.RIGHT } } for (k in 0 until ants.size - 1) { if (ants[k].pos == ants[k + 1].pos && ants[k].dir == Direction.RIGHT && ants[k + 1].dir == Direction.LEFT ) { ants[k].dir = Direction.LEFT ants[k + 1].dir = Direction.RIGHT } } time += move } } val res = drops.sortedWith(compareBy(Drop::time, Drop::num)) .map { it.num } .joinToString(" ") println("Case #$case: $res") } } enum class Direction { LEFT, RIGHT } data class Ant(var num: Int, var pos: Int, var dir: Direction) data class Drop(val num: Int, val time: Long)
0
Kotlin
0
0
fc694f84bd313cc9e8fcaa629bafa1d16ca570fb
2,924
kickstart
MIT License
src/Day01.kt
nordberg
573,769,081
false
{"Kotlin": 47470}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { return input.fold(Pair(Int.MIN_VALUE, 0)) { bestSoFarAndCurrent, currCalAsStr -> if (currCalAsStr.isEmpty()) { Pair(max(bestSoFarAndCurrent.first, bestSoFarAndCurrent.second), 0) } else { Pair(bestSoFarAndCurrent.first, bestSoFarAndCurrent.second + currCalAsStr.toInt()) } }.first } fun part2(input: List<String>): Int { val biggest = mutableListOf<Int>() var maxSoFar = Int.MIN_VALUE var currentCounter = 0 input.forEach { s -> if (s.isEmpty()) { biggest += currentCounter currentCounter = 0 } else { currentCounter += s.toInt() } } biggest.sortDescending() return biggest.take(3).sum() } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") //check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3de1e2b0d54dcf34a35279ba47d848319e99ab6b
1,154
aoc-2022
Apache License 2.0
src/Day01.kt
gnuphobia
578,967,785
false
{"Kotlin": 17559}
fun main() { fun part1(input: List<String>): Int { var largest = 0 var total = 0 for (row in input) { if (row.isBlank()) { if (total > largest) { largest = total } total = 0 } else { total += Integer.parseInt(row) } } return largest } fun part2(input: List<String>): Int { val calories = mutableListOf<Int>() var total = 0 for (row in input) { if (row.isBlank() || row.isEmpty()) { calories.add(total) total = 0 continue } total += Integer.parseInt(row); } calories.add(total) calories.sortDescending() return calories[0] + calories[1] + calories[2] } // test if implementation meets criteria from the description, like: var part1TestResult = 24000 val testInput = readInput("Day01_test") check(part1(testInput) == part1TestResult) var part2TestResult = 45000 check(part2(testInput) == part2TestResult) val input = readInput("Day01") part1(input).println() part2(input).println() check(part1(input) == 69912) check(part2(input) == 208180) }
0
Kotlin
0
0
a1b348ec33f85642534c46af8c4a69e7b78234ab
1,313
aoc2022kt
Apache License 2.0
src/Day3.kt
syncd010
324,790,559
false
null
import kotlin.math.min import kotlin.math.max import kotlin.system.exitProcess class Day3: Day { data class Line(val from: Position, val to: Position) { val isVertical: Boolean get() = from.x == to.x val isHorizontal: Boolean get() = from.y == to.y val isPosition: Boolean get() = isVertical && isHorizontal val isOrigin: Boolean get() = (from.x == 0 && from.y == 0) || (to.x == 0 && to.y == 0) val minX: Int get() = min(from.x, to.x) val minY: Int get() = min(from.y, to.y) val maxX: Int get() = max(from.x, to.x) val maxY: Int get() = max(from.y, to.y) infix fun intersect(other: Line): Line? { when { this.isHorizontal && other.isHorizontal && (this.from.y == other.from.y) -> { val maxMinX = max(this.minX, other.minX) val minMaxX = min(this.maxX, other.maxX) val y = this.from.y return if (minMaxX >= maxMinX) Line(Position(maxMinX, y), Position(minMaxX, y)) else null } this.isVertical && other.isVertical && (this.from.x == other.from.x) -> { val maxMinY = max(this.minY, other.minY) val minMaxY = min(this.maxY, other.maxY) val x = this.from.x return if (minMaxY >= maxMinY) Line(Position(maxMinY, x), Position(minMaxY, x)) else null } this.isHorizontal && other.isVertical && (this.minX <= other.minX) && (this.maxX >= other.maxX) && (other.minY <= this.minY) && (other.maxY >= this.maxY) -> { val intersection = Position(other.minX, this.minY) return Line(intersection, intersection) } this.isVertical && other.isHorizontal && (this.minY <= other.minY) && (this.maxY >= other.maxY) && (other.minX <= this.minX) && (other.maxX >= this.maxX) -> { val intersection = Position(this.minX, other.minY) return Line(intersection, intersection) } } return null } } private fun convert(input: List<String>) : Pair<List<Line>, List<Line>> { fun convertLine(directions: List<String>): List<Line> { val lines = mutableListOf<Line>() for ((index, dir) in directions.withIndex()) { val from: Position = if (index == 0) Position(0, 0) else lines[index - 1].to val steps = dir.substring(1).toInt() val to: Position = when (dir[0]) { 'R' -> Position(from.x + steps, from.y) 'L' -> Position(from.x - steps, from.y) 'U' -> Position(from.x, from.y + steps) 'D' -> Position(from.x, from.y - steps) else -> { println("Unknown direction: $dir[0]") exitProcess(-1) } } lines.add(Line(from, to)) } return lines } return Pair(convertLine(input[0].split(",")), convertLine(input[1].split(","))) } override fun solvePartOne(input: List<String>): Int? { val wires = convert(input) val intersections = mutableListOf<Line>() for (firstLine in wires.first) { for (secondLine in wires.second) { if (firstLine.isOrigin && secondLine.isOrigin) continue val tmp = (firstLine.intersect(secondLine)) if (tmp != null) { intersections.add(tmp) } } } val origin = Position(0, 0) val distances = intersections.map { if (it.isPosition) manhattanDist(origin, it.from) else min(manhattanDist(origin, it.from), manhattanDist(origin, it.to)) } return distances.min() } override fun solvePartTwo(input: List<String>): Int? { val wires = convert(input) val intersectionSteps = mutableListOf<Int>() var firstWireSteps = 0 for (firstLine in wires.first) { var secondWireSteps = 0 for (secondLine in wires.second) { val inter = (firstLine.intersect(secondLine)) if ((inter != null) && !(firstLine.isOrigin && secondLine.isOrigin)) { val totalSteps = firstWireSteps + secondWireSteps + min(manhattanDist(firstLine.from, inter.from), manhattanDist(firstLine.from, inter.to)) + min(manhattanDist(secondLine.from, inter.from), manhattanDist(secondLine.from, inter.to)) intersectionSteps.add(totalSteps) } secondWireSteps += manhattanDist(secondLine.from, secondLine.to) } firstWireSteps += manhattanDist(firstLine.from, firstLine.to) } return intersectionSteps.min() } }
0
Kotlin
0
0
11c7c7d6ccd2488186dfc7841078d9db66beb01a
5,201
AoC2019
Apache License 2.0
Cinema.kt
hahaslav
453,238,848
false
{"Jupyter Notebook": 155781, "Kotlin": 82973}
package cinema const val SEATSLIMIT = 60 const val VIPRICE = 10 const val POORPRICE = 8 fun inputRoom(): String { println("Enter the number of rows:") val r = readLine()!! println("Enter the number of seats in each row:") val s = readLine()!! return "$r $s" } fun scheme(cinema: MutableList<MutableList<Char>>) { print("\nCinema:\n ") for (i in 1..cinema[0].size) print(" $i") println() for (i in 0 until cinema.size) println("${i + 1} ${cinema[i].joinToString(" ")}") } fun inputSeat(): String { println("\nEnter a row number:") val r = readLine()!! println("Enter a seat number in that row:") val s = readLine()!! return "$r $s" } fun smallRoom() = VIPRICE fun bigRoom(rows: Int, seatR: Int) = if (seatR <= rows / 2) VIPRICE else POORPRICE fun calculateSeat(cinema: MutableList<MutableList<Char>>, seatR: Int): Int { if (cinema.size * cinema[0].size <= SEATSLIMIT) { return smallRoom() } return bigRoom(cinema.size, seatR) } fun shopping(cinema: MutableList<MutableList<Char>>) { val (seatR, seatS) = inputSeat().split(" ").map { it.toInt() } println() if (seatR < 1 || seatR > cinema.size || seatS < 1 || seatS > cinema[0].size) { println("Wrong input!") shopping(cinema) return } when (cinema[seatR - 1][seatS - 1]) { 'S' -> { cinema[seatR - 1][seatS - 1] = 'B' println("Ticket price: \$${calculateSeat(cinema, seatR)}") } 'B' -> { println("That ticket has already been purchased!") shopping(cinema) } } } fun calculateAll(cinema: MutableList<MutableList<Char>>): Int { var result = 0 for (row in 0 until cinema.size) for (seat in cinema[row]) result += calculateSeat(cinema, row + 1) return result } fun stats(cinema: MutableList<MutableList<Char>>) { var bought = 0 var income = 0 for (row in cinema) for (seat in row) bought += if (seat == 'B') 1 else 0 println("\nNumber of purchased tickets: $bought") var notPrc = bought * 100000 / (cinema.size * cinema[0].size) notPrc = (notPrc + if (notPrc % 10 > 4) 10 else 0) / 10 val prc = (notPrc / 100).toString() + "." + (notPrc % 100 / 10).toString() + (notPrc % 10).toString() println("Percentage: ${prc}%") for (row in 0 until cinema.size) for (seat in cinema[row]) income += if (seat == 'B') calculateSeat(cinema, row + 1) else 0 println("Current income: \$$income") println("Total income: \$${calculateAll(cinema)}") } fun main() { val (rows, seats) = inputRoom().split(" ").map { it.toInt() } val cinema = MutableList(rows) { MutableList(seats) { 'S' } } var choice = -1 while (choice != 0) { println() println(""" 1. Show the seats 2. Buy a ticket 3. Statistics 0. Exit """.trimIndent()) choice = readLine()!!.toInt() when (choice) { 1 -> scheme(cinema) 2 -> shopping(cinema) 3 -> stats(cinema) } } }
0
Jupyter Notebook
0
0
5ca7234db040f585167a774fcc66b3fc878e1ebc
3,084
Kotlin-Basics
MIT License
src/Day05.kt
gischthoge
573,509,147
false
{"Kotlin": 5583}
fun main() { fun moveCratesAndGetTop(input: List<String>, reverse: Boolean): String { val cratesInput = input .filter { it.contains("[") } .map { row -> row.chunked(4).map { it.replace(Regex("[\\s\\[\\]]"), "") }} val maxSize = cratesInput.maxOf { it.size } val stacks = (0 until maxSize).map { stack -> cratesInput.mapNotNull { it.getOrNull(stack) } .filter { it.isNotEmpty() } } return input.mapNotNull { Regex("move (\\d+) from (\\d+) to (\\d+)") .find(it) ?.groupValues?.drop(1) ?.map { s -> s.toInt() } } .fold(stacks.toMutableList()) { acc, (take, from, to) -> val crates = if (reverse) acc[from - 1].take(take).reversed() else acc[from - 1].take(take) acc[from - 1] = acc[from - 1].drop(take) acc[to - 1] = crates + acc[to - 1] acc }.joinToString("") { it.firstOrNull() ?: "" } } fun part1(input: List<String>): String { return moveCratesAndGetTop(input, reverse = true) } fun part2(input: List<String>): String { return moveCratesAndGetTop(input, reverse = false) } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e403f738572360d4682f9edb6006d81ce350ff9d
1,349
aock
Apache License 2.0
app/src/main/kotlin/kotlinadventofcode/2023/2023-02.kt
pragmaticpandy
356,481,847
false
{"Kotlin": 1003522, "Shell": 219}
// Originally generated by the template in CodeDAO package kotlinadventofcode.`2023` import com.github.h0tk3y.betterParse.combinators.* import com.github.h0tk3y.betterParse.grammar.* import com.github.h0tk3y.betterParse.lexer.* import kotlinadventofcode.Day class `2023-02` : Day { override fun runPartOneNoUI(input: String): String { return parseGames(input) .filter { it.possiblyContains(12, 13, 14) } .sumOf { it.id }.toString() } override fun runPartTwoNoUI(input: String): String { return parseGames(input).sumOf { it.powerOfMinimumRequired() }.toString() } private data class Game(val id: Int, val draws: List<Draw>) { fun possiblyContains(numRed: Int, numGreen: Int, numBlue: Int): Boolean = draws.all { draw -> draw.counts.all { count -> when (count.color) { Color.RED -> count.count <= numRed Color.GREEN -> count.count <= numGreen Color.BLUE -> count.count <= numBlue } } } fun maximumSeen(color: Color): Int = draws.mapNotNull { draw -> draw.counts.find { it.color == color } }.maxOfOrNull { it.count } ?: 0 fun powerOfMinimumRequired(): Int { return maximumSeen(Color.RED) * maximumSeen(Color.GREEN) * maximumSeen(Color.BLUE) } } private data class Draw(val counts: List<ColorCount>) {} private data class ColorCount(val color: Color, val count: Int) {} private enum class Color { RED, GREEN, BLUE } private fun parseGames(input: String): List<Game> { val grammar = object : Grammar<List<Game>>() { val newlineLit by literalToken("\n") val spaceLit by literalToken(" ") val commaLit by literalToken(",") val semicolonLit by literalToken(";") val colonLit by literalToken(":") val redLit by literalToken("red") val greenLit by literalToken("green") val blueLit by literalToken("blue") val gameLit by literalToken("Game") val positiveIntRegex by regexToken("\\d+") val positiveInt by positiveIntRegex use { text.toInt() } val red by redLit use { Color.RED } val green by greenLit use { Color.GREEN } val blue by blueLit use { Color.BLUE } val color by red or green or blue val colorCount by (positiveInt and skip(spaceLit) and color) map { ColorCount(it.t2, it.t1) } val draw by separatedTerms(colorCount, commaLit and spaceLit) map { Draw(it) } val draws by separatedTerms(draw, semicolonLit and spaceLit) val game by (skip(gameLit) and skip(spaceLit) and positiveInt and skip(colonLit) and skip(spaceLit) and draws) map { Game(it.t1, it.t2) } override val rootParser by separatedTerms(game, newlineLit) } return grammar.parseToEnd(input) } override val defaultInput = """Game 1: 4 red, 1 green, 15 blue; 6 green, 2 red, 10 blue; 7 blue, 6 green, 4 red; 12 blue, 10 green, 3 red Game 2: 3 green, 18 blue; 14 green, 4 red, 2 blue; 3 red, 14 green, 15 blue Game 3: 12 green, 2 blue; 9 green; 1 red, 11 blue, 4 green Game 4: 4 blue, 8 green, 5 red; 6 red, 7 blue, 9 green; 2 green, 2 red, 2 blue; 2 green, 6 blue, 9 red; 10 red, 9 green Game 5: 12 red, 1 green, 7 blue; 13 red, 16 blue; 16 blue, 10 red; 4 blue; 16 blue, 7 red; 1 blue, 7 red Game 6: 17 blue, 2 red; 5 blue, 6 green, 2 red; 5 green, 5 blue; 5 green, 12 blue, 4 red Game 7: 2 red, 1 blue, 10 green; 8 red, 14 green, 9 blue; 15 red, 1 blue, 6 green; 9 blue, 3 green, 10 red; 7 blue, 13 red, 4 green Game 8: 1 green, 2 blue; 7 red, 2 blue, 1 green; 1 red, 2 green; 4 red, 1 blue; 11 red, 2 green, 2 blue; 1 blue, 2 green, 11 red Game 9: 11 green, 11 blue, 6 red; 2 green, 3 blue, 2 red; 2 red, 11 blue, 14 green; 5 green, 7 red, 7 blue; 7 green, 1 red, 12 blue; 1 red, 8 green, 7 blue Game 10: 2 red, 8 green, 7 blue; 10 red, 5 green, 2 blue; 4 red, 8 green, 16 blue; 10 blue, 3 green, 15 red Game 11: 2 blue, 2 green, 5 red; 1 green, 3 red, 3 blue; 11 green, 1 red, 2 blue Game 12: 8 blue, 11 green, 14 red; 10 green, 13 red, 2 blue; 1 red, 6 green, 4 blue; 13 red, 11 green, 6 blue Game 13: 15 red, 17 green, 1 blue; 12 red, 1 blue, 1 green; 2 red, 1 blue, 14 green Game 14: 6 green, 11 red, 3 blue; 6 green, 2 blue; 2 green, 10 red, 8 blue; 2 red; 1 green, 9 red; 3 blue, 1 green, 3 red Game 15: 11 blue, 11 green, 4 red; 3 green, 10 blue; 2 red, 9 green, 9 blue Game 16: 2 blue, 11 green; 1 red, 1 blue, 11 green; 12 green, 1 blue, 1 red; 3 blue, 14 green, 1 red; 14 green, 4 blue; 2 blue, 12 green Game 17: 1 red, 2 blue, 4 green; 4 blue, 3 green; 1 green, 1 red, 6 blue; 1 red, 7 blue; 2 green Game 18: 3 red, 3 blue, 7 green; 2 blue, 2 red, 2 green; 4 red, 12 green; 5 green, 2 blue, 4 red; 3 red Game 19: 15 red, 7 blue, 10 green; 5 green, 8 red; 9 green, 8 red; 5 red, 10 green Game 20: 15 blue, 6 green, 11 red; 13 red, 9 blue, 1 green; 15 blue, 10 red, 11 green Game 21: 15 red, 4 green; 11 red, 2 blue, 4 green; 5 blue, 2 green, 4 red; 4 red, 5 blue; 6 red, 3 blue, 1 green Game 22: 4 green, 4 red, 13 blue; 3 red, 7 blue, 9 green; 12 blue, 13 green, 5 red Game 23: 20 green, 4 red; 6 blue, 9 red, 7 green; 6 green Game 24: 1 green, 3 blue, 6 red; 1 green, 1 blue, 2 red; 3 blue, 5 red, 1 green Game 25: 2 red, 9 blue, 2 green; 2 green, 1 red, 5 blue; 3 red, 1 green, 3 blue; 8 blue, 2 green, 3 red; 12 blue, 3 red; 1 blue, 2 green, 1 red Game 26: 2 blue, 5 green, 20 red; 2 blue, 6 red, 9 green; 3 red, 2 blue, 5 green Game 27: 17 blue, 2 red, 14 green; 15 green, 16 blue, 2 red; 13 blue, 13 green; 1 red, 7 green, 3 blue; 1 blue, 2 green Game 28: 5 blue, 6 red, 3 green; 7 red, 19 green; 11 blue, 13 green Game 29: 1 blue, 8 red, 7 green; 1 green, 1 red; 8 red, 7 green, 1 blue; 7 green, 2 red; 1 blue, 7 red; 1 blue, 2 red, 5 green Game 30: 3 red, 17 blue; 11 red, 3 blue, 8 green; 7 green, 12 blue, 10 red; 5 blue, 2 green Game 31: 14 blue, 7 green; 12 green, 14 blue, 2 red; 17 blue, 2 red, 8 green; 2 red, 3 blue, 11 green; 9 green, 4 blue; 1 red, 3 green, 1 blue Game 32: 15 red, 1 blue, 10 green; 15 green, 10 red, 1 blue; 2 red, 6 green, 1 blue Game 33: 10 green, 1 red, 16 blue; 11 blue, 14 green, 3 red; 14 green, 13 blue; 17 blue, 2 red, 3 green Game 34: 8 red, 7 blue, 8 green; 3 green, 1 red; 1 red, 1 green, 5 blue; 6 red, 8 green, 2 blue; 7 red, 8 blue, 3 green Game 35: 5 blue, 19 red; 2 blue, 11 red, 1 green; 16 red, 10 blue; 7 green, 3 blue, 6 red; 3 green, 18 red, 5 blue; 8 blue, 5 red Game 36: 9 red, 6 green, 10 blue; 9 red, 15 green, 6 blue; 6 red, 1 blue, 14 green Game 37: 7 green, 8 red, 2 blue; 3 blue, 5 red, 16 green; 1 green, 1 red, 3 blue Game 38: 5 green, 5 red, 3 blue; 10 blue, 19 red, 9 green; 2 red, 3 blue, 11 green Game 39: 15 red, 11 blue, 5 green; 11 green, 2 red, 6 blue; 2 blue, 3 green, 6 red; 15 red, 3 blue, 13 green Game 40: 7 green, 4 red, 1 blue; 6 blue, 6 green, 2 red; 2 blue, 3 red, 1 green; 1 blue, 3 red, 3 green; 2 red, 5 green, 3 blue Game 41: 10 blue, 8 green, 9 red; 7 blue, 9 red, 2 green; 10 blue, 4 red, 5 green Game 42: 8 blue, 13 green, 14 red; 8 blue, 1 green, 11 red; 4 red, 6 green, 3 blue; 14 green, 4 red, 2 blue Game 43: 2 red, 10 green, 19 blue; 5 blue, 4 green, 9 red; 9 green, 9 red, 2 blue Game 44: 6 red, 2 green, 3 blue; 2 blue, 12 red, 6 green; 1 red, 10 blue; 12 red, 6 green, 2 blue; 14 red, 13 green, 3 blue; 10 green, 9 blue, 11 red Game 45: 2 blue, 1 red, 1 green; 1 green, 1 blue; 2 green, 2 blue Game 46: 7 green, 1 red; 1 green, 4 blue, 1 red; 3 blue, 4 green, 1 red; 1 red, 4 green; 1 blue, 12 green, 1 red; 16 green, 1 blue Game 47: 4 blue, 8 green, 3 red; 6 red, 1 green, 3 blue; 16 green, 4 blue, 1 red; 4 blue, 8 red Game 48: 1 blue, 9 red, 8 green; 8 green, 2 blue, 6 red; 2 green; 4 blue, 5 red; 1 blue, 9 red, 9 green; 1 red, 1 blue, 3 green Game 49: 3 green, 2 blue; 7 blue, 4 red; 20 green, 5 red, 13 blue; 20 green, 1 red, 6 blue Game 50: 3 red, 3 green; 3 green, 3 red; 2 blue, 10 red; 3 blue, 5 green; 14 red, 2 green, 2 blue; 7 red, 2 green Game 51: 3 green, 3 blue, 2 red; 4 green, 16 red, 3 blue; 1 blue, 3 red; 9 red, 1 blue, 4 green Game 52: 6 red, 18 green, 7 blue; 2 blue, 1 red, 5 green; 8 blue, 6 red, 1 green; 1 red, 1 blue; 6 red, 3 green, 10 blue Game 53: 1 blue, 10 red, 3 green; 13 red, 2 green, 1 blue; 1 green, 2 red Game 54: 4 blue, 6 green, 2 red; 5 blue, 6 red, 2 green; 6 blue, 4 green, 8 red; 13 red, 10 blue, 1 green; 5 red, 5 green, 9 blue Game 55: 4 green, 18 red, 4 blue; 9 blue, 7 green, 16 red; 5 red, 6 blue, 14 green; 13 green, 11 red, 9 blue; 6 blue, 13 green, 1 red; 10 blue, 12 red, 14 green Game 56: 8 green, 5 blue, 10 red; 10 green, 7 red, 12 blue; 11 red, 12 blue, 1 green; 4 blue, 6 red, 10 green; 17 blue, 8 green, 2 red Game 57: 1 green, 2 red; 2 green, 5 red, 1 blue; 13 red, 3 green, 4 blue; 3 blue, 13 red, 9 green Game 58: 1 red, 7 blue, 4 green; 2 green, 1 blue, 1 red; 1 green, 11 blue; 12 blue; 1 blue, 5 green, 1 red; 3 green, 11 blue, 1 red Game 59: 5 green, 3 blue, 17 red; 2 red, 9 green; 1 blue, 4 green Game 60: 5 red, 5 green, 1 blue; 2 red, 2 blue, 6 green; 2 red, 3 blue, 3 green Game 61: 2 green, 3 blue, 4 red; 17 green, 1 blue; 1 green, 6 red, 4 blue; 3 blue, 9 green, 3 red; 18 green, 7 red, 2 blue Game 62: 5 red; 3 blue, 9 green; 3 red, 13 blue, 10 green; 14 green, 1 red, 2 blue; 7 blue, 13 green Game 63: 12 blue, 5 green; 5 green, 1 red, 1 blue; 4 red, 7 green, 9 blue; 8 blue, 2 green, 7 red Game 64: 3 blue, 11 green; 5 blue, 2 red, 5 green; 17 green, 5 blue, 1 red; 4 red, 3 blue, 4 green Game 65: 2 red, 1 blue, 2 green; 7 green, 2 red, 1 blue; 2 blue, 7 green, 1 red; 3 blue, 8 green, 3 red Game 66: 4 red, 12 blue, 1 green; 20 blue, 3 green, 2 red; 11 blue, 1 green Game 67: 12 blue, 10 red, 13 green; 19 green, 4 red, 7 blue; 12 red, 9 blue, 13 green Game 68: 2 blue, 17 green; 12 green, 2 red; 5 red, 2 green, 4 blue; 4 blue Game 69: 17 blue, 3 red, 1 green; 4 green, 8 blue, 8 red; 4 green, 7 red, 1 blue; 8 red, 1 green, 11 blue; 13 blue, 10 red, 9 green; 14 blue, 5 green, 6 red Game 70: 1 red, 2 blue, 4 green; 13 blue, 3 red, 2 green; 6 green, 8 blue Game 71: 5 red, 7 green, 1 blue; 11 green, 4 red, 1 blue; 1 red, 12 green, 10 blue; 1 red, 7 blue, 12 green Game 72: 9 blue, 4 green, 1 red; 6 green, 4 blue; 8 green, 5 blue, 1 red Game 73: 1 blue, 10 green, 14 red; 4 green; 2 blue, 9 red, 4 green; 2 blue, 13 green; 13 green, 13 red; 7 red, 5 green, 2 blue Game 74: 3 red, 1 blue, 3 green; 4 green, 1 blue, 1 red; 2 blue, 10 green, 1 red; 1 blue, 3 red, 1 green Game 75: 1 red, 1 blue, 1 green; 2 red, 1 green, 4 blue; 2 red, 4 blue; 1 blue, 1 red Game 76: 4 green, 2 blue, 6 red; 7 green, 1 red; 8 green, 4 red Game 77: 8 green, 7 blue, 5 red; 6 red, 14 green, 7 blue; 8 green, 7 blue; 1 red, 8 green, 8 blue Game 78: 6 red, 3 blue, 3 green; 7 blue, 10 red; 5 green, 10 blue, 1 red; 3 green, 11 blue, 4 red; 14 red, 9 blue, 2 green; 16 red, 2 green, 12 blue Game 79: 1 green; 5 green; 11 green, 3 blue, 2 red; 3 blue Game 80: 2 green, 2 red; 1 blue, 1 green, 1 red; 1 blue, 1 green, 2 red; 2 red; 5 green Game 81: 10 blue, 2 red, 9 green; 4 red, 12 blue, 5 green; 7 green, 4 blue, 6 red; 1 red, 13 green, 14 blue; 13 green, 11 blue Game 82: 4 blue, 2 green; 7 blue, 3 green, 5 red; 1 red, 4 blue, 3 green; 5 blue, 1 red, 6 green; 6 green, 4 red; 11 blue, 3 red, 5 green Game 83: 12 green; 5 red, 8 green; 11 red, 14 green, 1 blue; 9 green, 4 red Game 84: 5 blue, 1 red; 16 blue, 5 green; 1 red, 9 blue, 3 green; 11 blue; 1 green, 2 blue; 1 red, 7 blue, 4 green Game 85: 17 red, 5 blue; 18 blue, 2 red, 2 green; 18 blue, 2 green, 8 red Game 86: 4 red, 1 blue, 11 green; 6 blue, 7 green, 1 red; 3 green, 4 blue; 2 red, 7 blue, 2 green Game 87: 4 red, 5 blue; 1 green, 15 red, 1 blue; 11 blue, 12 red Game 88: 11 green, 3 red, 1 blue; 6 green, 1 blue, 1 red; 1 blue, 3 green; 2 blue, 4 green, 2 red Game 89: 2 green; 1 red, 2 green, 3 blue; 4 blue, 1 red, 10 green; 4 blue, 5 green; 6 blue, 1 red, 10 green Game 90: 15 red, 7 green, 17 blue; 7 blue, 1 red; 7 green, 6 red, 3 blue Game 91: 2 blue, 17 red, 6 green; 1 green, 1 blue, 6 red; 6 red, 4 blue; 10 green, 14 red, 1 blue; 7 blue, 10 green, 10 red; 16 red, 11 green, 9 blue Game 92: 1 green, 8 blue, 4 red; 4 green, 4 red, 4 blue; 1 green, 7 red, 4 blue Game 93: 11 blue, 12 red, 1 green; 9 blue, 2 green, 5 red; 7 red, 5 blue, 2 green Game 94: 7 blue, 10 green; 9 green, 9 blue, 2 red; 1 red, 5 green, 4 blue Game 95: 1 green, 1 blue, 2 red; 6 red; 1 blue; 1 green, 1 blue, 6 red Game 96: 1 blue, 1 red, 2 green; 4 red, 13 green, 1 blue; 1 blue, 13 green, 5 red; 7 green, 4 red Game 97: 10 blue, 5 red, 5 green; 4 red, 8 green, 2 blue; 5 red, 2 green, 15 blue; 2 red, 1 green, 4 blue; 2 red, 14 blue; 14 blue, 4 green Game 98: 11 red, 8 green, 9 blue; 3 blue, 1 green, 14 red; 10 blue, 2 red, 4 green; 7 blue, 11 red, 3 green; 5 red, 12 blue, 4 green; 7 green, 7 blue, 8 red Game 99: 3 green, 2 blue, 1 red; 15 red, 8 blue, 7 green; 18 red, 12 blue, 2 green Game 100: 11 red, 1 blue, 2 green; 3 red, 3 green; 1 blue, 8 red, 4 green; 5 green, 5 blue, 1 red; 2 green, 1 red, 6 blue; 2 green, 8 red, 1 blue""" }
0
Kotlin
0
3
26ef6b194f3e22783cbbaf1489fc125d9aff9566
13,326
kotlinadventofcode
MIT License
src/main/kotlin/codes/jakob/aoc/solution/Day13.kt
The-Self-Taught-Software-Engineer
433,875,929
false
{"Kotlin": 56277}
package codes.jakob.aoc.solution import codes.jakob.aoc.shared.Coordinates import codes.jakob.aoc.shared.Grid object Day13 : Solution() { private val DEFAULT_CELL_VALUE: (Grid.Cell<Boolean>) -> Boolean = { false } override fun solvePart1(input: String): Any { val foldedGrid: Grid<Boolean> = foldOver(input, 1) return foldedGrid.cells.count { it.value } } override fun solvePart2(input: String): Any { val foldedGrid: Grid<Boolean> = foldOver(input) return "\n" + foldedGrid.toPrettyString() } private fun foldOver(input: String, foldFirstNOnly: Int? = null): Grid<Boolean> { val (coordinates: List<Coordinates>, instructions: List<FoldInstruction>) = parseInput(input) val coordinateValues: Map<Coordinates, (Grid.Cell<Boolean>) -> Boolean> = coordinates.associateWith { { true } } val grid: Grid<Boolean> = Grid(coordinateValues, DEFAULT_CELL_VALUE) return instructions .take(foldFirstNOnly ?: instructions.count()) .fold(grid) { acc: Grid<Boolean>, fi: FoldInstruction -> acc.foldOver(fi) } } private fun parseInput(input: String): Pair<List<Coordinates>, List<FoldInstruction>> { val (coordinateLines: String, instructionLines: String) = input.split("\n\n") val coordinates: List<Coordinates> = coordinateLines.splitMultiline().map { line: String -> val (x: String, y: String) = line.split(",") Coordinates(x.toInt(), y.toInt()) } val instructions: List<FoldInstruction> = instructionLines.splitMultiline().map { line: String -> val (axis: String, value: String) = line.split("fold along ").last().split("=") FoldInstruction(FoldInstruction.Axis.valueOf(axis.uppercase()), value.toInt()) } return coordinates to instructions } data class FoldInstruction( val axis: Axis, val value: Int, ) { val linesMerged: Set<Pair<Int, Int>> = linesMerged() private fun linesMerged(): Set<Pair<Int, Int>> { return (1..value).map { distance: Int -> (value - distance) to (value + distance) }.toSet() } enum class Axis { X, Y; } } @Suppress("UNUSED_ANONYMOUS_PARAMETER") private fun Grid<Boolean>.foldOver(instruction: FoldInstruction): Grid<Boolean> { val (matrix: List<List<Grid.Cell<Boolean>>>, coordinatesConstructor: (Int, Int) -> Coordinates) = when (instruction.axis) { FoldInstruction.Axis.X -> this.matrix to { x: Int, y: Int -> Coordinates(x, y) } FoldInstruction.Axis.Y -> this.matrix.transpose() to { x: Int, y: Int -> Coordinates(y, x) } } val coordinateValues: Map<Coordinates, (Grid.Cell<Boolean>) -> Boolean> = matrix .mapIndexed { y: Int, row: List<Grid.Cell<Boolean>> -> instruction.linesMerged.map { (xRetained: Int, xDiscarded: Int) -> val coordinates: Coordinates = coordinatesConstructor(xRetained, y) val value: Boolean = row.getOrNull(xRetained)?.value ?: false || row.getOrNull(xDiscarded)?.value ?: false return@map coordinates to value } } .flatten() .associate { (coordinates: Coordinates, value: Boolean) -> coordinates to { cell: Grid.Cell<Boolean> -> value } } return Grid(coordinateValues, DEFAULT_CELL_VALUE) } private fun Grid<Boolean>.toPrettyString(): String { return this.matrix.joinToString("\n") { row -> row.joinToString("") { cell -> if (cell.value) "█" else "░" } } } } fun main() { Day13.solve() }
0
Kotlin
0
6
d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c
3,821
advent-of-code-2021
MIT License
src/2022/Day03.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun Iterable<Char>.priority(): Int { return this.sumOf { if (it in 'a'..'z') it - 'a' + 1 else it - 'A' + 27 } } fun part1(input: List<String>): Int { return input.sumOf { val firstCompartment = it.substring(0, it.length / 2) val secondCompartment = it.substring(it.length / 2) val intersect = firstCompartment.asIterable().intersect(secondCompartment.toSet()) intersect.priority() } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { group -> val common = group.reduce { commonItems, elfItems -> val intersect = commonItems.asIterable().intersect(elfItems.toSet()) String(intersect.toCharArray()) } common.asIterable().priority() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
1,162
aoc-2022-in-kotlin
Apache License 2.0
Problem Solving/Algorithms/Basic - Plus Minus.kt
MechaArms
525,331,223
false
{"Kotlin": 30017}
/* Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with places after the decimal. Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable. Example arr = [1,1,0,-1,-1] There are n = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as: 0.400000 0.400000 0.200000 Function Description Complete the plusMinus function in the editor below. plusMinus has the following parameter(s): int arr[n]: an array of integers Print the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with digits after the decimal. The function should not return a value. Input Format The first line contains an integer, n, the size of the array. The second line contains space-separated integers that describe arr[n]. Output Format Print the following 3 lines, each to 6 decimals: 1.proportion of positive values 2.proportion of negative values 3.proportion of zeros Sample Input STDIN Function ----- -------- 6 arr[] size n = 6 -4 3 -9 0 4 1 arr = [-4, 3, -9, 0, 4, 1] Sample Output 0.500000 0.333333 0.166667 Explanation There are 3 positive numbers, 2 negative numbers, and 1 zero in the array. The proportions of occurrence are positive: 3/6 = 0.500000, negative: 2/6 = 0.333333 and zeros: 1/6 = 0.166667. */ //My Solution //=========== fun plusMinus(arr: Array<Int>): Unit { // answer var pos: Int = 0 var neg: Int = 0 var zero: Int = 0 for (num in arr){ if (num < 0){ pos ++ }else if (num > 0){ neg ++ }else{ zero ++ } } var negResult: Float = neg.toFloat() / arr.size // sum all positive / length array var posResult: Float = pos.toFloat() / arr.size // sum all negative / length array var zeroResult: Float = zero.toFloat() / arr.size // sum all zero / length array println(negResult) println(posResult) println(zeroResult) } fun main(args: Array<String>) { val n = readLine()!!.trim().toInt() val arr = readLine()!!.trimEnd().split(" ").map{ it.toInt() }.toTypedArray() plusMinus(arr) } //Clever Solution //=============== fun plusMinus(arr: Array<Int>): Unit { var positives: Int = 0 var negatives: Int = 0 var neutral: Int = 0 for(i in arr){ when {i > 0 -> positives ++ i < 0 -> negatives ++ i == 0 -> neutral ++} } println(positives.toDouble()/arr.size) println(negatives.toDouble()/arr.size) println(neutral.toDouble()/arr.size) } fun main(args: Array<String>) { val n = readLine()!!.trim().toInt() val arr = readLine()!!.trimEnd().split(" ").map{ it.toInt() }.toTypedArray() plusMinus(arr) }
0
Kotlin
0
1
eda7f92fca21518f6ee57413138a0dadf023f596
3,046
My-HackerRank-Solutions
MIT License
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day24/Day24.kt
jntakpe
433,584,164
false
{"Kotlin": 64657, "Rust": 51491}
package com.github.jntakpe.aoc2021.days.day24 import com.github.jntakpe.aoc2021.shared.Day import com.github.jntakpe.aoc2021.shared.readInputLines object Day24 : Day { override val input = readInputLines(24).chunked(18).map { Variables.from(it) } override fun part1() = solve(Part1) override fun part2() = solve(Part2) private fun solve(part: Part): Long { return buildMap { val stack = mutableListOf<Pair<Int, Int>>() var count = 0 input.forEach { if (it.div) stack.add(count to it.offset) else { val (previous, offset) = stack.removeLast() val diff = offset + it.check this[previous] = part.previous(diff) this[count] = part.count(diff) } count++ } }.toSortedMap().values.joinToString("").toLong() } data class Variables(val div: Boolean, val check: Int, val offset: Int) { companion object { fun from(chunk: List<String>): Variables { return chunk.filterIndexed { i, _ -> i in listOf(4, 5, 15) }.map { it.substringAfterLast(" ").toInt() } .let { (div, check, offset) -> Variables(div == 1, check, offset) } } } } interface Part { fun previous(diff: Int): Int fun count(diff: Int): Int } object Part1 : Part { override fun previous(diff: Int) = if (diff < 0) 9 else 9 - diff override fun count(diff: Int) = if (diff < 0) 9 + diff else 9 } object Part2 : Part { override fun previous(diff: Int) = if (diff < 0) 1 - diff else 1 override fun count(diff: Int) = if (diff < 0) 1 else 1 + diff } }
0
Kotlin
1
5
230b957cd18e44719fd581c7e380b5bcd46ea615
1,794
aoc2021
MIT License
leetcode/src/offer/middle/Offer56_1.kt
zhangweizhe
387,808,774
false
null
package offer.middle fun main() { // 剑指 Offer 56 - I. 数组中数字出现的次数 // https://leetcode.cn/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/ println(singleNumbers(intArrayOf(1,2,10,4,1,4,3,3)).contentToString()) } fun singleNumbers(nums: IntArray): IntArray { // [1,2,10,4,1,4,3,3],结果是2,10 // 设两个不同的数为 x y,遍历 nums,每次执行异或操作,最终结果 z 就是 x ^ y 的值 // 因为其他的数是有重复的,两个相同的数异或,结果是0,就抵消了 // 例子中,x=2(0010),y=10(1010),z = x^y = (1000) var z = 0 for (i in nums) { z = z.xor(i) } // 找到 z 低位的第一个1,x y 在这一位上的数肯定是不一样的,因为异或结果是1 // 初始化 m = 1,当 m&z == 0 时,将 m 左移一位,循环直到 m&z != 0 // 例子中,经过计算,m = (1000) var m = 1 while (m.and(z) == 0) { m = m.shl(1) } // 遍历数组,每个元素和 m 做与&运算,根据结果是否为0,可将数组分为两个自数组 // 子数组中,每个元素再和 m 异或,最终两个自数组的结果就是 x y var x = 0 var y = 0 for (i in nums) { if (i.and(m) == 0) { x = x.xor(i) }else { y = y.xor(i) } } return intArrayOf(x, y) } fun singleNumbers1(nums: IntArray): IntArray { // 整个数组的异或结果 var z = 0 for (i in nums) { z = z.xor(i) } // 计算异或结果中,最低位的1的位置 var n = 1 while(n.and(z) == 0) { n = n.shl(1) } var x = 0 var y = 0 for (i in nums) { if (i.and(n) == 0) { x = x.xor(i) }else { y = y.xor(i) } } return intArrayOf(x,y) }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,844
kotlin-study
MIT License
src/Day25.kt
StephenVinouze
572,377,941
false
{"Kotlin": 55719}
import kotlin.math.pow fun main() { fun String.fromSnafu(): Long = reversed() .mapIndexed { index, digit -> when (digit) { '=' -> -2 '-' -> -1 else -> digit.digitToInt() } * 5.0.pow(index) } .sumOf { it.toLong() } fun Long.toSnafu(): String { var power = 1L var remainder = this var snafu = "" while (remainder != 0L) { val snafuDigit = when (remainder % (5L * power)) { 0L -> '0' 1L * power -> '1'.also { remainder -= 1 * power } 2L * power -> '2'.also { remainder -= 2 * power } 3L * power -> '='.also { remainder += 2 * power } 4L * power -> '-'.also { remainder += 1 * power } else -> throw IllegalArgumentException() } power *= 5 snafu += snafuDigit } return snafu.reversed() } fun part1(input: List<String>): String = input .map { it.fromSnafu() } .sumOf { it } .toSnafu() fun part2(input: List<String>): Int { return 0 } check(part1(readInput("Day25_test")) == "2=-1=0") //check(part2(readInput("Day25_test")) == 20) val input = readInput("Day25") println(part1(input)) //println(part2(input)) }
0
Kotlin
0
0
11b9c8816ded366aed1a5282a0eb30af20fff0c5
1,437
AdventOfCode2022
Apache License 2.0
advent-of-code-2021/src/code/day9/Main.kt
Conor-Moran
288,265,415
false
{"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733}
package code.day9 import java.io.File fun main() { doIt("Day 9 Part 1: Test Input", "src/code/day9/test.input", part1) doIt("Day 9 Part 1: Real Input", "src/code/day9/part1.input", part1) doIt("Day 9 Part 2: Test Input", "src/code/day9/test.input", part2); doIt("Day 9 Part 2: Real Input", "src/code/day9/part1.input", part2); } fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Int) { val grid = arrayListOf<String>() File(input).forEachLine { grid.add(it) } println(String.format("%s: Ans: %d", msg , calc(grid))) } val part1: (List<String>) -> Int = { lines -> val inputs = parse(lines).grid val lowPts = mutableListOf<Int>() for(i in inputs.indices) { for(j in inputs[i].indices) { if (isLow(i, j, inputs)) { lowPts.add(inputs[i][j]) } } } lowPts.sum() + lowPts.size } val part2: (List<String>) -> Int = { lines -> val grid = parse(lines).grid val lowCoords = mutableListOf<Pair<Int,Int>>() val allBasinValues = mutableListOf<List<Int>>() for(i in grid.indices) { for(j in grid[i].indices) { if (isLow(i, j, grid)) { lowCoords.add(Pair(i, j)) } } } for (lowCoord in lowCoords) { val basinValues = mutableListOf<Int>() allBasinValues.add(basinValues) addBasin(lowCoord, grid, basinValues); } allBasinValues.sortByDescending { it.size } allBasinValues[0].size * allBasinValues[1].size * allBasinValues[2].size } fun addBasin(lowCoord: Pair<Int, Int>, grid: Array<IntArray>, basinValues: MutableList<Int>) { addBasin(lowCoord.first, lowCoord.second, grid, basinValues, mutableListOf<Pair<Int,Int>>()) } fun addBasin(i: Int, j: Int, grid: Array<IntArray>, basinValues: MutableList<Int>, visited: MutableList<Pair<Int,Int>>) { val coord = Pair(i, j) if (visited.contains(coord)) { return } else { basinValues.add(getValue(i, j, grid)) visited.add(coord) } if (upValue(i, j, grid) < 9) { addBasin(i - 1, j, grid, basinValues, visited); } if (downValue(i, j, grid) < 9) { addBasin(i + 1, j, grid, basinValues, visited); } if (leftValue(i, j, grid) < 9) { addBasin(i, j - 1, grid, basinValues, visited); } if (rightValue(i, j, grid) < 9) { addBasin(i, j + 1, grid, basinValues, visited); } } val parse: (List<String>) -> Input = { lines -> val parsed = Array(lines.size) { IntArray(lines[0].length) } for (i in lines.indices) { val nums = lines[i].toCharArray() for (j in nums.indices) { parsed[i][j] = nums[j].toString().toInt() } } Input(parsed) } fun isLow(i: Int, j: Int, grid: Array<IntArray>): Boolean { val item = grid[i][j] val up = upValue(i, j, grid) val down = downValue(i, j, grid) val left = leftValue(i, j, grid) val right = rightValue(i, j, grid) return item < up && item < down && item < left && item < right } fun upValue(i: Int, j: Int, grid: Array<IntArray>): Int { return getValue(i-1, j, grid) } fun downValue(i: Int, j: Int, grid: Array<IntArray>): Int { return getValue(i+1, j, grid) } fun leftValue(i: Int, j: Int, grid: Array<IntArray>): Int { return getValue(i, j-1, grid) } fun rightValue(i: Int, j: Int, grid: Array<IntArray>): Int { return getValue(i, j+1, grid) } fun getValue(i: Int, j: Int, grid: Array<IntArray>): Int { val dimI = grid.size val dimJ = grid[0].size var value = Int.MAX_VALUE if (i in 0 until dimI && j in 0 until dimJ) { value = grid[i][j] } return value } class Input(val grid: Array<IntArray>)
0
Kotlin
0
0
ec8bcc6257a171afb2ff3a732704b3e7768483be
3,750
misc-dev
MIT License
year2022/src/cz/veleto/aoc/year2022/Day15.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay import cz.veleto.aoc.core.Pos import cz.veleto.aoc.core.manhattanTo import kotlin.math.abs class Day15(config: Config) : AocDay(config) { private val inputLineRegex = Regex("""^.*x=(-?[0-9]+), y=(-?[0-9]+).+x=(-?[0-9]+), y=(-?[0-9]+).*$""") override fun part1(): String = parseSensors() .map { sensor -> val row = config.year2022day15part1row val (x, y) = sensor.pos val (bx, by) = sensor.closestBeacon val dToRow = abs(row - y) val halfIntersectSize = sensor.distance - dToRow (x - halfIntersectSize..x + halfIntersectSize).toSet() .let { if (by == row) it - bx else it } } .reduce { acc, longs -> acc.union(longs) } .count() .toString() override fun part2(): String { val max = config.year2022day15part2max val sensors = parseSensors().toList() return sensors .flatMap { sensor -> val (x, y) = sensor.pos sequence { val dJustOutOfRange = sensor.distance + 1 for (i in 0 until dJustOutOfRange) { yield(x + i to y - dJustOutOfRange + i) yield(x + dJustOutOfRange - i to y + i) yield(x - i to y + dJustOutOfRange - i) yield(x - dJustOutOfRange + i to y - i) } } } .filter { (x, y) -> x in 0..max && y in 0..max } .filter { pos -> sensors.all { sensor -> pos.manhattanTo(sensor.pos) > sensor.distance } } .toSet() .single() .let { (x, y) -> x * 4_000_000L + y } .toString() } private fun parseSensors(): Sequence<Sensor> = input .map { line -> val (sensorX, sensorY, beaconX, beaconY) = inputLineRegex.matchEntire(line)!! .groupValues.drop(1).map { it.toInt() } val sensorPos = sensorX to sensorY val beaconPos = beaconX to beaconY Sensor( pos = sensorPos, closestBeacon = beaconPos, distance = sensorPos.manhattanTo(beaconPos), ) } private data class Sensor( val pos: Pos, val closestBeacon: Pos, val distance: Int, ) }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
2,462
advent-of-pavel
Apache License 2.0
src/day03/Day03.kt
jpveilleux
573,221,738
false
{"Kotlin": 42252}
package day03 import readInput fun main () { val testInputFileName = "./day03/Day03_test" val controlInputFileName = "./day03/Day03_part2_control" val inputFileName = "./day03/Day03" val testInput = readInput(testInputFileName) val controlInput = readInput(controlInputFileName) val input = readInput(inputFileName) val alpha = arrayListOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); fun getCharValue(char: Char): Int { if (char.isUpperCase()) { return alpha.indexOf(char.lowercaseChar()) + (1 + alpha.size) } return alpha.indexOf(char) + 1 } fun part1(input: List<String>): Int { return input.sumOf { it -> val ruckSacks = it.chunked(it.length/2); val ruckSack1Items = ruckSacks[0].toCharArray(); val ruckSack2Items = ruckSacks[1].toCharArray(); val dupRuckItem = ruckSack1Items.find { currentRuckItem -> ruckSack2Items.contains(currentRuckItem) } getCharValue(dupRuckItem!!); } } fun part2(input: List<String>): Int { val by3Chunks = input.chunked(3); return by3Chunks.sumOf { ruckSackTrio -> val ruckSack1Items = ruckSackTrio[0].toCharArray(); val ruckSack2Items = ruckSackTrio[1].toCharArray(); val ruckSack3Items = ruckSackTrio[2].toCharArray(); val dupRuckItem = ruckSack1Items.findLast { currentRuckItem -> ruckSack2Items.contains(currentRuckItem) && ruckSack3Items.contains(currentRuckItem) } getCharValue(dupRuckItem!!); } } // Validation check(part1(testInput) == 157); check(part2(controlInput) == 70); // Debug println(part1(input)); println(part2(input)); }
0
Kotlin
0
0
5ece22f84f2373272b26d77f92c92cf9c9e5f4df
1,900
jpadventofcode2022
Apache License 2.0
src/Day03.kt
sungi55
574,867,031
false
{"Kotlin": 23985}
fun main() { val day = "Day03" fun part1(input: List<String>): Int = input.map { rucksack -> rucksack.chunked(rucksack.length / 2) } .sumOf { rucksack -> val compartment1 = rucksack.component1().toSet() val compartment2 = rucksack.component2().toSet() compartment1.intersect(compartment2) .first() .asNumber() } fun part2(input: List<String>): Int = input.chunked(3) .sumOf { (rucksacks1, rucksacks2, rucksacks3) -> rucksacks1.toSet() .intersect(rucksacks2.toSet()) .intersect(rucksacks3.toSet()) .single() .asNumber() } val testInput = readInput(name = "${day}_test") val input = readInput(name = day) check(part1(testInput) == 157) check(part2(testInput) == 70) println(part1(input)) println(part2(input)) } private fun Char.asNumber(): Int = when { isLowerCase() -> ('a'..'z').indexOf(this) else -> ('A'..'Z').indexOf(this).plus(26) }.plus(1)
0
Kotlin
0
0
2a9276b52ed42e0c80e85844c75c1e5e70b383ee
1,160
aoc-2022
Apache License 2.0
src/main/kotlin/Day009.kt
ruffCode
398,923,968
false
null
import PuzzleInput.toStingList object Day009 { private val target = 556543474L val testInput = """ 35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576 """.trimIndent().split(newLine).map { it.toLong() } val input = PuzzleInput("day009.txt").toStingList().map { it.trim().toLong() } @JvmStatic fun main(args: Array<String>) { println( measureTimedValueMinOf { partOne() } ) println( measureTimedValueMinOf { partOneNicer() } ) println( measureTimedValueMinOf { partTwo() } ) println( measureTimedValueMinOf { partTwoSmallerArray() } ) } internal fun partOne(): Long? = input.findInvalidNumber(25) private fun partOneNicer(): Long? = input.findInvalidNumberNicer(25) internal fun partTwo(): Long { val result = input.findSublist(target) return result.minMaxSum() } private fun partTwoSmallerArray(): Long { val idx = input.indexOfFirst { it >= target } val smaller = input.subList(0, idx) val result = smaller.findSublist(target) return result.minMaxSum() } internal fun List<Long>.findInvalidNumber(preambleSize: Int = 5): Long? { val nums = this var result: Long? = null for (i in preambleSize until nums.size - preambleSize) { val pre = nums.subList(i - preambleSize, i) val num = nums[i] if (num !in pre.allSums()) { result = num break } } return result } private fun List<Long>.allSums(): Set<Long> { return flatMap { this.filter { v -> v != it }.map { v -> v + it } }.toSet() } // all credit to <NAME> private fun List<Long>.hasPairOfSum(sum: Long): Boolean = indices.any { i -> indices.any { j -> i != j && this[i] + this[j] == sum } } // all credit to <NAME> internal fun List<Long>.findSublist(sum: Long) = (2..size).firstNotNullOf { sublistSize -> asSequence() .windowed(sublistSize) .firstOrNull { sublist -> sublist.sum() == sum } } // all credit to <NAME> internal fun List<Long>.findInvalidNumberNicer(preambleSize: Int = 5): Long? = ((preambleSize + 1)..lastIndex) .firstOrNull { index -> val previousGroup = subList(index - preambleSize, index) !previousGroup.hasPairOfSum(this[index]) } ?.let { this[it] } internal fun List<Long>.minMaxSum(): Long = this.minOf { it } + this.maxOf { it } }
0
Kotlin
0
0
477510cd67dac9653fc61d6b3cb294ac424d2244
3,078
advent-of-code-2020-kt
MIT License
src/year2020/day04/Day04.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2020.day04 import util.assertTrue import util.read2020DayInput fun main() { val input = formatInput(read2020DayInput("Day04")) assertTrue(task01(input) == 237) assertTrue(task02(input) == 172) } private fun task01(input: List<String>) = convertStringsToPassports(input) .map { it.lazyIsValid() } .count { it } private fun task02(input: List<String>) = convertStringsToPassports(input) .map { it.strictIsValid() } .count { it } private fun convertStringsToPassports(input: List<String>) = input.map { s -> Passport( findPropertyInString(s, "byr"), findPropertyInString(s, "iyr"), findPropertyInString(s, "eyr"), findPropertyInString(s, "hgt"), findPropertyInString(s, "hcl"), findPropertyInString(s, "ecl"), findPropertyInString(s, "pid"), findPropertyInString(s, "cid") ) } private fun formatInput(input: List<String>): MutableList<String> { val formattedInput = mutableListOf("") var index = 0 input.forEach { if (it == "") { index += 1 formattedInput.add("") } else formattedInput[index] += " $it" } return formattedInput } private fun findPropertyInString(string: String, property: String) = string .split(" ") .firstOrNull { it.contains("$property:") } ?.substringAfter(":") private data class Passport( val byr: String? = null, val iyr: String? = null, val eyr: String? = null, val hgt: String? = null, val hcl: String? = null, val ecl: String? = null, val pid: String? = null, val cid: String? = null ) { fun lazyIsValid() = !byr.isNullOrBlank() && !iyr.isNullOrBlank() && !eyr.isNullOrBlank() && !hgt.isNullOrBlank() && !hcl.isNullOrBlank() && !ecl.isNullOrBlank() && !pid.isNullOrBlank() fun strictIsValid() = lazyIsValid() && isValidYear(byr, 1920..2002) && isValidYear(iyr, 2010..2020) && isValidYear(eyr, 2020..2030) && isValidHeight(hgt) && isValidHairColor(hcl) && isValidEyeColor(ecl) && isValidPassportId(pid) private fun isValidYear(year: String?, range: IntRange): Boolean = (year?.length == 4 && year.toInt() in range) private fun isValidHeight(height: String?): Boolean { val h = height ?: "" val regex = "(\\d*)(\\W?)(cm|in)".toRegex() if (!regex.matches(h ?: "")) return false val matchResults = regex.find(h) ?: return false return when (matchResults.groupValues[3]) { "cm" -> matchResults.groupValues[1].toInt() in 150..193 "in" -> matchResults.groupValues[1].toInt() in 59..76 else -> false } } private fun isValidHairColor(color: String?) = "^#(\\d|[a-zA-Z]){6}\$".toRegex().matches(color ?: "") private fun isValidEyeColor(color: String?) = listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth").contains(color) private fun isValidPassportId(id: String?): Boolean = "^\\d{9}\$".toRegex().matches(id ?: "") }
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
3,147
advent-of-code-kotlin-template
Apache License 2.0
codeforces/vk2022/round1/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.vk2022.round1 const val M = 26 private fun solve() { readln() val s = readln().map { it - 'a' }.toIntArray() val count = IntArray(M) for (c in s) count[c]++ val byFreq = count.indices.sortedByDescending { count[it] } var answer = s.size + 1 var answerString = "" val a = IntArray(s.size) val aCount = IntArray(M) for (diff in 1..M) { if (s.size % diff != 0) continue val need = s.size / diff val use = byFreq.take(diff).toSet() a.fill(-1) aCount.fill(0) var current = s.size for (i in s.indices) { if (s[i] in use && aCount[s[i]] < need) { a[i] = s[i] aCount[s[i]]++ current-- } } if (current < answer) { answer = current var j = 0 for (i in s.indices) { if (a[i] != -1) continue while (j !in use || aCount[j] == need) j++ a[i] = j aCount[j]++ } answerString = a.joinToString("") { ('a'.code + it).toChar().toString() } } } println(answer) println(answerString) } fun main() = repeat(readInt()) { solve() } private fun readInt() = readln().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,053
competitions
The Unlicense
src/main/kotlin/co/csadev/advent2020/Day12.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/* * Copyright (c) 2021 by <NAME> */ package co.csadev.advent2020 import co.csadev.adventOfCode.Point2D import kotlin.math.abs class Day12(input: List<String>) { private val directions = input.map { it[0] to it.substring(1).toInt() } enum class Direction { East, North, West, South; fun turn(t: Char, amount: Int) = when (t) { 'L' -> values()[(this.ordinal + (amount / 90) + 4) % 4] else -> values()[(this.ordinal - (amount / 90) + 4) % 4] } } private data class Ship( var direction: Direction = Direction.East, var point: Point2D = Point2D(0, 0), var waypoint: Point2D = Point2D(10, 1) ) { fun move(dir: Char, amount: Int) { point = when (dir) { 'E' -> point.move(Direction.East, amount) 'N' -> point.move(Direction.North, amount) 'W' -> point.move(Direction.West, amount) 'S' -> point.move(Direction.South, amount) 'F' -> point.move(direction, amount) else -> { direction = direction.turn(dir, amount) point } } } fun moveByWaypoint(dir: Char, amount: Int) { when (dir) { 'E' -> waypoint = waypoint.move(Direction.East, amount) 'N' -> waypoint = waypoint.move(Direction.North, amount) 'W' -> waypoint = waypoint.move(Direction.West, amount) 'S' -> waypoint = waypoint.move(Direction.South, amount) 'F' -> point += waypoint.times(amount) else -> { repeat(amount / 90) { waypoint = when (dir) { 'L' -> waypoint.rotateLeft() else -> waypoint.rotateRight() } } } } } } fun solvePart1(): Int { val s = Ship() directions.forEach { (d, a) -> s.move(d, a) } return abs(s.point.x) + abs(s.point.y) } fun solvePart2(): Int { val s = Ship() directions.forEach { (d, a) -> s.moveByWaypoint(d, a) } return abs(s.point.x) + abs(s.point.y) } } private fun Point2D.move(dir: Day12.Direction, amt: Int) = when (dir) { Day12.Direction.East -> copy(x = x + amt) Day12.Direction.North -> copy(y = y + amt) Day12.Direction.West -> copy(x = x - amt) else -> copy(y = y - amt) }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,608
advent-of-kotlin
Apache License 2.0
src/day02/Day02.kt
spyroid
433,555,350
false
null
package day02 import readInput fun main() { data class Command(val op: String, val value: Int) fun part1(seq: Sequence<Command>): Int { var depth = 0 var horizontal = 0 seq.forEach { when (it.op) { "forward" -> horizontal += it.value "down" -> depth += it.value "up" -> depth -= it.value } } return depth * horizontal } fun part2(seq: Sequence<Command>): Int { var depth = 0 var horizontal = 0 var aim = 0 seq.forEach { when (it.op) { "forward" -> { horizontal += it.value depth += it.value * aim } "down" -> aim += it.value "up" -> aim -= it.value } } return depth * horizontal } val testSeq = readInput("day02/test").asSequence().map { it.split(" ") }.map { Command(it[0], it[1].toInt()) } val seq = readInput("day02/input").asSequence().map { it.split(" ") }.map { Command(it[0], it[1].toInt()) } val res1 = part1(testSeq) check(res1 == 150) { "Expected 150 but got $res1" } println("Part1: " + part1(seq)) val res2 = part2(testSeq) check(res2 == 900) { "Expected 900 but got $res2" } println("Part2: " + part2(seq)) }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
1,370
Advent-of-Code-2021
Apache License 2.0
src/day14/fr/Day14_1.kt
BrunoKrantzy
433,844,189
false
{"Kotlin": 63580}
package day14.fr import java.io.File private fun readChars(): CharArray = readLn().toCharArray() private fun readLn() = readLine()!! // string line private fun readSb() = StringBuilder(readLn()) private fun readInt() = readLn().toInt() // single int private fun readLong() = readLn().toLong() // single long private fun readDouble() = readLn().toDouble() // single double private fun readStrings() = readLn().split(" ") // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of ints private fun readLongs() = readStrings().map { it.toLong() } // list of longs private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles private fun readIntArray() = readStrings().map { it.toInt() }.toIntArray() // Array of ints private fun readLongArray() = readStrings().map { it.toLong() }.toLongArray() // Array of longs fun readInput(name: String) = File("src", "$name.txt").readLines() fun main() { var rep = 0L val vTemplate = day11.fr.readInput("test14a") val vRules = day11.fr.readInput("test14b") //val vTemplate = day11.fr.readInput("input14a") //val vRules = day11.fr.readInput("input14b") var sTemplate = StringBuilder() sTemplate.append(vTemplate[0]) var regex = "^([A-Z]{2})\\s->\\s([A-Z])".toRegex() var mapRules = mutableMapOf<String, String>() vRules.forEach { val match = regex.find(it) val rDuo = match!!.groups[1]!!.value val rIns = match.groups[2]!!.value mapRules[rDuo] = rIns } var nbSteps = 10 for (i in 1..nbSteps) { var strT = sTemplate.toString() sTemplate.clear() var l1 = "" var l2 = "" for (let in 0 until strT.length - 1) { l1 = strT[let].toString() l2 = strT[let+1].toString() var duo:String = l1 + l2 var cIn = mapRules[duo] if (cIn != null) { sTemplate.append("$l1$cIn") } } sTemplate.append(l2) } var strFini = sTemplate.toString() var lgStr = strFini.length val frequencies = strFini.groupingBy { it }.eachCount() var vMax = Long.MIN_VALUE var vMin = Long.MAX_VALUE frequencies.forEach { var v = it.value.toLong() vMax = maxOf(vMax, v) vMin = minOf(vMin, v) } rep = vMax - vMin println(rep) }
0
Kotlin
0
0
0d460afc81fddb9875e6634ee08165e63c76cf3a
2,378
Advent-of-Code-2021
Apache License 2.0
src/day23/Day23.kt
gr4cza
572,863,297
false
{"Kotlin": 93944}
package day23 import Direction import Edges import Position import readInput import set import kotlin.math.abs fun main() { fun parse(input: List<String>): ElfMap { return ElfMap( elfs = input.mapIndexed { y, row -> row.mapIndexedNotNull { x, cell -> if (cell == '#') { Elf(Position(x, y)) } else { null } } }.flatten() ) } fun getProposedMoves( elfMap: ElfMap, currentPositions: List<Position>, dirs: ArrayDeque<Direction>, ) = elfMap.elfs.map { elf -> if (elf.countNeighbours(currentPositions) != 0) { dirs.forEach { dir -> when (dir) { Direction.U -> { if (listOf( elf.currentPos.newPosition(Direction.U) in currentPositions, elf.currentPos.newPosition(Direction.U) .newPosition(Direction.R) in currentPositions, elf.currentPos.newPosition(Direction.U) .newPosition(Direction.L) in currentPositions, ).none { it } ) { return@map elf to elf.currentPos.newPosition(Direction.U) } } Direction.D -> { if (listOf( elf.currentPos.newPosition(Direction.D) in currentPositions, elf.currentPos.newPosition(Direction.D) .newPosition(Direction.R) in currentPositions, elf.currentPos.newPosition(Direction.D) .newPosition(Direction.L) in currentPositions, ).none { it } ) { return@map elf to elf.currentPos.newPosition(Direction.D) } } Direction.L -> { if (listOf( elf.currentPos.newPosition(Direction.L) in currentPositions, elf.currentPos.newPosition(Direction.L) .newPosition(Direction.U) in currentPositions, elf.currentPos.newPosition(Direction.L) .newPosition(Direction.D) in currentPositions, ).none { it } ) { return@map elf to elf.currentPos.newPosition(Direction.L) } } Direction.R -> { if (listOf( elf.currentPos.newPosition(Direction.R) in currentPositions, elf.currentPos.newPosition(Direction.R) .newPosition(Direction.U) in currentPositions, elf.currentPos.newPosition(Direction.R) .newPosition(Direction.D) in currentPositions, ).none { it } ) { return@map elf to elf.currentPos.newPosition(Direction.R) } } } } return@map elf to elf.currentPos } else { return@map elf to elf.currentPos } } fun simulate(elfMap: ElfMap, times: Int, directions: ArrayDeque<Direction>) { repeat(times) { val currentPositions = elfMap.elfs.map { it.currentPos } val proposedMoves: List<Pair<Elf, Position>> = getProposedMoves(elfMap, currentPositions, directions) proposedMoves.forEach { (elf, newPos) -> if (proposedMoves.count { it.second == newPos } == 1) { elf.currentPos = newPos } } directions.removeFirst().also { directions.addLast(it) } } } fun part1(input: List<String>): Int { val elfMap = parse(input) val times = 10 val directions = ArrayDeque(listOf(Direction.U, Direction.D, Direction.L, Direction.R)) simulate(elfMap, times, directions) return elfMap.convertToMap().flatten().count { !it } } fun part2(input: List<String>): Int { val elfMap = parse(input) var previousMap = elfMap.hashCode() var i = 0 val directions = ArrayDeque(listOf(Direction.U, Direction.D, Direction.L, Direction.R)) while (true) { simulate(elfMap, 1, directions) if (previousMap == elfMap.hashCode()) { return i+1 } else { i++ previousMap = elfMap.hashCode() } } } // test if implementation meets criteria from the description, like: val testInput = readInput("day23/Day23_test") val input = readInput("day23/Day23") check((part1(testInput)).also { println(it) } == 110) println(part1(input)) check(part2(testInput).also { println(it) } == 20) println(part2(input)) } data class ElfMap( val elfs: List<Elf>, ) { fun convertToMap(): List<List<Boolean>> { val (startPos, endPos) = findEdges() val elfMap = List(abs(startPos.y - endPos.y) + 1) { MutableList(abs(startPos.x - endPos.x) + 1) { false } } elfs.forEach { elfMap[it.currentPos.copy(x = it.currentPos.x - startPos.x, y = it.currentPos.y - startPos.y)] = true } return elfMap } private fun findEdges(): Edges { val xValues = elfs.map { it.currentPos.x } val yValues = elfs.map { it.currentPos.y } return Edges( Position(xValues.min(), minOf(yValues.min(), 0)), Position(xValues.max(), yValues.max()), ) } override fun toString(): String { return buildString { append(findEdges().toString()) append("\n") append(convertToMap().joinToString("\n") { line -> line.joinToString("") { when (it) { false -> "." true -> "#" } } }) } } } data class Elf( var currentPos: Position, ) { fun countNeighbours(currentPositions: List<Position>): Int { return listOf( currentPos.newPosition(Direction.U) in currentPositions, currentPos.newPosition(Direction.R) in currentPositions, currentPos.newPosition(Direction.D) in currentPositions, currentPos.newPosition(Direction.L) in currentPositions, currentPos.newPosition(Direction.U).newPosition(Direction.R) in currentPositions, currentPos.newPosition(Direction.R).newPosition(Direction.D) in currentPositions, currentPos.newPosition(Direction.D).newPosition(Direction.L) in currentPositions, currentPos.newPosition(Direction.L).newPosition(Direction.U) in currentPositions, ).count { it } } }
0
Kotlin
0
0
ceca4b99e562b4d8d3179c0a4b3856800fc6fe27
7,357
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/summarisation/SummariseSentenceScore.kt
rock3125
138,799,834
false
{"Kotlin": 30711, "Java": 939, "Shell": 774}
package summarisation import summarisation.parser.Sentence import java.util.ArrayList /** * sentence sorting by both index and scoring after algorithm completes * */ class SummariseSentenceScore(var sentence: Sentence // the sentence held , var sentenceIndex: Int // original index of the sentence in the story , var score: Float // the summary score of this item ) : Comparable<SummariseSentenceScore> { private var sortKey: Int = 0 // sorting: 1 = by score (default), 2 = sentenceIndex init { this.sortKey = 1 } // sort highest scores first override fun compareTo(other: SummariseSentenceScore): Int { if (sortKey == 1) { if (score < other.score) return 1 if (score > other.score) return -1 } else { if (sentenceIndex < other.sentenceIndex) return -1 if (sentenceIndex > other.sentenceIndex) return 1 } return 0 } companion object { /** * generate the sorted summary * * @param sentenceList the sentences * @param scoreList the scores of these sentences * @param topN the top n items to return * @param sortBySentenceAfterTopN resort by story order after topN have been cut-off * @return the top n items */ fun getTopN(sentenceList: ArrayList<Sentence>, scoreList: ArrayList<Float>, topN: Int, sortBySentenceAfterTopN: Boolean): ArrayList<Sentence> { val results = ArrayList<SummariseSentenceScore>() for (i in sentenceList.indices) { results.add(SummariseSentenceScore(sentenceList[i], i, scoreList[i])) } results.sort() val summary = ArrayList<SummariseSentenceScore>() for (i in 0 until topN) { if (i < results.size) { val sss = results[i] sss.sortKey = 2 // change sort-key just in case we need resorting summary.add(sss) } } if (sortBySentenceAfterTopN) { summary.sort() } val sentenceSummary = ArrayList<Sentence>() for (sss in summary) { sentenceSummary.add(sss.sentence) } return sentenceSummary } } }
0
Kotlin
0
4
24d8916dbecde35eaeb760eb4307ca32a4ecb768
2,432
ExtractiveSummarisation
MIT License
src/day04/Day04.kt
martindacos
572,700,466
false
{"Kotlin": 12412}
package day04 import readInput fun main() { fun part1(input: List<String>): Int { var fullyContained = 0 for (line in input) { val numbers = line.split(",") // [2, 4] val initialAndFinalNumber = numbers[0].split("-").map { number -> number.toInt() } // [2,3,4] val listA: MutableList<Int> = mutableListOf() for (i in initialAndFinalNumber[0]..initialAndFinalNumber[initialAndFinalNumber.size - 1]) { listA.add(i) } // [6, 8] val initialAndFinalNumber2 = numbers[1].split("-").map { number -> number.toInt() } // [6,7,8] val listB: MutableList<Int> = mutableListOf() for (i in initialAndFinalNumber2[0]..initialAndFinalNumber2[initialAndFinalNumber2.size - 1]) { listB.add(i) } val intersect = listA.intersect(listB) if (intersect.size == listA.size || intersect.size == listB.size) fullyContained++ } return fullyContained } fun part2(input: List<String>): Int { var fullyContained = 0 for (line in input) { val numbers = line.split(",") // [2, 4] val initialAndFinalNumber = numbers[0].split("-").map { number -> number.toInt() } // [2,3,4] val listA: MutableList<Int> = mutableListOf() for (i in initialAndFinalNumber[0]..initialAndFinalNumber[initialAndFinalNumber.size - 1]) { listA.add(i) } // [6, 8] val initialAndFinalNumber2 = numbers[1].split("-").map { number -> number.toInt() } // [6,7,8] val listB: MutableList<Int> = mutableListOf() for (i in initialAndFinalNumber2[0]..initialAndFinalNumber2[initialAndFinalNumber2.size - 1]) { listB.add(i) } val intersect = listA.intersect(listB) if (intersect.size > 0) fullyContained++ } return fullyContained } // test if implementation meets criteria from the description, like: val testInput = readInput("/day04/Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("/day04/Day04") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f288750fccf5fbc41e8ac03598aab6a2b2f6d58a
2,367
2022-advent-of-code-kotlin
Apache License 2.0
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day14.kt
justinhorton
573,614,839
false
{"Kotlin": 39759, "Shell": 611}
package xyz.justinhorton.aoc2022 /** * https://adventofcode.com/2022/day/14 */ class Day14(override val input: String) : Day() { override fun part1(): String { val blockedPoints = initBlockedPoints() return dropSand(1, blockedPoints, blockedPoints.maxOf { it.y }).toString() } override fun part2(): String { val blockedPoints = initBlockedPoints() return dropSand(2, blockedPoints, blockedPoints.maxOf { it.y }).toString() } private fun initBlockedPoints(): MutableSet<GPoint> { return input.trim() .lineSequence() .flatMap { line -> line.split(" -> ") .map { it.split(",").let { csv -> GPoint(csv[0].toInt(), csv[1].toInt()) } } .zipWithNext() } .flatMap { sequenceOf(it.first, it.second) + pointsOnLine(it.first, it.second) } .toMutableSet() } private fun dropSand(part: Int, blockedPoints: MutableSet<GPoint>, maxRockY: Int): Int { var sandCount = 0 var sandLoc = sandStart val continueDropping = { if (part == 1) { sandLoc.y < maxRockY } else { sandStart !in blockedPoints } } while (continueDropping()) { val candidates = listOf( sandLoc.copy(y = sandLoc.y + 1), GPoint(sandLoc.x - 1, sandLoc.y + 1), GPoint(sandLoc.x + 1, sandLoc.y + 1) ) val firstOpen = if (part == 1) { candidates } else { candidates.filter { it.y <= maxRockY + 1 } }.firstOrNull { it !in blockedPoints } sandLoc = if (firstOpen == null) { blockedPoints.add(sandLoc) sandCount++ sandStart } else { firstOpen } } return sandCount } private fun pointsOnLine(p1: GPoint, p2: GPoint): Sequence<GPoint> { return sequence { if (p1.x == p2.x) { val (lowy, highy) = if (p1.y < p2.y) { p1.y to p2.y } else { p2.y to p1.y } for (y in (lowy + 1) until highy) { yield(GPoint(p1.x, y)) } } else { val (lowx, highx) = if (p1.x < p2.x) { p1.x to p2.x } else { p2.x to p1.x } for (x in (lowx + 1) until highx) { yield(GPoint(x, p1.y)) } } } } } private val sandStart = GPoint(500, 0)
0
Kotlin
0
1
bf5dd4b7df78d7357291c7ed8b90d1721de89e59
2,750
adventofcode2022
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumProductSubArray.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max import kotlin.math.min /** * Maximum Product Subarray * @see <a href="https://leetcode.com/problems/maximum-product-subarray/">Source</a> */ fun interface MaximumProductSubArray { fun maxProduct(nums: IntArray): Int } class MaxProductBruteForce : MaximumProductSubArray { override fun maxProduct(nums: IntArray): Int { if (nums.isEmpty()) return 0 var result = nums.first() for (i in nums.indices) { var accu = 1 for (j in i until nums.size) { accu *= nums[j] result = max(result, accu) } } return result } } class MaxProductDP : MaximumProductSubArray { override fun maxProduct(nums: IntArray): Int { if (nums.isEmpty()) return 0 var maxSoFar = nums.first() var minSoFar = nums.first() var result = maxSoFar for (i in 1 until nums.size) { val curr = nums[i] val tempMax = max(curr, max(maxSoFar * curr, minSoFar * curr)) minSoFar = min(curr, min(maxSoFar * curr, minSoFar * curr)) maxSoFar = tempMax result = max(maxSoFar, result) } return result } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,869
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DistanceLimitedPathsExist.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.Arrays /** * 1697. Checking Existence of Edge Length Limited Paths * @see <a href="https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/">Source</a> */ fun interface DistanceLimitedPathsExist { operator fun invoke(n: Int, edgeList: Array<IntArray>, queries: Array<IntArray>): BooleanArray } class DisjointSetUnion : DistanceLimitedPathsExist { override operator fun invoke(n: Int, edgeList: Array<IntArray>, queries: Array<IntArray>): BooleanArray { val uf = UnionFind(n) val queriesCount = queries.size val answer = BooleanArray(queriesCount) // Store original indices with all queries. val queriesWithIndex = Array(queriesCount) { IntArray(4) } for (i in 0 until queriesCount) { queriesWithIndex[i][0] = queries[i][0] queriesWithIndex[i][1] = queries[i][1] queriesWithIndex[i][2] = queries[i][2] queriesWithIndex[i][3] = i } // Sort all edges in increasing order of their edge weights. sort(edgeList) // Sort all queries in increasing order of the limit of edge allowed. sort(queriesWithIndex) var edgesIndex = 0 // Iterate on each query one by one. var queryIndex = 0 while (queryIndex < queriesCount) { val p = queriesWithIndex[queryIndex][0] val q = queriesWithIndex[queryIndex][1] val limit = queriesWithIndex[queryIndex][2] val queryOriginalIndex = queriesWithIndex[queryIndex][3] // We can attach all edges which satisfy the limit given by the query. while (edgesIndex < edgeList.size && edgeList[edgesIndex][2] < limit) { val node1 = edgeList[edgesIndex][0] val node2 = edgeList[edgesIndex][1] uf.join(node1, node2) edgesIndex += 1 } // If both nodes belong to the same component, it means we can reach them. answer[queryOriginalIndex] = uf.areConnected(p, q) queryIndex += 1 } return answer } // Sort in increasing order based on the 3rd element of the array. private fun sort(array: Array<IntArray>) { Arrays.sort(array) { a, b -> a[2] - b[2] } } class UnionFind(size: Int) { private val group: IntArray = IntArray(size) private val rank: IntArray = IntArray(size) init { for (i in 0 until size) { group[i] = i } } fun find(node: Int): Int { if (group[node] != node) { group[node] = find(group[node]) } return group[node] } fun join(node1: Int, node2: Int) { val group1 = find(node1) val group2 = find(node2) // node1 and node2 already belong to same group. if (group1 == group2) { return } if (rank[group1] > rank[group2]) { group[group2] = group1 } else if (rank[group1] < rank[group2]) { group[group1] = group2 } else { group[group1] = group2 rank[group2] += 1 } } fun areConnected(node1: Int, node2: Int): Boolean { val group1 = find(node1) val group2 = find(node2) return group1 == group2 } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,136
kotlab
Apache License 2.0
neetcode/src/main/java/org/twopointers/TwoPointers.kt
gouthamhusky
682,822,938
false
{"Kotlin": 24242, "Java": 24233}
import kotlin.math.max import kotlin.math.min fun main() { trap(intArrayOf(0,1,0,2,1,0,1,3,2,1,2,1)) } fun isPalindrome(s: String): Boolean { val stringBuilder = StringBuilder() for (c in s){ if (!c.isLetterOrDigit()) continue else if (c.isUpperCase()) stringBuilder.append(c.lowercaseChar()) else stringBuilder.append(c) } var start = 0 var end = stringBuilder.length - 1 while (start < end){ if (stringBuilder[start] != stringBuilder[end]) return false start++ end-- } return true } fun twoSum(numbers: IntArray, target: Int): IntArray { var start = 0 var end = numbers.size - 1 while ( start < end){ val currentElement = numbers[start] + numbers[end] if (currentElement == target) return intArrayOf(start + 1 , end + 1) else if (currentElement > target) end-- else start++ } return intArrayOf() } fun threeSum(nums: IntArray): List<List<Int>> { nums.sort() val ans = mutableListOf<List<Int>>() for (i in nums.indices){ val current = nums[i] if (i > 0 && current == nums[i-1]) continue var l = i +1 var r = nums.size - 1 while (l < r){ when{ nums[i] + nums[l] + nums[r] == 0 -> { ans.add(mutableListOf(i, l, r)) l++ while (nums[l] == nums[l+1] && l < r) l++ } nums[i] + nums[l] + nums[r] < 0 -> { l++ } else -> r-- } } } return ans } fun maxArea(height: IntArray): Int { var max = Int.MIN_VALUE var l = 0 var r = height.size - 1 while (l < r){ val area = minOf(height[l], height[r]) * (r - l) max = maxOf(max, area) if (height[l] < height[r]) l++ else r-- } return max } fun trap(height: IntArray): Int { val maxLeft = IntArray(height.size) val maxRight = IntArray(height.size) val ans = IntArray(height.size) for (i in height.indices){ if (i == 0) maxLeft[i] = 0 else maxLeft[i] = maxOf(maxLeft[i-1], height[i-1]) } for (i in height.size -1 downTo 0){ if (i == height.size-1) maxRight[i] = 0 else maxRight[i] = maxOf(maxRight[i+1], height[i+1]) } for (i in height.indices){ val storage = minOf(maxRight[i], maxLeft[i]) - height[i] if (storage > 0) ans[i] = storage } return ans.sum() } fun maxProfit(prices: IntArray): Int { var left = 0 var right = 1 var max = Int.MIN_VALUE while (left < prices.size - 1){ if (prices[right] - prices[right] <= 0){ left = right right++ } else { val sp = prices[right] - prices[left] max = maxOf(max, sp) right++ } } return max }
0
Kotlin
0
0
a0e158c8f9df8b2e1f84660d5b0721af97593920
3,057
leetcode-journey
MIT License
2015/Day06/src/main/kotlin/Main.kt
mcrispim
658,165,735
false
null
import java.io.File enum class Command { ON, OFF, TOGGLE } data class Rectangle(val x1: Int, val y1: Int, val x2: Int, val y2: Int) fun main() { fun readCommand(line: String): Pair<Command, Rectangle> { /* Command examples turn on 0,0 through 999,999 toggle 0,0 through 999,0 turn off 499,499 through 500,500 */ val parts = line.split(" ") val command = if (parts[1] == "on") Command.ON else if (parts[1] == "off") Command.OFF else Command.TOGGLE var numbersIndex = if (command == Command.TOGGLE) 1 else 2 val (x1, y1) = parts[numbersIndex].split(",").map { it.toInt() } val (x2, y2) = parts[numbersIndex + 2].split(",").map { it.toInt() } return Pair(command, Rectangle(x1, y1, x2, y2)) } fun part1(input: List<String>): Int { class Grid { val cells = Array(1000) { IntArray(1000) { 0 } } var lightsOn = 0 fun processComando(command: Command, rectangle: Rectangle) { for (x in rectangle.x1..rectangle.x2) { for (y in rectangle.y1..rectangle.y2) { when (command) { Command.ON -> if (cells[x][y] == 0) { cells[x][y] = 1 lightsOn++ } Command.OFF -> if (cells[x][y] == 1) { cells[x][y] = 0 lightsOn-- } Command.TOGGLE -> { if (cells[x][y] == 1) { cells[x][y] = 0 lightsOn-- } else { cells[x][y] = 1 lightsOn++ } } } } } } } val grid = Grid() input.forEach { val (command, rectangle) = readCommand(it) // println("Lights on: ${grid.lightsOn}") // println("$command, $rectangle") grid.processComando(command, rectangle) } // println("Lights on: ${grid.lightsOn}") return grid.lightsOn } fun part2(input: List<String>): Int { class Grid { val cells = Array(1000) { IntArray(1000) { 0 } } var totalBrightness = 0 fun processComando(command: Command, rectangle: Rectangle) { for (x in rectangle.x1..rectangle.x2) { for (y in rectangle.y1..rectangle.y2) { when (command) { Command.ON -> { cells[x][y] = cells[x][y] + 1 totalBrightness++ } Command.OFF -> if (cells[x][y] > 0) { cells[x][y] = cells[x][y] - 1 totalBrightness-- } Command.TOGGLE -> { cells[x][y] = cells[x][y] + 2 totalBrightness += 2 } } } } } } val grid = Grid() input.forEach { val (command, rectangle) = readCommand(it) // println("Lights on: ${grid.lightsOn}") // println("$command, $rectangle") grid.processComando(command, rectangle) } // println("Lights on: ${grid.lightsOn}") return grid.totalBrightness } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 998_996) check(part2(testInput) == 1_000_000 + 2_000 - 4) val input = readInput("Day06_data") println("Part 1 answer: ${part1(input)}") println("Part 2 answer: ${part2(input)}") } /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines()
0
Kotlin
0
0
2f4be35e78a8a56fd1e078858f4965886dfcd7fd
4,309
AdventOfCode
MIT License
src/main/kotlin/days/Day05.kt
julia-kim
435,257,054
false
{"Kotlin": 15771}
package days import readInput fun main() { fun mapCoordinates(x1: Int, y1: Int, map: MutableMap<Pair<Int, Int>, Int>) { if (map[x1 to y1] == null) { map[x1 to y1] = 1 } else map[x1 to y1] = map.getValue(x1 to y1) + 1 } fun part1(input: List<String>): Int { val map: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() input.forEach { it -> val (x1y1, x2y2) = it.split(" -> ") var (x1, y1) = x1y1.split(",").map { it.toInt() } val (x2, y2) = x2y2.split(",").map { it.toInt() } if (x1 != x2 && y1 != y2) return@forEach if (x1 < x2) { while (x1 <= x2) { mapCoordinates(x1, y1, map) x1++ } } else if (y1 < y2) { while (y1 <= y2) { mapCoordinates(x1, y1, map) y1++ } } else if (x1 > x2) { while (x1 >= x2) { mapCoordinates(x1, y1, map) x1-- } } else if (y1 > y2) { while (y1 >= y2) { mapCoordinates(x1, y1, map) y1-- } } } val filteredMap = map.filterValues { it >= 2 } return filteredMap.size } fun part2(input: List<String>): Int { var map: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() input.forEach { it -> val (x1y1, x2y2) = it.split(" -> ") var (x1, y1) = x1y1.split(",").map { it.toInt() } val (x2, y2) = x2y2.split(",").map { it.toInt() } if (x1 < x2 && y1 == y2) { while (x1 <= x2) { mapCoordinates(x1, y1, map) x1++ } } else if (y1 < y2 && x1 == x2) { while (y1 <= y2) { mapCoordinates(x1, y1, map) y1++ } } else if (x1 > x2 && y1 == y2) { while (x1 >= x2) { mapCoordinates(x1, y1, map) x1-- } } else if (y1 > y2 && x1 == x2) { while (y1 >= y2) { mapCoordinates(x1, y1, map) y1-- } } else if (y1 > y2 && x1 > x2) { while (y1 >= y2 && x1 >= x2) { mapCoordinates(x1, y1, map) y1-- x1-- } } else if (y1 > y2 && x1 < x2) { while (y1 >= y2 && x1 <= x2) { mapCoordinates(x1, y1, map) y1-- x1++ } } else if (y1 < y2 && x1 < x2) { while (y1 <= y2 && x1 <= x2) { mapCoordinates(x1, y1, map) y1++ x1++ } } else if (y1 < y2 && x1 > x2) { while (y1 <= y2 && x1 >= x2) { mapCoordinates(x1, y1, map) y1++ x1-- } } } val filteredMap = map.filterValues { it >= 2 } return filteredMap.size } val testInput = readInput("Day05_test") check(part1(testInput) == 5) check(part2(testInput) == 12) val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5febe0d5b9464738f9a7523c0e1d21bd992b9302
3,513
advent-of-code-2021
Apache License 2.0
src/main/kotlin/year2023/Day03.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2023 import utils.Direction typealias Coords = Pair<Int, Int> class Day03 { fun List<List<Char>>.findAllAdjacentNumbers(rowIdx: Int, colIdx: Int): Set<Coords> { val matrix = this return buildSet { Direction.entries.forEach { (dx, dy) -> val row = rowIdx + dy var col = colIdx + dx if (row in matrix.indices && col in matrix[row].indices && matrix[row][col].isDigit()) { while (col > 0 && matrix[row][col - 1].isDigit()) { col -= 1 } add(row to col) } } } } fun List<List<Char>>.readNumber(coords: Coords): Int { var number = 0 var (row, col) = coords while (col in this[row].indices && this[row][col].isDigit()) { number = number * 10 + (this[row][col] - '0') col += 1 } return number } fun buildMatrix(input: String): List<List<Char>> = input.lines() .filter { it.isNotBlank() } .map(CharSequence::toList) fun part1(input: String): Int { val matrix = buildMatrix(input) return buildSet { matrix.forEachIndexed { rowIdx, rowString -> rowString.forEachIndexed { colIdx, cell -> if (!cell.isDigit() && cell != '.') { addAll(matrix.findAllAdjacentNumbers(rowIdx, colIdx)) } } } }.map { matrix.readNumber(it) }.sum() } fun part2(input: String): Int { val matrix = buildMatrix(input) return matrix.flatMapIndexed { rowIdx, rowString -> rowString.mapIndexed { colIdx, cell -> if (cell == '*') { val numbers = matrix.findAllAdjacentNumbers(rowIdx, colIdx).toList() if (numbers.size == 2) { val number1 = matrix.readNumber(numbers[0]) val number2 = matrix.readNumber(numbers[1]) return@mapIndexed number1 * number2 } } 0 } }.sum() } }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
2,253
aoc-2022
Apache License 2.0
src/main/kotlin/dev/tasso/adventofcode/_2022/day11/Day11.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2022.day11 import dev.tasso.adventofcode.Solution import java.lang.IllegalArgumentException import kotlin.math.floor class Day11 : Solution<Int> { override fun part1(input: List<String>): Int { return input.asMonkeys() .let {monkeys -> (0..19).forEach { _ -> monkeys.forEach { monkey -> monkey.inspectAndTest().forEach { (monkeyNum, item) -> monkeys[monkeyNum].items.add(item) } } } monkeys.map { it.numInspected } .sortedDescending() .take(2) .reduce(Int::times) } } override fun part2(input: List<String>): Int { return 0 } /** * Splits a sequence of values which are delineated by an empty string, into subsequences (discarding empty strings) */ private fun Sequence<String>.chunkedOnEmpty(): Sequence<List<String>> = sequence { val subList = mutableListOf<String>() for (element in this@chunkedOnEmpty) { if (element.isNotEmpty()) { subList += element }else { yield(subList) subList.clear() } } if (subList.isNotEmpty()) yield(subList) } private data class Monkey(val items : MutableList<Int>, val operation : Operation, val testModulo : Int, val trueMonkey : Int, val falseMonkey : Int, var numInspected: Int = 0) { fun inspectAndTest() : List<Pair<Int, Int>> { numInspected += items.size val inspectedItems = items.map { item -> operation.invoke(item) } .map { inspectedItem -> floor(inspectedItem / 3.0).toInt() } .map { inspectedItem -> (if (inspectedItem % testModulo == 0) trueMonkey else falseMonkey) to inspectedItem } items.clear() return inspectedItems } } private class Operation(val leftOperand : (Int) -> Int, val operator: (Int, Int) -> Int, val rightOperand : (Int) -> Int) { fun invoke(oldValue : Int) : Int = operator.invoke(leftOperand.invoke(oldValue), rightOperand.invoke(oldValue)) } private fun String.toOperation() : Operation { fun getOperandFunc(operand: String) : (Int) -> Int = if(operand == "old") { value: Int -> value } else { _: Int -> operand.toInt() } fun getOperatorFunc(operator: String): (Int, Int) -> Int = when (operator) { "+" -> { left: Int, right: Int -> left + right } "*" -> { left: Int, right: Int -> left * right } else -> { throw IllegalArgumentException("Unexpected operator encountered!: $operator") } } return this.split(" ") .let { (leftOperand, operator, rightOperand) -> Operation(getOperandFunc(leftOperand), getOperatorFunc(operator), getOperandFunc(rightOperand)) } } private fun List<String>.asMonkeys() : List<Monkey> = this.asSequence() .chunkedOnEmpty() .map { it.asMonkey() } .toList() private fun List<String>.asMonkey() : Monkey { fun String.parseItems() : MutableList<Int> = this.split("Starting items: ") .last() .split(", ") .map{ it.toInt() } .toMutableList() fun String.parseOperation() : Operation = this.split(" new = ") .last() .toOperation() fun String.parseTestModulo() : Int = this.split(" divisible by ") .last() .toInt() fun String.parseThrownMonkey(): Int = this.split(" throw to monkey ") .last() .toInt() return Monkey(items = this[1].parseItems(), operation = this[2].parseOperation(), testModulo = this[3].parseTestModulo(), trueMonkey = this[4].parseThrownMonkey(), falseMonkey = this[5].parseThrownMonkey()) } }
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
4,696
advent-of-code
MIT License
src/Day02.kt
mkulak
573,910,880
false
{"Kotlin": 14860}
fun main() { fun part1(input: List<String>): Int = input.sumOf { line -> val their = line[0].code - 'A'.code val mine = line[2].code - 'X'.code when (their - mine) { 0 -> 3 -1, 2 -> 6 else -> 0 } + mine + 1 } fun part2(input: List<String>): Int = input.sumOf { line -> val their = line[0].code - 'A'.code val result = line[2].code - 'X'.code when (result) { 0 -> (their + 2) % 3 1 -> 3 + their else -> 6 + (their + 1) % 3 } + 1 } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3b4e9b32df24d8b379c60ddc3c007d4be3f17d28
753
AdventOfKo2022
Apache License 2.0
src/main/kotlin/days/Day13.kt
hughjdavey
572,954,098
false
{"Kotlin": 61752}
package days import days.Day13.Order.RIGHT import days.Day13.Order.SAME import days.Day13.Order.WRONG import xyz.hughjd.aocutils.Collections.takeWhileInclusive import java.util.Stack class Day13 : Day(13) { override fun partOne(): Any { return inputList.asSequence().filterNot { it.isEmpty() }.map { parsePackets(it) } .chunked(2).map { compare(it[0], it[1]) } .mapIndexedNotNull { index, order -> if (order == RIGHT) index + 1 else null } .sum() } override fun partTwo(): Any { val decoderPackets = listOf( listOf(listOf(listOf(2))), listOf(listOf(listOf(6))) ) return inputList.asSequence().filterNot { it.isEmpty() }.map { parsePackets(it) } .plus(decoderPackets).sortedWith { a1, a2 -> compare(a1, a2).ordinal - 1 } .mapIndexedNotNull { index, packet -> if (packet in decoderPackets) index + 1 else null } .fold(1) { acc, elem -> acc * elem } } enum class Order { RIGHT, SAME, WRONG } fun compare(packets1: List<Any>, packets2: List<Any>): Order { val foo = generateSequence(0) { it + 1 }.map { packets1.getOrNull(it) to packets2.getOrNull(it) }.map { val (left, right) = it when { left == null && right == null -> SAME left == null && right != null -> RIGHT left != null && right == null -> WRONG left is Int && right is Int -> if (left < right) RIGHT else if (left == right) SAME else WRONG left is List<*> && right is List<*> -> compare(left as List<Any>, right as List<Any>) else -> { // exactly one value is an integer val l = if (left is Int) listOf(left) else left val r = if (right is Int) listOf(right) else right compare(l as List<Int>, r as List<Int>) } } }.takeWhileInclusive { it == SAME }.take(10).toList() return foo.last() } private fun parsePackets(input: String): List<Any> { val packets = mutableListOf<Any>() val stack = Stack<MutableList<Any>>() var currentInt = "" fun getCurrentList(): MutableList<Any> { return if (!stack.empty()) stack.peek() else packets } fun addCurrentInt() { if (currentInt.isNotEmpty()) { getCurrentList().add(currentInt.toInt()) currentInt = "" } } input.drop(1).dropLast(1).forEach { c -> when (c) { '[' -> { val list = mutableListOf<Any>() getCurrentList().add(list) stack.push(list) } ']' -> { addCurrentInt() stack.pop() } ',' -> addCurrentInt() else -> currentInt += c } } addCurrentInt() return packets } }
0
Kotlin
0
2
65014f2872e5eb84a15df8e80284e43795e4c700
3,025
aoc-2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/treesandgraphs/Question7.kt
jimmymorales
446,845,269
false
{"Kotlin": 46222}
package treesandgraphs fun main() { val orderBuild1 = findBuildOrder( projects = setOf("a", "b", "c", "d", "e", "f"), dependencies = setOf("a" to "d", "f" to "b", "b" to "d", "f" to "a", "d" to "c"), ) assert(orderBuild1 == listOf("e", "f", "b", "a", "d", "c")) val orderBuild2 = findBuildOrder( projects = setOf("a", "b", "c", "d", "e", "f", "g"), dependencies = setOf( "a" to "e", "f" to "c", "b" to "a", "f" to "b", "d" to "g", "b" to "e", "c" to "a", "f" to "a", ), ) assert(orderBuild2 == listOf("d", "g", "f", "b", "c", "a", "e")) } private fun findBuildOrder(projects: Set<String>, dependencies: Set<Pair<String, String>>): List<String>? { val projectsLeft = projects.toMutableSet() val graph = buildGraph(dependencies, projectsLeft) ?: return null val result = ArrayDeque<String>(projects.size) val visiting = mutableSetOf<String>() val visited = mutableSetOf<String>() while (graph.isNotEmpty()) { val node = graph.keys.first() val res = doDFS(node, visiting, visited, result, graph) if (!res) return null } projectsLeft.forEach(result::addFirst) return result.toList() } private fun buildGraph( dependencies: Set<Pair<String, String>>, projects: MutableSet<String> ): MutableMap<String, List<String>>? { val graph = mutableMapOf<String, List<String>>() for (dep in dependencies) { if (dep.first == dep.second) return null val deps = graph.getOrElse(dep.first) { emptyList() } graph[dep.first] = deps + dep.second projects.remove(dep.first) projects.remove(dep.second) } return graph } private fun doDFS( node: String, visiting: MutableSet<String>, visited: MutableSet<String>, results: ArrayDeque<String>, graph: MutableMap<String, List<String>> ): Boolean { if (node in visited) return true if (node in visiting) return false visiting.add(node) if (node !in graph) { results.addFirst(node) visited.add(node) return true } for (dep in graph[node]!!) { val res = doDFS(dep, visiting, visited, results, graph) if (!res) return false } results.addFirst(node) visited.add(node) graph.remove(node) return true }
0
Kotlin
0
0
8a32d379d5f3a2e779f6594d949f63d2e02aad4c
2,122
algorithms
MIT License
src/main/kotlin/dev/paulshields/aoc/day2/PasswordPhilosophy.kt
Pkshields
318,658,287
false
null
package dev.paulshields.aoc.day2 import dev.paulshields.aoc.common.readFileAsStringList fun main() { println(" ** Day 2: Password Philosophy ** \n") val passwordEntries = readFileAsStringList("/day2/PasswordsDatabase.txt") .mapNotNull(::parsePasswordEntry) val firstValidPasswordsCount = passwordEntries .filter(::passwordIsValidByTheCharCountRule) .count() println("There are $firstValidPasswordsCount passwords in the database according to the char count rule!") val secondValidPasswordsCount = passwordEntries .filter(::passwordIsValidByTheCharPositionRule) .count() println("There are $secondValidPasswordsCount passwords in the database according to the char position rule!") } fun parsePasswordEntry(rawPasswordEntry: String): PasswordEntry? { val passwordEntryRegex = Regex("(\\d+)-(\\d+) (\\w): (\\w+)") val regexResult = passwordEntryRegex.find(rawPasswordEntry) return regexResult ?.destructured ?.let { PasswordEntry( it.component3()[0], it.component1().toInt(), it.component2().toInt(), it.component4()) } } fun passwordIsValidByTheCharCountRule(passwordEntry: PasswordEntry) = with(passwordEntry) { val countOfRequiredChar = password.count { it == requiredCharacter } countOfRequiredChar in minimum..maximum } fun passwordIsValidByTheCharPositionRule(passwordEntry: PasswordEntry) = with(passwordEntry) { val firstChar = password[minimum - 1] val secondChar = password[maximum - 1] (firstChar == requiredCharacter && secondChar != requiredCharacter) || (firstChar != requiredCharacter && secondChar == requiredCharacter) } data class PasswordEntry( val requiredCharacter: Char, val minimum: Int, val maximum: Int, val password: String)
0
Kotlin
0
0
a7bd42ee17fed44766cfdeb04d41459becd95803
1,886
AdventOfCode2020
MIT License
src/main/kotlin/dev/bogwalk/batch0/Problem3.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch0 import dev.bogwalk.util.maths.primeFactors import kotlin.math.max import kotlin.math.sqrt /** * Problem 3: Largest Prime Factor * * https://projecteuler.net/problem=3 * * Goal: Find the largest prime factor of N. * * Constraints: 10 <= N <= 1e12 * * Fundamental Theorem of Arithmetic: There will only ever be a unique set of prime factors for * any number greater than 1. * * e.g.: N = 10 * prime factors = {2, 5} * largest = 5 */ class LargestPrimeFactor { /** * Uses prime decomposition via trial division with some optimisations to return the largest * prime factor. * * SPEED (BETTER for N with small factors) 1.4e+05ns for N = 1e12 * SPEED (BETTER for N with large factors) 5.8e+04ns for N = 600_851_475_143 */ fun largestPrimeFactor(n: Long): Long { return primeFactors(n).keys.maxOrNull()!! } /** * Uses prime decomposition via trial division without any optimisation. * * SPEED (BEST for N with small factors) 3073ns for N = 1e12 * SPEED (BEST for N with large factors) 2.6e+04ns for N = 600_851_475_143 */ fun largestPrimeFactorSimple(n: Long): Long { var num = n var factor = 2L while (factor * factor <= num) { while (num % factor == 0L && num != factor) { num /= factor } factor++ } return num } /** * Identical to the optimised primeFactorsOG() algorithm but uses recursion instead of * storing the entire prime factorisation map. * * This method was implemented just to see how recursion could fit into this solution. * * SPEED (WORST for N with small factors) 122.06ms for N = 1e12 * SPEED (WORST for N with large factors) 37.80ms for N = 600_851_475_143 */ fun largestPrimeFactorRecursive(n: Long, largest: Long = 2L): Long { val maxFactor = sqrt(n.toDouble()).toLong() val factors = listOf(2L) + (3L..maxFactor step 2L) for (factor in factors) { if (n % factor == 0L) { return largestPrimeFactorRecursive(n / factor, factor) } } return if (n > 2) max(largest, n) else largest } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,266
project-euler-kotlin
MIT License
src/main/kotlin/com/nibado/projects/advent/Point3D.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent import java.lang.Integer.max import java.lang.Integer.min data class Point3D(val x: Int, val y: Int, val z: Int) { constructor() : this(0, 0, 0) fun neighbors() = neighbors(this) operator fun plus(other: Point3D) = Point3D(x + other.x, y + other.y, z + other.z) operator fun minus(other: Point3D) = Point3D(x - other.x, y - other.y, z - other.z) companion object { private val MAX = Point3D(Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE) private val MIN = Point3D(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE) private val ORIGIN = Point3D() fun neighbors(p: Point3D): List<Point3D> = (-1..1).flatMap { x -> (-1..1).flatMap { y -> (-1..1) .map { z -> Point3D(x + p.x, y + p.y, z + p.z) } } } .filterNot { (x, y, z) -> x == p.x && y == p.y && z == p.z } fun bounds(points: Collection<Point3D>) = points .fold(MAX to MIN) { (min, max), p -> Point3D(min(min.x, p.x), min(min.y, p.y), min(min.z, p.z)) to Point3D(max(max.x, p.x), max(min.y, p.y), max(max.z, p.z)) } fun points(min: Point3D, max: Point3D): List<Point3D> = (min.x..max.x).flatMap { x -> (min.y..max.y).flatMap { y -> (min.z..max.z).map { z -> Point3D(x, y, z) } } } } } fun Pair<Point3D, Point3D>.points() = let { (min, max) -> Point3D.points(min, max) } fun Collection<Point3D>.bounds() = Point3D.bounds(this)
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,638
adventofcode
MIT License
src/main/kotlin/name/valery1707/problem/leet/code/ConcatenationOfConsecutiveBinaryNumbersK.kt
valery1707
541,970,894
false
null
package name.valery1707.problem.leet.code import java.math.BigInteger /** * # 1680. Concatenation of Consecutive Binary Numbers * * Given an integer `n`, return the **decimal value** of the binary string formed by concatenating the binary representations of `1` to `n` in order, * **modulo** `10^9 + 7`. * * ### Constraints * * `1 <= n <= 10^5` * * @see <a href="https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/">1680. Concatenation of Consecutive Binary Numbers</a> */ interface ConcatenationOfConsecutiveBinaryNumbersK { fun concatenatedBinary(n: Int): Int @Suppress("EnumEntryName", "unused") enum class Implementation : ConcatenationOfConsecutiveBinaryNumbersK { naive { override fun concatenatedBinary(n: Int): Int { val modulo = (1e9 + 7).toLong().toBigInteger() return (1..n) .joinToString(separator = "") { it.toString(2) } .toBigInteger(2) .mod(modulo) .intValueExact() } }, sumThenModulo_fold { override fun concatenatedBinary(n: Int): Int { val modulo = (1e9 + 7).toLong().toBigInteger() return n.downTo(1) .fold(Pair(BigInteger.ZERO, 0)) { sumAndShift, item -> val shift = sumAndShift.second val sum = item.toBigInteger().shl(shift).plus(sumAndShift.first) Pair(sum, shift + item.toString(2).length) } .first .mod(modulo) .intValueExact() } }, sumThenModulo_for { override fun concatenatedBinary(n: Int): Int { val modulo = (1e9 + 7).toLong().toBigInteger() var sum = BigInteger.ZERO var shift = 0 for (item in n.downTo(1)) { sum = item.toBigInteger().shl(shift).plus(sum) shift += item.toString(2).length } return sum.mod(modulo).intValueExact() } }, /** * @see <a href="https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/discuss/2612207/Java-oror-Explained-in-Detailoror-Fast-O(N)-Solutionoror-Bit-Manipulation-and-Math">Java || 👍Explained in Detail👍 || Fast O(N) Solution✅ || Bit Manipulation & Math</a> */ cheehwatang { override fun concatenatedBinary(n: Int): Int { val modulo = (1e9 + 7).toLong() return (1..n) .fold(Pair(0L, 0)) { sumAndShift, item -> // Если мы на текущем элементе перешли на новую степень двойки val shift = if (item.and(item - 1) == 0) sumAndShift.second + 1 else sumAndShift.second // Предыдущую накопленную сумму смещаем на количество бит у текущего числа и добавляем к нему текущее число val sum = sumAndShift.first.shl(shift) + item // Чтобы не выскочить за границу Int нужно ограничить сумму по указанному модулю Pair(sum % modulo, shift) } .first .toInt() } }, } }
3
Kotlin
0
0
76d175f36c7b968f3c674864f775257524f34414
3,593
problem-solving
MIT License
src/Day09.kt
frungl
573,598,286
false
{"Kotlin": 86423}
import kotlin.math.abs import kotlin.math.sign typealias Point = Pair<Int, Int> @OptIn(ExperimentalStdlibApi::class) fun main() { fun direction(main: Point, other: Point): Point { val dx = main.first - other.first val dy = main.second - other.second return when((abs(dx) - abs(dy)).sign) { 0 -> dx.sign to dy.sign 1 -> dx.sign to 0 else -> 0 to dy.sign } } fun move(head: Point, tail: Point, move: Point): Pair<Point, Point> { val newHead = head + move val possibleMove = listOf( Point(0, 1), Point(0, -1), Point(1, 0), Point(-1, 0), Point(1, 1), Point(1, -1), Point(-1, 1), Point(-1, -1), Point(0, 0) ) val possibleTailPos = possibleMove.map { newHead + it } if(possibleTailPos.contains(tail)) { return Pair(newHead, tail) } val newTail = newHead - direction(newHead, tail) return Pair(newHead, newTail) } fun getMoveDir(ch: String): Point { return when(ch) { "U" -> Point(0, 1) "D" -> Point(0, -1) "L" -> Point(-1, 0) "R" -> Point(1, 0) else -> throw IllegalArgumentException("Unknown direction $ch") } } fun part1(input: List<String>): Int { var headPos = Point(0, 0) var tailPos = Point(0, 0) val vis = mutableSetOf<Point>() vis.add(tailPos) input.map { it.split(' ').toList() }.forEach { val (dir, dist) = it val move = getMoveDir(dir) repeat(dist.toInt()) { val (newHead, newTail) = move(headPos, tailPos, move) headPos = newHead tailPos = newTail vis.add(tailPos) } } return vis.size } fun part2(input: List<String>): Int { val snake = MutableList(10) { Point(0, 0) } val vis = mutableSetOf<Point>() vis.add(snake.last()) input.map { it.split(' ').toList() }.forEach { val (dir, dist) = it val move = getMoveDir(dir) repeat(dist.toInt()) { var lastMove = move for(i in 1..<snake.size) { val (newHead, newTail) = move(snake[i - 1], snake[i], lastMove) lastMove = newTail - snake[i] snake[i - 1] = newHead if(i == snake.size - 1 || lastMove == Point(0, 0)) { snake[i] = newTail break } } vis.add(snake.last()) } } return vis.size } val testInput = readInput("Day09_test") val testInput2 = readInput("Day09_test2") check(part1(testInput) == 13) check(part2(testInput) == 1) check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) } private operator fun Point.plus(move: Point): Point { return Point(first + move.first, second + move.second) } private operator fun Point.minus(move: Point): Point { return Point(first - move.first, second - move.second) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
3,323
aoc2022
Apache License 2.0
src/main/kotlin/aoc/utils/Geo.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package aoc.utils import java.lang.Long.max import java.lang.Long.min import kotlin.math.abs import kotlin.math.pow data class Point(val x: Long, val y: Long, val z: Long = 0) { fun distance(to: Point) = ((x.toDouble() - to.x).pow(2.0) + (y.toDouble() - to.y).pow(2.0) + (z.toDouble() - to.z).pow(2.0)).pow(0.5); // Not diagonally fun nextTo(point: Point): Boolean { return abs(x-point.x)+abs(y-point.y)+abs(z-point.z) == 1L } fun minus(it: Point): Point { return copy(x=x-it.x,y=y-it.y,z=z-it.z) } fun plus(it: Point): Point { return copy(x=x+it.x,y=y+it.y,z=z+it.z) } // e.g. (3,0,-2) -> (1,0,-1) fun unitComponents(): Point { return copy( x= if(x==0L) 0 else x/ abs(x), y= if(y==0L) 0 else y/abs(y), z= if(z==0L) 0 else z/abs(z) ) } /** * which of the given points are in the given direction e.g. (0,-1,0) */ fun onDirection(points: Set<Point>, direction: Point): Set<Point> { return points.filter { minus(it).unitComponents() == direction }.toSet() } // Points on direct line to any 6 directions fun onDirectLine(points: Set<Point>): Set<Point> { return points.filter { point -> val isOnSameLine = listOf(abs(x - point.x), abs(y - point.y), abs(z - point.z)) .filter { it != 0L }.size == 1 isOnSameLine }.toSet() } } data class Line(val start: Point, val end: Point) // Only for horizontal, vertical and 45 degree lines for now fun pointsInLine(line: Line): List<Point> { // Horizontal/vertical if (line.start.x == line.end.x || line.start.y == line.end.y) { return (min(line.start.y, line.end.y)..max(line.start.y, line.end.y)) .flatMap { y -> (min(line.start.x, line.end.x)..max(line.start.x, line.end.x)) .map { x -> Point(x, y) } } } // 45 degrees else { val xValues = if (line.start.x > line.end.x) line.start.x downTo line.end.x else (line.start.x..line.end.x) var yValues = if(line.start.y > line.end.y) line.start.y downTo line.end.y else (line.start.y..line.end.y) return yValues.toList().zip(xValues.toList()).map { Point(it.second, it.first) } } }
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
2,478
adventOfCode2022
Apache License 2.0
src/Day06.kt
dizney
572,581,781
false
{"Kotlin": 105380}
import kotlin.system.measureNanoTime object Day06 { const val EXPECTED_PART1_CHECK_ANSWER = 7 const val EXPECTED_PART2_CHECK_ANSWER = 19 const val MARKER_PACKET_LENGTH = 4 const val MARKER_MESSAGE_LENGTH = 14 } fun main() { fun String.findLengthUntilMarker(markerLength: Int): Int { var pointerInData = 0 var potentialMarker = "" do { when (val indexOfDuplicate = potentialMarker.indexOf(this[pointerInData])) { -1 -> potentialMarker += this[pointerInData] else -> potentialMarker = potentialMarker.drop(indexOfDuplicate + 1) + this[pointerInData] } pointerInData++ } while (potentialMarker.length < markerLength && pointerInData < this.length) return pointerInData } fun String.findLengthUntilMarkerWindowed(markerLength: Int) = windowedSequence(markerLength) { it.toSet().size }.indexOfFirst { it == markerLength } + markerLength fun part1(input: List<String>): Int { val windowedDuration = measureNanoTime { input.first().findLengthUntilMarkerWindowed(Day06.MARKER_PACKET_LENGTH) } val nonWindowedDuration = measureNanoTime { input.first().findLengthUntilMarker(Day06.MARKER_PACKET_LENGTH) } println("Windowed: $windowedDuration, Non windowed: $nonWindowedDuration") return input.first().findLengthUntilMarkerWindowed(Day06.MARKER_PACKET_LENGTH) } fun part2(input: List<String>): Int { val windowedDuration = measureNanoTime { input.first().findLengthUntilMarkerWindowed(Day06.MARKER_MESSAGE_LENGTH) } val nonWindowedDuration = measureNanoTime { input.first().findLengthUntilMarker(Day06.MARKER_MESSAGE_LENGTH) } println("Windowed: $windowedDuration, Non windowed: $nonWindowedDuration") return input.first().findLengthUntilMarkerWindowed(Day06.MARKER_MESSAGE_LENGTH) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == Day06.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" } check(part2(testInput) == Day06.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" } val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f684a4e78adf77514717d64b2a0e22e9bea56b98
2,366
aoc-2022-in-kotlin
Apache License 2.0
src/Day09.kt
AleksanderBrzozowski
574,061,559
false
null
import Day09.Direction.D import Day09.Direction.L import Day09.Direction.R import Day09.Direction.U import java.lang.IllegalArgumentException import kotlin.math.abs import kotlin.math.sign class Day09 { enum class Direction { L, R, U, D } } fun main() { data class Point(val x: Int, val y: Int) { operator fun minus(point: Point): Point = Point(x - point.x, y - point.y) operator fun plus(point: Point): Point = Point(x + point.x, y + point.y) } fun Point.update(direction: Day09.Direction): Point = when (direction) { L -> copy(x = x - 1) R -> copy(x = x + 1) U -> copy(y = y + 1) D -> copy(y = y - 1) } fun Point.isTouching(other: Point): Boolean = abs(x - other.x) <= 1 && abs(y - other.y) <= 1 val testData = readInput("Day09_test") .flatMap { line -> val (direction, times) = line.split(" ") (1..times.toInt()).map { when (direction) { "L" -> L "R" -> R "U" -> U "D" -> D else -> throw IllegalArgumentException("Unknown direction: $direction") } } } fun part1() { var tail = Point(0, 0) var head = Point(0, 0) var visited = setOf<Point>(tail) testData.forEach { direction -> val prevHead = head head = head.update(direction) if (tail.isTouching(head)) { return@forEach } tail = prevHead visited = visited + tail } println(visited.size) } fun visualize(knot: List<Point>) { (-5..15).map { y -> // (0..4).map { y -> (-11..15).map { x -> // (0..5).map { x -> when (val indexOfPoint = knot.indexOf(Point(x, y))) { -1 -> "." 0 -> "H" else -> indexOfPoint.toString() } } }.reversed().onEach { println(it.joinToString(separator = " ")) } } fun visualizeVisited(visited: Set<Point>) { (-5..15).map { y -> (-11..15).map { x -> if (visited.contains(Point(x, y))) "#" else "." } }.reversed().onEach { println(it.joinToString(separator = " ")) } } fun part2() { fun Int.isHead(): Boolean = this == 0 val knot = generateSequence { Point(0, 0) }.take(10).toMutableList() var visited = setOf(Point(0, 0)) var last = testData[0] testData.forEach { direction -> repeat(knot.size) { index -> val point = knot[index] when { index.isHead() -> { knot[index] = point.update(direction) } else -> { val precedingPoint = knot[index - 1] if (point.isTouching(precedingPoint)) { return@repeat } val movement = Point((precedingPoint.x - point.x).sign, (precedingPoint.y - point.y).sign) knot[index] = point + movement } } if (index == knot.size - 1) { visited = visited + knot[index] } } if (last != direction) { last = direction } // visualize(knot) // println() } // visualizeVisited(visited) println(visited.size) } part1() part2() }
0
Kotlin
0
0
161c36e3bccdcbee6291c8d8bacf860cd9a96bee
3,682
kotlin-advent-of-code-2022
Apache License 2.0
src/main/kotlin/solutions/Day09.kt
chutchinson
573,586,343
false
{"Kotlin": 21958}
import kotlin.math.* class Day09 : Solver { data class Vector2(var x: Int, var y: Int) data class Move(val direction: Char, val distance: Int) override fun solve (input: Sequence<String>) { fun parse (v: String) = Move(v[0], v.substring(2).toInt()) val moves = input.map(::parse).toList() println(first(moves)) println(second(moves)) } fun first (input: Iterable<Move>) = simulate(input, 2) fun second (input: Iterable<Move>) = simulate(input, 10) fun simulate (moves: Iterable<Move>, n: Int): Int { val knots = (0 until n).map { Vector2(0, 0) }.toList() val visited = mutableSetOf<Vector2>() fun move (dx: Int, dy: Int) { fun gap (a: Int, b: Int) = (a - b).absoluteValue >= 2 fun diaganol (a: Int, b: Int) = if (a != b) { (a - b).sign } else { 0 } val head = knots[0] val tail = knots[knots.size - 1] head.x += dx head.y += dy for (k in 0 until knots.size - 1) { val knot = knots[k] val next = knots[k + 1] if (gap(knot.x, next.x)) { next.x += (knot.x - next.x).sign next.y += diaganol(knot.y, next.y) } if (gap(knot.y, next.y)) { next.y += (knot.y - next.y).sign next.x += diaganol(knot.x, next.x) } } visited.add(Vector2(tail.x, tail.y)) } for (m in moves) { for (x in 0 until m.distance) { when (m.direction) { 'L' -> move(-1, 0) 'R' -> move(1, 0) 'U' -> move(0, 1) 'D' -> move(0, -1) } } } return visited.size } }
0
Kotlin
0
0
5076dcb5aab4adced40adbc64ab26b9b5fdd2a67
1,903
advent-of-code-2022
MIT License
src/day17/Day17.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day17 import java.io.File import java.util.PriorityQueue fun main() { val data = parse("src/day17/Day17.txt") println("🎄 Day 17 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private typealias Graph = List<List<Int>> private fun parse(path: String): Graph = File(path) .readLines() .map { it.map(Char::digitToInt) } private data class Vec2( val x: Int, val y: Int, ) private typealias Vertex = Vec2 private data class Endpoint( val vertex: Vertex, val streakDirection: Vec2, val streakLength: Int, ) private data class Path( val endpoint: Endpoint, val distance: Int, ) : Comparable<Path> { override fun compareTo(other: Path): Int = distance.compareTo(other.distance) } private val Graph.h get() = this.size private val Graph.w get() = this[0].size private fun Graph.neighborsOf(vertex: Vertex): List<Vertex> = listOfNotNull( if (vertex.x - 1 >= 0) Vertex(vertex.x - 1, vertex.y) else null, if (vertex.x + 1 < w) Vertex(vertex.x + 1, vertex.y) else null, if (vertex.y - 1 >= 0) Vertex(vertex.x, vertex.y - 1) else null, if (vertex.y + 1 < h) Vertex(vertex.x, vertex.y + 1) else null, ) private fun part1(graph: Graph): Int { val visited = mutableSetOf<Endpoint>() val (xs, xt) = (0 to graph.w - 1) val (ys, yt) = (0 to graph.h - 1) val source = Vertex(xs, ys) val target = Vertex(xt, yt) val sourceEndpoint = Endpoint(source, Vec2(0, 0), streakLength = 0) val queue = PriorityQueue<Path>() .apply { add(Path(sourceEndpoint, distance = 0)) } while (queue.isNotEmpty()) { val (endpoint, distanceToVertex) = queue.poll() if (endpoint in visited) { continue } else { visited += endpoint } val (vertex, streakDirection, streakLength) = endpoint if (vertex == target) { return distanceToVertex } for (neighbor in graph.neighborsOf(vertex)) { val dx = neighbor.x - vertex.x val dy = neighbor.y - vertex.y val nextDirection = Vec2(dx, dy) if (nextDirection.x == -streakDirection.x && nextDirection.y == -streakDirection.y) { continue } val nextLength = if (nextDirection == streakDirection) streakLength + 1 else 1 if (nextLength == 4) { continue } val endpointToNeighbor = Endpoint(neighbor, nextDirection, nextLength) val distanceToNeighbor = distanceToVertex + graph[neighbor.y][neighbor.x] queue += Path(endpointToNeighbor, distanceToNeighbor) } } error("Could not find any path from source to target.") } private fun part2(graph: Graph): Int { val visited = mutableSetOf<Endpoint>() val (xs, xt) = (0 to graph.w - 1) val (ys, yt) = (0 to graph.h - 1) val source = Vertex(xs, ys) val target = Vertex(xt, yt) val sourceEndpoint = Endpoint(source, Vec2(0, 0), streakLength = 0) val queue = PriorityQueue<Path>() .apply { add(Path(sourceEndpoint, distance = 0)) } while (queue.isNotEmpty()) { val (endpoint, distanceToVertex) = queue.poll() if (endpoint in visited) { continue } else { visited += endpoint } val (vertex, streakDirection, streakLength) = endpoint if (vertex == target && streakLength >= 4) { return distanceToVertex } for (neighbor in graph.neighborsOf(vertex)) { val dx = neighbor.x - vertex.x val dy = neighbor.y - vertex.y val nextDirection = Vec2(dx, dy) if (nextDirection.x == -streakDirection.x && nextDirection.y == -streakDirection.y) { continue } val nextLength = if (nextDirection == streakDirection) streakLength + 1 else 1 if (nextLength > 10) { continue } if (streakDirection != Vec2(0, 0) && nextDirection != streakDirection && streakLength < 4) { continue } val endpointToNeighbor = Endpoint(neighbor, nextDirection, nextLength) val distanceToNeighbor = distanceToVertex + graph[neighbor.y][neighbor.x] queue += Path(endpointToNeighbor, distanceToNeighbor) } } error("Could not find any path from source to target.") }
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
4,758
advent-of-code-2023
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2023/Day03.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day03 : AbstractDay() { @Test fun part1() { assertEquals(4361, compute1(testInput)) assertEquals(544664, compute1(puzzleInput)) } @Test fun part2() { assertEquals(467835, compute2(testInput)) assertEquals(84495585, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { val (partNumbers, symbols) = parseSchematics(input) val numbers = partNumbers.filter { (_, partPositions) -> symbols.any { (_, symbolPosition) -> partPositions.any { it.isAdjacentTo(symbolPosition) } } }.map { it.number } return numbers.sum() } private fun compute2(input: List<String>): Int { val (partNumbers, symbols) = parseSchematics(input) val partNumberLookup = partNumbers.flatMap { partNumber -> partNumber.positions.map { pos -> pos to partNumber } }.toMap() val ratios = symbols .filter { it.char == '*' } .mapNotNull { symbol -> val numbersForSymbol = symbol.position .edges() .mapNotNull { partNumberLookup[it] } .distinct() if (numbersForSymbol.size == 2) { numbersForSymbol.fold(1) { acc, partNumber -> acc * partNumber.number } } else { null } } return ratios.sum() } private fun parseSchematics(input: List<String>): Pair<List<PartNumber>, List<Symbol>> { val partNumbers = mutableListOf<PartNumber>() val symbols = mutableListOf<Symbol>() input.forEachIndexed { y, line -> Regex("[0-9]+|[^0-9.]").findAll(line).forEach { r -> r.groups.filterNotNull().forEach { g -> if (g.value.first().isDigit()) { val positionsOfNum = g.range.map { x -> Point(x, y) } partNumbers.add(PartNumber(g.value.toInt(), positionsOfNum)) } else { val positionOfSymbol = Point(g.range.first, y) symbols.add(Symbol(g.value.single(), positionOfSymbol)) } } } } return partNumbers to symbols } data class PartNumber( val number: Int, val positions: List<Point>, ) data class Symbol( val char: Char, val position: Point, ) }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
2,649
aoc
Apache License 2.0
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day25/Day25.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day25 import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input25-test.txt" const val FILENAME = "input25.txt" const val DIGITS = "=-012" fun main() { runTests() part1() } fun runTests() { val testCases = listOf( Pair(1L, "1"), Pair(2L, "2"), Pair(3L, "1="), Pair(4L, "1-"), Pair(5L, "10"), Pair(6L, "11"), Pair(7L, "12"), Pair(8L, "2="), Pair(9L, "2-"), Pair(10L, "20"), Pair(15L, "1=0"), Pair(20L, "1-0"), Pair(2022L, "1=11-2"), Pair(12345L, "1-0---0"), Pair(314159265L, "1121-1110-1=0"), ) testCases.forEach { (decimal, string) -> val from = string.fromSnafu() if (from != decimal) println("$string -> $decimal but was $from") } testCases.forEach { (decimal, string) -> val to = decimal.toSnafu() if (to != string) println("$decimal -> $string but was $to") } } fun part1() { val result = readLines(2022, FILENAME) .map(String::fromSnafu) .sum() .toSnafu() println(result) } fun String.fromSnafu(): Long { fun toDigit(ch: Char): Int { val index = DIGITS.indexOf(ch) if (index == -1) throw IllegalArgumentException("$ch") return index - 2 } return this.map(::toDigit).fold(0L) { acc, digit -> acc * 5 + digit } } fun Long.toSnafu(): String { val builder = StringBuilder() var current = this while (current != 0L) { val temp = current + 2 builder.append(DIGITS[(temp % 5).toInt()]) current = temp / 5 } return if (builder.isEmpty()) "0" else builder.reverse().toString() }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,472
advent-of-code
Apache License 2.0
src/main/kotlin/aoc/day8/TreetopTreeHouse.kt
hofiisek
573,543,194
false
{"Kotlin": 17421}
package aoc.day8 import aoc.Matrix import aoc.Position import aoc.loadInput import aoc.nodesDown import aoc.nodesToTheLeft import aoc.nodesToTheRight import aoc.nodesUp import java.io.File /** * https://adventofcode.com/2022/day/8 * * @author <NAME> */ typealias Forest = Matrix<Tree> data class Tree(val height: Int, val pos: Position) fun File.loadForest() = readLines() .map { it.split("").filterNot(String::isBlank).map(String::toInt) } .mapIndexed { rowIdx, row -> row.mapIndexed { colIdx, height -> Tree(height, Position(rowIdx, colIdx)) } }.let(::Matrix) infix fun List<Tree>.allShorterThan(tree: Tree): Boolean = all { it.height < tree.height } infix fun List<Tree>.numShorterTreesThan(tree: Tree): Int = when (val idx = indexOfFirst { it.height >= tree.height }) { 0 -> 1 -1 -> size else -> idx + 1 } context(Forest) fun Tree.isVisibleFromOutside(): Boolean = nodesToTheLeft(pos) allShorterThan this || nodesToTheRight(pos) allShorterThan this || nodesUp(pos) allShorterThan this || nodesDown(pos) allShorterThan this context(Forest) fun Tree.viewingDistance(): Int { val numShorterToLeft = nodesToTheLeft(pos) numShorterTreesThan this val numShorterToRight = nodesToTheRight(pos) numShorterTreesThan this val numShorterUp = nodesUp(pos) numShorterTreesThan this val numShorterDown = nodesDown(pos) numShorterTreesThan this return numShorterToLeft * numShorterToRight * numShorterUp * numShorterDown } fun File.part1() = with(loadForest()) { flatten().count { tree -> tree.isVisibleFromOutside() } }.also(::println) fun File.part2() = with(loadForest()) { flatten().map { tree -> tree.viewingDistance() }.maxBy { it } }.also(::println) fun main() { with(loadInput(day = 8)) { part1() part2() } }
0
Kotlin
0
2
5908a665db4ac9fc562c44d6907f81cd3cd8d647
1,858
Advent-of-code-2022
MIT License
src/main/kotlin/algorithmic_toolbox/week2/FibonnaciWarmup.kt
eniltonangelim
369,331,780
false
null
package algorithmic_toolbox.week2 import java.util.* fun calcFib(n: Long): Long { return if (n <= 1) n else calcFib(n - 1) + calcFib(n - 2) } fun power(n: Long, x: Int = 2): Long { if (x == 0) return n return power(n * n, x - 1) } fun lastDigitOfNumber(n: Long): Long { var fibAList = LongArray((n+1).toInt()) fibAList[0] = 0 fibAList[1] = 1 if ( n < 2) return n for (i in 2..n) { fibAList[i.toInt()] = (fibAList[(i-1).toInt()] + fibAList[(i-2).toInt()]) % 10 } return fibAList[n.toInt()] } fun getPisanoPeriod(m: Long): Long { var period = 0L var previous = 0L var current = 1L for (i in 2 until m*m) { val tmpPrevious = previous previous = current current = (tmpPrevious+current) % m if (previous == 0L && current == 1L){ period = i - 1 break } } return period } fun calcFibMod(n: Long, m: Long): Long { if ( n <= 1) return n val pisanoPeriod = getPisanoPeriod(m) val remainder = n % pisanoPeriod var previous = 0L var current = 1L for (i in 0 until remainder-1) { val tmpPrevious = previous previous = current current = (tmpPrevious+current) % m } return current % m } fun calcLastDigitOfTheSumFibonacci(n: Long): Long { if (n <= 2) return n var fibAList = LongArray((n + 1).toInt()) fibAList[0] = 0L fibAList[1] = 1L for (i in 2..n) { fibAList[i.toInt()] = (fibAList[(i - 1).toInt()] + fibAList[(i - 2).toInt()]) % 10 } return fibAList.sum() % 10 } fun calcLastDigitOfTheSumFibonacci(m: Long, n: Long): Long { val pisanoPeriod = 60 // pisanoPeriod(10) = 60 var fibAList = LongArray(pisanoPeriod - 1) fibAList[0] = 0L fibAList[1] = 1L for (i in 2 until pisanoPeriod - 1) { fibAList[i] = (fibAList[i-1] + fibAList[i-2]) % 10 } var begin = m % pisanoPeriod var end = n % pisanoPeriod if (end < begin) end += pisanoPeriod var result = 0L for (i in begin..end) { result += fibAList[(i % pisanoPeriod).toInt()] } return result % 10 } fun calcLastDigitOfTheSumOfSquaresFibonacci(n: Long): Long { val pisanoPeriod = 60 val horizontal = lastDigitOfNumber((n +1) % pisanoPeriod) val vertical = lastDigitOfNumber( n % pisanoPeriod) return (horizontal * vertical) % 10 } fun main(args: Array<String>) { val scanner = Scanner(System.`in`) val n = scanner.nextLong() println(calcFib(n)) }
0
Kotlin
0
0
031bccb323339bec05e8973af7832edc99426bc1
2,549
AlgorithmicToolbox
MIT License
src/main/kotlin/day4/GameCard.kt
remhiit
727,182,240
false
{"Kotlin": 12212}
package day4 class GameCard(input: List<String>) { val cards: List<Card> init { cards = input.withIndex().map { val splitted = it.value.split(":", "|") Card(it.index, getNumbers(splitted[1]), getNumbers(splitted[2])) } } private fun getNumbers(s: String): List<Int> { return s.trim().split(" ").filter { it.isNotBlank() }.map { it.toInt() } } fun getWinningScores(): List<Int> { return cards.map { it.getScore() } } fun getFinalStack(): Int { val stack = cards.map { it.id to 1 }.toMap().toMutableMap() cards.forEach { c -> val nbCopy = stack[c.id]!! for (x in 1..nbCopy) { for (i in 1..c.getCardsIdToAdd()) { if (stack[c.id + i] != null) { stack[c.id + i] = stack[c.id + i]!! + 1 } } } } return stack.values.sum() } } data class Card(val id: Int, val winningNumbers: List<Int>, val numbers: List<Int>) { fun getScore(): Int { return Math.pow(2.0, numbers.filter { winningNumbers.contains(it) }.size.minus(1).toDouble()).toInt() } fun getCardsIdToAdd(): Int { return numbers.filter { winningNumbers.contains(it) }.size } }
0
Kotlin
0
0
122ee235df1af8e3d0ea193b9a37162271bad7cb
1,320
aoc2023
Creative Commons Zero v1.0 Universal
src/main/java/challenges/educative_grokking_coding_interview/k_way_merge/_5/KthSmallest.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.k_way_merge._5 import java.util.* /** Find the kth smallest element in an (n×n) matrix, where each row and column of the matrix is sorted in ascending order. Although there can be repeating values in the matrix, each element is considered unique and, therefore, contributes to calculating the kth smallest element. https://www.educative.io/courses/grokking-coding-interview-patterns-java/mEoD8KqPyr3 */ internal object KthSmallest { private fun kthSmallestElement(matrix: Array<IntArray>, k: Int): Int { // storing the number of rows in the matrix to use it in later val rowCount = matrix.size // declaring a min-heap to keep track of smallest elements val minHeap = PriorityQueue { a: IntArray, b: IntArray -> a[0] - b[0] } for (i in 0 until rowCount) { // pushing the first element of each row in the min-heap // The offer() method pushes an element into an existing heap // in such a way that the heap property is maintained. minHeap.offer(intArrayOf(matrix[i][0], i, 0)) } var numbersChecked = 0 var smallestElement = 0 // iterating over the elements pushed in our minHeap while (!minHeap.isEmpty()) { // get the smallest number from top of heap and its corresponding row and column val curr = minHeap.poll() smallestElement = curr[0] val rowIndex = curr[1] val colIndex = curr[2] numbersChecked++ // when numbersChecked equals k, we'll return smallestElement if (numbersChecked == k) { break } // if the current element has a next element in its row, // add the next element of that row to the minHeap if (colIndex + 1 < matrix[rowIndex].size) { minHeap.offer(intArrayOf(matrix[rowIndex][colIndex + 1], rowIndex, colIndex + 1)) } } // return the Kth smallest number found in the matrix return smallestElement } @JvmStatic fun main(args: Array<String>) { val matrix = arrayOf( arrayOf(intArrayOf(2, 6, 8), intArrayOf(3, 7, 10), intArrayOf(5, 8, 11)), arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9)), arrayOf(intArrayOf(5)), arrayOf( intArrayOf(2, 5, 7, 9, 10), intArrayOf(4, 6, 8, 12, 14), intArrayOf(11, 13, 16, 18, 20), intArrayOf(15, 17, 21, 24, 26), intArrayOf(19, 22, 23, 25, 28) ), arrayOf( intArrayOf(3, 5, 7, 9, 11, 13), intArrayOf(6, 8, 10, 12, 14, 16), intArrayOf(15, 17, 19, 21, 23, 25), intArrayOf(18, 20, 22, 24, 26, 28), intArrayOf(27, 29, 31, 33, 35, 37), intArrayOf(30, 32, 34, 36, 38, 40) ) ) val k = intArrayOf(3, 4, 1, 10, 15) for (i in k.indices) { print(i + 1) println(".\tInput matrix: " + Arrays.deepToString(matrix[i])) println("\tK = " + k[i]) println("\tKth smallest number in the matrix is: " + kthSmallestElement(matrix[i], k[i])) println(String(CharArray(100)).replace('\u0000', '-')) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,449
CodingChallenges
Apache License 2.0
src/Day06.kt
euphonie
571,665,044
false
{"Kotlin": 23344}
fun main() { fun findFirstUniqueSequence(input: String, windowSize: Int) : Int { var startIndex = 0 for (i in IntRange(0, input.length-windowSize-1) step 1) { val letters = input.substring(i, i+windowSize) if (letters.toSet().size == letters.toList().size) { startIndex = i break } } return startIndex + windowSize } fun part1(input: List<String>) : List<Int> { val windowSize = 4 return input.map { findFirstUniqueSequence(it, windowSize) } } fun part2(input: List<String>) : List<Int> { val markerSize = 4 val messageSize = 14 return input.map { val markerIndex = findFirstUniqueSequence(it, markerSize) + 1 Pair( markerIndex, it.substring(markerIndex, it.length) ) } .map { findFirstUniqueSequence(it.second, messageSize) + it.first } } val testInput = readInput("Day06_test") check(part1(testInput) == listOf(7, 5, 6, 10, 11)) check(part2(testInput) == listOf(25,23,23,29,26)) val input = readInput("Day06") check(part1(input) == listOf(1598)) check(part2(input) == listOf(2414)) }
0
Kotlin
0
0
82e167e5a7e9f4b17f0fbdfd01854c071d3fd105
1,275
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CheckCompletenessOfBinaryTree.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.LinkedList import java.util.Queue /** * 958. Check Completeness of a Binary Tree * @see <a href="https://leetcode.com/problems/check-completeness-of-a-binary-tree/">Source</a> */ fun interface CheckCompletenessOfBinaryTree { fun isCompleteTree(root: TreeNode?): Boolean } class CheckCompletenessOfBinaryTreeBFS : CheckCompletenessOfBinaryTree { override fun isCompleteTree(root: TreeNode?): Boolean { val bfs: Queue<TreeNode> = LinkedList() bfs.offer(root) while (bfs.peek() != null) { val node = bfs.poll() bfs.offer(node.left) bfs.offer(node.right) } while (bfs.isNotEmpty() && bfs.peek() == null) bfs.poll() return bfs.isEmpty() } } class CheckCompletenessOfBinaryTreeDFS : CheckCompletenessOfBinaryTree { override fun isCompleteTree(root: TreeNode?): Boolean { return dfs(root) >= 0 } private fun dfs(root: TreeNode?): Int { if (root == null) return 0 val l = dfs(root.left) val r = dfs(root.right) if (l and l + 1 == 0 && l / 2 <= r && r <= l) { return l + r + 1 } return if (r and r + 1 == 0 && r <= l && l <= r * 2 + 1) { l + r + 1 } else { -1 } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,943
kotlab
Apache License 2.0
src/Day03.kts
Cicirifu
225,414,163
false
null
import java.io.File import kotlin.math.abs import kotlin.math.max import kotlin.math.min data class Bounds(val xMin: Int, val yMin: Int, val xMax: Int, val yMax: Int) data class Coord(val x: Int, val y: Int) data class LineSegment(val start: Coord, val end: Coord, val direction: Direction, val length: Int) data class Line(val id: Int, val segments: List<LineSegment>) data class Intersection(val coord: Coord, val lengthA: Int, val lengthB: Int) fun Coord.manhattan() = abs(x) + abs(y) fun Line.bounds() = segments.map { it.bounds() }.flatten() fun LineSegment.bounds() = Bounds( xMin = min(start.x, end.x), yMin = min(start.y, end.y), xMax = max(start.x, end.x), yMax = max(start.y, end.y) ) fun List<Bounds>.flatten() = Bounds( xMin = this.minBy { it.xMin }!!.xMin, xMax = this.maxBy { it.xMax }!!.xMax, yMin = this.minBy { it.yMin }!!.yMin, yMax = this.maxBy { it.yMax }!!.yMax ) fun Line.forEachCoordinate(body: (x: Int, y: Int, l: Int) -> Unit) { var length = 0 body(segments[0].start.x, segments[0].start.y, 0) this.segments.forEach { s -> (1 .. s.length).forEach { i -> body( s.start.x + s.direction.dx * i, s.start.y + s.direction.dy * i, ++length ) } } } class Grid(val bounds: Bounds) { val width = bounds.xMax - bounds.xMin + 1 val height = bounds.yMax - bounds.yMin + 1 private val backing = LongArray(width * height) { 0 } fun get(x: Int, y: Int): Long { return getRaw(x - bounds.xMin, y - bounds.yMin) } fun getRaw(x: Int, y: Int): Long { return backing[(y)*width+(x)] } fun set(x: Int, y: Int, value: Long) { backing[(y-bounds.yMin)*width+(x-bounds.xMin)] = value } } enum class Direction(val dx: Int, val dy: Int) { U(0, -1), D(0, 1), L(-1, 0), R(1, 0) } val input by lazy { File("Day03.txt").readLines(Charsets.UTF_8) } val lines = input.mapIndexed { id, it -> val segments = it.split(",") var currentX = 0; var currentY = 0; Line(id, segments.map { val length = it.substring(1).toInt() val command = enumValueOf<Direction>(it.substring(0, 1)) LineSegment( start = Coord(currentX, currentY), end = Coord(currentX + command.dx * length, currentY + command.dy * length), direction = command, length = length ).also { currentX += command.dx * length currentY += command.dy * length } }) } require(lines.size == 2) val grid = Grid(lines.map { it.bounds() }.flatten()) val intersections = mutableListOf<Intersection>() lines.forEach { val lineValue = it.hashCode() it.forEachCoordinate { x, y, l -> val currentValue = grid.get(x, y) val currentLine = (currentValue shr 32).toInt() val currentLength = currentValue.toInt() if (currentLength != 0 && currentLine != lineValue) { intersections += Intersection(Coord(x, y), currentLength, l) } grid.set(x, y, (lineValue.toLong() shl 32) or l.toLong()) } } val closestIntersection = intersections .filter { it.coord.manhattan() != 0 } .minBy { it.coord.manhattan() }!! println("Assignment A: closest intersection @ ${closestIntersection.coord}, distance: ${closestIntersection.coord.manhattan()}") require(closestIntersection.coord.manhattan() == 316) val shortestPath = intersections .filter { it.coord.manhattan() != 0 } .minBy { it.lengthA + it.lengthB }!! println("Assignment B: shortest intersection @ ${shortestPath.coord}, length: ${shortestPath.lengthA + shortestPath.lengthB}") require(shortestPath.lengthA + shortestPath.lengthB == 16368)
0
Kotlin
0
0
bbeb2ee39fd13bd57cd6384d0a82f91227e4541f
3,762
AdventOfCode2019
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2021/d12/Day12.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2021.d12 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines private const val START = "start" private const val END = "end" private data class Path(val currCave: String, val visitedCaves: Set<String>, val repeatedSmallCave: Boolean) private fun findPaths(map: Map<String, Set<String>>, partTwo: Boolean): Int { val queue = ArrayDeque<Path>() // if partTwo = false, pretend we've already visited // a small cave twice queue.add(Path(START, setOf(START), !partTwo)) var count = 0 while (queue.isNotEmpty()) { val (currCave, visitedCaves, repeatedSmallCave) = queue.removeFirst() // all adjacent caves map[currCave]!! // If repeatedSmallCave = false, we do not need to filter out // previously visited small caves. // We'll handle setting this to true for repeated small caves below. .filter { !repeatedSmallCave || it !in visitedCaves } .forEach { nextCave -> if (nextCave == END) { // end of the line -- don't add any new paths to the queue // and increment the path count count++ } else { // only add this cave to set of visited caves if it is // a small cave val nextVisited = if (nextCave[0].isUpperCase()) visitedCaves else visitedCaves + nextCave // if this cave was previously visited, then we've used up // our one allowed small cave revisit val nextRepeatSmall = repeatedSmallCave || nextCave in visitedCaves queue.add(Path(nextCave, nextVisited, nextRepeatSmall)) } } } return count } fun main() = timed { val map = (DATAPATH / "2021/day12.txt").useLines { val ret = mutableMapOf<String, MutableSet<String>>() it.forEach { line -> val (a, b) = line.split("-", limit = 2) if (a !in ret.keys) { ret[a] = mutableSetOf() } // do not add any back connections to START // we will never return there if (b != START) { ret[a]!!.add(b) } if (b !in ret.keys) { ret[b] = mutableSetOf() } // do not add any back connections to START // we will never return there if (a != START) { ret[b]!!.add(a) } } ret } println("Part one: ${findPaths(map, partTwo = false)}") println("Part two: ${findPaths(map, partTwo = true)}") }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,827
advent-of-code
MIT License
src/Day13.kt
arksap2002
576,679,233
false
{"Kotlin": 31030}
enum class Type { RIGHT, UNKNOWN, WRONG } fun main() { fun stringToArray(s: String): MutableList<String> { val arr = mutableListOf<String>() var bal = 0 var currentString = "" for (i in s.indices) { if (s[i] == ',' && bal == 0) { arr.add(currentString) currentString = "" continue } if (s[i] == '[') { bal++ } if (s[i] == ']') { bal-- } currentString += s[i] } arr.add(currentString) return arr } fun run(first: String, second: String): Type { if (first[0] != '[') return run("[$first]", second) if (second[0] != '[') return run(first, "[$second]") val newFirst = first.substring(1, first.length - 1) val newSecond = second.substring(1, second.length - 1) if (newFirst.isEmpty() && newSecond.isEmpty()) return Type.UNKNOWN if (newFirst.isEmpty()) return Type.RIGHT if (newSecond.isEmpty()) return Type.WRONG if (newFirst.toIntOrNull() != null && newSecond.toIntOrNull() != null) { if (newFirst.toInt() == newSecond.toInt()) return Type.UNKNOWN if (newFirst.toInt() < newSecond.toInt()) return Type.RIGHT return Type.WRONG } val elementsFirst = stringToArray(newFirst) val elementsSecond = stringToArray(newSecond) for (i in elementsFirst.indices) { if (i == elementsSecond.size) return Type.WRONG val result = run(elementsFirst[i], elementsSecond[i]) if (result == Type.UNKNOWN) continue return result } if (elementsFirst.size == elementsSecond.size) return Type.UNKNOWN return Type.RIGHT } fun part1(input: List<String>): Int { var result = 0 var i = 0 while (i < input.size) { val x = run(input[i], input[i + 1]) if (x == Type.RIGHT) { result += i / 3 + 1 } i += 3 } return result } fun part2(input: List<String>): Int { val tmpInput: MutableList<String> = mutableListOf() for (s in input) { tmpInput.add(s) } tmpInput.add("[[2]]") tmpInput.add("[[6]]") val lines = tmpInput.filter { it.isNotEmpty() } val myCustomComparator = Comparator<String> { a, b -> when { run(a, b) == Type.UNKNOWN -> 0 run(a, b) == Type.RIGHT -> -1 else -> 1 } } val sortedLines = lines.sortedWith(myCustomComparator) var result = 1 for (i in sortedLines.indices) { if (sortedLines[i] == "[[2]]") result *= i + 1 if (sortedLines[i] == "[[6]]") result *= i + 1 } return result } val input = readInput("Day13") part1(input).println() part2(input).println() }
0
Kotlin
0
0
a24a20be5bda37003ef52c84deb8246cdcdb3d07
3,028
advent-of-code-kotlin
Apache License 2.0
yandex/y2022/finals/a_small.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package yandex.y2022.finals import java.util.* import kotlin.math.sign fun main() { readLn() val our = readInts() val their = readInts() val e = List(our.size) { i -> IntArray(their.size) { j -> -(our[i] - their[j]).sign } } val h = hungarian(e) println(-h) } fun hungarian(e: List<IntArray>): Int { val ans = IntArray(e.size) Arrays.fill(ans, -1) val infty = Int.MAX_VALUE / 3 var swap = false val n1 = e.size val n2 = e[0].size val u = IntArray(n1 + 1) val v = IntArray(n2 + 1) val p = IntArray(n2 + 1) val way = IntArray(n2 + 1) for (i in 1..n1) { p[0] = i var j0 = 0 val minv = IntArray(n2 + 1) Arrays.fill(minv, infty) val used = BooleanArray(n2 + 1) do { used[j0] = true val i0 = p[j0] var j1 = 0 var delta = infty for (j in 1..n2) { if (!used[j]) { val cur = e[i0 - 1][j - 1] - u[i0] - v[j] if (cur < minv[j]) { minv[j] = cur way[j] = j0 } if (minv[j] < delta) { delta = minv[j] j1 = j } } } for (j in 0..n2) { if (used[j]) { u[p[j]] += delta v[j] -= delta } else { minv[j] -= delta } } j0 = j1 } while (p[j0] != 0) do { val j1 = way[j0] p[j0] = p[j1] j0 = j1 } while (j0 > 0) } var sum = 0 for (j in 1..n2) { if (p[j] > 0) { // if (e[p[j] - 1][j - 1] >= infty) no matching of size n1; sum += e[p[j] - 1][j - 1]; if (swap) { ans[j - 1] = p[j] - 1 } else { ans[p[j] - 1] = j - 1 } } } return sum } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,678
competitions
The Unlicense
src/Day01.kt
nielsz
573,185,386
false
{"Kotlin": 12807}
fun main() { fun part1(input: List<String>): Int { return getLargestStack(input) } fun part2(input: List<String>): Int { return getStacks(input) .sortedDescending() .take(3) .sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) } private fun getLargestStack(input: List<String>): Int { var largest = 0 var currentStack = 0 for (line in input) { if (line.isNotEmpty()) { currentStack += line.toInt() } else { largest = maxOf(largest, currentStack) currentStack = 0 } } largest = maxOf(largest, currentStack) return largest } private fun getStacks(input: List<String>): List<Int> { val list = mutableListOf<Int>() var currentStack = 0 for (line in input) { if (line.isNotEmpty()) { currentStack += line.toInt() } else { list.add(currentStack) currentStack = 0 } } list.add(currentStack) return list }
0
Kotlin
0
0
05aa7540a950191a8ee32482d1848674a82a0c71
1,084
advent-of-code-2022
Apache License 2.0
advent2022/src/main/kotlin/year2022/Day04.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay fun parseAssignment(input: String): Pair<IntRange, IntRange> { val (a, b) = input.split(",") return a.parsePair() to b.parsePair() } private fun String.parsePair(): IntRange { val (a, b) = split("-") return a.toInt() .. b.toInt() } infix fun IntRange.contains(other: IntRange): Boolean = first <= other.first && other.last <= last /* 5-7,7-9 overlaps in a single section, 7. 2-8,3-7 overlaps all the sections 3 through 7. 6-6,4-6 overlaps in a single section, 6. 2-6,4-8 */ infix fun IntRange.overlap(other: IntRange): Boolean = other.first in this || other.last in this || first in other || last in other class Day04 : AdventDay(2022, 4) { override fun part1(input: List<String>) = input.count { val (a, b) = parseAssignment(it) a contains b || b contains a } override fun part2(input: List<String>) = input.count { val (a, b) = parseAssignment(it) a overlap b } } fun main() = Day04().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
1,056
advent-of-code
Apache License 2.0
src/Day01.kt
dmarmelo
573,485,455
false
{"Kotlin": 28178}
fun main() { fun List<String>.parseInput(): List<List<Int>> { var rest = this return buildList { while (rest.isNotEmpty()) { val elfInventory = rest.takeWhile { it.isNotBlank() }.map { it.toInt() } add(elfInventory) rest = if (elfInventory.size == rest.size) emptyList() else rest.subList(elfInventory.size + 1, rest.size) } } } fun part1(elfInventories: List<List<Int>>): Int { return elfInventories.maxOf { it.sum() } } fun part2(elfInventories: List<List<Int>>): Int { return elfInventories .map { it.sum() } .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test").parseInput() check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01").parseInput() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5d3cbd227f950693b813d2a5dc3220463ea9f0e4
1,084
advent-of-code-2022
Apache License 2.0
src/Day25.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
import java.io.File import kotlin.math.pow // Advent of Code 2022, Day 25: Full of Hot Air class Day25(input: String) { private val lines: List<String> init { lines = input.split("\n").filter { it.isNotEmpty() } } private fun snafuToDec(input: String) : Long { return input.reversed().foldIndexed(0L) { idx, sum, c -> when (c) { '0' -> sum '1' -> sum + 5.0.pow((idx).toDouble()).toLong() '2' -> sum + 2 * 5.0.pow((idx).toDouble()).toLong() '-' -> sum - 5.0.pow((idx).toDouble()).toLong() '=' -> sum - 2 * 5.0.pow((idx).toDouble()).toLong() else -> throw Exception("bad char in SNAFU number: $c in $input") } } } private fun decToSnafu(input: Long) : String { var numInput = input val numOut = mutableListOf<Char>() do { val rem = numInput % 5 numOut.add(0, rem.toString().first()) numInput -= rem numInput /= 5 } while (numInput != 0L) val blah = mutableListOf<Char>() var carry = 0 numOut.reversed().forEach { c -> var d = c + carry carry = 0 if (d == '5') { d = '0' carry = 1 } blah.add( when (d) { '0' -> '0' '1' -> '1' '2' -> '2' '3' -> { carry = 1 '=' } '4' -> { carry = 1 '-' } else -> throw Exception("bad char $c") } ) } if (carry == 1 ) { blah.add('1') } return blah.reversed().joinToString(separator = "") } fun part1(): String { val decNumbers = lines.map { snafuToDec(it) } return decToSnafu(decNumbers.sum()) } } fun main() { fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText() val testSolver = Day25(readInputAsOneLine("Day25_test")) check(testSolver.part1()=="2=-1=0") val solver = Day25(readInputAsOneLine("Day25")) println(solver.part1()) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
2,366
AdventOfCode2022
Apache License 2.0
src/day25/Day25.kt
ritesh-singh
572,210,598
false
{"Kotlin": 99540}
package day25 import readInput import kotlin.math.pow // Only part 1 is done, as all previous stars are needed for part2 fun main() { fun convertToDecimal(lines: List<String>): Long { var total = 0L lines.forEach { var decimal = 0L it.forEachIndexed { index, c -> when { c.isDigit() -> { decimal += c.digitToInt() * 5.0.pow(it.length - 1 - index).toLong() } c == '-' -> { decimal += -1 * 5.0.pow(it.length - 1 - index).toLong() } c == '=' -> { decimal += -2 * 5.0.pow(it.length - 1 - index).toLong() } } } total += decimal } return total } fun convertToSNAFU(decimal: Long):String { fun convertToBase5():String { val base5 = StringBuilder() var number = decimal while (number > 0L){ base5.append(number.mod(5)) number /= 5 } return base5.toString().reversed() } var base5 = convertToBase5() for(idx in base5.length-1 downTo 0){ when { base5[idx] == '3' -> { if (idx == 0){ base5 = base5.replaceRange(idx..idx,"1=") continue } base5 = base5.replaceRange(idx..idx,"=") base5 = base5.replaceRange(idx-1 until idx,(base5[idx-1].digitToInt()+1).toString()) } base5[idx] == '4' -> { if (idx == 0){ base5 = base5.replaceRange(idx..idx,"1-") continue } base5 = base5.replaceRange(idx..idx,"-") base5 = base5.replaceRange(idx-1 until idx,(base5[idx-1].digitToInt()+1).toString()) } base5[idx].digitToInt() > 4 -> { if (idx == 0){ base5 = base5.replaceRange(idx..idx,"10") continue } base5 = base5.replaceRange(idx..idx,"0") base5 = base5.replaceRange(idx-1 until idx,(base5[idx-1].digitToInt()+1).toString()) } } } return base5 } fun solve1(lines: List<String>): String { val decimal = convertToDecimal(lines) return convertToSNAFU(decimal) } fun solve2(lines: List<String>): Int { return 0 } val testInput = readInput("/day25/Day25_test") println(solve1(testInput)) // println(solve2(testInput)) println("--------------------------------------") val input = readInput("/day25/Day25") println(solve1(input)) // println(solve2(input)) }
0
Kotlin
0
0
17fd65a8fac7fa0c6f4718d218a91a7b7d535eab
2,970
aoc-2022-kotlin
Apache License 2.0
src/test/kotlin/com/igorwojda/list/minsublistlength/Solution.kt
igorwojda
159,511,104
false
{"Kotlin": 254856}
package com.igorwojda.list.minsublistlength // Time complexity: O(n) // Space complexity O(n) // Use sliding window private object Solution1 { fun minSubListLength(list: List<Int>, sum: Int): Int { var total = 0 var start = 0 var end = 0 var minLen: Int? = null while (start < list.size) { // if current window doesn't add up to the given numElements then move the window to right if (total < sum && end < list.size) { total += list[end] end++ } // if current window adds up to at least the numElements given then we can shrink the window else if (total >= sum) { minLen = min(minLen, end - start) total -= list[start] start++ } // current total less than required total but we reach the end, need this or else we'll be in an infinite loop else { break } } return minLen ?: 0 } private fun min(i1: Int?, i2: Int?): Int? { return when { i1 != null && i2 != null -> Math.min(i1, i2) i1 != null && i2 == null -> i1 i1 == null && i2 != null -> i2 else -> null } } } // Time complexity: O(n^2) // Loop through all the elements and then loop through all sublists private object Solution2 { fun minSubListLength(list: List<Int>, sum: Int): Int { var minListLength: Int? = null repeat(list.size) { index -> var subListSum = 0 var numItems = 0 val subList = list.subList(index, list.size) for (item in subList) { subListSum += item numItems++ if (subListSum >= sum) { minListLength = min(minListLength, numItems) break } } } return minListLength ?: 0 } private fun min(i1: Int?, i2: Int?): Int? { return when { i1 != null && i2 != null -> Math.min(i1, i2) i1 != null && i2 == null -> i1 i1 == null && i2 != null -> i2 else -> null } } } // Solution without use a private fun min private object Solution3 { fun minSubListLength(list: List<Int>, sum: Int): Int { if (list.isEmpty()) return 0 var length = 1 while (length < list.size + 1) { val proposal = list.windowed(length) .toMutableList() .map { it.sum() } .filter { it >= sum } if (proposal.isNotEmpty()) { break } else { length++ } } if (length > list.size) length = 0 return length } } private object KtLintWillNotComplain
9
Kotlin
225
895
b09b738846e9f30ad2e9716e4e1401e2724aeaec
2,887
kotlin-coding-challenges
MIT License
src/Day03.kt
Vlisie
572,110,977
false
{"Kotlin": 31465}
import java.io.File fun main() { fun commonChar(s1: String, s2: String): Char { for (i in s1.indices) { for (element in s2) { if (s1[i] == element) { return s1[i] } } } return ' ' } fun commonChar2(s1: String, s2: String, s3: String): Char { for (i in s1.indices) { for (element in s2) { if (s1[i] == element) { for (element1 in s3) { if (s1[i] == element1) { return s1[i] } } } } } return ' ' } fun valueOfChar(commonChar: Char): Int { return if (commonChar.isLowerCase()) { commonChar.code - 96 } else { commonChar.code - 38 } } fun part1(file: File): Int = file .readText() .trimEnd() .split("\n".toRegex()) .map { val helft = it.length / 2 it.split("(?<=\\G.{$helft})".toRegex()).toTypedArray() } .map { element -> valueOfChar(commonChar(element[0], element[1])) } .sum() fun part2(file: File): Int { val lijst = ArrayList<String>() var som = 0 file.readText() .trimEnd() .split("\n".toRegex()) .mapIndexed { idx, element -> if ((idx + 1) % 3 == 0) { lijst.add(element) som += valueOfChar(commonChar2(lijst[0], lijst[1], lijst[2])) lijst.clear() } else { lijst.add(element) } } return som } // test if implementation meets criteria from the description, like: val testInput = File("src", "input/testInput.txt") check(part2(testInput) == 70) val input = File("src", "input/input3.txt") println(part2(input)) }
0
Kotlin
0
0
b5de21ed7ab063067703e4adebac9c98920dd51e
2,029
AoC2022
Apache License 2.0
src/Day09.kt
ty-garside
573,030,387
false
{"Kotlin": 75779}
// Day 09 - Rope Bridge // https://adventofcode.com/2022/day/9 import Direction.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sign fun main() { var debug = true data class Position( val x: Int, val y: Int ) data class Move( val dir: Direction, val times: Int ) fun Iterable<Position>.debugString(char: Char? = null): String { val rev = reversed() val xMin = min(0, rev.minOf { it.x }) - 1 val xMax = max(0, rev.maxOf { it.x }) + 1 val yMin = min(0, rev.minOf { it.y }) - 1 val yMax = max(0, rev.maxOf { it.y }) + 1 val map = List(yMax - yMin + 1) { MutableList(xMax - xMin + 1) { '.' } } map[0 - yMin][0 - xMin] = 's' val last = rev.size - 1 rev.forEachIndexed { i, it -> map[it.y - yMin][it.x - xMin] = char ?: when { i == 0 -> 'H' i == last -> 'T' i < 10 -> '0' + i else -> 'A' + (i - 10 % 26) } } return map.joinToString("\n") { it.joinToString("") } } class Rope( size: Int ) { val knots = MutableList(size) { Position(0, 0) } fun move(dir: Direction) { with(knots[0]) { knots[0] = when (dir) { Up -> copy(y = y - 1) Down -> copy(y = y + 1) Left -> copy(x = x - 1) Right -> copy(x = x + 1) } } for (i in 1 until knots.size) { val prv = knots[i - 1] val cur = knots[i] val dx = prv.x - cur.x val dy = prv.y - cur.y if (max(abs(dx), abs(dy)) > 1) { knots[i] = Position( cur.x + if (dx == 0) 0 else dx.sign, cur.y + if (dy == 0) 0 else dy.sign ) } } } override fun toString() = knots.debugString() } fun List<String>.parse() = map { val (dir, times) = it.trim().split(' ') Move( when (dir) { "U" -> Up "D" -> Down "L" -> Left "R" -> Right else -> error("Invalid: $it") }, times.toInt() ) } fun countUniqueTailPositions(rope: Rope, moves: List<Move>): Int { val positions = mutableSetOf<Position>() if(debug) { println(rope) } for (move in moves) { if(debug) { println(move) } repeat(move.times) { rope.move(move.dir) positions += rope.knots.last() } if(debug) { println(rope) } } if(debug) { println("=".repeat(30)) println(positions.debugString('#')) println("=".repeat(30)) } return positions.size } fun part1(input: List<String>): Int { return countUniqueTailPositions(Rope(2), input.parse()) } fun part2(input: List<String>): Int { return countUniqueTailPositions(Rope(10), input.parse()) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) val testInput2 = readInput("Day09_test2") check(part2(testInput2) == 36) debug = false val input = readInput("Day09") println(part1(input)) println(part2(input)) } /* --- Day 9: Rope Bridge --- This rope bridge creaks as you walk along it. You aren't sure how old it is, or whether it can even support your weight. It seems to support the Elves just fine, though. The bridge spans a gorge which was carved out by the massive river far below you. You step carefully; as you do, the ropes stretch and twist. You decide to distract yourself by modeling rope physics; maybe you can even figure out where not to step. Consider a rope with a knot at each end; these knots mark the head and the tail of the rope. If the head moves far enough away from the tail, the tail is pulled toward the head. Due to nebulous reasoning involving Planck lengths, you should be able to model the positions of the knots on a two-dimensional grid. Then, by following a hypothetical series of motions (your puzzle input) for the head, you can determine how the tail will move. Due to the aforementioned Planck lengths, the rope must be quite short; in fact, the head (H) and tail (T) must always be touching (diagonally adjacent and even overlapping both count as touching): .... .TH. .... .... .H.. ..T. .... ... .H. (H covers T) ... If the head is ever two steps directly up, down, left, or right from the tail, the tail must also move one step in that direction so it remains close enough: ..... ..... ..... .TH.. -> .T.H. -> ..TH. ..... ..... ..... ... ... ... .T. .T. ... .H. -> ... -> .T. ... .H. .H. ... ... ... Otherwise, if the head and tail aren't touching and aren't in the same row or column, the tail always moves one step diagonally to keep up: ..... ..... ..... ..... ..H.. ..H.. ..H.. -> ..... -> ..T.. .T... .T... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..H.. -> ...H. -> ..TH. .T... .T... ..... ..... ..... ..... You just need to work out where the tail goes as the head follows a series of motions. Assume the head and the tail both start at the same position, overlapping. For example: R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2 This series of motions moves the head right four steps, then up four steps, then left three steps, then down one step, and so on. After each step, you'll need to update the position of the tail if the step means the head is no longer adjacent to the tail. Visually, these motions occur as follows (s marks the starting position as a reference point): == Initial State == ...... ...... ...... ...... H..... (H covers T, s) == R 4 == ...... ...... ...... ...... TH.... (T covers s) ...... ...... ...... ...... sTH... ...... ...... ...... ...... s.TH.. ...... ...... ...... ...... s..TH. == U 4 == ...... ...... ...... ....H. s..T.. ...... ...... ....H. ....T. s..... ...... ....H. ....T. ...... s..... ....H. ....T. ...... ...... s..... == L 3 == ...H.. ....T. ...... ...... s..... ..HT.. ...... ...... ...... s..... .HT... ...... ...... ...... s..... == D 1 == ..T... .H.... ...... ...... s..... == R 4 == ..T... ..H... ...... ...... s..... ..T... ...H.. ...... ...... s..... ...... ...TH. ...... ...... s..... ...... ....TH ...... ...... s..... == D 1 == ...... ....T. .....H ...... s..... == L 5 == ...... ....T. ....H. ...... s..... ...... ....T. ...H.. ...... s..... ...... ...... ..HT.. ...... s..... ...... ...... .HT... ...... s..... ...... ...... HT.... ...... s..... == R 2 == ...... ...... .H.... (H covers T) ...... s..... ...... ...... .TH... ...... s..... After simulating the rope, you can count up all of the positions the tail visited at least once. In this diagram, s again marks the starting position (which the tail also visited) and # marks other positions the tail visited: ..##.. ...##. .####. ....#. s###.. So, there are 13 positions the tail visited at least once. Simulate your complete hypothetical series of motions. How many positions does the tail of the rope visit at least once? Your puzzle answer was 6406. --- Part Two --- A rope snaps! Suddenly, the river is getting a lot closer than you remember. The bridge is still there, but some of the ropes that broke are now whipping toward you as you fall through the air! The ropes are moving too quickly to grab; you only have a few seconds to choose how to arch your body to avoid being hit. Fortunately, your simulation can be extended to support longer ropes. Rather than two knots, you now must simulate a rope consisting of ten knots. One knot is still the head of the rope and moves according to the series of motions. Each knot further down the rope follows the knot in front of it using the same rules as before. Using the same series of motions as the above example, but with the knots marked H, 1, 2, ..., 9, the motions now occur as follows: == Initial State == ...... ...... ...... ...... H..... (H covers 1, 2, 3, 4, 5, 6, 7, 8, 9, s) == R 4 == ...... ...... ...... ...... 1H.... (1 covers 2, 3, 4, 5, 6, 7, 8, 9, s) ...... ...... ...... ...... 21H... (2 covers 3, 4, 5, 6, 7, 8, 9, s) ...... ...... ...... ...... 321H.. (3 covers 4, 5, 6, 7, 8, 9, s) ...... ...... ...... ...... 4321H. (4 covers 5, 6, 7, 8, 9, s) == U 4 == ...... ...... ...... ....H. 4321.. (4 covers 5, 6, 7, 8, 9, s) ...... ...... ....H. .4321. 5..... (5 covers 6, 7, 8, 9, s) ...... ....H. ....1. .432.. 5..... (5 covers 6, 7, 8, 9, s) ....H. ....1. ..432. .5.... 6..... (6 covers 7, 8, 9, s) == L 3 == ...H.. ....1. ..432. .5.... 6..... (6 covers 7, 8, 9, s) ..H1.. ...2.. ..43.. .5.... 6..... (6 covers 7, 8, 9, s) .H1... ...2.. ..43.. .5.... 6..... (6 covers 7, 8, 9, s) == D 1 == ..1... .H.2.. ..43.. .5.... 6..... (6 covers 7, 8, 9, s) == R 4 == ..1... ..H2.. ..43.. .5.... 6..... (6 covers 7, 8, 9, s) ..1... ...H.. (H covers 2) ..43.. .5.... 6..... (6 covers 7, 8, 9, s) ...... ...1H. (1 covers 2) ..43.. .5.... 6..... (6 covers 7, 8, 9, s) ...... ...21H ..43.. .5.... 6..... (6 covers 7, 8, 9, s) == D 1 == ...... ...21. ..43.H .5.... 6..... (6 covers 7, 8, 9, s) == L 5 == ...... ...21. ..43H. .5.... 6..... (6 covers 7, 8, 9, s) ...... ...21. ..4H.. (H covers 3) .5.... 6..... (6 covers 7, 8, 9, s) ...... ...2.. ..H1.. (H covers 4; 1 covers 3) .5.... 6..... (6 covers 7, 8, 9, s) ...... ...2.. .H13.. (1 covers 4) .5.... 6..... (6 covers 7, 8, 9, s) ...... ...... H123.. (2 covers 4) .5.... 6..... (6 covers 7, 8, 9, s) == R 2 == ...... ...... .H23.. (H covers 1; 2 covers 4) .5.... 6..... (6 covers 7, 8, 9, s) ...... ...... .1H3.. (H covers 2, 4) .5.... 6..... (6 covers 7, 8, 9, s) Now, you need to keep track of the positions the new tail, 9, visits. In this example, the tail never moves, and so it only visits 1 position. However, be careful: more types of motion are possible than before, so you might want to visually compare your simulated rope to the one above. Here's a larger example: R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20 These motions occur as follows (individual steps are not shown): == Initial State == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ...........H.............. (H covers 1, 2, 3, 4, 5, 6, 7, 8, 9, s) .......................... .......................... .......................... .......................... .......................... == R 5 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ...........54321H......... (5 covers 6, 7, 8, 9, s) .......................... .......................... .......................... .......................... .......................... == U 8 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... ................H......... ................1......... ................2......... ................3......... ...............54......... ..............6........... .............7............ ............8............. ...........9.............. (9 covers s) .......................... .......................... .......................... .......................... .......................... == L 8 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... ........H1234............. ............5............. ............6............. ............7............. ............8............. ............9............. .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... .......................... == D 3 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .........2345............. ........1...6............. ........H...7............. ............8............. ............9............. .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... .......................... == R 17 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ................987654321H .......................... .......................... .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... .......................... == D 10 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ...........s.........98765 .........................4 .........................3 .........................2 .........................1 .........................H == L 25 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... H123456789................ == U 20 == H......................... 1......................... 2......................... 3......................... 4......................... 5......................... 6......................... 7......................... 8......................... 9......................... .......................... .......................... .......................... .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... .......................... Now, the tail (9) visits 36 positions (including s) at least once: .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... #......................... #.............###......... #............#...#........ .#..........#.....#....... ..#..........#.....#...... ...#........#.......#..... ....#......s.........#.... .....#..............#..... ......#............#...... .......#..........#....... ........#........#........ .........########......... Simulate your complete series of motions on a larger rope with ten knots. How many positions does the tail of the rope visit at least once? Your puzzle answer was 2643. Both parts of this puzzle are complete! They provide two gold stars: ** */
0
Kotlin
0
0
49ea6e3ad385b592867676766dafc48625568867
16,885
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/org/sjoblomj/adventofcode/day2/Day2.kt
sjoblomj
225,241,573
false
null
package org.sjoblomj.adventofcode.day2 import org.sjoblomj.adventofcode.readFile private const val OPCODE_ADD = 1 private const val OPCODE_MUL = 2 private const val OPCODE_EXIT = 99 private const val WANTED_OUTPUT = 19690720 private const val inputFile = "src/main/resources/inputs/day2.txt" fun day2(): Pair<Int, Int> { val content = readFile(inputFile)[0].toIntList() val program = initializeProgram(content, 12, 2) val programOutput = calculateProgramOutput(program) println("The program output is $programOutput") val (noun, verb) = findInputPair(content, WANTED_OUTPUT) val nounAndVerbCalculation = nounAndVerbCalculation(noun, verb) println("The noun and verb producing $WANTED_OUTPUT is $nounAndVerbCalculation") return Pair(programOutput, nounAndVerbCalculation) } internal fun nounAndVerbCalculation(noun: Int, verb: Int) = 100 * noun + verb internal fun initializeProgram(content: List<Int>, noun: Int, verb: Int) = listOf(content[0], noun, verb) .plus(content.subList(3, content.size)) internal fun calculateProgramOutput(program: List<Int>) = calculateOpcodes(program.toMutableList())[0] internal fun calculateOpcodes(prg: MutableList<Int>): List<Int> { loop@ for (ip in (0 until prg.size) step 4) { when { prg[ip] == OPCODE_ADD -> prg[prg[ip + 3]] = prg[prg[ip + 1]] + prg[prg[ip + 2]] prg[ip] == OPCODE_MUL -> prg[prg[ip + 3]] = prg[prg[ip + 1]] * prg[prg[ip + 2]] prg[ip] == OPCODE_EXIT -> break@loop else -> throw IllegalArgumentException("Unexpected data at position $ip: ${prg[ip]}") } } return prg } internal fun findInputPair(input: List<Int>, wantedOutput: Int, maxValue: Int = 100): Pair<Int, Int> { for (noun in (0 until maxValue)) { for (verb in (0 until maxValue)) { val program = initializeProgram(input, noun, verb) if (calculateProgramOutput(program) == wantedOutput) { return noun to verb } } } throw RuntimeException("Failed to find wanted noun and verb") } internal fun String.toIntList() = this .split(",") .map { it.toInt() }
0
Kotlin
0
0
f8d03f7ef831bc7e26041bfe7b1feaaadcb40e68
2,046
adventofcode2019
MIT License
src/Day05.kt
jdpaton
578,869,545
false
{"Kotlin": 10658}
fun main() { fun part1(reversed: Boolean = false) { val testInput = readInput("Day05_test") val stacks = mapStacks(testInput) testInput.filter { it.startsWith("move") }.forEach { val moveSpl = it.split(" ") val numberOfCratesToMove = moveSpl[1].toInt() check(moveSpl[2] == "from") val fromColumn = moveSpl[3].toInt() check(moveSpl[4] == "to") val toColumn = moveSpl[5].toInt() val stacksMoving: MutableList<String?> = mutableListOf() for(i in 1..numberOfCratesToMove){ stacksMoving.add( stacks[fromColumn] ?.removeLast() .toString() ) } if(reversed) { stacksMoving .reversed().forEach { crate -> stacks[toColumn] ?.addLast(crate.toString()) } } else { stacksMoving .forEach { crate -> stacks[toColumn] ?.addLast(crate.toString()) } } } val output = stacks .map { stack -> stack.value.last() } .joinToString("") println(output) } fun part2() { part1(reversed = true)} part1() part2() } fun mapStacks(input: List<String>): Map<Int,ArrayDeque<String>>{ val stacks: MutableMap<Int,ArrayDeque<String>> = mutableMapOf() input.filter{it.startsWith('[')}.map { val lineFormatted = it.replace(" ", " [] ") val iter = lineFormatted.iterator() var column = 1 while(iter.hasNext()) { val char = iter.next().toString() if( char == "[") { if(iter.hasNext()) { if(stacks[column] == null) { stacks[column] = ArrayDeque() } val nextChar = iter.next().toString() if(nextChar != "]") { stacks[column]?.addFirst(nextChar) } else { column += 1 } } } else if(char == "]") { column += 1 } } } return stacks }
0
Kotlin
0
0
f6738f72e2a6395815840a13dccf0f6516198d8e
2,300
aoc-2022-in-kotlin
Apache License 2.0
src/Day04.kt
NunoPontes
572,963,410
false
{"Kotlin": 7416}
fun main() { fun part1(input: List<String>): Int { return input.map { it -> it.split(",", "-").map { it.toInt() } }.count { val (first, second, third, fourth) = it (first in third..fourth && second in third..fourth) || (third in first..second && fourth in first..second) } } fun part2(input: List<String>): Int { return input.map { it -> it.split(",", "-").map { it.toInt() } }.count { val (first, second, third, fourth) = it (first in third..fourth || second in third..fourth) || (third in first..second || fourth in first..second) } } val inputPart1 = readInput("Day04_part1") val inputPart2 = readInput("Day04_part2") println(part1(inputPart1)) println(part2(inputPart2)) }
0
Kotlin
0
0
78b67b952e0bb51acf952a7b4b056040bab8b05f
794
advent-of-code-2022
Apache License 2.0
src/year_2021/day_07/Day07.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2021.day_07 import readInput import kotlin.math.abs object Day07 { /** * @return */ fun solutionOne(text: String): Int { val positions = parsePositions(text) val minPosition = positions.min() val maxPosition = positions.max() var minFuel = Integer.MAX_VALUE for (i in minPosition..maxPosition) { val fuel = positions.sumOf { abs(it - i) } if (fuel < minFuel) { minFuel = fuel } } return minFuel } /** * @return */ fun solutionTwo(text: String): Int { val positions = parsePositions(text) val minPosition = positions.min() val maxPosition = positions.max() var minFuel = Integer.MAX_VALUE for (i in minPosition..maxPosition) { val fuel = positions.sumOf { val n = abs(it - i) var sum = 0 for (i in 1..n) { sum += i } sum } if (fuel < minFuel) { minFuel = fuel } } return minFuel } private fun parsePositions(text: String): List<Int> { return text.split(",").map { Integer.parseInt(it) }.sorted() } } fun main() { val inputText = readInput("year_2021/day_07/Day08.txt").first() val solutionOne = Day07.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day07.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
1,576
advent_of_code
Apache License 2.0
src/main/kotlin/days/Day10.kt
hughjdavey
159,955,618
false
null
package days import util.scan class Day10 : Day(10) { // move these here instead of in each part to save calculation time private val seq = (0..100000).asSequence().scan(0 to parsePoints(inputList)) { (_, points), i -> i + 1 to points.map { moveOneSecond(it) } } private val minDistPoints = seq.minBy { getMaxDistanceBetweenPoints(it.second) } override fun partOne(): Any { return drawOnGrid(minDistPoints!!.second) } override fun partTwo(): Any { return minDistPoints!!.first } data class LightPoint(private val initialPosition: Pair<Int, Int>, val velocity: Pair<Int, Int>) { var position = initialPosition } companion object { fun getMaxDistanceBetweenPoints(points: List<LightPoint>): Int { val positions = points.map { it.position } return Math.max( positions.map { it.first }.max()!! - positions.map { it.first }.min()!!, positions.map { it.second }.max()!! - positions.map { it.second }.min()!! ) } fun drawOnGrid(points: List<LightPoint>): String { val positions = points.map { it.position } val minX = positions.minBy { it.first }!!.first val maxX = positions.maxBy { it.first }!!.first val minY = positions.minBy { it.second }!!.second val maxY = positions.maxBy { it.second }!!.second val xExtent = maxX - minX val yExtent = maxY - minY val grid = Array(yExtent + 1) { Array(xExtent + 1) { '.' } } points.forEach { grid[it.position.second - minY][it.position.first - minX] = '#' } val s = StringBuilder() for (y in 0..yExtent) { s.append('\n') for (x in 0..xExtent) { s.append(grid[y][x]).append(" ") } } return s.toString() } fun moveOneSecond(point: LightPoint): LightPoint { return LightPoint( point.position.first + point.velocity.first to point.position.second + point.velocity.second, point.velocity ) } fun parsePoints(input: List<String>): List<LightPoint> { return input.map { val position = parsePair(it, it.indexOf('<') + 1, it.indexOf('>')) val velocity = parsePair(it, it.lastIndexOf('<') + 1, it.lastIndexOf('>')) LightPoint(position, velocity) } } private fun parsePair(string: String, start: Int, end: Int): Pair<Int, Int> { return string.substring(start, end).split(',').map { it.trim().toInt() }.zipWithNext().first() } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
2,762
aoc-2018
Creative Commons Zero v1.0 Universal
aoc-day5/src/Day5.kt
rnicoll
438,043,402
false
{"Kotlin": 90620, "Rust": 1313}
import java.nio.file.Files import java.nio.file.Path import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.streams.toList fun main() { val file = Path.of("input") val lines = Files.lines(file).map { line -> parseLine(line) }.toList() part1(lines) part2(lines) } fun part1(lines: Iterable<Line>) { val seenOnce = mutableSetOf<Coord>() val seenTwice = mutableSetOf<Coord>() lines.filter { it.from.x == it.to.x || it.from.y == it.to.y }.forEach { line -> getCoords(line.from, line.to).forEach { if (!seenOnce.add(it)) { seenTwice.add(it) } } } println("Part 1: ${seenTwice.count()}") } fun part2(lines: Iterable<Line>) { val seenOnce = mutableSetOf<Coord>() val seenTwice = mutableSetOf<Coord>() lines.forEach { line -> getCoords2(line.from, line.to).forEach { coord -> if (!seenOnce.add(coord)) { seenTwice.add(coord) } } } println("Part 2: ${seenTwice.count()}") } fun getCoords(from: Coord, to: Coord): Iterable<Coord> { val coords = mutableListOf<Coord>() when { (from.y == to.y) -> { for (x in min(from.x, to.x)..max(from.x, to.x)) { coords.add(Coord(x, from.y)) } } (from.x == to.x) -> { for (y in min(from.y, to.y)..max(from.y, to.y)) { coords.add(Coord(from.x, y)) } } else -> { throw Exception("Invalid line") } } return coords } fun getCoords2(from: Coord, to: Coord): Iterable<Coord> { val coords = mutableListOf<Coord>() val distanceX = abs(from.x - to.x) val distanceY = abs(from.y - to.y) val delta = max(distanceX, distanceY) val deltaX = (to.x - from.x) / delta val deltaY = (to.y - from.y) / delta for (i in 0..delta) { coords.add(Coord(from.x + (i * deltaX), from.y + (i * deltaY))) } return coords } fun parseLine(input: String): Line { val parts = input.split(" ") assert(parts.size == 3) return Line(Coord.parse(parts[0]), Coord.parse(parts[2])) } data class Coord(val x: Int, val y: Int): Comparable<Coord> { companion object { fun parse(input: String) = input.split(",").let { Coord(it[0].toInt(), it[1].toInt()) } } override fun toString(): String { return "$x,$y" } override fun compareTo(other: Coord): Int { return (this.x - other.x) - (this.y - other.y); } } data class Line(val from: Coord, val to: Coord) { override fun toString(): String { return "$from -> $to" } }
0
Kotlin
0
0
8c3aa2a97cb7b71d76542f5aa7f81eedd4015661
2,729
adventofcode2021
MIT License
src/Day01.kt
colmmurphyxyz
572,533,739
false
{"Kotlin": 19871}
import java.util.* fun main() { fun getInput(): List<Int> { val input = readInput("Day01") val elfCaloriesString = mutableListOf<List<String>>() var sliceStart = 0 for (i in input.indices) { if (i == input.lastIndex) { elfCaloriesString.add(input.slice(sliceStart..i)) break } if (input[i] == "") { elfCaloriesString.add(input.slice(sliceStart until i)) sliceStart = i + 1 } } // convert the strings to ints val elfCalories: List<List<Int>> = elfCaloriesString.map { it: List<String> -> it.map { str: String -> str.toInt() } } // get and return the sum of each inner list return elfCalories.map { it -> it.sum() } } fun part1(): Int { return getInput().max() } fun part2(): Int { val totalElfCalories = getInput() val top3Calories = intArrayOf(-1, -2, -3) for (cals in totalElfCalories) { if (cals > top3Calories[2]) { top3Calories[2] = cals if (top3Calories[2] > top3Calories[1]) { top3Calories.swap(2, 1) } if (top3Calories[1] > top3Calories[0]) { top3Calories.swap(1, 0) } } } println(top3Calories.joinToString(", ")) return top3Calories.sum() } println("Part 1 answer: ${part1()}") println("Part 2 answer: ${part2()}") // if (cals > top3Calories[0]) { // top3Calories[2] = top3Calories[1] // top3Calories[1] = top3Calories[0] // top3Calories[0] = cals // } else if (cals > top3Calories[1]) { // top3Calories[2] = top3Calories[1] // top3Calories[1] = cals // } else if (cals > top3Calories[2]) { // top3Calories[2] = cals // } // } }
0
Kotlin
0
0
c5653691ca7e64a0ee7f8e90ab1b450bcdea3dea
1,965
aoc-2022
Apache License 2.0
src/main/kotlin/io/dp/ExpressionAddOperator.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.dp import io.utils.runTests import java.util.* import java.util.function.Consumer // https://leetcode.com/problems/expression-add-operators/ class ExpressionAddOperator { fun execute(input: String, target: Int): List<String> = helperRecursion(input).filter { evaluate(it) == target } private fun evaluate(input: String, i: Int = input.lastIndex): Int? { var accum = 0 var index = i loop@ while (index in input.indices) { when (input[index]) { '+' -> return evaluate(input, index - 1)?.let { it + accum } '-' -> return evaluate(input, index - 1)?.let { it - accum } '*' -> { readInteger(input, index - 1)?.let { (number, newIndex) -> accum *= number index = newIndex } ?: return null } else -> { readInteger(input, index)?.let { (number, newIndex) -> accum = number index = newIndex } ?: return null } } } return accum } private fun readInteger(input: String, index: Int): Pair<Int, Int>? { var accum = "" var currentIndex = index while (currentIndex >= 0 && input[currentIndex].isDigit()) { accum = input[currentIndex] + accum currentIndex-- } return accum.toIntOrNull()?.let { it to currentIndex } } private fun helperRecursion(input: String, index: Int = 0, dp: MutableMap<Int, List<String>> = mutableMapOf()): List<String> { if (input.isEmpty()) return emptyList() if (dp.contains(index)) return dp.getValue(index) if (index == input.lastIndex) return listOf(input[index].toString()).also { dp[index] = it } val value = input[index].toString().toInt() return helperRecursion(input, index + 1, dp) .flatMap { result -> when (value) { 0 -> listOf(sum(result, value), minus(result, value), plus(result, value)) else -> listOf(sum(result, value), minus(result, value), add(result, value), plus(result, value)) } } .also { dp[index] = it } } fun sum(accum: String, value: Int) = "$value+$accum" fun minus(accum: String, value: Int) = "$value-$accum" fun add(accum: String, value: Int) = "$value$accum" fun plus(accum: String, value: Int): String = "$value*$accum" // https://leetcode.com/problems/expression-add-operators/solution/ lateinit var answer: ArrayList<String> var digits: String? = null var target: Long = 0 fun recurse( index: Int, previousOperand: Long, operand: Long, value: Long, ops: ArrayList<String>) { var currentOperand = operand val nums = digits // Done processing all the digits in num if (index == nums!!.length) { // If the final value == target expected AND // no operand is left unprocessed if (value == target && currentOperand == 0L) { val sb = StringBuilder() ops.subList(1, ops.size).forEach(Consumer { v: String? -> sb.append(v) }) answer.add(sb.toString()) } return } // Extending the current operand by one digit currentOperand = currentOperand * 10 + Character.getNumericValue(nums[index]) val currentValRep = java.lang.Long.toString(currentOperand) val length = nums.length // To avoid cases where we have 1 + 05 or 1 * 05 since 05 won't be a // valid operand. Hence this check if (currentOperand > 0) { // NO OP recursion recurse(index + 1, previousOperand, currentOperand, value, ops) } // ADDITION ops.add("+") ops.add(currentValRep) recurse(index + 1, currentOperand, 0, value + currentOperand, ops) ops.removeAt(ops.size - 1) ops.removeAt(ops.size - 1) if (ops.size > 0) { // SUBTRACTION ops.add("-") ops.add(currentValRep) recurse(index + 1, -currentOperand, 0, value - currentOperand, ops) ops.removeAt(ops.size - 1) ops.removeAt(ops.size - 1) // MULTIPLICATION ops.add("*") ops.add(currentValRep) recurse( index + 1, currentOperand * previousOperand, 0, value - previousOperand + currentOperand * previousOperand, ops) ops.removeAt(ops.size - 1) ops.removeAt(ops.size - 1) } } fun addOperators(num: String, target: Int): List<String>? { if (num.isEmpty()) return ArrayList() this.target = target.toLong() digits = num answer = ArrayList() recurse(0, 0, 0, 0, ArrayList()) return answer } } fun main() { runTests(listOf( Triple("123", 6, setOf("1*2*3", "1+2+3")), Triple("105", 5, setOf("10-5", "1*0+5")), Triple("232", 8, setOf("2*3+2", "2+3*2")), Triple("3456237490", 9191, setOf()) )) { (input, target, value) -> value to ExpressionAddOperator().execute(input, target).toSet() } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
4,846
coding
MIT License
src/main/kotlin/g1201_1300/s1210_minimum_moves_to_reach_target_with_rotations/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1201_1300.s1210_minimum_moves_to_reach_target_with_rotations // #Hard #Array #Breadth_First_Search #Matrix // #2023_06_09_Time_230_ms_(100.00%)_Space_44.8_MB_(100.00%) import java.util.LinkedList import java.util.Objects import java.util.Queue class Solution { fun minimumMoves(grid: Array<IntArray>): Int { val n = grid.size val visited = Array(n) { IntArray(n) } val bq: Queue<IntArray> = LinkedList() bq.offer(intArrayOf(0, 0, 1)) visited[0][0] = visited[0][0] or 1 var level = 0 while (bq.isNotEmpty()) { val levelSize = bq.size for (l in 0 until levelSize) { val cur = bq.poll() val xtail = Objects.requireNonNull(cur)[0] val ytail = cur[1] val dir = cur[2] if (xtail == n - 1 && ytail == n - 2 && dir == 1) { return level } val xhead = xtail + if (dir == 1) 0 else 1 val yhead = ytail + if (dir == 1) 1 else 0 if (dir == 2) { if (ytail + 1 < n && grid[xtail][ytail + 1] != 1 && grid[xtail + 1][ytail + 1] != 1) { if (visited[xtail][ytail] and 1 == 0) { bq.offer(intArrayOf(xtail, ytail, 1)) visited[xtail][ytail] = visited[xtail][ytail] or 1 } if (visited[xtail][ytail + 1] and 2 == 0) { bq.offer(intArrayOf(xtail, ytail + 1, 2)) visited[xtail][ytail + 1] = visited[xtail][ytail + 1] or 2 } } if (xhead + 1 < n && grid[xhead + 1][yhead] != 1 && visited[xhead][yhead] and 2 == 0) { bq.offer(intArrayOf(xhead, yhead, 2)) visited[xhead][yhead] = visited[xhead][yhead] or 2 } } else { if (xtail + 1 < n && grid[xtail + 1][ytail] != 1 && grid[xtail + 1][ytail + 1] != 1) { if (visited[xtail][ytail] and 2 == 0) { bq.offer(intArrayOf(xtail, ytail, 2)) visited[xtail][ytail] = visited[xtail][ytail] or 2 } if (visited[xtail + 1][ytail] and 1 == 0) { bq.offer(intArrayOf(xtail + 1, ytail, 1)) visited[xtail + 1][ytail] = visited[xtail + 1][ytail] or 1 } } if (yhead + 1 < n && grid[xhead][yhead + 1] != 1 && visited[xhead][yhead] and 1 == 0) { bq.offer(intArrayOf(xhead, yhead, 1)) visited[xhead][yhead] = visited[xhead][yhead] or 1 } } } level += 1 } return -1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,972
LeetCode-in-Kotlin
MIT License
src/main/aoc2016/Day20.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2016 class Day20(input: List<String>) { // Sorted list of ranges, ranges fully contained in another range are not included private val blacklist = parseInput(input) private fun parseInput(input: List<String>): List<LongRange> { val ranges = mutableListOf<LongRange>() for (line in input) { val parts = line.split("-") ranges.add(parts[0].toLong()..parts[1].toLong()) } val sorted = ranges.sortedBy { it.first } val ret = mutableListOf(sorted.first()) sorted.forEach { range -> if (ret.last().contains(range.first) && ret.last().contains(range.last)) { // Range fully contained in previous range, skip it. } else { ret.add(range) } } return ret } private fun findFirstAllowed(): Long { var toTest = 0L for (range in blacklist) { if (toTest < range.first) { return toTest } toTest = range.last + 1 } return toTest } private fun findAllAllowed(): List<LongRange> { val ret = mutableListOf<LongRange>() var toTest = 0L blacklist.forEach { range -> if (toTest < range.first) { ret.add(toTest until range.first) } toTest = range.last + 1 } if (toTest < 4294967295) { ret.add(toTest..4294967295) } return ret } fun solvePart1(): Long { return findFirstAllowed() } fun solvePart2(): Int { return findAllAllowed().sumOf { it.count() } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,673
aoc
MIT License
advent-of-code-2022/src/main/kotlin/year_2022/Day12.kt
rudii1410
575,662,325
false
{"Kotlin": 37749}
package year_2022 import util.Pos2 import util.Runner import util.wrap import java.util.LinkedList import java.util.Queue fun main() { fun <T> List<List<T>>.get(p: Pos2): T = this[p.x][p.y] fun <T> List<MutableList<T>>.set(p: Pos2, data: T) { this[p.x][p.y] = data } fun canClimb(tmpCurrentHeight: Char, destHeight: Char): Boolean { val currentHeight = if (tmpCurrentHeight == 'E') 'z' else tmpCurrentHeight return destHeight == 'S' || (destHeight in currentHeight - 1..currentHeight) || currentHeight <= destHeight } fun traverse(map: List<List<Char>>, start: Pos2, target: Char): Int { val q: Queue<Triple<Pos2, Char, Int>> = LinkedList() val vLen = map.size val hLen = map.first().size val visited = List(vLen) { MutableList(hLen) { false } } q.add(Triple(start, ' ', 0)) while(q.isNotEmpty()) { val (pos, lastChar, score) = q.remove() if (pos.x !in 0 until vLen || pos.y !in 0 until hLen) continue if (visited.get(pos)) continue if (map.get(pos) != 'E' && !canClimb(lastChar, map.get(pos))) continue if (map.get(pos) == target) return score visited.set(pos, true) wrap(map.get(pos), score + 1) { a, b -> q.add(Triple(pos.getLeft(), a, b)) q.add(Triple(pos.getTop(), a, b)) q.add(Triple(pos.getRight(), a, b)) q.add(Triple(pos.getBottom(), a, b)) } } return -1 } fun prepareMap(input: String): Pair<List<List<Char>>, Pos2> { var end = Pos2.ZERO val map = input.split("\n").map { it.toList() } for (i in map.indices) { end = Pos2(i, map[i].indexOf('E')) if (end.y != -1) break } return Pair(map, end) } /* Part 1 */ fun part1(input: String): Int { val (map, end) = prepareMap(input) return traverse(map, end, 'S') } Runner.runAll(::part1, 31) /* Part 2 */ fun part2(input: String): Int { val (map, end) = prepareMap(input) return traverse(map, end, 'a') } Runner.runAll(::part2, 29) }
1
Kotlin
0
0
ab63e6cd53746e68713ddfffd65dd25408d5d488
2,235
advent-of-code
Apache License 2.0
style_transfer/app/src/main/java/org/tensorflow/lite/examples/styletransfer/camera/CameraSizes.kt
SunitRoy2703
405,389,854
false
{"Kotlin": 441677, "Java": 11281}
/* * Copyright 2019 Google LLC * * 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 * * https://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 org.tensorflow.lite.examples.styletransfer.camera import android.graphics.Point import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.params.StreamConfigurationMap import android.util.Size import android.view.Display import kotlin.math.max import kotlin.math.min /** Helper class used to pre-compute shortest and longest sides of a [Size] */ class SmartSize(width: Int, height: Int) { var size = Size(width, height) var long = max(size.width, size.height) var short = min(size.width, size.height) override fun toString() = "SmartSize(${long}x$short)" } /** Standard High Definition size for pictures and video */ val SIZE_1080P: SmartSize = SmartSize(1920, 1080) /** Returns a [SmartSize] object for the given [Display] */ fun getDisplaySmartSize(display: Display): SmartSize { val outPoint = Point() display.getRealSize(outPoint) return SmartSize(outPoint.x, outPoint.y) } // verify that the given width and height are on the expected aspect ratio fun verifyAspectRatio(width: Int, height: Int, aspectRatio: Size): Boolean { return (width * aspectRatio.height) == (height * aspectRatio.width) } /** * Returns the largest available PREVIEW size. For more information, see: * https://d.android.com/reference/android/hardware/camera2/CameraDevice */ fun <T> getPreviewOutputSize( display: Display, characteristics: CameraCharacteristics, targetClass: Class<T>, aspectRatio: Size, format: Int? = null ): Size { // Find which is smaller: screen or 1080p val screenSize = getDisplaySmartSize(display) val hdScreen = screenSize.long >= SIZE_1080P.long || screenSize.short >= SIZE_1080P.short val maxSize = if (hdScreen) SIZE_1080P else screenSize // If image format is provided, use it to determine supported sizes; else use target class val config = characteristics.get( CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP )!! if (format == null) { assert(StreamConfigurationMap.isOutputSupportedFor(targetClass)) } else { assert(config.isOutputSupportedFor(format)) } val allSizes = if (format == null) { config.getOutputSizes(targetClass) } else { config.getOutputSizes(format) } // Get available sizes and sort them by area from largest to smallest val validSizes = allSizes .sortedWith(compareBy { it.height * it.width }) .filter { verifyAspectRatio(it.width, it.height, aspectRatio) } .map { SmartSize(it.width, it.height) }.reversed() // Then, get the largest output size that is smaller or equal than our max size return validSizes.first { it.long <= maxSize.long && it.short <= maxSize.short }.size }
3
Kotlin
11
37
c7628b3e58d9ae1ff902f4a9ff0142a051f91958
3,246
Tensorflow-lite-kotlin-samples
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2023/day3/EngineSchematic.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.day3 import com.github.michaelbull.advent2023.math.Vector2 import com.github.michaelbull.advent2023.math.toVector2CharMap fun Sequence<String>.toEngineSchematic(): EngineSchematic { val data = this.toVector2CharMap() val numbers = buildList { for (y in data.yRange) { var startPosition: Vector2? = null var number = 0 for (x in data.xRange) { val position = Vector2(x, y) val char = data[position] if (char.isDigit()) { if (startPosition == null) { startPosition = position } number *= 10 number += char.digitToInt() } else if (startPosition != null) { add(number.inEngineAt(startPosition)) startPosition = null number = 0 } } if (startPosition != null) { add(number.inEngineAt(startPosition)) } } } val symbols = data .filter { (_, value) -> value.isEngineSymbol() } .map { (position, value) -> EngineSymbol(position, value) } return EngineSchematic( numbers, symbols ) } data class EngineSchematic( val numbers: List<EngineNumber>, val symbols: List<EngineSymbol>, ) { private val symbolPositions = symbols.map(EngineSymbol::position) private val gearPositions = symbols.filter(EngineSymbol::isGear).map(EngineSymbol::position) fun partNumbers(): List<Int> { return numbers .filter(::isAdjacentToSymbol) .map(EngineNumber::value) } fun gearRatios(): List<Int> { return gearPositions .map(::numbersAdjacentTo) .filter(::isBinary) .map(::ratio) } private fun isAdjacentToSymbol(number: EngineNumber): Boolean { return symbolPositions.any(number::adjacentTo) } private fun numbersAdjacentTo(position: Vector2): List<EngineNumber> { return numbers.filter { number -> number adjacentTo position } } private fun <E> isBinary(collection: Collection<E>): Boolean { return collection.size == 2 } private fun ratio(list: List<EngineNumber>): Int { return list[0].value * list[1].value } }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
2,437
advent-2023
ISC License