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/AoC5.kt
Pi143
317,631,443
false
null
import java.io.File fun main() { //tests() println("Starting Day 5 A Test 1") calculateDay5PartA("Input/2020_Day5_A_Test1") println("Starting Day 5 A Real") calculateDay5PartA("Input/2020_Day5_A") println("Starting Day 5 B Test 1") calculateDay5PartB("Input/2020_Day5_A_Test1") println("Starting Day 5 B Real") calculateDay5PartB("Input/2020_Day5_A") } fun tests(){ assert(calculateDay5PartA("Input/2020_Day5_A_Test1")==820) } fun calculateDay5PartA(file: String): Int { val Day5Data = readDay5Data(file) var maxChecksum = 0 for (seatDef in Day5Data) { val checkSum = seatDef.first * 8 + seatDef.second maxChecksum = if (checkSum > maxChecksum) checkSum else maxChecksum } println("$maxChecksum is the highestChecksum") return maxChecksum } fun calculateDay5PartB(file: String) { val checkSumList = (0..calculateDay5PartA(file)).toList().toMutableList() val Day5Data = readDay5Data(file) for (seatDef in Day5Data) { val checkSum = seatDef.first * 8 + seatDef.second checkSumList.remove(checkSum) } val removalList: MutableList<Int> = ArrayList() for (checkSum in checkSumList){ if(checkSumList.contains(checkSum+1) || checkSumList.contains(checkSum-1)){ removalList.add(checkSum) } } checkSumList.removeAll(removalList) println(checkSumList) } fun readDay5Data(input: String): MutableList<Pair<Int, Int>> { val seatList: MutableList<Pair<Int, Int>> = ArrayList() File(localdir + input).forEachLine { seatList.add(decodeSeat(it)) } return seatList } fun decodeSeat(it: String): Pair<Int, Int> { val rowPattern = "([F|B])+".toRegex() val rowDefintion = rowPattern.find(it)?.value val colPattern = "([L|R])+".toRegex() val colDefintion = colPattern.find(it)?.value val rowInt = Integer.parseInt(rowDefintion?.replace('F', '0')?.replace('B', '1'),2) val colInt = Integer.parseInt(colDefintion?.replace('L', '0')?.replace('R', '1'),2) return Pair(rowInt,colInt) }
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
2,078
AdventOfCode2020
MIT License
src/main/kotlin/y2022/day02/Day2.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2022.day02 fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } enum class Option { ROCK, PAPER, SCISSOR } enum class Result { WIN, LOSS, DRAW } data class Match ( val myChoice: Option, val enemyChoice: Option, val desiredResult: Result ) fun String.toOption(): Option { return when (this) { "A" -> Option.ROCK "B" -> Option.PAPER "C" -> Option.SCISSOR "X" -> Option.ROCK "Y" -> Option.PAPER "Z" -> Option.SCISSOR else -> throw IllegalStateException("Invalid Input") } } fun String.toResult(): Result { return when (this) { "X" -> Result.LOSS "Y" -> Result.DRAW "Z" -> Result.WIN else -> throw IllegalStateException("Invalid Input") } } fun input(): List<Match> { return AoCGenerics.getInputLines("/y2022/day02/input.txt").map { line -> val inputs = line.split(" ") val enemyChoice = inputs[0] val myChoice = inputs[1] // For Part 1 val desiredResult = inputs[1] // For Part 2 Match(myChoice.toOption(), enemyChoice.toOption(), desiredResult.toResult()) } } fun Match.getScorePart1(): Int { var score = 0 score += when (myChoice) { Option.ROCK -> 1 Option.PAPER -> 2 Option.SCISSOR -> 3 } // Loss gives no points, so no need to look at it when { myChoice == enemyChoice -> score += 3 // Draws myChoice == Option.ROCK && enemyChoice == Option.SCISSOR -> score += 6 myChoice == Option.PAPER && enemyChoice == Option.ROCK -> score += 6 myChoice == Option.SCISSOR && enemyChoice == Option.PAPER -> score += 6 } return score } fun Match.getScorePart2(): Int { var score = 0 when (desiredResult) { Result.WIN -> score += 6 Result.DRAW -> score += 3 Result.LOSS -> {} } when { enemyChoice == Option.ROCK && desiredResult == Result.WIN -> score += 2 // Paper enemyChoice == Option.PAPER && desiredResult == Result.WIN -> score += 3 // Scissor enemyChoice == Option.SCISSOR && desiredResult == Result.WIN -> score += 1 // Rock enemyChoice == Option.ROCK && desiredResult == Result.DRAW -> score += 1 // Rock enemyChoice == Option.PAPER && desiredResult == Result.DRAW -> score += 2 // Paper enemyChoice == Option.SCISSOR && desiredResult == Result.DRAW -> score += 3 // Scissor enemyChoice == Option.ROCK && desiredResult == Result.LOSS -> score += 3 // Scissor enemyChoice == Option.PAPER && desiredResult == Result.LOSS -> score += 1 // Rock enemyChoice == Option.SCISSOR && desiredResult == Result.LOSS -> score += 2 // Paper } return score } fun part1(): Int { return input().sumOf { it.getScorePart1() } } fun part2(): Int { return input().sumOf { it.getScorePart2() } }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
2,963
AdventOfCode
MIT License
src/main/kotlin/day13.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
class Day13 : Solvable("13") { override fun solveA(input: List<String>): String { val (positions, foldInstrs) = getGridFolds(input) return doFold(positions.toSet(), foldInstrs.first()).size.toString() } override fun solveB(input: List<String>): String { val (positions, foldInstrs) = getGridFolds(input) var folded = positions.toSet() foldInstrs.forEach { folded = doFold(folded, it) } var maxX = (folded.map { it.first }.max() ?:0) + 1 var maxY = (folded.map { it.second }.max() ?:0) + 1 val grid = Array<Array<Char>>(maxY) { Array<Char>(maxX) { ' ' } } folded.forEach { grid[it.second][it.first] = '#' } return grid.joinToString(separator = "\n") { it.joinToString(separator = "") } } private fun doFold( positions: Set<Pair<Int, Int>>, fold: Pair<Boolean, Int> ): Set<Pair<Int, Int>> { return positions .map { val (x, y) = it if (fold.first && x > fold.second) { Pair(fold.second - (x - fold.second), y) } else if (!fold.first && y > fold.second) Pair(x, fold.second - (y - fold.second)) else it } .toSet() } private fun getGridFolds( input: List<String> ): Pair<List<Pair<Int, Int>>, List<Pair<Boolean, Int>>> { val emptyLineIndex = input.indexOf("") val positions = input.subList(0, emptyLineIndex).map { val (x, y) = it.split(",") Pair(x.toInt(), y.toInt()) } val foldInstrs = input.subList(emptyLineIndex + 1, input.size).map { val (text, pos) = it.split("=") Pair(text.last() == 'x', pos.toInt()) } return Pair(positions, foldInstrs) } }
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
1,981
AdventOfCode
Creative Commons Zero v1.0 Universal
advent-of-code-2022/src/Day03.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
fun main() { fun readInput(name: String) = readLines(name).asSequence() // Common function to solve both part one and two. // Time - O(N*M), Space - O(N*M) // where N - number of lines, M - number of chars in the lines fun Sequence<List<String>>.sumOfPriorities(): Int { // 1. Convert strings in group to Sets of chars and find intersection of these sets // 2. Calculate priorities and it's sum return map { it.map(String::toSet).reduce(Set<Char>::intersect).single() } .sumOf { if (it in 'a'..'z') it - 'a' + 1 else it - 'A' + 27 } } fun part1(input: Sequence<String>): Int = input.map { it.chunked(it.length / 2) }.sumOfPriorities() fun part2(input: Sequence<String>): Int = input.chunked(3).sumOfPriorities() val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
981
advent-of-code
Apache License 2.0
src/Day04.kt
OskarWalczak
573,349,185
false
{"Kotlin": 22486}
fun main() { fun getRanges(line: String): Pair<IntRange, IntRange>{ val nums = line.split(',', '-').map { Integer.parseInt(it) } return Pair((nums[0]..nums[1]), (nums[2]..nums[3])) } fun part1(input: List<String>): Int { var containCount: Int = 0 input.forEach { val elfRanges = getRanges(it) val bigger = if (elfRanges.first.count() >= elfRanges.second.count()) elfRanges.first else elfRanges.second val smaller = if (bigger == elfRanges.first) elfRanges.second else elfRanges.first for(i in smaller){ if(!bigger.contains(i)){ break } if(i == smaller.last) containCount++ } } return containCount } fun part2(input: List<String>): Int { var overlapCount: Int = 0 input.forEach { val elfRanges = getRanges(it) for(i in elfRanges.first){ if(elfRanges.second.contains(i)){ overlapCount++ break } } } return overlapCount } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d34138860184b616771159984eb741dc37461705
1,427
AoC2022
Apache License 2.0
src/main/kotlin/io/github/aarjavp/aoc/day14/Day14.kt
AarjavP
433,672,017
false
{"Kotlin": 73104}
package io.github.aarjavp.aoc.day14 import io.github.aarjavp.aoc.readFromClasspath class Day14 { data class Rule(val matchId: String, val addChar: Char) { init { check(matchId.length == 2) } val leftPair = "${matchId[0]}$addChar" val rightPair = "$addChar${matchId[1]}" } class State(startingPolymer: String, val rules: List<Rule>) { val characterCounts = mutableMapOf<Char, Long>() val pairCounts = mutableMapOf<String, Long>() init { for (c in startingPolymer) { characterCounts.merge(c, 1, Long::plus) } for (pair in startingPolymer.zipWithNext { a, b -> "$a$b" }) { pairCounts.merge(pair, 1, Long::plus) } } fun applyRules() { val newPairs = mutableMapOf<String, Long>() val toRemove = mutableSetOf<String>() for (rule in rules) { val count = pairCounts[rule.matchId] ?: continue toRemove += rule.matchId characterCounts.merge(rule.addChar, count, Long::plus) newPairs.merge(rule.leftPair, count, Long::plus) newPairs.merge(rule.rightPair, count, Long::plus) } for (pair in toRemove) { pairCounts.remove(pair) } for (newPair in newPairs) { pairCounts.merge(newPair.key, newPair.value, Long::plus) } } } fun parseState(input: Sequence<String>): State { val iterator = input.iterator() val startingPolymer = iterator.next() check(iterator.next().isBlank()) val rules = mutableListOf<Rule>() while (iterator.hasNext()) { val rawRule = iterator.next() val (matchId, addCharStr) = rawRule.split(" -> ") rules += Rule(matchId, addCharStr[0]) } return State(startingPolymer, rules) } fun part1(input: Sequence<String>): Long { val state = parseState(input) repeat(10) { state.applyRules() } val entries = state.characterCounts.entries return entries.maxOf { it.value } - entries.minOf { it.value } } fun part2(input: Sequence<String>): Long { val state = parseState(input) repeat(40) { state.applyRules() } val entries = state.characterCounts.entries return entries.maxOf { it.value } - entries.minOf { it.value } } } fun main() { val solution = Day14() val part1: Long = readFromClasspath("Day14.txt").useLines { input -> solution.part1(input) } println(part1) val part2: Long = readFromClasspath("Day14.txt").useLines { input -> solution.part2(input) } println(part2) }
0
Kotlin
0
0
3f5908fa4991f9b21bb7e3428a359b218fad2a35
2,802
advent-of-code-2021
MIT License
src/day04/day04.kt
LostMekka
574,697,945
false
{"Kotlin": 92218}
package day04 import util.readInput import util.shouldBe fun main() { val day = 4 val testInput = readInput(day, testInput = true).parseInput() part1(testInput) shouldBe 2 part2(testInput) shouldBe 4 val input = readInput(day).parseInput() println("output for part1: ${part1(input)}") println("output for part2: ${part2(input)}") } private class Input( val pairs: List<Pair<IntRange, IntRange>>, ) private val inputRegex = Regex("""^(\d+)-(\d+),(\d+)-(\d+)$""") private fun List<String>.parseInput(): Input { return Input( map { line -> val (a, b, c, d) = inputRegex .matchEntire(line)!! .groupValues .drop(1) .map { it.toInt() } a..b to c..d } ) } private operator fun IntRange.contains(other: IntRange) = other.first in this && other.last in this private infix fun IntRange.overlapsWith(other: IntRange) = first in other || last in other || other in this private fun part1(input: Input): Int { return input.pairs.count { (a, b) -> a in b || b in a } } private fun part2(input: Input): Int { return input.pairs.count { (a, b) -> a overlapsWith b } }
0
Kotlin
0
0
58d92387825cf6b3d6b7567a9e6578684963b578
1,211
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2020/Day19.kt
tginsberg
315,060,137
false
null
/* * Copyright (c) 2020 by <NAME> */ /** * Advent of Code 2020, Day 19 - Monster Messages * Problem Description: http://adventofcode.com/2020/day/19 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day19/ */ package com.ginsberg.advent2020 class Day19(input: List<String>) { private val rules: MutableMap<Int, List<List<Rule>>> = parseRules(input) private val messages: List<String> = input.dropWhile { it.isNotBlank() }.drop(1) fun solvePart1(): Int = countRuleMatches() fun solvePart2(): Int { rules[8] = listOf( listOf(RuleReference(42)), listOf(RuleReference(42), RuleReference(8)) ) rules[11] = listOf( listOf(RuleReference(42), RuleReference(31)), listOf(RuleReference(42), RuleReference(11), RuleReference(31)) ) return countRuleMatches() } private fun countRuleMatches(): Int = messages.count { message -> message.ruleMatch(0).any { it == message.length } } private fun parseRules(input: List<String>): MutableMap<Int, List<List<Rule>>> = input.takeWhile{ it.isNotBlank() }.map { line -> val (id, rhs) = line.split(": ") val sides = rhs.split(" | ") id.toInt() to sides.map { side -> side.split(' ').map { part -> if (part.startsWith('"')) Atom(part[1]) else RuleReference(part.toInt()) } } }.toMap().toMutableMap() private fun String.ruleMatch(ruleId: Int, position: Int = 0): List<Int> = rules.getValue(ruleId).flatMap { listOfRules -> // OR Rule var positions = listOf(position) listOfRules.forEach { rule -> // AND Rule positions = positions.mapNotNull { idx -> when { rule is Atom && getOrNull(idx) == rule.symbol -> listOf(idx + 1) // End condition rule is RuleReference -> ruleMatch(rule.id, idx) else -> null } }.flatten() } positions } interface Rule class Atom(val symbol: Char) : Rule class RuleReference(val id: Int) : Rule }
0
Kotlin
2
38
75766e961f3c18c5e392b4c32bc9a935c3e6862b
2,384
advent-2020-kotlin
Apache License 2.0
src/Day05.kt
proggler23
573,129,757
false
{"Kotlin": 27990}
import java.util.* fun main() { fun part1(input: List<String>): String { val cargo = input.parse5() cargo.performOperations() return cargo.cratesOnTop.joinToString("") } fun part2(input: List<String>): String { val cargo = input.parse5() cargo.performOperations(true) return cargo.cratesOnTop.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } fun List<String>.parse5(): Cargo { val separator = indexOf("") val stacks = this[separator - 1].chunked(4).map { Stack<Char>() } take(separator - 1).reversed().forEach { line -> line.chunked(4).map { it.trim() }.forEachIndexed { index, slot -> slot.getOrNull(1)?.let { stacks[index].push(it) } } } val operations = drop(separator + 1).mapNotNull { line -> operationRegex.find(line)?.let { Operation(it.groupValues[1].toInt(), it.groupValues[2].toInt() - 1, it.groupValues[3].toInt() - 1) } } return Cargo(stacks, operations) } data class Cargo(val stacks: List<Stack<Char>>, val operations: List<Operation>) { val cratesOnTop: List<Char> get() = stacks.mapNotNull { it.peek() } fun performOperations(part2: Boolean = false) = operations.forEach { it.perform(stacks, part2) } } data class Operation(val amount: Int, val from: Int, val to: Int) { fun perform(stacks: List<Stack<Char>>, part2: Boolean = false) { val crates = buildList { repeat(amount) { add(stacks[from].pop()) } if (part2) reverse() } crates.forEach { stacks[to].push(it) } } } val operationRegex = Regex("move (\\d+) from (\\d+) to (\\d+)")
0
Kotlin
0
0
584fa4d73f8589bc17ef56c8e1864d64a23483c8
1,919
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2018/Day06.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 6 - Chronal Coordinates * * Problem Description: http://adventofcode.com/2018/day/6 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day6/ */ package com.ginsberg.advent2018 class Day06(input: List<String>) { private val points: List<Point> = input.map { Point.of(it) } private val xRange: IntRange = (points.minBy { it.x }!!.x..points.maxBy { it.x }!!.x) private val yRange: IntRange = (points.minBy { it.y }!!.y..points.maxBy { it.y }!!.y) fun solvePart1(): Int { val infinite: MutableSet<Point> = mutableSetOf() return xRange.asSequence().flatMap { x -> yRange.asSequence().map { y -> val closest = points.map { it to it.distanceTo(x, y) }.sortedBy { it.second }.take(2) if (isEdge(x, y)) { infinite.add(closest[0].first) } closest[0].first.takeUnless { closest[0].second == closest[1].second } } } .filterNot { it in infinite } .groupingBy { it } .eachCount() .maxBy { it.value }!! .value } fun solvePart2(range: Int = 10_000): Int = xRange.asSequence().flatMap { x -> yRange.asSequence().map { y -> points.map { it.distanceTo(x, y) }.sum() } } .filter { it < range } .count() private fun isEdge(x: Int, y: Int): Boolean = x == xRange.first || x == xRange.last || y == yRange.first || y == yRange.last }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
1,631
advent-2018-kotlin
MIT License
src/Day04.kt
manuel-martos
574,260,226
false
{"Kotlin": 7235}
fun main() { println("part01 -> ${solveDay04Part01()}") println("part02 -> ${solveDay04Part02()}") } private fun solveDay04Part01() = solver { range1, range2 -> if ((range1.contains(range2.first) && range1.contains(range2.last)) || (range2.contains(range1.first) && range2.contains(range1.last)) ) { 1 } else { 0 } } private fun solveDay04Part02() = solver { range1, range2 -> if (range1.contains(range2.first) || range1.contains(range2.last) || range2.contains(range1.first) || range2.contains(range1.last) ) { 1 } else { 0 } } private fun solver(reducer: (IntRange, IntRange) -> Int) = readInput("day04") .map { it.split(",", "-") } .sumOf { val range1 = it[0].toInt()..it[1].toInt() val range2 = it[2].toInt()..it[3].toInt() reducer(range1, range2) }
0
Kotlin
0
0
5836682fe0cd88b4feb9091d416af183f7f70317
1,005
advent-of-code-2022
Apache License 2.0
src/Day03.kt
cvb941
572,639,732
false
{"Kotlin": 24794}
fun main() { fun Char.score(): Int { return when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("Invalid character: $this") } } fun part1(input: List<String>): Int { return input.map { case -> // Split list into two halves val first = case.take(case.length / 2) val second = case.drop(case.length / 2) val inBoth = first.toSet().intersect(second.toSet()).first() inBoth.score() }.sum() } fun part2(input: List<String>): Int { return input.map { it.toSet() }.chunked(3).map { it[0].intersect(it[1].intersect(it[2])).first().score() }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
fe145b3104535e8ce05d08f044cb2c54c8b17136
1,041
aoc-2022-in-kotlin
Apache License 2.0
src/Day04.kt
purdyk
572,817,231
false
{"Kotlin": 19066}
fun main() { fun IntRange.contains(other: IntRange): Boolean { return other.first >= this.first && other.last <= this.last } fun IntRange.touches(other: IntRange): Boolean { return this.first <= other.first && this.last >= other.first } fun part1(input: List<String>): String { val rangePairs = input.map { it.split(",").map { it.split("-").let { it[0].toInt()..it[1].toInt() } } } val contained = rangePairs.filter { it[0].contains(it[1]) || it[1].contains(it[0]) } return contained.size.toString() } fun part2(input: List<String>): String { val rangePairs = input.map { it.split(",").map { it.split("-").let { it[0].toInt()..it[1].toInt() } } } val contained = rangePairs.filter { it[0].touches(it[1]) || it[1].touches(it[0]) } return contained.size.toString() } val day = "04" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test").split("\n") check(part1(testInput) == "2") check(part2(testInput) == "4") println("Test: ") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day${day}").split("\n") println("\nProblem: ") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
02ac9118326b1deec7dcfbcc59db8c268d9df096
1,351
aoc2022
Apache License 2.0
src/day02/Day02.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day02 import readInput fun main() { val scoreMapPart1 = mapOf<Pair<String, String>, Int>( Pair("A", "X") to 4, Pair("A", "Y") to 8, Pair("A", "Z") to 3, Pair("B", "X") to 1, Pair("B", "Y") to 5, Pair("B", "Z") to 9, Pair("C", "X") to 7, Pair("C", "Y") to 2, Pair("C", "Z") to 6, ) val scoreMapPart2 = mapOf<Pair<String, String>, Int>( Pair("A", "Y") to 4, Pair("A", "Z") to 8, Pair("A", "X") to 3, Pair("B", "X") to 1, Pair("B", "Y") to 5, Pair("B", "Z") to 9, Pair("C", "Z") to 7, Pair("C", "X") to 2, Pair("C", "Y") to 6, ) fun part1(input: List<Pair<String, String>>): Int = input.sumOf { scoreMapPart1[it]!! } fun part2(input: List<Pair<String, String>>): Int = input.sumOf { scoreMapPart2[it]!! } fun preprocess(input: List<String>): List<Pair<String, String>> = input.map { val split = it.split(" ") Pair(split[0], split[1]) } // test if implementation meets criteria from the description, like: val testInput = readInput(2, true) check(part1(preprocess(testInput)) == 15) val input = readInput(2) println(part1(preprocess(input))) check(part2(preprocess(testInput)) == 12) println(part2(preprocess(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
1,358
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day14_extended_polymerization/ExtendedPolymerization.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day14_extended_polymerization import histogram.Histogram import histogram.count import histogram.histogramOf import histogram.mutableHistogramOf import util.extent import util.length /** * Chopping up strings and reassembling them is easy! A little parsing, a loop, * and done! Hopefully part two isn't like Lanternfish (#6)... * * It's like Lanternfish. But here we need a character-based result, while the * growth rules are based on pairs, so can't just keep track of char counts. * Every char except the first and last is part of two pairs, however. So * tracking pairs - plus the first/last wrinkle - should give us double the * answer we want. Dividing by two is easy; done! */ fun main() { util.solve(2891, ::partOne) // 975.249μs initially // 188.474μs w/ part two util.solve(4607749009683, ::partTwo) } fun partOne(input: String) = solve(input, 10) internal fun solve(input: String, steps: Int): Long { val lines = input.lines() val template = lines.first() val rules = lines.drop(2) .map { it.split(" -> ") } .associate { rule -> rule.first() .let { it to listOf(it[0] + rule.last(), rule.last() + it[1]) } } val initial = histogramOf(template .zipWithNext { a, b -> "$a$b" }) val pairHist = (1..steps).fold(initial) { hist, step -> mutableHistogramOf<String>().apply { for ((k, v) in hist) { rules[k]!!.forEach { count(it, v) } } } } val charHist: Histogram<Char> = mutableHistogramOf<Char>().apply { count(template.first()) count(template.last()) for ((p, n) in pairHist) { count(p[0], n) count(p[1], n) } } val extent = charHist.values.extent() if (extent.length % 2L == 1L) throw IllegalStateException("got an odd number?") return extent.length / 2 } fun partTwo(input: String) = solve(input, 40)
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
2,011
aoc-2021
MIT License
aoc-2023/src/main/kotlin/aoc/aoc5.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.getDayInput val testInput = """ seeds: 79 14 55 13 seed-to-soil map: 50 98 2 52 50 48 soil-to-fertilizer map: 0 15 37 37 52 2 39 0 15 fertilizer-to-water map: 49 53 8 0 11 42 42 0 7 57 7 4 water-to-light map: 88 18 7 18 25 70 light-to-temperature map: 45 77 23 81 45 19 68 64 13 temperature-to-humidity map: 0 69 1 1 0 69 humidity-to-location map: 60 56 37 56 93 4 """.parselines val List<Long>.destStart get() = this[0] val List<Long>.sourceStart get() = this[1] val List<Long>.destRange get() = LongRange(this[0], this[0]+this[2]-1) val List<Long>.sourceRange get() = LongRange(this[1], this[1]+this[2]-1) fun intersect(r1: LongRange, r2: LongRange) = if (r1.last < r2.first || r2.last < r1.first) null else LongRange(maxOf(r1.first, r2.first), minOf(r1.last, r2.last)) /** Remove intersection of target from all provided ranges. */ fun List<LongRange>.remove(o: LongRange) = flatMap { val intersection = intersect(it, o) if (intersection == null) listOf(it) else { val r1 = LongRange(it.first, intersection.first-1) val r2 = LongRange(intersection.last+1, it.last) listOfNotNull(r1, r2).filter { !it.isEmpty() } } } class SeedData( val seeds: List<Long>, val seedRanges: List<LongRange>, val s2s: List<List<Long>>, val s2f: List<List<Long>>, val f2w: List<List<Long>>, val w2l: List<List<Long>>, val l2t: List<List<Long>>, val t2h: List<List<Long>>, val h2loc: List<List<Long>> ) { val seedsByRange get() = seedRanges.flatMap { it.toList() } /** Determine the mapping of the seed for the given list. */ fun map(value: Long, map: List<List<Long>>): Long { val inRange = map.firstOrNull { value in it.sourceRange } return if (inRange == null) value else value + inRange.destStart - inRange.sourceStart } /** Determine the mapping of the seed range for the given list. */ fun map(range: LongRange, map: List<List<Long>>): List<LongRange> { var unmapped = listOf(range) val mapped = map.flatMap { val rSource = it.sourceRange val delta = it.destStart - it.sourceStart val intersection = intersect(range, rSource) if (intersection == null) listOf() else { val r = LongRange(maxOf(range.first, rSource.first) + delta, minOf(range.last, rSource.last) + delta) unmapped = unmapped.remove(LongRange(r.first - delta, r.last - delta)) listOf(r) } } return mapped + unmapped } } class Seed(val id: Long, val soil: Long, val fertilizer: Long, val water: Long, val light: Long, val temperature: Long, val humidity: Long, val loc: Long) fun String.parse(): SeedData { val groups = split("\n\n".toRegex()) val seeds = groups[0].substringAfter(" ").longs(" ") return SeedData( seeds, seeds.chunked(2).map { LongRange(it[0], it[0]+it[1]-1) }, groups[1].substringAfter(":\n").lines().map { it.longs(" ") }, groups[2].substringAfter(":\n").lines().map { it.longs(" ") }, groups[3].substringAfter(":\n").lines().map { it.longs(" ") }, groups[4].substringAfter(":\n").lines().map { it.longs(" ") }, groups[5].substringAfter(":\n").lines().map { it.longs(" ") }, groups[6].substringAfter(":\n").lines().map { it.longs(" ") }, groups[7].substringAfter(":\n").lines().map { it.longs(" ") } ) } // part 1 fun List<String>.part1(): Long { val data = joinToString("\n").parse() val seeds = data.seeds.map { with (data) { val soil = map(it, s2s) val fertilizer = map(soil, s2f) val water = map(fertilizer, f2w) val light = map(water, w2l) val temperature = map(light, l2t) val humidity = map(temperature, t2h) val loc = map(humidity, h2loc) Seed(it, soil, fertilizer, water, light, temperature, humidity, loc) } } return seeds.minOf { it.loc } } // part 2 fun List<String>.part2(): Long { val data = joinToString("\n").parse() val soil = data.seedRanges.flatMap { data.map(it, data.s2s) } val fertilizer = soil.flatMap { data.map(it, data.s2f) } val water = fertilizer.flatMap { data.map(it, data.f2w) } val light = water.flatMap { data.map(it, data.w2l) } val temperature = light.flatMap { data.map(it, data.l2t) } val humidity = temperature.flatMap { data.map(it, data.t2h) } val loc = humidity.flatMap { data.map(it, data.h2loc) } return loc.minOf { it.first } } // calculate answers val day = 5 val input = getDayInput(day, 2023) val testResult = testInput.part1() val testResult2 = testInput.part2() val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
5,125
advent-of-code
Apache License 2.0
src/main/kotlin/day16.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package day16 import aoc.utils.findInts import aoc.utils.graphs.Node import aoc.utils.graphs.allNodes import aoc.utils.readInput import aoc.utils.splitOn import kotlin.math.max data class Valve(val name: String, val flow: Int) fun part1(): Int { val start = buildMap() val result = venture(allNodes(start), 30, start, start, listOf(), 0, mutableMapOf()) // 198802956 // 9980871 println(iterations) return result } fun main() { } var iterations = 0L fun venture( allValves: Set<Node<Valve>>, timeLeft: Int, yourLocation: Node<Valve>, yourPrevious: Node<Valve>, valvesOpened: List<Node<Valve>>, pressureReleased: Int, highScore: MutableMap<Int, Int>, elephantLocation: Node<Valve>? = null, elephantPrevious: Node<Valve>? = null, ): Int { iterations++ val maximumAchievable = maxPossible(allValves, timeLeft, pressureReleased, valvesOpened, true) if (maximumAchievable < highScore[timeLeft] ?: -1) { return 0 } val accumPressure = pressureReleased + pressureChange(valvesOpened) if(highScore[timeLeft] ?: -1 < accumPressure) { highScore[timeLeft] = accumPressure } val timeRemaining = timeLeft - 1 if (timeRemaining == 0) return accumPressure // Never go back to where we just came from (if we opened current == from) val connections = yourLocation.edges.map { it.target }.filter { it != yourPrevious } // Can't move anywhere and current was already opened, we can just stand still? if (connections.isEmpty() && valvesOpened.contains(yourLocation)) { return venture(allValves, timeRemaining, yourLocation, yourPrevious, valvesOpened, accumPressure, highScore) } if (connections.isEmpty() && !valvesOpened.contains(yourLocation) && yourLocation.value.flow != 0) return venture(allValves, timeRemaining, yourLocation, yourLocation, valvesOpened.plus(yourLocation), accumPressure, highScore) val moveScore = connections.map { venture(allValves, timeRemaining, it, yourLocation, valvesOpened, accumPressure, highScore) }.maxOf { it } if (!valvesOpened.contains(yourLocation) && yourLocation.value.flow != 0) { return max( moveScore, venture(allValves, timeRemaining, yourLocation, yourLocation, valvesOpened.plus(yourLocation), accumPressure, highScore) ) } return moveScore } // What is the maximum pressure relased if miraculously all valves would open without moving fun maxPossible( allValves: Set<Node<Valve>>, timeLeft: Int, pressureReleased: Int, valvesOpened: List<Node<Valve>>, withElephant: Boolean ): Int { val valvesToOpen = allValves .minus(valvesOpened) .sortedByDescending { it.value.flow } .toMutableList() var max = pressureReleased var pressureChange = pressureChange(valvesOpened) var time = timeLeft while (time > 0) { max += pressureChange repeat(if(withElephant) 2 else 1) { valvesToOpen.removeFirstOrNull()?.let { pressureChange += it.value.flow }} time-- } return max } fun pressureChange(valvesOpened: List<Node<Valve>>): Int { return valvesOpened.sumOf { it.value.flow } } fun part2(): Int { return 1; } private fun buildMap(): Node<Valve> { val input = "test.txt" // Create valves val valves = readInput(input) .map { it.split(" ").let { it[1] to it[4].findInts()[0] } } .map { Node(Valve(it.first, it.second)) } // Link valves readInput(input) .map { it.replace("valve ", "valves ") } .map { it.split(" ").let { val connected = it.splitOn { it == "valves" }[1].map { it.replace(",", "") } it[1] to connected } } .forEach { connection -> val valve = valves.firstOrNull { it.value.name == connection.first }!! connection.second.forEach { target -> if (valves.firstOrNull { it.value.name == target } == null) println() val targetValve = valves.firstOrNull { it.value.name == target }!! valve.biLink(1, targetValve) } } val start = valves.firstOrNull { it.value.name == "AA" }!! return start }
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
4,357
adventOfCode2022
Apache License 2.0
2022/18/18.kt
LiquidFun
435,683,748
false
{"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191}
data class Point(var x: Int, var y: Int, var z: Int) { operator fun plus(o: Point): Point = Point(x+o.x, y+o.y, z+o.z) fun adjacent(): List<Point> = dirs.map { this+it }.toList() fun min(): Int = minOf(x, y, z) fun max(): Int = maxOf(x, y, z) } val dirs = listOf( Point(1, 0, 0), Point(0, 1, 0), Point(0, 0, 1), Point(-1, 0, 0), Point(0, -1, 0), Point(0, 0, -1), ) fun main() { val input = generateSequence(::readlnOrNull) .map { it.split(",").map { it.toInt() } } .map { (x, y, z) -> Point(x, y, z) }.toList() val bounds = input.minOf { it.min()-1 }..input.maxOf { it.max()+1 } // Part 1 input.sumOf { it.adjacent().count { !input.contains(it) } }.run(::println) // Part 2 val queue = mutableListOf(Point(bounds.first, bounds.first, bounds.first)) val visited: MutableSet<Point> = mutableSetOf() var count = 0 while (queue.isNotEmpty()) { val point = queue.removeAt(0) if (point in visited) continue visited.add(point) for (adj in point.adjacent()) { if (adj in input) count++ else if (adj.x in bounds && adj.y in bounds && adj.z in bounds) queue.add(adj) } } println(count) }
0
Kotlin
7
43
7cd5a97d142780b8b33b93ef2bc0d9e54536c99f
1,130
adventofcode
Apache License 2.0
src/main/kotlin/nl/tiemenschut/aoc/y2023/day8.kt
tschut
723,391,380
false
{"Kotlin": 61206}
package nl.tiemenschut.aoc.y2023 import nl.tiemenschut.aoc.lib.dsl.aoc import nl.tiemenschut.aoc.lib.dsl.day import nl.tiemenschut.aoc.lib.dsl.parser.InputParser import nl.tiemenschut.aoc.lib.util.infiniterator data class Node(val id: String) { var left: Node? = null var right: Node? = null } data class DesertMap( val directions: String, val start: Node?, val end: Node?, val nodes: List<Node>, ) object MapParser : InputParser<DesertMap> { override fun parse(input: String): DesertMap { val nodeRegex = "(.{3}) = \\((.{3}), (.{3})\\)".toRegex() val (directions, nodesInput) = input.split("\n\n") val nodeMap = nodeRegex.findAll(nodesInput).associate { nodeInput: MatchResult -> val (_, root, left, right) = nodeInput.groupValues root to (left to right) } val nodes = nodeMap.map { Node(it.key) } nodes.forEach { node -> node.left = nodes.find { it.id == nodeMap[node.id]!!.first } node.right = nodes.find { it.id == nodeMap[node.id]!!.second } } return DesertMap( directions, nodes.find { it.id == "AAA" }, nodes.find { it.id == "ZZZ" }, nodes, ) } } fun main() { aoc(MapParser) { puzzle { 2023 day 8 } part1 { input -> var steps = 0 var current = input.start!! run loop@ { input.directions.toList().infiniterator().forEach { current = if (it == 'L') current.left!! else current.right!! steps ++ if (current === input.end) return@loop } } steps } part2(submit = true) { input -> val starts = input.nodes.filter { it.id.endsWith("A") } val progression: List<MutableList<Pair<Node, Int>>> = List(starts.size) { mutableListOf<Pair<Node, Int>>() } val loopStarts = mutableListOf<Int>() starts.forEachIndexed { iStart, start -> var index = 0 var current = start while (true) { val loopStart = progression[iStart].indexOf(current to index) if (loopStart != -1) { loopStarts.add(loopStart) break } progression[iStart].add(current to index) current = if (input.directions[index] == 'L') current.left!! else current.right!! if (++index == input.directions.length) index = 0 } } data class Loop( val offset: Long, val loop: Long, val indexOfEnd: Long, ) { fun isZ(index: Long) = ((index - offset) % loop) == indexOfEnd } val loops = progression.mapIndexed { i, p -> Loop( loopStarts[i].toLong(), (p.size - loopStarts[i]).toLong(), p.indexOfLast { n -> n.first.id.endsWith('Z') }.toLong() - loopStarts[i] ) } val smallestLoop = loops.minBy { it.loop } val firstZInSmallestLoop = (smallestLoop.offset .. smallestLoop.loop + smallestLoop.offset).first { smallestLoop.isZ(it) } var count = 0L var tiredCamel = firstZInSmallestLoop while (loops.any { !it.isZ(tiredCamel) }) { tiredCamel += smallestLoop.loop if (count++ % 1_000_000L == 0L) println("$tiredCamel million tiredCamels") } tiredCamel } } }
0
Kotlin
0
1
a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3
3,735
aoc-2023
The Unlicense
day5/day5_B.kts
jshap999
575,148,328
false
{"Kotlin": 19624, "Shell": 452, "Nim": 433, "JavaScript": 404}
#!/usr/bin/env kotlin import java.io.File data class Move(val count: Int, val fromIndex: Int, val toIndex: Int) if (args.size != 1) { println("Please provide the file containing the puzzle input.") } else { runCatching { val puzzleInput = readFile(args.first()) .splitInput() val boardInput = puzzleInput.first .normalizeSpaces() .splitRowsIntoColumns() val board = setupBoard(boardInput) val moves = puzzleInput.second .toMoves() moves.forEach { move -> val movingValues = (0 until move.count).map { board[move.fromIndex].removeFirst() } board[move.toIndex].addAll(0,movingValues) } val message = board.map { it.first()}.joinToString("") println(message) }.getOrElse { println("Something went wrong.") println("${it.stackTraceToString()}") } } fun readFile(fileName: String): List<String> { val file = File(fileName) return file.readLines() .map { if (it.isNullOrBlank()) null else it } .filterNotNull() } fun List<String>.splitInput(): Pair<List<String>, List<String>> { return this.fold(Pair(listOf(), listOf())) { end, item -> when { "^[ 0-9]+$".toRegex().matches(item) -> end "^move .*".toRegex().matches(item) -> Pair(end.first, end.second.plus(item)) else -> Pair(end.first.plus(item), end.second) } } } fun List<String>.normalizeSpaces(): List<String> { return this.map { it.replace(" ".toRegex(), " [_] ") .trim() .replace(" +".toRegex(), " ") .replace("\\[|\\]".toRegex(), "") } } fun List<String>.splitRowsIntoColumns(): List<List<String>> { return this.map { it.split(" ") } } fun setupBoard(input: List<List<String>>): List<MutableList<String>> { val longestRow = input.fold(0) { longest, row -> if (row.size > longest) row.size else longest } val board = List<MutableList<String>>(longestRow) { mutableListOf() } input.forEach { row -> row.forEachIndexed { col, item -> if (item != "_") board[col].add(item) } } return board } fun List<String>.toMoves(): List<Move> { val regex = "move ([0-9]+) from ([0-9]+) to ([0-9]+)".toRegex() return this.map { val (_, count, from, to) = regex.matchEntire(it)?.groupValues ?: listOf(0, 0, 0, 0) Move("$count".toInt(), "$from".toInt() - 1, "$to".toInt() - 1) } }
0
Kotlin
0
0
1295c6dc1776b5e61bc774cd0d0649b0e31732f1
2,551
aoc2022
MIT License
src/Day06.kt
mlidal
572,869,919
false
{"Kotlin": 20582}
sealed class Entry(val name: String) { override fun toString(): String { return name } } class File(name: String, val size: Int) : Entry(name) { } class Directory(name: String, val parent: Directory? = null, val children: MutableList<Entry> = mutableListOf()) : Entry(name) { override fun toString(): String { return name } fun getSize() : Int { var size = 0 children.forEach { child -> size += when(child) { is File -> child.size is Directory -> child.getSize() } } return size } } fun main() { fun part1(input: List<String>): Int { val rootDirectory = Directory("/") var currentDirectory = rootDirectory val directories = mutableListOf(rootDirectory) input.forEach { line -> if (line.startsWith("$")) { val parts = line.split(" ") if (parts[1] == "cd") { currentDirectory = if (parts[2] == "/") { rootDirectory } else if (parts[2] == "..") { currentDirectory.parent!! } else { currentDirectory.children.first { it is Directory && it.name == parts[2] } as Directory } } } else { val parts = line.split(" ") if (parts[0] == "dir") { val directory = Directory(parts[1], currentDirectory) directories.add(directory) currentDirectory.children.add(directory) } else { val file = File(parts[1], parts[0].toInt()) currentDirectory.children.add(file) } } } var sum = 0 directories.forEach { directory -> val size = directory.getSize() if (size <= 100000) { sum += size } } return sum } fun part2(input: List<String>): Int { val rootDirectory = Directory("/") var currentDirectory = rootDirectory val directories = mutableListOf(rootDirectory) input.forEach { line -> if (line.startsWith("$")) { val parts = line.split(" ") if (parts[1] == "cd") { currentDirectory = if (parts[2] == "/") { rootDirectory } else if (parts[2] == "..") { currentDirectory.parent!! } else { currentDirectory.children.first { it is Directory && it.name == parts[2] } as Directory } } } else { val parts = line.split(" ") if (parts[0] == "dir") { val directory = Directory(parts[1], currentDirectory) directories.add(directory) currentDirectory.children.add(directory) } else { val file = File(parts[1], parts[0].toInt()) currentDirectory.children.add(file) } } } val diskSize = 70000000 val missingSpace = 30000000 - (diskSize - rootDirectory.getSize()) var smallestDirectory = rootDirectory var smallestSize = rootDirectory.getSize() directories.forEach { directory -> val size = directory.getSize() if (size >= missingSpace && size < smallestSize) { smallestDirectory = directory smallestSize = size } } return smallestSize } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bea7801ed5398dcf86a82b633a011397a154a53d
4,054
AdventOfCode2022
Apache License 2.0
src/main/kotlin/adventofcode2022/solution/day_8.kt
dangerground
579,293,233
false
{"Kotlin": 51472}
package adventofcode2022.solution import adventofcode2022.util.readDay import kotlin.math.max fun main() { Day8("8").solve() } class Day8(private val num: String) { private val inputText = readDay(num) fun solve() { println("Day $num Solution") println("* Part 1: ${solution1()}") println("* Part 2: ${solution2()}") } fun solution1(): Long { val forest = inputText.lines().mapIndexed { y, line -> y to line.toCharArray().mapIndexed { x, tree -> x to Pair(tree.digitToInt(), false) }.toMap().toMutableMap() }.toMap().toMutableMap() val width = forest.size val height = forest[0]?.size ?: 0 println("Dimension: $width X $height") // check by line IntRange(0, width - 1).forEach { x -> val column = IntRange(0, height) updateRow(x, column, forest) updateRow(x, column.reversed(), forest) } // check by coliumn IntRange(0, height - 1).forEach { y -> val column = IntRange(0, width) updateColumn(y, column, forest) updateColumn(y, column.reversed(), forest) } // debug var visible = 0 IntRange(0, width - 1).forEach { x -> IntRange(0, height).forEach { y -> if ((forest[x]?.get(y)?.second == true)) { //print("x") visible++ //} else { // print(".") } } //println() } return visible.toLong() } private fun updateRow( row: Int, range: IntProgression, forest: Forest<Boolean> ) { var lastHeight = -1 range.forEach { x -> val height = forest[row]?.get(x)?.first ?: 0 if (height > lastHeight) { forest[row]?.set(x, Pair(height, true)) lastHeight = height } } } private fun updateColumn( column: Int, range: IntProgression, forest: MutableMap<Int, MutableMap<Int, Pair<Int, Boolean>>> ) { var lastHeight = -1 range.forEach { y -> val tree = forest[y]?.get(column) val height = tree?.first if (height != null && height > lastHeight) { forest[y]?.set(column, Pair(height, true)) lastHeight = height } } } fun solution2(): Long { val forest = inputText.lines().mapIndexed { y, line -> y to line.toCharArray().mapIndexed { x, tree -> x to Pair(tree.digitToInt(), null as Int?) }.toMap().toMutableMap() }.toMap().toMutableMap() as Forest<Int> val width = forest.size val height = forest[0]?.size ?: 0 println("Dimension: $width X $height") val widthRange = IntRange(0, width - 1) val heightRange = IntRange(0, height - 1) // check trees heightRange.forEach { y -> widthRange.forEach { x -> val score = getScore(forest, x, y) forest[y]?.set(x, Pair(forest.height(x, y)!!, score)) } } // debug val bestScore = forest.maxOf { it.value .map { it.value.second } .maxOf { it } } println("---------") heightRange.forEach { y -> widthRange.forEach { x -> print("." + forest.height(x, y)) } println() } println("---------") return bestScore.toLong() } private fun getScore(forest: Forest<Int>, startX: Int, startY: Int): Int { val treeHeight = forest.height(startX, startY) ?: 0 var leftDistance = 1 val leftRange = IntRange(-2, startX - 1) for (x in leftRange.reversed()) { val current = forest.height(x, startY) if (current == null) { leftDistance = startX - x - 1 break } else if (current >= treeHeight) { leftDistance = startX - x break } } leftDistance = max(leftDistance, 1) var rightDistance = 1 val rightRange = IntRange(startX + 1, forest.size) for (x in rightRange) { val current = forest.height(x, startY) if (current == null) { rightDistance = x - startX - 1 break } else if (current >= treeHeight) { rightDistance = x - startX break } } rightDistance = max(rightDistance, 1) var topDistance = 1 val topRange = IntRange(-1, startY - 1) for (y in topRange.reversed()) { val current = forest.height(startX, y) if (current == null) { topDistance = startY - y - 1 break } else if (current >= treeHeight) { topDistance = startY - y break } } topDistance = max(topDistance, 1) var bottomDistance = 1 val bottomRange = IntRange(startY + 1, forest[0]!!.size) for (y in bottomRange) { val current = forest.height(startX, y) if (current == null) { bottomDistance = y - startY - 1 break } else if (current >= treeHeight) { bottomDistance = y - startY break } } bottomDistance = max(bottomDistance, 1) return leftDistance * rightDistance * topDistance * bottomDistance } } typealias Forest<T> = MutableMap<Int, MutableMap<Int, Pair<Int, T>>> fun Forest<Int>.height(x: Int, y: Int) = this[y]?.get(x)?.first fun Forest<Int>.score(x: Int, y: Int) = this[y]?.get(x)?.second
0
Kotlin
0
0
f1094ba3ead165adaadce6cffd5f3e78d6505724
5,960
adventofcode-2022
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions50.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import com.qiaoyuang.algorithm.round0.BinaryTreeNode fun test50() { printlnResult(testCase(), 8) } /** * Questions 50: Given a binary tree and a sum number, find the count of paths that equals the sum */ private infix fun BinaryTreeNode<Int>.findPathCount(sum: Int): Int { val count = intArrayOf(0) findPathCount(sum, listOf(), count) return count.first() } private fun BinaryTreeNode<Int>.findPathCount(sum: Int, preValues: List<Int>, count: IntArray) { when { value == sum -> { count[0]++ return } value > sum -> return } val nextPreValues = mutableListOf<Int>() preValues.forEach { val newValue = it + value when { newValue == sum -> count[0]++ newValue < sum -> nextPreValues.add(newValue) } } nextPreValues.add(value) left?.run { findPathCount(sum, nextPreValues, count) } right?.run { findPathCount(sum, nextPreValues, count) } } private fun printlnResult(root: BinaryTreeNode<Int>, sum: Int) = println("The count of paths that sum equals $sum is ${root findPathCount sum} in binary tree ${root.preOrderList()}(preorder)") private fun testCase(): BinaryTreeNode<Int> = BinaryTreeNode( value = 5, left = BinaryTreeNode( value = 2, left = BinaryTreeNode(value = 1), right = BinaryTreeNode(value = 6), ), right = BinaryTreeNode( value = 4, left = BinaryTreeNode(value = 3), right = BinaryTreeNode(value = 7), ) )
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,634
Algorithm
Apache License 2.0
src/Day02.kt
timmiller17
577,546,596
false
{"Kotlin": 44667}
import NeededResult.* import Play.PAPER import Play.ROCK import Play.SCISSORS import kotlin.IllegalStateException fun main() { fun part1(input: List<String>): Int { return input.map { it.split(' ') } .sumOf { it.score() } } fun part2(input: List<String>): Int { return input.map { it.split(' ') } .sumOf { it.scorePart2() } } // 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() } fun List<String>.scorePart2(): Int { val opponentPlay = when (this[0]) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS else -> throw IllegalStateException() } val neededResult = when (this[1]) { "X" -> LOSE "Y" -> DRAW "Z" -> WIN else -> throw IllegalStateException() } val yourPlay = when (opponentPlay) { ROCK -> when (neededResult) { LOSE -> SCISSORS DRAW -> ROCK WIN -> PAPER } PAPER -> when (neededResult) { LOSE -> ROCK DRAW -> PAPER WIN -> SCISSORS } SCISSORS -> when (neededResult) { LOSE -> PAPER DRAW -> SCISSORS WIN -> ROCK } } return yourPlay.score() + neededResult.score() } fun List<String>.score(): Int { val opponentPlay = this[0] val yourPlay = this[1] val resultScore = when (opponentPlay) { "A" -> when (yourPlay) { "X" -> 3 "Y" -> 6 "Z" -> 0 else -> throw IllegalStateException() } "B" -> when (yourPlay) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> throw IllegalStateException() } "C" -> when (yourPlay) { "X" -> 6 "Y" -> 0 "Z" -> 3 else -> throw IllegalStateException() } else -> throw IllegalStateException() } return yourPlay.score() + resultScore } fun String.score(): Int { return when (this) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } } enum class Play(val code: String) { ROCK("A"), PAPER("B"), SCISSORS("C"), } fun Play.score(): Int { return when (this) { ROCK -> 1 PAPER -> 2 SCISSORS -> 3 } } enum class NeededResult { LOSE, DRAW, WIN, } fun NeededResult.score(): Int { return when (this) { LOSE -> 0 DRAW -> 3 WIN -> 6 } }
0
Kotlin
0
0
b6d6b647c7bb0e6d9e5697c28d20e15bfa14406c
2,711
advent-of-code-2022
Apache License 2.0
src/Day04.kt
BenD10
572,786,132
false
{"Kotlin": 6791}
fun main() { fun part1(input: List<String>): Int { return input.map { it.split(",").map { it.split("-").let { (it.first().toInt()..it.last().toInt()) } }.let { ls -> if (ls.first().all { ls.last().contains(it) } || ls.last().all { ls.first().contains(it) }) { 1 } else { 0 } } }.sum() } fun part2(input: List<String>): Int { return input.map { it.split(",").map { it.split("-").let { (it.first().toInt()..it.last().toInt()) } }.let { ls -> if (ls.first().any { ls.last().contains(it) } || ls.last().any { ls.first().contains(it) }) { 1 } else { 0 } } }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) check(part2(testInput) == 4) println(part2(input)) }
0
Kotlin
0
0
e26cd35ef64fcedc4c6e40b97a63d7c1332bb61f
1,239
advent-of-code
Apache License 2.0
src/day13/day13.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day13 import day13.Package.Items import day13.Package.Value import readInput private fun parse(input: List<String>): List<Pair<Package, Package>> { val result = mutableListOf<Pair<Package, Package>>() var index = 0 while (index < input.size) { val first = parsePackage(input[index++]).second val second = parsePackage(input[index++]).second result.add(Pair(first, second)) index++ } return result } private fun parsePackage(input: String, startIndex: Int = 1): Pair<Int, Package> { val result = mutableListOf<Package>() var index = startIndex var numberIndex = startIndex while (index < input.length) { when (input[index++]) { '[' -> { val temp = parsePackage(input, index) index = temp.first numberIndex = index result.add(temp.second) } ']' -> { input.substring(numberIndex, index - 1) .takeIf { it.isNotBlank() }?.let { result.add(Value(it.toInt())) } return Pair(index, Items(result)) } ',' -> { input.substring(numberIndex, index - 1) .takeIf { it.isNotBlank() }?.let { result.add(Value(it.toInt())) } numberIndex = index } } } return Pair(index, Items(result)) } private fun verify(firstInput: Package, secondInput: Package): Int { if (firstInput == secondInput) return 0 var first = firstInput var second = secondInput if (firstInput is Value && secondInput is Value) { if (firstInput.value == secondInput.value) return 0 return if (firstInput.value < secondInput.value) 1 else -1 } else if (firstInput is Value) { first = Items(listOf(firstInput)) } else if (second is Value) { second = Items(listOf(secondInput)) } require(first is Items && second is Items) var index = 0 while (index < first.items.size.coerceAtLeast(second.items.size)) { if (index == first.items.size) return 1 if (index == second.items.size) return -1 val temp = verify(first.items[index], second.items[index]) if (temp != 0) return temp index++ } return 0 } private fun handle(input: List<String>): Int { val packages = parse(input) var result = 0 for ((index, item) in packages.withIndex()) { val temp = verify(item.first, item.second) if (temp >= 0) { result += index + 1 } } return result } private fun part1(input: List<String>): Int { return handle(input) } private fun part2(input: List<String>): Int { fun verify(first: Package, input: List<String>): Int { return input.mapNotNull { if (it.isBlank()) null else parsePackage(it).second } .map { verify(first, it) } .count { it == -1 } } val first = parsePackage("[[2]]").second val second = parsePackage("[[6]]").second return (verify(first, input) + 1) * (verify(second, input) + 2) } fun main() { val input = readInput("day13/input") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private sealed interface Package { data class Value(val value: Int) : Package data class Items(val items: List<Package>) : Package }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
3,474
aoc-2022
Apache License 2.0
src/main/kotlin/com/sk/todo-revise/1235. Maximum Profit in Job Scheduling.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.`todo-revise` import java.util.* class Solution1235 { // TLE fun jobScheduling( startTime: IntArray, endTime: IntArray, profit: IntArray ): Int { val jobs = Array(startTime.size) { IntArray(3) } for (i in startTime.indices) { jobs[i][0] = startTime[i] jobs[i][1] = endTime[i] jobs[i][2] = profit[i] } jobs.sortBy { it[0] } fun schedule(i: Int, curTime: Int, curProfit: Int): Int { var max = 0 for (k in i..startTime.lastIndex) { if (jobs[k][0] >= curTime) { max = maxOf(max, schedule(k + 1, jobs[k][1], jobs[k][2])) } } return curProfit + max } return schedule(0, 1, 0) } // TLE fun jobScheduling2( startTime: IntArray, endTime: IntArray, profit: IntArray ): Int { val jobs = Array(startTime.size) { IntArray(3) } for (i in startTime.indices) { jobs[i][0] = startTime[i] jobs[i][1] = endTime[i] jobs[i][2] = profit[i] } jobs.sortBy { it[0] } val dp = IntArray(startTime.size) { -1 } fun schedule(i: Int, curTime: Int, curProfit: Int): Int { if (i == startTime.size) return 0 if (dp[i] == -1) { var max = 0 for (k in i..startTime.lastIndex) { if (jobs[k][0] >= curTime) { max = maxOf(max, schedule(k + 1, jobs[k][1], jobs[k][2])) } } dp[i] = curProfit + max } return dp[i] } return schedule(0, 1, 0) } // MLE fun jobScheduling3( startTime: IntArray, endTime: IntArray, profit: IntArray ): Int { val jobs = Array(startTime.size) { IntArray(3) } for (i in startTime.indices) { jobs[i][0] = startTime[i] jobs[i][1] = endTime[i] jobs[i][2] = profit[i] } jobs.sortBy { it[0] } class Job(val endTime: Int, val profit: Int) var runningList = mutableListOf<Job>() runningList.add(Job(0, 0)) for (newJob in jobs) { val newList = mutableListOf<Job>() for (runningJob in runningList) { newList.add(runningJob) // don't start new job if (runningJob.endTime <= newJob[0]) { // start this new job newList.add(Job(newJob[1], runningJob.profit + newJob[2])) } } runningList = newList } return runningList.maxOf { it.profit } } // https://leetcode.com/problems/maximum-profit-in-job-scheduling/solutions/409009/java-c-python-dp-solution fun jobScheduling4(startTime: IntArray, endTime: IntArray, profit: IntArray): Int { val n = startTime.size val jobs = Array(n) { IntArray(3) } for (i in 0 until n) { jobs[i] = intArrayOf(startTime[i], endTime[i], profit[i]) } jobs.sortBy { it[1] } // sort by end time val dp = TreeMap<Int, Int>() // max profit at any end time dp[0] = 0 for (job in jobs) { val maxProfitHere = dp.floorEntry(job[0]).value + job[2] if (maxProfitHere > dp.lastEntry().value) dp[job[1]] = maxProfitHere } return dp.lastEntry().value } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
3,469
leetcode-kotlin
Apache License 2.0
src/Day07.kt
Kbzinho-66
572,299,619
false
{"Kotlin": 34500}
private fun addFile(map: MutableMap<String, Int>, cwd: String, size: Int) { // Se ele não existir no mapa ainda, inicializa ele map.putIfAbsent(cwd, 0) // Somar o tamanho passado tanto pros que já existiam quando os que foram inicializados agora map[cwd] = map[cwd]!! + size // Se aqui o cwd estiver vazio, chegou na raiz e não tem mais o que subir if (cwd.isEmpty()) return // Se não, subir um nível do endereço e repetir o processo val parent = cwd.substringBeforeLast('/') addFile(map, parent, size) } fun main() { fun calculateSizes(input:List<String>): Map<String, Int> { val directories: MutableMap<String, Int> = hashMapOf(Pair("", 0)) var cwd = "" for (line in input) { when { line.startsWith("$ ls") -> {} line.startsWith("$ cd") -> { // Se for uma mudança de diretório, atualizar o endereço atual if (line.endsWith("..")) { cwd = cwd.substringBeforeLast("/", "") } else { cwd += ( if (line.isEmpty()) "" else "/" ) + line.substringAfterLast(' ') } } else -> { if (line.startsWith("dir")) { // Se for um diretório, inicializar ele no map val dir = "/" + line.substringAfter(' ') addFile(directories, cwd + dir, 0) } else { // Se for um arquivo, adicionar o tamanho dele em todas as pastas que o contêm val size = line.substringBefore(' ').toInt() addFile(directories, cwd, size) } } } } return directories } fun part1(input: List<String>): Int = calculateSizes(input).values.filter { it <= 100000 }.sum() fun part2(input: List<String>): Int { val totalDisk = 70000000 val requiredDisk = 30000000 val files = calculateSizes(input) val freeDisk = totalDisk - files[""]!! return files .filter { (key, size) -> key.isNotEmpty() && size + freeDisk >= requiredDisk } .minOf { (_, size) -> size } } // Testar os casos básicos val testInput = readInput("../inputs/Day07_test").drop(1) sanityCheck(part1(testInput), 95437) sanityCheck(part2(testInput), 24933642) // Tirar o primeiro comando que é sempre "$ cd /" val input = readInput("../inputs/Day07").drop(1) println("Parte 1 = ${part1(input)}") println("Parte 2 = ${part2(input)}") }
0
Kotlin
0
0
e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b
2,689
advent_of_code_2022_kotlin
Apache License 2.0
advent-of-code-2021/src/code/day8/Main.kt
Conor-Moran
288,265,415
false
{"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733}
package code.day8 import java.io.File fun main() { doIt("Day 8 Part 1: Test Input", "src/code/day8/test.input", part1) doIt("Day 8 Part 1: Real Input", "src/code/day8/part1.input", part1) doIt("Day 8 Part 2: Test Input", "src/code/day8/test.input", part2); doIt("Day 8 Part 2: Real Input", "src/code/day8/part1.input", part2); } fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Int) { val lines = arrayListOf<String>() File(input).forEachLine { lines.add(it) } println(String.format("%s: Ans: %d", msg , calc(lines))) } val part1: (List<String>) -> Int = { lines -> val inputs = parse(lines).inputs /* * 1 -> 2 * 4 -> 4 * 7 -> 3 * 8 -> 7 * 2, 3, 5 -> 5 * 0, 6, 9 -> 6 */ var sum = 0 for (i in inputs.indices) { sum += inputs[i].second.filter { listOf(2, 3, 4, 7).contains(it.length) }.size } sum } val valids = mapOf(0 to "abcefg", 1 to "cf", 2 to "acdeg", 3 to "acdfg", 4 to "bcdf", 5 to "abdfg", 6 to "abdefg", 7 to "acf", 8 to "abcdefg", 9 to "abcdfg") val part2: (List<String>) -> Int = { lines -> val inputs = parse(lines).inputs var sum = 0 for (i in inputs.indices) { val decryptor = decrypt(inputs[i].first) var num = "" for (elem in inputs[i].second) { num = num.plus(decryptor[key(elem)]) } sum += num.toInt() } sum } fun key(str: String): String { return String(str.toCharArray().apply { sort() }) } val decrypt: (List<String>) -> Map<String, String> = { encoded -> val digit = MutableList<String>(10) {""} digit[7] = encoded.first { it.length == 3 } digit[1] = encoded.first { it.length == 2 } digit[4] = encoded.first { it.length == 4 } digit[8] = encoded.first { it.length == 7 } digit[9] = encoded.first { it.length == 6 && containsAll(digit[4], it) } digit[0] = encoded.first { it.length == 6 && !containsAll(digit[4], it) && containsAll(digit[1], it) } digit[6] = encoded.first { it.length == 6 && it != digit[9] && it != digit[0] } digit[3] = encoded.first { it.length == 5 && containsAll(digit[7], it) } digit[5] = encoded.first { it.length == 5 && containsAll(it, digit[6]) } digit[2] = encoded.first { it.length == 5 && it != digit[5] && it != digit[3] } val ret = mutableMapOf<String, String>() for (i in digit.indices) { ret[key(digit[i])] = i.toString() } ret } fun containsAll(chars: String, str: String): Boolean { var ret = true for (i in 0 until chars.length) { if (!str.contains(chars[i])) { ret = false break } } return ret } val parse: (List<String>) -> Input = { lines -> val parsed = MutableList<Pair<List<String>, List<String>>>(lines.size) { Pair(mutableListOf(), mutableListOf()) } for (i in lines.indices) { val raw = lines[i].split("|").map { it.trim() } parsed[i] = Pair(raw[0].split(" "), raw[1].split(" ")) } Input(parsed) } class Input(val inputs: List<Pair<List<String>, List<String>>>)
0
Kotlin
0
0
ec8bcc6257a171afb2ff3a732704b3e7768483be
3,081
misc-dev
MIT License
src/main/kotlin/com/hopkins/aoc/day12/main.kt
edenrox
726,934,488
false
{"Kotlin": 88215}
package com.hopkins.aoc.day12 import java.io.File const val debug = true const val part = 2 /** Advent of Code 2023: Day 12 */ fun main() { val lines: List<String> = File("input/input12.txt").readLines() val lineInputs: List<LineInput> = lines.mapIndexed { index, line -> val max = if (part == 2) 5 else 1 var (left, right) = line.split(" ") left = (0 until max).joinToString(separator = "?") { left } right = (0 until max).joinToString(separator = ",") { right } LineInput(index + 1, left, right) } val sum: Long = lineInputs.sumOf { val numWays = countNumWaysCached(it.groups, it.counts) println("Line Input: $it") println("Num ways: $numWays") numWays } println("Sum: $sum") } val cache = mutableMapOf<CacheKey, Long>() fun countNumWaysCached(groups: List<String>, counts: List<Int>): Long { val key = CacheKey(groups, counts) if (cache.containsKey(key)) { return cache[key]!! } val result = countNumWays(key.groups, key.counts) cache[key] = result if (debug) { if (counts.size < 2) { println("key=$key, result=$result") } } return result } fun countNumWays(groups: List<String>, counts: List<Int>): Long { if (groups.isEmpty() || (groups.size == 1 && groups.first() == "")) { // Base cases: groups is empty return if (counts.isEmpty()) 1 else 0 } if (groups.size == 1) { val firstGroup = groups[0] if (firstGroup.length == 1) { // Base case: groups has 1 element and it is 1 character if (firstGroup == "#") { return if (counts.size == 1 && counts.first() == 1) { 1 } else { 0 } } else { require(firstGroup == "?") return if (counts.isEmpty()) { 1 } else if (counts.size == 1 && counts.first() == 1) { 1 } else { 0 } } } else if (!firstGroup.contains("?")) { // Base case: group contains only "#" return if (counts.size == 1 && counts.first() == firstGroup.length) 1 else 0 } else if (counts.isEmpty()) { // Base case: there are no counts, so there can be no more operational springs return if (firstGroup.contains("#")) { 0 } else { 1 } } else { require(counts.isNotEmpty()) // Recursive case: group has 1 element and it is 2+ characters with 1 or more '?'s val partitionPositions = firstGroup.indices.filter { firstGroup[it] == '?'} var ways = 0L // Option 1: we don't partition the group, thus it is all # if (counts.size == 1 && counts.first() == firstGroup.length) { return 1 } // Option 2: we partition the group at one of the question marks for (position in partitionPositions) { val leftGroup = listOf(firstGroup.take(position).replace("?", "#")) val rightGroup = listOf(firstGroup.drop(position + 1)) //println("firstGroup=$firstGroup partitionPos=$position left=$leftGroup right=$rightGroup") val leftWays = countNumWaysCached(leftGroup, emptyList()) * countNumWaysCached(rightGroup, counts) val rightWays = countNumWaysCached(leftGroup, counts.take(1)) * countNumWaysCached(rightGroup, counts.drop(1)) ways += leftWays + rightWays //if (firstGroup == "????" && ways > 0) { println("O2: group=$firstGroup left=${leftGroup[0]} right=${rightGroup[0]} counts=$counts leftWay=$leftWays rightWays=$rightWays") //} } return ways } } else { var ways = 0L for (i in 0..counts.size) { val leftWays = countNumWaysCached(groups.take(1), counts.take(i)) val rightWays = countNumWaysCached(groups.drop(1), counts.drop(i)) ways += leftWays * rightWays } return ways } } data class CacheKey(val groups: List<String>, val counts: List<Int>) data class LineInput(val index: Int, val left: String, val right: String) { val groups = left.split(".").filter { it.isNotBlank() } val counts = right.split(",").map { it.toInt() } }
0
Kotlin
0
0
45dce3d76bf3bf140d7336c4767e74971e827c35
4,595
aoc2023
MIT License
2022/src/Day18.kt
Saydemr
573,086,273
false
{"Kotlin": 35583, "Python": 3913}
package src import java.util.* import kotlin.math.abs fun manhattanDistance(a: Triple<Int, Int, Int>, b: Triple<Int, Int, Int>): Int { return abs(a.first - b.first) + abs(a.second - b.second) + abs(a.third - b.third) } val directions = listOf( Triple(1, 0, 0), Triple(-1, 0, 0), Triple(0, 1, 0), Triple(0, -1, 0), Triple(0, 0, 1), Triple(0, 0, -1) ) fun main() { val cubes = readInput("input18") .map { it.trim().split(",") } .map { Triple(it[0].toInt(), it[1].toInt(), it[2].toInt()) } .toSet() var numNeighbors = 0 cubes.forEach { current -> numNeighbors += 6 - cubes.filter { it2 -> it2 != current }.count { manhattanDistance(it, current) <= 1 } } println(numNeighbors) // part 2 // find exterior surface val minX = cubes.minBy { it.first }.first - 1 val maxX = cubes.maxBy { it.first }.first + 1 val minY = cubes.minBy { it.second }.second - 1 val maxY = cubes.maxBy { it.second }.second + 1 val minZ = cubes.minBy { it.third }.third - 1 val maxZ = cubes.maxBy { it.third }.third + 1 fun isInRange(a: Triple<Int, Int, Int>): Boolean { return a.first in minX..maxX && a.second in minY..maxY && a.third in minZ..maxZ } val stack = Stack<Triple<Int, Int, Int>>() stack.push(Triple(minX, minY, minZ)) val seen = mutableSetOf<Triple<Int, Int, Int>>() while (stack.isNotEmpty()) { val current = stack.pop() if (!seen.contains(current) && !cubes.contains(current) && isInRange(current)) { seen.add(current) directions.forEach { dir -> stack.push(Triple(current.first + dir.first, current.second + dir.second, current.third + dir.third)) } } } var part2Neighbors = 0 seen.forEach { current -> part2Neighbors += cubes.count { manhattanDistance(it, current) <= 1 } } println(part2Neighbors) }
0
Kotlin
0
1
25b287d90d70951093391e7dcd148ab5174a6fbc
1,953
AoC
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2022/Day13.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2022 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.resultFrom import kotlin.math.min import kotlin.math.sign /** * --- Day 13: Distress Signal --- * https://adventofcode.com/2022/day/13 */ class Day13 : Solver { override fun solve(lines: List<String>): Result { val pairs = lines.windowed(2, 3).flatten().map { parse(it) } var part1 = 0 for ((i, it) in pairs.windowed(2, 2).withIndex()) { if (ThingComparator.compare(it[0], it[1]) < 0) part1 += (i + 1) } val pairsB = mutableListOf<Thing>() pairs.windowed(2, 2) { pairsB.add(it[0]); pairsB.add(it[1]) } pairsB.addAll(listOf(parse("[[2]]"), parse("[[6]]"))) pairsB.sortWith(ThingComparator) var a = 0 var b = 0 for ((i, thing) in pairsB.withIndex()) { if (thing.toString() == "[[2]]") a = i + 1 if (thing.toString() == "[[6]]") b = i + 1 } return resultFrom(part1, a * b) } fun parse(str: String): Thing { var level = 0 val result = mutableListOf<Thing>() var curr = "" for ((i, ch) in str.substring(1).withIndex()) { if (ch == ',' && level == 0) { if (curr.isNotEmpty()) result.add(Thing(curr.toInt(), listOf())) curr = "" } else if (ch == '[') { if (level == 0) result.add(parse(str.substring(1).substring(i))) level++ } else if (ch == ']') { level-- if (level < 0) { if (curr.isNotEmpty()) result.add(Thing(curr.toInt(), listOf())) return Thing(-1, result) } } else if (level == 0) { curr += ch } } throw RuntimeException("Oh no, my hovercraft is full of eels") } data class Thing(val value: Int, val other: List<Thing> = emptyList()) { fun asList() = other.ifEmpty { if (value >= 0) listOf(Thing(value, emptyList())) else emptyList() } override fun toString(): String = if (value >= 0) "$value" else "[" + other.joinToString(",") { it.toString() } + "]" } } class ThingComparator { companion object : Comparator<Day13.Thing> { override fun compare(a: Day13.Thing, b: Day13.Thing): Int { val list1 = a.asList() val list2 = b.asList() for (i in 0 until (min(list1.size, list2.size))) { if (list1[i].value == -1 || list2[i].value == -1) { val o = compare(list1[i], list2[i]) if (o != 0) return o } else { if (list1[i].value < list2[i].value) return -1 if (list1[i].value > list2[i].value) return 1 } } return (list1.size - list2.size).sign } } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,623
euler
Apache License 2.0
src/Day02.kt
afranken
572,923,112
false
{"Kotlin": 15538}
fun main() { fun part1(input: List<String>): Int { val scores: List<Int> = input.map { val shapeInput = it.split(" ") val theirShape = Shape.of(shapeInput[0]) val myShape = Shape.of(shapeInput[1]) myShape.score + myShape.outcomeAgainst(theirShape) } val sum = scores.sum() println("Sum of input is $sum") return sum } fun part2(input: List<String>): Int { val scores: List<Int> = input.map { val shapeInput = it.split(" ") val theirShape = Shape.of(shapeInput[0]) val myShape = Shape.of2(shapeInput[1], theirShape) myShape.score + myShape.outcomeAgainst(theirShape) } val sum = scores.sum() println("Sum of input is $sum") return sum } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") check(part1(input) == 12794) check(part2(input) == 14979) } abstract class Shape { abstract val score: Int abstract fun outcomeAgainst(other: Shape): Int companion object { const val WIN: Int = 6 const val DRAW: Int = 3 const val LOSS: Int = 0 fun of(s: String) : Shape { return when (s) { "A" -> Rock() "Y" -> Paper() "B" -> Paper() "X" -> Rock() "C" -> Scissors() else -> Scissors() // "Z" } } fun of2(s: String, theirs: Shape) : Shape { when (theirs) { is Rock -> { return when(s) { "X" -> Scissors() "Y" -> Rock() else -> Paper() } } is Paper -> { return when(s) { "X" -> Rock() "Y" -> Paper() else -> Scissors() } } else -> return when(s) { // Scissors() "X" -> Paper() "Y" -> Scissors() else -> Rock() } } } } } class Rock : Shape() { override val score: Int = 1 override fun outcomeAgainst(other: Shape): Int { return when (other) { is Rock -> DRAW is Scissors -> WIN else -> LOSS } } } class Paper : Shape() { override val score: Int = 2 override fun outcomeAgainst(other: Shape): Int { return when (other) { is Paper -> DRAW is Rock -> WIN else -> LOSS } } } class Scissors : Shape() { override val score: Int = 3 override fun outcomeAgainst(other: Shape): Int { return when (other) { is Scissors -> DRAW is Paper -> WIN else -> LOSS } } }
0
Kotlin
0
0
f047d34dc2a22286134dc4705b5a7c2558bad9e7
3,036
advent-of-code-kotlin-2022
Apache License 2.0
src/Day03.kt
sms-system
572,903,655
false
{"Kotlin": 4632}
fun main() { fun getItemPriority (item: String): Int = if (item.uppercase() == item) { item.first().toInt() - 38 } else { item.first().toInt() - 96 } fun part1(input: List<String>): Int = input .map { it.substring(0, it.length / 2).split("") .intersect(it.substring(it.length / 2).split("")) .filter { !it.isBlank() } .single() } .map { getItemPriority(it) } .sum() fun part2(input: List<String>): Int = input .chunked(3) .map { it[0].split("") .intersect(it[1].split("")) .intersect(it[2].split("")) .filter { !it.isBlank() } .single() } .map { getItemPriority(it) } .sum() 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
266dd4e52f3b01912fbe2aa23d1ee70d1292827d
1,025
adventofcode-2022-kotlin
Apache License 2.0
2020/kotlin/src/main/kotlin/io/franmosteiro/aoc2020/Day07.kt
franmosteiro
433,734,642
false
{"Kotlin": 27170, "Ruby": 16611, "Shell": 389}
package io.franmosteiro.aoc2020 /** * Advent of Code 2020 - Day 7: Handy Haversacks - * Problem Description: http://adventofcode.com/2020/day/7 */ class Day07(input: List<String>) { private val allBags: List<Bag> private val MY_BAG = "shiny gold" companion object { private val bagPattern = """(\w+ \w+) bags contain (.*)""".toRegex() private val bagChildsPattern = """(\d+) (\w+ \w+) bags?""".toRegex() fun fromString(line: String): Bag { val (name, rest) = bagPattern.matchEntire(line)!!.destructured val contains = bagChildsPattern.findAll(rest).map { match -> val (c, n) = match.destructured c.toInt() to Bag(n, emptyList()) }.toList() return Bag(name, contains) } } init { val bags = input.map { fromString(it) } fun buildRules(name: String): Bag { val containedBags = bags.first { it.color == name }.contains.map { it.first to buildRules(it.second.color) } return Bag(name, containedBags) } allBags = bags.map { buildRules(it.color) } } fun resolvePartOne(): Int = allBags.count { it.canHold(MY_BAG) } fun resolvePartTwo(): Int = allBags.first { it.color == MY_BAG }.numContains() data class Bag(val color : String, val contains : List<Pair<Int, Bag>> = emptyList()){ fun canHold(what: String): Boolean { return contains.any { it.second.color == what || it.second.canHold(what) } } fun numContains(): Int { return contains.sumBy { it.first * (it.second.numContains() + 1) } } } }
0
Kotlin
0
0
dad555d9cd0c3060c4b1353c7c6f170aa340c285
1,775
advent-of-code
MIT License
src/Day04.kt
Krzychuk9
573,127,179
false
null
fun main() { fun part1(input: List<String>): Int { return input.toRanges().count { val firstGroup = it[0] val secondGroup = it[1] firstGroup.subtract(secondGroup).isEmpty() || secondGroup.subtract(firstGroup).isEmpty() } } fun part2(input: List<String>): Int { return input.toRanges().count { val firstGroup = it[0] val secondGroup = it[1] firstGroup.subtract(secondGroup).size != firstGroup.toSet().size } } // 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))//582 println(part2(input))//893 } fun List<String>.toRanges() = this.map { it.split(",") .map { range -> range.toRange() } } fun String.toRange(): IntRange { val split = this.split("-") return split[0].toInt()..split[1].toInt() }
0
Kotlin
0
0
ded55d03c9d4586166bf761c7d5f3f45ac968e81
1,037
adventOfCode2022
Apache License 2.0
src/day02/Day02.kt
devEyosiyas
576,863,541
false
null
package day02 import println import readInput const val ROCK = 1 const val PAPER = 2 const val SCISSORS = 3 const val WINNER_POINT = 6 fun main() { fun point(c: Char): Int = when (c) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> 0 } fun computeWinner(a: Int, b: Int): Char = when { a == b -> 'T' a == ROCK && b == SCISSORS -> 'A' a == PAPER && b == ROCK -> 'A' a == SCISSORS && b == PAPER -> 'A' else -> 'B' } fun swapMove(moveA: Int, c: Char): Int = when (c) { 'Y' -> moveA 'X' -> when (moveA) { ROCK -> SCISSORS PAPER -> ROCK else -> PAPER } else -> when (moveA) { ROCK -> PAPER PAPER -> SCISSORS else -> ROCK } } fun awardPoint(moveA: Char, moveB: Char, swap: Boolean): Int { val pointA = point(moveA) val pointB = if (swap) swapMove(pointA, moveB) else point(moveB) return when (computeWinner(pointA, pointB)) { 'A' -> pointB 'B' -> WINNER_POINT + pointB 'T' -> (WINNER_POINT / 2) + pointB else -> 0 } } fun solve(input: List<String>, swap: Boolean = false): Int { var score = 0 input.forEach { it.split(" ").let { (a, b) -> score += awardPoint(a[0], b[0], swap) } } return score } val testInput = readInput("day02", true) val input = readInput("day02") // part one solve(testInput).println() solve(input).println() // part two solve(testInput, true).println() solve(input, true).println() }
0
Kotlin
0
0
91d94b50153bdab1a4d972f57108d6c0ea712b0e
1,734
advent_of_code_2022
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2021/Day8.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 8: Seven Segment Search --- * https://adventofcode.com/2021/day/8 */ class Day8 : Solver { override fun solve(lines: List<String>): Result { var partA = 0 for (line in lines) { val parsed = parseLine(line) partA += parsed.output.map { it.length } .count { length -> length == 2 || length == 3 || length == 4 || length == 7 } } val partB = lines.map { parseLine(it) }.map { calcLine(it.input, it.output) }.sum() return Result("$partA", "$partB") } private fun calcLine(inputs: List<String>, outputs: List<String>): Int { assert(inputs.size == 10) // Important constraints of the input, every position is unique. val inputCandidates = MutableList(inputs.size) { mutableSetOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) } val digitToCode = mutableMapOf<Int, String>() // Digits for which we definitely know the code. // Called to lock in a digit. Remove from all candidate sets except the one, and set code. val lockDigit = { inputIdx: Int, digit: Int, code: String -> inputCandidates.forEach { it.remove(digit) } inputCandidates[inputIdx] = mutableSetOf(digit) digitToCode[digit] = code.sorted() } // If we compare a locked number with codes of given length, lock digit if overlap matches. val reduce = { num: Int, length: Int, input: String, i: Int, overlap: Int, digit: Int -> if (digitToCode.containsKey(num) && input.length == length) { if (digitToCode[num]!!.toSet().intersect(input.toSet()).size == overlap) { lockDigit(i, digit, input) } } } // Lock in the unique numbers first. for ((i, input) in inputs.withIndex()) { if (input.length == 2) lockDigit(i, 1, input) if (input.length == 3) lockDigit(i, 7, input) if (input.length == 4) lockDigit(i, 4, input) if (input.length == 7) lockDigit(i, 8, input) } // Reduce until we have exactly one candidate per input position. while (inputCandidates.count { it.size != 1 } != 0) { for ((i, input) in inputs.withIndex()) { reduce(1, 5, input, i, 2, 3) reduce(7, 6, input, i, 2, 6) reduce(4, 6, input, i, 4, 9) reduce(4, 5, input, i, 2, 2) reduce(6, 5, input, i, 5, 5) } } // Ensure all codes are set. for ((idx, digit) in inputCandidates.withIndex()) { digitToCode[digit.first()] = inputs[idx].sorted() } // Create map from code to digit and use it to construct final output result. val codeToDigit = digitToCode.map { it.value to it.key }.toMap() return outputs.map { it.sorted() }.map { codeToDigit[it] }.joinToString("").toInt() } private fun parseLine(str: String): Line { val split = str.split(" | ") return Line(split[0].split(" "), split[1].split(" ")) } private data class Line(val input: List<String>, val output: List<String>) private fun String.sorted() = this.toCharArray().sorted().joinToString("") }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
3,047
euler
Apache License 2.0
src/Day07.kt
JIghtuse
572,807,913
false
{"Kotlin": 46764}
data class File(val size: Int) typealias Files = List<File> data class Directory( val path: String, val nestedDirectories: List<Directory>, val files: Files) typealias Directories = List<Directory> typealias FilesAndDirs = Pair<Files, Directories> fun joinPath(absolutePath: String, component: String) = absolutePath + if (absolutePath.last() == '/') component else "/$component" fun dropLastComponent(absolutePath: String) = absolutePath.substringBeforeLast('/').ifEmpty { "/" } fun lsDir(currentPath: String, lsOutput: List<String>): Directory { val (files, dirs) = lsOutput .fold(listOf<File>() to listOf()) { acc: FilesAndDirs, x: String -> val parts = x.split(" ") when (parts[0]) { "dir" -> acc.copy( second = acc.second.plus( Directory(joinPath(currentPath, parts[1]), listOf(), listOf()))) else -> acc.copy(first = acc.first.plus(File(parts[0].toInt()))) } } return Directory(currentPath, dirs, files) } fun fill(dirWithNoData: Directory, dirWithData: Directory): Directory { if (dirWithNoData.path == dirWithData.path) { return dirWithData } val subdirIndex = dirWithNoData.nestedDirectories.indexOfFirst { dirWithData.path.startsWith(it.path) } return dirWithNoData.copy( nestedDirectories = dirWithNoData.nestedDirectories .take(subdirIndex) .plus(fill(dirWithNoData.nestedDirectories[subdirIndex], dirWithData)) .plus(dirWithNoData.nestedDirectories.drop(subdirIndex + 1))) } fun buildDirectory(input: List<String>): Directory { var i = 0 var currentPath = "/" var root = Directory(currentPath, listOf(), listOf()) while (i != input.size) { val parts = input[i].split(" ") when (parts[1]) { "ls" -> { val start = i + 1 i += 1 while (i != input.size && input[i].first() != '$') { i += 1 } root = fill(root, lsDir(currentPath, input.subList(start, i))) } "cd" -> { i += 1 currentPath = when (parts[2]) { ".." -> dropLastComponent(currentPath) "/" -> "/" else -> joinPath(currentPath, parts[2]) } } } } return root } fun display(dir: Directory, level: Int = 0) { println("${" ".repeat(level)}${dir.path}") dir.files.forEach { println("${" ".repeat(level + 2)}$it") } dir.nestedDirectories.forEach { display(it, level + 2) } } fun directorySize(dir: Directory): Int { return dir.files.sumOf { it.size } + dir.nestedDirectories.sumOf { directorySize(it) } } fun sumDirSizesLessThanOrEqual(dir: Directory, limit: Int): Int { fun suitableDir(d: Directory): Boolean { return directorySize(d) <= limit } val nestedSum: Int = dir.nestedDirectories .sumOf { d -> sumDirSizesLessThanOrEqual(d, limit) } return nestedSum + if (suitableDir(dir)) { directorySize(dir) } else { 0 } } fun smallestDirectoryWithSizeUpTo(dir: Directory, limit: Int): Int { val size = directorySize(dir) val smallestNestedDirectory = dir.nestedDirectories.minOfOrNull { smallestDirectoryWithSizeUpTo(it, limit) } ?: Int.MAX_VALUE return minOf( if (size >= limit) size else Int.MAX_VALUE, smallestNestedDirectory) } fun main() { fun part1(input: List<String>): Int { val root = buildDirectory(input) return sumDirSizesLessThanOrEqual(root, 100_000) } fun part2(input: List<String>): Int { val root = buildDirectory(input) val totalDiskSpace = 70_000_000 val spaceNeededForUpdate = 30_000_000 val unusedSpace = totalDiskSpace - directorySize(root) val needToFree = spaceNeededForUpdate - unusedSpace return smallestDirectoryWithSizeUpTo(root, needToFree) } // 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
8f33c74e14f30d476267ab3b046b5788a91c642b
4,443
aoc-2022-in-kotlin
Apache License 2.0
kotlin/src/2022/Day18_2022.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
import kotlin.math.* fun main() { val pts = readInput(18).trim().lines() .map {it.split(",").map {x -> x.toInt()}}.toSet() fun neighbors(pt: List<Int>): List<List<Int>> { val (x, y, z) = pt return listOf(listOf(x-1, y, z), listOf(x+1, y, z), listOf(x, y-1, z), listOf(x, y+1, z), listOf(x, y, z-1), listOf(x, y, z+1)) } // part1 println(pts.sumOf { neighbors(it).count {x -> x !in pts} }) // part2 val (mi, mx) = mutableListOf(10000, 10000, 10000) to mutableListOf(-10000, -10000, -10000) pts.forEach { for ((i, q) in it.withIndex()) { mi[i] = min(mi[i], q) mx[i] = max(mx[i], q) } } fun good(pt: List<Int>) = pt !in pts && pt.withIndex().all {it.value >= mi[it.index] - 1 && it.value <= mx[it.index] + 1} val outpts = mutableSetOf(mi.map {x -> x - 1}) val q = mutableSetOf(mi.map {x -> x - 1}) while (q.isNotEmpty()) { val pt = q.first().also {q.remove(it)} neighbors(pt).filter(::good) .filter {it !in outpts} .forEach { outpts.add(it) q.add(it) } } println(pts.sumOf { neighbors(it).count {x -> x !in pts && x in outpts} }) }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
1,264
adventofcode
Apache License 2.0
src/Day08.kt
hijst
572,885,261
false
{"Kotlin": 26466}
fun main() { fun IntGrid.isCellVisibleFromLeft(row: Int, col: Int) = rows[row].take(col) .all { value -> value < rows[row][col] } fun IntGrid.isCellVisibleFromRight(row: Int, col: Int) = rows[row].takeLast(cols.size - 1 - col) .all { value -> value < rows[row][col] } fun IntGrid.isCellVisibleFromTop(row: Int, col: Int) = cols[col].take(row) .all { value -> value < rows[row][col]} fun IntGrid.isCellVisibleFromBottom(row: Int, col: Int) = cols[col].takeLast(rows.size - 1 - row) .all { value -> value < rows[row][col] } fun IntGrid.isCellVisibleInRow(row: Int, col: Int): Boolean = isCellVisibleFromLeft(row, col) || isCellVisibleFromRight(row, col) fun IntGrid.isCellVisibleInColumn(row: Int, col: Int): Boolean = isCellVisibleFromTop(row, col) || isCellVisibleFromBottom(row, col) fun IntGrid.isCellVisible(row: Int, col: Int): Boolean { if (row == 0 || col == 0 || row == rows.size - 1 || col == cols.size - 1) return true return isCellVisibleInRow(row, col) || isCellVisibleInColumn(row, col) } fun IntGrid.calculateScenicScore(row: Int, col: Int): Long { val left: Long = rows[row].mapIndexed { index, i -> index to i } .lastOrNull { (ind, height) -> ind < col && height >= rows[row][col] }?.first?.toLong() ?: 0L val right: Long = rows[row].mapIndexed { index, i -> index to i } .firstOrNull { (ind, height) -> ind > col && height >= rows[row][col] }?.first?.toLong() ?: (cols.size - 1).toLong() val top: Long = cols[col].mapIndexed { index, i -> index to i } .lastOrNull { (ind, height) -> ind < row && height >= rows[row][col] }?.first?.toLong() ?: 0L val bottom: Long = cols[col].mapIndexed { index, i -> index to i } .firstOrNull { (ind, height) -> ind > row && height >= rows[row][col] }?.first?.toLong() ?: (rows.size - 1).toLong() return (col - left) * (right - col) * (row - top) * (bottom - row) } fun part1(grid: IntGrid): Int = grid.rows.mapIndexed { row, values -> List(values.size) { col -> grid.isCellVisible(row, col) } }.flatten() .count() fun part2(grid: IntGrid): Long = grid.rows.mapIndexed { row, values -> List(values.size) { col -> grid.calculateScenicScore(row, col) } }.flatten() .max() val testInput = readIntGrid("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8L ) val input = readIntGrid("Day08_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2258fd315b8933642964c3ca4848c0658174a0a5
2,623
AoC-2022
Apache License 2.0
2021/src/day21/Day21.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day21 import readInput data class Player(val name: String, var pos: Int, var score: Int) fun String.toPlayer(): Player { return Player(this.substringBefore(" starting"), this.split(" ").last().toInt(), 0) } fun getRolls(rollsNb: List<Int>): Int { return rollsNb.map { val nb = it % 100 if (nb == 0) 100 else nb }.sum() } // Just execute the game manually fun part1(lines: List<String>): Int { val players = listOf(lines.first().toPlayer(), lines.last().toPlayer()) var currentPlayer = 0 var rollsNb = 1 while (!players.any { it.score >= 1000 }) { val p = players[currentPlayer] val rolled = getRolls(listOf(rollsNb, rollsNb + 1, rollsNb + 2)) rollsNb += 3 p.pos = (p.pos + rolled) % 10 if (p.pos == 0) p.pos = 10 p.score += p.pos currentPlayer = (currentPlayer + 1) % players.size } return players.first { it.score < 1000 }.score * (rollsNb - 1) } val waysMemo = mutableMapOf<String, Long>() fun findWays(throws: Int, sum: Int, faces: Int = 3) : Long { if (sum == 0 && throws == 0) return 1 if (sum < 0 || throws == 0) return 0 val key = "$sum-$throws" if (!waysMemo.containsKey(key)) { waysMemo[key] = (1..faces).toList().sumOf { findWays(throws - 1, sum - it) } } return waysMemo[key]!! } fun Pair<Long, Long>.multiply(multiplier: Long) = Pair(first * multiplier, second * multiplier) fun Pair<Long, Long>.add(other: Pair<Long, Long>) = Pair(first + other.first, second + other.second) val memo = mutableMapOf<String, Pair<Long, Long>>() fun numberOfWaysToWin(pos1: Int, score1: Int, pos2: Int, score2: Int, rolled: Int, player1turn: Boolean) : Pair<Long, Long> { val key = "$pos1-$score1-$pos2-$score2-$rolled-$player1turn" if (!memo.containsKey(key)) { if (player1turn) { var posAfterThrow = (pos1 + rolled) % 10 if (posAfterThrow == 0) posAfterThrow = 10 val scoreAfterThrow = score1 + posAfterThrow if (scoreAfterThrow >= 21) return Pair(1, 0) // 27 total possibilities to obtain a total between 3 and 9 rolling 3 times a 3 faced dice var totalWays = Pair(0L, 0L) for (possibleTotal in 3..9) { totalWays = totalWays.add( numberOfWaysToWin(posAfterThrow, scoreAfterThrow, pos2, score2, rolled = possibleTotal, false) .multiply(findWays(throws = 3, possibleTotal)) ) } memo[key] = totalWays } else { var posAfterThrow = (pos2 + rolled) % 10 if (posAfterThrow == 0) posAfterThrow = 10 val scoreAfterThrow = score2 + posAfterThrow if (scoreAfterThrow >= 21) return Pair(0, 1) // 27 total possibilities to obtain a total between 3 and 9 rolling 3 times a 3 faced dice var totalWays = Pair(0L, 0L) for (possibleTotal in 3..9) { totalWays = totalWays.add( numberOfWaysToWin(pos1, score1, posAfterThrow, scoreAfterThrow, rolled = possibleTotal, true) .multiply(findWays(throws = 3, possibleTotal)) ) } memo[key] = totalWays } } return memo[key]!! } fun part2(lines: List<String>): Long { val players = listOf(lines.first().toPlayer(), lines.last().toPlayer()) val pos1 = players.first().pos val pos2 = players.last().pos var total = Pair(0L, 0L) for (possibleTotal in 3..9) { total = total.add( numberOfWaysToWin(pos1, 0, pos2, 0, rolled = possibleTotal, true) // Player1 starts .multiply(findWays(throws = 3, possibleTotal)) ) } return maxOf(total.first, total.second) } fun main() { val testInput = readInput("day21/test") println("part1(testInput) => " + part1(testInput)) println("part2(testInput) => " + part2(testInput)) val input = readInput("day21/input") println("part1(input) => " + part1(input)) println("part2(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
4,156
advent-of-code
Apache License 2.0
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day11.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2020 import nl.dirkgroot.adventofcode.util.Input import nl.dirkgroot.adventofcode.util.Puzzle class Day11(input: Input) : Puzzle() { private val empty = 'L' private val occupied = '#' private val floor = '.' private val area by lazy { val area = input.lines().map { listOf(floor) + it.toList() + listOf(floor) } val floorRow = listOf(List(area[0].size) { floor }) floorRow + area + floorRow } private val rowCount by lazy { area.size } private val colCount by lazy { area[0].size } private val directions = listOf(-1 to -1, -1 to 0, -1 to 1, 1 to -1, 1 to 0, 1 to 1, 0 to -1, 0 to 1) override fun part1() = createRounds(4, ::adjacentNeighbors) .last() .countOccupiedSeats() private fun adjacentNeighbors(rowIndex: Int, colIndex: Int) = directions.map { (rowDiff, colDiff) -> rowIndex + rowDiff to colIndex + colDiff } override fun part2() = createRounds(5, ::visibleNeighbors) .last() .countOccupiedSeats() private fun visibleNeighbors(rowIndex: Int, colIndex: Int) = directions.map { (rowDiff, colDiff) -> visibleNeighbor(rowIndex, colIndex, rowDiff, colDiff) } private tailrec fun visibleNeighbor(rowIndex: Int, colIndex: Int, rowDiff: Int, colDiff: Int): Pair<Int, Int> { val row = rowIndex + rowDiff val col = colIndex + colDiff return when { row == 0 || col == 0 -> row to col row == rowCount - 1 || col == colCount - 1 -> row to col area[row][col] != floor -> row to col else -> visibleNeighbor(row, col, rowDiff, colDiff) } } private fun createRounds(maxOccupied: Int, neighbors: (Int, Int) -> List<Pair<Int, Int>>) = generateSequence(area) { state -> state .mapIndexed { rowIndex, row -> row.mapIndexed { colIndex, col -> when (col) { empty -> if (allEmpty(state, neighbors(rowIndex, colIndex))) occupied else empty occupied -> if (tooManyOccupied(state, maxOccupied, neighbors(rowIndex, colIndex))) empty else occupied else -> col } } } .let { if (it == state) null else it } } private fun allEmpty(state: List<List<Char>>, neighbors: List<Pair<Int, Int>>) = neighbors.all { (row, column) -> state[row][column] != occupied } private fun tooManyOccupied(state: List<List<Char>>, max: Int, neighbors: List<Pair<Int, Int>>) = neighbors.count { (r, c) -> state[r][c] == occupied } >= max private fun List<List<Char>>.countOccupiedSeats() = sumOf { row -> row.count { it == occupied } } }
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
3,111
adventofcode-kotlin
MIT License
src/main/kotlin/day11/Day11ChronalCharge.kt
Zordid
160,908,640
false
null
package day11 import shared.Coordinate import shared.allCoordinates import shared.measureRuntime import shared.readPuzzle import kotlin.math.min private fun powerLevelOf(x: Int, y: Int, serialNumber: Int): Int { val rackId = x + 10 val powerLevel = ((rackId * y) + serialNumber) * rackId return ((powerLevel % 1000) / 100) - 5 } fun Coordinate.powerLevel(serialNumber: Int) = powerLevelOf(x, y, serialNumber) fun Coordinate.powerLevelOfRegion(serialNumber: Int) = allCoordinates(3, 3, x, y).sumOf { it.powerLevel(serialNumber) } fun Coordinate.maximumPowerLevel(serialNumber: Int): Pair<Int, Int> { val maxSizeForCoordinate = min(301 - x, 301 - y) var power = powerLevelOf(x, y, serialNumber) var bestPower = power var bestSize = 1 for (size in 2..maxSizeForCoordinate) { power += (0 until size - 1).sumOf { delta -> powerLevelOf(x + size - 1, y + delta, serialNumber) + powerLevelOf(x + delta, y + size - 1, serialNumber) } power += powerLevelOf(x + size - 1, y + size - 1, serialNumber) if (power > bestPower) { bestPower = power bestSize = size } } return (bestSize to bestPower) } fun part1(serialNumber: Int) = allCoordinates(298, baseCol = 1, baseRow = 1) .maxBy { it.powerLevelOfRegion(serialNumber) } .let { "${it.x},${it.y}" } fun part2(serialNumber: Int) = allCoordinates(300, baseCol = 1, baseRow = 1).asIterable() .map { c -> c to c.maximumPowerLevel(serialNumber) } .maxBy { (_, p) -> p.second } .let { "${it.first.x},${it.first.y},${it.second.first}" } fun main() { val puzzle = readPuzzle(11).single().toInt() println(part1(puzzle)) measureRuntime { println(part2(puzzle)) } }
0
Kotlin
0
0
f246234df868eabecb25387d75e9df7040fab4f7
1,814
adventofcode-kotlin-2018
Apache License 2.0
src/main/kotlin/roundC2021/smallerstrings.kt
kristofersokk
422,727,227
false
null
package roundC2021 import kotlin.math.max import kotlin.math.min fun main() { val cases = readLine()!!.toInt() (1..cases).forEach { caseIndex -> val (N, K) = readLine()!!.split(" ").map { it.toLong() } val S = readLine()!! if (N == 1L) { val y = max(min((S[0].letterNr).code.toLong(), K), 0) println("Case #$caseIndex: $y") } else { val maxi = (N.toInt() - 1) / 2 val result = algorithm(S, K, 0, maxi) println("Case #$caseIndex: $result") } } } private fun Long.modPow(power: Long, mod: Long): Long { if (power == 0L) { return 1L } if (power == 1L) { return this % mod } val halfPower = this.modPow(power / 2L, mod) return if (power % 2 == 0L) { (halfPower * halfPower) % mod } else { val halfPlusOnePower = (halfPower * this) % mod (halfPower * halfPlusOnePower) % mod } } private fun algorithm(S: String, K: Long, index: Int, maxi: Int): Long { if (index > maxi) { return 0 } val possibleSmallerLetters = max(min((S[index].letterNr).code.toLong(), K), 0) var result = (possibleSmallerLetters * K.modPow((maxi - index).toLong(), 1000000007)).appropriateMod() if (K >= S[index].letterNr.code.toLong()) { if (index == maxi) { if (S.length % 2 == 0) { val half = S.substring(0..index) if (half + half.reversed() < S) { result += 1 } } else { val half = S.substring(0 until index) if (half + S[index] + half.reversed() < S) { result += 1 } } } else { result = (result + algorithm(S, K, index + 1, maxi)).appropriateMod() } } return result.appropriateMod() } private val Char.letterNr: Char get() = this - 97 private fun Long.appropriateMod() = ((this % 1000000007) + 1000000007) % 1000000007
0
Kotlin
0
0
3ebd59df60ee425b7af86a147f49361dc56ee38d
2,032
Google-coding-competitions
MIT License
src/Day10.kt
Fenfax
573,898,130
false
{"Kotlin": 30582}
fun main() { fun part1(input: List<ValueCommand>): Int { var register = 1 var cycleCount = 0 var score = 0 for (valueCommand in input) { score += (cycleCount + 1..cycleCount + valueCommand.command.cycleCount) .firstOrNull { (it - 20).mod(40) == 0 }?.let { it * register } ?: 0 cycleCount += valueCommand.command.cycleCount register += valueCommand.value } return score } fun part2(input: List<ValueCommand>) { var register = 1 var cycleCount = 1 val lines = mutableListOf<List<Char>>() var displayLine = mutableListOf<Char>() for (valueCommand in input) { val spite = CharArray(40) { if (it in register - 1..register + 1) '#' else '.' } repeat(valueCommand.command.cycleCount) { displayLine.add(spite[displayLine.size]) if ((it + cycleCount).mod(40) == 0) { lines.add(displayLine) displayLine = mutableListOf() } } cycleCount += valueCommand.command.cycleCount register += valueCommand.value } lines.forEach { println(it.joinToString("")) } } val input = readInput("Day10").map { cmd -> cmd.split(" ").let { ValueCommand(Command.valueOf(it[0].uppercase()), it.getOrNull(1)?.toInt() ?: 0) } } println(part1(input)) part2(input) } enum class Command(val cycleCount: Int) { ADDX(2), NOOP(1) } data class ValueCommand(val command: Command, val value: Int)
0
Kotlin
0
0
28af8fc212c802c35264021ff25005c704c45699
1,599
AdventOfCode2022
Apache License 2.0
day11/Part2.kt
anthaas
317,622,929
false
null
import java.io.File private const val EMPTY = 'L' private const val OCCUPIED = '#' fun main(args: Array<String>) { var board = File("input.txt").readLines().map { it.toCharArray() } var nextIter = evolve(board) var same = areSame(board, nextIter) while (!same) { nextIter = evolve(board) same = areSame(board, nextIter) board = nextIter } val occupiedSeats = board.map { it.map { it == OCCUPIED }.count { it } }.sum() println(occupiedSeats) } private fun areSame(board: List<CharArray>, nextIter: List<CharArray>): Boolean { return board.zip(nextIter) .map { outer -> outer.first.zip(outer.second).map { inner -> inner.first == inner.second }.all { it } } .all { it } } private fun countOccupiedNeigboursOf(x: Int, y: Int, board: List<CharArray>): Int { var count = 0 (-1..1).forEach { i -> (-1..1).forEach { j -> count += if (i == 0 && j == 0) 0 else countOccupiedInDirection(Pair(x + i, y + j), i, j, board) } } return count } fun countOccupiedInDirection(position: Pair<Int, Int>, i: Int, j: Int, board: List<CharArray>): Int { var (x, y) = position while (!((x !in 0 until board.size) || (y !in 0 until board[0].size))) { when (board[x][y]) { EMPTY -> return 0 OCCUPIED -> return 1 } x += i y += j } return 0 } private fun evolve(board: List<CharArray>): List<CharArray> { val newBoard = MutableList(board.size) { " ".repeat(board[0].size).toCharArray() } board.forEachIndexed { x, line -> line.forEachIndexed { y, actualPositionSymbol -> newBoard[x][y] = when (actualPositionSymbol) { EMPTY -> if (countOccupiedNeigboursOf(x, y, board) == 0) OCCUPIED else EMPTY OCCUPIED -> if (countOccupiedNeigboursOf(x, y, board) > 4) EMPTY else OCCUPIED else -> actualPositionSymbol } } } return newBoard }
0
Kotlin
0
0
aba452e0f6dd207e34d17b29e2c91ee21c1f3e41
2,001
Advent-of-Code-2020
MIT License
src/Day13.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import kotlin.math.max fun main() { val testInput = """ [1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [[1],4] [9] [[8,7,6]] [[4,4],4,4] [[4,4],4,4,4] [7,7,7,7] [7,7,7] [] [3] [[[]]] [[]] [1,[2,[3,[4,[5,6,7]]]],8,9] [1,[2,[3,[4,[5,6,0]]]],8,9] """.trimIndent() generatePackets(testInput).foldIndexed(0) { index, acc, packagePair -> if (packagePair.isRightOrder) acc + (index + 1) else acc }.let { check(it == 13) } val input = readString("Day13.txt") generatePackets(input).foldIndexed(0) { index, acc, packagePair -> if (packagePair.isRightOrder) acc + (index + 1) else acc }.let { println(it) } val dividerPacket1 = PackageData.Arr(listOf(PackageData.Arr(listOf(PackageData.Integer(2))))) val dividerPacket2 = PackageData.Arr(listOf(PackageData.Arr(listOf(PackageData.Integer(6))))) val testGenerated = generatePackets(testInput) val testAllPackets = ArrayList<PackageData.Arr>(testGenerated.size * 2 + 2) testAllPackets.add(dividerPacket1) testAllPackets.add(dividerPacket2) testGenerated.forEach { testAllPackets.add(it.left) testAllPackets.add(it.right) } val testSorted = testAllPackets.sorted() val testPacket1Ix = testSorted.indexOfFirst { it == dividerPacket1 } + 1 val testPacket2Ix = testSorted.indexOfFirst { it == dividerPacket2 } + 1 check(testPacket1Ix * testPacket2Ix == 140) val generated = generatePackets(input) val allPackets = ArrayList<PackageData.Arr>(generated.size * 2 + 2) allPackets.add(dividerPacket1) allPackets.add(dividerPacket2) generated.forEach { allPackets.add(it.left) allPackets.add(it.right) } val sorted = allPackets.sorted() val packet1Ix = sorted.indexOfFirst { it == dividerPacket1 } + 1 val packet2Ix = sorted.indexOfFirst { it == dividerPacket2 } + 1 println(packet1Ix * packet2Ix) } private fun generatePackets(src: String): List<PackagePair> { return src.split("\n\n").map { packets -> val (left, right) = packets.split("\n") // remove first and last brackets val leftArr = buildArr(StringIterator(left.substring(1, left.length - 1))) val rightArr = buildArr(StringIterator(right.substring(1, right.length - 1))) PackagePair( left = leftArr, right = rightArr ) } } private fun buildArr(iterator: StringIterator): PackageData.Arr { val arr = mutableListOf<PackageData>() val charRangeCheck = '0'..'9' while (iterator.hasNext()) { when (val c = iterator.nextChar()) { '[' -> arr.add(buildArr(iterator)) ']' -> break ',' -> Unit in charRangeCheck -> { val peek = iterator.peekNextChar() val intBuilder = StringBuilder(1).append(c.digitToInt()) if (peek != null && peek in charRangeCheck) { val next = iterator.nextChar() intBuilder.append(next.digitToInt()) } arr.add(PackageData.Integer(intBuilder.toString().toInt())) } } } return PackageData.Arr(arr) } class StringIterator( s: String ): CharIterator() { val array = s.toCharArray() var index = 0 override fun hasNext() = index < array.size override fun nextChar() = try { array[index++] } catch (e: ArrayIndexOutOfBoundsException) { index -= 1; throw NoSuchElementException(e.message) } fun peekNextChar(): Char? = array.getOrNull(index) } sealed interface PackageData: Comparable<PackageData> { data class Integer(val int: Int): PackageData, Comparable<PackageData> { override fun compareTo(other: PackageData): Int { return when (other) { is Arr -> this.toArr().compareTo(other) is Integer -> this.int.compareTo(other.int) } } override fun toString(): String { return int.toString() } } data class Arr(val packageData: List<PackageData>): PackageData, Comparable<PackageData> { private fun compare(t: Arr, other: Arr): Int { val maxIx = max(t.packageData.lastIndex, other.packageData.lastIndex) for (i in 0..maxIx) { // t is smaller therefore right order if (t.packageData.lastIndex < i) { return -1 } else if (other.packageData.lastIndex < i) { // t is bigger therefore wrong order return 1 } else { val thisI = t.packageData[i] val otherI = other.packageData[i] if (thisI is Integer && otherI is Integer) { // both ints so can compare. If not equal then we can finish early val comparison = thisI.compareTo(otherI) if (comparison != 0) { return comparison } } else { // mixed types so convert to arrays and compare them val iArr = thisI.toArr() val oArr = otherI.toArr() val comparison = iArr.compareTo(oArr) if (comparison != 0) { return comparison } } } } // fallback return 0... return 0 } override fun compareTo(other: PackageData): Int { return when (other) { is Arr -> compare(this, other) is Integer -> compare(this, other.toArr()) } } override fun toString(): String { return this.packageData.toString() } } } fun PackageData.toArr(): PackageData.Arr = when (this) { is PackageData.Arr -> this is PackageData.Integer -> PackageData.Arr(listOf(this)) } data class PackagePair( val left: PackageData.Arr, val right: PackageData.Arr ) { val isRightOrder get() = left < right override fun toString(): String { return "${left}, $right" } }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
6,368
advent-of-code-2022-kotlin
Apache License 2.0
src/Day05.kt
Totwart123
573,119,178
false
null
import java.util.Stack fun main() { fun part1(input: List<String>): String { val emptyLine = input.indexOfFirst{it.isEmpty()} val stacks = mutableMapOf<Int, ArrayDeque<String>>() val stackInfo = input.subList(0, emptyLine-1).reversed() //no need for the numbers val moveInfo = input.subList(emptyLine +1, input.size) stackInfo.forEach { line -> line.chunked(4).forEachIndexed { index, s -> if(s.isNotEmpty() && s.isNotBlank()){ stacks.getOrPut(index+1) { ArrayDeque() }.addFirst(s.trim().filterNot { it == '[' || it == ']' }) } } } moveInfo.forEach { move -> val splittedMove = move.split(" ") val count = splittedMove[1].toInt() val from = splittedMove[3].toInt() val to = splittedMove[5].toInt() (1..count).forEach { _ -> if(stacks.containsKey(to)){ stacks[from]?.removeFirst()?.let { stacks[to]?.addFirst(it) } } else{ throw IllegalArgumentException("Der Stack existiert nicht.") } } } return stacks.map { it.value.first() }.toList().joinToString("") } fun part2(input: List<String>): String { val emptyLine = input.indexOfFirst{it.isEmpty()} val stacks = mutableMapOf<Int, MutableList<String>>() val stackInfo = input.subList(0, emptyLine-1).reversed() //no need for the numbers val moveInfo = input.subList(emptyLine +1, input.size) stackInfo.forEach { line -> line.chunked(4).forEachIndexed { index, s -> if(s.isNotEmpty() && s.isNotBlank()){ stacks.getOrPut(index+1) { mutableListOf() }.add(s.trim().filterNot { it == '[' || it == ']' }) } } } moveInfo.forEach { move -> val splittedMove = move.split(" ") val count = splittedMove[1].toInt() val from = splittedMove[3].toInt() val to = splittedMove[5].toInt() if(stacks.containsKey(to) && stacks.containsKey(from)){ stacks[from]?.takeLast(count)?.let { stacks[to]?.addAll(it) } stacks[from] = stacks[from]?.take((stacks[from]?.size ?: 0) - count)?.toMutableList()!! } else{ throw IllegalArgumentException("Der Stack existiert nicht.") } } return stacks.map { if(it.value.isEmpty()) "" else it.value.last() }.toList().joinToString("") } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
33e912156d3dd4244c0a3dc9c328c26f1455b6fb
2,851
AoC
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinMatrixFlips.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix * @see <a href="https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix"> * Source</a> */ fun interface MinMatrixFlips { operator fun invoke(mat: Array<IntArray>): Int } class MinMatrixFlipsBFS : MinMatrixFlips { override operator fun invoke(mat: Array<IntArray>): Int { val n = mat.size val m = mat[0].size val dp: HashMap<String, Int> = HashMap() val ans = func(mat, n, m, HashSet(), dp) return if (ans == Int.MAX_VALUE) -1 else ans } fun check(mat: Array<IntArray>, n: Int, m: Int): Boolean { for (i in 0 until n) { for (j in 0 until m) { if (mat[i][j] == 1) return false } } return true } private fun flip(mat: Array<IntArray>, n: Int, m: Int, i: Int, j: Int) { mat[i][j] = mat[i][j] xor 1 if (i - 1 >= 0) mat[i - 1][j] = mat[i - 1][j] xor 1 if (j - 1 >= 0) mat[i][j - 1] = mat[i][j - 1] xor 1 if (i + 1 < n) mat[i + 1][j] = mat[i + 1][j] xor 1 if (j + 1 < m) mat[i][j + 1] = mat[i][j + 1] xor 1 } private fun func(mat: Array<IntArray>, n: Int, m: Int, set: HashSet<String>, dp: HashMap<String, Int>): Int { if (check(mat, n, m)) return 0 var t = "" for (i in 0 until n) { for (j in 0 until m) { t += mat[i][j].toString() } } if (dp.containsKey(t)) return dp[t]!! if (set.contains(t)) return Int.MAX_VALUE set.add(t) var min = Int.MAX_VALUE for (i in 0 until n) { for (j in 0 until m) { flip(mat, n, m, i, j) val small = func(mat, n, m, set, dp) if (small != Int.MAX_VALUE) min = min(min, 1 + small) flip(mat, n, m, i, j) } } set.remove(t) dp[t] = min return min } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,676
kotlab
Apache License 2.0
src/main/kotlin/aoc2023/Day03.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2023 import utils.* class EngineSchematic(val parts: List<String>): ArrayAsSurface(parts) { fun symbols() = indexed() .filter { it.second.isSymbol() } fun numbersTouching(c: Coordinates): Sequence<Int> = c.adjacentIncludeDiagonal() .filter { at(it).isDigit() } .map { expandNumber(it) } .distinct() .map { it.second } fun expandNumber(initial: Coordinates): Pair<Coordinates, Int> { val start = initial.heading(W).takeWhile { checkedAt(it).isDigit() }.last() val number = start.heading(E) .map { checkedAt(it)} .takeWhile { it.isDigit() } .joinToString("") .toInt() return Pair(start, number) } fun Char.isSymbol() = !(isDigit() || (this == '.')) } fun main() { val testInput = """467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...${'$'}.*.... .664.598..""".trimIndent().split("\n") fun part1(input: List<String>): Int { val schematic = EngineSchematic(input) return schematic.symbols() .flatMap { schematic.numbersTouching(it.first) } .sum() } fun part2(input: List<String>): Int { val schematic = EngineSchematic(input) return schematic.symbols() .filter { it.second == '*' } .map { val numbers = schematic.numbersTouching(it.first).toList() if (numbers.size == 2) { numbers[0] * numbers[1] } else { 0 } } .sum() } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 4361) println(part2(testInput)) val puzzleInput = InputUtils.downloadAndGetLines(2023, 3) val input = puzzleInput.toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
2,017
aoc-2022-kotlin
Apache License 2.0
solutions/aockt/y2021/Y2021D10.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2021 import aockt.y2021.Y2021D10.SyntaxCheckResult.* import io.github.jadarma.aockt.core.Solution object Y2021D10 : Solution { /** The possible outcomes of syntax checking the submarine's navigation subsystem. */ private sealed interface SyntaxCheckResult { /** The syntax is valid. */ object Pass : SyntaxCheckResult /** The input contains invalid characters (i.e.: not a brace). */ object Invalid : SyntaxCheckResult /** The input is corrupted, an [illegalChar] was used to close another bracket. */ data class Corrupted(val illegalChar: Char) : SyntaxCheckResult /** The input is incomplete, it ended at a time the [stack] was still not empty. */ data class Incomplete(val stack: CharSequence) : SyntaxCheckResult } /** Maps the brackets to their other pair. */ private val matchingBraceOf: Map<Char, Char> = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') .flatMap { (a, b) -> listOf(a to b, b to a) } .toMap() /** Returns the matching brace of this character, a convenience wrapper over [matchingBraceOf]. */ private val Char.matchingBrace: Char get() = matchingBraceOf[this] ?: throw IllegalArgumentException("Not a brace.") /** Analyzes the [input]'s syntax and returns whether it is valid or the cause of failure. */ private fun checkSyntax(input: String): SyntaxCheckResult = input.fold(ArrayDeque<Char>()) { stack, char -> stack.apply { when (char) { '(', '[', '{', '<' -> stack.addLast(char) ')', ']', '}', '>' -> when (stack.lastOrNull()) { char.matchingBrace -> stack.removeLast() else -> return Corrupted(char) } else -> return Invalid } } }.let { stack -> if (stack.isEmpty()) Pass else Incomplete(stack.joinToString("")) } /** Given the [stack] on an incomplete line, determine the remaining characters. */ private fun completeLine(stack: CharSequence): String = buildString { for (i in stack.indices.reversed()) { append(stack[i].matchingBrace) } } /** Parse the [input] and return a sequence of the lines and their syntax analyses. */ private fun parseInput(input: String): Sequence<Pair<String, SyntaxCheckResult>> = input.lineSequence().map { it to checkSyntax(it) } override fun partOne(input: String): Long = parseInput(input) .map { it.second } .filterIsInstance<Corrupted>() .sumOf { when (it.illegalChar) { ')' -> 3L ']' -> 57L '}' -> 1197L '>' -> 25137L else -> error("Invalid illegal character.") } } override fun partTwo(input: String): Long = parseInput(input) .map { it.second } .filterIsInstance<Incomplete>() .map { completeLine(it.stack).fold(0L) { acc, char -> acc * 5 + ")]}>".indexOf(char) + 1 } } .sorted().toList() .let { it[it.size / 2] } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
3,267
advent-of-code-kotlin-solutions
The Unlicense
src/day03/Code.kt
ldickmanns
572,675,185
false
{"Kotlin": 48227}
package day03 import readInput fun main() { val input = readInput("day03/input") // val input = readInput("day03/input_test") println("asdfasdfasdf".toSet()) println(part1(input)) println(part2(input)) } val Char.priority: Int get() = if (isLowerCase()) { code - 'a'.code + 1 } else code - 'A'.code + 27 fun part1(input: List<String>): Int { var sumOfPriorities = 0 outer@ for (line in input) { val halfLength = line.length / 2 val firstCompartment = line.take(halfLength) val secondCompartment = line.takeLast(halfLength) for (char in firstCompartment) { if (char in secondCompartment) { sumOfPriorities += char.priority continue@outer } } } return sumOfPriorities } fun part2(input: List<String>): Int { var sumOfPriorities = 0 input.windowed( size = 3, step = 3, ) { lines: List<String> -> val charSets = lines.map { it.toSet() } val intersectionChar = charSets[0].intersect(charSets[1]).intersect(charSets[2]).first() sumOfPriorities += intersectionChar.priority } return sumOfPriorities }
0
Kotlin
0
0
2654ca36ee6e5442a4235868db8174a2b0ac2523
1,209
aoc-kotlin-2022
Apache License 2.0
leetcode2/src/leetcode/longest-palindromic-substring.kt
hewking
68,515,222
false
null
package leetcode import kotlin.math.max /** * 5. 最长回文子串 * https://leetcode-cn.com/problems/longest-palindromic-substring/ * @program: leetcode * @description: ${description} * @author: hewking * @create: 2019-04-26 13:39 * * 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 示例 1: 输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。 示例 2: 输入: "cbbd" 输出: "bb" 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-palindromic-substring 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 典型题: 动态规划 题解: https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zui-chang-hui-wen-zi-chuan-by-leetcode/ **/ object LongestPalindromicSubstring { class Solution { /** * 思路: * 暴力法 * 典型动态规划题 */ fun longestPalindrome(s: String): String { var ans = "" if (s.length == 1) { return s } for (i in s.indices) { for (j in i until s.length) { for (k in i .. j) { val subStr = s.substring(i,k + 1) if (isPalindromeStr(subStr)) { ans = if (subStr.length > ans.length) subStr else ans } } } } return ans } fun isPalindromeStr (str: String) : Boolean { var i = 0 var j = str.length - 1 while (i <= j) { if (str[i] != str[j]) { return false } i ++ j -- } return true } /** * 以下为中心拓展算法 * *********************************************** * 思路: * 1. 从某个字符作为中心的位置出发 * 2. 往两边遍历,然后对比是否一致 * 3. 会有两种情况,中心为一个,比如 aba 或者中心在之间的情况 abba 两种情况 * 这样就会有 n + n - 1 = 2 * n -1 个中心 * 4. 找出回文子串最大长度 * 5. 找出在原始字符串中的位置 * 6. 获取最长回文子串 */ fun longestPalindrome2(s: String): String { if (s.isEmpty()) { return s; } var start = 0 var end = 0 for (i in 0 until s.length) { var len = this.expandAroundCenter(s,i,i) val len2 = this.expandAroundCenter(s,i,i + 1) len = max(len, len2) if ( len > end - start) { start = i - (len - 1) / 2 end = i + len / 2 } } return s.substring(start,end) } /** * 获取从中间出发的长度。 */ fun expandAroundCenter(s: String, left: Int,right: Int) : Int{ var L = left var R = right while (L >= 0 && R < s.length && s[L] == s[R]) { L -- R ++ } return R - L - 1 } } } fun main(){ print(LongestPalindromicSubstring.Solution().longestPalindrome("bb")) }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
3,495
leetcode
MIT License
src/main/kotlin/advent/of/code/day07/Solution.kt
brunorene
160,263,437
false
null
package advent.of.code.day07 import java.io.File import java.util.* val lineRegex = Regex("^Step ([A-Z]) must.+step ([A-Z]) can begin.$") fun part1(): String { val dependsOn = mutableMapOf<Char, String>() val steps = TreeSet<Char>() File("day07.txt").readLines().forEach { line -> val res = lineRegex.find(line) steps += res!!.groupValues[1][0] steps += res!!.groupValues[2][0] dependsOn.compute(res!!.groupValues[2][0]) { _, v -> (v ?: "") + res.groupValues[1][0] } } var stepOrder = "" while (steps.isNotEmpty()) { val nextSteps = TreeSet<Char>() nextSteps.addAll(dependsOn.filter { it.value.isEmpty() }.keys.sorted()) nextSteps.addAll(steps.filter { !dependsOn.contains(it) }) val step = nextSteps.first() stepOrder += step steps.remove(step) dependsOn.remove(step) dependsOn.forEach { k, v -> dependsOn[k] = v.replace(step.toString(), "") } } return stepOrder } fun part2(): Int { val dependsOn = mutableMapOf<Char, String>() val steps = TreeSet<Char>() File("day07.txt").readLines().forEach { line -> val res = lineRegex.find(line) steps += res!!.groupValues[1][0] steps += res!!.groupValues[2][0] dependsOn.compute(res!!.groupValues[2][0]) { _, v -> (v ?: "") + res.groupValues[1][0] } } val workerCount = 5 val workers = MutableList(workerCount) { Pair('-', 0) } while (steps.isNotEmpty()) { if (workers.any { it.first != '-' }) { val nextFreeWorker = workers.filter { it.first != '-' }.minBy { it.second } val nextWorker = Pair('-', nextFreeWorker!!.second) workers.remove(nextFreeWorker) workers.add(nextWorker) val lateWorkers = workers.filter { it.second < nextFreeWorker.second } workers.removeAll(lateWorkers) while (workers.size < workerCount) workers.add(nextWorker.copy()) steps.remove(nextFreeWorker.first) dependsOn.remove(nextFreeWorker.first) dependsOn.forEach { k, v -> dependsOn[k] = v.replace(nextFreeWorker.first.toString(), "") } } while (workers.any { it.first == '-' }) { val nextSteps = TreeSet<Char>() nextSteps.addAll(dependsOn.filter { it.value.isEmpty() }.keys.sorted()) nextSteps.addAll(steps.filter { !dependsOn.contains(it) }) workers.forEach { nextSteps.remove(it.first) } if (nextSteps.isEmpty()) break val step = nextSteps.first() val freeWorker = workers.first { it.first == '-' } val newWorker = Pair(step, freeWorker.second + 60 + step.toInt() - 'A'.toInt() + 1) workers.remove(freeWorker) workers.add(newWorker) } } return workers.maxBy { it.second }!!.second }
0
Kotlin
0
0
0cb6814b91038a1ab99c276a33bf248157a88939
2,893
advent_of_code_2018
The Unlicense
src/Day05.kt
ked4ma
573,017,240
false
{"Kotlin": 51348}
typealias Stack<T> = ArrayList<T> /** * [Day05](https://adventofcode.com/2022/day/5) */ fun main() { data class Operation(val num: Int, val from: Int, val to: Int) fun conv(input: List<String>): Pair<List<Stack<Char>>, List<Operation>> { val index = input.indexOfFirst(String::isEmpty) val len = input[index - 1].trim().split("""\s+""".toRegex()).size val stacks = (0 until len).map { Stack<Char>() } for (i in index - 2 downTo 0) { for (j in 1 until input[i].length step 4) { if (input[i][j] != ' ') { stacks[(j - 1) / 4].add(input[i][j]) } } } val operations = (index + 1 until input.size).mapNotNull { i -> """move (\d+) from (\d+) to (\d+)""".toRegex().find(input[i])?.let { val (_, num, from, to) = it.groupValues Operation(num.toInt(), from.toInt() - 1, to.toInt() - 1) } } return Pair(stacks, operations) } fun build(stacks: List<Stack<Char>>): String = buildString { stacks.forEach { it.lastOrNull()?.let { c -> append(c) } } } fun part1(input: List<String>): String { val (stacks, operations) = conv(input) operations.forEach { op -> repeat(op.num) { val c = stacks[op.from].removeLast() stacks[op.to].add(c) } } return build(stacks) } fun part2(input: List<String>): String { val (stacks, operations) = conv(input) operations.forEach { op -> val pos = stacks[op.to].size repeat(op.num) { val c = stacks[op.from].removeLast() stacks[op.to].add(pos, c) } } return build(stacks) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
1
Kotlin
0
0
6d4794d75b33c4ca7e83e45a85823e828c833c62
2,175
aoc-in-kotlin-2022
Apache License 2.0
src/Day18.kt
anilkishore
573,688,256
false
{"Kotlin": 27023}
import java.util.* import kotlin.math.abs fun main() { val input = readInput("Day18") val cubes = input.map { s -> s.split(",").map { it.toInt() } } val cubeSet = cubes.toMutableSet() val max = cubes.flatten().max() + 1 val min = cubes.flatten().min() - 1 fun part1(): Int { var res = cubes.size * 6 for (i in cubes.indices) for (j in i + 1 until cubes.size) { if ((0..2).sumOf { k -> abs(cubes[i][k] - cubes[j][k]) } == 1) res -= 2 } return res } val airVis = mutableSetOf<List<Int>>() fun dfs(start: List<Int>) { val stack = Stack<List<Int>>() stack.add(start) while (stack.isNotEmpty()) { val cube = stack.pop() airVis.add(cube) for (d in listOf(-1, 1)) repeat(3) { k -> val ncube = (0..2).map { i -> cube[i] + if (i == k) d else 0 }.toList() if (ncube.max() <= max && ncube.min() >= min && !cubeSet.contains(ncube) && !airVis.contains(ncube) ) { stack.push(ncube) } } } } fun part2(): Int { dfs(listOf(min, min, min)) return cubes.sumOf { cube -> listOf(-1, 1).map { d -> listOf(0, 1, 2).map { k -> val ncube = (0..2).map { i -> cube[i] + if (i == k) d else 0 }.toList() if (airVis.contains(ncube)) 1 else 0 } }.flatten().sum() } } println(part1()) println(part2()) }
0
Kotlin
0
0
f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9
1,714
AOC-2022
Apache License 2.0
2017/src/main/java/p7/Problem7.kt
ununhexium
113,359,669
false
null
package p7 import com.google.common.io.Resources import more.Input fun main(args: Array<String>) { val input = Input.getFor("p7") val tree = buildTree(input) println("The root is $tree") println(tree.toTree()) println(tree.filter({ !it.isBalanced() })) } val arrow = " -> " val naming = Regex("(?<name>\\p{Lower}+) \\((?<weight>\\p{Digit}+)\\)(?<children> \\-> .*)?") class Program(val name: String, val weight: Int, val children: List<Program>) { fun getTotalWeight(): Int = weight + children.map { it.getTotalWeight() }.sum() fun toTree(depth: Int = 1): String { return this.run { depth.toString() + " ".repeat(depth) + "$name ($weight ${getTotalWeight()})\n" + children.map { it.toTree(depth + 1) }.joinToString(separator = "") { it } } } fun isBalanced(): Boolean { println("Children " + children.joinToString()) val byWeight = children.groupBy { it.getTotalWeight() } // there can only be 1 unbalanced weight val unbalanced = byWeight.filterValues { it.size == 1 }.flatMap { it.value } println(unbalanced) if (unbalanced.isNotEmpty()) { println("Problem at " + unbalanced) /* * There may be at most either 1 or 2 "wrong". * If there are only 2 process, either may be wrong. */ if (unbalanced.size > 1) { /** * Here we may guess which one is actually wrong if it's * not possible to balance the weight of 1 of them. * But the exercise doesn't give any information for that case. */ throw RuntimeException("How am I supposed to guess which one to change? " + unbalanced) } // this only works because there is the assumption that only 1 program is off balance // https://adventofcode.com/2017/day/7 val wrong = unbalanced.first() return !wrong.isBalanced() } else { return true } } override fun toString() = "$name ($weight / ${getTotalWeight()})" fun filter(filter: (Program) -> Boolean): List<Program> { val result = children .flatMap { it.filter(filter) } .toMutableList() if (filter(this)) result.add(this) return result } } data class OrphanProgram( val name: String, val weight: Int, val children: List<String> ) { /** * Converts an orphan program to a real program, given a complete program tree */ fun asProgram(bag: List<OrphanProgram>): Program { return Program( this.name, this.weight, this.children.map { childName -> bag.find { it.name == childName }!!.asProgram(bag) } ) } companion object { /** * Converts a string to an orphan program */ fun from(input: String): OrphanProgram { val matcher = naming.toPattern().matcher(input) if (!matcher.matches()) { throw RuntimeException("broken input for " + input) } val name = matcher.group("name") val weight = matcher.group("weight").toInt() val potentialChildren = matcher.group("children") ?: "" val children: List<String> = if (potentialChildren.isNotEmpty()) { potentialChildren .substring(arrow.length) // remove the arrow .split(", ") } else listOf() return OrphanProgram(name, weight, children) } } } fun buildTree(input: String): Program { val bag = input .split("\n") .sortedBy { if (it.contains(arrow)) 1 else 0 } .map { OrphanProgram.from(it) } .toMutableList() /* * Get the root node. * This is the node which has children but is the child of no other node. */ val children = bag.flatMap { it.children } val root = bag.first { !children.contains(it.name) } return root.asProgram(bag) }
6
Kotlin
0
0
d5c38e55b9574137ed6b351a64f80d764e7e61a9
3,809
adventofcode
The Unlicense
calendar/day12/Day12.kt
starkwan
573,066,100
false
{"Kotlin": 43097}
package day12 import Day import Lines import java.util.Comparator.comparingInt class Day12 : Day() { override fun part1(input: Lines): Any { val dijkstra = Dijkstra( input, cost = { node, other -> if (node.elevation - other.elevation >= -1) 1 else -10000 } ) val processedNodes = dijkstra.findShortestPath(dijkstra.nodes.single { it.symbol == 'S' }) return processedNodes.single { it.symbol == 'E' }.costFromStart } override fun part2(input: Lines): Any { // Find the shortest path starting from the end // Since we are going in reversed way, we provide another the cost function val dijkstraStartFromEnd = Dijkstra( input, cost = { node, other -> if (other.elevation - node.elevation >= -1) 1 else -10000 } ) val originalEnd = dijkstraStartFromEnd.nodes.single { it.symbol == 'E' } val originalStart = dijkstraStartFromEnd.nodes.single { it.symbol == 'S' } val possibleStarts = findPossibleStartNodes(dijkstraStartFromEnd.graph, originalStart) val processedNodes = dijkstraStartFromEnd.findShortestPath(originalEnd) return processedNodes.filter { possibleStarts.contains(it) }.minOf { it.costFromStart } } private fun findPossibleStartNodes(graph: List<List<Node>>, startNode: Node): List<Node> { val candidates = mutableSetOf<Node>() val nodes = mutableSetOf<Node>() val visitedNotes = mutableSetOf<Node>() candidates.add(startNode) while (candidates.isNotEmpty()) { val candidate = candidates.first() candidates.remove(candidate) visitedNotes.add(candidate) if (candidate.elevation != startNode.elevation) { continue } // if the candidate has the same elevation as the startNode, add it to return set nodes.add(candidate) val cIndex = candidate.pos.first val rIndex = candidate.pos.second val row = graph[rIndex] // Also, add the valid unvisited surrounding nodes to the candidate list to process in next interation val rules = listOf( (cIndex > 0) to { row[cIndex - 1] }, (cIndex < row.size - 1) to { row[cIndex + 1] }, (rIndex > 0) to { graph[rIndex - 1][cIndex] }, (rIndex < graph.size - 1) to { graph[rIndex + 1][cIndex] }, ) for ((condition, nodeSupplier) in rules) { if (condition) { val node = nodeSupplier() if (!visitedNotes.contains(node)) { candidates.add(node) } } } } return nodes.toList() } // Dijkstra's algorithm // https://isaaccomputerscience.org/concepts/dsa_search_dijkstra class Dijkstra( input: Lines, val cost: (node: Node, other: Node) -> Int ) { private var visited = mutableListOf<Node>() private var unvisited = mutableListOf<Node>() val graph: List<List<Node>> val nodes: List<Node> get() = visited + unvisited init { graph = input.map { row -> row.toList().map { Node(it) } } graph.forEachIndexed { rIndex, row -> row.forEachIndexed { cIndex, node -> node.pos = cIndex to rIndex val neighbours = mutableListOf<Node>() if (cIndex > 0) neighbours.add(row[cIndex - 1]) if (cIndex < row.size - 1) neighbours.add(row[cIndex + 1]) if (rIndex > 0) neighbours.add(graph[rIndex - 1][cIndex]) if (rIndex < graph.size - 1) neighbours.add(graph[rIndex + 1][cIndex]) node.neighbours = neighbours.filter { cost(node, it) > 0 } } } unvisited = graph.flatten().toMutableList() } fun findShortestPath(startNode: Node): List<Node> { unvisited.single { it == startNode }.costFromStart = 0 // Repeat until there are no more nodes in the unvisited list while (unvisited.isNotEmpty()) { // Get the unvisited node with the lowest cost val currentNode = unvisited.minWith(comparingInt { it.costFromStart }) if (currentNode.costFromStart != Int.MAX_VALUE) { // A node has MAX_VALUE if it is an orphan node. for (neighbour in currentNode.neighbours) { if (visited.contains(neighbour)) { continue } val costFromStart = currentNode.costFromStart + cost(currentNode, neighbour) // Check if the new cost is less if (costFromStart < neighbour.costFromStart) { // Update costFromStart and previous node reference neighbour.costFromStart = costFromStart neighbour.previousNode = currentNode } } } // Add the current node to the visited list visited.add(currentNode) unvisited.remove(currentNode) } return visited } } class Node(var symbol: Char) { var pos: Pair<Int, Int> = -1 to -1 var previousNode: Node? = null var costFromStart = Int.MAX_VALUE var neighbours = emptyList<Node>() val elevation get() = when (symbol) { 'S' -> 'a' 'E' -> 'z' else -> symbol } override fun equals(other: Any?) = if (other is Node) pos == other.pos else false } }
0
Kotlin
0
0
13fb66c6b98d452e0ebfc5440b0cd283f8b7c352
5,910
advent-of-kotlin-2022
Apache License 2.0
kotlin/src/x2022/day5/Day5.kt
freeformz
573,924,591
false
{"Kotlin": 43093, "Go": 7781}
package day5 import readInput fun parseStackInput(stackInput: List<String>): List<ArrayDeque<Char>> { val stacks = stackInput[0].split(" ").mapNotNull { it.ifEmpty { null }?.toInt() }.map { ArrayDeque<Char>() } stackInput.drop(1).forEach { it.chunked(4).forEachIndexed { i, its -> val c = its[1] if (!c.isWhitespace()) { stacks[i].addLast(c) } } } return stacks } fun parseInput(input: List<String>): Pair<List<String>, List<String>> { var moves = false val parts = input.groupBy { if (it.isEmpty()) { moves = true } when (moves) { true -> if (it.isEmpty()) "empty" else "moves" false -> "stacks" } } return Pair( parts["stacks"]?.reversed() ?: throw Exception("invalid input"), parts["moves"] ?: throw Exception("invalid input") ) } fun partOne(stacks: List<ArrayDeque<Char>>, movesInput: List<String>) { for (mi in movesInput) { val mp = mi.split(" ") val qty = mp[1].toInt() val from = mp[3].toInt() val to = mp[5].toInt() val src = stacks[from - 1] val dst = stacks[to - 1] for (i in 1..qty) { dst.addLast(src.removeLast()) } } println(stacks.fold("") { out, stack -> out + stack.last() }) } fun partTwo(stacks: List<ArrayDeque<Char>>, movesInput: List<String>) { for (mi in movesInput) { val mp = mi.split(" ") val qty = mp[1].toInt() val from = mp[3].toInt() val to = mp[5].toInt() val src = stacks[from - 1] val dst = stacks[to - 1] val tmp = ArrayDeque<Char>() for (i in 1..qty) { tmp.addFirst(src.removeLast()) } for (i in tmp) { dst.addLast(i) } } println(stacks.fold("") { out, stack -> out + stack.last() }) } fun main() { val (stackInput, movesInput) = parseInput(readInput("day5")) partOne(parseStackInput(stackInput), movesInput) partTwo(parseStackInput(stackInput), movesInput) }
0
Kotlin
0
0
5110fe86387d9323eeb40abd6798ae98e65ab240
2,137
adventOfCode
Apache License 2.0
src/main/kotlin/algorithms/sorting/quicksort/QuickSort.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package algorithms.sorting.quicksort fun main() { val numbers = intArrayOf(87, 34, 7, 12, 11, 54, 6, 42, 150, 15, 92, 69) val quickSort = QuickSort() quickSort.quickSort(numbers, 0, numbers.size - 1) quickSort.printArray(numbers) } //The QuickSort algorithm is a divide-and-conquer algorithm that sorts an array by partitioning it into two subarrays, // sorting each subarray independently, and then combining the sorted subarrays. The key operation in QuickSort is // partitioning the array. The partitioning step selects a pivot element, rearranges the array so that all elements // less than the pivot come before it, and all elements greater than the pivot come after it. The pivot element is // now in its final position, and the two subarrays on either side of it can be sorted independently. // //The time complexity of QuickSort is O(n log n) in the average case, but can degrade to O(n^2) in the worst case if // the pivot element is consistently chosen poorly. The space complexity of QuickSort is O(log n) due to the recursion // used in the algorithm. class QuickSort { fun quickSort(arr: IntArray, low: Int, high: Int) { if (low < high) { val pIndex = partition(arr, low, high) quickSort(arr, low, pIndex - 1) quickSort(arr, pIndex + 1, high) } } private fun partition(arr: IntArray, low: Int, high: Int): Int { val pivot = arr[high] var i = low - 1 for (j in low until high) { if (arr[j] <= pivot) { i++ // swap arr[i] and arr[j] val temp = arr[i] arr[i] = arr[j] arr[j] = temp } } val temp = arr[i + 1] arr[i + 1] = arr[high] arr[high] = temp return i + 1 } fun printArray(arr: IntArray) { for (value in arr) print("$value ") println() } }
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
1,936
dsa-kotlin
MIT License
src/Day07.kt
vonElfvin
572,857,181
false
{"Kotlin": 11658}
import kotlin.math.abs fun main() { data class Directory( val name: String, val parent: String, val childDirs: MutableSet<String> = mutableSetOf(), var filesSize: Long = 0, var totalSize: Long = 0, ) fun part1(input: List<String>): Long { val dirTree: MutableMap<String, Directory> = mutableMapOf( "/" to Directory("/", "/") ) var current = "/" var candidate = "/" input.drop(1).forEach { line -> when { line == "$ cd .." -> current = dirTree[current]!!.parent line.startsWith("$ cd") -> candidate = current + line.split(' ')[2] + "/" line == "$ ls" -> { current = candidate dirTree[current]!!.filesSize = 0 } line.startsWith("dir") -> { val directory = line.split(' ')[1] val dirPath = "$current$directory/" if (dirTree[dirPath] == null) dirTree[dirPath] = Directory(name = dirPath, parent = current) dirTree[current]!!.childDirs += dirPath } else -> { dirTree[current]!!.filesSize += line.split(' ')[0].toLong() } } } val sortedDirectories = dirTree.values.sortedByDescending { it.name.split('/').size } sortedDirectories.forEachIndexed { currentIndex, currentDir -> currentDir.totalSize += currentDir.filesSize sortedDirectories .filterIndexed { index, dir -> index != currentIndex && dir.childDirs.contains(currentDir.name) } .forEach { it.totalSize += currentDir.totalSize } } val currentSize = dirTree.values.sumOf { it.filesSize } val sizeNeed = abs(70000000 - 30000000 - currentSize) return dirTree.values.filter { it.totalSize >= sizeNeed }.minOf { it.totalSize } } fun part2(input: List<String>): Int { return 0 } val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6210f23f871f646fcd370ec77deba17da4196efb
2,175
Advent-of-Code-2022
Apache License 2.0
yandex/y2022/qual/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package yandex.y2022.qual import kotlin.random.Random fun main() { val (n, _) = readInts() val s = List(n) { readLn().map { "ACGT".indexOf(it) }.toIntArray() } .let { it.plus(IntArray(it[0].size)) } data class Edge(val u: Int, val v: Int, val len: Int) val edges = mutableListOf<Edge>() for (i in s.indices) for (j in 0 until i) { val len = s[i].indices.sumOf { k -> dist(s[i][k], s[j][k]) } edges.add(Edge(i, j, len)) } val dsu = DisjointSetUnion(s.size) var ans = 0 for (edge in edges.sortedBy { it.len }) { if (dsu.unite(edge.u, edge.v)) ans += edge.len } println(ans) } private fun dist(x: Int, y: Int): Int { if (x == y) return 0 if (x xor y == 2) return 2 return 1 } private class DisjointSetUnion(n: Int) { var p: IntArray var r: Random = Random(566) init { p = IntArray(n) clear() } fun clear() { for (i in p.indices) { p[i] = i } } operator fun get(v: Int): Int { if (p[v] == v) { return v } p[v] = get(p[v]) return p[v] } fun unite(v: Int, u: Int): Boolean { val vv = get(v) val uu = get(u) if (vv == uu) return false if (r.nextBoolean()) { p[vv] = uu } else { p[uu] = vv } return true } } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,325
competitions
The Unlicense
src/main/kotlin/days/Pathfinding.kt
andilau
429,206,599
false
{"Kotlin": 113274}
package days import java.util.PriorityQueue fun Map<Point, Boolean>.findPath(from: Point, to: Point? = null): List<Point> { val queue = PriorityQueue<List<Point>>(Comparator.comparing { size }) .apply { add(listOf(from)) } val visited = mutableSetOf<Point>() var longestPath = emptyList<Point>() while (queue.isNotEmpty()) { val path = queue.poll() if (path.last() == to) return path if (path.last() in visited) continue visited += path.last() val next = path.last() .neighbors() .filter { this.getOrDefault(it, false) } .filter { it !in visited } if (next.isEmpty()) { if (path.size > longestPath.size) longestPath = path } next.forEach { queue += path + it } } return longestPath.ifEmpty { error("No path found") } } data class Stride(val turn: Turn, val length: Int) { enum class Turn { LEFT, RIGHT } override fun toString(): String = "${turn.toString().first()}$length" } fun Map<Point, Boolean>.findPathStrides(from: Point, orientation: Point) = sequence { val path = mutableListOf(from) var stride: Stride? = null while (true) { val direction = path .takeLast(2) .takeIf { list -> list.size == 2 } ?.let { list -> list.last() - list.first() } ?: orientation stride = when { path.last() + direction in this@findPathStrides.keys -> { path += (path.last() + direction) stride?.copy(length = stride.length + 1) } path.last() + direction.rotateLeft() in this@findPathStrides.keys -> { path += (path.last() + direction.rotateLeft()) stride?.let { yield(it) } Stride(Stride.Turn.LEFT, 1) } path.last() + direction.rotateRight() in this@findPathStrides.keys -> { path += (path.last() + direction.rotateRight()) stride?.let { yield(it) } Stride(Stride.Turn.RIGHT, 1) } else -> { stride?.let { yield(it) } break } } } }
2
Kotlin
0
0
f51493490f9a0f5650d46bd6083a50d701ed1eb1
2,225
advent-of-code-2019
Creative Commons Zero v1.0 Universal
src/main/kotlin/kt/kotlinalgs/app/graph/KruskalMST.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph println("Test") Solution().test() class Solution { fun test() { //https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/ val vertice0 = Vertice(0) val vertice1 = Vertice(1) val vertice2 = Vertice(2) val vertice3 = Vertice(3) val vertice4 = Vertice(4) val vertice5 = Vertice(5) val vertice6 = Vertice(6) val vertice7 = Vertice(7) val vertice8 = Vertice(8) val graph = WeightedUndirectedGraph( listOf( vertice0, vertice1, vertice2, vertice3, vertice4, vertice5, vertice6, vertice7, vertice8 ) ) graph.addEdge(vertice0, vertice1, 4) graph.addEdge(vertice0, vertice7, 8) graph.addEdge(vertice1, vertice2, 8) graph.addEdge(vertice1, vertice7, 11) graph.addEdge(vertice2, vertice3, 7) graph.addEdge(vertice2, vertice5, 4) graph.addEdge(vertice2, vertice8, 2) graph.addEdge(vertice3, vertice4, 9) graph.addEdge(vertice3, vertice5, 14) graph.addEdge(vertice4, vertice5, 10) graph.addEdge(vertice5, vertice6, 2) graph.addEdge(vertice6, vertice7, 1) graph.addEdge(vertice6, vertice8, 6) graph.addEdge(vertice7, vertice8, 7) val kruskal = Kruskal() val edges = kruskal.minimumSpanningTree(graph) println("Edges:") edges.forEach { println("${it.from.value} - ${it.to.value}: ${it.weight}") } } } // https://www.geeksforgeeks.org/union-find-algorithm-set-2-union-by-rank/ class UnionFind(size: Int) { private val parent = IntArray(size) { it } private val rank = IntArray(size) { 1 } // [0,1,2,3] fun find(component: Int): Int { //println("find: $component, ${parent[component]}") if (component == parent[component]) return component // path compression parent[component] = find(parent[component]) return parent[component] } fun union(first: Int, second: Int) { val firstComponent = find(first) val secondComponent = find(second) if (firstComponent != secondComponent) { // union by rank when { rank[firstComponent] < rank[secondComponent] -> { parent[firstComponent] = secondComponent } rank[secondComponent] < rank[firstComponent] -> { parent[secondComponent] = firstComponent } else -> { parent[secondComponent] = firstComponent rank[firstComponent]++ } } } } } data class Vertice(val value: Int) data class Edge( val from: Vertice, val to: Vertice, val weight: Int ) : Comparable<Edge> { override fun compareTo(other: Edge): Int { return weight - other.weight } } data class WeightedUndirectedGraph(val vertices: List<Vertice>) { var edges: MutableList<Edge> = mutableListOf() fun addEdge(first: Vertice, second: Vertice, weight: Int) { val edge = Edge(first, second, weight) edges.add(edge) } } class Kruskal() { fun minimumSpanningTree(graph: WeightedUndirectedGraph): MutableList<Edge> { val unionFind = UnionFind(graph.vertices.size) val output: MutableList<Edge> = mutableListOf() val edges = graph.edges.toMutableList() edges.sort() // O(E log E) var edgeIndex = 0 while (output.size < graph.vertices.size - 1 && !edgeIndex >= edges.size) { //O(V) val nextEdge = edges[edgeIndex] // O(1) edgeIndex++ // Don't allow cycles if (unionFind.find(nextEdge.from.value) != unionFind.find(nextEdge.to.value)) { unionFind.union(nextEdge.from.value, nextEdge.to.value) output.add(nextEdge) } // O(1) with path compression + weighted UF } // total loop = O(V * log E) // total = O(E log E + V) return output } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
4,159
KotlinAlgs
MIT License
src/day04/Day04.kt
sanyarajan
572,663,282
false
{"Kotlin": 24016}
package day04 import readInput fun main() { fun part1(input: List<String>): Int { var fullyEnclosedRanges = 0 input.forEach { line -> val (rangeStringElf1, rangeStringElf2) = line.split(",") val (rangeStartElf1, rangeEndElf1) = rangeStringElf1.split("-").map { it.toInt() } val (rangeStartElf2, rangeEndElf2) = rangeStringElf2.split("-").map { it.toInt() } if (rangeStartElf1 in rangeStartElf2..rangeEndElf2 && rangeEndElf1 in rangeStartElf2..rangeEndElf2 || rangeStartElf2 in rangeStartElf1..rangeEndElf1 && rangeEndElf2 in rangeStartElf1..rangeEndElf1) { fullyEnclosedRanges++ } } return fullyEnclosedRanges } fun part2(input: List<String>): Int { var partiallyEnclosedRanges = 0 input.forEach { line -> val (rangeStringElf1, rangeStringElf2) = line.split(",") val (rangeStartElf1, rangeEndElf1) = rangeStringElf1.split("-").map { it.toInt() } val (rangeStartElf2, rangeEndElf2) = rangeStringElf2.split("-").map { it.toInt() } if (rangeStartElf1 in rangeStartElf2..rangeEndElf2 || rangeEndElf1 in rangeStartElf2..rangeEndElf2 || rangeStartElf2 in rangeStartElf1..rangeEndElf1 || rangeEndElf2 in rangeStartElf1..rangeEndElf1) { partiallyEnclosedRanges++ } } return partiallyEnclosedRanges } // test if implementation meets criteria from the description, like: val testInput = readInput("day04/Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("day04/day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e23413357b13b68ed80f903d659961843f2a1973
1,714
Kotlin-AOC-2022
Apache License 2.0
src/main/kotlin/com/hopkins/aoc/day19/main.kt
edenrox
726,934,488
false
{"Kotlin": 88215}
package com.hopkins.aoc.day19 import java.io.File const val debug = true const val part = 1 /** Advent of Code 2023: Day 19 */ fun main() { // Step 1: Read the file input val lines: List<String> = File("input/input19.txt").readLines() if (debug) { println("Step 1: Read file") println("=======") println(" num lines: ${lines.size}") } // Step 2: Parse the workflows and parts val workflows = lines.takeWhile { line -> line.isNotBlank() }.map { parseWorkflow(it) }.associateBy { it.label } val parts = lines.dropWhile { line -> line.isNotBlank() }.drop(1).mapIndexed { index, line -> parsePart(index, line) } if (debug) { println("Step 2: Parse workflows and parts") println("=======") println(" num workflows: ${workflows.size}") println(" num parts: ${parts.size}") //parts.forEach { println(it) } //workflows.forEach { println(it) } } var total = 0 for (part in parts) { if (debug) { println("Mapping part: $part") } val start = "in" var current = start print(" ") while (current != "A" && current != "R") { print("$current -> ") val workflow = workflows[current]!! val firstApplies = workflow.inequalities.firstOrNull { it.applies(part) } current = firstApplies?.output ?: workflow.next } print(current) if (current == "A") { val value = part.values.values.sum() print(" value=$value") total += value } println() } print("Total: $total") } fun parsePart(index: Int, line: String): Part { val pieces = line.substring(1, line.length - 1).split(",") val valueMap = pieces.map { piece -> val (left, right) = piece.split("=") left.first() to right.toInt() }.toMap() return Part(index, valueMap) } fun parseWorkflow(line: String): Workflow { val (label, inequalitiesStr) = line.split("{") val inequalityPieces = inequalitiesStr.dropLast(1).split(",") val next = inequalityPieces.last() val inequalities = inequalityPieces.dropLast(1).map { parseInequality(it) } return Workflow(label, inequalities, next) } fun parseInequality(item: String): Inequality { val (left, right) = item.split(":") val operator = left[1] val value = left.first() val quantity = left.substring(2).toInt() return Inequality(value, operator, quantity, right) } data class Workflow(val label: String, val inequalities: List<Inequality>, val next: String) { } data class Inequality(val value: Char, val operator: Char, val quantity: Int, val output: String) { fun applies(part: Part): Boolean { val partValue = part.values[value]!! if (operator == '<' && partValue < quantity) { return true } else if (operator == '>' && partValue > quantity) { return true } return false } } data class Part(val num: Int, val values: Map<Char, Int>) { }
0
Kotlin
0
0
45dce3d76bf3bf140d7336c4767e74971e827c35
3,077
aoc2023
MIT License
2021/src/main/kotlin/Day12.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
class Day12(input: List<String>) { private val connections = input.map { it.split("-") }.flatMap { (begin, end) -> listOf(begin to end, end to begin) } .filterNot { (_, end) -> end == "start" }.groupBy({ it.first }, { it.second }) private fun countPaths( cave: String = "start", path: List<String> = listOf(), smallCaveAllowance: (cave: String, currentPath: List<String>) -> Boolean ): Int { return when { cave == "end" -> 1 cave.isLowerCase() && smallCaveAllowance(cave, path) -> 0 else -> connections.getValue(cave).sumOf { countPaths(it, path + cave, smallCaveAllowance) } } } fun solve1(): Int { return countPaths { cave, currentPath -> cave in currentPath } } fun solve2(): Int { return countPaths { cave, currentPath -> val counts = currentPath.filter { it.isLowerCase() }.groupingBy { it }.eachCount() cave in counts.keys && counts.any { it.value > 1 } } } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
1,054
adventofcode-2021-2025
MIT License
src/main/kotlin/Probability.kt
fcruzel
183,215,777
false
{"Kotlin": 17006, "Java": 6293, "Assembly": 154}
import kotlin.math.ln fun calculateProbability(corpus: List<String>, vocabulary: List<String>): List<Word> { val freq = HashMap<String, Int>() val tokens = makeTokens(corpus).sorted() vocabulary.forEach { word -> freq[word] = appearances(word, tokens) } freq["<UNK>"] = 0 val wordFrecuency = ArrayList<Word>() for ((word, appearances) in freq.toSortedMap(/*compareBy(String.CASE_INSENSITIVE_ORDER) { it }*/)) { val frequency = appearances + 1 // the first 1.0 is the laplacian smooth val totalSize = tokens.size + vocabulary.size + 1.0 // addition of <UNK> val logprob = ln(frequency / totalSize) wordFrecuency.add(Word(word, frequency, logprob)) } return wordFrecuency } fun appearances(word: String, words: List<String>): Int { var appearances = 0 val pos = words.binarySearch(word) return if (pos < 0) { 0 } else { var i = pos - 1 while (i >= 0 && words[i] == word) { appearances++ i-- } i = pos while (i < words.size && words[i] == word) { appearances++ i++ } appearances } }
0
Kotlin
0
0
ecf073f58ff077064b6fc3e021d1f5b54db128b0
1,195
pln-iaa
MIT License
classroom/src/main/kotlin/com/radix2/algorithms/week3/CountingInversionsV2.kt
rupeshsasne
190,130,318
false
{"Java": 66279, "Kotlin": 50290}
package com.radix2.algorithms.week3 import java.util.* // Counting inversions. An inversion in an array a[] is a pair of entries a[i] and a[j] such that i < j but a[i] > a[j]. // Given an array, design a linear arithmetic algorithm to count the number of inversions. fun sort(array: IntArray, aux: IntArray, lo: Int, hi: Int): Long { if (lo >= hi) return 0 val mid = lo + (hi - lo) / 2 var inversions: Long inversions = sort(array, aux, lo, mid) inversions += sort(array, aux, mid + 1, hi) return inversions + merge(array, aux, lo, mid, hi) } fun merge(array: IntArray, aux: IntArray, lo: Int, mid: Int, hi: Int): Long { System.arraycopy(array, lo, aux, lo, (hi - lo) + 1) var i = lo var j = mid + 1 val nextToMid = j var inversions = 0L for (k in lo..hi) { when { i > mid -> array[k] = aux[j++] j > hi -> array[k] = aux[i++] aux[i] > aux[j] -> { array[k] = aux[j++] inversions += nextToMid - i } else -> array[k] = aux[i++] } } return inversions } fun countInversions(array: IntArray): Long { return sort(array, IntArray(array.size), 0, array.size - 1) } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val t = scan.nextLine().trim().toInt() for (tItr in 1..t) { val n = scan.nextLine().trim().toInt() val arr = scan.nextLine().split(" ").map{ it.trim().toInt() }.toIntArray() val result = countInversions(arr) println(result) } }
0
Java
0
1
341634c0da22e578d36f6b5c5f87443ba6e6b7bc
1,584
coursera-algorithms-part1
Apache License 2.0
src/day04/Day04.kt
hamerlinski
572,951,914
false
{"Kotlin": 25910}
package day04 import readInput fun main() { val input = readInput("Day04", "day04") val inputIterator = input.iterator() var solution1 = 0 var solution2 = 0 fun part1and2(input: Iterator<String>) { input.forEach { val elvesAssignmentRanges = it.split(",") val elf0 = Elf(elvesAssignmentRanges[0]) val elf1 = Elf(elvesAssignmentRanges[1]) val pair = Pair(elf0, elf1) if (pair.overlappedCompletely()) { solution1 += 1 } if (pair.overlappedPartially()) { solution2 += 1 } } println("solution1: $solution1") println("solution2: $solution2") } part1and2(inputIterator) } class Elf(private val assignmentRange: String) { fun assignment(): MutableList<Int> { val assignmentList: MutableList<Int> = mutableListOf() val first: Int = assignmentRange.split("-")[0].toInt() val second: Int = assignmentRange.split("-")[1].toInt() for (i in first..second) { assignmentList.add(i) } return assignmentList } } class Pair(private val elf0: Elf, private val elf1: Elf) { fun overlappedCompletely(): Boolean { return (elf0.assignment().contains(elf1.assignment()[0]) && elf0.assignment() .contains(elf1.assignment()[elf1.assignment().lastIndex]) || elf1.assignment().contains(elf0.assignment()[0]) && elf1.assignment() .contains(elf0.assignment()[elf0.assignment().lastIndex])) } fun overlappedPartially(): Boolean { return (elf0.assignment().contains(elf1.assignment()[0]) || elf0.assignment() .contains(elf1.assignment()[elf1.assignment().lastIndex]) || elf1.assignment().contains(elf0.assignment()[0]) || elf1.assignment() .contains(elf0.assignment()[elf0.assignment().lastIndex])) } }
0
Kotlin
0
0
bbe47c5ae0577f72f8c220b49d4958ae625241b0
1,945
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2023/Day03.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2023 import se.saidaspen.aoc.util.* fun main() = Day03.run() object Day03 : Day(2023, 3) { private val map = toMap(input) private val ymax = map.keys.map { it.second }.max() private val xmax = map.keys.map { it.first }.max() override fun part1(): Any { val partIds = mutableListOf<Int>() for (y in 0..ymax) { var num = "" var isPart = false for (x in 0..xmax) { val p = P(x, y) val character = map[p]!! if (character.isDigit()) { num += character if (p.neighbors().filter { map[it] != null } .any { map[it]!! != '.' && !map[it]!!.isLetterOrDigit() }) { isPart = true } } if (!character.isLetterOrDigit() || x == xmax) { if (isPart && num != "") { partIds.add(num.toInt()) } num = "" isPart = false } } } return partIds.sum() } override fun part2(): Any { val partIds = mutableListOf<Int>() val partsLocations = mutableMapOf<P<Int, Int>, Int>() for (y in 0..ymax) { var num = "" var isPart = false for (x in 0..xmax) { val p = P(x, y) val character = map[p]!! if (character.isDigit()) { num += character if (p.neighbors().filter { map[it] != null }.any { map[it]!! != '.' && !map[it]!!.isLetterOrDigit() }) { isPart = true } } if (!character.isLetterOrDigit() || x == xmax) { if (isPart && num != "") { partIds.add(num.toInt()) val partNumRangeShift = if (!character.isLetterOrDigit()) (1.. num.length) else num.indices for (d in partNumRangeShift) { partsLocations[p - P(d, 0)] = num.toInt() } } num = "" isPart = false } } } return map.filter { it.value == '*' } .map { neighbors(it.key).filter { n -> partsLocations.contains(n) }.map { n -> partsLocations[n]!! }.distinct() }.filter { it.size == 2 } .sumOf { it[0] * it[1] } } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,613
adventofkotlin
MIT License
2015/src/main/kotlin/day24.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.mapItems import utils.selections fun main() { Day24.run() } object Day24 : Solution<List<Long>>() { override val name = "day24" override val parser = Parser.intLines.mapItems { it.toLong() } override fun part1(): Long { val targetSize = input.sum() / 3 return (1 .. input.size - 3).firstNotNullOf { firstSize -> input.selections(firstSize).filter { sele -> sele.sum() == targetSize && (1..input.size - 6).any { secondCount -> (input.toSet() - sele.toSet()).toList().selections(secondCount).any { it.sum() == targetSize } } }.minOfOrNull { it.reduce { a, b -> a * b } } } } override fun part2(): Long { val targetSize = input.sum() / 4 return (1 .. input.size - 4).firstNotNullOf { firstSize -> input.selections(firstSize) .filter { sele -> sele.sum() == targetSize } .filter { sele -> val rest = (input.toSet() - sele.toSet()).toList() (1..rest.size).any { rest.selections(it) .filter { sele2 -> sele2.sum() == targetSize } .any { sele2 -> val rest2 = (rest.toSet() - sele2.toSet()).toList() (1..rest2.size).any { rest2.selections(it).any { sele3 -> sele3.sum() == targetSize } } } } } .minOfOrNull { it.reduce { a, b -> a * b } } } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,518
aoc_kotlin
MIT License
src/main/kotlin/github/walkmansit/aoc2020/Day19.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 class Day19(val input: String) : DayAoc<Int, Int> { interface Component { val id: Int fun isTerminal(): Boolean } class Terminal(val value: Char, override val id: Int) : Component { override fun isTerminal() = true } class Reference(val pairs: List<List<Int>>, override val id: Int) : Component { override fun isTerminal() = false } private fun calc(replace: Boolean): Int { val parts = input.split("\n\n") val rules = parts[0].split("\n").toTypedArray() val strings = parts[1].split("\n").toTypedArray() fun mapToPair(rule: String): Pair<Int, String> { val rulesParts = rule.split(": ") var temp = rulesParts[1] if (replace) { if (rule == "8: 42") { temp = "42 | 42 8" } if (rule == "11: 42 31") { temp = "42 31 | 42 11 31" } } return rulesParts[0].toInt() to temp } val sortedArray = rules.map { mapToPair(it) }.sortedBy { it.first }.map { it.second }.toTypedArray() val components = Array<Component>(rules.size) { Terminal('c', -1) } fun getComponent(idx: Int, set: MutableSet<Int> = mutableSetOf()): Int { if (set.contains(idx)) return idx val strRule = sortedArray[idx] if (strRule.length == 3 && strRule[0] == '"') { components[idx] = Terminal(strRule[1], idx) return idx } else { val rulesParts = strRule.split(" | ") val list: MutableList<List<Int>> = mutableListOf() for (part in rulesParts) { val terminals = part.split(" ") set.add(idx) val termIdxs = terminals.asSequence().map { getComponent(it.toInt(), set) }.toList() set.remove(idx) list.add(termIdxs) } components[idx] = Reference(list.toList(), idx) return idx } } fun isValidComponent(component: Component, idx: Int, str: String): List<Int> { fun validateByMult(idx: Int, str: String, list: List<Int>): List<Int> { var currentIdxList = listOf(idx) for (item in list) { var i = currentIdxList.flatMap { isValidComponent(components[item], it, str) } if (i.isNotEmpty()) // valid currentIdxList = i else return listOf() } return currentIdxList } if (component is Terminal) { if (idx >= str.length) return listOf() return if (str[idx] == component.value) listOf(idx + 1) else listOf() } else { val compRef = component as Reference return compRef.pairs.flatMap { validateByMult(idx, str, it) } } } val component = getComponent(0) val pairs = strings.asSequence().map { isValidComponent(components[0], 0, it) to it.length } return pairs.count { it.first.contains(it.second) } } override fun getResultPartOne(): Int { return calc(false) } override fun getResultPartTwo(): Int { return calc(true) } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
3,492
AdventOfCode2020
MIT License
src/Day07.kt
matusekma
572,617,724
false
{"Kotlin": 119912, "JavaScript": 2024}
class Day07 { fun part1(input: List<String>): Int { val directoryFileSizes = mutableMapOf<String, Int>() var currentDirectoryTree = mutableListOf<String>() var currentDirectoryPath = "" for (line in input) { if (line == "$ cd ..") { currentDirectoryTree.removeLast() currentDirectoryPath = currentDirectoryTree.joinToString("-") } else if (line.contains(" cd ")) { currentDirectoryTree.add(line.split(' ')[2]) currentDirectoryPath = currentDirectoryTree.joinToString("-") } else if (line.contains("dir")) { val dirPath = currentDirectoryPath + "-" + line.split(' ')[1] directoryFileSizes[dirPath] = directoryFileSizes.getOrDefault(dirPath, 0) } else if (line.matches(Regex("[0-9]+ .*"))) { directoryFileSizes[currentDirectoryPath] = directoryFileSizes.getOrDefault(currentDirectoryPath, 0) + line.split(' ')[0].toInt() } } val directorySizes = mutableMapOf<String, Int>() directoryFileSizes.entries.forEach { (dirPath, dirSize) -> directorySizes[dirPath] = dirSize directoryFileSizes.entries.forEach { (otherDirPath, otherDirSize) -> if (otherDirPath.contains("$dirPath-")) { directorySizes[dirPath] = directorySizes[dirPath]!! + otherDirSize } } } return directorySizes.filterValues { size -> size <= 100000 }.values.sum() } fun part2(input: List<String>): Int { val directoryFileSizes = mutableMapOf<String, Int>() var currentDirectoryTree = mutableListOf<String>() var currentDirectoryPath = "" for (line in input) { if (line == "$ cd ..") { currentDirectoryTree.removeLast() currentDirectoryPath = currentDirectoryTree.joinToString("-") } else if (line.contains(" cd ")) { currentDirectoryTree.add(line.split(' ')[2]) currentDirectoryPath = currentDirectoryTree.joinToString("-") } else if (line.contains("dir")) { val dirPath = currentDirectoryPath + "-" + line.split(' ')[1] directoryFileSizes[dirPath] = directoryFileSizes.getOrDefault(dirPath, 0) } else if (line.matches(Regex("[0-9]+ .*"))) { directoryFileSizes[currentDirectoryPath] = directoryFileSizes.getOrDefault(currentDirectoryPath, 0) + line.split(' ')[0].toInt() } } val directorySizes = mutableMapOf<String, Int>() directoryFileSizes.entries.forEach { (dirPath, dirSize) -> directorySizes[dirPath] = dirSize directoryFileSizes.entries.forEach { (otherDirPath, otherDirSize) -> if (otherDirPath.contains("$dirPath-")) { directorySizes[dirPath] = directorySizes[dirPath]!! + otherDirSize } } } val neededSpace = 30000000 - (70000000 - directorySizes["/"]!!) return directorySizes.filterValues { size -> size >= neededSpace }.values.min() } } fun main() { val day07 = Day07() val input = readInput("input07_1") println(day07.part1(input)) println(day07.part2(input)) }
0
Kotlin
0
0
744392a4d262112fe2d7819ffb6d5bde70b6d16a
3,380
advent-of-code
Apache License 2.0
src/Day07.kt
cvb941
572,639,732
false
{"Kotlin": 24794}
class FileSystem { sealed class FileOrDirectory(val name: String) { abstract val size: Int } class Directory(name: String, var files: Map<String, FileOrDirectory> = emptyMap()) : FileOrDirectory(name) { override val size: Int get() = files.values.sumOf { it.size } fun allFiles(): List<FileOrDirectory> { return files.values.flatMap { when (it) { is Directory -> it.allFiles() + it is File -> listOf(it) } } } override fun toString(): String { return "Directory $name:\n" + "\t ${files.values.joinToString("\n")}" } } class File(name: String, override val size: Int) : FileOrDirectory(name) { override fun toString(): String { return "File $name ($size)" } } val root = Directory("root") private var currentPath = mutableListOf(root) private val currentDirectory get() = currentPath.last() private fun handleCommand(command: String) { val command = command.trim() if (command.startsWith("cd")) { cd(command.substringAfter("cd")) } } private fun cd(path: String) { val path = path.trim() when (path) { "/" -> { currentPath = mutableListOf(root) } ".." -> { if (currentPath.size > 1) currentPath.removeLast() } else -> { currentPath += currentDirectory.files.getOrDefault(path, Directory(path)) as Directory } } } private fun parseLs(ls: String) { val (first, second) = ls.split(" ") if (first == "dir") { // Is directory currentDirectory.files += second to Directory(second) } else { // Is file currentDirectory.files += second to File(second, first.toInt()) } } fun handleInput(input: String) { if (input.startsWith("$")) { // Is command handleCommand(input.substringAfter("$")) } else { // Is output parseLs(input) } } override fun toString(): String { // Print out the filesystem return root.toString() } } fun main() { fun part1(input: List<String>): Int { val fileSystem = FileSystem() input.forEach { fileSystem.handleInput(it) } // Get directories with at most 100000 val directories = fileSystem.root.allFiles().filterIsInstance<FileSystem.Directory>().filter { it.size <= 100000 } return directories.sumOf { it.size } } fun part2(input: List<String>): Int { val fileSystem = FileSystem() input.forEach { fileSystem.handleInput(it) } // Get all directories val directories = fileSystem.root.allFiles().filterIsInstance<FileSystem.Directory>() val totalSize = fileSystem.root.size val currentFreeSize = 70000000 - totalSize val targetFreeSize = 30000000 val sizeNeeded = targetFreeSize - currentFreeSize val directoryToDelete = directories.sortedBy { it.size }.first { it.size >= sizeNeeded } return directoryToDelete.size } // 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
fe145b3104535e8ce05d08f044cb2c54c8b17136
3,596
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
OskarWalczak
573,349,185
false
{"Kotlin": 22486}
fun main() { val symbolValueMap: Map<Char, Int> = mapOf('A' to 1, 'B' to 2, 'C' to 3, 'X' to 1, 'Y' to 2, 'Z' to 3) fun calculateOutcomeScore(theirSymbol: Char, mySymbol: Char): Int { if(symbolValueMap[theirSymbol] == symbolValueMap[mySymbol]) return symbolValueMap[mySymbol]!! + 3 val diff = symbolValueMap[theirSymbol]?.minus(symbolValueMap[mySymbol]!!) return if(diff == -1 || diff == 2) symbolValueMap[mySymbol]!! + 6 else symbolValueMap[mySymbol]!! } fun part1(input: List<String>): Int { var score: Int = 0 input.forEach{input -> score += calculateOutcomeScore(input[0], input[2]) } return score } fun part2(input: List<String>): Int { var score: Int = 0 input.forEach{line -> if(line[2] == 'X'){ if(line[0] == 'A') score += calculateOutcomeScore(line[0], 'C') if(line[0] == 'B') score += calculateOutcomeScore(line[0], 'A') if(line[0] == 'C') score += calculateOutcomeScore(line[0], 'B') } else if(line[2] == 'Y'){ score += calculateOutcomeScore(line[0], line[0]) } else{ if(line[0] == 'A') score += calculateOutcomeScore(line[0], 'B') if(line[0] == 'B') score += calculateOutcomeScore(line[0], 'C') if(line[0] == 'C') score += calculateOutcomeScore(line[0], 'A') } } 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(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d34138860184b616771159984eb741dc37461705
1,951
AoC2022
Apache License 2.0
src/Day04.kt
chrisjwirth
573,098,264
false
{"Kotlin": 28380}
fun main() { fun rangeAsLowHighInts(range: String): Pair<Int, Int> { val (rangeLow, rangeHigh) = range.split("-") return rangeLow.toInt() to rangeHigh.toInt() } fun rangeContainsOther(range1: String, range2: String): Boolean { val (range1Low, range1High) = rangeAsLowHighInts(range1) val (range2Low, range2High) = rangeAsLowHighInts(range2) return ( (range1Low >= range2Low && range1High <= range2High) || (range2Low >= range1Low && range2High <= range1High)) } fun rangesOverlap(range1: String, range2: String): Boolean { val (range1Low, range1High) = rangeAsLowHighInts(range1) val (range2Low, range2High) = rangeAsLowHighInts(range2) return ( (range1Low in range2Low..range2High) || (range2Low in range1Low..range1High)) } fun part1(input: List<String>): Int { var containedAssignments = 0 input.forEach { val (range1, range2) = it.split(",") if (rangeContainsOther(range1, range2)) containedAssignments++ } return containedAssignments } fun part2(input: List<String>): Int { var overlappingAssignments = 0 input.forEach { val (range1, range2) = it.split(",") if (rangesOverlap(range1, range2)) overlappingAssignments++ } return overlappingAssignments } // Test val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) // Final val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8b1f2a0d0f579dd23fa1dc1f7b156f728152c2d
1,730
AdventOfCode2022
Apache License 2.0
src/adventofcode/blueschu/y2017/day11/solution.kt
blueschu
112,979,855
false
null
package adventofcode.blueschu.y2017.day11 import java.io.File import kotlin.math.max import kotlin.test.assertEquals val input: List<String> by lazy { File("resources/y2017/day11.txt") .bufferedReader() .use { r -> r.readText() } .trim() .split(",") } fun main(args: Array<String>) { assertEquals(3, part1(listOf("ne", "ne", "ne"))) assertEquals(0, part1(listOf("ne", "ne", "sw", "sw"))) assertEquals(2, part1(listOf("ne", "ne", "s", "s"))) assertEquals(3, part1(listOf("se", "sw", "se", "sw", "sw"))) println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } data class Point(var x: Int = 0, var y: Int = 0) enum class HexDirection { NORTH, NORTH_EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, NORTH_WEST } fun parseHexDirection(token: String): HexDirection = when (token) { "n" -> HexDirection.NORTH "ne" -> HexDirection.NORTH_EAST "se" -> HexDirection.SOUTH_EAST "s" -> HexDirection.SOUTH "sw" -> HexDirection.SOUTH_WEST "nw" -> HexDirection.NORTH_WEST else -> throw IllegalArgumentException("token can not be parsed as hex direction: $token") } // see http://keekerdc.com/2011/03/hexagon-grids-coordinate-systems-and-distance-calculations/ // for an explanation of the hexagonal grid system employed class HexGridWalker(private val origin: Point = Point()) { private val position = origin.copy() val distanceFromStart get() = position.hexDistanceFrom(origin) fun walk(dir: HexDirection) = when (dir) { HexDirection.NORTH -> position.y += 1 HexDirection.SOUTH -> position.y -= 1 HexDirection.NORTH_EAST -> position.x += 1 HexDirection.SOUTH_WEST -> position.x -= 1 HexDirection.NORTH_WEST -> { position.x -= 1 position.y += 1 } HexDirection.SOUTH_EAST -> { position.x += 1 position.y -= 1 } } private fun Point.hexDistanceFrom(other: Point) = max(max(x - other.x, y - other.y), -((x - other.x) + (y - other.y))) } fun part1(instructions: List<String>): Int { val walker = HexGridWalker() instructions.map { parseHexDirection(it) }.forEach { walker.walk(it) } return walker.distanceFromStart } fun part2(instructions: List<String>): Int { val walker = HexGridWalker() var peakDistance = Int.MIN_VALUE instructions.map { parseHexDirection(it) }.forEach { walker.walk(it) peakDistance = max(peakDistance, walker.distanceFromStart) } return peakDistance }
0
Kotlin
0
0
9f2031b91cce4fe290d86d557ebef5a6efe109ed
2,548
Advent-Of-Code
MIT License
src/main/kotlin/kt/kotlinalgs/app/dynprog/StackOfBoxes.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.dynprog println("Test") val boxes = listOf( Box(5, 7, 5), Box(1, 3, 1), Box(2, 4, 3), // not include Box(3, 5, 3), // include Box(4, 6, 4) ) println(Solution().maxHeight(boxes)) // 7 + 3 + 5 + 6 = 21 // 1. Achung: Versuchen für memo arguments zu verringern // zb nur index statt index + lastWidth + lastDepth .. in dem Fall zb vor Aufruf und in Wrapper method auf valid checken! // 2. auch maxHeight nicht nötig mitzugeben, kann in rec. Method ausgerechnet werden!! // schema immer: max = 0. // for x in .. : max = Math.max(max, rec(..)). // ev. max += cur // 3. und wenn möglich start bei index 0, nicht -1!! lieber mehr code/extra loop in wrapper! data class Box( val width: Int, val height: Int, val depth: Int ) class Solution { // create max height stack, where each below box is strictly smaller in width, height and depth // with memo: O(N) runtime + space .. bzw. O(N log N) wegen sorting // without memo: O(N^2) runtime fun maxHeight(boxes: List<Box>): Int { // 1. sort by height decreasing (eliminate 1 dimension) val sorted = boxes.sortedByDescending { it.height } println(sorted) val memo = IntArray(boxes.size) { -1 } // try each start box var max = 0 for (index in boxes.indices) { max = maxOf(max, maxHeightRec(sorted, index, memo)) } return max /* for each box: include (if valid - check width + depth) not include fun maxHeightRec(boxes, index, lastWidth, lastDepth, sumHeight) BC: if (index == boxes.size) return sumHeight include box (if valid - check width + depth) not include box */ } private fun maxHeightRec( boxes: List<Box>, index: Int, memo: IntArray ): Int { //if (index == boxes.size) return sumHeight // BC if (memo[index] != -1) return memo[index] //println("$index: $sumHeight") val curBox = boxes[index] var maxHeight = 0 for (nextBoxIndex in index + 1 until boxes.size) { val nextBox = boxes[nextBoxIndex] if (isValid(curBox, nextBox)) { val heightIncludingBox = maxHeightRec( boxes, nextBoxIndex, memo ) maxHeight = maxOf(maxHeight, heightIncludingBox) } } memo[index] = curBox.height + maxHeight return memo[index] } private fun isValid(cur: Box?, nextBox: Box): Boolean { val curBox = cur ?: return true return nextBox.width < curBox.width && nextBox.depth < curBox.depth && nextBox.height < curBox.height } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
2,788
KotlinAlgs
MIT License
src/aoc2023/Day04.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2023 import readInput fun main() { val regex = "Card[^:]+:([^|]+)\\|([^|]+)".toRegex() fun part1(lines: List<String>): Int { var sum = 0 for (line in lines) { val matches = regex.findAll(line) val winning = matches.first().groupValues[1].trim().split("\\s+".toRegex()).map { it.toInt() }.toSet() val mine = matches.first().groupValues[2].trim().split("\\s+".toRegex()).map { it.toInt() }.toSet() val wins = winning.intersect(mine).size if (wins > 0) { sum += (1 shl (wins - 1)) } } return sum } fun part2(lines: List<String>): Int { val copies = Array(lines.size) { 1 } for ((index, line) in lines.withIndex()) { val matches = regex.findAll(line) val winning = matches.first().groupValues[1].trim().split("\\s+".toRegex()).map { it.toInt() }.toSet() val mine = matches.first().groupValues[2].trim().split("\\s+".toRegex()).map { it.toInt() }.toSet() val wins = winning.intersect(mine).size for (i in (index + 1)..(index + wins)) { if (i < copies.size) { copies[i] += copies[index] } } } return copies.sum() } println(part1(readInput("aoc2023/Day04_test"))) println(part1(readInput("aoc2023/Day04"))) println(part2(readInput("aoc2023/Day04_test"))) println(part2(readInput("aoc2023/Day04"))) }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
1,520
advent-of-code-kotlin
Apache License 2.0
kotlin/1162-as-far-from-land-as-possible.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
// BFS solution class Solution { fun maxDistance(grid: Array<IntArray>): Int { fun isValid(i: Int, j: Int) = i in (0..grid.lastIndex) && j in (0..grid[0].lastIndex) && grid[i][j] == 0 val q = ArrayDeque<Pair<Int, Int>>() var distance = -1 for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 1) q.add(i to j) } } while (q.isNotEmpty()) { distance++ val size = q.size repeat (size) { val (i,j) = q.poll() for (dir in dirs) { val nextI = i + dir[0] val nextJ = j + dir[1] if (isValid(nextI, nextJ)) { q.add(nextI to nextJ) grid[nextI][nextJ] = 1 } } } } return if (distance > 0) distance else -1 } val dirs = arrayOf( intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0) ) } //DP solution class Solution { fun maxDistance(grid: Array<IntArray>): Int { val defaultValue = 100 + 100 + 1 for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 1) continue grid[i][j] = defaultValue if(i > 0) grid[i][j] = minOf(grid[i][j], grid[i - 1][j] + 1) if(j > 0) grid[i][j] = minOf(grid[i][j], grid[i][j - 1] + 1) } } var res = 0 for (i in grid.lastIndex downTo 0) { for (j in grid[0].lastIndex downTo 0) { if (grid[i][j] == 1) continue if(i < grid.lastIndex) grid[i][j] = minOf(grid[i][j], grid[i + 1][j] + 1) if(j < grid[0].lastIndex) grid[i][j] = minOf(grid[i][j], grid[i][j + 1] + 1) res = maxOf(res, grid[i][j]) } } return if (res == defaultValue) -1 else res - 1 } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
2,081
leetcode
MIT License
src/2022/Day02.kt
bartee
575,357,037
false
{"Kotlin": 26727}
fun main() { val winning_combo_lookup = mapOf("rock" to "scissors", "scissors" to "paper", "paper" to "rock") val shape_score_lookup = mapOf("rock" to 1, "paper" to 2, "scissors" to 3) fun charToShape(input: String): String{ val rockArray = arrayOf("A", "X") val paperArray = arrayOf("B", "Y") val scissorArray = arrayOf("C", "Z") if ( rockArray.contains(input)){ return "rock" } if ( paperArray.contains(input)){ return "paper" } if (scissorArray.contains(input)){ return "scissors" } return "Unknown" } fun doIWin(me:String, opponent: String): String { if (me == opponent) { return "draw" } var winning = winning_combo_lookup.get(opponent) if (me != winning) { return "me" } return "opponent" } fun getScoreByResponse(response: String, counterShape: String): Int{ var shapeScore = 0 var matchScore = 0 if (response == "Y") { shapeScore = shape_score_lookup.getOrDefault(counterShape,0) matchScore = 3 } if (response == "X") { // you should lose, so I should not have the current or the winning shape val myShape = winning_combo_lookup.get(counterShape) shapeScore = shape_score_lookup.getOrDefault(myShape,0) } if (response == "Z") { // you should win val lookupPos = winning_combo_lookup.values.indexOf(counterShape) val myShape = winning_combo_lookup.keys.elementAt(lookupPos) shapeScore = shape_score_lookup.getOrDefault(myShape,0) matchScore = 6 } return matchScore + shapeScore } fun scoreRound(me: String, opponent: String): Int { var score = 0 var winner = doIWin(me, opponent) if (winner == "draw") { score = 3 } else if (winner == "me" ){ score = 6 } val shapeScore = shape_score_lookup.getOrDefault(me,0) score += shapeScore return score } fun part1(input: List<String>): Int { var score = 0 input.map{ var entries = it.split(" ") var player1_choice = charToShape(entries[0]) var player2_choice = charToShape(entries[1]) var res = scoreRound(player2_choice, player1_choice) score += res } return score } fun part2(input: List<String>): Int { var score = 0 input.map { var entries = it.split(" ") var player1_choice = charToShape(entries[0]) var roundRes = getScoreByResponse(entries[1], player1_choice) score += roundRes } return score } // test if implementation meets criteria from the description, like: val test_input = readInput("resources/day02_example") check(part1(test_input) == 15) check(part2(test_input) == 12) // Calculate the results from the input: val input = readInput("resources/day02_dataset") println("Total score by shape: " + part1(input)) println("Total score by outcome: " + part2(input)) }
0
Kotlin
0
0
c7141d10deffe35675a8ca43297460a4cc16abba
2,906
adventofcode2022
Apache License 2.0
src/Day12.kt
fouksf
572,530,146
false
{"Kotlin": 43124}
import java.io.File import java.lang.Exception import kotlin.math.abs fun main() { fun parseInput(input: String): List<List<String>> { return input.split("\n") .filter { it != "" } .map { line -> line.split("").filter { it != "" } } } fun shouldVisit( p: Pair<Int, Int>, grid: List<List<String>>, visited: List<Pair<Int, Int>>, current: Pair<Int, Int> ): Boolean { return p.first in grid.indices && p.second in grid[p.first].indices && !visited.contains(p) && grid[current.first][current.second][0].code - grid[p.first][p.second][0].code > -2 } fun findHighGround( grid: List<List<String>>, start: Pair<Int, Int>, end: Pair<Int, Int>, visited: MutableList<Pair<Int, Int>> ): Int { val toVisit = ArrayDeque<Pair<Int, Int>>() val distances = HashMap<Pair<Int, Int>, Int>() toVisit.add(start) distances[start] = 0 while (!toVisit.isEmpty()) { val currentPoint = toVisit.removeFirst() visited.add(currentPoint) if (currentPoint == end) { if (distances.contains(currentPoint)) { return distances[currentPoint]!! } throw Exception("something went wrong") } else { for (p in listOf( Pair(currentPoint.first - 1, currentPoint.second), Pair(currentPoint.first + 1, currentPoint.second), Pair(currentPoint.first, currentPoint.second - 1), Pair(currentPoint.first, currentPoint.second + 1) )) { if (shouldVisit(p, grid, visited, currentPoint)) { if (!toVisit.contains(p)) { toVisit.add(p) } if (!distances.contains(p) || distances[p]!! > distances.getOrDefault( currentPoint, Int.MAX_VALUE ) + 1 ) { distances[p] = distances.getOrDefault(currentPoint, -2) + 1 } } } } } return Int.MAX_VALUE } fun fixThingy(thingy: String): String { if (thingy == "S") { return "a" } else if (thingy == "E") { return "z" } return thingy } fun part1(grid: List<List<String>>): Int? { var start: Pair<Int, Int>? = null var end: Pair<Int, Int>? = null for (i in grid.indices) { for (j in grid[i].indices) { if (grid[i][j] == "S") { start = Pair(i, j) } if (grid[i][j] == "E") { end = Pair(i, j) } } } if (start == null || end == null) { throw Exception("ko stana tuka we") } val newGrid = grid.map { line -> line.map { fixThingy(it) } } val visited = mutableListOf<Pair<Int, Int>>() return findHighGround(newGrid, start, end, visited) } fun part2(grid: List<List<String>>): Int? { var end: Pair<Int, Int>? = null for (i in grid.indices) { for (j in grid[i].indices) { if (grid[i][j] == "E") { end = Pair(i, j) } } } if (end == null) { throw Exception("ko stana tuka we") } val newGrid = grid.map { line -> line.map { fixThingy(it) } } val distances = HashMap<Pair<Int, Int>, Int>() for (i in grid.indices) { for (j in grid[i].indices) { if (grid[i][j] == "a") { val start = Pair(i, j) val visited = mutableListOf<Pair<Int, Int>>() distances[start] = findHighGround(newGrid, start, end!!, visited) } } } return distances.values.toList().min() } // test if implementation meets criteria from the description, like: val testInput = parseInput(File("src", "Day12_test.txt").readText()) println(part1(testInput)) println(part2(testInput)) val input = parseInput(File("src", "Day12.txt").readText()) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
701bae4d350353e2c49845adcd5087f8f5409307
4,522
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day007.kt
ruffCode
398,923,968
false
null
import kotlin.time.measureTimedValue object Day007 { internal val testInput = """ light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags. """.trimIndent().trim().split(newLine) internal val testInputPart2 = """ shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags. """.trimIndent().trim().split(newLine) private val input = PuzzleInput("day007.txt").readText().trim().split(newLine) private const val SG = "shiny gold" private val regex = Regex("""(.bags)|(.bag)|(\.)""") private val digitsReg = """\d+""".toRegex() private const val bagsReg = """bags?\.?""" internal fun List<String>.toBags(): Bags = associate { val (first, second) = it.replace(regex, "").trim() .split(" contain ") val containsBags = second.split(", ") if (containsBags.first().contains("no other")) first to emptyMap() else first.trim() to second.split(", ") .associate { v -> digitsReg.replace(v, "").trim() to digitsReg.findAll(v).first().value.toInt() } } // very inefficient private fun Bags.possibleColors( bagName: String, result: Set<String> = emptySet(), ): Set<String> { return filterKeys { it !in result }.filterValues { it.containsKey(bagName) }.keys.run { val acc = this + result acc + flatMap { possibleColors(it, acc) } } } internal fun Bags.total(bagName: String): Int { val bag = getOrDefault(bagName, emptyMap()) if (bag.isEmpty()) return 0 var total = 0 for (b in bag) { total += b.value + b.value * total(b.key) } return total } private fun buildBagTreeOne(): Map<Color, Set<String>> { val rules = hashMapOf<Color, Rule>() input.forEach { line -> val (parent, allChildren) = line.replace(Regex("""\d+"""), "") .replace(Regex("""bags?\.?"""), "") .split("contain") .map { it.trim() } val childrenColors = allChildren.split(',').map { it.trim() }.toSet() for (childColor in childrenColors) { rules.compute(childColor) { _, current -> if (current == null) setOf(parent) else current + parent } } } return rules } private fun findContainersDFSOne(rules: Map<Color, Rule>): Set<Color> { var known = setOf(SG) var next = setOf(SG) + rules.getValue(SG) while (true) { val toFind = next - known if (toFind.isEmpty()) break known = known + next next = toFind.mapNotNull { rules[it] }.flatten().toSet() } return known - SG } private fun buildBagTreeTwo(): Map<Color, Rule> { val rules = hashMapOf<Color, Rule>() input.forEach { line -> val (parent, allChildren) = line.replace(Regex(bagsReg), "") .split("contain") .map { it.trim() } val rule = if (allChildren.contains("no other")) emptySet() else allChildren.split(',').map { it.trim() }.toSet() rules[parent] = rule } return rules } private fun Map<Color, Rule>.getChildrenCountBFS(color: Color): Int { val children = getOrDefault(color, setOf()) if (children.isEmpty()) return 0 var total = 0 for (child in children) { val count = digitsReg.findAll(child).first().value.toInt() val bag = digitsReg.replace(child, "").trim() total += count + count * getChildrenCountBFS(bag) } return total } fun partOne(): Int = input.toBags().possibleColors(SG).size fun partTwo(): Int = input.toBags().total(SG) fun partOneTree(): Int { val rules: Map<Color, Rule> = buildBagTreeOne() val containers = findContainersDFSOne(rules) return containers.size } fun partTwoTree(): Int { val rules = buildBagTreeTwo() return rules.getChildrenCountBFS(SG) } @JvmStatic fun main(args: Array<String>) { measureTimedValue { partOne() }.also { println("part one result: ${it.value}") println("took ${it.duration.inWholeMicroseconds}") } measureTimedValue { partOneTree() }.also { println("part one tree result: ${it.value}") println("took ${it.duration.inWholeMicroseconds}") } measureTimedValue { partTwo() }.also { println("part two result: ${it.value}") println("took ${it.duration.inWholeMicroseconds}") } measureTimedValue { partTwoTree() }.also { println("part two tree result: ${it.value}") println("took ${it.duration.inWholeMicroseconds}") } } } typealias Bags = Map<String, Container> typealias Container = Map<String, Int> typealias Color = String typealias Rule = Set<String>
0
Kotlin
0
0
477510cd67dac9653fc61d6b3cb294ac424d2244
5,981
advent-of-code-2020-kt
MIT License
src/Day02.kt
robinpokorny
572,434,148
false
{"Kotlin": 38009}
/* Move - enum and utils */ private enum class Move { ROCK, PAPER, SCISSORS; } private fun scoreMove(mine: Move) = when (mine) { Move.ROCK -> 1 Move.PAPER -> 2 Move.SCISSORS -> 3 } private fun toMove(input: String) = when (input) { "A", "X" -> Move.ROCK "B", "Y" -> Move.PAPER "C", "Z" -> Move.SCISSORS else -> throw Exception("Unsupported move") } private val winningRounds = mapOf( Move.ROCK to Move.PAPER, Move.PAPER to Move.SCISSORS, Move.SCISSORS to Move.ROCK ) private val losingRounds = winningRounds.entries.associate { (k, v) -> v to k } /* Outcome - enum and utils */ enum class Outcome { WIN, LOSE, DRAW } private fun scoreOutcome(outcome: Outcome) = when (outcome) { Outcome.WIN -> 6 Outcome.DRAW -> 3 Outcome.LOSE -> 0 } private fun toOutcome(input: String) = when (input) { "X" -> Outcome.LOSE "Y" -> Outcome.DRAW "Z" -> Outcome.WIN else -> throw Exception("Unsupported outcome") } /* Parse input */ private fun parse(input: List<String>): List<Pair<String, String>> = input .map { it.split(" ") } .map { it[0] to it[1] } /* Part 1 */ private fun scoreRoundMoveMove(round: Pair<Move, Move>): Int { val (theirs, mine) = round val outcome = when (mine) { theirs -> Outcome.DRAW winningRounds[theirs] -> Outcome.WIN else -> Outcome.LOSE } return scoreMove(mine) + scoreOutcome(outcome) } private fun calcTotalScoreMoveMove(rounds: List<Pair<String, String>>): Int = rounds .map { (first, second) -> toMove(first) to toMove(second) } .sumOf(::scoreRoundMoveMove) /* Part 2 */ private fun scoreRoundMoveOutcome(round: Pair<Move, Outcome>): Int { val (theirs, outcome) = round val mine: Move = when (outcome) { Outcome.DRAW -> theirs Outcome.WIN -> winningRounds[theirs]!! Outcome.LOSE -> losingRounds[theirs]!! } return scoreMove(mine) + scoreOutcome(outcome) } private fun calcTotalScoreMoveOutcome(rounds: List<Pair<String, String>>): Int = rounds .map { (first, second) -> toMove(first) to toOutcome(second) } .sumOf(::scoreRoundMoveOutcome) fun main() { val input = parse(readDayInput(2)) val testInput = parse(rawTestInput) // PART 1 assertEquals(calcTotalScoreMoveMove(testInput), 15) println("Part1: ${calcTotalScoreMoveMove(input)}") // PART 2 assertEquals(calcTotalScoreMoveOutcome(testInput), 12) println("Part2: ${calcTotalScoreMoveOutcome(input)}") } private val rawTestInput = """ A Y B X C Z """.trimIndent().lines()
0
Kotlin
0
2
56a108aaf90b98030a7d7165d55d74d2aff22ecc
2,595
advent-of-code-2022
MIT License
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day18.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.adventofcode.twentytwenty fun List<String>.day18Part1(): Long = this.map { it.split(" ").filter { it.isNotBlank() } } .map { it.calculateBasic() } .sum() private fun List<String>.calculateBasic(): Long { when { this.size == 1 -> { return this.first().toLong() } this[0].startsWith("(") -> { val closingExpressionIndex = this.indexOfClosingParenthesis() val subExpression = this.subList(1, closingExpressionIndex - 1).toMutableList() subExpression.add(0, this[0].drop(1)) subExpression.add(this[closingExpressionIndex - 1].dropLast(1)) val subExpressionResult = subExpression.calculateBasic().toString() return (listOf(subExpressionResult) + this.drop(closingExpressionIndex)).calculateBasic() } this[2].startsWith("(") -> { val closingExpressionIndex = this.drop(2).indexOfClosingParenthesis() + 1 val subExpression = this.subList(3, closingExpressionIndex).toMutableList() subExpression.add(0, this[2].drop(1)) subExpression.add(this[closingExpressionIndex].dropLast(1)) val subExpressionResult = subExpression.calculateBasic().toString() val expressionResult = calculateNumbers(this[0], this[1], subExpressionResult) return (listOf(expressionResult) + this.drop(closingExpressionIndex + 1)).calculateBasic() } else -> { val tmpResult = calculateNumbers(this[0], this[1], this[2]) return (listOf(tmpResult) + this.drop(3)).calculateBasic() } } } private fun List<String>.indexOfClosingParenthesis(): Int { var index = 0 var openParenthesis = 0 do { if (this[index].contains("(")) { openParenthesis += this[index].count { it == '(' } } else if (this[index].contains(")")) { openParenthesis -= this[index].count { it == ')' } } index++ } while (openParenthesis != 0) return index } private fun calculateNumbers(firstValue: String, operator: String, secondValue: String): String = when (operator) { "+" -> firstValue.toLong() + secondValue.toLong() "-" -> firstValue.toLong() - secondValue.toLong() "*" -> firstValue.toLong() * secondValue.toLong() "/" -> firstValue.toLong() / secondValue.toLong() else -> throw IllegalArgumentException("Unknown Operator") }.toString()
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
2,504
AdventOfCode
MIT License
src/main/kotlin/co/csadev/advent2022/Day13.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 13 * Problem Description: http://adventofcode.com/2021/day/13 */ package co.csadev.advent2022 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsText class Day13(override val input: String = resourceAsText("22day13.txt")) : BaseDay<String, Int, Int> { private val packets = input.split("\n\n").map { it.lines().map { l -> Packet(l) } } override fun solvePart1() = packets.indices.filter { packets[it].run { first() > last() } }.sumOf { it + 1 } private val newPackets = listOf("[[2]]", "[[6]]") override fun solvePart2(): Int { val mPackets = packets.flatten().toMutableList().apply { addAll(newPackets.map { Packet(it) }) }.sorted().reversed() return mPackets.indices.filter { newPackets.contains(mPackets[it].str) } .fold(1) { acc, p -> acc * (p + 1) } } } class Packet(val str: String) : Comparable<Packet> { private val children = mutableListOf<Packet>() private var integer = true var value = 0 init { var packet = str if (packet == "[]") { value = -1 } if (!packet.startsWith("[")) { value = packet.toInt() } else { packet = packet.substring(1, packet.length - 1) var depth = 0 var curr = "" for (c in packet) { if (c == ',' && depth == 0) { children.add(Packet(curr)) curr = "" } else { depth += if (c == '[') 1 else if (c == ']') -1 else 0 curr += c } } if (curr != "") { children.add(Packet(curr)) } integer = false } } override fun compareTo(other: Packet): Int { return if (integer && other.integer) { return other.value - value } else if (!integer && !other.integer) { (0 until children.size.coerceAtMost(other.children.size)).mapNotNull { val value = children[it].compareTo(other.children[it]) if (value != 0) { value } else { null } }.firstOrNull() ?: (other.children.size - children.size) } else { val lst1 = if (integer) Packet("[$value]") else this val lst2 = if (other.integer) Packet("[" + other.value + "]") else other lst1.compareTo(lst2) } } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,615
advent-of-kotlin
Apache License 2.0
src/Day21.kt
anisch
573,147,806
false
{"Kotlin": 38951}
import kotlin.math.abs enum class Job { TIMES, PLUS, MINUS, DIV } open class MonkeyJob(val name: String) class MonkeyNumber( name: String, var number: Long, ) : MonkeyJob(name) class MonkeyOperation( name: String, val a: String, val b: String, val job: Job, ) : MonkeyJob(name) fun getMonkeyJobs(input: List<String>) = input .map { line -> val name = line.substringBefore(":") if (line.matches("[a-zA-Z]{4}: [a-zA-Z]{4} [-+*/] [a-zA-Z]{4}".toRegex())) { val op = line.substringAfter(": ").split(" ") val job = when (op[1]) { "*" -> Job.TIMES "/" -> Job.DIV "+" -> Job.PLUS "-" -> Job.MINUS else -> error("wtf???") } MonkeyOperation(name, op[0], op[2], job) } else { MonkeyNumber(name, line.substringAfter(": ").toLong()) } } fun doJob(monkeyJob: List<MonkeyJob>, node: MonkeyJob?): Long = when (node) { null -> 0 is MonkeyNumber -> node.number is MonkeyOperation -> { val ma = monkeyJob.find { it.name == node.a } val mb = monkeyJob.find { it.name == node.b } when (node.job) { Job.PLUS -> doJob(monkeyJob, ma) + doJob(monkeyJob, mb) Job.MINUS -> doJob(monkeyJob, ma) - doJob(monkeyJob, mb) Job.TIMES -> doJob(monkeyJob, ma) * doJob(monkeyJob, mb) Job.DIV -> doJob(monkeyJob, ma) / doJob(monkeyJob, mb) } } else -> error("wtf???") } fun main() { fun part1(input: List<String>): Long { val monkeyJobs = getMonkeyJobs(input) val root = monkeyJobs.find { it.name == "root" } return doJob(monkeyJobs, root) } fun part2(input: List<String>): Long { val monkeyJobs = getMonkeyJobs(input) val root = monkeyJobs.find { it.name == "root" } as MonkeyOperation val rootA = monkeyJobs.find { it.name == root.a } val rootB = monkeyJobs.find { it.name == root.b } val human = monkeyJobs.find { it.name == "humn" } as MonkeyNumber do { val sumA = doJob(monkeyJobs, rootA) val sumB = doJob(monkeyJobs, rootB) val isNotEqual = sumA != sumB if (isNotEqual) { // simple bruteforce val diff = abs(sumA - sumB) when { diff <= 10_000 -> human.number++ diff <= 100_000 -> human.number += 100 diff <= 1_000_000 -> human.number += 1_000 diff <= 10_000_000 -> human.number += 10_000 diff <= 100_000_000 -> human.number += 100_000 diff <= 1_000_000_000 -> human.number += 1_000_000 diff <= 10_000_000_000 -> human.number += 10_000_000 diff <= 100_000_000_000 -> human.number += 100_000_000 diff <= 1_000_000_000_000 -> human.number += 1_000_000_000 else -> human.number += 10_000_000_000 } } } while (isNotEqual) return human.number } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") val input = readInput("Day21") check(part1(testInput) == 152L) println(part1(input)) check(part2(testInput) == 301L) println(part2(input)) }
0
Kotlin
0
0
4f45d264d578661957800cb01d63b6c7c00f97b1
3,540
Advent-of-Code-2022
Apache License 2.0
src/Day03.kt
rbraeunlich
573,282,138
false
{"Kotlin": 63724}
fun main() { fun assignPoints(c: Char): Int { val lowercase = ('a'..'z').toList() val uppercase =('A'..'Z').toList() val i = if (lowercase.contains(c)) { lowercase.indexOf(c) + 1 } else { uppercase.indexOf(c) + 27 } // println(i) return i } fun part1(input: List<String>): Int { var sum = 0 for (line in input){ val firstCompartment = line.take(line.length / 2) val secondCompartment = line.takeLast(line.length / 2) // println(firstCompartment) // println(secondCompartment) for (c in firstCompartment) { if (secondCompartment.contains(c)) { sum += assignPoints(c) break } } } return sum } fun findBadge(group: List<String>): Char { group[0].forEach { c -> if(group[1].contains(c) && group[2].contains(c)) { return c } } throw RuntimeException() } fun part2Rec(group: List<String>, remainder: List<String>): Int { return if(group.isEmpty()) { 0 } else { val badge: Char = findBadge(group) val point = assignPoints(badge) point + part2Rec(remainder.take(3), remainder.drop(3)) } } fun part2(input: List<String>): Int { return part2Rec(input.take(3), input.drop(3)) } // 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
1
3c7e46ddfb933281be34e58933b84870c6607acd
1,787
advent-of-code-2022
Apache License 2.0
src/day11/Day11.kt
molundb
573,623,136
false
{"Kotlin": 26868}
package day11 import readInput fun main() { val input = readInput(parent = "src/day11", name = "Day11_input") println(solvePartOne(input)) println(solvePartTwo(input)) } private fun solvePartTwo(input: List<String>): Long { val monkeys = mutableListOf<Monkey>() var divisibleMod = 1L var i = 0 val monkeyInfoSize = 7 while (i < input.size) { val items = input[i + 1].split(": ")[1].split(", ").map { it.toLong() } val operation = input[i + 2].split(' ')[6] val operationVal = input[i + 2].split(' ')[7] val divisibleBy = input[i + 3].split(' ')[5].toInt() divisibleMod *= divisibleBy val ifTrue = input[i + 4].split(' ')[9].toInt() val ifFalse = input[i + 5].split(' ')[9].toInt() monkeys.add( Monkey( items = items.toMutableList(), operation = getOperation(operation, operationVal), test = Test(divisibleBy, ifTrue, ifFalse) ) ) i += monkeyInfoSize } repeat(10000) { for (m in monkeys) { for (item in m.items) { val new = m.operation(item) % divisibleMod if (new % m.test.divisibleBy == 0L) { monkeys[m.test.ifTrue].items.add(new) } else { monkeys[m.test.ifFalse].items.add(new) } } m.inspections += m.items.size.toLong() m.items.clear() } } monkeys.sortByDescending { it.inspections } return monkeys[0].inspections * monkeys[1].inspections } private fun solvePartOne(input: List<String>): Long { val monkeys = mutableListOf<Monkey>() var i = 0 val monkeyInfoSize = 7 while (i < input.size) { val items = input[i + 1].split(": ")[1].split(", ").map { it.toLong() } val operation = input[i + 2].split(' ')[6] val operationVal = input[i + 2].split(' ')[7] val divisibleBy = input[i + 3].split(' ')[5].toInt() val ifTrue = input[i + 4].split(' ')[9].toInt() val ifFalse = input[i + 5].split(' ')[9].toInt() monkeys.add( Monkey( items = items.toMutableList(), operation = getOperation(operation, operationVal), test = Test(divisibleBy, ifTrue, ifFalse) ) ) i += monkeyInfoSize } repeat(20) { for (m in monkeys) { for (item in m.items) { m.inspections++ val new = m.operation(item) / 3 if (new % m.test.divisibleBy == 0L) { monkeys[m.test.ifTrue].items.add(new) } else { monkeys[m.test.ifFalse].items.add(new) } } m.items.clear() } } monkeys.sortByDescending { it.inspections } return monkeys[0].inspections * monkeys[1].inspections } private fun getOperation(operation: String, operationVal: String) = if (operation == "+") { if (operationVal == "old") { add2() } else { add(operationVal.toLong()) } } else { if (operationVal == "old") { multiply2() } else { multiply(operationVal.toLong()) } } private fun add(x: Long): (Long) -> Long = { old: Long -> x + old } private fun add2(): (Long) -> Long = { old: Long -> old + old } private fun multiply(x: Long): (Long) -> Long = { old: Long -> x * old } private fun multiply2(): (Long) -> Long = { old: Long -> old * old } data class Monkey( var inspections: Long = 0, val items: MutableList<Long>, val operation: (Long) -> Long, val test: Test, ) data class Test( val divisibleBy: Int, val ifTrue: Int, val ifFalse: Int, )
0
Kotlin
0
0
a4b279bf4190f028fe6bea395caadfbd571288d5
3,870
advent-of-code-2022
Apache License 2.0
src/day02/Day02.kt
TimberBro
572,681,059
false
{"Kotlin": 20536}
package day02 import readInput fun main() { fun part1(input: List<String>): Int { val result = input.stream() .map { it.split(" ") } .map { (a, b) -> when (a to b) { "A" to "X" -> 1 + 3 "A" to "Y" -> 2 + 6 "A" to "Z" -> 3 + 0 "B" to "X" -> 1 + 0 "B" to "Y" -> 2 + 3 "B" to "Z" -> 3 + 6 "C" to "X" -> 1 + 6 "C" to "Y" -> 2 + 0 "C" to "Z" -> 3 + 3 else -> error(a to b) } }.reduce { t, u -> t + u }.orElseThrow() return result } fun part2(input: List<String>): Int { val result = input.stream() .map { it.split(" ") } .map { (a, b) -> when (a to b) { "A" to "X" -> 3 + 0 "A" to "Y" -> 1 + 3 "A" to "Z" -> 2 + 6 "B" to "X" -> 1 + 0 "B" to "Y" -> 2 + 3 "B" to "Z" -> 3 + 6 "C" to "X" -> 2 + 0 "C" to "Y" -> 3 + 3 "C" to "Z" -> 1 + 6 else -> error(a to b) } }.reduce { t, u -> t + u }.orElseThrow() return result } val testInput = readInput("day02/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
516a98e5067d11f0e6ff73ae19f256d8c1bfa905
1,615
AoC2022
Apache License 2.0
src/main/kotlin/day3/Day3.kt
Arch-vile
317,641,541
false
null
package day3 import readFile data class Terrain(val pattern: List<List<Char>>) { fun isThereATree(location: Coordinate): Boolean = pattern[location.y][location.x % pattern[0].size] == '#' fun isThisTheBottom(location: Coordinate): Boolean = location.y + 1 == pattern.size } data class Coordinate(var x: Int, var y: Int) { fun add(xOffset: Int, yOffset: Int): Coordinate = Coordinate(x + xOffset, y + yOffset) } typealias SlopeFunction = (Coordinate) -> Coordinate data class Tobogga(val slope: SlopeFunction, var location: Coordinate) { fun move() { location = slope(location) } } fun main(args: Array<String>) { val terrain = Terrain(loadTerrainFromFile()) val toboggas = listOf( createTobogga { current -> current.add( 1, 1) }, createTobogga { current -> current.add( 3, 1) }, createTobogga { current -> current.add( 5, 1) }, createTobogga { current -> current.add( 7, 1) }, createTobogga { current -> current.add( 1, 2) }) var totalTreeCount = toboggas.map { countTreesOnPath(terrain, it) }.reduce { acc, i -> acc * i } println(totalTreeCount) } private fun countTreesOnPath(terrain: Terrain, it: Tobogga): Int { var treeCount = 0 while (!terrain.isThisTheBottom(it.location)) { it.move() if (terrain.isThereATree(it.location)) { treeCount++ } } return treeCount } private fun createTobogga(slope: SlopeFunction): Tobogga { return Tobogga( slope, Coordinate(0, 0)) } fun loadTerrainFromFile(): List<List<Char>> = readFile("./src/main/resources/day3Input.txt") .map { it.toCharArray().asList() }
0
Kotlin
0
0
12070ef9156b25f725820fc327c2e768af1167c0
1,738
adventOfCode2020
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year20/Day16.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year20 import com.grappenmaker.aoc.* import java.util.PriorityQueue fun PuzzleSet.day16() = puzzle(day = 16) { val (rulesPart, yourPart, othersPart) = input.doubleLines().map(String::lines) data class Rule(val name: String, val firstRange: IntRange, val secondRange: IntRange) fun Rule.isValid(value: Int) = value in firstRange || value in secondRange val rules = rulesPart.map { l -> val (name, rest) = l.split(": ") val (r1, r2) = rest.split(" or ").map { r -> val (a, b) = r.split("-").map(String::toInt) a..b } Rule(name, r1, r2) } val otherTickets = othersPart.drop(1).map { it.split(",").map(String::toInt) } partOne = otherTickets.sumOf { ticket -> ticket.sumOf { v -> if (rules.none { it.isValid(v) }) v else 0 } }.s() val us = yourPart[1].split(",").map(String::toInt) val valid = otherTickets.filter { t -> t.all { v -> rules.any { it.isValid(v) } } }.plusElement(us) fun solve(): List<String> { val initial = rules to emptyList<String>() val seen = hashSetOf(initial) val queue = PriorityQueue(compareBy<Pair<List<Rule>, List<String>>> { it.first.size }) .also { it.offer(initial) } queue.drain { (left, found) -> if (left.isEmpty()) return found else { val currIdx = found.size left.forEach { next -> if (valid.all { t -> next.isValid(t[currIdx]) }) { val n = left - next to found + next.name if (seen.add(n)) queue.offer(n) } } } } error("Impossible") } val found = solve() partTwo = found.withIndex().filter { "departure" in it.value }.map { us[it.index].toLong() }.product().s() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,875
advent-of-code
The Unlicense
src/Day03.kt
alex-rieger
573,375,246
false
null
fun main() { fun splitIntoCompartment(s: String): Pair<String, String> { val half = s.length / 2 return Pair(s.substring(0, half), s.substring(half, s.length)) } fun toIterableChars(i: String): Iterable<Char> { return i.toCharArray().asIterable() } fun toPriority(i: Char): Int { if (i.isUpperCase()) { return i.code.minus(38) } return i.code.minus(96) } fun part1(input: List<String>): Int { return input.map { splitIntoCompartment(it) }.map { compartments -> val (first, second) = compartments toIterableChars(first).intersect(toIterableChars(second)) }.flatten().map { toPriority(it) }.reduce { acc, priority -> acc + priority } } fun part2(input: List<String>): Int { return input.chunked(3).map { chunk -> val (first, second, third) = chunk toIterableChars(first).intersect(toIterableChars(second)).intersect(toIterableChars(third)) }.flatten().map { toPriority(it) }.reduce { acc, priority -> acc + priority } } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
77de0265ff76160e7ea49c9b9d31caa1cd966a46
1,216
aoc-2022-kt
Apache License 2.0
2021/src/main/kotlin/sh/weller/aoc/Day04.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.aoc object Day04 : SomeDay<String, Int> { override fun partOne(input: List<String>): Int { val drawnNumbers: List<Int> = input.first().getDrawnNumbers() var boards: List<List<List<Pair<Int, Boolean>>>> = input.drop(2).toBoards() for (drawnNumber in drawnNumbers) { boards = boards.map { it.markNumberOnBoard(drawnNumber) } for (board in boards) { if (board.hasBingo()) { val sumUnmarked = board.flatten().filter { !it.second }.sumOf { it.first } return sumUnmarked * drawnNumber } } } return 0 } private fun String.getDrawnNumbers(): List<Int> = split(",") .map { it.toInt() } private fun List<String>.toBoards(): List<List<List<Pair<Int, Boolean>>>> = filter { it.isNotBlank() } .chunked(5) .map { board -> board.map { line -> line.split(" ").filter { it.isNotBlank() } .map { number -> number.toInt() to false } } } private fun List<List<Pair<Int, Boolean>>>.markNumberOnBoard(drawnNumber: Int) = map { line -> line.map { (number, marked) -> if (number == drawnNumber) { number to true } else { number to marked } } } private fun List<List<Pair<Int, Boolean>>>.hasBingo(): Boolean = this.checkHorizontalLines() || this.checkVerticalLines() private fun List<List<Pair<Int, Boolean>>>.checkHorizontalLines(): Boolean { this.forEach { line -> if (line.isBingoLine()) { return true } } return false } private fun List<List<Pair<Int, Boolean>>>.checkVerticalLines(): Boolean { repeat(this.size) { index -> val line = this.map { it[index] } if (line.isBingoLine()) { return true } } return false } private fun List<Pair<Int, Boolean>>.isBingoLine(): Boolean = map { it.second } .reduce { first, second -> first && second } override fun partTwo(input: List<String>): Int { val drawnNumbers: List<Int> = input.first().getDrawnNumbers() var boards: List<List<List<Pair<Int, Boolean>>>> = input.drop(2).toBoards() for (drawnNumber in drawnNumbers) { if(boards.size > 1) { boards = boards .map { it.markNumberOnBoard(drawnNumber) } .filter { it.hasBingo().not() } }else{ boards = boards.map { it.markNumberOnBoard(drawnNumber) } if(boards.first().hasBingo()){ val sumUnmarked = boards.first().flatten().filter { !it.second }.sumOf { it.first } return sumUnmarked * drawnNumber } } } return 0 } }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
3,072
AdventOfCode
MIT License
src/Day14.kt
PascalHonegger
573,052,507
false
{"Kotlin": 66208}
fun main() { data class Point(val x: Int, val y: Int) { operator fun rangeTo(other: Point) = buildList { val fromX = minOf(x, other.x) val toX = maxOf(x, other.x) val fromY = minOf(y, other.y) val toY = maxOf(y, other.y) for (newX in fromX..toX) { for (newY in fromY..toY) { add(Point(x = newX, y = newY)) } } } } fun String.toPoint() = split(',').let { (x, y) -> Point(x = x.toInt(), y = y.toInt()) } fun String.toCorners() = split(" -> ").map { it.toPoint() } fun String.toPoints() = toCorners().zipWithNext().flatMap { (start, end) -> start..end } fun List<String>.toSetOfPoints() = flatMap { it.toPoints() }.toSet() val sandStartingPoint = Point(x = 500, y = 0) fun simulateSand(fixedPoints: Set<Point>, abyss: Int): Int { val points = fixedPoints.toMutableSet() var didPlaceSand: Boolean do { didPlaceSand = false var sandPos = sandStartingPoint while (sandPos.y < abyss) { val currentPos = sandPos // Move Down sandPos = sandPos.copy(y = sandPos.y + 1) if(sandPos !in points) { continue } // Move Down Left sandPos = sandPos.copy(x = sandPos.x - 1) if(sandPos !in points) { continue } // Move Down Right sandPos = sandPos.copy(x = sandPos.x + 2) if(sandPos !in points) { continue } // Sand cannot move anymore -> Place it didPlaceSand = points.add(currentPos) break } } while (didPlaceSand) return points.size - fixedPoints.size } fun part1(input: List<String>): Int { val fixedPoints = input.toSetOfPoints() val abyss = fixedPoints.maxOf { it.y } return simulateSand(fixedPoints = fixedPoints, abyss = abyss) } fun part2(input: List<String>): Int { val fixedPoints = input.toSetOfPoints() val abyss = fixedPoints.maxOf { it.y } + 2 val floor = Point(x = 0, y = abyss)..Point(x = 1000, y = abyss) return simulateSand(fixedPoints = fixedPoints + floor, abyss = abyss) } val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2215ea22a87912012cf2b3e2da600a65b2ad55fc
2,635
advent-of-code-2022
Apache License 2.0
src/Day11.kt
maciekbartczak
573,160,363
false
{"Kotlin": 41932}
fun main() { fun part1(input: String): Long { return simulateMonkeys(input, 20, true) } fun part2(input: String): Long { return simulateMonkeys(input, 10000, false) } val testInput = readInputAsString("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158) val input = readInputAsString("Day11") println(part1(input)) println(part2(input)) } private fun simulateMonkeys(input: String, nRounds: Int, inspectionAffectsWorryLevel: Boolean): Long { val monkeyLines = input.split("\n\n") val monkeys = monkeyLines. map { Monkey(it, inspectionAffectsWorryLevel) } val supermodulo = monkeys .map { it.testNumber.toLong() } .reduce { acc, i -> acc * i } repeat(nRounds) { processRound(monkeys, supermodulo) } return monkeys .map { it.inspectedTimes } .sortedDescending() .take(2) .reduce { acc, i -> acc * i} } private fun processRound(monkeys: List<Monkey>, supermodulo: Long) { monkeys.forEach { val toRemove = mutableListOf<Long>() for (i in it.items.indices) { val (item, target) = it.getThrowTarget(i, supermodulo) monkeys[target].items.add(item) toRemove.add(item) } it.items.removeAll { value -> value in toRemove } toRemove.clear() } } private class Monkey( monkey: String, val inspectionAffectsWorryLevel: Boolean ) { val items = mutableListOf<Long>() val operation: (old: Long) -> Long val outcomes: List<Int> val testNumber: Long var inspectedTimes: Long = 0 init { val lines = monkey.split("\n") items.addAll(parseItems(lines[1])) operation = parseOperation(lines[2]) testNumber = parseTest(lines[3]) outcomes = parseOutcomes(lines[4], lines[5]) } private fun parseOutcomes(ifTrue: String, ifFalse: String): List<Int> { return listOf( ifTrue.last().digitToInt(), ifFalse.last().digitToInt() ) } private fun parseTest(line: String): Long { val startIndex = line.indexOf(':') val test = line .substring(startIndex + 1) .trim() .split(" ") val operation = test[0] val value = test[2].toLong() return when (operation) { "divisible" -> value else -> { throw IllegalStateException() } } } private fun parseOperation(line: String): (old: Long) -> Long { val startIndex = line.indexOf(':') val function = line .substring(startIndex + 1) .trim() .split("= ")[1] val components = function.split(" ") val operation = components[1] val operationValue = components[2] return { old -> val value = if (operationValue == "old") { old } else { operationValue.toLong() } when (operation) { "+" -> old + value "-" -> old - value "*" -> old * value "/" -> old / value else -> { throw IllegalStateException() } } } } private fun parseItems(line: String): List<Long> { val startIndex = line.indexOf(':') val items = line.substring(startIndex + 1).trim() return items .split(", ") .map { it.toLong() } } fun getThrowTarget(i: Int, supermodulo: Long): Pair<Long, Int> { inspectedTimes++ var worryLevel = items[i] worryLevel = if (inspectionAffectsWorryLevel) { operation(worryLevel) / 3 } else { operation(worryLevel) % supermodulo } items[i] = worryLevel return if (items[i] % testNumber == 0L) { items[i] to outcomes[0] } else { items[i] to outcomes[1] } } }
0
Kotlin
0
0
53c83d9eb49d126e91f3768140476a52ba4cd4f8
4,042
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/TopologicalSortAdjList.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.graph import java.util.* // Use Edge from {AdjacencyList.class} //data class Edge(val source: Int, val dest: Int, val weight: Int) fun dfs( i: Int, at: Int, visited: Array<Boolean>, ordering: Array<Int>, graph: MutableMap<Int, MutableList<Edge>> ): Int { visited[at] = true var te = i val edges = graph[at] if (edges != null) { for (edge in edges) { if (!visited[edge.dst]) { te = dfs(i, edge.dst, visited, ordering, graph) } } } ordering[i] = at return te - 1 } fun topologicalSort(graph: MutableMap<Int, MutableList<Edge>>, numOfNode: Int): Array<Int> { val ordering = Array<Int>(numOfNode) { 0 } val visited = Array<Boolean>(numOfNode) { false } var i = numOfNode - 1 for (at in 0 until numOfNode) { if (!visited[at]) { i = dfs(i, at, visited, ordering, graph) } } return ordering } fun dagShortestPath(graph: MutableMap<Int, MutableList<Edge>>, start: Int, numNodes: Int): Array<Int> { val topSort = topologicalSort(graph, numNodes) val distance = Array<Int>(numNodes) { -1 } distance[start] = 0 for (i in 0 until numNodes) { val nodeIdx = topSort[i] if (distance[nodeIdx] != -1) { val adjacencyList = graph[nodeIdx] if (adjacencyList != null) { for (edge in adjacencyList) { val newDest = distance[nodeIdx] + edge.weight if (distance[edge.dst] == null) distance[edge.dst] = newDest else distance[edge.dst] = kotlin.math.min(distance[edge.dst], newDest) } } } } return distance } // Example usage of topological sort fun main(args: Array<String>) { // Graph setup val N = 7 val graph = mutableMapOf<Int, MutableList<Edge>>() for (i in 0 until N) graph[i] = ArrayList() graph[0]!!.add(Edge(0, 1, 3)) graph[0]!!.add(Edge(0, 2, 2)) graph[0]!!.add(Edge(0, 5, 3)) graph[1]!!.add(Edge(1, 3, 1)) graph[1]!!.add(Edge(1, 2, 6)) graph[2]!!.add(Edge(2, 3, 1)) graph[2]!!.add(Edge(2, 4, 10)) graph[3]!!.add(Edge(3, 4, 5)) graph[5]!!.add(Edge(5, 4, 7)) val ordering = topologicalSort(graph, N) // // Prints: [6, 0, 5, 1, 2, 3, 4] println(ordering) // Finds all the shortest paths starting at node 0 val dists = dagShortestPath(graph, 0, N) // Find the shortest path from 0 to 4 which is 8.0 println(dists[4]) // Find the shortest path from 0 to 6 which // is null since 6 is not reachable! println(dists[6]) }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
2,687
DS_Algo_Kotlin
MIT License
src/main/kotlin/days/aoc2015/Day13.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2015 import days.Day // Bob would lose 31 happiness units by sitting next to David. class Day13: Day(2015, 13) { override fun partOne(): Any { val people = LinkedHashSet<Person>() val edges = LinkedHashSet<PreferenceEdge>() inputList.map { Regex("(\\w+) would (\\w+) (\\d+) happiness units by sitting next to (\\w+).").matchEntire(it)?.destructured?.let { (subject, disposition, amount, target) -> val subjectPerson = people.find { it.name == subject } ?: Person(subject) val targetPerson = people.find { it.name == target } ?: Person(target) people.add(subjectPerson) people.add(targetPerson) edges.add(PreferenceEdge(subjectPerson, targetPerson, if (disposition == "lose") amount.toInt().unaryMinus() else amount.toInt())) } } return permute(people.toList()).map { listOfPeople -> listOfPeople.mapIndexed { index, person -> val left = when (index) { 0 -> listOfPeople.last() else -> listOfPeople[index - 1] } val right = when (index) { listOfPeople.size - 1 -> listOfPeople.first() else -> listOfPeople[index + 1] } ((edges.find { it.from == person && it.to == left }?.amount ?: 0) + (edges.find { it.from == person && it.to == right }?.amount ?: 0)) }.sum() }.maxOrNull()!! } fun permute(people: List<Person>): List<List<Person>> { if (people.size == 1) { return listOf(people) } val permutations = mutableListOf<List<Person>>() val toInsert = people[0] for (perm in permute(people.drop(1))) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) permutations.add(newPerm) } } return permutations } override fun partTwo(): Any { val people = LinkedHashSet<Person>() val edges = LinkedHashSet<PreferenceEdge>() inputList.map { Regex("(\\w+) would (\\w+) (\\d+) happiness units by sitting next to (\\w+).").matchEntire(it)?.destructured?.let { (subject, disposition, amount, target) -> val subjectPerson = people.find { it.name == subject } ?: Person(subject) val targetPerson = people.find { it.name == target } ?: Person(target) people.add(subjectPerson) people.add(targetPerson) edges.add(PreferenceEdge(subjectPerson, targetPerson, if (disposition == "lose") amount.toInt().unaryMinus() else amount.toInt())) } } val me = Person("Brian") people.forEach { person -> edges.add(PreferenceEdge(me, person, 0)) edges.add(PreferenceEdge(person, me, 0)) } people.add(me) return permute(people.toList()).map { listOfPeople -> listOfPeople.mapIndexed { index, person -> val left = when (index) { 0 -> listOfPeople.last() else -> listOfPeople[index - 1] } val right = when (index) { listOfPeople.size - 1 -> listOfPeople.first() else -> listOfPeople[index + 1] } ((edges.find { it.from == person && it.to == left }?.amount ?: 0) + (edges.find { it.from == person && it.to == right }?.amount ?: 0)) }.sum() }.maxOrNull()!! } class Person(val name: String) class PreferenceEdge(val from: Person, val to: Person, val amount: Int) }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
3,789
Advent-Of-Code
Creative Commons Zero v1.0 Universal