path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/AoC8.kt
Pi143
317,631,443
false
null
import java.io.File fun main() { println("Starting Day 8 A Test 1") calculateDay8PartA("Input/2020_Day8_A_Test1") println("Starting Day 8 A Real") calculateDay8PartA("Input/2020_Day8_A") println("Starting Day 8 B Test 1") calculateDay8PartB("Input/2020_Day8_A_Test1") println("Starting Day 8 B Real") calculateDay8PartB("Input/2020_Day8_A") } fun calculateDay8PartA(file: String): Int { val Day8Data = readDay8Data(file) val result = runIntructions(Day8Data) println(result.second) return result.second } fun calculateDay8PartB(file: String): Int { val Day8Data = readDay8Data(file) var modifiedInstructionLists: MutableList<MutableList<Instruction>> = ArrayList() for(i in 0 until Day8Data.size){ var tempList = Day8Data.toMutableList() if(Day8Data[i].operation == "nop"){ tempList[i] = Instruction("jmp", Day8Data[i].param) } if(Day8Data[i].operation == "jmp"){ tempList[i] = Instruction("nop", Day8Data[i].param) } modifiedInstructionLists.add(tempList) } for(instructions in modifiedInstructionLists){ val result = runIntructions(instructions) if(result.first == instructions.size){ println(result.second) return result.second } } return -1 } fun runIntructions(instructionList: MutableList<Instruction>): Pair<Int, Int> { var accumulator = 0 var position = 0 val stopPositions: MutableList<Int> = ArrayList() stopPositions.add(instructionList.size) while (!stopPositions.contains(position)) { stopPositions.add(position) //https://youtrack.jetbrains.com/issue/KT-11362 val (newPosition, newAccumulator) = executeInstruction(instructionList[position], position, accumulator) position = newPosition accumulator = newAccumulator } return Pair(position, accumulator) } fun executeInstruction(instruction: Instruction, position: Int, accumulator: Int): Pair<Int, Int> { return when (instruction.operation) { "nop" -> Pair(position+1, accumulator) "acc" -> Pair(position+1, accumulator+ instruction.param) "jmp" -> Pair(position+instruction.param, accumulator) else -> Pair(position, accumulator) } } fun readDay8Data(input: String): MutableList<Instruction> { //will this be ordered? val instructionList: MutableList<Instruction> = ArrayList() File(localdir + input).forEachLine { instructionList.add(parseInstructionDefinition(it)) } return instructionList } fun parseInstructionDefinition(line: String): Instruction { val operation = line.split(" ")[0] val param = line.split(" ")[1].toInt() return Instruction(operation, param) } class Instruction(operation: String, param: Int) { val operation = operation val param = param }
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
2,900
AdventOfCode2020
MIT License
advent-of-code-2022/src/Day25.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import kotlin.math.pow fun main() { val testInput = readLines("Day25_test") val input = readLines("Day25") "Part 1" { part1(testInput) shouldBe "2=-1=0" measureAnswer { part1(input) } } } private fun part1(input: List<String>): String = input.sumOf { it.snafuToDecimal() }.decimalToSnafu() private val decimalToSnafu = mapOf('=' to -2, '-' to -1, '0' to 0, '1' to 1, '2' to 2) private val snafuDigits = listOf('=', '-', '0', '1', '2') private fun String.snafuToDecimal(): Long { return reversed() .withIndex() .sumOf { (i, char) -> decimalToSnafu.getValue(char) * (5L pow i) } } private infix fun Long.pow(other: Int): Long = this.toDouble().pow(other).toLong() private fun Long.decimalToSnafu(): String { var decimal = this val result = StringBuilder() while (decimal > 0) { val rem = (decimal + 2) % 5; decimal = (decimal + 2) / 5; result.append(snafuDigits[rem.toInt()]) } return result.reversed().toString() }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
1,019
advent-of-code
Apache License 2.0
year2023/src/cz/veleto/aoc/year2023/Day02.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2023 import cz.veleto.aoc.core.AocDay class Day02(config: Config) : AocDay(config) { private val availableCubes = mapOf( Cube.Red to 12, Cube.Green to 13, Cube.Blue to 14, ) override fun part1(): String = input .parse() .filter { (_, grabs) -> grabs .all { grab -> grab.all { (cube, count) -> count <= availableCubes[cube]!! } } } .map(Game::first) .sum() .toString() override fun part2(): String = input .parse() .map { (_, grabs) -> grabs .flatMap(Grab::entries) .groupBy( keySelector = { (cube, _) -> cube }, valueTransform = { (_, count) -> count }, ) .values .map { counts -> counts.max() } .reduce(Int::times) } .sum() .toString() private fun Sequence<String>.parse(): Sequence<Game> = map { line -> val (label, grabs) = line.split(": ") val gameId = label.drop(5).toInt() gameId to grabs .split("; ") .map { grab -> grab .split(", ") .associate { singleTypeGrab -> val (count, type) = singleTypeGrab.split(" ") val cube = Cube.entries.first { it.name.lowercase() == type } cube to count.toInt() } } } enum class Cube { Red, Green, Blue } } private typealias Game = Pair<Int, Grabs> private typealias Grabs = List<Grab> private typealias Grab = Map<Day02.Cube, Int>
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
1,778
advent-of-pavel
Apache License 2.0
src/Day02.kt
joshpierce
573,265,121
false
{"Kotlin": 46425}
import java.io.File fun main() { // read the lines from the file var lines: List<String> = File("Day02.txt").readLines() // setup a new list of Games so we can calculate the outcome of each var games: MutableList<Game> = lines.map { var parts = it.split(" ") return@map Game(parts[0].translateRPS(), parts[1].translateRPS()) }.toMutableList() // calculate the outcome of each game, and sum the scores println("The sum of the score of all games is: " + games.sumOf { it.score() }.toString()) // setup a new list of Games so we can calculate the outcome of each based on the new rules in part 2 var gamesNew: MutableList<Game> = lines.map { var parts = it.split(" ") var oppPick = parts[0].translateRPS() var myPick: String // Calculate a Loss if (parts[1] == "X") { myPick = when (oppPick) { "Rock" -> "Scissors" "Paper" -> "Rock" "Scissors" -> "Paper" else -> throw Exception ("Invalid Opponent Pick") } } // Calculate a Draw else if (parts[1] == "Y") { myPick = oppPick } // Calculate a Win else { myPick = when (oppPick) { "Rock" -> "Paper" "Paper" -> "Scissors" "Scissors" -> "Rock" else -> throw Exception ("Invalid Opponent Pick") } } return@map Game(parts[0].translateRPS(), myPick) }.toMutableList() // calculate the outcome of each game, and sum the scores println("The sum of the score of all games with the new rules is: " + gamesNew.sumOf { it.score() }.toString()) } class Game(oppPick: String, yourPick: String) { var oppPick: String = oppPick var yourPick: String = yourPick } fun Game.score(): Int { var currScore: Int = when (this.yourPick) { "Rock" -> 1 "Paper" -> 2 "Scissors" -> 3 else -> throw Exception("Invalid RPS") } if (this.oppPick == this.yourPick) { currScore += 3 } else if (this.oppPick == "Rock" && this.yourPick == "Paper" || this.oppPick == "Paper" && this.yourPick == "Scissors" || this.oppPick == "Scissors" && this.yourPick == "Rock") { currScore += 6 } else { currScore += 0 } return currScore } fun String.translateRPS(): String { return when (this) { "A", "X" -> "Rock" "B", "Y" -> "Paper" "C", "Z" -> "Scissors" else -> throw Exception("Invalid RPS") } }
0
Kotlin
0
1
fd5414c3ab919913ed0cd961348c8644db0330f4
2,675
advent-of-code-22
Apache License 2.0
src/day04/Day04.kt
tschens95
573,743,557
false
{"Kotlin": 32775}
fun main() { // check if r1 in r2 or r2 in r1 fun contains(r1: IntRange, r2: IntRange) : Boolean { return (r2.first <= r1.first && r1.last <= r2.last) || (r1.first <= r2.first && r2.last <= r1.last) } // check borders of ranges for overlapping fun overlap(r1: IntRange, r2: IntRange) : Boolean { return if (r2.first > r1.first) { r2.first <= r1.last } else if (r2.first < r1.first) { r1.first <= r2.last } else { true } } fun part1(input: List<String>) : Int { var count = 0 for(line in input) { val ranges = line.split(",") val range1 = ranges[0] val range2 = ranges[1] val r1b = range1.split("-") val r2b = range2.split("-") if (contains(IntRange(r1b[0].toInt(), r1b[1].toInt()), IntRange(r2b[0].toInt(), r2b[1].toInt()))) { count++ } } return count } fun part2(input: List<String>) : Int { var count = 0 for(line in input) { val ranges = line.split(",") val range1 = ranges[0] val range2 = ranges[1] val r1b = range1.split("-") val r2b = range2.split("-") if (overlap(IntRange(r1b[0].toInt(), r1b[1].toInt()), IntRange(r2b[0].toInt(), r2b[1].toInt()))) { count++ } } return count } val testInput = "2-4,6-8\n" + "2-3,4-5\n" + "5-7,7-9\n" + "2-8,3-7\n" + "6-6,4-6\n" + "2-6,4-8" println(part1(testInput.split("\n"))) println(part2(testInput.split("\n"))) val input = readInput("04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
9d78a9bcd69abc9f025a6a0bde923f53c2d8b301
1,820
AdventOfCode2022
Apache License 2.0
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day16.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.days.Day /** * * @author <NAME> */ class Day16 : Day(title = "Aunt Sue") { private companion object Configuration { private const val TARGET_AUNT_STRING = "Sue 0: " + "children: 3, " + "cats: 7, " + "samoyeds: 2, " + "pomeranians: 3, " + "akitas: 0, " + "vizslas: 0, " + "goldfish: 5, " + "trees: 3, " + "cars: 2, " + "perfumes: 1" private val TARGET_AUNT = Aunt.parse(TARGET_AUNT_STRING) } override fun first(input: Sequence<String>) = input .map(Aunt.Companion::parse) .first { it.matches(TARGET_AUNT, false) }.id override fun second(input: Sequence<String>) = input .map(Aunt.Companion::parse) .first { it.matches(TARGET_AUNT, true) }.id private class Aunt(val id: Int, val compounds: Map<Compound, Int>) { fun matches(other: Aunt, useModifier: Boolean) = compounds .keys .all { matches(other, useModifier, it) } fun matches(other: Aunt, useModifier: Boolean, c: Compound) = when { other.compounds[c] == null -> true useModifier -> c.modifier(this.compounds[c]!!, other.compounds[c]!!) else -> this.compounds[c]!! == other.compounds[c]!! } companion object { fun parse(input: String): Aunt = input .split(": ", limit = 2) .let { (id, compounds) -> Aunt(id.substring(4).toInt(), compounds.split(", ").associate { it.split(": ").let { (k, v) -> Compound.fromString(k) to v.toInt() } }) } } } private enum class Compound(val modifier: ((Int, Int) -> Boolean)) { CHILDREN({ i, j -> i == j }), CATS({ i, j -> i > j }), SAMOYEDS({ i, j -> i == j }), POMERANIANS({ i, j -> i < j }), AKITAS({ i, j -> i == j }), VIZSLAS({ i, j -> i == j }), GOLDFISH({ i, j -> i < j }), TREES({ i, j -> i > j }), CARS({ i, j -> i == j }), PERFUMES({ i, j -> i == j }); companion object { fun fromString(s: String) = Compound.valueOf(s.toUpperCase()) } } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,408
AdventOfCode
MIT License
src/main/kotlin/dev/tasso/adventofcode/_2021/day12/Day12.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2021.day12 import dev.tasso.adventofcode.Solution class Day12 : Solution<Int> { override fun part1(input: List<String>): Int { return getPathsSmallCavesOnce(parseCaveGraph(input)).size } override fun part2(input: List<String>): Int { return getPathsSmallCavesTwice(parseCaveGraph(input)).size } } fun parseCaveGraph(input: List<String>) : Map<String, List<String>> { val caveMap = mutableMapOf<String, MutableList<String>>() val edges = input.map { it.split("-") } edges.forEach { edge -> caveMap.getOrPut(edge.first()) { mutableListOf() }.add(edge.last()) caveMap.getOrPut(edge.last()) { mutableListOf() }.add(edge.first()) } return caveMap } fun getPathsSmallCavesOnce(caveMap : Map<String, List<String>>, currPath : List<String> = mutableListOf(), startNode : String = "start") : List<List<String>>{ val paths = mutableListOf<List<String>>() val newPath = currPath.toMutableList() newPath.add(startNode) if(startNode == "end" ) { paths.add(newPath) } else { caveMap[startNode]!!.forEach { node -> if (!(node.isLowerCase() && currPath.contains(node))) { paths.addAll(getPathsSmallCavesOnce(caveMap, newPath, node)) } } } return paths } fun getPathsSmallCavesTwice(caveMap : Map<String, List<String>>, currPath : List<String> = mutableListOf(), startNode : String = "start") : List<List<String>>{ val paths = mutableListOf<List<String>>() val newPath = currPath.toMutableList() newPath.add(startNode) if(startNode == "end" ) { paths.add(newPath) } else { caveMap[startNode]!!.forEach { node -> if(node.isUpperCase()) { paths.addAll(getPathsSmallCavesTwice(caveMap, newPath, node)) }else { if(node != "start") { if(!newPath.hasTwoSmallCaveVisits()) { paths.addAll(getPathsSmallCavesTwice(caveMap, newPath, node)) } else if(newPath.hasTwoSmallCaveVisits() && !currPath.contains(node)) { paths.addAll(getPathsSmallCavesTwice(caveMap, newPath, node)) } } } } } return paths } fun String.isLowerCase() = this.all { it.isLowerCase() } fun String.isUpperCase() = !this.isLowerCase() fun List<String>.hasTwoSmallCaveVisits() = this.filter { it.isLowerCase() }.groupingBy { it }.eachCount().filter { it.value >= 2 }.isNotEmpty()
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
2,717
advent-of-code
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-21.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2022, "21-input") val testInput1 = readInputLines(2022, "21-test1") println("Part1:") part1(testInput1).println() part1(input).println() println() println("Part2:") part2(testInput1).println() part2(input).println() } private fun part1(input: List<String>): Long { return MonkeyMath(input).part1() } private fun part2(input: List<String>): Long { return MonkeyMath(input).part2() } class MonkeyMath(input: List<String>) { private val root = run { val parsed = input.associate { val (monkey, op) = it.split(": ") monkey to op } parse("root", parsed) } fun part1(): Long { return (root.simplify() as Monkey.Number).number } fun part2(): Long { require(root is Monkey.Op) val m1 = root.m1.replaceHuman().simplify() val m2 = root.m2.replaceHuman().simplify() require(m1 is Monkey.Op) require(m2 is Monkey.Number) return m1.calculateForHuman(m2.number) } private fun parse(name: String, all: Map<String, String>): Monkey { val value = all[name]!! val num = value.toLongOrNull() if (num != null) return Monkey.Number(name, num) val (m1, op, m2) = value.split(' ') return Monkey.Op(name, op, parse(m1, all), parse(m2, all)) } private sealed class Monkey { abstract fun replaceHuman(): Monkey abstract fun simplify(): Monkey data class Number(val name: String, val number: Long) : Monkey() { override fun replaceHuman() = if (name == "humn") Human else this override fun simplify(): Number = this override fun calculateForHuman(wanted: Long) = error("can't calculateForHuman on Number") } data class Op(val name: String, val type: String, val m1: Monkey, val m2: Monkey) : Monkey() { override fun replaceHuman(): Monkey = copy(m1 = m1.replaceHuman(), m2 = m2.replaceHuman()) override fun simplify(): Monkey { val s1 = m1.simplify() val s2 = m2.simplify() return if (s1 is Number && s2 is Number) { when (type) { "+" -> Number(name, s1.number + s2.number) "-" -> Number(name, s1.number - s2.number) "*" -> Number(name, s1.number * s2.number) "/" -> Number(name, s1.number / s2.number) else -> error("bad op: $type") } } else { this.copy(m1 = s1, m2 = s2) } } override fun calculateForHuman(wanted: Long) = when (type) { "+" -> { if (m1 is Number) m2.calculateForHuman(wanted - m1.number) else { m1.calculateForHuman(wanted - (m2 as Number).number) } } "-" -> if (m1 is Number) m2.calculateForHuman(m1.number - wanted) else { m1.calculateForHuman(wanted + (m2 as Number).number) } "*" -> if (m1 is Number) m2.calculateForHuman(wanted / m1.number) else { m1.calculateForHuman(wanted / (m2 as Number).number) } "/" -> { if (m1 is Number) m2.calculateForHuman(m1.number / wanted) else { m1.calculateForHuman(wanted * (m2 as Number).number) } } else -> error("bad op: $type") } } data object Human : Monkey() { override fun replaceHuman() = error("already human") override fun simplify() = this override fun calculateForHuman(wanted: Long) = wanted } abstract fun calculateForHuman(wanted: Long): Long } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
4,115
advent-of-code
MIT License
src/Day12.kt
MickyOR
578,726,798
false
{"Kotlin": 98785}
import java.util.Queue fun main() { fun getElevation(c: Char): Int { if (c == 'S') return 0 if (c == 'E') return 'z' - 'a' return c - 'a' } fun part1(input: List<String>): Int { var n = input.size-1 var m = input[0].length var r = 0 var c = 0 for (i in 0 until n) { for (j in 0 until m) { if (input[i][j] == 'S') { r += i c += j } } } var q = mutableListOf<Pair<Int, Int>>() var dist = MutableList(n) { MutableList(m) { -1 } } q.add(Pair(r, c)) dist[r][c] = 0 var dr = listOf(0, 0, 1, -1) var dc = listOf(1, -1, 0, 0) while (q.size > 0) { r = q.first().first c = q.first().second q.removeAt(0) for (i in 0 until 4) { var nr = r + dr[i] var nc = c + dc[i] if (nr >= 0 && nr < n && nc >= 0 && nc < m && dist[nr][nc] == -1 && getElevation(input[nr][nc]) <= getElevation(input[r][c])+1) { dist[nr][nc] = dist[r][c] + 1 q.add(Pair(nr, nc)) } } } for (i in 0 until n) { for (j in 0 until m) { if (input[i][j] == 'E') { return dist[i][j] } } } return 0 } fun part2(input: List<String>): Int { var n = input.size-1 var m = input[0].length var r = 0 var c = 0 var q = mutableListOf<Pair<Int, Int>>() var dist = MutableList(n) { MutableList(m) { -1 } } for (i in 0 until n) { for (j in 0 until m) { if (getElevation(input[i][j]) == 0) { q.add(Pair(i, j)) dist[i][j] = 0 } } } var dr = listOf(0, 0, 1, -1) var dc = listOf(1, -1, 0, 0) while (q.size > 0) { r = q.first().first c = q.first().second q.removeAt(0) for (i in 0 until 4) { var nr = r + dr[i] var nc = c + dc[i] if (nr >= 0 && nr < n && nc >= 0 && nc < m && dist[nr][nc] == -1 && getElevation(input[nr][nc]) <= getElevation(input[r][c])+1) { dist[nr][nc] = dist[r][c] + 1 q.add(Pair(nr, nc)) } } } for (i in 0 until n) { for (j in 0 until m) { if (input[i][j] == 'E') { return dist[i][j] } } } return 0 } val input = readInput("Day12") part1(input).println() part2(input).println() }
0
Kotlin
0
0
c24e763a1adaf0a35ed2fad8ccc4c315259827f0
2,825
advent-of-code-2022-kotlin
Apache License 2.0
src/iii_conventions/MyDate.kt
jerome-fosse
149,761,327
true
{"Kotlin": 75783, "Java": 4952}
package iii_conventions import iii_conventions.TimeInterval.* data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) { fun nextDay(): MyDate = this + DAY operator fun compareTo(other: MyDate): Int { if (this.year == other.year) { if (this.month == other.month) { return this.dayOfMonth.compareTo(other.dayOfMonth) } else { return this.month.compareTo(other.month) } } else { return this.year.compareTo(other.year) } } operator fun rangeTo(other: MyDate): DateRange { return DateRange(this, other) } operator fun plus(ti: TimeInterval): MyDate { return this.plus(RepeatedTimeInterval(ti)) } operator fun plus(ti: RepeatedTimeInterval): MyDate { fun addDays(myDate: MyDate, days: Int): MyDate { fun isLeapYear(year: Int): Boolean = year % 4 == 0 fun loop(md: MyDate, toadd: Int, added: Int): MyDate { val remainingDays = when(md.month) { 0,2,4,6,7,9,11 -> 31 - md.dayOfMonth 1 -> if (isLeapYear(md.year)) 29 - md.dayOfMonth else 28 - md.dayOfMonth else -> 30 - md.dayOfMonth } return when { toadd == 0 -> md toadd <= remainingDays -> md.copy(dayOfMonth = md.dayOfMonth + toadd) month < 11 -> loop(md.copy(month = md.month + 1, dayOfMonth = 1), toadd - remainingDays - 1, added + remainingDays + 1) else -> loop(md.copy(year = md.year + 1, month = 0, dayOfMonth = 1), toadd - remainingDays - 1, added + remainingDays + 1) } } return loop(myDate, days, 0) } fun addYear(n: Int): MyDate = this.copy(year = year + 1 * n) return when(ti.timeInterval) { DAY -> addDays(this, 1 * ti.times) WEEK -> addDays(this, 7 * ti.times) YEAR -> addYear(ti.times) } } } enum class TimeInterval { DAY, WEEK, YEAR; operator fun times(n: Int): RepeatedTimeInterval = RepeatedTimeInterval(this, n) } data class RepeatedTimeInterval(val timeInterval: TimeInterval, val times: Int = 1) class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> { override fun iterator(): Iterator<MyDate> { fun loop(collection: Collection<MyDate>, start: MyDate, end: MyDate): Iterator<MyDate> { return when { start < end -> loop(collection.plus(start), start.nextDay(), end) start == end -> collection.plus(start).iterator() else -> collection.iterator() } } return loop(ArrayList(), start, endInclusive) } operator fun contains(myDate : MyDate) : Boolean { return myDate >= start && myDate <= endInclusive } }
0
Kotlin
0
0
e2029254a81d3de7c1ded41aa33a411e75a15dac
2,942
kotlin-koans
MIT License
src/main/kotlin/Day16.kt
jcornaz
573,137,552
false
{"Kotlin": 76776}
import java.util.* private typealias ValveId = String object Day16 { private val LINE_REGEX = Regex("Valve ([A-Z]+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)") fun part1(input: String, time: Int = 30): Int { val valves = input.lineSequence() .map(::parseValve) .toMap() val solver = Solver(maxStep = time, initialState = SearchState(valves.keys.first(), valves.mapValues { false }, 0, null), valves = valves) return solver.solve() } private fun parseValve(input: String): Pair<ValveId, Valve> { val (_, valve, rate, edges) =LINE_REGEX.find(input)?.groupValues ?: error("failed to match input line: $input") return valve to Valve(rate.toInt(), edges.split(", ")) } @Suppress("UNUSED_PARAMETER") fun part2(input: String): Long = TODO() data class Valve(val rate: Int, val connections: Collection<ValveId>) class SearchState(val valve: ValveId, val openValves: Map<ValveId, Boolean>, val step: Int, val parent: SearchState?) { override fun equals(other: Any?): Boolean { if (other !is SearchState) return false return valve == other.valve && openValves == other.openValves } override fun hashCode(): Int = valve.hashCode() + 31 * openValves.hashCode() override fun toString(): String = "$valve at $step (${openValves.filterValues { it }.keys})" } class Solver(val maxStep: Int, private val initialState: SearchState, private val valves: Map<ValveId, Valve>) { private val visitedStates: MutableSet<SearchState> = mutableSetOf() private val priorityQueue: PriorityQueue<Pair<SearchState, Int>> = PriorityQueue<Pair<SearchState, Int>>(compareBy { -it.second }) .apply { add(initialState to 0) } private fun getSuccessorState(searchState: SearchState, score: Int): Sequence<Pair<SearchState, Int>> { if (searchState.step >= maxStep) return emptySequence() val currentValve = valves[searchState.valve] ?: return emptySequence() val nextStep = searchState.step + 1 val connectedStates = currentValve.connections.asSequence().map { SearchState(it, searchState.openValves, nextStep, searchState) to score } return if(searchState.openValves[searchState.valve] == false && currentValve.rate != 0) connectedStates + (SearchState(searchState.valve, searchState.openValves + (searchState.valve to true), nextStep, searchState.parent) to computeScore(score, nextStep, currentValve.rate)) else connectedStates } private fun computeScore(score: Int, step: Int, rate: Int) = score + ((maxStep - step) * rate) fun solve() : Int { var bestStateThusFar = initialState to 0 while (!priorityQueue.isEmpty()) { val (state, score) = priorityQueue.poll() visitedStates.add(state) if (bestStateThusFar.second < score) bestStateThusFar = state to score getSuccessorState(state, score) .filter { it.first !in visitedStates } .forEach { priorityQueue.add(it) } } val seq = sequence { var currentState: SearchState = bestStateThusFar.first while (currentState.parent != null) { yield(currentState) currentState = currentState.parent!! } } seq.toList().reversed().forEach(::println) return bestStateThusFar.second } } }
1
Kotlin
0
0
979c00c4a51567b341d6936761bd43c39d314510
3,668
aoc-kotlin-2022
The Unlicense
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[剑指 Offer 53 - I]在排序数组中查找数字 I.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//统计一个数字在排序数组中出现的次数。 // // // // 示例 1: // // 输入: nums = [5,7,7,8,8,10], target = 8 //输出: 2 // // 示例 2: // // 输入: nums = [5,7,7,8,8,10], target = 6 //输出: 0 // // // // 限制: // // 0 <= 数组长度 <= 50000 // // // // 注意:本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last- //position-of-element-in-sorted-array/ // Related Topics 数组 二分查找 // 👍 83 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun search(nums: IntArray, target: Int): Int { //排序数组 二分查找 寻找左右边界 相减则为重复数字的次数 //左边界则为当前 target 减一 return find(nums,target) - find(nums,target-1) } fun find(nums: IntArray,target: Int):Int { var left = 0 var right = nums.size-1 while(left <= right){ var mid = left + (right-left)/2 if(nums[mid] <= target){ left = mid+1 }else { right = mid-1 } } return left } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,248
MyLeetCode
Apache License 2.0
2022/src/test/kotlin/Day20.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe class Day20 : StringSpec({ "puzzle part 01" { val (file, mix) = getFile() file.indices.forEach { mix.move(file[it]) } mix.sumOfGroveCoordinates() shouldBe 9945 } "puzzle part 02" { val (file, mix) = getFile(811589153) repeat(10) { file.indices.forEach { mix.move(file[it]) } } mix.sumOfGroveCoordinates() shouldBe 3338877775442 } }) private fun MutableMap<String, String>.move(number: String) { val value = number.toValue() % (size - 1) if (value % size == 0L) return val steps = if (value > 0) value.toInt() else size + value.toInt() - 1 val dest = keyAfter(number, steps) this[keyBefore(number)] = this[number]!! this[number] = this[dest]!! this[dest] = number } private fun Map<String, String>.keyAfter(number: String, moves: Int): String { var current = number repeat(moves) { current = this[current]!! } return current } private fun Map<String, String>.keyBefore(number: String) = entries.single { it.value == number }.key private fun String.toValue() = split('#')[1].toLong() private fun MutableMap<String, String>.sumOfGroveCoordinates(): Long { val zero = keys.single { it.endsWith("#0") } return listOf(1000, 2000, 3000).sumOf { keyAfter(zero, it).toValue() } } private fun getFile(key: Int = 1): Pair<List<String>, MutableMap<String, String>> { val file = getPuzzleInput("day20-input.txt") .map { it.toLong() * key }.withIndex() .map { "${it.index}#${it.value}" } .toList() val mix = file.zipWithNext().toMap() .plus(file.last() to file.first()) .toMutableMap() return file to mix }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
1,772
adventofcode
MIT License
y2020/src/main/kotlin/adventofcode/y2020/Day14.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution import adventofcode.util.SimpleParser fun main() = Day14.solve() object Day14 : AdventSolution(2020, 14, "Docking Data") { override fun solvePartOne(input: String): Long { val mem = mutableMapOf<Long, Long>() lateinit var mask: String fun applyMask(i: Long): Long { val str = i.toString(2).padStart(36, '0') return mask.zip(str) { m, ch -> if (m == 'X') ch else m }.toCharArray().let(::String).toLong(2) } val parser = SimpleParser<() -> Unit>().apply { rule("""mem\[(\d+)\] = (\d+)""") { (adr, v) -> { mem[adr.toLong()] = applyMask(v.toLong()) } } rule("""mask = (.+)""") { (s) -> { mask = s } } } input.lineSequence().mapNotNull { parser.parse(it) }.forEach { it() } return mem.values.sum() } override fun solvePartTwo(input: String): Any { val mem = mutableMapOf<Long, Long>() lateinit var mask: String fun applyMask(adr: Long): LongArray { val str = adr.toString(2).padStart(36, '0') var masked = LongArray(1) mask.zip(str) { m, ch -> for (i in masked.indices) masked[i] *= 2L when { m == 'X' -> masked += masked.map { it + 1 } m == '1' || ch == '1' -> for (i in masked.indices) masked[i]++ } } return masked } val parser = SimpleParser<() -> Unit>().apply { rule("""mem\[(\d+)\] = (\d+)""") { (adr, v) -> { applyMask(adr.toLong()).forEach { a -> mem[a] = v.toLong() } } } rule("""mask = (.+)""") { (s) -> { mask = s } } } input.lineSequence().mapNotNull(parser::parse).forEach { it() } return mem.values.sum() } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,918
advent-of-code
MIT License
src/test/kotlin/be/brammeerten/y2022/Day21Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2022 import be.brammeerten.extractRegexGroups import be.brammeerten.readFile import be.brammeerten.y2022.Day21Test.MonkeyOperation.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class Day21Test { @Test fun `part 1a`() { val monkeys = readInput("2022/day21/exampleInput.txt") assertThat(getSolutions(monkeys)["root"]).isEqualTo(152L) } @Test fun `part 1b`() { val monkeys = readInput("2022/day21/input.txt") assertThat(getSolutions(monkeys)["root"]).isEqualTo(364367103397416) } @Test fun `part 2a`() { val monkeys = readInput("2022/day21/exampleInput.txt").filter { it.name != "humn" } assertThat(findHumanValue(monkeys)).isEqualTo(301) } @Test fun `part 2b`() { val monkeys = readInput("2022/day21/input.txt").filter { it.name != "humn" } assertThat(findHumanValue(monkeys)).isEqualTo(3782852515583) } fun getSolutions(monkeys: List<Monkey>): Map<String, Long> { val solutions = monkeys .filter { it.operation == ABSOLUTE } .map { it.name to it.arg1!!.toLong() } .toMap().toMutableMap() val unsolved = monkeys .filter { it.operation != ABSOLUTE } .map { it.name to it } .toMap().toMutableMap() while (solutions["root"] == null) { val initialSize = solutions.size unsolved.values .filter { m -> solutions.containsKey(m.arg1) && solutions.containsKey(m.arg2) } .forEach { m -> val solution = m.solve(solutions[m.arg1]!!, solutions[m.arg2]!!) solutions[m.name] = solution unsolved.remove(m.name) } if (initialSize == solutions.size) break } return solutions } fun findHumanValue(monkeys: List<Monkey>): Long { val solutions = getSolutions(monkeys) val unsolved = monkeys.filter { !solutions.containsKey(it.name) }.map { it.name to it }.toMap() val root = monkeys.find { it.name == "root" }!! if (solutions.containsKey(root.arg1)) { return findHumanValue(solutions, unsolved, root.arg2!!, solutions[root.arg1]!!) } else if (solutions.containsKey(root.arg2)) { return findHumanValue(solutions, unsolved, root.arg1!!, solutions[root.arg2]!!) } else { throw IllegalStateException("Can't solve this") } } fun findHumanValue(solutions: Map<String, Long>, unsolved: Map<String, Monkey>, monkeyName: String, monkeyValue: Long): Long { var next = unsolved[monkeyName]!!.whatToSolve(monkeyValue, solutions) while(next.first != "humn") { next = unsolved[next.first]!!.whatToSolve(next.second, solutions) } return next.second } fun readInput(file: String): List<Monkey> { return readFile(file) .map { extractRegexGroups("(.+): (.+)", it) } .map { (name, operation) -> val toMonkey = {type: MonkeyOperation -> val matches = extractRegexGroups("^(.+) [\\/\\*\\+\\-] (.+)$", operation) Monkey(name, type, matches[0], matches[1]) } if (operation.contains(" / ")) toMonkey(DIVIDE) else if (operation.contains(" * ")) toMonkey(MULTIPLY) else if (operation.contains(" + ")) toMonkey(ADD) else if (operation.contains(" - ")) toMonkey(SUBTRACT) else Monkey(name, ABSOLUTE, operation) } } data class Monkey(val name: String, val operation: MonkeyOperation, val arg1: String? = null, val arg2: String? = null) { fun solve(a1: Long, a2: Long): Long { return when (operation) { DIVIDE -> a1 / a2 MULTIPLY -> a1 * a2 ADD -> a1 + a2 SUBTRACT -> a1 - a2 else -> throw IllegalStateException("NO!") } } fun whatToSolve(expectedValue: Long, solutions: Map<String, Long>): Pair<String, Long> { if (solutions.containsKey(arg1)) { val a = solutions[arg1]!! return when (operation) { DIVIDE -> arg2!! to a / expectedValue MULTIPLY -> arg2!! to expectedValue / a ADD -> arg2!! to expectedValue - a SUBTRACT -> arg2!! to a - expectedValue else -> throw IllegalStateException("OH") } } else if (solutions.containsKey(arg2)) { val b = solutions[arg2]!! return when (operation) { DIVIDE -> arg1!! to b * expectedValue MULTIPLY -> arg1!! to expectedValue / b ADD -> arg1!! to expectedValue - b SUBTRACT -> arg1!! to b + expectedValue else -> throw IllegalStateException("OHo") } } else { throw IllegalStateException("SHIT") } } } enum class MonkeyOperation { ABSOLUTE, ADD, SUBTRACT, MULTIPLY, DIVIDE } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
5,296
Advent-of-Code
MIT License
gcj/y2022/round2/b_wip.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2022.round2 import kotlin.math.floor import kotlin.math.round import kotlin.math.sqrt private fun rFloor(x: Int, y: Int) = floor(sqrt(1.0 * x * x + 1.0 * y * y)).toInt() private fun y(x: Int, r: Int): Int { return round(sqrt(1.0 * r * r - 1.0 * x * x)).toInt() } private fun skips(rFloor: Int, x: Int, y: Int): Boolean { val y1 = y(x, rFloor) val y2 = y(x, rFloor + 1) return (y1 < y) and (y < y2) } private fun research2(m: Int): Int { /* val a = List(m + 2) { BooleanArray(m + 2) } val b = List(m + 2) { BooleanArray(m + 2) } for (r in 0..m) { for (x in 0..r) { val y = round(sqrt(1.0 * r * r - 1.0 * x * x)).toInt() b[x][y] = true b[y][x] = true } } // println(m) // var res = 0 for (x in 0..m + 1) for (y in 0..m + 1) { if (y == 0) println(x) a[x][y] = round(sqrt(1.0 * x * x + 1.0 * y * y)) <= m if (a[x][y] != b[x][y]) { // println("$x $y ${a[x][y]} ${b[x][y]}") require(a[x][y]) // res += 1 } } */ val holes = IntArray(m + 1) for (y in 0..m) { if (y % 1000 == 0) System.err.println(y) for (x in 0..m) { val rFloor = rFloor(x, y) if (rFloor > m) break val skips = skips(rFloor, x, y) and skips(rFloor, y, x) if (skips) { val rFull = round(sqrt(1.0 * x * x + 1.0 * y * y)).toInt() if (rFull > m) continue holes[rFull]++ println("$x $y") // if (b[x][y] || !a[x][y]) { // println("$x $y ${a[x][y]} ${b[x][y]}") // } } } } println(holes.contentToString()) // var s = 0 // for (x in holes) { // s += x // println(s) // } return 0 } private fun solve(): Long { return 777L // return research(readInt()) * 4L } fun main() { // for (r in 1..100) { // val v = research(r) // println("$r $v") // println(research(r) - research(r-1)) // } // System.setIn(java.io.File("input.txt").inputStream()) // System.setOut(java.io.PrintStream("output.txt")) research2(500) // repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,127
competitions
The Unlicense
src/Day10.kt
eo
574,058,285
false
{"Kotlin": 45178}
// https://adventofcode.com/2022/day/10 fun main() { fun registerValuesAtEachCycle(input: List<String>): List<Int> { var lastRegisterValue = 1 return buildList { add(lastRegisterValue) for (operation in input.map(Operation::fromString)) { repeat(operation.cycle) { add(lastRegisterValue) } lastRegisterValue = when (operation) { is NoOperation -> lastRegisterValue is AddOperation -> lastRegisterValue + operation.value } } add(lastRegisterValue) } } fun part1(input: List<String>): Int { return registerValuesAtEachCycle(input) .withIndex() .toList() .slice(20..220 step 40) .sumOf { it.index * it.value } } fun part2(input: List<String>): String { val crtHeight = 6 val crtWidth = 40 val registerValuesAtEachCycle = registerValuesAtEachCycle(input) return List(crtHeight) { row -> List(crtWidth) { col -> val cycle = crtWidth * row + col + 1 val registerValue = registerValuesAtEachCycle[cycle] if (col in registerValue - 1..registerValue + 1) "#" else "." }.joinToString("") }.joinToString("\n") } val input = readLines("Input10") println("Part 1: " + part1(input)) println("Part 2: ") println(part2(input)) } private sealed class Operation(val cycle: Int) { companion object { fun fromString(str: String): Operation = when (val operationName = str.substringBefore(" ")) { "addx" -> AddOperation(str.substringAfter(" ").toInt()) "noop" -> NoOperation else -> error("Invalid operation! $operationName") } } } private class AddOperation(val value: Int) : Operation(2) private object NoOperation : Operation(1)
0
Kotlin
0
0
8661e4c380b45c19e6ecd590d657c9c396f72a05
2,008
aoc-2022-in-kotlin
Apache License 2.0
src/Day04.kt
tomoki1207
572,815,543
false
{"Kotlin": 28654}
fun main() { fun toPairs(input: List<String>) = input.map { line -> val pair = line.split(",") val first = pair[0].split("-").let { Pair(it[0].toInt(), it[1].toInt()) } val second = pair[1].split("-").let { Pair(it[0].toInt(), it[1].toInt()) } Pair((first.first..first.second).map { it }, (second.first..second.second).map { it }) } fun part1(input: List<String>) = toPairs(input) .count { pair -> pair.first.containsAll(pair.second) || pair.second.containsAll(pair.first) } fun part2(input: List<String>) = toPairs(input) .count { pair -> pair.first.intersect(pair.second.toSet()).isNotEmpty() } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2ecd45f48d9d2504874f7ff40d7c21975bc074ec
906
advent-of-code-kotlin-2022
Apache License 2.0
src/hongwei/leetcode/playground/leetcodecba/M75SortColors.kt
hongwei-bai
201,601,468
false
{"Java": 143669, "Kotlin": 38875}
package hongwei.leetcode.playground.leetcodecba import hongwei.leetcode.playground.common.print class M75SortColors { fun test() { val testData = listOf( arrayOf( intArrayOf(2, 0, 2, 1, 1, 0), intArrayOf(0, 0, 1, 1, 2, 2) ), arrayOf( intArrayOf(2, 0, 1), intArrayOf(0, 1, 2) ), arrayOf( intArrayOf(0), intArrayOf(0) ), arrayOf( intArrayOf(1), intArrayOf(1) ) ) val onlyTestIndex = -1 testData.forEachIndexed { i, data -> if (!(onlyTestIndex >= 0 && onlyTestIndex != i)) { val input1 = data[0] as IntArray var output = IntArray(input1.size).apply { forEachIndexed { index, _ -> set(index, input1[index]) } } val expectedOutput = data[1] sortColors(output) var pass = expectedOutput.size == output.size if (pass) { expectedOutput.forEachIndexed { index, ints -> if (ints != output[index]) { pass = false } } } if (pass) { println("test[$i] passed.") } else { println("test[$i] FAILED!") output.print() } } } } fun sortColors(nums: IntArray): Unit { var red = 0 var white = 0 nums.forEach { when (it) { 0 -> red++ 1 -> white++ } } nums.fill(0, 0, red) nums.fill(1, red, red + white) nums.fill(2, red + white, nums.size) } } /* https://leetcode.com/problems/sort-colors/ 75. Sort Colors Medium 4896 278 Add to List Share Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. Example 1: Input: nums = [2,0,2,1,1,0] Output: [0,0,1,1,2,2] Example 2: Input: nums = [2,0,1] Output: [0,1,2] Example 3: Input: nums = [0] Output: [0] Example 4: Input: nums = [1] Output: [1] Constraints: n == nums.length 1 <= n <= 300 nums[i] is 0, 1, or 2. Follow up: Could you solve this problem without using the library's sort function? Could you come up with a one-pass algorithm using only O(1) constant space? Accepted 634.8K Submissions 1.3M */
0
Java
0
1
9d871de96e6b19292582b0df2d60bbba0c9a895c
2,760
leetcode-exercise-playground
Apache License 2.0
tasks-3/lib/src/main/kotlin/flows/algo/Dinitz.kt
AzimMuradov
472,473,231
false
{"Kotlin": 127576}
package flows.algo import flows.structures.Matrix import flows.structures.Network /** * The Dinitz's Algorithm. */ public fun <V> Network<V>.calculateDinitzMaxflow(): UInt { var maxflow = 0u val verticesList = graph.vertices.toList() val verticesIndexed = run { var j = 0 graph.vertices.associateWith { j++ } } val residualNetworkCapacities = Matrix.empty(keys = graph.vertices, noValue = 0u).apply { for ((v, u, cap) in graph.edges) { set(v, u, cap) } } val depths = graph.vertices.associateWithTo(mutableMapOf()) { UInt.MAX_VALUE } fun bfs() = bfs(residualNetworkCapacities, depths) fun dfs(pointers: MutableMap<V, V?>) = dfs( residualNetworkCapacities, depths, verticesList, verticesIndexed, pointers, source, UInt.MAX_VALUE ) while (bfs()) { val pointers: MutableMap<V, V?> = graph.vertices.associateWithTo(mutableMapOf()) { graph.vertices.first() } maxflow += generateSequence(seed = dfs(pointers)) { dfs(pointers).takeUnless { it == 0u } }.sum() } return maxflow } private fun <V> Network<V>.bfs( residualNetworkCapacities: Matrix<V, UInt>, depths: MutableMap<V, UInt>, ): Boolean { depths.replaceAll { _, _ -> UInt.MAX_VALUE } depths[source] = 0u val deque = ArrayDeque<V>().apply { add(source) } while (deque.isNotEmpty()) { val v = deque.removeFirst() for ((u, cap) in residualNetworkCapacities[v]) { if (depths.getValue(u) == UInt.MAX_VALUE && cap != 0u) { depths[u] = depths.getValue(v) + 1u deque.add(u) } } } return depths.getValue(sink) != UInt.MAX_VALUE } private fun <V> Network<V>.dfs( residualNetworkCapacities: Matrix<V, UInt>, depth: MutableMap<V, UInt>, verticesList: List<V>, verticesIndexed: Map<V, Int>, pointers: MutableMap<V, V?>, u: V, minC: UInt, ): UInt { if (u == sink || minC == 0u) return minC if (pointers[u] != null) { for (v in verticesList.subList(verticesIndexed.getValue(pointers[u]!!), verticesList.size)) { if (depth.getValue(v) == depth.getValue(u) + 1u) { val delta = dfs( residualNetworkCapacities, depth, verticesList, verticesIndexed, pointers, v, minOf(minC, residualNetworkCapacities[u, v]) ) if (delta != 0u) { residualNetworkCapacities[u, v] -= delta residualNetworkCapacities[v, u] += delta return delta } } pointers[u] = verticesList.getOrNull(verticesIndexed[pointers.getValue(u)]!! + 1) } } return 0u }
0
Kotlin
0
0
01c0c46df9dc32c2cc6d3efc48b3a9ee880ce799
2,925
discrete-math-spbu
Apache License 2.0
src/aoc2022/day05/Day05.kt
svilen-ivanov
572,637,864
false
{"Kotlin": 53827}
package aoc2022.day05 import readInput fun parseConfig(input: List<String>): List<ArrayDeque<String>> { val stacks = mutableListOf<ArrayDeque<String>>() for ((index, line) in input.withIndex()) { val chunks = line.chunked(4) val stackEntries = chunks.map { it[1].toString().trim() } if (index == 0) { repeat(stackEntries.size) { stacks.add(ArrayDeque()) } } if (index != input.size - 1) { stackEntries.forEachIndexed { stackIndex, stackEntry -> if (stackEntry.isNotBlank()) { stacks[stackIndex].add(stackEntry) } } } } println(stacks) return stacks } fun main() { fun part1(input: List<String>) { val split = input.indexOf("") val config = input.subList(0, split) val stacks = parseConfig(config) val commands = input.subList(split + 1, input.size) commands.forEach { commandLine -> val command = commandLine.split(" ") val count = command[1].toInt() val sourceIndex = command[3].toInt() - 1 val destIndex = command[5].toInt() - 1 val sourceStack = stacks[sourceIndex] val destStack = stacks[destIndex] repeat(count) { destStack.addFirst(sourceStack.removeFirst()) } } val result = stacks.joinToString("") { it.first() } println(result) check(result == "BWNCQRMDB") } fun part2(input: List<String>) { val split = input.indexOf("") val config = input.subList(0, split) val stacks = parseConfig(config) val commands = input.subList(split + 1, input.size) commands.forEach { commandLine -> val command = commandLine.split(" ") val count = command[1].toInt() val sourceIndex = command[3].toInt() - 1 val destIndex = command[5].toInt() - 1 val sourceStack = stacks[sourceIndex] val destStack = stacks[destIndex] val pack = (1..count).map { sourceStack.removeFirst() } pack.reversed().forEach { destStack.addFirst(it) } } val result = stacks.joinToString("") { it.first() } println(result) check(result == "NHWZCBNBF") } val testInput = readInput("day05/day05") part1(testInput) part2(testInput) }
0
Kotlin
0
0
456bedb4d1082890d78490d3b730b2bb45913fe9
2,466
aoc-2022
Apache License 2.0
src/main/kotlin/Sand.kt
alebedev
573,733,821
false
{"Kotlin": 82424}
fun main() = Sand.solve() private object Sand { fun solve() { val input = readInput() val (grid, start) = inputToGrid(input) drawGrid(grid) println("Start: $start") drawGrid(addSand(grid, start)) } private fun addSand(grid: List<MutableList<Cell>>, start: Pos): List<List<Cell>> { val result = grid.map { it.toMutableList() } fun nextPos(pos: Pos): Pos? { val variants = listOf( Pos(pos.x, pos.y + 1), Pos(pos.x - 1, pos.y + 1), Pos(pos.x + 1, pos.y + 1) ) for (variant in variants) { if (variant.y >= result.size) { return null } if (variant.x < 0 || variant.x >= result.first().size) { return null } if (result[variant.y][variant.x] == Cell.Empty) { return variant } } return pos } fun percolate(): Boolean { var pos = start while (true) { val next = nextPos(pos) ?: return false if (next == pos) { result[pos.y][pos.x] = Cell.Sand return pos != start } pos = next } } var iterations = 1 while (percolate()) { iterations += 1 } println("Iterations: $iterations") return result } private fun readInput(): List<List<Pos>> { return generateSequence(::readLine).map { it.splitToSequence(" -> ").map { val parts = it.split(",") Pos(parts[0].toInt(10), parts[1].toInt(10)) }.toList() }.toList() } private fun inputToGrid(input: List<List<Pos>>): Pair<List<MutableList<Cell>>, Pos> { val start = Pos(500, 0) val positions = input.flatten() val minX = minOf(start.x, positions.map { it.x }.min()) - 200 val maxX = maxOf(start.x, positions.map { it.x }.max()) + 200 val minY = minOf(start.y, positions.map { it.y }.min()) val maxY = maxOf(start.y, positions.map { it.y }.max()) + 2 println("$minX $maxX $minY $maxY") val result = mutableListOf<MutableList<Cell>>() for (y in minY..maxY) { val line = mutableListOf<Cell>() for (x in minX..maxX) { line.add(Cell.Empty) } result.add(line) } fun fillWithRock(grid: List<MutableList<Cell>>, from: Pos, to: Pos) { // println("$from $to") if (from.x != to.x) { val src = Pos(minOf(from.x, to.x), from.y) val dst = Pos(maxOf(from.x, to.x), from.y) for (x in src.x..dst.x) { grid[src.y - minY][x - minX] = Cell.Rock } } else { val src = Pos(from.x, minOf(from.y, to.y)) val dst = Pos(from.x, maxOf(from.y, to.y)) for (y in src.y..dst.y) { grid[y - minY][src.x - minX] = Cell.Rock } } } for (rock in input) { val points = rock.toMutableList() var from = points.removeFirst() while (!points.isEmpty()) { val to = points.removeFirst() fillWithRock(result, from, to) from = to } } fillWithRock(result, Pos(minX, maxY), Pos(maxX, maxY)) return Pair(result, Pos(start.x - minX, start.y - minY)) } private fun drawGrid(grid: List<List<Cell>>) { for (line in grid) { println(line.map { when (it) { Cell.Empty -> '.' Cell.Rock -> '#' Cell.Sand -> 'o' } }.joinToString("")) } } enum class Cell { Empty, Rock, Sand, } data class Pos(val x: Int, val y: Int) : Comparable<Pos> { override fun compareTo(other: Pos): Int { val cmpX = x.compareTo(other.x) if (cmpX != 0) { return cmpX } val cmpY = y.compareTo(other.y) if (cmpY != 0) { return cmpY } return 0 } } }
0
Kotlin
0
0
d6ba46bc414c6a55a1093f46a6f97510df399cd1
4,436
aoc2022
MIT License
src/Day10.kt
OskarWalczak
573,349,185
false
{"Kotlin": 22486}
fun main() { fun readRegisterValues(input: List<String>): Map<Int, Int>{ val registerValues: MutableMap<Int, Int> = HashMap() registerValues[0] = 1 var currentCycleNumber = 1 input.forEach { line -> if (line.trim() == "noop"){ if(registerValues[currentCycleNumber] == null) registerValues[currentCycleNumber] = registerValues[currentCycleNumber - 1]!! currentCycleNumber++ } else if(line.startsWith("addx")){ val numberToAdd = line.split(' ').last().toInt() if(registerValues[currentCycleNumber] == null) registerValues[currentCycleNumber] = registerValues[currentCycleNumber - 1]!! currentCycleNumber++ if(registerValues[currentCycleNumber] == null) registerValues[currentCycleNumber] = registerValues[currentCycleNumber - 1]!! currentCycleNumber++ registerValues[currentCycleNumber] = registerValues[currentCycleNumber-1]!! + numberToAdd } } return registerValues } fun part1(input: List<String>): Int { val registerValues = readRegisterValues(input) var cycleSums = 0 for(i in 20 until registerValues.size step 40) cycleSums += registerValues[i]!! * i return cycleSums } fun part2(input: List<String>) { val registerValues = readRegisterValues(input) val crtVals: Array<CharArray> = Array(6){CharArray(40)} for(i in crtVals.indices){ for( j in crtVals[i].indices){ crtVals[i][j] = '.' } } registerValues.forEach { (index, value) -> val newIndex = (index-1) if(newIndex.mod(40) in value-1..value+1){ crtVals[newIndex.div(40)][newIndex.mod(40)] = '#' } } for(i in crtVals.indices){ for( j in crtVals[i].indices){ print(crtVals[i][j]) } println() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
d34138860184b616771159984eb741dc37461705
2,363
AoC2022
Apache License 2.0
src/2022/Day20.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun mixing(coordinates: List<Long>, items: MutableList<IndexedValue<Long>>, iterations: Int) { repeat(iterations) { coordinates.forEachIndexed { coordIndex, coord -> val index = items.indexOfFirst { it.index == coordIndex } if (coord < 0L) { items.removeAt(index) var nextIndex = index + coord if (nextIndex <= 0L) { val nums = (nextIndex / items.size) * -1 + 1 nextIndex += nums * items.size } items.add(nextIndex.toInt(), IndexedValue(coordIndex, coord)) } else if (coord > 0L) { items.removeAt(index) var nextIndex = index + coord if (nextIndex >= items.size.toLong()) { val nums = (nextIndex / items.size) nextIndex -= nums * items.size } items.add(nextIndex.toInt(), IndexedValue(coordIndex, coord)) } } } } fun part1(input: List<String>): Long { val coordinates = input.map { it.toLong() } val state = coordinates.withIndex().toMutableList() mixing(coordinates, state, 1) val index = state.indexOfFirst { it.value == 0L } return state[(index + 1000) % coordinates.size].value + state[(index + 2000) % coordinates.size].value + state[(index + 3000) % coordinates.size].value } fun part2(input: List<String>): Long { val coordinates = input.map { it.toLong() * 811589153 } val state = coordinates.withIndex().toMutableList() mixing(coordinates, state, 10) val index = state.indexOfFirst { it.value == 0L } return state[(index + 1000) % coordinates.size].value + state[(index + 2000) % coordinates.size].value + state[(index + 3000) % coordinates.size].value } // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
2,363
aoc-2022-in-kotlin
Apache License 2.0
src/Day05.kt
paulbonugli
574,065,510
false
{"Kotlin": 13681}
typealias Stacks = Array<ArrayDeque<Char>> val UPPERCASE_LETTERS = "([A-Z])".toRegex() fun makeStacks(lines : List<String>) : Stacks { var stackLines = lines.takeWhile { it.isNotBlank() } val numStacks = stackLines.last().split(" ").last().toInt() stackLines = stackLines.dropLast(1) val stacks : Stacks = Array(numStacks) { ArrayDeque(stackLines.size) } stackLines.reversed().forEach{ line -> line.chunked(4) .forEachIndexed {i, pos -> UPPERCASE_LETTERS.find(pos)?.value?.first()?.let { ch -> stacks[i].add(ch) } } } return stacks } fun printStacks(stacks : Stacks) { stacks.forEach(::println) } fun getMsg(stacks : Stacks) : String { return String(stacks.mapNotNull { it.lastOrNull() }.toCharArray()) } fun main() { val inputLines = readInput("Day05") val stacksPart1 = makeStacks(inputLines) val stacksPart2 = makeStacks(inputLines) val moves = inputLines.mapNotNull(Move::newMove) // part 1 moves.forEach {move -> repeat(move.numToMove) { stacksPart1[move.toStack].add(stacksPart1[move.fromStack].removeLast()) } } // part 2 moves.forEach {move -> val cratesToMove = (1..move.numToMove).map { stacksPart2[move.fromStack].removeLast() } stacksPart2[move.toStack].addAll(cratesToMove.reversed()) } println("Part 1: ${getMsg(stacksPart1)}") println("Part 2: ${getMsg(stacksPart2)}") } data class Move(val numToMove: Int, val fromStack: Int, val toStack: Int) { companion object { fun newMove(input: String) : Move? { "^move (\\d+) from (\\d) to (\\d)" .toRegex() .matchEntire(input) ?.let { val (numToMove, fromStack, toStack) = it.destructured return Move(numToMove.toInt(), fromStack.toInt()-1, toStack.toInt()-1) } return null } } }
0
Kotlin
0
0
d2d7952c75001632da6fd95b8463a1d8e5c34880
1,959
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/be/seppevolkaerts/day8/Day8.kt
Cybermaxke
727,453,020
false
{"Kotlin": 35118}
package be.seppevolkaerts.day8 class Data( val instructions: String, val nodes: List<Node> ) interface Node { val key: String val left: Node? val right: Node? } fun parseData(iterable: Iterable<String>): Data { val instructions = iterable.first() data class NodeImpl( override val key: String, val leftKey: String, val rightKey: String, ) : Node { override var left: NodeImpl? = null override var right: NodeImpl? = null } val nodeRegex = "(\\w+) = \\((\\w+), (\\w+)\\)".toRegex() val nodes = iterable.asSequence().drop(2) .map { value -> val match = nodeRegex.find(value) ?: error("Unexpected: $value") NodeImpl(match.groupValues[1], match.groupValues[2], match.groupValues[3]) } .toList() val nodesByKey = nodes.associateBy { it.key } nodes.forEach { node -> node.left = if (node.leftKey == node.key) null else nodesByKey[node.leftKey]!! node.right = if (node.rightKey == node.key) null else nodesByKey[node.rightKey]!! } return Data(instructions, nodes) } const val Left = 'L' const val Right = 'R' fun List<Node>.stepsUntilEnd(instructions: String): Int { var result = first { it.key == "AAA" } var steps = 0 while (result.key != "ZZZ") { val instruction = instructions[steps++ % instructions.length] result = when (instruction) { Left -> result.left ?: error("Reached end") Right -> result.right ?: error("Reached end") else -> error("Unexpected instruction: $instruction") } } return steps } private tailrec fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) private fun lcm(a: Long, b: Long): Long = (a * b) / gcd(a, b) private fun Iterable<Long>.lcm() = reduce { acc, l -> lcm(acc, l) } fun List<Node>.ghostStepsUntilEnd(instructions: String): Long { val nodes = filter { it.key.endsWith("A") }.toMutableList() val minima = ArrayList<Long>(nodes.size) var steps = 0 while (nodes.isNotEmpty()) { val instruction = instructions[steps++ % instructions.length] val itr = nodes.listIterator() while (itr.hasNext()) { var node = itr.next() node = when (instruction) { Left -> node.left ?: error("Reached end") Right -> node.right ?: error("Reached end") else -> error("Unexpected instruction: $instruction") } if (node.key.endsWith("Z")) { minima.add(steps.toLong()) itr.remove() } else { itr.set(node) } } } return minima.lcm() }
0
Kotlin
0
1
56ed086f8493b9f5ff1b688e2f128c69e3e1962c
2,494
advent-2023
MIT License
codeforces/codeton6/e.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.codeton6 import java.util.BitSet private fun solve(): Int { readln() val a = readInts() val highMex = (a.size + 1).takeHighestOneBit() * 2 val mark = IntArray(a.size + 1) { -1 } val memo = List(highMex) { BitSet() } val dp = mutableListOf(BitSet()) val (dpMax, dpSum) = List(2) { IntArray(a.size + 1) { 0 } } dp[0][0] = true dpSum[0] = 1 var leastAbsent = 1 for (i in a.indices) { val dpCurrent = dp[i].clone() as BitSet var mex = 0 for (j in i downTo 0) { mark[a[j]] = i if (a[j] == mex) { while (mark[mex] == i) mex++ val t = (dpMax[j] or mex).takeHighestOneBit() * 2 - 1 if (leastAbsent > t) continue val memoJ = memo[dpSum[j]] if (memoJ[mex]) continue memoJ[mex] = true val dpJ = dp[j] for (k in 0..dpMax[j]) if (dpJ[k]) dpCurrent[k xor mex] = true while (dpCurrent[leastAbsent]) leastAbsent++ } } dp.add(dpCurrent) dpSum[i + 1] = dpCurrent.cardinality() dpMax[i + 1] = dpCurrent.length() - 1 } return dpMax.last() } fun main() = repeat(readInt()) { println(solve()) } private fun readInt() = readln().toInt() private fun readStrings() = readln().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,215
competitions
The Unlicense
src/main/kotlin/Day03.kt
uipko
572,710,263
false
{"Kotlin": 25828}
val characters = ('a'..'z') + ('A'..'Z') fun main() { val items = doubleItems("Day03.txt").sum() println("The total sum of double items is: $items") val badges = badges("Day03.txt").sum() println("The total sum of double items is: $badges") } fun doubleItems(fileName: String): List<Int> { return readInput(fileName).map { rucksack -> val parts = rucksack.chunked(rucksack.length / 2) parts.first().toCharArray().distinct().filter { parts.last().contains(it) }.sumOf { characters.indexOf(it) + 1 } } } fun badges(fileName: String): List<Int> { return readInput(fileName).chunked(3).map { group -> group.first().toCharArray().distinct().filter { group[1].contains(it) && group[2].contains(it) }.sumOf { characters.indexOf(it) + 1 } } }
0
Kotlin
0
0
b2604043f387914b7f043e43dbcde574b7173462
807
aoc2022
Apache License 2.0
src/Day02.kt
mddanishansari
576,622,315
false
{"Kotlin": 11861}
fun main() { fun <T> List<T>.toPair(): Pair<T, T> { if (this.size != 2) { throw IllegalArgumentException("List is not of length 2!") } return Pair(this[0], this[1]) } fun round(round: String): Pair<String, String> { return round.replace("X", "A") .replace("Y", "B") .replace("Z", "C") .split(" ") .toPair() } fun part1(input: List<String>): Int { // A, X = Rock // B, Y = Paper // C, Z = Scissor fun decideWinnerAndGetScore(opponentSelection: String, playerSelection: String): Int { // Draw if (opponentSelection == playerSelection) return 3 // Won if ((playerSelection == "A" && opponentSelection == "C") || (playerSelection == "B" && opponentSelection == "A") || (playerSelection == "C" && opponentSelection == "B") ) return 6 // Lost return 0 } var score = 0 input.forEach { val (opponentSelection, playerSelection) = round(it) score += when (playerSelection) { "A" -> 1 "B" -> 2 "C" -> 3 else -> 0 } score += decideWinnerAndGetScore(opponentSelection, playerSelection) } return score } fun part2(input: List<String>): Int { fun calculateScore(opponentSelection: String, whatToDo: String): Int { // Player has to Draw if (whatToDo == "B") { if (opponentSelection == "A") return 1 if (opponentSelection == "B") return 2 if (opponentSelection == "C") return 3 } // Player has to Lose if (whatToDo == "A") { if (opponentSelection == "A") return 3 if (opponentSelection == "B") return 1 if (opponentSelection == "C") return 2 } // Player has to Win if (opponentSelection == "A") return 2 if (opponentSelection == "B") return 3 if (opponentSelection == "C") return 1 // Dafuq? return 0 } var score = 0 input.forEach { val (opponentSelection, whatToDo) = round(it) score += when (whatToDo) { "A" -> 0 "B" -> 3 "C" -> 6 else -> 0 } score += calculateScore(opponentSelection, whatToDo) } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") part1(input).println() part2(input).println() }
0
Kotlin
0
0
e032e14b57f5e6c2321e2b02b2e09d256a27b2e2
2,927
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/lucaszeta/adventofcode2020/day16/part2.kt
LucasZeta
317,600,635
false
null
package com.lucaszeta.adventofcode2020.day16 fun identifyFieldIndex( nearbyTickets: List<List<Int>>, ticketFields: Map<String, List<IntRange>> ): Map<String, Int> { val possibilities = findPossibleIndexesForFields(nearbyTickets, ticketFields) val resultMap = mutableMapOf<String, Int>() while (resultMap.size < ticketFields.size) { val fieldsThatCanOnlyBeInOnePlace = possibilities.filterValues { it.size == 1 } for (field in fieldsThatCanOnlyBeInOnePlace) { val index = field.value.first() resultMap[field.key] = index possibilities.forEach { it.value.remove(index) } } } return resultMap } fun filterValidTickets( nearbyTickets: List<List<Int>>, ticketFields: Map<String, List<IntRange>> ) = nearbyTickets.filter { nearbyTicket -> for (value in nearbyTicket) { val valid = ticketFields.any { value in it.value.first() || value in it.value.last() } if (!valid) { return@filter false } } return@filter true } private fun findPossibleIndexesForFields( nearbyTickets: List<List<Int>>, ticketFields: Map<String, List<IntRange>> ): MutableMap<String, MutableSet<Int>> { val possibilities = mutableMapOf<String, MutableSet<Int>>() for (ticketField in ticketFields) { val possibleIndexes = nearbyTickets .map { nearbyTicket -> val matchingIndexes = mutableSetOf<Int>() nearbyTicket.forEachIndexed { index, value -> if (value in ticketField.value.first() || value in ticketField.value.last()) { matchingIndexes.add(index) } } return@map matchingIndexes } .filterNot { it.isEmpty() } .reduce { accumulator, currentIndexes -> accumulator.intersect(currentIndexes).toMutableSet() } possibilities[ticketField.key] = possibleIndexes } return possibilities }
0
Kotlin
0
1
9c19513814da34e623f2bec63024af8324388025
2,098
advent-of-code-2020
MIT License
src/day3/Day03.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
import java.math.BigInteger private fun createResult(text: String): BigInteger { var result = BigInteger.ZERO for (item in text) { val index = item - if (item.isUpperCase()) 'A' - 26 else 'a' result = result or (BigInteger.ONE shl index) } return result } private fun findIndex(item: BigInteger): Int { var temp = item for (index in 0 until 52) { if ((temp and BigInteger.ONE) == BigInteger.ONE) { return index } temp = temp shr 1 } return -1 } private fun part1(input: List<String>): Int { var result = 0 for (rucksack in input) { val size = rucksack.length / 2 val firstResult = createResult(rucksack.substring(0, size)) val secondResult = createResult(rucksack.substring(size)) result += findIndex(firstResult and secondResult) + 1 } return result } private fun part2(input: List<String>): Int { var result = 0 var temp = (BigInteger.ONE shr 52) - BigInteger.ONE for ((index, item) in input.withIndex()) { val itemResult = createResult(item) temp = temp and itemResult if ((index + 1) % 3 == 0) { result += findIndex(temp) + 1 temp = (BigInteger.ONE shr 52) - BigInteger.ONE } } return result } fun main() { val input = readInput("day3/input") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
1,421
aoc-2022
Apache License 2.0
src/main/kotlin/problems/Day8.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems class Day8(override val input: String) : Problem { override val number: Int = 8 private val entries: List<Entry> = input.lines().map { Entry.fromString(it) } override fun runPartOne(): String { return entries .flatMap { entry -> entry.outputValues } .count { outputValue -> outputValue.length in 2..4 || outputValue.length == 7 } .toString() } override fun runPartTwo(): String { return entries .sumOf { entry -> entry.output() } .toString() } private data class Entry(val signalPatterns: List<String>, val outputValues: List<String>) { companion object { fun fromString(str: String): Entry { val (signalPatterns, outputValues) = str.split(" | ") return Entry( signalPatterns.split(" "), outputValues.split(" ") ) } } private enum class Segment { A, B, C, D, E, F, G; } val digits = mapOf( 1 to signalPatterns.single { pattern -> pattern.length == 2 }.toSet(), 4 to signalPatterns.single { pattern -> pattern.length == 4 }.toSet(), 7 to signalPatterns.single { pattern -> pattern.length == 3 }.toSet(), ) private val segmentsToDigit = mapOf( setOf(Segment.A, Segment.C, Segment.F, Segment.G, Segment.E, Segment.B) to '0', setOf(Segment.C, Segment.F) to '1', setOf(Segment.A, Segment.C, Segment.G, Segment.E, Segment.D) to '2', setOf(Segment.A, Segment.C, Segment.F, Segment.G, Segment.D) to '3', setOf(Segment.C, Segment.F, Segment.B, Segment.D) to '4', setOf(Segment.A, Segment.F, Segment.G, Segment.B, Segment.D) to '5', setOf(Segment.A, Segment.F, Segment.G, Segment.E, Segment.B, Segment.D) to '6', setOf(Segment.A, Segment.C, Segment.F) to '7', setOf(Segment.A, Segment.C, Segment.F, Segment.G, Segment.E, Segment.B, Segment.D) to '8', setOf(Segment.A, Segment.C, Segment.F, Segment.G, Segment.B, Segment.D) to '9', ) private val hits = signalPatterns .flatMap { it.toCharArray().toList() } .groupingBy { it } .eachCount() private val charToSegment: Map<Char, Segment> = mapOf( segmentAChar() to Segment.A, segmentBChar() to Segment.B, segmentCChar() to Segment.C, segmentDChar() to Segment.D, segmentEChar() to Segment.E, segmentFChar() to Segment.F, segmentGChar() to Segment.G, ) fun output(): Int { return outputValues .map { value -> valueToSegments(value) } .map { segments -> segmentsToDigit[segments]!! } .joinToString(separator = "") .toInt() } private fun valueToSegments(value: String): Set<Segment> { return value.toCharArray() .map { charToSegment[it]!! } .toSet() } private fun segmentAChar(): Char { return (digits[7]!! - digits[1]!!).single() } private fun segmentBChar(): Char { return hits.filterValues { hits -> hits == 6 } .keys .single() } private fun segmentCChar(): Char { return hits.filter { (char, hits) -> hits == 8 && char != segmentAChar() } .keys .single() } private fun segmentDChar(): Char { return (digits[4]!! - digits[1]!! - segmentBChar()).single() } private fun segmentEChar(): Char { return hits.filterValues { hits -> hits == 4 } .keys .single() } private fun segmentFChar(): Char { return hits.filterValues { hits -> hits == 9 } .keys .single() } private fun segmentGChar(): Char { return hits.filter { (char, hits) -> hits == 7 && char != segmentDChar() } .keys .single() } } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
4,261
AdventOfCode2021
MIT License
src/Day04.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
fun main() { fun parseElfPairs(input: List<String>): List<Pair<InclusiveRange, InclusiveRange>> { return input.map { line-> val points = line.split(',', '-').map { it.toInt() } check(points.size == 4) Pair(InclusiveRange(points[0], points[1]), InclusiveRange(points[2], points[3])) } } fun part1(input: List<String>): Int { val elfPairs = parseElfPairs(input) return elfPairs.count { (elf1, elf2) -> elf1.fullyContains(elf2) || elf2.fullyContains(elf1) } } fun part2(input: List<String>): Int { val elfPairs = parseElfPairs(input) return elfPairs.count { (elf1, elf2) -> elf1.overlaps(elf2) } } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
906
aoc2022
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/RiverSize.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.graph import java.util.* fun riverSizes(matrix: List<List<Int>>): List<Int> { val visited = List(matrix.size) { MutableList(matrix[0].size) { false } } val result = mutableListOf<Int>() for (i in 0 until matrix.size) { for (j in 0 until matrix[0].size) { if (visited[i][j]) { continue } traverse(matrix, visited, result, Pair(i, j)) } } return result } fun traverse(matrix: List<List<Int>>, visited: List<MutableList<Boolean>>, result: MutableList<Int>, pair: Pair<Int, Int>) { val queue = ArrayDeque<Pair<Int, Int>>() queue.add(pair) var currentRiverSize = 0 while (queue.isNotEmpty()) { var node = queue.poll() if (visited[node.first][node.second]) continue visited[node.first][node.second] = true if (matrix[node.first][node.second] == 0) continue currentRiverSize++ val neighbours = getNeighbours(node, visited, matrix) for (neighbour in neighbours){ queue.add(neighbour) } } if (currentRiverSize > 0) result.add(currentRiverSize) } fun getNeighbours(node: Pair<Int, Int>, visited: List<List<Boolean>>, matrix: List<List<Int>>): List<Pair<Int, Int>> { // left, right, top, bottom val unvisitedArray = mutableListOf<Pair<Int, Int>>() val x = node.first val y = node.second if (x > 0 && !visited[x - 1][y]) { unvisitedArray.add(Pair(x-1, y)) } if (x < matrix.size - 1 && !visited[x + 1][y]){ unvisitedArray.add(Pair(x+1, y)) } if (y > 0 && !visited[x][y - 1]) { unvisitedArray.add(Pair(x, y-1)) } if (y < matrix[0].size - 1 && !visited[x][y + 1]){ unvisitedArray.add(Pair(x, y + 1)) } return unvisitedArray }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,844
DS_Algo_Kotlin
MIT License
src/main/kotlin/adventofcode2023/day1/day1.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day1 import adventofcode2023.readInput fun main() { val list = readInput("day1.txt") println("Day 1") println("Puzzle 1 : ${puzzle1(list)}") println("Puzzle 2 : ${puzzle2(list)}") } fun puzzle1(input: List<String>): Int { return input.sumOf { l -> l.first(Char::isDigit).digitToInt() * 10 + l.last(Char::isDigit).digitToInt() } } fun puzzle2(input: List<String>): Int = input.map(::processLine).sum() private val wordsMapping = arrayOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9 ) fun processLine(line: String): Int { var firstIndexWord = -1 var firstValueWord = 0 var lastIndexWord = -1 var lastValueWord = 0 wordsMapping.forEach { (w, v) -> val i = line.indexOf(w) if (i > -1 && (firstIndexWord == -1 || i < firstIndexWord)) { firstIndexWord = i firstValueWord = v } val li = line.lastIndexOf(w) if (li > -1 && (lastIndexWord == -1 || li > lastIndexWord)) { lastIndexWord = li lastValueWord = v } } val firstIndexDigit = line.indexOfFirst(Char::isDigit) val firstDigit = if (firstIndexDigit > -1 && (firstIndexWord == -1 || firstIndexDigit < firstIndexWord)) { line[firstIndexDigit].digitToInt() } else { firstValueWord } val lastIndexDigit = line.indexOfLast(Char::isDigit) val secondDigit = if (lastIndexDigit > lastIndexWord) { line[lastIndexDigit].digitToInt() } else { lastValueWord } return firstDigit * 10 + secondDigit }
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
1,684
adventofcode2023
MIT License
src/Day02/Day02.kt
JamesKing95
574,470,043
false
{"Kotlin": 7225}
package Day02 import readInput fun main() { val testInput = readInput("Day02/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02/Day02") println("Part 1: ".plus(part1(input))) println("Part 2: ".plus(part2(input))) } fun part1(input: List<String>): Int { var totalScore = 0 input.forEach{ round -> val roundPicks = round.split(" ") totalScore += playMatch(roundPicks[0], roundPicks[1]) } return totalScore } fun playMatch(opponentPick: String, myPick: String): Int { val opponentPickOption = getOptionFromCode(opponentPick) val myPickOption = getOptionFromCode(myPick) val outcomeScore = if((myPickOption == Option.ROCK && opponentPickOption == Option.SCISSORS) || (myPickOption.weight > opponentPickOption.weight && !(myPickOption == Option.SCISSORS && opponentPickOption == Option.ROCK))){ 6 } else if(myPickOption.weight == opponentPickOption.weight) { 3 } else { 0 } val totalScore = outcomeScore + myPickOption.weight return totalScore } fun part2(input: List<String>): Int { var totalScore = 0 input.forEach{ round -> val roundPicks = round.split(" ") val option = getOptionFromCode(roundPicks[0]) val optionToPlay: Option if(roundPicks[1] == "X") { // Lose val weight = option.weight - 1 optionToPlay = if(weight != 0) { getOptionByWeight(weight) } else { Option.SCISSORS } } else if(roundPicks[1] == "Y") { //Draw optionToPlay = getOptionByWeight(option.weight) } else { // Win val weight = option.weight + 1 optionToPlay = if(weight > 3) { Option.ROCK } else { getOptionByWeight(weight) } } totalScore += playMatch(roundPicks[0], optionToPlay.code) } return totalScore }
0
Kotlin
0
0
cf7b6bd5ae6e13b83d871dfd6f0a75b6ae8f04cf
2,078
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/Day7.kt
pavittr
317,532,861
false
null
import java.io.File import java.nio.charset.Charset fun main() { fun countOptions(policyLines: List<String>): Int { val policies = policyLines.associate { policy -> val separators = policy.split("bags contain"); Pair( separators[0].trim(), separators[1].dropLast(1).replace("bags", "").replace("bag", "").split(",") .map { containers -> containers.trim().split(" ").drop(1).filter { it != "other" }.joinToString(" ") }) } fun findChildren(curreLevel: String): List<String> { val directChildren = policies.getOrDefault(curreLevel, listOf()) val allChildren = directChildren.map { findChildren(it) }.flatMap { it }.filter { it.isNotEmpty() } return directChildren.union(allChildren).toList() } val policyParents = policies.keys return policyParents.map { findChildren(it) }.filter { it.contains("shiny gold") }.size } val testDocs = File("test/day7").readLines(Charset.defaultCharset()) val puzzles = File("puzzles/day7").readLines(Charset.defaultCharset()) println(countOptions(testDocs)) println(countOptions(puzzles)) fun countBags(policyLines: List<String>): Int { val policies = policyLines.associate { policy -> val separators = policy.split("bags contain"); Pair( separators[0].trim(), separators[1].dropLast(1).replace("bags", "").replace("bag", "").split(",") .map { containers -> containers.trim().let{val description = it.replace("no other", "0 adjectivised colour").split(" "); Pair(description[0].toInt(), description[1] + " " + description[2] )}}) } fun findSubBags(entrybag: String): Int { val bagChildren = policies.getOrDefault(entrybag, listOf()) return 1 + bagChildren.map { findSubBags(it.second) * it.first }.sum() } return findSubBags("shiny gold") -1 } println(countBags(testDocs)) println(countBags(puzzles)) }
0
Kotlin
0
0
3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04
2,039
aoc2020
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2021/d13/Day13.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2021.d13 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.points.Point import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines import kotlin.math.min // e.g. y=3 corresponds to Fold(along=3, isHorizontal=true) private data class Fold(val along: Int, val isHorizontal: Boolean) private class Solution(originalPoints: Set<Point>, private val folds: List<Fold>) { private var points = originalPoints private var foldIdx = 0 fun fold() { val (foldAlong, foldIsHorizontal) = folds[foldIdx] points = points.mapTo(mutableSetOf()) { (x, y) -> if (foldIsHorizontal) { Point(x, min(y, 2 * foldAlong - y)) } else { Point(min(x, 2 * foldAlong - x), y) } } foldIdx++ } fun doAllFolds() { repeat(folds.size - foldIdx) { fold() } } val numPoints get() = points.size fun drawPaper() { val maxX = points.maxOf { it.x } val maxY = points.maxOf { it.y } (0..maxY).forEach { y -> (0..maxX).forEach { x -> if (Point(x, y) in points) print("#") else print(".") } println() } } } fun main() = timed { val solution = (DATAPATH / "2021/day13.txt").useLines { lines -> val points = mutableSetOf<Point>() val folds = mutableListOf<Fold>() var readPoints = true lines.forEach { line -> when { line.isBlank() -> { readPoints = false } readPoints -> { val (x, y) = line.split(",") points.add(Point(x.toInt(), y.toInt())) } else -> { val (direction, along) = line.substring(11).split("=") folds.add(Fold(along.toInt(), direction == "y")) } } } Solution(points, folds) } solution.fold() println("Part one: ${solution.numPoints}") solution.doAllFolds() println("\nPart two:") solution.drawPaper() }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,222
advent-of-code
MIT License
src/Day02.kt
daletools
573,114,602
false
{"Kotlin": 8945}
fun main() { fun part1(input: List<String>): Int { var score = 0 for (match in input) { val elf = match.first() val player = match.last() when (player) { 'X' -> score += 1 'Y' -> score += 2 'Z' -> score += 3 } if (elf - 'A' == player - 'X') { score += 3 continue } when (elf) { 'A' -> { if (player == 'Y') { score += 6 } } 'B' -> { if (player == 'Z') { score += 6 } } 'C' -> { if (player == 'X') { score += 6 } } } } return score } fun part2(input: List<String>): Int { var score = 0 val match = mapOf<Pair<Char, Char>, Int>( Pair('A', 'X') to 3, Pair('A', 'Y') to 4, Pair('A', 'Z') to 8, Pair('B', 'X') to 1, Pair('B', 'Y') to 5, Pair('B', 'Z') to 9, Pair('C', 'X') to 2, Pair('C', 'Y') to 6, Pair('C', 'Z') to 7 ) for (round in input) { val elf = round.first() val result = round.last() score += match[Pair(elf, result)] ?: 0 } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println("Part 1 Test:") println(part1(testInput)) println("Part 2 Test:") println(part2(testInput)) val input = readInput("Day02") println("Part 1:") println(part1(input)) println("Part 2:") println(part2(input)) }
0
Kotlin
0
0
c955c5d0b5e19746e12fa6a569eb2b6c3bc4b355
1,853
adventOfCode2022
Apache License 2.0
src/year2022/day10/Day.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2022.day10 import kotlin.math.abs import readInput fun main() { val day = "10" val expectedTest1 = 13140 val expectedTest2 = """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """.trimIndent() fun asTimedOperations(input: List<String>) = input.flatMap { when (it) { "noop" -> listOf(0) else -> listOf(0, it.split(" ")[1].toInt()) } } fun part1(input: List<String>): Int { val cycles = asTimedOperations(input) return List(10) { 20 + (it * 40) }.takeWhile { it < cycles.size }.sumOf { val i = 1 + cycles.take(it - 1).sum() i * it } } fun part2(input: List<String>): String { val asTimedOperations = asTimedOperations(input) return (0..239).map { when (abs((it % 40) - (asTimedOperations.take(it).sum() + 1)) < 2) { true -> "#" else -> "." } }.chunked(40).joinToString("\n", "\n") { it.joinToString("") } } // test if implementation meets criteria from the description, like: val testInput = readInput("year2022/day$day/test") val part1Test = part1(testInput) check(part1Test == expectedTest1) { "expected $expectedTest1 but was $part1Test" } val input = readInput("year2022/day$day/input") println(part1(input)) val part2Test = part2(testInput) check(part2Test == expectedTest2) { "expected $expectedTest2 but was $part2Test" } println(part2(input)) }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
1,780
adventOfCode
Apache License 2.0
src/main/kotlin/aoc/year2023/Day05.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2023 import aoc.Puzzle /** * [Day 5 - Advent of Code 2023](https://adventofcode.com/2023/day/5) */ object Day05 : Puzzle<Long, Long> { override fun solvePartOne(input: String): Long { val sections = input.split(Regex("(\\r?\\n){2}")) val seeds = sections.first().removePrefix("seeds: ").split(' ').map { it.toLong() } return sections.drop(1) .map { category -> category.lines() .drop(1) .map { line -> line.split(' ') .map { it.toLong() } .let { Mapping(it[0], it[1], it[2]) } } .sortedBy { it.srcStart } } .fold(seeds) { numbers, mappings -> numbers.map { number -> val index = mappings.binarySearchBy(number) { it.srcStart } .let { if (it < 0) -it - 2 else it } .coerceAtLeast(0) val (dstStart, srcStart, length) = mappings[index] if (number in srcStart..srcStart + length) { dstStart + number - srcStart } else { number } } } .min() } override fun solvePartTwo(input: String): Long = TODO() private data class Mapping(val dstStart: Long, val srcStart: Long, val length: Long) }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,510
advent-of-code
Apache License 2.0
src/day11/day11.kt
Eynnzerr
576,874,345
false
{"Kotlin": 23356}
package day11 import java.io.File import kotlin.math.absoluteValue fun main() { val rounds = 10000 val monkeys = File("src/day11/input.txt") .readLines() .split("") .map { val (items, operation, test, b1, b2) = it.drop(1) Monkey( items = extractNumbers(items), operate = constructActions(operation), testNum = extractNumbers(test).first(), next = extractNumbers(b1).first().toInt() to extractNumbers(b2).first().toInt() ) } val inspectCount = MutableList(monkeys.size) { 0 } // for part2: val cm = monkeys.map { it.testNum }.reduce { acc, i -> acc lcm i } repeat(rounds) { monkeys.forEachIndexed { index, monkey -> inspectCount[index] += monkey.items.size monkey.items.forEach { val level = monkey.operate(it) % cm // The problem says 'rounded down' val next = if (level % monkey.testNum == 0L) monkey.next.first else monkey.next.second monkeys[next].items.add(level) } monkey.items.clear() } } inspectCount.sortDescending() println("result: ${inspectCount[0].toULong() * inspectCount[1].toULong()}") } private fun <T> List<T>.split(vararg delimiters: T): List<List<T>> { val result = mutableListOf<List<T>>() var lastIndex = 0 this.forEachIndexed { index, t -> if (t in delimiters) { result.add(this.subList(lastIndex, index)) lastIndex = index + 1 } } result.add(this.subList(lastIndex, this.size)) return result } private fun extractNumbers(s: String) = Regex("[+-]?\\d+") .findAll(s) .map { it.value.toLong() } .toMutableList() private fun constructActions(s: String): (Level) -> Level { val (operator, operand) = s .substringAfter("old ") .split(" ") return when (operator) { "+" -> { old -> old + (operand.toLongOrNull() ?: old) } "*" -> { old -> old * (operand.toLongOrNull() ?: old) } else -> { old -> old } } } private infix fun Level.gcd(x: Level): Level = if (x == 0L) this.absoluteValue else x gcd (this % x) private infix fun Level.lcm(x: Level): Level = (this * x) / (this gcd x)
0
Kotlin
0
0
92e85d65f62900d98284cbc9f6f9a3010efb21b7
2,315
advent-of-code-2022
Apache License 2.0
src/Day07.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
import java.io.File // Advent of Code 2022, Day 07, No Space Left On Device fun main() { fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim() data class SubFile(val name: String, val size: Int) data class Node(val name: String, val parent: Node?, val files: MutableMap<String, SubFile> = mutableMapOf(), val subDirs: MutableMap<String, Node> = mutableMapOf(), var totalSize: Long = 0 ) fun calcTotal(input:Node): Long { input.totalSize = input.subDirs.values.fold(0L) { acc, next -> acc + calcTotal(next) } input.totalSize += input.files.values.sumOf { it.size } return input.totalSize } fun parse(input: String) : Node { val root = Node("/", null) var curr: Node = root val commands = input.split("$") for (cmd in commands) { val line = cmd.trim() if (line.isEmpty()) continue if (line == "cd /") { curr = root } else if (line == "cd ..") { curr = curr.parent!! // but in macOS it's ok to cd.. from / } else if (line.substring(0, 2) == "ls") { val contents = line.split("\n").map { it.trim() } for (sub in contents.drop(1)) { // drop initial empty string val parts = sub.split(" ").map{ it.trim() } if (parts[0].isEmpty()) continue if (parts[0] == "dir" ) { curr.subDirs[parts[1]] = Node(parts[1], curr) } else { curr.files[parts[1]] = SubFile(parts[1], parts[0].toInt()) } } } else { check("cd " == line.substring(0..2)) val dir = line.substring(3) check(curr.subDirs.contains(dir)) curr = curr.subDirs[dir]!! } } calcTotal(root) return root } fun part1(input:Node): Long { var overall = 0L val nodeQueue = mutableListOf<Node>() nodeQueue.add(input) while(nodeQueue.isNotEmpty()) { val node = nodeQueue.removeFirst() if (node.totalSize <= 100_000) { overall += node.totalSize } nodeQueue.addAll(node.subDirs.values) } return overall } fun part2(input:Node): Long { val freeSpace = 70_000_000L - input.totalSize val needToFree = 30_000_000L - freeSpace check(freeSpace > 0) val nodeQueue = mutableListOf<Node>() nodeQueue.add(input) var size = Long.MAX_VALUE while(nodeQueue.isNotEmpty()) { val node = nodeQueue.removeFirst() if (node.totalSize in needToFree until size) { size = node.totalSize } nodeQueue.addAll(node.subDirs.values) } return size } val testInput = parse(readInputAsOneLine("Day07_test")) check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = parse(readInputAsOneLine("Day07")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
3,273
AdventOfCode2022
Apache License 2.0
src/Day11.kt
dizney
572,581,781
false
{"Kotlin": 105380}
object Day11 { const val EXPECTED_PART1_CHECK_ANSWER = 10605L const val EXPECTED_PART2_CHECK_ANSWER = 2713310158 const val PART1_RUNS = 20 const val PART2_RUNS = 10_000 const val WORRY_LEVEL_DIVISION_AMOUNT = 3 val MONKEY_LINE_ITEMS = Regex("\\s+Starting items: ([, \\d]+)") val MONKEY_LINE_OPERATION = Regex("\\s+Operation: new = old ([+*]) (\\w+)") val MONKEY_LINE_TEST = Regex("\\s+Test: divisible by (\\d+)") val MONKEY_LINE_THROW = Regex("\\s+If (true|false): throw to monkey (\\d+)") } data class Item(var worryLevel: Long) class Monkey( startingItems: List<Item>, val operation: (Long) -> Long, val testDivisibleBy: Int, private val testTrueDestinationMonkey: Int, private val testFalseDestinationMonkey: Int, private val relieve: Boolean = true, ) { private val items: MutableList<Item> = startingItems.toMutableList() var itemsInspected = 0 private set fun addItems(items: List<Item>) { this.items.addAll(items) } fun turn(worryReduceVale: Int): Map<Int, List<Item>> { val itemsToThrow = mutableMapOf<Int, List<Item>>() for (item in items) { item.worryLevel = operation(item.worryLevel) if (relieve) { item.worryLevel /= Day11.WORRY_LEVEL_DIVISION_AMOUNT } item.worryLevel %= worryReduceVale itemsToThrow.compute( if (item.worryLevel % testDivisibleBy == 0L) testTrueDestinationMonkey else testFalseDestinationMonkey ) { _, currentItems -> (currentItems ?: emptyList()) + item } itemsInspected++ } items.clear() return itemsToThrow } } class MonkeyBusiness(private val monkeys: List<Monkey>) { private val worryReduceVale = monkeys.map { it.testDivisibleBy }.reduce(Int::times) private fun round() { monkeys.forEach { monkey -> val itemsToPass = monkey.turn(worryReduceVale) itemsToPass.forEach { (toMonkey, items) -> monkeys[toMonkey].addItems(items) } } } fun process(numberOfRounds: Int): Long { repeat(numberOfRounds) { round() } return monkeys.map { it.itemsInspected }.sortedDescending().take(2).let { it[0].toLong() * it[1].toLong() } } } fun main() { fun List<String>.parseMonkeyBusiness(doRelieve: Boolean = true): MonkeyBusiness { val monkeys = mutableListOf<Monkey>() var inputIdx = 1 while (inputIdx < size) { val (itemsWorryLevels) = Day11.MONKEY_LINE_ITEMS.matchEntire(this[inputIdx++])!!.destructured val items = itemsWorryLevels.split(",").map(String::trim).map { Item(it.toLong()) } val (operation, operationValue) = Day11.MONKEY_LINE_OPERATION.matchEntire(this[inputIdx++])!!.destructured val (testDivisibleValue) = Day11.MONKEY_LINE_TEST.matchEntire(this[inputIdx++])!!.destructured val (_, throwToWhenTrue) = Day11.MONKEY_LINE_THROW.matchEntire(this[inputIdx++])!!.destructured val (_, throwToWhenFalse) = Day11.MONKEY_LINE_THROW.matchEntire(this[inputIdx++])!!.destructured monkeys.add( Monkey( items, { val operand = when (operationValue) { "old" -> it else -> operationValue.toLong() } when (operation) { "*" -> it * operand "+" -> it + operand else -> error("Unknown operation $operation") } }, testDivisibleValue.toInt(), throwToWhenTrue.toInt(), throwToWhenFalse.toInt(), doRelieve, ) ) inputIdx += 2 } return MonkeyBusiness(monkeys) } fun part1(input: List<String>): Long { val monkeyBusiness = input.parseMonkeyBusiness() return monkeyBusiness.process(Day11.PART1_RUNS) } fun part2(input: List<String>): Long { val monkeyBusiness = input.parseMonkeyBusiness(false) return monkeyBusiness.process(Day11.PART2_RUNS) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == Day11.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" } check(part2(testInput) == Day11.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" } val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f684a4e78adf77514717d64b2a0e22e9bea56b98
4,764
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
frungl
573,598,286
false
{"Kotlin": 86423}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val (f, s) = it.split(' ') val fVal = when(f) { "A" -> 0 "B" -> 1 "C" -> 2 else -> -1 } val sVal = when(s) { "X" -> 0 "Y" -> 1 "Z" -> 2 else -> -1 } 1 + sVal + when(sVal) { fVal -> 3 (fVal + 1) % 3 -> 6 else -> 0 } } } fun part2(input: List<String>): Int { return input.sumOf { val (f, s) = it.split(' ') val fVal = when(f) { "A" -> 0 "B" -> 1 "C" -> 2 else -> -1 } val sVal = when(s) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> -1 } sVal + 1 + when(sVal) { 0 -> (fVal + 2) % 3 3 -> fVal 6 -> (fVal + 1) % 3 else -> -1 } } } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
1,377
aoc2022
Apache License 2.0
src/main/kotlin/aoc2023/day13/day13Solver.kt
Advent-of-Code-Netcompany-Unions
726,531,711
false
{"Kotlin": 94973}
package aoc2023.day13 import lib.* suspend fun main() { setupChallenge().solveChallenge() } fun setupChallenge(): Challenge<List<Area>> { return setup { day(13) year(2023) //input("example.txt") parser { it.getStringsGroupedByEmptyLine() .map { Area( it.toMutableList(), it.first().indices.map { i -> it.map { it[i] }.fold("") { s, c -> s + c } }.toMutableList() ) } } partOne { it.sumOf { it.findReflectionValue() } .toString() } partTwo { val mirrors = it.map { fixSmudges(it) to it.findReflectionValue() } var sum = 0L mirrors.forEach { val iterator = it.first.iterator() while(iterator.hasNext()) { val area = iterator.next() val res = area.findReflectionValue(it.second) if(res > 0) { sum += res break } } } sum.toString() } } } data class Area(val rows: MutableList<String>, val columns: MutableList<String>) fun Area.findReflectionValue(ignore: Long = 0): Long { (0 until columns.size - 1).forEach { i -> val start = 0..i val end = i + 1..minOf(start.last + start.size(), columns.size - 1) if (rows.all { it.substring(start).reversed().take(end.size()) == it.substring(end) }) { val res = (i + 1).toLong() if(res != ignore) { return res } } } (0 until rows.size - 1).forEach { i -> val start = 0..i val end = i + 1..minOf(start.last + start.size(), rows.size - 1) if (columns.all { it.substring(start).reversed().take(end.size()) == it.substring(end) }) { val res = (i + 1) * 100L if(res != ignore) { return res } } } return 0 } suspend fun fixSmudges(area: Area): Sequence<Area> = sequence { val rows = area.rows val columns = area.columns rows.indices.forEach { i -> columns.indices.forEach { j -> val newChar = rows[i][j].invert() val updatedRow = rows[i].take(j) + newChar + rows[i].takeLast(columns.size - (j + 1)) val updatedColumn = columns[j].take(i) + newChar + columns[j].takeLast(rows.size - (i + 1)) val newRows = rows.take(i) + updatedRow + rows.takeLast(rows.size - (i + 1)) val newColumns = columns.take(j) + updatedColumn + columns.takeLast(columns.size - (j + 1)) val res = Area(newRows.toMutableList(), newColumns.toMutableList()) yield(res) } } } fun Char.invert(): Char { return when (this) { '.' -> '#' '#' -> '.' else -> this } }
0
Kotlin
0
0
a77584ee012d5b1b0d28501ae42d7b10d28bf070
2,988
AoC-2023-DDJ
MIT License
app/src/main/java/com/pryanik/mastermind/logic/Mastermind.kt
oQaris
447,290,858
false
{"Kotlin": 28432}
package com.pryanik.mastermind.logic import com.google.common.collect.Collections2 import com.google.common.collect.Sets import com.google.common.math.LongMath import kotlin.math.min data class ResultGuess(val guess: String, val isWin: Boolean) data class BullsAndCows(val bulls: Int) fun genPossibleAnswers(values: List<Char> = ('1'..'6').toList(), k: Int) = Array(LongMath.checkedPow(values.size.toLong(), k).toInt()) { idx -> CharArray(k) { values[(idx / LongMath.pow(values.size.toLong(), k - 1 - it) % values.size).toInt()] } }.map { it.joinToString("") } fun getEverythingNotRepeat(values: List<Char>, k: Int) = Sets.combinations(values.toSet(), k) .flatMap { Collections2.orderedPermutations(it) } .map { it.toCharArray() } /** * Возвращает число быков и коров для текущей догадки */ fun evaluate(guess: String, answer: String): Pair<Int, Int> { val counterAnswer = answer.toList().counting() val matches = guess.toList().counting().entries .sumOf { (t, u) -> min(u, counterAnswer[t] ?: 0) } val bulls = guess.zip(answer).count { it.first == it.second } return bulls to matches - bulls } fun evaluateCows(guess: String, answer: String): Int { val counterAnswer = answer.toList().counting() var matches = 0 guess.toList().counting().forEach { (t, u) -> matches += min(u, counterAnswer[t] ?: 0) } val bulls = evaluateBulls(guess, answer) return matches - bulls } fun evaluateBulls(guess: String, answer: String) = guess.zip(answer).count { it.first == it.second } fun <T> Iterable<T>.counting() = groupingBy { it }.eachCount().toMap()
0
Kotlin
0
0
21c7a6874c1ca58c7c9cdf473e9d032a43002493
1,732
MasterMind
MIT License
src/day08/Day08.kt
martindacos
572,700,466
false
{"Kotlin": 12412}
package day08 import readInput fun main() { fun readMatrix(input: List<String>): List<List<Int>> { val matrix: MutableList<List<Int>> = mutableListOf() for (line in input) { matrix.add(line.toCharArray().map { c -> c.digitToInt() }) } return matrix } fun biggerInLine(treeLine: List<Int>, treeSize: Int): Boolean { val maxOrNull = treeLine.maxOrNull() ?: 0 return (treeSize > maxOrNull) } fun treesThanCanSee(treeLine: List<Int>, treeSize: Int): Int { var treesThanCanSee = 0 for (tree in treeLine) { if (tree < treeSize) treesThanCanSee++ else { treesThanCanSee++ break } } return treesThanCanSee } fun topToEdge(matrix: List<List<Int>>, i: Int, j: Int): List<Int> { val line: MutableList<Int> = mutableListOf() for (x in i - 1 downTo 0) { line.add(matrix[x][j]) } return line } fun leftToEdge(matrix: List<List<Int>>, i: Int, j: Int): List<Int> { val line: MutableList<Int> = mutableListOf() for (x in j - 1 downTo 0) { line.add(matrix[i][x]) } return line } fun downToEdge(matrix: List<List<Int>>, i: Int, j: Int): List<Int> { val line: MutableList<Int> = mutableListOf() for (x in i + 1 until matrix.size) { line.add(matrix[x][j]) } return line } fun rightToEdge(matrix: List<List<Int>>, i: Int, j: Int): List<Int> { val line: MutableList<Int> = mutableListOf() for (x in j + 1 until matrix[i].size) { line.add(matrix[i][x]) } return line } fun calculateVisibleTrees(input: List<String>): Int { /** 30373 25512 65332 33549 35390 */ val matrix = readMatrix(input) var visibleTrees = 0 for (i in matrix.indices) { for (j in 0 until matrix[i].size) { //print(matrix[i][j]) if (i == 0 || j == 0) visibleTrees++ else if (i == matrix.size - 1 || j == matrix[i].size - 1) visibleTrees++ else { val treeSize = matrix[i][j] if (biggerInLine(topToEdge(matrix, i, j), treeSize) || biggerInLine(leftToEdge(matrix, i, j), treeSize) || biggerInLine(downToEdge(matrix, i, j), treeSize) || biggerInLine(rightToEdge(matrix, i, j), treeSize) ) visibleTrees++ } } //println() } return visibleTrees } fun calculateHighestScenic(input: List<String>): Int { /** 30373 25512 65332 33549 35390 */ val matrix = readMatrix(input) var highestScenic = 0 for (i in matrix.indices) { for (j in 0 until matrix[i].size) { //print(matrix[i][j]) val treeSize = matrix[i][j] val topView = treesThanCanSee(topToEdge(matrix, i, j), treeSize) val leftView = treesThanCanSee(leftToEdge(matrix, i, j), treeSize) val downView = treesThanCanSee(downToEdge(matrix, i, j), treeSize) val rightView = treesThanCanSee(rightToEdge(matrix, i, j), treeSize) val scenic = topView * leftView * downView * rightView if (scenic > highestScenic) highestScenic = scenic } //println() } return highestScenic } // test if implementation meets criteria from the description, like: val testInput = readInput("/day08/Day08_test") check(calculateVisibleTrees(testInput) == 21) check(calculateHighestScenic(testInput) == 8) val input = readInput("/day08/Day08") println(calculateVisibleTrees(input)) println(calculateHighestScenic(input)) }
0
Kotlin
0
0
f288750fccf5fbc41e8ac03598aab6a2b2f6d58a
4,045
2022-advent-of-code-kotlin
Apache License 2.0
src/Day20.kt
anilkishore
573,688,256
false
{"Kotlin": 27023}
fun main() { fun part1(nums: List<Long>, mult: Long = 1, times: Int = 1): Long { val n = nums.size val numList = mutableListOf<Pair<Long, Int>>() for (i in nums.indices) { numList.add(Pair(nums[i] * mult, i)) } repeat(times) { for (i in nums.indices) { var p = 0 for (j in nums.indices) { if (numList[j].second == i) { p = j break } } val k = numList[p].first if (k == 0L) continue val elem = numList.removeAt(p) var nk = ((p + k % (n - 1) + (n - 1)) % (n - 1)).toInt() if (nk == 0) nk = (n - 1) numList.add(nk, elem) } } var p = 0 for (j in nums.indices) { if (numList[j].first == 0L) { p = j break } } return listOf(1000, 2000, 3000).sumOf { k -> val nk = (p + k) % n numList[nk].first } } fun part2(nums: List<Long>): Long { return part1(nums, 811589153L, 10) } val input = readInput("Day20").map { it.toLong() } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9
1,341
AOC-2022
Apache License 2.0
src/Day04.kt
mihansweatpants
573,733,975
false
{"Kotlin": 31704}
fun main() { fun part1(input: List<String>): Int { return input.stream() .map { it.parseRegionPair() } .filter { (first, second) -> first.fullyContains(second) || second.fullyContains(first) } .count() .toInt() } fun part2(input: List<String>): Int { return input.stream() .map { it.parseRegionPair() } .filter { (first, second) -> first.overlaps(second) } .count() .toInt() } val input = readInput("Day04").lines() println(part1(input)) println(part2(input)) } private fun String.parseRegionPair(): Pair<IntRange, IntRange> { val (first, second) = this.split(",") return first.parseRegion() to second.parseRegion() } private fun String.parseRegion(): IntRange { val (start, end) = this.split("-") return start.toInt()..end.toInt() } private fun IntRange.fullyContains(other: IntRange): Boolean { return this.contains(other.first) && this.contains(other.last) } private fun IntRange.overlaps(other: IntRange): Boolean { if (other.first < this.first) return other.overlaps(this) return other.first <= this.last }
0
Kotlin
0
0
0de332053f6c8f44e94f857ba7fe2d7c5d0aae91
1,188
aoc-2022
Apache License 2.0
day04/kotlin/gysel/src/main/kotlin/Main.kt
rdmueller
158,926,869
false
null
import kotlin.system.measureTimeMillis fun main() { val millis = measureTimeMillis { val data = openStream().reader().useLines { lines: Sequence<String> -> lines.filter(String::isNotEmpty) .sorted() .map(::parse) .toList() } println("Parsed ${data.size} records") val naps: List<GuardNap> = data.fold(ProcessingState()) { acc, record -> val action = record.action when { action.startsWith("Guard") -> acc.processGuard(action) action == "falls asleep" -> acc.processSleep(record.time) action == "wakes up" -> acc.processWakeup(record.date, record.time) else -> throw IllegalStateException("Unexpected action '$action'!") } acc }.naps println("Found ${naps.size} naps") // Part 1 val sleepHabitsOfGuards: List<SleepHabits> = naps.groupBy { it.guard }.map { entry -> val (sleepyGuard, napsOfGuard) = entry calculateSleepHabitsOfGuard(napsOfGuard, sleepyGuard) } val guardWithLongestNapDuration = sleepHabitsOfGuards.maxBy { it.totalSleepDuration } ?: throw IllegalStateException("No max found!") val (guard, minute, total) = guardWithLongestNapDuration println("Guard $guard slept for a total of $total") println("Most sleepy minute of guard $guard was minute $minute") println("Answer of part 1 is ${guard * minute}") // Part 2 val guardMostLikelyToBeSleeping = sleepHabitsOfGuards.maxBy { it.numberOfNapsAtMinuteOfMostNaps } ?: throw IllegalStateException("No max found!") println("Most sleepy guard is ${guardMostLikelyToBeSleeping.guard}, most likely asleep at 00:${guardMostLikelyToBeSleeping.minuteOfMostNaps}") println("Answer of part 2 is ${guardMostLikelyToBeSleeping.guard * guardMostLikelyToBeSleeping.minuteOfMostNaps}") } println("Calculated solution in ${millis}ms") } data class Record(val date: String, val time: String, val action: String) data class SleepHabits(val guard: Int, val minuteOfMostNaps: Int, val numberOfNapsAtMinuteOfMostNaps: Int, val totalSleepDuration: Int) data class GuardNap(val guard: Int, val date: String, val timeStart: String, val timeEnd: String) { fun calculateDuration(): Int { val from = extractMinutes(timeStart) val to = extractMinutes(timeEnd) return to - from } fun minutes() = (extractMinutes(timeStart) until extractMinutes(timeEnd)).toList() private fun extractMinutes(time: String) = time.split(":")[1].toInt() } private fun calculateSleepHabitsOfGuard(napsOfSleepyGuard: List<GuardNap>, guard: Int): SleepHabits { val mostSleepyMinute = napsOfSleepyGuard.flatMap { it.minutes() } .groupingBy { it } .eachCount() .maxBy { it.value } ?: throw IllegalStateException("No max found!") val totalSleepDuration = napsOfSleepyGuard.asSequence().map { it.calculateDuration() }.sum() return SleepHabits(guard, mostSleepyMinute.key, mostSleepyMinute.value, totalSleepDuration) } fun parse(line: String): Record { // [1518-03-18 00:03] Guard #3529 begins shift val (date, time, action) = line.split(delimiters = *arrayOf(" "), limit = 3) return Record(date.drop(1), time.dropLast(1), action) } fun extractGuardId(action: String): Int { return action.split(" ")[1].drop(1).toInt() } class ProcessingState { val naps = mutableListOf<GuardNap>() private var currentGuard: Int? = null private var startedSleepTime: String? = null fun processGuard(action: String) { currentGuard = extractGuardId(action) } fun processSleep(time: String) { if (currentGuard == null) throw IllegalStateException("No guard defined yet!") startedSleepTime = time } fun processWakeup(date: String, time: String) { naps.add(GuardNap(currentGuard!!, date, startedSleepTime!!, time)) startedSleepTime = null } } // object {} is a little hack as Java needs a class to open a resource from the classpath private fun openStream() = object {}::class.java.getResourceAsStream("/day04.txt")
26
HTML
18
19
1a0e6d89d5594d4e6e132172abea78b41be3850b
4,377
aoc-2018
MIT License
src/main/kotlin/_2022/Day24.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readInput fun main() { val directions = listOf( Pair(0, 1), //right Pair(1, 0), // bottom Pair(0, -1), // left Pair(-1, 0), // top Pair(0, 0), // current position ) data class Blizzard(val position: Pair<Int, Int>, val direction: Pair<Int, Int>) data class PlayerState(val step: Int, val position: Pair<Int, Int>) fun buildBlizzardsOnStep(blizzards: Set<Blizzard>, maxX: Int, maxY: Int): Set<Blizzard> { return blizzards.map { var first = it.position.first + it.direction.first var second = it.position.second + it.direction.second if (first == 0) { first = maxX - 1 } if (first == maxX) { first = 1 } if (second == 0) { second = maxY - 1 } if (second == maxY) { second = 1 } Blizzard(Pair(first, second), it.direction) }.toSet() } fun solve( position: Pair<Int, Int>, endPosition: Pair<Int, Int>, maxX: Int, maxY: Int, stepToBlizzardsPosition: MutableMap<Int, Set<Blizzard>>, cycle: Int, startStep: Int ): PlayerState { val queue = ArrayDeque<PlayerState>() val seen = mutableSetOf<PlayerState>() queue.add(PlayerState(startStep, position)) while (queue.isNotEmpty()) { val state = queue.removeFirst() val currentStep = state.step val currentPosition = state.position val currentBlizzards = stepToBlizzardsPosition.computeIfAbsent(currentStep.mod(cycle)) { step -> buildBlizzardsOnStep( stepToBlizzardsPosition[step - 1]!!, maxX, maxY ) }.toSet() val nextPositions = directions.map { Pair(it.first + currentPosition.first, it.second + currentPosition.second) }.toSet() if (endPosition in nextPositions) { return PlayerState(currentStep + 1, endPosition) } val currentBlizzardPositions = currentBlizzards.map { it.position }.toSet() val validNextPositions = nextPositions.filter { it == position || (it.first in (1 until maxX) && it.second in (1 until maxY) && it !in currentBlizzardPositions) } validNextPositions.forEach { val playerState = PlayerState(currentStep + 1, it) if (seen.add(playerState)) { queue.add(playerState) } } } return PlayerState(-1, position) } fun part1(input: List<String>): Int { val blizzards = mutableListOf<Blizzard>() input.forEachIndexed { xIndex, str -> str.forEachIndexed { yIndex, char -> when (char) { '>' -> blizzards.add(Blizzard(Pair(xIndex, yIndex), directions[0])) '<' -> blizzards.add(Blizzard(Pair(xIndex, yIndex), directions[2])) 'v' -> blizzards.add(Blizzard(Pair(xIndex, yIndex), directions[1])) '^' -> blizzards.add(Blizzard(Pair(xIndex, yIndex), directions[3])) } } } val maxX = input.size - 1 val maxY = input.first().length - 1 val cycle = input.size * input.first().length val stepToBlizzardsPosition = mutableMapOf(-1 to blizzards.toSet()) val position = Pair(0, input.first().indexOf('.')) val endPosition = Pair(maxX, input.last().indexOf('.')) return solve(position, endPosition, maxX, maxY, stepToBlizzardsPosition, cycle, 0).step } fun part2(input: List<String>): Int { val blizzards = mutableListOf<Blizzard>() input.forEachIndexed { xIndex, str -> str.forEachIndexed { yIndex, char -> when (char) { '>' -> blizzards.add(Blizzard(Pair(xIndex, yIndex), directions[0])) '<' -> blizzards.add(Blizzard(Pair(xIndex, yIndex), directions[2])) 'v' -> blizzards.add(Blizzard(Pair(xIndex, yIndex), directions[1])) '^' -> blizzards.add(Blizzard(Pair(xIndex, yIndex), directions[3])) } } } val maxX = input.size - 1 val maxY = input.first().length - 1 val cycle = input.size * input.first().length val stepToBlizzardsPosition = mutableMapOf(-1 to blizzards.toSet()) val position = Pair(0, input.first().indexOf('.')) val endPosition = Pair(maxX, input.last().indexOf('.')) val first = solve(position, endPosition, maxX, maxY, stepToBlizzardsPosition, cycle, 0) val second = solve(endPosition, position, maxX, maxY, stepToBlizzardsPosition, cycle, first.step) return solve(position, endPosition, maxX, maxY, stepToBlizzardsPosition, cycle, second.step).step } // test if implementation meets criteria from the description, like: val testInput = readInput("Day24_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day24") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
5,409
advent-of-code
Apache License 2.0
src/main/kotlin/io/github/ajoz/puzzles/Day01.kt
ajoz
574,043,593
false
{"Kotlin": 21275}
package io.github.ajoz.puzzles import io.github.ajoz.utils.head import io.github.ajoz.utils.readInput import io.github.ajoz.utils.tail /** * --- Day 1: Calorie Counting --- * * The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition * traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One * important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input). * * The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that * they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's * inventory (if any) by a blank line. * * For example, suppose the Elves finish writing their items' Calories and end up with the list in the Day01_test.txt file. * * This list represents the Calories of the food carried by five Elves: * * The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories. * The second Elf is carrying one food item with 4000 Calories. * The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories. * The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories. * The fifth Elf is carrying one food item with 10000 Calories. * * In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how * many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried * by the fourth Elf). */ fun main() { val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) } /** * --- Part One --- * * Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? */ private fun part1(input: List<String>): Int { return input.toCalories().maxByOrNull { it }?.value!! } /** * --- Part Two --- * * By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most * Calories of food might eventually run out of snacks. * * To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top * three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have * two backups. * * In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf * (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves * is 45000. * * Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? */ private fun part2(input: List<String>): Int { return input.toCalories().sortedDescending().take(3).sumOf { it.value } } @JvmInline value class Calories(val value: Int) : Comparable<Calories> { override fun compareTo(other: Calories): Int = value.compareTo(other.value) } operator fun Calories.plus(other: Calories): Calories = Calories(this.value + other.value) /** * Changes the List of input Strings to a List of Calories. */ fun List<String>.toCalories(): List<Calories> { // we create a single element list with Calories set to 0 // we then go through the input and sum the Calories in the input lines // if an empty string is found then a new Calories 0 is added at the top of the list val initial = listOf(Calories(0)) return fold(initial) { calories, inputLine -> val currentCalories = calories.head if (inputLine.isNotBlank()) { val inputCalories = Calories(inputLine.toInt()) val newCalories = currentCalories + inputCalories listOf(newCalories) + calories.tail } else { initial + calories } } }
0
Kotlin
0
0
6ccc37a4078325edbc4ac1faed81fab4427845b8
4,067
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/io/dp/LongestIncreasingSubsequence.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.dp import io.utils.runTests import java.util.* // https://leetcode.com/problems/longest-increasing-subsequence/ class LongestIncreasingSubsequence { fun execute(input: IntArray): Int { val dp = IntArray(input.size) var len = 0 for (value in input) { val index = Arrays.binarySearch(dp, 0, len, value).let { index -> if (index < 0) -(index + 1) else index } dp[index] = value if (index == len) len++ } return len } // https://www.youtube.com/watch?v=S9oUiVYEq7E&feature=emb_title fun execute1(input: IntArray): Int { if (input.isEmpty()) return 0 val dp = IntArray(input.size) var len = 0 input.forEachIndexed { index, value -> if (value > input[dp[len]]) { len++ dp[len] = index } else { val dpIndex = dp.binarySearch(input, value, 0, len) dp[dpIndex] = index } } return len + 1 } } private fun IntArray.binarySearch(input: IntArray, value: Int, start: Int, end: Int): Int { var first = start var last = end while (first <= last) { val pivot = first + (last - first) / 2 when { input[this[pivot]] == value -> return pivot input[this[pivot]] < value -> first = pivot + 1 else -> last = pivot - 1 } } return first } fun main() { runTests(listOf( intArrayOf(10, 9, 2, 5, 3, 7, 101, 18) to 4, intArrayOf(5, 7, 9, 8, 4, 15, 3, 5, 14, 3, 6, 122, 1231, 124, 7, 3, 5, 6, 14, 8, -1, 12, 10, 9, -14, -18, 14, 31, 2, 2, 4, 10, 11, 12) to 9, intArrayOf(3, 4, -1, 5, 8, 2, 3, 12, 7, 9, 10) to 6 )) { (input, value) -> value to LongestIncreasingSubsequence().execute1(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,667
coding
MIT License
src/day05/Day05.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day05 import readInput import readTestInput private fun List<String>.parse(): Pair<List<String>, List<String>> { val stackNumberLineIndex = this.indexOfFirst { line -> line.contains("""\d""".toRegex()) } val stacksDefinitions = this.take(stackNumberLineIndex + 1) val rawInstructions = this.drop(stackNumberLineIndex + 2) return stacksDefinitions to rawInstructions } private data class MoveInstruction( val fromIndex: Int, val toIndex: Int, val amount: Int, ) private val instructionRegex = """move (\d+) from (\d+) to (\d+)""".toRegex() private fun String.toMoveInstruction(): MoveInstruction { val (amount, from, to) = checkNotNull(instructionRegex.matchEntire(this)).destructured return MoveInstruction( fromIndex = from.toInt() - 1, toIndex = to.toInt() - 1, amount = amount.toInt() ) } private fun Array<ArrayDeque<Char>>.retrieveTopCrates() = joinToString(separator = "") { "${it.removeLast()}" } private fun List<String>.toStacks(): Array<ArrayDeque<Char>> { val stackDefinitions = this val stackAmount = stackDefinitions .last() .replace("""^.+\s+(\d+)\s*$""".toRegex()) { it.groupValues[1] } .toInt() val stacks = Array(stackAmount) { ArrayDeque<Char>() } for (crateLayer in stackDefinitions.dropLast(1)) { for (index in 0 until stackAmount) { val crateDefinition = crateLayer.drop(index * 4).take(3) if (crateDefinition.startsWith('[')) { stacks[index].addFirst(crateDefinition[1]) } } } return stacks } private fun ArrayDeque<Char>.moveTo(target: ArrayDeque<Char>, amount: Int) { val source = this repeat(amount) { target.addLast(source.removeLast()) } } private fun ArrayDeque<Char>.moveBulkTo(target: ArrayDeque<Char>, amount: Int) { val source = this val cache = mutableListOf<Char>() repeat(amount) { cache.add(source.removeLast()) } for (cachedCrate in cache.asReversed()) { target.addLast(cachedCrate) } } private fun part1(input: List<String>): String { val (stacksDefinitions, rawInstructions) = input.parse() val stacks = stacksDefinitions.toStacks() val instructions = rawInstructions.map { rawInstruction -> rawInstruction.toMoveInstruction() } for (instruction in instructions) { val source = stacks[instruction.fromIndex] val target = stacks[instruction.toIndex] source.moveTo(target = target, amount = instruction.amount) } return stacks.retrieveTopCrates() } private fun part2(input: List<String>): String { val (stacksDefinitions, rawInstructions) = input.parse() val stacks = stacksDefinitions.toStacks() val instructions = rawInstructions.map { rawInstruction -> rawInstruction.toMoveInstruction() } for (instruction in instructions) { val source = stacks[instruction.fromIndex] val target = stacks[instruction.toIndex] source.moveBulkTo(target = target, amount = instruction.amount) } return stacks.retrieveTopCrates() } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day05") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
3,421
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/dp/SubsetSum.kt
yx-z
106,589,674
false
null
package dp import util.OneArray import util.get import util.set import util.toOneArray // given an array of positive integers and an integer, determine if any subset of the array can sum // up to the integer fun main(args: Array<String>) { val arr = intArrayOf(1, 6, 4) val ints = intArrayOf(7, // true 5, // true 8, // false 3, // false 11, // true 9, // false 10) // true // ints.forEach { println(arr.subsetSum(it)) } // println() // ints.forEach { println(arr.subsetSum2(it)) } ints.forEach { println(arr.toOneArray().subsetSumRedo(it)) } } // O(size * n) fun IntArray.subsetSum(n: Int): Boolean { // dp[i][j] = whether any subset of this[i..size - 1] can sum up to j // dp[i][j] = false, if j <= 0 or i >= size // = true, if arr[i] == j // = dp[i + 1][j - this[i]] || dp[i + 1][j], o/w val dp = Array(size + 1) { BooleanArray(n + 1) } for (i in size - 1 downTo 0) { for (j in 1..n) { dp[i][j] = when { this[i] == j -> true j - this[i] < 0 -> dp[i + 1][j] else -> dp[i + 1][j - this[i]] || dp[i + 1][j] } } } return dp[0][n] } // O(2^n) fun IntArray.subsetSum2(n: Int, idx: Int = 0): Boolean { if (idx == size) { return n == 0 } return subsetSum2(n, idx + 1) || subsetSum2(n - this[idx], idx + 1) } fun OneArray<Int>.subsetSumRedo(T: Int): Set<Int>? { val A = this val n = size // dp[i, j]: a subset of A[1..i] that sums up to j // note that empty set is a subset of any set that sums up to 0 // so we use null to represent the case of no such set exists // memoization structure: 2d arr dp[0..n, 0..T] val dp = Array(n + 1) { Array<HashSet<Int>?>(T + 1) { null } } // note that each cell contains a subset of A, taking space O(n) // space: O(Tn * n) = O(Tn^2) // base case: // dp[i, 0] = { } for all i for (i in 0..n) { dp[i, 0] = HashSet() } // dp[0, j] = null for all j > 0 // dp[i, j] = null for all j < 0 // recursive case: // dp[i, j] = NOT include A[i]: dp[i - 1, j] if any // include A[i]: find dp[i - 1, j - A[i]] // dependency: dp[i, j] depends on dp[i - 1, j], dp[i - 1, j - A[i]] // that is entries above // eval order: outer loop for i increasing from 1 to n for (i in 1..n) { // inner loop for j with no specific order, say 1..T for (j in 1..T) { if (dp[i - 1, j] != null) { dp[i, j] = HashSet(dp[i - 1, j]) } else { if (j - A[i] >= 0 && dp[i - 1, j - A[i]] != null) { dp[i, j] = HashSet(dp[i - 1, j - A[i]]) dp[i, j]!!.add(A[i]) } // o/w dp[i, j] = null as initialized } } } // we are filling a table of O(Tn), with each step (at worst case) // taking O(n) work for copying all elements of A // time: O(Tn^2) // we want to find the subset of A[1..n] that sums up to T return dp[n, T] }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
2,787
AlgoKt
MIT License
src/Day05.kt
atsvetkov
572,711,515
false
{"Kotlin": 10892}
import java.util.Stack typealias CrateStack = Stack<Char> data class Crates(val crateStacks: List<CrateStack>) { fun apply(move: Move) { val fromStack = crateStacks[move.from-1] val toStack = crateStacks[move.to-1] move.take(fromStack).forEach(toStack::push) } override fun toString(): String { val result = StringBuilder() for ((index, crate) in crateStacks.withIndex()) { result.append("${index+1}: $crate") result.append("\r\n") } return result.toString() } fun topCrates() = crateStacks.map(CrateStack::peek).joinToString("") } sealed class Move(val amount: Int, val from: Int, val to: Int) { companion object { fun parseOneByOneMove(move: String): Move { val parts = move.split(' ') return OneByOneMove(amount = parts[1].toInt(), from = parts[3].toInt(), to = parts[5].toInt()) } fun parseAtOnceMove(move: String): Move { val parts = move.split(' ') return AtOnceMove(amount = parts[1].toInt(), from = parts[3].toInt(), to = parts[5].toInt()) } } abstract fun take(crateStack: CrateStack): List<Char> class OneByOneMove(amount: Int, from: Int, to: Int) : Move(amount, from, to) { override fun take(crateStack: CrateStack) = (1 .. amount).map { crateStack.pop() } } class AtOnceMove(amount: Int, from: Int, to: Int) : Move(amount, from, to) { override fun take(crateStack: CrateStack) = (1 .. amount).map { crateStack.pop() }.reversed() } } fun parseInitialState(stateLines: List<String>): Crates { val size = stateLines.last().split(' ').filter { !it.isNullOrBlank() }.size val crates = Array(size) { _ -> CrateStack()} for (line in stateLines.dropLast(1).reversed()) { for (crateIndex in 0 until size) { if (1+4*crateIndex >= line.length) continue val crate = line[1+4*crateIndex] if (!crate.isWhitespace()) crates[crateIndex].push(crate) } } return Crates(crates.toList()) } fun parseMoves(moveLines: List<String>, init: (s: String) -> Move) = moveLines.map(init) fun splitInput(input: List<String>): Pair<List<String>, List<String>> { var parsingState = true val stateLines = mutableListOf<String>() val moveLines = mutableListOf<String>() for (line in input) { if (line.isEmpty()) { parsingState = false } else if (parsingState) { stateLines.add(line) } else { moveLines.add(line) } } return Pair(stateLines, moveLines) } fun main() { fun part1(input: List<String>): String { val (stateLines, moveLines) = splitInput(input) val crates = parseInitialState(stateLines) val moves = parseMoves(moveLines) { Move.parseOneByOneMove(it) } moves.forEach { crates.apply(it) } return crates.topCrates() } fun part2(input: List<String>): String { val (stateLines, moveLines) = splitInput(input) val crates = parseInitialState(stateLines) val moves = parseMoves(moveLines) { Move.parseAtOnceMove(it) } moves.forEach { crates.apply(it) } return crates.topCrates() } val testInput = readInput("Day05_test") println("Test Part 1: " + part1(testInput)) println("Test Part 2: " + part2(testInput)) println() val input = readInput("Day05") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
01c3bb6afd658a2e30f0aee549b9a3ac4da69a91
3,536
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day4.kt
C06A
435,034,782
false
{"Kotlin": 20662}
package days class Day4 : Day(4) { override fun partOne(): Any { val drowing = inputList[0].split(",").map { it.toInt() } val cards = inputList.drop(1).fold(mutableListOf<Card>()) { cards, line -> if (line.trim().length == 0) { cards += Card() } else { val card = cards.last() card + line.trim().split("\\W+".toRegex()).map { it.toInt() } } cards } return drowing.asSequence().map { cards.forEach { card -> card - it } it to cards.find { it.isWin() } }.find { it.second != null }?.run { first * (second?.getSum() ?: 0) } ?: throw Exception() } override fun partTwo(): Any { val drowing = inputList[0].split(",").map { it.toInt() } val cards = inputList.drop(1).fold(mutableListOf<Card>()) { cards, line -> if (line.trim().length == 0) { cards += Card() } else { val card = cards.last() card + line.trim().split("\\W+".toRegex()).map { it.toInt() } } cards } return drowing.asSequence().map { drowed -> cards -= cards.fold(mutableListOf<Card>()) { wonCards, card: Card -> card - drowed if (card.isWin()) { wonCards += card } wonCards }.toSet().also { if(cards.size == 1 && cards[0].isWin()) { return@map drowed * cards[0].getSum() } } }.first { it is Int } } class Card() { private var count = 0 private val rows = mutableMapOf<Int, Int>() private val cols = mutableMapOf<Int, Int>() operator fun plus(row: List<Int>) { count++ row.forEachIndexed { i, v -> rows[v] = count cols[v] = i } } operator fun minus(value: Int) { if(rows[value] != null) { rows -= value } if(cols[value] != null) { cols -= value } } private fun hasEmptyRowOrCol(data: Map<Int, Int>): Boolean { return data.values.groupBy { it }.size < count } fun isWin(): Boolean { return hasEmptyRowOrCol(rows) || hasEmptyRowOrCol(cols) } fun getSum(): Int { return rows.keys.sum() } } }
0
Kotlin
0
0
afbe60427eddd2b6814815bf7937a67c20515642
2,629
Aoc2021
Creative Commons Zero v1.0 Universal
src/leetcodeProblem/leetcode/editor/en/BestTimeToBuyAndSellStockWithTransactionFee.kt
faniabdullah
382,893,751
false
null
//You are given an array prices where prices[i] is the price of a given stock //on the iᵗʰ day, and an integer fee representing a transaction fee. // // Find the maximum profit you can achieve. You may complete as many //transactions as you like, but you need to pay the transaction fee for each transaction. // // Note: You may not engage in multiple transactions simultaneously (i.e., you //must sell the stock before you buy again). // // // Example 1: // // //Input: prices = [1,3,2,8,4,9], fee = 2 //Output: 8 //Explanation: The maximum profit can be achieved by: //- Buying at prices[0] = 1 //- Selling at prices[3] = 8 //- Buying at prices[4] = 4 //- Selling at prices[5] = 9 //The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. // // // Example 2: // // //Input: prices = [1,3,7,5,10,3], fee = 3 //Output: 6 // // // // Constraints: // // // 1 <= prices.length <= 5 * 10⁴ // 1 <= prices[i] < 5 * 10⁴ // 0 <= fee < 5 * 10⁴ // // Related Topics Array Dynamic Programming Greedy 👍 3117 👎 84 package leetcodeProblem.leetcode.editor.en class BestTimeToBuyAndSellStockWithTransactionFee { //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun maxProfit(prices: IntArray, fee: Int): Int { var cash = 0 var hold = -prices[0] for (i in 1 until prices.size) { cash = maxOf(cash, hold + prices[i] - fee) hold = maxOf(hold, cash - prices[i]) } return cash } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { println(BestTimeToBuyAndSellStockWithTransactionFee.Solution().maxProfit(intArrayOf(1, 3, 2, 8, 4, 9), 2)) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,835
dsa-kotlin
MIT License
src/main/kotlin/dp/LDIS.kt
yx-z
106,589,674
false
null
package dp import util.get import util.max import util.set // longest double increaasing subsequence // X[1..n] is double increasing if X[i] > X[i - 2] for all i > 2 // intuitively, X is a perfect shuffle of two increasing sequences // find the length of the ldis of A[1..n] fun main(args: Array<String>) { val A = intArrayOf(0, 7, 1, 4, 6, 5, 3, 2) println(ldis(A)) // [0, 1, 4, 6, 5] -> 5 } fun ldis(A: IntArray): Int { val n = A.size // trivial case if (n < 2) { return n } // dp(i, j): the length of ldis with first two elements A[i] and A[j] // memoization structure: 2d array dp[1..n - 1, 1..n] : dp[i, j] = dp(i, j) val dp = Array(n) { IntArray(n) } // space complexity: O(n^2) // base case: // dp(i, j) = 0 if i >= j // process only when i < j // = 2 if j = n for (i in 0 until n - 1) { dp[i, n - 1] = 2 } // we want max dp(i, j) // which is at least 2 considering the base case var max = 2 // assume max{ } = 0 // recursive case: // dp(i, j) = max{2, 1 + max{ dp(j, k) } : where i < j < k and A[i] < A[k]} // dependency: dp(i, j) depends on dp(j, k) where j > i and k > j // i.e. all entries on a row below and to right of current entry // evaluation order: outer loop for i from down to top (n - 2 down to 0) for (i in n - 2 downTo 0) { // inner loop for j from right to left (n down to i + 1) for (j in n - 2 downTo i + 1) { var maxLen = 2 // innermost loop for k from left to right (j + 1..n) for (k in j + 1 until n) { if (A[i] < A[k]) { maxLen = max(maxLen, 1 + dp[j, k]) } } dp[i, j] = maxLen max = max(max, dp[i, j]) } } // time complexity: O(n^2) return max }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,678
AlgoKt
MIT License
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day24/Day24.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2020.day24 import eu.janvdb.aocutil.kotlin.hexagonal.HexagonalCoordinate import eu.janvdb.aocutil.kotlin.hexagonal.HexagonalDirection import eu.janvdb.aocutil.kotlin.hexagonal.bottomRight import eu.janvdb.aocutil.kotlin.hexagonal.topLeft import eu.janvdb.aocutil.kotlin.readLines const val NUMBER_OF_DAYS = 100 fun main() { val flippedCoordinates = mutableSetOf<HexagonalCoordinate>() readLines(2020, "input24.txt") .map(::parseLine) .forEach { if (flippedCoordinates.contains(it)) flippedCoordinates.remove(it) else flippedCoordinates.add(it) } var floor = HexagonalFloor(flippedCoordinates) println("0: ${floor.blackTiles.size}") for (i in 0 until NUMBER_OF_DAYS) { floor = floor.step() println("${i+1}: ${floor.blackTiles.size}") } } fun parseLine(input: String): HexagonalCoordinate { var result = HexagonalCoordinate.ORIGIN val inputUpperCase = input.uppercase() var i = 0 while (i < input.length) { val hexagonalDirection: HexagonalDirection if (inputUpperCase[i] == 'E' || inputUpperCase[i] == 'W') { hexagonalDirection = HexagonalDirection.valueOf(inputUpperCase.substring(i, i + 1)) i++ } else { hexagonalDirection = HexagonalDirection.valueOf(inputUpperCase.substring(i, i + 2)) i += 2 } result = result.add(hexagonalDirection.coordinate) } return result } data class HexagonalFloor(val blackTiles: Set<HexagonalCoordinate>) { fun step(): HexagonalFloor { fun countBlackNeighbours(coordinate: HexagonalCoordinate): Int { return coordinate.neighbours().count(blackTiles::contains) } fun shouldBeBlack(coordinate: HexagonalCoordinate): Boolean { val isBlack = blackTiles.contains(coordinate) val neighbours = countBlackNeighbours(coordinate) return (isBlack && neighbours in 1..2) || (!isBlack && neighbours == 2) } val topLeft = blackTiles.topLeft().add(HexagonalDirection.NW, 2) val bottomRight = blackTiles.bottomRight().add(HexagonalDirection.SE, 2) val newCoordinates = HexagonalCoordinate.iterate(topLeft, bottomRight).filter(::shouldBeBlack).toSet() return HexagonalFloor(newCoordinates) } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
2,115
advent-of-code
Apache License 2.0
src/Day03.kt
jordan-thirus
573,476,470
false
{"Kotlin": 41711}
fun main() { fun getItemPriority(item: Char): Int{ val priority = if(item.isLowerCase()) { item.minus('a') + 1 } else { item.minus('A') + 27 } return priority } fun part1(input: List<String>): Int { fun findItemToRearrange(items: String): Char{ val midPoint = items.length / 2 return items.toCharArray(0, midPoint).intersect(items.toCharArray(midPoint, items.length).toSet()) .single() } return input.map { line -> findItemToRearrange(line) } .sumOf { item -> getItemPriority(item) } } fun part2(input: List<String>): Int { return input.chunked(3) .map { elves -> elves.map {rucksack -> rucksack.toSet() } .reduce{ acc, rucksack -> acc.intersect(rucksack) } .single() } .sumOf { badge -> getItemPriority(badge) } } // 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
59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e
1,228
advent-of-code-2022
Apache License 2.0
neetcode/src/main/java/org/arrays/Arrays&Hashing.kt
gouthamhusky
682,822,938
false
{"Kotlin": 24242, "Java": 24233}
package org.arrays import kotlin.math.max fun containsDuplicate(nums: IntArray): Boolean = nums.size > nums.toSet().size fun isAnagram(s: String, t: String): Boolean { if (s.length != t.length) return false val list = MutableList(26){0} for (i in s.indices){ val sPosition = s[i].toInt() - 97 val tPosition = t[i].toInt() - 97 list[sPosition]++ list[tPosition]-- } list.forEach { if (it != 0) return false } return true } fun twoSum(nums: IntArray, target: Int): IntArray { val map = mutableMapOf<Int, Int>() for (i in nums.indices){ if (map.containsKey(target - nums[i])) return intArrayOf(i, map[target - nums[i]]!!) map[nums[i]] = i } return intArrayOf() } fun topKFrequent(nums: IntArray, k: Int): IntArray { val map = mutableMapOf<Int, Int>() val ans = mutableListOf<Int>() val frequency = MutableList<MutableList<Int>>(nums.size + 1){ mutableListOf() } for (num in nums){ map.put(num, map.getOrDefault(num, 0) + 1) } for ((key, v) in map){ frequency[v].add(key) } for (i in frequency.size - 1 downTo 0){ for (j in frequency[i]){ ans.add(j) if (ans.size == k) return ans.toIntArray() } } return intArrayOf() } fun groupAnagrams(strs: Array<String>): List<List<String>> { val map = mutableMapOf<String, List<String>>() val ans = mutableListOf<List<String>>() for (str in strs){ val charArray = IntArray(26){0} for (c in str){ charArray[c.toInt() - 97]++ } val key = charArray.joinToString("") if (map.containsKey(key)){ map[key] = map[key]!!.plus(str) } else{ map[key] = listOf(str) } } for (v in map.values) ans.add(v) return ans } fun longestConsecutive(nums: IntArray): Int { val set = mutableSetOf<Int>() var max = Int.MIN_VALUE var count = 0 for (num in nums){ set.add(num) } for (num in set){ if (! set.contains(num - 1)){ var length = 0 var seq = num while (set.contains(seq +1)){ length++ seq++ } max = max(max, length) } } return max } fun isValidSudoku(board: Array<CharArray>): Boolean { val rowMap = hashMapOf<Int, MutableSet<Char>>() val colMap = hashMapOf<String, Set<Int>>() val gridMap = hashMapOf<String, Set<Int>>() // checking the rows for (ri in board.indices){ val currRow = board[ri] val rowSet = hashSetOf<Char>() for (c in currRow.indices){ if (currRow[c] == '.') continue if (rowSet.contains(currRow[c])) return false rowSet.add(currRow[c]) } } // checking the columns for (r in board.indices){ val colSet = hashSetOf<Char>() for (c in board[r].indices){ if (board[c][r] == '.') continue if (colSet.contains(board[c][r])) return false colSet.add(board[c][r]) } } for (r in 0..<9 step 3){ for (c in 0 ..<9 step 3){ if (!checkGrid(r, c, board)) return false } } return true } fun checkGrid(row: Int, col: Int, board: Array<CharArray>): Boolean{ val rowBound = row + 3 val colBound = col + 3 for (i in row..<rowBound){ val gridSet = hashSetOf<Char>() for (j in col ..<colBound){ if (board[i][j] == '.') continue if (gridSet.contains(board[i][j])) return false } } return true } fun main() { groupAnagrams(arrayOf("bdddddddddd","bbbbbbbbbbc")) }
0
Kotlin
0
0
a0e158c8f9df8b2e1f84660d5b0721af97593920
3,910
leetcode-journey
MIT License
src/Day08.kt
Jintin
573,640,224
false
{"Kotlin": 30591}
import kotlin.math.max fun main() { fun buildMap(input: List<String>): Array<IntArray> { val map: Array<IntArray> = Array(input.size) { IntArray(input[0].length) } input.forEachIndexed { i, s -> s.forEachIndexed { j, c -> map[i][j] = c - '0' } } return map } fun part1(input: List<String>): Int { val map: Array<IntArray> = buildMap(input) val record: Array<BooleanArray> = Array(input.size) { BooleanArray(input[0].length) } var max: Int for (i in map.indices) { max = -1 for (j in map[0].indices) { if (map[i][j] > max) { record[i][j] = true max = map[i][j] } } max = -1 for (j in map[0].indices.reversed()) { if (map[i][j] > max) { record[i][j] = true max = map[i][j] } } } for (j in map[0].indices) { max = -1 for (i in map.indices) { if (map[i][j] > max) { record[i][j] = true max = map[i][j] } } max = -1 for (i in map.indices.reversed()) { if (map[i][j] > max) { record[i][j] = true max = map[i][j] } } } return record.sumOf { it.count { it } } } fun part2(input: List<String>): Int { val map: Array<IntArray> = buildMap(input) var max = 0 for (i in map.indices) { for (j in map[0].indices) { var countA = 0 var countB = 0 var countC = 0 var countD = 0 val target = map[i][j] for (a in i - 1 downTo 0) { if (map[a][j] <= target) { countA++ } if (map[a][j] >= target) { break } } for (b in i + 1 until map.size) { if (map[b][j] <= target) { countB++ } if (map[b][j] >= target) { break } } for (c in j - 1 downTo 0) { if (map[i][c] <= target) { countC++ } if (map[i][c] >= target) { break } } for (d in j + 1 until map[0].size) { if (map[i][d] <= target) { countD++ } if (map[i][d] >= target) { break } } max = max(max, countA * countB * countC * countD) } } return max } val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
4aa00f0d258d55600a623f0118979a25d76b3ecb
3,206
AdventCode2022
Apache License 2.0
src/day3/day3.kts
SebastianSiebert
225,128,001
false
null
import java.io.File import kotlin.system.exitProcess data class Point(val x: Int, val y: Int) enum class Direction { UP, DOWN, LEFT, RIGHT, INVALID } val wire1: ArrayList<Point> = ArrayList<Point>() val wire2: ArrayList<Point> = ArrayList<Point>() fun getDirection(direction: String) = when (direction.substring(0, 1)) { "U" -> Direction.UP "D" -> Direction.DOWN "L" -> Direction.LEFT "R" -> Direction.RIGHT else -> Direction.INVALID } fun getDistance(direction: String): Int = direction.substring(1).toInt() fun getCurrentList(number: Int): ArrayList<Point> = when(number) { 0 -> wire1 1 -> wire2 else -> ArrayList<Point>() } fun fillWire(number: Int, directions: List<String>) { var x = 0 var y = 0 val wire = getCurrentList(number) wire.add(Point(0,0)) directions.forEach({ val dir = getDirection(it) val distance = getDistance(it) val range = when(dir) { Direction.UP -> y+1..y+distance Direction.DOWN -> y-1 downTo y-distance Direction.LEFT -> x-1 downTo x-distance Direction.RIGHT -> x+1..x+distance Direction.INVALID -> 0..0 } when (dir) { Direction.UP, Direction.DOWN -> for (i in range) { wire.add(Point(x, i)) y = i } Direction.RIGHT, Direction.LEFT -> for (i in range) { wire.add(Point(i, y)) x = i } Direction.INVALID -> {} } }) } fun readInput(fileName: String) { File(fileName).useLines { it.forEachIndexed { index, s -> run { fillWire(index, s.split(",")) } } } } fun manhattanDistance(point1: Point, point2: Point) = Math.abs(point1.x - point2.x) + Math.abs(point1.y - point2.y) if (args.size == 0) exitProcess(0) readInput(args[0]) // Puzzle1 val wireIntersection = wire1.intersect(wire2) val crossing = wireIntersection.filter { it != Point(0,0) }.minBy { manhattanDistance(Point(0,0), it) } if (crossing != null) { print("Distance to shortest Intersection: ") println(manhattanDistance(Point(0, 0), crossing)) }
0
Kotlin
0
0
69a734d8abf2dd93c62a6e0e5a7eedb76e0c13a3
2,214
AdventOfCode2019
MIT License
src/Day03.kt
pydaoc
573,843,750
false
{"Kotlin": 8484}
fun main() { fun generateAlphabet(): Set<Char> { var lowercaseFirstCharacter = 'a' val lowercaseAlphabet = generateSequence { (lowercaseFirstCharacter++).takeIf { it <= 'z' } } var uppercaseFirstCharacter = 'A' val uppercaseAlphabet = generateSequence { (uppercaseFirstCharacter++).takeIf { it <= 'Z' } } val alphabet = lowercaseAlphabet.toList().union(uppercaseAlphabet.toList()) println(alphabet.toList()) return alphabet } fun part1(input: List<String>): Int { val alphabet = generateAlphabet() var result = 0 for (line in input) { val partOne = line.substring(0, line.length / 2) val partTwo = line.substring(line.length / 2) val charactersPartOne = partOne.toCharArray() val charactersPartTwo = partTwo.toCharArray() val commonCharacter = charactersPartOne.intersect(charactersPartTwo.toSet()).first() result += alphabet.indexOf(commonCharacter) + 1 } return result } fun part2(input: List<String>): Int { val alphabet = generateAlphabet() var result = 0 for (i in 0 until input.count() step 3) { val lineOne = input[i] val lineTwo = input[i + 1] val lineThree = input[i + 2] val charactersLineOne = lineOne.toCharArray() val charactersLineTwo = lineTwo.toCharArray() val charactersLineThree = lineThree.toCharArray() val commonCharacter = charactersLineOne .intersect(charactersLineTwo.toSet()) .intersect(charactersLineThree.toSet()) .first() result += alphabet.indexOf(commonCharacter) + 1 } return result } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
970dedbfaf09d12a29315c6b8631fa66eb394054
1,940
advent-of-code-kotlin-2022
Apache License 2.0
src/Day03.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
fun main() { fun letterToCode(it: Char) = if (it.isUpperCase()) it.code - 38 else it.code - 96 fun part1(input: List<String>): Int { return input .asSequence() .filterNot(String::isBlank) .map(String::toList) .map { it.subList(0, it.size / 2).toSet().intersect(it.subList(it.size / 2, it.size).toSet()) } .filter { it.size == 1 } .map { it.single() } .sumOf(::letterToCode) } fun part2(input: List<String>): Int { return input .asSequence() .filterNot(String::isBlank) .chunked(3) { it.map(String::toSet).reduce(Set<Char>::intersect) } .filter { it.size == 1 } .map { it.single() } .sumOf(::letterToCode) } val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
999
aoc-2022
Apache License 2.0
src/Day01.kt
alex-damico
573,006,242
false
{"Kotlin": 1664}
fun main() { fun headAndTail(input: List<String>): Pair<List<String>, List<String>> { val head = input.takeWhile { it.isNotBlank() } val tail = input.dropWhile { it.isNotBlank() }.drop(1) return head to tail } fun splitOnSpaces(input: List<String>): List<List<String>> { val (head, tail) = headAndTail(input) if (tail.isEmpty()) return listOf(head) return splitOnSpaces(tail).plus(listOf(head)) } fun toCalories(input: List<String>): List<Int> { val groups = splitOnSpaces(input) val calories = groups.map { group: List<String> -> group.sumOf { it.toInt() } } return calories } fun part1(input: List<String>) = toCalories(input).maxOf { it } fun part2(input: List<String>): Int { val calories = toCalories(input).sortedDescending() return calories.take(3).sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
656c679139519ab4548a4c8457114e904399a83d
1,023
adventofcode
Apache License 2.0
src/main/kotlin/days/Solution21.kt
Verulean
725,878,707
false
{"Kotlin": 62395}
package days import adventOfCode.InputHandler import adventOfCode.Solution import adventOfCode.util.Point2D import adventOfCode.util.plus private val directions = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1) object Solution21 : Solution<Triple<Set<Point2D>, Point2D, Int>>(AOC_YEAR, 21) { override fun getInput(handler: InputHandler): Triple<Set<Point2D>, Point2D, Int> { val grid = handler.getInput("\n") val n = grid.size var start = -1 to -1 val garden = mutableSetOf<Point2D>() grid.forEachIndexed { i, row -> row.forEachIndexed { j, c -> when (c) { '.' -> garden.add(i to j) 'S' -> { garden.add(i to j) start = i to j } } } } return Triple(garden, start, n) } override fun solve(input: Triple<Set<Point2D>, Point2D, Int>): Pair<Int?, Long> { val (garden, start, n) = input var currBoundary = setOf(start) var prevBoundary = setOf<Point2D>() val currDifferences = mutableListOf(0, 0, 0, 0) var prevDifferences = listOf(0, 0, 0, 0) val counts = mutableListOf(0, 0) var ans1: Int? = null val steps = 26501365 for (step in 0..steps) { val parity = step % 2 counts[parity] += currBoundary.size if (step == 64) ans1 = counts[parity] if ((steps - step) % n == 0) { currDifferences[0] = counts[parity] currDifferences.indices.forEach { i -> val diff = currDifferences[i] - prevDifferences[i] if (diff == 0) { val x = ((steps - step) / n).toLong() val (a0, a1, a2, _) = currDifferences val ans2 = a2 * x * (x + 1) / 2 + a1 * x + a0 return ans1 to ans2 } else if (i + 1 in currDifferences.indices) { currDifferences[i + 1] = diff } } prevDifferences = currDifferences.toList() } val temp = currBoundary .flatMap { p -> directions.map { p + it } } .filter { it !in prevBoundary } .filter { (i, j) -> i.mod(n) to j.mod(n) in garden } .toSet() prevBoundary = currBoundary currBoundary = temp } throw Exception("unreachable") } }
0
Kotlin
0
1
99d95ec6810f5a8574afd4df64eee8d6bfe7c78b
2,569
Advent-of-Code-2023
MIT License
src/Day02.kt
imavroukakis
572,438,536
false
{"Kotlin": 12355}
fun main() { val handLookup = mapOf( "A" to Rock, "B" to Paper, "C" to Scissors, "X" to Rock, "Y" to Paper, "Z" to Scissors, ) fun String.toHand(): Hand = handLookup.getValue(this) fun part1(input: List<String>): Int = input.sumOf { val split = it.split(" ") val opponentHand = split[0].toHand() val playerHand = split[1].toHand() playerHand.pointsAgainst(opponentHand) + playerHand.value() } fun part2(input: List<String>): Int = input.sumOf { val split = it.split(" ") val opponentHand = split[0].toHand() val playerHand = when (split[1]) { "X" -> opponentHand.defeats() "Y" -> opponentHand "Z" -> opponentHand.loses() else -> throw IllegalArgumentException() } playerHand.pointsAgainst(opponentHand) + playerHand.value() } val testInput = readInput("Day02_test") check(part1(testInput) == 15) println(part1(readInput("Day02"))) check(part2(testInput) == 12) println(part2(readInput("Day02"))) } sealed interface Hand { fun pointsAgainst(hand: Hand): Int fun value(): Int fun defeats(): Hand fun loses(): Hand } object Rock : Hand { override fun pointsAgainst(hand: Hand): Int = when (hand) { is Rock -> 3 is Paper -> 0 is Scissors -> 6 } override fun value(): Int = 1 override fun defeats(): Hand = Scissors override fun loses(): Hand = Paper } object Paper : Hand { override fun pointsAgainst(hand: Hand): Int = when (hand) { is Rock -> 6 is Paper -> 3 is Scissors -> 0 } override fun value(): Int = 2 override fun defeats(): Hand = Rock override fun loses(): Hand = Scissors } object Scissors : Hand { override fun pointsAgainst(hand: Hand): Int = when (hand) { is Rock -> 0 is Paper -> 6 is Scissors -> 3 } override fun value(): Int = 3 override fun defeats(): Hand = Paper override fun loses(): Hand = Rock }
0
Kotlin
0
0
bb823d49058aa175d1e0e136187b24ef0032edcb
2,105
advent-of-code-kotlin
Apache License 2.0
src/Day07.kt
tsschmidt
572,649,729
false
{"Kotlin": 24089}
import java.security.InvalidParameterException fun main() { data class File(val name: String, val size: Long) class Directory(val name: String, val parent: Directory?) { val files = mutableListOf<File>() val dirs = mutableListOf<Directory>() var size = 0L } fun addSize(node: Directory, size: Long) { node.size += size if (node.parent !== null) { addSize(node.parent, size) } } fun createTree(input: List<String>): Directory { val root = Directory("/", null) var node = root input.drop(1).forEach { if (it.startsWith("$ cd")) { val d = it.split(" ").last() node = if (d == "..") { node.parent ?: throw IndexOutOfBoundsException("") } else { node.dirs.find { it.name == d } ?: throw InvalidParameterException("") } } else if (it.contains("dir")) { val d = it.split(" ").last() node.dirs.add(Directory(d, node)) } else if (!it.startsWith("$")){ val (size, name) = it.split(" ") node.files.add(File(name, size.toLong())) addSize(node, size.toLong()) } } return root } fun flattenDirs(node: Directory, dirs: MutableList<Directory>): List<Directory> { dirs.addAll(node.dirs) node.dirs.forEach { flattenDirs(it, dirs) } return dirs } fun part1(input: List<String>): Long { val tree = createTree(input) val dirs = flattenDirs(tree, mutableListOf(tree)) return dirs.filter { it.size < 100000 }.sumOf { it.size } } fun part2(input: List<String>): Long { val tree = createTree(input) val dirs = flattenDirs(tree, mutableListOf(tree)) val used = tree.size val free = 70000000 - used val needed = 30000000 - free return dirs.filter { it.size > needed }.minOf { it.size } } //val input = readInput("Day07_test") //check(part1(input) == 95437L) val input = readInput("Day07") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7bb637364667d075509c1759858a4611c6fbb0c2
2,263
aoc-2022
Apache License 2.0
src/Day02.kt
Aldas25
572,846,570
false
{"Kotlin": 106964}
fun main() { fun outcome(opponent: Int, me: Int): Int { if (opponent == me) { return 1 } if ((opponent+1)%3 == me) { return 2 } return 0 } fun charToNum(c: Char): Int { if (c == 'A' || c == 'X') return 0 if (c == 'B' || c == 'Y') return 1 return 2 } fun evalPermutation(permutation: List<Int>, input: List<String>): Int { var answer = 0 // println("Evaluating $permutation") for (s in input) { val res = outcome( charToNum(s[0]), permutation[charToNum(s[2])] ) answer += 3 * res + permutation[charToNum(s[2])] + 1 // println(" current input: $s") // println(" current outcome: $res") // println(" perm: ${permutation[charToNum(s[2])]}") } return answer } fun part1(input: List<String>): Int { var answer = evalPermutation(listOf(0, 1, 2), input) // for (x in 0..2) // for (y in 0..2) // for (z in 0..2) // if (x != y && y != z && z != x) // answer = maxOf( // answer, // part1_evalScore(listOf(x, y, z), input) // ) return answer } fun part2(input: List<String>): Int { var answer = 0 // println("Evaluating $permutation") for (s in input) { val res = charToNum(s[2]) val opponent = charToNum(s[0]) val myChoice: Int if (res == 1) myChoice = opponent else if (res == 2) myChoice = (opponent+1)%3 else myChoice = (opponent+2)%3 answer += 3 * res + myChoice + 1 // println(" current input: $s") // println(" current outcome: $res") // println(" myChoice: $myChoice") } return answer } val filename = // "inputs\\day02_sample" "inputs\\day02" val input = readInput(filename) println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
80785e323369b204c1057f49f5162b8017adb55a
2,226
Advent-of-Code-2022
Apache License 2.0
src/Day02.kt
tbilou
572,829,933
false
{"Kotlin": 40925}
fun main() { fun score(row: String): Int { return when (row) { "A X" -> 3 + 1 "A Y" -> 6 + 2 "A Z" -> 0 + 3 "B X" -> 0 + 1 "B Y" -> 3 + 2 "B Z" -> 6 + 3 "C X" -> 6 + 1 "C Y" -> 0 + 2 "C Z" -> 3 + 3 else -> -1 } } fun score2(row: String): Int { return when (row) { "A X" -> 0 + 3 "A Y" -> 3 + 1 "A Z" -> 6 + 2 "B X" -> 0 + 1 "B Y" -> 3 + 2 "B Z" -> 6 + 3 "C X" -> 0 + 2 "C Y" -> 3 + 3 "C Z" -> 6 + 1 else -> -1 } } fun part1(input: List<String>): Int { return input.sumOf { score(it) } } fun part2(input: List<String>): Int { return input.sumOf { score2(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) // test if implementation meets criteria from the description, like: val testInput2 = readInput("Day02_test") check(part2(testInput2) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
de480bb94785492a27f020a9e56f9ccf89f648b7
1,279
advent-of-code-2022
Apache License 2.0
src/Day04.kt
jaldhar
573,188,501
false
{"Kotlin": 14191}
fun main() { fun String.parse(): Pair<IntRange, IntRange> { val matches = """(\d+)\-(\d+)\,(\d+)\-(\d+)""".toRegex().find(this) val (a1, a2, b1, b2) = matches!!.destructured val first = IntRange(a1.toInt(), a2.toInt()) val second = IntRange(b1.toInt(), b2.toInt()) return Pair(first, second) } fun part1(input: List<String>): Int { var total = 0 for (line in input) { val (first, second) = line.parse() if (first.all { second.contains(it) } || second.all { first.contains(it) }) { total++; } } return total; } fun part2(input: List<String>): Int { var total = 0 for (line in input) { val (first, second) = line.parse() if (!first.intersect(second).isEmpty()) { total++ } } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b193df75071022cfb5e7172cc044dd6cff0f6fdf
1,209
aoc2022-kotlin
Apache License 2.0
src/day05/Day05.kt
EdwinChang24
572,839,052
false
{"Kotlin": 20838}
package day05 import readInput fun main() { part1() part2() } fun part1() = common { input, stacks -> for (line in input) if (line.startsWith("move")) { val asList = line.removePrefix("move ").split(" from ", " to ").map { it.toInt() } repeat(asList[0]) { stacks[asList[2] - 1] += stacks[asList[1] - 1].removeLast() } } } fun part2() = common { input, stacks -> for (line in input) if (line.startsWith("move")) { val asList = line.removePrefix("move ").split(" from ", " to ").map { it.toInt() } val popped = mutableListOf<Char>() repeat(asList[0]) { popped += stacks[asList[1] - 1].removeLast() } popped.reverse() stacks[asList[2] - 1].addAll(popped) } } fun common(moveStrategy: (input: List<String>, stacks: MutableList<MutableList<Char>>) -> Unit) { val input = readInput(5) val stacks = mutableListOf<MutableList<Char>>() for (line in input) if (line.startsWith(" 1")) { repeat(line.split(" ").last().toInt()) { stacks += mutableListOf<Char>() } } for (line in input) { if (line.startsWith(" 1")) break for (index in line.indices) if (line[index].isLetter()) stacks[(index - 1) / 4] += line[index] } for (s in stacks) s.reverse() moveStrategy(input, stacks) stacks.forEach { print(it.last()) } println() }
0
Kotlin
0
0
e9e187dff7f5aa342eb207dc2473610dd001add3
1,360
advent-of-code-2022
Apache License 2.0
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day04/Day04.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2022.day04 import nerok.aoc.utils.Input import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: List<String>): Long { return input .map { line -> line.split(',') .map { range -> range.split('-') .map { endpoint -> endpoint.toLong() } } .map { longs -> LongRange(longs.first(), longs.last()) } }.count { longRanges -> val intersect = longRanges.first().intersect(longRanges.last()) longRanges.first().toSet() == intersect || longRanges.last().toSet() == intersect }.toLong() } fun part2(input: List<String>): Long { return input .map { line -> line.split(',') .map { range -> range.split('-') .map { endpoint -> endpoint.toLong() } } .map { longs -> LongRange(longs.first(), longs.last()) } }.count { longRanges -> longRanges.first().intersect(longRanges.last()).isNotEmpty() }.toLong() } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day04_test") check(part1(testInput) == 2L) check(part2(testInput) == 4L) val input = Input.readInput("Day04") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
1,751
AOC
Apache License 2.0
kotlin/src/main/kotlin/de/p58i/advent-03.kt
mspoeri
573,120,274
false
{"Kotlin": 31279}
package de.p58i import java.io.File import java.util.LinkedList class Backpack( val items: List<Char> ) { val firstCompartment: List<Char> val secondCompartment: List<Char> val sharedItem: Char companion object{ fun separateCompartments(items: List<Char>): Pair<List<Char>,List<Char>>{ assert(items.size.mod(2) == 0) val splitIndex = items.size / 2 val firstCompartment = items.subList(0, splitIndex) val secondCompartment = items.subList(splitIndex, items.size) assert(firstCompartment.size == secondCompartment.size) return Pair(firstCompartment, secondCompartment) } } init { val (first, second) = separateCompartments(items) firstCompartment = first secondCompartment = second val sharedList = firstCompartment.intersect(secondCompartment) assert(sharedList.size == 1) sharedItem = sharedList.first() } } class ElfGroup( val backpacks: List<Backpack> ) { val groupIdentifier: Char init { val identifier = backpacks.map{ it.items}.fold(backpacks.first().items){ acc, chars -> acc.intersect(chars).toList() } assert(identifier.size == 1) groupIdentifier = identifier.first() } } fun Char.toPriority(): Int { return if (this - 'a' < 0){ this - 'A' + 27 } else { this - 'a' + 1 } } fun main(){ val backpacks = LinkedList<Backpack>() File("./task-inputs/advent-03.input").forEachLine { backpacks.add(Backpack(it.toCharArray().toList())) } backpacks.forEachIndexed { index, backpack -> println("#$index:\t ${backpack.sharedItem}(${backpack.sharedItem.toPriority()})") } println("shared priority sum: ${backpacks.sumOf { it.sharedItem.toPriority() }}") val groups = backpacks.chunked(3).map { ElfGroup(it) } groups.forEachIndexed { index, elfGroup -> println("#$index:\t ${elfGroup.groupIdentifier}(${elfGroup.groupIdentifier.toPriority()})") } println("group priority sum: ${groups.sumOf { it.groupIdentifier.toPriority() }}") }
0
Kotlin
0
1
62d7f145702d9126a80dac6d820831eeb4104bd0
2,162
Advent-of-Code-2022
MIT License
src/Day02.kt
andyludeveloper
573,249,939
false
{"Kotlin": 7818}
fun main() { val map = mapOf( "A Y" to 8, "A X" to 4, "A Z" to 3, "B X" to 1, "B Y" to 5, "B Z" to 9, "C X" to 7, "C Y" to 2, "C Z" to 6 ) val map2 = mapOf( "A X" to "Z", "A Y" to "X", "A Z" to "Y", "B X" to "X", "B Y" to "Y", "B Z" to "Z", "C X" to "Y", "C Y" to "Z", "C Z" to "X" ) fun part1(input: List<String>): Int { var result = 0 input.forEach { result += map[it] ?: 0 } return result } fun part2(input: List<String>): Int { var result = 0 for (item in input) { if (item.endsWith("X")) { result += 0 } if (item.endsWith("Y")) { result += 3 } if (item.endsWith("Z")) { result += 6 } val myTurn = map2[item] when (myTurn) { "X" -> result += 1 "Y" -> result += 2 "Z" -> result += 3 } } return result } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
684cf9ff315f15bf29914ca25b44cca87ceeeedf
1,348
Kotlin-in-Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/aoc2016/day3/Triangles.kt
arnab
75,525,311
false
null
package aoc2016.day3 data class Triangle(val a: Int, val b: Int, val c: Int) { fun isValid(): Boolean = (a + b > c) && (b + c > a) && (c + a > b) } object Triangles { fun countValid(data: String): Int { return data.lines() .map(String::trim) .filter(String::isNotBlank) .map { it.split(Regex("""\s+""")) } .map { line -> val (a, b, c) = line Triangle(a.toInt(), b.toInt(), c.toInt()) } .count { it.isValid() } } fun countValidVertical(data: String): Int { return data.lines() .map(String::trim) .filter(String::isNotBlank) .map { it.split(Regex("""\s+""")) } .withIndex() .groupBy { val (index, _) = it index / 3 } .values .toList() .map { it.map { it.value } } .map(this::trianglesFromGroupsOfThree) .flatten() .count { it.isValid() } } private fun trianglesFromGroupsOfThree(group: List<List<String>>): List<Triangle> { return listOf(trianglesFromGroups(group, 0), trianglesFromGroups(group, 1), trianglesFromGroups(group, 2)) .flatten() } private fun trianglesFromGroups(group: List<List<String>>, i: Int): List<Triangle> { return listOf( Triangle(group[0][i].toInt(), group[1][i].toInt(), group[2][i].toInt()) ) } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
1,604
adventofcode
MIT License
src/Day11.kt
ajmfulcher
573,611,837
false
{"Kotlin": 24722}
import java.math.BigInteger class Operation(private val op: (BigInteger, BigInteger) -> BigInteger) { fun apply(operand: BigInteger, i: BigInteger) = op(operand, i) } fun operation(sign: String): Operation = when(sign) { "+" -> Operation { a, b -> a.plus(b) } "-" -> Operation { a, b -> a.minus(b) } "/" -> Operation { a, b -> a.div(b) } "*" -> Operation { a, b -> a.times(b) } else -> throw Error() } typealias ThrowTo = (Int, BigInteger) -> Unit typealias ManageWorries = (BigInteger) -> BigInteger class Monkey( private val operation: Operation, val divisor: BigInteger, private val trueIdx: Int, private val falseIdx: Int, startItems: List<BigInteger>, private val operand: BigInteger? ) { private val items = ArrayDeque<BigInteger>(startItems) var inspections = 0.toBigInteger() fun takeTurn(manageWorries: ManageWorries, throwTo: ThrowTo) { while (items.isNotEmpty()) { val item = items.removeFirst() val o = operand ?: item val worryLevel = manageWorries(operation.apply(o, item)) if (worryLevel.rem(divisor) == 0.toBigInteger()) throwTo(trueIdx, worryLevel) else throwTo(falseIdx, worryLevel) inspections += 1.toBigInteger() } } fun catch(item: BigInteger) { items += item } } fun main() { fun createMonkey( block: List<String> ): Monkey { val startItems = block[1].split(":")[1].trim().split(", ").map { BigInteger(it) } val op = block[2].split("=")[1].trim().split(" ") val sign = op[1] val operand = op[2] val divisor = BigInteger(block[3].split(" ").last()) val trueIdx = block[4].split(" ").last().toInt() val falseIdx = block[5].split(" ").last().toInt() return Monkey( operation = operation(sign), divisor = divisor, trueIdx = trueIdx, falseIdx = falseIdx, startItems = startItems, operand = if (operand == "old") null else BigInteger(operand) ) } fun createMonkeys(input: List<String>): List<Monkey> { val monkeys = mutableListOf<Monkey>() (0..input.lastIndex step 7).forEach { idx -> monkeys.add(createMonkey(input.subList(idx, input.size))) } return monkeys } fun List<Monkey>.productOfTwoLargest() = map { monkey -> monkey.inspections } .sortedDescending() .take(2) .reduce { a, b -> a.times(b) } fun part1(input: List<String>): BigInteger { val monkeys = createMonkeys(input) val throwTo: ThrowTo = { idx, item -> monkeys[idx].catch(item) } val manageWorries: ManageWorries = { i -> i.div(3.toBigInteger()) } (1..20).forEach { _ -> monkeys.forEach { monkey -> monkey.takeTurn(manageWorries, throwTo) } } return monkeys.productOfTwoLargest() } fun part2(input: List<String>): BigInteger { val monkeys = createMonkeys(input) val modulo = monkeys.map { it.divisor }.reduce { acc, i -> acc.times(i) } val throwTo: ThrowTo = { idx, item -> monkeys[idx].catch(item) } val manageWorries: ManageWorries = { i -> i.rem(modulo) } (1..10000).forEach { round -> monkeys.forEach { monkey -> monkey.takeTurn(manageWorries, throwTo) } } return monkeys.productOfTwoLargest() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") println(part1(testInput)) check(part1(testInput) == 10605.toBigInteger()) val input = readInput("Day11") println(part1(input)) check(part1(input) == 101436.toBigInteger()) println(part2(testInput)) check(part2(testInput) == 2713310158.toBigInteger()) println(part2(input)) }
0
Kotlin
0
0
981f6014b09e347241e64ba85e0c2c96de78ef8a
3,893
advent-of-code-2022-kotlin
Apache License 2.0
day10/src/Day10.kt
rnicoll
438,043,402
false
{"Kotlin": 90620, "Rust": 1313}
import java.nio.file.Files import java.nio.file.Path import java.util.* object Day10 { val PART1_SCORES: Map<Char, Int> = mapOf( Pair(')', 3), Pair(']', 57), Pair('}', 1197), Pair('>', 25137) ) val PART2_SCORES: Map<Char, Int> = mapOf( Pair(')', 1), Pair(']', 2), Pair('}', 3), Pair('>', 4) ) val COMPLETION: Map<Char, Char> = mapOf( Pair('(', ')'), Pair('[', ']'), Pair('{', '}'), Pair('<', '>') ) } fun main() { val commands = Files.readAllLines(Path.of("input")) .map { it.trim() } .filter { it.isNotBlank() } part1(commands) part2(commands) } fun part1(commands: Iterable<String>) { val incorrect = mutableListOf<Char>() commands.forEach { command -> val stack = Stack<Char>() for (i in command.indices) { when (val c = command[i]) { '(' -> stack.add(c) '[' -> stack.add(c) '{' -> stack.add(c) '<' -> stack.add(c) ')' -> { if (stack.pop() != '(') { incorrect.add(c) break } } '}' -> { if (stack.pop() != '{') { incorrect.add(c) break } } ']' -> { if (stack.pop() != '[') { incorrect.add(c) break } } '>' -> { if (stack.pop() != '<') { incorrect.add(c) break } } } } } println(incorrect.mapNotNull { Day10.PART1_SCORES[it] }.sum()) } fun part2(commands: Iterable<String>) { val scores = commands.map { command -> val missing = completeLine(command) var lineScore: Long = 0L missing.mapNotNull { Day10.PART2_SCORES[it] }.forEach { lineScore = lineScore * 5 + it } lineScore }.filter { it != 0L } .sorted() println(scores) println(scores[(scores.size - 1) / 2]) } fun completeLine(command: String): Iterable<Char> { val stack = Stack<Char>() for (i in command.indices) { when (val c = command[i]) { '(', '[', '{', '<' -> stack.add(c) ')', '}', ']', '>' -> { if (Day10.COMPLETION[stack.pop()] != c) { return emptyList() } } } } return stack.mapNotNull { Day10.COMPLETION[it] }.toList().reversed() }
0
Kotlin
0
0
8c3aa2a97cb7b71d76542f5aa7f81eedd4015661
2,755
adventofcode2021
MIT License
src/Day02.kt
cornz
572,867,092
false
{"Kotlin": 35639}
fun main() { fun toNum(alpha: String): Int { val ret = when (alpha) { "A", "X" -> 1 "B", "Y" -> 2 else -> 3 } return ret } fun getDecidedOutcomeChar(alpha: String): String { val ret = when (alpha) { "X" -> "loss" "Z" -> "win" else -> "draw" } return ret } fun computeOutcomeScore(result: Pair<Int,Int>): Int { val (a,b) = result return when (a-b) { -1, 2 -> { 6 } 1, -2 -> { 0 } else -> 3 } } fun verifyOutcome(desiredOutcome: Pair<Int,String>): Boolean { val (a,b) = desiredOutcome if (a == 6 && b == "win") { return true } if (a == 3 && b == "draw") { return true } if (a == 0 && b == "loss") { return true } return false } fun part1(input: List<String>): Int { var totalScore = 0 for (line in input) { var score: Int val values = line.split(" ") val left = toNum(values[0]) val right = toNum(values[1]) val outcome = computeOutcomeScore(Pair(left, right)) score = right + outcome totalScore += score } return totalScore } fun part2(input: List<String>): Int { var totalScore = 0 for (line in input) { var score: Int val values = line.split(" ") val left = toNum(values[0]) var right = 0 val desiredOutcome = getDecidedOutcomeChar(values[1]) for (char in listOf("X", "Y", "Z")) { val testRight = toNum(char) val testOutcome = computeOutcomeScore(Pair(left, testRight)) if (verifyOutcome(Pair(testOutcome, desiredOutcome))) { right = toNum(char) } } val outcome = computeOutcomeScore(Pair(left,right)) score = right + outcome totalScore += score } return totalScore } // test if implementation meets criteria from the description, like: val testInput = readInput("input/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("input/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2800416ddccabc45ba8940fbff998ec777168551
2,512
aoc2022
Apache License 2.0
src/Day06.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 288L private const val EXPECTED_2 = 71503L private class Day06(isTest: Boolean) : Solver(isTest) { fun part1(): Any { val lines = readAsLines() val times = lines[0].splitInts() val distance = lines[1].splitInts() var sum = 1L for (i in 0 until times.size) { val time = times[i] val dist = distance[i] var t = 0 for (press in 0..time) { val speed = press val mydist = speed * (time - press) if (mydist > dist) t++ } sum *= t } return sum } fun part2(): Any { val lines = readAsLines().map { it.filter { it.isDigit() }.toLong() } val time = lines[0] val dist = lines[1] println("$time $dist") var t = 0L for (press in 0..time) { val speed = press val mydist = speed * (time - press) if (mydist > dist) t++ } return t } } fun main() { val testInstance = Day06(true) val instance = Day06(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
1,458
advent-of-code-2022
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2023/Day11.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2023 import ru.timakden.aoc.util.Point import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 11: Cosmic Expansion](https://adventofcode.com/2023/day/11). */ object Day11 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2023/Day11") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>) = solve(input, 2) fun part2(input: List<String>) = solve(input, 1_000_000) private fun solve(input: List<String>, multiplier: Int): Long { val emptyRowIndices = getEmptyRowIndices(input) val emptyColumnIndices = getEmptyColumnIndices(input) val galaxies = extractGalaxies(input, emptyRowIndices, emptyColumnIndices, multiplier) var sum = 0L galaxies.forEachIndexed { i, point -> for (j in i..galaxies.lastIndex) { sum += point.distanceTo(galaxies[j]) } } return sum } private fun getEmptyRowIndices(input: List<String>) = input.mapIndexedNotNull { i, s -> if (s.all { it == '.' }) i else null } private fun getEmptyColumnIndices(input: List<String>): List<Int> { val indices = mutableListOf<Int>() for (i in 0..input.first().lastIndex) { if (input.all { it[i] == '.' }) indices += i } return indices } private fun extractGalaxies( input: List<String>, emptyRowIndices: List<Int>, emptyColumnIndices: List<Int>, multiplier: Int ): List<Point> { val galaxies = mutableListOf<Point>() input.forEachIndexed { row, s -> s.forEachIndexed { column, c -> if (c == '#') { val rowOffset = (multiplier - 1) * emptyRowIndices.count { it < row } val columnOffset = (multiplier - 1) * emptyColumnIndices.count { it < column } galaxies += Point(column + columnOffset, row + rowOffset) } } } return galaxies } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,175
advent-of-code
MIT License
src/main/kotlin/g2601_2700/s2646_minimize_the_total_price_of_the_trips/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2601_2700.s2646_minimize_the_total_price_of_the_trips // #Hard #Array #Dynamic_Programming #Depth_First_Search #Tree #Graph // #2023_07_19_Time_264_ms_(100.00%)_Space_39.6_MB_(100.00%) class Solution { fun minimumTotalPrice(n: Int, edges: Array<IntArray>, price: IntArray, trips: Array<IntArray>): Int { val counts = IntArray(n) val adj: MutableList<MutableList<Int?>?> = ArrayList() for (i in 0 until n) adj.add(ArrayList()) for (edge in edges) { adj[edge[0]]!!.add(edge[1]) adj[edge[1]]!!.add(edge[0]) } for (trip in trips) { val vis = BooleanArray(n) dfsTraverse(trip[0], trip[1], counts, adj, vis) } val dp = IntArray(n) for (i in dp.indices) { dp[i] = -1 } val paths = BooleanArray(n) return dpDFS(n - 1, dp, adj, paths, price, counts) } private fun dfsTraverse( start: Int, tgt: Int, counts: IntArray, adj: MutableList<MutableList<Int?>?>, vis: BooleanArray ): Boolean { if (vis[start]) return false vis[start] = true if (start == tgt) { counts[start]++ return true } var ans = false for (adjacent in adj[start]!!) { ans = ans or dfsTraverse(adjacent!!, tgt, counts, adj, vis) } if (ans) { counts[start]++ } return ans } private fun dpDFS( node: Int, dp: IntArray, adj: MutableList<MutableList<Int?>?>, paths: BooleanArray, prices: IntArray, counts: IntArray ): Int { if (paths[node]) return 0 if (dp[node] != -1) return dp[node] var ans1 = 0 var ans2 = 0 var childval = 0 paths[node] = true for (child1 in adj[node]!!) { if (paths[child1!!]) continue paths[child1] = true for (child2 in adj[child1]!!) { val `val` = dpDFS(child2!!, dp, adj, paths, prices, counts) ans2 += `val` } paths[child1] = false childval += counts[child1] * prices[child1] ans1 += dpDFS(child1, dp, adj, paths, prices, counts) } val ans = (ans2 + childval + prices[node] * counts[node] / 2).coerceAtMost(ans1 + prices[node] * counts[node]) paths[node] = false return ans.also { dp[node] = it } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,499
LeetCode-in-Kotlin
MIT License
src/main/kotlin/adventofcode2020/solution/Day4.kt
lhess
320,667,380
false
null
package adventofcode2020.solution import adventofcode2020.Solution import adventofcode2020.resource.PuzzleInput import adventofcode2020.resource.asBlocks import java.io.File class Day4(puzzleInput: PuzzleInput<String>) : Solution<String, Int>(puzzleInput) { private val blocks = puzzleInput.asBlocks().map { it.replace("\n", " ") } override fun runPart1() = blocks .count { it.isValidPassport(validate = false) } .apply { check(this == 206) } override fun runPart2() = blocks .count { it.isValidPassport(validate = true) } .apply { check(this == 123) } companion object { private val fieldConfig = mapOf<String, (String) -> Boolean>( "byr" to { it.toIntOrNull() in 1920..2002 }, "iyr" to { it.toIntOrNull() in 2010..2020 }, "eyr" to { it.toIntOrNull() in 2020..2030 }, "hgt" to { when { it.endsWith("in") -> it.filter { it.isDigit() }.toInt() in 59..76 it.endsWith("cm") -> it.filter { it.isDigit() }.toInt() in 150..193 else -> false } }, "hcl" to { Regex("""#[a-f0-9]{6}""").matches(it) }, "ecl" to { setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth").contains(it) }, "pid" to { Regex("""[0-9]{9}""").matches(it) }, ) private fun String.isValidPassport(validate: Boolean): Boolean = split(" ") .map { it.split(":", limit = 2).let { it[0] to it[1] } } .toMap() .let { keyValuePairs -> fieldConfig.count { (fieldName, validator) -> !keyValuePairs.containsKey(fieldName) || (validate && !validator(keyValuePairs[fieldName]!!)) } == 0 } private fun File.parseAsBlocks(): List<String> = bufferedReader() .use { it.readText() } .split("\n\n") .map { it.replace("\n", " ") } } }
0
null
0
1
cfc3234f79c27d63315994f8e05990b5ddf6e8d4
2,057
adventofcode2020
The Unlicense
src/main/kotlin/de/tek/adventofcode/y2022/day13/DistressSignal.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.day13 import de.tek.adventofcode.y2022.util.readInputLines import de.tek.adventofcode.y2022.util.splitByBlankLines import kotlinx.serialization.json.* sealed class PacketContent : Comparable<PacketContent> class Integer(val value: Int) : PacketContent() { override fun compareTo(other: PacketContent) = when (other) { is Integer -> this.value.compareTo(other.value) is PacketList -> PacketList(this).compareTo(other) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Integer) return false return value == other.value } override fun hashCode() = value override fun toString() = value.toString() companion object { fun from(jsonPrimitive: JsonPrimitive): Integer { val item = jsonPrimitive.content.toInt() return Integer(item) } } } typealias Packet = PacketList class PacketList() : PacketContent() { private val content = mutableListOf<PacketContent>() constructor(vararg elements: PacketContent) : this() { content.addAll(elements) } fun add(item: PacketContent): PacketList { content.add(item) return this } override fun compareTo(other: PacketContent): Int { val otherList = if (other is PacketList) other else PacketList(other) if (this.content.isEmpty() && otherList.content.isEmpty()) return 0 val contentSizeDifference = this.content.size - otherList.content.size val resultFromContentComparison = compareContent(otherList) return resultFromContentComparison ?: contentSizeDifference } private fun compareContent(otherList: PacketList) = this.content.zip(otherList.content).asSequence().map { it.first.compareTo(it.second) }.filter { it != 0 } .firstOrNull() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PacketList) return false if (content != other.content) return false return true } override fun hashCode() = content.hashCode() override fun toString() = "[" + content.joinToString(",") + "]" companion object { fun from(jsonElement: JsonElement): Packet { val result = Packet() for (element in jsonElement.jsonArray) { when (element) { is JsonArray -> result.add(Packet.from(element)) is JsonPrimitive -> result.add(Integer.from(element)) else -> throw IllegalArgumentException("Invalid list in packet string: $element.") } } return result } } } fun main() { val input = readInputLines(PacketList::class) println("The sum of the indices of the pairs that are in right order is ${part1(input)}.") println("The decoder key is ${part2(input)}.") } fun part1(input: List<String>): Int { val packetPairs = splitByBlankLines(input).map { parseTwoLinesAsPackets(it) }.map { Pair(it[0], it[1]) } return packetPairs.map { pair -> pair.first <= pair.second }.withIndex().filter { it.value }.sumOf { it.index + 1 } } fun part2(input: List<String>): Int { val packets = parsePackets(input) fun createDivider(int: Int) = Packet(Packet(Integer(int))) val firstDivider = createDivider(2) val secondDivider = createDivider(6) val packetsWithDividers = packets + firstDivider + secondDivider val sortedPackets = packetsWithDividers.sorted() fun Iterable<Packet>.oneBasedIndexOf(element: PacketContent) = indexOf(element) + 1 val firstDividerIndex = sortedPackets.oneBasedIndexOf(firstDivider) val secondDividerIndex = sortedPackets.oneBasedIndexOf(secondDivider) return firstDividerIndex * secondDividerIndex } private fun parseTwoLinesAsPackets(it: List<String>) = it.take(2).map(Json::parseToJsonElement).map(Packet::from) fun parsePackets(input: List<String>) = input.filter { it.isNotBlank() }.map(Json::parseToJsonElement).map(Packet::from)
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
4,135
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc/Day04.kt
fluxxion82
573,716,300
false
{"Kotlin": 39632}
package aoc import java.io.File fun List<String>.rangeValueStart() = this.first().toInt() fun List<String>.rangeValueEnd() = this.last().toInt() fun List<String>.getRange() = (this.rangeValueStart() .. this.rangeValueEnd()) fun main() { val testInput = File("src/Day04_test.txt").readText() val input = File("src/Day04.txt").readText() fun part1(input: String): Int { return input.split("\n") .map { it.split(",") }.associate { pairs -> pairs.first().split("-") to pairs.last().split("-") }.count { val firstRange = it.key val secondRange = it.value firstRange.getRange().contains(secondRange.rangeValueStart()) && firstRange.getRange().contains(secondRange.rangeValueEnd()) || secondRange.getRange().contains(firstRange.rangeValueStart()) && secondRange.getRange().contains(firstRange.rangeValueEnd()) } } fun part2(input: String): Int { return input.split("\n") .map { it.split(",") }.associate { pairs -> pairs.first().split("-") to pairs.last().split("-") }.count { val firstRange = it.key val secondRange = it.value firstRange.getRange().contains(secondRange.rangeValueStart()) && firstRange.getRange().contains(secondRange.rangeValueEnd()) || secondRange.getRange().contains(firstRange.rangeValueStart()) || secondRange.getRange().contains(firstRange.rangeValueEnd()) } } println("part one test: ${part1(testInput)}") println("part one: ${part1(input)}") println("part two test: ${part2(testInput)}") println("part two: ${part2(input)}") }
0
Kotlin
0
0
3920d2c3adfa83c1549a9137ffea477a9734a467
1,918
advent-of-code-kotlin-22
Apache License 2.0
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day13/Day13.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * 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 com.pietromaggi.aoc2021.day13 import com.pietromaggi.aoc2021.readInput data class Dot(val x: Int, val y:Int) data class FoldInfo(val type: Char, val cord: Int) fun parseInput(input: List<String>): Pair<MutableSet<Dot>, MutableList<FoldInfo>> { val dots = mutableSetOf<Dot>() val folds = mutableListOf<FoldInfo>() var readDotsCoords = true for (line in input) { if (line.isBlank()) readDotsCoords = false else { if (readDotsCoords) { val (x, y) = line.split(",").map(String::toInt) dots.add(Dot(x, y)) } else { val (axes, value) = line.split("=") folds.add(FoldInfo(axes.trimEnd().last(), value.toInt())) } } } return Pair(dots, folds) } fun doFold(foldInfo: FoldInfo, dots: Set<Dot>): Set<Dot> { return if (foldInfo.type == 'x') { // fold is vertical buildSet { for (dot in dots) { this.add( Dot( ( if (dot.x > foldInfo.cord) { foldInfo.cord * 2 - dot.x } else dot.x), dot.y ) ) } } } else { // fold is horizontal buildSet { for (dot in dots) { this.add( Dot( dot.x, if (dot.y > foldInfo.cord) { foldInfo.cord * 2 - dot.y } else dot.y ) ) } } } } fun buildCode(dots: Set<Dot>) : List<String> { val sizeX = dots.maxOf { it.x } val sizeY = dots.maxOf { it.y } return buildList { for (y in 0..sizeY) { var line = "" for (x in 0..sizeX) { line += if (dots.contains(Dot(x, y))) "#" else " " } this.add(line) } } } fun part1(input: List<String>): Int { val (dots, folds) = parseInput(input) // evaluate just the first fold return doFold(folds[0], dots).size } fun part2(input: List<String>): List<String> { val (dots, folds) = parseInput(input) var foldedDots = dots as Set<Dot> folds.forEach { foldInfo -> foldedDots = doFold(foldInfo, foldedDots) } return buildCode(foldedDots) } fun main() { val input = readInput("Day13") println(part1(input)) for (line in part2(input)) { println(line) } }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
3,186
AdventOfCode
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch3/Problem36.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch3 import dev.bogwalk.util.strings.isPalindrome /** * Problem 36: Double-Base Palindromes * * https://projecteuler.net/problem=36 * * Goal: Find the sum of all natural numbers (without leading zeroes) less than N that are * palindromic in both base 10 and base K. * * Constraints: 10 <= N <= 1e6, 2 <= K <= 9 * * e.g.: N = 10, K = 2 * result = {(1, 1), (3, 11), (5, 101), (7, 111), (9, 1001)} * sum = 25 */ class DoubleBasePalindromes { /** * SPEED (WORSE) 39.84s for N = 1e9, K = 2 */ fun sumOfPalindromesBrute(n: Int, k: Int): Int { return (1 until n).sumOf { num -> if (num.toString().isPalindrome() && num.switchBase(k).isPalindrome()) { num } else 0 } } /** * In-built function that returns String representation of base 10 to base x conversion. */ private fun Int.switchBase(base: Int) = this.toString(radix=base) /** * Solution is optimised by only iterating over generated base-k palindromes less than N. * * This also means that, unlike in the brute force solution, only 1 number (the base-10 * result) needs to be checked as a palindrome. * * SPEED (BETTER) 16.45ms for N = 1e9, K = 2 */ fun sumOfPalindromes(n: Int, k: Int): Int { var sum = 0 var oddTurn = true // generate both odd & even length palindromes repeat(2) { var i = 1 do { // generate decimal representation of base-k palindrome val decimalRepr = getPalindrome(i, k, oddTurn) // check if decimal is also a palindrome if (decimalRepr.toString().isPalindrome()) { sum += decimalRepr } i++ } while (decimalRepr < n) oddTurn = false } return sum } /** * Returns the decimal representation of the nth odd-/even-length palindrome in the * specified [base]. * e.g. The 2nd odd-length base 2 palindrome is 101 == 5. */ private fun getPalindrome(num: Int, base: Int, oddLength: Boolean = true): Int { var palindrome = num var n = num if (oddLength) { // base 2 -> n shr 1 n /= base } while (n > 0) { // base 2 -> palindrome shl 1 + n and 1 palindrome = palindrome * base + n % base // base 2 -> n shr 1 n /= base } return palindrome } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,571
project-euler-kotlin
MIT License
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day22CrabCombat.kt
Scavi
68,294,098
false
{"Java": 1449516, "Kotlin": 59149}
package com.scavi.brainsqueeze.adventofcode import java.util.* class Day22CrabCombat { private enum class Player { Unknown, Player1, Player2 } fun solveA(input: List<String>): Int { val playersCards = getCards(input) val res = play(playersCards.first, playersCards.second, false) return res.second.withIndex().map { res.second[it.index] * (res.second.size-it.index)}.sum() } fun solveB(input: List<String>): Int { val playersCards = getCards(input) val res = play(playersCards.first, playersCards.second, true) return res.second.withIndex().map { res.second[it.index] * (res.second.size-it.index)}.sum() } private fun play( playersCards1: LinkedList<Int>, playersCards2: LinkedList<Int>, recursion: Boolean): Pair<Boolean, LinkedList<Int>> { val seen = mutableSetOf<Int>() while (playersCards1.isNotEmpty() and playersCards2.isNotEmpty()) { if (playersCards1.hashCode() in seen || playersCards2.hashCode() in seen) { return Pair(true, playersCards1) } // Major improvement from 1,6 seconds to 155 ms after discussing / looking at // https://github.com/shaeberling/euler/blob/master/kotlin/src/com/s13g/aoc/aoc2020/Day22.kt seen.add(playersCards1.hashCode()) seen.add(playersCards2.hashCode()) val card1 = playersCards1.pop() val card2 = playersCards2.pop() var player1Won = card1 > card2 if (recursion && playersCards1.size >= card1 && playersCards2.size >= card2) { player1Won = play(LinkedList(playersCards1.subList(0, card1)), LinkedList(playersCards2.subList(0, card2)), recursion).first } if (player1Won) { playersCards1.add(card1) playersCards1.add(card2) } else { playersCards2.add(card2) playersCards2.add(card1) } } return Pair(playersCards1.isNotEmpty(), if (playersCards1.isEmpty()) playersCards2 else playersCards1) } private fun getCards(input: List<String>): Pair<LinkedList<Int>, LinkedList<Int>> { val cardsPlayer1 = LinkedList<Int>() val cardsPlayer2 = LinkedList<Int>() var player = Player.Unknown for (line in input) { if (line.isNotEmpty()) { when { "Player 1" in line -> player = Player.Player1 "Player 2" in line -> player = Player.Player2 else -> { when (player) { Player.Player1 -> cardsPlayer1.add(line.toInt()) Player.Player2 -> cardsPlayer2.add(line.toInt()) else -> error("wooops!") } } } } } return Pair(cardsPlayer1, cardsPlayer2) } }
0
Java
0
1
79550cb8ce504295f762e9439e806b1acfa057c9
3,027
BrainSqueeze
Apache License 2.0
src/Day16.kt
halirutan
575,809,118
false
{"Kotlin": 24802}
data class Valve(val neighbors: List<String>, val flow: Int, val pressureRelease: Int = 0) data class Player(val currentValve: String, val remainingTime: Int) // We use these for the stack where we store the search progression data class OnePlayerGame(val g: GameState, val p1: Player) data class TwoPlayerGame(val g: GameState, val p1: Player, val p2: Player) val globalPathStore = mutableMapOf<Set<String>, Int>() data class ValveOnAction(val target: String) data class GameState(val valves: Map<String, Valve>) { val score = valves.values.sumOf { it.pressureRelease } override fun toString(): String { val builder = StringBuilder() builder.append("Used valves ${valves.values.filter { it.pressureRelease > 0 }.size}:") for (valve in valves) { if (valve.value.pressureRelease > 0) { builder .append(valve.key) .append(" (${valve.value.flow} -> ${valve.value.pressureRelease}) ") } } return builder.toString() } fun getPossibleActions(): List<ValveOnAction> { val result = mutableListOf<ValveOnAction>() for (v in valves.filter { it.value.flow > 0 && it.value.pressureRelease == 0 }) { result.add(ValveOnAction(v.key)) } return result } fun doAction(act: ValveOnAction, player: Player): Pair<GameState, Player> { assert(player.remainingTime > 0) val vToTurnOn = valves[act.target] ?: throw Error("Valve ${act.target} does not exist") assert(vToTurnOn.flow > 0) val timeToTravel = findShortestPath(player.currentValve, act.target) val newValves = valves.toMutableMap() val remainingTimeAfterAction = player.remainingTime - timeToTravel - 1 newValves[act.target] = Valve( vToTurnOn.neighbors, vToTurnOn.flow, remainingTimeAfterAction * vToTurnOn.flow, ) return Pair(GameState(newValves), Player(act.target, remainingTimeAfterAction)) } /** * @return The time it takes to navigate from valve1 to valve2 */ fun findShortestPath(valve1: String, valve2: String): Int { if (valve1 == valve2) { return 0 } val cache = globalPathStore[setOf(valve1, valve2)] if (cache is Int) { return cache } val q = ArrayDeque<Pair<String, Int>>() val visited = mutableSetOf(valve1) q.add(Pair(valve1, 0)) while (q.isNotEmpty()) { val current = q.removeFirst() val neighbors = valves[current.first]!!.neighbors.filterNot { visited.contains(it) } for (neighbor in neighbors) { val timeUsed = current.second + 1 if (neighbor == valve2) { globalPathStore[setOf(valve1, valve2)] = timeUsed return timeUsed } q.add(Pair(neighbor, timeUsed)) } } throw Error("Could not find path from $valve1 to $valve2") } fun getUnusedValveValue(): Int { return valves.values.filter { it.pressureRelease == 0 && it.flow > 0 }.sumOf { it.flow } } } fun parseGameState(input: List<String>): GameState { val valves = mutableMapOf<String, Valve>() for (line in input) { val parts = line.split(", ", " ") val name = parts[1] val flow = parts[4].split("=", ";")[1].toInt() val neighbors = parts.subList(9, parts.size) valves[name] = Valve(neighbors, flow) } return GameState(valves) } /** * A quick test if the shortest path works */ @Suppress("unused") fun checkShortestPath(input: List<String>) { val game = parseGameState(input) println(game.findShortestPath("AA", "II")) println(game.findShortestPath("AA", "HH")) println(game.findShortestPath("AA", "JJ")) println(game.findShortestPath("CC", "AA")) } fun main() { val smallInput = readInput("Day16_test") val realInput = readInput("Day16") fun part1(input: List<String>) { val remainingTime = 30 val initialValve = "AA" val me = Player(initialValve, remainingTime) val game = parseGameState(input) val stack = ArrayDeque<OnePlayerGame>() stack.add(OnePlayerGame(game, me)) var maxScore = 0 while (stack.isNotEmpty()) { val (g, p) = stack.removeFirst() if (p.remainingTime < 0) { continue } val score = g.score if (score > maxScore) { maxScore = score print(".") } g.getPossibleActions().map { g.doAction(it, p) }.forEach { stack.addFirst(OnePlayerGame(it.first, it.second)) } } println() println("Best Score Part 1: $maxScore") } /** * For part 2 we do the same as for part 1, but we just alternate two players between each move. */ fun part2(input: List<String>) { val remainingTime = 26 val initialValve = "AA" val me = Player(initialValve, remainingTime) val elephant = Player(initialValve, remainingTime) val game = parseGameState(input) val stack = ArrayDeque<TwoPlayerGame>() stack.add(TwoPlayerGame(game, me, elephant)) var maxScore = 0 var iter = 0 while (stack.isNotEmpty()) { val (g, p1, p2) = stack.removeFirst() val score = g.score if (p1.remainingTime < 0 || p2.remainingTime < 0) { continue } // We over-estimate what additional score we can get from the remaining closed valves. // If it can't get bigger than our current max score, we can prune this whole subtree. val remainingValueEstimate = g.getUnusedValveValue() * (p1.remainingTime+p2.remainingTime)/2 if (score + remainingValueEstimate < maxScore) { continue } if (score > maxScore) { maxScore = score print(".") } // Alternating moves between the player and the elephant if (iter.mod(2) == 0) { g .getPossibleActions() .map { g.doAction(it, p1) } .forEach { stack.addFirst(TwoPlayerGame(it.first, it.second, p2)) } }else{ g .getPossibleActions() .map { g.doAction(it, p2) } .forEach { stack.addFirst(TwoPlayerGame(it.first, p1, it.second)) } } iter++ } println() println("Best Score Part 2: $maxScore") } println("Part 1 Small Input") part1(smallInput) println() println() println("Part 1 Real Input") part1(realInput) println() println() println("Part 2 Small Input") part2(smallInput) println() println() println("Part 2 Real Input") part2(realInput) println() println() }
0
Kotlin
0
0
09de80723028f5f113e86351a5461c2634173168
7,247
AoC2022
Apache License 2.0
src/Day02.kt
ExpiredMinotaur
572,572,449
false
{"Kotlin": 11216}
fun main() { //1 = Rock 2 = Paper 3 = Scissors val opponentMap = mapOf("A" to 1, "B" to 2, "C" to 3) //Map opponent to value val playerMap = mapOf("X" to 1, "Y" to 2, "Z" to 3) //Map player to value val winMap = mapOf(1 to 3, 2 to 1, 3 to 2) //win conditions val loseMap = mapOf(3 to 1, 1 to 2, 2 to 3) //lose conditions fun part1(input: List<String>): Int { var score = 0 for (line in input) { val game = line.split(" ") val opponent = opponentMap[game[0]] val player = playerMap[game[1]] if (winMap[player] == opponent) score += 6 //6 points for win else if (player == opponent) score += 3 //3 points for win score += player!! //always score value of what the player played } return score } fun part2(input: List<String>): Int { var score = 0 for (line in input) { val game = line.split(" ") val opponent = opponentMap[game[0]] when (game[1]) { "X" -> score += winMap[opponent]!! //lose "Y" -> score += opponent!! + 3 //draw "Z" -> score += loseMap[opponent]!! + 6 //win } } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
7ded818577737b0d6aa93cccf28f07bcf60a9e8f
1,567
AOC2022
Apache License 2.0
kotlin/521.Longest Uncommon Subsequence I (最长特殊序列 Ⅰ).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p> Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be <b>any</b> subsequence of the other strings. </p> <p> A <b>subsequence</b> is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string. </p> <p> The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1. </p> <p><b>Example 1:</b><br /> <pre> <b>Input:</b> "aba", "cdc" <b>Output:</b> 3 <b>Explanation:</b> The longest uncommon subsequence is "aba" (or "cdc"), <br/>because "aba" is a subsequence of "aba", <br/>but not a subsequence of any other strings in the group of two strings. </pre> </p> <p><b>Note:</b> <ol> <li>Both strings' lengths will not exceed 100.</li> <li>Only letters from a ~ z will appear in input strings. </li> </ol> </p><p>给定两个字符串,你需要从这两个字符串中找出最长的特殊序列。最长特殊序列定义如下:该序列为某字符串独有的最长子序列(即不能是其他字符串的子序列)。</p> <p><strong>子序列</strong>可以通过删去字符串中的某些字符实现,但不能改变剩余字符的相对顺序。空序列为所有字符串的子序列,任何字符串为其自身的子序列。</p> <p>输入为两个字符串,输出最长特殊序列的长度。如果不存在,则返回 -1。</p> <p><strong>示例 :</strong></p> <pre> <strong>输入:</strong> &quot;aba&quot;, &quot;cdc&quot; <strong>输出:</strong> 3 <strong>解析:</strong> 最长特殊序列可为 &quot;aba&quot; (或 &quot;cdc&quot;) </pre> <p><strong>说明:</strong></p> <ol> <li>两个字符串长度均小于100。</li> <li>字符串中的字符仅含有&nbsp;&#39;a&#39;~&#39;z&#39;。</li> </ol> <p>给定两个字符串,你需要从这两个字符串中找出最长的特殊序列。最长特殊序列定义如下:该序列为某字符串独有的最长子序列(即不能是其他字符串的子序列)。</p> <p><strong>子序列</strong>可以通过删去字符串中的某些字符实现,但不能改变剩余字符的相对顺序。空序列为所有字符串的子序列,任何字符串为其自身的子序列。</p> <p>输入为两个字符串,输出最长特殊序列的长度。如果不存在,则返回 -1。</p> <p><strong>示例 :</strong></p> <pre> <strong>输入:</strong> &quot;aba&quot;, &quot;cdc&quot; <strong>输出:</strong> 3 <strong>解析:</strong> 最长特殊序列可为 &quot;aba&quot; (或 &quot;cdc&quot;) </pre> <p><strong>说明:</strong></p> <ol> <li>两个字符串长度均小于100。</li> <li>字符串中的字符仅含有&nbsp;&#39;a&#39;~&#39;z&#39;。</li> </ol> **/ class Solution { fun findLUSlength(a: String, b: String): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
3,134
leetcode
MIT License
src/Day03.kt
wujingwe
574,096,169
false
null
fun main() { fun Char.toPriority(): Int = when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> 0 } fun part1(inputs: List<String>): Int { return inputs.map { s -> val (first, second) = s.chunked(s.length / 2) (first.toSet() intersect second.toSet()).first().toPriority() }.reduce { acc, elem -> acc + elem } } fun part2(inputs: List<String>): Int { return inputs.chunked(3) .map { (first, second, third) -> (first.toSet() intersect second.toSet() intersect third.toSet()) .first() .toPriority() }.reduce { acc, elem -> acc + elem } } val testInput = readInput("../data/Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("../data/Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a5777a67d234e33dde43589602dc248bc6411aee
963
advent-of-code-kotlin-2022
Apache License 2.0
src/test/kotlin/be/brammeerten/y2022/Day2Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2022 import be.brammeerten.readFile import be.brammeerten.y2022.Day2Test.Shape.* import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class Day2Test { private val scores = mapOf( ROCK to Score(SCISSORS, ROCK, PAPER), PAPER to Score(ROCK, PAPER, SCISSORS), SCISSORS to Score(PAPER, SCISSORS, ROCK) ) @Test fun `part 1`() { val lines = readFile("2022/2022/day2/exampleInput.txt") val result = lines .map { it.split(" ") } .map { (a, b) -> mapABC(a) to mapXYZ(b) } .sumOf { (a, b) -> wonScore(a, b) + shapeScore(b) } assertEquals(15, result) } @Test fun `part 2`() { val lines = readFile("2022/2022/day2/exampleInput.txt") val result = lines .map { it.split(" ") } .map { (a, b) -> mapABC(a) to chooseShapePart2(b, mapABC(a)) } .sumOf { (a, b) -> wonScore(a, b) + shapeScore(b) } assertEquals(12, result) } private fun wonScore(opponent: Shape, me: Shape): Int { return scores[me]!!.score(opponent) } private fun shapeScore(chosenShape: Shape) = mapOf(ROCK to 1, PAPER to 2, SCISSORS to 3)[chosenShape]!! private fun mapXYZ(value: String) = mapOf("X" to ROCK, "Y" to PAPER, "Z" to SCISSORS)[value]!! private fun mapABC(value: String) = mapOf("A" to ROCK, "B" to PAPER, "C" to SCISSORS)[value]!! private fun chooseShapePart2(what: String, value: Shape): Shape { return when (what) { "X" -> scores[value]!!.winsFrom // lose "Y" -> scores[value]!!.drawsFrom // draw else -> scores[value]!!.losesFrom // from } } enum class Shape { ROCK, PAPER, SCISSORS } class Score(val winsFrom: Shape, val drawsFrom: Shape, val losesFrom: Shape) { fun score(other: Shape): Int { if (this.winsFrom == other) return 6 if (this.losesFrom == other) return 0 return 3 } } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
2,095
Advent-of-Code
MIT License
src/main/kotlin/aoc2022/Day13.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.parser.* import java.lang.IllegalStateException class Day13 { sealed class ElementOrList : Comparable<ElementOrList> { class E(val value: Int) : ElementOrList() class L(val list: List<ElementOrList>) : ElementOrList() override fun compareTo(other: ElementOrList): Int { return when { this is E && other is E -> { when { value == other.value -> 0 value < other.value -> -1 else -> 1 } } this is L && other is E -> compareTo(L(listOf(other))) this is E && other is L -> L(listOf(this)).compareTo(other) this is L && other is L -> { val notEqual: Int? = list.zip(other.list).map { (f, s) -> f.compareTo(s) }.find { it != 0 } when { notEqual != null -> notEqual else -> when { list.size == other.list.size -> 0 list.size < other.list.size -> -1 else -> 1 } } } else -> throw IllegalStateException() } } } val element = number() map ElementOrList::E val list: Parser<ElementOrList.L> = ("[" followedBy (element or ref(::list) sepBy ",") followedBy "]") map ElementOrList::L val pair = seq(list followedBy "\n", list followedBy "\n") val pairs = pair sepBy "\n" fun part1(input: String): Int { val p = pairs.parse(input) val r = p.map { (f, s) -> f.compareTo(s)} return r.withIndex().filter { (_, v) -> v <= 0}.sumOf { (i, _) -> i+1} } fun part2(input: String): Int { val p = pairs.parse(input).flatMap { it.toList() } val marker1 = ElementOrList.L(listOf(ElementOrList.E(2))) val marker2 = ElementOrList.L(listOf(ElementOrList.E(6))) val n = p + listOf(marker1, marker2) val set = n.toSortedSet() val i1 = set.indexOf(marker1) + 1 val i2 = set.indexOf(marker2) + 1 return i1 * i2 } }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
2,287
aoc-kotlin
Apache License 2.0
src/Day07.kt
mpythonite
572,671,910
false
{"Kotlin": 29542}
fun main() { data class File(val name: String, val size: Int) class Directory(val name: String, val dirs: MutableList<Directory> = mutableListOf(), val files: MutableList<File> = mutableListOf(), val parent: Directory? = null) { fun size(): Int { var size = this.files.fold(0){ sum, element -> sum + element.size} dirs.forEach{ size += it.size() } return size } } fun createFileSystem(input: List<String>): List<Directory> { val directories = mutableListOf(Directory(name = "/")) val fileSystem: MutableList<Directory> = mutableListOf(directories[0]) var currentDirectory = Directory("") var iterator = input.listIterator() while (iterator.hasNext()) { var current = iterator.next() when (current.first()) { '$' -> { when (current.substring(2, 4)) { "cd" -> { val arg = current.substring((5)) if (arg == "/") { currentDirectory = fileSystem.first() } else if (arg == "..") { currentDirectory = currentDirectory.parent!! } else { currentDirectory = currentDirectory.dirs.find { it.name == arg }!! } } "ls" -> { while (iterator.hasNext()) { current = iterator.next() if (current.first() == '$') { current = iterator.previous() break } else { if (current.substring(0, 3) == "dir") { val newDir = Directory(name = current.substring(4), parent = currentDirectory) currentDirectory.dirs.add(newDir) directories.add(newDir) } else { val fileArgs = current.split(' ') currentDirectory.files.add(File(size = fileArgs[0].toInt(), name = fileArgs[1])) } } } } } } } } return directories } fun part1(input: List<String>): Int { val directories = createFileSystem(input) var totalSize = 0 directories.forEach{ if (it.size() <= 100000) totalSize += it.size()} return totalSize } fun part2(input: List<String>): Int { val directories = createFileSystem(input) val freeSpace = 70000000 - directories.first().size() val neededSpace = 30000000 var minSize = Int.MAX_VALUE directories.forEach{ if (freeSpace + it.size() >= neededSpace && it.size() <= minSize) minSize = it.size() } return minSize } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
cac94823f41f3db4b71deb1413239f6c8878c6e4
3,522
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2016/Day01.kt
tginsberg
74,924,040
false
null
/* * Copyright (c) 2016 by <NAME> */ package com.ginsberg.advent2016 /** * Advent of Code - Day 1: December 1, 2016 * * From http://adventofcode.com/2016/day/1 * */ class Day01(instructionText: String) { private val instructions = inputToInstructions(instructionText) private data class Instruction(val move: Int = 1, val turn: Char? = null) private data class State(val x: Int = 0, val y: Int = 0, val facing: Char = 'N') { val distance by lazy { Math.abs(x) + Math.abs(y) } val coordinates by lazy { Pair(x, y) } } /** * How many blocks away is Easter Bunny HQ? */ fun solvePart1(): Int { return instructions .fold(State()) { carry, next -> instruct(carry, next) } .distance } /** * How many blocks away is the first location you visit twice? */ fun solvePart2(): Int { tailrec fun inner(beenTo: Set<Pair<Int,Int>>, path: List<Instruction>, state: State = State()): Int = when { beenTo.contains(state.coordinates) -> state.distance path.isEmpty() -> 0 else -> { inner(beenTo + state.coordinates, path.drop(1), instruct(state, path[0])) } } return inner(emptySet(), instructionToSteps(instructions)) } private fun instruct(state: State, instruction: Instruction): State { val next = if(instruction.turn == null) state else turn(state, instruction.turn) return move(next, instruction.move) } private fun turn(state: State, turn: Char?): State { val next = when (state.facing) { 'N' -> if (turn == 'L') 'W' else 'E' 'S' -> if (turn == 'L') 'E' else 'W' 'E' -> if (turn == 'L') 'N' else 'S' 'W' -> if (turn == 'L') 'S' else 'N' else -> state.facing } return state.copy(facing = next) } private fun move(state: State, amount: Int = 1): State = when(state.facing) { 'N' -> state.copy(x = state.x + amount) 'S' -> state.copy(x = state.x - amount) 'E' -> state.copy(y = state.y + amount) 'W' -> state.copy(y = state.y - amount) else -> state } private fun inputToInstructions(input: String): List<Instruction> = input.split(", ") .map{ Instruction(it.substring(1).toInt(), it[0]) } private fun instructionToSteps(instruction: List<Instruction>): List<Instruction> = instruction.flatMap { listOf(it.copy(move = 1)) + (1 until it.move).map { Instruction() } } }
0
Kotlin
0
3
a486b60e1c0f76242b95dd37b51dfa1d50e6b321
2,754
advent-2016-kotlin
MIT License
src/Day02.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
class Solution02(private val input: List<String>) { private fun scorePart1(shapes: String): Int { return when(shapes.trim()) { "A X" -> 3 + 1 "A Y" -> 6 + 2 "A Z" -> 0 + 3 "B X" -> 0 + 1 "B Y" -> 3 + 2 "B Z" -> 6 + 3 "C X" -> 6 + 1 "C Y" -> 0 + 2 "C Z" -> 3 + 3 else -> throw IllegalArgumentException() } } private fun scorePart2(shapes: String): Int { return when(shapes.trim()) { "A X" -> 0 + 3 "A Y" -> 3 + 1 "A Z" -> 6 + 2 "B X" -> 0 + 1 "B Y" -> 3 + 2 "B Z" -> 6 + 3 "C X" -> 0 + 2 "C Y" -> 3 + 3 "C Z" -> 6 + 1 else -> throw IllegalArgumentException() } } fun part1() = input.sumOf { scorePart1(it) } fun part2() = input.sumOf { scorePart2(it) } } fun main() { val testSolution = Solution02(readInput("Day02_test")) check(testSolution.part1() == 15) check(testSolution.part2() == 12) val solution = Solution02(readInput("Day02")) println(solution.part1()) println(solution.part2()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
1,216
aoc-2022
Apache License 2.0