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/Day02.kt
benwicks
572,726,620
false
{"Kotlin": 29712}
import kotlin.IllegalArgumentException fun main() { fun calculateTotalScore(input: List<String>, selfPlayInterpretationMethod: SelfPlayInterpretationMethod): Int { var totalScore = 0 for (round in input) { // parse plays in each round val opponentPlay = Play.from(round[0]) val selfPlayCode = round[2] val selfPlay = when (selfPlayInterpretationMethod) { SelfPlayInterpretationMethod.WHAT_TO_PLAY -> Play.from(selfPlayCode) SelfPlayInterpretationMethod.HOW_TO_PLAY -> Play.fromHowToPlayCode(selfPlayCode, opponentPlay) } // calculate scores for each round val selfPlayScore = selfPlay.scoreForPlaying val roundOutcomeScore = selfPlay.calculateOutcome(opponentPlay).score // sum score of each round totalScore += selfPlayScore + roundOutcomeScore } return totalScore } fun part1(input: List<String>): Int { return calculateTotalScore(input, SelfPlayInterpretationMethod.WHAT_TO_PLAY) } fun part2(input: List<String>): Int { return calculateTotalScore(input, SelfPlayInterpretationMethod.HOW_TO_PLAY) } // 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)) } enum class SelfPlayInterpretationMethod { WHAT_TO_PLAY, HOW_TO_PLAY } enum class Play(val opponentCode: Char, val selfWhatToPlayCode: Char, val scoreForPlaying: Int) { ROCK('A', 'X', 1), PAPER('B', 'Y', 2), SCISSORS('C', 'Z', 3); fun winsAgainst(): Play = when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } fun losesAgainst(): Play = when (this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } fun calculateOutcome(other: Play) = when (other) { this -> Outcome.DRAW this.winsAgainst() -> Outcome.WON else -> Outcome.LOST } companion object { fun from(playCode: Char): Play { for (play in Play.values()) { if (playCode == play.opponentCode || playCode == play.selfWhatToPlayCode) { return play } } throw IllegalArgumentException("'$playCode' is not a valid play code.") } fun fromHowToPlayCode(selfPlayCode: Char, opponentPlay: Play): Play { return when (selfPlayCode) { 'X' -> { // I need to lose opponentPlay.winsAgainst() } 'Y' -> { // I need to end the round in a draw opponentPlay } 'Z' -> { // I need to win opponentPlay.losesAgainst() } else -> throw IllegalArgumentException("'$selfPlayCode' is not a valid \"how to play\" code.") } } } } enum class Outcome(val score: Int) { LOST(0), DRAW(3), WON(6) }
0
Kotlin
0
0
fbec04e056bc0933a906fd1383c191051a17c17b
3,193
aoc-2022-kotlin
Apache License 2.0
src/day3/Day3.kt
calvin-laurenson
572,736,307
false
{"Kotlin": 16407}
package day2 import readInput import java.lang.Exception fun main() { val priority = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toList() fun commonChars(first: String, second: String): List<Char> { val chars = mutableListOf<Char>() for (char in first) { if (second.contains(char)) { chars.add(char) } } return chars } fun part1(input: List<String>): Int { var sum = 0 for (line in input) { val first = line.take(line.length / 2) val second = line.takeLast(line.length / 2) sum += priority.indexOf(commonChars(first, second)[0]) + 1 } return sum } fun part2(input: List<String>): Int { var sum = 0 for (group in input.chunked(3)) { val (first, second, third) = group val common1 = commonChars(first, second) val common2 = commonChars(first, third) val common3 = commonChars(second, third) loop@ for (l in listOf(common1, common2, common3).sortedBy { it.size }.reversed()) { for (char in l) { if (common2.contains(char) && common3.contains(char)) { sum += priority.indexOf(char) + 1 break@loop } } } } return sum } val testInput = readInput("day3/test") check(part1(testInput) == 157) val input = readInput("day3/input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
155cfe358908bbe2a554306d44d031707900e15a
1,623
aoc2022
Apache License 2.0
leetcode2/src/leetcode/subsets.kt
hewking
68,515,222
false
null
package leetcode import java.util.ArrayList /** * 78. 子集 *https://leetcode-cn.com/problems/subsets/ * *给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 说明:解集不能包含重复的子集。 示例: 输入: nums = [1,2,3] 输出: [ [3],   [1],   [2],   [1,2,3],   [1,3],   [2,3],   [1,2],   [] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/subsets 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object Subsets { class Solution { val ans = mutableListOf<List<Int>>() fun subsets(nums: IntArray): List<List<Int>> { nums.sort() subset2(nums, mutableListOf(),0) return ans } /** * 思路: * 有点问题,没考虑周全 */ fun subset(nums:IntArray,ans: MutableList<List<Int>>,index: Int) { if (index == nums.size) { ans.add(mutableListOf()) return } ans.add(mutableListOf(nums[index])) for (i in index + 1 until nums.size) { ans.add(mutableListOf(nums[index],nums[i])) } if (nums.size - index > 2) { val lastElement = nums.toMutableList().subList(index,nums.size) ans.add(lastElement) } subset(nums,ans,index + 1) } /** * 思路2: * 跟全排列有点像 * https://leetcode-cn.com/problems/subsets/solution/xiang-xi-jie-shao-di-gui-hui-su-de-tao-lu-by-reedf/ */ fun subset2(nums:IntArray,list: MutableList<Int>,index: Int) { ans.add(list.toList()) for (i in index until nums.size) { list.add(nums[i]) subset2(nums,list,i + 1) list.removeAt(list.size - 1) // 递归完每次移除添加的 } } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,030
leetcode
MIT License
src/Day13.kt
mihansweatpants
573,733,975
false
{"Kotlin": 31704}
import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.* fun main() { fun part1(input: String): Int { val packetPairs = input .split("\n\n") .map { it.split("\n") } .map { (left, right) -> Packet(Json.decodeFromString(left)) to Packet(Json.decodeFromString(right)) } return packetPairs .mapIndexed { index, (left, right) -> index + 1 to left.compareTo(right) } .mapNotNull { (index, check) -> if (check <= 0) index else null } .sum() } fun part2(input: String): Int { val dividerPackets = setOf( Packet(Json.decodeFromString("[[2]]")), Packet(Json.decodeFromString("[[6]]")) ) val packets = mutableListOf<Packet>().apply { addAll(dividerPackets) } input.lines() .filterNot { it.isBlank() } .mapTo(packets) { Packet(Json.decodeFromString(it)) } packets.sort() return dividerPackets .map { packets.indexOf(it) + 1 } .reduce(Int::times) } val input = readInput("Day13") part1(input).also { check(it == 5198) println(it) } part2(input).also { check(it == 22344) println(it) } } private data class Packet( val payload: JsonArray ) : Comparable<Packet> { override fun compareTo(other: Packet): Int { return comparePayload(this.payload, other.payload) } private fun comparePayload(left: Any, right: Any): Int { return when { left is JsonPrimitive && right is JsonPrimitive -> left.int - right.int left is JsonArray && right is JsonPrimitive -> comparePayload(left, buildJsonArray { add(right) }) left is JsonPrimitive && right is JsonArray -> comparePayload(buildJsonArray { add(left) }, right) left is JsonArray && right is JsonArray -> { if (left.isEmpty() && right.isEmpty()) return 0 var index = 0 while (index < minOf(left.size, right.size)) { val check = comparePayload(left[index], right[index]) if (check != 0) return check index++ } return left.size - right.size } else -> throw RuntimeException("Left is ${left.javaClass} and right is ${right.javaClass}. What do i do???") } } }
0
Kotlin
0
0
0de332053f6c8f44e94f857ba7fe2d7c5d0aae91
2,478
aoc-2022
Apache License 2.0
src/day13/day13.kt
diesieben07
572,879,498
false
{"Kotlin": 44432}
package day13 import streamInput import java.io.IOException import java.util.Comparator import kotlin.text.StringBuilder private val file = "Day13" //private val file = "Day13Example" sealed interface PacketElement { fun toList(): L data class C(val value: Int) : PacketElement { override fun toList(): L { return L(listOf(this)) } } data class L(val values: List<PacketElement>) : PacketElement { override fun toList(): L { return this } } } object Comp : Comparator<PacketElement> { override fun compare(o1: PacketElement, o2: PacketElement): Int { return when { o1 is PacketElement.C && o2 is PacketElement.C -> o1.value - o2.value o1 is PacketElement.L && o2 is PacketElement.L -> { val leftI = o1.values.iterator() val rightI = o2.values.iterator() while (leftI.hasNext() && rightI.hasNext()) { val leftV = leftI.next() val rightV = rightI.next() val cmp = compare(leftV, rightV) if (cmp != 0) return cmp } if (leftI.hasNext()) { if (!rightI.hasNext()) { return 1 } else { return 0 } } else { if (!rightI.hasNext()) { return 0 } else { return -1 } } } else -> return compare(o1.toList(), o2.toList()) } } } fun String.parsePacket(): PacketElement.L { check(this@parsePacket[0] == '[') val stack = ArrayDeque<MutableList<PacketElement>>() var currentNumber = StringBuilder() for (c in this@parsePacket) { if (c.isDigit()) { currentNumber.append(c) } else { if (currentNumber.isNotEmpty()) { stack.last().add(PacketElement.C(currentNumber.toString().toInt())) currentNumber.clear() } if (c == '[') { stack.addLast(mutableListOf()) } else if (c == ']') { val done = stack.removeLast() if (stack.isNotEmpty()) { stack.last().add(PacketElement.L(done)) } else { return PacketElement.L(done) } } } } throw IOException("invalid input") } fun Sequence<String>.parseInput(): Sequence<Pair<PacketElement.L, PacketElement.L>> { return this.windowed(size = 2, step = 3).map { (a, b) -> Pair(a.parsePacket(), b.parsePacket()) } } fun Sequence<String>.parseInput2(): Sequence<PacketElement.L> { return this.mapNotNull { if (it.isBlank()) null else it.parsePacket() } } private fun part1() { println( streamInput(file) { input -> input.parseInput() .mapIndexed { index, (left, right) -> if (Comp.compare(left, right) < 0) index + 1 else 0 } .sum() } ) } private fun part2() { val input = streamInput(file) { it.parseInput2().toMutableList() } val divider1 = PacketElement.L(listOf(PacketElement.L(listOf(PacketElement.C(2))))) val divider2 = PacketElement.L(listOf(PacketElement.L(listOf(PacketElement.C(6))))) input.add(divider1) input.add(divider2) input.sortWith(Comp) println((input.indexOf(divider1) + 1) * (input.indexOf(divider2) + 1)) } fun main() { part1() part2() }
0
Kotlin
0
0
0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6
3,620
aoc-2022
Apache License 2.0
leetcode2/src/leetcode/coin-change.kt
hewking
68,515,222
false
null
package leetcode /** * 322. 零钱兑换 * https://leetcode-cn.com/problems/coin-change/ * Created by test * Date 2019/12/1 12:01 * Description * 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。 * 如果没有任何一种硬币组合能组成总金额,返回 -1。 示例 1: 输入: coins = [1, 2, 5], amount = 11 输出: 3 解释: 11 = 5 + 5 + 1 示例 2: 输入: coins = [2], amount = 3 输出: -1 说明: 你可以认为每种硬币的数量是无限的。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/coin-change 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object CoinChange { class Solution { /** * 回溯法,暴力法 * 跟跳跃游戏,加油站一类解法 */ fun coinChange(coins: IntArray, amount: Int): Int { return coin(0,coins,amount) } fun coin(coinIndx: Int,coins: IntArray,amount: Int): Int { if (amount == 0) { return 0 } else if (coinIndx < coins.size && amount > 0){ val maxCoin = amount / coins[coinIndx] var minCost = Int.MAX_VALUE for (i in 0 .. maxCoin) { if (amount >= coins[coinIndx] * coinIndx) { val res = coin(coinIndx + 1, coins,amount - coins[coinIndx] * i) if (res != -1) { minCost = Math.min(minCost,res + i) } } } return if (minCost == Int.MAX_VALUE) { -1 } else minCost } return -1 } /** * 带备忘录的解法 * 1. 状态转移公式: * f(n) = {0 ,n = 0 * 1+ min{ f(n - ci) , i 属于 [0,k]} * } * n为金额 * ci 为币值 */ fun coinChange2(coins: IntArray, amount: Int): Int { val memo = IntArray(amount + 1) memo.forEachIndexed { index, i -> memo[index] = -2 } return coin2(0,coins,amount,memo) } fun coin2(coinIndx: Int,coins: IntArray,amount: Int,memo: IntArray): Int { if (amount == 0) { return 0 } else { if (memo[amount] != -2) return memo[amount] if (coinIndx < coins.size && amount > 0) { val maxCoin = amount / coins[coinIndx] var minCost = Int.MAX_VALUE for (i in 0..maxCoin) { if (amount >= coins[coinIndx] * coinIndx) { val res = coin2(coinIndx + 1, coins, amount - coins[coinIndx] * i, memo) if (res != -1) { minCost = Math.min(minCost, res + i) } } } return if (minCost == Int.MAX_VALUE) { -1 } else { memo[amount] = minCost memo[amount] } } return -1 } } } fun coinChange3(coins: IntArray, amount: Int): Int { val dp = IntArray(amount + 1) dp.forEachIndexed { index, i -> dp[index] = amount + 1 } dp[0] = 0 for (i in 1 .. amount) { for (coin in coins) { if (coin <= i) { dp[i] = Math.min(dp[i],dp[i - coin] + 1) } } } return if (dp[amount] > amount) -1 else dp[amount] } @JvmStatic fun main(args: Array<String>) { println(coinChange3(intArrayOf(1,2,5),11)) } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
3,977
leetcode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ImageOverlap.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 835. Image Overlap * @see <a href="https://leetcode.com/problems/image-overlap/">Source</a> */ fun interface ImageOverlap { fun largestOverlap(img1: Array<IntArray>, img2: Array<IntArray>): Int } /** * Approach 1: Shift and Count */ class ImageOverlapShiftAndCount : ImageOverlap { override fun largestOverlap(img1: Array<IntArray>, img2: Array<IntArray>): Int { var maxOverlaps = 0 for (yShift in img1.indices) { for (xShift in img1.indices) { // move the matrix A to the up-right and up-left directions. maxOverlaps = max(maxOverlaps, shiftAndCount(xShift, yShift, img1, img2)) // move the matrix B to the up-right and up-left directions, which is equivalent to moving A to the // down-right and down-left directions maxOverlaps = max(maxOverlaps, shiftAndCount(xShift, yShift, img2, img1)) } } return maxOverlaps } /** * Shift the matrix M in up-left and up-right directions * and count the ones in the overlapping zone. */ private fun shiftAndCount(xShift: Int, yShift: Int, m: Array<IntArray>, r: Array<IntArray>): Int { var leftShiftCount = 0 var rightShiftCount = 0 var rRow = 0 // count the cells of ones in the overlapping zone. for (mRow in yShift until m.size) { var rCol = 0 for (mCol in xShift until m.size) { if (m[mRow][mCol] == 1 && m[mRow][mCol] == r[rRow][rCol]) leftShiftCount += 1 if (m[mRow][rCol] == 1 && m[mRow][rCol] == r[rRow][mCol]) rightShiftCount += 1 rCol += 1 } rRow += 1 } return max(leftShiftCount, rightShiftCount) } } /** * Approach 2: Linear Transformation */ class ImageOverlapLinear : ImageOverlap { override fun largestOverlap(img1: Array<IntArray>, img2: Array<IntArray>): Int { val onesA = nonZeroCells(img1) val onesB = nonZeroCells(img2) var maxOverlaps = 0 val groupCount: HashMap<Pair<Int, Int>, Int> = HashMap() for (a in onesA) { for (b in onesB) { val vec: Pair<Int, Int> = Pair(b.first - a.first, b.second - a.second) if (groupCount.containsKey(vec)) { groupCount[vec] = groupCount.getOrDefault(vec, 0) + 1 } else { groupCount[vec] = 1 } maxOverlaps = max(maxOverlaps, groupCount.getOrDefault(vec, 0)) } } return maxOverlaps } private fun nonZeroCells(m: Array<IntArray>): List<Pair<Int, Int>> { val ret: MutableList<Pair<Int, Int>> = ArrayList() for (row in m.indices) { for (col in m.indices) { if (m[row][col] == 1) ret.add(Pair(row, col)) } } return ret } } /** * Approach 3: Imagine Convolution */ class ImageOverlapImagineConvolution : ImageOverlap { override fun largestOverlap(img1: Array<IntArray>, img2: Array<IntArray>): Int { val n = img1.size val paddedB = Array(3 * n - 2) { IntArray(3 * n - 2) } for (row in 0 until n) { for (col in 0 until n) { paddedB[row + n - 1][col + n - 1] = img2[row][col] } } var maxOverlaps = 0 for (xShift in 0 until 2 * n - 1) { for (yShift in 0 until 2 * n - 1) { maxOverlaps = max( maxOverlaps, convolute(img1, paddedB, xShift, yShift), ) } } return maxOverlaps } private fun convolute(a: Array<IntArray>, kernel: Array<IntArray>, xShift: Int, yShift: Int): Int { var result = 0 for (row in a.indices) { for (col in a.indices) { result += a[row][col] * kernel[row + yShift][col + xShift] } } return result } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,693
kotlab
Apache License 2.0
src/day03/Day03.kt
shiddarthbista
572,833,784
false
{"Kotlin": 9985}
package day03 import readInput fun main() { fun priorityScore(commonChar: Char): Int = when { commonChar.isLowerCase() -> { commonChar.code - 'a'.code + 1 } commonChar.isUpperCase() -> { commonChar.code - 'A'.code + 27 } else -> error("Invalid character") } fun part1(input: List<String>): Int { return input.sumOf {rucksack-> val ruckSackOne = rucksack.substring(0,(rucksack.length/2)).toList() val ruckSackTwo = rucksack.substring(rucksack.length/2).toList() priorityScore((ruckSackOne intersect ruckSackTwo).first()) } } fun part2(input:List<String>):Int { return input.chunked(3).sumOf { rucksacks -> val(rucksackOne,rucksackTwo,rucksackThree) = rucksacks.map { it.toList() } val commonChar = rucksackOne intersect rucksackTwo intersect rucksackThree priorityScore(commonChar.first()) } } val testInput = readInput("Day03_test") val input = readInput("Day03") check(part1(testInput) == 157) check(part2(testInput) == 70) println(part1(testInput)) println(part2(testInput)) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ed1b6a132e201e98ab46c8df67d4e9dd074801fe
1,295
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/Day21.kt
Yeah69
317,335,309
false
{"Kotlin": 73241}
class Day21 : Day() { override val label: String get() = "21" data class Food(val ingredients: List<String>, val allergens: List<String>) private val foodRegex = """(.+) \(contains (.+)\)""".toRegex() private val foods by lazy { input .lineSequence() .map { val (ingredients, allergens) = foodRegex.find(it)?.destructured ?: throw Exception() Food(ingredients.split(' '), allergens.split(", ")) } .toList() } private val allergens by lazy { foods.flatMap { it.allergens }.distinct().toList() } private val ingredients by lazy { foods.flatMap { it.ingredients }.distinct().toList() } private val inertIngredients by lazy { allergens .flatMap { allergen -> val foodsWhichContain = foods.filter { it.allergens.contains(allergen) }.toList() foodsWhichContain .flatMap { it.ingredients } .distinct() .filter { ingredient -> foodsWhichContain.all { it.ingredients.contains(ingredient) } } } .distinct() .toHashSet() } private val safeIngredients by lazy { ingredients .filterNot { inertIngredients.contains(it) } .distinct() .toHashSet() } override fun taskZeroLogic(): String = foods.flatMap { it.ingredients }.filter { safeIngredients.contains(it) }.count().toString() override fun taskOneLogic(): String { val excludedIngredients = safeIngredients.toHashSet() val excludedAllergens = HashSet<String>() val allergensToIngredients = mutableListOf<Pair<String,String>>() for(i in allergens.indices) { val nextExclude = allergens .filterNot { excludedAllergens.contains(it) } .map { allergen -> val foodsWhichContain = foods.filter { it.allergens.contains(allergen) }.toList() allergen to foodsWhichContain .flatMap { it.ingredients } .distinct() .filter { ingredient -> foodsWhichContain.all { it.ingredients.contains(ingredient) } } .filterNot { excludedIngredients.contains(it) } .toList() } .firstOrNull { it.second.count() == 1 } if (nextExclude != null) { allergensToIngredients.add(nextExclude.first to nextExclude.second[0]) excludedIngredients.add(nextExclude.second[0]) excludedAllergens.add(nextExclude.first) } else throw Exception() } return allergensToIngredients.asSequence().sortedBy { it.first }.map { it.second }.joinToString(",") } }
0
Kotlin
0
0
23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec
2,750
AdventOfCodeKotlin
The Unlicense
archive/2022/Day19.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 33 private const val EXPECTED_2 = 62 * 56 private class Day19(isTest: Boolean) : Solver(isTest) { // State: 8 ints // 0,1,2,3 = produced good // 4,5,6,7 = robots private fun MutableList<Int>.produceGoods() { (0..3).forEach { this[it] += this[it + 4] } } fun reduceSpace(states: Set<List<Int>>): Set<List<Int>> { //My submission had this criterion, which requires a bit of a wait for the program to finish: // return states.sortedByDescending { it[3] * 10000 + it[7] * 1000 + it[6] * 100 + it.sum() }.take(100_000).toSet() var result = mutableSetOf<List<Int>>() // Ideally we'd like to keep the convex hull of the 8D vector, but I don't know a // short solution to that // Alternative: just take the max 500 points in each single dimension, it makes // sense that at different stages of the puzzle, one metric is the one to maximize // (ore robots in the beginning, geode robots and/or geode count in the end) for (sortIndex in 0..7) { result.addAll(states.sortedByDescending { it[sortIndex] * 10000 + it[3] + it[7] }.take(200)) // If we don't break ties on the geode + robots, then we have to take some more items: // result.addAll(states.sortedByDescending { it[sortIndex] }.take(1000)) } // Alternatively, we could remove states that are useless (e.g. creating more ore every // timestep than needed to manufacture any of the robots) //println("Reduced from ${states.size} to ${result.size}") return result } fun addStates(states: MutableSet<List<Int>>, state: List<Int>, bp: List<Int>) { if (state[0] >= bp[1]) { states.add(state.toMutableList().apply { this[0] -= bp[1] produceGoods() this[4]++ }) } if (state[0] >= bp[2]) { states.add(state.toMutableList().apply { this[0] -= bp[2] produceGoods() this[5]++ }) } if (state[0] >= bp[3] && state[1] >= bp[4]) { states.add(state.toMutableList().apply { this[0] -= bp[3] this[1] -= bp[4] produceGoods() this[6]++ }) } if (state[0] >= bp[5] && state[2] >= bp[6]) { states.add(state.toMutableList().apply { this[0] -= bp[5] this[2] -= bp[6] produceGoods() this[7]++ }) } state.toMutableList().let { it.produceGoods() states.add(it) } } fun quality(bp: List<Int>, num: Int): Int { var states = setOf(listOf(0, 0, 0, 0, 1, 0, 0, 0)) for (t in 1..num) { val newStates = mutableSetOf<List<Int>>().also { for (state in states) { addStates(it, state, bp) } } //println("$t ${newstates.size}") states = reduceSpace(newStates) } return states.maxOf { it[3] } } val bluePrints = readAsLines().map { it.splitInts() as List<Int> } fun part1() = bluePrints.sumOf { it[0] * quality(it, 24) } fun part2() = bluePrints.take(3).map { quality(it, 32) }.reduce { a, b -> a * b } } fun main() { val testInstance = Day19(true) val instance = Day19(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
3,810
advent-of-code-2022
Apache License 2.0
src/Day09.kt
IvanChadin
576,061,081
false
{"Kotlin": 26282}
import kotlin.math.abs import kotlin.math.sign fun main() { val inputName = "Day09_test" val commands = readInput(inputName).map { s -> s.split(" ") } data class Pt(var x: Int, var y: Int) fun part1(commands: List<List<String>>): Int { val visited = HashSet<Pt>() val head = Pt(0, 0) val tail = Pt(0, 0) for (cmd in commands) { repeat(cmd[1].toInt()) { when (cmd[0]) { "R" -> head.x++ "U" -> head.y++ "L" -> head.x-- "D" -> head.y-- } if (abs(head.x - tail.x) + abs(head.y - tail.y) == 3) { tail.x += sign((head.x - tail.x).toDouble()).toInt() tail.y += sign((head.y - tail.y).toDouble()).toInt() } else { if (abs(head.x - tail.x) == 2) { tail.x += sign((head.x - tail.x).toDouble()).toInt() } if (abs(head.y - tail.y) == 2) { tail.y += sign((head.y - tail.y).toDouble()).toInt() } } visited.add(tail.copy()) } } return visited.size } fun part2(commands: List<List<String>>): Int { val visited = HashSet<Pt>() val knots = HashMap<Int, Pt>() for (i in 0..9) { knots[i] = Pt(0, 0) } for (cmd in commands) { repeat(cmd[1].toInt()) { when (cmd[0]) { "R" -> knots[0]!!.x++ "U" -> knots[0]!!.y++ "L" -> knots[0]!!.x-- "D" -> knots[0]!!.y-- } for (i in 1..9) { val head = knots[i - 1]!! val tail = knots[i]!! if (abs(head.x - tail.x) + abs(head.y - tail.y) == 3) { tail.x += sign((head.x - tail.x).toDouble()).toInt() tail.y += sign((head.y - tail.y).toDouble()).toInt() } else { if (abs(head.x - tail.x) == 2) { tail.x += sign((head.x - tail.x).toDouble()).toInt() } if (abs(head.y - tail.y) == 2) { tail.y += sign((head.y - tail.y).toDouble()).toInt() } } } visited.add(knots[9]!!.copy()) } } return visited.size } val result = part2(commands) println(result) check(result == 36) //check(part2(a) == 8) }
0
Kotlin
0
0
2241437e6c3a20de70306a0cb37b6fe2ed8f9e3a
2,716
aoc-2022
Apache License 2.0
src/Day20.kt
azat-ismagilov
573,217,326
false
{"Kotlin": 75114}
fun main() { val day = 20 data class IndexedNumber(val index: Int, val number: Long) fun part1(input: List<String>): Long { val array = input.mapIndexed { index, c -> IndexedNumber(index, c.toLong()) } val interestingPoints = listOf(1000, 2000, 3000) val mutableArray = array.toMutableList() for (element in array) { val index = mutableArray.indexOf(element) mutableArray.removeAt(index) val newIndex = (index + element.number).mod(mutableArray.size) mutableArray.add(newIndex, element) } return interestingPoints.sumOf { delay -> mutableArray[(mutableArray.indexOfFirst { it.number == 0L } + delay).mod(mutableArray.size)].number } } fun part2(input: List<String>): Long { val array = input.mapIndexed { index, c -> IndexedNumber(index, 811589153L * c.toLong()) } val interestingPoints = listOf(1000, 2000, 3000) val mutableArray = array.toMutableList() repeat(10) { for (element in array) { val index = mutableArray.indexOf(element) mutableArray.removeAt(index) val newIndex = (index + element.number).mod(mutableArray.size) mutableArray.add(newIndex, element) } } return interestingPoints.sumOf { delay -> mutableArray[(mutableArray.indexOfFirst { it.number == 0L } + delay).mod(mutableArray.size)].number } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
abdd1b8d93b8afb3372cfed23547ec5a8b8298aa
1,816
advent-of-code-kotlin-2022
Apache License 2.0
src/day03/Day03.kt
skempy
572,602,725
false
{"Kotlin": 13581}
package day03 import readInputAsList fun main() { var priority = 1 val priorities: Map<Char, Int> = (('a'..'z') + ('A'..'Z')).associateWith { priority++ } fun part1(input: List<String>): Int { return input .map { it.chunked(it.length / 2) } .map { Pair(it[0].toSet(), it[1].toSet()) } .sumOf { priorities[(it.first intersect it.second).single()]!! } } fun part2(input: List<String>): Int { return input .map { it.toSet() } .chunked(3) .sumOf { priorities[(it[0] intersect it[1] intersect it[2]).single()]!! } } // test if implementation meets criteria from the description, like: val testInput = readInputAsList("Day03", "_test") println("Test Part1: ${part1(testInput)}") println("Test Part2: ${part2(testInput)}") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInputAsList("Day03") println("Actual Part1: ${part1(input)}") println("Actual Part2: ${part2(input)}") check(part1(input) == 7811) check(part2(input) == 2639) }
0
Kotlin
0
0
9b6997b976ea007735898083fdae7d48e0453d7f
1,119
AdventOfCode2022
Apache License 2.0
src/Day03.kt
RogozhinRoman
572,915,906
false
{"Kotlin": 28985}
fun main() { fun getPriority(c: Char): Int { return if (c.isLowerCase()) c.code - 'a'.code + 1 else c.code - 'A'.code + 27 } fun part1(input: List<String>) = input.sumOf { it -> it.subSequence(0 until it.length / 2) .toSet() .intersect(it.subSequence(it.length / 2, it.length).toSet()) .map { getPriority(it) } .single() } fun part2(input: List<String>) = input.chunked(3).sumOf { it -> it[0].toSet() .intersect(it[1].toSet()) .intersect(it[2].toSet()) .map { getPriority(it) } .single() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
6375cf6275f6d78661e9d4baed84d1db8c1025de
921
AoC2022
Apache License 2.0
src/Day16.kt
zfz7
573,100,794
false
{"Kotlin": 53499}
fun main() { println(day16A(readFile("Day16"))) println(day16B(readFile("Day16"))) } fun parse16Input(input: String): Map<String, Valve> { val list = input.trim().split("\n").map { line -> val splitLine = line .replace("valves", "valve") .replace("leads", "lead") .replace("tunnels", "tunnel") .split("Valve ", " has flow rate=", "; tunnel lead to valve ") Valve( name = splitLine[1], flowRate = splitLine[2].toInt(), tunnels = splitLine[3].split(", ").toSet() ) } return list.associateBy { valve -> valve.name } } val MAX_TIME_A = 30 val MAX_TIME_B = 26 fun day16A(input: String): Int { val valves = parse16Input(input) val valesWithWater = valves.values.filter { it.flowRate > 0 }.size val totalFlows:MutableList<TotalFlow> = mutableListOf() totalFlows.add(TotalFlow(humanValve = valves["AA"]!!, elephantValve = valves["AA"]!!, humanTime = 0, elephantTime = 0, humanTotalEventualPressure = 0, elephantTotalEventualPressure = 0, opened = emptySet())) val ret = mutableSetOf<Int>() while (!totalFlows.isEmpty()) { val current = totalFlows.removeAt(0) if (current.humanTime > MAX_TIME_A || current.opened.size == valesWithWater) { ret.add(current.humanTotalEventualPressure) } else { current.humanValve.tunnels.forEach { tunnel -> if (valves[tunnel]!!.flowRate > 0 && (MAX_TIME_A - current.humanTime) >= 2 && !current.opened.contains(tunnel)) { totalFlows.add( TotalFlow( humanTime = current.humanTime + current.humanValve.travelTime + current.humanValve.openingTime,//opening valve humanValve = valves[tunnel]!!, humanTotalEventualPressure = current.humanTotalEventualPressure + ((MAX_TIME_A - current.humanTime - 2) * valves[tunnel]!!.flowRate), elephantTime = current.elephantTime, elephantValve = current.elephantValve, elephantTotalEventualPressure = current.elephantTotalEventualPressure, opened = current.opened.toSet() + setOf(tunnel) ) ) } //dont open totalFlows.add( TotalFlow( humanTime = current.humanTime + current.humanValve.travelTime,//dont open valve humanValve = valves[tunnel]!!, humanTotalEventualPressure = current.humanTotalEventualPressure, elephantValve = current.elephantValve, elephantTotalEventualPressure = current.elephantTotalEventualPressure, elephantTime = current.elephantTime, opened = current.opened.toSet(), ) ) } if(totalFlows.size > 100000){ val new = totalFlows.sortedByDescending { it.humanTotalEventualPressure }.take(50000) totalFlows.clear() totalFlows.addAll(new) } } } return ret.maxOf { it } } fun day16B(input: String): Int { val valves = parse16Input(input) val valesWithWater = valves.values.filter { it.flowRate > 0 }.size val totalFlows:MutableList<TotalFlow> = mutableListOf() totalFlows.add(TotalFlow(humanValve = valves["AA"]!!, elephantValve = valves["AA"]!!, humanTime = 0, elephantTime = 0, humanTotalEventualPressure = 0, elephantTotalEventualPressure = 0, opened = emptySet())) val ret = mutableSetOf<Int>() while (totalFlows.isNotEmpty()) { val current = totalFlows.removeAt(0) if ((current.humanTime >= MAX_TIME_B && current.elephantTime >= MAX_TIME_B)|| current.opened.size == valesWithWater) { ret.add(current.humanTotalEventualPressure + current.elephantTotalEventualPressure) } else { //move human if(current.humanTime < MAX_TIME_B) current.humanValve.tunnels.forEach { tunnel -> if (valves[tunnel]!!.flowRate > 0 && (MAX_TIME_B - current.humanTime) >= 2 && !current.opened.contains(tunnel)) { totalFlows.add( TotalFlow( humanTime = current.humanTime + current.humanValve.travelTime + current.humanValve.openingTime,//opening valve humanValve = valves[tunnel]!!, humanTotalEventualPressure = current.humanTotalEventualPressure + ((MAX_TIME_B - current.humanTime - 2) * valves[tunnel]!!.flowRate), elephantTime = current.elephantTime, elephantValve = current.elephantValve, elephantTotalEventualPressure = current.elephantTotalEventualPressure, opened = current.opened.toSet() + setOf(tunnel) ) ) } //dont open totalFlows.add( TotalFlow( humanValve = valves[tunnel]!!, humanTotalEventualPressure = current.humanTotalEventualPressure, elephantTime = current.elephantTime, elephantValve = current.elephantValve, elephantTotalEventualPressure = current.elephantTotalEventualPressure, humanTime = current.humanTime + current.humanValve.travelTime,//dont open valve opened = current.opened.toSet() ) ) } //move elephant if(current.elephantTime <MAX_TIME_B) current.elephantValve.tunnels.forEach { tunnel -> if (valves[tunnel]!!.flowRate > 0 && (MAX_TIME_B - current.elephantTime) >= 2 && !current.opened.contains(tunnel)) { totalFlows.add( TotalFlow( humanTime = current.humanTime, humanValve = current.humanValve, humanTotalEventualPressure = current.humanTotalEventualPressure, elephantValve = valves[tunnel]!!, elephantTotalEventualPressure = current.elephantTotalEventualPressure + ((MAX_TIME_B - current.elephantTime - 2) * valves[tunnel]!!.flowRate), elephantTime = current.elephantTime + current.elephantValve.travelTime + current.elephantValve.openingTime,//opening valve opened = current.opened.toSet() + setOf(tunnel) ) ) } //dont open totalFlows.add( TotalFlow( humanTime = current.humanTime, humanValve = current.humanValve, humanTotalEventualPressure = current.humanTotalEventualPressure, elephantValve = valves[tunnel]!!, elephantTotalEventualPressure = current.elephantTotalEventualPressure, elephantTime = current.elephantTime + current.elephantValve.travelTime,//dont open valve opened = current.opened, ) ) } if(totalFlows.size > 100000){ val new = totalFlows.sortedByDescending { it.humanTotalEventualPressure + it.elephantTotalEventualPressure}.take(70000) totalFlows.clear() totalFlows.addAll(new) } } } return ret.maxOf { it} } data class Valve( val name: String, val travelTime: Int = 1, val openingTime: Int = 1, val flowRate: Int, val tunnels: Set<String> ) data class TotalFlow( val humanTime: Int, val humanValve: Valve, val humanTotalEventualPressure: Int, val elephantTime: Int, val elephantValve: Valve, val elephantTotalEventualPressure: Int, val opened: Set<String> )
0
Kotlin
0
0
c50a12b52127eba3f5706de775a350b1568127ae
8,319
AdventOfCode22
Apache License 2.0
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day04.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day class Day04 : Day("25410", "2730") { private val markedNumbers = input .lines()[0] .split(",") .map { it.toInt() } private val boards = input.split("\n\n").drop(1).map { board -> board.split("\n").map { row -> row.split(" ").filter { it.isNotBlank() }.map { it.toInt() } } } override fun solvePartOne(): Any { return getWinningScore(true) } override fun solvePartTwo(): Any { return getWinningScore(false) } private fun getWinningScore(firstWin: Boolean): Int { val boardsToMarkedIndices = boards .map { board -> val columns = board[0].indices.map { column -> board.indices.map { board[it][column] } } val bestIndex = (board + columns) .minOf { numbers -> if (numbers.intersect(markedNumbers).size != numbers.size) { Int.MAX_VALUE } else { numbers.maxOf { markedNumbers.indexOf(it) } } } board to bestIndex } val (winningBoard, markedIndex) = if (firstWin) { boardsToMarkedIndices.minByOrNull { it.second }!! } else { boardsToMarkedIndices.maxByOrNull { it.second }!! } val unmarkedSum = winningBoard.sumOf { row -> row.filter { !markedNumbers.contains(it) || markedNumbers.indexOf(it) > markedIndex }.sum() } return unmarkedSum * markedNumbers[markedIndex] } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
1,674
advent-of-code-2021
MIT License
src/main/kotlin/de/dikodam/calendar/Day02.kt
dikodam
573,126,346
false
{"Kotlin": 26584}
package de.dikodam.calendar import de.dikodam.AbstractDay import de.dikodam.calendar.MatchResult.* import de.dikodam.calendar.RPS.* import de.dikodam.executeTasks import kotlin.time.ExperimentalTime @ExperimentalTime fun main() { Day02().executeTasks() } class Day02 : AbstractDay() { val inputLines = readInputLines() override fun task1(): String { return inputLines .map { parseLineToEncounter(it) } .map(Encounter::score) .sum() .toString() } override fun task2(): String { return inputLines .map { parseLineToActualStrategy(it) } .map(ActualStrategy::score) .sum() .toString() } } private fun parseLineToEncounter(line: String): Encounter { val (theirString, mineString) = line.split(" ") return Encounter(RPS.parse(mineString), RPS.parse(theirString)) } private fun parseLineToActualStrategy(line: String): ActualStrategy { val (theirString, mineString) = line.split(" ") val desiredMatchResult = when (mineString) { "X" -> LOSS "Y" -> DRAW "Z" -> WIN else -> error("invalid input: $mineString") } return ActualStrategy(RPS.parse(theirString), desiredMatchResult) } private enum class RPS(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun parse(char: String) = when (char) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> error("invalid input $char") } } } private enum class MatchResult(val score: Int) { WIN(6), DRAW(3), LOSS(0) } private class Encounter(val mine: RPS, val theirs: RPS) { fun score(): Int { val matchResult = when (mine) { ROCK -> when (theirs) { ROCK -> DRAW PAPER -> LOSS SCISSORS -> WIN } PAPER -> when (theirs) { ROCK -> WIN PAPER -> DRAW SCISSORS -> LOSS } SCISSORS -> when (theirs) { ROCK -> LOSS PAPER -> WIN SCISSORS -> DRAW } } return mine.score + matchResult.score } } private class ActualStrategy(val theirs: RPS, val desiredResult: MatchResult) { fun score(): Int { val mine = when (desiredResult) { DRAW -> theirs WIN -> when (theirs) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } LOSS -> when (theirs) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } } return mine.score + desiredResult.score } }
0
Kotlin
0
1
3eb9fc6f1b125565d6d999ebd0e0b1043539d192
2,914
aoc2022
MIT License
src/Day25.kt
sitamshrijal
574,036,004
false
{"Kotlin": 34366}
fun main() { fun parse(input: List<String>): List<Long> = input.map { it.toDecimal() } fun part1(input: List<String>): String { val numbers = parse(input) return numbers.sum().toSnafu() } fun part2(input: List<String>): Int { return input.size } val input = readInput("input25") println(part1(input)) println(part2(input)) } /** * Convert a decimal number to a SNAFU number. */ fun Long.toSnafu(): String { var decimal = this // Input number var snafu = "" // Output number while (decimal != 0L) { when (val digit = decimal.mod(5L)) { in 0..2 -> snafu += digit 3L -> { snafu += '=' decimal += 5L } 4L -> { snafu += '-' decimal += 5L } } decimal /= 5L } return snafu.reversed() } /** * Convert a SNAFU number to decimal. */ fun String.toDecimal(): Long { var decimal = 0L indices.forEach { val place = if (it == 0) 1L else List(it) { 5L }.reduce { a, b -> a * b } val digit = this[lastIndex - it] decimal += when (digit) { '=' -> -2 * place '-' -> -place else -> digit.digitToInt() * place } } return decimal }
0
Kotlin
0
0
fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d
1,329
advent-of-code-2022
Apache License 2.0
src/day05/Day05.kt
jacobprudhomme
573,057,457
false
{"Kotlin": 29699}
import java.io.File typealias CrateStacks = Array<ArrayDeque<Char>> typealias CraneProcedure = List<Triple<Int, Int, Int>> fun main() { fun readInput(name: String) = File("src/day05", name) .readLines() fun processInput(input: List<String>): Pair<CrateStacks, CraneProcedure> { val craneProcedureStrs = input.takeLastWhile { it.isNotEmpty() } val craneProcedure: CraneProcedure = craneProcedureStrs.map { procedure -> Regex("\\d+") .findAll(procedure) .map(MatchResult::value) .map(String::toInt) .toList() .let { (num, from, to, _) -> Triple(num, from-1, to-1) } } val (crateStacksStrs, stackNumbersStr) = input .takeWhile { it.isNotEmpty() } .let { Pair(it.dropLast(1).reversed(), it.last()) } val numStacks = Regex("\\d+") .findAll(stackNumbersStr) .count() val crateStacks = Array(numStacks) { ArrayDeque<Char>() } for (line in crateStacksStrs) { val cratesAtLevel = line.chunked(4) { it.filter(Char::isLetter) } cratesAtLevel.forEachIndexed { i, crate -> if (crate.isNotEmpty()) { crateStacks[i].addLast(crate.first()) } } } return Pair(crateStacks, craneProcedure) } fun part1(input: List<String>): String { val (crateStacks, craneProcedure) = processInput(input) for ((num, from, to) in craneProcedure) { repeat(num) { val crate = crateStacks[from].removeLast() crateStacks[to].addLast(crate) } } return crateStacks.map { it.last() }.joinToString("") } fun part2(input: List<String>): String { val (crateStacks, craneProcedure) = processInput(input) for ((num, from, to) in craneProcedure) { val crates = crateStacks[from].takeLast(num) repeat(num) { crateStacks[from].removeLast() } crateStacks[to].addAll(crates) } return crateStacks.map { it.last() }.joinToString("") } val input = readInput("input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
9c2b080aea8b069d2796d58bcfc90ce4651c215b
2,300
advent-of-code-2022
Apache License 2.0
day04/kotlin/RJPlog/day2304_1_2.kt
mr-kaffee
720,687,812
false
{"Rust": 223627, "Kotlin": 46100, "Python": 39390, "Shell": 3369, "Haskell": 3122, "Dockerfile": 2236, "Gnuplot": 1678, "C++": 980, "HTML": 592, "CMake": 314}
import java.io.File import kotlin.math.* fun scratchCard(): Int { var result = 0 val pattern = """(\d)+""".toRegex() File("day2304_puzzle_input.txt").forEachLine { var winningNumbers = pattern.findAll(it.substringAfter(": ").split(" | ")[0]).map { it.value }.toList() var numbersYouHave = pattern.findAll(it.substringAfter(": ").split(" | ")[1]).map { it.value }.toList() result += Math.pow( 2.0, ((winningNumbers + numbersYouHave).size - (winningNumbers + numbersYouHave).distinct().size).toDouble() - 1.0 ).toInt() } return result } fun scratchCardPart2(): Int { var puzzle_input = mutableListOf<String>() File("day2304_puzzle_input.txt").forEachLine { puzzle_input.add(it) } val pattern = """(\d)+""".toRegex() val wonCards = puzzle_input.toMutableList() val wonCardsIterator = wonCards.listIterator() while (wonCardsIterator.hasNext()) { var card = wonCardsIterator.next() var cardNumber = pattern.find(card.substringBefore(":"))!!.value.toInt() var winningNumbers = pattern.findAll(card.substringAfter(": ").split(" | ")[0]).map { it.value }.toList() var numbersYouHave = pattern.findAll(card.substringAfter(": ").split(" | ")[1]).map { it.value }.toList() var wins = (winningNumbers + numbersYouHave).size - (winningNumbers + numbersYouHave).distinct().size for (i in 0..wins - 1) { wonCardsIterator.add(puzzle_input[cardNumber + i]) wonCardsIterator.previous() } } return wonCards.size } fun main() { var t1 = System.currentTimeMillis() var solution1 = scratchCard() var solution2 = scratchCardPart2() // print solution for part 1 println("*******************************") println("--- Day 4: Scratchcards ---") println("*******************************") println("Solution for part1") println(" $solution1 points are they worth in total") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 total scratchcards do you end up with") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
0
Rust
2
0
5cbd13d6bdcb2c8439879818a33867a99d58b02f
2,085
aoc-2023
MIT License
src/Day08.kt
phoenixli
574,035,552
false
{"Kotlin": 29419}
fun main() { fun part1(input: List<String>): Int { val rows: MutableList<MutableList<Int>> = mutableListOf() input.forEach{ val row = mutableListOf<Int>() for(c in it.toCharArray()) { row.add(c.toString().toInt()) } rows.add(row) } val cols = List(rows[0].size) { mutableListOf<Int>() } for (row in rows) { for (i in row.indices) { cols[i].add(row[i]) } } var count = 0 for (i in rows.indices) { if (i == 0 || i == (rows.size - 1)) { count += rows.size continue } val row = rows[i] for (j in row.indices) { if (j == 0 || j == (row.size - 1)) { count++ continue } val tree = row[j] val leftMax = row.subList(0, j).maxOrNull() ?: 0 val rightMax = row.subList(j+1, row.size).maxOrNull() ?: 0 if (tree > leftMax || tree > rightMax) { count++ } else { // Check column max val col = cols[j] val topMax = col.subList(0, i).maxOrNull() ?: 0 val bottomMax = col.subList(i+1, col.size).maxOrNull() ?: 0 if (tree > topMax || tree > bottomMax) { count++ } } } } return count } fun part2(input: List<String>): Int { val rows: MutableList<MutableList<Int>> = mutableListOf() input.forEach{ val row = mutableListOf<Int>() for(c in it.toCharArray()) { row.add(c.toString().toInt()) } rows.add(row) } val cols = List(rows[0].size) { mutableListOf<Int>() } for (row in rows) { for (i in row.indices) { cols[i].add(row[i]) } } var maxScore = 0 var currScore = 0 for (i in rows.indices) { currScore = 0 if (i == 0 || i == (rows.size - 1)) { continue } val row = rows[i] for (j in row.indices) { if (j == 0 || j == (row.size - 1)) { continue } val tree = row[j] val left = row.subList(0, j).asReversed() val leftScore = getScoreForTree(tree, left) val right = row.subList(j+1, row.size) val rightScore = getScoreForTree(tree, right) val col = cols[j] val top = col.subList(0, i).asReversed() val topScore = getScoreForTree(tree, top) val bottom = col.subList(i+1, col.size) val bottomScore = getScoreForTree(tree, bottom) currScore = leftScore * rightScore * topScore * bottomScore maxScore = maxOf(maxScore, currScore) } } return maxScore } val input = readInput("Day08") println(part1(input)) println(part2(input)) } fun getScoreForTree(tree: Int, list: List<Int>): Int { var score = 0 for (it in list) { if (it >= tree) { score += 1 return score } if (it < tree) { score += 1 } } return score }
0
Kotlin
0
0
5f993c7b3c3f518d4ea926a792767a1381349d75
3,535
Advent-of-Code-2022
Apache License 2.0
src/aoc2022/Day23.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import utils.Vertex import utils.checkEquals private typealias Elf = Vertex fun main() { fun part1(input: List<String>): Int { return input.locateElvas().spreadOut(rounds = 10) } fun part2(input: List<String>): Int { var firstNoMoveRound = 0 input.locateElvas().spreadOut(rounds = Int.MAX_VALUE) { firstNoMoveRound = it } return firstNoMoveRound } // parts execution val testInput = readInput("Day23_test") val input = readInput("Day23") part1(testInput).checkEquals(110) part1(input) .checkEquals(3874) // .sendAnswer(part = 1, day = "23", year = 2022) part2(testInput).checkEquals(20) part2(input) .checkEquals(948) // .sendAnswer(part = 2, day = "23", year = 2022) } private fun List<String>.locateElvas() = flatMapIndexed { index, s -> s.mapIndexedNotNull { i, c -> if (c == '.') null else aoc2022.Elf(x = i, y = index) } }.toHashSet() private fun HashSet<Elf>.spreadOut(rounds: Int, onNoMoves: ((round: Int) -> Unit)? = null): Int { val elves: HashSet<Elf> = this val validDirections = ArrayDeque(listOf( { e: Elf -> e.northAdjacent() to e.up() }, { e: Elf -> e.southAdjacent() to e.down() }, { e: Elf -> e.westAdjacent() to e.left() }, { e: Elf -> e.eastAdjacent() to e.right() } )) var round = 1 while (round <= rounds) { //first half val movingAbility = elves.filter { elf -> elf.allAdjacent().any { it in elves } } if (movingAbility.isEmpty()) break round++ val proposedElvasMoves: Map<Elf, List<Elf>> = movingAbility.mapNotNull { elf -> return@mapNotNull validDirections.firstNotNullOfOrNull { consideringDirection -> val (adjacent, destinationDir) = consideringDirection.invoke(elf) (elf to destinationDir).takeIf { adjacent.none { it in elves } } } } .groupBy { (_, destination) -> destination } .mapValues { (_, elvasWithSameDes) -> elvasWithSameDes.map { it.first } } // second half proposedElvasMoves.filter { it.value.singleOrNull() != null }.forEach {(desElfPos, currElfPos) -> elves.remove(currElfPos.single()) elves.add(desElfPos) } validDirections.addLast(validDirections.removeFirst()) } // no need for tiles counts on second part if (onNoMoves != null) { onNoMoves(round) return -1 } return elves.countTiles() } private fun Set<Elf>.countTiles(): Int { val mostLeft = minOf { it.x } val mostRight = maxOf { it.x } val mostTop = minOf { it.y } val mostDown = maxOf { it.y } return (mostTop..mostDown).sumOf { row -> (mostLeft..mostRight).count { col -> aoc2022.Elf(x = col, y = row) !in this } } }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
2,963
Kotlin-AOC-2023
Apache License 2.0
src/Day12.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
typealias Board = List<String> fun Point.toUp(): Point = Point(this.x - 1, y) fun Point.toDown(): Point = Point(this.x + 1, y) fun Point.toRight(): Point = Point(this.x, y + 1) fun Point.toLeft(): Point = Point(this.x, y - 1) fun Board.get(p: Point): Char = this[p.x][p.y] fun Board.height(p: Point): Int { return when (get(p)) { 'S' -> 'a' 'E' -> 'z' else -> get(p) }.code } fun Board.canMoveUp(from: Point, to: Point): Boolean { val (x, y) = to if (x < 0 || x == rows || y < 0 || y == columns || this[from.x][from.y] == 'E') { return false } val currentHeight = height(from) val targetHeight = height(to) return targetHeight - currentHeight < 2 } fun Board.canMoveDown(from: Point, to: Point): Boolean { val (x, y) = to if (x < 0 || x == this.size || y < 0 || y == this[0].length || this[from.x][from.y] == 'a' || this[from.x][from.y] == 'S') { return false } return height(from) - height(to) < 2 } fun Array<Array<Int>>.get(p: Point): Int = this[p.x][p.y] fun Array<Array<Int>>.set(p: Point, value: Int): Point { this[p.x][p.y] = value return p } fun Array<Array<Int>>.printState() { println( this.joinToString( "\n", "=========\n" ) { it.joinToString { num -> if (num < 10) "0$num" else if (num < 100) "$num" else "HI" } }) } val Board.start: Point get() = Point(this.indexOfFirst { it.startsWith("S") }, 0) val Board.end: Point get() { val endRow = indexOfFirst { it.contains('E') } return Point(endRow, this[endRow].indexOf('E')) } val Board.rows: Int get() = size val Board.columns: Int get() = this[0].length fun Board.buildSteps(init: (Point) -> Int): Array<Array<Int>> = Array(rows) { row -> Array(columns) { column -> init(Point(row, column)) } } fun Board.allOf(ch: Char): List<Point> { return this.flatMapIndexed { row, line -> line.mapIndexedNotNull { column, char -> if (char == ch) Point( row, column ) else null } } } fun main() { fun part1(input: Board): Int { val steps = input.buildSteps { if (input.start == it) 0 else Int.MAX_VALUE } val pathQueue = mutableListOf(input.start) while (pathQueue.isNotEmpty()) { val from = pathQueue.removeLast() listOf(from.toLeft(), from.toRight(), from.toDown(), from.toUp()) .filter { input.canMoveUp(from, it) } .forEach { target -> val targetSteps = steps.get(from) + 1 if (steps.get(target) > targetSteps) { pathQueue.add(steps.set(target, targetSteps)) } } } return steps.get(input.end) } fun part2(input: List<String>): Int { val steps = input.buildSteps { if (input.end == it) 0 else Int.MAX_VALUE } val pathQueue = mutableListOf(input.end) while (pathQueue.isNotEmpty()) { val from = pathQueue.removeLast() listOf(from.toLeft(), from.toRight(), from.toDown(), from.toUp()) .filter { input.canMoveDown(from, it) } .forEach { target -> val targetSteps = steps.get(from) + 1 if (steps.get(target) > targetSteps) { pathQueue.add(steps.set(target, targetSteps)) } } } return input.allOf('a').map { steps.get(it) }.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") check(part1(input) == 534) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
3,871
advent-of-code-2022
Apache License 2.0
src/main/kotlin/adventofcode2023/day15/day15.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day15 import adventofcode2023.readInput import kotlin.time.measureTime fun main() { println("Day 15") val input = readInput("day15") val time1 = measureTime { println("Puzzle 1 ${handleSequence(input.first)}") } println("Puzzle 1 took $time1") val time2 = measureTime { println("Puzzle 2 ${calculateFocusingPower(handleSequence2(input.first))}") } println("Puzzle 2 took $time2") } fun calculateHash(s: String): Short { var currentValue = 0 s.forEach { c -> currentValue += c.code currentValue *= 17 currentValue %= 256 } return currentValue.toShort() } fun handleSequence(line: String): Int = line.split(',').map { calculateHash(it) }.sum() fun handleSequence2(line: String): Array<LinkedHashMap<String, Int>> { val myMap = Array(256) { LinkedHashMap<String, Int>() } line.split(',').forEach { s -> val label = s.filter { it.isLetter() } val hash = calculateHash(label) val lenses = myMap[hash.toInt()] if (s.contains('-')) { lenses.remove(label) } else { s.split('=').let { (label, focus) -> lenses.put(label, focus.toInt()) } } } return myMap } fun calculateFocusingPower(boxes: Array<LinkedHashMap<String, Int>>): Long { val result = boxes.flatMapIndexed { boxIndex, lenses -> lenses.entries.mapIndexed { lenseIndex, mutableEntry -> ((boxIndex + 1) * (lenseIndex + 1) * mutableEntry.value).toLong() } }.sum() return result }
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
1,580
adventofcode2023
MIT License
src/main/kotlin/adventofcode/year2021/Day13TransparentOrigami.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2021 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day13TransparentOrigami(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val paper by lazy { val dots = input.split("\n\n").first().lines().map { it.split(",").first().toInt() to it.split(",").last().toInt() }.toSet() val maxX = dots.maxOf { it.first } val maxY = dots.maxOf { it.second } (0..maxY).map { y -> (0..maxX).map { x -> dots.contains(x to y) } } } private val instructions by lazy { input.split("\n\n").last().lines().map { it.split("=").first().last() to it.split("=").last().toInt() } } override fun partOne() = paper .fold(instructions.first()) .flatten() .count { it } override fun partTwo() = generateSequence(0 to paper.fold(instructions.first())) { (previousFold, previousPaper) -> if (previousFold + 1 < instructions.size) previousFold + 1 to previousPaper.fold(instructions[previousFold + 1]) else null } .last() .second .joinToString(separator = "\n", prefix = "\n", postfix = "\n") { row -> row.joinToString("") { cell -> if (cell) "█" else " " } } companion object { private fun List<List<Boolean>>.fold(instruction: Pair<Char, Int>) = when (instruction.first) { 'x' -> foldLeft(instruction.second) 'y' -> foldUp(instruction.second) else -> throw IllegalArgumentException("${instruction.first} is not a valid fold direction") } private fun List<List<Boolean>>.foldLeft(along: Int) = map { it.take(along) } .zip(map { it.takeLast(along).reversed() }) .map { it.first.zip(it.second) } .map { it.map { it.first || it.second } } private fun List<List<Boolean>>.foldUp(along: Int) = take(along) .zip(takeLast(along).reversed()) .map { it.first.zip(it.second) } .map { it.map { it.first || it.second } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,020
AdventOfCode
MIT License
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day21.kt
jntakpe
572,853,785
false
{"Kotlin": 72329, "Rust": 15876}
package com.github.jntakpe.aoc2022.days import com.github.jntakpe.aoc2022.shared.Day import com.github.jntakpe.aoc2022.shared.readInputLines object Day21 : Day { override val input = readInputLines(21).associate { parse(it) } private val results = input.mapNotNull { (k, v) -> (v as? Operation.Result)?.let { k to v.result } }.toMap() private val root = input.getValue("root") as Operation.Nested override fun part1() = total("root", results.toMutableMap()) override fun part2() = newtonRaphson(0) private tailrec fun newtonRaphson(value: Long): Long { val leftDiff = diff(value) val rightDiff = diff(value + 1) return when { leftDiff == 0L -> value rightDiff == 0L -> value + 1 rightDiff - leftDiff == 0L -> newtonRaphson(value + 1) else -> newtonRaphson(value - (leftDiff / (rightDiff - leftDiff))) } } private fun diff(guess: Long): Long { return total(root.left, withHumanValue(guess)) - total(root.right, withHumanValue(guess)) } private fun withHumanValue(value: Long) = results.toMutableMap().apply { compute("humn") { _, _ -> value } } private fun total(monkey: String, results: MutableMap<String, Long>): Long { return when (val operation = input.getValue(monkey)) { is Operation.Result -> operation.result is Operation.Nested -> { val left = results[operation.left] ?: total(operation.left, results) val right = results[operation.right] ?: total(operation.right, results) val result = when (operation.sign) { Sign.ADD -> left + right Sign.MINUS -> left - right Sign.TIMES -> left * right Sign.DIVIDE -> left / right } results[monkey] = result result } } } private fun parse(line: String): Pair<String, Operation> { val (key, ope) = line.split(':').map { it.trim() } return key to Operation.from(ope) } sealed interface Operation { companion object { fun from(input: String): Operation { input.toLongOrNull()?.let { return Result(it) } val (left, rawSign, right) = input.split(' ') val sign = when (rawSign.single()) { '+' -> Sign.ADD '-' -> Sign.MINUS '*' -> Sign.TIMES '/' -> Sign.DIVIDE else -> error("Unknown sign $rawSign") } return Nested(left, right, sign) } } data class Result(val result: Long) : Operation data class Nested(val left: String, val right: String, val sign: Sign) : Operation } enum class Sign { ADD, MINUS, TIMES, DIVIDE } }
1
Kotlin
0
0
63f48d4790f17104311b3873f321368934060e06
2,946
aoc2022
MIT License
src/Day04.kt
stevennoto
573,247,572
false
{"Kotlin": 18058}
fun main() { fun part1(input: List<String>): Int { // Parse input ranges, check whether one contains another, count number that do val regex = Regex("(\\d+)-(\\d+),(\\d+)-(\\d+)") return input.count { val (i, j, m, n) = regex.find(it)!!.destructured.toList().map { it.toInt() } ((i >= m && j <= n) || (m >= i && n <= j)) } } fun part2(input: List<String>): Int { // Parse input ranges, check whether they overlap at all, count number that do val regex = Regex("(\\d+)-(\\d+),(\\d+)-(\\d+)") return input.count { val (i, j, m, n) = regex.find(it)!!.destructured.toList().map { it.toInt() } (i in m..n || j in m..n || m in i..j || n in i..j) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
42941fc84d50b75f9e3952bb40d17d4145a3036b
1,047
adventofcode2022
Apache License 2.0
src/aoc2023/Day02.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2023 import readInput fun main() { val MAX_RED = 12 val MAX_GREEN = 13 val MAX_BLUE = 14 val RED_REGEX = " (\\d+) red".toRegex() val GREEN_REGEX = " (\\d+) green".toRegex() val BLUE_REGEX = " (\\d+) blue".toRegex() fun part1(input: List<String>): Long { var sumOfIds = 0L for ((index, line) in input.withIndex()) { var valid = true val reds = RED_REGEX.findAll(line) for (red in reds) { if (red.groups[1]!!.value.toInt() > MAX_RED) { valid = false; break; } } val greens = GREEN_REGEX.findAll(line) for (green in greens) { if (green.groups[1]!!.value.toInt() > MAX_GREEN) { valid = false; break; } } val blues = BLUE_REGEX.findAll(line) for (blue in blues) { if (blue.groups[1]!!.value.toInt() > MAX_BLUE) { valid = false; break; } } if (valid) sumOfIds += (index + 1) } return sumOfIds } fun part2(input: List<String>): Long { var sumOfPowers = 0L for ((index, line) in input.withIndex()) { var minReds = 0 val reds = RED_REGEX.findAll(line) for (red in reds) { val minRed = red.groups[1]!!.value.toInt() if (minRed > minReds) { minReds = minRed } } var minGreens = 0 val greens = GREEN_REGEX.findAll(line) for (green in greens) { val minGreen = green.groups[1]!!.value.toInt() if (minGreen > minGreens) { minGreens = minGreen } } var minBlues = 0 val blues = BLUE_REGEX.findAll(line) for (blue in blues) { val minBlue = blue.groups[1]!!.value.toInt() if (minBlue > minBlues) { minBlues = minBlue } } sumOfPowers += (minReds * minGreens * minBlues) } return sumOfPowers } println(part1(readInput("aoc2023/Day02"))) println(part2(readInput("aoc2023/Day02"))) }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
2,341
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/com/txq/sort/Sort.kt
flyingyizi
124,735,014
false
null
package com.txq.com.txq.sort //https://rosettacode.org/wiki/Category:Sorting_Algorithms import java.util.Comparator import java.util.Arrays private val COMPARATOR = Comparator<Int> { o1, o2 -> when { o1 < o2 -> -1 o1 > o2 -> 1 else -> 0 } } fun main(args: Array<String>) { val list = arrayOf<Int>(2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1,2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1) println( "Original:\n${list.asList()}" ) /** * 计算两个时间点直接逝去的毫秒数 * */ val start = System.currentTimeMillis() //BubbleSort< Int > (list, COMPARATOR) //CircleSort< Int > (list, COMPARATOR) //HeapSort< Int > (list, COMPARATOR) QuickSort<Int>(list, COMPARATOR) val end = System.currentTimeMillis() println( "Sorted :\n${list.asList()}. consumed ${(end - start)} ms. " ) } private fun <T> Array<T>.swap(index1: Int, index2: Int) { val tmp = this[index1] // “this”对应该列表 this[index1] = this[index2] this[index2] = tmp } fun <T> BubbleSort(a: Array<T>, c: Comparator<T>) { var changed: Boolean do { changed = false for (i in 0..a.size - 2) { if (c.compare(a[i], a[i + 1]) > 0) { a.swap( i, i + 1) changed = true } } } while (changed) } //https://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort#Java fun<T> CircleSort( a: Array<T>, c: Comparator<T> ) { if (a.size > 0) do { println(Arrays.toString(a)) } while (circleSortR(a, 0, a.size - 1, 0, c) != 0) } private fun<T> circleSortR(arr: Array<T>, lo: Int, hi: Int, numSwaps: Int, c: Comparator<T> ): Int { var lo = lo var hi = hi var swaped = numSwaps if (lo == hi) return swaped val high = hi val low = lo val mid = (hi - lo) / 2 while (lo < hi ) { if ( c.compare(arr[lo], arr[hi])>0 ) { arr.swap( lo, hi) swaped++ } lo++ hi-- } if (lo == hi && c.compare(arr[lo], arr[hi + 1])>0 ) { arr.swap( lo, hi + 1) swaped++ } swaped = circleSortR(arr, low, low + mid, swaped, c) swaped = circleSortR(arr, low + mid + 1, high, swaped, c) return swaped } fun<T> HeapSort(a: Array<T>, c: Comparator<T> ) { // 建堆 heapify(a, c) // 堆排序 var end = a.size - 1 while (end > 0) { val temp = a[end] a[end] = a[0] a[0] = temp end-- siftDown(a, 0, end, c) } } private fun<T> heapify(a: Array<T>, c: Comparator<T> ) { /* 数组存放二叉堆: root /\ / \ left right index 关系(下标从0开始): left = root*2+ 1 right = left + 1 */ //从右往左,处理每一个二叉堆 var root = (a.size - 2) / 2 while (root >= 0) { siftDown(a, root, a.size - 1, c) root-- } } private fun<T> siftDown(a: Array<T>, start: Int, end: Int, c: Comparator<T> ) { var root = start while (root * 2 + 1 <= end) { var child = root * 2 + 1 if (child + 1 <= end && c.compare(a[child], a[child+1])<0 ) child++ if ( c.compare(a[root], a[child])<0 ) { a.swap(root,child) root = child } else return } } fun<T> QuickSort(array: Array<T>, c: Comparator<T>) { subQuickSort(array, 0, array.size - 1, c) } private fun<T> subQuickSort(a: Array<T>?, start: Int, end: Int, c: Comparator<T>) { if (a == null || end - start + 1 < 2) { return } val part = partition(a, start, end, c) if (part == start) { subQuickSort(a, part + 1, end, c) } else if (part == end) { subQuickSort(a, start, part - 1, c) } else { subQuickSort(a, start, part - 1, c) subQuickSort(a, part + 1, end, c) } } private fun<T> partition(a: Array<T>, start: Int, end: Int, c: Comparator<T>): Int { val value = a[end] var index = start - 1 for (i in start until end) { if ( c.compare(a[i], value)<0 ) { index++ if (index != i) { a.swap(index,i) } } } if (index + 1 != end) { a.swap(index+1,end) } return index + 1 }
0
Kotlin
0
0
f4ace2d018ae8a93becaee85b7db882098074b7a
4,319
helloworldprovider
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindCheapestPrice.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.PriorityQueue import java.util.Queue import kotlin.math.min /** * 787. Cheapest Flights Within K Stops * @see <a href="https://leetcode.com/problems/cheapest-flights-within-k-stops/">Source</a> */ fun interface FindCheapestPrice { operator fun invoke(n: Int, flights: Array<IntArray>, src: Int, dst: Int, k: Int): Int } class FindCheapestPriceBFS : FindCheapestPrice { override operator fun invoke(n: Int, flights: Array<IntArray>, src: Int, dst: Int, k: Int): Int { val map: MutableMap<Int, MutableList<IntArray>> = HashMap() for (i in flights) { map.putIfAbsent(i[0], ArrayList()) map[i[0]]?.add(intArrayOf(i[1], i[2])) } var step = 0 val q: Queue<IntArray> = LinkedList() q.offer(intArrayOf(src, 0)) var ans = Int.MAX_VALUE while (q.isNotEmpty()) { val size = q.size for (i in 0 until size) { val curr = q.poll() if (curr[0] == dst) ans = min(ans, curr[1]) if (!map.containsKey(curr[0])) continue for (f in map[curr[0]]!!) { if (curr[1] + f[1] > ans) { // Pruning continue } q.offer(intArrayOf(f[0], curr[1] + f[1])) } } if (step++ > k) break } return if (ans == Int.MAX_VALUE) -1 else ans } } class FindCheapestPriceBellmanFord : FindCheapestPrice { override operator fun invoke(n: Int, flights: Array<IntArray>, src: Int, dst: Int, k: Int): Int { var cost = IntArray(n) { Int.MAX_VALUE } cost[src] = 0 for (i in 0..k) { val temp: IntArray = cost.copyOf(n) for (f in flights) { val curr = f[0] val next = f[1] val price = f[2] if (cost[curr] == Int.MAX_VALUE) continue temp[next] = min(temp[next], cost[curr] + price) } cost = temp } return if (cost[dst] == Int.MAX_VALUE) -1 else cost[dst] } } class FindCheapestPriceDijkstra : FindCheapestPrice { override operator fun invoke(n: Int, flights: Array<IntArray>, src: Int, dst: Int, k: Int): Int { val map: MutableMap<Int, MutableList<IntArray>> = HashMap() for (f in flights) { map.putIfAbsent(f[0], ArrayList()) map[f[0]]?.add(intArrayOf(f[1], f[2])) } val q: PriorityQueue<IntArray> = PriorityQueue { o1, o2 -> o1[0].compareTo(o2[0]) } q.offer(intArrayOf(0, src, k + 1)) while (q.isNotEmpty()) { val c: IntArray = q.poll() val cost = c[0] val curr = c[1] val stop = c[2] if (curr == dst) return cost if (stop > 0) { if (!map.containsKey(curr)) continue for (next in map[curr]!!) { q.add(intArrayOf(cost + next[1], next[0], stop - 1)) } } } return -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,757
kotlab
Apache License 2.0
src/Day07.kt
timlam9
573,013,707
false
{"Kotlin": 9410}
fun main() { class Node( val name: String, val parent: Node?, var children: List<Node> = emptyList() ) { var size: Long = 0L val totalSize: Long get() = size + children.sumOf { it.totalSize } } fun List<String>.createTree(): Pair<Node, MutableList<Node>> { val root = Node("/", null) val nodes = mutableListOf<Node>() var currentNode = root forEach { command -> when { command == "$ cd /" -> currentNode = root command == "$ cd .." -> currentNode = currentNode.parent!! command.startsWith("$ cd") -> { currentNode = currentNode.children.first { it.name == command.split(" ").last() } } command.startsWith("dir") -> Node(name = command.split(" ").last(), parent = currentNode) .apply { currentNode.children += this nodes += this } command.startsWith("$ ls") -> Unit else -> currentNode.size += command.split(" ").first().toLong() } } return root to nodes } fun part1(input: List<String>): Long { val nodes = input.createTree().second return nodes.filter { it.totalSize <= 100000L }.sumOf { it.totalSize } } fun part2(input: List<String>): Long { val (root, nodes) = input.createTree() val spaceNeeded = 30000000 - (70000000 - root.totalSize) return nodes.filter { it.totalSize >= spaceNeeded }.minOf { it.totalSize } } val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1df3465966915590022981546659ee4f1cdeb33b
1,734
AdventOfCodeKotlin2022
Apache License 2.0
src/day03/Day03.kt
iulianpopescu
572,832,973
false
{"Kotlin": 30777}
package day03 import readInput private const val DAY = "03" private const val DAY_TEST = "day${DAY}/Day${DAY}_test" private const val DAY_INPUT = "day${DAY}/Day${DAY}" fun main() { fun countCommonItems(value: String): Int { val halfIndex = value.length / 2 val left = value.substring(0, halfIndex).toSet() val right = value.substring(halfIndex).toSet() return left.sumOf { if (right.contains(it)) it.priority else 0 } } fun countCommonItems(a: String, b: String, c: String): Int { val aSet = a.toSet() val bSet = b.toSet() val cSet = c.toSet() return aSet.sumOf { if (bSet.contains(it) && cSet.contains(it)) it.priority else 0 } } fun part1(input: List<String>) = input.sumOf { countCommonItems(it) } fun part2(input: List<String>) = input .windowed(3, 3) .sumOf { (a, b, c) -> countCommonItems(a, b, c) } // test if implementation meets criteria from the description, like: val testInput = readInput(DAY_TEST) check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput(DAY_INPUT) println(part1(input)) println(part2(input)) } private val Char.priority: Int get() { return if (this.isLowerCase()) { this.code - 'a'.code + 1 } else { this.code - 'A'.code + 27 } }
0
Kotlin
0
0
4ff5afb730d8bc074eb57650521a03961f86bc95
1,454
AOC2022
Apache License 2.0
src/day10/Day10.kt
tobihein
569,448,315
false
{"Kotlin": 58721}
package day10 import readInput class Day10 { fun part1(): Int { val readInput = readInput("day10/input") return part1(readInput) } fun part2(): List<String> { val readInput = readInput("day10/input") return part2(readInput) } fun part1(input: List<String>): Int { val cycleValues = getCycleValues(input) return valuesFrom(cycleValues, 20, 60, 100, 140, 180, 220) } fun part2(input: List<String>): List<String> { val cycleValues = getCycleValues(input) val result = mutableListOf<String>() for (cycle in 1..cycleValues.size) { val x = cycleValues.get(cycle)?.first if (x == null) { throw RuntimeException("No value found for cycle cycle") } result.add(output(cycle, x)) } return result.chunked(40).map { it.joinToString("", "", "") } } private fun getCycleValues(input: List<String>): Map<Int, Pair<Int, Int>> { val cycleValues = mutableMapOf<Int, Pair<Int, Int>>() var cycle = 0 var x = 1 input.forEach { cycle++ if (it == "noop") { cycleValues.put(cycle, Pair(x, x)) } else if (it.startsWith("addx")) { val addValue = it.split(" ")[1].toInt() cycleValues.put(cycle, Pair(x, x)) cycle++ cycleValues.put(cycle, Pair(x, x + addValue)) x = x + addValue } } return cycleValues } private fun output(cycle: Int, x: Int): String = (if (pixelPos(cycle) in (x - 1)..(x + 1)) "#" else ".") private fun pixelPos(cycle: Int): Int = ((cycle - 1) % 40) private fun valuesFrom(cycleValues: Map<Int, Pair<Int, Int>>, vararg cycles: Int): Int = cycleValues.filter { cycles.contains(it.key) }.map { it.key * it.value.first }.sum() }
0
Kotlin
0
0
af8d851702e633eb8ff4020011f762156bfc136b
1,931
adventofcode-2022
Apache License 2.0
src/Day07.kt
DiamondMiner88
573,073,199
false
{"Kotlin": 26457, "Rust": 4093, "Shell": 188}
import kotlin.math.abs import kotlin.math.max fun main() { val input = readInput("input/day07.txt") .split("\n") .filter { it.isNotBlank() } var cd = "" val files = mutableMapOf<String, Int>() var curCmd: String? = null for (line in input) { if (line[0] == '$') { curCmd = line.substring(2) when { curCmd.startsWith("cd") -> { val dir = line.substring(5) if (dir == "..") { cd = cd.substring(0, cd.lastIndexOf("/")) if (cd == "") cd = "/" } else if (dir == "/") { cd = "/" } else { if (cd == "/") { cd = "/$dir" } else { cd = "$cd/$dir" } } curCmd = null } curCmd == "ls" -> { curCmd = "ls" } } } else if (curCmd == "ls") { val splits = line.split(" ") if (splits[0].all { it.isDigit() }) { if (cd == "/") { files["/${splits[1]}"] = splits[0].toInt() } else { files["$cd/${splits[1]}"] = splits[0].toInt() } } } } val allDirs = files.flatMap { val names = mutableListOf<String>() for (i in 0 until it.key.length) { if (it.key[i] == '/') { names += it.key.substring(0, i) } } names }.distinct().filter { it.isNotBlank() } + "/" val dirSizes = allDirs.associateWith { var totalSize = 0 for ((file, size) in files) { if (file.substring(0, max(file.lastIndexOf("/"), 1)).startsWith("$it")) totalSize += size } totalSize } var part1 = 0 for (size in dirSizes.values) if (size <= 100000) part1 += size println(part1) val neededSpace = abs(70000000 - dirSizes["/"]!! - 30000000) var part2 = 70000000 for (size in dirSizes.values) if (neededSpace <= size && part2 > size) part2 = size println(part2) }
0
Kotlin
0
0
55bb96af323cab3860ab6988f7d57d04f034c12c
2,362
advent-of-code-2022
Apache License 2.0
src/Day01.kt
timj11dude
572,900,585
false
{"Kotlin": 15953}
fun main() { fun Collection<String>.groupByBlankLine() = buildMap<Int, List<String>> { var i = 0 this@groupByBlankLine.forEach { if (it.isBlank()) i++ else this.compute(i) { _, e -> if (e == null) listOf(it) else (e + it) } } } fun shared(input: Collection<String>) = input.groupByBlankLine() .mapValues { entry -> entry.value.map { it.toInt() } } fun part1(input: Collection<String>): Int { return shared(input) .maxOf { entry -> entry.value.sum() } } fun part2(input: Collection<String>): Int { return shared(input) .values.map { it.sum() } .sorted() .takeLast(3) .sum() } // 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
28aa4518ea861bd1b60463b23def22e70b1ed481
1,065
advent-of-code-2022
Apache License 2.0
src/Day04.kt
lbilger
574,227,846
false
{"Kotlin": 5366}
fun main() { fun <T: Comparable<T>> ClosedRange<T>.containsAll(other: ClosedRange<T>) = start <= other.start && endInclusive >= other.endInclusive fun String.toRange(): IntRange { val parts = split("-") return parts[0].toInt()..parts[1].toInt() } fun ranges(input: List<String>) = input.map { it.split(",").map { it.toRange() } } fun part1(input: List<String>): Int { return ranges(input) .count { it[0].containsAll(it[1]) || it[1].containsAll(it[0]) } } fun part2(input: List<String>): Int { return ranges(input) .count { it[0].intersect(it[1]).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") checkTestAnswer(part1(testInput), 2, part = 1) checkTestAnswer(part2(testInput), 4, part = 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
40d94a4bb9621af822722d20675684555cbee877
965
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
kkaptur
573,511,972
false
{"Kotlin": 14524}
fun main() { val winningPairs = listOf(listOf("A", "B"), listOf("B", "C"), listOf("C", "A")) fun part1(input: List<String>): Int { var totalScore = 0 var myShapeTranslated = "" var round = emptyList<String>() var roundTranslated = emptyList<String>() input.forEach { round = it.split(" ") when (round[1]) { "X" -> { totalScore += 1 myShapeTranslated = "A" } "Y" -> { totalScore += 2 myShapeTranslated = "B" } "Z" -> { totalScore += 3 myShapeTranslated = "C" } } roundTranslated = listOf(round[0], myShapeTranslated) when { (myShapeTranslated == round[0]) -> totalScore += 3 winningPairs.contains(roundTranslated) -> totalScore += 6 } } return totalScore } fun part2(input: List<String>): Int { var totalScore = 0 var myShape = "" var round = emptyList<String>() input.forEach { round = it.split(" ") when (round[1]) { "X" -> { totalScore += 0 myShape = winningPairs.find { pair -> pair[1] == round[0] }?.get(0) ?: "" } "Y" -> { totalScore += 3 myShape = round[0] } "Z" -> { totalScore += 6 myShape = winningPairs.find { pair -> pair[0] == round[0] }?.get(1) ?: "" } } when (myShape) { "A" -> totalScore += 1 "B" -> totalScore += 2 "C" -> totalScore += 3 } } return totalScore } 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
055073b7c073c8c1daabbfd293139fecf412632a
2,151
AdventOfCode2022Kotlin
Apache License 2.0
src/main/kotlin/solutions/day21/Day21.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day21 import solutions.Solver enum class Operator { TIMES, PLUS, DIV, MINUS } sealed class MathMonkey { abstract val name: String abstract var value: Long? data class ConstantMonkey( override val name: String, override var value: Long? ) : MathMonkey() data class OperationMonkey( override val name: String, override var value: Long? = null, val operand1Name: String, val operand2Name: String, val operation: (Long, Long) -> Long, val operator: Operator ) : MathMonkey() } class Day21 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val monkeys = input.filter { !(partTwo && it.startsWith("humn")) }.map { parseMonkey(it) } val monkeyMap = mutableMapOf<String, MathMonkey>() monkeys.forEach { monkeyMap[it.name] = it } do { val isUnstable = simplify(monkeyMap, partTwo) if (!partTwo) { val rootValue = monkeyMap.getValue("root").value if (rootValue != null) { return rootValue.toString() } } } while (isUnstable) val root = monkeyMap.getValue("root") as MathMonkey.OperationMonkey var curr = if (monkeyMap.getValue(root.operand1Name).value != null) { monkeyMap.getValue(root.operand2Name) as MathMonkey.OperationMonkey } else { monkeyMap.getValue(root.operand1Name) as MathMonkey.OperationMonkey } var rhs = if (monkeyMap.getValue(root.operand1Name).value != null) { monkeyMap.getValue(root.operand1Name).value!! } else { monkeyMap.getValue(root.operand2Name).value!! } while (true) { val opLhs = monkeyMap[curr.operand1Name] val opRhs = monkeyMap[curr.operand2Name] rhs = reverseOperation(curr, opLhs, rhs, opRhs) if (curr.operand1Name == "humn" || curr.operand2Name == "humn") { break } curr = if (opLhs is MathMonkey.OperationMonkey) { opLhs } else if (opRhs is MathMonkey.OperationMonkey) { opRhs } else { throw Error("Neither LHS or RHS is operator") } } return rhs.toString() } private fun reverseOperation( curr: MathMonkey.OperationMonkey, opLhs: MathMonkey?, rhs: Long, opRhs: MathMonkey? ) = when (curr.operator) { Operator.TIMES -> if (opLhs is MathMonkey.ConstantMonkey) rhs / opLhs?.value!! else rhs / opRhs?.value!! Operator.PLUS -> if (opLhs is MathMonkey.ConstantMonkey) rhs - opLhs?.value!! else rhs - opRhs?.value!! Operator.DIV -> if (opLhs is MathMonkey.ConstantMonkey) opLhs.value!! / rhs else opRhs?.value!! * rhs Operator.MINUS -> if (opLhs is MathMonkey.ConstantMonkey) -(rhs - opLhs.value!!) else rhs + opRhs?.value!! } private fun simplify( monkeyMap: MutableMap<String, MathMonkey>, partTwo: Boolean, ): Boolean { var isUnstable = false monkeyMap.values .filter { (it.name != "root" || !partTwo) && it.value == null } .forEach { when (it) { is MathMonkey.OperationMonkey -> { val operand1 = monkeyMap[it.operand1Name] val operand2 = monkeyMap[it.operand2Name] if (operand1?.value != null && operand2?.value != null) { val value = it.operation(operand1.value!!, operand2.value!!) monkeyMap[it.name] = MathMonkey.ConstantMonkey(name = it.name, value = value) isUnstable = true } } is MathMonkey.ConstantMonkey -> {} } } return isUnstable } private fun parseMonkey(s: String): MathMonkey { val parts = s.split(":") val name = parts[0].trim() val rhs = parts[1].trim().split(" ") return if (rhs.size > 1) { val n1 = rhs[0].trim() val n2 = rhs[2].trim() val op: (Long, Long) -> Long = when (rhs[1].trim()) { "*" -> { i1: Long, i2: Long -> i1 * i2 } "/" -> { i1: Long, i2: Long -> i1 / i2 } "-" -> { i1: Long, i2: Long -> i1 - i2 } "+" -> { i1: Long, i2: Long -> i1 + i2 } else -> throw Error("Unexpected operator: " + rhs[1].trim()) } val operator = when (rhs[1].trim()) { "*" -> Operator.TIMES "/" -> Operator.DIV "-" -> Operator.MINUS "+" -> Operator.PLUS else -> throw Error("Unexpected operator: " + rhs[1].trim()) } MathMonkey.OperationMonkey(name, null, operand1Name = n1, operand2Name = n2, op, operator) } else { MathMonkey.ConstantMonkey(name, value = rhs[0].toLong()) } } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
5,206
Advent-of-Code-2022
MIT License
src/Day03.kt
hrach
572,585,537
false
{"Kotlin": 32838}
fun main() { fun part1(input: List<String>): Int { return input .sumOf { val l = it.length / 2 val a = it.substring(0, l).toSet() val b = it.substring(l).toSet() val shared = a.intersect(b).first() if (shared.isLowerCase()) { shared.code - 96 } else { shared.code - 64 + 26 } } } fun part2(input: List<String>): Int { return input .chunked(3) .sumOf { val i = it.map { it.toSet() }.reduce { a: Set<Char>, b -> a.intersect(b) } val shared = i.first() if (shared.isLowerCase()) { shared.code - 96 } else { shared.code - 64 + 26 } } } val testInput = readInput("Day03_test") check(part1(testInput), 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
40b341a527060c23ff44ebfe9a7e5443f76eadf3
777
aoc-2022
Apache License 2.0
src/Day06.kt
strindberg
572,685,170
false
{"Kotlin": 15804}
fun main() { fun distinct(chars: List<Char>): Boolean { for ((index, c) in chars.withIndex()) { if (index + 1 <= chars.size) { for (d in chars.subList(index + 1, chars.size)) { if (c == d) return false } } } return true } fun signature(input: String, length: Int): Int = input.fold(Triple(0, listOf<Char>(), false)) { (index, list, found), char -> if (list.size < length - 1) { Triple(index + 1, list + char, false) } else if (found) { Triple(index, list, true) } else { val newList = list.takeLast(length - 1) + char if (distinct(newList)) { Triple(index + 1, newList, true) } else { Triple(index + 1, newList, false) } } }.first val input = readInput("Day06")[0] println(signature(input, 4)) check(signature(input, 4) == 1909) println(signature(input, 14)) check(signature(input, 14) == 3380) }
0
Kotlin
0
0
c5d26b5bdc320ca2aeb39eba8c776fcfc50ea6c8
1,189
aoc-2022
Apache License 2.0
kotlin/graphs/matchings/MaxBipartiteMatchingHopcroftKarpEsqrtV.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.matchings import java.util.stream.Stream // https://en.wikipedia.org/wiki/Hopcroft–Karp_algorithm // time complexity: O(E * sqrt(V)) object MaxBipartiteMatchingHopcroftKarpEsqrtV { fun maxMatching(graph: Array<List<Integer>>): Int { val n1 = graph.size val n2: Int = Arrays.stream(graph).flatMap(Collection::stream).mapToInt(Integer::intValue).max().orElse(-1) + 1 val dist = IntArray(n1) val matching = IntArray(n2) Arrays.fill(matching, -1) val used = BooleanArray(n1) var res = 0 while (true) { bfs(graph, used, matching, dist) val vis = BooleanArray(n1) var f = 0 for (u in 0 until n1) if (!used[u] && dfs(graph, vis, used, matching, dist, u)) ++f if (f == 0) return res res += f } } fun bfs(graph: Array<List<Integer>>, used: BooleanArray, matching: IntArray, dist: IntArray) { Arrays.fill(dist, -1) val n1 = graph.size val Q = IntArray(n1) var sizeQ = 0 for (u in 0 until n1) { if (!used[u]) { Q[sizeQ++] = u dist[u] = 0 } } for (i in 0 until sizeQ) { val u1 = Q[i] for (v in graph[u1]) { val u2 = matching[v] if (u2 >= 0 && dist[u2] < 0) { dist[u2] = dist[u1] + 1 Q[sizeQ++] = u2 } } } } fun dfs( graph: Array<List<Integer>>, vis: BooleanArray, used: BooleanArray, matching: IntArray, dist: IntArray, u1: Int ): Boolean { vis[u1] = true for (v in graph[u1]) { val u2 = matching[v] if (u2 < 0 || !vis[u2] && dist[u2] == dist[u1] + 1 && dfs(graph, vis, used, matching, dist, u2)) { matching[v] = u1 used[u1] = true return true } } return false } // Usage example fun main(args: Array<String?>?) { val graph: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(2).toArray { _Dummy_.__Array__() } graph[0].add(0) graph[0].add(1) graph[1].add(1) System.out.println(2 == maxMatching(graph)) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
2,359
codelibrary
The Unlicense
src/main/kotlin/com/hj/leetcode/kotlin/problem1926/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1926 /** * LeetCode page: [1926. Nearest Exit from Entrance in Maze](https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/); */ class Solution { /* Complexity: * Time O(|maze|) and Space O(|maze|); */ fun nearestExit(maze: Array<CharArray>, entrance: IntArray): Int { var steps = 0 val visited = newInitialVisitedTable(maze) val currStepPositions = ArrayDeque<IntArray>() currStepPositions.addLast(entrance) visited[entrance[0]][entrance[1]] = true while (currStepPositions.isNotEmpty()) { steps++ repeat(currStepPositions.size) { val position = currStepPositions.removeFirst() val neighbours = getNeighbourPositions(position) for (neighbour in neighbours) { if (isValidAndNonVisited(neighbour, maze, visited)) { if (isAtBorder(neighbour, maze)) return steps currStepPositions.addLast(neighbour) visited[neighbour[0]][neighbour[1]] = true } } } } return -1 } private fun newInitialVisitedTable(maze: Array<CharArray>): List<BooleanArray> { return List(maze.size) { row -> BooleanArray(maze[row].size) { column -> maze[row][column] == '+' } } } private fun getNeighbourPositions(position: IntArray): List<IntArray> { return listOf( intArrayOf(position[0] - 1, position[1]), intArrayOf(position[0] + 1, position[1]), intArrayOf(position[0], position[1] - 1), intArrayOf(position[0], position[1] + 1) ) } private fun isValidAndNonVisited( position: IntArray, maze: Array<CharArray>, visited: List<BooleanArray> ): Boolean { return !isOutOfRange(position, maze) && !visited[position[0]][position[1]] } private fun isOutOfRange(position: IntArray, maze: Array<CharArray>): Boolean { return position[0] !in maze.indices || position[1] !in maze[position[0]].indices } private fun isAtBorder(position: IntArray, maze: Array<CharArray>): Boolean { if (isOutOfRange(position, maze)) return false return position[0] == 0 || position[0] == maze.lastIndex || position[1] == 0 || position[1] == maze[position[0]].lastIndex } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,513
hj-leetcode-kotlin
Apache License 2.0
src/Year2022Day15.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
import kotlin.math.abs fun main() { val re = Regex("Sensor at x=(.*), y=(.*): closest beacon is at x=(.*), y=(.*)") data class Sensor( val x: Int, val y: Int, val r: Int, // scanningDistance ) { fun canDiscover(x: Int, y: Int): Boolean = abs(this.x - x) + abs(this.y - y) <= this.r } data class Beacon( val x: Int, val y: Int, ) fun parse(lines: List<String>): Pair<MutableList<Sensor>, MutableSet<Beacon>> { val sensors = mutableListOf<Sensor>() val beacons = mutableSetOf<Beacon>() for (line in lines) { val (sx, sy, bx, by) = re.matchEntire(line)!!.destructured .toList().map { it.toInt() } sensors.add(Sensor(sx, sy, abs(sx - bx) + abs(sy - by))) beacons.add(Beacon(bx, by)) } return sensors to beacons } fun part1(lines: List<String>, expectedY: Int): Int { val (sensors, beacons) = parse(lines) var minX = 0 var maxX = 0 sensors.forEach { val dx = it.r - abs(it.y - expectedY) if (dx >= 0) { minX = minX.coerceAtMost(it.x - dx) maxX = maxX.coerceAtLeast(it.x + dx) } } return (minX..maxX).count { x -> sensors.any { it.canDiscover(x, expectedY) } && Beacon(x, expectedY) !in beacons } } fun part2(lines: List<String>): Long { val (sensors, _) = parse(lines) val minY = sensors.minOf { it.y }.coerceAtLeast(0) val maxY = sensors.maxOf { it.y }.coerceAtMost(4000000) for (y in minY..maxY) { val segments = sensors.asSequence().mapNotNull { val dx = it.r - abs(it.y - y) if (dx >= 0) Pair(it.x - dx, it.x + dx) else null }.sortedWith(compareBy({ it.first }, { it.second })) var last = 0 segments.forEach { if (it.first > last) return (last + 1) * 4000000L + y last = last.coerceAtLeast(it.second) } } return -1 } val testLines = readLines(true) assertEquals(26, part1(testLines, 10)) assertEquals(56000011L, part2(testLines)) val lines = readLines() println(part1(lines, 2000000)) println(part2(lines)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
2,388
aoc-2022-in-kotlin
Apache License 2.0
src/year2021/05/Day05.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2021.`05` import readInput private data class AdventPoint( val x: Int, val y: Int ) { override fun toString(): String = "($x,$y)" operator fun plus(other: AdventPoint): AdventPoint { return this.copy( x = x + other.x, y = y + other.y ) } } private data class CustomLine( val from: AdventPoint, val to: AdventPoint ) { override fun toString(): String = "$from->$to" } fun main() { fun parse(input: List<String>): List<CustomLine> { return input.map { fun String.toPoint(): AdventPoint { val (x, y) = split(",").map { it.trimStart().trimEnd().toInt() } return AdventPoint(x, y) } val (first, second) = it.split("->") val fromPoint = first.toPoint() val toPoint = second.toPoint() CustomLine(fromPoint, toPoint) } } fun MutableMap<AdventPoint, Int>.incrementCounter(point: AdventPoint) { if (this.containsKey(point)) { this[point] = this[point]?.inc() ?: error("Impossible state") } else { this[point] = 1 } } fun between(line: CustomLine): Set<AdventPoint> { val from = line.from val to = line.to val deltaPoint = AdventPoint( x = when { from.x > to.x -> -1 from.x < to.x -> 1 else -> error("ILLEGAL") }, y = when { from.y > to.y -> -1 from.y < to.y -> 1 else -> error("ILLEGAL") } ) val mutableSet = mutableSetOf<AdventPoint>() var currentPoint = from do { mutableSet.add(currentPoint) currentPoint += deltaPoint } while ((currentPoint != to)) mutableSet.add(currentPoint) return mutableSet } fun processItem( line: CustomLine, mutableSet: MutableMap<AdventPoint, Int>, hasDiagonal: Boolean = false ) { val fromX = line.from.x val toX = line.to.x val fromY = line.from.y val toY = line.to.y when { fromX == toX -> (minOf(fromY, toY)..maxOf(fromY, toY)).forEach { mutableSet.incrementCounter(AdventPoint(fromX, it)) } fromY == toY -> (minOf(fromX, toX)..maxOf(fromX, toX)).forEach { mutableSet.incrementCounter(AdventPoint(it, fromY)) } else -> if (hasDiagonal) { between(line).forEach { mutableSet.incrementCounter(it) } } else { Unit } } } fun part1(input: List<String>): Int { val lines = parse(input) val mapOf = mutableMapOf<AdventPoint, Int>() lines.forEach { processItem(it, mapOf) } return mapOf.count { it.value >= 2 } } fun part2(input: List<String>): Int { val lines = parse(input) val mapOf = mutableMapOf<AdventPoint, Int>() lines.forEach { processItem(it, mapOf, true) } return mapOf.count { it.value >= 2 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") val part1Test = part1(testInput) val part2Test = part2(testInput) println(part1Test) println(part2Test) check(part1Test == 5) check(part2Test == 12) val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
3,563
KotlinAdventOfCode
Apache License 2.0
src/Day16.kt
mrugacz95
572,881,300
false
{"Kotlin": 102751}
import kotlin.math.max import kotlin.math.min import kotlin.time.ExperimentalTime import kotlin.time.measureTime private const val START = "AA" private const val DEBUG = true private data class Valve(val id: Int, val name: String, val rate: Int, val neighbours: List<String>, var open: Boolean = false) { fun canOpen(): Boolean = name != START && !open && rate > 0 override fun hashCode(): Int { return name.hashCode() } override fun equals(other: Any?): Boolean { return this.name == (other as? Valve)?.name } } private fun floydWarshall(graph: Map<String, Valve>): List<MutableList<Int>> { val dist = List(graph.size) { MutableList(graph.size) { Int.MAX_VALUE } } for (v in graph.values) { for (n in v.neighbours) { dist[v.id][graph[n]!!.id] = 1 } dist[v.id][v.id] = 0 } for (v1 in graph.values) { for (v2 in graph.values) { for (v3 in graph.values) { if (dist[v2.id][v1.id] != Int.MAX_VALUE && dist[v1.id][v3.id] != Int.MAX_VALUE) { dist[v2.id][v3.id] = min(dist[v2.id][v3.id], dist[v2.id][v1.id] + dist[v1.id][v3.id]) } } } } return dist } private fun solveReleasingPressure(graph: Map<String, Valve>, allowedValves: List<Valve>, dist: List<MutableList<Int>>, maxTime: Int): Int { val visited = BooleanArray(graph.size) fun dfs(valve: Valve, time: Int, released: Int): Int { if (visited[valve.id]) { return released } visited[valve.id] = true val releasedPressure = released + valve.rate * (maxTime - time) var result: Int = releasedPressure // released when waiting for (next in allowedValves) { val d = dist[valve.id][next.id] val t = time + 1 + d if (t > maxTime) { continue } result = max(result, dfs(next, t, releasedPressure)) } visited[valve.id] = false return result } return dfs(graph[START] ?: error("Vertex not found"), 0, 0) } private fun <T> Set<T>.allSplits() = sequence<Pair<Set<T>, Set<T>>> { if (size > 32) error("set is too big") val maxBitMask = ((1 shl size + 1) - 1) / 2 + 1 var mask = 0 val items = toList() while (mask < maxBitMask) { var bits = mask val set1 = mutableSetOf<T>() val set2 = mutableSetOf<T>() for (item in items) { if (bits % 2 == 0) { set1 += item } else { set2 += item } bits = bits shr 1 } mask += 1 if (DEBUG) print("\r$mask/$maxBitMask") yield(set1 to set2) } println() } @OptIn(ExperimentalTime::class) fun main() { fun List<String>.parse(): Map<String, Valve> { val regex = "Valve (?<name>[A-Z]{2}) has flow rate=(?<rate>\\d+); tunnels? leads? to valves? (?<n>([A-Z]{2}(, )?)+)".toRegex() return mapIndexed { idx, it -> val groups = regex.matchEntire(it)?.groups ?: error("doesnt match '$it'") Valve( id = idx, name = groups["name"]?.value ?: error("no name"), rate = groups["rate"]?.value?.toInt() ?: error("no rate"), neighbours = groups["n"]?.value?.split(", ") ?: error("no neighbours"), ) }.associateBy({ it.name }, { it }) } fun part1(input: List<String>): Int { val graph = input.parse() val dist = floydWarshall(graph) val withRate = graph.filter { it.value.canOpen() }.map { it.value } val maxTime = 30 return solveReleasingPressure(graph, withRate, dist, maxTime) } fun part2(input: List<String>): Int { val graph = input.parse() val dist = floydWarshall(graph) val allSplits = graph.filter { it.value.canOpen() }.map { it.value }.toSet().allSplits() var result = -Int.MAX_VALUE val maxTime = 26 for ((set1, set2) in allSplits){ val human = solveReleasingPressure(graph, set1.toList(), dist, maxTime) val elephant = solveReleasingPressure(graph, set2.toList(), dist, maxTime) result = max(human + elephant, result) } return result } val testInput = readInput("Day16_test") val time = measureTime { val input = readInput("Day16") assert(part1(testInput), 1651) println(part1(input)) assert(part2(testInput), 1707) println(part2(input)) } println("Exec time: $time") } // Time: 08:00
0
Kotlin
0
0
29aa4f978f6507b182cb6697a0a2896292c83584
4,645
advent-of-code-2022
Apache License 2.0
solutions/aockt/y2021/Y2021D02.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2021 import aockt.y2021.Y2021D02.SubmarineCommand.* import io.github.jadarma.aockt.core.Solution object Y2021D02 : Solution { /** The valid submarine commands, they might do different things depending on how you read the manual. */ private sealed interface SubmarineCommand { val amount: UInt data class Up(override val amount: UInt) : SubmarineCommand data class Down(override val amount: UInt) : SubmarineCommand data class Forward(override val amount: UInt) : SubmarineCommand companion object { fun parse(value: String): SubmarineCommand { val (command, amount) = value .split(" ") .let { (a, b) -> a to (b.toUIntOrNull() ?: throw IllegalArgumentException("Invalid value: $b")) } return when (command) { "up" -> ::Up "down" -> ::Down "forward" -> ::Forward else -> throw IllegalArgumentException("Invalid command: $command.") }(amount) } } } /** Holds the coordinates of a submarine's position at a given time. */ private data class Position(val depth: Int = 0, val horizontal: Int = 0, val aim: Int = 0) { init { require(depth >= 0) { "Submarines can't fly." } } } /** Parse the [input] and return the [SubmarineCommand]s to steer the submarine with. */ private fun parseInput(input: String): Sequence<SubmarineCommand> = input .lineSequence() .map(SubmarineCommand::parse) override fun partOne(input: String) = parseInput(input) .fold(Position()) { position, command -> when (command) { is Up -> position.copy(depth = maxOf(0, position.depth - command.amount.toInt())) is Down -> position.copy(depth = position.depth + command.amount.toInt()) is Forward -> position.copy(horizontal = position.horizontal + command.amount.toInt()) } } .let { it.horizontal * it.depth } override fun partTwo(input: String) = parseInput(input) .fold(Position()) { position, command -> when (command) { is Up -> position.copy(aim = position.aim - command.amount.toInt()) is Down -> position.copy(aim = position.aim + command.amount.toInt()) is Forward -> position.copy( horizontal = position.horizontal + command.amount.toInt(), depth = maxOf(0, position.depth + (position.aim * command.amount.toInt())), ) } } .let { it.horizontal * it.depth } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
2,836
advent-of-code-kotlin-solutions
The Unlicense
advent/src/main/kotlin/org/elwaxoro/advent/Extensions.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent import java.math.BigInteger /** * Nullable Long plusser, null defaults to 0 */ fun Long.plusNull(that: Long?): Long = (that ?: 0L) + this /** * Split a string into a list of integers * Ex: "01234" becomes [0, 1, 2, 3, 4] */ fun String.splitToInt(): List<Int> = map(Character::getNumericValue) /** * Replace matching values */ fun List<Int>.replace(oldInt: Int, newInt: Int): List<Int> = map { it.takeUnless { it == oldInt } ?: newInt } /** * Based on https://stackoverflow.com/questions/9562605/in-kotlin-can-i-create-a-range-that-counts-backwards * Kotlin ranges don't support positive or negative directions at the same time */ fun Int.toward(to: Int): IntProgression = IntProgression.fromClosedRange(this, to, 1.takeIf { this <= to } ?: -1) /** * Pads a progression of Int to the desired size, using the final Int as the pad value */ fun IntProgression.padTo(newSize: Int): List<Int> = toList().padTo(newSize) /** * Pads a list of anything to the desired size, using the final object as the pad object * ex * listOf(1,2,3).padTo(10) * becomes * [1, 2, 3, 3, 3, 3, 3, 3, 3, 3] */ fun <T> List<T>.padTo(newSize: Int): List<T> = takeIf { size >= newSize } ?: plus(List(newSize - size) { last() }) /** * Splits a list into two, one with the first N elements the other with the remainder of the original list * I wanted something like partition or windowed, except with the first part having a fixed size and the second part being the entire remainder */ fun <T> List<T>.takeSplit(n: Int): Pair<List<T>, List<T>> = take(n) to drop(n) /** * Get the median from a list of Int */ fun List<Int>.median(): Double = sorted().let { if (size % 2 == 0) { (it[size / 2] + it[size / 2 - 1]) / 2.0 } else { it[size / 2].toDouble() } } /** * Merge a list of maps by adding up values for matching keys * Merge values of matching keys using the provided merge function */ fun <T, U> List<Map<T, U>>.merge(merger: (value: U, existing: U?) -> U): Map<T, U> = fold(mutableMapOf()) { acc, map -> acc.also { map.entries.map { (key, value) -> acc[key] = merger(value, acc[key]) } } } /** * Generates all possible permutations of the provided list * Should be "in-order" depending on your definition of "in-order" when it comes to permutations * It's in some sort of order, anyway * Ex: [A, B, C] becomes [[A, B, C], [A, C, B], [B, A, C], [B, C, A], [C, A, B], [C, B, A]] * * NOTE: this will only work on lists up to size 8 or so without running the jvm out of memory, so I guess if you really need to go that hard, give it more RAMs * 8: 40,320 combos * 9: 362,880 combos * 10: 3,628,800 combos */ fun <T> List<T>.permutations(): List<List<T>> = (0..lastIndex).fold(listOf(listOf<T>() to this)) { acc, _ -> acc.flatMap { (permutation, candidates) -> candidates.map { permutation.plus(it) to candidates.minus(it) } } }.map { it.first } /** * greatest common factor (GCF, HCF, GCD) for a list */ fun List<BigInteger>.gcd(): BigInteger = fold(BigInteger.ZERO) { acc, int -> acc.gcd(int) } /** * least common multiple (LCM, LCD) for a list */ fun List<BigInteger>.lcm(): BigInteger = fold(BigInteger.ONE) { acc, int -> acc * (int / int.gcd(acc)) }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
3,302
advent-of-code
MIT License
advent-of-code2015/src/main/kotlin/day14/Advent14.kt
REDNBLACK
128,669,137
false
null
package day14 import parseInput import splitToLines import java.lang.Math.min import java.util.* /** --- Day 14: Reindeer Olympics --- This year is the Reindeer Olympics! Reindeer can fly at high speeds, but must rest occasionally to recover their energy. Santa would like to know which of his reindeer is fastest, and so he has them race. Reindeer can only either be flying (always at their top speed) or resting (not moving at all), and always spend whole seconds in either state. For example, suppose you have the following Reindeer: Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds. Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds. After one second, Comet has gone 14 km, while Dancer has gone 16 km. After ten seconds, Comet has gone 140 km, while Dancer has gone 160 km. On the eleventh second, Comet begins resting (staying at 140 km), and Dancer continues on for a total distance of 176 km. On the 12th second, both reindeer are resting. They continue to rest until the 138th second, when Comet flies for another ten seconds. On the 174th second, Dancer flies for another 11 seconds. In this example, after the 1000th second, both reindeer are resting, and Comet is in the lead at 1120 km (poor Dancer has only gotten 1056 km by that point). So, in this situation, Comet would win (if the race ended at 1000 seconds). Given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, what distance has the winning reindeer traveled? --- Part Two --- Seeing how reindeer move in bursts, Santa decides he's not pleased with the old scoring system. Instead, at the end of each second, he awards one point to the reindeer currently in the lead. (If there are multiple reindeer tied for the lead, they each get one point.) He keeps the traditional 2503 second time limit, of course, as doing otherwise would be entirely ridiculous. Given the example reindeer from above, after the first second, Dancer is in the lead and gets one point. He stays in the lead until several seconds into Comet's second burst: after the 140th second, Comet pulls into the lead and gets his first point. Of course, since Dancer had been in the lead for the 139 seconds before that, he has accumulated 139 points by the 140th second. After the 1000th second, Dancer has accumulated 689 points, while poor Comet, our old champion, only has 312. So, with the new scoring system, Dancer would win (if the race ended at 1000 seconds). Again given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, how many points does the winning reindeer have? */ fun main(args: Array<String>) { val test = """ |Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds. |Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds. """.trimMargin() val input = parseInput("day14-input.txt") println(findWinner(test, 1000)) println(findWinner(input, 2503)) } fun findWinner(input: String, totalTime: Int): Map<String, Pair<String, Int>?> { val reindeers = parseReindeers(input) tailrec fun maxPoints(counter: Int, points: HashMap<String, Int>): Pair<String, Int>? { val allDistances = reindeers.map { it.getDistance(counter) } val maxDistance = allDistances.maxBy { it.second }?.second allDistances.filter { it.second == maxDistance } .map { it.first } .forEach { points.computeIfPresent(it, { k, v -> v + 1 }) } if (counter == totalTime) return points.maxBy { it.value }?.toPair() return maxPoints(counter + 1, points) } return mapOf( "distance" to reindeers.map { it.getDistance(totalTime) }.maxBy { it.second }, "points" to maxPoints(1, HashMap(reindeers.map { it.name to 0 }.toMap())) ) } data class Reindeer(val name: String, val speed: Int, val fly: Int, val rest: Int) { fun total() = fly + rest fun getDistance(time: Int) = (name to speed * fly * (time / total()) + speed * min(fly, time % total())) } private fun parseReindeers(input: String) = input.splitToLines() .map { val name = it.split(" ", limit = 2).first() val (speed, flyTime, restTime) = Regex("""(\d+)""") .findAll(it) .map { it.groupValues[1] } .map(String::toInt) .toList() Reindeer(name = name, speed = speed, fly = flyTime, rest = restTime) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
4,564
courses
MIT License
src/main/kotlin/aoc2022/Day15.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2022 import AoCDay import util.match import kotlin.math.abs import kotlin.math.max // https://adventofcode.com/2022/day/15 object Day15 : AoCDay<Long>( title = "Beacon Exclusion Zone", part1Answer = 5832528, part2Answer = 13360899249595, ) { private fun manhattanDistance(x1: Int, y1: Int, x2: Int, y2: Int) = abs(x1 - x2) + abs(y1 - y2) private fun manhattanDistance(p: Position, x: Int, y: Int) = manhattanDistance(p.x, p.y, x, y) private fun manhattanDistance(p1: Position, p2: Position) = manhattanDistance(p1.x, p1.y, p2.x, p2.y) private data class Position(val x: Int, val y: Int) private data class SensorReport(val sensor: Position, val beacon: Position, val radius: Int) private val SENSOR_REPORT_REGEX = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""") private fun parseSensorReports(input: String) = input .lines() .map { line -> SENSOR_REPORT_REGEX.match(line) } .map { (xs, ys, xb, yb) -> val sensor = Position(xs.toInt(), ys.toInt()) val beacon = Position(xb.toInt(), yb.toInt()) SensorReport(sensor, beacon, radius = manhattanDistance(sensor, beacon)) } private val IntRange.size get() = if (isEmpty()) 0 else last - first + 1 override fun part1(input: String): Long { val row = 2000000 data class XRangesAndBeacons(val xRanges: List<IntRange>, val beacons: List<Position>) val (xRanges, beacons) = parseSensorReports(input) .fold( initial = XRangesAndBeacons(xRanges = emptyList(), beacons = emptyList()) ) { (xRanges, beacons), (sensor, beacon, radius) -> val dy = abs(sensor.y - row) val dx = radius - dy val xrs = if (dy <= radius) xRanges.plusElement(sensor.x - dx..sensor.x + dx) else xRanges val bs = if (beacon.y == row) beacons + beacon else beacons XRangesAndBeacons(xRanges = xrs, beacons = bs) } val mergedXRanges = xRanges .sortedBy { it.first } .fold(initial = emptyList<IntRange>()) { mergedXRanges, xRange -> val prev = mergedXRanges.lastOrNull() when { prev == null -> listOf(xRange) xRange.first in prev -> { val mergedXRange = prev.first..max(xRange.last, prev.last) mergedXRanges.dropLast(1).plusElement(mergedXRange) } else -> mergedXRanges.plusElement(xRange) } } val positionsInRow = mergedXRanges.fold(initial = 0L) { acc, xRange -> acc + xRange.size } val beaconsInRow = mergedXRanges.count { xRange -> beacons.any { it.x in xRange } } return positionsInRow - beaconsInRow } // this is somewhat brute force, could be solved more efficiently using some clever geometry I couldn't come up with override fun part2(input: String): Long { val range = 0..4000000 val sensorReports = parseSensorReports(input) for ((sensor, _, radius) in sensorReports) { // start at top of sensor diamond and walk clockwise var x = sensor.x var y = sensor.y - (radius + 1) repeat(4) { time -> val dx = if (time == 0 || time == 3) 1 else -1 val dy = if (time == 0 || time == 1) 1 else -1 repeat(radius + 1) { if ( x in range && y in range && sensorReports.all { (sensor, _, radius) -> manhattanDistance(sensor, x, y) > radius } ) { return x.toLong() * 4000000 + y } x += dx y += dy } } } error("Did not find the distress beacon") } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
3,989
advent-of-code-kotlin
MIT License
src/main/kotlin/day6/day6.kt
lavong
317,978,236
false
null
/* --- Day 6: Custom Customs --- As your flight approaches the regional airport where you'll switch to a much larger plane, customs declaration forms are distributed to the passengers. The form asks a series of 26 yes-or-no questions marked a through z. All you need to do is identify the questions for which anyone in your group answers "yes". Since your group is just you, this doesn't take very long. However, the person sitting next to you seems to be experiencing a language barrier and asks if you can help. For each of the people in their group, you write down the questions for which they answer "yes", one per line. For example: abcx abcy abcz In this group, there are 6 questions to which anyone answered "yes": a, b, c, x, y, and z. (Duplicate answers to the same question don't count extra; each question counts at most once.) Another group asks for your help, then another, and eventually you've collected answers from every group on the plane (your puzzle input). Each group's answers are separated by a blank line, and within each group, each person's answers are on a single line. For example: abc a b c ab ac a a a a b This list represents answers from five groups: The first group contains one person who answered "yes" to 3 questions: a, b, and c. The second group contains three people; combined, they answered "yes" to 3 questions: a, b, and c. The third group contains two people; combined, they answered "yes" to 3 questions: a, b, and c. The fourth group contains four people; combined, they answered "yes" to only 1 question, a. The last group contains one person who answered "yes" to only 1 question, b. In this example, the sum of these counts is 3 + 3 + 3 + 1 + 1 = 11. For each group, count the number of questions to which anyone answered "yes". What is the sum of those counts? --- Part Two --- As you finish the last group's customs declaration, you notice that you misread one word in the instructions: You don't need to identify the questions to which anyone answered "yes"; you need to identify the questions to which everyone answered "yes"! Using the same example as above: abc a b c ab ac a a a a b This list represents answers from five groups: In the first group, everyone (all 1 person) answered "yes" to 3 questions: a, b, and c. In the second group, there is no question to which everyone answered "yes". In the third group, everyone answered yes to only 1 question, a. Since some people did not answer "yes" to b or c, they don't count. In the fourth group, everyone answered yes to only 1 question, a. In the fifth group, everyone (all 1 person) answered "yes" to 1 question, b. In this example, the sum of these counts is 3 + 0 + 1 + 1 + 1 = 6. For each group, count the number of questions to which everyone answered "yes". What is the sum of those counts? */ package day6 fun main() { val input = AdventOfCode.file("day6/input") solvePartOne(input) solvePartTwo(input) } fun solvePartOne(input: String) { val groupAnswers = input .split("\n\n") .map { it.replace("\n", "") } .map { setOf(*it.toCharArray().toTypedArray()) } .map { it.size } println("solution part one: ${groupAnswers.sum()}") } fun solvePartTwo(input: String) { var solution = 0 val groups = input .split("\n\n") .map { it.split("\n") .map { setOf(*it.toCharArray().toTypedArray()) } .filterNot { it.isEmpty() } } val groupAnswers = input .split("\n\n") .map { it.replace("\n", "") } .map { setOf(*it.toCharArray().toTypedArray()) } groupAnswers.zip(groups) .onEach { (answers, groups) -> var commonAnswers: Set<Char> = mutableSetOf<Char>().apply { addAll(answers) } groups.forEach { commonAnswers = commonAnswers.intersect(it) } solution += commonAnswers.size } println("solution part2: $solution") }
0
Kotlin
0
1
a4ccec64a614d73edb4b9c4d4a72c55f04a4b77f
4,041
adventofcode-2020
MIT License
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day08/Day08.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pietromaggi.aoc2021.day08 import com.pietromaggi.aoc2021.readInput import java.util.Collections.swap // from https://gist.github.com/dmdrummond/4b1d8a4f024183375f334a5f0a984718 fun <V> List<V>.permutations(): List<List<V>> { val retVal: MutableList<List<V>> = mutableListOf() fun generate(k: Int, list: List<V>) { // If only 1 element, just output the array if (k == 1) { retVal.add(list.toList()) } else { for (i in 0 until k) { generate(k - 1, list) if (k % 2 == 0) { swap(list, i, k - 1) } else { swap(list, 0, k - 1) } } } } generate(this.count(), this.toList()) return retVal } fun part1(input: List<String>) = input.map { val (_, digits) = it.split(" | ") digits.split(" ").map(String::length) }.sumOf { line -> line.count { len -> (len == 2) or (len == 3) or (len == 4) or (len == 7) } } fun part2(input: List<String>): Int { val segmentsMapping = mapOf( setOf('A', 'B', 'C', 'E', 'F', 'G') to 0, setOf('C', 'F') to 1, setOf('A', 'C', 'D', 'E', 'G') to 2, setOf('A', 'C', 'D', 'F', 'G') to 3, setOf('B', 'C', 'D', 'F') to 4, setOf('A', 'B', 'D', 'F', 'G') to 5, setOf('A', 'B', 'D', 'E', 'F', 'G') to 6, setOf('A', 'C', 'F') to 7, setOf('A', 'B', 'C', 'D', 'E', 'F', 'G') to 8, setOf('A', 'B', 'C', 'D', 'F', 'G') to 9 ) // evaluate all the 5040 permutations :-( val inputCables = ('A'..'G').toList() val inputChars = ('a'..'g').toList() val permutations = inputChars.permutations().map { perm -> perm.zip(inputCables).toMap() } fun bruteForceIt(words: List<String>, expectedNumbers: List<String>): Int { fun getMapping(): Map<Char, Char> { evaluateNext@ for (perm in permutations) { for (word in words) { val mapped = word.map { perm[it]!! }.toSet() if (!segmentsMapping.containsKey(mapped)) continue@evaluateNext } return perm } // It should never happen... return mapOf() } val mapping = getMapping() val num = expectedNumbers.joinToString("") { digit -> val segments = digit.map { mapping[it]!! }.toSet() val dig = segmentsMapping[segments]!! "$dig" } return num.toInt() } val lists = input.map { val (signals, digits) = it.split(" | ") signals.split(" ") to digits.split(" ") } val result = lists.sumOf { (input, output) -> bruteForceIt(input, output) } return result } fun main() { val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
3,531
AdventOfCode
Apache License 2.0
src/main/java/com/barneyb/aoc/aoc2022/day20/GrovePositioningSystem.kt
barneyb
553,291,150
false
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
package com.barneyb.aoc.aoc2022.day20 import com.barneyb.aoc.util.Slice import com.barneyb.aoc.util.Solver import com.barneyb.aoc.util.toLong import com.barneyb.aoc.util.toSlice fun main() { Solver.execute( ::parse, ::sumOfCoords_ptr, // 14888 ::fullDecryption_ptr, // 3760092545849 ) Solver.execute( ::parse, ::sumOfCoords_arr, // 14888 ::fullDecryption_arr, // 3760092545849 ) } internal const val DECRYPTION_KEY: Long = 811589153 internal const val ROUNDS = 10 internal fun parse(input: String) = input.toSlice() .trim() .lines() .map(Slice::toLong) internal fun sumOfCoords_arr( list: List<Long>, key: Long = 1, rounds: Int = 1 ): Long { val arr = ArrayList<Pair<Int, Long>>(list.size) arr.addAll(list.mapIndexed { i, n -> Pair(i, n * key) }) repeat(rounds) { _ -> for (n in 0 until arr.size) { val src = arr.indexOfFirst { (i, _) -> i == n } val it = arr.removeAt(src) val tgt = (src + it.second) % arr.size arr.add(tgt.toInt() + if (tgt < 0) arr.size else 0, it) } } val idx = arr.indexOfFirst { (_, n) -> n == 0L } return listOf(1000, 2000, 3000).sumOf { arr[(idx + it) % arr.size].second } } internal fun fullDecryption_arr(list: List<Long>) = sumOfCoords_arr(list, DECRYPTION_KEY, ROUNDS) private class Node( val value: Long, var _prev: Node? = null, var _next: Node? = null, ) { var prev get() = _prev!! set(value) { _prev = value } var next get() = _next!! set(value) { _next = value } override fun toString(): String { return "Node(value=$value)" } } internal fun sumOfCoords_ptr( list: List<Long>, key: Long = 1, rounds: Int = 1 ): Long { val nodes = Array(list.size) { Node(list[it] * key) } // println("Initial arrangement:") // println(nodes.map(Node::value).joinToString(", ")) nodes.first().prev = nodes.last() nodes.last().next = nodes.first() var zero: Node? = if (nodes[0].value == 0L) nodes[0] else null for (i in 1 until nodes.size) { if (nodes[i].value == 0L) zero = nodes[i] nodes[i].prev = nodes[i - 1] nodes[i - 1].next = nodes[i] } // println(draw(zero!!)) val countOfOthers = list.size - 1 val mid = list.size / 2 val negMid = -mid repeat(rounds) { for (n in nodes) { var offset = (n.value % countOfOthers).toInt() if (offset == 0) continue else if (offset < negMid) offset += countOfOthers else if (offset > mid) offset -= countOfOthers var curr = n if (offset < 0) repeat(list.size - offset + 1) { curr = curr.prev } else repeat(offset) { curr = curr.next } // pull it out of the ring n.prev.next = n.next n.next.prev = n.prev // put it back after curr n.prev = curr n.next = curr.next curr.next = n n.next.prev = n // println(draw(zero)) } // println("\nAfter ${it + 1} round${if (it == 0) "" else "s"} of mixing:") // println(draw(zero)) } var curr = zero!! var sum = 0L repeat(3) { repeat(1000) { curr = curr.next } sum += curr.value } return sum } @Suppress("unused") private fun draw(zero: Node) = generateSequence(zero) { if (it.next == zero) null else it.next }.map(Node::value) .joinToString(", ") internal fun fullDecryption_ptr(list: List<Long>) = sumOfCoords_ptr(list, DECRYPTION_KEY, ROUNDS)
0
Kotlin
0
0
8b5956164ff0be79a27f68ef09a9e7171cc91995
3,795
aoc-2022
MIT License
src/Day10.kt
valerakostin
574,165,845
false
{"Kotlin": 21086}
fun main() { fun isCheckPoint(cycle: Int): Boolean { return cycle == 20 || cycle == 60 || cycle == 100 || cycle == 140 || cycle == 180 || cycle == 220 } fun part1(input: List<String>): Int { var x = 1 var sum = 0 var cycles = 0 for (line in input) { if ("noop" == line) { cycles++ if (isCheckPoint(cycles)) sum += x * cycles } else if (line.startsWith("addx")) { val (_, num) = line.split(" ") val value = num.toInt() cycles++ if (isCheckPoint(cycles)) sum += x * cycles cycles++ if (isCheckPoint(cycles)) sum += x * cycles x += value } } return sum } fun part2(input: List<String>) { var x = 1 val values = mutableSetOf<Int>() var cycles = 0 for (line in input) { if ("noop" == line) { if (cycles%40 in x - 1..x + 1) values.add(cycles) cycles++ } else if (line.startsWith("addx")) { val (_, num) = line.split(" ") val value = num.toInt() if (cycles%40 in x - 1..x + 1) values.add(cycles) cycles++ if (cycles%40 in x - 1..x + 1) values.add(cycles) cycles++ x += value } } for (row in 0 until 6) { for (i in 0 until 40) { val symbol = if (values.contains(row * 40 + i)) '#' else ' ' print(symbol) } println() } } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) val input = readInput("Day10") println(part1(input)) // check(part2(testInput)) part2(input) }
0
Kotlin
0
0
e5f13dae0d2fa1aef14dc71c7ba7c898c1d1a5d1
2,034
AdventOfCode-2022
Apache License 2.0
2019/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2019/day06/day06.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.aoc2019.day06 import nl.sanderp.aoc.aoc2019.IO import java.util.* fun checksum(data: List<Pair<String, String>>): Int { var checksum = 0 val visited = mutableSetOf<String>() val queue = LinkedList<Pair<String, Int>>() queue.add("COM" to 0) while (queue.isNotEmpty()) { val (obj, level) = queue.pop() visited.add(obj) checksum += level data.neighboursOf(obj) .filterNot { visited.contains(it) } .forEach { queue.add(it to level + 1) } } return checksum } fun orbitalTransfers(data: List<Pair<String, String>>): Int { val start = "YOU" val end = "SAN" val distances = mutableMapOf(start to 0) val visited = mutableSetOf<String>() val queue = LinkedList<String>() queue.add(start) while (queue.isNotEmpty()) { val obj = queue.pop() visited.add(obj) data.neighboursOf(obj) .filterNot { visited.contains(it) } .forEach { neighbour -> val distance = distances[obj]!! + 1 distances.merge(neighbour, distance) { old, new -> if (new < old) new else old } queue.add(neighbour) } } return distances[end]!! - 2 } fun List<Pair<String, String>>.neighboursOf(obj: String): List<String> = this.filter { it.first == obj || it.second == obj } .map { if (it.first == obj) it.second else it.first } fun main() { val input = IO.readLines("day06.txt") { it.split(')') }.map { it[0] to it[1] } println("Part one: ${checksum(input)}") println("Part two: ${orbitalTransfers(input)}") }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
1,648
advent-of-code
MIT License
advent-of-code-2021/src/main/kotlin/Day10.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
//Day 10: Syntax Scoring //https://adventofcode.com/2021/day/10 import java.io.File fun main() { val lines = File("src/main/resources/Day10.txt").readLines() countSyntaxErrorScore(lines) countIncompleteScore(lines) } fun countSyntaxErrorScore(lines: List<String>) { val syntaxScore = lines.sumOf { line -> when (getInvalidChunk(line.toList())) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 }.toInt() } println(syntaxScore) } fun getInvalidChunk(chunks: List<Char>): Char? { val stack = mutableListOf<Char>() chunks.forEach { chunk -> when (chunk) { in listOf('{', '(', '[', '<') -> stack.add(chunk) ')' -> if (stack.lastOrNull() == '(') stack.removeLast() else return chunk ']' -> if (stack.lastOrNull() == '[') stack.removeLast() else return chunk '}' -> if (stack.lastOrNull() == '{') stack.removeLast() else return chunk '>' -> if (stack.lastOrNull() == '<') stack.removeLast() else return chunk } } return null } fun countIncompleteScore(lines: List<String>) { val scores = lines.filter { getInvalidChunk(it.toList()) == null }.map { getChunksToComplete(it).fold(0L) { acc, chunk -> (acc * 5) + when (chunk) { ')' -> 1 ']' -> 2 '}' -> 3 '>' -> 4 else -> 0 } } }.sorted() println(scores[scores.size / 2]) } fun getChunksToComplete(incompleteChunks: String): List<Char> { val chunks = mutableListOf<Char>() incompleteChunks.toList().forEach { chunk -> when (chunk) { in listOf('{', '(', '[', '<') -> chunks.add(chunk) in listOf('}', ')', ']', '>') -> chunks.removeLastOrNull() } } chunks.replaceAll { chunk -> when (chunk) { '(' -> ')' '[' -> ']' '{' -> '}' '<' -> '>' else -> chunk } } return chunks.reversed() }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
2,097
advent-of-code
Apache License 2.0
src/day14/Day14.kt
gr4cza
572,863,297
false
{"Kotlin": 93944}
package day14 import Direction.* import Edges import Position import readInput val sandStartPos = Position(500, 0) fun main() { fun parseLines(input: List<String>): List<RockLine> { return input.map { line -> RockLine(line.split(" -> ").map { coords -> val (x, y) = coords.split(",").map { it.toInt() } Position(x, y) }) } } fun findEdges(rockLines: List<RockLine>): Edges { val xValues = rockLines.map { rockLine -> rockLine.linePoints.map { it.x } }.flatten() val yValues = rockLines.map { rockLine -> rockLine.linePoints.map { it.y } }.flatten() return Edges( Position(xValues.min(), minOf(yValues.min(), 0)), Position(xValues.max(), yValues.max()), ) } fun getRange(start: Int, end: Int) = minOf(start, end)..maxOf(start, end) fun addLines(grid: OffsetGrid, rockLines: List<RockLine>) { rockLines.forEach { rockLine -> rockLine.linePoints.windowed(2).forEach { (start, end) -> if (start.x == end.x) { for (i in getRange(start.y, end.y)) { grid[Position(start.x, i)] = 1 } } else if (start.y == end.y) { for (i in getRange(start.x, end.x)) { grid[Position(i, start.y)] = 1 } } } } } fun addSand(grid: OffsetGrid): Int { var sandCount = 0 while (grid[sandStartPos] == 0) { try { var currentSandPos = sandStartPos var inMotion = true while (inMotion) { if (grid[currentSandPos.newPosition(D)] == 0) { currentSandPos = currentSandPos.newPosition(D) } else if (grid[currentSandPos.newPosition(D).newPosition(L)] == 0) { currentSandPos = currentSandPos.newPosition(D).newPosition(L) } else if (grid[currentSandPos.newPosition(D).newPosition(R)] == 0) { currentSandPos = currentSandPos.newPosition(D).newPosition(R) } else { grid[currentSandPos] = 2 inMotion = false } } sandCount++ } catch (e: IndexOutOfBoundsException) { break } } return sandCount } fun part1(input: List<String>): Int { val rockLines = parseLines(input) val grid = OffsetGrid(findEdges(rockLines)) addLines(grid, rockLines) return addSand(grid) } fun part2(input: List<String>): Int { val rockLines = parseLines(input) val edges = findEdges(rockLines) val newRockLines = rockLines.toMutableList() val newEndPosY = edges.endPos.y + 2 newRockLines.add( RockLine( listOf( Position(sandStartPos.x - newEndPosY, newEndPosY), Position(sandStartPos.x + newEndPosY, newEndPosY), ) ) ) val newEdges = findEdges(newRockLines) val grid = OffsetGrid(newEdges) addLines(grid, newRockLines) return addSand(grid) } // test if implementation meets criteria from the description, like: val testInput = readInput("day14/Day14_test") check(part1(testInput).also { println(it) } == 24) val input = readInput("day14/Day14") println(part1(input)) check(part2(testInput).also { println(it) } == 93) println(part2(input)) } class OffsetGrid( edges: Edges ) { private val offsetX: Int = edges.startPos.x private val offsetY: Int = edges.startPos.y private val grid: List<MutableList<Int>> init { grid = List(edges.endPos.y - edges.startPos.y + 1) { MutableList(edges.endPos.x - edges.startPos.x + 1) { 0 } } } override fun toString(): String { return grid.joinToString("\n") { line -> line.map { when (it) { 0 -> "." 1 -> "#" 2 -> "o" else -> " " } }.joinToString(",", prefix = "[", postfix = "]") } } operator fun get(position: Position): Int { return grid[position.y - offsetY][position.x - offsetX] } operator fun set(position: Position, value: Int) { grid[position.y - offsetY][position.x - offsetX] = value } } data class RockLine( val linePoints: List<Position> )
0
Kotlin
0
0
ceca4b99e562b4d8d3179c0a4b3856800fc6fe27
4,793
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Day18.kt
hughjdavey
159,955,618
false
null
package days class Day18 : Day(18) { override fun partOne(): Any { var parsed = Day18.parseArea(inputList) (1..10).forEach { parsed = Day18.doMinute(parsed) } return parsed.flatten().count { it.isTrees() } * parsed.flatten().count { it.isYard() } } override fun partTwo(): Any { println("// Day 18 Part 2 takes about 6 seconds...") var parsed = Day18.parseArea(inputList) val seen = mutableListOf(parsed) (1..1000000000).forEach { minute -> parsed = Day18.doMinute(parsed) val seenBefore = seen.find { prettyPrint(it) == prettyPrint(parsed) } if (seenBefore != null) { val patternLength = seen.size - seen.indexOfFirst { prettyPrint(it) == prettyPrint(seenBefore) } val remainingMinutes = 1000000000 - minute // now we have a pattern figure how many more iterations needed to reach the place in the pattern where we'd also be after 1000000000 val howManyMore = remainingMinutes % patternLength for (i in 0 until howManyMore) { parsed = Day18.doMinute(parsed) } return parsed.flatten().count { it.isTrees() } * parsed.flatten().count { it.isYard() } } else { seen.add(parsed) } } return parsed.flatten().count { it.isTrees() } * parsed.flatten().count { it.isYard() } } data class Acre(var type: Char, val index: Pair<Int, Int>) { fun isOpen() = type == OPEN fun isTrees() = type == TREES fun isYard() = type == YARD var next = type companion object { const val OPEN = '.' const val TREES = '|' const val YARD = '#' } } companion object { fun doMinute(area: Array<Array<Acre>>): Array<Array<Acre>> { val newArea = Array(area.size) { Array(area.first().size) { Acre('?', 0 to 0) } } area.flatten().forEach { acre -> val adjacent = getAdjacent(acre, area) val newType = when { acre.isOpen() -> if (adjacent.count { it.isTrees() } >= 3) Acre.TREES else acre.type acre.isTrees() -> if (adjacent.count { it.isYard() } >= 3) Acre.YARD else acre.type acre.isYard() -> if (adjacent.count { it.isYard() } >= 1 && adjacent.count { it.isTrees() } >= 1) Acre.YARD else Acre.OPEN else -> acre.type } newArea[acre.index.first][acre.index.second] = acre.copy(type = newType) } return newArea } fun parseArea(input: List<String>): Array<Array<Acre>> { val area = Array(input.size) { Array(input.first().length) { Acre('?', 0 to 0) } } for (y in 0 .. input.lastIndex) { for (x in 0 .. input[y].lastIndex) { area[x][y] = Acre(input[y][x], x to y) } } return area } fun prettyPrint(area: Array<Array<Acre>>): String { val s = StringBuilder() for (y in 0 .. area.lastIndex) { for (x in 0 .. area[y].lastIndex) { s.append(area[x][y].type) } s.append('\n') } return s.toString() } fun getAdjacent(acre: Acre, area: Array<Array<Acre>>): List<Acre> { return adjacentIndices(acre.index).mapNotNull { try { area[it.first][it.second] } catch (e: ArrayIndexOutOfBoundsException) { null } } } private fun adjacentIndices(index: Pair<Int, Int>): List<Pair<Int, Int>> { val (x, y) = index return listOf(x - 1 to y - 1, x to y - 1, x + 1 to y - 1, x - 1 to y, /* x to y */ x + 1 to y, x - 1 to y + 1, x to y + 1, x + 1 to y + 1) } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
4,029
aoc-2018
Creative Commons Zero v1.0 Universal
2022/kotlin/app/src/main/kotlin/doy08/Day08.kt
jghoman
726,228,039
false
{"Kotlin": 15309, "Rust": 14555, "Scala": 1804, "Shell": 737}
package doy08 fun part1(input:String): Int { val inputSplit = input .split("\n") .map { it -> it.map { it.digitToInt() } } println("numRows = ${inputSplit.size}") println("numCols = ${inputSplit[0].size}") val z= (1 until inputSplit[0].size - 1) .map{ i -> (1 until inputSplit.size - 1) .map { j -> Pair(i, j) }} .flatten() .map{ isVisible(inputSplit, it.first, it.second) } .count { it } val perimeterSize = (4 * inputSplit.size - 4 ) println("perimeterSize = ${perimeterSize}") return z + perimeterSize //(4 * (inputSplit.size - 1 )) } private fun isVisible( inputSplit: List<List<Int>>, i: Int, j: Int ): Boolean { val treeHeight = inputSplit[i][j] val width = inputSplit[0].size val visibleFromRight = inputSplit[i].subList(j + 1, width).all { it < treeHeight } val visibleFromLeft = inputSplit[i].subList(0, j).all { it < treeHeight } val visibleFromDown = (i + 1 until inputSplit.size) .asSequence() .map { inputSplit[it][j] } .toList() .all { it < treeHeight } val visibleFromUp = (0 until i) .asSequence() .map { inputSplit[it][j] } .toList() .all { it < treeHeight } return visibleFromDown || visibleFromUp || visibleFromLeft || visibleFromRight } fun part2(input:String): Int { val inputSplit = input .split("\n") .map { it -> it.map { it.digitToInt() } } val z= (1 until inputSplit[0].size - 1) .map{ i -> (1 until inputSplit.size - 1) .map { j -> Pair(i, j) }} .flatten() .map{ viewingScore(inputSplit, it.first, it.second) } .max() // Don't forget perimeter! return z } fun <T> List<T>.takeUntilInclusive(predicate: (T) -> Boolean): List<T> { val result = mutableListOf<T>() for (element in this) { result.add(element) if (predicate(element)) { break } } return result } fun viewingScore(inputSplit: List<List<Int>>, i: Int, j: Int): Int { val treeHeight = inputSplit[i][j] val width = inputSplit[0].size println("treeHeight = $treeHeight") val upScore = maxOf(1, (0 until i) .asSequence() .map { inputSplit[it][j] } .toList() .reversed() .takeUntilInclusive { it >= treeHeight } .size) val leftScore = maxOf(1, inputSplit[i] .subList(0, j) .reversed() .takeUntilInclusive { it >= treeHeight } .size) val rightScore = maxOf(1, inputSplit[i] .subList(j + 1, width) .takeUntilInclusive { it >= treeHeight } .size) //------- println("Hmmmmmmm: ${(i + 1 until inputSplit.size) .asSequence() .map { inputSplit[it][j] } .toList() .takeUntilInclusive { it >= treeHeight } }") val downScore = maxOf(1, (i + 1 until inputSplit.size) .asSequence() .map { inputSplit[it][j] } .toList() .takeUntilInclusive { it >= treeHeight } .size) val up = upScore val down = downScore val left = leftScore val right = rightScore println("up = $up (1), left = $left (1), right = $right (2), down = $down (2)") return up * down * left * right } fun main() { val realInput = util.readFileUsingGetResource("day-8-input.txt") val testInput = "30373\n" + "25512\n" + "65332\n" + "33549\n" + "35390" //val input = testInput val input = realInput //println("Part 1 result = ${part1(input)}" ) // 21 val inputSplit = input .split("\n") .map { it -> it.map { it.digitToInt() } } //val result = viewingScore(inputSplit, 1, 2) val result = part2(input) println("Result = ${result}") }
0
Kotlin
0
0
2eb856af5d696505742f7c77e6292bb83a6c126c
3,986
aoc
Apache License 2.0
src/day20/Code.kt
fcolasuonno
225,219,560
false
null
package day20 import isDebug import java.io.File import kotlin.math.abs fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val (paths, portals) = parse(input) println("Part 1 = ${part1(paths, portals)}") println("Part 2 = ${part2(paths, portals)}") } fun parse(input: List<String>) = input.withIndex().flatMap { (j, s) -> s.withIndex().mapNotNull { (i, c) -> if (c == '.') (i to j) else null } }.toSet().let { passages -> Pair(passages, input.withIndex().flatMap { (j, s) -> s.withIndex().mapNotNull { (i, c) -> if (c.isLetter()) ((i to j) to c) else null } }.toMap().let { portal -> portal.filterKeys { it.neighbours().any { it in passages } }.mapValues { (it.key.neighbours().take(2) + it.key + it.key.neighbours().drop(2)).mapNotNull { portal[it] } .joinToString("") } }) } fun part1(input: Set<Pair<Int, Int>>, portals: Map<Pair<Int, Int>, String>): Any? { val start = portals.filterValues { it == "AA" }.flatMap { it.key.neighbours() }.single { it in input } val end = portals.filterValues { it == "ZZ" }.flatMap { it.key.neighbours() }.single { it in input } val wormholePos = portals.entries.groupBy { it.value }.filter { it.value.size == 2 } .map { it.value.map { it.key.neighbours().single { it in input } } }.flatMap { (fromPos, toPos) -> listOf(fromPos to toPos, toPos to fromPos) }.toMap() val seen = mutableSetOf<Pair<Int, Int>>() val frontier = listOf(start).map { it to 0 } .toSortedSet(compareBy<Pair<Pair<Int, Int>, Int>> { it.second }.thenBy { it.first.first }.thenBy { it.first.second }) while (frontier.isNotEmpty()) { val pos = frontier.first() frontier.remove(pos) seen.add(pos.first) if (pos.first == end) { return pos.second } val next = pos.first.neighbours().filter { it in input } + wormholePos[pos.first] frontier.addAll(next.filterNotNull().filter { it !in seen }.map { it to (pos.second + 1) }) } return 0 } fun part2(input: Set<Pair<Int, Int>>, portals: Map<Pair<Int, Int>, String>): Any? { val start = portals.filterValues { it == "AA" }.flatMap { it.key.neighbours() }.single { it in input } val end = portals.filterValues { it == "ZZ" }.flatMap { it.key.neighbours() }.single { it in input } val wormholePos = portals.entries.groupBy { it.value }.filter { it.value.size == 2 } .map { it.value.map { it.key.neighbours().single { it in input } } }.flatMap { (fromPos, toPos) -> listOf(fromPos to toPos, toPos to fromPos) }.toMap() val innerWormholePos = wormholePos.filterKeys { !it.isOuter(input) } val outerWormholePos = wormholePos.filterKeys { it.isOuter(input) } val seen = mutableSetOf<Triple<Int, Int, Int>>() val frontier = listOf(start).map { Triple(it, 0, 0) } .toSortedSet(compareBy<Triple<Pair<Int, Int>, Int, Int>> { it.third }.thenBy { abs(it.second) }.thenBy { it.first.first }.thenBy { it.first.second }) while (frontier.isNotEmpty()) { val pos = frontier.first() frontier.remove(pos) seen.add(Triple(pos.first.first, pos.first.second, pos.second)) if (pos.first == end && pos.second == 0) { return pos.third } val next = pos.first.neighbours().filter { it in input }.map { Triple(it.first, it.second, pos.second) } + innerWormholePos[pos.first]?.let { Triple(it.first, it.second, pos.second + 1) } + outerWormholePos[pos.first]?.takeIf { pos.second != 0 }?.let { Triple( it.first, it.second, pos.second - 1 ) } frontier.addAll(next.filterNotNull().filter { it !in seen }.map { Triple( it.first to it.second, it.third, pos.third + 1 ) }) } return 0 } private fun Pair<Int, Int>.isOuter(input: Set<Pair<Int, Int>>) = first == 2 || second == 2 || first == input.map { it.first }.max() || second == input.map { it.second }.max() private fun Pair<Int, Int>.neighbours() = listOf( copy(first = first - 1), copy(second = second - 1), copy(first = first + 1), copy(second = second + 1) )
0
Kotlin
0
0
d1a5bfbbc85716d0a331792b59cdd75389cf379f
4,535
AOC2019
MIT License
src/day05/Day05.kt
tobihein
569,448,315
false
{"Kotlin": 58721}
package day05 import readInput import java.util.* class Day05 { fun part1(): String { val readInput = readInput("day05/input") return part1(readInput) } fun part2(): String { val readInput = readInput("day05/input") return part2(readInput) } fun part1(input: List<String>): String { val stacks = readStacks(input) val moves = readMoves(input) doMoves(stacks, moves) return getTops(stacks) } fun part2(input: List<String>): String { val stacks = readStacks(input) val moves = readMoves(input) doMovesPart2(stacks, moves) return getTops(stacks) } private fun readStacks(input: List<String>): Map<Int, Stack<String>> { val stackInput = input.takeWhile { it.contains("[") }.map { it.chunked(4) } val stacks = mutableMapOf<Int, Stack<String>>() stackInput.reversed().forEach { for ((idx, s) in it.withIndex()) { // it.forEachIndexed { idx, s -> // { if (s.isNotBlank()) { val stack = stacks.getOrDefault(idx, Stack()) stack.push(s.substring(1, 2)) stacks.put(idx, stack) } // } } } return stacks } private fun readMoves(input: List<String>): List<Triple<Int, Int, Int>> { return input.takeLastWhile { it != "" }.map { it.split(" ") } .map { Triple(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1) } } private fun doMoves(stacks: Map<Int, Stack<String>>, moves: List<Triple<Int, Int, Int>>) { moves.forEach { for (i in 0 until it.first) { stacks.get(it.third)?.push(stacks.get(it.second)?.pop()) } } } private fun doMovesPart2(stacks: Map<Int, Stack<String>>, moves: List<Triple<Int, Int, Int>>) { moves.forEach { val tempStack = Stack<String>() for (i in 0 until it.first) { tempStack.push(stacks.get(it.second)?.pop()) } while (tempStack.isNotEmpty()) { stacks.get(it.third)?.push(tempStack.pop()) } } } private fun getTops(stacks: Map<Int, Stack<String>>): String { return stacks.values.map { it.pop() }.joinToString("") } }
0
Kotlin
0
0
af8d851702e633eb8ff4020011f762156bfc136b
2,400
adventofcode-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/sorts/BubbleSorts.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <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.sorts import dev.shtanko.algorithms.extensions.swap /** * Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares * each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated * until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, * is named for the way smaller or larger elements "bubble" to the top of the list. Although the algorithm is simple, * it is too slow and impractical for most problems even when compared to insertion sort. It can be practical * if the input is usually in sorted order but may occasionally have some out-of-order elements nearly in position. * * Worst-case performance O(n^2) * Best-case performance O(n) * Average performance O(n^2) * Worst-case space complexity O(1) */ class BubbleSort : AbstractSortStrategy { override fun <T : Comparable<T>> perform(arr: Array<T>) { var exchanged: Boolean do { exchanged = false for (i in 1 until arr.size) { if (arr[i] < arr[i - 1]) { arr.swap(i, i - 1) exchanged = true } } } while (exchanged) } } class SimpleBubbleSort : AbstractSortStrategy { override fun <T : Comparable<T>> perform(arr: Array<T>) { for (i in 0 until arr.size - 1) { for (j in i + 1 until arr.size) { if (arr[i] > arr[j]) { arr.swap(i, j) } } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,263
kotlab
Apache License 2.0
src/test/kotlin/Day01.kt
christof-vollrath
317,635,262
false
null
import io.kotest.core.spec.style.DescribeSpec import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import java.lang.IllegalArgumentException /* --- Day 1: Report Repair --- See https://adventofcode.com/2020/day/1 */ fun findMatchingEntries(stars: List<Int>): Set<Int> { stars.forEach { star1 -> stars.forEach { star2 -> if (star1 + star2 == 2020) return setOf(star1, star2) } } throw IllegalArgumentException("No matching entries found") } fun find3MatchingEntries(stars: List<Int>): Set<Int> { stars.forEach { star1 -> stars.forEach { star2 -> if (star1 + star2 <= 2020) { stars.forEach { star3 -> if (star1 + star2 + star3 == 2020) return setOf(star1, star2, star3) } } } } throw IllegalArgumentException("No matching entries found") } fun parseStars(inputString: String): List<Int> = inputString.split("\n").map { it.toInt() } val exampleInput = """ 1721 979 366 299 675 1456 """.trimIndent() class Day01_ReadInput : FunSpec({ val stars = parseStars(exampleInput) test("should be parsed correctly") { stars.size shouldBe 6 stars[0] shouldBe 1721 } }) class Day01_FindMatchingEntries : DescribeSpec({ describe("find matching pair") { val matching = findMatchingEntries(parseStars(exampleInput)) it("should find matching entries") { matching shouldBe setOf(1721 ,299) } describe("find solution") { val solution = calculateSolution(matching) it("should have calculated solution") { solution shouldBe 514579 } } } }) fun calculateSolution(entries: Set<Int>) = entries.fold(1) { x, y -> x * y } class Day01_Part1: FunSpec({ val inputStrings = readResource("day01Input.txt")!! val solution = calculateSolution(findMatchingEntries(parseStars(inputStrings))) test("solution") { solution shouldBe 381699 } }) class Day01_Find3MatchingEntries : DescribeSpec({ describe("find matching pair") { val matching = find3MatchingEntries(parseStars(exampleInput)) it("should find matching entries") { matching shouldBe setOf(979, 366, 675) } describe("find solution") { val solution = calculateSolution(matching) it("should have calculated solution") { solution shouldBe 241861950 } } } }) class Day01_Part2: FunSpec({ val inputStrings = readResource("day01Input.txt")!! test("how big is the input") { parseStars(inputStrings).size shouldBe 200 } val solution = calculateSolution(find3MatchingEntries(parseStars(inputStrings))) test("solution") { solution shouldBe 111605670 } })
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
2,918
advent_of_code_2020
Apache License 2.0
src/Day04-2.kt
casslabath
573,177,204
false
{"Kotlin": 27085}
fun main() { operator fun IntRange.contains(other: IntRange): Boolean { if(this.first >= other.first && this.last <= other.last) { return true } return false } fun part1(input: List<String>): Int { var containedPairs = 0 input.map {line -> val pairs = line.split(",").map { it.split("-") } val firstRange = pairs[0][0].toInt()..pairs[0][1].toInt() val secondRange = pairs[1][0].toInt()..pairs[1][1].toInt() if(firstRange in secondRange || secondRange in firstRange) { containedPairs++ } } return containedPairs } fun part2(input: List<String>): Int { var containedPairs = 0 input.map {line -> val pairs = line.split(",").map { it.split("-") } val firstRange = pairs[0][0].toInt()..pairs[0][1].toInt() val secondRange = pairs[1][0].toInt()..pairs[1][1].toInt() if(firstRange.any() { it in secondRange}) { containedPairs++ } } return containedPairs } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f7305e45f41a6893b6e12c8d92db7607723425e
1,279
KotlinAdvent2022
Apache License 2.0
src/day14.kts
miedzinski
434,902,353
false
{"Kotlin": 22560, "Shell": 113}
data class Rule(val pair: Pair<Char, Char>, val insertion: Char) fun <K> MutableMap<K, Long>.increment(key: K, count: Long = 1) { set(key, getOrDefault(key, 0) + count) } val elements = mutableMapOf<Char, Long>() val pairs = readLine()!!.asSequence() .onEach { elements.increment(it) } .windowed(2) { (first, second) -> Pair(first, second) } .groupingBy { it } .eachCount() .mapValuesTo(mutableMapOf()) { (_, count) -> count.toLong() } readLine() val ruleRegex = "([A-Z])([A-Z]) -> ([A-Z])".toRegex() val rules = generateSequence(::readLine).map { line -> val (left, right, insertion) = ruleRegex.matchEntire(line)!!.destructured Rule(left.single() to right.single(), insertion.single()) }.toList() fun tick() { val toDelete = mutableSetOf<Pair<Char, Char>>() val toInsert = mutableMapOf<Pair<Char, Char>, Long>() rules.asSequence() .filter { it.pair in pairs } .forEach { val count = pairs[it.pair]!! toDelete.add(it.pair) toInsert.increment(Pair(it.pair.first, it.insertion), count) toInsert.increment(Pair(it.insertion, it.pair.second), count) elements.increment(it.insertion, count) } toDelete.forEach(pairs::remove) toInsert.forEach { pairs.increment(it.key, it.value) } } fun solve(steps: Int): Long { repeat(steps) { tick() } return elements.values.maxOf { it } - elements.values.minOf { it } } println("part1: ${solve(10)}") println("part2: ${solve(30)}")
0
Kotlin
0
0
6f32adaba058460f1a9bb6a866ff424912aece2e
1,525
aoc2021
The Unlicense
src/Day04.kt
petoS6
573,018,212
false
{"Kotlin": 14258}
fun main() { fun part1(input: List<String>): Int { return input.filter { it.doesContainEachOther() }.size } fun part2(input: List<String>): Int { return input.filter { it.hasOverlap() }.size } val testInput = readInput("Day04.txt") println(part1(testInput)) println(part2(testInput)) } private fun String.doesContainEachOther(): Boolean { val commaSplit = split(",") val first = commaSplit[0].split("-").let { it[0].toInt() .. it[1].toInt() } val second = commaSplit[1].split("-").let { it[0].toInt() .. it[1].toInt() } return (first.first in second && first.last in second) || (second.first in first && second.last in first) } private fun String.hasOverlap(): Boolean { val commaSplit = split(",") val first = commaSplit[0].split("-").let { it[0].toInt() .. it[1].toInt() } val second = commaSplit[1].split("-").let { it[0].toInt() .. it[1].toInt() } return first.first in second || first.last in second || second.first in first || second.last in first }
0
Kotlin
0
0
40bd094155e664a89892400aaf8ba8505fdd1986
1,022
kotlin-aoc-2022
Apache License 2.0
src/Day07.kt
mnajborowski
573,619,699
false
{"Kotlin": 7975}
fun main() { fun prepareTree(input: List<String>): Map<String, Int> { var cwd = "" return buildMap { (input + "\$ cd ..").forEach { command -> when { command.any { it.isDigit() } -> putAll(mapOf(cwd to getOrElse(cwd) { 0 } + command.filter { it.isDigit() }.toInt())) command.matches("\\$ cd [a-z]+".toRegex()) -> cwd += "/" + command.split(" ").last() command.matches("\\$ cd ..".toRegex()) -> { val pwd = cwd.substring(0, cwd.indexOfLast { it == '/' }) putAll(mapOf(pwd to getOrElse(pwd) { 0 } + getOrElse(cwd) { 0 })) cwd = pwd } } } while (cwd != "") { val pwd = cwd.substring(0, cwd.indexOfLast { it == '/' }) putAll(mapOf(pwd to getOrElse(pwd) { 0 } + getOrElse(cwd) { 0 })) cwd = pwd } } } fun part1(input: List<String>): Int = prepareTree(input).values.filter { it <= 100000 }.sum() fun part2(input: List<String>): Int { val tree = prepareTree(input) return tree.values.sorted().first { 70000000 - tree[""]!! + it >= 30000000 } } val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e54c13bc5229c6cb1504db7e3be29fc9b9c4d386
1,401
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/day13/Day13.kt
W3D3
572,447,546
false
{"Kotlin": 159335}
package day13 import com.beust.klaxon.JsonArray import com.beust.klaxon.Parser import common.InputRepo import common.readSessionCookie import common.solve import util.split fun main(args: Array<String>) { val day = 13 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay13Part1, ::solveDay13Part2) } fun solveDay13Part1(input: List<String>): Int { val split = input.split({ it.isEmpty() }) val pairs = split.map { it.toList() } .map { parseBrackets(it[0]) to parseBrackets(it[1]) } var index = 1 var sum = 0 for ((left, right) in pairs) { val compareArrays = compareArrays(left, right) if (compareArrays == true) { sum += index } index++ } return sum } fun solveDay13Part2(input: List<String>): Int { val packetListInput: MutableList<JsonArray<Any>> = input.filter { it.isNotBlank() } .map { parseBrackets(it) } .toMutableList() val dividerPacket1: JsonArray<Any> = JsonArray(JsonArray(listOf(2))) val dividerPacket2: JsonArray<Any> = JsonArray(JsonArray(listOf(6))) packetListInput.add(dividerPacket1) packetListInput.add(dividerPacket2) val sortedArrays = packetListInput.sortedWith { o1, o2 -> when (compareArrays(o1, o2)) { true -> { -1 } false -> { 1 } else -> { 0 } } } return (sortedArrays.indexOf(dividerPacket1) + 1) * (sortedArrays.indexOf(dividerPacket2) + 1) } private fun compareArrays( left: JsonArray<*>, right: JsonArray<*> ): Boolean? { var i = 0 while (true) { var comparison: Boolean? = null if (i >= left.size && i < right.size) { // left ran out of values first return true } else if (i < left.size && i >= right.size) { // right ran out of values first return false } else if (i >= left.size) { // no decision return null } val leftValue = left[i] val rightValue = right[i] when { leftValue is Int && rightValue is Int -> { comparison = compare(leftValue, rightValue) } leftValue is JsonArray<*> && rightValue is JsonArray<*> -> { comparison = compareArrays(leftValue, rightValue) } leftValue is Int && rightValue is JsonArray<*> -> { comparison = compareArrays(JsonArray(listOf(leftValue)), rightValue) } leftValue is JsonArray<*> && rightValue is Int -> { comparison = compareArrays(leftValue, JsonArray(listOf(rightValue))) } } if (comparison != null) { println("Compare $leftValue vs $rightValue: $comparison") return comparison } i++ } } fun compare(left: Int, right: Int): Boolean? { return if (left < right) true else if (left > right) false else null } fun parseBrackets(s: String): JsonArray<Any> { val parser: Parser = Parser.default() val stringBuilder: StringBuilder = StringBuilder(s) @Suppress("UNCHECKED_CAST") return parser.parse(stringBuilder) as JsonArray<Any> }
0
Kotlin
0
0
34437876bf5c391aa064e42f5c984c7014a9f46d
3,362
AdventOfCode2022
Apache License 2.0
kotlin/2020/round-1a/pascal-walk/src/main/kotlin/Solution.kt
ShreckYe
345,946,821
false
null
import java.util.* fun main() { val T = readLine()!!.toInt() repeat(T) { t -> val N = readLine()!!.toInt() println("Case #${t + 1}:\n${case(N).joinToString("\n")}}") } } data class Position(val r: Int, val k: Int) { fun isValid() = r >= 0 && k >= 0 && k <= r } fun case(N: Int): List<Position> { val cache = IntArray(CAPACITY) for (r in 0 until MAX_R) for (k in 0..r) cache[index(r, k)] = cache.getOrElse(index(r - 1, k - 1)) { 0 } + cache.getOrElse(index(r - 1, k)) { 0 } fun value(r: Int, k: Int): Int { val index = index(r, k) return if (index < CAPACITY) cache[index] else value(r - 1, k - 1) + value(r - 1, k) } fun value(position: Position) = value(position.r, position.k) fun allWalksFrom( fromWalk: Sequence<Position>, fromCurrent: Position, walked: BitSet ): Sequence<Sequence<Position>> { println(fromCurrent) val (ri, ki) = fromCurrent return sequenceOf( Position(ri - 1, ki - 1), Position(ri - 1, ki), Position(ri, ki - 1), Position(ri, ki + 1), Position(ri + 1, ki), Position(ri + 1, ki + 1) ) .filter { it.isValid() && !walked[index(it)] } .flatMap {newPosition -> allWalksFrom(fromWalk + newPosition, newPosition, walked.run { val newWalked = clone() as BitSet newWalked[index(newPosition)] = true newWalked }).map { fromWalk + newPosition + it } } } val allWalks = allWalksFrom(emptySequence(), Position(0, 0), BitSet(CAPACITY)) return allWalks.first { it.sumBy(::value) == N }.toList() } const val MAX_R = 30 val CAPACITY = index(MAX_R, 0) fun index(position: Position): Int = index(position.r, position.k) fun index(r: Int, k: Int): Int = r * (r + 1) / 2 + k
0
Kotlin
1
1
743540a46ec157a6f2ddb4de806a69e5126f10ad
1,911
google-code-jam
MIT License
src/day23/Day23.kt
felldo
572,233,925
false
{"Kotlin": 86889}
package day23 import readInput private const val DAY_ID = "23" private enum class Direction(val dx: Int, val dy: Int) { N(-1, 0), S(1, 0), W(0, -1), E(0, 1), NW(-1, -1), NE(-1, 1), SW(1, -1), SE(1, 1) } private data class Position(val row: Int, val col: Int) { fun next(d: Direction): Position = Position(row + d.dx, col + d.dy) } private sealed class MoveProposal { object Bad : MoveProposal() data class Good(val source: Position) : MoveProposal() } private data class SimulationResult(val grid: Set<Position>, val rounds: Int) fun main() { fun parseInput(input: List<String>): MutableSet<Position> = input.foldIndexed(sortedSetOf(compareBy({ it.row }, { it.col }))) { row, acc, line -> line.forEachIndexed { col, c -> if (c == '#') { acc += Position(row, col) } } acc } fun runSimulation(input: List<String>, maxRounds: Int = Int.MAX_VALUE): SimulationResult { val grid = parseInput(input) fun hasNoElvesAround(curr: Position, vararg ds: Direction): Boolean { check(ds.isNotEmpty()) return ds.none { d -> val next = curr.next(d) next in grid } } fun canMove(curr: Position, d: Direction): Boolean = when (d) { Direction.N -> hasNoElvesAround(curr, Direction.N, Direction.NE, Direction.NW) Direction.S -> hasNoElvesAround(curr, Direction.S, Direction.SE, Direction.SW) Direction.W -> hasNoElvesAround(curr, Direction.W, Direction.NW, Direction.SW) Direction.E -> hasNoElvesAround(curr, Direction.E, Direction.NE, Direction.SE) else -> false } // 4 directions for an elf to propose moving to val directions = listOf(Direction.N, Direction.S, Direction.W, Direction.E) var offset = 0 var rounds = 1 while(rounds <= maxRounds) { // next -> curr val proposals = mutableMapOf<Position, MoveProposal>() // 1st half of each round: each Elf considers the eight positions adjacent to himself for (curr in grid) { // 8 adjacent positions to (row, col) val ok = hasNoElvesAround(curr, *Direction.values()) if (ok) { continue } // propose moving one step in the first valid direction for (i in 0 until 4) { // choose direction val d = directions[(i + offset) % 4] val canMove = canMove(curr, d) if (canMove) { val next = curr.next(d) proposals[next] = if (next !in proposals) MoveProposal.Good(curr) else MoveProposal.Bad break } } } // the first round where no Elf moves; no need to continue the simulation if (proposals.isEmpty()) { break } // 2nd half of the round proposals.asSequence() .filter { (_, proposal) -> proposal is MoveProposal.Good } .forEach { (next, proposal) -> val curr = (proposal as MoveProposal.Good).source grid -= curr grid += next } // end of the round offset++ offset %= 4 rounds++ } return SimulationResult(grid, rounds) } fun part1(input: List<String>): Int { val rounds = 10 val (grid, _) = runSimulation(input, rounds) // the edges of the smallest rectangle that contains every Elf var minRow = Int.MAX_VALUE var maxRow = Int.MIN_VALUE var minCol = Int.MAX_VALUE var maxCol = Int.MIN_VALUE grid.forEach { minRow = minOf(minRow, it.row) maxRow = maxOf(maxRow, it.row) minCol = minOf(minCol, it.col) maxCol = maxOf(maxCol, it.col) } // count the number of empty ground tiles return (maxRow - minRow + 1) * (maxCol - minCol + 1) - grid.size } fun part2(input: List<String>): Int { val (_, rounds) = runSimulation(input) return rounds } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 110) check(part2(testInput) == 20) val input = readInput("day${DAY_ID}/Day${DAY_ID}") println(part1(input)) // answer = 3874 println(part2(input)) // answer = 948 }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
4,774
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
nic-dgl-204-fall-2022
552,171,003
false
{"Kotlin": 6125}
fun main() { fun remove(arr: IntArray, index: Int): IntArray { if (index < 0 || index >= arr.size) { return arr } val result = arr.toMutableList() result.removeAt(index) return result.toIntArray() } fun getSurfaceArea(l: Int, w: Int, h: Int): Int = 2 * (l * w) + 2 * (w * h) + 2 * (h * l) fun getExtraSlack(l: Int, w: Int, h: Int): Int = minOf(l * w, w * h, h * l) // Part 1 fun part1(input: List<String>): Int { val measurements = input .map { it.split('x') } .map { it.map { it.toInt() }} var totalPaper = 0 for (i in measurements.indices) { val (length, width, height) = Triple(measurements[i][0], measurements[i][1], measurements[i][2]) val paperRequired = getSurfaceArea(length, width, height) val slackRequired = getExtraSlack(length, width, height) totalPaper += (paperRequired + slackRequired) } return totalPaper } fun getSmallestPerimeter(l: Int, w: Int, h: Int): Int { val measurementSet = intArrayOf(l, w, h) val indexOfMax = measurementSet.indexOf(maxOf(l, w, h)) val measurementPair = remove(measurementSet, indexOfMax) return measurementPair[0] + measurementPair[0] + measurementPair[1] + measurementPair[1] } fun getVolumeCubed(l: Int, w: Int, h: Int): Int { return l*w*h } fun part2(input: List<String>): Int { val measurements = input .map { it.split('x') } .map { it.map { it.toInt() }} var totalRibbon: Int = 0 for (i in measurements.indices) { val perimeter = getSmallestPerimeter(measurements[i][0], measurements[i][1], measurements[i][2]) val volume = getVolumeCubed(measurements[i][0], measurements[i][1], measurements[i][2]) totalRibbon += perimeter + volume } return totalRibbon } val input = readInput("input") println("Part 1 Paper required: " + part1(input)) println("Part 2 Ribbon required: " + part2(input)) }
1
Kotlin
0
0
9abea167f1f43668eb7d4ddb445a45f501d4c4e1
2,164
redjinator-aoc-1
Apache License 2.0
src/main/kotlin/io/github/aarjavp/aoc/day10/Day10.kt
AarjavP
433,672,017
false
{"Kotlin": 73104}
package io.github.aarjavp.aoc.day10 import io.github.aarjavp.aoc.readFromClasspath class Day10 { enum class Brackets(val openingChar: Char, val closingChar: Char, val syntaxScore: Int, val autocompleteScore: Int) { ROUND('(', ')', 3, 1), SQUARE('[', ']', 57, 2), CURLY('{', '}', 1197, 3), ANGLE('<', '>', 25137, 4), ; companion object { val values = Brackets.values().asList() fun of(char: Char): Brackets = values.first { it.openingChar == char || it.closingChar == char } } } fun getIllegalType(line: String): Brackets? { val stack = ArrayDeque<Brackets>() for (char in line) { val type = Brackets.of(char) if (char == type.openingChar) { stack.addLast(type) } else { val actual = stack.removeLast() if (actual != type) return type } } return null } fun complete(line: String): List<Brackets> { val stack = ArrayDeque<Brackets>() for (char in line) { val type = Brackets.of(char) if (char == type.openingChar) { stack.addLast(type) } else { val actual = stack.removeLast() if (actual != type) error("unexpected") } } return stack.reversed() } fun score(completion: List<Brackets>): Long { return completion.fold(0L) { score, current -> score * 5 + current.autocompleteScore } } fun part1(lines: Sequence<String>): Int { return lines.mapNotNull { getIllegalType(it) }.sumOf { it.syntaxScore } } fun part2(lines: Sequence<String>): Long { val scores = lines.filter { getIllegalType(it) == null } .map { score(complete(it)) }.toMutableList().apply { sort() } check(scores.size % 2 == 1) return scores[scores.size/2] } } fun main() { val solution = Day10() readFromClasspath("Day10.txt").useLines { lines -> val part1 = solution.part1(lines) println(part1) } readFromClasspath("Day10.txt").useLines { lines -> val part2 = solution.part2(lines) println(part2) } }
0
Kotlin
0
0
3f5908fa4991f9b21bb7e3428a359b218fad2a35
2,279
advent-of-code-2021
MIT License
src/day15/a/day15a.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day15.a import readInputLines import shouldBe import util.IntRange import util.IntRangeSet import util.IntVector import vec2 import java.util.regex.Pattern import kotlin.math.abs typealias Input = ArrayList<Pair<IntVector, IntVector>> fun main() { val input = read() val row = 2000000 val e = IntRangeSet() for (p in input) { val l = distance(p.first, p.second) rangeAtRow(p.first, l, row)?.let { e.add(it) } } // beacons in that row and detection range are not to be counted val b = input.map { it.second }.filter { it[1] == row }.toSet().filter { e.contains(it[0]) }.size // size of detected range val n = e.sumOf { it.size } shouldBe(4907780, n-b) } fun distance(a: IntVector, b: IntVector): Int { return abs(a[0] - b[0]) + abs(a[1]-b[1]) } fun rangeAtRow(sensor: IntVector, dist: Int, y: Int): IntRange? { val w = 1 + 2*(dist - abs(sensor[1] - y)) if (w <= 0) return null return IntRange(sensor[0]-w/2, sensor[0]+w/2) } fun read(): Input { val g = Input() readInputLines(15).forEach { line -> val i = line.split(Pattern.compile("[^0-9-]+")).filter { it.isNotBlank() }.map { it.toInt() } val s = vec2(i[0], i[1]) val b = vec2(i[2], i[3]) g.add(Pair(s,b)) } return g }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
1,305
advent-of-code-2022
Apache License 2.0
src/main/kotlin/fr/chezbazar/aoc21/day5/Day5.kt
chezbazar
728,404,822
false
{"Kotlin": 54427}
package fr.chezbazar.aoc21.day5 import fr.chezbazar.aoc21.Point import fr.chezbazar.aoc21.computeFrom const val arraySize = 1000 fun main() { val ranges = mutableListOf<Pair<Point, Point>>() computeFrom("day5/input.txt") {line -> val (p1, p2) = line.split(" -> ") ranges.add(p1.toPoint() to p2.toPoint()) } println(intersectionsStraight(arraySize, ranges)) println(intersections(arraySize, ranges)) } fun intersectionsStraight(arraySize: Int, ranges: List<Pair<Point, Point>>): Int { val grid = List(arraySize) { MutableList(arraySize) { 0 } } ranges.forEach { (p1, p2) -> p1.straightRangeTo(p2).forEach { (x,y) -> grid[x][y] += 1 } } grid.forEach { println(it) } return grid.sumOf { list -> list.count { it > 1 } } } fun intersections(arraySize: Int, ranges: List<Pair<Point, Point>>): Int { val grid = List(arraySize) { MutableList(arraySize) { 0 } } ranges.forEach { (p1, p2) -> p1.rangeTo(p2).forEach { (x,y) -> grid[x][y] += 1 } } grid.forEach { println(it) } return grid.sumOf { list -> list.count { it > 1 } } } fun String.toPoint() = this.split(",").map { it.toInt() }.let { (x, y) -> Point(x,y) }
0
Kotlin
0
0
223f19d3345ed7283f4e2671bda8ac094341061a
1,227
adventofcode
MIT License
src/main/kotlin/dev/tasso/adventofcode/_2015/day03/Day03.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2015.day03 import dev.tasso.adventofcode.Solution class Day02 : Solution<Int> { override fun part1(input: List<String>): Int = input.first() .fold(listOf(Pair(0,0))) { visitedHouses, direction -> visitedHouses.plus( when(direction) { '^' -> Pair(visitedHouses.last().first, visitedHouses.last().second + 1) 'v' -> Pair(visitedHouses.last().first, visitedHouses.last().second - 1) '>' -> Pair(visitedHouses.last().first + 1, visitedHouses.last().second) '<' -> Pair(visitedHouses.last().first - 1, visitedHouses.last().second) else -> throw IllegalArgumentException("Unexpected move encountered ($direction)") } ) } .toSet() .count() override fun part2(input: List<String>): Int = input.first() .withIndex() .partition { it.index % 2 == 0 } .toList() .asSequence() .map { it.map{ indexed -> indexed.value} } .map{ it.fold(listOf(Pair(0,0))) { visitedHouses, direction -> visitedHouses.plus( when(direction) { '^' -> Pair(visitedHouses.last().first, visitedHouses.last().second + 1) 'v' -> Pair(visitedHouses.last().first, visitedHouses.last().second - 1) '>' -> Pair(visitedHouses.last().first + 1, visitedHouses.last().second) '<' -> Pair(visitedHouses.last().first - 1, visitedHouses.last().second) else -> throw IllegalArgumentException("Unexpected move encountered ($direction)") } ) } } .flatten() .toSet() .count() }
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
2,035
advent-of-code
MIT License
lib/src/main/kotlin/com/bloidonia/advent/day22/Day22.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day22 import com.bloidonia.advent.readList data class Cube(val on: Boolean, val x: IntRange, val y: IntRange, val z: IntRange) fun String.toCube() = this.split(" ", limit = 2).let { (type, ranges) -> ranges.split(",", limit = 3).let { (x, y, z) -> val xs = x.split("=", limit = 2).last().split("\\.\\.".toPattern(), limit = 2) val ys = y.split("=", limit = 2).last().split("\\.\\.".toPattern(), limit = 2) val zs = z.split("=", limit = 2).last().split("\\.\\.".toPattern(), limit = 2) Cube(type == "on", xs[0].toInt()..xs[1].toInt(), ys[0].toInt()..ys[1].toInt(), zs[0].toInt()..zs[1].toInt()) } } class Space(private val cubes: List<Cube>) { fun isOn(x: Int, y: Int, z: Int): Boolean = cubes.fold(false) { isOn, cube -> if (cube.x.contains(x) && cube.y.contains(y) && cube.z.contains(z)) { cube.on } else { isOn } } } fun main() { val cubes = Space(readList("/day22input.txt") { it.toCube() }) val part1 = (-50..50).flatMap { x -> (-50..50).flatMap { y -> (-50..50).map { z -> cubes.isOn(x, y, z) } } }.count { it } println(part1) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
1,183
advent-of-kotlin-2021
MIT License
src/main/kotlin/com/groundsfam/advent/y2022/d02/Day02.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2022.d02 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines fun scorePartOne(opponentChoice: String, playerChoice: String): Int { val opponentN = when (opponentChoice) { "A" -> 1 // rock "B" -> 2 // paper "C" -> 3 // scissors else -> throw RuntimeException("Invalid opponent choice: $opponentChoice") } val playerN = when (playerChoice) { "X" -> 1 // rock "Y" -> 2 // paper "Z" -> 3 // scissors else -> throw RuntimeException("Invalid player choice: $playerChoice") } val winLoseScore = when ((playerN - opponentN + 3) % 3) { 0 -> 3 // draw 1 -> 6 // win 2 -> 0 // lose else -> throw RuntimeException("Impossible error reached!") } return playerN + winLoseScore } fun scorePartTwo(opponentChoice: String, result: String): Int { val opponentN = when (opponentChoice) { "A" -> 1 // rock "B" -> 2 // paper "C" -> 3 // scissors else -> throw RuntimeException("Invalid opponent choice: $opponentChoice") } val (resultN, playerN) = when (result) { "X" -> 0 to (opponentN + 1) % 3 + 1 // need to lose, choose opponentN + 2 mod 3 "Y" -> 3 to opponentN // need to tie, choose opponentN "Z" -> 6 to opponentN % 3 + 1 // need to win, choose opponentN + 1 mod 3 else -> throw RuntimeException("Invalid result: $result") } return resultN + playerN } fun main() = timed { val rounds: List<Pair<String, String>> = (DATAPATH / "2022/day02.txt").useLines { lines -> lines.toList().map { line -> val (a, b) = line.split(" ") a to b } } rounds.sumOf { (opponent, player) -> scorePartOne(opponent, player) } .also { println("Total part one = $it") } rounds.sumOf { (opponent, result) -> scorePartTwo(opponent, result) } .also { println("Total part two = $it")} }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,076
advent-of-code
MIT License
src/Day05.kt
cnietoc
572,880,374
false
{"Kotlin": 15990}
fun main() { fun createCratesStack(inputIterator: Iterator<String>): CratesStack { var line: String = inputIterator.next() val cratesRaw: ArrayDeque<String> = ArrayDeque() while (line.isNotBlank()) { cratesRaw.addFirst(line) line = inputIterator.next() } val lastCrateLine = cratesRaw.removeFirst() val cratesNumber = lastCrateLine.split(" ").filterNot { it.isBlank() } val cratesStack = CratesStack(cratesNumber.size) for (cratesLine in cratesRaw) { for (stackNumber in cratesNumber) { val crate = cratesLine.getOrNull(lastCrateLine.indexOf(stackNumber)) if (crate != null && crate.isLetter()) { cratesStack.add(stackNumber.toInt(), crate) } } } return cratesStack } fun part1(input: List<String>): String { val inputIterator = input.iterator() val cratesStack = createCratesStack(inputIterator) for (movement in inputIterator) { val movementSplinted = movement.split(" ").mapNotNull { it.toIntOrNull() } cratesStack.move(movementSplinted[0], movementSplinted[1], movementSplinted[2]) } return cratesStack.getTopCrates().concatToString() } fun part2(input: List<String>): String { val inputIterator = input.iterator() val cratesStack = createCratesStack(inputIterator) for (movement in inputIterator) { val movementSplinted = movement.split(" ").mapNotNull { it.toIntOrNull() } cratesStack.moveOnPack(movementSplinted[0], movementSplinted[1], movementSplinted[2]) } return cratesStack.getTopCrates().concatToString() } val testInput = readInput("Day05_test") val input = readInput("Day05") check(part1(testInput) == "CMZ") println(part1(input)) check(part2(testInput) == "MCD") println(part2(input)) } class CratesStack(cratesStackNumber: Int) { fun add(stackNumber: Int, crate: Char) { stacks[stackNumber - 1].addLast(crate) } private val stacks = ArrayList<ArrayDeque<Char>>(cratesStackNumber) init { for (i in 0 until cratesStackNumber) { stacks.add(ArrayDeque()) } } override fun toString(): String { return "CratesStack(stacks=$stacks)" } fun move(crates: Int, fromStack: Int, toStack: Int) { repeat(crates) { val crateOnMovement = stacks[fromStack - 1].removeLast() stacks[toStack - 1].addLast(crateOnMovement) } } fun moveOnPack(crates: Int, fromStack: Int, toStack: Int) { val cratesOnMovement = ArrayDeque<Char>() repeat(crates) { cratesOnMovement.add(stacks[fromStack - 1].removeLast()) } repeat(crates) { stacks[toStack - 1].addLast(cratesOnMovement.removeLast()) } } fun getTopCrates(): CharArray = stacks.map { it.last() }.toCharArray() }
0
Kotlin
0
0
bbd8e81751b96b37d9fe48a54e5f4b3a0bab5da3
3,042
aoc-2022
Apache License 2.0
src/main/aoc2020/Day18.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2020 import java.lang.Integer.max class Day18(input: List<String>) { private val problems = input .map { line -> line.mapNotNull { ch -> ch.takeUnless { it == ' ' } } } .map { parseInput(it) } sealed class Expression { data class Operator(private val op: Char) : Expression() { // *, + fun calculate(lValue: Expression, rValue: Expression): Long { lValue as Literal; rValue as Literal return when (op) { '+' -> lValue.value + rValue.value '*' -> lValue.value * rValue.value else -> error("unknown operator") } } } data class Literal(val value: Long) : Expression() // numbers data class Complex(val list: MutableList<Expression>) : Expression() // The root problem / inside a parenthesis } private fun parseInput(problem: List<Char>): Expression { // List of complex expressions, where the first entry is the root expression and // the rest each yet unfinished parenthesis val expression = mutableListOf(Expression.Complex(mutableListOf())) for (token in problem) { when (token) { '(' -> { // Start a new complex expression expression.add(Expression.Complex(mutableListOf())) } ')' -> { // Finalize the latest complex expression val finishedExpression = expression.removeLast() expression.last().list.add(finishedExpression) } else -> { // Add the operator or literal to the current expression val toAdd = if (token in listOf('+', '*')) { Expression.Operator(token) } else { Expression.Literal(token.toString().toLong()) } expression.last().list.add(toAdd) } } } return expression.first() } /** * Calculate the given expression. Complex expressions is reduced to a literal expression * while all other expressions are returned back immediately. */ private fun calculate(expression: Expression, indexOfNextToCalculate: (Expression.Complex) -> Int): Expression { if (expression !is Expression.Complex) { return expression } // calculate all parenthesis first expression.list.forEachIndexed { index, expr -> expression.list[index] = calculate(expr, indexOfNextToCalculate) } // Reduce the complex expression one operator at a time until there is only one literal remaining. while (expression.list.size > 1) { calculateAtIndex(indexOfNextToCalculate(expression), expression) } return expression.list.first() } /** * Calculates the result of the two literals and the in between operator at the given position in the given * expression. The literals and operator is removed and replaced in the given expression. */ private fun calculateAtIndex(index: Int, expression: Expression.Complex) { val operator = expression.list[index + 1] as Expression.Operator val res = operator.calculate(expression.list[index], expression.list[index + 2]) expression.list.removeAt(index) expression.list.removeAt(index) expression.list[index] = Expression.Literal(res) } /** * As long as there are any pluses left calculate those first, otherwise calculate the left most pair */ private fun plusFirstStrategy(expression: Expression.Complex): Int { return max(expression.list.indexOf(Expression.Operator('+')) - 1, 0) } private fun solve(strategy: (Expression.Complex) -> Int): Long { return problems.map { calculate(it, strategy) }.sumOf { (it as Expression.Literal).value } } fun solvePart1(): Long { return solve { 0 } // always choose the leftmost pair to calculate first } fun solvePart2(): Long { return solve(this::plusFirstStrategy) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
4,165
aoc
MIT License
src/main/kotlin/com/colinodell/advent2022/Day22.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 import kotlin.math.sqrt class Day22(input: List<String>) { private val grid = input.dropLast(2).toGrid().filter { it.value != ' ' }.toMutableMap() private val pathToFollow = input.last().split("(?<=[A-Z])|(?=[A-Z])".toRegex()) private val startingPosition = grid.minOf { it.key.y }.let { y -> Vector2(grid.filter { it.key.y == y }.minOf { it.key.x }, y) } private val faceSize = sqrt((grid.count() / 6).toDouble()).toInt() fun solvePart1() = solve(::wrapNaive) fun solvePart2() = solve(::wrapCube) private data class State(val pos: Vector2, val dir: Direction) { fun password() = (1000 * (pos.y + 1)) + (4 * (pos.x + 1)) + when (dir) { Direction.RIGHT -> 0 Direction.DOWN -> 1 Direction.LEFT -> 2 Direction.UP -> 3 } } private fun solve(wrap: (State) -> State): Int { var state = State(startingPosition, Direction.RIGHT) pathToFollow.forEach { step -> state = when (step) { "R" -> State(state.pos, state.dir.turnRight()) "L" -> State(state.pos, state.dir.turnLeft()) else -> move(step.toInt(), state, wrap) } } return state.password() } private fun move(distance: Int, state: State, wrap: (State) -> State): State { var state = state for (i in 1..distance) { var nextState = State(state.pos + state.dir.vector(), state.dir) var peek = grid[nextState.pos] // Did we hit the edge? if (peek == null) { nextState = wrap(state) peek = grid[nextState.pos] } if (peek == '#') { return state } state = nextState } return state } private fun wrapNaive(state: State): State { val newPosition = when (state.dir) { Direction.RIGHT -> Vector2(grid.filter { it.key.y == state.pos.y }.minOf { it.key.x }, state.pos.y) Direction.LEFT -> Vector2(grid.filter { it.key.y == state.pos.y }.maxOf { it.key.x }, state.pos.y) Direction.DOWN -> Vector2(state.pos.x, grid.filter { it.key.x == state.pos.x }.minOf { it.key.y }) Direction.UP -> Vector2(state.pos.x, grid.filter { it.key.x == state.pos.x }.maxOf { it.key.y }) } return State(newPosition, state.dir) } private fun wrapCube(state: State): State { val curFace = state.pos / faceSize val nextFace = faces[curFace]!![state.dir]!! var nextRelativePos = (state.pos + state.dir.vector()).negativeSafeModulo(faceSize) var newDir = state.dir while (faces[nextFace]!![newDir.opposite()] != curFace) { nextRelativePos = Vector2(faceSize - 1 - nextRelativePos.y, nextRelativePos.x) newDir = newDir.turnRight() } val newPosition = (nextFace * faceSize) + nextRelativePos return State(newPosition, newDir) } /** * Adapted from https://bit.ly/3WENzKQ */ private val faces by lazy { // Generate initial adjacencies val queue = ArrayDeque<Vector2>().apply { add(startingPosition) } val visited = mutableMapOf<Vector2, MutableMap<Direction, Vector2>>() while (queue.isNotEmpty()) { val v = queue.removeFirst() for (dir in Direction.values()) { val w = v + (dir.vector() * faceSize) if (w !in grid) continue if (w !in visited.keys) { visited.getOrPut(v) { mutableMapOf() }[dir] = w visited.getOrPut(w) { mutableMapOf() }[dir.opposite()] = v queue.add(w) } } } // Normalize face-edge mapping val faces = visited .mapKeys { it.key / faceSize } .mapValues { it.value.mapValues { it.value / faceSize }.toMutableMap() } // Fill in missing edge data using corners while (faces.any { it.value.size < 4 }) { for (face in faces.keys) { for (dir in Direction.values()) { if (faces[face]?.get(dir) != null) continue for (rotation in Direction.Rotation.values()) { val commonFace = faces[face]?.get(dir.turn(rotation)) ?: continue val commonFaceEdge = faces[commonFace]?.entries?.firstOrNull { it.value == face }?.key ?: continue val missingFace = faces[commonFace]?.get(commonFaceEdge.turn(rotation)) ?: continue val missingFaceEdge = faces[missingFace]?.entries?.firstOrNull { it.value == commonFace }?.key ?: continue faces[missingFace]!![missingFaceEdge.turn(rotation)] = face faces[face]!![dir] = missingFace break } } } } faces } }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
5,061
advent-2022
MIT License
src/main/kotlin/day20/Day20ARegularMap.kt
Zordid
160,908,640
false
null
package day20 import shared.* class NorthPoleMap(puzzle: String) { private val rooms = mutableMapOf(0 toY 0 to BooleanArray(4)) private val searchEngine = SearchEngineWithNodes<Coordinate> { it.manhattanNeighbors.filterIndexed { index, _ -> rooms[it]?.get(index) ?: false } } init { processLevel(puzzle.substring(1, puzzle.length - 1)) } private fun processLevel(path: String, startRoom: Coordinate = 0 toY 0): Set<Coordinate> { return path.splitToOptionals().flatMap { processOptional(it, startRoom) }.toSet() } private fun processOptional(path: String, startRoom: Coordinate): Set<Coordinate> { var index = 0 var room = startRoom while (index < path.length) { val c = path[index++] if (c != '(') { val direction = Direction.valueOf(c.toString()) val enteredRoom = room.neighborToThe(direction) room.doors()[direction.ordinal] = true enteredRoom.doors()[direction.opposite.ordinal] = true room = enteredRoom } else { val end = path.findMatchingClosing(index - 1) val level = path.substring(index, end) val endRooms = processLevel(level, room) if (end == path.length) return endRooms if (endRooms.size > 1) { val rest = path.substring(end + 1) return endRooms.flatMap { processOptional(rest, it) }.toSet() } index = end + 1 room = endRooms.single() } } return setOf(room) } private fun Coordinate.doors() = rooms.getOrPut(this) { BooleanArray(4) } private fun String.splitToOptionals(): List<String> { val dividers = mutableListOf(-1) var counter = 0 forEachIndexed { idx, c -> if (c == '|' && counter == 0) dividers.add(idx) if (c == '(') counter++ if (c == ')') counter-- } dividers.add(length) return dividers.windowed(2, step = 1).map { (s, e) -> substring(s + 1, e) } } private fun String.findMatchingClosing(openIdx: Int): Int { var idx = openIdx var count = 0 while (true) { when (this[idx]) { '(' -> count++ ')' -> count-- } if (count == 0) return idx idx++ } } private val solutions: Pair<Int, Int> by lazy { var maxLevel = 0 var aboveThreshold = 0 searchEngine.completeAcyclicTraverse(0 toY 0).forEach { (level, onLevel) -> maxLevel = level if (level >= 1000) aboveThreshold += onLevel.size } maxLevel to aboveThreshold } fun graphicalMap(): List<String> { val area = rooms.keys.enclosingArea() val map = Array(area.height * 2 + 1) { CharArray(area.width * 2 + 1) { '#' } } val offset = area.topLeft for (room in area) { val mapCoordinate = (room - offset).let { it.x * 2 + 1 toY it.y * 2 + 1 } val doors = rooms[room] if (doors != null) { map[mapCoordinate.y][mapCoordinate.x] = if (room.x == 0 && room.y == 0) '$' else '.' mapCoordinate.manhattanNeighbors.filterIndexed { idx, _ -> doors[idx] }.forEach { map[it.y][it.x] = if (it.y == mapCoordinate.y) '|' else '-' } } } return map.map { it.joinToString("") } } fun solvePart1() = solutions.first fun solvePart2() = solutions.second } fun main() { val northPoleMap = NorthPoleMap(readPuzzle(20).single()) measureRuntime { println(northPoleMap.solvePart1()) println(northPoleMap.solvePart2()) } }
0
Kotlin
0
0
f246234df868eabecb25387d75e9df7040fab4f7
3,982
adventofcode-kotlin-2018
Apache License 2.0
src/year2022/day04/Day04.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day04 import io.kotest.matchers.shouldBe import utils.readInput fun main() { val testInput = readInput("04", "test_input") val realInput = readInput("04", "input") parseInput(testInput) .count { (firstRange, secondRange) -> fullyContains(firstRange, secondRange) } .also(::println) shouldBe 2 parseInput(realInput) .count { (firstRange, secondRange) -> fullyContains(firstRange, secondRange) } .let(::println) parseInput(testInput) .count { (firstRange, secondRange) -> partiallyContains(firstRange, secondRange) } .also(::println) shouldBe 4 parseInput(realInput) .count { (firstRange, secondRange) -> partiallyContains(firstRange, secondRange) } .let(::println) } private val parsingRegex = "\\A(\\d+)-(\\d+),(\\d+)-(\\d+)\\z".toRegex() private fun parseInput(input: List<String>): Sequence<Pair<IntRange, IntRange>> { return input.asSequence() .mapNotNull { parsingRegex.matchEntire(it) } .map { matchResult -> val (_, firstStart, firstEnd, secondStart, secondEnd) = matchResult.groupValues firstStart.toInt()..firstEnd.toInt() to secondStart.toInt()..secondEnd.toInt() } } private fun partiallyContains(firstRange: IntRange, secondRange: IntRange): Boolean { return firstRange.first in secondRange || firstRange.last in secondRange || secondRange.first in firstRange || secondRange.last in firstRange } private fun fullyContains(firstRange: IntRange, secondRange: IntRange): Boolean { return (secondRange.first <= firstRange.first && firstRange.last <= secondRange.last) || (firstRange.first <= secondRange.first && secondRange.last <= firstRange.last) }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
1,765
Advent-of-Code
Apache License 2.0
src/main/kotlin/problems/Day23.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems import kotlin.math.abs class Day23(override val input: String) : Problem { override val number: Int = 23 override fun runPartOne(): String { val burrow = Burrow.fromString(input) return findMinimumComplete(burrow) .toString() } override fun runPartTwo(): String { val newLines = """ #D#C#B#A# #D#B#A#C#""" val modifiedInput = (input.lines().subList(0, 3) + newLines.lines() + input.lines() .subList(3, input.lines().size)).joinToString(separator = "\n") val burrow = Burrow.fromString(modifiedInput) return findMinimumComplete(burrow) .toString() } fun findMinimumComplete(burrow: Burrow, cost: Long = 0L): Long? { if (burrow.complete()) { return cost } val availableMoves = burrow.availableMoves() if (availableMoves.isEmpty()) { return null } return availableMoves .mapNotNull { (burrow, c) -> findMinimumComplete(burrow, cost + c) } .minOrNull() } data class Burrow(val rooms: List<List<Char>>, val hallway: List<Char>) { val EMPTY = '.' companion object { fun fromString(input: String): Burrow { val rooms = input.lines() .drop(2) .dropLast(1) .map { line -> listOf(line[3], line[5], line[7], line[9]) } .fold(List(4) { mutableListOf<Char>() }) { rooms, line -> (0..3).forEach { i -> rooms[i].add(0, line[i]) } rooms } val hallway = input .lines()[1] .toCharArray() .drop(1) .dropLast(1) return Burrow(rooms, hallway) } } fun availableMoves(): List<Pair<Burrow, Long>> { val movableColumns = (0..3).mapNotNull { if (movableColumn(it) != null) { Pair(it, movableColumn(it)!!) } else { null } } val movesFromColumnsToColumns = movableColumns .flatMap { (columnIdx, positionIdx) -> availableMovesFromColumnToColumn(columnIdx, positionIdx) } if (movesFromColumnsToColumns.isNotEmpty()) { return movesFromColumnsToColumns } val movesFromHallway = hallway .mapIndexed { index, c -> Pair(index, c) } .filter { (_, c) -> c != EMPTY } .flatMap { availableMovesFromHallwayToColumn(it.first) } if (movesFromHallway.isNotEmpty()) { return movesFromHallway } val movesFromColumnsToHallway = movableColumns .flatMap { (columnIdx, positionIdx) -> availableMovesFromColumnToHallway(columnIdx, positionIdx) } if (movesFromColumnsToHallway.isNotEmpty()) { return movesFromColumnsToHallway } return emptyList() } private fun availableMovesFromColumnToColumn(columnIdx: Int, positionIdx: Int): List<Pair<Burrow, Long>> { val movesToHallway = rooms[columnIdx].size - positionIdx val char = rooms[columnIdx][positionIdx] val destinyColumnIdx = char - 'A' val destinyHallwayIdx = 2 + 2 * destinyColumnIdx val currentHallwayIdx = 2 + 2 * columnIdx if (destinyHallwayIdx != currentHallwayIdx && !complete(destinyColumnIdx) && canPutInto(destinyColumnIdx)) { val range = when (currentHallwayIdx > destinyHallwayIdx) { true -> currentHallwayIdx downTo destinyHallwayIdx false -> currentHallwayIdx..destinyHallwayIdx } val canMoveToDestinyColumn = range.all { hallway[it] == EMPTY } if (canMoveToDestinyColumn) { val firstEmpty = firstEmpty(destinyColumnIdx) val updatedRooms = rooms.map { it.toMutableList() } updatedRooms[columnIdx][positionIdx] = EMPTY updatedRooms[destinyColumnIdx][firstEmpty] = char val moveToFinalPosition = movesToHallway + abs(destinyHallwayIdx - currentHallwayIdx) + (rooms[columnIdx].size - firstEmpty( destinyColumnIdx )) return listOf(Pair(this.copy(rooms = updatedRooms), cost(char, moveToFinalPosition))) } } return emptyList() } private fun availableMovesFromColumnToHallway(columnIdx: Int, positionIdx: Int): List<Pair<Burrow, Long>> { val movesList = mutableListOf<Pair<Burrow, Long>>() val movesToHallway = rooms[columnIdx].size - positionIdx val char = rooms[columnIdx][positionIdx] val destinyColumnIdx = char - 'A' val currentHallwayIdx = 2 + 2 * columnIdx val updatedRooms = rooms.map { it.toMutableList() } updatedRooms[columnIdx][positionIdx] = EMPTY for (hallwayIdx in currentHallwayIdx downTo 0) { if (hallwayIdx in listOf(2, 4, 6, 8)) { continue } val moveToFinalPosition = movesToHallway + currentHallwayIdx - hallwayIdx if (hallway[hallwayIdx] != EMPTY) { break } val updatedHallway = hallway.toMutableList() updatedHallway[hallwayIdx] = char movesList.add( Pair( this.copy(rooms = updatedRooms, hallway = updatedHallway), cost(char, moveToFinalPosition) ) ) } for (hallwayIdx in currentHallwayIdx until hallway.size) { if (hallwayIdx in listOf(2, 4, 6, 8)) { continue } val moveToFinalPosition = movesToHallway + hallwayIdx - currentHallwayIdx if (hallway[hallwayIdx] != EMPTY) { break } val updatedHallway = hallway.toMutableList() updatedHallway[hallwayIdx] = char movesList.add( Pair( this.copy(rooms = updatedRooms, hallway = updatedHallway), cost(char, moveToFinalPosition) ) ) } return movesList } private fun availableMovesFromHallwayToColumn(currentHallwayIdx: Int): List<Pair<Burrow, Long>> { val char = hallway[currentHallwayIdx] val destinyColumnIdx = char - 'A' val destinyHallwayIdx = 2 + 2 * destinyColumnIdx val range = when (currentHallwayIdx > destinyHallwayIdx) { true -> currentHallwayIdx - 1 downTo destinyHallwayIdx false -> currentHallwayIdx + 1..destinyHallwayIdx } val canMoveToDestinyColumn = range.all { hallway[it] == EMPTY } if (canMoveToDestinyColumn && canPutInto(destinyColumnIdx)) { val firstEmpty = firstEmpty(destinyColumnIdx) val updatedRooms = rooms.map { it.toMutableList() } updatedRooms[destinyColumnIdx][firstEmpty] = char val updatedHallway = hallway.toMutableList() updatedHallway[currentHallwayIdx] = EMPTY val moveToFinalPosition = abs(destinyHallwayIdx - currentHallwayIdx) + (rooms.first().size - firstEmpty(destinyColumnIdx)) return listOf( Pair( this.copy(rooms = updatedRooms, hallway = updatedHallway), cost(char, moveToFinalPosition) ) ) } return emptyList() } private fun cost(char: Char, moves: Int): Long { return moves * when (char) { 'A' -> 1L 'B' -> 10 'C' -> 100 'D' -> 1000 else -> throw Exception("Invalid char $char") } } private fun movableColumn(columnIdx: Int): Int? { val lastFilled = rooms[columnIdx].indexOfLast { it != EMPTY } if (lastFilled < 0) { return null } if (rooms[columnIdx][lastFilled] != roomChar(columnIdx)) { return lastFilled } if (lastFilled >= finalElements(columnIdx)) { return lastFilled } return null } fun complete(): Boolean { return (0..3).all { complete(it) } } private fun complete(columnIdx: Int): Boolean { return rooms[columnIdx].all { it == roomChar(columnIdx) } } private fun canPutInto(columnIdx: Int): Boolean { val empty = rooms[columnIdx].count { it == EMPTY } return rooms[columnIdx].size == finalElements(columnIdx) + empty } private fun firstEmpty(columnIdx: Int): Int { return rooms[columnIdx].indexOfFirst { it == EMPTY } } private fun finalElements(columnIdx: Int): Int { var filled = 0 for (i in rooms[columnIdx].indices) { if (rooms[columnIdx][i] == roomChar(columnIdx)) { filled++ } else { break } } return filled } private fun roomChar(columnIdx: Int): Char { return 'A' + columnIdx } } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
9,954
AdventOfCode2021
MIT License
src/main/kotlin/com/sk/set0/64. Minimum Path Sum.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set0 import kotlin.math.min private fun minPathSum2(grid: Array<IntArray>): Int { val r = grid.size val c = grid[0].size for (i in 1 until c) { grid[0][i] += grid[0][i - 1] } for (i in 1 until r) { grid[i][0] += grid[i - 1][0] } for (i in 1 until r) { for (j in 1 until c) { grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]) } } return grid[r - 1][c - 1] } class Solution64 { fun minPathSum(grid: Array<IntArray>): Int { val r = grid.size val c = grid[0].size for (i in 1 until c) { grid[0][i] += grid[0][i - 1] } for (i in 1 until r) { grid[i][0] += grid[i - 1][0] } for (i in 1 until r) { for (j in 1 until c) { grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]) } } return grid[r - 1][c - 1] } fun minPathSum2(grid: Array<IntArray>): Int { val m = grid.size val n = grid[0].size val max = 200 * (m + n - 1) val dp = Array(m) { IntArray(n) { max } } dp[0][0] = grid[0][0] fun min(r: Int, c: Int): Int { if (r !in grid.indices || c !in grid[0].indices) return 200 return dp[r][c] } for (r in grid.indices) { for (c in grid[0].indices) { if (r == 0 && c == 0) continue dp[r][c] = minOf(min(r - 1, c), min(r, c - 1)) + grid[r][c] } } return dp[m - 1][n - 1] } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,572
leetcode-kotlin
Apache License 2.0
src/Day01.kt
rickbijkerk
572,911,701
false
{"Kotlin": 31571}
fun main() { fun getCalories(input: List<String>): MutableList<Int> { val calories = mutableListOf<Int>() val newLines = input.withIndex().filter { x -> x.value.isEmpty() }.map { it.index }.toMutableList() newLines.add(input.size) var start = 0 newLines.map { index -> val caloriesAsInt = input.subList(start + 1, index).map { stringValue -> stringValue.toInt() } val sumOfCalories = caloriesAsInt.sumOf { calorie -> calorie } start = index calories.add(sumOfCalories) } return calories } fun part1(input: List<String>): Int { val calories = getCalories(input) return calories.max() } fun part2(input: List<String>): Int { val calories = getCalories(input) return calories.toMutableList().sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") val result = part1(testInput) val expected = 24000 println("test result: $result") println("test expected:$expected \n") check(result == expected) val input = readInput("Day01") println("Part1 ${part1(input)}") println("Part2 ${part2(input)}") }
0
Kotlin
0
0
817a6348486c8865dbe2f1acf5e87e9403ef42fe
1,292
aoc-2022
Apache License 2.0
src/Day09.kt
WhatDo
572,393,865
false
{"Kotlin": 24776}
fun main() { val input = readInput("Day09") val rope2 = moveRope(RopeState.create(2), input) println(rope2.tailHistory.size) val rope10 = moveRope(RopeState.create(10), input) println(rope10.tailHistory.size) //10553 high } private fun moveRope(state: RopeState, input: List<String>): RopeState { return input.fold(state) { state, s -> val move = getMove(s) moveRope(state, move) } } fun moveRope(state: RopeState, move: Vec2): RopeState { // println(move) var toMove = move var newState = state while (toMove.size > 0) { val move1 = toMove.normalize() val newHead = newState.head + move1 val newTail = moveTailToHead(newHead, newState.tail) newState = newState.copy(rope = newTail, tailHistory = newState.tailHistory + newTail.last()) toMove -= move1 // println(newState) } return newState } fun moveTailToHead(newHead: Vec2, tails: List<Vec2>): List<Vec2> { return tails.scan(newHead) { head, tail -> if (head.distanceTo(tail) > 1) { val toMove = (head - tail).normalize() tail + toMove } else { tail } } } data class RopeState( val rope: List<Vec2>, val tailHistory: Set<Vec2> = rope.toSet() ) { val head get() = rope.first() val tail get() = rope.subList(1, rope.size) override fun toString(): String { return "RopeState($rope)" } companion object { fun create(size: Int): RopeState { return RopeState( List(size) { Vec2(0, 0) } ) } } } private fun getMove(string: String): Vec2 { val (dir, amountStr) = string.split(" ") val amount = amountStr.toInt() return when (dir) { "R" -> Vec2(amount, 0) "L" -> Vec2(-amount, 0) "U" -> Vec2(0, amount) "D" -> Vec2(0, -amount) else -> TODO("No move for $dir") } }
0
Kotlin
0
0
94abea885a59d0aa3873645d4c5cefc2d36d27cf
1,954
aoc-kotlin-2022
Apache License 2.0
src/Day03.kt
JIghtuse
572,807,913
false
{"Kotlin": 46764}
import java.lang.IllegalStateException fun main() { fun toPriority(c: Char): Int = when (c) { in 'a'..'z' -> c.code - 'a'.code + 1 in 'A'..'Z' -> c.code - 'A'.code + 27 else -> throw IllegalStateException("unexpected input $c") } fun part1(input: List<String>): Int { fun rucksackToPriority(s: String): Int { val left = s.substring(0, s.length / 2) val right = s.substring(s.length / 2) val c = left.filter { letter -> letter in right } return toPriority(c.first()) } return input.map(::rucksackToPriority).sum() } fun part2(input: List<String>): Int { fun threeRucksacksToPriority(threeLines: List<String>): Int { val c = threeLines[0].filter { letter -> letter in threeLines[1] && letter in threeLines[2] } return toPriority(c.first()) } return input .windowed(3, 3) .map(::threeRucksacksToPriority) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8f33c74e14f30d476267ab3b046b5788a91c642b
1,321
aoc-2022-in-kotlin
Apache License 2.0
src/Day04.kt
illarionov
572,508,428
false
{"Kotlin": 108577}
val pairPattern: Regex = Regex("""(\d+)-(\d+),(\d+)-(\d+)""") data class SectionAssignment( val first: IntRange, val second: IntRange ) fun String.parseSectionAssignment(): SectionAssignment { val result = pairPattern.matchEntire(this)?.groupValues ?: error ("Can not parse `$this`") return SectionAssignment( result[1].toInt() .. result[2].toInt(), result[3].toInt() .. result[4].toInt(), ) } fun main() { fun part1(input: List<SectionAssignment>): Int { return input.count { a -> (a.first - a.second).isEmpty() || (a.second - a.first).isEmpty() } } fun part2(input: List<SectionAssignment>): Int { return input.count { a -> a.first.intersect(a.second).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") .map(String::parseSectionAssignment) println(part1(testInput)) check(part1(testInput) == 2) val input = readInput("Day04") .map(String::parseSectionAssignment) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
1,168
aoc22-kotlin
Apache License 2.0
src/questions/ThreeSumClosest.kt
realpacific
234,499,820
false
null
package questions import algorithmdesignmanualbook.print import kotlin.math.abs import kotlin.test.assertEquals /** * Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. * Return the sum of the three integers. * * [Source](https://leetcode.com/problems/3sum-closest/) */ fun threeSumClosest(nums: IntArray, target: Int): Int { require(nums.size >= 3) val sorted = nums.sorted() var closest = sorted[0] + sorted[1] + sorted.last() for (i in 0..sorted.lastIndex) { // `i` is fixed, left & right keeps converging to middle var left = i + 1 var right = sorted.lastIndex while (left < right) { // sum right now val sums = sorted[left] + sorted[right] + sorted[i] if (sums == target) { // closest value is 0 so return immediately println("${sorted[left]} ${sorted[right]} ${sorted[i]}") return sums } else if (abs(sums - target) < abs(closest - target)) { // update if closer value is found println("${sorted[left]} ${sorted[right]} ${sorted[i]}") closest = sums } if (sums > target) { // Sum is larger so decrease right index right -= 1 } else if (sums < target) { // Smaller so increase left index left += 1 } } } return closest } fun main() { assertEquals(expected = 2, threeSumClosest(intArrayOf(-4, -1, 1, 2), 1).print()) assertEquals(expected = 5, threeSumClosest(intArrayOf(-1, 0, 1, 2, 3, 4, 6), 5).print()) assertEquals(expected = 5, threeSumClosest(intArrayOf(-1, 0, 1, 2, 3, 4, 7), 5).print()) assertEquals(expected = 6, threeSumClosest(intArrayOf(-1, 0, 1, 2, 10, 7), 5).print()) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,912
algorithms
MIT License
2020/src/year2020/day05/Day05.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2020.day05 import util.readAllLines private fun findHighestSeat(seats: Set<Int>): Int { return seats.maxOrNull() ?: -1 } private fun findMySeat(seats: Set<Int>): Int { for (i in 0 until 8*128) { if (!seats.contains(i) && seats.contains(i - 1) && seats.contains(i + 1)) { return i } } return -1 } private fun getSeats(filename: String): Set<Int> = readAllLines(filename).map { line -> var rowRange = 0..127 var seatRange = 0..7 line.forEach { when (it) { 'F' -> rowRange = rowRange.first..(rowRange.last - rowRange.count() / 2) 'B' -> rowRange = (rowRange.first + rowRange.count() / 2)..rowRange.last 'L' -> seatRange = seatRange.first..(seatRange.last - seatRange.count() / 2) 'R' -> seatRange = (seatRange.first + seatRange.count() / 2)..seatRange.last } } (rowRange.first * 8 + seatRange.first).also { println("$line -> $it") } }.toSet() fun main() { val seats = getSeats("input.txt") println("Highest: ${findHighestSeat(seats)}") println("My: ${findMySeat(seats)}") }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
1,204
adventofcode
MIT License
src/main/kotlin/day11/Day11.kt
mortenberg80
574,042,993
false
{"Kotlin": 50107}
package day11 import java.lang.IllegalArgumentException class Day11(val input: List<String>) { fun part1(): Long { val monkies = parseInput(input, true) println(monkies) val game = Game(monkies) (0 until 20).forEach { _ -> game.performRound(1) } println(game.monkies) return monkies.map { it.inspectCounter }.sortedDescending().take(2).reduce {a, b -> a*b} } fun part2(): Long { val monkies = parseInput(input, false) val lcm = monkies.map { it.divisor }.reduce { acc, i -> acc * i }.toLong() val game = Game(monkies) (0 until 10000).forEach { it -> game.performRound(lcm) } println(game.monkies) // 2147483647 // 2713310158 return monkies.map { it.inspectCounter }.sortedDescending().take(2).reduce {a, b -> a*b} } fun parseInput(input: List<String>, worryDivisor: Boolean): List<Monkey> { return input.chunked(7).map { toMonkey(it, worryDivisor) } } fun toMonkey(input: List<String>, worryDivisor: Boolean): Monkey { val id = Regex("""Monkey (\d+):""").find(input[0])!!.destructured.toList()[0].toInt() val startingItems = input[1].split(":")[1].trim().split(",").map { it.trim().toLong() }.toMutableList() val operationValues = "Operation: new = old ([*+]) ([a-zA-Z0-9]+)".toRegex().find(input[2])!!.destructured.toList() val operation = Operation.create(operationValues) val divisor = "Test: divisible by ([0-9]+)".toRegex().find(input[3])!!.destructured.toList()[0].toInt() val trueMonkey = "If true: throw to monkey ([0-9]+)".toRegex().find(input[4])!!.destructured.toList()[0].toInt() val falseMonkey = "If false: throw to monkey ([0-9]+)".toRegex().find(input[5])!!.destructured.toList()[0].toInt() return Monkey(id, startingItems, divisor, worryDivisor, operation::calculate) { input -> if (input) { trueMonkey } else { falseMonkey } } } } sealed class Operation { abstract fun calculate(old: Long): Long data class MultiplyWithNumber(val number: Long): Operation() { override fun calculate(old: Long): Long { return old * number } } object MultiplyWithOld: Operation() { override fun calculate(old: Long): Long { return old * old } } data class PlusWithNumber(val number: Long): Operation() { override fun calculate(old: Long): Long { return old + number } } object PlusWithOld: Operation() { override fun calculate(old: Long): Long { return old + old } } companion object { fun create(operationValues: List<String>): Operation { val operand = operationValues[0] val factor = operationValues[1] return when (operand) { "*" -> if (factor == "old") { MultiplyWithOld } else { MultiplyWithNumber(factor.toLong()) } "+" -> if (factor == "old") { PlusWithOld } else { PlusWithNumber(factor.toLong()) } else -> throw IllegalArgumentException("could not parse operation: $operationValues") } } } } class Game(val monkies: List<Monkey>) { fun performRound(lcm: Long) { monkies.forEach { it.performAction(monkies, lcm) } } } class Monkey( val id: Int, val items: MutableList<Long>, val divisor: Int, val worryDivisor: Boolean, val operation: (Long) -> Long, val monkeyChooser: (Boolean) -> Int ) { var inspectCounter = 0L fun performAction(monkies: List<Monkey>, lcm: Long) { val iterator = items.iterator() while (iterator.hasNext()) { inspectCounter++ val item = iterator.next() val newWorryLevel = operation.invoke(item) val boredWorryLevel = if (worryDivisor) { newWorryLevel / 3 } else { newWorryLevel % lcm } val monkeyReceiverId = monkeyChooser.invoke(boredWorryLevel % divisor == 0L) monkies[monkeyReceiverId].receive(boredWorryLevel) iterator.remove() } } fun receive(value: Long) { items.add(value) } override fun toString(): String { return "Monkey$id: inpsectCounter=$inspectCounter. '${items}'" } } fun main() { val testInput = Day11::class.java.getResourceAsStream("/day11_test.txt").bufferedReader().readLines() val input = Day11::class.java.getResourceAsStream("/day11_input.txt").bufferedReader().readLines() val day11test = Day11(testInput) val day11input = Day11(input) println("Day11 part 1 test result: ${day11test.part1()}") println("Day11 part 1 result: ${day11input.part1()}") println("Day11 part 2 test result: ${day11test.part2()}") println("Day11 part 2 result: ${day11input.part2()}") }
0
Kotlin
0
0
b21978e145dae120621e54403b14b81663f93cd8
5,243
adventofcode2022
Apache License 2.0
src/Day20.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import java.math.BigInteger import java.util.* import kotlin.math.max import kotlin.math.min class Day20 { fun readInput(input: List<String>): List<Long> { return input.map { it.toLong() } } fun decrypt(input: List<Long>, loop: Int = 1): List<Long> { val result = input.mapIndexed { i, value -> i to value}.toMutableList() repeat(loop) { for ((i, value) in input.withIndex()) { val idx = result.indexOfFirst { it.first == i } Collections.rotate(result, -idx) result.removeFirst() Collections.rotate(result, (-value % result.size).toInt()) result.add(0, i to value) Collections.rotate(result, (value % result.size).toInt()) } } return result.map { it.second } } } fun main() { val day = Day20() fun part1(input: List<String>): Long { val data = day.readInput(input) println("input: $data") val decrypted = day.decrypt(data) println("output: $decrypted") val zeroIdx = decrypted.indexOfFirst { it == 0L} val digits = listOf( decrypted[(zeroIdx + 1000) % decrypted.size], decrypted[(zeroIdx + 2000) % decrypted.size], decrypted[(zeroIdx + 3000) % decrypted.size] ) println("$zeroIdx, $digits") return digits.sumOf { it } } fun part2(input: List<String>): Long { val decryptionKey = 811_589_153 val data = day.readInput(input).map { it * decryptionKey } println("input: $data") val decrypted = day.decrypt(data, 10) println("output: $decrypted") val zeroIdx = decrypted.indexOfFirst { it == 0L} val digits = listOf( decrypted[(zeroIdx + 1000) % decrypted.size], decrypted[(zeroIdx + 2000) % decrypted.size], decrypted[(zeroIdx + 3000) % decrypted.size] ) println("$zeroIdx, $digits") return digits.sumOf { it } } val test = readInput("Day20_test") println("=== Part 1 (test) ===") println(part1(test)) println("=== Part 2 (test) ===") println(part2(test)) val input = readInput("Day20") println("=== Part 1 (puzzle) ===") println(part1(input)) println("=== Part 2 (puzzle) ===") println(part2(input)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
2,365
Advent-Of-Code-2022
Apache License 2.0
src/main/kotlin/net/rafaeltoledo/kotlin/advent/Day04.kt
rafaeltoledo
726,542,427
false
{"Kotlin": 11895}
package net.rafaeltoledo.kotlin.advent import kotlin.math.pow class Day04 { fun invoke(input: List<String>): Int { val cards = input.map { it.toScratchCard() } return cards .map { card -> card.numbers.filter { card.winningNumbers.contains(it) } } .sumOf { it.size.calculateCardValue() } } fun invoke2(input: List<String>): Int { val cards = input.map { it.toScratchCard() } val cardCounter = cards.associate { it.identifier to 1 }.toMutableMap() cards .forEachIndexed { index, card -> val id = index + 1 val multiplier = cardCounter[id] ?: 1 val extras = card.numbers.filter { card.winningNumbers.contains(it) }.count() for (i in 0 until extras) { val targetId = id + (i + 1) cardCounter[targetId]?.let { current -> cardCounter[targetId] = current + multiplier } } } return cardCounter.toList().sumOf { it.second } } } private fun Int.calculateCardValue(): Int { return 2.0.pow((this - 1).toDouble()).toInt() } private fun String.toScratchCard(): ScratchCard { val parts = split(":") val identifier = parts.first().replace("Card", "").trim().toInt() val content = parts.last().split("|") val winningNumbers = content.first().split(" ").filter { it.isNotEmpty() }.map { it.trim().toInt() } val numbers = content.last().split(" ").filter { it.isNotEmpty() }.map { it.trim().toInt() } return ScratchCard(identifier, numbers, winningNumbers) } data class ScratchCard( val identifier: Int, val numbers: List<Int>, val winningNumbers: List<Int>, )
0
Kotlin
0
0
7bee985147466cd796e0183d7c719ca6d01b5908
1,619
aoc2023
Apache License 2.0
src/main/kotlin/dev/claudio/adventofcode2021/Day16Part2.kt
ClaudioConsolmagno
434,559,159
false
{"Kotlin": 78336}
package dev.claudio.adventofcode2021 import org.apache.commons.lang3.StringUtils import java.math.BigInteger fun main() { Day16Part2().main() } private class Day16Part2 { fun main() { tests() val input: List<String> = Support.readFileAsListString("day16-input.txt") val inputBinary = processInput(input[0]) val bits = processor(inputBinary) println(bits.eval()) } fun processInput(input: String) = input.toList() .map { BigInteger(it.toString(), 16).toString(2) } .map { StringUtils.leftPad(it, 4, '0') } .joinToString("") private fun tests() { if (sumAllVersions(processor(processInput("D2FE28"))) != 6) throw Error() if (sumAllVersions(processor(processInput("38006F45291200"))) != 9) throw Error() if (sumAllVersions(processor(processInput("EE00D40C823060"))) != 14) throw Error() if (sumAllVersions(processor(processInput("8A004A801A8002F478"))) != 16) throw Error() if (sumAllVersions(processor(processInput("620080001611562C8802118E34"))) != 12) throw Error() if (sumAllVersions(processor(processInput("C0015000016115A2E0802F182340"))) != 23) throw Error() if (sumAllVersions(processor(processInput("A0016C880162017C3686B18A3D4780"))) != 31) throw Error() } fun sumAllVersions(bits : BITS) : Int { if (bits is BITSLiteral) { return bits.getPacketVersion() } else if (bits is BITSOperator) { return bits.getPacketVersion() + bits.packets.sumOf { sumAllVersions(it) } } else { return 0 } } fun processor(inputBinary: String) : BITS { // val version = Integer.parseInt(inputBinary.substring(0, 3), 2) val typeId = Integer.parseInt(inputBinary.substring(3, 6), 2) val packetsString: String = inputBinary.substring(6, inputBinary.length) if (typeId == 4) { var shift = 0 var isLast: Boolean val res2 = mutableListOf<String>() do { res2.add(packetsString.substring(shift + 1, shift + 5)) isLast = packetsString[shift] == '0' shift += 5 } while (!isLast) return BITSLiteral(inputBinary.substring(0, shift + 6), res2.joinToString("").toLong(2)) } else { var operatorLength = 7 val subPackets = mutableListOf<BITS>() val lengthTypeId = packetsString[0] if (lengthTypeId == '0') { var lengthOfBitsToRead = Integer.parseInt(packetsString.substring(1, 16), 2) var startPosition = 16 operatorLength += 15 do { subPackets.add(processor(packetsString.substring(startPosition, startPosition + lengthOfBitsToRead))) startPosition += subPackets.last().inputBinary.length lengthOfBitsToRead -= subPackets.last().inputBinary.length operatorLength += subPackets.last().inputBinary.length } while (lengthOfBitsToRead > 3) } else { var startPosition = 12 val repeat = Integer.parseInt(packetsString.substring(1, 12), 2) operatorLength += 11 repeat(repeat) { subPackets.add(processor(packetsString.substring(startPosition))) startPosition += subPackets.last().inputBinary.length operatorLength += subPackets.last().inputBinary.length } } return BITSOperator(inputBinary.substring(0, operatorLength), subPackets) } } class BITSLiteral(inputBinary: String, val literalDec: Long) : BITS(inputBinary){ override fun eval() : Long { return literalDec } override fun toString(): String { return "BITSLiteral(version=${getPacketVersion()}, typeId=${getTypeId()}, literalDec=$literalDec)" } } class BITSOperator(inputBinary: String, val packets: List<BITS>) : BITS(inputBinary){ override fun eval() : Long { when(getTypeId()) { 0 -> return packets.sumOf { it.eval() } 1 -> return packets.fold(1L) { acc, bits -> acc * bits.eval() } 2 -> return packets.minOf { it.eval() } 3 -> return packets.maxOf { it.eval() } 5 -> return if (packets[0].eval() > packets[1].eval()) { 1L } else { 0L } 6 -> return if (packets[0].eval() < packets[1].eval()) { 1L } else { 0L } 7 -> return if (packets[0].eval() == packets[1].eval()) { 1L } else { 0L } } throw Error() } override fun toString(): String { return "BITSOperator(version=${getPacketVersion()}, typeId=${getTypeId()}, packets=$packets)" } } abstract class BITS(val inputBinary: String) { abstract fun eval() : Long fun getPacketVersion(): Int { return Integer.parseInt(inputBinary.substring(0, 3), 2) } fun getTypeId(): Int { return Integer.parseInt(inputBinary.substring(3, 6), 2) } } }
0
Kotlin
0
0
5f1aff1887ad0a7e5a3af9aca7793f1c719e7f1c
5,231
adventofcode-2021
Apache License 2.0
2022/src/main/kotlin/day23.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Grid import utils.Parser import utils.Solution import utils.Vec2i import utils.borderWith import utils.createGrid import utils.mapParser import java.util.Collections import kotlin.math.absoluteValue fun main() { Day23.run() } object Day23 : Solution<Grid<Char>>() { override val name = "day23" override val parser = Parser { it.trim() }.mapParser(Parser.charGrid) enum class Direction(val vs: List<Vec2i>, val move: Vec2i) { NORTH((-1 .. 1).map { Vec2i(it, -1) }, Vec2i(0, -1)), SOUTH((-1 .. 1).map { Vec2i(it, 1) }, Vec2i(0, 1)), WEST((-1 .. 1).map { Vec2i(-1, it) }, Vec2i(-1, 0)), EAST((-1 .. 1).map { Vec2i(1, it) }, Vec2i(1, 0)), } fun makeRound(grid: Grid<Char>, round: Int): Grid<Char> { val moves = mutableMapOf<Vec2i, Vec2i>() val moveCounts = mutableMapOf<Vec2i, Int>() val elves = grid.coords.filter { grid[it] == '#' } for (elf in elves) { if (elf.surrounding.all { grid[it] == '.' }) { // do nothing moves[elf] = elf moveCounts[elf] = moveCounts.getOrDefault(elf, 0) + 1 continue } val opts = Direction.values().toMutableList() Collections.rotate(opts, 0 - (round % 4)) val dir = opts.firstOrNull { dir -> dir.vs.all { grid[elf + it] == '.' } } if (dir != null) { moves[elf] = elf + dir.move moveCounts[elf + dir.move] = moveCounts.getOrDefault(elf + dir.move, 0) + 1 } else { // don't move moves[elf] = elf moveCounts[elf] = moveCounts.getOrDefault(elf, 0) + 1 } } val invalidMoves = moveCounts.entries.filter { (_, count) -> count > 1 }.map { (coord, _) -> coord }.toSet() moves.keys.forEach { // reset to starting if invalid if (moves[it] in invalidMoves) { moves[it] = it } } val newElves = moves.values.toSet() require(newElves.size == elves.size) return createGrid(grid.width, grid.height) { if (it in newElves) '#' else '.' } } override fun part1(input: Grid<Char>): Int { var grid = input repeat(10) { round -> val (tl, br) = grid.bounds { it == '#' } if (tl.x == 0 || tl.y == 0 || br.x == grid.width - 1 || br.y == grid.height - 1) { // grow the grid to make room for automata grid = grid.borderWith('.') } grid = makeRound(grid, round) } val (tl, br) = grid.bounds { it == '#' } return (((tl.x - br.x).absoluteValue + 1) * (((tl.y - br.y).absoluteValue) + 1)) - grid.values.count { it == '#' } } override fun part2(input: Grid<Char>): Any? { var grid = input var round = 0 while (true) { val (tl, br) = grid.bounds { it == '#' } if (tl.x == 0 || tl.y == 0 || br.x == grid.width - 1 || br.y == grid.height - 1) { // grow the grid to make room for automata grid = grid.borderWith('.') } val newGrid = makeRound(grid, round) round++ // break if newGrid is the same as old grid val newElves = newGrid.cells.filter { (_, c) -> c == '#' }.map { (v, _) -> v }.toSet() val oldElves = grid.cells.filter { (_, c) -> c == '#' }.map { (v, _) -> v }.toSet() if ((oldElves - newElves).isEmpty()) { break } grid = newGrid } return round } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
3,303
aoc_kotlin
MIT License
src/main/kotlin/com/groundsfam/advent/points/Points.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.points import com.groundsfam.advent.Direction import com.groundsfam.advent.asPoint data class Point(val x: Int, val y: Int) { operator fun plus(other: Point) = Point(x + other.x, y + other.y) operator fun minus(other: Point) = Point(x - other.x, y - other.y) operator fun times(factor: Int) = Point(x * factor, y * factor) } // north, south, east, west, and diagonals val Point.n get() = Point(x, y - 1) val Point.s get() = Point(x, y + 1) val Point.e get() = Point(x + 1, y) val Point.w get() = Point(x - 1, y) val Point.nw get() = Point(x - 1, y - 1) val Point.ne get() = Point(x + 1, y - 1) val Point.sw get() = Point(x - 1, y + 1) val Point.se get() = Point(x + 1, y + 1) // up, down, left and right directions val Point.up get() = this.n val Point.down get() = this.s val Point.left get() = this.w val Point.right get() = this.e fun Point.adjacents(diagonal: Boolean = true): List<Point> = if (diagonal) listOf(n, nw, w, sw, s, se, e, ne) else listOf(n, w, s, e) fun Point.go(d: Direction): Point = this + d.asPoint() fun Iterable<Point>.sum(): Point = this.fold(Point(0, 0)) { sum, point -> sum + point } data class Point3(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Point3) = Point3(x + other.x, y + other.y, z + other.z) } fun Point3.adjacents(): List<Point3> = listOf( Point3(1, 0, 0) + this, Point3(-1, 0, 0) + this, Point3(0, 1, 0) + this, Point3(0, -1, 0) + this, Point3(0, 0, 1) + this, Point3(0, 0, -1) + this, )
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,536
advent-of-code
MIT License
src/main/kotlin/dev/paulshields/aoc/Day11.kt
Pkshields
433,609,825
false
{"Kotlin": 133840}
/** * Day 11: Dumbo Octopus */ package dev.paulshields.aoc import dev.paulshields.aoc.common.Point import dev.paulshields.aoc.common.readFileAsString fun main() { println(" ** Day 11: Dumbo Octopus ** \n") val dumboOctopuses = readFileAsString("/Day11DumboOctopuses.txt") val numberOfFlashes = countNumberOfFlashesAfterSteps(dumboOctopuses, 100) println("The number of Dumbo Octopus flashes after 100 steps is $numberOfFlashes") val stepNumber = calculateStepNumberWhenEveryOctopusIsFlashing(dumboOctopuses) println("The step where every octopus is flashing is $stepNumber") } fun countNumberOfFlashesAfterSteps(rawOctopusEnergyGrid: String, numberOfSteps: Int): Long { var flashCount = 0L var octopusEnergyGrid = parseOctopusEnergyGrid(rawOctopusEnergyGrid) (1..numberOfSteps).forEach { _ -> octopusEnergyGrid = iterateOctopusesOnce(octopusEnergyGrid) flashCount += countNumberOfFlashes(octopusEnergyGrid) } return flashCount } fun calculateStepNumberWhenEveryOctopusIsFlashing(rawOctopusEnergyGrid: String): Int { var runs = 0 var octopusEnergyGrid = parseOctopusEnergyGrid(rawOctopusEnergyGrid) do { ++runs octopusEnergyGrid = iterateOctopusesOnce(octopusEnergyGrid) } while (countNumberOfFlashes(octopusEnergyGrid) != octopusEnergyGrid.size) return runs } private fun parseOctopusEnergyGrid(octopusesStartingEnergy: String) = octopusesStartingEnergy .lines() .flatMapIndexed { xPos, line -> line.toCharArray().mapIndexed { yPos, char -> Pair(Point(xPos, yPos), char.digitToInt()) } }.toMap() private fun iterateOctopusesOnce(octopusEnergyGrid: Map<Point, Int>): Map<Point, Int> { val octopuses = octopusEnergyGrid.toMutableMap() val flashedOctopuses = mutableListOf<Point>() octopuses.keys.forEach { octopuses.incrementValueIfAvailable(it) } var flashingOctopuses = octopuses.filter { it.value > 9 } while (flashingOctopuses.isNotEmpty()) { flashingOctopuses .flatMap { getAllAdjacentPoints(it.key) } .forEach { octopuses.incrementValueIfAvailable(it) } flashedOctopuses.addAll(flashingOctopuses.keys) flashingOctopuses = octopuses.filter { it.value > 9 && !flashedOctopuses.contains(it.key) } } flashedOctopuses.forEach { octopuses[it] = 0 } return octopuses.toMap() } private fun countNumberOfFlashes(octopusEnergyGrid: Map<Point, Int>) = octopusEnergyGrid.values.count { it == 0 } private fun getAllAdjacentPoints(point: Point) = listOf( Point(point.x - 1, point.y - 1), Point(point.x - 1, point.y), Point(point.x - 1, point.y + 1), Point(point.x, point.y - 1), Point(point.x, point.y + 1), Point(point.x + 1, point.y - 1), Point(point.x + 1, point.y), Point(point.x + 1, point.y + 1)) private fun MutableMap<Point, Int>.incrementValueIfAvailable(key: Point) { if (contains(key)) { this[key] = this[key]?.plus(1) ?: 0 } }
0
Kotlin
0
0
e3533f62e164ad72ec18248487fe9e44ab3cbfc2
3,017
AdventOfCode2021
MIT License
src/Day10.kt
bigtlb
573,081,626
false
{"Kotlin": 38940}
import java.lang.Math.abs fun main() { fun generateValues(input: List<String>): List<Int> { val values = mutableListOf<Int>() input.fold(1) { acc, cur -> when (cur.substring(0..3)) { "noop" -> { values.add(acc) acc } "addx" -> { repeat(2) { values.add(acc) } acc + cur.substring(5).toInt() } else -> acc } } return values } fun part1(input: List<String>): Int = generateValues(input).mapIndexed { idx, cur -> if ((idx - 19) % 40 == 0) cur * (idx + 1) else 0 }.sum() fun part2(input: List<String>) { val values = generateValues(input) println((0..5).map{row -> println(String((0..39).map{col -> if (abs(values[row * 40 + col] - col)<=1) 'X' else '.'}.toCharArray())) }) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) //check(part2(testInput) == 0) part2(testInput) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8f76d3c75a30ae00c563c997ed2fb54827ea94a
1,254
aoc-2022-demo
Apache License 2.0
src/Day14.kt
lsimeonov
572,929,910
false
{"Kotlin": 66434}
import kotlin.math.abs import kotlin.math.max typealias Dot = Pair<Int, Int> fun main() { fun moveDot(a: Dot, b: Dot): Dot { return Dot(a.first + b.first, a.second + b.second) } fun dotEquals(a: Dot, b: Dot): Boolean { return a.first == b.first && a.second == b.second } fun part1(input: List<String>): Int { val walls = input.map { it.split(" -> ").map { val coord = it.split(",") Dot(coord[0].toInt(), coord[1].toInt()) } }.let { r -> r.map { d -> d.mapIndexed { idx, cur -> val line = mutableSetOf(cur) val next = d.getOrNull(idx + 1) if (next != null) { val xDiff = next.first - cur.first val yDiff = next.second - cur.second val xDir = if (xDiff > 0) 1 else if (xDiff < 0) -1 else 0 val yDir = if (yDiff > 0) 1 else if (yDiff < 0) -1 else 0 val xSteps = abs(xDiff) val ySteps = abs(yDiff) val xStep = if (xSteps > 0) xDir else 0 val yStep = if (ySteps > 0) yDir else 0 for (i in 1..max(xSteps, ySteps)) { line.add(moveDot(line.last(), Dot(xStep, yStep))) } } line }.flatten().toSet() }.flatten().toSet() } val maxY = walls.maxOf { it.second } // Begin loop var movement = true val startSand = Dot(500, 0) val sands = mutableSetOf<Pair<Dot, Boolean>>(Pair(startSand, true)) val movements = listOf(Pair(0, 1), Pair(-1, 1), Pair(1, 1)) while (movement) { var s = sands.find { it.second } if (s == null) { s = Pair(startSand, true) sands.add(s) } // move it var moved = false run breaking@{ movements.forEach { val next = moveDot(s.first, it) if (!walls.contains(next) && !sands.any { sand -> dotEquals(sand.first, next) }) { // We can moveit sands.remove(s) sands.add(Pair(next, true)) moved = true return@breaking } } } if (!moved) { // We can't move it so stop it sands.remove(s) sands.add(Pair(s.first, false)) } else { // check if we are out of bounds if (sands.last().first.second > maxY) { // we are out of bounds movement = false } } } return sands.size - 1 } fun part2(input: List<String>): Int { val walls = input.map { it.split(" -> ").map { val coord = it.split(",") Dot(coord[0].toInt(), coord[1].toInt()) } }.let { r -> r.map { d -> d.mapIndexed { idx, cur -> val line = mutableSetOf(cur) val next = d.getOrNull(idx + 1) if (next != null) { val xDiff = next.first - cur.first val yDiff = next.second - cur.second val xDir = if (xDiff > 0) 1 else if (xDiff < 0) -1 else 0 val yDir = if (yDiff > 0) 1 else if (yDiff < 0) -1 else 0 val xSteps = abs(xDiff) val ySteps = abs(yDiff) val xStep = if (xSteps > 0) xDir else 0 val yStep = if (ySteps > 0) yDir else 0 for (i in 1..max(xSteps, ySteps)) { line.add(moveDot(line.last(), Dot(xStep, yStep))) } } line }.flatten().toSet() }.flatten().toSet() } val maxY = walls.maxOf { it.second } // Begin loop var movement = true val startSand = Dot(500, 0) var movingSand = startSand val restedSands = mutableSetOf<Dot>() val movements = listOf(Pair(0, 1), Pair(-1, 1), Pair(1, 1)) while (movement) { // move it var moved = false run breaking@{ movements.forEach { val next = moveDot(movingSand, it) if (next.second < (maxY + 2) && !walls.contains(next) && !restedSands.any { sand -> dotEquals( sand, next ) }) { // We can moveit movingSand = next moved = true return@breaking } } } if (!moved) { if (movingSand == startSand) { movement = false } restedSands.add(movingSand) movingSand = startSand } } return restedSands.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") // check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
5,781
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SimilarStringGroups.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.extensions.swap import java.util.LinkedList import java.util.Queue /** * 839. Similar String Groups * @see <a href="https://leetcode.com/problems/similar-string-groups">Source</a> */ fun interface SimilarStringGroups { fun numSimilarGroups(strings: Array<String>): Int } private fun numSimilarGroupsCount( strings: Array<String>, strategy: (n: Int, adj: Map<Int, MutableList<Int>>, visit: BooleanArray) -> Unit, ): Int = run { fun isSimilar(a: String, b: String): Boolean { var diff = 0 for (i in a.indices) { if (a[i] != b[i]) { diff++ } } return diff == 0 || diff == 2 } val n = strings.size val adj: MutableMap<Int, MutableList<Int>> = HashMap() // Form the required graph from the given strings array. for (i in 0 until n) { for (j in i + 1 until n) { if (isSimilar(strings[i], strings[j])) { adj.computeIfAbsent(i) { ArrayList() }.add(j) adj.computeIfAbsent(j) { ArrayList() }.add(i) } } } val visit = BooleanArray(n) var count = 0 // Count the number of connected components. for (i in 0 until n) { if (!visit[i]) { strategy(i, adj, visit) count++ } } return count } /** * Approach 1: Depth First Search */ class SimilarStringGroupsBFS : SimilarStringGroups { override fun numSimilarGroups(strings: Array<String>): Int { return numSimilarGroupsCount(strings, ::bfs) } private fun bfs(n: Int, adj: Map<Int, MutableList<Int>>, visit: BooleanArray) { var node = n val q: Queue<Int> = LinkedList() q.offer(node) visit[node] = true while (q.isNotEmpty()) { node = q.poll() if (!adj.containsKey(node)) { continue } for (neighbor in adj[node]!!) { if (!visit[neighbor]) { visit[neighbor] = true q.offer(neighbor) } } } } } /** * Approach 2: Breadth First Search */ class SimilarStringGroupsDFS : SimilarStringGroups { override fun numSimilarGroups(strings: Array<String>): Int { return numSimilarGroupsCount(strings, ::dfs) } private fun dfs(node: Int, adj: Map<Int, MutableList<Int>>, visit: BooleanArray) { visit[node] = true if (!adj.containsKey(node)) { return } for (neighbor in adj[node]!!) { if (!visit[neighbor]) { visit[neighbor] = true dfs(neighbor, adj, visit) } } } } /** * Approach 3: Union-find */ class SimilarStringGroupsUnionFind : SimilarStringGroups { override fun numSimilarGroups(strings: Array<String>): Int { val n: Int = strings.size val dsu = UnionFind(n) var count = n // Form the required graph from the given strings array. for (i in 0 until n) { for (j in i + 1 until n) { if (isSimilar(strings[i], strings[j]) && dsu.find(i) != dsu.find(j)) { count-- dsu.unionSet(i, j) } } } return count } private fun isSimilar(a: String, b: String): Boolean { var diff = 0 for (i in a.indices) { if (a[i] != b[i]) { diff++ } } return diff == 0 || diff == 2 } } /** * Approach 4: Union-find 2 */ class SimilarStringGroupsDSU : SimilarStringGroups { override fun numSimilarGroups(strings: Array<String>): Int { val n: Int = strings.size val w: Int = strings[0].length val dsu = DSU(n) if (n < w * w) { // If few words, then check for pairwise similarity: O(N^2 W) for (i in 0 until n) for (j in i + 1 until n) if (similar(strings[i], strings[j])) dsu.union(i, j) } else { // If short words, check all neighbors: O(N W^3) val buckets: MutableMap<String, MutableList<Int>> = HashMap() for (i in 0 until n) { val l: CharArray = strings[i].toCharArray() for (j0 in l.indices) { for (j1 in j0 + 1 until l.size) { l.swap(j0, j1) val sb = StringBuilder() for (c in l) sb.append(c) buckets.computeIfAbsent(sb.toString()) { ArrayList() }.add(i) l.swap(j0, j1) } } } for (i1 in strings.indices) { if (buckets.containsKey(strings[i1])) { for (i2 in buckets[strings[i1]]!!) { dsu.union(i1, i2) } } } } var ans = 0 for (i in 0 until n) if (dsu.parent[i] == i) ans++ return ans } private fun similar(word1: String, word2: String): Boolean { var diff = 0 for (i in word1.indices) if (word1[i] != word2[i]) diff++ return diff <= 2 } class DSU(n: Int) { var parent: IntArray = IntArray(n) init { for (i in 0 until n) parent[i] = i } fun find(x: Int): Int { if (parent[x] != x) parent[x] = find(parent[x]) return parent[x] } fun union(x: Int, y: Int) { parent[find(x)] = find(y) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
6,224
kotlab
Apache License 2.0
src/main/kotlin/Day22.kt
clechasseur
267,632,210
false
null
import org.clechasseur.adventofcode2016.Day22Data import org.clechasseur.adventofcode2016.Pt object Day22 { private val input = Day22Data.input private val dfRegex = """^/dev/grid/node-x(\d+)-y(\d+)\s+(\d+)T\s+(\d+)T\s+(\d+)T\s+(\d+)%$""".toRegex() fun part1(): Int { val nodes = input.lines().associate { it.toNode() } return nodes.flatMap { (pta, a) -> nodes.filter { (ptb, _) -> ptb != pta }.map { (_, b) -> a to b } }.count { (a, b) -> a.used > 0 && a.used <= b.avail } } fun part2(): Int { // I solved this one simply by printing the maze and calculating the path by hand // val nodes = input.lines().associate { it.toNode() } // val (emptyPt, emptyNode) = nodes.asSequence().single { (_, node) -> node.used == 0 } // (0..37).map { x -> // (0..25).joinToString("") { y -> // val node = nodes[Pt(x, y)]!! // when { // x == 0 && y == 0 -> "S" // x == 37 && y == 0 -> "G" // Pt(x, y) == emptyPt -> "_" // node.size <= emptyNode.size -> "." // node.used > emptyNode.size -> "#" // else -> error("Wrong configuration") // } // } // }.forEach { println(it) } return 246 } private data class Node(val size: Int, val used: Int) { val avail: Int get() = size - used } private fun String.toNode(): Pair<Pt, Node> { val match = dfRegex.matchEntire(this) ?: error("Wrong df output: $this") val (x, y, size, used) = match.destructured return Pt(x.toInt(), y.toInt()) to Node(size.toInt(), used.toInt()) } }
0
Kotlin
0
0
120795d90c47e80bfa2346bd6ab19ab6b7054167
1,770
adventofcode2016
MIT License