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/aoc2020/MonsterMessages.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2020 import komu.adventofcode.utils.nonEmptyLines fun monsterMessages(input: String, alterRule: (String) -> String = { it }): Int { val (rulesPart, messagesPart) = input.split("\n\n") val rule = buildRules(rulesPart.nonEmptyLines().map(alterRule)) val messages = messagesPart.nonEmptyLines() return messages.count { rule.matches(it) } } fun monsterMessages2(input: String): Int = monsterMessages(input) { when { it.startsWith("8:") -> "8: 42 | 42 8" it.startsWith("11:") -> "11: 42 31 | 42 11 31" else -> it } } private fun buildRules(rules: List<String>): Rule { val rulePattern = Regex("""(\d+): (.+)""") val ruleMap = mutableMapOf<Int, Lazy<Rule>>() ruleMap += rules.associate { s -> val (_, id, text) = rulePattern.matchEntire(s)?.groupValues ?: error("invalid rule '$s'") id.toInt() to lazy { Rule.parse(text, ruleMap) } } return ruleMap[0]!!.value } private sealed class Rule { fun matches(s: String) = accept(s).any { it == "" } protected abstract fun accept(input: String): List<String> class Literal(private val text: String) : Rule() { override fun accept(input: String) = if (input.startsWith(text)) listOf(input.removePrefix(text)) else emptyList() } class Sequence(private val rules: List<Lazy<Rule>>) : Rule() { override fun accept(input: String) = rules.fold(listOf(input)) { remaining, rule -> remaining.flatMap { rule.value.accept(it) }} } class OneOf(private val rules: List<Rule>) : Rule() { override fun accept(input: String) = rules.flatMap { it .accept(input) } } companion object { fun parse(rule: String, ruleMap: Map<Int, Lazy<Rule>>): Rule = when { rule[0] == '"' -> Literal(rule.substring(1, rule.length - 1)) '|' in rule -> OneOf(rule.split(" | ").map { parse(it, ruleMap) }) else -> Sequence(rule.split(' ').map { ruleMap[it.toInt()]!! }) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,120
advent-of-code
MIT License
advent2022/src/main/kotlin/year2022/Day05.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay private typealias Move = Triple<Int, Int, Int> data class Field(val cols: List<List<Char>>, val pickup: (List<Char>, Int) -> List<Char>): List<List<Char>> by cols { val result: String get() = cols.joinToString("") { it[0].toString() } fun makeMove(move: Move): Field { val column = this[move.second] val moved = pickup(column, move.first) val newColumn = column.drop(move.first) return copy( cols = cols.mapIndexed { index, chars -> when (index) { move.second -> newColumn move.third -> moved + cols[index] else -> chars } } ) } } private fun String.parseMove(): Move { val (a, b, c) = split(" ").mapNotNull { it.toIntOrNull() } // fixup count starts with 0 return Triple(a, b - 1, c - 1) } private fun List<String>.parseOpenField(pickup: (List<Char>, Int) -> List<Char>): Field { val size = this.last().split(" ").mapNotNull { it.toIntOrNull() }.last() - 1 val result = (0..size).map { mutableListOf<Char>() }.toMutableList() this.reversed().drop(1).map { it.chunked(4) }.forEach { it.map { str -> str.getOrNull(1) }.forEachIndexed { index, c -> if (c != null && c != ' ') { result[index] += c } } } return Field(result.map { it.reversed() }, pickup) } private fun computeInstructions(input: List<String>, pickup: (List<Char>, Int) -> List<Char>): Field { val start = input.takeWhile { it.isNotBlank() } val field = start.parseOpenField(pickup) val instructions = input.drop(start.size + 1).map { it.parseMove() } val result = instructions.fold(field) { f, m -> f.makeMove(m) } return result } class Day05 : AdventDay(2022, 5) { override fun part1(input: List<String>): String { val result = computeInstructions(input) { column, i -> column.take(i).reversed() } return result.result } override fun part2(input: List<String>): String { val result = computeInstructions(input) { column, i -> column.take(i) } return result.result } } fun main() = Day05().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
2,319
advent-of-code
Apache License 2.0
src/Day03.kt
rxptr
572,717,765
false
{"Kotlin": 9737}
fun main() { fun mapPriorities(chars: List<Char>) = chars.map { if (it.isLowerCase()) it.code - 96 else it.code - 38 } fun part1(input: List<String>): Int { val pairs = input.map { val (a, b) = it.chunked(it.length / 2) Pair(a.toSet(), b.toSet()) } val duplicates = pairs.map { (it.first intersect it.second).first() } return mapPriorities(duplicates).sum() } fun part2(input: List<String>): Int { val common = input.chunked(3) .map { it.map(CharSequence::toSet) } .map { (a, b, c) -> (a intersect b intersect c).first() } return mapPriorities(common).sum() } val testInput = readInputLines("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInputLines("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
989ae08dd20e1018ef7fe5bf121008fa1c708f09
893
aoc2022
Apache License 2.0
src/Day05.kt
BHFDev
572,832,641
false
null
fun main() { fun part1(input: List<String>): String { val separator = input.indexOf(input.find { it.isBlank() }) val crates = input.subList(0, separator - 1) val instructions = input.subList(separator + 1, input.size) val stacks = mutableListOf<ArrayDeque<Char>>() crates.forEach { it.chunked(4).mapTo(stacks) { ArrayDeque() } } crates .map { it .chunked(4) .map { it.find { it.isLetter() } } .forEachIndexed { index, crate -> if(crate != null) { stacks[index].addLast(crate) } } } instructions .map { instruction -> val groupValues = Regex("move (\\d*) from (\\d*) to (\\d*)").find(instruction)!!.groupValues groupValues .subList(1, groupValues.size) .map { it.toInt() } } .forEach { instruction -> (1..(instruction[0])).forEach {_ -> val crate = stacks[instruction[1] - 1].removeFirst() stacks[instruction[2] - 1].addFirst(crate) } } return stacks.map { if(!it.isEmpty()) it.removeFirst() else "" }.joinToString("") } fun part2(input: List<String>): String { val separator = input.indexOf(input.find { it.isBlank() }) val crates = input.subList(0, separator - 1) val instructions = input.subList(separator + 1, input.size) val stacks = mutableListOf<ArrayDeque<Char>>() crates.forEach { it.chunked(4).mapTo(stacks) { ArrayDeque() } } crates .map { it .chunked(4) .map { it.find { it.isLetter() } } .forEachIndexed { index, crate -> if(crate != null) { stacks[index].addLast(crate) } } } instructions .map { instruction -> val groupValues = Regex("move (\\d*) from (\\d*) to (\\d*)").find(instruction)!!.groupValues groupValues .subList(1, groupValues.size) .map { it.toInt() } } .forEach { instruction -> (1..(instruction[0])) .map { stacks[instruction[1] - 1].removeFirst() } .reversed() .forEach { stacks[instruction[2] - 1].addFirst(it) } } return stacks.map { if(!it.isEmpty()) it.removeFirst() else "" }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b158069483fa02636804450d9ea2dceab6cf9dd7
2,923
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem57/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem57 /** * LeetCode page: [57. Insert Interval](https://leetcode.com/problems/insert-interval/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the size of intervals; */ fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { if (intervals.isEmpty()) return arrayOf(newInterval) val indexMergeStart = findIndexAtMergeStart(intervals, newInterval) val indexMergeEnded = findIndexAtMergeEnded(intervals, newInterval) return buildIntervalsAfterInsertion(intervals, newInterval, indexMergeStart, indexMergeEnded) } private fun findIndexAtMergeStart(intervals: Array<IntArray>, newInterval: IntArray): Int { val (newStart, newEnd) = newInterval /* BinarySearch start of newInterval against the end of existing intervals such that * end_i-1 < start_new <= end_i */ val i = intervals .binarySearchBy(newStart) { it[1] } .let { if (it < 0) -(it + 1) else it } return when (i) { 0 -> if (newEnd < intervals[0][0]) -1 else 0 else -> i } } private fun <T, K : Comparable<K>> Array<T>.binarySearchBy( key: K, fromIndex: Int = 0, untilIndex: Int = size, selector: (T) -> K ): Int { var left = fromIndex var right = untilIndex - 1 while (left <= right) { val midIndex = (left + right) ushr 1 val midValue = this[midIndex] val midKey = selector(midValue) when { key > midKey -> left = midIndex + 1 key < midKey -> right = midIndex - 1 else -> return midIndex } } return -left - 1 } private fun findIndexAtMergeEnded(intervals: Array<IntArray>, newInterval: IntArray): Int { val (newStart, newEnd) = newInterval /* BinarySearch end of newInterval against the start of existing intervals such that * start_i-1 < newEnd <= start_i */ val i = intervals .binarySearchBy(newEnd) { it[0] } .let { if (it < 0) -(it + 1) else it } return when (i) { 0 -> if (newEnd < intervals[0][0]) -1 else 0 intervals.size -> if (newStart > intervals.last()[1]) intervals.size else intervals.size - 1 else -> if (intervals[i][0] == newEnd) i else i - 1 } } private fun buildIntervalsAfterInsertion( intervals: Array<IntArray>, newInterval: IntArray, indexMergeStart: Int, indexMergeEnded: Int ): Array<IntArray> { if (intervals.isEmpty()) return arrayOf(newInterval) val revisedIntervals = mutableListOf<IntArray>() for (index in 0 until indexMergeStart) { revisedIntervals.add(intervals[index]) } revisedIntervals.add( getMergedInterval(intervals, newInterval, indexMergeStart, indexMergeEnded) ) for (index in indexMergeEnded + 1 until intervals.size) { revisedIntervals.add(intervals[index]) } return revisedIntervals.toTypedArray() } private fun getMergedInterval( intervals: Array<IntArray>, newInterval: IntArray, indexMergeStart: Int, indexMergeEnded: Int ): IntArray { val (newStart, newEnd) = newInterval val mergedStart = when (indexMergeStart) { -1, intervals.size -> newStart else -> minOf(newStart, intervals[indexMergeStart][0]) } val mergedEnd = when (indexMergeEnded) { -1, intervals.size -> newEnd else -> maxOf(newEnd, intervals[indexMergeEnded][1]) } return intArrayOf(mergedStart, mergedEnd) } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
3,881
hj-leetcode-kotlin
Apache License 2.0
src/day13/Day13.kt
spyroid
433,555,350
false
null
package day13 import com.github.ajalt.mordant.terminal.Terminal import readInput import kotlin.random.Random import kotlin.system.measureTimeMillis fun main() { data class Point(var x: Int, var y: Int) class Paper(input: List<String>) { var points = mutableSetOf<Point>() val folds = mutableListOf<Point>() init { input.filter { it.isNotBlank() }.forEach { line -> if (line.contains("fold")) { val s = line.split(" ").last().split("=") if (s[0] == "x") folds.add(Point(s[1].toInt(), 0)) else folds.add(Point(0, s[1].toInt())) } else { line.split(",").map { it.toInt() }.let { points.add(Point(it[0], it[1])) } } } } fun fold() { val fold = folds.removeFirst() if (fold.x == 0) { points = points.onEach { if (it.y > fold.y) it.y = fold.y * 2 - it.y }.toMutableSet() } else { points = points.onEach { if (it.x > fold.x) it.x = fold.x * 2 - it.x }.toMutableSet() } } fun foldAll() { while (folds.isNotEmpty()) fold() } override fun toString() = buildString { for (y in 0..points.maxOf { it.y }) { for (x in 0..points.maxOf { it.x }) { if (Point(x, y) in points) append("#") else append(" ") } appendLine() } } } fun part1(input: List<String>): Int { val paper = Paper(input) paper.fold() return paper.points.size } fun part2(input: List<String>): String { val paper = Paper(input) paper.foldAll() return paper.toString() } val testData = readInput("day13/test") val inputData = readInput("day13/input") val term = Terminal() var res1 = part1(testData) check(res1 == 17) { "Expected 17 but got $res1" } var time = measureTimeMillis { res1 = part1(inputData) } term.success("⭐️ Part1: $res1 in $time ms") var res2: String time = measureTimeMillis { res2 = part2(inputData) } term.success("⭐️ Part2: in $time ms\n\n\n\n\n") res2.split("\n").forEach { val c = term.colors.hsl(Random.nextInt(0, 25) * 10, 1_00, 60) term.println("\t\t" + c(it)) }.let { println("\n\n") } }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
2,426
Advent-of-Code-2021
Apache License 2.0
src/Day04.kt
stephenkao
572,205,897
false
{"Kotlin": 14623}
fun main() { /** * @param rangesStr the ranges string (e.g., '1-2,3-4') * @return list of integer sets per range */ fun getSetsFromRanges(rangesStr: String): Pair<Set<Int>, Set<Int>> { val (startIdx1, endIdx1, startIdx2, endIdx2) = rangesStr.split("[,\\-]".toRegex()) return Pair( (startIdx1.toInt()..endIdx1.toInt()).toSet(), (startIdx2.toInt()..endIdx2.toInt()).toSet() ) } fun part1(input: List<String>): Int { fun isFullSubset(set: Set<Int>, subset: Set<Int>): Boolean { return (set + subset).size == set.size } var sum = 0 for (line in input) { val (set1, set2) = getSetsFromRanges(line) if (isFullSubset(set1, set2) || isFullSubset(set2, set1)) { sum += 1 } } return sum } fun part2(input: List<String>): Int { fun isPartialSubset(set: Set<Int>, subset: Set<Int>): Boolean { return (set + subset).size < (set.size + subset.size) } var sum = 0 for (line in input) { val (set1, set2) = getSetsFromRanges(line) if (isPartialSubset(set1, set2) || isPartialSubset(set2, set1)) { sum += 1 } } return sum } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
7a1156f10c1fef475320ca985badb4167f4116f1
1,553
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch9/Problem92.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch9 import dev.bogwalk.util.combinatorics.permutationID import dev.bogwalk.util.maths.factorial import java.math.BigInteger /** * Problem 92: Square Digit Chains * * https://projecteuler.net/problem=92 * * Goal: Return the count of starting numbers below 10^K will arrive at 89 (modulo 10^9 + 7). * * Constraints: 1 <= K <= 200 * * Square Digit Chain: Sequence created by adding the square of the digits in a number to form a * new number until it has been seen before. * e.g. 44 -> 32 -> 13 -> 10 -> 1 -> 1 * 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 * All starting numbers will eventually end in an infinite loop of 1 or 89. * * Happy Number: A positive integer whose square digit chain ends in 1. The first few are: {1, 7, * 10, 13, 19, 23}. If a number is known to be happy, any number in its sequence is also happy, * as are any permutations of that number. * Unhappy Number: A positive integer whose square digit chain does not end in 1. The first few are: * {2, 3, 4, 5, 6, 8}. * * e.g.: K = 1 * 1 -> 1 * 2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 * 3 -> 9 -> 81 -> 65 -> 61 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 * 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 * 5 -> 25 -> 29 -> 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 * 6 -> 36 -> 45 -> 41 -> 17 -> 50 -> 25 -> 29 -> 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 * 7 -> 49 -> 97 -> 130 -> 10 -> 1 -> 1 * 8 -> 64 -> 52 -> 29 -> 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 * 9 -> 81 -> 65 -> 61 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 * count = 7 */ class SquareDigitChains { private val modulo = 1_000_000_007 private val squares = List(10) { it * it } /** * Iterates through all starters to find the end chain value and stores results in a cache to * reduce chain formation in later starters. * * SPEED (WORSE) 2.95s for K = 7 (becomes unbearably long at K = 10) */ fun countSDChainsBrute(k: Int): Int { val sumLimit = 200 * 9 * 9 val cache = IntArray(sumLimit + 1) var count = 0 val limit = BigInteger.TEN.pow(k) var starter = BigInteger.TWO while (starter < limit) { var number = digitSquaredSum(starter.toString()) while (number != 1 && number != 89) { when (cache[number]) { 1 -> { number = 1 break } 89 -> { number = 89 break } 0 -> { number = digitSquaredSum(number.toString()) } } } if (number == 89) { count++ count %= modulo } if (starter < sumLimit.toBigInteger()) { cache[starter.intValueExact()] = number } starter++ } return count } private fun digitSquaredSum(number: String): Int { return number.sumOf { ch -> squares[ch.digitToInt()] } } /** * Iterates through all potential sums of squared [k] digits and stores in a cache the amount * of starters that will result in each sum. Each potential sum is then iterated over and, if * found to have the desired end chain value, its stored count is accumulated. * * SPEED (BEST) 1.6e+05ns for K = 7 */ fun countSDChainsImproved(k: Int): Int { val cache = IntArray(k * 9 * 9 + 1) // single digit sums for (square in squares) { cache[square]++ } for (digits in 2..k) { for (sum in digits * 9 * 9 downTo 1) { for (d in 1..9) { val square = d * d if (square > sum) { break } // since sums are iterating backwards, add count of all sums without // the most recent digit d cache[sum] += cache[sum-square] cache[sum] %= modulo } } } var count = 0 for (i in 2..k * 9 * 9) { if (cache[i] == 0) continue var sum = i while (sum != 1 && sum != 89) { sum = digitSquaredSum(sum.toString()) } if (sum == 89) { count += cache[i] count %= modulo } } return count } /** * Similar to the brute force method but attempts to cache starters based on the premise that * all permutations of an unhappy number will also be unhappy. * * SPEED (WORSE) 2.96s for K = 7 */ fun countSDChainsPerm(k: Int): Int { val cache = mutableMapOf( permutationID(1L) to 1, permutationID(89L) to 89 ) var count = 0 val limit = BigInteger.TEN.pow(k) var starter = BigInteger.TWO while (starter < limit) { var number = digitSquaredSum(starter.toString()) val starterPermID = permutationID(number.toLong()) if (starterPermID in cache.keys) { if (cache[starterPermID] == 89) { count++ count %= modulo } } else { while (number != 1 && number != 89) { number = digitSquaredSum(number.toString()) val nPermID = permutationID(number.toLong()) if (nPermID in cache.keys) { number = cache[nPermID]!! if (number == 89) { count++ count %= modulo } break } } cache[starterPermID] = number } starter++ } return count } /** * This solution attempts to mimic the PARI/GP code that generates a count of all happy * numbers below 10^[k]. This could then be subtracted from the limit or the helper function * switched to find the count of unhappy numbers. * * TODO!!! - issue with mimicking `forvec` iterative behaviour. * * @see <a href="https://oeis.org/A068571">PARI/GP code</a> */ fun countHappyNums(k: Int): Int { val factor = k.factorial() val digits = List(9) { (it + 1).toBigInteger() } var count = 0 var v: IntArray var d: IntArray for (length in 1..k) { v = IntArray(9) { if (it == 8) length else 0 } d = IntArray(9) { (if (it > 7) k else v[it+1]) - v[it] } val sum = (1..9).sumOf { d[it-1] * it * it } if (isHappy(sum)) { val p = digits.reduce { acc, pI -> acc * d[pI.intValueExact()-1].factorial() } val toAdd = (factor / p / v[0].factorial()).intValueExact() count += toAdd count %= modulo } } for (i in 8 downTo 1) { v = IntArray(9) { if (it >= i-1) 1 else 0 } d = IntArray(9) { (if (it > 7) k else v[it+1]) - v[it] } var sum = (1..9).sumOf { d[it-1] * it * it } if (isHappy(sum)) { val p = digits.reduce { acc, pI -> acc * d[pI.intValueExact()-1].factorial() } val toAdd = (factor / p / v[0].factorial()).intValueExact() count += toAdd count %= modulo } for (j in 9 downTo i) { for (length in 2..k) { v[j-1] = length d = IntArray(9) { (if (it > 7) k else v[it+1]) - v[it] } sum = (1..9).sumOf { d[it-1] * it * it } if (isHappy(sum)) { val p = digits.reduce { acc, pI -> acc * d[pI.intValueExact()-1].factorial() } val toAdd = (factor / p / v[0].factorial()).intValueExact() count += toAdd count %= modulo } } } } return count + 1 } private fun isHappy(number: Int): Boolean { var sum = number // the first happy number is 7 while (sum > 6 && sum != 89) { sum = digitSquaredSum(sum.toString()) } return sum == 1 } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
8,762
project-euler-kotlin
MIT License
src/main/kotlin/com/jacobhyphenated/advent2022/day11/Day11.kt
jacobhyphenated
573,603,184
false
{"Kotlin": 144303}
package com.jacobhyphenated.advent2022.day11 import com.jacobhyphenated.advent2022.Day /** * Day 11: Monkey in the Middle * * Monkeys are playing keep away with your items. Each item has a score of how worried you are about losing it. * During a round, each monkey inspects each item it has, calculates a new worry score (operation) * Then does a "test" to determine which other monkey to throw the item to. */ class Day11: Day<List<Monkey>> { override fun getInput(): List<Monkey> { return parseInput(readInputFile("day11")) } /** * Every time a monkey inspects your item, you divide the worry score by 3 out of relief. * Calculate how many times each monkey inspects an item. * After 20 rounds, return the product of the two highest inspection counts. */ override fun part1(input: List<Monkey>): Long { // deep copy for mutability val monkeys = input.map { it.copy(items = it.items.toMutableList()) } repeat(20) { monkeys.forEach { monkey -> monkey.doRound().forEach { (item, monkeyIndex) -> monkeys[monkeyIndex].items.add(item) } } } return monkeys.map { it.itemsInspected } .sorted().reversed() .take(2) .reduce { a, b -> a * b} } /** * Your worry score no longer gets divided by 3 after the inspection. Also, go for 10,000 rounds. * return the product of the two highest inspection counts. */ override fun part2(input: List<Monkey>): Long { // deep copy for mutability val monkeys = input.map { it.copy(items = it.items.toMutableList()) } // Even longs will eventually overflow over 10,000 rounds. // However, because every test uses a modulo of a prime number, we can get use the least common multiple val leastCommonMultiple = monkeys.map { it.divisibleTest }.reduce{ a, b -> a*b} repeat(10_000) { monkeys.forEach { monkey -> monkey.doRound(true).forEach { (item, monkeyIndex) -> monkeys[monkeyIndex].items.add(item) } } // Using the least common multiple, we can mod the worry scores to keep them well below overflow monkeys.forEach { monkey -> monkey.reduceItems(leastCommonMultiple) } } return monkeys.map { it.itemsInspected } .sorted().reversed() .take(2) .reduce { a, b -> a * b} } fun parseInput(input: String): List<Monkey> { return input.split("\n\n").map { val lines = it.lines() val startingItems = lines[1].trim().split(":")[1].trim().split(", ").map { s -> s.toLong() } val operationString = lines[2].split("=")[1].trim() val divisibleTest = lines[3].trim().split(" ").last().toLong() val ifTestTrue = lines[4].trim().split(" ").last().toInt() val ifTestFalse = lines[5].trim().split(" ").last().toInt() val (lhs, operator, rhs) = operationString.split(" ") val resolveValue = { value: String, oldValue: Long -> if (value == "old") { oldValue } else { value.toLong() } } val operation = when(operator) { "+" -> { oldValue: Long -> resolveValue(lhs, oldValue) + resolveValue(rhs, oldValue) } "*" -> { oldValue: Long -> resolveValue(lhs, oldValue) * resolveValue(rhs, oldValue) } else -> throw NotImplementedError("Invalid operator $operator") } Monkey(items = startingItems.toMutableList(), operation, divisibleTest, ifTestTrue, ifTestFalse) } } } data class Monkey( val items: MutableList<Long>, private val operation: (Long) -> Long, val divisibleTest: Long, private val ifTestTrue: Int, private val ifTestFalse: Int ) { var itemsInspected = 0L /** * Perform the round of inspections for this monkey. * The list of items will be empty after this function completes * * @param extraWorry do not divide the worry score by 3 if this is true. Used for part 2. * @return A List of pairs containing the item score and the index of the monkey it should be passed to */ fun doRound(extraWorry: Boolean = false): List<Pair<Long,Int>> { return items .map { operation(it) } .map { if (extraWorry) { it } else { it / 3 } } .map { itemsInspected++ if (it % divisibleTest == 0L) { Pair(it, ifTestTrue) } else { Pair(it, ifTestFalse) } }.also { items.clear() } } fun reduceItems(lcm: Long) { for (i in items.indices) { items[i] = items[i] % lcm } } }
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
4,870
advent2022
The Unlicense
src/main/kotlin/aoc2022/Day16.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.* import aoc.parser.* import kotlin.math.absoluteValue private const val empty: Int = Int.MAX_VALUE class Day16() { data class Valve(val name: String, val flowRate: Int, val tunnelsTo: List<String>) { override fun toString() = "$name($flowRate)" } //Valve AA has flow rate=0; tunnels lead to valves DD, II, BB val valve = seq( "Valve " followedBy regex("[A-Z]{2}"), " has flow rate=" followedBy number(), seq( literal("; tunnel leads to valve ") or literal("; tunnels lead to valves "), regex("[A-Z]{2}") sepBy ", ") { _, result -> result }, ::Valve) followedBy "\n" val valves = zeroOrMore(valve) class MapValvesBackedGraphNode(override val value: Valve, private val valves: Map<String, Valve>): GraphNode<Valve> { override val neighbours by lazy { value.tunnelsTo.map { 1 to MapValvesBackedGraphNode(valves.getValue(it), valves) } } override fun toString(): String { return value.toString() } override fun equals(other: Any?): Boolean = when (other) { is MapValvesBackedGraphNode -> other.valves == this.valves && other.value == this.value else -> false } override fun hashCode(): Int { return this.value.hashCode() } val shortestPaths by lazy { findShortestPaths(this).mapValues { it.value.first } } } private fun setup(input: String): Pair<MapValvesBackedGraphNode, Set<MapValvesBackedGraphNode>> { val parsed = valves.parse(input) val mapValves = parsed.associateBy { it.name } val startValve = mapValves.getValue("AA") val startNode = MapValvesBackedGraphNode(startValve, mapValves) val openableValves = parsed.filter { it.flowRate > 0 }.map { MapValvesBackedGraphNode(it, mapValves) }.toSet() return Pair(startNode, openableValves) } fun part1(input: String): Int { val (graph, openableValves) = setup(input) return calcPressure(30, graph, openableValves, 1) } fun part2(input: String): Int { val (graph, openableValves) = setup(input) return calcPressure(26, graph, openableValves, 2) } fun calcPressure( timeLeft: Int, node: GraphNode<Valve>, openableValves: Set<GraphNode<Valve>>, players: Int ): Int { val distanceNodes = (openableValves + setOf(node)).toList() .map { if (it is MapValvesBackedGraphNode) it else throw IllegalStateException() } val distanceMap = distanceNodes.map { distanceNodes.indexOf(it) to it.shortestPaths.mapKeys { e -> distanceNodes.indexOf(e.key) } } .toMap() val distanceArray = distanceMap.filterKeys { it >= 0 }.toList().sortedBy { it.first } .map { it.second.filterKeys { it >= 0 }.toList().sortedBy { it.first }.map { it.second }.toIntArray() } val countNodes = distanceNodes.size - 1 val keyMult1 = players + 1 val keyMult2a = timeLeft + 1 val keyMult2 = keyMult1 * keyMult2a val keyMult3a = countNodes + 1 val keyMult3 = keyMult2 * keyMult3a val cache = IntArray((1 shl keyMult3a) * keyMult2a * (countNodes) * keyMult1) { empty } // Due to symmetry, not all possibilities need to be check from the elephant perspective. // Thy this is the right number is a little unclear. Might not work for all input. val minDepth = countNodes / 2 - 1 fun go( currentTimeLeft: Int, currentNode: Int, currentOpenableValves: Int, player: Int, depth: Int ): Int { val key = (keyMult3 * currentOpenableValves) + (keyMult2 * currentNode) + (keyMult1 * currentTimeLeft) + player val cached = cache[key] val newValves = if (cached != empty) { val positive = cached.absoluteValue cache[key] = -positive positive } else { val newCache = (0 until countNodes).maxOf { gotoNode -> if ((currentOpenableValves and (1 shl gotoNode)) == 0) 0 else { val distance = distanceArray[currentNode][gotoNode] val newTimeLeft = currentTimeLeft - distance - 1 val addedPressure = distanceNodes[gotoNode].value.flowRate * newTimeLeft val newOpenableValves = currentOpenableValves - (1 shl gotoNode) if (newOpenableValves == 0 || (newTimeLeft <= 1)) { addedPressure } else { val pressure = go( newTimeLeft, gotoNode, newOpenableValves, player, depth + 1 ) + addedPressure pressure } } } cache[key] = newCache newCache } return if (player > 1 && depth >= minDepth) { val newPlayer = go( timeLeft, countNodes, currentOpenableValves, player - 1, depth + 1 ) maxOf( newValves, newPlayer ) } else newValves } return go(timeLeft, countNodes, (1 shl countNodes) - 1, players, 0) } }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
5,884
aoc-kotlin
Apache License 2.0
y2023/src/main/kotlin/adventofcode/y2023/Day10.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2023 import adventofcode.io.AdventSolution import adventofcode.util.vector.Direction import adventofcode.util.vector.Direction.* import adventofcode.util.vector.Vec2 import adventofcode.util.vector.toGrid fun main() { Day10.solve() } object Day10 : AdventSolution(2023, 10, "Pipe Maze") { override fun solvePartOne(input: String): Any? { val grid = input.lines().flatMapIndexed { y, line -> line.mapIndexed { x, ch -> Vec2(x, y) to ch } }.toMap() val start = grid.filterValues { it == 'S' }.keys.first() val direction = Direction.entries.first { it.reverse in grid[start + it.vector]!!.let(edges::getValue) } val seq = generateSequence(Pair(start, direction)) { (pos, dir) -> val newPos = pos + dir.vector val newDir = grid[newPos]!!.let(edges::getValue).first { it != dir.reverse } newPos to newDir } val result = seq.drop(1).indexOfFirst { grid[it.first] == 'S' } return (result + 1) / 2 } override fun solvePartTwo(input: String): Int { val grid = input.lines().flatMapIndexed { y, line -> line.mapIndexed { x, ch -> Vec2(x, y) to ch } }.toMap() val startPosition = grid.filterValues { it == 'S' }.keys.first() val connections = Direction.entries.filter { it.reverse in (grid[startPosition + it.vector]?.let { edges[it]} ?: emptyList()) }.toSet() val seq = generateSequence(Pair(startPosition, connections.first())) { (pos, dir) -> val newPos = pos + dir.vector val newDir = edges[grid[newPos]!!]!!.first { it != dir.reverse } newPos to newDir } val pipes = seq.drop(1).takeWhile { grid[it.first] != 'S' }.map { it.first }.toSet() val startSymbol = edges.entries.first { it.value == connections }.key val pipeMap = grid.filterKeys { it in pipes } + (startPosition to startSymbol) //pretend we're standing on the 'lower half' of a tile, moving right. //these are the pipe shapes where we cross from inside/outside the loop val pipeCrossing = edges.filterValues { DOWN in it }.keys.joinToString("") return pipeMap.toGrid(' ').flatMap { row -> //scan the row, keeping track of whether we're on an open space and whether we're inside or outside the loop row.scan(Pair(true, false)) { (_, isInside), ch -> Pair(ch == ' ', if (ch in pipeCrossing) !isInside else isInside) } } .count { (isOpenSpace, isInside) -> isOpenSpace && isInside } } } private val edges = mapOf( '|' to setOf(UP, DOWN), '-' to setOf(LEFT, RIGHT), 'L' to setOf(UP, RIGHT), 'J' to setOf(UP, LEFT), '7' to setOf(DOWN, LEFT), 'F' to setOf(DOWN, RIGHT), '.' to emptySet(), 'S' to setOf(UP, DOWN, LEFT, RIGHT) //ugly hack for last step in traversal )
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,950
advent-of-code
MIT License
2021/src/main/kotlin/day24.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.cut fun main() { Day24Imp.run(skipTest = true) } object Day24Imp : Solution<List<List<Day24Imp.Insn>>>() { override val name = "day24" private const val DIGITS = 14 override val parser = Parser { input -> val progStrings = input.split("inp w\n").map { it.trim() }.filter { it.isNotBlank() } val progs = progStrings.map { it.lines().filter(String::isNotBlank).map(Insn::parse) } // assumptions made about the input require(progs.size == DIGITS) progs.forEach { insns -> // W is only input require(insns.none { it.left == Register.W }) // X and Y are always reset before calculating require(insns.first { it.left == Register.X } == Insn(Opcode.mul, Register.X, Literal(0))) require(insns.first { it.left == Register.Y } == Insn(Opcode.mul, Register.Y, Literal(0))) } progs } data class Regs(var x: Int = 0, var y: Int = 0, var z: Int = 0, var w: Int = 0) enum class Opcode { add, mul, div, mod, eql } sealed interface Value { operator fun get(regs: Regs): Int } enum class Register(val getter: (Regs) -> Int, val setter: (Regs, Int) -> Unit) : Value { X(Regs::x, { r, v -> r.x = v }), Y(Regs::y, { r, v -> r.y = v }), Z(Regs::z, { r, v -> r.z = v }), W(Regs::w, { r, v -> r.w = v }); override fun get(regs: Regs) = getter(regs) operator fun set(regs: Regs, value: Int) = setter(regs, value) } data class Literal(val value: Int) : Value { override fun get(regs: Regs) = value } data class Insn(val op: Opcode, val left: Register, val right: Value) { companion object { fun parse(str: String): Insn { val (op, values) = str.cut(" ") val (left, right) = values.cut(" ") return Insn(Opcode.valueOf(op), Register.valueOf(left.uppercase()), right.toIntOrNull()?.let { Literal(it) } ?: Register.valueOf(right.uppercase())) } } } fun exec(insn: Insn, regs: Regs) { insn.left[regs] = when (insn.op) { Opcode.add -> insn.left[regs] + insn.right[regs] Opcode.mul -> insn.left[regs] * insn.right[regs] Opcode.div -> insn.left[regs] / insn.right[regs] Opcode.mod -> insn.left[regs] % insn.right[regs] Opcode.eql -> if (insn.left[regs] == insn.right[regs]) 1 else 0 } } /** * Return Z register for the given input */ fun checkDigit(insns: List<Insn>, inp: Int, z: Int): Int { val r = Regs(z = z, w = inp) insns.forEach { exec(it, r) } return r.z } private fun solve(input: List<List<Insn>>): List<Long> { var zRange = setOf(0) var idx = input.size - 1 val constrained = Array<MutableMap<Int, MutableSet<Int>>>(14) { mutableMapOf() } input.reversed().forEach { prog -> val validZ = mutableSetOf<Int>() for (input in 1 .. 9) { for (z in 0 .. 1000000) { if (checkDigit(prog, input, z) in zRange) { val set = constrained[idx].getOrPut(input) { mutableSetOf() } set.add(z) validZ.add(z) } } } require(validZ.isNotEmpty()) { "No valid z for input input[$idx]?" } idx-- zRange = validZ } fun findSerial(index: Int, z: Int): List<String> { if (index == 14) return listOf("") val opts = constrained[index].entries.filter { z in it.value } return opts.flatMap { (digit, _) -> val newZ = checkDigit(input[index], digit, z) findSerial(index + 1, newZ).map { digit.toString() + it } } } return findSerial(0, 0).map { it.toLong() } } override fun part1(input: List<List<Insn>>): Long? { return solve(input).maxOrNull() } override fun part2(input: List<List<Insn>>): Long? { return solve(input).minOrNull() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
3,815
aoc_kotlin
MIT License
y2020/src/main/kotlin/adventofcode/y2020/Day18.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution import java.util.Stack fun main() = Day18.solve() object Day18 : AdventSolution(2020, 18, "Operation Order") { override fun solvePartOne(input: String) = input.lineSequence().sumOf { evaluate(it, ::evalLeftToRight) } override fun solvePartTwo(input: String) = input.lineSequence().sumOf { evaluate(it, ::evalWithWeirdPrecedence) } private inline fun evaluate(input: String, resolve: (Long, List<Pair<Char, Long>>) -> Long): Long { val scope = Stack<MutableList<Any>>().apply { push(mutableListOf()) } input.forEach { t -> when (t) { '(' -> scope.push(mutableListOf()) ')' -> scope.pop().let { scope.peek() += eval(it, resolve) } in '0'..'9' -> scope.peek() += t.toString().toLong() '+', '*' -> scope.peek() += t } } return eval(scope.single(), resolve) } private inline fun eval(tokens: List<Any>, resolve: (Long, List<Pair<Char, Long>>) -> Long): Long = tokens .drop(1) .chunked(2) .map { (operator, value) -> Pair(operator as Char, value as Long) } .let { resolve(tokens.first() as Long, it) } private fun evalLeftToRight(initial: Long, tokens: List<Pair<Char, Long>>): Long = tokens.fold(initial) { acc, (op, v) -> if (op == '+') acc + v else acc * v } private fun evalWithWeirdPrecedence(initial: Long, tokens: List<Pair<Char, Long>>): Long = tokens.fold(Pair(1L, initial)) { (prod, sum), (op, v) -> if (op == '+') Pair(prod, sum + v) else Pair(prod * sum, v) }.let { (prod, sum) -> prod * sum } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,745
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumMatrix.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 /** * 304. Range Sum Query 2D - Immutable * @see <a href="https://leetcode.com/problems/range-sum-query-2d-immutable/">Source</a> */ fun interface NumMatrix { fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int } class CachingRows(matrix: Array<IntArray>) : NumMatrix { private lateinit var dp: Array<IntArray> init { if (matrix.isNotEmpty() || matrix[0].isNotEmpty()) { dp = Array(matrix.size) { IntArray(matrix[0].size + 1) } for (r in matrix.indices) { for (c in 0 until matrix[0].size) { dp[r][c + 1] = dp[r][c] + matrix[r][c] } } } } override fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int { var sum = 0 for (row in row1..row2) { sum += dp[row][col2 + 1] - dp[row][col1] } return sum } } class CachingSmarter(matrix: Array<IntArray>) : NumMatrix { private lateinit var dp: Array<IntArray> init { if (matrix.isNotEmpty() || matrix[0].isNotEmpty()) { dp = Array(matrix.size + 1) { IntArray(matrix[0].size + 1) } for (r in matrix.indices) { for (c in 0 until matrix[0].size) { dp[r + 1][c + 1] = dp[r + 1][c] + dp[r][c + 1] + matrix[r][c] - dp[r][c] } } } } override fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int { return dp[row2 + 1][col2 + 1] - dp[row1][col2 + 1] - dp[row2 + 1][col1] + dp[row1][col1] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,209
kotlab
Apache License 2.0
src/Day07.kt
rweekers
573,305,041
false
{"Kotlin": 38747}
fun main() { fun part1(input: List<String>): Long { return determineCumulativeDirectorySizes(input) .filter { it.value <= 100000 } .map { it.value } .sum() } fun part2(input: List<String>): Long { val cumulativeSizes = determineCumulativeDirectorySizes(input) val spaceUnused = 70_000_000 - (cumulativeSizes["/"] ?: throw IllegalArgumentException()) val spaceNeeded = 30_000_000 - spaceUnused return cumulativeSizes .filter { it.value >= spaceNeeded } .minOf { it.value } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) } private fun parseCliOutput(input: List<String>): List<CliOutput> = input .filterIndexed { index, s -> index != 0 } .filterNot { it.filterNot { c -> c.isWhitespace() }.startsWith("\$ls") } .map { if (it.filterNot { c -> c.isWhitespace() }.startsWith("\$cd")) { Command(it.split(" ")[2]) } else if (it.split(" ")[0] == "dir") { Directory(it.split(" ")[1]) } else { Output(it.split(" ")[1], it.split(" ")[0].toLong()) } } private fun determineDirectorySizes(cliOutput: List<CliOutput>): Map<String, Long> = buildMap { var currentDir = "/" put(currentDir, 0) cliOutput.forEach { when (it) { is Directory -> { // do nothing } is Command -> { currentDir = if (it.location == "..") currentDir.substring( 0, currentDir.lastIndexOf("/") ) else (currentDir + "/${it.location}").replace("//", "/") if (currentDir.isNotEmpty()) { putIfAbsent(currentDir, 0) } } is Output -> this[currentDir] = (this[currentDir] ?: throw IllegalArgumentException()) + it.size } } } private fun determineCumulativeDirectorySizes(input: List<String>): Map<String, Long> { val sizes = determineDirectorySizes(parseCliOutput(input)) return buildMap { sizes .forEach { m -> val totalValue = sizes .filter { it.key.startsWith(m.key) } .map { it.value } .sum() this[m.key] = totalValue } } } sealed interface CliOutput class Command(val location: String) : CliOutput class Output(val name: String, val size: Long) : CliOutput class Directory(val name: String) : CliOutput
0
Kotlin
0
1
276eae0afbc4fd9da596466e06866ae8a66c1807
2,903
adventofcode-2022
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day17.kt
EmRe-One
726,902,443
false
{"Kotlin": 95869, "Python": 18319}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.automation.Day import tr.emreone.kotlin_utils.data_structures.Dijkstra import tr.emreone.kotlin_utils.data_structures.Graph import tr.emreone.kotlin_utils.extensions.area import tr.emreone.kotlin_utils.extensions.formatted import tr.emreone.kotlin_utils.math.* class Day17 : Day(17, 2023, "Clumsy Crucible") { val heatMap = inputAsGrid.map { it.map { it.digitToInt() } } val area = heatMap.area data class State( val pos: Point, val movedStraight: Int, val dir: Direction4?, ) override fun part1(): Int { val graph = object : Graph<State> { override fun neighborsOf(node: State): Collection<State> { return Direction4.all .map { d -> State( node.pos + d, movedStraight = if (d == node.dir) node.movedStraight + 1 else 1, dir = d ) } .filter { it.pos in area && it.movedStraight <= 3 && it.dir != node.dir?.opposite } } override fun cost(from: State, to: State): Int = heatMap[to.pos.y][to.pos.x] } val start = State(origin, 0, null) val x = Dijkstra(start, graph::neighborsOf, graph::cost).search { it.pos == area.lowerRight } val path = x.path heatMap.formatted { pos, v -> if (pos in path.map { it.pos }) path.first { it.pos == pos }.movedStraight.toString() else "." } return path.drop(1).sumOf { heatMap[it.pos.y][it.pos.x] } } override fun part2(): Int { val graph = object : Graph<State> { override fun neighborsOf(node: State): Collection<State> { return (if (node.movedStraight < 4 && node.pos != origin) listOf(node.copy(node.pos + node.dir!!, movedStraight = node.movedStraight + 1)) else Direction4.all.map { d -> State( node.pos + d, movedStraight = if (d == node.dir) node.movedStraight + 1 else 1, dir = d ) }).filter { it.pos in area && it.movedStraight <= 10 && it.dir != node.dir?.opposite } } override fun cost(from: State, to: State): Int = heatMap[to.pos.y][to.pos.x] override fun costEstimation(from: State, to: State): Int = from.pos manhattanDistanceTo to.pos } val start = State(origin, 0, null) val x = Dijkstra(start, graph::neighborsOf, graph::cost).search { it.pos == area.lowerRight && it.movedStraight >= 4 } val path = x.path heatMap.formatted { pos, v -> if (pos in path.map { it.pos }) path.first { it.pos == pos }.movedStraight.toString() else "." } return path.drop(1).sumOf { heatMap[it.pos.y][it.pos.x] } } }
0
Kotlin
0
0
c75d17635baffea50b6401dc653cc24f5c594a2b
3,225
advent-of-code-2023
Apache License 2.0
Word_Search_II.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
// Given a 2D board and a list of words from the dictionary, find all words in the board. //https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00) class Solution { fun findWords(board: Array<CharArray>, words: Array<String>): List<String> { val root = buildTrie(words) val res = ArrayList<String>() for (i in board.indices) { for (j in board[i].indices) { dfs(root, board, res, i, j) } } return res } private fun dfs(root: TrieNode, board: Array<CharArray>, res: MutableList<String>, i: Int, j: Int) { val ch = board[i][j] if (ch == '#' || root.next[ch - 'a'] == null) return val p = root.next[ch - 'a']!! if (p.word != null) { p.word?.let { res.add(it) } p.word = null // de-duplicate } board[i][j] = '#' if (i > 0) dfs(p, board, res, i - 1, j) if (j > 0) dfs(p, board, res, i, j - 1) if (i < board.size - 1) dfs(p, board, res, i + 1, j) if (j < board[i].size - 1) dfs(p, board, res, i, j + 1) board[i][j] = ch } private fun buildTrie(words: Array<String>): TrieNode { val root = TrieNode(); for (word in words) { var p = root for (ch in word.toCharArray()) { val i = ch - 'a' if (p.next[i] == null) { p.next[i] = TrieNode() } p = p.next[i]!! } p.word = word } return root } } class TrieNode { val next: Array<TrieNode?> = Array(26) { null } var word: String? = null } fun main(args: Array<String>) { val solution = Solution() val testset = arrayOf( arrayOf( charArrayOf('o', 'a', 'a', 'n'), charArrayOf('e', 't', 'a', 'e'), charArrayOf('i', 'h', 'k', 'r'), charArrayOf('i', 'f', 'l', 'v') ), arrayOf( charArrayOf('a', 'b'), charArrayOf('c', 'd') ) ) val words = arrayOf( arrayOf("oath", "pea", "eat", "rain"), arrayOf("ab", "cb", "ad", "bd", "ac", "ca", "da", "bc", "db", "adcb", "dabc", "abb", "acb") ) for (i in testset.indices) { val res = solution.findWords(testset[i], words[i]) res.forEach { println(it) } } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
2,488
leetcode
MIT License
src/Day02.kt
virtualprodigy
572,945,370
false
{"Kotlin": 8043}
import kotlin.math.max fun main() { val winningsMap = hashMapOf<String, Int>( "Lose" to 0, "Win" to 6, "Draw" to 3 ) val fightResultsMap = hashMapOf<String, String>( "ax" to "Draw", "ay" to "Win", "az" to "Lose", "bx" to "Lose", "by" to "Draw", "bz" to "Win", "cx" to "Win", "cy" to "Lose", "cz" to "Draw", ) val playerMoveToPoints = hashMapOf<String, Int>( "x" to 1, "y" to 2, "z" to 3 ) // Maps the player requested outcome to a move // X means you need to lose // Y means you need to end the round in a draw, // Z means you need to win val matchOutcomeToPlayerMoveMap = hashMapOf<String, String>( "ax" to "z", "ay" to "x", "az" to "y", "bx" to "x", "by" to "y", "bz" to "z", "cx" to "y", "cy" to "z", "cz" to "x", ) fun part1(input: List<String>): Int { var totalPoints = 0 input.forEach { battle -> totalPoints += battle .lowercase() .replace(" ", "") .partition { "abc".contains(it) } .run { val move = this.second fightResultsMap[this.first + move].run { winningsMap[this]!! + playerMoveToPoints[move]!! } } } return totalPoints } fun part2(input: List<String>): Int { var totalPoints = 0 for (battle in input) { val moveList = battle.lowercase().split(" ") val enemyMove = moveList[0] val playerMove = matchOutcomeToPlayerMoveMap[moveList[0] + moveList[1]] totalPoints += fightResultsMap[enemyMove + playerMove].run { winningsMap[this]!! + playerMoveToPoints[playerMove]!! } } return totalPoints } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
025f3ae611f71a00e9134f0e2ba4b602432eea93
2,296
advent-code-code-kotlin-jetbrains-2022
Apache License 2.0
src/Day04.kt
mvanderblom
573,009,984
false
{"Kotlin": 25405}
fun String.toIntRange(delimiter: String): IntRange { val (from, to) = this .split(delimiter) .map { it.toInt() } return IntRange(from, to) } fun IntRange.contains(other: IntRange): Boolean = this.first <= other.first && other.last <= this.last fun main() { val dayName = 4.toDayName() fun parseRange(it: String) = it .split(",") .map { it.toIntRange("-") } fun parseRanges(input: List<String>) = input .map(::parseRange) fun part1(input: List<String>): Int = parseRanges(input) .count { (first, second) -> first.contains(second) || second.contains(first) } fun part2(input: List<String>): Int = parseRanges(input) .count { (first, second) -> first.intersect(second).isNotEmpty() } val testInput = readInput("${dayName}_test") val input = readInput(dayName) // Part 1 val testOutputPart1 = part1(testInput) testOutputPart1 isEqualTo 2 val outputPart1 = part1(input) outputPart1 isEqualTo 450 // Part 2 val testOutputPart2 = part2(testInput) testOutputPart2 isEqualTo 4 val outputPart2 = part2(input) outputPart2 isEqualTo 837 }
0
Kotlin
0
0
ba36f31112ba3b49a45e080dfd6d1d0a2e2cd690
1,200
advent-of-code-kotlin-2022
Apache License 2.0
src/Day01.kt
geodavies
575,035,123
false
{"Kotlin": 13226}
fun main() { fun part1(input: List<String>): Int { var elfNumber = 1 val elfCalories = mutableMapOf<Int, Int>() var mostCalories = 0 input.forEach { calories -> if (calories == "") { elfNumber++ } else { val currentCalories = elfCalories.getOrDefault(elfNumber, 0) val newCalories = currentCalories + calories.toInt() elfCalories[elfNumber] = newCalories if (mostCalories < newCalories) { mostCalories = newCalories } } } return mostCalories } fun part2(input: List<String>): Int { var elfNumber = 1 val elfCalories = mutableMapOf<Int, Int>() input.forEach { calories -> if (calories == "") { elfNumber++ } else { val currentCalories = elfCalories.getOrDefault(elfNumber, 0) val newCalories = currentCalories + calories.toInt() elfCalories[elfNumber] = newCalories } } var topThreeCalories = mutableListOf(0, 0, 0) elfCalories.values.forEach { calories -> topThreeCalories.add(calories) topThreeCalories.sortDescending() topThreeCalories = topThreeCalories.subList(0, 3) } return topThreeCalories.reduce { acc, i -> acc + i } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d04a336e412ba09a1cf368e2af537d1cf41a2060
1,732
advent-of-code-2022
Apache License 2.0
src/Day06.kt
makobernal
573,037,099
false
{"Kotlin": 16467}
fun findIndex(list: List<String>, condition: (String) -> Boolean): Int { for (i in list.indices) { if (condition(list[i])) { return i } } return -1 } fun main() { fun solutioner(input: List<String>, windowSize: Int): Int { val indexWhereThisHappens = findIndex( input[0].windowed(windowSize) ) { it.toSet().size == it.length } return indexWhereThisHappens + windowSize } fun part1(input: List<String>): Int { return solutioner(input, 4) } fun part2(input: List<String>): Int { return solutioner(input, 14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") val testResult = part1(testInput) val testResult2 = part2(testInput) check(testResult == 7) { "wrong solution for part 1, $testResult is not 7" } check(testResult2 == 19) { "wrong solution for part 2, $testResult is not 19" } val input = readInput("Day06") val result1 = part1(input) val result2 = part2(input) println("solution for your input, part 1 = $result1") println("solution for your input, part 2 = $result2") }
0
Kotlin
0
0
63841809f7932901e97465b2dcceb7cec10773b9
1,229
kotlin-advent-of-code-2022
Apache License 2.0
src/Day03/Day03.kt
ctlevi
578,257,705
false
{"Kotlin": 10889}
fun main() { fun part1(input: List<String>): Int { return input.map { row -> val first = row.toList().subList(0, row.length / 2).toSet() val second = row.toList().subList(row.length / 2, row.length).toSet() val overlappingChar = first.intersect(second).first() if (overlappingChar in 'a'..'z') { overlappingChar.code - 96 } else { overlappingChar.code - 64 + 26 } }.sum() } fun part2(input: List<String>): Int { return input.chunked(3).map { val first = it[0].toSet() val second = it[1].toSet() val third = it[2].toSet() val overlappingChar = first.intersect(second).intersect(third).first() if (overlappingChar in 'a'..'z') { overlappingChar.code - 96 } else { overlappingChar.code - 64 + 26 } }.sum() } val testInput = readInput("Day03/test") val testResult = part1(testInput) "Test Result: ${testResult}".println() val input = readInput("Day03/input") "Part 1 Result: ${part1(input)}".println() "Part 2 Result: ${part2(input)}".println() }
0
Kotlin
0
0
0fad8816e22ec0df9b2928983713cd5c1ac2d813
1,241
advent_of_code_2022
Apache License 2.0
src/main/kotlin/g1901_2000/s1932_merge_bsts_to_create_single_bst/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1932_merge_bsts_to_create_single_bst // #Hard #Hash_Table #Depth_First_Search #Tree #Binary_Search #Binary_Tree // #2023_06_20_Time_1146_ms_(100.00%)_Space_84.5_MB_(100.00%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun canMerge(trees: List<TreeNode>): TreeNode? { val valToNode: MutableMap<Int, TreeNode> = HashMap() val count: MutableMap<Int, Int> = HashMap() for (tree in trees) { valToNode[tree.`val`] = tree count.merge( tree.`val`, 1 ) { a: Int?, b: Int? -> Integer.sum( a!!, b!! ) } if (tree.left != null) count.merge( tree.left!!.`val`, 1 ) { a: Int?, b: Int? -> Integer.sum( a!!, b!! ) } if (tree.right != null) count.merge( tree.right!!.`val`, 1 ) { a: Int?, b: Int? -> Integer.sum( a!!, b!! ) } } for (tree in trees) if (count[tree.`val`] == 1) { return if (isValidBST(tree, null, null, valToNode) && valToNode.size <= 1 ) tree else null } return null } fun isValidBST( tree: TreeNode?, minNode: TreeNode?, maxNode: TreeNode?, valToNode: MutableMap<Int, TreeNode> ): Boolean { if (tree == null) return true if (minNode != null && tree.`val` <= minNode.`val`) return false if (maxNode != null && tree.`val` >= maxNode.`val`) return false if (tree.left == null && tree.right == null && valToNode.containsKey(tree.`val`)) { val `val` = tree.`val` tree.left = valToNode[`val`]!!.left tree.right = valToNode[`val`]!!.right valToNode.remove(`val`) } return isValidBST(tree.left, minNode, tree, valToNode) && isValidBST(tree.right, tree, maxNode, valToNode) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,292
LeetCode-in-Kotlin
MIT License
src/Day07.kt
romainbsl
572,718,344
false
{"Kotlin": 17019}
fun main() { fun initFileSystem(input: List<String>): Directory { val root = Directory("/", null) var dir: Directory = root input.drop(1).forEach { line -> when (line.first()) { '$' -> { val command = line.split(" ") when (command[1]) { "cd" -> dir = when (command[2]) { ".." -> dir.parent!! else -> dir.findDirectory(command[2]) } else -> { /* ignore */ } } } else -> { val (left, right) = line.split(" ") when (left) { "dir" -> { val newDir = Directory(right, dir) dir.addChild(newDir) } else -> dir.size += left.toLong() } } } } return root } fun part1(input: List<String>): Long { val root = initFileSystem(input) return root .flattenChildren() .filter { it.totalSize <= 100_000 } .sumOf(Directory::totalSize) } fun part2(input: List<String>): Long { val root = initFileSystem(input) val unused = 70_000_000L - root.totalSize val missing = 30_000_000L - unused return root .flattenChildren() .filter { it.totalSize >= missing } .minOf(Directory::totalSize) } val testInput = readInput("Day07_test") check(part1(testInput) == 95_437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") check(part1(input) == 1_243_729L) check(part2(input) == 4_443_914L) } private fun Directory.flattenChildren(): List<Directory> { return children + children.flatMap { it.flattenChildren() } } data class Directory( val name: String, val parent: Directory?, ) { val children: MutableList<Directory> = mutableListOf() val totalSize: Long get() = size + children.sumOf { it.totalSize } var size: Long = 0L fun addChild(directory: Directory) { children.add(directory) } fun reset() = children.clear() fun findDirectory(name: String): Directory { return children .firstOrNull { it.name == name } ?: error("NOT FOUND!") } } fun String.isChangeDirCommand(): Boolean = startsWith("$ cd") fun String.isListCommand(): Boolean = startsWith("$ ls")
0
Kotlin
0
0
b72036968769fc67c222a66b97a11abfd610f6ce
2,674
advent-of-code-kotlin-2022
Apache License 2.0
leetcode/src/daily/easy/Q1800.kt
zhangweizhe
387,808,774
false
null
package daily.easy fun main() { // 1800. 最大升序子数组和 // https://leetcode.cn/problems/maximum-ascending-subarray-sum/ println(maxAscendingSum1(intArrayOf(10,20,30,5,10,50))) } fun maxAscendingSum(nums: IntArray): Int { if (nums.size == 1) { return nums[0] } var max = 0 var tmpMax = nums[0] for (i in 1 until nums.size) { if (nums[i] > nums[i-1]) { // 升序的 tmpMax += nums[i] }else { if (tmpMax > max) { max = tmpMax } // 更新 tmpMax tmpMax = nums[i] } } if (tmpMax > max) { // 和最大的升序自数组在最后 max = tmpMax } return max } fun maxAscendingSum1(nums: IntArray): Int { /** * 动态规划 * 1、状态定义:dp[i] 表示以 nums[i] 结尾的升序子数组的和 * 2、递推公式:分两种情况 * 2.1 升序的,nums[i] >= nums[i-1]:dp[i] = dp[i-1] + nums[i] * 2.2 降序的,nums[i] < nums[i-1]:dp[i] = nums[i] * 3、初始值:dp[0] = nums[0] */ val dp = IntArray(nums.size) dp[0] = nums[0] var max = dp[0] for (i in 1 until nums.size) { dp[i] = if (nums[i] > nums[i-1]) { dp[i-1] + nums[i] }else { nums[i] } if (max < dp[i]) { max = dp[i] } } return max }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,437
kotlin-study
MIT License
src/Day08.kt
tigerxy
575,114,927
false
{"Kotlin": 21255}
fun main() { fun part1(input: List<String>): Int { return with(input.parse()) { isVerticalVisible() .or(isHorizontalVisible()) .sum() } } fun part2(input: List<String>): Int { return 0 } val day = "08" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") val testOutput1 = part1(testInput) println("part1_test=$testOutput1") assert(testOutput1 == 21) val testOutput2 = part2(testInput) println("part2_test=$testOutput2") assert(testOutput2 == 0) val input = readInput("Day$day") println("part1=${part1(input)}") println("part2=${part2(input)}") } private fun List<List<Boolean>>.sum() = sumOf { line -> line.sumOf { cell -> cell.toInt() } } private infix fun List<List<Boolean>>.or(other: List<List<Boolean>>): List<List<Boolean>> = mapIndexed { x, line -> line.mapIndexed { y, cell -> cell || other[x][y] } } private fun List<List<Int>>.isVerticalVisible() = rotate().isHorizontalVisible().rotate() private fun <E> List<List<E>>.rotate(): List<List<E>> = List(first().size) { x -> List(size) { y -> this[y][x] } } private fun List<List<Int>>.isHorizontalVisible(): List<List<Boolean>> = map { it.visible() } private fun List<Int>.visible(): List<Boolean> { var p1 = 0 var p2 = lastIndex var leftMax = this[p1] var rightMax = this[p2] val visible = List(size) { false }.toMutableList() visible[p1] = true visible[p2] = true while (p1 != p2) { if (leftMax < rightMax) { p1++ if (this[p1] > leftMax) { leftMax = this[p1] visible[p1] = true } } else { p2-- if (this[p2] > rightMax) { rightMax = this[p2] visible[p2] = true } } } return visible.toList() } private fun List<String>.parse() = map { line -> line.toCharArray() .map { it.digitToInt() } }
0
Kotlin
0
1
d516a3b8516a37fbb261a551cffe44b939f81146
2,192
aoc-2022-in-kotlin
Apache License 2.0
Dynamic Programming/Longest Palindromic Subsequence/src/Task.kt
jetbrains-academy
515,621,972
false
{"Kotlin": 123026, "TeX": 51581, "Java": 3566, "Python": 1156, "CSS": 671}
import kotlin.math.max private class PalindromicSubsequenceFinder(private val seq: CharSequence) { companion object { const val PLACEHOLDER = -1 } val longest = Array(seq.length) { IntArray(seq.length) { PLACEHOLDER } } private fun calculateLongest(left: Int, right: Int): Int { if (left >= right) return 0 if (left + 1 == right) return 1 if (longest[left][right - 1] != PLACEHOLDER) { return longest[left][right - 1] } var res = max(calculateLongest(left + 1, right), calculateLongest(left, right - 1)) if (seq[left] == seq[right - 1]) { res = max(res, calculateLongest(left + 1, right - 1) + 2) } longest[left][right - 1] = res return res } private fun getLongest(left: Int, right: Int, subSeq: Appendable) { if (left >= right) return if (left + 1 == right) { subSeq.append(seq[left]) return } when (calculateLongest(left, right)) { calculateLongest(left + 1, right) -> { getLongest(left + 1, right, subSeq) } calculateLongest(left, right - 1) -> { getLongest(left, right - 1, subSeq) } else -> { // length == calculateLongest(left + 1, right - 1) + 2 subSeq.append(seq[left]) getLongest(left + 1, right - 1, subSeq) subSeq.append(seq[right - 1]) } } } fun find(): CharSequence { if (seq.isEmpty()) { return "" } val result = StringBuilder() getLongest(0, seq.length, result) return result } } fun findLongestPalindromicSubsequence(seq: CharSequence): CharSequence { return PalindromicSubsequenceFinder(seq).find() }
2
Kotlin
0
10
a278b09534954656175df39601059fc03bc53741
1,837
algo-challenges-in-kotlin
MIT License
aoc/src/main/kotlin/com/bloidonia/aoc2023/day15/Main.kt
timyates
725,647,758
false
{"Kotlin": 45518, "Groovy": 202}
package com.bloidonia.aoc2023.day15 import com.bloidonia.aoc2023.text import kotlin.streams.asSequence private const val example = "rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7" private fun score(s: String) = s.chars().asSequence().fold(0L) { acc, n -> ((acc + n) * 17).mod(256L) } private fun part1(input: String) = input.split(",").map(::score).sum() private data class Lens(val key: String, val length: Long?) { val box by lazy { score(key) } companion object { private val regex = Regex("""(\w+)(?:[=-](\d*))""") operator fun invoke(s: String) = regex.matchEntire(s)!!.let { val (key, length) = it.destructured Lens(key, length.toLongOrNull()) } } } private data class Box(val lenses: List<Lens> = listOf()) { fun score() = lenses.mapIndexed { index, lens -> (index + 1) * lens.length!! } } private data class Lenses(val boxes: Map<Int, Box> = (0..255).associateWith { Box() }) { fun score() = boxes.flatMap { boxEntry -> boxEntry.value.score().map { score -> (boxEntry.key + 1) * score } }.sum() fun apply(lens: Lens): Lenses { val box = boxes[lens.box.toInt()]!! val lenses = box.lenses.toMutableList() if (lens.length == null) { lenses.removeAll { it.key == lens.key } } else if (lenses.any { it.key == lens.key }) { lenses.replaceAll { if (it.key == lens.key) lens else it } } else { lenses.add(lens) } return Lenses(boxes + (lens.box.toInt() to Box(lenses))) } } private fun part2(input: String) = input.split(",") .fold(Lenses()) { lenses: Lenses, lens: String -> lenses.apply(Lens.invoke(lens)) }.let { lenses -> println(lenses.score()) } fun main() { println(score("rn")) println(part1(example)) println(part1(text("/day15.input"))) part2(example) part2(text("/day15.input")) }
0
Kotlin
0
0
158162b1034e3998445a4f5e3f476f3ebf1dc952
1,941
aoc-2023
MIT License
src/Day09.kt
papichulo
572,669,466
false
{"Kotlin": 16864}
import kotlin.math.absoluteValue import kotlin.math.sign data class Point(val x: Int = 0, val y: Int = 0) { fun move(direction: Char): Point = when (direction) { 'U' -> copy(y = y - 1) 'D' -> copy(y = y + 1) 'L' -> copy(x = x - 1) 'R' -> copy(x = x + 1) else -> throw IllegalArgumentException() } fun moveTowards(other: Point): Point = Point( (other.x - x).sign + x, (other.y - y).sign + y ) fun touches(other: Point): Boolean = (x - other.x).absoluteValue <= 1 && (y - other.y).absoluteValue <= 1 } fun main() { fun followPath(path: String, knots: Int): Int { val rope = Array(knots) { Point() } val tailVisits = mutableSetOf(Point()) path.forEach { direction -> rope[0] = rope[0].move(direction) rope.indices.windowed(2, 1) { (head, tail) -> if (!rope[head].touches(rope[tail])) { rope[tail] = rope[tail].moveTowards(rope[head]) } } tailVisits += rope.last() } return tailVisits.size } fun getPathFromInput(input: List<String>): String { return input.joinToString("") { row -> val direction = row.substringBefore(" ") val numberOfMoves = row.substringAfter(" ").toInt() direction.repeat(numberOfMoves) } } fun part1(input: List<String>): Int { return followPath(getPathFromInput(input), 2) } fun part2(input: List<String>): Int { return followPath(getPathFromInput(input), 10) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) val testInput2 = readInput("Day09_test2") check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e277ee5bca823ce3693e88df0700c021e9081948
1,988
aoc-2022-in-kotlin
Apache License 2.0
src/Day04.kt
cornz
572,867,092
false
{"Kotlin": 35639}
fun main() { fun getUpperAndLowerBounds(input: String): Pair<Int, Int> { //2-4 val parts = input.split("-") val startIndex = parts[0].toInt() val endIndex = parts[1].toInt() return Pair(startIndex, endIndex) } fun intersection(input: String): Boolean { val intersections = arrayListOf<List<Int>>() val elements = input.split(",") //2-4, 3-5 for (element in elements) { val parts = element.split("-") val startIndex = parts[0].toInt() val endIndex = parts[1].toInt() val toBeIntersected = arrayListOf<Int>() for (i in startIndex..endIndex) { toBeIntersected.add(i) } intersections.add(toBeIntersected) } val numbers = intersections[0].intersect(intersections[1].toSet()) return numbers.isNotEmpty() } fun containsEachOther(input: List<String>): Int { var howManyPairs = 0 for (it in input) { val parts = it.split(",") val firstPart = getUpperAndLowerBounds(parts[0]) val secondPart = getUpperAndLowerBounds(parts[1]) if ((firstPart.first >= secondPart.first && firstPart.second <= secondPart.second) || secondPart.first >= firstPart.first && secondPart.second <= firstPart.second ) { howManyPairs += 1 continue } } return howManyPairs } fun overlapEachOther(input: List<String>): Int { var howManyIntersections = 0 for (it in input) { if (intersection(it)) { howManyIntersections += 1 } } return howManyIntersections } fun part1(input: List<String>): Int { return containsEachOther(input) } fun part2(input: List<String>): Int { return overlapEachOther(input) } // test if implementation meets criteria from the description, like: val testInput = readInput("input/Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("input/Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2800416ddccabc45ba8940fbff998ec777168551
2,240
aoc2022
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day18.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution import kotlin.math.ceil open class Part18A : PartSolution() { private val pairPattern = Regex("""\[(\d+),(\d+)]""") private val numberPattern = Regex("""\d+""") private val doubleDigitPattern = Regex("""\d\d""") lateinit var numbers: List<String> override fun parseInput(text: String) { numbers = text.split("\n") } override fun compute(): Int { val number = add(numbers) return magnitude(number) } fun add(numbers: Iterable<String>): String { var left = numbers.first() for (right in numbers.drop(1)) { left = reduce("[$left,$right]") } return left } private tailrec fun reduce(number: String): String { var reduced = explode(number) if (reduced != number) { return reduce(reduced) } reduced = split(number) if (reduced != number) { return reduce(reduced) } return reduced } private fun explode(num: String): String { var i = 0 var number = num while (i < number.length) { val pair = pairPattern.find(number.substring(i)) ?: break var depth = number.substring(0, pair.range.first + i).count { it == '[' } depth -= number.substring(0, pair.range.first + i).count { it == ']' } if (depth < 4) { i += pair.range.last + 1 continue } val lAdd = pair.groupValues[1].toInt() val rAdd = pair.groupValues[2].toInt() var leftPart = number.substring(0, pair.range.first + i).reversed() var rightPart = number.substring(pair.range.last + i + 1) val left = numberPattern.find(leftPart) if (left != null) { leftPart = "${leftPart.substring(0, left.range.first)}${ (lAdd + left.value.reversed().toInt()).toString().reversed() }${leftPart.substring(left.range.last + 1)}" } val right = numberPattern.find(number.substring(pair.range.last + i + 1)) if (right != null) { rightPart = "${rightPart.substring(0, right.range.first)}${rAdd + right.value.toInt()}${ rightPart.substring(right.range.last + 1) }" } number = "${leftPart.reversed()}0${rightPart}" break } return number } fun split(number: String): String { val regularNum = doubleDigitPattern.find(number) ?: return number val left = regularNum.value.toInt() / 2 val right = ceil(regularNum.value.toDouble() / 2).toInt() return "${number.substring(0, regularNum.range.first)}[$left,$right]${ number.substring(regularNum.range.last + 1)}" } fun magnitude(num: String): Int { var number = num while (true) { val pair = pairPattern.find(number) ?: return number.toInt() val mag = 3 * pair.groupValues[1].toInt() + 2 * pair.groupValues[2].toInt() number = "${number.substring(0, pair.range.first)}$mag${number.substring(pair.range.last + 1)}" } } override fun getExampleAnswer(): Int { return 4230 } } class Part18B : Part18A() { override fun compute(): Int { val magnitudes = mutableListOf<Int>() for (pair in permutations(numbers)) { val number = add(pair.toList()) magnitudes.add(magnitude(number)) } return magnitudes.max() } private fun permutations(list: List<String>): Iterable<Pair<String, String>> { return buildList { for (first in list) { for (second in list) { if (first != second) { add(first to second) } } } } } override fun getExampleAnswer(): Int { return 4647 } } fun main() { Day(2021, 18, Part18A(), Part18B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
4,150
advent-of-code-kotlin
MIT License
jk/src/main/kotlin/leetcode/Solution_LeetCode_215_347_Heap_Related.kt
lchang199x
431,924,215
false
{"Kotlin": 86230, "Java": 23581}
package leetcode import java.util.* /** * 堆相关的一些题目解法 */ class Solution_LeetCode_215_347_Heap_Related { /** * 数组中第k大元素: LeetCode_215 * [](https://leetcode-cn.com/problems/kth-largest-element-in-an-array/) * * 另堆排序解法 */ fun findKthLargest(nums: IntArray, k: Int): Int { val queue = PriorityQueue<Int>(k) nums.forEach { queue.offer(it) if (queue.size > k) queue.poll() } return queue.peek() } /** * 数组中第k大元素: LeetCode_215 * [](https://leetcode-cn.com/problems/kth-largest-element-in-an-array/) * * 另堆排序解法 */ fun findKthLargest2(nums: IntArray, k: Int): Int { val minHeap = PriorityQueue<Int>(k) nums.forEach { if (minHeap.size < k) minHeap.offer(it) else if (minHeap.peek() < it) { minHeap.poll() minHeap.offer(it) } } return minHeap.peek() } /** * 前k个高频元素:LeetCode_347 * [](https://leetcode-cn.com/problems/top-k-frequent-elements/) */ fun topKFrequent(nums: IntArray, k: Int): IntArray { val queue = PriorityQueue<IntArray> { o1, o2 -> o1[1] - o2[1] } val map = hashMapOf<Int, Int>().apply { nums.forEach { put(it, this.getOrDefault(it, 0) + 1) } }.forEach { // 固定处理模式:先offer,看size是不是比k大,实际上queue的大小永远时k+1 queue.offer(intArrayOf(it.key, it.value)) if (queue.size > k) { queue.poll() } } return queue.map { it[0] }.toIntArray() } /** * 前k个高频元素:LeetCode_347 * [](https://leetcode-cn.com/problems/top-k-frequent-elements/) */ fun topKFrequent2(nums: IntArray, k: Int): IntArray { // Map.Entry<Int, Int>占用的存储空间应该比IntArray大一点?处理慢一点? val queue = PriorityQueue<Map.Entry<Int, Int>> { o1, o2 -> o1.value - o2.value } hashMapOf<Int, Int>().apply { nums.forEach { put(it, this.getOrDefault(it, 0) + 1) } }.forEach { queue.offer(it) if (queue.size > k) { queue.poll() } } return queue.map { it.key }.toIntArray() } } fun main() { println(Solution_LeetCode_215_347_Heap_Related().findKthLargest(intArrayOf(1, 2, 2, 3, 5, 4, 7), 3)) println(Solution_LeetCode_215_347_Heap_Related().findKthLargest2(intArrayOf(1, 2, 2, 3, 5, 4, 7), 3)) println(Solution_LeetCode_215_347_Heap_Related().topKFrequent(intArrayOf(1, 1, 2, 2, 3, 5, 4, 4, 4, 7), 3).contentToString()) println(Solution_LeetCode_215_347_Heap_Related().topKFrequent2(intArrayOf(1, 1, 2, 2, 3, 5, 4, 4, 4, 7), 3).contentToString()) }
0
Kotlin
0
0
52a008325dd54fed75679f3e43921fcaffd2fa31
3,018
Codelabs
Apache License 2.0
src/Day21.kt
sitamshrijal
574,036,004
false
{"Kotlin": 34366}
fun main() { fun parse(input: List<String>): List<Job> = input.map { Job.parse(it) } fun part1(input: List<String>): Long { val jobs = parse(input) val monkeys = jobs.associateBy { it.monkey } monkeys.values.filterIsInstance<Job.Operate>().forEach { operateJob -> operateJob.job1 = monkeys[operateJob.monkey1]!! operateJob.job2 = monkeys[operateJob.monkey2]!! } val root = jobs.first { it.monkey == "root" } return root.yell() } fun part2(input: List<String>): Int { return input.size } val input = readInput("input21") println(part1(input)) println(part2(input)) } enum class Operation { ADD, SUBTRACT, MULTIPLY, DIVIDE } sealed interface Job { val monkey: String fun yell(): Long data class Yell(override val monkey: String, val number: Long) : Job { override fun yell(): Long = number } data class Operate( override val monkey: String, val monkey1: String, val monkey2: String, val operation: Operation ) : Job { lateinit var job1: Job lateinit var job2: Job override fun yell(): Long = when (operation) { Operation.ADD -> job1.yell() + job2.yell() Operation.SUBTRACT -> job1.yell() - job2.yell() Operation.MULTIPLY -> job1.yell() * job2.yell() Operation.DIVIDE -> job1.yell() / job2.yell() } } companion object { fun parse(input: String): Job { val (monkey, job) = input.split(": ") return when { job.all { it.isDigit() } -> Yell(monkey, job.toLong()) "+" in job -> { val (monkey1, monkey2) = job.split(" + ") Operate(monkey, monkey1, monkey2, Operation.ADD) } "-" in job -> { val (monkey1, monkey2) = job.split(" - ") Operate(monkey, monkey1, monkey2, Operation.SUBTRACT) } "*" in job -> { val (monkey1, monkey2) = job.split(" * ") Operate(monkey, monkey1, monkey2, Operation.MULTIPLY) } "/" in job -> { val (monkey1, monkey2) = job.split(" / ") Operate(monkey, monkey1, monkey2, Operation.DIVIDE) } else -> error("Error!") } } } }
0
Kotlin
0
0
fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d
2,492
advent-of-code-2022
Apache License 2.0
src/Day10/Day10.kt
G-lalonde
574,649,075
false
{"Kotlin": 39626}
package Day10 import readInput fun main() { data class Instruction(val cycle: Int, val increment: Int) fun execute(instruction: String): Instruction { if (instruction == "noop") { return Instruction(1, 0) } val (_, increment) = instruction.split(" ") return Instruction(2, increment.toInt()) } fun part1(input: List<String>): Int { var X = 1 var cycle = 0 val cycleCheck = intArrayOf(20, 60, 100, 140, 180, 220) val signalStrength = mutableListOf<Int>() for (instruction in input) { val (cycleIncrement, increment) = execute(instruction) for (i in 0 until cycleIncrement) { cycle += 1 if (cycle in cycleCheck) { signalStrength.add(cycle * X) } } X += increment } return signalStrength.sum() } fun part2(input: List<String>): Int { var X = 1 var cycle = 0 val sprite = mutableListOf<Char>() for (instruction in input) { val (cycleIncrement, increment) = execute(instruction) for (i in 0 until cycleIncrement) { val CRT = listOf(X - 1, X, X + 1) sprite.add(if (cycle % 40 in CRT) '|' else ' ') cycle += 1 } X += increment } for (i in intArrayOf(40, 80, 120, 160, 200, 240)) { println(sprite.subList(i - 40, i).joinToString("")) } return 2 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10/Day10_test") check(part1(testInput) == 13140) { "Got instead : ${part1(testInput)}" } // check(part2(testInput) == 2) { "Got instead : ${part2(testInput)}" } val input = readInput("Day10/Day10") println("Answer for part 1 : ${part1(input)}") println("Answer for part 2 : \n${part2(input)}") }
0
Kotlin
0
0
3463c3228471e7fc08dbe6f89af33199da1ceac9
1,995
aoc-2022
Apache License 2.0
src/Day07.kt
orirabi
574,124,632
false
{"Kotlin": 14153}
enum class FillUpState { NOT_INIT, IN_PROGRESS, FULL } data class Dir( val parent: Dir?, val name: String, var fillUpState: FillUpState = FillUpState.NOT_INIT, val files: MutableList<File> = mutableListOf(), val directories: MutableList<Dir> = mutableListOf(), ) { val size: Int by lazy { files.sumOf { it.size } + directories.sumOf { it.size } } } data class File(val name: String, val size: Int) val root = Dir( parent = null, name = "/", ) var currentDir = root fun main() { fun changeDirectory(arg: String) { currentDir = when (arg) { root.name -> root ".." -> currentDir.parent ?: currentDir else -> currentDir.directories.single { it.name == arg } } } fun listContents(terminal: List<String>, i: Int): Int { currentDir.fillUpState = FillUpState.IN_PROGRESS val listIterator = terminal.listIterator(i + 1) while (listIterator.hasNext()) { val current = listIterator.next() if (current.startsWith("$")) { currentDir.fillUpState = FillUpState.FULL return listIterator.previousIndex() } if (currentDir.fillUpState != FillUpState.FULL) { val split = current.split(" ") when { split[0] == "dir" -> currentDir.directories.add(Dir(currentDir, split[1])) else -> currentDir.files.add(File(split[1], split[0].toInt())) } } } currentDir.fillUpState = FillUpState.FULL return listIterator.nextIndex() } fun parseTerminal(terminal: List<String>) { var i = 0 while (i < terminal.size) { val currentCommand = terminal[i].split(" ") println ("Parsing index $i command: $currentCommand") i = when (currentCommand[1]) { "cd" -> { changeDirectory(currentCommand[2]) i + 1 } "ls" -> listContents(terminal, i) else -> throw IllegalStateException("Cannot handle command $currentCommand") } println("Next index is $i") } } fun iterateAllSubDirs(dir: Dir = root, toIterate: MutableList<Dir> = mutableListOf()): MutableList<Dir> { toIterate.add(dir) dir.directories.forEach {iterateAllSubDirs(it, toIterate)} return toIterate } fun getSumSizeLeq100K(): Int { return iterateAllSubDirs().asSequence() .map { it.size } .filter { it <= 100000 } .sum() } fun getSmallestDirToDelete(): Int { val maxSize = 40000000 return iterateAllSubDirs().asSequence() .map { it.size } .filter { root.size - it <= maxSize } .min() } val input = readInput("Day07") parseTerminal(input) println(getSumSizeLeq100K()) println(getSmallestDirToDelete()) }
0
Kotlin
0
0
41cb10eac3234ae77ed7f3c7a1f39c2f9d8c777a
3,004
AoC-2022
Apache License 2.0
src/day3/Day03.kt
blundell
572,916,256
false
{"Kotlin": 38491}
package day3 import readInput fun main() { /** * https://theasciicode.com.ar/ */ fun Char.toElfIndex() = if (isLowerCase()) { (code - 96) } else { (code - 38) } /** * Lowercase item types a through z have priorities 1 through 26. * Uppercase item types A through Z have priorities 27 through 52. * * Find the item type that appears in both compartments of each rucksack. * What is the sum of the priorities of those item types? */ fun part1(input: List<String>): Int { return input.map { val leftCompartment = it.take(it.length / 2) val rightCompartment = it.substring(it.length / 2) var dupe = ' ' for (c in leftCompartment) { for (rC in rightCompartment) { if (rC == c) { dupe = c } } } dupe }.sumOf { it.toElfIndex() } } fun part2(input: List<String>): Int { return input.chunked(3) .map { for (a in it[0]) { for (b in it[1]) { for (c in it[2]) { if (a == b && b == c) { return@map a.toElfIndex().also { n -> println("F $a $n") } } } } } throw IllegalStateException("No match!") } .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("day3/Day03_test") check(part2(testInput) == 70) { "[${part2(testInput)}] is wrong." } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f41982912e3eb10b270061db1f7fe3dcc1931902
1,847
kotlin-advent-of-code-2022
Apache License 2.0
src/Day03.kt
iProdigy
572,297,795
false
{"Kotlin": 33616}
fun main() { fun part1(input: List<String>): Int = input .map { it.chunked(it.length / 2, CharSequence::toSet) } .map { (a, b) -> a.first { it in b } } .sumOf(::priority) fun part2(input: List<String>): Int = input .map { it.toSet() } .chunked(3) .map { (a, b, c) -> a.first { it in b && it in c } } .sumOf(::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)) // 7742 println(part2(input)) // 2276 } private fun priority(c: Char): Int = 1 + if (c in 'a'..'z') c - 'a' else c - 'A' + 26
0
Kotlin
0
1
784fc926735fc01f4cf18d2ec105956c50a0d663
764
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/tonnoz/adventofcode23/day11/Day11.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day11 import com.tonnoz.adventofcode23.utils.readInput import com.tonnoz.adventofcode23.utils.toCharMatrix import kotlin.system.measureTimeMillis const val FIRST_CHAR = 47 // starting from 47 because 46 it's '.' which was causing problems object Day11 { @JvmStatic fun main(args: Array<String>) { val input = "input11.txt".readInput().toCharMatrix() val time = measureTimeMillis { val (universe, galaxyPairs) = createUniverseAndGalaxyPairs(input) val galaxyPairsWithDistance = updateGalaxyPairsWithDistances(galaxyPairs, universe) println("Part1: ${galaxyPairsWithDistance.sumOf { it.distance }}") } println("P1 time: $time ms") } data class Galaxy(val row: Int, val column: Int, val value: Char) data class GalaxyPair(val a: Galaxy, val b: Galaxy, val distance: Int = 0) private fun updateGalaxyPairsWithDistances(galaxyPairs: Set<GalaxyPair>, universe: List<List<Galaxy>>) = galaxyPairs.map { addDistanceToGalaxyPair(it, universe) }.toSet() private fun addDistanceToGalaxyPair(it: GalaxyPair, universe: List<List<Galaxy>>) = it.copy(a = it.a, b = it.b, distance = it.calculateDistanceBetween(universe)) private fun GalaxyPair.calculateDistanceBetween(universe: List<List<Galaxy>>): Int { val (smallICol, bigICol) = listOf(this.a.column, this.b.column).sorted() val (smallIRow, bigIRow) = listOf(this.a.row, this.b.row).sorted() val expandedSpaceRow = countNrExpandedSpace(smallIRow, bigIRow, universe, ::isExpandedSpacesRow) val expandedSpaceColumn = countNrExpandedSpace(smallICol, bigICol, universe, ::isExpandedSpacesColumn) val rowDistance = bigIRow - smallIRow + expandedSpaceRow val colDistance = bigICol - smallICol + expandedSpaceColumn return colDistance + rowDistance } private fun countNrExpandedSpace(smallI: Int, bigI: Int, universe: List<List<Galaxy>>, isExpandedFunction: (List<List<Galaxy>>, Int) -> Int)= (smallI..<bigI).sumOf { isExpandedFunction(universe, it) } private fun Boolean.toInt() = if(this) 1 else 0 private fun isExpandedSpacesRow(universe:List<List<Galaxy>>, row: Int) = universe[row].all { it.value == '.' }.toInt() private fun isExpandedSpacesColumn(universe: List<List<Galaxy>>, col: Int) = universe.all { it[col].value == '.' }.toInt() private fun List<List<Galaxy>>.findGalaxy(aChar: Char) : Galaxy { this.forEach { it.forEach { galaxy -> if(galaxy.value == aChar) return galaxy } } throw IllegalArgumentException("Not possible to find galaxy with char $aChar") } private fun createUniverseAndGalaxyPairs(input: ArrayList<CharArray>): Pair<List<List<Galaxy>>, Set<GalaxyPair>> { var counter = FIRST_CHAR val universe = input.mapIndexed { rowI, row -> row.mapIndexed { columnI, aChar -> if (aChar == '#') Galaxy(rowI, columnI, counter++.toChar()) else Galaxy(rowI, columnI, aChar) }} return Pair(universe, createGalaxyPairs(counter, universe)) } private fun createGalaxyPairs(counter: Int, universe: List<List<Galaxy>>): Set<GalaxyPair> { val galaxyPairs = mutableSetOf<GalaxyPair>() for (i in FIRST_CHAR..<counter) { for (j in i..<counter) { if (i != j) galaxyPairs.add(GalaxyPair(universe.findGalaxy(i.toChar()), universe.findGalaxy(j.toChar()))) } } return galaxyPairs.toSet() } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
3,347
adventofcode23
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2021/day12/day12.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day12 import biz.koziolek.adventofcode.* fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val graph = parseCavesGraph(lines) val paths1 = findAllPaths(graph, ::visitSmallCavesOnlyOnce) println("There is ${paths1.size} possible paths when visiting small caves only once") val paths2 = findAllPaths(graph, ::visitAtMostOneSmallCaveTwice) println("There is ${paths2.size} possible paths when visiting at most one small cave twice") } sealed interface CaveNode : GraphNode object StartCave : CaveNode { override val id = "start" override fun toGraphvizString(exactXYPosition: Boolean, xyPositionScale: Float) = "node [shape=box]; $id;" override fun toString() = "${javaClass.simpleName}(id=$id)" } object EndCave : CaveNode { override val id = "end" override fun toGraphvizString(exactXYPosition: Boolean, xyPositionScale: Float) = "node [shape=box]; $id;" override fun toString() = "${javaClass.simpleName}(id=$id)" } data class BigCave(override val id: String) : CaveNode { override fun toGraphvizString(exactXYPosition: Boolean, xyPositionScale: Float) = "node [shape=doublecircle]; $id;" } data class SmallCave(override val id: String) : CaveNode { override fun toGraphvizString(exactXYPosition: Boolean, xyPositionScale: Float) = "node [shape=circle]; $id;" } fun parseCavesGraph(lines: List<String>): Graph<CaveNode, BiDirectionalGraphEdge<CaveNode>> { return lines.fold(Graph()) { graph, line -> val (node1Id, node2Id) = line.split('-', limit = 2) val edge = BiDirectionalGraphEdge(createNode(node1Id), createNode(node2Id)) graph.addEdge(edge) } } private fun createNode(id: String): CaveNode = when (id) { "start" -> StartCave "end" -> EndCave id.uppercase() -> BigCave(id) id.lowercase() -> SmallCave(id) else -> throw IllegalArgumentException("Unknown cave ID: $id") } fun findAllPaths(graph: Graph<CaveNode, BiDirectionalGraphEdge<CaveNode>>, smallCaveVisitDecider: (SmallCave, List<CaveNode>) -> Boolean): Set<List<CaveNode>> { return buildSet { var incompletePaths: List<List<CaveNode>> = listOf(listOf(StartCave)) while (incompletePaths.isNotEmpty()) { incompletePaths = incompletePaths.flatMap { path -> graph.getAdjacentNodes(path.last()) .flatMap { node -> when (node) { is StartCave -> emptySet() is EndCave -> { add(path + node) emptySet() } is BigCave -> setOf(path + node) is SmallCave -> { if (smallCaveVisitDecider(node, path)) { setOf(path + node) } else { emptySet() } } } } } } } } fun visitSmallCavesOnlyOnce(cave: SmallCave, path: List<CaveNode>) = cave !in path fun visitAtMostOneSmallCaveTwice(cave: SmallCave, path: List<CaveNode>): Boolean { val eachCount = path.filterIsInstance<SmallCave>() .groupingBy { it } .eachCount() val thisCaveVisits = eachCount.getOrDefault(cave, 0) val anyCaveVisitedTwice = eachCount.any { it.value == 2 } return (thisCaveVisits == 0) || (!anyCaveVisitedTwice && thisCaveVisits < 2) }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
3,699
advent-of-code
MIT License
src/main/kotlin/days/Day19.kt
mstar95
317,305,289
false
null
package days import arrow.core.extensions.list.foldable.isNotEmpty class Day19 : Day(19) { override fun partOne(): Any { val (grammars, words) = prepareInput(inputList) val map = words.map { parse(grammars, it, grammars[0]!!) } // println(map) return map.filter { it.isNotEmpty() && it[0].isEmpty() }.size } //451 za duza //270 za malo private fun parse(grammars: Map<Int, Grammar>, word: String, grammar: Grammar): List<String> { // println("${word.length} $grammar $word ") if (word.isEmpty()) { return emptyList() } return when (grammar) { is Literal -> { val literal = word.first() return if (literal == grammar.value) { listOf(word.drop(1)) } else { emptyList() } } is Rule -> grammar.left.fold(listOf(word)) { w: List<String>, id: Int -> w.flatMap { parse(grammars, it, grammars[id]!!) } } + (grammar.right?.fold(listOf(word)) { w: List<String>, id: Int -> w.flatMap { parse(grammars, it, grammars[id]!!) } } ?: emptyList()) } } override fun partTwo(): Any { return 0 } private fun prepareInput(input: List<String>): Pair<Map<Int, Grammar>, List<String>> { val grammars = mutableMapOf<Int, Grammar>() val messages = mutableListOf<String>() input.forEach { row -> if (row.contains(":")) { val splitted: List<String> = row.split(": ") val key = splitted[0].toInt() val rest = splitted[1] grammars[key] = prepareGrammar(rest, key) } else { if (row.isNotEmpty()) { messages.add(row) } } } grammars[8] = Rule(8, listOf(42), listOf(42, 8)) grammars[11] = Rule(11, listOf(42, 31), listOf(42, 11, 31)) return grammars.toMap() to messages.toList() } private fun prepareGrammar(rest: String, key: Int) = if (rest.contains("\"")) { Literal(key, rest[1]) } else { val rules: List<List<Int>> = rest.split(" | ").map { it.split(" ").map { it.toInt() } } Rule(key, rules[0], rules.getOrNull(1)) } } private sealed class Grammar private data class Literal(val id: Int, val value: Char) : Grammar() private data class Rule(val id: Int, val left: List<Int>, val right: List<Int>?) : Grammar() //Rule(id=31, left=[14, 17], right=[1, 13]) bbbbbaabaaabaaa //Rule(id=11, left=[42, 31], right=[42, 11, 31]) bbbbbaabaaabaaa //Rule(id=8, left=[42], right=[42, 8]) aaaaabbaabaaaaababaa // 11: bbaabaaaaababaa //42- bbaab //41 - aaaaababaa //aaaaababaa //babaa
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
2,822
aoc-2020
Creative Commons Zero v1.0 Universal
Create-an-euphonious-word/src/main/kotlin/Main.kt
victorYghor
610,409,660
false
null
val vowels: List<Char> = listOf('a', 'e', 'i', 'o', 'u', 'y') val consonants: List<Char> = listOf('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z') fun fixClusterVowels(cluster: String): String { val listOfVowels: MutableList<Char> = cluster.toMutableList() val correctionI = listOfVowels.size / 2 for (i in 2 until(listOfVowels.lastIndex + correctionI) step 3) { listOfVowels.add(i, consonants.random()) } return listOfVowels.joinToString("") } fun fixClusterConsonants(cluster:String): String { val listOfConsonants: MutableList<Char> = cluster.toMutableList() val correctionI = listOfConsonants.size / 2 for (i in 2 until(listOfConsonants.lastIndex + correctionI) step 3) { // start in the index 2 because a vowel is put in the 3rd element if a put index 3 the word fit in the 4th and don't solve the problem listOfConsonants.add(i, vowels.random()) } return listOfConsonants.joinToString("") } fun findClusters(word: String): List<Int?> { val clusterIndices: List<Int?> for (i in word.indices) { var quantV = 0 do { if (vowels.contains(word[i + quantV]) && i + quantV + 1 <= word.lastIndex) { ++quantV } else if (i + quantV == word.lastIndex && vowels.contains(word[i + quantV])) { ++quantV } } while (i + quantV <= word.lastIndex && vowels.contains(word[i + quantV])) if (quantV >= 3) { clusterIndices = listOf(i, i + quantV) return clusterIndices } var quantC = 0 do { if (consonants.contains(word[i + quantC]) && i + quantC + 1 <= word.lastIndex) { ++quantC } else if (i + quantC == word.lastIndex && consonants.contains(word[i + quantC])) { ++quantC } } while (i + quantC <= word.lastIndex && consonants.contains(word[i + quantC])) if (quantC >= 3) { clusterIndices = listOf(i, i + quantC) return clusterIndices } } clusterIndices = listOf(null) return clusterIndices } fun solveClusters(wordParam: String): String { var word = wordParam var indexCluster = findClusters(word) while (indexCluster[0] != null) { val cluster: String = word.substring(indexCluster[0] ?: 0, indexCluster[1] ?: 0) if (vowels.contains(cluster[0])) { val fixedCluster = fixClusterVowels(cluster) word = word.replaceFirst(cluster, fixedCluster) indexCluster = findClusters(word) } else if (consonants.contains(cluster[0])) { val fixedCluster = fixClusterConsonants(cluster) word = word.replaceFirst(cluster, fixedCluster) indexCluster = findClusters(word) } else { break } } return word } fun main() { val word = readln() println(solveClusters(word)) println(solveClusters(word).length - word.length) } /* val vowels: List<Char> = listOf('a', 'e', 'i', 'o', 'u', 'y') val consonants: List<Char> = listOf('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z') fun findClusters(word: String):MutableList<Int?> { val sizesOfClusters: MutableList<Int?> = mutableListOf() var countV = 2 var countC = 2 var lastLetter: Char? = null var nextToLetter: Char? = null for (letter in word) { if (vowels.contains(letter) && (if (lastLetter != null ) vowels.contains(lastLetter) else false) && vowels.contains(nextToLetter)) { ++countV } else if (consonants.contains(letter) && (if (lastLetter != null ) consonants.contains(lastLetter) else false) && consonants.contains(nextToLetter)){ ++countC } else if (countV >= 3) { sizesOfClusters.add(countV) countV = 2 } else if (countC >= 3) { sizesOfClusters.add(countC) countC = 2 } nextToLetter = lastLetter lastLetter = letter } if (countV >= 3) { sizesOfClusters.add(countV) } else if (countC >= 3) { sizesOfClusters.add(countC) } return sizesOfClusters } fun lettersToPut(clusters: MutableList<Int?>): Int { if (clusters.size == 0) { return 0 } for (i in clusters.indices) { if (clusters[i]!! % 2 == 0 ) { clusters[i] = clusters[i]!! / 2 - 1 } else if (clusters[i]!! % 2 == 1) { clusters[i] = clusters[i]!! / 2 } } var sum = 0 for (size in clusters){ sum += size!! } return sum } fun main() { val word = readln() println(lettersToPut(findClusters(word))) } */
0
Kotlin
0
0
0d30e37016cd2158d87de59f7cf17125627fc785
4,786
Kotlin-Problems
MIT License
src/Day08.kt
msernheim
573,937,826
false
{"Kotlin": 32820}
fun main() { fun getWest(row: String, until: Int): List<Int> { if (until > 0) { return row.substring(0, until).map { c -> c.digitToInt() } } return emptyList() } fun getEast(row: String, start: Int): List<Int> { if (start < row.length) { return row.substring(start).map { c -> c.digitToInt() } } return emptyList() } fun getNorth(grid: List<String>, max: Int, j: Int): List<Int> { if (max > 0) { val north = mutableListOf<Int>() for (k in 0 until max) { val vertDirTree = grid[k][j].digitToInt() north.add(vertDirTree) } return north } return emptyList() } fun getSouth(grid: List<String>, min: Int, j: Int): List<Int> { if (min < grid.size) { val south = mutableListOf<Int>() for (k in min until grid.size) { val vertDirTree = grid[k][j].digitToInt() south.add(vertDirTree) } return south } return emptyList() } fun isVisibleHorizontally(row: String, j: Int): Boolean { val tree = row[j].digitToInt() return tree > getWest(row, j).max() || tree > getEast(row, j + 1).max() } fun isVisibleVertically(grid: List<String>, i: Int, j: Int): Boolean { val tree = grid[i][j].digitToInt() return tree > getNorth(grid, i, j).max() || tree > getSouth(grid, i + 1, j).max() } fun part1(grid: List<String>): Int { val edge: Int = grid.size - 1 var visibles = 0 for (i in grid.indices) { when (i) { 0 -> visibles += grid[i].length edge -> visibles += grid[i].length else -> { for (j in grid[i].indices) { when (j) { 0 -> visibles += 1 grid[i].length - 1 -> visibles += 1 else -> { if (isVisibleHorizontally(grid[i], j) || isVisibleVertically(grid, i, j)) { visibles += 1 } } } } } } } return visibles } fun countTrees(treeHeight: Int, treeLine: List<Int>): Int { return when (treeLine.size) { 0 -> 0 1 -> 1 else -> { for (i in treeLine.indices) { if (treeHeight <= treeLine[i]) return i + 1 } return treeLine.size } } } fun getScore(treeHeight: Int, west: List<Int>, east: List<Int>, north: List<Int>, south: List<Int>): Int { var score = 1 score *= countTrees(treeHeight, west.reversed()) score *= countTrees(treeHeight, east) score *= countTrees(treeHeight, north.reversed()) score *= countTrees(treeHeight, south) return score } fun part2(grid: List<String>): Int { var highscore = 0 for (i in grid.indices) { for (j in grid[i].indices) { val score = getScore( grid[i][j].digitToInt(), getWest(grid[i], j), getEast(grid[i], j + 1), getNorth(grid, i, j), getSouth(grid, i + 1, j) ) highscore = if (score > highscore) score else highscore } } return highscore } val input = readInput("Day08") val part1 = part1(input) val part2 = part2(input) println("Result part1: $part1") println("Result part2: $part2") }
0
Kotlin
0
3
54cfa08a65cc039a45a51696e11b22e94293cc5b
3,836
AoC2022
Apache License 2.0
year2020/src/main/kotlin/net/olegg/aoc/year2020/day19/Day19.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2020.day19 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.parseInts import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2020.DayOf2020 import net.olegg.aoc.year2020.day19.Day19.Rule.CharRule import net.olegg.aoc.year2020.day19.Day19.Rule.RefRule /** * See [Year 2020, Day 19](https://adventofcode.com/2020/day/19) */ object Day19 : DayOf2020(19) { private val CHAR_RULE_PATTERN = "\"(.)\"".toRegex() override fun first(): Any? { val (rulesList, messages) = data.split("\n\n") val rules = rulesList .lines() .map { it.split(": ").toPair() } .associate { (num, rule) -> num.toInt() to when { CHAR_RULE_PATTERN.matches(rule) -> CharRule(rule.trim('\"').first()) else -> RefRule(rule.split('|').map { it.parseInts(" ") }) } } return solve(rules, messages.lines()) } override fun second(): Any? { val (rulesList, messages) = data.split("\n\n") val rules = rulesList .lines() .map { it.split(": ").toPair() } .map { (num, rule) -> num to when (num) { "8" -> "42 | 42 8" "11" -> "42 31 | 42 11 31" else -> rule } } .associate { (num, rule) -> num.toInt() to when { CHAR_RULE_PATTERN.matches(rule) -> CharRule(rule.trim('\"').first()) else -> RefRule(rule.split('|').map { it.parseInts(" ") }) } } return solve(rules, messages.lines()) } private fun solve( rules: Map<Int, Rule>, messages: List<String> ): Int { return messages.count { message -> val cache = mutableMapOf<Triple<Int, Int, Int>, Boolean>() fun matches( from: Int, to: Int, ruleNum: Int ): Boolean { fun matches( from: Int, to: Int, rules: List<Int> ): Boolean { return when (rules.size) { 0 -> false 1 -> matches(from, to, rules.first()) else -> (from + 1..<to).any { mid -> matches(from, mid, rules.first()) && matches(mid, to, rules.drop(1)) } } } return cache.getOrPut(Triple(from, to, ruleNum)) { when (val rule = rules[ruleNum]) { is CharRule -> to - from == 1 && message[from] == rule.char is RefRule -> rule.refs.any { matches(from, to, it) } else -> false } } } return@count matches(0, message.length, 0) } } sealed class Rule { data class CharRule(val char: Char) : Rule() data class RefRule(val refs: List<List<Int>>) : Rule() } } fun main() = SomeDay.mainify(Day19)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,709
adventofcode
MIT License
src/Day09.kt
monsterbrain
572,819,542
false
{"Kotlin": 42040}
import kotlin.math.abs import kotlin.math.sign class Point(val x: Int, val y: Int) { override fun toString(): String { return "[$x,$y]" } override fun equals(other: Any?): Boolean { return x == (other as Point).x && y == (other as Point).y } } class Node(var x: Int, var y: Int, val name: String) { val visitedNodes = ArrayList<Point>() fun follow(head: Node) { if (abs(head.x - x) + abs(head.y - y) > 2) { // println("head diagonally far") x += (head.x - x).sign y += (head.y - y).sign // println("move $name by ${(head.x - x).sign}, ${(head.y - y).sign}") } else if (abs(head.x - x) > 1) { // println("move $name ${(head.x - x).sign}") x += (head.x - x).sign } else if (abs(head.y - y) > 1) { // println("move $name ${(head.y - y).sign}") y += (head.y - y).sign } visited() } fun visited() { visitedNodes.find { it.x == x && it.y == y }?: visitedNodes.add(Point(x,y)) } } fun main() { fun part1(input: List<String>): Int { val headPos = Node(0, 0, "H") val tailPos = Node(0, 0, "T") tailPos.visited() // add 0, 0 fun move(hor: Int, ver: Int, steps: Int) { repeat(steps) { headPos.x += hor headPos.y += ver // println("- tail at ${tailPos.x}, ${tailPos.y}") tailPos.follow(headPos) } } input.forEach { val (dir, steps) = it.split(" ") val stepDir = when (dir) { "R" -> Point(1, 0) "U" -> Point(0, -1) "L" -> Point(-1, 0) "D" -> Point(0, 1) else -> TODO() } // println("move $it") move(stepDir.x, stepDir.y, steps.toInt()) } return tailPos.visitedNodes.count() } fun part2(input: List<String>): Int { val headPos = Node(0, 0, "H") val tailList = arrayListOf<Node>().apply { repeat(9) { add(Node(0, 0, "${it+1}").apply { visited() }) } } fun move(hor: Int, ver: Int, steps: Int) { repeat(steps) { headPos.x += hor headPos.y += ver // println("- tail at ${tailPos.x}, ${tailPos.y}") for (i in tailList.indices) { if (i==0) { tailList[0].follow(headPos) } else { tailList[i].follow(tailList[i-1]) } } } } input.forEach { val (dir, steps) = it.split(" ") val stepDir = when (dir) { "R" -> Point(1, 0) "U" -> Point(0, -1) "L" -> Point(-1, 0) "D" -> Point(0, 1) else -> TODO() } // println("move $it") move(stepDir.x, stepDir.y, steps.toInt()) } return tailList.last().visitedNodes.count() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val test1Result = part1(testInput) check(test1Result == 13) val input = readInput("Day09") println(part1(input)) val testInput2 = readInput("Day09_test2") val test2Result = part2(testInput2) check(test2Result == 36) // val input = readInput("Day09") println(part2(input)) }
0
Kotlin
0
0
3a1e8615453dd54ca7c4312417afaa45379ecf6b
3,590
advent-of-code-kotlin-2022-Solutions
Apache License 2.0
src/day10/Day10.kt
pientaa
572,927,825
false
{"Kotlin": 19922}
package day10 import readLines fun main() { fun generateOperations(input: List<String>): List<Operation> = input.map { when { it.contains("noop") -> { Operation(1, 0) } it.contains("addx") -> { Operation(2, it.split(" ").last().toInt()) } else -> throw Exception() } } fun List<Operation>.calculateRegisterValues() = fold(mutableListOf(1)) { acc: MutableList<Int>, operation: Operation -> val currentX = acc.last() repeat(operation.cycles - 1) { acc.add(currentX) } acc.add(currentX + operation.toAdd) acc } fun part1(input: List<String>): Int { return generateOperations(input) .calculateRegisterValues() .mapIndexedNotNull { index, value -> if ((index - 19) % 40 == 0) (index + 1) * value else null } .sum() } fun part2(input: List<String>) { generateOperations(input) .calculateRegisterValues() .apply { removeAt(0) } .chunked(40) .fold(1) { previousLineLastRegisterValue, line -> var spriteRange = (1..3) line.foldIndexed(previousLineLastRegisterValue) { index: Int, _, next: Int -> if (index + 1 in spriteRange) print("#") else print(".") spriteRange = (next..next + 2) next } println() line.last() } } // test if implementation meets criteria from the description, like: val testInput = readLines("day10/Day10_test") val input = readLines("day10/Day10") println(part1(input)) part2(input) } data class Operation( val cycles: Int, val toAdd: Int )
0
Kotlin
0
0
63094d8d1887d33b78e2dd73f917d46ca1cbaf9c
1,875
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.io.Reader import java.util.* fun main() { val testInput = """ A Y B X C Z """.trimIndent() check( partOne(testInput.reader()) == 15 ) val input = file("Day02.txt") println(partOne(input.bufferedReader())) check( partTwo(testInput.reader()) == 12 ) println(partTwo(input.bufferedReader())) } private fun partOne(reader: Reader): Int { var tally = 0 reader.forEachLine { line -> val (opponent, me) = line.split(' ').map { RockPaperScissor.fromChar(it[0]) } tally += RockPaperScissor.play(me, opponent) } return tally } private fun partTwo(reader: Reader): Int { var tally = 0 reader.forEachLine { line -> val (opponentChar, neededResultChar) = line.split(' ').map { it[0] } val opponent = RockPaperScissor.fromChar(opponentChar) val me = when (neededResultChar.uppercaseChar()) { 'X' -> opponent.winsTo 'Y' -> opponent.drawsTo 'Z' -> opponent.losesTo else -> TODO() } tally += RockPaperScissor.play(me, opponent) } return tally } enum class RockPaperScissor(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); val drawsTo get() = this val winsTo get() = when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } val losesTo get() = when (this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } companion object { fun fromChar(character: Char): RockPaperScissor { return when (character.uppercaseChar()) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> TODO() } } private val resultLookupTable: Map<RockPaperScissor, Map<RockPaperScissor, Int>> = run { val result = mutableMapOf<RockPaperScissor, Map<RockPaperScissor, Int>>() result[ROCK] = mapOf( ROCK to 3, PAPER to 0, SCISSORS to 6 ) result[PAPER] = mapOf( ROCK to 6, PAPER to 3, SCISSORS to 0 ) result[SCISSORS] = mapOf( ROCK to 0, PAPER to 6, SCISSORS to 3 ) result } fun getResult(x: RockPaperScissor, y: RockPaperScissor): Int { return resultLookupTable[x]!![y]!! } fun play(me: RockPaperScissor, opponent: RockPaperScissor): Int { return me.score + getResult(me, opponent) } } }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
2,717
advent-of-code-2022-kotlin
Apache License 2.0
codeforces/kotlinheroes3/h.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.kotlinheroes3 private fun solve() { val s = readLn() val inf = (s.maxOrNull()!! + 1).toString() val init = listOf(listOf(inf to listOf<Boolean>()), listOf("" to listOf())) val ans = s.foldIndexed(init) { i, (sure, unsure), c -> val next = List(2) { MutableList(i + 1) { inf to listOf<Boolean>()} } fun update(isSure: Boolean, index: Int, new: Pair<String, List<Boolean>>) { val a = next[if (isSure) 0 else 1] if (!new.first.startsWith(inf) && new.first < a[index].first) a[index] = new } sure.forEachIndexed { j, (t, how) -> val storeShort = if (t.length == j) 1 else 0 update(true, j + 1 - storeShort, t to how + false) update(true, minOf(j + storeShort, i - j), t + c to how + true) } unsure.forEachIndexed { j, (t, how) -> update(false, j, t + c to how + true) if (j != i - j && t != inf) when { c > t[j] -> update(true, j + 1, t.substring(0, j) + c to how + true) else -> update(c < t[j], j + 1, t to how + false) } } next } println(ans.flatten().minByOrNull { it.first }!!.second.joinToString("") { if (it) "R" else "B" }) } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,226
competitions
The Unlicense
src/main/kotlin/com/psmay/exp/advent/y2021/Day05.kt
psmay
434,705,473
false
{"Kotlin": 242220}
package com.psmay.exp.advent.y2021 import kotlin.math.abs object Day05 { data class Point(val x: Int, val y: Int) private fun sgn(n: Int) = if (n < 0) -1 else if (n > 0) 1 else 0 fun forwardRange(a: Int, b: Int) = if (a > b) b..a else a..b data class Line(val start: Point, val end: Point) { val isHorizontal get() = deltaY == 0 val isVertical get() = deltaX == 0 val isDiagonal get() = !(isHorizontal || isVertical) val isIn45DegreeStep get() = abs(deltaX) == abs(deltaY) val deltaX = (end.x - start.x) val deltaY = (end.y - start.y) fun getCoveredPoints(): List<Point> { return if (isVertical) { val range = forwardRange(start.y, end.y) range.map { y -> Point(start.x, y) } } else if (isHorizontal) { val range = forwardRange(start.x, end.x) range.map { x -> Point(x, start.y) } } else if (isIn45DegreeStep) { // "a..b step s" syntax doesn't allow negative increments val xRange = IntProgression.fromClosedRange(start.x, end.x, sgn(deltaX)) val yRange = IntProgression.fromClosedRange(start.y, end.y, sgn(deltaY)) xRange.zip(yRange).map { pair -> pair.toPoint() } } else { throw IllegalStateException("Line $this is diagonal and does not fit in a 45-degree step.") } } } fun Pair<Int, Int>.toPoint(): Point { val (x, y) = this return Point(x, y) } fun Pair<Pair<Int, Int>, Pair<Int, Int>>.toLine(): Line { val (pair0, pair1) = this return Line(pair0.toPoint(), pair1.toPoint()) } fun part1(lineDefinitions: Sequence<Pair<Pair<Int, Int>, Pair<Int, Int>>>): Int { val lines = lineDefinitions .map { it.toLine() } .filter { !it.isDiagonal } val hits = lines.flatMap { it.getCoveredPoints() } val countedHits = hits .groupBy { it } .map { (point, instances) -> point to instances.size } val overlappedPoints = countedHits .filter { (_, hitCount) -> hitCount >= 2 } .map { (point, _) -> point } return overlappedPoints.size } fun part2(lineDefinitions: Sequence<Pair<Pair<Int, Int>, Pair<Int, Int>>>): Int { val lines = lineDefinitions.map { it.toLine() } val hits = lines.flatMap { it.getCoveredPoints() } val countedHits = hits .groupBy { it } .map { (point, instances) -> point to instances.size } val overlappedPoints = countedHits .filter { (_, hitCount) -> hitCount >= 2 } .map { (point, _) -> point } return overlappedPoints.size } }
0
Kotlin
0
0
c7ca54612ec117d42ba6cf733c4c8fe60689d3a8
2,813
advent-2021-kotlin
Creative Commons Zero v1.0 Universal
src/twentytwentytwo/day11/Day11.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentytwo.day11 import readInput fun main() { data class Monkey( val items: MutableList<Long>, val operation: (Long, Int) -> Long, val test: Long, val trueId: Int, val falseId: Int, var inspected: Long = 0, ) fun part1(input: List<String>): Long { val monkeys = mutableListOf<Monkey>() val parts = mutableListOf<List<String>>() input.chunked(7) { section -> parts.add(section[2].dropWhile { it != '=' }.split(" ")) monkeys.add( Monkey( items = section[1].split(",").map { it.filter { !it.isLetter() && it != ':' && !it.isWhitespace() }.toLong() } .toMutableList(), operation = { old, index -> val op = parts[index][2] val delta = if (parts[index][3] == "old") old else parts[index][3].toLong() if (op == "*") { old * delta } else { old + delta } }, test = section[3].split(" ").last().toLong(), trueId = section[4].split(" ").last().toInt(), falseId = section[5].split(" ").last().toInt(), ) ) } repeat(20) { monkeys.forEachIndexed { index, monkey -> monkey.items.forEach { startingWorry -> val itemWorry = monkey.operation(startingWorry, index) / 3.toLong() if (itemWorry % monkey.test == 0L) { monkeys[monkey.trueId].items.add(itemWorry) } else { monkeys[monkey.falseId].items.add(itemWorry) } monkey.inspected++ } monkey.items.clear() } } val topTwo = monkeys.sortedByDescending { it.inspected }.take(2).map { it.inspected } return (topTwo[0] * topTwo[1]) } fun part2(input: List<String>): Long { val monkeys = mutableListOf<Monkey>() val parts = mutableListOf<List<String>>() input.chunked(7) { section -> parts.add(section[2].dropWhile { it != '=' }.split(" ")) monkeys.add( Monkey( items = section[1].split(",").map { it.filter { !it.isLetter() && it != ':' && !it.isWhitespace() }.toLong() } .toMutableList(), operation = { old, index -> val op = parts[index][2] val delta = if (parts[index][3] == "old") old else parts[index][3].toLong() if (op == "*") { old * delta } else { old + delta } }, test = section[3].split(" ").last().toLong(), trueId = section[4].split(" ").last().toInt(), falseId = section[5].split(" ").last().toInt(), ) ) } val lcm = monkeys.map { it.test }.reduce(Long::times) repeat(10_000) { monkeys.forEachIndexed { index, monkey -> monkey.items.forEach { startingWorry -> val itemWorry = monkey.operation(startingWorry, index) % lcm if (itemWorry % monkey.test == 0L) { monkeys[monkey.trueId].items.add(itemWorry) } else { monkeys[monkey.falseId].items.add(itemWorry) } monkey.inspected++ } monkey.items.clear() } } val topTwo = monkeys.sortedByDescending { it.inspected }.take(2).map { it.inspected } return (topTwo[0] * topTwo[1]) } val input = readInput("day11", "Day11_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
4,118
advent-of-code
Apache License 2.0
src/main/kotlin/days/y2023/day18/Day18.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day18 import util.InputReader typealias PuzzleLine = String typealias PuzzleInput = List<PuzzleLine> class Day18(val input: PuzzleInput) { val instructions = input.toInstructions() fun partOne(): Int { val loop = instructions.drawLoop() val minX = loop.minOf { it.x } val maxX = loop.maxOf { it.x } val minY = loop.minOf { it.y } val maxY = loop.maxOf { it.y } var result = 0 val str = (minY..maxY).joinToString("\n") { y -> (minX..maxX).joinToString("") { x -> if (x == 0 && y == 0) { result += 1 "O" } else if (Position(x, y) in loop) { result += 1 "#" } else { "." } } } println(str) return result } } private fun List<DigInstruction>.drawLoop(): List<Position> { val positions = mutableListOf(Position(0, 0)) var i = 0 for (instruction in this) { i++ val lastPosition = positions.last() val newPositions = lastPosition.move(instruction.direction, instruction.distance) positions.addAll(newPositions) } println(i) return positions } data class Position(val x: Int, val y: Int) { fun move(direction: Direction, distance: Int): List<Position> { return (1..distance).map { d -> when (direction) { Direction.Up -> Position(x = x, y = y - d) Direction.Down -> Position(x = x, y = y + d) Direction.Left -> Position(x = x - d, y = y) Direction.Right -> Position(x = x + d, y = y) } } } } enum class Direction { Up, Down, Left, Right } data class DigInstruction(val direction: Direction, val distance: Int) { companion object { fun fromString(input: String): DigInstruction { val direction = when (input[0]) { 'U' -> Direction.Up 'D' -> Direction.Down 'L' -> Direction.Left 'R' -> Direction.Right else -> throw IllegalArgumentException("Invalid direction: ${input[0]}") } val distance = input.substring(2, 3).toInt() return DigInstruction(direction, distance) } } } fun PuzzleInput.toInstructions(): List<DigInstruction> { return this.map { DigInstruction.fromString(it) } } fun main() { val year = 2023 val day = 18 val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day) val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day) fun partOne(input: PuzzleInput) = Day18(input).partOne() println("Example 1: ${partOne(exampleInput)}") println("Puzzle 1: ${partOne(puzzleInput)}") }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
2,938
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountRangeSum.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 327. Count of Range Sum * @see <a href="https://leetcode.com/problems/count-of-range-sum">Source</a> */ fun interface CountRangeSum { operator fun invoke(nums: IntArray, lower: Int, upper: Int): Int } class CountRangeSumSegmentTree : CountRangeSum { override operator fun invoke(nums: IntArray, lower: Int, upper: Int): Int { if (nums.isEmpty()) return 0 var ans = 0 val valSet: MutableSet<Long> = HashSet() var sum: Long = 0 for (i in nums.indices) { sum += nums[i].toLong() valSet.add(sum) } val valArr = valSet.toTypedArray() valArr.sort() val root = buildSegmentTree(valArr, 0, valArr.size - 1) for (i in nums.indices.reversed()) { updateSegmentTree(root, sum) sum -= nums[i].toLong() ans += getCount(root, lower.toLong() + sum, upper.toLong() + sum) } return ans } private fun buildSegmentTree(valArr: Array<Long>, low: Int, high: Int): SegmentTreeNode? { if (low > high) return null val stn = SegmentTreeNode(valArr[low], valArr[high]) if (low == high) return stn val mid = (low + high) / 2 stn.left = buildSegmentTree(valArr, low, mid) stn.right = buildSegmentTree(valArr, mid + 1, high) return stn } private fun updateSegmentTree(stn: SegmentTreeNode?, value: Long) { if (stn == null) return if (value >= stn.min && value <= stn.max) { stn.count++ updateSegmentTree(stn.left, value) updateSegmentTree(stn.right, value) } } private fun getCount(stn: SegmentTreeNode?, min: Long, max: Long): Int { if (stn == null) return 0 if (min > stn.max || max < stn.min) return 0 return if (min <= stn.min && max >= stn.max) { stn.count } else { getCount(stn.left, min, max) + getCount( stn.right, min, max, ) } } private data class SegmentTreeNode(var min: Long, var max: Long) { var left: SegmentTreeNode? = null var right: SegmentTreeNode? = null var count = 0 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,883
kotlab
Apache License 2.0
src/Day10.kt
TheGreatJakester
573,222,328
false
{"Kotlin": 47612}
package day10 import utils.string.asLines import utils.readInputAsText import utils.runSolver import utils.string.blockChar import utils.string.squiggleChar private typealias SolutionType = Int private const val defaultSolution = 0 private const val dayNumber: String = "10" private val testSolution1: SolutionType? = 13140 private val testSolution2: SolutionType? = null private fun part1(input: String): SolutionType { val instructions = input.asLines() val cycleSteps = instructions.map { if (it == "noop") { listOf(0) } else { val s = it.split(" ") listOf(0, s[1].toInt()) } }.flatten() val totals = mutableListOf<Int>() var runningTotal = 1 cycleSteps.forEachIndexed { index, step -> val cycleIndex = index + 1 if (cycleIndex == 20 || (cycleIndex - 20) % 40 == 0) { totals.add(cycleIndex * runningTotal) } runningTotal += step } return totals.sum() } private fun part2(input: String): SolutionType { val instructions = input.asLines() val cycleSteps = instructions.map { if (it == "noop") { listOf(0) } else { val s = it.split(" ") listOf(0, s[1].toInt()) } }.flatten() val pixels = mutableListOf<Boolean>() var runningTotal = 1 cycleSteps.forEachIndexed { index, step -> val screenPosition = index % 40 if (runningTotal in (screenPosition - 1)..(screenPosition + 1)) { pixels.add(true) } else { pixels.add(false) } runningTotal += step } pixels.chunked(40) { println(it.joinToString(separator = "") { if (it) squiggleChar else " " }) } return defaultSolution } fun main() { runSolver("Test 1", readInputAsText("Day${dayNumber}_test"), testSolution1, ::part1) runSolver("Part 1", readInputAsText("Day${dayNumber}"), null, ::part1) runSolver("Test 2", readInputAsText("Day${dayNumber}_test"), testSolution2, ::part2) runSolver("Part 2", readInputAsText("Day${dayNumber}"), null, ::part2) }
0
Kotlin
0
0
c76c213006eb8dfb44b26822a44324b66600f933
2,137
2022-AOC-Kotlin
Apache License 2.0
src/main/kotlin/g1301_1400/s1334_find_the_city_with_the_smallest_number_of_neighbors_at_a_threshold_distance/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1334_find_the_city_with_the_smallest_number_of_neighbors_at_a_threshold_distance // #Medium #Dynamic_Programming #Graph #Shortest_Path // #2023_06_06_Time_223_ms_(88.89%)_Space_37.5_MB_(77.78%) class Solution { fun findTheCity(n: Int, edges: Array<IntArray>, maxDist: Int): Int { val graph = Array(n) { IntArray(n) } for (edge in edges) { graph[edge[0]][edge[1]] = edge[2] graph[edge[1]][edge[0]] = edge[2] } return fllowdWarshall(graph, n, maxDist) } private fun fllowdWarshall(graph: Array<IntArray>, n: Int, maxDist: Int): Int { val inf = 10001 val dist = Array(n) { IntArray(n) } for (i in 0 until n) { for (j in 0 until n) { if (i != j && graph[i][j] == 0) { dist[i][j] = inf } else { dist[i][j] = graph[i][j] } } } for (k in 0 until n) { for (i in 0 until n) { for (j in 0 until n) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j] } } } } return getList(dist, n, maxDist) } private fun getList(dist: Array<IntArray>, n: Int, maxDist: Int): Int { val map = HashMap<Int, MutableList<Int>>() for (i in 0 until n) { for (j in 0 until n) { if (!map.containsKey(i)) { map[i] = ArrayList() if (dist[i][j] <= maxDist && i != j) { map[i]!!.add(j) } } else if (map.containsKey(i) && dist[i][j] <= maxDist && i != j) { map[i]!!.add(j) } } } var numOfEle = Int.MAX_VALUE var ans = 0 for (i in 0 until n) { if (numOfEle >= map[i]!!.size) { numOfEle = Math.min(numOfEle, map[i]!!.size) ans = i } } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,127
LeetCode-in-Kotlin
MIT License
src/Day04.kt
stevefranchak
573,628,312
false
{"Kotlin": 34220}
import java.util.function.Predicate class SectionAssignment( private val start: Int, private val end: Int, ) { fun contains(other: SectionAssignment) = other.start >= start && other.end <= end fun overlaps(other: SectionAssignment) = end >= other.start && start <= other.end companion object { fun fromString(input: String) = input.split("-").map(String::toInt).let { SectionAssignment(it[0], it[1]) } } } fun main() { fun processPart(input: List<String>, filter: Predicate<Pair<SectionAssignment, SectionAssignment>>) = input.asSequence() .filter(String::isNotBlank) .map { it.split(",").map(SectionAssignment::fromString).let { assignments -> Pair(assignments[0], assignments[1]) } } .filter(filter::test) .count() fun part1(input: List<String>) = processPart(input) { it.first.contains(it.second) || it.second.contains(it.first) } fun part2(input: List<String>) = processPart(input) { it.first.overlaps(it.second) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") val part1TestOutput = part1(testInput) val part1ExpectedOutput = 2 check(part1TestOutput == part1ExpectedOutput) { "$part1TestOutput != $part1ExpectedOutput" } val part2TestOutput = part2(testInput) val part2ExpectedOutput = 4 check(part2TestOutput == part2ExpectedOutput) { "$part2TestOutput != $part2ExpectedOutput" } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
22a0b0544773a6c84285d381d6c21b4b1efe6b8d
1,653
advent-of-code-2022
Apache License 2.0
facebook/y2020/round3/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2020.round3 import java.util.* private fun solve(): Int { val (n, m, k, x) = readInts() val (sIn, pIn) = listOf(n, m).map { length -> val array = readInts().toIntArray() + IntArray(length - k) { 0 } val (a, b, c, d) = readInts() for (i in k until length) { array[i] = ((a.toLong() * array[i - 2] + b.toLong() * array[i - 1] + c) % d).toInt() + 1 } array } val set = TreeMap<Int, Deque<Int>>() fun add(size: Int) { val r = size % x set.putIfAbsent(r, LinkedList()) set[r]!!.addLast(size) } fun remove(p: Int): Int { val r = p % x val q = set.ceilingKey(r) ?: set.ceilingKey(0) val size = set[q]!!.pollFirst() if (set[q]!!.isEmpty()) { set.remove(q) } return (size - p) / x } val sizes = sIn.sortedDescending() val sizesLarge = sizes.filter { it >= x } val sizesSmall = sizes.filter { it < x } val packages = pIn.sorted() var low = 0 var high = minOf(n, m) + 1 while (low + 1 < high) { val mid = (low + high) / 2 var i = 0 var j = 0 val deque = LinkedList<Int>() var keys = 0L var bad = false for (p in packages.take(mid).reversed()) { while ((i < sizesLarge.size) && (sizesLarge[i] >= p)) { add(sizesLarge[i]) i++ } while ((j < sizesSmall.size) && (sizesSmall[j] >= p)) { deque.addLast(sizesSmall[j]) j++ } if (set.isEmpty()) { if (p < x) { if (deque.isNotEmpty()) { deque.removeLast() continue } } bad = true break } keys += remove(p) } while (i < sizesLarge.size) { add(sizesLarge[i]) i++ } while (j < sizesSmall.size) { deque.addLast(sizesSmall[j]) j++ } while (set.isNotEmpty()) { keys += remove(0) } while (deque.isNotEmpty()) { deque.removeLast() keys++ } if (bad || keys < n - 1) high = mid else low = mid } return low } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,089
competitions
The Unlicense
src/main/kotlin/dev/paulshields/aoc/Day19.kt
Pkshields
433,609,825
false
{"Kotlin": 133840}
/** * Day 19: Beacon Scanner */ package dev.paulshields.aoc import dev.paulshields.aoc.common.Point3D import dev.paulshields.aoc.common.readFileAsString import kotlin.math.abs fun main() { println(" ** Day 19: Beacon Scanner ** \n") val scannerReport = readFileAsString("/Day19ScannerReport.txt") val allScannersAndBeacons = findAllScannersAndBeacons(scannerReport) println("There are ${allScannersAndBeacons.beaconLocations.size} beacons in the ocean trench.") val largestManhattanDistance = calculateLargestManhattanDistance(allScannersAndBeacons.scannerPositions) println("The manhattan distance between the 2 scanners furthest away from each other is $largestManhattanDistance") } fun findAllScannersAndBeacons(scannerReport: String) = findAllScannersAndBeacons(parseScannerReport(scannerReport)) /** * Assumes scanner 0 is at point (0, 0, 0) */ fun findAllScannersAndBeacons(relativeBeaconPositions: List<List<Point3D>>): ScannerMap { var unmappedScanners = relativeBeaconPositions .mapIndexed { index, scanner -> index to getAllRotationsOfAScanner(scanner) } .toMap() val mappedScanners = mutableMapOf(0 to Scanner(Point3D(0, 0, 0), relativeBeaconPositions[0])) val mappedScannerToProcessQueue = mutableListOf(0) while (mappedScannerToProcessQueue.size > 0) { val mappedScannerIndex = mappedScannerToProcessQueue.removeFirst() val mappedScanner = mappedScanners[mappedScannerIndex] ?: return ScannerMap(emptyList(), emptyList()) for ((unmappedScannerIndex, allRotationsOfUnmappedScanner) in unmappedScanners) { val newlyMappedScanner = findScannerLocationRelativeToAnotherScanner(allRotationsOfUnmappedScanner, mappedScanner) newlyMappedScanner?.let { mappedScanners[unmappedScannerIndex] = it mappedScannerToProcessQueue.add(unmappedScannerIndex) } } unmappedScanners = unmappedScanners.filter { (key, _) -> !mappedScanners.keys.contains(key) } } val allBeacons = mappedScanners .map { it.value } .fold(emptyList<Point3D>()) { accumulator, scanner -> (accumulator + scanner.beaconsWithinSight.map { it + scanner.position }).distinct() } val allScannerPositions = mappedScanners.map { it.value.position } return ScannerMap(allScannerPositions, allBeacons) } private fun getAllRotationsOfAScanner(scanner: List<Point3D>): List<List<Point3D>> { return scanner .map { it.rotations() } .flatMap { it.mapIndexed { index, value -> index to value } } .groupBy(keySelector = { it.first }, valueTransform = { it.second }) .map { it.value } } private fun findScannerLocationRelativeToAnotherScanner(allRotationsOfUnmappedScanner: List<List<Point3D>>, anotherScanner: Scanner): Scanner? { val newlyMappedScanner = allRotationsOfUnmappedScanner.firstNotNullOfOrNull { rotatedScanner -> val offsetToMappedScanner = rotatedScanner .flatMap { beacon -> anotherScanner.beaconsWithinSight.map { otherBeacon -> otherBeacon - beacon } } .groupingBy { it } .eachCount() .filter { it.value >= 12 } .map { it.key } .firstOrNull() offsetToMappedScanner?.let { Pair(it, rotatedScanner) } } return newlyMappedScanner?.let { val offsetToZero = newlyMappedScanner.first.plus(anotherScanner.position) Scanner(offsetToZero, newlyMappedScanner.second) } } fun calculateLargestManhattanDistance(locations: List<Point3D>) = locations .flatMap { left -> locations .filter { left != it } .map { right -> abs(left.x - right.x) + abs(left.y - right.y) + abs(left.z - right.z) } } .maxOf { it } private fun parseScannerReport(report: String) = report.split("\n\n") .map { it .lines() .drop(1) .map { Point3D.fromList(it.split(',').map { it.toInt() }) } } data class Scanner(val position: Point3D, val beaconsWithinSight: List<Point3D>) data class ScannerMap(val scannerPositions: List<Point3D>, val beaconLocations: List<Point3D>) /* ktlint-disable no-multi-spaces */ private fun Point3D.rotations() = listOf( this, // Standard Point3D(this.y, this.x * -1, this.z), // Rotated 90 degrees Point3D(this.x * -1, this.y * -1, this.z), // Rotated 180 degrees Point3D(this.y * -1, this.x, this.z), // Rotated 180 degrees Point3D(this.z * -1, this.y, this.x), // Pointing right Point3D(this.y, this.z, this.x), // Pointing right, rotated 90 degrees Point3D(this.z, this.y * -1, this.x), // Pointing right, rotated 180 degrees Point3D(this.y * -1, this.z * -1, this.x), // Pointing right, rotated 270 degrees Point3D(this.x * -1, this.y, this.z * -1), // Pointing backwards Point3D(this.y, this.x, this.z * -1), // Pointing backwards, rotated 90 degrees Point3D(this.x, this.y * -1, this.z * -1), // Pointing backwards, rotated 180 degrees Point3D(this.y * -1, this.x * -1, this.z * -1), // Pointing backwards Point3D(this.z, this.y, this.x * -1), // Pointing right Point3D(this.y, this.z * -1, this.x * -1), // Pointing right, rotated 90 degrees Point3D(this.z * -1, this.y * -1, this.x * -1), // Pointing right, rotated 180 degrees Point3D(this.y * -1, this.z, this.x * -1), // Pointing right, rotated 270 degrees Point3D(this.x, this.z * -1, this.y), // Pointing up Point3D(this.z * -1, this.x * -1, this.y), // Pointing up, rotated 90 degrees Point3D(this.x * -1, this.z, this.y), // Pointing up, rotated 180 degrees Point3D(this.z, this.x, this.y), // Pointing up, rotated 270 degrees Point3D(this.x, this.z, this.y * -1), // Pointing down Point3D(this.z, this.x * -1, this.y * -1), // Pointing down, rotated 90 degrees Point3D(this.x * -1, this.z * -1, this.y * -1), // Pointing down, rotated 180 degrees Point3D(this.z * -1, this.x, this.y * -1), // Pointing down, rotated 270 degrees ) /* ktlint-disable no-multi-spaces */
0
Kotlin
0
0
e3533f62e164ad72ec18248487fe9e44ab3cbfc2
6,446
AdventOfCode2021
MIT License
src/year2023/day18/Day18.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day18 import check import readInput import kotlin.math.absoluteValue fun main() { val testInput = readInput("2023", "Day18_test") check(part1(testInput), 62) check(part2(testInput), 952408144115) val input = readInput("2023", "Day18") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>) = input.parsePolygonEdges().polygonArea() private fun part2(input: List<String>) = input.repairInstructions().parsePolygonEdges().polygonArea() private data class Pos(val x: Long, val y: Long) { fun up(steps: Int = 1) = Pos(x, y - steps) fun down(steps: Int = 1) = Pos(x, y + steps) fun left(steps: Int = 1) = Pos(x - steps, y) fun right(steps: Int = 1) = Pos(x + steps, y) fun moveInDir(dir: String, steps: Int = 1) = when (dir) { "U" -> up(steps) "D" -> down(steps) "L" -> left(steps) "R" -> right(steps) else -> error("unknown $dir") } } @OptIn(ExperimentalStdlibApi::class) private fun List<String>.repairInstructions(): List<String> { fun String.toDir() = when (this@toDir) { "3" -> "U" "1" -> "D" "2" -> "L" "0" -> "R" else -> error("Cannot convert ${this@toDir}") } return map { line -> val (steps, dir) = line.split(' ').last() .removePrefix("(#").removeSuffix(")") .chunked(5) .let { it.first().hexToInt() to it.last().toDir() } "$dir $steps" } } private fun List<String>.parsePolygonEdges() = dropLast(1).fold(mutableListOf(Pos(0,0))) { edges, line -> val (dir, steps) = line.split(' ') edges += edges.last().moveInDir(dir, steps.toInt()) edges } private fun List<Pos>.polygonArea(): Long { val vertices = (this + first()).windowed(2) val area = vertices.sumOf { (a,b) -> (b.x + a.x) * (b.y - a.y) }.absoluteValue / 2 val border = vertices.sumOf { (a, b) -> (b.x - a.x + b.y - a.y).absoluteValue } return area + border / 2 + 1 }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,038
AdventOfCode
Apache License 2.0
solutions/aockt/y2023/Y2023D02.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import io.github.jadarma.aockt.core.Solution object Y2023D02 : Solution { /** * Holds observations for one instance of the elf's game. * @property id The ID of the game. * @property rounds The color-count of the balls revealed during the game. */ private data class Game(val id: Int, val rounds: List<Balls>) { /** A set of balls, associated by their color. */ data class Balls(val red: Int, val green: Int, val blue: Int) { val power: Int get() = red * green * blue } /** Whether the game's [rounds] could have been played with a [set] of this dimension. */ fun isPossibleWith(set: Balls): Boolean = rounds.all { it.red <= set.red && it.green <= set.green && it.blue <= set.blue } /** The smallest set of balls required to play the [rounds] of this game successfully. */ fun minimumSet(): Balls = Balls( red = rounds.maxOf { it.red }, green = rounds.maxOf { it.green }, blue = rounds.maxOf { it.blue }, ) companion object { /** Attempt to parse a [Game] notation from the [input] line. */ fun parse(input: String): Game = runCatching { Game( id = input.substringBefore(": ").substringAfter("Game ").toInt(), rounds = input .substringAfter(": ") .split("; ") .map { round -> round .split(", ", limit = 3) .filterNot(String::isEmpty) .map { it.split(" ", limit = 2) } .associate { (count, color) -> color to count.toInt() } .run { Balls( red = getOrDefault("red", 0), green = getOrDefault("green", 0), blue = getOrDefault("blue", 0), ) } }, ) }.getOrElse { cause -> throw IllegalArgumentException("Invalid input.", cause) } } } /** Parse the [input] and return the list of [Game]s the elf played. */ private fun parseInput(input: String): Sequence<Game> = input.lineSequence().map(Game.Companion::parse) override fun partOne(input: String) = parseInput(input) .filter { game -> game.isPossibleWith(Game.Balls(red = 12, green = 13, blue = 14)) } .sumOf { it.id } override fun partTwo(input: String) = parseInput(input).sumOf { game -> game.minimumSet().power } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
2,820
advent-of-code-kotlin-solutions
The Unlicense
src/day14/Day14.kt
ayukatawago
572,742,437
false
{"Kotlin": 58880}
package day14 import readInput fun main() { val testInput = readInput("day14/test") val rocks = mutableSetOf<Position>() testInput.forEach { input -> val iterator = input.split(" -> ").map { Position(it.split(',')[1].toInt(), it.split(',')[0].toInt()) }.iterator() var currentPosition = iterator.next() while (iterator.hasNext()) { val nextPosition = iterator.next() if (currentPosition.row == nextPosition.row) { getIntRange(currentPosition.column, nextPosition.column).forEach { column -> rocks.add(Position(currentPosition.row, column)) } } else if (currentPosition.column == nextPosition.column) { getIntRange(currentPosition.row, nextPosition.row).forEach { row -> rocks.add(Position(row, currentPosition.column)) } } currentPosition = nextPosition } } part1(rocks) part2(rocks) } private fun part1(rocks: Set<Position>) { val sands = mutableSetOf<Position>() var sandPosition = Position.START var shouldRun = true while (shouldRun) { val nextPosition = listOf( Position(sandPosition.row + 1, sandPosition.column), Position(sandPosition.row + 1, sandPosition.column - 1), Position(sandPosition.row + 1, sandPosition.column + 1) ).firstOrNull { it !in rocks && it !in sands } when { nextPosition == null && sandPosition == Position.START -> { sands.add(Position.START) shouldRun = false } nextPosition == null -> { sands.add(sandPosition) sandPosition = Position.START } nextPosition.row == rocks.maxOf { it.row } -> shouldRun = false else -> sandPosition = nextPosition } } printStatus(rocks, sands, Position.START) println(sands.size) } private fun part2(rocks: Set<Position>) { val floorRow = rocks.maxOf { it.row + 2 } val floors = mutableSetOf<Position>() (Position.START.column - floorRow..Position.START.column + floorRow).forEach { colomn -> floors.add(Position(floorRow, colomn)) } part1(rocks + floors) } private fun printStatus(rocks: Set<Position>, sands: Set<Position>, startPosition: Position) { val left = rocks.minOf { it.column - 1 } val right = rocks.maxOf { it.column + 1 } val bottom = rocks.maxOf { it.row + 1 } (0..bottom).forEach { row -> (left..right).forEach { column -> when { Position(row, column) in rocks -> print('#') Position(row, column) in sands -> print('o') row == startPosition.row && column == startPosition.column -> print('+') else -> print('.') } } println() } } private fun getIntRange(num1: Int, num2: Int): IntRange = if (num1 >= num2) { num2..num1 } else { num1..num2 } private data class Position(val row: Int, val column: Int) { companion object { val START = Position(0, 500) } }
0
Kotlin
0
0
923f08f3de3cdd7baae3cb19b5e9cf3e46745b51
3,206
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day13/Day13Puzzle.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day13 import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver abstract class Day13Puzzle : PuzzleSolver { final override fun solve(inputLines: Sequence<String>): String { val manualSections = inputLines.partition { !it.startsWith("fold") } val manual = manualSections.first .asSequence() .filter { it.isNotBlank() } .map { it.split(',') } .map { it.map(String::toInt) } .map { Dot(it[0], it[1]) } .toSet() val foldInstructions = manualSections.second .asSequence() .filter { it.isNotBlank() } .map { it.split(' ') } .map { it.last() } .map { it.split('=') } .mapNotNull { if (it[0] == "y") FoldInstruction.Up(it[1].toInt()) else if (it[0] == "x") FoldInstruction.Left(it[1].toInt()) else null } .toList() return solve(manual, foldInstructions) } abstract fun solve(manual: Set<Dot>, foldInstructions: List<FoldInstruction>): String protected fun Set<Dot>.fold(instruction: FoldInstruction): Set<Dot> { return when (instruction) { is FoldInstruction.Up -> fold(instruction) is FoldInstruction.Left -> fold(instruction) } } private fun Set<Dot>.fold(instruction: FoldInstruction.Up): Set<Dot> { val dotsToMove = filter { it.y > instruction.alongY }.toSet() val movedDots = dotsToMove.map { it.copy(y = it.y - 2 * (it.y - instruction.alongY)) }.toSet() return this - dotsToMove + movedDots } private fun Set<Dot>.fold(instruction: FoldInstruction.Left): Set<Dot> { val dotsToMove = filter { it.x > instruction.alongX }.toSet() val movedDots = dotsToMove.map { it.copy(x = it.x - 2 * (it.x - instruction.alongX)) }.toSet() return this - dotsToMove + movedDots } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
2,009
AdventOfCode2021
Apache License 2.0
2021/src/day08/day8.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day08 import java.io.File import kotlin.math.pow import kotlin.streams.toList fun main() { val input = File("src/day08", "day8input.txt").readLines().map { parseLine(it) } println(getUniqueSegments(input.map { it.second }).size) val outputSum = input.sumOf { val digitMap = analyzeInput(it.first) parseOutput(it.second, digitMap) } println(outputSum) } /** * Input a line of input signal and output separated by | * Output a pair with the input signals in one list and the output signals in 1 list */ fun parseLine(input: String): Pair<List<String>, List<String>> { val inputList = input.split("|").map { it.trim() } return Pair(inputList[0].split(" "), inputList[1].split(" ")) } fun getUniqueSegments(segments: List<List<String>>): List<String> { return segments.flatten().filter { isUniqueSegments(it) } } fun isUniqueSegments(segment: String): Boolean { return when (segment.length) { 2 -> true 3 -> true 4 -> true 7 -> true else -> false } } /** * Analyzes 10 input strings and returns a mapping from String to int segment */ fun analyzeInput(input: List<String>): Map<String, Int> { val sortedInput = input.sortedBy { it.length } // Maps number 0 -> 9 to the input string. val numberMap: MutableMap<Int, String> = mutableMapOf() // Stores the map of position to segment /* 0 1 2 3 4 5 6 */ val segmentMap: MutableMap<Int, Char> = mutableMapOf() // The first item should be length 2 and correspond to 1 if (sortedInput[0].length == 2) { numberMap[1] = sortedInput[0] } else throw Exception("Could not find 1") // The second item should be length 3 and correspond to 7 if (sortedInput[1].length == 3) { numberMap[7] = sortedInput[1] } else throw Exception("Could not find 7") if (sortedInput[2].length == 4) { numberMap[4] = sortedInput[2] } else throw Exception("Could not find 4") if (sortedInput[9].length == 7) { numberMap[8] = sortedInput[9] } else throw Exception("Could not find 8") // Now from these strings, figure out the 2, 7 and 0 segments // Top segment is whichever part of 7 is not in 1 segmentMap[0] = findUniqueChar(numberMap[7], numberMap[1]) val segOneFourCandidates = findUniqueChars(numberMap[4], numberMap[1]) if (segOneFourCandidates.size != 2) throw Exception("Too many chars between 1 and 4 $segOneFourCandidates") val zeroSixNineCandidates = input.filter { it.length == 6 } if (zeroSixNineCandidates.size != 3) throw Exception("Didn't find right number of 6 segments") numberMap[6] = zeroSixNineCandidates.filterNot { containsAll(it, numberMap[1]) }.first() numberMap[9] = zeroSixNineCandidates.first { containsAll(it, numberMap[4]) } numberMap[0] = zeroSixNineCandidates.first { !containsAll(it, numberMap[4]) && it != numberMap[6] } // Now we can get 5 and 3 which are the only numbers that are 1 away from 9 that are also length 5 val fiveThreeCandidates = input.filter { it.length == 5 && findUniqueChars(numberMap[9], it).size == 1 } if (fiveThreeCandidates.size != 2) throw Exception("Too many strings match 5 and 3") // Now one of these contains both elements of 1 and one of these doesn't. if (containsAll(fiveThreeCandidates[0], numberMap[1])) { numberMap[3] = fiveThreeCandidates[0] numberMap[5] = fiveThreeCandidates[1] } else { numberMap[3] = fiveThreeCandidates[1] numberMap[5] = fiveThreeCandidates[0] } segmentMap[1] = findUniqueChar(numberMap[9], numberMap[3]) segmentMap[2] = findUniqueChar(numberMap[9], numberMap[6]) // Now we have segment 4 which is the only letter not in 9 segmentMap[4] = findUniqueChar(numberMap[8], numberMap[9]) segmentMap[3] = findUniqueChar(numberMap[8], numberMap[0]) segmentMap[5] = if (numberMap[1]!![0] == segmentMap[2]) numberMap[1]!![1] else numberMap[1]!![0] segmentMap[6] = findUniqueChar(numberMap[8], numberMap[4] + segmentMap[0] + segmentMap[4]) // Now return a map of char to segment return makeDigitMapFromSegmentMap(segmentMap) } fun findUniqueChars(base: String?, compare: String?): List<Char> { return base!!.chars().toList().toSet().subtract(compare!!.chars().toList().toSet()).map { it.toChar() } } fun findUniqueChar(base: String?, compare: String?): Char { // Finds the 1 unique char or throws and exception val diffSet = findUniqueChars(base, compare) if (diffSet.size == 1) { return diffSet.first() } throw Exception("Found too many characters between $base and $compare") } fun containsAll(base: String?, all: String?): Boolean { return all!!.all { base!!.contains(it) } } /** * Takes a segment map and makes a sorted string to digit map. */ fun makeDigitMapFromSegmentMap(segmentMap: Map<Int, Char>): Map<String, Int> { return buildMap { put(makeSortedString(listOf(0, 1, 2, 4, 5, 6), segmentMap), 0) put(makeSortedString(listOf(2, 5), segmentMap), 1) put(makeSortedString(listOf(0, 2, 3, 4, 6), segmentMap), 2) put(makeSortedString(listOf(0, 2, 3, 5, 6), segmentMap), 3) put(makeSortedString(listOf(1, 2, 3, 5), segmentMap), 4) put(makeSortedString(listOf(0, 1, 3, 5, 6), segmentMap), 5) put(makeSortedString(listOf(0, 1, 3, 4, 5, 6), segmentMap), 6) put(makeSortedString(listOf(0, 2, 5), segmentMap), 7) put(makeSortedString(listOf(0, 1, 2, 3, 4, 5, 6), segmentMap), 8) put(makeSortedString(listOf(0, 1, 2, 3, 5, 6), segmentMap), 9) } } fun makeSortedString(input: List<Int>, segmentMap: Map<Int, Char>): String { return input.map { segmentMap.getOrDefault(it, 'z').toChar() }.sorted().joinToString() } fun sortString(input: String): String { return input.toCharArray().sorted().joinToString() } fun parseOutput(output: List<String>, digitMap: Map<String, Int>): Int { return output.reversed().foldIndexed(0) { index, acc, string -> (digitMap.getOrDefault(sortString(string), 0) * (10.0.pow(index)) + acc).toInt() } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
6,180
adventofcode
Apache License 2.0
src/Day05.kt
eps90
574,098,235
false
{"Kotlin": 9738}
private fun <T> ArrayDeque<T>.push(element: T) = addLast(element) private fun <T> ArrayDeque<T>.push(elements: Collection<T>) = addAll(elements) private fun <T> ArrayDeque<T>.pop() = removeLast() private fun <T> ArrayDeque<T>.peek() = lastOrNull() fun main() { val componentRegex = """\s?(\[?(\w|\d)]?| {3})""".toRegex() val instructionRegex = """move (\d+) from (\d+) to (\d+)""".toRegex() fun parseStacks(input: List<String>, untilRow: Int): MutableMap<Int, ArrayDeque<String>> { val rows = input .take(untilRow) .map { line -> componentRegex .findAll(line) .map { it.groupValues[2] } .toList() } val numberOfStacks = rows.last().last().toInt() val onlyRows = rows.dropLast(1) return (1..numberOfStacks).associateWith { stackNo -> ArrayDeque(onlyRows.reversed().mapNotNull { row -> row.getOrNull(stackNo - 1)?.takeIf { it.isNotEmpty() } }) }.toMutableMap() } fun part1(input: List<String>): String { val stacksLimit = input.indexOf("") val stacks = parseStacks(input, stacksLimit) input .filter { it.startsWith("move") } .forEach { instruction -> val instructionsParsed = instructionRegex.find(instruction) if (instructionsParsed != null) { val (noOfElems, from, to) = instructionsParsed.destructured repeat(noOfElems.toInt()) { val nextElem = stacks[from.toInt()]!!.pop() stacks[to.toInt()]!!.push(nextElem) } } } return stacks.mapNotNull {(_, value) -> value.peek() }.joinToString(separator = "") } fun part2(input: List<String>): String { val stacksLimit = input.indexOf("") val stacks = parseStacks(input, stacksLimit) input .filter { it.startsWith("move") } .forEach { instruction -> val instructionsParsed = instructionRegex.find(instruction) if (instructionsParsed != null) { val (noOfElems, from, to) = instructionsParsed.destructured val elToRemove = stacks[from.toInt()]!!.takeLast(noOfElems.toInt()) repeat(noOfElems.toInt()) { stacks[from.toInt()]!!.pop() } stacks[to.toInt()]!!.push(elToRemove) } } return stacks.mapNotNull {(_, value) -> value.peek() }.joinToString(separator = "") } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") println(part2(testInput)) check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bbf58c512fddc0ef1112c3bee5e5c6d43f5aabc0
2,933
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day1.kt
dlew
75,886,947
false
null
class Day1 { enum class Direction { NORTH, EAST, SOUTH, WEST; fun turn(turn: Turn) = when (turn) { Turn.NONE -> this Turn.LEFT -> when (this) { NORTH -> WEST WEST -> SOUTH SOUTH -> EAST EAST -> NORTH } Turn.RIGHT -> when (this) { NORTH -> EAST EAST -> SOUTH SOUTH -> WEST WEST -> NORTH } } } enum class Turn { NONE, RIGHT, LEFT } data class Location(val x: Int, val y: Int) { fun blocksAway() = Math.abs(x) + Math.abs(y) } data class State(val loc: Location, val direction: Direction) data class Step(val turn: Turn, val blocks: Int) { // Turns things like R3 into R1 N1 N1 fun stepByStep(): Iterable<Step> = (1..blocks).asIterable() .map { if (it == 1) Step(turn, 1) else Step(Turn.NONE, 1) } } companion object { private fun parseInput(input: String) = input.split(", ") .map { val direction = if (it[0] == 'L') Turn.LEFT else Turn.RIGHT val blocks = it.drop(1).toInt() Step(direction, blocks) } fun blocksAway(input: String) = parseInput(input) .fold(State(Location(0, 0), Direction.NORTH), { state, step -> applyStep(state, step) }) .loc.blocksAway() fun firstStateVisitedTwice(input: String) = parseInput(input) .flatMap { it.stepByStep() } .scan(State(Location(0, 0), Direction.NORTH), { state, step -> applyStep(state, step) }) .map { it.loc } .fold(Pair<Set<Location>, Location?>(emptySet(), null), { p, location -> if (p.second != null) { p } else if (location in p.first) { Pair(p.first, location) } else { Pair(p.first.plusElement(location), null) } }) .second?.blocksAway() private fun applyStep(state: State, step: Step) = when (state.direction.turn(step.turn)) { Direction.NORTH -> State(Location(state.loc.x, state.loc.y + step.blocks), Direction.NORTH) Direction.EAST -> State(Location(state.loc.x + step.blocks, state.loc.y), Direction.EAST) Direction.SOUTH -> State(Location(state.loc.x, state.loc.y - step.blocks), Direction.SOUTH) Direction.WEST -> State(Location(state.loc.x - step.blocks, state.loc.y), Direction.WEST) } } }
0
Kotlin
2
12
527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd
2,478
aoc-2016
MIT License
src/main/kotlin/puzzle8/SevenSegmentsDemystifier.kt
tpoujol
436,532,129
false
{"Kotlin": 47470}
package puzzle8 import kotlin.math.pow import kotlin.system.measureTimeMillis fun main() { val sevenSegmentsDemystifier = SevenSegmentsDemystifier() val basicDigitWiring = DigitWiring() val time = measureTimeMillis { println("test: ${basicDigitWiring.findNumber("acf")}") println("Part 1 solution is: ${sevenSegmentsDemystifier.countEasyDigits()}") println("Part 2 solution is: ${sevenSegmentsDemystifier.findAllDigits()}") } println("Time: $time") } data class InputEntry(val patterns: List<String>, val output: List<String>) data class DigitWiring( private val one: String = "a", private val two: String = "b", private val three: String = "c", private val four: String = "d", private val five: String = "e", private val six: String = "f", private val seven: String = "g" ) { private fun produceDisplayForInt(value: Int): List<String> { return when (value) { 0 -> listOf(one, two, three, five, six, seven) 1 -> listOf(three, six) 2 -> listOf(one, three, four, five, seven) 3 -> listOf(one, three, four, six, seven) 4 -> listOf(two, three, four, six) 5 -> listOf(one, two, four, six, seven) 6 -> listOf(one, two, four, five, six, seven) 7 -> listOf(one, three, six) 8 -> listOf(one, two, three, four, five, six, seven) 9 -> listOf(one, two, three, four, six, seven) else -> throw IllegalArgumentException("This is not a single digit number") } } fun findNumber(toFind: String): Int { // has to be checked in that order otherwise an 8 could be caught by a 0 for example val splitString = toFind.toList().map { it.toString() } return when { splitString.containsAll(produceDisplayForInt(8)) -> 8 splitString.containsAll(produceDisplayForInt(0)) -> 0 splitString.containsAll(produceDisplayForInt(9)) -> 9 splitString.containsAll(produceDisplayForInt(6)) -> 6 splitString.containsAll(produceDisplayForInt(2)) -> 2 splitString.containsAll(produceDisplayForInt(3)) -> 3 splitString.containsAll(produceDisplayForInt(5)) -> 5 splitString.containsAll(produceDisplayForInt(4)) -> 4 splitString.containsAll(produceDisplayForInt(7)) -> 7 splitString.containsAll(produceDisplayForInt(1)) -> 1 else -> -1 } } fun findNumberForList(toFind: List<String>): Int { return toFind .reversed() .foldIndexed(0) {index: Int, acc: Int, s: String -> acc + findNumber(s) * 10.0.pow(index).toInt() } } } class SevenSegmentsDemystifier { private val input = SevenSegmentsDemystifier::class.java.getResource("/input/puzzle8.txt") ?.readText() ?.split("\n") ?.filter { it.isNotBlank() } ?.map { s: String -> val (patterns, output) = s.split("|").map { it.trim() } InputEntry( patterns.split(" ").map { it.trim() }, output.split(" ").map { it.trim() } ) } ?: listOf() fun countEasyDigits(): Int { var counter = 0 input.forEach { entry: InputEntry -> counter += entry.output.sumOf { val result = when(it.length) { 2, 3, 4, 7 -> 1 else -> 0 } result } } return counter } private fun decryptPattern(patterns: List<String>): DigitWiring { val dividedPatterns = patterns.groupBy { it.length } val segmentOne: Char val segmentTwo: Char val segmentThree: Char val segmentFour: Char val segmentFive: Char val segmentSix: Char val segmentSeven: Char // Extract possibilities for the obvious digits val patternForOne = dividedPatterns.getOrDefault(2, null)?.get(0)?.toList() val patternForSeven = dividedPatterns.getOrDefault(3, null)?.get(0)?.toList() val patternForFour = dividedPatterns.getOrDefault(4, null)?.get(0)?.toList() if (patternForSeven == null || patternForOne == null || patternForFour == null ) { return DigitWiring() } segmentOne = patternForSeven.filterNot { patternForOne.contains(it) }[0] val possibilitiesForSegments3And6 = patternForSeven.filter { patternForOne.contains(it) } val possibilitiesForSegment2And4 = patternForFour.filterNot { patternForOne.contains(it) || it == segmentOne } // Find a 3 in the patterns, this will be a number // with 5 segments, // with all the possibilities for 3 and 6, // with the segment 1, // and with one of the possibilities of the 2 and 4 val patternForThree = dividedPatterns .getOrDefault(5, null) ?.map { it.toList() } ?.filter { it.contains(segmentOne) } ?.filter { it.containsAll(possibilitiesForSegments3And6) } ?.filter { chars -> possibilitiesForSegment2And4.any { chars.contains(it) } } ?.getOrNull(0) if (patternForThree == null) { println("no pattern for 3") return DigitWiring() } segmentFour = patternForThree.filter { possibilitiesForSegment2And4.contains(it) }[0] segmentTwo = possibilitiesForSegment2And4.filterNot { it == segmentFour }[0] segmentSeven = patternForThree.filterNot { it == segmentOne || it == segmentFour || patternForOne.contains(it) }[0] // Next, we find a segment representing a 5, this will be a number with // 5 segments // the segments 1, 2, 4 and 7 in it // one of the segments from the possibilities for 3 and 6 val patternForFive = dividedPatterns .getOrDefault(5, null) ?.map { it.toList()} ?.filter{ it.containsAll(listOf(segmentOne, segmentTwo, segmentFour, segmentSeven)) } ?.filter { list: List<Char> -> possibilitiesForSegments3And6.any { list.contains(it) } } ?.getOrNull(0) if (patternForFive == null) { println("no pattern for 5") return DigitWiring() } segmentSix = patternForFive.filter { possibilitiesForSegments3And6.contains(it) }[0] segmentThree = possibilitiesForSegments3And6.filterNot { it == segmentSix }[0] // Finally, we deduce the last segment segmentFive = "abcdefg".toList().filterNot { listOf(segmentOne, segmentTwo, segmentThree, segmentFour, segmentSix, segmentSeven).contains(it) }[0] return DigitWiring( segmentOne.toString(), segmentTwo.toString(), segmentThree.toString(), segmentFour.toString(), segmentFive.toString(), segmentSix.toString(), segmentSeven.toString() ) } fun findAllDigits(): Int { val display = decryptPattern(input[0].patterns) println("$display -> ${display.findNumberForList(input[0].output)}") return input.fold(0) { acc, inputEntry -> val digitWiring = decryptPattern(inputEntry.patterns) acc + digitWiring.findNumberForList(inputEntry.output) } } }
0
Kotlin
0
1
6d474b30e5204d3bd9c86b50ed657f756a638b2b
7,497
aoc-2021
Apache License 2.0
src/Day02.kt
Akaneiro
572,883,913
false
null
import Shape.Scissors.drawShape import Shape.Scissors.losingShape import Shape.Scissors.winningShape import java.lang.Exception fun main() { fun getShapesList(input: List<String>) = input.map { val inputInline = it.split(" ", limit = 2) val opponent = inputInline.first() val mine = inputInline.last() opponent to mine } fun part1(input: List<String>): Int { val shapesList = getShapesList(input).map { Shape.parseExactShape(it.first) to Shape.parseExactShape(it.second) } return shapesList.map { (opponent, mine) -> mine.score + mine.scoreAccordingToOpponentShape(opponent) }.sum() } fun part2(input: List<String>): Int { val shapesList = getShapesList(input).map { val opponentShape = Shape.parseExactShape(it.first) opponentShape to Shape.parseShapeByWinningStrategy(it.second, opponentShape) } return shapesList.map { (opponent, mine) -> mine.score + mine.scoreAccordingToOpponentShape(opponent) }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } sealed class Shape(val score: Int) { object Rock : Shape(1) object Paper : Shape(2) object Scissors : Shape(3) companion object { fun parseExactShape(char: String) = when (char) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> throw Exception("unknown shape") } fun parseShapeByWinningStrategy(char: String, opponentShape: Shape) = when (char) { "X" -> losingShape(opponentShape) "Y" -> drawShape(opponentShape) "Z" -> winningShape(opponentShape) else -> throw Exception("unknown shape") } } fun losingShape(opponentShape: Shape) = when (opponentShape) { Paper -> Rock Rock -> Scissors Scissors -> Paper } fun winningShape(opponentShape: Shape) = when (opponentShape) { Paper -> Scissors Rock -> Paper Scissors -> Rock } fun drawShape(opponentShape: Shape) = opponentShape fun scoreAccordingToOpponentShape(opponentShape: Shape): Int = when { this == losingShape(opponentShape) -> 0 this == winningShape(opponentShape)-> 6 this == drawShape(opponentShape) -> 3 else -> throw Exception("strange situation...") } }
0
Kotlin
0
0
f987830a70a2a1d9b88696271ef668ba2445331f
2,822
aoc-2022
Apache License 2.0
src/main/kotlin/day19.kt
gautemo
433,582,833
false
{"Kotlin": 91784}
import shared.Point3D import shared.getText import kotlin.math.abs val seenFromScanner0 = mutableSetOf<Point3D>() val scannerLocationsFromScanner0 = mutableSetOf<Point3D>() fun findBeacons(input: String, minimumOverlap: Int = 12): Int{ seenFromScanner0.clear() scannerLocationsFromScanner0.clear() val scanners = input.split("\n\n").map { Scanner(it.lines()) } seenFromScanner0.addAll(scanners.first().points) scannerLocationsFromScanner0.add(Point3D(0,0,0)) do{ for(scanner in scanners.filter { it.id != 0 }){ matchBeacons(scanner, minimumOverlap) } } while(scannerLocationsFromScanner0.size != scanners.size) return seenFromScanner0.size } private fun matchBeacons(scanner: Scanner, minimumOverlap: Int) { for(referencePoint1 in seenFromScanner0){ val rest1 = seenFromScanner0.filter { it != referencePoint1 } for(possiblePoints in scanner.flipFlops()){ for(referencePoint2 in possiblePoints){ val matches = possiblePoints.filter { it != referencePoint2 }.count { hasDistPoint(referencePoint1, rest1, referencePoint2, it) } + 1 if(matches >= minimumOverlap){ val diffX = referencePoint1.x - referencePoint2.x val diffY = referencePoint1.y - referencePoint2.y val diffZ = referencePoint1.z - referencePoint2.z seenFromScanner0.addAll(possiblePoints.map { Point3D(it.x + diffX, it.y + diffY, it.z + diffZ) }) scannerLocationsFromScanner0.add(Point3D(referencePoint1.x-referencePoint2.x,referencePoint1.y-referencePoint2.y,referencePoint1.z-referencePoint2.z)) return } } } } } private fun hasDistPoint(reference1: Point3D, rest1: List<Point3D>, reference2: Point3D, check: Point3D): Boolean{ val checkXDist = reference2.x - check.x val checkYDist = reference2.y - check.y val checkZDist = reference2.z - check.z return rest1.any { val xDist = reference1.x - it.x val yDist = reference1.y - it.y val zDist = reference1.z - it.z xDist == checkXDist && yDist == checkYDist && zDist == checkZDist } } class Scanner(input: List<String>){ val id = Regex("""\d+""").find(input.first())!!.value.toInt() val points: List<Point3D> = input.drop(1).map { beacon -> val points = beacon.split(',') Point3D(points[0].toInt(), points[1].toInt(), points[2].toInt()) } fun flipFlops(): List<List<Point3D>>{ return listOf( points.map { Point3D(it.x, it.y, it.z) }, // 1 points.map { Point3D(-it.y, it.x, it.z) }, // 2 points.map { Point3D(-it.x, -it.y, it.z) }, // 3 points.map { Point3D(it.y, -it.x, it.z) }, // 4 points.map { Point3D(-it.z, it.y, it.x) }, // 5 points.map { Point3D(-it.y, -it.z, it.x) }, // 6 points.map { Point3D(it.z, -it.y, it.x) }, // 7 points.map { Point3D(it.y, it.z, it.x) }, // 8 points.map { Point3D(-it.x, it.z, it.y) }, // 9 points.map { Point3D(-it.z, -it.x, it.y) }, // 10 points.map { Point3D(it.x, -it.z, it.y) }, // 11 points.map { Point3D(it.z, it.x, it.y) }, // 12 points.map { Point3D(-it.x, it.y, -it.z) }, // 13 points.map { Point3D(-it.y, -it.x, -it.z) }, // 14 points.map { Point3D(it.x, -it.y, -it.z) }, // 15 points.map { Point3D(it.y, it.x, -it.z) }, // 16 points.map { Point3D(-it.z, -it.y, -it.x) }, // 17 points.map { Point3D(it.y, -it.z, -it.x) }, // 18 points.map { Point3D(it.z, it.y, -it.x) }, // 19 points.map { Point3D(-it.y, it.z, -it.x) }, // 20 points.map { Point3D(-it.z, it.x, -it.y) }, // 21 points.map { Point3D(-it.x, -it.z, -it.y) }, // 22 points.map { Point3D(it.z, -it.x, -it.y) }, // 23 points.map { Point3D(it.x, it.z, -it.y) }, // 24 ) } } fun main(){ val input = getText("day19.txt") val task1 = findBeacons(input) println(task1) val task2 = largestDistBetweenScanners() println(task2) } fun largestDistBetweenScanners(): Int{ var max = 0 for(scanner1 in scannerLocationsFromScanner0){ for(scanner2 in scannerLocationsFromScanner0){ val dist = abs(scanner1.x-scanner2.x) + abs(scanner1.y-scanner2.y) + abs(scanner1.z-scanner2.z) if(dist > max) max = dist } } return max }
0
Kotlin
0
0
c50d872601ba52474fcf9451a78e3e1bcfa476f7
4,581
AdventOfCode2021
MIT License
src/aoc2023/Day05.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2023 import readInput fun main() { fun part1(lines: List<String>): Long { val seeds = lines[0].substring("seeds: ".length).trim().split(" ").map { it.toLong() } var currentlyTranslating = seeds.toTypedArray() var translated = Array(seeds.size) { 0L } var afterBlank = false for (i in 4 until lines.size) { if (lines[i].isBlank()) { afterBlank = true for ((index, cur) in translated.withIndex()) { if (cur == 0L) { translated[index] = currentlyTranslating[index] } } currentlyTranslating = translated translated = Array(seeds.size) { 0 } continue } if (afterBlank) { afterBlank = false continue } for ((index, current) in currentlyTranslating.withIndex()) { val mapping = lines[i].split(" ").map { it.toLong() } if (current >= mapping[1] && current < mapping[1] + mapping[2]) { translated[index] = mapping[0] + (current - mapping[1]) } } } for ((index, cur) in translated.withIndex()) { if (cur == 0L) { translated[index] = currentlyTranslating[index] } } return translated.min() } // intersect on ranges goe OOM as it does not evaluate to range but list of elements :( fun LongRange.intersect(other: LongRange): LongRange? { var first: LongRange var second: LongRange if (this.first < other.first) { first = this second = other } else { first = other second = this } if (first.last() < second.first()) { return null } return second.first()..Math.min(first.last(), second.last()) } fun part2(lines: List<String>): Long { val currentlyTranslating = mutableListOf<Pair<LongRange, LongRange>>() var afterHeader = false var locationMapping = true for (i in lines.size - 1 downTo 4) { if (lines[i].isBlank() || !lines[i][0].isDigit()) { afterHeader = true continue } if (afterHeader) { afterHeader = false if (locationMapping) { currentlyTranslating.sortWith { a, b -> if (a.first.first - b.first.first > 0) 1 else if (a.first.first == b.first.first) 0 else -1 } if (currentlyTranslating.first().first.first != 0L) { currentlyTranslating.add( 0, Pair( 0 until currentlyTranslating[0].first.first(), 0 until currentlyTranslating[0].first.first() ) ) } } locationMapping = false } if (locationMapping) { val mapping = lines[i].split(" ").map { it.toLong() } currentlyTranslating.add( Pair( (mapping[0] until mapping[0] + mapping[2]), // location (mapping[1] until mapping[1] + mapping[2]) ) ) } else { val mapping = lines[i].split(" ").map { it.toLong() } val from = (mapping[1] until mapping[1] + mapping[2]) val to = (mapping[0] until mapping[0] + mapping[2]) val iterator = currentlyTranslating.iterator() val toAdd = mutableListOf<Pair<LongRange, LongRange>>() while (iterator.hasNext()) { val toTranslate = iterator.next() if (toTranslate.second.intersect(to) != null) { iterator.remove() val intersection = toTranslate.second.intersect(to)!! val fromBeginning = intersection.first() - toTranslate.second.first val fromEnd = toTranslate.second.last - intersection.last() if (fromBeginning > 0) { toAdd.add( Pair( toTranslate.first.first..toTranslate.first.first + fromBeginning - 1, toTranslate.second.first..toTranslate.second.first + fromBeginning - 1 ) ) } if (fromEnd > 0) { toAdd.add( Pair( toTranslate.first.last - (fromEnd - 1)..toTranslate.first.last, toTranslate.second.last - (fromEnd - 1)..toTranslate.second.last ) ) } val fromBeginningSource = intersection.first() - to.first val fromEndSource = to.last - intersection.last() toAdd.add( Pair( toTranslate.first.first + fromBeginning..toTranslate.first.last - fromEnd, from.first + fromBeginningSource..from.last - fromEndSource ) ) } } currentlyTranslating.addAll(toAdd) toAdd.clear() } } val seedRanges = lines[0].substring("seeds: ".length).trim().split(" ").map { it.toLong() } val seeds = mutableListOf<LongRange>() for (i in seedRanges.indices step 2) { seeds.add(seedRanges[i] until seedRanges[i] + seedRanges[i + 1]) } currentlyTranslating.sortWith { a, b -> if (a.first.first - b.first.first > 0) 1 else if (a.first.first == b.first.first) 0 else -1 } for (location in currentlyTranslating) { for (seed in seeds) { if (location.second.intersect(seed) != null) { val intersection = location.second.intersect(seed)!! val fromBeginning = intersection.first() - location.second.first return location.first.first + fromBeginning } } } return -1 } // println(part1(readInput("aoc2023/Day05_test"))) // println(part1(readInput("aoc2023/Day05"))) println(part2(readInput("aoc2023/Day05_test"))) println(part2(readInput("aoc2023/Day05"))) }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
6,809
advent-of-code-kotlin
Apache License 2.0
src/Day10.kt
iam-afk
572,941,009
false
{"Kotlin": 33272}
fun main() { fun part1(input: List<String>): Int { var sum = 0 var x = 1 var c = 20 for (line in input) { val cmd = line.split(' ') val (dx, dc) = when (cmd[0]) { "noop" -> 0 to 1 "addx" -> cmd[1].toInt() to 2 else -> error("unknown command: $line") } if (c / 40 != (c + dc) / 40) { val k = (c + dc) / 40 * 40 - 20 sum += x * k } x += dx c += dc } return sum } fun part2(input: List<String>): List<String> { val d = Array(6) { CharArray(40) { '.' } } var x = 1 var c = 0 for (line in input) { val cmd = line.split(' ') val (dx, dc) = when (cmd[0]) { "noop" -> 0 to 1 "addx" -> cmd[1].toInt() to 2 else -> error("unknown command: $line") } repeat(dc) { val cycle = c + it if (cycle % 40 in x - 1..x + 1) { d[cycle / 40][cycle % 40] = '#' } } x += dx c += dc } return d.map { String(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check( part2(testInput) == listOf( "##..##..##..##..##..##..##..##..##..##..", "###...###...###...###...###...###...###.", "####....####....####....####....####....", "#####.....#####.....#####.....#####.....", "######......######......######......####", "#######.......#######.......#######....." ) ) val input = readInput("Day10") println(part1(input)) part2(input).forEach { println(it) } }
0
Kotlin
0
0
b30c48f7941eedd4a820d8e1ee5f83598789667b
1,925
aockt
Apache License 2.0
kotlin/src/main/kotlin/year2021/Day02.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2021 private enum class Direction(val value: String) { FORWARD("forward"), DOWN("down"), UP("up"); companion object { infix fun from(value: String): Direction? = entries.firstOrNull { it.value == value } } } private class Command(val direction: Direction, val unit: Int) private fun part1(commands: List<Command>): Int { var depth = 0 var horizontal = 0 for (command in commands) { when (command.direction) { Direction.FORWARD -> horizontal += command.unit Direction.DOWN -> depth += command.unit Direction.UP -> depth = if (depth - command.unit > 0) (depth - command.unit) else (0) } } return depth * horizontal } private fun part2(commands: List<Command>): Int { var depth = 0 var horizontal = 0 var aim = 0 for (command in commands) { when (command.direction) { Direction.FORWARD -> { horizontal += command.unit depth += command.unit * aim } Direction.DOWN -> aim += command.unit Direction.UP -> aim -= command.unit } } return depth * horizontal } private fun String.firstWord() = this.split(" ")[0] private fun String.secondWord() = this.split(" ")[1] fun main() { val testCommands = readInput("Day02_test").map { Command(Direction.from(it.firstWord())!!, it.secondWord().toInt()) } check(part1(testCommands) == 150) check(part2(testCommands) == 900) val commands = readInput("Day02").map { Command(Direction.from(it.firstWord())!!, it.secondWord().toInt()) } println(part1(commands)) println(part2(commands)) }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
1,696
advent-of-code
MIT License
src/Day04.kt
Kaaveh
572,838,356
false
{"Kotlin": 13188}
infix fun IntRange.fullyOverlap(other: IntRange): Boolean = (first in other && last in other) || other.first in this && other.last in this private fun parse(row: String): Pair<IntRange, IntRange> { val (section1Start, section1End) = row.substringBefore(",").split("-").map { it.toInt() } val (section2Start, section2End) = row.substringAfter(",").split("-").map { it.toInt() } return section1Start..section1End to section2Start..section2End } private fun part1(input: List<String>): Int = input.count { row -> val (section1, section2) = parse(row = row) section1 fullyOverlap section2 } private fun part2(input: List<String>): Int = input.count { row -> val (section1, section2) = parse(row = row) section1.any { it in section2 } } fun main() { 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
9022f1a275e9c058655898b64c196f7a0a494b48
981
advent-of-code-kotlin-2022
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2022/day14/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2022.day14 import com.kingsleyadio.adventofcode.util.readInput fun main() { val cave = buildCave() part1(cave) part2(cave) } fun part1(cave: Cave) { val sand = hashSetOf<Point>() fun pourSand(grain: IntArray): Boolean { while (true) { val current = Point(grain[0], grain[1]) if (current.x !in cave.leftmost..cave.rightmost || current.y > cave.bottom) return false val down = Point(current.x, current.y + 1) val ld = Point(current.x - 1, down.y) val rd = Point(current.x + 1, down.y) grain[1]++ if (down !in cave.outline && down !in sand) continue else if (ld !in cave.outline && ld !in sand) grain[0]-- else if (rd !in cave.outline && rd !in sand) grain[0]++ else break } grain[1]-- return true } while (true) { val grain = intArrayOf(500, 0) if (pourSand(grain)) sand.add(Point(grain[0], grain[1])) else break } println(sand.size) } fun part2(cave: Cave) { val sand = hashSetOf<Point>() fun pourSand(grain: IntArray): Boolean { while (true) { val current = Point(grain[0], grain[1]) val down = Point(current.x, current.y + 1) val ld = Point(current.x - 1, down.y) val rd = Point(current.x + 1, down.y) grain[1]++ if (down.y == cave.bottom + 2) break // can't move any further if (down !in cave.outline && down !in sand) continue else if (ld !in cave.outline && ld !in sand) grain[0]-- else if (rd !in cave.outline && rd !in sand) grain[0]++ else break } grain[1]-- return Point(grain[0], grain[1]) != Point(500, 0) } while (true) { val grain = intArrayOf(500, 0) if (pourSand(grain)) sand.add(Point(grain[0], grain[1])) else break } println(sand.size + 1) // cater for the last grain blocking the source } fun buildCave(): Cave { var left = Int.MAX_VALUE var right = 0 var bottom = 0 val outline = buildSet { readInput(2022, 14).forEachLine { line -> val spots = line.split(" -> ").map { spot -> val (x, y) = spot.split(",").map(String::toInt) Point(x, y) } spots.zipWithNext().forEach { (start, end) -> val xProgression = if (end.x > start.x) start.x..end.x else end.x..start.x val yProgression = if (end.y > start.y) start.y..end.y else end.y..start.y left = minOf(left, xProgression.first) right = maxOf(right, xProgression.last) bottom = maxOf(bottom, yProgression.last) for (x in xProgression) add(Point(x, start.y)) for (y in yProgression) add(Point(start.x, y)) } } } return Cave(outline, left, right, bottom) } class Cave(val outline: Set<Point>, val leftmost: Int, val rightmost: Int, val bottom: Int) data class Point(val x: Int, val y: Int)
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
3,128
adventofcode
Apache License 2.0
atcoder/arc155/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package atcoder.arc155 private fun solve(a: List<Int>, b: List<Int>): Boolean { if (a.sorted() != b.sorted()) return false val aIsOmnipotent = isOmnipotent(a) val bIsOmnipotent = isOmnipotent(b) val aEven = mutableListOf<Int>() val bEven = mutableListOf<Int>() fun canSortEven(): Boolean { return (aEven.size >= 3 && aEven.sorted() == bEven.sorted()) || aEven == bEven } if (aIsOmnipotent && bIsOmnipotent) { aEven.addAll(a.filter { it % 2 == 0 }) bEven.addAll(b.filter { it % 2 == 0 }) return canSortEven() } if (aIsOmnipotent xor bIsOmnipotent) return false for (i in a.indices) { if (a[i] % 2 != 0) { if (b[i] != a[i]) return false if (!canSortEven()) return false aEven.clear(); bEven.clear() continue } if (b[i] % 2 != 0) return false aEven.add(a[i]); bEven.add(b[i]) } if (!canSortEven()) return false return true } private fun isOmnipotent(a: List<Int>): Boolean { for (i in 0..a.size - 3) { if ((a[i] + a[i + 1] + a[i + 2]) % 2 == 0 && (a[i] % 2 != 0 || a[i + 1] % 2 != 0 || a[i + 2] % 2 != 0)) return true } return false } fun main() { readInt() val a = readInts() val b = readInts() println(solve(a, b).iif("Yes", "No")) } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() } private fun <T> Boolean.iif(onTrue: T, onFalse: T) = if (this) onTrue else onFalse
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,457
competitions
The Unlicense
src/day05/Day05.kt
robin-schoch
572,718,550
false
{"Kotlin": 26220}
package day05 import AdventOfCodeSolution fun main() { Day05.run() } object Day05 : AdventOfCodeSolution<String, String> { override val testSolution1 = "CMZ" override val testSolution2 = "MCD" private val stacks = mutableMapOf<Int, ArrayDeque<Char>>() private fun constructStacks(intput: List<String>) { stacks.clear() intput .takeWhile { !it.startsWith(" 1") } .flatMap { it.windowed(3, 4) .mapIndexed { index, s -> index + 1 to s } .filter { (_, container) -> container.isNotBlank() } }.forEach { (stack, container) -> stacks.computeIfPresent(stack) { _, tower -> tower.addLast(container[1]).let { tower } } stacks.putIfAbsent(stack, ArrayDeque(listOf(container[1]))) } } private fun readSolution() = stacks .map { it.key to it.value.first() } .sortedBy { it.first } .joinToString(separator = "") { it.second.uppercase() } private fun readInstructions(input: List<String>) = input.filter { it.startsWith('m') } .map { it.split(" ") } .map { Triple(it[1].toInt(), it[3].toInt(), it[5].toInt()) } override fun part1(input: List<String>): String { constructStacks(input) readInstructions(input) .forEach { (count, fromIndex, toIndex) -> repeat(count) { stacks[toIndex]!!.addFirst(stacks[fromIndex]!!.removeFirst()) } } return readSolution() } override fun part2(input: List<String>): String { constructStacks(input) readInstructions(input) .forEach { (count, fromIndex, toIndex) -> val crane = mutableListOf<Char>() repeat(count) { crane.add(stacks[fromIndex]!!.removeFirst()) } crane.reversed().forEach { stacks[toIndex]!!.addFirst(it) } } return readSolution() } }
0
Kotlin
0
0
fa993787cbeee21ab103d2ce7a02033561e3fac3
1,975
aoc-2022
Apache License 2.0
src/Day02.kt
arturradiuk
571,954,377
false
{"Kotlin": 6340}
fun calculateScore(round: List<Char>): Int = when (round.last() - round.first()) { 21, 24 -> 6 + round.last().code - 87 9, 23 -> 3 + round.last().code - 87 else -> round.last().code - 87 } fun calculateScoreWithInstruction(round: List<Char>): Int = when (round.last()) { 'X' -> (round.first().code).mod(3) + 1 // lose 'Y' -> 3 + (round.first().code + 1).mod(3) + 1 // draw 'Z' -> 6 + 1 + (round.first().code + 2).mod(3) // win else -> throw Exception() } fun main() { fun part1(input: String): Int = input .lines() .flatMap { it.split(" ") }.map(String::first) .windowed(size = 2, step = 2) .map(::calculateScore) .sum() fun part2(input: String): Int = input .lines() .flatMap { it.split(" ") }.map(String::first) .windowed(size = 2, step = 2) .map(::calculateScoreWithInstruction) .sum() val input = readInputToString("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
85ef357643e5e4bd2ba0d9a09f4a2d45653a8e28
1,048
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
Krzychuk9
573,127,179
false
null
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val opponentStrategy = getGameStrategy(it[0]) val strategy = getGameStrategy(it[2]) strategy.getResult(opponentStrategy) + strategy.getPoint() } } fun part2(input: List<String>): Int { return input.sumOf { val opponentStrategy = getGameStrategy(it[0]) val strategy = getGameStrategy(opponentStrategy, it[2]) strategy.getResult(opponentStrategy) + strategy.getPoint() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun getGameStrategy(type: Char) = when (type) { 'A', 'X' -> RockStrategy() 'B', 'Y' -> PaperStrategy() 'C', 'Z' -> ScissorsStrategy() else -> throw IllegalArgumentException() } fun getGameStrategy(opponentStrategy: GameStrategy, result: Char) = when (result) { 'X' -> opponentStrategy.getLose() 'Y' -> opponentStrategy 'Z' -> opponentStrategy.getWin() else -> throw IllegalArgumentException() } sealed interface GameStrategy { fun getResult(opponentStrategy: GameStrategy): Int fun getPoint(): Int fun getWin(): GameStrategy fun getLose(): GameStrategy } class RockStrategy() : GameStrategy { override fun getResult(opponentStrategy: GameStrategy) = when (opponentStrategy) { is ScissorsStrategy -> 6 is RockStrategy -> 3 is PaperStrategy -> 0 } override fun getPoint() = 1 override fun getWin() = PaperStrategy() override fun getLose() = ScissorsStrategy() } class PaperStrategy() : GameStrategy { override fun getResult(opponentStrategy: GameStrategy) = when (opponentStrategy) { is RockStrategy -> 6 is PaperStrategy -> 3 is ScissorsStrategy -> 0 } override fun getPoint() = 2 override fun getWin() = ScissorsStrategy() override fun getLose() = RockStrategy() } class ScissorsStrategy() : GameStrategy { override fun getResult(opponentStrategy: GameStrategy) = when (opponentStrategy) { is PaperStrategy -> 6 is ScissorsStrategy -> 3 is RockStrategy -> 0 } override fun getPoint() = 3 override fun getWin() = RockStrategy() override fun getLose() = PaperStrategy() }
0
Kotlin
0
0
ded55d03c9d4586166bf761c7d5f3f45ac968e81
2,518
adventOfCode2022
Apache License 2.0
src/Day02.kt
fex42
575,013,600
false
{"Kotlin": 4342}
import java.lang.IllegalStateException enum class Thing { ROCK, PAPER, SCISOR } enum class Result { WIN, LOOSE, DRAW } fun result(player: Thing, opponent: Thing): Result = when (player) { Thing.ROCK -> when (opponent) { Thing.ROCK -> Result.DRAW Thing.PAPER -> Result.LOOSE Thing.SCISOR -> Result.WIN } Thing.PAPER -> when (opponent) { Thing.ROCK -> Result.WIN Thing.PAPER -> Result.DRAW Thing.SCISOR -> Result.LOOSE } Thing.SCISOR -> when (opponent) { Thing.ROCK -> Result.LOOSE Thing.PAPER -> Result.WIN Thing.SCISOR -> Result.DRAW } } fun move(player: Thing, result: Result): Thing = when (player) { Thing.ROCK -> when (result) { Result.WIN -> Thing.PAPER Result.LOOSE -> Thing.SCISOR Result.DRAW -> Thing.ROCK } Thing.PAPER -> when (result) { Result.WIN -> Thing.SCISOR Result.LOOSE -> Thing.ROCK Result.DRAW -> Thing.PAPER } Thing.SCISOR -> when (result) { Result.WIN -> Thing.ROCK Result.LOOSE -> Thing.PAPER Result.DRAW -> Thing.SCISOR } } fun String.toThing() = when (this) { "A" -> Thing.ROCK "B" -> Thing.PAPER "C" -> Thing.SCISOR "X" -> Thing.ROCK "Y" -> Thing.PAPER "Z" -> Thing.SCISOR else -> throw IllegalStateException("unknown: $this") } fun String.toResult() = when (this) { "X" -> Result.LOOSE "Y" -> Result.DRAW "Z" -> Result.WIN else -> throw IllegalStateException("unknown: $this") } fun Thing.points() = when (this) { Thing.ROCK -> 1 Thing.PAPER -> 2 Thing.SCISOR -> 3 } fun Result.points() = when (this) { Result.WIN -> 6 Result.LOOSE -> 0 Result.DRAW -> 3 } fun main() { fun part1(input: List<String>): Int { val l1 = input.map { it.split(" ").map(String::toThing) }.map { list -> Pair(list[0], list[1]) } return l1.map { move -> move.second.points() + result(move.second, move.first).points() }.sum() } fun part2(input: List<String>): Int { val r = input.map { it.split(" ") }.map { Pair(it[0].toThing(), it[1].toResult()) }.map { (opponentThing, result) -> move(opponentThing, result).points() + result.points() }.sum() return r } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dd5d9ff58afc615bcac0fd76b86e737833eb7576
2,811
AuC-2022
Apache License 2.0
yacht/src/main/kotlin/YachtCategory.kt
3mtee
98,672,009
false
null
internal fun countDices(dices: List<Int>, digit: Int) = dices.filter { it == digit }.sum() enum class YachtCategory(val score: (dices: List<Int>) -> Int) { YACHT({ if (it.toSet().size == 1) 50 else 0 }), ONES({ countDices(it, 1) }), TWOS({ countDices(it, 2) }), THREES({ countDices(it, 3) }), FOURS({ countDices(it, 4) }), FIVES({ countDices(it, 5) }), SIXES({ countDices(it, 6) }), FULL_HOUSE({ dices -> dices .groupingBy { it } .eachCount() .let { if (it.values.toSet() != setOf(2,3)) { emptyMap() } else { it } } .entries .filter { it.value == 2 || it.value == 3 } .sumOf { it.key * it.value } }), FOUR_OF_A_KIND({ dices -> dices .groupingBy { it } .eachCount() .entries .filter { it.value >= 4 } .sumOf { it.key * 4 } }), LITTLE_STRAIGHT({ if (it.sorted() == listOf(1, 2, 3, 4, 5)) 30 else 0 }), BIG_STRAIGHT({ if (it.sorted() == listOf(2, 3, 4, 5, 6)) 30 else 0 }), CHOICE({ it.sum() }) }
0
Kotlin
0
0
6e3eb88cf58d7f01af2236e8d4727f3cd5840065
1,200
exercism-kotlin
Apache License 2.0
src/Day10.kt
andrikeev
574,393,673
false
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
fun main() { fun List<String>.mapToOps(): List<Op> = this.map { it.split(" ") } .map { if (it[0] == "noop") Op.Nop else Op.AddX(it[1].toInt()) } fun part1(input: List<String>): Int { val timestamps = setOf(20, 60, 100, 140, 180, 220) return sequence { var cyclesCounter = 1 var x = 1 input .mapToOps() .forEach { op -> cyclesCounter++ if (cyclesCounter in timestamps) { yield(cyclesCounter * x) } if (op is Op.AddX) { cyclesCounter++ x += op.value if (cyclesCounter in timestamps) { yield(cyclesCounter * x) } } } }.sum() } fun part2(input: List<String>) { val sprite = Sprite() var cyclesCounter = 0 var x = 1 fun tick() { val drawPixelIndex = cyclesCounter % 40 if (drawPixelIndex in sprite.pixels) { print("#") } else { print(".") } cyclesCounter++ if (cyclesCounter % 40 == 0) { println() } } input .mapToOps() .forEach { op -> when (op) { is Op.Nop -> tick() is Op.AddX -> { tick() tick() x += op.value sprite.position = x } } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput).also { println(it) } == 13140) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) } private sealed interface Op { val length: Int val value: Int data class AddX(override val value: Int) : Op { override val length = 2 } object Nop : Op { override val length = 1 override val value = 0 } } private class Sprite { var position: Int = 1 val pixels: IntRange get() = (position - 1..position + 1) }
0
Kotlin
0
1
1aedc6c61407a28e0abcad86e2fdfe0b41add139
2,394
aoc-2022
Apache License 2.0
src/year2021/day04/Day04.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2021.day01.day04 import util.assertTrue import util.read2021DayInput fun main() { val input = read2021DayInput("Day04") fun task01() = calculateScores(input).first().first fun task02() = calculateScores(input).last().first assertTrue(task01() == 63424) assertTrue(task02() == 23541) } fun calculateScores(input: List<String>): MutableList<Pair<Int, Int>> { val list = input.map { it.replace(" ", ",").split(",").filter { it.isNotBlank() } } val drawnOrder = list[0] val bingoList = mutableListOf<MutableList<MutableList<String>>>() list.drop(1).toMutableList().forEach { if (it.isEmpty()) bingoList.add(mutableListOf()) else bingoList[bingoList.size - 1].add(it as MutableList<String>) } val scoreList = mutableListOf<Pair<Int, Int>>() drawnOrder.forEachIndexed { i, number -> val numbersDrawn = drawnOrder.take(i + 1) bingoList.forEachIndexed { j, board -> if (checkBingo(board, numbersDrawn) && !scoreList.any { it.second == j }) { val uncheckedNumbers = board.map { it.filter { !numbersDrawn.contains(it) } } scoreList.add(Pair(uncheckedNumbers.flatten().sumOf { it.toInt() } * number.toInt(), j)) } } } return scoreList } fun checkBingo(bingoBoard: MutableList<MutableList<String>>, numbersDrawn: List<String>): Boolean { bingoBoard.forEachIndexed { i, column -> if (numbersDrawn.containsAll(column)) return true // horizontal if (numbersDrawn.containsAll(column.mapIndexed { l, _ -> bingoBoard[l][i] })) return true // vertical } return false }
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
1,639
advent-of-code-kotlin-template
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1293/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1293 /** * LeetCode page: [1293. Shortest Path in a Grid with Obstacles Elimination](https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/); */ class Solution { /* Complexity: * Time O(MNK) and Space O(MN) where M and N are the number of rows and columns of grid and K equals k; */ fun shortestPath(grid: Array<IntArray>, k: Int): Int { val totalRows = grid.size val totalColumns = grid[0].size val isSingleCell = totalRows == 1 && totalColumns == 1 if (isSingleCell) return 0 val directions = Direction.values() var pathLength = 0 val maxAvailableElimination = List(totalRows) { IntArray(totalColumns) { -1 } } val stateQueue = ArrayDeque<State>() stateQueue.addLast(State(0, 0, k)) while (stateQueue.isNotEmpty()) { repeat(stateQueue.size) { val state = stateQueue.removeFirst() with(state) { val canEliminateMore = availableElimination > maxAvailableElimination[row][column] if (canEliminateMore) { maxAvailableElimination[row][column] = availableElimination for (direction in directions) { val nextState = state.moveOrNull(direction, grid) ?: continue stateQueue.addLast(nextState) val reachGoal = nextState.row == totalRows - 1 && nextState.column == totalColumns - 1 if (reachGoal) return pathLength + 1 } } } } pathLength++ } return -1 } private enum class Direction(val rowChange: Int, val columnChange: Int) { North(-1, 0), South(1, 0), West(0, -1), East(0, 1) } private class State(val row: Int, val column: Int, val availableElimination: Int) private fun State.moveOrNull(direction: Direction, grid: Array<IntArray>): State? { val newRow = row + direction.rowChange val newColumn = column + direction.columnChange val isOutOfGrid = newRow !in grid.indices || newColumn !in grid[newRow].indices if (isOutOfGrid) return null val newAvailableElimination = availableElimination - grid[newRow][newColumn] val cannotReach = newAvailableElimination < 0 if (cannotReach) return null return State(newRow, newColumn, newAvailableElimination) } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,594
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/adventofcode2022/solution/day_14.kt
dangerground
579,293,233
false
{"Kotlin": 51472}
package adventofcode2022.solution import adventofcode2022.util.readDay import kotlin.math.max import kotlin.math.min fun main() { Day14("14").solve() } class Day14(private val num: String) { private val inputText = readDay(num) fun solve() { println("Day $num Solution") println("* Part 1: ${solution1()}") println("* Part 2: ${solution2()}") } fun solution1(): Int { val sandCastle = SandCastle() parseLineSegments().forEach { sandCastle.add(it) } while (sandCastle.pourSand(500, 0)) { // just loop } sandCastle.debug() return sandCastle.countSand() } private fun parseLineSegments(): MutableList<LineSegment> { val segments = mutableListOf<LineSegment>() inputText.lines() .map { it.split(" -> ").map { it.parsePoint() } } .forEach { linePoints -> for (i in 0 until linePoints.size - 1) { segments.add(LineSegment(linePoints[i], linePoints[i + 1])) } } return segments } fun solution2(): Int { val sandCastle = SandCastle() parseLineSegments().forEach { sandCastle.add(it) } val height = sandCastle.maxY + 2 val startX = 500 val floor = LineSegment(Point(startX - height, height), Point(startX + height, height)) println("floor: $floor") sandCastle.add(floor) while (sandCastle.pourSand(500, 0)) { // just loop } sandCastle.debug() return sandCastle.countSand() } } data class LineSegment(val p1: Point, val p2: Point) { override fun toString(): String { return "${p1.str()} -> ${p2.str()}" } } fun String.parsePoint() = split(",").let { Point(it[0].toInt(), it[1].toInt()) } fun Point.str() = "$x,$y" enum class SandType { ROCK, SAND } class SandCastle : HashMap<Int, MutableMap<Int, SandType>>() { private var maxX = 0 private var minX = 9999 var maxY = 0 private var minY = 0 fun add(l: LineSegment) { minX = min(minX, min(l.p1.x, l.p2.x)) //minY = min(minY, min(l.p1.y, l.p2.y)) maxX = max(maxX, max(l.p1.x, l.p2.x)) maxY = max(maxY, max(l.p1.y, l.p2.y)) val yRange = if (l.p1.y < l.p2.y) IntRange(l.p1.y, l.p2.y) else IntRange(l.p2.y, l.p1.y) val xRange = if (l.p1.x < l.p2.x) IntRange(l.p1.x, l.p2.x) else IntRange(l.p2.x, l.p1.x) for (y in yRange) { for (x in xRange) { set(x, y, SandType.ROCK) } } } private fun set(x: Int, y: Int, type: SandType) { putIfAbsent(y, mutableMapOf()) get(y)!![x] = type } private fun get(x: Int, y: Int) = get(y)?.get(x) fun debug() { println("Debug: ($minX,$minY)-($maxX,$maxY)") for (y in minY..maxY) { for (x in minX..maxX) { val type = get(x, y) if (type == SandType.ROCK) { print("#") } else if (type == SandType.SAND) { print("O") } else { print(".") } } println() } } fun countSand() = values.sumOf { it.values.count { it == SandType.SAND } } fun pourSand(startX: Int, startY: Int): Boolean { //debug() var falling = true var x = startX var y = startY do { if (get(x, y + 1) == null) { // println("down $$x,$y)") y++ } else if (get(x - 1, y + 1) == null) { // println("left $$x,$y)") y++ x-- } else if (get(x + 1, y + 1) == null) { //println("right $$x,$y)") y++ x++ } else { if (x == startX && y == startY) { set(x, y, SandType.SAND) return false } else { falling = false } } if (y > maxY) { println("maxxx $$x,$y )$maxY") return false } } while (falling) // println("add $x,$y") set(x, y, SandType.SAND) return true } }
0
Kotlin
0
0
f1094ba3ead165adaadce6cffd5f3e78d6505724
4,389
adventofcode-2022
MIT License
src/main/kotlin/advent/y2018/day5.kt
IgorPerikov
134,053,571
false
{"Kotlin": 29606}
package advent.y2018 import misc.readAdventInput import java.util.* fun main(args: Array<String>) { val polymersChain = readAdventInput(5, 2018)[0] println(remainUnitsAfterAllReactions(polymersChain)) println(leastPossiblePolymerChainAfterRemovingAny(polymersChain)) } private fun leastPossiblePolymerChainAfterRemovingAny(polymers: String): Int { val allChars = polymers.toCharArray().map { it.toLowerCase().toString() }.distinct() return allChars .map { removedChar -> remainUnitsAfterAllReactions(polymers.replace(removedChar, "", ignoreCase = true)) } .min()!! } private fun remainUnitsAfterAllReactions(polymers: String): Int { val indexesOfRemainedPolymers: TreeSet<Int> = TreeSet() for (i in 0 until polymers.length) { indexesOfRemainedPolymers.add(i) } var left = 0 var right = 1 var reactions = 0 while (true) { if (left >= polymers.length || right >= polymers.length) { break } if (shouldReact(polymers[left], polymers[right])) { reactions++ indexesOfRemainedPolymers.remove(left) indexesOfRemainedPolymers.remove(right) val closestOneToTheLeft = getClosestOneToTheLeft(left, indexesOfRemainedPolymers) if (closestOneToTheLeft == null) { left = right + 1 right += 2 } else { left = closestOneToTheLeft right++ } } else { left = right right++ } } return polymers.length - reactions * 2 } private fun getClosestOneToTheLeft(left: Int, indexesOfRemainedPolymers: TreeSet<Int>): Int? { return indexesOfRemainedPolymers.floor(left - 1) } private fun shouldReact(a: Char, b: Char): Boolean { return (a.isLowerCase() && b.isUpperCase() && a.toUpperCase() == b) || (b.isLowerCase() && a.isUpperCase() && b.toUpperCase() == a) }
0
Kotlin
0
0
b30cf179f7b7ae534ee55d432b13859b77bbc4b7
1,980
kotlin-solutions
MIT License
src/Day13.kt
buongarzoni
572,991,996
false
{"Kotlin": 26251}
fun solveDay13() { val lines = readInput("Day13") solve(lines) } private fun solve( input: List<String>, ) { val packets = input .chunked(3) .flatMap { line -> line .take(2) .map { it.parsePacketData() } } val part1 = packets .chunked(2) .mapIndexed { zeroIndex, (first, second) -> if (first < second) zeroIndex + 1 else 0 }.sum() println("Solution part 1 : $part1") val firstDivider = "[[2]]".parsePacketData() val secondDivider = "[[6]]".parsePacketData() val sortedPackets = (packets + listOf(firstDivider, secondDivider)).sorted() val part2 = (sortedPackets.indexOf(firstDivider) + 1) * (sortedPackets.indexOf(secondDivider) + 1) println("Solution part 2 : $part2") } sealed interface PacketData : Comparable<PacketData> @JvmInline value class Values(val values: List<PacketData>) : PacketData { override operator fun compareTo(other: PacketData): Int = when (other) { is Values -> values.zip(other.values).asSequence() .map { (a, b) -> a.compareTo(b) } .firstOrNull { it != 0 } ?: values.size.compareTo(other.values.size) else -> compareTo(Values(listOf(other))) } } @JvmInline value class Value(val int: Int) : PacketData { override operator fun compareTo(other: PacketData) = when (other) { is Value -> int.compareTo(other.int) else -> Values(listOf(this)).compareTo(other) } } fun String.parsePacketData(): PacketData { if (!startsWith("[")) return Value(toInt()) val innerData = mutableListOf<PacketData>() val remaining = ArrayDeque(drop(1).toList()) while (remaining.size > 1) { val innerLine = mutableListOf<Char>() var braceCounter = 0 while (true) { val character = remaining.removeFirst() when (character) { '[' -> braceCounter++ ']' -> { braceCounter-- if (braceCounter < 0) break } ',' -> if (braceCounter == 0) break } innerLine.add(character) } innerData.add(innerLine.joinToString("").parsePacketData()) } return Values(innerData) }
0
Kotlin
0
0
96aadef37d79bcd9880dbc540e36984fb0f83ce0
2,298
AoC-2022
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2022/Day8.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2022 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report class Day8: AdventDay(2022, 8) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day8() report { day.part1() } report { day.part2() } } } fun parseInput(lines: List<String>): Pair<List<List<Int>>, List<List<Int>>> { val rows = lines.map { line -> line.map { it.digitToInt() }} val columns = List(lines.size) { m -> rows.map { it[m] } } return columns to rows } fun findVisible(columns: List<List<Int>>, rows: List<List<Int>>): Int { val visible = List(rows.size) { MutableList(columns.size) { false } } for (i in rows.indices) { for (j in columns.indices) { visible[i][j] = rows[i].visible(j) || columns[j].visible(i) } } return visible.sumOf { it.count { it }} } fun findScenicScore(columns: List<List<Int>>, rows: List<List<Int>>): Int { var scenicScore = -1 rows.forEachIndexed { i, r -> columns.forEachIndexed { j, c -> scenicScore = maxOf(scenicScore, (i to j).scenicScore(r, c)) } } return scenicScore } fun part1(): Int { val (columns, rows) = parseInput(inputAsLines) return findVisible(columns, rows) } fun part2(): Int { val (columns, rows) = parseInput(inputAsLines) return findScenicScore(columns, rows) } fun Pair<Int, Int>.scenicScore(row: List<Int>, column: List<Int>): Int { val right = row.scenicScore(second) val left = row.reversed().scenicScore(row.size - 1 - second) val down = column.scenicScore(first) val up = column.reversed().scenicScore(column.size - 1 - first) return right*left*up*down } fun List<Int>.scenicScore(i: Int): Int { val rest = drop(i + 1) return if (rest.none { it >= get(i) }) rest.count() else 1 + rest.takeWhile { it < get(i) }.count() } fun List<Int>.visible(i: Int) = drop(i + 1).none { it >= get(i) } || reversed().drop(size - i).none { it >= get(i) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,284
adventofcode
MIT License
src/Day03.kt
kkaptur
573,511,972
false
{"Kotlin": 14524}
fun main() { fun part1(input: List<String>): Int { var score = 0 var firstCompartment = emptySet<Char>() var secondCompartment = emptySet<Char>() input.forEach { rucksack -> firstCompartment = rucksack.subSequence(0, (rucksack.length / 2)).toSet() secondCompartment = rucksack.subSequence((rucksack.length / 2), rucksack.length).toSet() firstCompartment.filter { secondCompartment.contains(it) }.forEach { score += if (it.isUpperCase()) it.code - 65 + 27 else it.code - 97 + 1 } } return score } fun part2(input: List<String>): Int { var score = 0 input.chunked(3).forEach { group -> group[0].toCharArray().toSet() .filter { group[1].contains(it) } .filter { group[2].contains(it) } .forEach { score += if (it.isUpperCase()) it.code - 65 + 27 else it.code - 97 + 1 } } return score } 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
055073b7c073c8c1daabbfd293139fecf412632a
1,369
AdventOfCode2022Kotlin
Apache License 2.0
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p09/Leet983.kt
artemkaxboy
513,636,701
false
{"Kotlin": 547181, "Java": 13948}
package com.artemkaxboy.leetcode.p09 import java.util.TreeMap import kotlin.system.measureTimeMillis /** * You have planned some train traveling one year in advance. The days of the year in which you will travel are given * as an integer array days. Each day is an integer from 1 to 365. * * Train tickets are sold in three different ways: * * a 1-day pass is sold for costs[0] dollars, * a 7-day pass is sold for costs[1] dollars, and * a 30-day pass is sold for costs[2] dollars. * The passes allow that many days of consecutive travel. * * For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8. * Return the minimum number of dollars you need to travel every day in the given list of days. */ class Leet983 { private val map = TreeMap<Int, Int>() fun mincostTickets(days: IntArray, costs: IntArray): Int { (listOf(0) + days.asList()).zipWithNext().forEach { (prev, it) -> calcFor(prev, it, costs) } println(map) return findLowestValueAfterKey(days.last()) } private fun calcFor(prevDay: Int, day: Int, costs: IntArray) { val offset = findLowestValueAfterKey(prevDay) map[day + 1] = minOfNullableMax(map[day + 1], offset + costs[0]) map[day + 7] = minOfNullableMax(map[day + 7], offset + costs[1]) map[day + 30] = minOfNullableMax(map[day + 30], offset + costs[2]) } private fun minOfNullableMax(a: Int?, b: Int) = minOf(a ?: Int.MAX_VALUE, b) private fun findLowestValueAfterKey(keyGt: Int): Int { return minOrNull(map.filterKeys { key -> key > keyGt }.values) ?: 0 } private fun minOrNull(iterable: Iterable<Int>): Int? { val iterator = iterable.iterator() if (!iterator.hasNext()) return null var min = Int.MAX_VALUE while (iterator.hasNext()) { val candidate = iterator.next() if (candidate < min) min = candidate } return min } } fun main() { measureTimeMillis { // println(Leet983().mincostTickets(intArrayOf(1, 4, 6, 7, 8, 20), intArrayOf(2, 7, 15))) // 11 println(Leet983().mincostTickets(intArrayOf(1, 4, 6, 7, 8, 20), intArrayOf(7, 2, 15))) // 6 // println(Leet983().mincostTickets(intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31), intArrayOf(2, 7, 15))) // 17 // println( // Leet983().mincostTickets( // intArrayOf(1, 4, 6, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 27, 28), // intArrayOf(3, 13, 45) // ) // ) // 44 // println(Leet983().mincostTickets(intArrayOf(1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 24, 25, 27, 28, 29, 30, 31, 34, 37, 38, 39, 41, 43, 44, 45, 47, 48, 49, 54, 57, 60, 62, 63, 66, 69, 70, 72, 74, 76, 78, 80, 81, 82, 83, 84, 85, 88, 89, 91, 93, 94, 97, 99), intArrayOf(9, 38, 134))) // ?? // println(Leet983().mincostTickets(intArrayOf(2, 3, 5, 6, 7, 8, 9, 10, 11, 17, 18, 19, 23, 26, 27, 29, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 45, 47, 51, 54, 55, 57, 58, 64, 65, 67, 68, 72, 73, 74, 75, 77, 78, 81, 86, 87, 88, 89, 91, 93, 94, 95, 96, 98, 99), intArrayOf(5, 24, 85))) // ?? }.also { println("Time: ${it}ms") } }
0
Kotlin
0
0
516a8a05112e57eb922b9a272f8fd5209b7d0727
3,264
playground
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions8.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test8() { printlnResult(intArrayOf(5, 1, 4, 3), 7) } /** * Questions 8: Given an IntArray and an integer k, find the shortest continues sub-array that sum equals or greater than k */ private infix fun IntArray.findShortestSizeOfSubArray(k: Int): Int { require(isNotEmpty()) { "The IntArray can't be empty" } var shortestSize = 0 repeat(size) { i -> var j = i + 1 while (j < size) { val sum = subSum(i, j) if (sum >= k) { val newSize = j - i + 1 if (shortestSize == 0 || newSize < shortestSize) shortestSize = newSize break } else j++ } } return shortestSize } private fun IntArray.subSum(i: Int, j: Int): Int { var sum = 0 for (index in i..j) sum += this[index] return sum } private fun printlnResult(array: IntArray, k: Int) = println("The shortest size is (${array findShortestSizeOfSubArray k}) of sub-array in IntArray: ${array.toList()} that sum equals or greater than $k")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,105
Algorithm
Apache License 2.0
src/Day05.kt
ChAoSUnItY
572,814,842
false
{"Kotlin": 19036}
import java.util.* fun main() { val instructionRegex = Regex("\\d+") data class Instruction(val count: Int, val from: Int, val to: Int) fun parseStackData(data: List<String>): List<LinkedList<Char>> { val stackSize = (data[0].length + 1) / 4 val stacks = MutableList(stackSize) { LinkedList<Char>() } for (line in data.dropLast(1)) { val layerElements = line.chunked(4) for ((i, element) in layerElements.withIndex()) { if (element.isBlank()) continue stacks[i].add(element[1]) } } return stacks } fun processInstructions(data: List<String>): List<Instruction> = data.map { val (count, from, to) = instructionRegex.findAll(it) .map { match -> match.value.toInt() } .toList() Instruction(count, from, to) } fun processData(data: List<String>): Pair<List<LinkedList<Char>>, List<Instruction>> { val (stackGraph, instructions) = data.joinToString("\n") .split("\n\n") .map { it.split("\n") } return parseStackData(stackGraph) to processInstructions(instructions) } fun part1(data: Pair<List<LinkedList<Char>>, List<Instruction>>): String { val (stacks, instructions) = data for ((count, from, to) in instructions) { (0 until count).map { stacks[from - 1].pop() } .forEach { stacks[to - 1].push(it) } } return stacks.map(LinkedList<Char>::peek) .joinToString("") } fun part2(data: Pair<List<LinkedList<Char>>, List<Instruction>>): String { val (stacks, instructions) = data for ((count, from, to) in instructions) { (0 until count).map { stacks[from - 1].pop() } .reversed() .forEach { stacks[to - 1].push(it) } } return stacks.map(LinkedList<Char>::peek) .joinToString("") } val input = readInput("Day05") println(part1(processData(input))) println(part2(processData(input))) }
0
Kotlin
0
3
4fae89104aba1428820821dbf050822750a736bb
2,129
advent-of-code-2022-kt
Apache License 2.0
src/Day11.kt
hrach
572,585,537
false
{"Kotlin": 32838}
data class Monkey( val items: MutableList<Long>, val op: (Long) -> Long, val divBy: Int, val divByTrue: Int, val divByFalse: Int, ) { var inspectCount = 0 } val testInput get() = listOf( Monkey(mutableListOf(79, 98), { it * 19 }, 23, 2, 3), Monkey(mutableListOf(54, 65, 75, 74), { it + 6 }, 19, 2, 0), Monkey(mutableListOf(79, 60, 97), { it * it }, 13, 1, 3), Monkey(mutableListOf(74), { it + 3 }, 17, 0, 1), ) val finalInput get() = listOf( Monkey(mutableListOf(71, 56, 50, 73), { it * 11 }, 13, 1, 7), Monkey(mutableListOf(70, 89, 82), { it + 1 }, 7, 3, 6), Monkey(mutableListOf(52, 95), { it * it }, 3, 5, 4), Monkey(mutableListOf(94, 64, 69, 87, 70), { it + 2 }, 19, 2, 6), Monkey(mutableListOf(98, 72, 98, 53, 97, 51), { it + 6 }, 5, 0, 5), Monkey(mutableListOf(79), { it + 7 }, 2, 7, 0), Monkey(mutableListOf(77, 55, 63, 93, 66, 90, 88, 71), { it * 7 }, 11, 2, 4), Monkey(mutableListOf(54, 97, 87, 70, 59, 82, 59), { it + 8 }, 17, 1, 3), ) fun main() { fun part1(monkeys: List<Monkey>): Long { repeat(20) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { monkey.inspectCount += 1 val item = monkey.items.removeFirst() val level = monkey.op(item).floorDiv(3) val toMonkey = when (level.rem(monkey.divBy) == 0L) { true -> monkey.divByTrue false -> monkey.divByFalse } monkeys[toMonkey].items.add(level) } } } return monkeys .sortedByDescending { it.inspectCount.toLong() } .take(2) .fold(1) { acc, monkey -> acc * monkey.inspectCount } } fun part2(monkeys: List<Monkey>): Long { val product = monkeys.fold(1) { acc, m -> acc * m.divBy } repeat(10000) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { monkey.inspectCount += 1 val item = monkey.items.removeFirst() val level = monkey.op(item) val toMonkey = when (level.rem(monkey.divBy) == 0L) { true -> monkey.divByTrue false -> monkey.divByFalse } monkeys[toMonkey].items.add(level.rem(product)) } } } return monkeys .sortedByDescending { it.inspectCount } .take(2) .fold(1) { acc, monkey -> acc * monkey.inspectCount } } check(part1(testInput), 10605L) check(part2(testInput), 2713310158) println(part1(finalInput)) println(part2(finalInput)) }
0
Kotlin
0
1
40b341a527060c23ff44ebfe9a7e5443f76eadf3
2,880
aoc-2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch3/Problem35.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch3 import dev.bogwalk.util.maths.isPrime import dev.bogwalk.util.maths.primeNumbers import dev.bogwalk.util.search.binarySearch /** * Problem 35: Circular Primes * * https://projecteuler.net/problem=35 * * Goal: Find the sum of all circular primes less than N, with rotations allowed to exceed N, & * the rotations themselves allowed as duplicates if below N. * * Constraints: 10 <= N <= 1e6 * * Circular Prime: All rotations of the number's digits are themselves prime. * e.g. 197 -> {197, 719, 971}. * * e.g.: N = 100 * circular primes = {2,3,5,7,11,13,17,31,37,71,73,79,97} * sum = 446 */ class CircularPrimes { /** * Increase this solution's efficiency by only using Sieve of Eratosthenes once * to calculate all primes less than the upper constraint. */ fun sumOfCircularPrimes(n: Int): Int { return getCircularPrimes(n).sum() } /** * Solution is optimised by filtering out primes with any even digits as an even digit means * at least 1 rotation will be even and therefore not prime. * * The primes list is also searched using a binary search algorithm, which brings solution * speed from 489.23ms (originally using r in primes) to 205.29ms. * * @return unsorted list of circular primes < [n]. */ fun getCircularPrimes(n: Int): List<Int> { val primes = primeNumbers(n - 1).filter { it == 2 || it > 2 && it.toString().none { ch -> ch in "02468" } } if (n == 10) return primes val circularPrimes = mutableListOf<Int>() for (prime in primes) { if (prime < 10) { circularPrimes.add(prime) continue } val pRotated = getRotations(prime) // avoid duplicates and non-primes if ( pRotated.any { r -> r in circularPrimes || r < n && !binarySearch(r, primes) || !r.isPrime() } ) continue circularPrimes += pRotated.filter { it < n } } return circularPrimes } private fun getRotations(num: Int): Set<Int> { val rotations = mutableSetOf(num) var rotation = num.toString() // number of possible rotations minus original already listed val r = rotation.length - 1 repeat(r) { rotation = rotation.substring(r) + rotation.substring(0 until r) rotations += rotation.toInt() } return rotations } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,552
project-euler-kotlin
MIT License
src/main/kotlin/Day2.kt
vw-anton
574,945,231
false
{"Kotlin": 33295}
fun main() { val pairs = readFile("input/2.txt") .map { line -> line.split(" ") } .map { chars -> mapItem(chars.first()) to mapResult(chars.last()) } val items = pairs.map { pair -> chooseItem(pair) }.sumOf { it.points } val results = pairs.sumOf { pair -> pair.second.points } println(results + items) } fun chooseItem(pair: Pair<Item, Result>): Item { if (pair.second == Result.Draw) return pair.first if (pair.second == Result.Win) { return when (pair.first) { Item.Scissor -> Item.Rock Item.Rock -> Item.Paper Item.Paper -> Item.Scissor else -> Item.Invalid } } if (pair.second == Result.Loss) { return when (pair.first) { Item.Scissor -> Item.Paper Item.Rock -> Item.Scissor Item.Paper -> Item.Rock else -> Item.Invalid } } return Item.Invalid } fun chooseWinner(pair: Pair<Item, Item>): Result { if (pair.first == pair.second) return Result.Draw if (pair.second == Item.Rock) { return if (pair.first == Item.Paper) Result.Loss else Result.Win } if (pair.second == Item.Paper) { return if (pair.first == Item.Scissor) Result.Loss else Result.Win } if (pair.second == Item.Scissor) { return if (pair.first == Item.Rock) Result.Loss else Result.Win } return Result.Invalid } enum class Result(val points: Int) { Draw(3), Win(6), Loss(0), Invalid(1000) } enum class Item(val points: Int) { Scissor(3), Paper(2), Rock(1), Invalid(0) } fun mapItem(s: String): Item { return when (s) { "A" -> Item.Rock "B" -> Item.Paper "C" -> Item.Scissor else -> Item.Invalid } } fun mapResult(s: String): Result { return when (s) { "X" -> Result.Loss "Y" -> Result.Draw "Z" -> Result.Win else -> Result.Invalid } }
0
Kotlin
0
0
a823cb9e1677b6285bc47fcf44f523e1483a0143
2,073
aoc2022
The Unlicense
src/main/kotlin/year2022/day-18.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2022 import lib.TraversalBreadthFirstSearch import lib.aoc.Day import lib.aoc.Part import lib.math.Vector fun main() { Day(18, 2022, PartA18(), PartB18()).run() } open class PartA18 : Part() { protected lateinit var cubes: List<Vector> override fun parse(text: String) { cubes = text.split("\n") .map { it.split(",") } .map { Vector.at(it[0].toInt(), it[1].toInt(), it[2].toInt()) } } override fun compute(): String { return cubes.flatMap { it.neighbours() } .count { it !in cubes } .toString() } protected fun Vector.neighbours(): List<Vector> { return listOf( Vector.at(this.x + 1, this.y, this.z), Vector.at(this.x - 1, this.y, this.z), Vector.at(this.x, this.y + 1, this.z), Vector.at(this.x, this.y - 1, this.z), Vector.at(this.x, this.y, this.z + 1), Vector.at(this.x, this.y, this.z - 1), ) } override val exampleAnswer: String get() = "64" } class PartB18 : PartA18() { override fun compute(): String { val exteriorCubes = findExteriorCubes() return cubes.flatMap { it.neighbours() } .count { it in exteriorCubes } .toString() } private fun findExteriorCubes(): Set<Vector> { val lowerLimit = Vector.at(cubes.minOf { it.x } - 1, cubes.minOf { it.y } - 1, cubes.minOf { it.z } - 1) val upperLimit = Vector.at(cubes.maxOf { it.x } + 2, cubes.maxOf { it.y } + 2, cubes.maxOf { it.z } + 2) fun nextNodes(node: Vector): List<Vector> { return node.neighbours() .filter { it.x in lowerLimit.x..upperLimit.x && it.y in lowerLimit.y..upperLimit.y && it.z in lowerLimit.z..upperLimit.z } } val traversal = TraversalBreadthFirstSearch { node, _ -> nextNodes(node) } .startFrom(lowerLimit) .withAlreadyVisited(cubes.toSet()) return traversal.toSet() } override val exampleAnswer: String get() = "58" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
2,257
Advent-Of-Code-Kotlin
MIT License
src/main/kotlin/twentytwentytwo/Day5.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo fun main() { val (crates, moves) = {}.javaClass.getResource("input-5.txt")!!.readText().split("\n\n") val day = Day5(crates, moves) println(day.part1()) println(day.part2()) } class Day5(private val crates: String, private val moves: String) { fun part1(): String { val stacks = getStacks() getMoves().forEach { (number, from, to) -> repeat(number) { stacks[to]!!.add(stacks[from]!!.removeLast()) } } return stacks.values.joinToString("") { it.last() } } fun part2(): String { val stacks = getStacks() getMoves().forEach { (number, from, to) -> val (first, second) = stacks[from]!!.split(number) stacks[from] = first stacks[to]!!.addAll(second) } return stacks.values.joinToString("") { it.last() } } private fun getStacks(): MutableMap<Int, MutableList<String>> { val indexes = 1..33 step 4 val lines = crates.linesFiltered { it.contains("[") }.reversed() val listOfStacks = indexes.map { i -> lines.map { it[i] }.filter { it.isUpperCase() }.map { it.toString() } } return listOfStacks.mapIndexed { i, v -> i + 1 to v.toMutableList() }.toMap(HashMap()) } /** * transforms "'move 8 from 3 to 2'\n 'move 8 from 3 to 2'" to [[8,3,2],[8,3,2]] */ private fun getMoves(): List<List<Int>> { return moves.linesFiltered { it.isNotEmpty() } .map { s -> s.split(" ").filter { s1 -> s1.any { it.isDigit() } } .map { it.toInt() } } } private fun MutableList<String>.split(number: Int): Pair<MutableList<String>, MutableList<String>> { return Pair(take(size - number).toMutableList(), takeLast(number).toMutableList()) } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
1,864
aoc202xkotlin
The Unlicense
src/main/kotlin/com/sk/set0/45. Jump Game II.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set0 // https://www.geeksforgeeks.org/minimum-number-of-jumps-to-reach-end-of-a-given-array/ class Solution45 { fun jump(nums: IntArray): Int { val table = IntArray(nums.size) { Int.MAX_VALUE } table[0] = 0 // find min jumps to reach at every index i for (i in 1..nums.lastIndex) { for (j in 0 until i) { if (j + nums[j] >= i) { table[i] = minOf(table[i], table[j] + 1) } } } return table.last() } /** * This is an implicit bfs solution. i == curEnd means you visited all the items on the current level. * Incrementing jumps++ is like incrementing the level you are on. And curEnd = curFarthest is like getting * the queue size (level size) for the next level you are traversing. */ fun jump3(nums: IntArray): Int { var jumps = 0 var curEnd = 0 var curFarthest = 0 for (i in 0 until nums.lastIndex) { curFarthest = maxOf(curFarthest, i + nums[i]) if (i == curEnd) { jumps++ curEnd = curFarthest } } return jumps } } private class RecursiveSolution { fun jump(nums: IntArray): Int { return minJumps(0, nums.lastIndex, nums) } private fun minJumps(l: Int, h: Int, arr: IntArray): Int { if (h == l) return 0 if (arr[l] == 0) return Int.MAX_VALUE var min = Int.MAX_VALUE var i = l + 1 while (i <= h && i <= l + arr[l]) { val jumps: Int = minJumps(i, h, arr) if (jumps != Int.MAX_VALUE && jumps + 1 < min) { min = jumps + 1 } i++ } return min } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,791
leetcode-kotlin
Apache License 2.0
src/main/kotlin/lain/RangeList.kt
liminalitythree
269,473,503
false
null
package lain import java.math.BigInteger data class RangeList(val list: List<Range>) { companion object { // creates a rangelist from input range // merges ranges that overlap fun from(list: List<Range>):RangeList { val first = RangeList(listOf(list[0])) val rest = list.subList(1, list.size) return rest.fold(first) { a, e -> a.plus(e) } } fun from(range: Range):RangeList { return from(listOf(range)) } // all values that are a member of a, b, or both fun union(a: RangeList, b: RangeList): RangeList { return from(a.list.plus(b.list)) } // all values that are a member of both a and b fun intersection(a: RangeList, b: RangeList): RangeList { val aover = a.list.filter { b.hasOverlap(it) } val bover = b.list.filter { a.hasOverlap(it) } val both = aover.plus(bover) val first = RangeList(listOf(both[0])) val rest = both.subList(1, both.size) return rest.fold(first) { q, e -> plusAnd(q, e) } } // All values of u that are not values of a fun setDiff (u: RangeList, a: RangeList): RangeList { val (match, rest) = u.list.partition { a.hasOverlap(it) } val amatch = a.list.filter { u.hasOverlap(it) } // rest are all not values of a // just need to check match now... // maybe val res = match.map { val muta = mutableListOf<List<Range>>() for (q in amatch) if (Range.overlaps(it, q)) muta.add(Range.subtract(it, q)) muta.toList() }.flatten().flatten() return RangeList(res.subList(1, res.size).fold(RangeList(listOf(res[0]))) { q, e -> plusAnd(q, e) }.list.plus(rest)) } // Values that are in either a or b, but not both fun symmetricDiff(a: RangeList, b: RangeList): RangeList { // union minus intersection return setDiff(union(a, b), intersection(a, b)) } // idk how this works but uhh i think it does work... // maybe fun plusAnd (a: RangeList, b: Range): RangeList { val (m, r) = a.list.partition { Range.overlaps(it, b) } val c:Range = m.fold(b) { q, e -> Range.and(q, e) } return RangeList(r.plus(c)) } } fun union(b: RangeList): RangeList { return union(this, b) } fun intersection(b: RangeList): RangeList { return intersection(this, b) } fun setDiff(b: RangeList): RangeList { return setDiff(this, b) } fun symmetricDiff(b: RangeList): RangeList { return symmetricDiff(this, b) } // returns a rangelist that is this list with range element added // merges ranges if there is an overlap with range fun plus(range: Range): RangeList { // list of elements in the rangelist that overlap with range val (match, rest) = this.list.partition { Range.overlaps(it, range) } val c:Range = match.fold(range) { a, e -> Range.or(a, e) } return RangeList(rest.plus(c)) } // sorts the rangelist and returns it fun sort(): RangeList { return RangeList(this.list.sortedBy { it.min }) } // returns true if range overlaps with any member of this fun hasOverlap(range: Range): Boolean { for (e in this.list) if (Range.overlaps(e, range)) return true return false } // prints the RangeList by turning the width of each range into a char array fun print() { val list = this.sort().list val arr = list.subList(1, list.size).fold(BigInteger.valueOf(list[0].width().toLong()).toByteArray()) { a, e -> a.plus(BigInteger.valueOf(e.width().toLong()).toByteArray()) } for (a in arr) { print(a.toChar()) } } }
2
Kotlin
0
0
6d5fbcc29da148fd72ecb58b164fc5c845267e5c
4,052
bakadesu
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/sk/topicWise/unionfind/200. Number of Islands.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.unionfind import java.util.* class Solution200 { fun numIslands(grid: Array<CharArray>): Int { val seen = HashSet<Pair<Int, Int>>() var count = 0 for (r in grid.indices) { for (c in grid[0].indices) { if (dfs(grid, r, c, seen)) count++ } } return count } fun dfs(grid: Array<CharArray>, r: Int, c: Int, seen: HashSet<Pair<Int, Int>>): Boolean { if (r < 0 || r >= grid.size || c < 0 || c >= grid[0].size) return false if (grid[r][c] == '0' || seen.contains(Pair(r, c))) return false seen.add(Pair(r, c)) dfs(grid, r, c + 1, seen) dfs(grid, r, c - 1, seen) dfs(grid, r - 1, c, seen) dfs(grid, r + 1, c, seen) return true } //var distance = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) var distance = arrayOf(intArrayOf(-1, 0), intArrayOf(0, -1)) // Only top and left fun numIslands2(grid: Array<CharArray>): Int { if (grid.isEmpty()) return 0 val uf = UnionFind(grid) val rows = grid.size val cols = grid[0].size for (i in 0 until rows) { for (j in 0 until cols) { if (grid[i][j] == '1') { for (d in distance) { val x = i + d[0] val y = j + d[1] if (x in 0..<rows && y >= 0 && y < cols && grid[x][y] == '1') { val id1 = i * cols + j val id2 = x * cols + y uf.union(id1, id2) } } } } } return uf.count } } private class UnionFind(grid: Array<CharArray>) { var parent: IntArray var m: Int var n: Int var count = 0 init { m = grid.size n = grid[0].size parent = IntArray(m * n) for (i in 0 until m) { for (j in 0 until n) { if (grid[i][j] == '1') { val id = i * n + j parent[id] = id count++ } } } } fun union(node1: Int, node2: Int) { val find1 = find(node1) val find2 = find(node2) if (find1 != find2) { parent[find1] = find2 count-- } } fun find(node: Int): Int { if (parent[node] == node) { return node } parent[node] = find(parent[node]) return parent[node] } } class Solution200_1 { lateinit var parent: IntArray fun numIslands(grid: Array<CharArray>): Int { if (grid.isEmpty()) return 0 val n = grid.size val m = grid[0].size parent = IntArray(m * n) Arrays.fill(parent, -1) for (i in 0 until n) { for (j in 0 until m) { if (grid[i][j] == '1') { parent[i * m + j] = i * m + j // note, that `parent` was filled witn -1 values if (i > 0 && grid[i - 1][j] == '1') union(i * m + j, (i - 1) * m + j) // union current+top if (j > 0 && grid[i][j - 1] == '1') union(i * m + j, i * m + (j - 1)) // union current+left } } } val set = HashSet<Int>() for (k in parent.indices) { if (parent[k] != -1) set.add(find(k)) } return set.size } fun find(x: Int): Int { if (parent[x] == x) return x parent[x] = find(parent[x]) return parent[x] } fun union(x: Int, y: Int) { val px = find(x) val py = find(y) parent[px] = parent[py] } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
3,792
leetcode-kotlin
Apache License 2.0
2021/src/main/kotlin/days/Day3.kt
pgrosslicht
160,153,674
false
null
package days import Day class Day3 : Day(3) { override fun partOne(): Int { val map = dataList.flatMap { it.mapIndexed { index, c -> index to c } }.groupingBy { it }.eachCount().entries.groupBy( { it.key.first }) { it.key.second to it.value } val gamma = map.values.map { if (it[0].second > it[1].second) it[0].first else it[1].first } .joinToString(separator = "") val epsilon = gamma.map { if (it == '1') '0' else '1' }.joinToString(separator = "") return Integer.parseInt(gamma, 2) * Integer.parseInt(epsilon, 2) } override fun partTwo(): Int { tailrec fun findNumber(input: List<String>, filter: (Int, Int) -> Boolean, position: Int = 0): List<String> { val ones = input.count { it[position].digitToInt() == 1 } val zeroes = input.size - ones val mostCommonOrOne = if (ones >= zeroes) 1 else 0 val filtered = input.filter { filter(it[position].digitToInt(), mostCommonOrOne) } return if (filtered.size == 1) filtered else findNumber(filtered, filter, position + 1) } val oxygen = findNumber(dataList, { digit, mostCommonOrOne -> digit == mostCommonOrOne }).single().toInt(2) val co2 = findNumber(dataList, { digit, mostCommonOrOne -> digit != mostCommonOrOne }).single().toInt(2) return oxygen * co2 } } fun main() = Day.mainify(Day3::class)
0
Kotlin
0
0
1f27fd65651e7860db871ede52a139aebd8c82b2
1,441
advent-of-code
MIT License
src/year2021/day07/Day07.kt
kingdongus
573,014,376
false
{"Kotlin": 100767}
package year2021.day07 import readInputFileByYearAndDay import readTestFileByYearAndDay import kotlin.math.abs fun main() { fun minimizeCost(input: List<String>, costFunction: (List<Int>, Int) -> Int): Int { val crabPositions = input[0].split(",").map { it.toInt() } // start in the middle // binary search adjust the interval to converge towards a minimum var left = crabPositions.min() var right = crabPositions.max() var min = Int.MAX_VALUE while (right > left) { val pivot = (left + right) / 2 val pivotCost = costFunction(crabPositions, pivot) val costLeft = costFunction(crabPositions, pivot - 1) if (costLeft < pivotCost) { right = pivot - 1 min = costLeft continue } else { val costRight = costFunction(crabPositions, pivot + 1) if (costRight < pivotCost) { left = pivot + 1 min = costRight continue } } return pivotCost } return min } fun part1(input: List<String>): Int = minimizeCost(input) { crabPositions, targetPosition -> crabPositions.sumOf { abs(it - targetPosition) } } fun part2(input: List<String>): Int = minimizeCost(input) { crabPositions, targetPosition -> crabPositions.sumOf { (0..abs(targetPosition - it)).sum() } } val testInput = readTestFileByYearAndDay(2021, 7) check(part1(testInput) == 37) check(part2(testInput) == 168) val input = readInputFileByYearAndDay(2021, 7) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
aa8da2591310beb4a0d2eef81ad2417ff0341384
1,733
advent-of-code-kotlin
Apache License 2.0
src/Day03.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
import javax.management.Query.match fun main() { fun part1(input: List<String>): Int { var sum = 0 for (rucksack in input) { val firstCompartment = mutableSetOf<Char>() val secondCompartment = mutableSetOf<Char>() for ((index, item) in rucksack.withIndex()) { if (index < rucksack.length / 2) { firstCompartment.add(item) } else { secondCompartment.add(item) } } // Find the intersection of the two compartment sets val intersection = firstCompartment.intersect(secondCompartment) // Iterate over each item in the intersection and add its priority to the sum for (item in intersection) { sum += if (item.isLowerCase()) item - 'a' + 1 else item - 'A' + 27 } } return sum } fun part2(input: List<String>): Int { var sum = 0 for (rucksack in input.chunked(3)) { var firstRucksack = rucksack[0].toSet() var secondRucksack = rucksack[1].toSet() var thirdRucksack = rucksack[2].toSet() // Find the intersection of the three rucksacks val intersection = firstRucksack.intersect(secondRucksack.intersect(thirdRucksack)) // Iterate over each item in the intersection and add its priority to the sum for (item in intersection) { sum += if (item.isLowerCase()) item - 'a' + 1 else item - 'A' + 27 } } return sum } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
1,822
aoc-2022
Apache License 2.0
src/Day12.kt
rromanowski-figure
573,003,468
false
{"Kotlin": 35951}
object Day12 : Runner<Int, Int>(12, 31, 29) { private fun grid(input: List<String>): Grid<Square> { val width = input.first().toCharArray().size val height = input.size val grid = Grid<Square>(height, width) input.forEachIndexed { y, s -> s.toCharArray().forEachIndexed { x, c -> grid.set(x, y, Square.of(c)) } } return grid } override fun part1(input: List<String>): Int { val grid = grid(input) traverse(grid, grid.indexOf(Square.of('E'))) println(grid) val end = grid.indexOf { label == 'S' } return grid.get(end.first, end.second)!!.stepsToVisit } private fun traverse(grid: Grid<Square>, start: Pair<Int, Int>) { val curPost = grid.get(start.first, start.second)!! grid.neighbors(start.first, start.second).filter { it.second.stepsToVisit > curPost.stepsToVisit + 1 }.forEach { (p, next) -> if (next.elevation >= curPost.elevation - 1) { next.stepsToVisit = curPost.stepsToVisit + 1 traverse(grid, p.first to p.second) } } } override fun part2(input: List<String>): Int { val grid = grid(input) traverse(grid, grid.indexOf(Square.of('E'))) println(grid.grid.flatten().filterNotNull().filter { it.elevation == 1 }) return grid.grid.flatten().filterNotNull().filter { it.elevation == 1 }.minOf { it.stepsToVisit } } data class Grid<T>( val height: Int, val width: Int, ) { val grid: List<MutableList<T?>> = List(height) { MutableList(width) { null } } fun indexOf(t: T): Pair<Int, Int> { grid.flatMapIndexed { y, row -> row.mapIndexed { x, cell -> if (cell == t) return x to y } } return -1 to -1 } fun indexOf(lambda: T.() -> Boolean): Pair<Int, Int> { grid.flatMapIndexed { y, row -> row.mapIndexed { x, cell -> if (cell?.lambda() == true) return x to y } } return -1 to -1 } fun get(x: Int, y: Int) = grid[y][x] fun set(x: Int, y: Int, t: T) { grid[y][x] = t } fun column(x: Int) = grid.map { it[x] } fun row(y: Int) = grid[y] fun neighbors(x: Int, y: Int): List<Pair<Pair<Int, Int>, T>> { return listOf( (x to y - 1), (x - 1 to y), (x to y + 1), (x + 1 to y), ).map { it to grid.getOrNull(it.second)?.getOrNull(it.first) }.filter { it.second != null }.filterIsInstance<Pair<Pair<Int, Int>, T>>() } override fun toString(): String { return grid.joinToString("\n") { it.joinToString(" ") } } } data class Square( val label: Char, val elevation: Int, var stepsToVisit: Int = Int.MAX_VALUE, ) { companion object { fun of(c: Char): Square { if (c == 'S') return Square(c, 1) if (c == 'E') return Square(c, 26, 0) return Square(c, c.code - 'a'.code + 1) } } override fun toString(): String { return "${ elevation.toString().padStart(2, '0') }-${ if (stepsToVisit == Int.MAX_VALUE) "na" else stepsToVisit.toString().padStart(2, '0') }" } } }
0
Kotlin
0
0
6ca5f70872f1185429c04dcb8bc3f3651e3c2a84
3,623
advent-of-code-2022-kotlin
Apache License 2.0