path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/days/Day19.kt | nuudles | 316,314,995 | false | null | package days
class Day19 : Day(19) {
sealed class Rule {
data class Letter(val char: String) : Rule()
data class RuleSet(val rules: List<List<Int>>) : Rule()
}
private val rules: Map<Int, Rule> by lazy {
val rules = mutableMapOf<Int, Rule>()
inputString
.split("\n\n")
.first()
.split("\n")
.forEach { line ->
line
.split(":")
.let { components ->
rules[components[0].toInt()] = when {
components[1] == " \"a\"" -> Rule.Letter("a")
components[1] == " \"b\"" -> Rule.Letter("b")
else -> Rule.RuleSet(
components[1]
.trim()
.split("|")
.map { ruleList ->
ruleList
.trim()
.split(" ")
.map { it.toInt() }
}
)
}
}
}
return@lazy rules
}
private fun possibleStrings(ruleNumber: Int): Set<String> {
return when (val rule = rules[ruleNumber] ?: return setOf()) {
is Rule.Letter ->
setOf(rule.char)
is Rule.RuleSet ->
rule
.rules
.fold(setOf()) { set, subRules ->
set + subRules
.map { possibleStrings(it) }
.fold(setOf("")) { subset, possibleStrings ->
val newSet = mutableSetOf<String>()
possibleStrings.forEach { possibleString ->
subset.forEach {
newSet.add(it + possibleString)
}
}
newSet
}
}
}
}
override fun partOne(): Any {
val possibleStrings = possibleStrings(0)
return inputString
.split("\n\n")
.last()
.split("\n")
.count { possibleStrings.contains(it) }
}
override fun partTwo(): Any {
val rule42Set = possibleStrings(42)
val rule31Set = possibleStrings(31)
val rule42Pattern = rule42Set.joinToString("|")
val rule31Pattern = rule31Set.joinToString("|")
val regex = Regex("""^(?:$rule42Pattern)+(?:${
(1..11)
.joinToString("|") { count ->
"(?:$rule42Pattern){$count}(?:$rule31Pattern){$count}$"
}
})$"""
)
return inputString
.split("\n\n")
.last()
.split("\n")
.count { regex.matches(it) }
}
} | 0 | Kotlin | 0 | 0 | 5ac4aac0b6c1e79392701b588b07f57079af4b03 | 3,149 | advent-of-code-2020 | Creative Commons Zero v1.0 Universal |
advanced-algorithms/kotlin/src/fP1PrecFMax.kt | nothingelsematters | 135,926,684 | false | {"Jupyter Notebook": 7400788, "Java": 512017, "C++": 378834, "Haskell": 261217, "Kotlin": 251383, "CSS": 45551, "Vue": 37772, "Rust": 34636, "HTML": 22859, "Yacc": 14912, "PLpgSQL": 10573, "JavaScript": 9741, "Makefile": 8222, "TeX": 7166, "FreeMarker": 6855, "Python": 6708, "OCaml": 5977, "Nix": 5059, "ANTLR": 4802, "Logos": 3516, "Perl": 2330, "Mustache": 1527, "Shell": 1105, "MATLAB": 763, "M": 406, "Batchfile": 399} | import java.io.File
import java.math.BigInteger
import java.util.Scanner
private fun scheduleP1PrecFMax(
times: List<Int>,
functions: List<(Int) -> BigInteger>,
prec: Map<Int, List<Int>>,
): Pair<BigInteger, List<Int>> {
val n = times.size
val children = MutableList(n) { 0 }
prec.forEach { (_, row) -> row.forEach { i -> children[i] += 1 } }
val excluded = (0 until n).toMutableSet()
var p = times.sum()
val reverseSchedule = MutableList(n) { 0 }
for (k in n - 1 downTo 0) {
val j = excluded.asSequence().filter { children[it] == 0 }.minBy { functions[it](p) }
excluded.remove(j)
reverseSchedule[k] = j
p -= times[j]
prec[j]?.forEach { children[it] -= 1 }
}
val schedule = MutableList(n) { 0 }
reverseSchedule.fold(0) { sum, it ->
schedule[it] = sum
sum + times[it]
}
val fMaxMin = (0 until n)
.maxOfOrNull { functions[it](schedule[it] + times[it]) } ?: 0.toBigInteger()
return fMaxMin to schedule
}
fun main() {
val inputFile = Scanner(File("p1precfmax.in").bufferedReader())
val n = inputFile.nextInt()
val times = List(n) { inputFile.nextInt() }
val functions = List(n) {
val m = inputFile.nextInt()
val coefficients = List(m + 1) { inputFile.nextInt() };
{ x: Int ->
coefficients.asSequence()
.withIndex()
.sumOf { (i, it) -> x.toBigInteger().pow(coefficients.size - 1 - i) * it.toBigInteger() }
}
}
val d = inputFile.nextInt()
val prec = buildMap {
for (i in 0 until d) {
val from = inputFile.nextInt() - 1
val to = inputFile.nextInt() - 1
val list: MutableList<Int> = getOrPut(to) { mutableListOf() }
list += from
}
}
val (fMaxMin, schedule) = scheduleP1PrecFMax(times, functions, prec)
File("p1precfmax.out").printWriter().use { output ->
output.println(fMaxMin.toString())
for (i in schedule) {
output.print("$i ")
}
}
}
| 0 | Jupyter Notebook | 3 | 5 | d442a3d25b579b96c6abda13ed3f7e60d1747b53 | 2,092 | university | Do What The F*ck You Want To Public License |
src/Day04.kt | josepatinob | 571,756,490 | false | {"Kotlin": 17374} | fun main() {
fun IntRange.containsAll(valueList: List<Int>) = valueList.all { value ->
this.contains(value)
}
fun IntRange.containsAny(valueList: List<Int>) = valueList.any { value ->
this.contains(value)
}
fun part1(input: List<String>): Int {
var overlapCount = 0
input.forEach {
val assignments = it.split(",")
val assignmentOne = assignments[0]
val assignmentTwo = assignments[1]
val assignmentOneRanges = assignmentOne.split("-")
val assignmentTwoRanges = assignmentTwo.split("-")
val rangeOne = assignmentOneRanges[0].toInt() ..assignmentOneRanges[1].toInt()
val rangeTwo = assignmentTwoRanges[0].toInt()..assignmentTwoRanges[1].toInt()
if (rangeOne.containsAll(rangeTwo.toList()) || rangeTwo.containsAll(rangeOne.toList())) {
overlapCount++
}
}
return overlapCount
}
fun part2(input: List<String>): Int {
var overlapCount = 0
input.forEach {
val assignments = it.split(",")
val assignmentOne = assignments[0]
val assignmentTwo = assignments[1]
val assignmentOneRanges = assignmentOne.split("-")
val assignmentTwoRanges = assignmentTwo.split("-")
val rangeOne = assignmentOneRanges[0].toInt() ..assignmentOneRanges[1].toInt()
val rangeTwo = assignmentTwoRanges[0].toInt()..assignmentTwoRanges[1].toInt()
if (rangeOne.containsAny(rangeTwo.toList()) || rangeTwo.containsAny(rangeOne.toList())) {
overlapCount++
}
}
return overlapCount
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day04Sample")
//println(part1(testInput))
//println(part2(testInput))
val input = readInput("Day04")
//println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d429a5fff7ddc3f533d0854e515c2ba4b0d461b0 | 1,988 | aoc-kotlin-2022 | Apache License 2.0 |
src/twentytwentythree/day01/Day01.kt | colinmarsch | 571,723,956 | false | {"Kotlin": 65403, "Python": 6148} | package twentytwentythree.day01
import readInput
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val filtered = line.filter { it.isDigit() }
filtered.first().digitToInt() * 10 + filtered.last().digitToInt()
}
}
fun part2(input: List<String>): Int {
val digitWords = listOf(
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
)
return input.sumOf { line ->
val firstDigitIndex = line.indexOfFirst { it.isDigit() }
val firstDigitWord = line.findAnyOf(digitWords)
val firstDigitWordIndex = firstDigitWord?.first ?: Int.MAX_VALUE
val firstDigit = if (firstDigitIndex != -1 && firstDigitIndex < firstDigitWordIndex) {
line[firstDigitIndex].digitToInt()
} else {
digitWords.indexOf(firstDigitWord!!.second) + 1
}
val lastDigitIndex = line.indexOfLast { it.isDigit() }
val lastDigitWord = line.findLastAnyOf(digitWords)
val lastDigitWordIndex = lastDigitWord?.first ?: Int.MIN_VALUE
val lastDigit = if (lastDigitIndex != -1 && lastDigitIndex > lastDigitWordIndex) {
line[lastDigitIndex].digitToInt()
} else {
digitWords.indexOf(lastDigitWord!!.second) + 1
}
firstDigit * 10 + lastDigit
}
}
val input = readInput("twentytwentythree/day01", "Day01_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bcd7a08494e6db8140478b5f0a5f26ac1585ad76 | 1,467 | advent-of-code | Apache License 2.0 |
Day10/src/MonitoringStation.kt | gautemo | 225,219,298 | false | null | import java.io.File
import java.lang.Math.pow
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.sqrt
fun main(){
val map = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText()
val astroids = getAstroids(map)
val best = findBestCount(astroids)
println(best)
val killed200 = get200Kill(astroids.toMutableList())
println(killed200)
}
fun get200Kill(astroids: MutableList<Astroid>): Int{
val station = findBest(astroids)
val loop = astroids.map { angle(station, it) }.toSet().sortedDescending()
var kills = 0
var i = 0
var killed: Astroid? = null
while(kills < 200){
val angle = loop[i]
killed = kill(station, astroids, angle)
if(killed != null){
astroids.remove(killed)
kills++
}
i++
if(i >= loop.size) i = 0
}
return killed!!.x * 100 + killed.y
}
fun kill(station: Astroid, astroids: List<Astroid>, angle: Double) = astroids.filter { angle(station, it) == angle }.minBy { distance(station, it) }
fun distance(a1: Astroid, a2: Astroid) = sqrt(pow(abs(a1.x.toDouble() - a2.x.toDouble()), 2.0) + pow(abs(a1.y.toDouble() - a2.y.toDouble()), 2.0))
fun getAstroids(map: String): List<Astroid>{
val astroids = mutableListOf<Astroid>()
map.lines().forEachIndexed { y, xLine -> xLine.forEachIndexed { x, c -> if(c == '#') astroids.add(Astroid(x, y)) } }
return astroids
}
fun findBestCount(astroids: List<Astroid>) = astroids.map { count(it, astroids) }.max()!!
fun findBest(astroids: List<Astroid>) = astroids.maxBy { count(it, astroids) }!!
fun count(a: Astroid, astroids: List<Astroid>): Int{
val hits = mutableSetOf<Double>()
astroids.forEach {
if(a != it){
hits.add(angle(a, it))
}
}
return hits.size
}
fun angle(a1: Astroid, a2: Astroid): Double{
val degree = 90 - Math.toDegrees(atan2(a1.y.toDouble() - a2.y.toDouble(), a1.x.toDouble() - a2.x.toDouble())) //+90 to point to north
return if(degree > 0) degree else degree + 360
}
data class Astroid(val x: Int, val y: Int) | 0 | Kotlin | 0 | 0 | f8ac96e7b8af13202f9233bb5a736d72261c3a3b | 2,132 | AdventOfCode2019 | MIT License |
src/day10/Day10.kt | ivanovmeya | 573,150,306 | false | {"Kotlin": 43768} | package day10
import readInput
fun main() {
data class Instruction(val cycles: Int, val registryValue: Int? = null)
fun parseInstructions(input: List<String>): List<Instruction> {
return input.map {
if (it.contains(' ')) {
val (_, registry) = it.split(' ')
Instruction(2, registry.toInt())
} else {
Instruction(1, null)
}
}
}
fun printRegistry(registry: IntArray) {
registry.forEachIndexed { index, i ->
println("r[$index] = $i ")
}
}
fun part1(input: List<String>): Int {
val instructions = parseInstructions(input)
val registry = IntArray(250) { 0 }
registry[1] = 1
var currentCycle = 1
instructions.forEach { instruction ->
repeat(instruction.cycles) {
currentCycle++
registry[currentCycle] = registry[currentCycle - 1]
}
if (instruction.registryValue != null) {
registry[currentCycle] = registry[currentCycle - 1] + instruction.registryValue
}
}
return (20..220 step 40).sumOf {
it * registry[it]
}
}
fun part2(input: List<String>): Int {
val instructions = parseInstructions(input)
val registry = IntArray(250) { 0 }
registry[1] = 1
//CRT draws pixel at currentCycle Position
//CRT has 40 wide, and 6 height
var currentCycle = 1
instructions.forEach { instruction ->
repeat(instruction.cycles) {
val spritePosition = currentCycle % 40
val registryValue = registry[currentCycle]
print(if (registryValue in (spritePosition - 2 .. spritePosition)) "#" else ".")
if ((currentCycle % 40) == 0) {
println()
}
currentCycle++
registry[currentCycle] = registry[currentCycle - 1]
}
if (instruction.registryValue != null) {
registry[currentCycle] = registry[currentCycle - 1] + instruction.registryValue
}
}
println()
return (20..220 step 40).sumOf {
it * registry[it]
}
}
val testInput = readInput("day10/input_test")
val test1Result = part1(testInput)
println(test1Result)
check(test1Result == 13140)
val test2Result = part2(testInput)
val input = readInput("day10/input")
println(part1(input))
part2(input)
} | 0 | Kotlin | 0 | 0 | 7530367fb453f012249f1dc37869f950bda018e0 | 2,594 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day5.kt | hughjdavey | 159,955,618 | false | null | package days
import util.parallelMap
import util.sameLetterDifferentCase
class Day5 : Day(5) {
override fun partOne(): Int {
val reactedPolymer = scanAndReact("", inputString)
return reactedPolymer.length - 1
}
override fun partTwo(): Int {
println("// Day 5 Part 2 takes about 11 seconds...")
return shortestPolymer(inputString) - 1
}
companion object {
// todo do this with coroutines not java parallelStream
fun shortestPolymer(polymer: String): Int {
// map each distinct char in string to string without that char (all cases)
// then map to reacted polymer and take the length, returning the lowest length
val distinctUnits = polymer.toLowerCase().toCharArray().distinct()
return distinctUnits
.map { polymer.replace(it.toString(), "", true) }
.parallelMap { scanAndReact("", it).length }
.min() ?: 0
}
tailrec fun scanAndReact(oldPolymer: String, polymer: String): String {
return if (oldPolymer.length == polymer.length) {
polymer
} else {
scanAndReact(polymer, scanAndReact(polymer))
}
}
private fun scanAndReact(polymer: String): String {
// map each char in string into a pair of index to char and remove indices that would break the lookaheads
// then find first pair of units that can react (converting the string to a lazy sequence drastically improves performance)
val firstReaction = polymer.asSequence()
.mapIndexed { index, char -> Pair(index, char) }
.filter { it.first < polymer.length - 1 }
.find { polymer[it.first].sameLetterDifferentCase(polymer[it.first + 1]) }
return if (firstReaction == null) {
polymer
} else {
polymer.replaceRange(firstReaction.first, firstReaction.first + 2, "")
}
}
}
}
| 0 | Kotlin | 0 | 0 | 4f163752c67333aa6c42cdc27abe07be094961a7 | 2,081 | aoc-2018 | Creative Commons Zero v1.0 Universal |
src/Day03.kt | hottendo | 572,708,982 | false | {"Kotlin": 41152} |
fun main() {
fun getItemPriority(character: Char): Int {
val lowerCaseAsciiOffset = 96 // ascii code of a is 97
val upperCaseAsciiOffset = 64 // ascii code of A is 65
val priority: Int
// println("Char: $character - Code: ${character.code}")
if (character.code < 97) { // upper case
priority = character.code - upperCaseAsciiOffset + 26
} else {
priority = character.code - lowerCaseAsciiOffset
}
// println("$priority")
return priority
}
fun part1(input: List<String>): Int {
var score = 0
val rucksackLeftCompartment = mutableSetOf<Char>()
val rucksackRightCompartment = mutableSetOf<Char>()
for(item in input) {
//println(item)
for(i in 0..item.length/2-1) {
rucksackLeftCompartment.add(item[i])
}
for(i in item.length/2..item.length-1) {
rucksackRightCompartment.add(item[i])
}
val doubleItems = rucksackLeftCompartment.intersect(rucksackRightCompartment)
// println(doubleItems)
if(doubleItems.size == 1) {
score += getItemPriority(doubleItems.first())
} else {
println("Error: there are ${doubleItems.size} duplicate items!")
}
rucksackLeftCompartment.clear()
rucksackRightCompartment.clear()
doubleItems.drop(doubleItems.size)
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
val rucksack1 = mutableSetOf<Char>()
val rucksack2 = mutableSetOf<Char>()
val rucksack3 = mutableSetOf<Char>()
val elvesGroups = input.chunked(3)
for(group in elvesGroups) {
for(c in group[0]) { rucksack1.add(c) }
for(c in group[1]) { rucksack2.add(c) }
for(c in group[2]) { rucksack3.add(c) }
val badge = rucksack1 intersect rucksack2 intersect rucksack3
score += getItemPriority(badge.first())
rucksack1.clear()
rucksack2.clear()
rucksack3.clear()
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println(part1(testInput))
println(part2(testInput))
// check(part1(testInput) == 1)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a166014be8bf379dcb4012e1904e25610617c550 | 2,531 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountAllPossibleRoutes.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
import java.util.Arrays
import kotlin.math.abs
/**
* 1575. Count All Possible Routes
* @see <a href="https://leetcode.com/problems/count-all-possible-routes/">Source</a>
*/
fun interface CountAllPossibleRoutes {
fun countRoutes(locations: IntArray, start: Int, finish: Int, fuel: Int): Int
}
/**
* Approach 1: Recursive Dynamic Programming
*/
class CountAllPossibleRoutesRec : CountAllPossibleRoutes {
override fun countRoutes(locations: IntArray, start: Int, finish: Int, fuel: Int): Int {
val n: Int = locations.size
val memo = Array(n) { IntArray(fuel + 1) { -1 } }
return solve(locations, start, finish, fuel, memo)
}
private fun solve(locations: IntArray, currCity: Int, finish: Int, remainingFuel: Int, memo: Array<IntArray>): Int {
if (remainingFuel < 0) {
return 0
}
if (memo[currCity][remainingFuel] != -1) {
return memo[currCity][remainingFuel]
}
var ans = if (currCity == finish) 1 else 0
for (nextCity in locations.indices) {
if (nextCity != currCity) {
ans = ans.plus(
solve(
locations,
nextCity,
finish,
remainingFuel - abs(locations[currCity] - locations[nextCity]),
memo,
),
) % MOD
}
}
return ans.also { memo[currCity][remainingFuel] = it }
}
}
/**
* Approach 2: Iterative Dynamic Programming
*/
class CountAllPossibleRoutesIter : CountAllPossibleRoutes {
override fun countRoutes(locations: IntArray, start: Int, finish: Int, fuel: Int): Int {
val n: Int = locations.size
val dp = Array(n) { IntArray(fuel + 1) }
Arrays.fill(dp[finish], 1)
for (j in 0..fuel) {
for (i in 0 until n) {
for (k in 0 until n) {
if (k == i) {
continue
}
if (abs(locations[i] - locations[k]) <= j) {
dp[i][j] = (dp[i][j] + dp[k][j - abs(locations[i] - locations[k])]) % MOD
}
}
}
}
return dp[start][fuel]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,981 | kotlab | Apache License 2.0 |
src/main/kotlin/be/seppevolkaerts/day4/Day4.kt | Cybermaxke | 727,453,020 | false | {"Kotlin": 35118} | package be.seppevolkaerts.day4
import be.seppevolkaerts.splitInts
import kotlin.math.pow
fun matches(card: String): Int {
val winningAndOurNumbers = card.substringAfter(':', "").split('|')
if (winningAndOurNumbers.size < 2) {
return 0
}
val winningNumbers = winningAndOurNumbers[0].splitInts().toSet()
return winningAndOurNumbers[1].splitInts().count { winningNumbers.contains(it) }
}
// Part One
fun partOneScore(cards: Iterable<String>) = cards.sumOf { partOneScore(it) }
fun partOneScore(card: String): Int {
val matches = matches(card)
return if (matches > 0) 2.0.pow(matches - 1).toInt() else 0
}
// Part Two
data class Card(
var matches: Int,
var instances: Int,
)
fun cardInstances(iterable: Iterable<String>): Int {
val cards = iterable.map { Card(matches(it), 1) }
cards.forEachIndexed { index, card ->
repeat(card.matches) { match ->
val next = cards.getOrNull(index + match + 1)
if (next != null) {
next.instances += card.instances
}
}
}
return cards.sumOf { it.instances }
}
| 0 | Kotlin | 0 | 1 | 56ed086f8493b9f5ff1b688e2f128c69e3e1962c | 1,059 | advent-2023 | MIT License |
src/year_2022/day_04/Day04.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_04
import readInput
data class Assignment(
val elfOneSectionIds: List<Int>,
val elfTwoSectionIds: List<Int>
) {
val assignmentFullyContained: Boolean get() {
return elfOneSectionIds.all { it in elfTwoSectionIds }
|| elfTwoSectionIds.all { it in elfOneSectionIds }
}
val assignmentsOverlap: Boolean get() {
return elfOneSectionIds.any { it in elfTwoSectionIds }
}
}
object Day04 {
/**
* @return the number of assignments fully contained inside another
*/
fun solutionOne(text: List<String>): Int {
return calculateAssignments(text).count { it.assignmentFullyContained }
}
/**
* @return the number of assignments with any overlap
*/
fun solutionTwo(text: List<String>): Int {
return calculateAssignments(text).count { it.assignmentsOverlap }
}
private fun calculateAssignments(text: List<String>): List<Assignment> {
return text.map { textLine ->
val assignments = textLine.split(",")
Assignment(
elfOneSectionIds = convertRangeToList(assignments[0]),
elfTwoSectionIds = convertRangeToList(assignments[1])
)
}
}
private fun convertRangeToList(range: String): List<Int> {
val split = range.split("-")
val start = split[0].toInt()
val end = split[1].toInt()
return (start..end).toList()
}
}
fun main() {
val inputText = readInput("year_2022/day_04/Day04.txt")
val solutionOne = Day04.solutionOne(inputText)
println("Solution 1: $solutionOne")
val solutionTwo = Day04.solutionTwo(inputText)
println("Solution 2: $solutionTwo")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 1,737 | advent_of_code | Apache License 2.0 |
app/src/main/kotlin/day05/Day05.kt | W3D3 | 572,447,546 | false | {"Kotlin": 159335} | package day05
import common.InputRepo
import common.readSessionCookie
import common.solve
import util.split
fun main(args: Array<String>) {
val day = 5
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay05Part1, ::solveDay05Part2)
}
fun solveDay05Part1(input: List<String>): String {
val (initialConditions, instructions) = input.split({ it.isBlank() })
val map = generateStackMap(initialConditions)
for (instructionLine in instructions) {
val instruction = parseInstruction(instructionLine)
repeat(instruction.repetitions) {
val removed = map[instruction.origin]!!.removeLast()
map[instruction.target]?.addLast(removed)
}
}
return map.values.mapNotNull { it.lastOrNull() }
.joinToString(separator = "") { it.toString() }
}
private fun generateStackMap(split: Collection<String>): MutableMap<Int, ArrayDeque<Char>> {
val initialStrings = split.reversed()
var numOfStacks: Int
val map = mutableMapOf<Int, ArrayDeque<Char>>()
for ((index, initialString) in initialStrings.withIndex()) {
if (index == 0) {
numOfStacks = initialString.split("""\w""".toRegex()).count()
for (i in 0..numOfStacks) {
map[i] = ArrayDeque()
}
} else {
initialString
.windowed(3, 4)
.mapIndexed { i, s ->
if (s.isNotBlank()) {
map[i]?.addLast(getChar(s))
}
}
}
}
return map
}
private fun getChar(boxSyntax: String): Char {
return boxSyntax.toCharArray()[1]
}
data class Instruction(val repetitions: Int, val origin: Int, val target: Int)
private fun parseInstruction(line: String): Instruction {
val moveRegex = """move (\d+) from (\d+) to (\d+)""".toRegex()
return moveRegex.matchEntire(line)
?.destructured
?.let { (repetitions, origin, target) ->
Instruction(repetitions.toInt(), origin.toInt() - 1, target.toInt() - 1)
}
?: throw IllegalArgumentException("Bad input '$line'")
}
fun solveDay05Part2(input: List<String>): String {
val (initialConditions, instructions) = input.split({ it.isBlank() })
val map = generateStackMap(initialConditions)
for (instructionLine in instructions) {
val instruction = parseInstruction(instructionLine)
val removedList = mutableListOf<Char>()
repeat(instruction.repetitions) {
removedList.add(map[instruction.origin]!!.removeLast())
}
removedList.reversed().forEach {
map[instruction.target]?.add(it)
}
}
return map.values
.mapNotNull { it.lastOrNull() }
.joinToString(separator = "") { it.toString() }
} | 0 | Kotlin | 0 | 0 | 34437876bf5c391aa064e42f5c984c7014a9f46d | 2,848 | AdventOfCode2022 | Apache License 2.0 |
leetcode2/src/leetcode/evaluate-reverse-polish-notation.kt | hewking | 68,515,222 | false | null | package leetcode
import java.util.*
/**
* 150. 逆波兰表达式求值
* https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
* Created by test
* Date 2019/9/29 12:55
* Description
* 根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:
输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6
示例 3:
输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
输出: 22
解释:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object EvaluateReversePolishNotation {
@JvmStatic
fun main(args: Array<String>) {
println(Solution().evalRPN(arrayOf("2", "1", "+", "3", "*")))
}
class Solution {
fun evalRPN(tokens: Array<String>): Int {
val stack = Stack<Int>()
tokens.forEach {
val op = it
when (op) {
"+" -> {
val left = stack.pop()
val right = stack.pop()
stack.push(left + right)
}
"-" -> {
val right = stack.pop()
val left = stack.pop()
stack.push(left - right)
}
"*" -> {
val left = stack.pop()
val right = stack.pop()
stack.push(left * right)
}
"/" -> {
val right = stack.pop()
val left = stack.pop()
if (right != 0) {
stack.push((left / right).toInt())
} else {
stack.push(left)
}
}
else -> {
stack.push(op.toInt())
}
}
}
return stack.pop().toInt()
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,697 | leetcode | MIT License |
src/day19/Parser.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day19
import readInput
import java.lang.IllegalArgumentException
import java.util.regex.Pattern
class Resources {
private val data = mutableMapOf<Material, Int> ()
fun get (material: Material): Int = data[material] ?: 0
fun set (material: Material, count: Int) {
data[material] = count
}
fun clear () {
data.clear ()
}
fun increment (material: Material, count: Int): Int {
return (get (material) + count).apply {
set (material, this)
}
}
fun decrement (material: Material, count: Int): Int {
return (get (material) - count).apply {
set (material, this)
}
}
fun canAfford (pairs: List<Pair<Material, Int>>): Boolean {
pairs.forEach { (material, count) ->
if (count > get (material)) {
return false
}
}
return true
}
fun dump () = println (toString ())
fun addAll (resources: Resources) {
data.putAll (resources.data)
}
fun copy (): Resources {
val other = Resources ()
other.data.putAll (data)
return other
}
fun spend (pairs: List<Cost>, count: Int = 1) {
for ((material, cost) in pairs) {
decrement (material, count * cost)
}
}
override fun toString(): String = data.entries.toString ()
}
enum class Material (val encoded: String, val rank: Int) {
ORE ("ore", 0),
CLAY ("clay", 1),
OBSIDIAN ("obsidian", 2),
GEODE ("geode", 3);
companion object {
private val map = mutableMapOf<String, Material> ().apply {
Material.values ().forEach {
put (it.encoded, it)
}
}
fun decode (encoded: String): Material = map [encoded] ?: throw IllegalArgumentException ("Invalid material: $encoded")
}
}
data class Robots (val material: Material, val count: Int) {
override fun toString(): String = "${count} $material"
}
data class Cost (val material: Material, val count: Int) {
override fun toString(): String = "${count} $material"
}
data class Recipe (val robot: Material, val cost: List<Cost>) {
fun dump () = println (toString ())
fun maxAffordable (resources: Resources): Int {
var count: Int? = null
for (el in cost) {
val canAfford = resources.get (el.material) / el.count
if (count == null) {
count = canAfford
} else {
count = Math.min (count, canAfford)
}
}
return count as Int
}
override fun toString(): String = "${robot} = ${cost.joinToString (", ")}"
}
data class Blueprint (val index: Int, val recipes: List<Recipe>) {
val robots = mutableMapOf<Material, Recipe> ().apply {
recipes.forEach {
put (it.robot, it)
}
}
/**
* Calculate the maximum number of each robot type that we could afford with the
* given amount of resources.
*/
fun maxAffordable (resources: Resources): List<Robots> {
return recipes.map {
Robots (it.robot, it.maxAffordable (resources))
}.filter { it.count != 0 }
}
/**
* Used to scrub the list of possible affordable permutations to remove
* any of those that doesn't fully spend the budget since those are by definition
* suboptimal strategies.
*/
fun isOptimal (pairs: List<Robots>, resources: Resources): Boolean {
// Calculate what resources we'll have left after building the specified robots
val leftover = resources.copy ()
for (pair in pairs) {
val recipe = robots[pair.material] as Recipe
val count = pair.count
leftover.spend (recipe.cost, count)
}
// Now see if we can still afford to build any robots
for (recipe in recipes) {
if (recipe.maxAffordable (leftover) > 0) {
return false
}
}
return true
}
/**
* Tests to see whether we can actually afford to purchase this many robots
* with the specified resources.
*/
private fun canAfford (pairs: List<Robots>, resources: Resources): Boolean {
val copy = resources.copy ()
for ((robot, count) in pairs) {
val recipe = robots[robot] as Recipe
recipe.cost.forEach { (material, cost) ->
if (copy.decrement (material, count * cost) < 0) {
return false
}
}
}
return true
}
/**
* Figure out all the possible set of robots that could be provisioned using
* the given amount of resources.
*/
fun canAfford (resources: Resources): List<List<Robots>> {
val affordable = maxAffordable (resources)
val permutations = permutations (affordable)
.filter { canAfford (it, resources) }
.filter { isOptimal (it, resources) }
return permutations
}
fun dump () = println (toString ())
override fun toString(): String {
val buf = StringBuffer ()
buf.append ("Blueprint $index:\n")
recipes.forEach {
buf.append (" ${it}\n")
}
return buf.toString ()
}
companion object {
private val REGEX0 = "^Blueprint (\\d+):$"
private val PATTERN0 = Pattern.compile (REGEX0)
private val REGEX1 = "^\\s*(\\w+) robot costs (\\d+) (\\w+)(?: and (\\d++) (\\w+))?.$"
private val PATTERN1 = Pattern.compile (REGEX1)
fun parse (str: String): Blueprint {
val strs = str.split (" Each ")
val p0 = PATTERN0.matcher (strs[0])
if (! p0.matches ()) {
throw IllegalArgumentException ("No match: ${strs[0]}")
}
val index = p0.group (1).toInt ()
val recipes = mutableListOf<Recipe> ()
for (i in 1 until strs.size) {
val p = PATTERN1.matcher (strs[i])
if (! p.matches ()) {
throw IllegalArgumentException ("No match: ${strs[i]}")
}
val robot = p.group (1)
val costs = mutableListOf<Cost> ().apply {
add (Cost (Material.decode (p.group (3)), p.group (2).toInt ()))
if (p.group (4) != null) {
add (Cost (Material.decode (p.group (5)), p.group (4).toInt ()))
}
}
recipes.add (Recipe (Material.decode (robot), costs))
}
return Blueprint (index, recipes)
}
}
}
fun loadBlueprints (example: Boolean): List<Blueprint> {
val input = readInput (19, example)
val blueprints = input.trim ().split ("\n").map {
Blueprint.parse (it)
}
return blueprints
}
fun main (args: Array<String>) {
val example = true
val blueprints = loadBlueprints(example)
blueprints.forEach {
println (it)
}
return
}
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 7,050 | advent_of_code_2022 | Apache License 2.0 |
src/Day13.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | import kotlin.math.min
/**
* [Day13](https://adventofcode.com/2022/day/13)
*/
private class Day13 {
sealed class Packet {
abstract fun toData(): Data
companion object {
fun parse(input: String): Packet {
val packet = innerParse(input).second!!
// check parsed correctly
check(packet.toString() == input.replace(",", ", "))
return packet
}
private fun innerParse(input: String): Pair<Int, Packet?> {
if (input.isEmpty()) return 0 to null
if (input.startsWith('[')) {
val data = Data()
var index = 1
var current = 1
while (current < input.length) {
when (input[current]) {
',' -> {
if (index < current) {
data.list.add(Value(input.substring(index, current).toInt()))
}
index = current + 1
current = index - 1
}
']' -> {
if (index < current) {
data.list.add(Value(input.substring(index, current).toInt()))
}
return current + 1 to data
}
'[' -> {
val (read, sub) = innerParse(input.substring(current))
data.list.add(sub!!)
index = current + read
current = index - 1
}
}
current++
}
return current to data
}
return input.length to Value(input.toInt())
}
}
}
data class Value(val n: Int) : Packet() {
override fun toData(): Data {
return Data().also {
it.list.add(this)
}
}
override fun toString(): String {
return n.toString()
}
}
class Data : Packet() {
val list = mutableListOf<Packet>()
override fun toData(): Data = this
override fun toString(): String {
return list.toString()
}
}
enum class STATUS {
RIGHT, INVALID, PASS
}
}
fun main() {
fun toPacketPairs(input: List<String>): List<Pair<Day13.Packet, Day13.Packet>> = buildList {
for (i in input.indices step 3) {
val left = Day13.Packet.parse(input[i])
val right = Day13.Packet.parse(input[i + 1])
add(left to right)
}
}
fun isRightOrder(left: Day13.Packet, right: Day13.Packet): Day13.STATUS {
when {
left is Day13.Value && right is Day13.Value -> {
if (left.n < right.n) return Day13.STATUS.RIGHT
if (left.n > right.n) return Day13.STATUS.INVALID
return Day13.STATUS.PASS
}
left is Day13.Data && right is Day13.Data -> {
val leftList = left.list
val rightList = right.list
for (i in 0 until min(leftList.size, rightList.size)) {
val status = isRightOrder(leftList[i], rightList[i])
if (status != Day13.STATUS.PASS) {
return status
}
}
return when {
leftList.size < rightList.size -> Day13.STATUS.RIGHT
leftList.size > rightList.size -> Day13.STATUS.INVALID
else -> Day13.STATUS.PASS
}
}
else -> {
return isRightOrder(left.toData(), right.toData())
}
}
}
fun part1(input: List<String>): Int {
val packets = toPacketPairs(input)
val sum = packets.foldIndexed(0) { index, acc, (left, right) ->
acc + (if (isRightOrder(left, right) == Day13.STATUS.INVALID) 0 else index + 1)
}
return sum
}
fun part2(input: List<String>): Int {
val additionalPackets = listOf(
Day13.Packet.parse("[[2]]"),
Day13.Packet.parse("[[6]]"),
)
val packets = toPacketPairs(input).flatMap { (left, right) ->
listOf(left, right)
} + additionalPackets
return packets.sortedWith { p1, p2 ->
when (isRightOrder(p1, p2)) {
Day13.STATUS.RIGHT -> -1
Day13.STATUS.INVALID -> 1
Day13.STATUS.PASS -> 0
}
}.mapIndexedNotNull { index, packet ->
if (packet in additionalPackets) index + 1 else null
}.reduce { acc, i -> acc * i }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 5,297 | aoc-in-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day11.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2022
import AoCDay
import util.illegalInput
private typealias Operation = (Long) -> Long
// https://adventofcode.com/2022/day/11
object Day11 : AoCDay<Long>(
title = "Monkey in the Middle",
part1ExampleAnswer = 10605,
part1Answer = 99852,
part2ExampleAnswer = 2713310158,
part2Answer = 25935263541,
) {
private val MONKEY_REGEX = """
Monkey (\d+):
{2}Starting items: (\d+(?:, \d+)*)
{2}Operation: new = old ([+*]) (old|\d+)
{2}Test: divisible by (\d+)
{4}If true: throw to monkey (\d+)
{4}If false: throw to monkey (\d+)
""".trimIndent().toRegex()
private class Item(var worryLevel: Long)
private class Monkey(
val items: ArrayDeque<Item>,
val operation: Operation,
val testDivisor: Long,
val monkeyTestTrue: Int,
val monkeyTestFalse: Int,
var inspectedItems: Long,
)
private val OLD_PLUS_OLD: Operation = { old -> old + old }
private val OLD_TIMES_OLD: Operation = { old -> old * old }
private fun parseMonkeys(input: String) = MONKEY_REGEX
.findAll(input)
.mapIndexed { index, monkey ->
val (monkeyIndex, worryLevels, operator, secondOperand, testDivisor, monkeyTestTrue, monkeyTestFalse) =
monkey.destructured
require(index == monkeyIndex.toInt())
val secondOperandValue = when (secondOperand) {
"old" -> null
else -> secondOperand.toLong()
}
Monkey(
items = worryLevels.split(", ").mapTo(ArrayDeque()) { worryLevel -> Item(worryLevel.toLong()) },
operation = when (operator) {
"+" -> if (secondOperandValue == null) OLD_PLUS_OLD else ({ old -> old + secondOperandValue })
"*" -> if (secondOperandValue == null) OLD_TIMES_OLD else ({ old -> old * secondOperandValue })
else -> illegalInput(operator)
},
testDivisor.toLong(),
monkeyTestTrue.toInt(),
monkeyTestFalse.toInt(),
inspectedItems = 0,
)
}
.toList()
private inline fun getLevelOfMonkeyBusiness(monkeys: List<Monkey>, rounds: Int, adjustWorryLevel: Operation): Long {
repeat(rounds) {
for (monkey in monkeys) with(monkey) {
var item = items.removeFirstOrNull()
while (item != null) {
inspectedItems++
item.worryLevel = item.worryLevel.let(operation).let(adjustWorryLevel)
val throwMonkey = if (item.worryLevel % testDivisor == 0L) monkeyTestTrue else monkeyTestFalse
monkeys[throwMonkey].items.addLast(item)
item = items.removeFirstOrNull()
}
}
}
val (first, second) = monkeys.sortedByDescending { it.inspectedItems }
return first.inspectedItems * second.inspectedItems
}
override fun part1(input: String): Long {
val monkeys = parseMonkeys(input)
return getLevelOfMonkeyBusiness(monkeys, rounds = 20, adjustWorryLevel = { it / 3 })
}
override fun part2(input: String): Long {
val monkeys = parseMonkeys(input)
val commonMultiple = monkeys.map { it.testDivisor }.distinct().reduce(Long::times)
return getLevelOfMonkeyBusiness(monkeys, rounds = 10000, adjustWorryLevel = { it % commonMultiple })
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 3,525 | advent-of-code-kotlin | MIT License |
src/main/kotlin/dev/tasso/adventofcode/_2021/day05/Day05.kt | AndrewTasso | 433,656,563 | false | {"Kotlin": 75030} | package dev.tasso.adventofcode._2021.day05
import dev.tasso.adventofcode.Solution
import java.lang.Integer.max
class Day05 : Solution<Int> {
override fun part1(input: List<String>): Int {
val ventLines = input.map { it.split(" -> ").map{it.split(",").map { it.toInt() }}}
.map { Line(Coordinate(it.first().first(), it.first().last()), Coordinate(it.last().first(), it.last().last())) }
val floorWidth = ventLines.maxOf { max(it.startCoordinate.x, it.endCoordinate.x) + 1 }
val floorHeight = ventLines.maxOf { max(it.startCoordinate.y, it.endCoordinate.y) + 1 }
val oceanFloor = StraightLineOceanFloor(floorWidth, floorHeight)
ventLines.forEach { oceanFloor.addVent(it) }
return oceanFloor.getNumOverlappingPoints()
}
override fun part2(input: List<String>): Int {
val ventLines = input.map { it.split(" -> ").map{it.split(",").map { it.toInt() }}}
.map { Line(Coordinate(it.first().first(), it.first().last()), Coordinate(it.last().first(), it.last().last())) }
val floorWidth = ventLines.maxOf { max(it.startCoordinate.x, it.endCoordinate.x) + 1 }
val floorHeight = ventLines.maxOf { max(it.startCoordinate.y, it.endCoordinate.y) + 1 }
val oceanFloor = DiagonalLineOceanFloor(floorWidth, floorHeight)
ventLines.forEach { oceanFloor.addVent(it) }
return oceanFloor.getNumOverlappingPoints()
}
}
| 0 | Kotlin | 0 | 0 | daee918ba3df94dc2a3d6dd55a69366363b4d46c | 1,451 | advent-of-code | MIT License |
src/Day07.kt | georgiizorabov | 573,050,504 | false | {"Kotlin": 10501} | import java.lang.Double.min
import kotlin.math.min
fun main() {
class Node(
val parent: Node?,
val files: MutableList<Pair<String, Int>> = ArrayList(),
val dirs: MutableMap<String, Node> = mutableMapOf(),
var size: Int = 0
)
var root: Node? = null
root = Node(root)
var curNode = root
fun processCommand(splittedCommand: List<String>) {
when (splittedCommand[1]) {
"cd" -> {
if (splittedCommand[2] == "/") {
curNode = root
} else if (splittedCommand[2] == "..") {
curNode = curNode!!.parent
} else {
curNode = curNode!!.dirs[splittedCommand[2]]
}
}
"ls" -> {
// skip
}
}
}
fun processCreateDir(splittedCommand: List<String>) {
curNode!!.dirs[splittedCommand[1]] = Node(curNode)
}
var sum = 0
fun processCreateFile(splittedCommand: List<String>) {
sum += splittedCommand[0].toInt()
curNode!!.files.add(Pair(splittedCommand[1], splittedCommand[0].toInt()))
}
fun processInput(command: String) {
val splittedCommand = command.split(" ")
when (splittedCommand[0]) {
"$" -> processCommand(splittedCommand)
"dir" -> processCreateDir(splittedCommand)
else -> processCreateFile(splittedCommand)
}
}
var cnt = 0
var min = 1_000_000_000
var diff = 0
fun dfs(curNode: Node) {
if (curNode.dirs.isNotEmpty()) {
for (dir in curNode.dirs.values) {
dfs(dir)
}
}
curNode.size = curNode.files.sumOf { it.second } + curNode.dirs.values.sumOf { it.size }
if (curNode.size <= 100000) {
cnt += curNode.size
}
}
fun dfs1(curNode: Node) {
if (curNode.dirs.isNotEmpty()) {
val m = curNode.dirs.values.filter { it.size >= diff }.minOfOrNull { it.size }
if (m != null) {
min = min(min, m)
}
for (dir in curNode.dirs.values) {
dfs1(dir)
}
}
}
fun part1(input: List<String>): Int {
input.forEach { processInput(it) }
dfs(root)
return cnt
}
fun part2(input: List<String>): Int {
input.forEach { processInput(it) }
dfs(root)
diff = -40000000 + sum / 2
dfs1(root)
return min
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bf84e55fe052c9c5f3121c245a7ae7c18a70c699 | 2,635 | aoc2022 | Apache License 2.0 |
src/Day04.kt | wellithy | 571,903,945 | false | null | package day04
import util.*
@JvmInline
value class Elf(private val assignment: IntRange) {
infix fun contained(other: Elf): Boolean =
assignment.first in other.assignment && assignment.last in other.assignment
infix fun overlaps(other: Elf): Boolean =
assignment.first in other.assignment || assignment.last in other.assignment
companion object {
fun of(str: String): Elf =
str.split('-').map { it.toInt() }.let { (first, last) -> Elf(IntRange(first, last)) }
}
}
@JvmInline
value class ElfPair(private val pair: Pair<Elf, Elf>) {
fun totalOverlap(): Boolean =
pair.first contained pair.second || pair.second contained pair.first
fun overlap(): Boolean =
pair.first overlaps pair.second || pair.second overlaps pair.first
companion object {
fun of(str: String): ElfPair =
str.split(',').map { Elf.of(it) }.let { (first, second) -> ElfPair(first to second) }
}
}
fun Sequence<String>.solve(by: ElfPair.() -> Boolean): Int =
count { ElfPair.of(it).by() }
fun part1(input: Sequence<String>): Int = input.solve(ElfPair::totalOverlap)
fun part2(input: Sequence<String>): Int = input.solve(ElfPair::overlap)
fun main() {
test(::part1, 2)
go(::part1, 305)
test(::part2, 4)
go(::part2, 811)
}
| 0 | Kotlin | 0 | 0 | 6d5fd4f0d361e4d483f7ddd2c6ef10224f6a9dec | 1,325 | aoc2022 | Apache License 2.0 |
src/main/kotlin/days/Day23.kt | andilau | 573,139,461 | false | {"Kotlin": 65955} | package days
@AdventOfCodePuzzle(
name = "Unstable Diffusion",
url = "https://adventofcode.com/2022/day/23",
date = Date(day = 23, year = 2022)
)
class Day23(input: List<String>) : Puzzle {
private val elfs = input.extract('#')
private val dirs = listOf("N", "S", "W", "E")
override fun partOne() =
generateSequence(elfs to dirs) { (set, dirs) -> move(set, dirs) to dirs.rotate() }.drop(10).first().first
.emptyGround()
override fun partTwo() =
generateSequence(elfs to dirs) { (set, dirs) -> move(set, dirs) to dirs.rotate() }
.zipWithNext().indexOfFirst { (one, two) -> one.first == two.first } + 1
private fun move(set: Set<Point>, dirs: List<String>): Set<Point> {
val elfs = set.toMutableSet()
val propose = mutableMapOf<Point, List<Point>>()
for (elf in elfs) {
if (elf.neighboursAll().none { it in elfs }) {
continue
}
var moved = false
for (dir in dirs) {
if (dir == "N" && !moved && listOf(elf.north, elf.northwest, elf.northeast).none { it in elfs }
) propose.compute(elf.north) { _, l -> if (l == null) listOf(elf) else l + elf }
.also { moved = true }
else if (dir == "S" && !moved && listOf(
elf.south,
elf.southwest,
elf.southeast
).none { it in elfs }
) propose.compute(elf.south) { _, l -> if (l == null) listOf(elf) else l + elf }
.also { moved = true }
else if (dir == "W" && !moved && listOf(
elf.west,
elf.northwest,
elf.southwest
).none { it in elfs }
) propose.compute(elf.west) { _, l -> if (l == null) listOf(elf) else l + elf }.also { moved = true }
else if (dir == "E" && !moved && listOf(
elf.east,
elf.northeast,
elf.southeast
).none { it in elfs }
) propose.compute(elf.east) { _, l -> if (l == null) listOf(elf) else l + elf }.also { moved = true }
}
}
propose.filterValues { it.size == 1 }.forEach { (to, from) ->
elfs += to
elfs -= from.single()
}
return elfs.toSet()
}
private fun Set<Point>.area() = (maxOf { it.x } - minOf { it.x } + 1) * (maxOf { it.y } - minOf { it.y } + 1)
private fun Set<Point>.emptyGround() = area() - size
private fun List<String>.rotate() = this.drop(1) + this.first()
}
| 0 | Kotlin | 0 | 0 | da824f8c562d72387940844aff306b22f605db40 | 2,726 | advent-of-code-2022 | Creative Commons Zero v1.0 Universal |
src/Day03.kt | samframpton | 572,917,565 | false | {"Kotlin": 6980} | fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (contents in input) {
val first = contents.subSequence(0, contents.length / 2)
val second = contents.subSequence(contents.length / 2, contents.length)
for (item in first) {
if (second.contains(item)) {
sum += item.priority
break
}
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
val elfGroups = input.windowed(3, 3)
for (elfGroup in elfGroups) {
for (item in elfGroup[0]) {
if (elfGroup[1].contains(item) && elfGroup[2].contains(item)) {
sum += item.priority
break
}
}
}
return sum
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private val Char.priority: Int
get() = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> 0
}
| 0 | Kotlin | 0 | 0 | e7f5220b6bd6f3c5a54396fa95f199ff3a8a24be | 1,124 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/fp/kotlin/example/chapter05/Main.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter05
import fp.kotlin.example.chapter05.FunList.Nil
import fp.kotlin.example.chapter05.solution.filter
fun main() {
val intList = funListOf(1, 2, 3)
val doubleList = funListOf(1.0, 2.0, 3.0)
printFunList(add3(intList)) // [4, 5, 6]
printFunList(product3(doubleList)) // [3.0, 6.0, 9.0]
printFunList(intList.map { it + 3 }) // [4, 5, 6]
printFunList(doubleList.map { it * 3 }) // [3.0, 6.0, 9.0]
println(sum(intList)) // 6
println(sumByFoldLeft(intList)) // 6
println(intList.map { it + 3 }.filter { it % 2 == 0 }.sum()) // 10
val lowerCharList = funListOf('a', 'b', 'c')
printFunList(toUpper(lowerCharList)) // [A, B, C]
printFunList(intList.mapByFoldLeft { it + 3 }) // [4, 5, 6]
val intList2 = funListOf(1, 3, 10, 14)
println(intList2.foldRight(0) { x, acc -> x - acc }) // -6
println(intList2.foldLeft(0) { acc, x -> x - acc }) // 6
printFunList(intList.mapByFoldRight { it + 3 }) // [4, 5, 6]
printFunList(intList.zipWith({ x, y -> x + y }, intList2)) // [2, 5, 13]
printFunList(intList.zipWith({ x, y -> if (x > y) x else y }, intList2)) // [1, 3, 10]
printFunList(intList.zipWith({ x, y -> x to y }, lowerCharList)) // [(1, a), (2, b), (3, c)]
println(funStreamOf(1, 2, 3).getHead()) // 1
println(funStreamOf(1, 2, 3).getTail()) // Cons(head=() -> T, tail=() -> fp.kotlin.example.chapter05.FunStream<T>)
println(funStreamOf(1, 2, 3, 4, 5).filter { it > 3 }.getHead())
val infiniteVal = generateFunStream(0) { it + 5 }
// infiniteVal.forEach { print(it) } // 0부터 계속 5씩 증가하는 값을 출력
println(funListOf(1, 2, 3).concat(funListOf(4, 5, 6)))
}
fun add3(list: FunList<Int>): FunList<Int> = when (list) {
FunList.Nil -> Nil
is FunList.Cons -> FunList.Cons(list.head + 3, add3(list.tail))
}
fun product3(list: FunList<Double>): FunList<Double> = when (list) {
FunList.Nil -> Nil
is FunList.Cons -> FunList.Cons(list.head * 3, product3(list.tail))
}
fun sum(list: FunList<Int>): Int = when (list) {
FunList.Nil -> 0
is FunList.Cons -> list.head + sum(list.tail)
}
fun sumByFoldLeft(list: FunList<Int>): Int = list.foldLeft(0) { acc, x -> acc + x }
fun toUpper(list: FunList<Char>): FunList<Char> =
list.foldLeft(Nil) { acc: FunList<Char>, char: Char -> acc.addHead(char.toUpperCase()) }
.reverse() | 1 | Kotlin | 23 | 39 | bb10ea01d9f0e1b02b412305940c1bd270093cb6 | 2,474 | fp-kotlin-example | MIT License |
src/day04/Day04.kt | iulianpopescu | 572,832,973 | false | {"Kotlin": 30777} | package day04
import readInput
private const val DAY = "04"
private const val DAY_TEST = "day${DAY}/Day${DAY}_test"
private const val DAY_INPUT = "day${DAY}/Day${DAY}"
fun main() {
fun intervalMapping(input: List<String>) = input.map {
val sections = it.split(',')
sections[0].toInterval() to sections[1].toInterval()
}
fun part1(input: List<String>): Int {
return intervalMapping(input).count { (a, b) ->
(a.left >= b.left && a.right <= b.right) || (b.left >= a.left && b.right <= a.right)
}
}
fun part2(input: List<String>): Int {
return intervalMapping(input).count { (a, b) ->
a.left in b.left..b.right ||
a.right in b.left..b.right ||
b.left in a.left..a.right ||
b.right in a.left..a.right
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(DAY_TEST)
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput(DAY_INPUT)
println(part1(input))
println(part2(input))
}
private data class Interval(val left: Int, val right: Int)
private fun String.toInterval(): Interval {
val items = this.split('-')
return Interval(items[0].toInt(), items[1].toInt())
} | 0 | Kotlin | 0 | 0 | 4ff5afb730d8bc074eb57650521a03961f86bc95 | 1,327 | AOC2022 | Apache License 2.0 |
src/day7/d7_1.kt | svorcmar | 720,683,913 | false | {"Kotlin": 49110} | fun main() {
val input = ""
val byTarget = input.lines().map { parseConnection(it) }.associate { it.target to it }
val cache = mutableMapOf<String, UShort>()
println(eval("a", byTarget, cache))
}
enum class Gate { WIRE, NOT, AND, OR, LSHIFT, RSHIFT }
data class Connection(val gate: Gate, val leftOp: String, val rightOp: String, val target: String)
fun parseConnection(input: String): Connection {
val lr = input.split(" -> ")
val target = lr[1]
val l = lr[0].split(" ")
return when (l.size) {
1 -> Connection(Gate.WIRE, l[0], "", target)
2 -> Connection(Gate.NOT, l[1], "", target)
else -> Connection(Gate.valueOf(l[1]), l[0], l[2], target)
}
}
fun eval(wire: String, connections: Map<String, Connection>, cache: MutableMap<String, UShort>): UShort {
if (!cache.containsKey(wire))
cache[wire] = evalConnection(connections[wire]!!, connections, cache)
return cache[wire]!!
}
fun evalConnection(connection: Connection, connections: Map<String, Connection>, cache: MutableMap<String, UShort>): UShort {
return when(connection.gate) {
Gate.WIRE -> evalOperand(connection.leftOp, connections, cache)
Gate.NOT -> evalOperand(connection.leftOp, connections, cache).inv()
Gate.AND -> evalOperand(connection.leftOp, connections, cache) and evalOperand(connection.rightOp, connections, cache)
Gate.OR -> evalOperand(connection.leftOp, connections, cache) or evalOperand(connection.rightOp, connections, cache)
Gate.LSHIFT -> (evalOperand(connection.leftOp, connections, cache).toInt() shl evalOperand(connection.rightOp, connections, cache).toInt()).toUShort()
Gate.RSHIFT -> (evalOperand(connection.leftOp, connections, cache).toInt() shr evalOperand(connection.rightOp, connections, cache).toInt()).toUShort()
}
}
fun evalOperand(operand: String, connections: Map<String, Connection>, cache: MutableMap<String, UShort>): UShort {
if (operand.matches("[0-9]+".toRegex()))
return operand.toUShort()
return eval(operand, connections, cache)
}
| 0 | Kotlin | 0 | 0 | cb097b59295b2ec76cc0845ee6674f1683c3c91f | 2,031 | aoc2015 | MIT License |
src/Day10.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | import kotlin.math.abs
private fun instructions(): List<Instruction> {
return readInput("Day10").map { if (it == "noop") Instruction(0, 1) else Instruction(it.split(" ")[1].toInt(), 2) }
}
private fun part1(instructions: List<Instruction>): Int {
val cyclesToCount = ArrayDeque(listOf(20, 60, 100, 140, 180, 220))
var sum = 0
var cycle = 0
var x = 1
instructions.forEach { i ->
if (cyclesToCount.first() <= cycle + i.cycles) {
sum += x * cyclesToCount.first();
cyclesToCount.removeFirst();
if (cyclesToCount.isEmpty()) return sum
}
if (i.cycles == 2) {
x += i.add
}
cycle += i.cycles
}
return sum
}
private fun part2(instructions: List<Instruction>) {
val screen = BooleanArray(240)
var cycle = 0
var x = 1
instructions.forEach { i ->
if (i.cycles == 1) {
cycle += 1
draw(cycle, x, screen)
}
if (i.cycles == 2) {
cycle += 1
draw(cycle, x, screen)
cycle += 1
draw(cycle, x, screen)
x += i.add
}
}
for (i in 0 until 6) {
for (j in 0 until 40) {
print(if (screen[40 * i + j]) "█" else " ")
}
println()
}
}
private fun draw(cycle: Int, x: Int, screen: BooleanArray) {
if (abs((cycle - 1) % 40 - x) <= 1) {
screen[cycle - 1] = true
}
}
fun main() {
println(part1(instructions()))
part2(instructions())
}
data class Instruction(val add: Int, val cycles: Int) | 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 1,585 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | stevennoto | 573,247,572 | false | {"Kotlin": 18058} | import java.util.Deque
fun main() {
fun part1(input: List<String>, numStacks: Int, moveBoxesOneAtATime: Boolean = true): String {
// Parse input diagram into 9 dequeues, 1 for each stack of crates, top of stack at ennd of dequeue
val stacks = List(numStacks) {ArrayDeque<Char>()}
val data = input.filter { it.trim().startsWith("[") }
data.reversed().forEach {
repeat(numStacks) { index ->
if (it[4 * index + 1] != ' ') stacks[index].addLast(it[4 * index + 1])
}
}
// Parse instructions, pop/push from source to target stack specified number of times
val instructions = input.filter { it.trim().startsWith("move") }
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
instructions.forEach {
val (num, source, target) = regex.find(it)!!.destructured.toList().map { it.toInt() }
if (moveBoxesOneAtATime)
repeat(num) { stacks[target - 1].addLast(stacks[source - 1].removeLast()) }
else {
stacks[target - 1].addAll(stacks[source - 1].takeLast(num))
repeat(num) { stacks[source - 1].removeLast() }
}
}
// Join letters at top of each stack
return stacks.joinToString("") { if(it.isNotEmpty()) it.last().toString() else "" }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput, 3) == "CMZ")
check(part1(testInput, 3, false) == "MCD")
val input = readInput("Day05")
println(part1(input, 9))
println(part1(input, 9, false))
}
| 0 | Kotlin | 0 | 0 | 42941fc84d50b75f9e3952bb40d17d4145a3036b | 1,673 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/day6/Day6ChronalCoordinates.kt | Zordid | 160,908,640 | false | null | package day6
import shared.enclosingArea
import shared.extractCoordinate
import shared.minByIfUnique
import shared.readPuzzle
fun part1(puzzle: List<String>): Int {
val coordinates = puzzle.map { it.extractCoordinate() }
val area = coordinates.enclosingArea()
val infinite = mutableSetOf<Int>()
val ownedArea = IntArray(coordinates.size)
area.forEach { test ->
val atEdge = test isAtEdgeOf area
coordinates
.mapIndexed { idx, c -> idx to c }
.minByIfUnique { (_, c) -> test manhattanDistanceTo c }
?.also { (belongsTo, _) ->
if (atEdge) infinite.add(belongsTo)
ownedArea[belongsTo]++
}
}
return (coordinates.indices - infinite).map { it to ownedArea[it] }.maxBy { it.second }.second
}
tailrec fun part2(puzzle: List<String>, threshold: Int = 10000, safetyMargin: Int = 0): Int {
val coordinates = puzzle.map { it.extractCoordinate() }
val area = coordinates.enclosingArea() + safetyMargin
var safeAreaTouchedEdge = false
val size = area.count { test ->
if (safeAreaTouchedEdge)
return@count false
val atEdge = test isAtEdgeOf area
val belongsToSafeArea = coordinates.sumOf { test manhattanDistanceTo it } < threshold
if (belongsToSafeArea && atEdge) {
println("Warning: safe area reached outer bounds, increasing margin to ${safetyMargin + 1}!")
safeAreaTouchedEdge = true
}
belongsToSafeArea
}
return if (safeAreaTouchedEdge) part2(puzzle, threshold, safetyMargin + 1) else size
}
fun main() {
val puzzle = readPuzzle(6)
println(part1(puzzle))
println(part2(puzzle))
} | 0 | Kotlin | 0 | 0 | f246234df868eabecb25387d75e9df7040fab4f7 | 1,723 | adventofcode-kotlin-2018 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions67.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
import kotlin.math.pow
import kotlin.math.max
fun test67() {
printlnResult(1, 3, 4, 7)
}
/**
* Questions 67: Find the two numbers in an IntArray(all integers equal or greater than 0) that their results of exclusive or is maximum
*/
private fun IntArray.maxXor(): Int {
val trieTree = TrieTree()
val binaryStringSequence = asSequence().map { it.toBinaryString() }
binaryStringSequence.forEach { trieTree.insert(it) }
var max = 0
binaryStringSequence.forEachIndexed { index, num ->
var pointer: TrieNode? = trieTree.head
val builder = StringBuilder()
repeat(31) {
val bit = num[it]
val nextNode = pointer?.next?.let { next ->
if (next[0] != null && next[1] != null) {
if (next[0]?.character != bit) next[0] else next[1]
} else {
next[0] ?: next[1]
}
}
builder.append(nextNode?.character)
pointer = nextNode
}
max = max(max, builder.toString().toInt(2) xor this[index])
}
return max
}
private fun Int.toBinaryString(): String {
var number = 2.0.pow(30).toInt()
return buildString(31) {
while (number > 0) {
val bit = if (this@toBinaryString and number != 0) '1' else '0'
append(bit)
number = number shr 1
}
}
}
private fun printlnResult(vararg numbers: Int) =
println("The maximum exclusive or value in IntArray ${numbers.toList()} is ${numbers.maxXor()}")
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,590 | Algorithm | Apache License 2.0 |
src/Day09.kt | arksap2002 | 576,679,233 | false | {"Kotlin": 31030} | import kotlin.math.abs
class Point(a: Int, b: Int) {
private var x = a
private var y = b
fun isNear(other: Point): Boolean = abs(x - other.x) <= 1 && abs(y - other.y) <= 1
fun goUp() = y++
fun goDown() = y--
fun goLeft() = x--
fun goRight() = x++
fun goToHead(head: Point) {
if (isNear(head)) return
if (y < head.y) y++
if (y > head.y) y--
if (x < head.x) x++
if (x > head.x) x--
}
fun getPair() = Pair(x, y)
}
fun main() {
fun part1(input: List<String>): Int {
val hashSet = HashSet<Pair<Int, Int>>()
val head = Point(0, 0)
val tail = Point(0, 0)
hashSet.add(tail.getPair())
for (line in input) {
val way = line.split(" ")[0]
val count = line.split(" ")[1].toInt()
repeat(count) {
if (way == "U") head.goUp()
if (way == "D") head.goDown()
if (way == "L") head.goLeft()
if (way == "R") head.goRight()
tail.goToHead(head)
hashSet.add(tail.getPair())
}
}
return hashSet.size
}
fun part2(input: List<String>): Int {
val n = 9
val hashSet = HashSet<Pair<Int, Int>>()
val head = Point(0, 0)
val tails = mutableListOf<Point>()
repeat(n) {
tails.add(Point(0, 0))
}
hashSet.add(tails[n - 1].getPair())
for (line in input) {
val way = line.split(" ")[0]
val count = line.split(" ")[1].toInt()
repeat(count) {
if (way == "U") head.goUp()
if (way == "D") head.goDown()
if (way == "L") head.goLeft()
if (way == "R") head.goRight()
tails[0].goToHead(head)
for (i in 1 until n) {
tails[i].goToHead(tails[i - 1])
}
hashSet.add(tails[n - 1].getPair())
}
}
return hashSet.size
}
val input = readInput("Day09")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | a24a20be5bda37003ef52c84deb8246cdcdb3d07 | 2,147 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/io/array/MaxNumberProductThreeNumbers.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.array
// https://leetcode.com/problems/maximum-product-of-three-numbers/
class MaxNumberProductThreeNumbers {
fun execute(input: IntArray): Int =
maxOf(
findBiggest(input, 3).reduce { acc, value -> acc * value },
findSmallest(input, 2).reduce { acc, value -> acc * value } * findBiggest(input, 1).first())
private fun findBiggest(input: IntArray, numbers: Int, founds: MutableList<Int> = mutableListOf()) =
find(input, numbers, founds) { acc, value -> value?.let { it < acc } ?: true }
private fun findSmallest(input: IntArray, numbers: Int, founds: MutableList<Int> = mutableListOf()) =
find(input, numbers, founds) { acc, value -> value?.let { it > acc } ?: true }
private fun find(input: IntArray, numbers: Int, founds: MutableList<Int> = mutableListOf(), condition: (Int, Int?) -> Boolean): List<Int> =
(0 until numbers).map {
input.foldIndexed(null as Pair<Int, Int>?) { index, acc, value ->
if (condition(value, acc?.second) && founds.none { i -> i == index }) index to value else acc
}?.also { founds.add(it.first) }
}.map { it!!.second }
}
fun main() {
val maxNumberProductThreeNumbers = MaxNumberProductThreeNumbers()
listOf(
intArrayOf(1, 2, 3) to 6
).forEachIndexed { index, (input, value) ->
val output = maxNumberProductThreeNumbers.execute(input)
val isValid = output == value
if (isValid)
println("index $index $output is valid")
else
println("index $index Except $value but instead got $output")
}
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,559 | coding | MIT License |
src/day16/Day16.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | package day16
import java.lang.Integer.max
import readInput
class Valve(val rate: Int, val tunnels: List<String>)
fun parseValve(input: String): Pair<String, Valve> {
val regex =
Regex("""Valve (\p{Upper}{2}) has flow rate=(\d+); tunnels? leads? to valves? (((\p{Upper}{2})(, )?)+)""")
val match = regex.matchEntire(input)
val name = match!!.groups[1]!!.value
val rate = match.groups[2]!!.value.toInt()
val tunnels = match.groups[3]!!.value.split(",").map { s -> s.trim() }
return Pair(name, Valve(rate, tunnels))
}
fun parseValves(input: List<String>): Map<String, Valve> {
return input.associate(::parseValve)
}
@Suppress("unused")
fun printValves(valves: Map<String, Valve>) {
for (valve in valves) {
println("${valve.key} : ${valve.value.rate} ${valve.value.tunnels}")
}
}
fun main() {
fun <K> updateData(dataset: MutableMap<K, Int>, key: K, value: Int) {
dataset[key] = max(dataset[key] ?: -1, value)
}
fun <K> increaseData(dataset: MutableMap<K, Int>, key: K, value: Int) {
dataset[key] = dataset[key]!! + value
}
fun getTotalRate(valves: Map<String, Valve>, openValves: Set<String>): Int {
return openValves.sumOf { x -> valves[x]!!.rate }
}
fun part1(valves: Map<String, Valve>): Int {
var currentStepData = mutableMapOf<Pair<Set<String>, String>, Int>()
currentStepData[setOf<String>() to "AA"] = 0
for (minute in 1..29) {
val nextStepData = mutableMapOf<Pair<Set<String>, String>, Int>()
for (option in currentStepData) {
val currentValve = option.key.second
val openValves = option.key.first
val releasedPressure = option.value
for (nextValve in valves[currentValve]!!.tunnels) {
updateData(nextStepData, openValves to nextValve, releasedPressure)
}
if (valves[currentValve]!!.rate > 0)
updateData(nextStepData, openValves.plusElement(currentValve) to currentValve, releasedPressure)
}
for (option in nextStepData) {
increaseData(nextStepData, option.key, getTotalRate(valves, option.key.first))
}
currentStepData = nextStepData
}
return currentStepData.values.max()
}
fun part2(valves: Map<String, Valve>): Int {
var currentStepData = mutableMapOf<Pair<Set<String>, Set<String>>, Int>()
currentStepData[setOf<String>() to setOf("AA")] = 0
for (minute in 1..25) {
val nextStepData = mutableMapOf<Pair<Set<String>, Set<String>>, Int>()
for (option in currentStepData) {
val me = option.key.second.first()
val elephant = option.key.second.last()
val openValves = option.key.first
val releasedPressure = option.value
for (myNext in valves[me]!!.tunnels) {
for (elephantNext in valves[elephant]!!.tunnels) {
updateData(nextStepData, openValves to setOf(myNext,elephantNext), releasedPressure)
}
if (valves[elephant]!!.rate > 0) {
updateData(
nextStepData,
openValves.plusElement(elephant) to setOf(myNext, elephant),
releasedPressure
)
}
}
if (valves[me]!!.rate > 0) {
for (elephantNext in valves[elephant]!!.tunnels) {
updateData(nextStepData, openValves.plusElement(me) to setOf(me, elephantNext), releasedPressure)
}
if (valves[elephant]!!.rate > 0) {
updateData(
nextStepData,
openValves.plusElement(elephant).plusElement(me) to setOf(me, elephant),
releasedPressure
)
}
}
}
for (option in nextStepData) {
increaseData(nextStepData, option.key, getTotalRate(valves, option.key.first))
}
val bestOption = nextStepData.maxBy { e -> e.value }
currentStepData = if (bestOption.key.first.size == valves.values.count { x -> x.rate > 0 }) {
println("Discarding old options")
mutableMapOf(bestOption.key to bestOption.value)
} else {
nextStepData
}
println("Step: $minute, len ${currentStepData.size}")
}
return currentStepData.values.max()
}
println("Day 16")
val testInput = readInput("Day16-test")
val testValves = parseValves(testInput)
val valves = parseValves(readInput("Day16"))
println("part 1 test: ${part1(testValves)}")
println("part 1 real: ${part1(valves)}")
val testPart2Result = part2(testValves)
println("part 2 test: $testPart2Result")
val realPart2Result = part2(valves)
println("part 2 real: $realPart2Result")
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 5,188 | aoc-2022 | Apache License 2.0 |
src/Day10.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} |
var cycle = 0
var x = 1
fun process(ticks: Int, operand: Int): Int {
var result = 0
repeat(ticks) {
cycle++
if ((cycle - 20) % 40 == 0) {
result += x * cycle
}
draw()
}
x += operand
return result
}
fun processDraw(ticks: Int, operand: Int) {
repeat(ticks) {
cycle++
draw()
}
x += operand
}
fun draw() {
val pos = (cycle - 1) % 40
if (pos in x - 1..x + 1) print("#") else print(".")
if (pos == 39) println()
}
fun main() {
fun part1(input: List<String>): Int {
cycle = 0
x = 1
var sum = 0
input.forEach { line ->
val op = line.substring(0, 4)
when (op) {
"noop" -> sum += process(1, 0)
"addx" -> sum += process(2, line.substring(5).toInt())
}
}
return sum
}
fun part2(input: List<String>): Int {
cycle = 0
x = 1
var sum = 0
input.forEach { line ->
val op = line.substring(0, 4)
when (op) {
"noop" -> processDraw(1, 0)
"addx" -> processDraw(2, line.substring(5).toInt())
}
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
println(part1(testInput))
check(part1(testInput) == 13140)
// println(part2(testInput))
// check(part2(testInput) == 36)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 1,592 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/com/keithwedinger/Day7.kt | jkwuc89 | 112,970,285 | false | null | package com.keithwedinger
import java.io.InputStream
import kotlin.math.absoluteValue
/**
* Day 7 Puzzle
* http://adventofcode.com/2017/day/7
*
* @author <NAME> <br>
* Created On: 12/14/17
*/
class Day7 {
private val utils = Utils()
/**
* Part 1
*/
fun findBottomProgram(programTowerInputStream: InputStream): String {
// Input regex, 1 = Node ID, 2 = Weight, 4 = Comma-delimited Children
val regex = """(\w+) \((\d+)\)( -> ([\w, ]+))?""".toRegex()
val programNames = HashMap<String, Boolean>()
val programs = ArrayList<MatchGroupCollection>()
// Split stream input and split lines into program names and program fields
utils.readTestInput(programTowerInputStream).forEach {
val programFields = regex.matchEntire(it)!!.groups
programNames.put(programFields[1]!!.value, true)
programs.add(programFields)
}
// If there are children, then delete those children from the program names
// as they obviously cannot be the root node (as they have a parent)
programs.forEach { programFields ->
if (programFields[4] != null) {
programFields[4]!!.value.split(", ").forEach {
programNames.remove(it)
}
}
}
// Program names map should have 1 node left, the root node.
var rootProgramName = ""
if (!programNames.isEmpty()) {
rootProgramName = programNames.iterator().next().key
}
return rootProgramName
}
/**
* From Day 7 solutions thread on subreddit
*/
fun solvePart1(programTowerInputStream: InputStream): String {
val headOfTree = parseInput(utils.readTestInput(programTowerInputStream))
return headOfTree.name
}
fun solvePart2(programTowerInputStream: InputStream): Int {
val headOfTree = parseInput(utils.readTestInput(programTowerInputStream))
return headOfTree.findImbalance()
}
private fun parseInput(input: List<String>): Node {
val nodesByName = mutableMapOf<String, Node>()
val parentChildPairs = mutableSetOf<Pair<Node, String>>()
val rowRegex = """\w+""".toRegex()
input.forEach {
val groups = rowRegex.findAll(it).toList().map { it.value }
val node = Node(groups[0], groups[1].toInt())
nodesByName.put(node.name, node)
groups.drop(2).forEach {
parentChildPairs.add(Pair(node, it))
}
}
parentChildPairs.forEach { (parent, childName) ->
with(nodesByName.getValue(childName)) {
parent.children.add(this)
this.parent = parent
}
}
// Find the one node we have without a parent. Or freak out.
return nodesByName.values.firstOrNull { it.parent == null }
?: throw IllegalStateException("No head node?!")
}
}
data class Node(val name: String,
private val weight: Int,
val children: MutableList<Node> = mutableListOf(),
var parent: Node? = null) {
fun findImbalance(imbalance: Int? = null): Int =
if (imbalance != null && childrenAreBalanced) {
// We end when I have a positive imbalance and my children are balanced.
weight - imbalance
} else {
// Find the child tree that is off.
val subtreesByWeight = children.groupBy { it.totalWeight }
// Find the imbalanced child tree (they will be the lone node in the list, when grouped by weight)
val badTree = subtreesByWeight.minBy { it.value.size }?.value?.first()
?: throw IllegalStateException("Should not be balanced here.")
// Recurse, passing down our imbalance. If we don't know the imbalance, calculate it.
// Calculate the imbalance as the absolute value of the difference of all distinct weights
badTree.findImbalance(imbalance ?: subtreesByWeight.keys.reduce { a, b -> a - b }.absoluteValue)
}
private val totalWeight: Int by lazy {
weight + children.sumBy { it.totalWeight }
}
private val childrenAreBalanced: Boolean by lazy {
children.map { it.totalWeight }.distinct().size == 1
}
} | 0 | Kotlin | 0 | 0 | 3b88f64a498e4640b021cc91160a5adfcb01d0ec | 4,372 | adventofcode | Apache License 2.0 |
src/Day11.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} | class Monkey(private val items: MutableList<Long>,
private val operation: Char,
private val value: Int,
val divisor: Int,
private val passTarget: Int,
private val failTarget: Int) {
var itemsProcessed = 0L
fun addItem(item: Long) {
items += item
}
fun inspectP1(item: Long): Long {
return when(operation) {
'x' -> item * value
'+' -> item + value
'^' -> {
var result = 1L
for (i in 0 until value) {
result *= item
}
result
}
else -> throw UnsupportedOperationException()
}
}
fun inspectP2(item: Long, lcm: Long): Long {
return when(operation) {
'x' -> (item * value) % lcm
'+' -> (item + value) % lcm
'^' -> {
var result = 1L
for (i in 0 until value) {
result = (result * item) % lcm
}
result
}
else -> throw UnsupportedOperationException()
}
}
private fun test(value: Long) = if (value % divisor == 0L) passTarget else failTarget
fun processAllItemsP1(): List<Pair<Long, Int>> {
if (items.isEmpty()) return listOf()
val result = mutableListOf<Pair<Long, Int>>()
for (item in items) {
val newValue = inspectP1(item) / 3
result += newValue to test(newValue)
}
itemsProcessed += items.size
items.clear()
return result
}
fun processAllItemsP2(lcm: Long): List<Pair<Long, Int>> {
if (items.isEmpty()) return listOf()
val result = mutableListOf<Pair<Long, Int>>()
for (item in items) {
val newValue = inspectP2(item, lcm)
result += newValue to test(newValue)
}
itemsProcessed += items.size
items.clear()
return result
}
}
fun main() {
fun part1(input: Array<Monkey>): Long {
for (i in 0 until 20) {
for (monkey in input) {
for ((item, target) in monkey.processAllItemsP1()) {
input[target].addItem(item)
}
}
}
input.sortByDescending { it.itemsProcessed }
return input[0].itemsProcessed * input[1].itemsProcessed
}
fun part2(input: Array<Monkey>): Long {
val lcm = input.map { it.divisor.toLong() }.reduce { acc, i -> acc * i }
for (i in 0 until 10_000) {
for (monkey in input) {
for ((item, target) in monkey.processAllItemsP2(lcm)) {
input[target].addItem(item)
}
}
}
input.sortByDescending { it.itemsProcessed }
return input[0].itemsProcessed * input[1].itemsProcessed
}
fun generateData(input: List<String>): Array<Monkey> {
return input.map { it ->
val tokens = it.split(" ")
Monkey(
tokens[0].split("|").map { item -> item.toLong() }.toMutableList(),
tokens[1][0],
tokens[2].toInt(),
tokens[3].toInt(),
tokens[4].toInt(),
tokens[5].toInt()
)
}.toTypedArray()
}
val test = readInput("Day11_test")
println(part1(generateData(test)))
println(part2(generateData(test)))
val input = readInput("Day11")
println(part1(generateData(input)))
println(part2(generateData(input)))
} | 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 3,601 | Advent-Of-Code-2022 | Apache License 2.0 |
2021/src/main/kotlin/Day11.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | class Day11(input: List<String>) {
private val grid = OctopusGrid.parse(input)
fun solve1(): Int {
return (1..100).sumOf {
grid.increase()
grid.flash().also { grid.reset() }
}
}
fun solve2(): Int {
return 1 + generateSequence {
grid.increase()
grid.flash()
grid.reset()
}.takeWhile { grid.notSynchronized() }.count()
}
private class OctopusGrid(private val arrays: Array<Array<Int>>) {
fun increase() {
arrays.forEachIndexed { y, row ->
row.forEachIndexed { x, _ ->
arrays[y][x]++
}
}
}
fun reset() {
arrays.forEachIndexed { y, row ->
row.forEachIndexed { x, _ ->
arrays[y][x] = if (arrays[y][x] > 9) 0 else arrays[y][x]
}
}
}
fun flash(): Int {
val visited = mutableSetOf<Pair<Int, Int>>()
arrays.forEachIndexed { y, row ->
row.forEachIndexed { x, energy ->
if (energy > 9 && (y to x) !in visited) {
val toVisit = ArrayDeque(listOf(y to x))
visited.add(y to x)
while (toVisit.isNotEmpty()) {
val (nextY, nextX) = toVisit.removeLast()
neighbours(nextY, nextX).filter { it !in visited }.filter { (y, x) -> ++arrays[y][x] > 9 }
.forEach { (y, x) ->
toVisit.addLast(y to x)
visited.add(y to x)
}
}
}
}
}
return visited.size
}
fun notSynchronized() = arrays.any { row -> row.any { energy -> energy > 0 } }
private fun neighbours(y: Int, x: Int): List<Pair<Int, Int>> {
return (-1..1).flatMap { dy -> (-1..1).map { dx -> dy to dx } }.filterNot { (dy, dx) -> dy == 0 && dx == 0 }
.map { (dy, dx) -> y + dy to x + dx }
.filter { (y, x) -> y in arrays.indices && x in arrays.first().indices }
}
companion object {
fun parse(input: List<String>): OctopusGrid =
input.map { row -> row.toCharArray().map { it.digitToInt() }.toTypedArray() }.toTypedArray()
.let { OctopusGrid(it) }
}
}
} | 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 2,545 | adventofcode-2021-2025 | MIT License |
kotlin/src/katas/kotlin/leetcode/add_two_numbers/AddTwoNumbers.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.add_two_numbers
import nonstdlib.printed
import datsok.shouldEqual
import org.junit.Test
import kotlin.random.Random
/**
* You are given two non-empty linked lists representing two non-negative integers.
* The digits are stored in reverse order and each of their nodes contain a single digit.
* Add the two numbers and return it as a linked list.
*
* You may assume the two numbers do not contain any leading zero, except the number 0 itself.
*
* https://leetcode.com/problems/add-two-numbers
*/
class AddTwoNumbers {
@Test fun `convert integer to linked list`() {
0.toLinkedList() shouldEqual Node(0)
1.toLinkedList() shouldEqual Node(1)
12.toLinkedList() shouldEqual Node(2).linkedTo(Node(1))
30.toLinkedList() shouldEqual Node(0).linkedTo(Node(3))
321.toLinkedList() shouldEqual Node(1).linkedTo(Node(2).linkedTo(Node(3)))
}
@Test fun `convert linked list to string`() {
Node(1).toString() shouldEqual "1"
Node(2).linkedTo(Node(1)).toString() shouldEqual "2 -> 1"
Node(2).linkedTo(Node(3).linkedTo(Node(4))).toString() shouldEqual "2 -> 3 -> 4"
}
@Test fun `add two numbers`() {
Node(1) + Node(2) shouldEqual Node(3)
Node(1) + Node(9) shouldEqual Node(0).linkedTo(Node(1))
Node(9) + Node(1) shouldEqual Node(0).linkedTo(Node(1))
Node(9) + Node(9) shouldEqual Node(8).linkedTo(Node(1))
19.toLinkedList() + 9.toLinkedList() shouldEqual 28.toLinkedList()
99.toLinkedList() + 9.toLinkedList() shouldEqual 108.toLinkedList()
21.toLinkedList() + 43.toLinkedList() shouldEqual 64.toLinkedList()
123.toLinkedList() + 456.toLinkedList() shouldEqual 579.toLinkedList()
342.toLinkedList() + 465.toLinkedList() shouldEqual 807.toLinkedList()
1342.toLinkedList() + 465.toLinkedList() shouldEqual 1807.toLinkedList()
}
@Test fun `add random positive numbers`() {
val random = Random(seed = Random.nextInt().printed("seed: "))
val a = random.nextInt(0, 1_000_000)
val b = random.nextInt(0, 1_000_000)
a.toLinkedList() + b.toLinkedList() shouldEqual (a + b).toLinkedList()
}
}
private fun Int.toLinkedList(): Node {
val node = Node(this % 10)
val n = this / 10
return if (n == 0) node else node.linkedTo(n.toLinkedList())
}
private data class Node(val value: Int, val next: Node? = null) {
fun linkedTo(that: Node?) = copy(next = that)
operator fun plus(that: Node): Node {
val sum = this.value + that.value
var nextSumNode =
if (this.next != null && that.next != null) this.next + that.next
else that.next ?: this.next
if (sum >= 10) nextSumNode = (nextSumNode ?: Node(0)) + Node(1)
return Node(sum % 10).linkedTo(nextSumNode)
}
override fun toString() = if (next == null) value.toString() else "$value -> $next"
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,946 | katas | The Unlicense |
src/main/kotlin/aoc2021/day11.kt | sodaplayer | 434,841,315 | false | {"Kotlin": 31068} | package aoc2021
import aoc2021.utils.head
import aoc2021.utils.loadInput
import aoc2021.utils.tail
fun main() {
val grid = loadInput("/2021/day11")
.bufferedReader()
.readLines()
.flatMap {
it.asSequence()
}
.mapIndexed { i, c -> i to (c.code - 48) }
.toMap()
val sim = generateSequence(Step(grid, 0)) { (state, total) ->
state
.let(::initializeStep)
.let(::reduceFlashes)
.run{ last().state }
.let {
val flashed = tallyFlashed(it)
Step(
it + flashed,
total + flashed.count()
)
}
}
val part1 = sim.take(1 + 100).last()
drawState(part1.state)
println(part1.total)
val part2 = sim
.takeWhile { (state, _) ->
state.values.any { it != 0 }
}
.count()
println(part2)
}
private fun reduceFlashes(initial: FlashResult) =
generateSequence(initial) { (state, queue) ->
if (queue.none()) null
else applyFlash(state, queue)
}
typealias State = Map<Int, Int?>
data class Step(val state: State, val total: Int)
data class FlashResult(val state: State, val queue: Iterable<Int>)
fun applyFlash(state: State, queue: Iterable<Int>): FlashResult {
val i = queue.head()
return if (state[i] == null) FlashResult(state, emptyList())
else state
// increment neighbors
.plus(neighborsMemoized(i).map { it to state[it]?.inc() })
// mark self as flashed
.plus(i to null)
.let { updated ->
FlashResult(
updated,
updated.filterValues { (it ?: 0) > 9 }.keys + queue.tail()
)
}
}
fun initializeStep(state: State): FlashResult {
val updated = state.mapValues { (_, i) ->
i!!.inc()
}
return FlashResult(
updated,
updated.filterValues { it > 9 }.keys.sorted()
)
}
/** Tally flashed octopuses and reset energy levels to 0 */
fun tallyFlashed(state: State): Iterable<Pair<Int, Int>> {
return state
.filterValues { it == null }
.map { (i, _) -> i to 0 }
}
/**
* @param i index into a 10x10 grid starting NW, going horizontal to NE, then row-by-row ending at SE
*/
fun neighbors(i: Int): List<Int> {
val x = i % 10
val y = i / 10
/* | -1 +0 +1
* -1 | -1,-1 +0,-1, +1,-1
* +0 | -1,+0 +0,+0, +1,+0
* +1 | -1,+1 +0,+1, +1,+1
*/
val nw = if (x > 0 && y > 0) x - 1 + (y - 1) * 10 else null
val w = if (x > 0 ) x - 1 + (y + 0) * 10 else null
val sw = if (x > 0 && y < 9) x - 1 + (y + 1) * 10 else null
val n = if ( y > 0) x + 0 + (y - 1) * 10 else null
// c = if ( ) x + 0 + (y + 0) * 10
val s = if ( y < 9) x + 0 + (y + 1) * 10 else null
val ne = if (x < 9 && y > 0) x + 1 + (y - 1) * 10 else null
val e = if (x < 9 ) x + 1 + (y + 0) * 10 else null
val se = if (x < 9 && y < 9) x + 1 + (y + 1) * 10 else null
return listOfNotNull(nw, n, ne, w, e, sw, s, se)
}
val neighborCache = mutableMapOf<Int, List<Int>>()
fun neighborsMemoized(i: Int): List<Int> =
neighborCache.getOrPut(i) {
neighbors(i)
}
/*
* 0 1 2 3 4 5 6 7 8 9
* 10 11 12 13 14 15 16 17 18 19
* 20 21 22 23 24 25 26 27 28 29
* 30 31 32 33 34 35 36 37 38 39
* 40 41 42 43 44 45 46 47 48 49
* 50 51 52 53 54 55 56 57 58 59
* 60 61 62 63 64 65 66 67 68 69
* 70 71 72 73 74 75 76 77 78 79
* 80 81 82 83 84 85 86 87 88 89
* 90 91 92 93 94 95 96 97 98 99
*/
fun drawGridIndices() {
drawState((0..99).associateWith { it })
}
fun drawState(state: State, withIndex: Boolean = false) {
(0..9).forEach { y ->
(0..9).forEach { x ->
if (withIndex) print("%2d:%2d| ".format(x + y * 10, state[x + y * 10]?: 0))
else print("%2d ".format(state[x + y * 10]?: 0))
}
println()
}
}
| 0 | Kotlin | 0 | 0 | 2d72897e1202ee816aa0e4834690a13f5ce19747 | 4,029 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch2/Problem28.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch2
import java.math.BigInteger
import kotlin.math.ceil
/**
* Problem 28: Number Spiral Diagonals
*
* https://projecteuler.net/problem=28
*
* Goal: Return the sum (mod 1e9 + 7) of the diagonal numbers in an NxN grid that is generated
* using a spiral pattern.
*
* Constraints: 1 <= N <= 1e18, with N always odd
*
* Spiral Pattern: Start with 1 & move to the right in a clockwise direction, incrementing the
* numbers.
*
* e.g.: N = 5
* grid = 21 22 23 24 25
* 20 7 8 9 10
* 19 6 1 2 11
* 18 5 4 3 12
* 17 16 15 14 13
* diagonals = {1,3,5,7,9,13,17,21,25}
* sum = 101
*/
class NumberSpiralDiagonals {
private val modulus = BigInteger.valueOf(1_000_000_007)
/**
* SPEED (BETTER) 303.11ms for N = 1e6 + 1
*
* @return Int value of result % (1e9 + 7).
*/
fun spiralDiagSumBrute(n: Long): Int {
var sum = BigInteger.ONE
var num = BigInteger.ONE
var step = BigInteger.TWO
while (step < n.toBigInteger()) {
repeat(4) {
num += step
sum += num
}
step += BigInteger.TWO
}
return sum.mod(modulus).toInt()
}
/**
* Solution based on the formula:
*
* f(n) = 4(2n + 1)^2 - 12n + f(n - 1),
*
* with n as the centre ring number, and
*
* f(0) = 1, as it is the only element, and
*
* f(1) = 25, as the first ring creates a 3x3 grid.
*
* So the side of a ring is 2N + 1 wide with the upper right corner being (2n + 1)^2 or the
* area. So [n] would need to be divided by 2.
*
* SPEED (WORST) 452.20ms for N = 1e6 + 1
*
* @return Int value of result % (1e9 + 7).
* */
fun spiralDiagSumFormulaBrute(n: Long): Int {
var fN = BigInteger.ONE
var num = BigInteger.ONE
val maxNum = BigInteger.valueOf(ceil(n / 2.0).toLong())
while (num < maxNum) {
val even = BigInteger.TWO * num
val odd = even + BigInteger.ONE
fN += 4.toBigInteger() * odd.pow(2) - 6.toBigInteger() * even
num = num.inc()
}
return fN.mod(modulus).toInt()
}
/**
* Solution optimised based on the same formula as above, but reduced to:
*
* f(n) = 16n^2 + 4n + 4 + f(n - 1)
*
* Third order polynomial function required as the 3rd delta between consecutive f(n) gives a
* constant, such that ->
*
* ax^3 + bx^2 + cx + d
*
* Solving for f(0) to f(3) derives the closed-form formula:
*
* f(n) = (16n^3 + 30n^2 + 26n + 3) / 3
*
* SPEED (BEST) 1.2e5ns for N = 1e6 + 1
*
* @return Int value of result % (1e9 + 7).
*/
fun spiralDiagSumFormulaDerived(n: Long): Int {
val x = BigInteger.valueOf((n - 1) / 2)
var sum = 16.toBigInteger() * x.pow(3) + 30.toBigInteger() * x.pow(2)
sum += 26.toBigInteger() * x + 3.toBigInteger()
sum /= 3.toBigInteger()
return sum.mod(modulus).toInt()
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,144 | project-euler-kotlin | MIT License |
src/Day02.kt | copperwall | 572,339,673 | false | {"Kotlin": 7027} | import kotlin.Exception
const val TIE = 3
const val LOSE = 0
const val WIN = 6
enum class Move {
ROCK, PAPER, SCISSORS
}
enum class Outcome {
LOSS, TIE, WIN
}
fun stringToOutcome(s: String): Outcome {
return when (s) {
"X" -> Outcome.LOSS
"Y" -> Outcome.TIE
"Z" -> Outcome.WIN
else -> throw Exception("Unknown string $s")
}
}
val pointsForMove = mapOf(Move.ROCK to 1, Move.PAPER to 2, Move.SCISSORS to 3)
fun strToMove(move: String): Move {
if (move == "A" || move == "X") return Move.ROCK
if (move == "B" || move == "Y") return Move.PAPER
if (move == "C" || move == "Z") return Move.SCISSORS
throw Exception("Unknown move $move")
}
fun main() {
part2()
}
fun part2() {
val testInput = readInput("Day02")
var sum = 0
for (roundStr in testInput) {
sum += calculateRound2(roundStr)
}
println(sum)
}
fun part1() {
val testInput = readInput("Day02")
var sum = 0
for (roundStr in testInput) {
sum += calculateRound1(roundStr)
}
println(sum)
}
fun calculateRound1(round: String): Int {
val (opponentMove, myMove) = round.split(" ").map {
strToMove(it)
}
val movePoints = pointsForMove.getValue(myMove)
val gamePoints = gameLogic(opponentMove, myMove)
return movePoints + gamePoints
}
fun determineMyMove(opponentMove: Move, outcome: Outcome): Move {
when (opponentMove) {
Move.ROCK -> {
return when (outcome) {
Outcome.WIN -> Move.PAPER
Outcome.LOSS -> Move.SCISSORS
Outcome.TIE -> Move.ROCK
}
}
Move.PAPER -> {
return when (outcome) {
Outcome.WIN -> Move.SCISSORS
Outcome.LOSS -> Move.ROCK
Outcome.TIE -> Move.PAPER
}
}
else -> {
return when (outcome) {
Outcome.WIN -> Move.ROCK
Outcome.LOSS -> Move.PAPER
Outcome.TIE -> Move.SCISSORS
}
}
}
}
fun calculateRound2(round: String): Int {
val (opponentMoveStr, outcomeStr) = round.split(" ")
val outcome = stringToOutcome(outcomeStr)
val opponentMove = strToMove(opponentMoveStr)
val myMove = determineMyMove(opponentMove, outcome)
val movePoints = pointsForMove.getValue(myMove)
val gamePoints = gameLogic(opponentMove, myMove)
return movePoints + gamePoints
}
fun gameLogic(opponent: Move, me: Move): Int {
// Tie
if (opponent == me) {
return TIE
}
return if (opponent == Move.ROCK) {
if (me == Move.SCISSORS) LOSE else WIN
} else if (opponent == Move.SCISSORS) {
if (me == Move.PAPER) LOSE else WIN
} else {
// Opponent Paper
if (me == Move.ROCK) LOSE else WIN
}
} | 0 | Kotlin | 0 | 1 | f7b856952920ebd651bf78b0e15e9460524c39bb | 2,854 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day15.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.*
fun main() = Day15.run()
object Day15: Day(2022, 15) {
private val dirs = mutableListOf(Point(1, 1), Point(-1, 1), Point(-1, -1), Point(1, -1))
private val beacons = input.lines().map { ints(it) }.map { (_, _, x2, y2) -> P(x2, y2) }.toSet()
private val pairs = input.lines().map { ints(it) }.map { (x1, y1, x2, y2) -> P(x1 to y1, (x1 to y1).manhattanDistTo(x2 to y2)) }
override fun part1(): Any {
val y = 2000000
val xMax = pairs.map { it.first.x + it.second }.max()
val xMin = pairs.map { it.first.x - it.second }.min()
return (xMin..xMax).count { x ->
!beacons.contains(P(x, y)) && pairs.any {
it.first.manhattanDistTo(
P(
x,
y
)
) <= it.second
}
}
}
override fun part2(): Any {
fun pointImpossible(p: Point): Boolean {
if (p.x <= 0 || p.x > 4000000) return true
if (p.y <= 0 || p.y > 4000000) return true
if (beacons.contains(p)) return true
return pairs.any { it.first.manhattanDistTo(p) <= it.second }
}
fun scanRing(s: Point, ring: Long): Point? {
val count = ring + 1
var cur: Point = s + Point(0, ( -ring - 1).toInt())
for (dir in dirs) for (step in 0 until count) {
cur += dir
if (!pointImpossible(cur)) {
return cur
}
}
return null
}
val target = pairs.firstNotNullOf { scanRing(it.first, it.second.toLong()) }
return target.first.toLong() * 4000000L + target.second.toLong()
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,800 | adventofkotlin | MIT License |
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12954_x_n.kt | boris920308 | 618,428,844 | false | {"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407} | package main.kotlin.programmers.lv01
/**
*
* https://school.programmers.co.kr/learn/courses/30/lessons/12954
*
* 문제 설명
* 함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다.
* 다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요.
*
* 제한 조건
* x는 -10000000 이상, 10000000 이하인 정수입니다.
* n은 1000 이하인 자연수입니다.
* 입출력 예
* x n answer
* 2 5 [2,4,6,8,10]
* 4 3 [4,8,12]
* -4 2 [-4, -8]
*/
fun main() {
println("result = ${solution(2, 5).toList()}")
println("result = ${secondSolution(4, 3).toList()}")
println("result = ${solution(-4, 2).toList()}")
println("result = ${secondSolution(0, 3).toList()}")
}
private fun solution(x: Int, n: Int): LongArray {
val answer = LongArray(n)
for (i in 0 until n) {
answer[i] = x * (i.toLong() + 1);
}
return answer
}
private fun secondSolution(x: Int, n: Int): LongArray = LongArray(n) { i -> x.toLong() * (i+1) }
| 1 | Kotlin | 1 | 2 | 88814681f7ded76e8aa0fa7b85fe472769e760b4 | 1,115 | HoOne | Apache License 2.0 |
src/main/kotlin/day21/day21.kt | corneil | 572,437,852 | false | {"Kotlin": 93311, "Shell": 595} | package day21
import day21.Day21.eval
import main.utils.measureAndPrint
import space.kscience.kmath.functions.ListRationalFunction
import space.kscience.kmath.functions.ListRationalFunctionSpace
import space.kscience.kmath.functions.listRationalFunctionSpace
import space.kscience.kmath.operations.JBigIntegerField
import space.kscience.kmath.operations.Ring
import utils.checkNumber
import utils.readFile
import utils.readLines
import utils.separator
import java.math.BigInteger
enum class Operation(val c: Char) {
PLUS('+'),
MINUS('-'),
MULTIPLY('*'),
DIVIDE('/')
}
sealed interface BaseMonkey {
val name: String
}
data class ValueMonkey(
override val name: String,
val value: Long
) : BaseMonkey
data class OperationMonkey(
override val name: String,
val operation: Operation,
val left: String,
val right: String
) : BaseMonkey
object Day21 {
// create a lif od rational functions for the polynomial solver.
context(ListRationalFunctionSpace<C, Ring<C>>)
fun <C> BaseMonkey.eval(
monkeys: Map<String, BaseMonkey>,
function: (Long) -> C
): ListRationalFunction<C> =
if (name == "humn") {
ListRationalFunction(listOf(ring.zero, ring.one))
} else when (this) {
is ValueMonkey -> ListRationalFunction(listOf(function(value)))
is OperationMonkey -> {
val leftValue = monkeys[left]?.eval(monkeys, function) ?: error("Cannot find $left")
val rightValue = monkeys[right]?.eval(monkeys, function) ?: error("Cannot find $right")
when (operation) {
Operation.PLUS -> leftValue + rightValue
Operation.MINUS -> leftValue - rightValue
Operation.MULTIPLY -> leftValue * rightValue
Operation.DIVIDE -> leftValue / rightValue
}
}
}
}
fun main() {
val testLines = readLines(
"""root: pppw + sjmn
dbpl: 5
cczh: sllz + lgvd
zczc: 2
ptdq: humn - dvpt
dvpt: 3
lfqf: 4
humn: 5
ljgn: 2
sjmn: drzm * dbpl
sllz: 4
pppw: cczh / lfqf
lgvd: ljgn * ptdq
drzm: hmdt - zczc
hmdt: 32"""
)
val lines = readFile("day21")
class Monkey(val name: String, val expression: String, var shout: (() -> Long)? = null) {
fun answer(): Long {
return shout?.invoke() ?: error("Monkey $name cannot shout with $expression")
}
}
fun calcSolution1(input: List<String>): Long {
val monkeys = input.map { line ->
line.split(": ")
.let { (a, b) ->
Monkey(a.trim(), b.trim()) }
}.associateBy { it.name }
monkeys.values.forEach { monkey ->
val value = monkey.expression.toLongOrNull()
if (value != null) {
monkey.shout = { -> value }
} else {
val (a, op, b) = monkey.expression.split(" ")
val left = monkeys[a] ?: error("Cannot find Monkey: $a")
val right = monkeys[b] ?: error("Cannot find Monkey: $b")
monkey.shout = when (op) {
"+" -> { -> left.answer() + right.answer() }
"/" -> { -> left.answer() / right.answer() }
"-" -> { -> left.answer() - right.answer() }
"*" -> { -> left.answer() * right.answer() }
else -> error("Cannot evaluate $op in ${monkey.expression}")
}
}
}
val root = monkeys["root"] ?: error("Cannot find root")
return root.answer()
}
fun calcSolution2(input: List<String>): Long {
val monkeyRules = input.associate { line ->
line.split(": ")
.let { (a, b) ->
a.trim() to b.trim()
}
}.toMutableMap()
val monkeys = monkeyRules.map { (name, expression) ->
val value = expression.toLongOrNull()
name to
if (value != null) {
ValueMonkey(name, value)
} else {
val (left, op, right) = expression.split(" ")
val operation = Operation.values().find { it.c == op.trim().first() }
check(operation != null) { "Operation not found $op" }
OperationMonkey(name, operation, left, right)
}
}.toMap()
val root = monkeys["root"] ?: error("Cannot find root")
@Suppress("UNCHECKED_CAST")
val answer = with(
JBigIntegerField.listRationalFunctionSpace as
ListRationalFunctionSpace<BigInteger, Ring<BigInteger>>
) {
root as OperationMonkey
val leftMonkey = monkeys[root.left] ?: error("Cannot find ${root.left}")
val rightMonkey = monkeys[root.right] ?: error("Cannot find ${root.right}")
val left = leftMonkey.eval(monkeys, BigInteger::valueOf)
val right = rightMonkey.eval(monkeys, BigInteger::valueOf)
val result = left.numerator * right.denominator - right.numerator * left.denominator
when (result.degree) {
0 -> error("We're done")
1 -> -result.coefficients[0] / result.coefficients[1]
else -> error("Wow degree ${result.degree}")
}
}.toLong()
return answer
}
fun part1() {
// warmup
repeat(1000) { calcSolution1(testLines) }
val testResult = measureAndPrint("Part 1 Test Time: ") { calcSolution1(testLines) }
println("Part 1 Test Answer = $testResult")
checkNumber(testResult, 152)
val result = measureAndPrint("Part 1 Time: ") { calcSolution1(lines) }
println("Part 1 Answer = $result")
checkNumber(result, 194501589693264L)
}
fun part2() {
// warmup
repeat(1000) { calcSolution2(testLines) }
val testResult = measureAndPrint("Part 2 Test Time: ") { calcSolution2(testLines) }
println("Part 2 Test Answer = $testResult")
checkNumber(testResult, 301)
val result = measureAndPrint("Part 2 Time: ") { calcSolution2(lines) }
println("Part 2 Answer = $result")
checkNumber(result, 3887609741189L)
}
println("Day - 21")
part1()
separator()
part2()
}
| 0 | Kotlin | 0 | 0 | dd79aed1ecc65654cdaa9bc419d44043aee244b2 | 5,694 | aoc-2022-in-kotlin | Apache License 2.0 |
AdventOfCodeDay20/src/nativeMain/kotlin/Day20a.kt | bdlepla | 451,510,571 | false | {"Kotlin": 165771} | data class Point2d(val x:Int, val y:Int)
class Day20a(lines:List<String>) {
val input = lines.takeWhile{it.isNotEmpty()}.joinToString("")
private val algorithmString: String = input.map { if (it == '#') '1' else '0' }.joinToString("")
private val startingImage: List<String> = parseInput(lines)
fun solvePart1(): Int =
solve(2)
fun solvePart2(): Int =
solve(50)
private fun parseInput(input: List<String>): List<String> =
input.dropWhile{it.isNotEmpty()}.drop(1).map { row ->
row.map { char ->
if (char == '#') 1 else 0
}.joinToString("")
}
private fun Point2d.surrounding(): List<Point2d> =
listOf(
Point2d(x - 1, y - 1), Point2d(x, y - 1), Point2d(x + 1, y - 1),
Point2d(x - 1, y), this, Point2d(x + 1, y),
Point2d(x - 1, y + 1), Point2d(x, y + 1), Point2d(x + 1, y + 1),
)
private operator fun List<String>.contains(pixel: Point2d): Boolean =
pixel.y in this.indices && pixel.x in this.first().indices
private fun List<String>.valueAt(pixel: Point2d, defaultValue: Char): Char =
if (pixel in this) this[pixel.y][pixel.x] else defaultValue
private fun List<String>.nextRound(defaultValue: Char): List<String> =
(-1..this.size).map { y ->
(-1..this.first().length).map { x ->
algorithmString[
Point2d(x, y)
.surrounding()
.map { this.valueAt(it, defaultValue) }
.joinToString("")
.toInt(2)
]
}.joinToString("")
}
private fun solve(rounds: Int): Int =
(1 .. rounds).fold(startingImage to '0') { (image, defaultValue), _ ->
image.nextRound(defaultValue) to if (defaultValue == '0') algorithmString.first() else algorithmString.last()
}.first.sumOf { it.count { char -> char == '1' } }
} | 0 | Kotlin | 0 | 0 | 1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871 | 2,014 | AdventOfCode2021 | The Unlicense |
src/Day02.kt | BionicCa | 574,904,899 | false | {"Kotlin": 20039} | import kotlin.random.Random
enum class RockPaperScissors(val shapeScore: Int) {
ROCK(1), PAPER(2), SCISSORS(3)
}
enum class GameState(val roundScore: Int) {
LOSS(0), DRAW(3), WIN(6)
}
fun main() {
fun part1(input: List<String>): Int {
val operations = input.map { it.split(' ')}
var score = 0
for ((opponent, response) in operations) {
val opponentMove = when (opponent) {
"A" -> RockPaperScissors.ROCK
"B" -> RockPaperScissors.PAPER
else -> RockPaperScissors.SCISSORS
}
val myMove = when (response) {
"X" -> RockPaperScissors.ROCK
"Y" -> RockPaperScissors.PAPER
else -> RockPaperScissors.SCISSORS
}
score += myMove.shapeScore
score += when {
opponentMove == myMove -> GameState.DRAW.roundScore
opponentMove == RockPaperScissors.ROCK && myMove == RockPaperScissors.PAPER
|| opponentMove == RockPaperScissors.PAPER && myMove == RockPaperScissors.SCISSORS
|| opponentMove == RockPaperScissors.SCISSORS && myMove == RockPaperScissors.ROCK
-> GameState.WIN.roundScore
else -> GameState.LOSS.roundScore
}
}
return score
}
fun part2(input: List<String>): Int {
val operations = input.map { it.split(' ')}
var score = 0
for ((opponent, response) in operations) {
val opponentMove = when (opponent) {
"A" -> RockPaperScissors.ROCK
"B" -> RockPaperScissors.PAPER
else -> RockPaperScissors.SCISSORS
}
val endResult = when (response) {
"X" -> GameState.LOSS
"Y" -> GameState.DRAW
else -> GameState.WIN
}
score += endResult.roundScore
when (endResult) {
GameState.LOSS -> {
score += when (opponentMove) {
RockPaperScissors.ROCK -> RockPaperScissors.SCISSORS.shapeScore
RockPaperScissors.PAPER -> RockPaperScissors.ROCK.shapeScore
RockPaperScissors.SCISSORS -> RockPaperScissors.PAPER.shapeScore
}
}
GameState.WIN -> {
score += when (opponentMove) {
RockPaperScissors.ROCK -> RockPaperScissors.PAPER.shapeScore
RockPaperScissors.PAPER -> RockPaperScissors.SCISSORS.shapeScore
RockPaperScissors.SCISSORS -> RockPaperScissors.ROCK.shapeScore
}
}
else -> {
score += opponentMove.shapeScore
}
}
}
return score
}
val testInput = readInput("Day02_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ed8bda8067386b6cd86ad9704bda5eac81bf0163 | 3,114 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin2023/Day001.kt | teodor-vasile | 573,434,400 | false | {"Kotlin": 41204} | package main.kotlin2023
class Day001 {
fun part1(input: String): Int {
val data = parseInput(input)
return data.map { row -> row.find { it.isDigit() }.toString() + row.findLast { it.isDigit() }.toString() }
.sumOf { it.toInt() }
}
fun part2(input: String): Int {
val data = parseInput(input)
val mapped = data
.map { row -> row.replace("nine", "n9e", false) }
.map { row -> row.replace("eight", "e8t", false) }
.map { row -> row.replace("seven", "s7n", false) }
.map { row -> row.replace("six", "s6x", false) }
.map { row -> row.replace("five", "f5e", false) }
.map { row -> row.replace("four", "f4r", false) }
.map { row -> row.replace("three", "t3e", false) }
.map { row -> row.replace("two", "t2o", false) }
.map { row -> row.replace("one", "o1e", false) }
.map { row -> row.find { it.isDigit() }.toString() + row.findLast { it.isDigit() }.toString() }
.sumOf { it.toInt() }
return mapped
}
private fun parseInput(input: String) = input.split("\n")
}
| 0 | Kotlin | 0 | 0 | 2fcfe95a05de1d67eca62f34a1b456d88e8eb172 | 1,161 | aoc-2022-kotlin | Apache License 2.0 |
kotlin/1160-find-words-that-can-be-formed-by-characters.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} | class Solution {
fun countCharacters(words: Array<String>, chars: String): Int {
val charMap = chars.groupingBy { it }.eachCount()
var res = 0
outer@for (word in words) {
val wordMap = word.groupingBy { it }.eachCount()
for ((ch, cnt) in wordMap) {
if (charMap[ch] == null || charMap[ch]!! < cnt)
continue@outer
}
res += word.length
}
return res
}
}
// modularize funtion for readability
class Solution {
fun countCharacters(words: Array<String>, chars: String): Int {
val charMap = chars.getMap()
var res = 0
for (word in words) {
val wordMap = word.getMap()
if (wordMap.canMake(charMap))
res += word.length
}
return res
}
fun IntArray.canMake(another: IntArray): Boolean {
for (i in 0 until 26) {
if (this[i] > another[i])
return false
}
return true
}
fun String.getMap(): IntArray {
val res = IntArray (26)
for (c in this)
res[c - 'a']++
return res
}
}
// Short Kotlin solution
class Solution {
fun countCharacters(words: Array<String>, chars: String) = words
.filter { word ->
word.none { c ->
word.count { it == c } > chars.count { it == c }
}
}
.sumOf { it.length }
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,470 | leetcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/KSmallestPairs.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
/**
* 373. Find K Pairs with Smallest Sums
* @see <a href="https://leetcode.com/problems/find-k-pairs-with-smallest-sums/">Source</a>
*/
fun interface KSmallestPairs {
operator fun invoke(nums1: IntArray, nums2: IntArray, k: Int): List<List<Int>>
}
/**
* Approach: Using Heap
*/
class KSmallestPairsHeap : KSmallestPairs {
override operator fun invoke(nums1: IntArray, nums2: IntArray, k: Int): List<List<Int>> {
val m: Int = nums1.size
val n: Int = nums2.size
val ans: MutableList<List<Int>> = ArrayList()
val visited: MutableSet<Pair<Int, Int>> = HashSet()
val minHeap: PriorityQueue<IntArray> = PriorityQueue { a, b -> a[0] - b[0] }
minHeap.offer(intArrayOf(nums1[0] + nums2[0], 0, 0))
visited.add(Pair(0, 0))
var k0 = k
while (k0-- > 0 && minHeap.isNotEmpty()) {
val top: IntArray = minHeap.poll()
val i = top[1]
val j = top[2]
ans.add(listOf(nums1[i], nums2[j]))
if (i + 1 < m && !visited.contains(Pair(i + 1, j))) {
minHeap.offer(intArrayOf(nums1[i + 1] + nums2[j], i + 1, j))
visited.add(Pair(i + 1, j))
}
if (j + 1 < n && !visited.contains(Pair(i, j + 1))) {
minHeap.offer(intArrayOf(nums1[i] + nums2[j + 1], i, j + 1))
visited.add(Pair(i, j + 1))
}
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,118 | kotlab | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions91.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
import kotlin.math.min
fun test91() {
printlnResult(arrayOf(
intArrayOf(17, 2, 16),
intArrayOf(15, 14, 5),
intArrayOf(13, 3, 1),
))
}
/**
* Questions 91: Paint houses to red, green or blue. The houses that nearby can't be painted with same color.
* Given a series IntArrays to represent the cost of painting, find the minimum cost.
*/
private fun minCost(costs: Array<IntArray>): Int {
require(costs.isNotEmpty()) { "The costs can't be empty" }
return min(
costs red costs.lastIndex,
costs green costs.lastIndex,
costs blue costs.lastIndex,
)
}
private infix fun Array<IntArray>.red(i: Int): Int =
if (i == 0)
first()[0]
else
min(green(i - 1), blue(i - 1)) + this[i][0]
private infix fun Array<IntArray>.green(i: Int): Int =
if (i == 0)
first()[1]
else
min(red(i - 1), blue(i - 1)) + this[i][1]
private infix fun Array<IntArray>.blue(i: Int): Int =
if (i == 0)
first()[2]
else
min(red(i - 1), green(i - 1)) + this[i][2]
private fun min(a: Int, b: Int, c: Int): Int =
min(min(a, b), c)
private fun minCostInLoop(costs: Array<IntArray>): Int {
require(costs.isNotEmpty()) { "The costs can't be empty" }
val first = costs.first()
val cache = intArrayOf(first[0], first[1], first[2])
if (costs.size == 1)
return cache.min()
for (i in 1 ..< costs.size) {
val red = min(cache[1], cache[2]) + costs[i][0]
val green = min(cache[0], cache[2]) + costs[i][1]
val blue = min(cache[0], cache[1]) + costs[i][2]
cache[0] = red
cache[1] = green
cache[2] = blue
}
return cache.min()
}
private fun printlnResult(costs: Array<IntArray>) {
val result = minCostInLoop(costs)
println("The minimum cost is $result, is: ${result == minCost(costs)}")
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,915 | Algorithm | Apache License 2.0 |
src/y2015/Day08.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2015
import util.readInput
object Day08 {
fun part1(input: List<String>): Int {
val quotes = input.sumOf { str ->
str.count { it == '"' }
}
val backs = input.sumOf {
it.split(Regex("\\\\\\\\")).count() - 1
}
val hex = input.sumOf {
(it.replace(Regex("\\\\\\\\"), "")
.split(Regex("\\\\x..")).count() - 1) * 3
}
println("qs, backs, hex: $quotes, $backs, $hex")
return quotes + backs + hex
}
fun part2(input: List<String>): Int {
val quotes = input.sumOf { str ->
str.count { it == '"' }
}
val backs = input.sumOf { str ->
str.count { it == '\\' }
}
println("qs, backs: $quotes, $backs")
return quotes + backs + (input.size * 2)
}
}
fun main() {
val testInput = """
""
"abc"
"aaa\"aaa"
"\x27"
""".trimIndent().split("\n")
println("------Tests------")
println(Day08.part1(testInput))
println(Day08.part2(testInput))
println("------Real------")
val input = readInput("resources/2015/day08")
println(Day08.part1(input))
println(Day08.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,231 | advent-of-code | Apache License 2.0 |
src/day19/Day19.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day19
import readInput
fun main() {
val testInput = readInput("day19/test")
val blueprints = testInput.mapNotNull {
val regex =
"""Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""".toRegex()
val result = regex.matchEntire(it) ?: return@mapNotNull null
val inputValues = result.groupValues.drop(1)
BluePrintData(
inputValues[0].toInt(),
inputValues[1].toInt(),
inputValues[2].toInt(),
inputValues[3].toInt(),
inputValues[4].toInt(),
inputValues[5].toInt(),
inputValues[6].toInt()
)
}
println(blueprints)
println(part1(blueprints))
println(part2(blueprints))
}
private fun part1(blueprints: List<BluePrintData>): Int =
blueprints.sumOf { blueprint ->
blueprint.id * blueprint.getMaxGeodeCount(24)
}
private fun part2(blueprints: List<BluePrintData>): Int =
blueprints.take(3).fold(1) { acc, blueprint ->
acc * blueprint.getMaxGeodeCount(32)
}
private data class BluePrintData(
val id: Int,
val oreCostForOre: Int,
val oreCostForClay: Int,
val oreCostForObsidian: Int,
val clayCostForObsidian: Int,
val oreCostForGeode: Int,
val obsidianCostForGeode: Int
) {
fun getMaxGeodeCount(time: Int): Int {
var currentResultMap: HashMap<RobotCount, MutableSet<AmountCount>> = hashMapOf()
currentResultMap[RobotCount()] = mutableSetOf(AmountCount())
var maxGeode = 0
repeat(time) {
val newResultMap: HashMap<RobotCount, MutableSet<AmountCount>> = hashMapOf()
val remainingTime = time - it
currentResultMap.forEach { (robots, amountList) ->
val checkedAmount = mutableSetOf<AmountCount>()
val nextStateSet = mutableSetOf<Pair<RobotCount, AmountCount>>()
amountList.forEach calculation@{ amount ->
if (checkedAmount.isNotEmpty() && checkedAmount.all { amount.isSmall(it) }) {
return@calculation
}
if (maxGeode > amount.geode + (remainingTime - 1) * robots.geodeRobot) {
return@calculation
}
checkedAmount.add(amount)
val nextAmount = AmountCount(
amount.ore + robots.oreRobot,
amount.clay + robots.clayRobot,
amount.obsidian + robots.obsidianRobot,
amount.geode + robots.geodeRobot
)
nextStateSet.add(robots to nextAmount)
if (amount.canBuildOre()) {
val nextRobot = robots.copy(oreRobot = robots.oreRobot + 1)
val newAmount = nextAmount.copy(ore = nextAmount.ore - oreCostForOre)
nextStateSet.add(nextRobot to newAmount)
}
if (amount.canBuildClay()) {
val nextRobot = robots.copy(clayRobot = robots.clayRobot + 1)
val newAmount = nextAmount.copy(ore = nextAmount.ore - oreCostForClay)
nextStateSet.add(nextRobot to newAmount)
}
if (amount.canBuildObsidian()) {
val nextRobot = robots.copy(obsidianRobot = robots.obsidianRobot + 1)
val newAmount = nextAmount.copy(
ore = nextAmount.ore - oreCostForObsidian,
clay = nextAmount.clay - clayCostForObsidian
)
nextStateSet.add(nextRobot to newAmount)
}
if (amount.canBuildGeode()) {
val nextRobot = robots.copy(geodeRobot = robots.geodeRobot + 1)
val newAmount = nextAmount.copy(
ore = nextAmount.ore - oreCostForGeode,
obsidian = nextAmount.obsidian - obsidianCostForGeode
)
nextStateSet.add(nextRobot to newAmount)
}
}
nextStateSet.forEach { (robots, amount) ->
if (newResultMap.containsKey(robots)) {
newResultMap[robots]!!.add(amount)
} else {
newResultMap[robots] = mutableSetOf(amount)
}
}
}
maxGeode = newResultMap.maxOf { it.value.maxOf { it.geode } }
println("[${it + 1}] $maxGeode - ${newResultMap.size}")
currentResultMap = newResultMap
}
return maxGeode
}
private fun AmountCount.canBuildOre(): Boolean =
ore >= oreCostForOre
private fun AmountCount.canBuildClay(): Boolean =
ore >= oreCostForClay
private fun AmountCount.canBuildObsidian(): Boolean =
clay >= clayCostForObsidian && ore >= oreCostForObsidian
private fun AmountCount.canBuildGeode(): Boolean =
obsidian >= obsidianCostForGeode && ore >= oreCostForGeode
private data class State(val robots: RobotCount, val amount: AmountCount)
private data class RobotCount(
val oreRobot: Int = 1,
val clayRobot: Int = 0,
val obsidianRobot: Int = 0,
val geodeRobot: Int = 0
)
private data class AmountCount(val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0) {
fun isSmall(from: AmountCount): Boolean =
ore <= from.ore && clay <= from.clay && obsidian <= from.obsidian && geode <= from.obsidian
}
}
| 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 5,877 | advent-of-code-2022 | Apache License 2.0 |
y2016/src/main/kotlin/adventofcode/y2016/Day01.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2016
import adventofcode.io.AdventSolution
import adventofcode.util.collections.firstDuplicate
import adventofcode.util.collections.onlyChanges
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
object Day01 : AdventSolution(2016, 1, "No Time for a Taxicab") {
override fun solvePartOne(input: String) = parseCommands(input)
.fold(Person(Direction.UP, Vec2.origin), Person::applyCommand)
.position
.distance(Vec2.origin)
override fun solvePartTwo(input: String) = parseCommands(input)
.flatMap(Command::decompose)
.scan(Person(Direction.UP, Vec2.origin), Person::applyCommand)
.map(Person::position)
.onlyChanges()
.firstDuplicate()
.distance(Vec2.origin)
private fun parseCommands(input: String) = input
.splitToSequence(", ")
.flatMap { listOf(it.substring(0, 1), it.substring(1)) }
.map(String::toCommand)
}
private sealed class Command {
abstract fun apply(p: Person): Person
open fun decompose() = listOf(this)
data class Forward(val distance: Int) : Command() {
override fun apply(p: Person) = p.copy(position = p.position + p.direction.vector * distance)
override fun decompose() = List(distance) { SingleStep }
}
object Left : Command() {
override fun apply(p: Person) = p.copy(direction = p.direction.turnLeft)
}
object Right : Command() {
override fun apply(p: Person) = p.copy(direction = p.direction.turnRight)
}
object SingleStep : Command() {
override fun apply(p: Person) = p.copy(position = p.position + p.direction.vector)
}
}
private fun String.toCommand() = when (this) {
"L" -> Command.Left
"R" -> Command.Right
"1" -> Command.SingleStep
else -> Command.Forward(toInt())
}
private data class Person(val direction: Direction, val position: Vec2) {
fun applyCommand(c: Command) = c.apply(this)
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,986 | advent-of-code | MIT License |
src/main/kotlin/y2015/day02/Day02.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2015.day02
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
data class Present(
val length: Int,
val width: Int,
val height: Int,
)
fun Present.calculatePaperNeeded(): Int {
return 2 * length * width + 2 * width * height + 2 * height * length + minOf(
length * width,
width * height,
height * length
)
}
fun Present.calculateRibbonNeeded(): Int {
val wrap = when {
maxOf(length, width, height) == length -> 2 * width + 2 * height
maxOf(length, width, height) == width -> 2 * length + 2 * height
else -> 2 * width + 2 * length
}
return length * width * height + wrap
}
fun input(): List<Present> {
return AoCGenerics.getInputLines("/y2015/day02/input.txt").map { line ->
val measures = line.split("x").map { it.toInt() }
Present(measures[0], measures[1], measures[2])
}
}
fun part1(): Int {
val presents = input()
return presents.sumOf { it.calculatePaperNeeded() }
}
fun part2(): Int {
val presents = input()
return presents.sumOf { it.calculateRibbonNeeded() }
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 1,174 | AdventOfCode | MIT License |
src/Day04.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | fun main() {
fun parse(line: String) = line
.split(',')
.map {
val (start, end) = it.split('-').map(String::toInt)
start..end
}
fun IntRange.includes(range: IntRange) = range.first in this && range.last in this
fun IntRange.overlaps(range: IntRange) = range.first in this || range.last in this
fun part1(input: List<String>): Int {
return input.count { line ->
val (a, b) = parse(line)
b.includes(a) || a.includes(b)
}
}
fun part2(input: List<String>): Int {
return input.count { line ->
val (a, b) = parse(line)
b.overlaps(a) || b.includes(a) || a.includes(b)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 1,000 | AdventOfCode2022 | Apache License 2.0 |
src/questions/NextGreaterElement.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
import java.util.*
/**
* The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
*
* You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2
* and all are unique.
*
* For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j]
* and determine the next greater element of nums2[j] in nums2. If there is no next greater element,
* then the answer for this query is -1.
*
* [Source](https://leetcode.com/problems/next-greater-element-i/)
*/
@UseCommentAsDocumentation
private fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray {
// Since nums1 values are unique, so order is maintained
val nums1Set = nums1.toSet()
// This will hold sorted value of nums2 as it is seen
val sortedSeenSet = TreeSet<Int>()
val result = IntArray(nums1.size) { -1 }
// how many of values in [nums1] is seen and updated in [result]
var count = result.size
for (i in nums2.lastIndex downTo 0) { // Start from last
val current = nums2[i]
sortedSeenSet.add(current) // add it to sorted data structure
val indexInNums1 = nums1Set.indexOf(current)
if (indexInNums1 != -1) { // [current] is present in [nums1]
// [current] is already added in [sortedSeenSet]
// Find where it is there
val indexInSeenSet = sortedSeenSet.indexOf(current)
// Find the next best answer which is right after
val nextElement = sortedSeenSet.elementAtOrNull(indexInSeenSet + 1)
if (nextElement == null) {
// there is no next greater value;
// this may be the biggest value
result[indexInNums1] = -1
} else {
// even though [nextElement] is the next biggest value in ascending order,
// there might be other larger values in between [current] and [nextElement]
// for eg:
var startFrom = i + 1
while (startFrom <= nums2.lastIndex && nums2[startFrom] != nextElement && nums2[startFrom] < current) {
startFrom++
}
result[indexInNums1] = nums2[startFrom]
}
count--
}
if (count == 0) {
break
}
}
return result
}
private fun nextGreaterElementSimple(nums1: IntArray, nums2: IntArray): IntArray {
// Since nums1 values are unique, so order is maintained
val nums1Set = nums1.toSet()
val result = IntArray(nums1.size) { -1 }
// how many of values in [nums1] is seen and updated in [result]
var count = result.size
for (i in nums2.lastIndex downTo 0) { // Start from last
val current = nums2[i]
val indexInNums1 = nums1Set.indexOf(current)
if (indexInNums1 != -1) { // [current] is present in nums1
var startFrom = i + 1
// find the greater element from current index
while (nums2.getOrNull(startFrom) != null && nums2[startFrom] < current) {
startFrom++
}
// if not found, use -1
result[indexInNums1] = nums2.getOrNull(startFrom) ?: -1
count--
}
if (count == 0) {
break
}
}
return result
}
fun main() {
nextGreaterElement(
nums1 = intArrayOf(1, 3, 5, 2, 4),
nums2 = intArrayOf(6, 5, 4, 3, 2, 1, 7)
) shouldBe intArrayOf(7, 7, 7, 7, 7)
nextGreaterElementSimple(
nums1 = intArrayOf(1, 3, 5, 2, 4),
nums2 = intArrayOf(6, 5, 4, 3, 2, 1, 7)
) shouldBe intArrayOf(7, 7, 7, 7, 7)
//Explanation: The next greater element for each value of nums1 is as follows:
// 4 is underlined in nums2 = (1,3,4,2). There is no next greater element, so the answer is -1.
// 1 is underlined in nums2 = (1,3,4,2). The next greater element is 3.
// 2 is underlined in nums2 = (1,3,4,2). There is no next greater element, so the answer is -1.
nextGreaterElement(nums1 = intArrayOf(4, 1, 2), nums2 = intArrayOf(1, 3, 4, 2)) shouldBe intArrayOf(-1, 3, -1)
nextGreaterElementSimple(nums1 = intArrayOf(4, 1, 2), nums2 = intArrayOf(1, 3, 4, 2)) shouldBe intArrayOf(-1, 3, -1)
// Explanation: The next greater element for each value of nums1 is as follows:
// 2 is underlined in nums2 = (1, 2, 3, 4).The next greater element is 3.
// 4 is underlined in nums2 = (1, 2, 3, 4).There is no next greater element, so the answer is-1.
nextGreaterElement(nums1 = intArrayOf(2, 4), nums2 = intArrayOf(1, 2, 3, 4)) shouldBe intArrayOf(3, -1)
nextGreaterElementSimple(nums1 = intArrayOf(2, 4), nums2 = intArrayOf(1, 2, 3, 4)) shouldBe intArrayOf(3, -1)
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 4,912 | algorithms | MIT License |
src/main/kotlin/days/Day7.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
class Day7 : Day(7) {
override fun partOne(): Any {
val root = Directory("/", null)
readInput(root)
return getAllSizesThat(root) { it < 100000 }.sum()
}
override fun partTwo(): Any {
val root = Directory("/", null)
readInput(root)
val (totalSize, requiredSize) = 70000000 to 30000000
return (totalSize - root.size).let { currentlyFree ->
getAllSizesThat(root) { currentlyFree + it >= requiredSize }.minOrNull()!!
}
}
private fun readInput(root: Directory) {
var currentDir = root
var line = 0
while (line < inputList.size) {
val input = inputList[line]
val (command, param) = "\\$ (cd|ls)( .*)?"
.toRegex().matchEntire(input)!!.groupValues.drop(1)
.map { it.trim() }
when (command) {
"cd" -> {
when (param) {
"/" -> {
currentDir = root
}
".." -> {
currentDir = currentDir.parent
?: throw IllegalStateException("Cannot go to parent directory of $currentDir")
}
else -> {
currentDir = currentDir.contents.find { it.name == param } as Directory?
?: throw IllegalStateException("Cannot go to $param directory of $currentDir")
}
}
line += 1
}
"ls" -> {
line = readContents(currentDir, inputList, line + 1)
}
else -> throw IllegalArgumentException("Unknown command: $command")
}
}
}
private fun getAllSizesThat(obj: FileSystemObj, filter: (Int) -> Boolean): Collection<Int> {
return obj.size.let {
if (obj is Directory && filter(it)) listOf(it) else emptyList()
}.plus(
if (obj is Directory) obj.contents.flatMap { getAllSizesThat(it, filter) } else emptyList()
)
}
private fun readContents(currentDir: Directory, inputList: List<String>, startLine: Int): Int {
var line = startLine
val contents = mutableListOf<FileSystemObj>()
while (line < inputList.size && !inputList[line].startsWith('$')) {
val (left, right) = inputList[line].split(" ")
when (left) {
"dir" -> contents.add(Directory(right, currentDir))
else -> contents.add(File(right, currentDir, left.toInt()))
}
line += 1
}
currentDir.contents = contents
return line
}
data class Directory(
val dirName: String,
val parent: Directory?,
var contents: List<FileSystemObj> = emptyList()
) : FileSystemObj() {
override val name = dirName
override val size: Int by lazy {
contents.sumOf { it.size }
}
}
data class File(val fileName: String, val parent: Directory, val fileSize: Int) : FileSystemObj() {
override val name: String = fileName
override val size: Int = fileSize
}
abstract class FileSystemObj {
abstract val name: String
abstract val size: Int
}
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 3,408 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/Day10.kt | armandmgt | 573,595,523 | false | {"Kotlin": 47774} | fun main() {
abstract class Triable {
abstract fun tryObservation(cycle: Int, reg: Int): Triable
abstract fun value(): Any
}
data class State(val cycle: Int, val reg: Int, val triable: Triable)
data class SumSignalStrengths(val value: Int) : Triable() {
override fun tryObservation(cycle: Int, reg: Int): SumSignalStrengths {
if ((cycle - 20) % 40 != 0) return this
return copy(value = value + reg * cycle).also {
// println("At cycle $cycle reg = $reg, signal = ${reg * cycle}, sum = $it")
}
}
override fun value(): Int = value
}
val addPattern = Regex("addx (-?\\d+)")
fun execInstructions(input: List<String>, initial: State) = input.fold(initial) { state, instr ->
var (cycle, reg, triable) = state
triable = triable.tryObservation(cycle, reg)
cycle += 1
when {
addPattern.matches(instr) -> {
triable = triable.tryObservation(cycle, reg)
val (value) = addPattern.find(instr)!!.destructured
reg += value.toInt()
cycle += 1
}
}
State(cycle, reg, triable)
}.triable.value()
fun part1(input: List<String>): Int {
val initial = State(1, 1, SumSignalStrengths(0))
return execInstructions(input, initial) as Int
}
@Suppress("ArrayInDataClass")
data class CRT(var value: Array<Char>) : Triable() {
override fun tryObservation(cycle: Int, reg: Int): CRT {
val crtCursorPos = (cycle - 1) % 40
(reg - 1..reg + 1).forEach {
if (crtCursorPos == it) {
value[cycle - 1] = '#'
}
}
return this
}
override fun value(): String = value.asIterable().chunked(40).joinToString("\n") { it.joinToString("") }
// .also(::println)
}
fun part2(input: List<String>): String {
val initial = State(1, 1, CRT(Array(6 * 40) { '.' }))
return execInstructions(input, initial) as String
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("resources/Day10_test")
check(part1(testInput) == 13140)
val input = readInput("resources/Day10")
println(part1(input))
val result2 = readInput("resources/Day10_test2").joinToString("\n")
check(part2(testInput) == result2)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 0d63a5974dd65a88e99a70e04243512a8f286145 | 2,493 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/days/Day11.kt | butnotstupid | 433,717,137 | false | {"Kotlin": 55124} | package days
class Day11 : Day(11) {
override fun partOne(): Any {
val grid = inputList.map { it.map { Character.getNumericValue(it) }.toTypedArray() }.toTypedArray()
return generateSequence { step(grid) }.take(100).sum()
}
override fun partTwo(): Any {
val grid = inputList.map { it.map { Character.getNumericValue(it) }.toTypedArray() }.toTypedArray()
return generateSequence { step(grid) }.indexOfFirst { it == 100 } + 1
}
private fun step(grid: Array<Array<Int>>): Int {
// increase each octopus level +1
for (i in grid.indices) {
for (j in grid[i].indices) {
grid[i][j] += 1
}
}
// flash all
val flashed = Array(grid.size) { Array(grid.first().size) { false } }
for (i in grid.indices) {
for (j in grid[i].indices) {
if (!flashed[i][j] && grid[i][j] > 9) {
flash(i, j, grid, flashed)
}
}
}
// zero flashed
for (i in grid.indices) {
for (j in grid[i].indices) {
if (grid[i][j] > 9) grid[i][j] = 0
}
}
return flashed.sumOf { it.count { it } }
}
private fun flash(i: Int, j: Int, grid: Array<Array<Int>>, flashed: Array<Array<Boolean>>) {
val di = listOf(-1, -1, -1, 0, 0, 1, 1, 1)
val dj = listOf(-1, 0, 1, -1, 1, -1, 0, 1)
flashed[i][j] = true
for ((dii, djj) in di.zip(dj)) {
if (i + dii in grid.indices && j + djj in grid.first().indices) {
grid[i + dii][j + djj] += 1
if (grid[i + dii][j + djj] > 9 && !flashed[i + dii][j + djj]) {
flash(i + dii, j + djj, grid, flashed)
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | a06eaaff7e7c33df58157d8f29236675f9aa7b64 | 1,835 | aoc-2021 | Creative Commons Zero v1.0 Universal |
day3/day3/src/main/kotlin/Day4.kt | teemu-rossi | 437,894,529 | false | {"Kotlin": 28815, "Rust": 4678} |
val CARD_WIDTH = 5
val CARD_HEIGHT = 5
fun List<Int>.isBingo(inputs: List<Int>) = this.all { inputs.contains(it) }
data class BingoCard(
val numbers: List<Int>
) {
fun get(row: Int, column: Int): Int = numbers[row * CARD_WIDTH + column]
fun getRow(row: Int) = (0 until CARD_WIDTH).map { get(row, it) }
fun getColumn(column: Int) = (0 until CARD_HEIGHT).map { get(it, column) }
fun isBingo(inputs: List<Int>): Boolean {
for (row in 0 until CARD_HEIGHT) {
if (getRow(row).isBingo(inputs)) {
return true
}
}
for (col in 0 until CARD_WIDTH) {
if (getColumn(col).isBingo(inputs)) {
return true
}
}
return false
}
fun getScore(inputs: List<Int>): Int = numbers.filter { it !in inputs }.sum()
}
fun main(args: Array<String>) {
println("Hello World!")
val values = generateSequence(::readLine)
.mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } }
.toList()
val bingoInput = values.first().split(",").map { it.toInt() }
val boards = values
.drop(1)
.windowed(CARD_HEIGHT, step = CARD_HEIGHT)
.map { list -> BingoCard(list.joinToString(" ").split(" ").filter { it.isNotBlank() }.map { num -> num.toInt() }) }
for (i in bingoInput.indices) {
val inputs = bingoInput.take(i)
val winner = boards.firstOrNull { it.isBingo(inputs) }
if (winner != null) {
println("score: ${winner.getScore(inputs)}")
println("result: ${winner.getScore(inputs) * bingoInput[i - 1]}")
break
}
}
val boards2 = boards.toMutableList()
for (i in 1 until bingoInput.size) {
val inputs = bingoInput.take(i)
println("i=$i inputs=$inputs")
val winners = boards2.filter { it.isBingo(inputs) }
if (winners.size == 1 && boards2.size == 1) {
println("2nd score: ${winners.first().getScore(inputs)}")
println("2nd result: ${winners.first().getScore(inputs) * inputs.last()}")
break
}
println("removed $winners, remaining ${boards2.size}")
boards2.removeAll(winners)
}
} | 0 | Kotlin | 0 | 0 | 16fe605f26632ac2e134ad4bcf42f4ed13b9cf03 | 2,246 | AdventOfCode | MIT License |
src/main/kotlin/de/dikodam/day07/Day07.kt | dikodam | 317,290,436 | false | null | package de.dikodam.day07
import de.dikodam.AbstractDay
fun main() {
Day07()()
}
private typealias DirectedAcyclWeightedGraph = List<Node>
private typealias Node = Pair<String, NodeChildren>
private typealias NodeChildren = List<Pair<String, Int>>
class Day07 : AbstractDay() {
override fun task1(): String {
val graph = input
.lineSequence()
.map { parseLine(it) }
.toList()
var newColorsWereAdded = true
val currentColors: MutableSet<String> = extractParentColorsForChildColor(graph, "shiny gold").toMutableSet()
while (newColorsWereAdded) {
val newParentColors: Set<String> = currentColors
.flatMap { childColor -> extractParentColorsForChildColor(graph, childColor) }
.toMutableSet()
val sizeBefore = currentColors.size
currentColors.addAll(newParentColors)
newColorsWereAdded = currentColors.size > sizeBefore
}
// task: how many different colors can contain "shiny gold"
currentColors.forEach { println(it) }
return "${currentColors.size}"
}
override fun task2(): String {
val graph = input
.lineSequence()
.map { parseLine(it) }
.toList()
fun DirectedAcyclWeightedGraph.getNode(color: String): Node {
return this.first { (nodeColor, _) -> color == nodeColor }
}
fun Node.count(): Int {
val children: NodeChildren = this.second
return if (children.isEmpty()) {
0
} else {
children.map { (name, count) -> count + count * graph.getNode(name).count() }.sum()
}
}
val sum = graph.getNode("shiny gold").count()
return "$sum"
}
fun extractParentColorsForChildColor(graph: DirectedAcyclWeightedGraph, childColor: String): Set<String> {
return graph.filter { (_, children) -> children.map { it.first }.contains(childColor) }
.map { (parentcolor, _) -> parentcolor }
.toSet()
}
// AMOUNT_DEF := "1 COLOR bag" OR "AMOUNT COLOR bags"
// AMOUNT_DEFINITIONS := "no other bags." OR "AMOUNT_DEF." OR "AMOUNT_DEF(, AMOUNT_DEF)*."
//x contains none: <COLOR contain no other bags.>
// "faded blue bags contain no other bags."
//x contains 1 colors: <COLOR + " contain AMOUNT_DEF.>
// "bright white bags contain 1 shiny gold bag."
//x contains 1+ colors: <COLOR contain AMOUNT_DEF(, AMOUNT_DEF)*. >
//"dark orange bags contain 3 bright white bags, 4 muted yellow bags."
// step 1:
// split(" contain ") -> COLOR, AMOUNT_DEFINITIONS
private fun parseLine(line: String): Pair<String, List<Pair<String, Int>>> {
val (keyColorBags, rawAmountDefinitions) = line
.dropLast(1) // the . is unnecessary
.split(" contain ")
val amountDefinitions: List<Pair<String, Int>> = parseAmountDefinitions(rawAmountDefinitions)
val keyColor = keyColorBags.dropLast(5) // drop " bags"
return keyColor to amountDefinitions
}
// step 2: decide how many amount definitions
// ends with "no other bags" -> none => COLOR : 0 (?)
// contains(',') -> several => parseSeveral()
// else -> exactly one => parseOne()
private fun parseAmountDefinitions(rawAmountDefinitions: String): List<Pair<String, Int>> {
return when {
rawAmountDefinitions.endsWith("no other bags") -> emptyList()
rawAmountDefinitions.contains(",") -> parseSeveralColorDefinitionLines(rawAmountDefinitions)
else -> listOf(parseOneColorDefinition(rawAmountDefinitions))
}
}
// parseSeveral() split(", "), forEach parseOne()
private fun parseSeveralColorDefinitionLines(rawAmountDefinitions: String): List<Pair<String, Int>> {
return rawAmountDefinitions.split(", ")
.map { colorDefinition -> parseOneColorDefinition(colorDefinition) }
}
// "1 faded blue bag"
// "4 muted yellow bags"
// split(" ") -> <AMOUNT, COLOR, COLOR, _> => return <COLOR, AMOUNT>
private fun parseOneColorDefinition(rawAmountDefinitions: String): Pair<String, Int> {
val (amount, colorPart1, colorPart2) = rawAmountDefinitions.split(" ")
return "$colorPart1 $colorPart2" to amount.toInt()
}
private 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."""
private val input = """mirrored silver bags contain 4 wavy gray bags.
clear tan bags contain 5 bright purple bags, 1 pale black bag, 5 muted lime bags.
dim crimson bags contain 5 vibrant salmon bags, 2 clear cyan bags, 2 striped lime bags, 5 vibrant violet bags.
mirrored beige bags contain 4 pale gold bags, 1 pale aqua bag.
pale maroon bags contain 2 dotted orange bags.
dim tan bags contain no other bags.
bright crimson bags contain 4 dull gold bags, 1 dim lime bag, 2 plaid crimson bags, 3 pale gold bags.
muted violet bags contain 2 dim lavender bags, 2 dotted fuchsia bags, 5 dull indigo bags.
drab yellow bags contain 4 shiny plum bags, 3 dark chartreuse bags.
dark cyan bags contain 2 wavy beige bags.
shiny olive bags contain 2 shiny indigo bags, 4 faded tomato bags.
wavy plum bags contain 4 posh gold bags, 5 light plum bags, 5 dotted lavender bags.
wavy gold bags contain 3 drab coral bags, 2 posh yellow bags, 4 pale magenta bags, 3 shiny orange bags.
wavy chartreuse bags contain 4 bright turquoise bags, 1 pale tan bag, 2 wavy gray bags, 4 muted plum bags.
dark tomato bags contain 2 shiny violet bags, 5 dim olive bags.
posh aqua bags contain 1 pale white bag, 5 pale olive bags, 3 dotted cyan bags, 2 striped teal bags.
drab blue bags contain 5 faded plum bags, 4 mirrored lime bags, 1 wavy teal bag.
drab orange bags contain 1 dull lavender bag.
vibrant orange bags contain 5 muted plum bags.
drab tan bags contain 3 pale tomato bags, 1 dull indigo bag, 2 clear tan bags, 1 dim green bag.
plaid beige bags contain 4 faded crimson bags, 5 faded purple bags.
shiny white bags contain 5 striped black bags.
shiny orange bags contain 2 faded olive bags.
bright blue bags contain 1 striped tan bag, 1 plaid crimson bag, 1 light magenta bag.
faded green bags contain 4 clear turquoise bags, 1 mirrored indigo bag, 3 vibrant fuchsia bags.
wavy red bags contain 5 shiny fuchsia bags, 1 dim bronze bag, 4 dim turquoise bags, 3 dotted violet bags.
dim aqua bags contain 4 striped plum bags, 5 posh tan bags, 1 mirrored gray bag, 2 muted brown bags.
striped bronze bags contain 4 pale red bags, 4 pale tomato bags, 1 faded gray bag.
shiny lavender bags contain 5 vibrant magenta bags, 1 bright turquoise bag, 2 shiny beige bags, 4 pale tan bags.
dotted olive bags contain 1 striped bronze bag, 1 dim lavender bag, 5 posh plum bags, 2 posh silver bags.
shiny tomato bags contain 2 shiny magenta bags, 1 shiny gold bag.
dark brown bags contain 5 shiny gold bags, 3 faded crimson bags, 1 mirrored gray bag.
pale violet bags contain 3 plaid blue bags.
muted brown bags contain 5 clear fuchsia bags, 2 shiny orange bags.
clear silver bags contain 1 shiny gold bag, 5 bright beige bags.
plaid green bags contain 3 striped magenta bags, 2 posh plum bags.
clear beige bags contain 4 plaid lavender bags.
pale red bags contain 4 muted maroon bags, 4 dark black bags.
dull lavender bags contain 5 clear fuchsia bags, 1 muted blue bag, 1 shiny gold bag, 5 dotted turquoise bags.
posh red bags contain 2 pale black bags, 3 shiny violet bags, 1 dull gray bag.
mirrored aqua bags contain 1 dull gold bag.
drab red bags contain 2 muted violet bags, 1 vibrant plum bag.
plaid crimson bags contain 4 faded olive bags, 2 shiny purple bags, 2 dotted magenta bags.
plaid tomato bags contain 1 plaid turquoise bag, 5 muted lime bags.
posh lavender bags contain 2 posh crimson bags, 5 striped magenta bags, 4 bright purple bags.
posh beige bags contain 4 drab tan bags, 2 posh salmon bags, 2 dotted brown bags, 3 muted plum bags.
drab aqua bags contain 5 pale red bags, 2 dim green bags, 3 dim white bags.
bright gray bags contain 5 faded green bags, 3 posh crimson bags.
shiny purple bags contain 4 dark black bags, 3 vibrant magenta bags, 3 pale tan bags, 4 bright turquoise bags.
dim yellow bags contain 1 dark black bag.
dotted magenta bags contain 5 pale lavender bags.
clear bronze bags contain 3 dim lavender bags, 3 drab indigo bags.
pale tomato bags contain 3 wavy teal bags, 2 posh tomato bags, 4 vibrant magenta bags, 2 pale orange bags.
dull violet bags contain 3 wavy beige bags, 4 wavy brown bags, 5 drab fuchsia bags, 1 mirrored white bag.
shiny teal bags contain 3 dark gray bags, 1 pale red bag, 3 light bronze bags, 1 dim cyan bag.
mirrored salmon bags contain 3 pale red bags, 3 dim white bags, 5 faded teal bags, 5 pale purple bags.
striped maroon bags contain 3 drab turquoise bags, 2 bright blue bags, 1 shiny indigo bag.
posh crimson bags contain 2 muted teal bags.
faded olive bags contain 2 muted plum bags, 4 mirrored lavender bags.
drab fuchsia bags contain 1 clear lavender bag, 3 dark yellow bags, 2 drab violet bags.
posh magenta bags contain 2 clear orange bags, 5 wavy silver bags, 1 striped magenta bag, 4 drab salmon bags.
dull bronze bags contain 4 dull indigo bags, 2 dim lavender bags.
vibrant coral bags contain 1 mirrored gray bag, 3 dull magenta bags, 1 faded crimson bag.
plaid cyan bags contain 3 dotted olive bags, 4 wavy tan bags.
dark fuchsia bags contain 1 dark turquoise bag, 2 shiny purple bags.
faded brown bags contain 2 clear green bags.
light gold bags contain 4 dim coral bags, 5 light violet bags, 5 wavy gold bags.
light lime bags contain 5 bright indigo bags, 5 striped teal bags.
dark white bags contain 5 shiny orange bags, 3 dotted blue bags, 1 striped salmon bag, 2 posh tomato bags.
muted magenta bags contain 5 mirrored salmon bags, 1 drab bronze bag.
vibrant bronze bags contain 2 mirrored lime bags, 2 plaid white bags.
dim lavender bags contain 3 clear yellow bags, 5 shiny beige bags.
dark turquoise bags contain 2 dull indigo bags.
dim coral bags contain 2 posh teal bags.
striped lime bags contain 2 clear yellow bags, 2 mirrored lavender bags, 5 drab olive bags, 1 bright orange bag.
wavy purple bags contain 5 shiny white bags, 5 striped aqua bags, 1 wavy cyan bag.
drab coral bags contain 3 dull orange bags, 3 posh yellow bags, 5 dim olive bags, 3 faded olive bags.
vibrant red bags contain 3 mirrored gray bags, 1 striped black bag, 1 plaid coral bag.
posh lime bags contain 3 drab olive bags, 3 clear magenta bags.
muted yellow bags contain 1 muted crimson bag, 2 dull yellow bags.
dull magenta bags contain 4 muted purple bags, 5 dull orange bags.
dull beige bags contain 5 light green bags.
bright black bags contain 2 dotted indigo bags, 4 faded yellow bags.
mirrored gold bags contain 2 faded tan bags, 1 faded maroon bag, 2 plaid purple bags, 5 bright blue bags.
muted green bags contain 4 muted gold bags, 4 wavy indigo bags.
posh gold bags contain 2 wavy cyan bags, 4 dark tomato bags, 3 shiny purple bags, 1 pale indigo bag.
muted blue bags contain 1 dark brown bag, 5 vibrant beige bags.
mirrored bronze bags contain 3 posh black bags, 4 striped silver bags, 4 bright olive bags, 4 muted yellow bags.
faded white bags contain 3 drab green bags, 5 dark black bags, 2 pale green bags.
clear indigo bags contain 3 shiny cyan bags, 4 plaid blue bags, 2 dark silver bags, 1 dotted cyan bag.
faded orange bags contain 3 pale plum bags, 1 posh plum bag, 4 mirrored lavender bags.
muted teal bags contain 3 pale olive bags, 1 clear chartreuse bag, 5 bright fuchsia bags.
dotted salmon bags contain 4 dotted magenta bags, 1 mirrored green bag, 5 pale chartreuse bags, 4 drab green bags.
wavy indigo bags contain 5 muted purple bags, 2 dark black bags, 2 dotted orange bags.
wavy teal bags contain 3 shiny purple bags, 2 clear yellow bags, 1 pale lavender bag.
plaid yellow bags contain 2 clear chartreuse bags, 2 clear crimson bags.
clear turquoise bags contain 4 pale tomato bags, 3 mirrored lavender bags.
bright silver bags contain 1 striped plum bag.
faded coral bags contain 2 shiny maroon bags, 5 wavy salmon bags, 1 wavy orange bag.
clear teal bags contain 2 drab olive bags, 5 posh red bags.
shiny black bags contain 5 faded gold bags, 1 bright tomato bag.
pale indigo bags contain 4 striped bronze bags, 3 drab olive bags.
drab purple bags contain 4 dim silver bags.
light beige bags contain 2 drab teal bags, 2 mirrored lime bags, 3 dotted coral bags, 3 vibrant cyan bags.
plaid teal bags contain 2 clear white bags.
dim bronze bags contain 2 dark bronze bags, 2 vibrant crimson bags.
muted aqua bags contain 1 vibrant magenta bag.
pale gray bags contain 2 pale orange bags, 3 faded olive bags, 1 vibrant brown bag.
drab gold bags contain 2 bright yellow bags, 2 light green bags, 5 light plum bags, 3 faded white bags.
dull lime bags contain 1 dotted maroon bag, 5 drab tan bags, 1 vibrant tomato bag.
dull aqua bags contain 5 mirrored crimson bags, 2 vibrant teal bags, 3 dim lime bags.
bright maroon bags contain 1 bright green bag, 4 shiny olive bags, 1 dotted magenta bag, 3 light plum bags.
dark silver bags contain 2 dotted indigo bags.
dark purple bags contain 3 shiny gray bags.
shiny beige bags contain 5 clear yellow bags, 5 posh salmon bags, 1 striped magenta bag, 3 bright turquoise bags.
mirrored fuchsia bags contain 5 muted blue bags, 5 muted coral bags, 1 light lavender bag.
vibrant silver bags contain 2 dull brown bags.
posh black bags contain 3 dotted orange bags.
pale crimson bags contain 5 drab plum bags, 1 pale red bag, 2 dark lavender bags.
posh tomato bags contain 4 shiny lavender bags, 2 clear yellow bags, 1 dotted turquoise bag, 1 muted gold bag.
muted silver bags contain 4 faded gray bags.
dull tan bags contain 2 faded gold bags, 4 dim yellow bags, 3 plaid white bags, 1 light green bag.
bright tomato bags contain 4 faded lime bags, 1 faded violet bag, 1 light green bag, 3 shiny turquoise bags.
shiny cyan bags contain 1 plaid black bag.
wavy magenta bags contain 5 drab coral bags, 2 vibrant gold bags.
dim green bags contain 2 shiny fuchsia bags, 1 dark chartreuse bag, 5 shiny purple bags, 4 dotted turquoise bags.
pale beige bags contain 2 wavy aqua bags, 3 wavy indigo bags, 2 dull gray bags.
clear purple bags contain 1 light plum bag, 2 wavy maroon bags, 2 posh white bags.
light magenta bags contain 3 dotted cyan bags.
light bronze bags contain 2 bright coral bags.
dim teal bags contain 3 vibrant aqua bags, 1 muted olive bag, 5 mirrored red bags, 2 muted maroon bags.
mirrored gray bags contain 4 dull orange bags, 1 dull bronze bag, 5 mirrored white bags, 1 plaid beige bag.
mirrored lavender bags contain 3 muted plum bags, 5 vibrant magenta bags, 4 pale tan bags, 5 bright turquoise bags.
vibrant yellow bags contain 1 dotted yellow bag, 5 mirrored gray bags.
drab cyan bags contain 1 shiny green bag, 2 dull yellow bags.
dim chartreuse bags contain 2 muted maroon bags, 1 dull bronze bag, 2 vibrant plum bags, 5 muted gold bags.
mirrored coral bags contain 4 dull crimson bags, 3 striped gold bags, 3 muted brown bags.
clear blue bags contain 4 clear lavender bags.
plaid coral bags contain 4 pale gold bags, 5 plaid violet bags, 1 muted aqua bag.
dark magenta bags contain 4 shiny turquoise bags.
drab crimson bags contain 5 mirrored olive bags, 4 dull silver bags, 1 wavy purple bag.
faded crimson bags contain 5 pale tan bags, 5 dim tan bags, 5 wavy indigo bags, 2 shiny lavender bags.
faded tan bags contain 4 dim green bags, 5 pale black bags, 5 muted maroon bags, 1 vibrant crimson bag.
dull black bags contain 4 wavy indigo bags, 2 bright crimson bags.
light black bags contain 3 vibrant magenta bags, 2 vibrant violet bags, 5 light purple bags, 3 striped beige bags.
light blue bags contain 2 dotted lavender bags, 4 pale beige bags.
drab beige bags contain 4 plaid blue bags, 1 dim blue bag, 5 pale aqua bags.
dim black bags contain 4 light bronze bags, 1 clear orange bag, 4 dark gray bags.
bright coral bags contain 4 wavy cyan bags, 1 posh aqua bag.
vibrant blue bags contain 4 wavy gray bags, 2 dim gold bags, 3 clear green bags, 1 dotted white bag.
shiny brown bags contain 3 pale tan bags, 1 drab purple bag.
light chartreuse bags contain 2 pale olive bags.
striped gray bags contain 1 dim orange bag, 1 bright lime bag.
mirrored cyan bags contain 4 drab bronze bags, 3 dotted red bags, 1 plaid indigo bag.
faded gold bags contain 3 vibrant yellow bags, 1 shiny fuchsia bag.
dull teal bags contain 5 dim purple bags.
bright yellow bags contain 5 posh gray bags.
dotted gold bags contain 1 clear gray bag, 4 light bronze bags.
light indigo bags contain 3 shiny olive bags.
plaid indigo bags contain 1 posh green bag, 3 mirrored red bags.
faded purple bags contain 4 muted purple bags, 3 dark gold bags, 3 shiny purple bags.
dark plum bags contain 4 drab aqua bags, 4 dull tomato bags.
bright turquoise bags contain no other bags.
drab gray bags contain 2 dim yellow bags, 1 dim white bag, 4 posh plum bags.
dull orange bags contain 5 dim tan bags.
pale bronze bags contain 5 dim salmon bags, 2 bright salmon bags, 2 striped aqua bags, 1 bright white bag.
dotted crimson bags contain 5 vibrant magenta bags.
pale orange bags contain 2 shiny beige bags, 2 dotted turquoise bags.
dim gold bags contain 4 bright bronze bags, 3 muted plum bags, 4 pale tomato bags.
clear magenta bags contain 4 muted turquoise bags.
shiny magenta bags contain 4 pale brown bags, 1 striped tan bag, 2 dark brown bags.
dark lavender bags contain 2 dull fuchsia bags, 3 striped salmon bags.
plaid white bags contain 3 mirrored red bags.
drab turquoise bags contain 5 mirrored blue bags.
striped red bags contain 2 faded indigo bags, 3 posh plum bags.
pale yellow bags contain 2 wavy yellow bags, 1 plaid purple bag, 3 striped black bags.
vibrant lime bags contain 1 dim teal bag, 3 pale salmon bags.
pale tan bags contain 2 muted gold bags.
posh olive bags contain 3 wavy bronze bags, 1 dull lavender bag, 5 dim white bags, 5 mirrored olive bags.
posh white bags contain 2 dark gray bags.
shiny red bags contain 4 striped crimson bags, 1 dark brown bag.
dark orange bags contain 2 wavy teal bags.
wavy white bags contain 2 posh green bags, 2 wavy maroon bags, 4 clear turquoise bags, 2 bright crimson bags.
pale plum bags contain 1 shiny beige bag, 5 wavy indigo bags, 3 muted plum bags.
dark violet bags contain 5 wavy indigo bags, 3 faded magenta bags, 4 dim teal bags.
posh maroon bags contain 5 posh aqua bags, 4 clear teal bags, 5 light aqua bags, 2 dim aqua bags.
pale gold bags contain 4 posh tomato bags, 3 clear yellow bags.
light yellow bags contain 1 plaid aqua bag, 1 pale aqua bag, 1 plaid violet bag, 4 drab bronze bags.
dotted red bags contain 2 light indigo bags, 2 posh tomato bags.
shiny bronze bags contain 1 drab coral bag, 5 vibrant magenta bags, 3 mirrored tomato bags, 2 pale teal bags.
dull gray bags contain 1 striped plum bag, 5 posh salmon bags, 5 posh yellow bags, 3 bright cyan bags.
bright plum bags contain 1 posh gray bag.
light aqua bags contain 4 light turquoise bags, 4 posh indigo bags, 1 drab tomato bag, 3 bright gold bags.
muted turquoise bags contain 3 muted crimson bags.
clear crimson bags contain 1 posh crimson bag, 2 posh coral bags, 2 pale tomato bags, 5 dull aqua bags.
faded fuchsia bags contain 3 striped bronze bags, 2 faded orange bags, 3 dark gold bags, 4 posh beige bags.
bright violet bags contain 1 bright olive bag, 2 faded olive bags, 1 muted aqua bag.
wavy lime bags contain 4 light lime bags.
plaid red bags contain 4 wavy silver bags, 1 plaid gray bag, 5 drab turquoise bags, 2 dotted tomato bags.
clear cyan bags contain 5 bright olive bags, 1 muted green bag, 4 striped magenta bags.
light silver bags contain 4 pale black bags, 5 dim aqua bags, 1 posh lavender bag.
vibrant indigo bags contain 1 dotted yellow bag, 3 dull gold bags.
pale turquoise bags contain 4 muted plum bags, 1 striped magenta bag, 4 shiny fuchsia bags.
faded bronze bags contain 4 dim blue bags, 5 faded salmon bags.
dark black bags contain 2 muted maroon bags, 2 bright turquoise bags.
posh tan bags contain 4 dark black bags.
dark olive bags contain 5 dotted olive bags.
dim blue bags contain 4 wavy maroon bags, 4 dull crimson bags.
dim salmon bags contain 3 clear lime bags, 5 pale indigo bags, 2 dull yellow bags.
striped indigo bags contain 2 wavy violet bags, 3 pale gold bags, 5 bright bronze bags, 3 dark beige bags.
clear plum bags contain 1 dark gray bag, 1 mirrored yellow bag, 3 light red bags, 3 dull olive bags.
drab plum bags contain 4 clear white bags, 3 vibrant cyan bags.
light teal bags contain 1 faded yellow bag, 5 striped brown bags, 2 dull magenta bags.
mirrored plum bags contain 4 mirrored tomato bags, 3 dotted cyan bags.
vibrant black bags contain 1 posh gray bag, 1 dotted fuchsia bag.
dark teal bags contain 3 bright indigo bags, 1 plaid violet bag, 2 faded plum bags.
pale teal bags contain 5 faded olive bags, 4 striped white bags, 3 dotted orange bags.
dotted chartreuse bags contain 2 clear teal bags, 1 clear brown bag, 3 dotted beige bags.
pale olive bags contain 2 clear chartreuse bags, 3 dotted turquoise bags, 2 dull bronze bags.
light tan bags contain 1 muted bronze bag.
light cyan bags contain 1 plaid lime bag.
posh coral bags contain 1 dotted turquoise bag, 1 pale plum bag.
wavy tomato bags contain 3 striped coral bags.
dull cyan bags contain 5 plaid white bags, 1 drab lime bag, 2 posh chartreuse bags.
bright white bags contain 5 posh green bags, 5 vibrant crimson bags.
dotted black bags contain 1 shiny chartreuse bag.
plaid silver bags contain 1 posh indigo bag, 4 dotted yellow bags, 2 vibrant beige bags.
striped magenta bags contain 2 bright turquoise bags, 5 dull indigo bags, 3 clear yellow bags.
dotted lime bags contain 4 vibrant gold bags, 3 posh crimson bags, 5 muted green bags, 4 posh plum bags.
shiny indigo bags contain 5 muted blue bags, 3 pale tomato bags.
dull olive bags contain 2 bright fuchsia bags.
wavy yellow bags contain 1 dark teal bag, 3 posh plum bags, 2 striped crimson bags.
vibrant aqua bags contain 1 pale green bag, 4 posh tan bags, 5 dotted brown bags.
dim purple bags contain 4 striped teal bags, 2 muted violet bags, 2 dim white bags, 3 light lime bags.
mirrored purple bags contain 3 muted green bags, 2 clear salmon bags, 2 light orange bags, 5 wavy purple bags.
striped blue bags contain 5 vibrant black bags.
posh brown bags contain 1 muted turquoise bag, 2 dim orange bags, 4 dim silver bags, 1 mirrored blue bag.
muted black bags contain 5 clear cyan bags, 3 mirrored teal bags, 3 posh turquoise bags, 4 dull plum bags.
posh salmon bags contain 4 dull indigo bags.
vibrant olive bags contain 1 dull beige bag, 2 posh tomato bags.
wavy orange bags contain 1 pale green bag, 2 plaid green bags, 4 vibrant black bags.
bright tan bags contain 3 dull purple bags, 1 dim chartreuse bag, 2 light lime bags, 4 pale plum bags.
striped yellow bags contain 5 bright plum bags.
faded blue bags contain 4 wavy indigo bags, 5 posh yellow bags, 3 pale black bags.
muted lime bags contain 4 shiny lavender bags.
light crimson bags contain 5 dull tomato bags, 3 bright beige bags, 1 dark silver bag.
dotted plum bags contain 2 muted blue bags, 5 wavy gray bags, 4 posh tan bags.
light white bags contain 5 dim indigo bags, 3 plaid plum bags, 1 clear gray bag, 2 faded gold bags.
dim maroon bags contain 2 plaid turquoise bags.
dull red bags contain 4 shiny orange bags, 2 dull crimson bags.
striped black bags contain 1 striped white bag.
plaid gray bags contain 1 muted violet bag, 3 faded black bags, 4 pale lavender bags.
light turquoise bags contain 1 faded crimson bag, 5 mirrored olive bags, 5 vibrant cyan bags.
pale chartreuse bags contain 2 drab coral bags, 5 mirrored crimson bags.
vibrant green bags contain 2 dim indigo bags, 3 bright cyan bags, 1 dull chartreuse bag.
dull indigo bags contain no other bags.
vibrant plum bags contain 4 vibrant magenta bags, 1 muted plum bag.
striped white bags contain 5 mirrored lavender bags, 5 dark black bags.
striped aqua bags contain 3 dim gold bags.
shiny violet bags contain 5 shiny red bags, 5 striped crimson bags, 3 shiny fuchsia bags, 4 dotted magenta bags.
vibrant violet bags contain 5 plaid turquoise bags.
drab tomato bags contain 3 pale tomato bags, 1 pale lavender bag, 3 pale plum bags, 1 posh red bag.
vibrant chartreuse bags contain 2 plaid fuchsia bags, 1 muted silver bag, 2 vibrant magenta bags.
vibrant salmon bags contain 1 clear olive bag, 3 light orange bags, 2 striped plum bags, 2 dark aqua bags.
dotted yellow bags contain 4 pale olive bags, 4 shiny purple bags, 1 dim lavender bag.
pale magenta bags contain 2 striped teal bags, 5 mirrored olive bags.
mirrored orange bags contain 5 pale coral bags.
bright beige bags contain 3 clear fuchsia bags, 2 muted orange bags.
vibrant tan bags contain 3 muted tan bags, 5 posh gray bags, 1 dim yellow bag.
clear aqua bags contain 3 pale plum bags, 1 wavy fuchsia bag.
striped cyan bags contain 2 posh olive bags, 3 light chartreuse bags, 2 muted turquoise bags, 1 pale teal bag.
posh purple bags contain 3 dotted brown bags.
striped green bags contain 2 light brown bags.
bright olive bags contain 2 drab coral bags, 5 striped orange bags.
vibrant beige bags contain 4 faded crimson bags.
wavy gray bags contain 5 posh salmon bags.
dull chartreuse bags contain 2 shiny purple bags, 3 faded maroon bags.
bright chartreuse bags contain 3 wavy beige bags.
striped orange bags contain 3 wavy indigo bags, 2 wavy teal bags.
drab white bags contain 2 bright fuchsia bags.
clear white bags contain 1 posh teal bag.
drab bronze bags contain 1 mirrored tan bag, 2 pale black bags, 1 bright cyan bag, 1 striped magenta bag.
dotted indigo bags contain 3 mirrored tan bags, 5 faded lavender bags, 4 dotted magenta bags, 3 dim silver bags.
posh violet bags contain 4 dotted maroon bags, 4 dotted magenta bags, 3 bright purple bags.
plaid blue bags contain 5 shiny tan bags, 1 wavy maroon bag, 2 muted crimson bags.
vibrant tomato bags contain 4 shiny fuchsia bags.
bright cyan bags contain 3 wavy black bags, 1 muted lime bag.
muted cyan bags contain 2 muted teal bags, 3 vibrant magenta bags, 5 dull magenta bags.
vibrant maroon bags contain 1 wavy aqua bag.
dark gold bags contain no other bags.
mirrored magenta bags contain 4 dim gold bags.
muted beige bags contain 4 dull magenta bags, 2 drab olive bags.
striped purple bags contain 3 vibrant beige bags.
light green bags contain 5 striped black bags, 5 clear orange bags, 5 muted indigo bags, 5 wavy yellow bags.
light orange bags contain 2 pale salmon bags, 2 dotted blue bags, 5 mirrored crimson bags.
dull plum bags contain 4 dotted fuchsia bags.
bright aqua bags contain 3 posh chartreuse bags, 2 dark tomato bags.
muted orange bags contain 1 posh salmon bag, 5 bright purple bags, 4 dotted magenta bags, 2 dark chartreuse bags.
plaid purple bags contain 3 posh gray bags, 5 vibrant coral bags, 4 vibrant yellow bags, 4 shiny aqua bags.
shiny tan bags contain 1 dotted cyan bag.
drab lime bags contain 4 striped orange bags, 4 muted green bags, 3 faded gray bags.
drab violet bags contain 3 bright olive bags, 4 drab indigo bags, 5 clear turquoise bags.
muted red bags contain 5 dotted plum bags, 4 striped plum bags, 1 bright violet bag, 1 mirrored tomato bag.
vibrant lavender bags contain 2 vibrant magenta bags, 4 shiny beige bags, 2 drab bronze bags, 1 faded indigo bag.
dark crimson bags contain 5 mirrored tan bags, 5 drab bronze bags.
muted salmon bags contain 4 dull tan bags, 2 faded magenta bags, 5 muted violet bags.
light maroon bags contain 5 dim lavender bags, 1 striped lime bag, 2 dotted maroon bags.
posh plum bags contain 3 dotted turquoise bags.
pale white bags contain 4 wavy indigo bags, 2 striped orange bags, 2 mirrored tomato bags.
dotted lavender bags contain 3 clear tan bags, 2 clear salmon bags, 2 faded brown bags.
mirrored indigo bags contain 3 muted olive bags, 2 striped purple bags, 4 light chartreuse bags, 5 bright magenta bags.
pale lavender bags contain no other bags.
wavy coral bags contain 2 drab salmon bags.
striped beige bags contain 1 plaid maroon bag, 5 pale olive bags, 5 pale yellow bags, 1 plaid violet bag.
wavy salmon bags contain 4 dotted purple bags, 4 light indigo bags, 5 faded green bags, 4 faded crimson bags.
faded turquoise bags contain 1 dim beige bag.
wavy brown bags contain 1 drab red bag, 2 shiny red bags, 2 vibrant aqua bags.
plaid aqua bags contain 1 muted yellow bag, 5 vibrant orange bags, 5 drab tomato bags, 2 drab brown bags.
wavy beige bags contain 4 dim red bags.
bright lime bags contain 3 pale lavender bags.
posh orange bags contain 5 dark chartreuse bags.
clear chartreuse bags contain 2 pale plum bags, 4 dull indigo bags.
dim silver bags contain 5 shiny purple bags, 1 mirrored olive bag.
shiny salmon bags contain 3 clear lavender bags, 3 shiny purple bags.
dull crimson bags contain 5 muted blue bags, 1 dark black bag, 1 bright purple bag, 2 shiny purple bags.
mirrored maroon bags contain 5 mirrored tan bags, 5 pale indigo bags, 2 pale olive bags, 3 vibrant plum bags.
vibrant teal bags contain 5 mirrored olive bags, 5 pale beige bags, 1 pale tan bag.
dim turquoise bags contain 4 dark plum bags, 3 dull orange bags, 3 plaid plum bags, 3 dark orange bags.
shiny lime bags contain 2 muted lavender bags, 4 vibrant magenta bags, 4 bright gold bags.
wavy cyan bags contain 3 light beige bags.
muted tomato bags contain 5 dim white bags, 2 vibrant gold bags, 1 vibrant coral bag.
muted gold bags contain no other bags.
dark blue bags contain 2 posh teal bags, 2 pale beige bags, 2 shiny green bags, 1 bright fuchsia bag.
faded chartreuse bags contain 4 wavy white bags.
striped teal bags contain 5 dim olive bags, 3 striped crimson bags, 1 faded crimson bag.
bright green bags contain 2 mirrored tan bags, 5 posh salmon bags, 5 shiny aqua bags.
wavy green bags contain 2 posh blue bags, 2 mirrored teal bags.
dim red bags contain 3 dull magenta bags.
shiny fuchsia bags contain 2 pale red bags.
dotted white bags contain 5 light beige bags, 5 dark beige bags.
shiny gold bags contain 2 clear chartreuse bags.
faded violet bags contain 1 dim chartreuse bag.
faded cyan bags contain 1 drab yellow bag, 3 muted crimson bags, 4 muted teal bags.
shiny gray bags contain 4 mirrored white bags.
dim beige bags contain 2 light chartreuse bags, 3 dim white bags, 3 shiny lavender bags.
muted white bags contain 1 drab gray bag, 2 wavy silver bags, 3 drab purple bags, 4 dim magenta bags.
dark green bags contain 4 muted tomato bags, 5 dotted coral bags, 5 mirrored tomato bags, 1 dull crimson bag.
shiny yellow bags contain 2 drab red bags.
bright gold bags contain 2 mirrored gray bags.
dim tomato bags contain 4 bright tomato bags, 5 bright plum bags, 1 light lime bag, 5 muted turquoise bags.
dim white bags contain 3 shiny beige bags.
mirrored turquoise bags contain 2 shiny cyan bags, 3 mirrored green bags, 4 dim silver bags, 1 faded aqua bag.
striped fuchsia bags contain 4 dark black bags, 1 plaid lavender bag, 4 mirrored yellow bags, 5 drab bronze bags.
clear orange bags contain 3 striped plum bags.
shiny coral bags contain 4 vibrant crimson bags.
posh indigo bags contain 3 dull indigo bags, 2 clear green bags, 3 pale tan bags, 4 clear tan bags.
dark bronze bags contain 3 striped orange bags, 4 drab lime bags.
striped olive bags contain 3 muted bronze bags.
clear gold bags contain 4 light red bags, 3 clear tan bags, 2 drab black bags.
clear brown bags contain 3 dull fuchsia bags, 3 clear white bags, 3 dull aqua bags.
bright magenta bags contain 3 light green bags, 1 muted yellow bag.
posh silver bags contain 5 pale silver bags, 3 bright crimson bags, 4 light orange bags, 4 posh beige bags.
muted crimson bags contain 5 dotted orange bags.
pale black bags contain 4 striped plum bags.
light gray bags contain 2 bright tan bags.
light salmon bags contain 2 drab olive bags, 4 light purple bags, 2 dull white bags.
dark red bags contain 4 muted aqua bags, 5 bright coral bags, 2 dotted tan bags, 1 drab tomato bag.
faded gray bags contain 2 clear fuchsia bags, 4 dotted magenta bags, 4 dim white bags, 4 dim tan bags.
dotted tomato bags contain 5 shiny tomato bags, 4 dull plum bags, 3 dull white bags.
posh cyan bags contain 2 bright bronze bags.
dark maroon bags contain 3 muted plum bags, 2 striped bronze bags, 2 shiny fuchsia bags.
clear olive bags contain 3 pale lavender bags, 5 plaid white bags, 3 clear chartreuse bags, 1 posh chartreuse bag.
bright salmon bags contain 5 dim beige bags, 4 dotted indigo bags.
faded red bags contain 1 drab white bag, 4 mirrored white bags.
dotted purple bags contain 1 vibrant magenta bag, 2 dull beige bags, 5 light orange bags, 4 plaid blue bags.
faded plum bags contain 3 mirrored tan bags, 1 drab bronze bag.
pale coral bags contain 4 plaid white bags.
muted olive bags contain 3 bright turquoise bags, 5 dim tan bags, 1 striped crimson bag, 3 clear yellow bags.
faded aqua bags contain 5 faded crimson bags.
mirrored olive bags contain 2 striped white bags, 2 posh yellow bags.
drab teal bags contain 5 dull black bags.
dark salmon bags contain 2 drab lime bags, 3 dim silver bags.
light brown bags contain 2 wavy violet bags.
light fuchsia bags contain 3 striped blue bags, 2 faded aqua bags, 4 mirrored tomato bags, 3 shiny bronze bags.
dim brown bags contain 4 faded gold bags.
dotted bronze bags contain 4 drab lime bags.
posh bronze bags contain 3 pale purple bags.
plaid maroon bags contain 2 dull cyan bags, 3 drab maroon bags, 3 shiny white bags.
bright purple bags contain 3 posh tomato bags, 5 dotted turquoise bags.
striped gold bags contain 3 dim lavender bags, 5 faded brown bags, 5 posh tomato bags, 5 bright cyan bags.
faded teal bags contain 1 wavy teal bag.
light lavender bags contain 1 faded violet bag, 2 bright beige bags.
dim plum bags contain 4 clear coral bags, 4 shiny cyan bags, 5 striped orange bags.
muted chartreuse bags contain 3 dim silver bags, 4 plaid black bags.
light red bags contain 5 dim gold bags, 2 dim beige bags, 4 striped teal bags, 4 muted indigo bags.
shiny aqua bags contain 5 drab aqua bags.
faded magenta bags contain 4 pale silver bags, 5 dull lavender bags.
light tomato bags contain 4 shiny silver bags, 5 striped aqua bags, 5 vibrant crimson bags.
faded maroon bags contain 1 striped magenta bag, 5 mirrored coral bags, 3 pale lavender bags.
shiny chartreuse bags contain 5 plaid coral bags, 3 dim beige bags, 1 dim yellow bag.
clear gray bags contain 5 dark yellow bags.
clear salmon bags contain 4 muted green bags, 3 vibrant gray bags.
clear black bags contain 3 muted plum bags, 1 muted cyan bag.
vibrant brown bags contain 3 bright bronze bags, 5 striped salmon bags, 1 dim tan bag, 5 wavy black bags.
wavy fuchsia bags contain 2 posh chartreuse bags.
dotted blue bags contain 1 pale brown bag, 5 dim olive bags, 1 dotted yellow bag.
plaid orange bags contain 2 dull lime bags, 2 bright maroon bags.
dull fuchsia bags contain 5 drab turquoise bags, 3 clear cyan bags.
shiny green bags contain 4 clear lavender bags, 4 light turquoise bags, 5 muted brown bags.
mirrored brown bags contain 3 dark lavender bags, 1 drab violet bag.
muted lavender bags contain 3 dim silver bags, 3 drab purple bags, 4 faded crimson bags.
mirrored yellow bags contain 4 drab olive bags, 5 dotted coral bags, 3 plaid purple bags.
plaid turquoise bags contain 4 mirrored tomato bags, 2 shiny gold bags, 5 dim lavender bags, 3 bright turquoise bags.
wavy tan bags contain 4 faded chartreuse bags.
dark chartreuse bags contain 2 muted aqua bags, 3 shiny purple bags, 5 shiny beige bags, 1 posh tomato bag.
faded beige bags contain 2 vibrant orange bags.
clear yellow bags contain no other bags.
wavy maroon bags contain 2 muted purple bags, 2 posh yellow bags.
bright fuchsia bags contain 2 muted lime bags, 2 pale black bags.
clear violet bags contain 4 vibrant violet bags, 1 vibrant tomato bag.
mirrored teal bags contain 3 faded olive bags, 3 dotted crimson bags, 2 drab bronze bags.
drab green bags contain 2 muted green bags, 5 mirrored crimson bags, 4 mirrored lavender bags, 2 bright turquoise bags.
wavy crimson bags contain 1 bright fuchsia bag, 1 posh crimson bag, 1 posh salmon bag, 1 dull gray bag.
drab silver bags contain 2 dull chartreuse bags, 4 striped bronze bags, 5 bright orange bags.
wavy aqua bags contain 5 dotted turquoise bags, 3 dull bronze bags.
mirrored red bags contain 4 bright purple bags, 4 wavy aqua bags.
vibrant fuchsia bags contain 2 shiny green bags, 3 clear green bags, 4 posh violet bags, 4 wavy magenta bags.
dim fuchsia bags contain 2 light fuchsia bags, 1 dark coral bag, 3 muted yellow bags.
posh yellow bags contain 2 mirrored lavender bags.
dull coral bags contain 1 dark purple bag, 3 faded turquoise bags, 5 striped brown bags, 5 mirrored white bags.
faded black bags contain 4 wavy turquoise bags, 3 faded gold bags, 5 wavy teal bags.
dull silver bags contain 2 wavy black bags, 3 posh salmon bags, 2 dim brown bags.
shiny turquoise bags contain 2 dull gray bags, 4 faded silver bags, 1 posh lavender bag, 4 plaid coral bags.
dark coral bags contain 1 pale purple bag.
pale purple bags contain 3 dim lime bags, 4 vibrant cyan bags, 4 dull indigo bags, 1 muted violet bag.
clear tomato bags contain 2 posh red bags, 3 dull aqua bags.
dotted aqua bags contain 2 vibrant fuchsia bags, 3 light olive bags, 1 clear salmon bag, 4 dotted yellow bags.
drab olive bags contain 3 wavy chartreuse bags, 4 bright orange bags.
vibrant cyan bags contain 3 pale tan bags, 4 pale gold bags.
muted tan bags contain 2 wavy silver bags, 4 dotted gold bags, 3 mirrored violet bags, 5 posh crimson bags.
faded silver bags contain 2 drab blue bags.
wavy olive bags contain 4 dark tomato bags.
dark beige bags contain 5 dotted cyan bags, 4 muted crimson bags.
pale cyan bags contain 3 plaid purple bags, 5 pale tan bags.
faded lavender bags contain 1 muted indigo bag, 4 posh cyan bags, 4 faded yellow bags, 4 wavy black bags.
clear lavender bags contain 5 pale tan bags, 1 vibrant beige bag, 5 drab olive bags, 2 muted purple bags.
mirrored lime bags contain 5 dull indigo bags.
dotted green bags contain 1 dull chartreuse bag, 3 drab cyan bags.
shiny blue bags contain 5 drab purple bags, 4 dim yellow bags.
dotted turquoise bags contain 1 dark gold bag, 2 striped magenta bags.
dull tomato bags contain 5 pale tomato bags, 5 mirrored tomato bags, 1 plaid crimson bag.
vibrant crimson bags contain 5 wavy white bags, 4 shiny salmon bags, 3 faded lavender bags.
dark indigo bags contain 3 bright yellow bags, 1 shiny violet bag, 4 dark turquoise bags, 1 muted brown bag.
vibrant turquoise bags contain 2 dotted teal bags, 4 dotted gray bags, 5 pale tomato bags, 5 dark lavender bags.
mirrored tan bags contain 4 pale white bags, 3 wavy indigo bags, 5 shiny gold bags, 5 posh plum bags.
clear green bags contain 2 shiny lavender bags.
wavy lavender bags contain 1 dim magenta bag, 4 drab red bags, 1 light chartreuse bag.
dull blue bags contain 4 dull magenta bags, 4 dotted brown bags, 1 faded brown bag.
dull turquoise bags contain 1 striped lime bag, 5 pale white bags, 4 posh tan bags, 5 faded fuchsia bags.
striped brown bags contain 4 light brown bags.
dotted cyan bags contain 3 muted purple bags, 1 dull orange bag.
dotted beige bags contain 2 dark brown bags, 5 posh gray bags, 5 light magenta bags, 4 wavy silver bags.
dotted brown bags contain 2 shiny gold bags, 4 mirrored olive bags.
dim magenta bags contain 4 muted yellow bags.
faded lime bags contain 4 dim orange bags.
drab magenta bags contain 2 muted teal bags.
bright brown bags contain 4 vibrant lime bags.
striped chartreuse bags contain 4 vibrant gray bags, 5 dull magenta bags, 1 vibrant cyan bag, 5 muted gray bags.
pale blue bags contain 4 striped fuchsia bags.
dull salmon bags contain 3 posh cyan bags, 5 dull magenta bags, 4 wavy violet bags.
dotted coral bags contain 4 muted teal bags, 4 posh tan bags.
plaid fuchsia bags contain 4 wavy chartreuse bags, 1 light orange bag, 1 bright silver bag.
vibrant magenta bags contain no other bags.
dotted tan bags contain 5 posh magenta bags, 1 drab magenta bag.
dull maroon bags contain 3 posh red bags, 4 posh indigo bags, 2 drab lime bags, 5 shiny magenta bags.
vibrant gold bags contain 4 bright crimson bags.
light coral bags contain 2 mirrored blue bags, 1 light red bag.
dotted orange bags contain 3 shiny purple bags.
vibrant gray bags contain 2 pale olive bags, 4 drab purple bags.
light olive bags contain 3 dotted blue bags, 5 pale white bags.
wavy black bags contain 2 muted olive bags.
dim indigo bags contain 1 bright crimson bag, 5 dull olive bags, 5 light orange bags.
dull white bags contain 2 drab gold bags, 4 drab gray bags, 5 striped salmon bags.
plaid brown bags contain 3 striped tan bags, 5 dark bronze bags, 4 faded tomato bags.
striped salmon bags contain 5 muted purple bags, 5 pale tan bags, 2 shiny bronze bags.
faded tomato bags contain 4 striped crimson bags.
clear lime bags contain 1 light green bag, 5 drab red bags, 3 muted bronze bags.
posh chartreuse bags contain 1 muted lime bag, 1 dull orange bag, 2 dotted cyan bags.
drab maroon bags contain 4 muted aqua bags, 1 shiny beige bag.
shiny silver bags contain 2 pale red bags, 4 light magenta bags, 2 dark crimson bags.
wavy silver bags contain 4 vibrant brown bags, 5 wavy lime bags.
striped coral bags contain 3 pale white bags.
mirrored white bags contain 2 dark gold bags.
dotted silver bags contain 1 dark crimson bag, 5 dotted turquoise bags.
muted gray bags contain 2 mirrored crimson bags, 3 mirrored white bags.
striped tomato bags contain 3 muted maroon bags, 5 posh beige bags, 3 vibrant plum bags.
dim cyan bags contain 4 muted brown bags, 5 dim magenta bags, 3 bright cyan bags.
dark gray bags contain 5 faded blue bags, 3 light magenta bags.
mirrored crimson bags contain 1 dark chartreuse bag, 5 striped lime bags.
muted indigo bags contain 4 pale silver bags, 4 striped white bags, 5 pale white bags, 5 striped plum bags.
drab indigo bags contain 5 plaid black bags.
dotted fuchsia bags contain 4 striped orange bags, 5 dim chartreuse bags.
posh blue bags contain 4 dotted lime bags, 1 vibrant cyan bag.
dark lime bags contain 3 clear maroon bags, 3 wavy white bags, 2 striped brown bags, 1 faded brown bag.
clear coral bags contain 4 dim cyan bags.
striped violet bags contain 5 vibrant yellow bags, 2 dim yellow bags.
drab brown bags contain 5 dark chartreuse bags, 2 pale gold bags, 3 mirrored maroon bags, 3 faded brown bags.
bright bronze bags contain 2 shiny lavender bags.
mirrored chartreuse bags contain 4 dim silver bags.
clear red bags contain 2 posh crimson bags, 2 drab brown bags, 5 vibrant violet bags, 1 faded turquoise bag.
mirrored blue bags contain 2 dull yellow bags, 3 dark yellow bags.
posh teal bags contain 4 muted indigo bags.
dotted teal bags contain 4 striped tomato bags, 3 clear salmon bags.
dim lime bags contain 3 wavy indigo bags, 4 shiny purple bags.
pale lime bags contain 3 clear salmon bags, 2 faded magenta bags, 4 drab fuchsia bags.
wavy violet bags contain 2 bright purple bags.
plaid tan bags contain 3 shiny orange bags, 2 striped tomato bags, 1 vibrant gray bag.
striped turquoise bags contain 2 muted brown bags, 2 clear tan bags, 1 vibrant lime bag.
plaid chartreuse bags contain 3 mirrored indigo bags.
dull brown bags contain 1 shiny salmon bag, 1 dull black bag, 5 striped violet bags, 4 muted maroon bags.
clear fuchsia bags contain 1 mirrored lavender bag, 5 striped magenta bags, 5 faded crimson bags.
mirrored green bags contain 4 shiny purple bags.
muted maroon bags contain no other bags.
wavy turquoise bags contain 1 striped magenta bag.
posh green bags contain 2 dim tan bags, 2 striped black bags, 4 striped magenta bags, 2 striped teal bags.
plaid salmon bags contain 5 pale olive bags.
striped plum bags contain 5 shiny lavender bags.
muted purple bags contain 2 shiny lavender bags, 4 shiny beige bags, 2 pale lavender bags.
posh gray bags contain 5 dark maroon bags, 5 shiny gray bags, 1 wavy black bag, 3 faded purple bags.
pale silver bags contain 1 wavy violet bag, 2 dim tan bags, 1 shiny red bag.
bright red bags contain 5 dotted indigo bags, 1 pale silver bag.
drab black bags contain 4 posh tomato bags.
plaid olive bags contain 4 posh coral bags, 4 dotted aqua bags, 5 shiny fuchsia bags.
plaid magenta bags contain 5 clear turquoise bags, 3 muted turquoise bags.
shiny maroon bags contain 5 dull blue bags.
pale brown bags contain 1 pale orange bag, 5 dotted orange bags, 1 bright lavender bag, 2 dull gray bags.
plaid lavender bags contain 4 drab coral bags, 4 dark tomato bags, 3 striped bronze bags, 5 shiny brown bags.
striped silver bags contain 1 posh chartreuse bag, 5 drab violet bags, 1 wavy crimson bag, 3 muted beige bags.
striped lavender bags contain 4 striped magenta bags.
dim violet bags contain 3 dull gray bags.
dull purple bags contain 1 posh green bag, 1 muted olive bag, 4 faded crimson bags.
vibrant purple bags contain 3 vibrant yellow bags.
light plum bags contain 4 pale lavender bags, 2 mirrored olive bags, 3 mirrored tomato bags.
dark aqua bags contain 4 plaid lavender bags.
faded yellow bags contain 5 drab teal bags.
mirrored tomato bags contain 3 vibrant magenta bags, 4 dim tan bags, 1 bright indigo bag.
shiny plum bags contain 5 wavy beige bags.
pale aqua bags contain 5 pale gold bags, 5 pale red bags, 5 striped orange bags, 1 dull bronze bag.
plaid violet bags contain 1 muted purple bag, 5 plaid turquoise bags, 4 posh chartreuse bags.
dim gray bags contain 5 dull teal bags.
light purple bags contain 1 striped plum bag.
posh turquoise bags contain 3 plaid aqua bags, 5 vibrant purple bags.
muted coral bags contain 4 bright crimson bags, 4 dotted salmon bags, 2 pale purple bags, 2 clear magenta bags.
posh fuchsia bags contain 5 drab aqua bags, 2 bright bronze bags.
dim orange bags contain 5 bright gold bags.
muted bronze bags contain 2 pale olive bags.
dotted violet bags contain 2 drab plum bags, 3 bright yellow bags, 2 plaid lime bags, 2 dark salmon bags.
pale green bags contain 5 clear lavender bags, 3 mirrored olive bags.
dark tan bags contain 4 wavy bronze bags.
bright indigo bags contain 5 muted purple bags.
striped tan bags contain 4 plaid white bags.
mirrored black bags contain 4 bright blue bags, 5 dull yellow bags, 5 dark teal bags, 5 wavy purple bags.
drab salmon bags contain 3 posh indigo bags, 1 plaid crimson bag, 1 pale purple bag.
dull yellow bags contain 2 plaid violet bags, 1 plaid fuchsia bag, 3 dark chartreuse bags.
drab lavender bags contain 5 dark white bags, 4 light green bags.
faded salmon bags contain 2 mirrored lime bags.
plaid bronze bags contain 4 wavy green bags, 4 mirrored blue bags, 4 faded magenta bags, 5 plaid olive bags.
faded indigo bags contain 2 vibrant orange bags, 5 faded violet bags, 3 dim orange bags.
shiny crimson bags contain 5 pale olive bags.
plaid lime bags contain 3 dotted brown bags, 2 drab lime bags, 3 bright fuchsia bags, 1 dotted crimson bag.
dotted maroon bags contain 2 vibrant gray bags, 1 faded blue bag, 5 bright turquoise bags.
pale fuchsia bags contain 4 dull tan bags.
plaid plum bags contain 2 dotted lime bags, 5 light green bags, 4 bright tan bags, 4 dark beige bags.
muted fuchsia bags contain 1 striped fuchsia bag, 5 plaid crimson bags, 1 vibrant red bag.
dull green bags contain 4 faded maroon bags, 2 dull gold bags, 2 wavy teal bags, 3 vibrant gold bags.
pale salmon bags contain 2 posh beige bags, 5 faded olive bags, 5 vibrant beige bags, 3 dark gold bags.
muted plum bags contain 1 muted maroon bag.
wavy blue bags contain 3 dark maroon bags.
dull gold bags contain 1 dim white bag, 4 wavy teal bags, 4 muted blue bags.
dotted gray bags contain 4 pale salmon bags.
clear maroon bags contain 3 mirrored indigo bags, 4 wavy coral bags, 1 dim brown bag, 2 bright chartreuse bags.
drab chartreuse bags contain 2 dim purple bags, 2 dark chartreuse bags, 1 bright teal bag.
vibrant white bags contain 2 dull aqua bags, 5 light gold bags, 5 clear silver bags, 4 muted purple bags.
plaid black bags contain 5 posh orange bags, 2 plaid violet bags, 4 pale olive bags.
dark yellow bags contain 5 dotted magenta bags, 5 pale black bags, 1 striped orange bag.
bright teal bags contain 1 light chartreuse bag, 3 posh magenta bags, 2 posh violet bags.
wavy bronze bags contain 5 bright cyan bags, 4 dull indigo bags.
mirrored violet bags contain 1 bright beige bag.
dim olive bags contain no other bags.
striped crimson bags contain 1 pale orange bag, 5 dim white bags, 3 clear fuchsia bags.
bright orange bags contain 5 faded olive bags, 5 posh tomato bags.
bright lavender bags contain 4 posh yellow bags, 4 posh salmon bags, 4 dim tan bags.
plaid gold bags contain 5 wavy magenta bags, 5 dim orange bags, 2 faded tomato bags, 4 faded purple bags.
light violet bags contain 1 plaid aqua bag."""
} | 0 | Kotlin | 0 | 0 | dc70d185cb9f6fd7d69bd1fe74c6dfc8f4aac097 | 49,340 | adventofcode2020 | MIT License |
src/main/kotlin/g2001_2100/s2035_partition_array_into_two_arrays_to_minimize_sum_difference/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2035_partition_array_into_two_arrays_to_minimize_sum_difference
// #Hard #Array #Dynamic_Programming #Binary_Search #Two_Pointers #Bit_Manipulation #Ordered_Set
// #Bitmask #2023_06_23_Time_1318_ms_(100.00%)_Space_53.2_MB_(100.00%)
class Solution {
fun minimumDifference(nums: IntArray): Int {
if (nums.isEmpty()) {
return -1
}
val n = nums.size / 2
var sum = 0
val arr1: MutableList<MutableList<Int>> = ArrayList()
val arr2: MutableList<MutableList<Int>> = ArrayList()
for (i in 0..n) {
arr1.add(ArrayList())
arr2.add(ArrayList())
if (i < n) {
sum += nums[i]
sum += nums[i + n]
}
}
for (state in 0 until (1 shl n)) {
var sum1 = 0
var sum2 = 0
for (i in 0 until n) {
if (state and (1 shl i) == 0) {
continue
}
val a1 = nums[i]
val a2 = nums[i + n]
sum1 += a1
sum2 += a2
}
val numOfEleInSet = Integer.bitCount(state)
arr1[numOfEleInSet].add(sum1)
arr2[numOfEleInSet].add(sum2)
}
for (i in 0..n) {
arr2[i].sort()
}
var min = Int.MAX_VALUE
for (i in 0..n) {
val sums1: List<Int> = arr1[i]
val sums2: List<Int> = arr2[n - i]
for (s1 in sums1) {
var idx = sums2.binarySearch(sum / 2 - s1)
if (idx < 0) {
idx = -(idx + 1)
}
if (idx < sums1.size) {
min = Math.min(
min,
Math.abs(sum - s1 - sums2[idx] - (sums2[idx] + s1))
)
}
if (idx - 1 >= 0) {
min = Math.min(
min,
Math.abs(
sum - s1 - sums2[idx - 1] -
(sums2[idx - 1] + s1)
)
)
}
}
}
return min
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,247 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/staricka/adventofcode2023/days/Day12.kt | mathstar | 719,656,133 | false | {"Kotlin": 107115} | package com.staricka.adventofcode2023.days
import com.staricka.adventofcode2023.framework.Day
class Day12: Day {
enum class Condition {
OPERATIONAL, BROKEN, UNKNOWN;
companion object {
fun fromChar(c: Char): Condition {
return when (c) {
'.' -> OPERATIONAL
'#' -> BROKEN
'?' -> UNKNOWN
else -> throw Exception()
}
}
}
}
data class Row(val conditions: List<Condition>, val groups: List<Int>) {
fun popCondition(): Pair<Condition, Row> {
return Pair(conditions.first(), Row(conditions.subList(1, conditions.size), groups))
}
fun popGroup(): Pair<Int, Row> {
return Pair(groups.first(), Row(conditions, groups.subList(1, groups.size)))
}
fun unfold(): Row {
val unfoldedConditions: List<Condition> = listOf(conditions, conditions, conditions, conditions, conditions)
.reduce {acc, next -> acc + listOf(Condition.UNKNOWN) + next }
val unfoldedGroups: List<Int> = listOf(groups, groups, groups, groups, groups).flatten()
return Row(unfoldedConditions, unfoldedGroups)
}
companion object {
fun fromString(line: String): Row {
val conditions = line.split(" ")[0].toCharArray().map { Condition.fromChar(it) }
val groups = line.split(" ")[1].split(",").map { it.toInt() }
return Row(conditions, groups)
}
}
}
private fun possibleArrangements(row: Row): Long {
return recurseArrangements(row, 0)
}
private val memos = HashMap<Pair<Row, Int>, Long>()
private fun recurseArrangements(row: Row, brokenCount: Int): Long {
return memos[Pair(row, brokenCount)] ?: recurseArrangementsBody(row, brokenCount).also { memos[Pair(row, brokenCount)] = it }
}
private fun recurseArrangementsBody(row: Row, brokenCount: Int): Long {
if (row.conditions.isEmpty()) {
return if (row.groups.isEmpty()) {
if (brokenCount == 0) 1 else 0
} else {
if (row.groups.size == 1 && row.groups[0] == brokenCount) 1 else 0
}
}
val (condition, next) = row.popCondition()
when (condition) {
Condition.OPERATIONAL -> {
if (brokenCount == 0) {
return recurseArrangements(next, 0)
}
if (row.groups.isNotEmpty() && row.groups[0] == brokenCount) {
return recurseArrangements(next.popGroup().second, 0)
}
return 0
}
Condition.BROKEN -> {
val nextBroken = brokenCount + 1
if (row.groups.isNotEmpty() && row.groups[0] >= nextBroken) {
return recurseArrangements(next, nextBroken)
}
return 0
}
Condition.UNKNOWN -> {
var result = 0L
// BROKEN case
if (row.groups.isNotEmpty() && row.groups[0] > brokenCount) {
result += recurseArrangements(next, brokenCount + 1)
}
// OPERATIONAL case
if (brokenCount == 0) {
result += recurseArrangements(next, 0)
} else if (row.groups.isNotEmpty() && row.groups[0] == brokenCount) {
result += recurseArrangements(next.popGroup().second, 0)
}
return result
}
}
}
override fun part1(input: String): Long {
return input.lines().filter { it.isNotBlank() }.map { Row.fromString(it) }.sumOf { possibleArrangements(it) }
}
override fun part2(input: String): Long {
val rows = input.lines().filter { it.isNotBlank() }.map { Row.fromString(it).unfold() }
return rows.parallelStream().mapToLong { possibleArrangements(it) }.sum()
}
} | 0 | Kotlin | 0 | 0 | 8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa | 4,082 | adventOfCode2023 | MIT License |
solutions/src/LongestPalindrome.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} | import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.HashSet
class LongestPalindrome {
//https://leetcode.com/problems/longest-palindromic-substring/description/
fun longestPalindrome(s: String): String {
if (s == null || s.length <= 1) {
return s
}
var start = 0
var end = 0
for(i in 0..s.length -1) {
val indexPairs = longestPalindromeAroundChar(s,i)
val length = indexPairs.first - indexPairs.second
val currLength = end - start
if (length > currLength) {
start = indexPairs.second
end = indexPairs.first
}
}
return s.substring(start,end + 1)
}
fun computePairLength(pair: Pair<Int,Int>): Int {
return pair.first - pair.second
}
fun longestPalindromeAroundChar(S: String, index: Int): Pair<Int,Int> {
val repeatingPair = repeatingPalindrome(S,index)
val standardPair = standardPalindrome(S,index,index)
val standardPairEven = standardPalindrome(S,index,index+1)
val sorter = TreeMap<Int,Pair<Int,Int>>(compareBy<Int>{it}.reversed())
sorter[computePairLength(repeatingPair)]=repeatingPair
sorter[computePairLength(standardPair)]=standardPair
sorter[computePairLength(standardPairEven)]=standardPairEven
return sorter.getOrDefault(sorter.firstKey(),Pair(index,index))
}
fun repeatingPalindrome(S: String, index: Int): Pair<Int,Int> {
val indexChar = S[index]
var start = index
var end = index
while (start >= 0 && S[start]==indexChar) {
start --
}
while (end < S.length && S[end]==indexChar) {
end ++
}
return Pair(end-1,start+1)
}
fun standardPalindrome(S: String, start: Int, end: Int ): Pair<Int,Int> {
var start = start
var end = end
if (end >= S.length) {
return Pair(start,start)
}
while (start >= 0 && end < S.length && S[start] == S[end]) {
start --
end ++
}
return Pair(end-1,start+1)
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 2,195 | leetcode-solutions | MIT License |
src/Day02.kt | zoidfirz | 572,839,149 | false | {"Kotlin": 15878} | fun main() {
partOneSolution(readInput("main/resources/Day02_Input"))
partTwoSolution(readInput("main/resources/Day02_Input"))
}
private fun partOneSolution(records: List<String>) {
var sum = 0
val newRecords = records.map { it.split(" ") }
for (record in newRecords) {
val p1Record = record[0]
val p2Record = record[1]
val p1 = firstColumnPlay(p1Record)
val p2 = secondColumnPlay(p2Record)
sum += checkWinnerPartOne(p1, p2)
}
println(sum)
}
private fun partTwoSolution(records: List<String>) {
var sum = 0
val newRecords = records.map { it.split(" ") }
for (record in newRecords) {
val p1Record = record[0]
val desiredOutComeRecord = record[1]
val p1 = firstColumnPlay(p1Record)
val desiredOutCome = desiredResult(desiredOutComeRecord)
sum += checkWinnerPartTwo(p1, desiredOutCome)
}
println(sum)
}
enum class RockPaperScissors(val pointValue: Int, val opponentLoss:Int, val opponentWin:Int) {
Rock(1,3,2),
Paper(2, 1,3),
Scissors(3, 2, 1),
None(0, 0, 0);
}
enum class Result() {
Win, Lose, Draw, None
}
private fun firstColumnPlay(value: String): RockPaperScissors {
when(value) {
"A" -> return RockPaperScissors.Rock
"B" -> return RockPaperScissors.Paper
"C" -> return RockPaperScissors.Scissors
else -> return RockPaperScissors.None
}
}
private fun secondColumnPlay(value: String): RockPaperScissors{
when(value) {
"X" -> return RockPaperScissors.Rock
"Y" -> return RockPaperScissors.Paper
"Z" -> return RockPaperScissors.Scissors
else -> return RockPaperScissors.None
}
}
private fun desiredResult(value: String): Result{
when(value) {
"X" -> return Result.Lose
"Y" -> return Result.Draw
"Z" -> return Result.Win
else -> return Result.None
}
}
private fun checkWinnerPartOne(value1: RockPaperScissors, value2: RockPaperScissors): Int {
return if(value1 == value2) { // draw
3 + value2.pointValue
}else if(value1 == RockPaperScissors.Rock && value2 == RockPaperScissors.Scissors ) {
value2.pointValue // loss
}else if (value1 == RockPaperScissors.Paper && value2 == RockPaperScissors.Rock ) {
value2.pointValue // loss
}else if (value1 == RockPaperScissors.Scissors && value2 == RockPaperScissors.Paper ) {
value2.pointValue // loss
}else if(value1 == RockPaperScissors.Rock && value2 == RockPaperScissors.Paper ) {
value2.pointValue + 6 // winner
}else if (value1 == RockPaperScissors.Paper && value2 == RockPaperScissors.Scissors ) {
value2.pointValue + 6 // winner
}else if (value1 == RockPaperScissors.Scissors && value2 == RockPaperScissors.Rock ) {
value2.pointValue + 6 // winner
}else 0
}
private fun checkWinnerPartTwo(playerOneInput: RockPaperScissors, desiredOutCome:Result ): Int {
return when(desiredOutCome) {
Result.Draw -> playerOneInput.pointValue + 3
Result.Win -> playerOneInput.opponentWin + 6
Result.Lose -> playerOneInput.opponentLoss
else -> {
0
}
}
// return if(desiredOutCome == Des) { // draw
// 3 + value2.pointValue
// }else if(value1 == RockPaperScissors.Rock && value2 == RockPaperScissors.Scissors ) {
// value2.pointValue // loss
// }else if (value1 == RockPaperScissors.Paper && value2 == RockPaperScissors.Rock ) {
// value2.pointValue // loss
// }else if (value1 == RockPaperScissors.Scissors && value2 == RockPaperScissors.Paper ) {
// value2.pointValue // loss
// }else if(value1 == RockPaperScissors.Rock && value2 == RockPaperScissors.Paper ) {
// value2.pointValue + 6 // winner
// }else if (value1 == RockPaperScissors.Paper && value2 == RockPaperScissors.Scissors ) {
// value2.pointValue + 6 // winner
// }else if (value1 == RockPaperScissors.Scissors && value2 == RockPaperScissors.Rock ) {
// value2.pointValue + 6 // winner
// }else 0
} | 0 | Kotlin | 0 | 0 | e955c1c08696f15929aaf53731f2ae926c585ff3 | 4,088 | kotlin-advent-2022 | Apache License 2.0 |
kotlin/structures/MetricTree.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package structures
import java.util.Random
// https://en.wikipedia.org/wiki/Metric_tree
class MetricTree(var x: IntArray, var y: IntArray) {
fun build(low: Int, high: Int) {
if (high - low <= 2) return
swap(low + rnd.nextInt(high - low), low)
val mid = low + 1 + high ushr 1
nth_element(low + 1, high, mid)
build(low + 1, mid)
build(mid + 1, high)
}
// See http://www.cplusplus.com/reference/algorithm/nth_element
fun nth_element(low: Int, high: Int, n: Int) {
var low = low
var high = high
val center = low - 1
while (true) {
val k = partition(center, low, high, low + rnd.nextInt(high - low))
if (n < k) high = k else if (n > k) low = k + 1 else return
}
}
fun partition(center: Int, fromInclusive: Int, toExclusive: Int, separatorIndex: Int): Int {
var i = fromInclusive
var j = toExclusive - 1
if (i >= j) return j
val separator = dist2(x[center], y[center], x[separatorIndex], y[separatorIndex])
swap(i++, separatorIndex)
while (i <= j) {
while (i <= j && dist2(x[center], y[center], x[i], y[i]) < separator) ++i
while (i <= j && dist2(x[center], y[center], x[j], y[j]) > separator) --j
if (i >= j) break
swap(i++, j--)
}
swap(j, fromInclusive)
return j
}
fun swap(i: Int, j: Int) {
var t = x[i]
x[i] = x[j]
x[j] = t
t = y[i]
y[i] = y[j]
y[j] = t
}
var bestDist: Long = 0
var bestNode = 0
fun findNearestNeighbour(px: Int, py: Int): Int {
bestDist = Long.MAX_VALUE
findNearestNeighbour(0, x.size, px, py)
return bestNode
}
fun findNearestNeighbour(low: Int, high: Int, px: Int, py: Int) {
if (high - low <= 0) return
val d2 = dist2(px, py, x[low], y[low])
if (bestDist > d2) {
bestDist = d2
bestNode = low
}
if (high - low <= 1) return
val mid = low + 1 + high ushr 1
val dist2 = dist2(px, py, x[mid], y[mid])
if (bestDist > dist2) {
bestDist = dist2
bestNode = mid
}
val R: Double = Math.sqrt(dist2(x[low], y[low], x[mid], y[mid]))
val r: Double = Math.sqrt(bestDist)
val d: Double = Math.sqrt(d2)
if (d <= R + r) {
findNearestNeighbour(low + 1, mid, px, py)
}
if (d >= R - r) {
findNearestNeighbour(mid + 1, high, px, py)
}
}
companion object {
val rnd: Random = Random(1)
fun dist2(x1: Int, y1: Int, x2: Int, y2: Int): Long {
val dx = x1 - x2
val dy = y1 - y2
return dx.toLong() * dx + dy.toLong() * dy
}
// random test
fun main(args: Array<String?>?) {
for (step in 0..99999) {
val qx: Int = rnd.nextInt(100) - 50
val qy: Int = rnd.nextInt(100) - 50
val n: Int = rnd.nextInt(100) + 1
val x = IntArray(n)
val y = IntArray(n)
var minDist = Long.MAX_VALUE
for (i in 0 until n) {
x[i] = rnd.nextInt(100) - 50
y[i] = rnd.nextInt(100) - 50
minDist = Math.min(minDist, dist2(qx, qy, x[i], y[i]))
}
val metricTree = MetricTree(x, y)
val index = metricTree.findNearestNeighbour(qx, qy)
if (minDist != metricTree.bestDist || dist2(
qx,
qy,
x[index],
y[index]
) != minDist
) throw RuntimeException()
}
}
}
init {
build(0, x.size)
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 3,906 | codelibrary | The Unlicense |
src/Day16.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | import java.lang.IllegalArgumentException
data class Valve(val name: String, val flowRate: Int, val connectionNames: List<String>)
fun buildSystem(valves: List<Valve>): ValveSystem {
val valvesByName = valves.associateByTo(mutableMapOf()) { it.name }
val toOpen = valves.filter { it.flowRate > 0 }.toMutableSet()
val indexByName: Map<String, Int> = valves.foldIndexed(mutableMapOf()) { index, map, valve ->
map[valve.name] = index
map
}
val distances = Array(valves.size) { Array(valves.size) { 100_000 } }
valves.forEachIndexed { valveIndex, valve ->
valve.connectionNames.forEach { connection ->
distances[valveIndex][indexByName[connection]!!] = 1
}
}
for (k in valves.indices) {
for (i in valves.indices) {
for (j in valves.indices) {
val proposed = distances[i][k] + distances[k][j]
if (distances[i][j] > proposed) {
distances[i][j] = proposed
}
}
}
}
return ValveSystem(toOpen, valvesByName, distances, indexByName)
}
class ValveSystem(
val toOpen: MutableSet<Valve>,
private val valvesByName: MutableMap<String, Valve>,
private val distances: Array<Array<Int>>,
private val indexByName: Map<String, Int>
) {
private fun index(valve: Valve) = indexByName[valve.name]!!
fun dist(from: Valve, to: Valve) = distances[index(from)][index(to)]
fun targets(from: Valve): List<Valve> = toOpen.filter { it !== from }
operator fun get(key: String): Valve = valvesByName[key]!!
fun open(valve: Valve) {
toOpen.remove(valve)
}
fun close(valve: Valve) = toOpen.add(valve)
}
fun main() {
val parserRegexp =
"^Valve (\\w\\w) has flow rate=(\\d+); tunnels? leads? to valves? ((?:\\w\\w(?:,\\s)?)+)$".toRegex()
fun parse(input: String): Valve {
val matcher =
parserRegexp.matchEntire(input) ?: throw IllegalArgumentException("Invalid regexp for input string $input")
val groups = matcher.groupValues
val valveName = groups[1]
val flowRate = groups[2].toInt()
val connections = groups[3].split(", ")
return Valve(valveName, flowRate, connections)
}
fun calcPressure(
valve: Valve,
timeLeft: Int,
system: ValveSystem,
): Int {
if (timeLeft < 2 || system.toOpen.isEmpty()) {
return 0
}
var time = timeLeft
if (valve.flowRate > 0) {
system.open(valve)
time--
}
val targets = system.targets(valve)
if (targets.isEmpty()) {
return valve.flowRate * time
}
val flow = targets.maxOf { calcPressure(it, time - system.dist(valve, it), system) }
system.close(valve)
return valve.flowRate * time + flow
}
val memo = mutableMapOf<String, Int>()
fun calcPressureMemo(valve: Valve,
timeLeft: Int,
system: ValveSystem): Int {
val key = valve.name + timeLeft + system.toOpen.asSequence().map { it.name }.sorted().joinToString("")
return memo[key] ?: calcPressure(valve, timeLeft, system).also { memo[key] = it }
}
fun calcPressureWithBuddy(
valve: Valve,
timeLeft: Int,
system: ValveSystem,
): Int {
if (timeLeft < 2 || system.toOpen.isEmpty()) {
return 0
}
var time = timeLeft
if (valve.flowRate > 0) {
system.open(valve)
time--
}
val targets = system.targets(valve)
if (targets.isEmpty()) {
return valve.flowRate * time
}
val flow = targets
.maxOf { calcPressureWithBuddy(it, time - system.dist(valve, it), system) }
val buddyFlow = calcPressureMemo(system["AA"], 26, system)
system.close(valve)
val maxFlow = if (flow > buddyFlow) flow else buddyFlow
return valve.flowRate * time + maxFlow
}
fun part1(input: List<String>, iterations: Int = 30): Int {
val valves = input.map { parse(it) }
val system = buildSystem(valves)
return calcPressure(system["AA"], iterations, system)
}
fun part2(input: List<String>): Int {
val valves = input.map { parse(it) }
val system = buildSystem(valves)
return calcPressureWithBuddy(system["AA"], 26, system)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
check(part1(input) == 2320)
println("checks passed")
println(part2(input))
check(part2(input) == 2967)
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 4,830 | advent-of-code-2022 | Apache License 2.0 |
src/Day16.kt | armandmgt | 573,595,523 | false | {"Kotlin": 47774} | fun main() {
data class Valve(val key: String, val rate: Int, val tunnels: List<String>)
val valvePattern = Regex("Valve (\\w+) has flow rate=(\\d+);")
val tunnelsPattern = Regex("tunnels? leads? to valves? ([\\w, ]+)")
fun parseGraph(input: List<String>): Map<String, Valve> {
val graph = mutableMapOf<String, Valve>()
input.forEach {
val (key, rate) = valvePattern.find(it)!!.destructured
val tunnels = tunnelsPattern.find(it)!!.groupValues[1].split(", ")
graph[key] = Valve(key, rate.toInt(), tunnels)
}
return graph
}
var callCount = 0
fun bfs(graph: Map<String, Valve>, minutesLeft: Int, currentValveKey: String, openedValves: Set<String>): Int {
callCount += 1
println("analyzing $currentValveKey ; call count $callCount")
// println("== Minute ${30 - minutesLeft} ==")
val currentPressurePerMinute = openedValves.sumOf { graph[it]!!.rate }
// println("Opened valves are ${openedValves.joinToString()} releasing $currentPressurePerMinute pressure.")
if (minutesLeft == 0) return currentPressurePerMinute
val currentValve = graph[currentValveKey]!!
// println("currentValve rate=${currentValve.rate} neighbor=${currentValve.tunnels.first()}")
val scoreIfOpening = if (currentValve.rate != 0 && !openedValves.contains(currentValve.key)) {
bfs(graph, minutesLeft - 1, currentValve.key, openedValves + setOf(currentValve.key))
} else { 0 }
val scoreOfNeighbors = currentValve.tunnels.map { neighbor ->
bfs(graph, minutesLeft - 1, neighbor, openedValves)
}
return currentPressurePerMinute + (arrayOf(scoreIfOpening) + scoreOfNeighbors).max()
}
fun part1(input: List<String>): Int {
val graph = parseGraph(input)
val openedValves = setOf<String>()
return bfs(graph, 30, "AA", openedValves).also { println(it) }
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("resources/Day16_test")
check(part1(testInput) == 1651)
val input = readInput("resources/Day16")
println(part1(input))
println(part2(input))
}
//val testResult = arrayListOf(
// Pair(graph["AA"]!!, false),
// Pair(graph["DD"]!!, false),
// Pair(graph["DD"]!!, true),
// Pair(graph["CC"]!!, false),
// Pair(graph["BB"]!!, false),
// Pair(graph["BB"]!!, true),
// Pair(graph["AA"]!!, false),
// Pair(graph["II"]!!, false),
// Pair(graph["JJ"]!!, false),
// Pair(graph["JJ"]!!, true),
// Pair(graph["II"]!!, false),
// Pair(graph["AA"]!!, false),
// Pair(graph["DD"]!!, false),
// Pair(graph["EE"]!!, false),
// Pair(graph["FF"]!!, false),
// Pair(graph["GG"]!!, false),
// Pair(graph["HH"]!!, false),
// Pair(graph["HH"]!!, true),
// Pair(graph["GG"]!!, false),
// Pair(graph["FF"]!!, false),
// Pair(graph["EE"]!!, false),
// Pair(graph["EE"]!!, true),
// Pair(graph["DD"]!!, false),
// Pair(graph["CC"]!!, false),
// Pair(graph["CC"]!!, true),
// Pair(graph["CC"]!!, false),
// Pair(graph["CC"]!!, false),
// Pair(graph["CC"]!!, false),
// Pair(graph["CC"]!!, false),
// Pair(graph["CC"]!!, false),
// Pair(graph["CC"]!!, false),
//) | 0 | Kotlin | 0 | 1 | 0d63a5974dd65a88e99a70e04243512a8f286145 | 3,388 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/day09/Day09.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day09
import runDay
import toUnit
import utils.Point
import kotlin.math.abs
fun main() {
fun part1(input: List<String>) =
input.toMoves()
.fold(Rope(2)) { path, next ->
// TODO: Condense
repeat(next.distance) {
path.moveHead(next.direction)
}
path
}.tailVisited.size
fun part2(input: List<String>) =
input.toMoves()
.fold(Rope(10)) { path, next ->
// TODO: Condense
repeat(next.distance) {
path.moveHead(next.direction)
}
path
}.tailVisited.size
(object {}).runDay(
part1 = ::part1,
part1Check = 13,
part2 = ::part2,
part2Check = 36,
)
}
private data class Move(val direction: Point, val distance: Int)
private fun abs(point: Point) = Point(
x = abs(point.x),
y = abs(point.y),
)
private class Rope(
knots: Int = 2,
) {
private var points: MutableList<Point> = MutableList(
knots
) { Point(0, 0) }
val tailVisited = mutableSetOf(points.last())
fun moveHead(point: Point) {
points[0] += point
points.indices.windowed(2).forEach { (head, tail) ->
points[tail] = moveTail(points[head], points[tail])
}
tailVisited.add(points.last())
}
}
private fun moveTail(head: Point, tail: Point): Point {
val distance = head - tail
val absoluteDistance = abs(distance)
if (absoluteDistance.x > 1 || absoluteDistance.y > 1) {
val dX = absoluteDistance.x
val dY = absoluteDistance.y
return tail + when {
dX > 0 && dY > 0 -> Point(distance.x.toUnit(), distance.y.toUnit())
dX > 0 -> Point(distance.x.toUnit(), 0)
else -> Point(0, distance.y.toUnit())
}
}
return tail
}
private typealias Direction = String
private fun Direction.toPoint() = when (this) {
"L" -> Point(-1, 0)
"R" -> Point(1, 0)
"U" -> Point(0, 1)
"D" -> Point(0, -1)
else -> throw IllegalArgumentException(this)
}
private fun List<String>.toMoves() = map {
it.split(' ', limit = 2)
.let { pair ->
Move(
direction = pair.first().toPoint(),
distance = pair.last().toInt()
)
}
} | 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 2,391 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g2901_3000/s2976_minimum_cost_to_convert_string_i/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2976_minimum_cost_to_convert_string_i
// #Medium #Array #String #Graph #Shortest_Path
// #2024_01_19_Time_421_ms_(85.29%)_Space_46_MB_(61.76%)
import kotlin.math.min
class Solution {
fun minimumCost(
inputText: String,
desiredText: String,
fromLetters: CharArray,
toLetters: CharArray,
transformationCost: IntArray
): Long {
val alphabetSize = 26
val transformationMatrix = Array(alphabetSize) { IntArray(alphabetSize) }
for (idx in 0 until alphabetSize) {
transformationMatrix[idx].fill(Int.MAX_VALUE)
transformationMatrix[idx][idx] = 0
}
var i = 0
while (i < fromLetters.size) {
val origChar = fromLetters[i].code - 'a'.code
val newChar = toLetters[i].code - 'a'.code
val changeCost = transformationCost[i]
transformationMatrix[origChar][newChar] =
min(transformationMatrix[origChar][newChar], changeCost)
i++
}
var k = 0
do {
for (row in 0 until alphabetSize) {
for (col in 0 until alphabetSize) {
if (transformationMatrix[row][k] != Int.MAX_VALUE &&
transformationMatrix[k][col] != Int.MAX_VALUE
) {
transformationMatrix[row][col] = min(
transformationMatrix[row][col],
(
transformationMatrix[row][k] +
transformationMatrix[k][col]
)
)
}
}
}
k++
} while (k < alphabetSize)
var totalCost: Long = 0
for (pos in 0 until inputText.length) {
val startChar = inputText[pos].code - 'a'.code
val endChar = desiredText[pos].code - 'a'.code
if (startChar == endChar) {
continue
}
if (transformationMatrix[startChar][endChar] == Int.MAX_VALUE) {
return -1
} else {
totalCost += transformationMatrix[startChar][endChar].toLong()
}
}
return totalCost
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,321 | LeetCode-in-Kotlin | MIT License |
aoc-day15/src/Day15.kt | rnicoll | 438,043,402 | false | {"Kotlin": 90620, "Rust": 1313} | import java.nio.file.Files
import java.nio.file.Path
import java.util.*
fun main() {
val map = Files.readAllLines(Path.of("input")).map { line ->
line.toCharArray().map {
it.toString().toInt()
}.toIntArray()
}.toTypedArray()
println(part1(map))
println(part2(map))
}
private fun part1(map: Array<IntArray>) = route(CaveMap(map), Coord(0, 0))
private fun part2(map: Array<IntArray>): Int? {
val expandedMap = Array<IntArray>(map.size * 5) { col ->
IntArray(map[0].size * 5) { 0 } }
for (colAdd in 0..4) {
for (rowAdd in 0..4) {
for (col in map.indices) {
for (row in map[col].indices) {
val expandedRow = row + (map.size * rowAdd)
val expandedCol = col + (map.size * colAdd)
expandedMap[expandedCol][expandedRow] = (map[col][row] + colAdd + rowAdd)
while (expandedMap[expandedCol][expandedRow] > 9) {
expandedMap[expandedCol][expandedRow] -= 9
}
}
}
}
}
return route(CaveMap(expandedMap), Coord(0, 0))
}
private fun route(map: CaveMap, source: Coord): Int? {
val q: PriorityQueue<CoordWithDistance> = PriorityQueue<CoordWithDistance>()
val dist: MutableMap<Coord, Int> = mutableMapOf()
val prev: MutableMap<Coord, Coord> = mutableMapOf()
dist[source] = 0
for (row in map.costs.indices) {
for (col in map.costs.indices) {
val v = Coord(col, row)
if (v != source) {
dist[v] = Int.MAX_VALUE / 2
}
q.add(CoordWithDistance(v, dist[v]!!))
}
}
val end = Coord(map.cols - 1, map.rows - 1)
while (q.isNotEmpty()) {
val u = q.poll().coord
println(q.size)
if (u == end) {
// We're at the end
var current = Coord(map.cols - 1, map.rows - 1)
while (current != source) {
println(current)
current = prev[current]!!
}
return dist[u]
}
u.adjacent(map).forEach { v ->
val alt = dist[u]!! + map.get(v)
if (alt < dist[v]!!) {
dist[v] = alt
prev[v] = u
val newCoord = CoordWithDistance(v, alt)
// Replace the coordinate in the priority queue
q.remove(newCoord)
q.add(newCoord)
}
}
}
return null
}
| 0 | Kotlin | 0 | 0 | 8c3aa2a97cb7b71d76542f5aa7f81eedd4015661 | 2,537 | adventofcode2021 | MIT License |
src/main/kotlin/com/sk/topicWise/dp/hard/1335. Minimum Difficulty of a Job Schedule.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.topicWise.dp.hard
class Solution1335 {
fun minDifficulty(jobDifficulty: IntArray, days: Int): Int {
val SIZE = jobDifficulty.size
if (SIZE < days) return -1
fun minAt(startIndex: Int, d: Int): Int {
if (d == 0 && startIndex == SIZE) return 0
if (d == 0 || startIndex == SIZE) return Int.MAX_VALUE
var curMax = jobDifficulty[startIndex]
var min = Int.MAX_VALUE
for (i in startIndex until SIZE) {
curMax = maxOf(curMax, jobDifficulty[i])
val temp = minAt(i + 1, d - 1)
if (temp != Int.MAX_VALUE) min = minOf(min, temp + curMax)
}
return min
}
return minAt(0, days)
}
fun minDifficulty2(jobDifficulty: IntArray, days: Int): Int {
val SIZE = jobDifficulty.size
if (SIZE < days) return -1
val memo = Array(SIZE) { IntArray(days + 1) { -1 } }
fun minAt(startIndex: Int, d: Int): Int {
if (d == 0 && startIndex == SIZE) return 0
if (d == 0 || startIndex == SIZE) return Int.MAX_VALUE
if (memo[startIndex][d] == -1) {
var curMax = jobDifficulty[startIndex]
var min = Int.MAX_VALUE
for (i in startIndex until SIZE) {
curMax = maxOf(curMax, jobDifficulty[i])
val temp = minAt(i + 1, d - 1)
if (temp != Int.MAX_VALUE) min = minOf(min, temp + curMax)
}
memo[startIndex][d] = min
}
return memo[startIndex][d]
}
return minAt(0, days)
}
fun minDifficulty3(jobDifficulty: IntArray, d: Int): Int {
val A = Array(jobDifficulty.size) { IntArray(d) { Int.MAX_VALUE } }
A[0][0] = jobDifficulty[0]
for (i in 1 until jobDifficulty.size) {
A[i][0] = maxOf(A[i - 1][0], jobDifficulty[i])
}
for (i in 1 until jobDifficulty.size) {
for (j in 1 until minOf(i + 1, d)) {
for (k in 0 until i) {
A[i][j] = minOf(A[i][j], A[k][j - 1] + jobDifficulty.sliceArray(k + 1..i + 1).maxOrNull()!!)
}
}
}
return A.last().last()
}
}
fun main() {
val s = Solution1335()
println(s.minDifficulty2(intArrayOf(6, 5, 4, 3, 2, 1), 2))
} | 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,410 | leetcode-kotlin | Apache License 2.0 |
src/Day18.kt | GarrettShorr | 571,769,671 | false | {"Kotlin": 82669} | import kotlin.math.abs
fun main() {
data class Cube(val x: Int, val y: Int, val z: Int) {
fun isAdjacent(other: Cube): Boolean {
if (x == other.x && y == other.y) {
return abs(z - other.z) == 1
} else if (y == other.y && z == other.z) {
return abs(x - other.x) == 1
} else if (z == other.z && x == other.x) {
return abs(y - other.y) == 1
} else {
return false
}
}
fun countExposedSides(others: List<Cube>): Int {
var count = 6
val cubes = others.filterNot { it.x == x && it.y == y && it.z == z }
if (cubes.any { (it.x == (x - 1)) && (it.y == y) && (it.z == z) }) {
count--
}
if (cubes.any { it.x == x + 1 && it.y == y && it.z == z }) {
count--
}
if (cubes.any { it.y == y - 1 && it.x == x && it.z == z }) {
count--
}
if (cubes.any { it.y == y + 1 && it.x == x && it.z == z }) {
count--
}
if (cubes.any { it.z == z - 1 && it.x == x && it.y == y }) {
count--
}
if (cubes.any { it.z == z + 1 && it.x == x && it.y == y }) {
count--
}
return count
}
fun getNeighbors(): MutableList<Cube> {
val neighbors = mutableListOf<Cube>()
neighbors.add(Cube(x - 1, y, z))
neighbors.add(Cube(x + 1, y, z))
neighbors.add(Cube(x, y - 1, z))
neighbors.add(Cube(x, y + 1, z))
neighbors.add(Cube(x, y, z - 1))
neighbors.add(Cube(x, y, z + 1))
// for (dx in -1..1) {
// for (dy in -1..1) {
// for (dz in -1..1) {
// if (dx != 0 && dy != 0 && dz != 0) {
// neighbors.add(Cube(x + dx, y + dy, z + dz))
// }
// }
// }
// }
return neighbors
}
}
fun part1(input: List<String>): Int {
var cubes = input.map {
var (x, y, z) = it.split(",").map { it.toInt() }
Cube(x, y, z)
}
var count = 0
cubes.forEach { count += it.countExposedSides(cubes) }
return count
}
fun hasNoEscape(cube: Cube, lavaDrops: Set<Cube>, dest: Cube,
maxX: Int, maxY: Int, maxZ: Int, minX: Int, minY : Int, minZ: Int) : Boolean {
val visited = mutableSetOf<Cube>()
val visitedMap = mutableMapOf<Cube, Int>()
visited.add(cube)
val queue = mutableSetOf<Cube>()
queue.addAll(cube.getNeighbors().filterNot { it in lavaDrops })
while(queue.isNotEmpty()) {
val nextMove = queue.first()
queue.remove(nextMove)
if(nextMove == dest) {
// println("Outside")
return false
}
val neighbors = nextMove.getNeighbors().filterNot { it in lavaDrops }
.filterNot { it in visited }
.filterNot { it.x > maxX + 2 || it.y > maxY + 2 || it.z > maxZ + 2
|| it.x < minX - 2 || it.y < minY - 2 || it.z < minZ - 2 }.shuffled()
// if(neighbors.isEmpty()) {
//// println("empty neighbors")
// return true
// }
// if(visitedMap.getOrDefault(nextMove, 0) > 100) {
//// println("going in circles")
// return true
// }
visited.add(nextMove)
visitedMap[nextMove] = visitedMap.getOrDefault(nextMove, 0) + 1
queue.addAll(neighbors)
}
return true
}
fun part2(input: List<String>): Int {
val cubes = input.map {
val (x, y, z) = it.split(",").map { it.toInt() }
Cube(x, y, z)
}
// find all holes
val minX = cubes.minOf { it.x }
val maxX = cubes.maxOf { it.x }
val minY = cubes.minOf { it.y }
val maxY = cubes.maxOf { it.y }
val minZ = cubes.minOf { it.z }
val maxZ = cubes.maxOf { it.z }
val empties = mutableListOf<Cube>()
for (x in minX + 1 until maxX) {
for (y in minY + 1 until maxY) {
for (z in minZ + 1 until maxZ) {
val cube = Cube(x, y, z)
if (cube !in cubes) {
empties.add(cube)
}
}
}
}
val airPockets = mutableSetOf<Cube>()
var outside = 0
for(i in empties.indices) {
if(hasNoEscape(empties[i], cubes.toSet(), Cube(minX , minY, minZ+1),
maxX, maxY, maxZ, minX, minY, minZ)) {
airPockets.add(empties[i])
} else {
outside++
}
}
println("Airpockets: ${airPockets.size} Outside: $outside")
var surfaceArea = 0
var adjacentPockets = 0
cubes.forEach { surfaceArea += it.countExposedSides(cubes) }
println(surfaceArea)
for(airPocket in airPockets) {
cubes.forEach {
if(it.isAdjacent(airPocket)) {
surfaceArea--
adjacentPockets++
}
}
}
println(adjacentPockets)
return surfaceArea
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
// println(part1(testInput))
println(part2(testInput))
val input = readInput("Day18")
// output(part1(input))
output(part2(input))
}
| 0 | Kotlin | 0 | 0 | 391336623968f210a19797b44d027b05f31484b5 | 4,915 | AdventOfCode2022 | Apache License 2.0 |
src/main/aoc2018/Day23.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
import java.util.*
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Day23(input: List<String>) {
data class Pos(val x: Int, val y: Int, val z: Int)
data class Nanobot(val pos: Pos, val range: Int) {
fun inRange(other: Nanobot): Boolean {
return abs(pos.x - other.pos.x) +
abs(pos.y - other.pos.y) +
abs(pos.z - other.pos.z) <= range
}
}
data class Cube(val xRange: IntRange, val yRange: IntRange, val zRange: IntRange,
val botsInRangeOfWholeParent: Int, val nanobotsToCheck: List<Nanobot>) {
// The number of nanobots in range of the cube. If the cube needs further splitting
// this is an upper limit estimate of maximum possible number of bots in range.
val botsInRange: Int
// If the cube doesn't have any partial intersections there is no need to split it
val needsSplitting get() = botsWithPartialIntersection.isNotEmpty()
private val botsInRangeOfWholeCube: Int
private val botsWithPartialIntersection = mutableListOf<Nanobot>()
init {
var containedByCount = 0
nanobotsToCheck.forEach { nanobot ->
when {
nanobot.range >= distanceToFurthestPoint(nanobot.pos) -> {
// Case 1: Whole cube is within the range of the current bot
containedByCount++
}
nanobot.range < shortestDistance(nanobot.pos) -> {
// Case 2: Whole cube is out of range of the current bot
// Just ignore this bot.
}
else -> {
// Case 3: Part of the cube is within range of the current bot
botsWithPartialIntersection.add(nanobot)
}
}
}
botsInRangeOfWholeCube = containedByCount
botsInRange = botsInRangeOfWholeParent + botsInRangeOfWholeCube + botsWithPartialIntersection.size
}
// Split this cube in up to 8 smaller cubes. Can be fewer than 8 if the cube is
// too small to split into 8.
fun split(): List<Cube> {
fun clamp(range: IntRange) = range.first..max(range.first, range.last)
fun IntRange.size() = last - first + 1
if (xRange.size() <= 1 && yRange.size() <= 1 && zRange.size() <= 1) {
throw RuntimeException("Trying to split a cube too small to split: $this")
}
return setOf(
Cube(clamp(xRange.first until xRange.first + xRange.size() / 2),
clamp(yRange.first until yRange.first + yRange.size() / 2),
clamp(zRange.first until zRange.first + zRange.size() / 2),
botsInRangeOfWholeParent + botsInRangeOfWholeCube,
botsWithPartialIntersection
),
Cube((xRange.first + xRange.size() / 2)..xRange.last,
clamp(yRange.first until yRange.first + yRange.size() / 2),
clamp(zRange.first until zRange.first + zRange.size() / 2),
botsInRangeOfWholeParent + botsInRangeOfWholeCube,
botsWithPartialIntersection
),
Cube(clamp(xRange.first until xRange.first + xRange.size() / 2),
(yRange.first + yRange.size() / 2)..yRange.last,
clamp(zRange.first until zRange.first + zRange.size() / 2),
botsInRangeOfWholeParent + botsInRangeOfWholeCube,
botsWithPartialIntersection
),
Cube(clamp(xRange.first until xRange.first + xRange.size() / 2),
clamp(yRange.first until yRange.first + yRange.size() / 2),
(zRange.first + zRange.size() / 2)..zRange.last,
botsInRangeOfWholeParent + botsInRangeOfWholeCube,
botsWithPartialIntersection
),
Cube((xRange.first + xRange.size() / 2)..xRange.last,
(yRange.first + yRange.size() / 2)..yRange.last,
clamp(zRange.first until zRange.first + zRange.size() / 2),
botsInRangeOfWholeParent + botsInRangeOfWholeCube,
botsWithPartialIntersection
),
Cube((xRange.first + xRange.size() / 2)..xRange.last,
clamp(yRange.first until yRange.first + yRange.size() / 2),
(zRange.first + zRange.size() / 2)..zRange.last,
botsInRangeOfWholeParent + botsInRangeOfWholeCube,
botsWithPartialIntersection
),
Cube(clamp(xRange.first until xRange.first + xRange.size() / 2),
(yRange.first + yRange.size() / 2)..yRange.last,
(zRange.first + zRange.size() / 2)..zRange.last,
botsInRangeOfWholeParent + botsInRangeOfWholeCube,
botsWithPartialIntersection
),
Cube((xRange.first + xRange.size() / 2)..xRange.last,
(yRange.first + yRange.size() / 2)..yRange.last,
(zRange.first + zRange.size() / 2)..zRange.last,
botsInRangeOfWholeParent + botsInRangeOfWholeCube,
botsWithPartialIntersection
)
).toList()
}
// Shortest distance from the given point to the cube, returns 0 if the point is inside the cube.
fun shortestDistance(from: Pos): Int {
fun IntRange.shortestDistance(point: Int) =
if (point in this) 0
else min(abs(point - last), abs(point - first))
return xRange.shortestDistance(from.x) + yRange.shortestDistance(from.y) + zRange.shortestDistance(from.z)
}
// Distance from the given point to the point in the cube that is furthest away from the point
private fun distanceToFurthestPoint(from: Pos): Int {
fun IntRange.furthestDistance(point: Int) = max(abs(point - last), abs(point - first))
return xRange.furthestDistance(from.x) + yRange.furthestDistance(from.y) + zRange.furthestDistance(from.z)
}
}
private val nanobots = input.map { line ->
val (x, y, z) = line.substringAfter("<").substringBefore(">").split(",")
val pos = Pos(x.toInt(), y.toInt(), z.toInt())
val range = line.substringAfter("r=").toInt()
Nanobot(pos, range)
}
fun solvePart1(): Int {
val strongest = nanobots.maxByOrNull { it.range }!!
return nanobots.filter { strongest.inRange(it) }.size
}
fun solvePart2(): Int {
val spaces = findSpacesWithMostBotsInRange()
return spaces.minOf { it.shortestDistance(Pos(0, 0, 0)) }
}
private fun findSpacesWithMostBotsInRange(): Set<Cube> {
var largestSoFar = -1
val cubesInRangeOfMostNanobots = mutableSetOf<Cube>()
val boundingCube = Cube(
nanobots.minByOrNull { it.pos.x }!!.pos.x..nanobots.maxByOrNull { it.pos.x }!!.pos.x,
nanobots.minByOrNull { it.pos.y }!!.pos.y..nanobots.maxByOrNull { it.pos.y }!!.pos.y,
nanobots.minByOrNull { it.pos.z }!!.pos.z..nanobots.maxByOrNull { it.pos.z }!!.pos.z,
0,
nanobots
)
val toSplit = PriorityQueue<Cube> { a, b -> b.botsInRange - a.botsInRange }
toSplit.add(boundingCube)
while (toSplit.isNotEmpty()) {
val cube = toSplit.poll()
if (cube.botsInRange >= largestSoFar) {
// Only split cubes that have a chance of being better than the current record
cube.split().forEach {subCube ->
if (subCube.botsInRange >= largestSoFar) {
// Only queue cubes for splitting that have a chance of being better than the current record
if (subCube.needsSplitting) {
toSplit.add(subCube)
} else {
if (subCube.botsInRange > largestSoFar) {
// New record, throw away previous data
cubesInRangeOfMostNanobots.clear()
}
cubesInRangeOfMostNanobots.add(subCube)
largestSoFar = subCube.botsInRange
}
}
}
}
}
return cubesInRangeOfMostNanobots
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 9,102 | aoc | MIT License |
src/Day04.kt | ka1eka | 574,248,838 | false | {"Kotlin": 36739} | fun main() {
fun expand(assigment: String): Set<Int> = assigment
.split('-')
.map { it.toInt() }
.let { Pair(it[0], it[1]) }
.let { (it.first..it.second).toSet() }
fun part1(input: List<String>): Int = input
.map { it.split(',') }
.map {
Pair(
expand(it[0]),
expand(it[1])
)
}.count {
it.first.containsAll(it.second) || it.second.containsAll(it.first)
}
fun part2(input: List<String>): Int = input
.map { it.split(',') }
.map {
expand(it[0]) intersect expand(it[1])
}.count {
it.isNotEmpty()
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f7893448db92a313c48693b64b3b2998c744f3b | 898 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | maewCP | 579,203,172 | false | {"Kotlin": 59412} | fun main() {
val regex = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex()
fun part1(input: List<String>): Int {
var containCount = 0
input.forEach { line ->
val g = regex.find(line)!!.destructured.toList().map { it.toInt() }
if ((g[0] <= g[2] && g[1] >= g[3]) || (g[2] <= g[0] && g[3] >= g[1])) containCount++
}
return containCount
}
fun part2(input: List<String>): Int {
var overlapCount = 0
input.forEach { line ->
val g = regex.find(line)!!.destructured.toList().map { it.toInt() }
if (!(g[2] > g[1] || g[0] > g[3])) overlapCount++
}
return overlapCount
}
// 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")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 8924a6d913e2c15876c52acd2e1dc986cd162693 | 960 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/year2022/day24/Day24.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day24
import Point2D
import readInputFileByYearAndDay
import readTestFileByYearAndDay
enum class Action(val offset: Point2D) {
UP(Point2D(0, -1)),
DOWN(Point2D(0, 1)),
RIGHT(Point2D(1, 0)),
LEFT(Point2D(-1, 0)),
WAIT(Point2D(0, 0));
companion object {
infix fun from(s: String): Action = when (s) {
">" -> RIGHT
"<" -> LEFT
"^" -> UP
"v" -> DOWN
else -> WAIT
}
}
}
data class Blizzard(var position: Point2D, var direction: Action)
fun main() {
fun simulateTrip(
startingPoint: Point2D,
goal: Point2D,
field: List<String>,
blizzards: MutableList<Blizzard>
): Int {
var toCheck = listOf(startingPoint)
var rounds = 0
while (true) {
// see if we already reached the goal
if (toCheck.contains(goal)) return rounds
rounds += 1
// simulate where blizzards are next iteration
// store blizzards redundantly for easy lookup in 2d space
val blizzardPositions = Array(field.size) { BooleanArray(field[0].length) { false } }
blizzards.onEach {
it.position += it.direction.offset
// blizzard preservation of energy
if (it.position.x == 0) it.position = Point2D(blizzardPositions[0].lastIndex - 1, it.position.y)
if (it.position.x == blizzardPositions[0].lastIndex) it.position = Point2D(1, it.position.y)
if (it.position.y == 0) it.position = Point2D(it.position.x, blizzardPositions.lastIndex - 1)
if (it.position.y == blizzardPositions.lastIndex) it.position = Point2D(it.position.x, 1)
}.forEach {
blizzardPositions[it.position.y][it.position.x] = true
}
// for each possible action, create a branching path
toCheck = toCheck.flatMap { pos ->
Action.values().map { action -> action.offset }.map { offset -> offset + pos }
}
.asSequence()
.distinct()
.filterNot { it.y < 0 || it.y > field.lastIndex } // just to avoid going upwards in first step
.filterNot { field[it.y][it.x] == '#' } // ignore rocks
.filterNot { blizzardPositions[it.y][it.x] }
.toList()// ignore the position where we predict blizzards
}
}
fun initializeBlizzardsFromInput(input: List<String>): MutableList<Blizzard> {
val blizzards = mutableListOf<Blizzard>()
for (i in 1 until input.size)
for (j in 1 until input[0].length)
if (listOf('<', '>', '^', 'v').contains(input[i][j]))
blizzards.add(Blizzard(Point2D(j, i), Action.from(input[i][j].toString())))
return blizzards
}
fun part1(input: List<String>): Int {
val startingPoint = Point2D(input.first().indexOf('.'), 0)
val goal = Point2D(input.last().indexOf('.'), input.lastIndex)
val blizzards = initializeBlizzardsFromInput(input)
return simulateTrip(startingPoint, goal, input, blizzards)
}
fun part2(input: List<String>): Int {
val startingPoint = Point2D(input.first().indexOf('.'), 0)
val goal = Point2D(input.last().indexOf('.'), input.lastIndex)
val blizzards = initializeBlizzardsFromInput(input)
// assume that optimal partial solutions contribute to an optimal complete solution
return simulateTrip(startingPoint, goal, input, blizzards) +
simulateTrip(goal, startingPoint, input, blizzards) +
simulateTrip(startingPoint, goal, input, blizzards)
}
val testInput = readTestFileByYearAndDay(2022, 24)
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInputFileByYearAndDay(2022, 24)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 3,986 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/aoc23/Day02.kt | asmundh | 573,096,020 | false | {"Kotlin": 56155} | package aoc23
import runTask
import toOnlyInteger
import utils.InputReader
import java.lang.IllegalStateException
import kotlin.math.max
fun day2part1(input: List<String>): Int {
val games = input.map { parseGame(it) }
val legalGames = games.filter { game ->
game.sets.all {
it.red <= 12 &&
it.green <= 13 &&
it.blue <= 14
}
}
return legalGames.sumOf { it.id }
}
fun day2part2(input: List<String>): Int {
val games = input.map { parseGame(it) }
return games.sumOf {
var red = 1
var blue = 1
var green = 1
it.sets.forEach {
red = max(it.red, red)
blue = max(it.blue, blue)
green = max(it.green, green)
}
red * blue * green
}
}
fun parseGame(game: String): Game {
val sets = game.substringAfter(':').split(";").map {
val cubes = it.split(",")
var red = 0
var blue = 0
var green = 0
cubes.forEach { cube ->
val count = cube.substringBeforeLast(' ').toOnlyInteger()
val color = cube.substringAfterLast(' ')
when (color.length) {
3 -> red = count
4 -> blue = count
5 -> green = count
else -> throw IllegalStateException("WTF: $cube")
}
}
GameSet(blue, red, green)
}
return Game(
game.substringBefore(':').toOnlyInteger(),
sets
)
}
data class Game(
val id: Int,
val sets: List<GameSet>
)
data class GameSet(
val blue: Int,
val red: Int,
val green: Int,
)
fun main() {
val input: List<String> = InputReader.getInputAsList(2)
runTask("D2p1") { day2part1(input) }
runTask("D2p2") { day2part2(input) }
}
| 0 | Kotlin | 0 | 0 | 7d0803d9b1d6b92212ee4cecb7b824514f597d09 | 1,807 | advent-of-code | Apache License 2.0 |
src/main/kotlin/year2022/day-07.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2022
import lib.aoc.Day
import lib.aoc.Part
fun main() {
Day(7, 2022, PartA7(), PartB7()).run()
}
open class PartA7 : Part() {
data class File(val name: String, val size: Int)
data class Directory(val name: String, val parent: Directory?) {
val directories = mutableListOf<Directory>()
private val files = mutableListOf<File>()
val size: Int
get() {
val filesSize = files.sumOf { it.size }
val directoriesSize = directories.sumOf { it.size }
return filesSize + directoriesSize
}
fun parseLs(lines: List<String>) {
lines.forEach {
if (it.substring(0..2) == "dir") {
val dir = Directory(it.drop(4), this)
directories.add(dir)
} else {
val (size, name) = it.split(" ")
files.add(File(name, size.toInt()))
}
}
}
}
sealed class Command(val action: (Directory) -> Directory)
class Ls(private val value: List<String>) : Command({
it.parseLs(value)
it
})
class Cd(private val value: String) : Command({
if (value == "..") {
it.parent!!
} else {
it.directories.first { it.name == value }
}
})
lateinit var rootDir: Directory
override fun parse(text: String) {
val lines = text.split("\n")
rootDir = Directory("root", null)
var currentDir = rootDir
for (i in 1 until lines.size) {
val parts = lines[i].split(" ")
if (parts[0] == "$") {
when (parts[1]) {
"cd" -> currentDir = Cd(parts[2]).action(currentDir)
"ls" -> {
val lsLines = lines.drop(i + 1).takeWhile { it[0] != '$' }
currentDir = Ls(lsLines).action(currentDir)
}
}
}
}
}
override fun compute(): String {
val sizes = mutableListOf<Int>()
calculateSizes(rootDir, sizes)
return sizes.filter { it <= 100_000 }.sum().toString()
}
private fun calculateSizes(dir: Directory, sizes: MutableList<Int>) {
sizes.add(dir.size)
dir.directories.forEach {
calculateSizes(it, sizes)
}
}
override val exampleAnswer: String
get() = "95437"
override val customExampleData: String
get() = day7exampleInput
}
class PartB7 : PartA7() {
override fun compute(): String {
val requiredSize = 30_000_000 - (70_000_000 - rootDir.size)
return findDirSizeToDelete(requiredSize, rootDir, rootDir.size).toString()
}
private fun findDirSizeToDelete(requiredSize: Int, dir: Directory, size: Int): Int {
dir.directories.forEach {
val result = findDirSizeToDelete(requiredSize, it, size)
if (result in requiredSize until size) {
return result
}
}
if (dir.size in requiredSize until size) {
return dir.size
}
return size
}
override val exampleAnswer: String
get() = "24933642"
}
private val day7exampleInput = """
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
""".trimIndent() | 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 3,644 | Advent-Of-Code-Kotlin | MIT License |
src/twentytwentythree/day06/Day06.kt | colinmarsch | 571,723,956 | false | {"Kotlin": 65403, "Python": 6148} | package twentytwentythree.day06
import readInput
fun main() {
fun part1(input: List<String>): Int {
val times = input[0].split(" ").mapNotNull { it.toIntOrNull() }
val distances = input[1].split(" ").mapNotNull { it.toIntOrNull() }
var sum = 1
for (i in times.indices) {
var ways = 0
val time = times[i]
val distance = distances[i]
for (j in 1 until time) {
val currentDistance = (time - j) * j
if (currentDistance > distance) {
ways++
}
}
sum *= ways
}
return sum
}
fun part2(input: List<String>): Int {
val times = input[0].split(" ").mapNotNull { it.toIntOrNull() }
val distances = input[1].split(" ").mapNotNull { it.toIntOrNull() }
val time = times.joinToString("").toLong()
val distance = distances.joinToString("").toLong()
var ways = 0
for (j in 1 until time) {
val currentDistance = (time - j) * j
if (currentDistance > distance) {
ways++
}
}
return ways
}
val input = readInput("twentytwentythree/day06", "Day06_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bcd7a08494e6db8140478b5f0a5f26ac1585ad76 | 1,150 | advent-of-code | Apache License 2.0 |
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day10_fucked.kt | loehnertz | 573,145,141 | false | {"Kotlin": 53239} | package codes.jakob.aoc
import codes.jakob.aoc.ClockCircuit.Instruction.Type.ADD_X
import codes.jakob.aoc.ClockCircuit.Instruction.Type.NOOP
import codes.jakob.aoc.ClockCircuit.Register
import codes.jakob.aoc.shared.splitMultiline
import java.util.*
class Day10_fucked : Solution() {
override fun solvePart1(input: String): Any {
val instructions: List<ClockCircuit.Instruction> = input.splitMultiline().map { parseInstruction(it) }
val command: (Int, RegisterState) -> Pair<Int, Long> = { cycle: Int, registerState: RegisterState ->
cycle to cycle * registerState.getValue(Register.X)
}
val recorded: Set<Pair<Int, Long>> = ClockCircuit(instructions, listOf(command)).run()
return recorded.filter { it.first in signalCycles }.sumOf { it.second }
}
override fun solvePart2(input: String): Any {
TODO()
}
private fun parseInstruction(line: String): ClockCircuit.Instruction {
return if (line == "noop") {
ClockCircuit.Instruction(NOOP, null)
} else {
val (type, value) = line.split(" ")
when (type) {
"addx" -> ClockCircuit.Instruction(ADD_X, value.toInt())
else -> error("Unknown instruction type: $type")
}
}
}
companion object {
private val signalCycles: Set<Int> = setOf(20, 60, 100, 140, 180, 220)
}
}
class ClockCircuit<T>(
private val instructions: List<Instruction>,
private val recordCommands: List<(Int, RegisterState) -> T>,
) {
fun run(): Set<T> {
var cycle = 0
val registerState: RegisterState = mutableMapOf<Register, Long>().withDefault { 1 }
val recorded: MutableList<T> = mutableListOf()
val eventQueue: PriorityQueue<Event> = PriorityQueue(instructions.convertToEvents())
while (eventQueue.isNotEmpty()) {
val event: Event = eventQueue.poll()
val residue: Residue = event.residue()
residue.effects.forEach { it(registerState) }
eventQueue.addAll(residue.events)
recorded.addAll(recordCommands.mapNotNull { it(cycle, registerState) })
cycle = event.cycle
}
return recorded.toSet()
}
class TriggerAdd(cycle: Int, private val register: Register, private val value: Long) : Event(cycle) {
override fun residue(): Residue {
return Residue(
events = listOf(ApplyAdd(cycle + 2, register, value)),
)
}
}
class ApplyAdd(cycle: Int, private val register: Register, private val value: Long) : Event(cycle) {
override fun residue(): Residue {
return Residue(
effects = listOf { state -> state[register] = state.getValue(register) + value },
)
}
}
class Noop(cycle: Int) : Event(cycle) {
override fun residue(): Residue = Residue()
}
abstract class Event(val cycle: Int) : Comparable<Event> {
abstract fun residue(): Residue
override fun compareTo(other: Event): Int = this.cycle.compareTo(other.cycle)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Event) return false
if (cycle != other.cycle) return false
return true
}
override fun hashCode(): Int {
return cycle
}
override fun toString(): String {
return "TickEvent(cycle=$cycle)"
}
}
data class Residue(
val effects: Collection<(RegisterState) -> Unit> = emptyList(),
val events: Collection<Event> = emptyList(),
)
enum class Register {
X
}
data class Instruction(
val type: Type,
val value: Int?,
) {
enum class Type {
NOOP,
ADD_X
}
}
private fun Collection<Instruction>.convertToEvents(): Collection<Event> {
return this.mapIndexed { index: Int, instruction: Instruction ->
val cycle: Int = index + 1
when (instruction.type) {
NOOP -> Noop(cycle)
ADD_X -> TriggerAdd(cycle, Register.X, instruction.value!!.toLong())
}
}
}
}
typealias RegisterState = MutableMap<Register, Long>
fun main() = Day10().solve()
| 0 | Kotlin | 0 | 0 | ddad8456dc697c0ca67255a26c34c1a004ac5039 | 4,388 | advent-of-code-2022 | MIT License |
src/Day09.kt | laricchia | 434,141,174 | false | {"Kotlin": 38143} | import org.jetbrains.kotlinx.multik.api.toNDArray
import org.jetbrains.kotlinx.multik.ndarray.data.D2Array
import org.jetbrains.kotlinx.multik.ndarray.data.get
fun firstPart09(list : List<List<Int>>) {
val caveHeatMap = list.toNDArray()
val rows = caveHeatMap.shape[0]
val cols = caveHeatMap.shape[1]
val minPoints = mutableListOf<Int>()
for (i in 0 until rows) {
for (j in 0 until cols) {
val toConsider = caveHeatMap[i, j]
val neighbours = mutableSetOf<Int>()
if (i > 0) { neighbours.add(caveHeatMap[(i - 1), j]) }
if ((i) < (rows - 1)) { neighbours.add(caveHeatMap[(i + 1), j]) }
if (j > 0) { neighbours.add(caveHeatMap[i, (j - 1)]) }
if ((j) < (cols - 1)) { neighbours.add(caveHeatMap[i, (j + 1)]) }
if (toConsider < neighbours.minOf { it }) minPoints.add(toConsider)
// println("To consider (${i+1}, ${j+1}): ${caveHeatMap[i, j]} - close points: $neighbours")
}
}
// println(minPoints)
println(minPoints.sumOf { it + 1 })
}
fun secondPart09(list : List<List<Int>>) {
val caveHeatMap = list.toNDArray()
val rows = caveHeatMap.shape[0]
val cols = caveHeatMap.shape[1]
val minPoints = mutableListOf<Pair<CaveCoordinates, Int>>()
for (i in 0 until rows) {
for (j in 0 until cols) {
val toConsider = caveHeatMap[i, j]
val neighbours = caveHeatMap.getNeighbours(CaveCoordinates(i, j))
if (toConsider < neighbours.minOf { it.second }) minPoints.add(CaveCoordinates(i, j) to toConsider)
}
}
// println(minPoints)
val result = minPoints.map { getBasinSize(caveHeatMap, mutableSetOf(), mutableListOf(it)) }
println(result.map { it.size }.sortedDescending().take(3).reduce { acc, i -> acc * i })
}
fun main() {
val input : List<String> = readInput("Day09")
val list = input.filter { it.isNotBlank() }.map { it.split("").filter { it.isNotEmpty() }.map { it.toInt() } }
firstPart09(list)
secondPart09(list)
}
data class CaveCoordinates(val x : Int, val y : Int) {
override fun toString(): String { return "(x: $y , y: $x)" }
}
fun D2Array<Int>.getNeighbours(coord : CaveCoordinates) : MutableSet<Pair<CaveCoordinates, Int>> {
val rows = shape[0]
val cols = shape[1]
val i = coord.x
val j = coord.y
val neighbours = mutableSetOf<Pair<CaveCoordinates, Int>>()
if (i > 0) { neighbours.add(CaveCoordinates(i - 1, j) to this[(i - 1), j]) }
if (i < (rows - 1)) { neighbours.add(CaveCoordinates(i + 1, j) to this[(i + 1), j]) }
if (j > 0) { neighbours.add(CaveCoordinates(i, j - 1) to this[i, (j - 1)]) }
if (j < (cols - 1)) { neighbours.add(CaveCoordinates(i, j + 1) to this[i, (j + 1)]) }
return neighbours
}
tailrec fun getBasinSize(
caveMap: D2Array<Int>,
alreadyExplored: MutableSet<CaveCoordinates> = mutableSetOf(),
nextToCheck : MutableList<Pair<CaveCoordinates, Int>>,
) : MutableSet<CaveCoordinates> {
val next = nextToCheck.removeFirstOrNull()
return if (next == null) alreadyExplored
else {
alreadyExplored.add(next.first)
val neighbours = caveMap.getNeighbours(next.first)
nextToCheck.addAll(neighbours.filter { it.second < 9 }.filterNot { it.first in alreadyExplored })
getBasinSize(caveMap, alreadyExplored, nextToCheck)
}
}
| 0 | Kotlin | 0 | 0 | 7041d15fafa7256628df5c52fea2a137bdc60727 | 3,397 | Advent_of_Code_2021_Kotlin | Apache License 2.0 |
src/day01/Puzzle1.kt | tmikulsk1 | 573,165,106 | false | {"Kotlin": 25281} | package day01
import readInput
/**
* Advent of Code 2022
* Day 1 / Puzzle 1
* @author tmikulsk1
*
* 1st read input values
* 2nd separate calories carried per elf
* 3rd separate and convert calories per elf
* p1: sum total amount of calories per elf
* p2: show top three calories sum
* final: print answers
*/
const val INPUT_FILE_NAME = "day01/input.txt"
fun main() {
val caloriesPerElf = getCaloriesPerElv()
/* puzzle 1 answer */
val maxCalorie = getMaximumCalorieCarried(caloriesPerElf)
/* puzzle 2 answer */
val topThreeCaloriesSum = caloriesPerElf.getTotalCaloriesCarriedByElves(untilValue = 3)
/* final: print answers */
println("Maximum calorie carried: $maxCalorie")
println("Top three calories sum: $topThreeCaloriesSum")
}
/* p1: sum total amount of calories per elf*/
fun getMaximumCalorieCarried(calories: List<Int>) = calories.max()
/* p2: show top three calories sum */
fun List<Int>.getTotalCaloriesCarriedByElves(untilValue: Int) =
sortedDescending().subList(0, untilValue).sum()
fun getCaloriesPerElv(): List<Int> {
/* 1st read input values */
val elvesCaloriesInput: String = readInput(INPUT_FILE_NAME).readText()
/* 2nd separate calories carried per elf */
val elvesCalories = elvesCaloriesInput.split("\n\n")
/* 3rd separate and convert calories per elf [and] 4th sum total amount of calories per elf */
return elvesCalories.map { calorie ->
return@map calorie.split("\n").map(String::toInt)
}.map(List<Int>::sum)
}
| 0 | Kotlin | 0 | 1 | f5ad4e601776de24f9a118a0549ac38c63876dbe | 1,531 | AoC-22 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day09.kt | codelicia | 627,407,402 | false | {"Kotlin": 49578, "PHP": 554, "Makefile": 293} | package com.codelicia.advent2021
import java.util.Stack
class Day09(private val input: List<String>) {
private fun parseHeightmap(xs: List<String>): List<List<Int>> =
xs.map { it.toCharArray().map(Char::digitToInt) }
private fun <T> List<List<T>>.getLocation(p: Pair<Int, Int>): T? =
this.getOrNull(p.first)?.getOrNull(p.second)
private fun Pair<Int, Int>.adjacentLocations() =
listOf(
this.first - 1 to this.second,
this.first + 1 to this.second,
this.first to this.second + 1,
this.first to this.second - 1
)
private fun Stack<Int>.riskLevel(): Int =
this.size + this.sum()
fun part1(): Int {
val heightmap = parseHeightmap(input)
val lowPoints = Stack<Int>()
heightmap.forEachIndexed { y, row ->
row.forEachIndexed { x, cell ->
var currentCellIsLower = true
for (adjacent in (y to x).adjacentLocations()) {
val adjacentCell = heightmap.getLocation(adjacent)
if (adjacentCell != null && adjacentCell <= cell) currentCellIsLower = false
}
if (currentCellIsLower) lowPoints.add(cell)
}
}
return lowPoints.riskLevel()
}
fun part2(): Int {
val heightmap = parseHeightmap(input)
val basins = mutableListOf<MutableList<Int>>()
heightmap.forEachIndexed { y, row ->
row.forEachIndexed { x, cell ->
var currentCellIsLower = true
for (adjacent in (y to x).adjacentLocations()) {
val adjacentCell = heightmap.getLocation(adjacent)
if (adjacentCell != null && adjacentCell < cell) currentCellIsLower = false
}
if (currentCellIsLower) {
basins.add(findSmallerFrom(heightmap, y to x, mutableSetOf())!!)
}
}
}
return basins.map { it.size }.sortedDescending().take(3).reduce {
x, y -> x * y
}
}
private fun findSmallerFrom(heightmap: List<List<Int>>, p: Pair<Int, Int>, visited: MutableSet<Pair<Int, Int>>): MutableList<Int>? {
val cell = heightmap.getLocation(p) ?: return null
val lowPoints = mutableListOf<Int>()
lowPoints.add(cell)
visited.add(p)
for (adjacent in p.adjacentLocations()) {
val adjacentCell = heightmap.getLocation(adjacent)
if (adjacentCell != null && adjacentCell > cell && adjacentCell != 9 && false == visited.contains(adjacent)) {
val x = findSmallerFrom(heightmap, adjacent, visited)
if (x != null) {
lowPoints.addAll(x)
}
}
}
return lowPoints
}
} | 2 | Kotlin | 0 | 0 | df0cfd5c559d9726663412c0dec52dbfd5fa54b0 | 2,865 | adventofcode | MIT License |
src/main/kotlin/com/rtarita/days/Day7.kt | RaphaelTarita | 570,100,357 | false | {"Kotlin": 79822} | package com.rtarita.days
import com.rtarita.structure.AoCDay
import com.rtarita.util.day
import kotlinx.datetime.LocalDate
object Day7 : AoCDay {
private sealed class TreeNode {
abstract val parent: IntermediateNode?
abstract val size: Int
fun root(): IntermediateNode {
var current = parent ?: return this as IntermediateNode
while (current.parent != null) {
current = current.parent!!
}
return current
}
}
private class IntermediateNode(override val parent: IntermediateNode?) : TreeNode() {
private val children: MutableMap<String, TreeNode> = mutableMapOf()
fun children(): Map<String, TreeNode> = children
fun intermediate(name: String): IntermediateNode {
return children.getOrPut(name) { IntermediateNode(this) } as IntermediateNode
}
fun leaf(name: String, size: Int): LeafNode {
return children.getOrPut(name) { LeafNode(this, size) } as LeafNode
}
override val size
get() = children.values.sumOf { it.size }
}
private class LeafNode(override val parent: IntermediateNode?, override val size: Int) : TreeNode()
override val day: LocalDate = day(7)
private tailrec fun scanTree(currentNode: IntermediateNode, current: String, lines: List<String>) {
when (current[2]) {
'c' -> {
val next = lines.getOrNull(0) ?: return
val newLines = lines.subList(1, lines.size)
when (val dirname = current.substring(5).trimEnd()) {
".." -> scanTree(currentNode.parent!!, next, newLines)
"/" -> scanTree(currentNode.root(), next, newLines)
else -> scanTree(currentNode.intermediate(dirname), next, newLines)
}
}
'l' -> {
val offset = lines.indexOfFirst { it.startsWith('$') }.let { if (it == -1) lines.size else it }
for (line in lines.subList(0, offset)) {
val (sizeOrDir, name) = line.split(' ')
if (sizeOrDir == "dir") {
currentNode.intermediate(name)
} else {
currentNode.leaf(name, sizeOrDir.toInt())
}
}
if (offset == lines.size) return
scanTree(currentNode, lines[offset], lines.subList(offset + 1, lines.size))
}
}
}
private fun getTree(input: String): IntermediateNode {
val tree = IntermediateNode(null)
val lines = input.lines()
scanTree(tree, lines[0], lines.subList(1, lines.size))
return tree
}
private fun IntermediateNode.dirSizesBelow(): Int {
val ownSize = size.let { if (it <= 100_000) it else 0 }
return ownSize + children().values.sumOf {
when (it) {
is LeafNode -> 0
is IntermediateNode -> it.dirSizesBelow()
}
}
}
private fun IntermediateNode.findSmallestAbove(threshold: Int): Int {
if (size < threshold) return Int.MAX_VALUE
val childMin = children().values.minOf {
when (it) {
is LeafNode -> Int.MAX_VALUE
is IntermediateNode -> if (it.size < threshold) Int.MAX_VALUE else it.findSmallestAbove(threshold)
}
}
return if (childMin == Int.MAX_VALUE) size else childMin
}
override fun executePart1(input: String): Int {
return getTree(input).dirSizesBelow()
}
override fun executePart2(input: String): Int {
val tree = getTree(input)
val target = 30_000_000 - (70_000_000 - tree.size)
return tree.findSmallestAbove(target)
}
} | 0 | Kotlin | 0 | 9 | 491923041fc7051f289775ac62ceadf50e2f0fbe | 3,845 | AoC-2022 | Apache License 2.0 |
src/Day13/Day13.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day13
import readInput
import java.util.PriorityQueue
import kotlin.math.*
class Index(var index: Int = 0)
fun main() {
fun processInput(input: List<String>): List<List<String>> {
return input
.withIndex()
.groupBy { it.index / 3 }
.map { it.value.map { it.value }.dropLast(1) }
}
fun processSignal(input: String, index: Index) : List<Any> {
var list = mutableListOf<Any>()
while(index.index < input.count()) {
var char = input[index.index]
index.index++
when (char) {
'[' -> list.add(processSignal(input, index))
',' -> continue
']' -> return list
else -> {
val startIndex = index.index - 1
while(input[index.index].isDigit()) {
index.index++
}
list.add(input.subSequence(startIndex, index.index).toString().toInt())
}
}
}
return list
}
fun processPair(input: List<String>): Pair<List<Any>, List<Any>> {
return Pair(processSignal(input[0], Index()), processSignal(input[1], Index()))
}
fun isPairInRightOrderHelper(left: List<Any>, right: List<Any>): Boolean? {
for (i in 0 until min(left.size, right.size)) {
if (left[i] is Int && right[i] is Int) {
val leftInt = left[i] as Int
val rightInt = right[i] as Int
if(leftInt < rightInt) return true
if (leftInt > rightInt) return false
}
else if(left[i] is List<*> && right[i] is List<*>) {
val arrayResult = isPairInRightOrderHelper(left[i] as List<Any>, right[i] as List<Any>)
if (arrayResult != null) return arrayResult
}
else if(left[i] is Int) {
if(!(right[i] is List<*>)) print("SOMETHING WENT VERY WRONG")
val arrayResult = isPairInRightOrderHelper(listOf(left[i]), right[i] as List<Any>)
if (arrayResult != null) return arrayResult
}
else if(right[i] is Int) {
if(!(left[i] is List<*>)) print("SOMETHING WENT VERY WRONG")
val arrayResult = isPairInRightOrderHelper(left[i] as List<Any>, listOf(right[i]))
if (arrayResult != null) return arrayResult
} else {
print("SOMETHING WENT VERY WRONG")
}
}
if(left.size < right.size) {
return true
} else if (left.size > right.size) {
return false
}
return null
}
fun isPairInRightOrder(pair: Pair<List<Any>, List<Any>>): Boolean {
return isPairInRightOrderHelper(pair.first, pair.second)!!
}
val myCustomComparator = Comparator<List<Any>> { a, b ->
val result = isPairInRightOrderHelper(a, b)
if(result == null) 0
else if (result) 1
else -1
}
fun part1(input: List<String>): Int {
val pairStrings = processInput(input)
val pairs = pairStrings.map { processPair(it) }
return pairs.withIndex().sumOf { if (isPairInRightOrder(it.value)) it.index + 1 else 0 }
}
fun part2(input: List<String>): Int {
var signals = input.filter { !it.isEmpty() }.map { processSignal(it, Index()) }.toMutableList()
signals.add(listOf(listOf(2)))
signals.add(listOf(listOf(6)))
val sortedSignals = signals.sortedWith(myCustomComparator).reversed()
val result = sortedSignals.withIndex().filter { !(it.value is ArrayList<*>) }
return (result[0].index + 1) * (result[1].index + 1)
}
val testInput = readInput("Day13","Day13_test")
println(part1(testInput))
check(part1(testInput) == 13)
println(part2(testInput))
check(part2(testInput) == 140)
val input = readInput("Day13","Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 4,045 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} | fun main() { // ktlint-disable filename
fun part1(input: List<String>): Long {
var registerX = 1
val signalStrengths = mutableListOf<Long>()
var cycle = 1
fun checkCycleStrengths(startCheckCycle: Int = 20, cycleCheckPoint: Int = 40) {
if ((cycle - startCheckCycle).rem(cycleCheckPoint) == 0) {
// println("Cycle:$cycle X:$registerX")
signalStrengths.add(cycle * registerX.toLong())
}
}
input.forEach { line ->
val tokens = line.split(" ")
when (tokens[0]) {
"addx" -> {
cycle++
checkCycleStrengths()
registerX += tokens[1].toInt()
cycle++
checkCycleStrengths()
}
"noop" -> {
cycle++
checkCycleStrengths()
}
}
}
return signalStrengths.sum()
}
fun part2(input: List<String>): List<String> {
var registerX = 1
var cycle = 1
val crtLine = StringBuilder()
val crtOutput = mutableListOf<String>()
val cyclesPerLine = 40
fun addCrtPoint() {
val xPos = (cycle - 1).rem(cyclesPerLine)
crtLine.append(
if (xPos >= registerX - 1 && xPos <= registerX + 1) '⚪' else '⚫'
)
if (xPos == cyclesPerLine - 1) {
crtOutput.add(crtLine.toString())
crtLine.clear()
}
}
input.forEach { line ->
val tokens = line.split(" ")
when (tokens[0]) {
"addx" -> {
addCrtPoint()
cycle++
addCrtPoint()
cycle++
registerX += tokens[1].toInt()
}
"noop" -> {
addCrtPoint()
cycle++
}
}
}
return crtOutput
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
println("Test sum of signal strengths: ${part1(testInput)}")
check(part1(testInput) == 13140L)
println("Test CRT output:\n${part2(testInput).joinToString("\n")}")
// check(part2(testInput) == 1)
val input = readInput("Day10_input")
println("Sum of signal strengths: ${part1(input)}")
println("CRT output:\n${part2(input).joinToString("\n")}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 2,572 | KotlinAdventOfCode2022 | Apache License 2.0 |
LeetCode/0416. Partition Equal Subset Sum/Soution.kt | InnoFang | 86,413,001 | false | {"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410} | /**
* Created by <NAME> on 2017/12/9.
*/
class Solution {
private val memo = MutableList<MutableList<Int>>(0) { MutableList<Int>(0) { 0 } }
fun canPartition(nums: IntArray): Boolean {
if (nums.isEmpty() || nums.sum() and 1 == 1) return false
val par = nums.sum() shr 1
memo.addAll(MutableList(nums.size) { MutableList(par + 1) { -1 } })
return tryPartition(nums, nums.size - 1, par)
}
private fun tryPartition(nums: IntArray, index: Int, sum: Int): Boolean {
if (sum == 0)
return true
if (sum < 0 || index < 0)
return false
if (memo[index][sum] != -1)
return memo[index][sum] == 1
memo[index][sum] = if (tryPartition(nums, index - 1, sum)
|| tryPartition(nums, index - 1, sum - nums[index])) 1 else 0
return memo[index][sum] == 1
}
}
class Solution2 {
fun canPartition(nums: IntArray): Boolean {
if (nums.isEmpty() || nums.sum() and 1 == 1) return false
val par = nums.sum() shr 1
val dp = MutableList(par + 1) { false }
(0..par).forEach {
dp[it] = (nums[0] == it)
}
(1 until nums.size).forEach { i ->
(par downTo nums[i]).forEach { j ->
dp[j] = dp[j] || dp[j - nums[i]]
}
}
return dp[par]
}
}
class Solution3 {
fun canPartition(nums: IntArray): Boolean {
if (nums.isEmpty() || nums.sum() and 1 == 1) return false
val par = nums.sum() shr 1
val dp = MutableList(nums.size) { MutableList(par + 1) { false } }
(0 until nums.size).forEach { i ->
(0..par).forEach { j ->
if (i < 1) dp[i][j] = (j == nums[i])
else dp[i][j] = dp[i - 1][j] || if (nums[i] <= j) dp[i - 1][j - nums[i]] else false
}
}
return dp[nums.size - 1][par]
}
}
class Solution4 {
fun canPartition(nums: IntArray): Boolean {
if (nums.isEmpty() || nums.sum() and 1 == 1) return false
val par = nums.sum() shr 1
val dp = MutableList(2) { MutableList(par + 1) { false } }
(0..par).forEach {
dp[0][it] = (nums[0] == it)
}
(1 until nums.size).forEach { i ->
(0..par).forEach { j ->
dp[i and 1][j] = dp[(i - 1) and 1][j] || if (nums[i] <= j) dp[(i - 1) and 1][j - nums[i]] else false
}
}
return dp[(nums.size - 1) and 1][par]
}
}
class Solution5 {
fun canPartition(nums: IntArray): Boolean {
if (nums.isEmpty() || nums.sum() and 1 == 1) return false
val par = nums.sum() shr 1
val dp = MutableList(par + 1) { false }
(0..par).forEach { dp[it] = (nums[0] == it) }
(1 until nums.size).forEach { i ->
(par downTo nums[i]).forEach { j ->
dp[j] = dp[j] || dp[j - nums[i]]
}
}
return dp[par]
}
}
fun main(args: Array<String>) {
val solution = Solution5()
solution.canPartition(intArrayOf(1, 5, 11, 5)).let(::println)
solution.canPartition(intArrayOf(1, 2, 2, 5)).let(::println)
solution.canPartition(intArrayOf(2, 2, 3, 5)).let(::println)
}
// 322. Coin Change | 0 | C++ | 8 | 20 | 2419a7d720bea1fd6ff3b75c38342a0ace18b205 | 3,266 | algo-set | Apache License 2.0 |
codeforces/polynomial2022/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.polynomial2022
import java.lang.StringBuilder
private fun solve() {
val (hei, wid) = readInts()
val a = List(hei) { readInts() }
val aSum = a.map { it.sum() }.toIntArray()
val totalOnes = aSum.sum()
if (totalOnes % hei != 0) return println(-1)
val needOnes = totalOnes / hei
val ans = StringBuilder()
val donors = IntArray(hei)
val acceptors = IntArray(hei)
var ops = 0
for (x in 0 until wid) {
var donorsCount = 0
var acceptorsCount = 0
for (y in 0 until hei) {
if (aSum[y] == needOnes) continue
if (aSum[y] > needOnes && a[y][x] == 1) {
donors[donorsCount++] = y
}
if (aSum[y] < needOnes && a[y][x] == 0) {
acceptors[acceptorsCount++] = y
}
}
for (i in 0 until minOf(donorsCount, acceptorsCount)) {
aSum[donors[i]]--
aSum[acceptors[i]]++
ans.append("${donors[i] + 1} ${acceptors[i] + 1} ${x + 1}\n")
ops++
}
}
println(ops)
print(ans)
}
fun main() = repeat(readInt()) { solve() }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,112 | competitions | The Unlicense |
src/main/kotlin/day13/Day13.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package day13
fun solveA(input: List<String>): Int {
val pairs =
input.chunked(3).map { signal ->
Pair(Packet(signal[0]).also { it.initialize() },
Packet(signal[1]).also { it.initialize() })
}
val result = pairs.mapIndexedNotNull { index, it ->
if (it.first.compareTo(it.second) == 1) index + 1
else null
}
return result.sum()
}
data class Packet(val input: String) : Comparable<Packet> {
private val indexIsPacket = mutableListOf<Boolean>()
private val packets = mutableListOf<Packet>()
private val content = mutableListOf<Int>()
private var current = -1
private fun getNext(): Any? {
current++
if (current >= indexIsPacket.size) return null
return if (indexIsPacket[current]) packets.removeFirstOrNull()
else content.removeFirstOrNull()
}
fun initialize() {
val inner = input.drop(1).dropLast(1)
val openIndices = mutableListOf<Int>()
val closeIndices = mutableListOf<Int>()
for (i in inner.indices) {
if (inner[i] == '[') openIndices.add(i)
else if (inner[i] == ']') {
if (openIndices.count() == closeIndices.count() + 1) {
val openIndex = openIndices.removeFirst()
indexIsPacket.add(true)
packets.add(Packet(inner.substring(openIndex, i + 1)).also { it.initialize() })
} else closeIndices.add(i)
} else if (openIndices.count() == closeIndices.count() && inner[i] != ',') {
indexIsPacket.add(false)
val digitString = inner.drop(i).takeWhile { it.isDigit() }
if (digitString.isNotBlank()) content.add(digitString.toInt())
}
}
}
override fun compareTo(other: Packet): Int {
val thisCopy = Packet(this.input).also { it.initialize() }
val otherCopy = Packet(other.input).also { it.initialize() }
while (true) {
val p1 = thisCopy.getNext()
val p2 = otherCopy.getNext()
if (p1 == null && p2 != null) return 1
if (p1 != null && p2 == null) return -1
if (p1 == null) return 0
if (p1 is Int && p2 is Int) {
if (p1 < p2) return 1
if (p1 > p2) return -1
}
if (p1 is Packet && p2 is Packet) {
val innerResult = p1.compareTo(p2)
if (innerResult != 0) return innerResult
}
if (p1 is Packet && p2 is Int) {
val innerResult = p1.compareTo(Packet("[$p2]").also { it.initialize() })
if (innerResult != 0) return innerResult
}
if (p1 is Int && p2 is Packet) {
val innerResult = Packet("[$p1]").also { it.initialize() }.compareTo(p2)
if (innerResult != 0) return innerResult
}
}
}
}
fun solveB(input: List<String>): Int {
val pairs =
input.mapNotNull { signal ->
if (signal.isNotBlank()) Packet(signal).also { it.initialize() }
else null
}.toMutableList()
val firstDivider = Packet("[[2]]").also { it.initialize() }
val secondDivider = Packet("[[6]]").also { it.initialize() }
pairs.addAll(listOf(firstDivider, secondDivider))
val sorted = pairs.sortedWith(compareBy<Packet> { it }.reversed().thenBy { it.input.length })
return (sorted.indexOf(firstDivider) + 1) * (sorted.indexOf(secondDivider) + 1)
} | 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 3,565 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumGap.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.DECIMAL
/**
* Maximum Gap
* @see <a href="https://leetcode.com/problems/maximum-gap/">Source</a>
*/
fun interface MaximumGap {
operator fun invoke(nums: IntArray): Int
}
/**
* Approach 1: Comparison Sorting
* Time complexity: O(n log n)
* Space complexity: No extra space needed, other than the input array (since sorting can usually be done in-place).
*/
class MaximumGapComparisonSorting : MaximumGap {
override operator fun invoke(nums: IntArray): Int {
if (nums.isEmpty() || nums.size < 2) {
return 0
}
nums.sort()
var maxGap = 0
for (i in 0 until nums.size - 1) {
maxGap = kotlin.math.max(nums[i + 1] - nums[i], maxGap)
}
return maxGap
}
}
/**
* Approach 2: Radix Sort
* Time complexity: O(n)O(d⋅(n+k))≈O(n).
* Space complexity: O(n)O(n+k)≈O(n) extra space.
*/
class MaximumGapRadixSort : MaximumGap {
override operator fun invoke(nums: IntArray): Int {
if (nums.isEmpty() || nums.size < 2) {
return 0
}
val maxVal = nums.maxOrNull() ?: 0
var exp = 1
val aux = IntArray(nums.size)
while (maxVal / exp > 0) {
val count = IntArray(RADIX)
for (i in nums.indices) {
count[nums[i].div(exp) % DECIMAL]++
}
for (i in 1 until count.size) {
count[i] += count[i - 1]
}
for (i in nums.size - 1 downTo 0) {
aux[--count[nums[i].div(exp) % DECIMAL]] = nums[i]
}
for (i in nums.indices) {
nums[i] = aux[i]
}
exp *= DECIMAL
}
var maxGap = 0
for (i in 0 until nums.size - 1) {
maxGap = kotlin.math.max(nums[i + 1] - nums[i], maxGap)
}
return maxGap
}
companion object {
private const val RADIX = 10
}
}
/**
* Approach 3: Buckets and The Pigeonhole Principle
*/
class MaximumGapBuckets : MaximumGap {
override operator fun invoke(nums: IntArray): Int {
if (nums.isEmpty() || nums.size < 2) {
return 0
}
val mini = nums.minOrNull() ?: 0
val maxi = nums.maxOrNull() ?: 0
val bucketSize = kotlin.math.max(1, (maxi - mini) / (nums.size - 1))
val bucketNum = (maxi - mini) / bucketSize + 1
val buckets = Array(bucketNum) { Bucket() }
for (num in nums) {
val bucketIdx = (num - mini) / bucketSize
buckets[bucketIdx].used = true
buckets[bucketIdx].minVal = kotlin.math.min(num, buckets[bucketIdx].minVal)
buckets[bucketIdx].maxVal = kotlin.math.max(num, buckets[bucketIdx].maxVal)
}
var prevBucketMax = mini
var maxGap = 0
for (bucket in buckets) {
if (!bucket.used) {
continue
}
maxGap = kotlin.math.max(maxGap, bucket.minVal - prevBucketMax)
prevBucketMax = bucket.maxVal
}
return maxGap
}
private data class Bucket(
var used: Boolean = false,
var maxVal: Int = Int.MIN_VALUE,
var minVal: Int = Int.MAX_VALUE,
)
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,889 | kotlab | Apache License 2.0 |
src/day05/Code.kt | ldickmanns | 572,675,185 | false | {"Kotlin": 48227} | package day05
import readInput
fun main() {
val input = readInput("day05/input")
// val input = readInput("day05/input_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): String {
val separatorLine = input.indexOfFirst { it.isEmpty() }
val startConfiguration = input.slice(0 until separatorLine).dropLast(1)
val instructions = input.slice((separatorLine + 1) until input.size)
val configuration = extractStartConfiguration(startConfiguration)
configuration.carryOutInstructions(instructions)
return buildString {
configuration.forEach { append(it.last()) }
}
}
fun extractStartConfiguration(input: List<String>): Array<ArrayDeque<Char>> {
val size = input.maxOf { getPositionRange(it).toList().size }
val configuration = Array(size) { ArrayDeque<Char>() }
input.forEach { line ->
val range = getPositionRange(line)
range.forEachIndexed { index, position ->
val char = line[position]
if (char == ' ') return@forEachIndexed
configuration[index].addFirst(char)
}
}
return configuration
}
fun getPositionRange(line: String) = 1 until line.length step 4
fun Array<ArrayDeque<Char>>.carryOutInstructions(
instructions: List<String>
) = instructions.forEach { instruction ->
val split = instruction.split(" ")
val amount = split[1].toInt()
val from = split[3].toInt() - 1
val to = split[5].toInt() - 1
repeat(amount) {
val item = this[from].removeLast()
this[to].addLast(item)
}
}
fun part2(input: List<String>): String {
val separatorLine = input.indexOfFirst { it.isEmpty() }
val startConfiguration = input.slice(0 until separatorLine).dropLast(1)
val instructions = input.slice((separatorLine + 1) until input.size)
val configuration = extractStartConfiguration(startConfiguration)
configuration.carryOutInstructionsWith9001(instructions)
return buildString {
configuration.forEach { append(it.last()) }
}
}
fun Array<ArrayDeque<Char>>.carryOutInstructionsWith9001(
instructions: List<String>
) = instructions.forEach { instruction ->
val split = instruction.split(" ")
val amount = split[1].toInt()
val from = split[3].toInt() - 1
val to = split[5].toInt() - 1
val tmp = ArrayDeque<Char>()
repeat(amount) {
val item = this[from].removeLast()
tmp.addFirst(item)
}
tmp.forEach { this[to].addLast(it) }
}
| 0 | Kotlin | 0 | 0 | 2654ca36ee6e5442a4235868db8174a2b0ac2523 | 2,516 | aoc-kotlin-2022 | Apache License 2.0 |
src/day6/puzzle06.kt | brendencapps | 572,821,792 | false | {"Kotlin": 70597} | package day6
import Puzzle
import PuzzleInput
import java.io.File
class Day6PuzzleInput(private val input: String, val numMarkers: Int, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) {
fun getPuzzleInput(): String {
val puzzleInput = File(input).readText()
check(puzzleInput.length >= numMarkers)
return puzzleInput
}
}
class Day6PuzzleSolutionMutableSet : Puzzle<Int, Day6PuzzleInput>() {
override fun solution(input: Day6PuzzleInput): Int {
val message = input.getPuzzleInput()
val code = mutableSetOf<Char>()
for (i in message.indices) {
if (code.contains(message[i])) {
val it = code.iterator()
while (it.hasNext()) {
if (it.next() == message[i]) {
it.remove()
break
}
it.remove()
}
}
code.add(message[i])
if (code.size == input.numMarkers) {
return i + 1
}
}
error("Did not find start of stream")
}
}
class Day6PuzzleSolutionArray : Puzzle<Int, Day6PuzzleInput>() {
override fun solution(input: Day6PuzzleInput): Int {
val message = input.getPuzzleInput()
val code2 = CharArray(input.numMarkers)
var end = 0
var start = 0
for (i in message.indices) {
for(j in start until end) {
if(message[i] == code2[j % input.numMarkers]) {
start = j + 1
break
}
}
code2[end % input.numMarkers] = message[i]
end++
if(end - start == input.numMarkers) {
return end
}
}
error("Did not find start of stream")
}
}
fun day6Puzzle() {
val solutions = listOf(Day6PuzzleSolutionMutableSet(), Day6PuzzleSolutionArray())
val inputs = listOf(
Day6PuzzleInput("inputs/day6/example.txt", 4, 7),
Day6PuzzleInput("inputs/day6/example2.txt", 4, 5),
Day6PuzzleInput("inputs/day6/example3.txt", 4, 6),
Day6PuzzleInput("inputs/day6/example4.txt", 4, 10),
Day6PuzzleInput("inputs/day6/example5.txt", 4, 11),
Day6PuzzleInput("inputs/day6/input.txt", 4, 1760),
Day6PuzzleInput("inputs/day6/example.txt", 14, 19),
Day6PuzzleInput("inputs/day6/example2.txt", 14, 23),
Day6PuzzleInput("inputs/day6/example3.txt", 14, 23),
Day6PuzzleInput("inputs/day6/example4.txt", 14, 29),
Day6PuzzleInput("inputs/day6/example5.txt", 14, 26),
Day6PuzzleInput("inputs/day6/input.txt", 14, 2974)
)
for(solution in solutions) {
for(input in inputs) {
solution.solve(input)
}
}
}
| 0 | Kotlin | 0 | 0 | 00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3 | 2,919 | aoc_2022 | Apache License 2.0 |
src/main/kotlin/day13/Day13.kt | limelier | 725,979,709 | false | {"Kotlin": 48112} | package day13
import common.InputReader
import common.split
private fun List<String>.checkMirroredHorizontal(rowsBefore: Int): Boolean {
for (row in rowsBefore..<this.size) {
val rowMir = rowsBefore * 2 - row - 1
if (rowMir !in indices) break
if (this[row] != this[rowMir]) return false
}
return true
}
private fun List<String>.checkMirroredHorizontalWithSmudge(rowsBefore: Int): Boolean {
var smudge = false
for (row in rowsBefore..<this.size) {
val rowMir = rowsBefore * 2 - row - 1
if (rowMir !in indices) break
for (col in this[row].indices) {
if (this[row][col] != this[rowMir][col]) {
if (!smudge) {
smudge = true
} else {
return false
}
}
}
}
return smudge
}
private fun List<String>.transpose(): List<String> = this[0].indices.map { c -> this.map { it[c] }.joinToString() }
public fun main() {
val lines = InputReader("day13/input.txt").lines()
val patterns = lines.split("")
val sum1 = patterns.sumOf { pattern ->
val rowsBeforeMirror = (1..<pattern.size).firstOrNull { pattern.checkMirroredHorizontal(it) }
val transposed = pattern.transpose()
val colsBeforeMirror = (1..<transposed.size).firstOrNull { transposed.checkMirroredHorizontal(it) }
colsBeforeMirror ?: (rowsBeforeMirror!! * 100)
}
println("Part 1: $sum1")
val sum2 = patterns.sumOf { pattern ->
val rowsBeforeMirror = (1..<pattern.size).firstOrNull { pattern.checkMirroredHorizontalWithSmudge(it) }
val transposed = pattern.transpose()
val colsBeforeMirror = (1..<transposed.size).firstOrNull { transposed.checkMirroredHorizontalWithSmudge(it) }
colsBeforeMirror ?: (rowsBeforeMirror!! * 100)
}
println("Part 2: $sum2")
} | 0 | Kotlin | 0 | 0 | 0edcde7c96440b0a59e23ec25677f44ae2cfd20c | 1,895 | advent-of-code-2023-kotlin | MIT License |
src/Day23.kt | sabercon | 648,989,596 | false | null | fun main() {
fun move(current: Int, linkMap: MutableMap<Int, Int>): Int {
val picked = generateSequence(current) { linkMap[it]!! }
.drop(1).take(3).toList()
val destination = generateSequence(current - 1) { it - 1 }
.map { if (it < 1) linkMap.size + it else it }
.first { it !in picked }
linkMap[current] = linkMap[picked.last()]!!
linkMap[picked.last()] = linkMap[destination]!!
linkMap[destination] = picked.first()
return linkMap[current]!!
}
fun move(cups: List<Int>, times: Int): Map<Int, Int> {
val linkMap = cups.zipWithNext().toMap(mutableMapOf())
linkMap[cups.last()] = cups.first()
var current = cups.first()
repeat(times) { current = move(current, linkMap) }
return linkMap
}
val input = readText("Day23").map { it.digitToInt() }
move(input, 100)
.let { map -> generateSequence(map[1]!!) { map[it]!! } }
.takeWhile { it != 1 }
.joinToString("")
.println()
move(input + (input.size + 1..1_000_000), 10_000_000)
.let { 1L * it[1]!! * it[it[1]!!]!! }
.println()
}
| 0 | Kotlin | 0 | 0 | 81b51f3779940dde46f3811b4d8a32a5bb4534c8 | 1,177 | advent-of-code-2020 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxRunTime.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 2141. Maximum Running Time of N Computers
* @see <a href="https://leetcode.com/problems/maximum-running-time-of-n-computers/">Source</a>
*/
fun interface MaxRunTime {
operator fun invoke(n: Int, batteries: IntArray): Long
}
/**
* Approach 1: Sorting and Prefix Sum
*/
class MaxRunTimePrefixSum : MaxRunTime {
override operator fun invoke(n: Int, batteries: IntArray): Long {
// Get the sum of all extra batteries.
batteries.sort()
var extra: Long = 0
for (i in 0 until batteries.size - n) {
extra += batteries[i]
}
// live stands for the n largest batteries we chose for n computers.
val live = batteries.sliceArray(batteries.size - n until batteries.size)
// We increase the total running time using 'extra' by increasing
// the running time of the computer with the smallest battery.
for (i in 0 until n - 1) {
// If the target running time is between live[i] and live[i + 1].
if (extra < (i + 1) * (live[i + 1] - live[i]).toLong()) {
return live[i] + extra / (i + 1).toLong()
}
// Reduce 'extra' by the total power used.
extra -= (i + 1) * (live[i + 1] - live[i]).toLong()
}
// If there is power left, we can increase the running time
// of all computers.
return live[n - 1] + extra / n.toLong()
}
}
/**
* Approach 2: Binary Search
*/
class MaxRunTimeBS : MaxRunTime {
override operator fun invoke(n: Int, batteries: IntArray): Long {
var sumPower: Long = 0
for (power in batteries)
sumPower += power
var left: Long = 1
var right: Long = sumPower / n
while (left < right) {
val target: Long = right - (right - left) / 2
var extra: Long = 0
for (power in batteries)
extra += power.toLong().coerceAtMost(target)
if (extra >= n * target) {
left = target
} else {
right = target - 1
}
}
return left
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,776 | kotlab | Apache License 2.0 |
src/Day03.kt | Soykaa | 576,055,206 | false | {"Kotlin": 14045} | private fun getPriority(itemType: Char): Int = if (itemType in 'a'..'z')
itemType - 'a' + 1
else
itemType - 'A' + 27
private fun findIntersection(items: String): List<Int> {
val (fstPart, sndPart) = items.chunked(items.length / 2)
return fstPart.toSet().intersect(sndPart.toSet()).map { getPriority(it) }
}
fun main() {
fun part1(input: List<String>): Int = input.sumOf { line ->
findIntersection(line).sum()
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.sumOf {
it.map { line -> line.toSet() }
.reduce { acc, line -> acc.intersect(line) }
.sumOf { badge -> getPriority(badge) }
}
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1e30571c475da4db99e5643933c5341aa6c72c59 | 823 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | emersonf | 572,870,317 | false | {"Kotlin": 17689} | typealias Item = Char
val Item.priority: Int
get() = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> throw IllegalStateException()
}
fun main() {
fun part1(input: List<String>): Int =
input.sumOf {
val (sack1, sack2) = it.chunked(it.length / 2)
// n^2 to get this working for now, let's see what the next part brings
var priority = 0
outerLoop@ for (item1 in sack1) {
for (item2 in sack2) {
if (item1 == item2) {
priority = item1.priority
break@outerLoop
}
}
}
priority
}
fun part2(input: List<String>): Int =
input.chunked(3)
.sumOf { group ->
group
.map { sack -> sack.toSet() }
.reduce { commonItems, nextSack -> commonItems intersect nextSack }
.first()
.priority
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0e97351ec1954364648ec74c557e18ccce058ae6 | 1,361 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/advent/day3/BinaryDiagnostic.kt | hofiisek | 434,171,205 | false | {"Kotlin": 51627} | package advent.day3
import advent.loadInput
import java.io.File
/**
* @author <NAME>
*/
fun part1(input: File) {
val lines = input.readLines()
val numBits = lines.firstOrNull()?.length ?: throw IllegalArgumentException("Empty input")
lines
.map { bits -> bits.map { it.digitToInt() } } // string to int array
.fold(List(numBits) { 0 }) { acc, curr ->
// sum bits on each position, positive = 1, negative = -1
curr.mapIndexed { idx, bit ->
when (bit) {
0 -> acc[idx] - 1
1 -> acc[idx] + 1
else -> throw IllegalArgumentException("Not a bit :D")
}
}
}
.let { sums ->
// convert sum back to bits, negative sum = 0, positive sum = 1
val gammaBits = sums.joinToString(separator = "") { sum -> if (sum < 0) "0" else "1" }
val epsilonBits = sums.joinToString(separator = "") { sum -> if (sum < 0) "1" else "0" }
gammaBits.toInt(2) * epsilonBits.toInt(2)
}
.also(::println)
}
fun part2(input: File) {
val lines = input.readLines().map { bits -> bits.map { it.digitToInt() } }
val numBits = lines.firstOrNull()?.size ?: throw IllegalArgumentException("Empty input")
var oxygenLines = lines
for (i in 0 until numBits) {
oxygenLines = oxygenLines
.map { it[i] }
.let { bits ->
// alternative way than in part one - no need to convert 0 to -1
val isPositiveSum = bits.sum() >= oxygenLines.size/2.0
oxygenLines.filter { if (isPositiveSum) it[i] == 1 else it[i] == 0 }
}
.also(::println)
if (oxygenLines.size == 1){
break
}
}
var co2lines = lines
for (i in 0 until numBits) {
co2lines = co2lines
.map { it[i] }
.let { bits ->
val positiveSum = bits.sum() >= co2lines.size/2.0
co2lines.filter { if (positiveSum) it[i] == 0 else it[i] == 1 }
}
.also(::println)
if (co2lines.size == 1){
break
}
}
val oxygen = oxygenLines.first().joinToString(separator = "").toInt(2)
val co2 = co2lines.first().joinToString(separator = "").toInt(2)
println(oxygen)
println(co2)
println(oxygen * co2)
}
fun main() {
with(loadInput(day = 3)) {
part1(this)
part2(this)
}
} | 0 | Kotlin | 0 | 2 | 3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb | 2,518 | Advent-of-code-2021 | MIT License |
src/main/kotlin/aoc2023/Day14.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2023
import AoCDay
// https://adventofcode.com/2023/day/14
object Day14 : AoCDay<Int>(
title = "Parabolic Reflector Dish",
part1ExampleAnswer = 136,
part1Answer = 106378,
part2ExampleAnswer = 64,
part2Answer = 90795,
) {
private fun List<String>.tiltNorth(): List<String> {
val p = map { it.toCharArray() }
for ((rowIdx, row) in p.withIndex()) {
for ((colIdx, char) in row.withIndex()) {
if (char == '.') {
val replace = ((rowIdx + 1)..<p.size)
.takeWhile { p[it][colIdx] != '#' }
.firstOrNull { p[it][colIdx] == 'O' }
if (replace != null) {
row[colIdx] = 'O'
p[replace][colIdx] = '.'
}
}
}
}
return p.map(CharArray::concatToString)
}
private fun List<String>.tiltSouth() = reversed().tiltNorth().reversed()
private fun List<String>.tiltWest() = map {
val row = it.toCharArray()
for ((index, char) in row.withIndex()) {
if (char == '.') {
val replace = ((index + 1)..<row.size)
.takeWhile { i -> row[i] != '#' }
.firstOrNull { i -> row[i] == 'O' }
if (replace != null) {
row[index] = 'O'
row[replace] = '.'
}
}
}
row.concatToString()
}
private fun List<String>.tiltEast() = map(String::reversed).tiltWest().map(String::reversed)
private fun List<String>.cycle() = tiltNorth().tiltWest().tiltSouth().tiltEast()
private val List<String>.northSupportBeamLoad
get() = reversed().withIndex().sumOf { (index, row) -> row.count('O'::equals) * (index + 1) }
override fun part1(input: String) = input.lines().tiltNorth().northSupportBeamLoad
override fun part2(input: String): Int {
val platform = input.lines()
val seen = linkedSetOf(platform)
val (duplicate, _) = generateSequence(platform.cycle()) { it.cycle() }
.map { p -> Pair(p, p in seen) }
.onEach { (p, _) -> seen.add(p) }
.first { (_, duplicate) -> duplicate }
val repetitionLength = seen.size - seen.indexOf(duplicate)
val nonRepetitionStart = seen.size - repetitionLength
val missingCycles = (1_000_000_000 - nonRepetitionStart) % repetitionLength
return generateSequence(duplicate.cycle()) { it.cycle() }.take(missingCycles).last().northSupportBeamLoad
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 2,624 | advent-of-code-kotlin | MIT License |
src/main/kotlin/Day13.kt | andrewrlee | 434,584,657 | false | {"Kotlin": 29493, "Clojure": 14117, "Shell": 398} | import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
object Day13 {
data class Coord(val x: Int, val y: Int) {
constructor(coord: Pair<Int, Int>) : this(coord.first, coord.second)
}
enum class Direction {
x {
override fun extract(c: Coord) = c.x
override fun adjust(c: Coord, value: Int) = Coord((c.x - (c.x - value) * 2) to c.y)
},
y {
override fun extract(c: Coord) = c.y
override fun adjust(c: Coord, value: Int) = Coord(c.x to (c.y - (c.y - value) * 2))
};
abstract fun extract(coord: Coord): Int
abstract fun adjust(coord: Coord, value: Int): Coord
}
private fun toCoordinates(line: String) = line
.split(",".toRegex())
.map(Integer::parseInt)
.let { Coord(it[0] to it[1]) }
private fun toInstructions(line: String): Pair<Direction, Int> {
val (axis, value) = "fold along (.)=(.+)".toRegex().find(line)!!.destructured
return Direction.valueOf(axis) to Integer.parseInt(value)
}
private fun fold(instruction: Pair<Direction, Int>, coordinates: Collection<Coord>): Set<Coord> {
val (top, bottom) = coordinates.partition { instruction.first.extract(it) > instruction.second }
val adjusted = top.map { instruction.first.adjust(it, instruction.second) }
return bottom.toMutableSet() + adjusted
}
private fun draw(coordinates: Collection<Coord>) {
println("\n")
println("Contains: ${coordinates.size}")
val maxCols = coordinates.maxOf { it.x }
val maxRows = coordinates.maxOf { it.y }
(0..maxRows).forEach { row ->
(0..maxCols).forEach { col ->
print(if (coordinates.contains(Coord(col, row))) "#" else ".")
}
println()
}
}
object Part1 {
fun run() {
val (instr, coords) = File("day13/input-real.txt")
.readLines(UTF_8)
.partition { it.startsWith("fold along") }
val coordinates = coords.filter { it.isNotBlank() }.map(::toCoordinates)
val instructions = instr.map(::toInstructions)
val first = fold(instructions.first(), coordinates)
println(first.size)
}
}
object Part2 {
fun run() {
val (instr, coords) = File("day13/input-real.txt")
.readLines(UTF_8)
.partition { it.startsWith("fold along") }
val coordinates: Collection<Coord> = coords.filter { it.isNotBlank() }.map(::toCoordinates)
val instructions = instr.map(::toInstructions)
val result = instructions.fold(coordinates) { acc, i -> fold(i, acc) }
draw(result)
// L R G P R E C B
}
}
}
fun main() {
Day13.Part1.run()
Day13.Part2.run()
}
| 0 | Kotlin | 0 | 0 | aace0fccf9bb739d57f781b0b79f2f3a5d9d038e | 2,894 | adventOfCode2021 | MIT License |
src/Day03.kt | iam-afk | 572,941,009 | false | {"Kotlin": 33272} | fun main() {
fun priority(type: Char): Int = when (type) {
in 'a'..'z' -> type - 'a' + 1
in 'A'..'Z' -> type - 'A' + 27
else -> error("unknown type '$type'")
}
fun part1(input: List<String>): Int = input.sumOf {
val first = it.substring(0, it.length / 2).toSet()
val second = it.substring(it.length / 2, it.length).toSet()
val type = (first intersect second).first()
priority(type)
}
fun part2(input: List<String>): Int = input.chunked(3).sumOf {
val type = it.map(String::toSet).reduce(Set<Char>::intersect).first()
priority(type)
}
// 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 | b30c48f7941eedd4a820d8e1ee5f83598789667b | 910 | aockt | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.