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
kotlin/src/katas/kotlin/leetcode/longest_valid_parens/LongestValidParens.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.longest_valid_parens import datsok.shouldEqual import org.junit.Test class LongestValidParensTest { @Test fun examples() { longestValidParentheses("") shouldEqual "" longestValidParentheses(")") shouldEqual "" longestValidParentheses(")(") shouldEqual "" longestValidParentheses("()") shouldEqual "()" longestValidParentheses("(()") shouldEqual "()" // 1 2 1 longestValidParentheses("())") shouldEqual "()" // 1 0 -1 longestValidParentheses(")()(") shouldEqual "()" // -1 0 -1 1 "(())".let { longestValidParentheses(")$it)") shouldEqual it // -1 0 1 0 -1 -2 longestValidParentheses("())$it") shouldEqual it // 1 0 -1 0 1 0 -1 longestValidParentheses("$it(()") shouldEqual it } "()()".let { longestValidParentheses(")$it)") shouldEqual it longestValidParentheses("())$it") shouldEqual it longestValidParentheses("$it(()") shouldEqual it } longestValidParentheses("))(())())(") shouldEqual "(())()" } } private fun longestValidParentheses(s: String): String { var result = "" (0..s.length).forEach { i -> (i..s.length).forEach { j -> val ss = s.substring(i, j) if (ss.hasValidParens() && ss.length > result.length) { result = ss } } } return result } private fun String.hasValidParens(): Boolean { var counter = 0 forEach { char -> when (char) { '(' -> counter++ ')' -> counter-- } if (counter < 0) return false } return counter == 0 }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,696
katas
The Unlicense
src/main/kotlin/Question.kt
pjangam
216,003,701
false
null
class Question(private val words: List<String>) { private val questionType: QuestionType private val crypticRoman: List<String> init { require(isQuestion(words)) questionType = when { QuestionType.MetalCost.matches(words) -> QuestionType.MetalCost QuestionType.NumberValue.matches(words) -> QuestionType.NumberValue else -> QuestionType.Blah } crypticRoman = words .drop(questionType.whWordsCount) .take(words.count() - questionType.nonNumberWords) } companion object { fun isQuestion(words: List<String>): Boolean { return words.last() == "?" } } fun getAnswer(costLedger: CostLedger, language: Language): String { val romanValue = getNumber(language) return when (questionType) { QuestionType.NumberValue -> "${crypticRoman.joinToString(" ")} is $romanValue" QuestionType.MetalCost -> { val metal = words[words.count() - 2] val totalValue: Double = romanValue * (costLedger.get(metal)) "${crypticRoman.joinToString(" ")} $metal is ${totalValue.toInt()} Credits" } QuestionType.Blah -> "I have no idea what you are talking about" } } private fun getNumber(language: Language): Int { return if (questionType == QuestionType.Blah) 0 else { val romanString = language.toEnglish(crypticRoman) RomanNumber(romanString) .toInt() } } } enum class QuestionType(val nonNumberWords: Int, private val beginWords: List<String>) { Blah(0, emptyList()), MetalCost(6, listOf("how", "many", "Credits", "is")), //wh =4 , ?=1, metal=1 NumberValue(4, listOf("how", "much", "is")); //wh=3, ?=1 val whWordsCount: Int = beginWords.count() fun matches(words: List<String>): Boolean = words.take(whWordsCount) == beginWords }
0
Kotlin
0
0
2c4c43b42f705f408e667e13d8a1158bb33245a7
1,965
MerchantGuideToGalaxy
MIT License
src/Day08/day08.kt
NST-d
573,224,214
false
null
package Day08 import utils.readInputLines import utils.readTestLines import java.util.Arrays import kotlin.math.max fun main() { fun printArray(arr: Array<BooleanArray>){ arr.forEach { it.forEach { print("$it ") } println() } } fun part1(input: List<String>): Int{ val n = input.size val m = input.first().length val visible = Array(n) {BooleanArray(m)} visible[0] = BooleanArray(m) {true} visible[n-1] = BooleanArray(m) {true} for ( i in 0 until m){ visible[i][0] = true visible[i][m-1] = true } for (i in 1 until n-1) { for(j in 1 until m-1){ if (input[i].substring(0,j).all { it < input[i][j]}){ visible[i][j] = true } } for(j in m-2 downTo 1){ if (input[i].substring(j+1,m).all { it < input[i][j]}){ visible[i][j] = true } } } for (j in 1 until m-1) { val column = input.map { it[j] } for(i in 1 until n-1){ if (column.take(i).all { it < input[i][j]}){ visible[i][j] = true } if (column.takeLast(i).all { it < input[n-i-1][j]}){ visible[n-i-1][j] = true } } } //printArray(visible) return visible.sumOf { it.count { it } } } fun part2(input: List<String>):Int{ var max = 0 val n = input.size var (bestI, bestJ) = Pair(0,0) for (i in 1 until n-1){ for (j in 1 until n-1){ val height = input[i][j] var maxLeft = 1 for(k in j-1 downTo 1){ if (input[i][k] < height){ maxLeft++ }else{ break } } var maxRight = 1 for(k in j+1 until n-1){ if (input[i][k] < height){ maxRight++ }else{ break } } var maxUp = 1 for(k in i-1 downTo 1){ if (input[k][j] < height){ maxUp++ }else{ break } } var maxDown = 1 for(k in i+1 until n-1){ if (input[k][j] < height){ maxDown++ }else{ break } } val score = maxDown * maxUp * maxLeft * maxRight //println("($i, $j) $maxUp $maxRight $maxDown $maxLeft") if(score > max){ max = score bestI = i bestJ = j } } } //println("$bestI, $bestJ") return max } val test = readTestLines("Day08") val input = readInputLines("Day08") println(part2(input)) }
0
Kotlin
0
0
c4913b488b8a42c4d7dad94733d35711a9c98992
3,255
aoc22
Apache License 2.0
src/Day12.kt
vitind
578,020,578
false
{"Kotlin": 60987}
import java.util.* import kotlin.math.absoluteValue fun main() { data class Node(val position: Pair<Int,Int>, val cost: Int, val estimate: Int, val parentNode: Node? = null) fun loadGrid(input: List<String>) = input.map { it.toCharArray() } fun getLetter(grid: List<CharArray>, xPos: Int, yPos: Int) = grid[yPos][xPos] fun getLetter(grid: List<CharArray>, position: Pair<Int,Int>) = grid[position.second][position.first] fun findPosition(grid: List<CharArray>, ch: Char) : Pair<Int,Int> { for (yPos in grid.indices) { for (xPos in 0 until grid[yPos].size) { if (grid[yPos][xPos] == ch) { return Pair(xPos, yPos) } } } return Pair(-1,-1) } fun findStartPosition(grid: List<CharArray>) : Pair<Int,Int> { // xPos, yPos return findPosition(grid, 'S') } fun findEndPosition(grid: List<CharArray>) : Pair<Int, Int> { return findPosition(grid, 'E') } fun getHeuristicDistance(firstPosition: Pair<Int,Int>, secondPosition: Pair<Int,Int>) : Int { // Manhattan distance return (firstPosition.first - secondPosition.first).absoluteValue + (firstPosition.second - secondPosition.second).absoluteValue } fun isPositionVisited(positionVisited: MutableSet<Pair<Int,Int>>, position: Pair<Int,Int>) : Boolean = positionVisited.contains(position) fun addVisitedPosition(positionVisited: MutableSet<Pair<Int,Int>>, position: Pair<Int,Int>) { positionVisited.add(position) } fun isValidMove(currentLetter: Char, nextLetter: Char) : Boolean = if ((nextLetter.code <= (currentLetter.code + 1))) true else false fun expandNode(open: PriorityQueue<Node>, positionVisited: MutableSet<Pair<Int, Int>>, grid: List<CharArray>, endPosition: Pair<Int,Int>, node: Node) { val xPos = node.position.first val yPos = node.position.second val letter = getLetter(grid, xPos, yPos) // Left if ((xPos - 1) >= 0) { val newPosition = Pair(xPos - 1, yPos) val newLetter = getLetter(grid, newPosition) if (isValidMove(letter, newLetter) && !isPositionVisited(positionVisited, newPosition)) { open.add(Node(newPosition, node.cost + 1, getHeuristicDistance(newPosition, endPosition), node)) } } // Right if ((xPos + 1) < grid[0].size) { val newPosition = Pair(xPos + 1, yPos) val newLetter = getLetter(grid, newPosition) if (isValidMove(letter, newLetter) && !isPositionVisited(positionVisited, newPosition)) { open.add(Node(newPosition, node.cost + 1, getHeuristicDistance(newPosition, endPosition), node)) } } // Up if ((yPos - 1) >= 0) { val newPosition = Pair(xPos, yPos - 1) val newLetter = getLetter(grid, newPosition) if (isValidMove(letter, newLetter) && !isPositionVisited(positionVisited, newPosition)) { open.add(Node(newPosition, node.cost + 1, getHeuristicDistance(newPosition, endPosition), node)) } } // Down if ((yPos + 1) < grid.size) { val newPosition = Pair(xPos, yPos + 1) val newLetter = getLetter(grid, newPosition) if (isValidMove(letter, newLetter) && !isPositionVisited(positionVisited, newPosition)) { open.add(Node(newPosition, node.cost + 1, getHeuristicDistance(newPosition, endPosition), node)) } } } fun displayGrid(grid: List<CharArray>) { for (gridLine in grid) { println(gridLine) } } fun part1(input: List<String>): Int { val grid = loadGrid(input) val startPosition = findStartPosition(grid) val endPosition = findEndPosition(grid) val positionVisited = mutableSetOf<Pair<Int,Int>>() // A* search algorithm with Manhattan distance heuristic val open = PriorityQueue<Node>(1000, compareBy { it.cost + it.estimate }) open.add(Node(startPosition, 0, getHeuristicDistance(startPosition, endPosition))) // Change the grid positions to be their elevations grid[startPosition.second][startPosition.first] = 'a' grid[endPosition.second][endPosition.first] = 'z' var cost = 0 while (open.isNotEmpty()) { val node = open.remove() if (node.position.equals(endPosition)) { // println("End Goal Found | Cost = ${node.cost}") cost = node.cost break } addVisitedPosition(positionVisited, node.position) expandNode(open, positionVisited, grid, endPosition, node) } return cost } fun part2(input: List<String>): Int { val grid = loadGrid(input) val startPosition = findStartPosition(grid) val endPosition = findEndPosition(grid) val positionVisited = mutableSetOf<Pair<Int,Int>>() // A* search algorithm with Manhattan distance heuristic val open = PriorityQueue<Node>(1000, compareBy { it.cost + it.estimate }) // Change the grid positions to be their elevations grid[startPosition.second][startPosition.first] = 'a' grid[endPosition.second][endPosition.first] = 'z' // Find all the positions of 'a' val aPositions = arrayListOf<Pair<Int,Int>>() for (yPos in grid.indices) { for (xPos in 0 until grid[yPos].size) { val position = Pair(xPos, yPos) if (getLetter(grid, position) == 'a') { aPositions.add(position) } } } // var shortestCost = Int.MAX_VALUE var shortestPosition = Pair(-1,-1) while (aPositions.isNotEmpty()) { val aPosition = aPositions.removeFirst() open.add(Node(aPosition, 0, getHeuristicDistance(aPosition, endPosition))) while (open.isNotEmpty()) { val node = open.remove() if (node.position.equals(endPosition)) { // println("End Goal Found | Cost = ${node.cost}") if (shortestCost > node.cost) { shortestCost = node.cost shortestPosition = node.position } open.clear() positionVisited.clear() break } addVisitedPosition(positionVisited, node.position) expandNode(open, positionVisited, grid, endPosition, node) } } // println("Shortest Distance = ${shortestCost} at Position = ${shortestPosition}") return shortestCost } val input = readInput("Day12") part1(input).println() part2(input).println() }
0
Kotlin
0
0
2698c65af0acd1fce51525737ab50f225d6502d1
6,936
aoc2022
Apache License 2.0
src/Day17.kt
syncd010
324,790,559
false
null
class Day17: Day { private fun convert(input: List<String>) : List<Long> { return input[0].split(",").map { it.toLong() } } override fun solvePartOne(input: List<String>): Int { val view = Intcode(convert(input)) .execute() .map { it.toChar() } .joinToString("") { it.toString() } .trim() .split("\n") return view.mapIndexed { y, row -> if (y == 0 || y == view.size - 1) 0 else { row.mapIndexed { x, c -> if (x == 0 || x == row.length - 1 || c != '#' || view[y - 1][x] != '#' || view[y + 1][x] != '#' || view[y][x - 1] != '#' || view[y][x + 1] != '#') 0 else x * y }.sum() } }.sum() } override fun solvePartTwo(input: List<String>): Int { val computer = Intcode(convert(input)) computer.mem[0] = 2 val commands = ("A , A , B , C , B , C , B , C , C , A \n " + "L , 1 0 , R , 8 , R , 8 \n " + "L , 1 0 , L , 1 2 , R , 8 , R , 1 0 \n " + "R , 1 0 , L , 1 2 , R , 1 0 \n " + "n \n") .split(" ") .map { it[0].toLong() } val out = computer.execute(commands) return out.last().toInt() } }
0
Kotlin
0
0
11c7c7d6ccd2488186dfc7841078d9db66beb01a
1,522
AoC2019
Apache License 2.0
src/Day04.kt
ty-garside
573,030,387
false
{"Kotlin": 75779}
// Day 04 - Camp Cleanup // https://adventofcode.com/2022/day/4 fun main() { infix fun IntRange.fullyContains(that: IntRange) = (this.first <= that.first) && (this.last >= that.last) infix fun IntRange.overlapsWith(that: IntRange) = (this.first >= that.first && this.first <= that.last) || (this.last >= that.first && this.last <= that.last) fun range(it: String): IntRange { val (from, to) = it.split('-') return from.toInt()..to.toInt() } fun parse(it: String): Pair<IntRange, IntRange> { val (first, second) = it.split(',') return range(first) to range(second) // .also { println(it) } } fun part1(input: List<String>): Int { return input .map { parse(it) } .count { it.first fullyContains it.second || it.second fullyContains it.first } } fun part2(input: List<String>): Int { return input .map { parse(it) } .count { it.first overlapsWith it.second || it.second overlapsWith it.first } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) println(part2(input)) } /* --- Day 4: Camp Cleanup --- Space needs to be cleared before the last supplies can be unloaded from the ships, and so several Elves have been assigned the job of cleaning up sections of the camp. Every section has a unique ID number, and each Elf is assigned a range of section IDs. However, as some of the Elves compare their section assignments with each other, they've noticed that many of the assignments overlap. To try to quickly find overlaps and reduce duplicated effort, the Elves pair up and make a big list of the section assignments for each pair (your puzzle input). For example, consider the following list of section assignment pairs: 2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8 For the first few pairs, this list means: Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4), while the second Elf was assigned sections 6-8 (sections 6, 7, 8). The Elves in the second pair were each assigned two sections. The Elves in the third pair were each assigned three sections: one got sections 5, 6, and 7, while the other also got 7, plus 8 and 9. This example list uses single-digit section IDs to make it easier to draw; your actual list might contain larger numbers. Visually, these pairs of section assignments look like this: .234..... 2-4 .....678. 6-8 .23...... 2-3 ...45.... 4-5 ....567.. 5-7 ......789 7-9 .2345678. 2-8 ..34567.. 3-7 .....6... 6-6 ...456... 4-6 .23456... 2-6 ...45678. 4-8 Some of the pairs have noticed that one of their assignments fully contains the other. For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6. In pairs where one assignment fully contains the other, one Elf in the pair would be exclusively cleaning sections their partner will already be cleaning, so these seem like the most in need of reconsideration. In this example, there are 2 such pairs. In how many assignment pairs does one range fully contain the other? Your puzzle answer was 466. --- Part Two --- It seems like there is still quite a bit of duplicate work planned. Instead, the Elves would like to know the number of pairs that overlap at all. In the above example, the first two pairs (2-4,6-8 and 2-3,4-5) don't overlap, while the remaining four pairs (5-7,7-9, 2-8,3-7, 6-6,4-6, and 2-6,4-8) do overlap: 5-7,7-9 overlaps in a single section, 7. 2-8,3-7 overlaps all of the sections 3 through 7. 6-6,4-6 overlaps in a single section, 6. 2-6,4-8 overlaps in sections 4, 5, and 6. So, in this example, the number of overlapping assignment pairs is 4. In how many assignment pairs do the ranges overlap? Your puzzle answer was 865. Both parts of this puzzle are complete! They provide two gold stars: ** */
0
Kotlin
0
0
49ea6e3ad385b592867676766dafc48625568867
4,131
aoc-2022-in-kotlin
Apache License 2.0
grind-75-kotlin/src/main/kotlin/ClimbingStairs.kt
Codextor
484,602,390
false
{"Kotlin": 27206}
/** * You are climbing a staircase. It takes n steps to reach the top. * * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? * * * * Example 1: * * Input: n = 2 * Output: 2 * Explanation: There are two ways to climb to the top. * 1. 1 step + 1 step * 2. 2 steps * Example 2: * * Input: n = 3 * Output: 3 * Explanation: There are three ways to climb to the top. * 1. 1 step + 1 step + 1 step * 2. 1 step + 2 steps * 3. 2 steps + 1 step * * * Constraints: * * 1 <= n <= 45 * @see <a href="https://leetcode.com/problems/climbing-stairs/">LeetCode</a> */ fun climbStairs(n: Int): Int { return when (n) { 1 -> 1 2 -> 2 else -> waysToClimbStairs(n) } } private fun waysToClimbStairs(n: Int): Int { val array = IntArray(n) array[0] = 1 array[1] = 2 for (index in 2..n - 1) { array[index] = array[index - 1] + array[index - 2] } return array[n - 1] }
0
Kotlin
0
0
87aa60c2bf5f6a672de5a9e6800452321172b289
983
grind-75
Apache License 2.0
src/main/kotlin/io/github/kmakma/adventofcode/utils/GeneralUtilities.kt
kmakma
225,714,388
false
null
package io.github.kmakma.adventofcode.utils import java.math.BigInteger /** * Returns lists with elements of the list ordered in all possible ways */ fun <E> List<E>.allPermutations(): List<List<E>> { return allPermutations(unordered = this) } private fun <E> allPermutations(ordered: List<E> = emptyList(), unordered: List<E>): List<List<E>> { if (unordered.size == 1) { return listOf(ordered + unordered.first()) } return unordered.flatMap { allPermutations(ordered + it, unordered - it) } } fun generateStringPermutations(lists: List<List<String>>, maxStringLength: Int = 0): List<String> { val result = mutableListOf<String>() stringPermutations(lists, result, 0, "", maxStringLength) return result } private fun stringPermutations( lists: List<List<String>>, result: MutableList<String>, depth: Int, current: String, maxLength: Int ) { if (depth == lists.size || (maxLength > 0 && current.length >= maxLength)) { result.add(current) return } if (lists[depth].isEmpty()) { stringPermutations(lists, result, depth + 1, current, maxLength) return } for (s in lists[depth]) { stringPermutations(lists, result, depth + 1, current + s, maxLength) } } /** * greatest common divisor * * tip: with a fraction x/y divide by gcd/gcd to get lowest form of x/y */ fun gcd(a: Int, b: Int): Int { return if (b == 0) a else gcd(b, a % b) } /** * greatest common divisor * * tip: with a fraction x/y divide by gcd/gcd to get lowest form of x/y */ fun gcd(a: Long, b: Long): Long { return if (b == 0L) a else gcd(b, a % b) } /** * lowest common multiple */ fun lcm(a: Long, b: Long): Long { return (a * b) / gcd(a, b) } /** * to be used for methods like [List.getOrElse], if a `0` is required as result. Example: * * `list.getOrElse(index, ::else0)` */ @Suppress("UNUSED_PARAMETER") fun else0(x: Int) = 0 /** * planned as a faster alternative to y2019.d16.t2... * But an index of around 523k created a tiny little 1E411 (which didn't even took that long) */ @Suppress("unused") object StupidBigAssNumberCreator { private val factorList = mutableListOf(BigInteger("100")) internal fun getFactor(index: Int): BigInteger { if (factorList.lastIndex < index) { factorList.add(index, getFactor(index - 1) * (100L + index).toBigInteger() / (index + 1).toBigInteger()) } return factorList[index] } } @JvmName("productOfInt") fun Iterable<Int>.product(): Long { var product = 1L for (element in this) { product *= element } return product } @JvmName("productOfLong") fun Iterable<Long>.product(): Long { var product = 1L for (element in this) { product *= element } return product }
0
Kotlin
0
0
7e6241173959b9d838fa00f81fdeb39fdb3ef6fe
2,828
adventofcode-kotlin
MIT License
2022/Day12.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun main() { val input = readInput("Day12").map { it.toCharArray() } val n = input.size val m = input[0].size var source: Pair<Int, Int>? = null var end: Pair<Int, Int>? = null for (i in 0 until n) { for (j in 0 until m) { when (input[i][j]) { 'S' -> { source = i to j input[i][j] = 'a' } 'E' -> { end = i to j input[i][j] = 'z' } } } } require(end != null) require(source != null) val dist = Array(n) { IntArray(m) { Int.MAX_VALUE } } val queue = ArrayDeque<Pair<Int,Int>>() queue.add(end.first to end.second) dist[end.first][end.second] = 0 while (queue.isNotEmpty()) { val (i0, j0) = queue.removeFirst() fun check(i: Int, j: Int) { if (i in 0 until n && j in 0 until m && input[i0][j0] - input[i][j] <= 1 && dist[i][j] > dist[i0][j0] + 1) { queue.add(i to j) dist[i][j] = dist[i0][j0] + 1 } } check(i0, j0+1) check(i0+1, j0) check(i0, j0-1) check(i0-1, j0) } println(dist[source.first][source.second]) var res2 = Int.MAX_VALUE for (i in 0 until n) { for (j in 0 until m) { if (input[i][j] == 'a') { res2 = minOf(res2, dist[i][j]) } } } println(res2) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,490
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/dynamicprogramming/MaximumProductSubarray.kt
e-freiman
471,473,372
false
{"Kotlin": 78010}
package dynamicprogramming fun processSubarray(a: Int, b: Int, negatives: Int, nums: IntArray): Int { if (a > b) { return 0 } if (a == b) { return nums[a] } var i = a var j = b var leftProd = 1 var rightProd = 1 if (negatives % 2 == 1) { while (nums[i] > 0) { leftProd *= nums[i] i++ } while (nums[j] > 0) { rightProd *= nums[j] j-- } if (i == j) { return maxOf(leftProd, rightProd) } return if (-leftProd * nums[i] > -rightProd * nums[j]) { for (k in i..j - 1) { leftProd *= nums[k] } leftProd } else { for (k in j downTo i + 1) { rightProd *= nums[k] } rightProd } } else { var prod = 1 for (k in a..b) { prod *= nums[k] } return prod } } fun maxProduct(nums: IntArray): Int { var maxProd = Int.MIN_VALUE var begin = 0 var negatives = 0 for (i in nums.indices) { if (nums[i] < 0) { negatives++ } if (nums[i] == 0) { val prod = processSubarray(begin, i - 1, negatives, nums) maxProd = maxOf(prod, maxProd, 0) negatives = 0 begin = i + 1 } } val prod = processSubarray(begin, nums.lastIndex, negatives, nums) maxProd = maxOf(prod, maxProd) return maxProd } fun main() { println(maxProduct(intArrayOf(2,3,-2,4))) }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
1,594
LeetcodeGoogleInterview
Apache License 2.0
src/util/algorithms/ConvexHull.kt
JBWills
291,822,812
false
null
package util.algorithms import coordinate.Point import util.algorithms.PointOrientation.Clockwise import util.algorithms.PointOrientation.Colinear import util.algorithms.PointOrientation.CounterClockwise import util.polylines.MutablePolyLine import util.polylines.PolyLine // from: https://www.nayuki.io/res/convex-hull-algorithm/ConvexHull.java // Returns a new list of points representing the convex hull of // the given set of points. The convex hull excludes collinear points. // This algorithm runs in O(n log n) time. fun Iterable<Point>.makeHull(): PolyLine = makeHullPresorted(sorted()) // from: https://www.nayuki.io/res/convex-hull-algorithm/ConvexHull.java // Returns the convex hull, assuming that each points[i] <= points[i + 1]. Runs in O(n) time. fun makeHullPresorted(points: PolyLine): PolyLine { if (points.size <= 1) return points.toList() // Andrew's monotone chain algorithm. Positive y coordinates correspond to "up" // as per the mathematical convention, instead of "down" as per the computer // graphics convention. This doesn't affect the correctness of the result. val upperHull: MutablePolyLine = ArrayList() for (p in points) { while (upperHull.size >= 2) { val q = upperHull[upperHull.size - 1] val r = upperHull[upperHull.size - 2] if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) upperHull.removeAt(upperHull.size - 1) else break } upperHull.add(p) } upperHull.removeAt(upperHull.size - 1) val lowerHull: MutablePolyLine = ArrayList() for (i in points.indices.reversed()) { val p = points[i] while (lowerHull.size >= 2) { val q = lowerHull[lowerHull.size - 1] val r = lowerHull[lowerHull.size - 2] if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) lowerHull.removeAt(lowerHull.size - 1) else break } lowerHull.add(p) } lowerHull.removeAt(lowerHull.size - 1) if (!(upperHull.size == 1 && upperHull == lowerHull)) upperHull.addAll(lowerHull) return upperHull } private enum class PointOrientation { Colinear, Clockwise, CounterClockwise } fun Set<Point>.convexHull(): PolyLine { if (size < 3) return listOf() val hull = mutableListOf<Point>() val leftmostPoint = minByOrNull { it.x } ?: return listOf() var p: Point = leftmostPoint do { hull.add(p) p = minus(p).reduce { acc, point -> if (orientation(p, point, acc) == Clockwise) acc else point } } while (p != leftmostPoint) if (hull.last() != hull.first()) hull.add(hull.last()) return hull } /** * From: https://www.geeksforgeeks.org/convex-hull-set-1-jarviss-algorithm-or-wrapping/ * To find orientation of ordered triplet (p, q, r). * The function returns following values * 0 --> p, q and r are colinear * 1 --> Clockwise * 2 --> Counterclockwise */ private fun orientation(p: Point, q: Point, r: Point): PointOrientation { val v = ( (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y) ).toInt() return when { v == 0 -> Colinear v > 0 -> Clockwise else -> CounterClockwise } }
0
Kotlin
0
0
569b27c1cb1dc6b2c37e79dfa527b9396c7a2f88
3,094
processing-sketches
MIT License
src/day09/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day09 import Coord import day06.main import readInput import kotlin.math.abs import kotlin.math.sign fun main() { fun parse(input: List<String>) = input .map { motion -> val (dir, amount) = motion.split(" ") (1..amount.toInt()).map { when (dir) { "R" -> Coord(it, 0) "L" -> Coord(-it, 0) "U" -> Coord(0, it) else -> Coord(0, -it) } } }.reduce { prevSegment, newSegment -> prevSegment + newSegment.map { (dx, dy) -> val (x, y) = prevSegment.last() Coord(x + dx, y + dy) } } fun Coord.following(head: Coord): Coord { val dx = head.first - first val dy = head.second - second return if (abs(dx) <= 1 && abs(dy) <= 1) { this } else { copy(first + dx.sign, second + dy.sign) } } fun part1(input: List<Coord>) = buildSet { input.fold(Coord(0, 0)) { tail, head -> tail.following(head) .also { add(it) } } }.size fun part2(input: List<Coord>) = buildSet { input.fold(List(9) { Coord(0, 0) }) { tail, head -> tail.runningFold(head) { prev, knot -> knot.following(prev) }.drop(1) //remove the head .also { add(it.last()) } } }.size val input = parse(readInput(::main.javaClass.packageName)) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
1,587
AOC2022
Apache License 2.0
src/main/kotlin/com/sk/topicWise/string/17. Letter Combinations of a Phone Number.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.string class Solution17 { fun letterCombinations(digits: String): List<String> { val map = mapOf( 2 to listOf('a', 'b', 'c'), 3 to listOf('d', 'e', 'f'), 4 to listOf('g', 'h', 'i'), 5 to listOf('j', 'k', 'l'), 6 to listOf('m', 'n', 'o'), 7 to listOf('p', 'q', 'r', 's'), 8 to listOf('t', 'u', 'v'), 9 to listOf('w', 'x', 'y', 'z') ) val res = mutableListOf<String>() if (digits.isNotEmpty()) { dfs(0, StringBuilder(), digits, res, map) } return res } private fun dfs(idx: Int, str: StringBuilder, digits: String, res: MutableList<String>, map: Map<Int, List<Char>>) { if (idx == digits.length) { res.add(str.toString()) return } val value = digits[idx].digitToInt() for (ch in map[value]!!) { dfs(idx + 1, StringBuilder(str).append(ch), digits, res, map) } } fun letterCombinations2(digits: String): List<String> { if (digits.isEmpty()) return emptyList() val map = mapOf( 2 to listOf('a', 'b', 'c'), 3 to listOf('d', 'e', 'f'), 4 to listOf('g', 'h', 'i'), 5 to listOf('j', 'k', 'l'), 6 to listOf('m', 'n', 'o'), 7 to listOf('p', 'q', 'r', 's'), 8 to listOf('t', 'u', 'v'), 9 to listOf('w', 'x', 'y', 'z') ) val q = ArrayDeque<String>() q.addLast("") for (i in digits.indices) { val d = digits[i].digitToInt() while (q.first().length == i) { val s = q.removeFirst() for (ch in map[d]!!) { q.addLast("$s$ch") } } } return q.toList() } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,888
leetcode-kotlin
Apache License 2.0
src/Day10.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
fun main() { fun Int.isInteresting():Int{ if (this in listOf(20, 60, 100, 140, 180, 220)){ return 1 } return 0 } fun part1(input: List<String>): Int { var cycle = 0 var X = 1 var res = 0 for (line in input){ if (line.startsWith("noop")){ cycle += 1 res += cycle.isInteresting()*cycle*X } else{ repeat(2){ cycle += 1 res += cycle.isInteresting()*cycle*X } X += line.split(" ")[1].toInt() } } return res } fun part2(input: List<String>): Int { val CRT = MutableList(6, { MutableList(40, {0}) }) var row: Int var col: Int var cycle = 0 var X = 1 for (line in input){ if (line.startsWith("noop")){ row = cycle / 40 col = cycle % 40 cycle += 1 if (kotlin.math.abs(X-col) <= 1){ CRT[row][col] += 1 } } else{ repeat(2) { row = cycle / 40 col = cycle % 40 cycle += 1 if (kotlin.math.abs(X - col) <= 1) { CRT[row][col] += 1 } } X += line.split(" ")[1].toInt() } } for (line in CRT){ println(line.map { when(it){ 0 -> "." else -> "#" } }.joinToString(separator = "")) } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") val input = readInput("Day10") check(part1(testInput) == 13140) println(part1(input)) part2(input) }
0
Kotlin
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
1,945
aoc22
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2022/day18/day18.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day18 import biz.koziolek.adventofcode.Coord3d import biz.koziolek.adventofcode.findInput import biz.koziolek.adventofcode.getAdjacentCoords import java.util.ArrayDeque import java.util.Queue fun main() { val inputFile = findInput(object {}) val droplet = parseDroplet(inputFile.bufferedReader().readLines()) println("Droplet surface area: ${getSurfaceArea(droplet)}") val lavaAirMap = mapOutside(droplet) println("Droplet outside surface area: ${getOutsideSurfaceArea(lavaAirMap)}") } fun parseDroplet(lines: Iterable<String>): Set<Coord3d> = lines.map { Coord3d.fromString(it) }.toSet() fun getSurfaceArea(droplet: Set<Coord3d>): Int = droplet.sumOf { 6 - droplet.getAdjacentCoords(it).size } const val LAVA = 'L' const val OUTSIDE = 'O' fun mapOutside(droplet: Set<Coord3d>): Map<Coord3d, Char> = buildMap { putAll(droplet.map { it to LAVA }) val minX = droplet.minOf { it.x } val maxX = droplet.maxOf { it.x } val minY = droplet.minOf { it.y } val maxY = droplet.maxOf { it.y } val minZ = droplet.minOf { it.z } val maxZ = droplet.maxOf { it.z } val xRange = (minX - 1)..(maxX + 1) val yRange = (minY - 1)..(maxY + 1) val zRange = (minZ - 1)..(maxZ + 1) val toCheck: Queue<Coord3d> = ArrayDeque() fun shouldBeChecked(coord: Coord3d) = coord.x in xRange && coord.y in yRange && coord.z in zRange && !contains(coord) && !toCheck.contains(coord) for (x in (minX-1)..(maxX+1)) { for (y in (minY - 1)..(maxY + 1)) { val coord = Coord3d(x, y, z = minZ - 1) put(coord, OUTSIDE) coord.getAdjacentCoords() .filter { shouldBeChecked(it) } .forEach { toCheck.add(it) } } } while (toCheck.isNotEmpty()) { val coord = toCheck.poll() val adjCoords = coord.getAdjacentCoords() if (adjCoords.any { get(it) == OUTSIDE }) { put(coord, OUTSIDE) } adjCoords .filter { shouldBeChecked(it) } .forEach { toCheck.add(it) } } } fun getOutsideSurfaceArea(lavaAirMap: Map<Coord3d, Char>): Int = lavaAirMap .filterValues { it == LAVA } .keys .sumOf { coord -> lavaAirMap.keys.getAdjacentCoords(coord).count { adjCoord -> lavaAirMap[adjCoord] == OUTSIDE } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,643
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxAncestorDiff.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.abs import kotlin.math.max import kotlin.math.min /** * 1026. Maximum Difference Between Node and Ancestor * @see <a href="https://leetcode.com/problems/maximum-difference-between-node-and-ancestor"> * Source</a> */ fun interface MaxAncestorDiff { operator fun invoke(root: TreeNode?): Int } /** * Approach #1: Recursion */ class MaxAncestorDiffRecursion : MaxAncestorDiff { // record the required maximum difference var result = 0 override operator fun invoke(root: TreeNode?): Int { if (root == null) { return 0 } result = 0 helper(root, root.value, root.value) return result } private fun helper(node: TreeNode?, curMax: Int, curMin: Int): Int { var cMax = curMax var cMin = curMin if (node == null) { return 0 } val possibleResult: Int = max(abs(cMax - node.value), abs(cMin - node.value)) result = max(result, possibleResult) cMax = max(cMax, node.value) cMin = min(cMin, node.value) helper(node.left, cMax, cMin) helper(node.right, cMax, cMin) return result } } /** * Approach #2: Maximum Minus Minimum */ class MaxAncestorDiffMM : MaxAncestorDiff { override operator fun invoke(root: TreeNode?): Int { return if (root == null) { 0 } else { helper(root, root.value, root.value) } } fun helper(node: TreeNode?, curMax: Int, curMin: Int): Int { // if encounter leaves, return the max-min along the path var cMax = curMax var cMin = curMin if (node == null) { return cMax - cMin } // else, update max and min // and return the max of left and right subtrees cMax = max(cMax, node.value) cMin = min(cMin, node.value) val left = helper(node.left, cMax, cMin) val right = helper(node.right, cMax, cMin) return max(left, right) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,663
kotlab
Apache License 2.0
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day18/Vault.kt
jrhenderson1988
289,786,400
false
{"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37}
package com.github.jrhenderson1988.adventofcode2019.day18 import com.github.jrhenderson1988.adventofcode2019.common.Direction import com.github.jrhenderson1988.adventofcode2019.common.bfs import kotlin.math.min class Vault( grid: Set<Pair<Int, Int>>, private val keys: Map<Char, Pair<Int, Int>>, private val doors: Map<Char, Pair<Int, Int>>, private val positions: Set<Pair<Int, Int>> ) { private val cells = optimise(grid) private val positionsToKeys = positions.map { position -> getPathsBetweenKeys(position, keys) } private val keysToKeys = keys.map { k -> k.key to getPathsBetweenKeys(k.value, keys.filter { it.key != k.key }) }.toMap() private val cache = mutableMapOf<Pair<List<Char?>, Set<Char>>, Int>() fun shortestPathToCollectAllKeys( robotKeys: List<Char?> = positions.map { null }, collectedKeys: Set<Char> = setOf() ): Int { if (collectedKeys.size == keys.size) { return 0 } val cacheKey = Pair(robotKeys, collectedKeys) if (cache.containsKey(cacheKey)) { return cache[cacheKey]!! } var best = Int.MAX_VALUE val potentialMoves: List<Map<Char, Path>> = robotKeys.mapIndexed { robot, key -> reachablePaths( if (key == null) positionsToKeys[robot] else keysToKeys[key] ?: error("Can't find path from key $key"), collectedKeys ) } potentialMoves.forEachIndexed { robot, paths -> paths.forEach { p -> best = min( best, p.value.size + shortestPathToCollectAllKeys( robotKeys.mapIndexed { index, key -> if (index == robot) p.key else key }, collectedKeys.union(p.value.keys) ) ) } } cache[cacheKey] = best return best } @Suppress("UNCHECKED_CAST") private fun getPathsBetweenKeys(from: Pair<Int, Int>, keys: Map<Char, Pair<Int, Int>>): Map<Char, Path> = keys.map { it.key to getPathBetween(from, it.value) } .filter { it.second != null } .toMap() as Map<Char, Path> private fun getPathBetween(a: Pair<Int, Int>, b: Pair<Int, Int>): Path? { val path = bfs(a, b) { Direction.neighboursOf(it).filter { p -> p in cells } } return if (path != null) { Path(path.drop(1).toSet(), doors, keys) } else { null } } private fun reachablePaths(paths: Map<Char, Path>, collectedKeys: Set<Char>) = paths.filter { it.value.doors.subtract(collectedKeys).isEmpty() && it.key !in collectedKeys } override fun toString(): String = (0..cells.map { it.second }.max()!! + 1).joinToString("\n") { y -> (0..cells.map { it.first }.max()!! + 1).joinToString("") { x -> when (Pair(x, y)) { in positions -> "@" in keys.values -> keys.filter { it.value == Pair(x, y) }.keys.first().toString() in doors.values -> doors.filter { it.value == Pair(x, y) }.keys.first().toString().toUpperCase() in cells -> "." else -> "#" } } } private fun optimise(paths: Set<Pair<Int, Int>>): Set<Pair<Int, Int>> { val optimised = paths.toMutableSet() while (true) { val deadEnds = findDeadEnds(optimised) if (deadEnds.isEmpty()) { return optimised } optimised.removeAll(deadEnds) } } private fun findDeadEnds(paths: Set<Pair<Int, Int>>) = paths.filter { pos -> isDeadEnd(pos, paths) } private fun isDeadEnd(pos: Pair<Int, Int>, paths: Set<Pair<Int, Int>>) = Direction.neighboursOf(pos).filter { neighbour -> neighbour in paths }.size == 1 && isOpenCell(pos, paths) private fun isOpenCell(pos: Pair<Int, Int>, paths: Set<Pair<Int, Int>>) = pos in paths && pos !in positions && pos !in keys.values && pos !in doors.values companion object { fun parse(input: String, quadrants: Boolean = false): Vault { val grid = mutableSetOf<Pair<Int, Int>>() var initialPosition: Pair<Int, Int>? = null val keys = mutableMapOf<Char, Pair<Int, Int>>() val doors = mutableMapOf<Char, Pair<Int, Int>>() input.trim().split('\n').forEachIndexed { y, line -> line.forEachIndexed { x, char -> val pos = Pair(x, y) if (char == '@') { initialPosition = pos grid.add(pos) } else if (char.isLetter() && char.isUpperCase()) { doors[char.toLowerCase()] = pos grid.add(pos) } else if (char.isLetter()) { keys[char] = pos grid.add(pos) } else if (char == '.') { grid.add(pos) } } } val positions = if (quadrants) { setOf(Pair(-1, 0), Pair(0, -1), Pair(1, 0), Pair(0, 1), Pair(0, 0)).forEach { grid.remove(Pair(initialPosition!!.first + it.first, initialPosition!!.second + it.second)) } setOf(Pair(-1, -1), Pair(1, -1), Pair(1, 1), Pair(-1, 1)).map { val pos = Pair(initialPosition!!.first + it.first, initialPosition!!.second + it.second) grid.add(pos) pos }.toSet() } else { setOf(initialPosition!!) } return Vault(grid, keys, doors, positions) } } }
0
Kotlin
0
0
7b56f99deccc3790c6c15a6fe98a57892bff9e51
5,858
advent-of-code
Apache License 2.0
src/Day2.kt
devPalacio
574,493,024
false
{"Kotlin": 8009, "Python": 1346}
import java.io.File fun main() { val input = File("src/day2.txt").readText().trim() val games = input.split(System.lineSeparator()) .map { game -> game.split(" ") } .map { it[0].first() to it[1].first() } fun getTotalPoints(games: List<Pair<Char,Char>>) = games.sumOf { val shapeScore = getShapeScore(it.second) val outcomeScore = getOutcomeScore(it) shapeScore + outcomeScore } val totalPointsWithStrat = getTotalPoints(games.map(::getRightMove)) println(getTotalPoints(games)) println(totalPointsWithStrat) } fun getShapeScore(letter: Char): Int = when (letter) { 'X' -> 1 // rock 'Y' -> 2 // paper 'Z' -> 3 // scissors else -> throw Exception("Not a valid shape") } fun getOutcomeScore(game: Pair<Char, Char>): Int { when (game.first) { 'A' -> { return when (game.second) { 'X' -> 3 // draw 'Y' -> 6 // win 'Z' -> 0 // loss else -> throw Exception("Not a valid outcome") } } 'B' -> { return when (game.second) { 'X' -> 0 // paper vs rock 'Y' -> 3 // paper vs paper 'Z' -> 6 // paper vs scissor else -> throw Exception("Not a valid outcome") } } 'C' -> { return when (game.second) { 'X' -> 6 // scissor vs rock 'Y' -> 0 // scissor vs paper 'Z' -> 3 // scissor vs scissor else -> throw Exception("Not a valid outcome") } } else -> throw java.lang.Exception("Not a valid outcome") } } fun getRightMove(game: Pair<Char, Char>): Pair<Char, Char> { return when (game.second) { // X means lose, we need to look at first and pick what loses 'X' -> game.copy(second = loseStratMap[game.first]!!) 'Y' -> game.copy(second = tieStratMap[game.first]!!) 'Z' -> game.copy(second = winStratMap[game.first]!!) else -> throw java.lang.Exception("Invalid Game") } } val loseStratMap = mapOf('A' to 'Z', 'B' to 'X', 'C' to 'Y') val tieStratMap = mapOf('A' to 'X', 'B' to 'Y', 'C' to 'Z') val winStratMap = mapOf('A' to 'Y', 'B' to 'Z', 'C' to 'X')
0
Kotlin
0
0
648755244e07887335d05601b5fe78bdcb8b1baa
2,358
AoC-2022
Apache License 2.0
dcp_kotlin/src/main/kotlin/dcp/day194/day194.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day194 // day194.kt // By <NAME>, 2019. typealias PointType = Int typealias Segment = Pair<PointType, PointType> typealias Points = List<PointType> /** * Given a set of 2n points of the form (p_i, 0) and (q_i, 1) for i in [0,n), determine the number of line segments * of the form (p_i, 0) to (q_i, 0) that intersect. * * @param ps The x coordinates of the points of the form (p_i, 0): must have same size as qs * @param qs The x coordinates of the points of the form (q_i, 0): must have same size as ps * @return the number of intersections * * @sample countIntersections(listOf(0, 2, 5, 6), listOf(1, 3, 4, 5)) */ fun countIntersections(ps: Points, qs: Points): Int { val n = ps.size assert(ps.size == qs.size) {"ps and qs must have same size (ps.size =${ps.size}, qs.size=${qs.size}"} infix fun Segment.intersect(other: Segment): Boolean { val (p1, q1) = this val (p2, q2) = other return if (p1 <= p2 && q1 >= q2) true else p1 >= p2 && q1 <= q2 } val points = sequence { for (i in 0 until n) yield (ps[i] to qs[i]) }.toList() val intervals = sequence { for (i1 in 0 until n) for (i2 in (i1 + 1) until n) yield(points[i1] to points[i2]) } return intervals.count{ (i1, i2) -> i1 intersect i2} }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
1,360
daily-coding-problem
MIT License
src/day03/Day03.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day03 import readInput fun main() { val priority = buildMap { ('a'..'z').forEachIndexed { i, c -> put(c, i + 1) } ('A'..'Z').forEachIndexed { i, c -> put(c, i + 27) } } fun part1(input: List<String>): Int { return input.sumOf { line -> val c1 = line.substring(0, line.length / 2) val c2 = line.substring(line.length / 2, line.length) val commonItems = c1.asIterable().intersect(c2.asIterable().toSet()) commonItems.sumOf { priority[it]!! } } } fun part2(input: List<String>): Int { return input.windowed(3, 3) { (g1, g2, g3) -> val commonBadge = g1.asIterable().intersect(g2.asIterable().toSet()).intersect(g3.asIterable().toSet()).first() priority[commonBadge]!! }.sum() } val testInput = readInput("day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("day03") println(part1(input)) // 8123 println(part2(input)) // 2620 }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
1,069
advent-of-code-2022
Apache License 2.0
stepik/sportprogramming/LongestCommonSubsequenceDynamicProgramming.kt
grine4ka
183,575,046
false
{"Kotlin": 98723, "Java": 28857, "C++": 4529}
package stepik.sportprogramming import java.io.File import java.io.PrintWriter import java.util.* import kotlin.math.max fun main() { output { val n = readInt() val a = readIntArray(n) val m = readInt() val b = readIntArray(m) val d = Array(n + 1) { IntArray(m + 1) } for (i in 0..n) { d[i][0] = 0 } for (j in 0..m) { d[0][j] = 0 } val path = Array(n + 1) { IntArray(m + 1) } for (i in 1..n) { for (j in 1..m) { if (d[i - 1][j] > d[i][j - 1]) { d[i][j] = d[i - 1][j] path[i][j] = d[i-1][j] } else { d[i][j] = d[i][j - 1] path[i][j] = d[i][j - 1] } if (a[i - 1] == b[j - 1] && (d[i - 1][j - 1] + 1 > d[i][j])) { d[i][j] = d[i - 1][j - 1] + 1 path[i][j] = d[i - 1][j - 1] + 1 } } } println("Longest common subsequence is ${d[n][m]}") println("Path of longest subsequence is ") recout(path, a, n, m) } } private fun PrintWriter.recout(p: Array<IntArray>, a: IntArray, i: Int, j: Int) { if (i <= 0 || j <= 0) { return } when { p[i][j] == p[i - 1][j] -> recout(p, a, i - 1, j) p[i][j] == p[i][j - 1] -> recout(p, a, i, j - 1) else -> { recout(p, a, i - 1, j - 1) print("${a[i - 1]} ") } } } /** IO code start */ //private val INPUT = System.`in` private val INPUT = File("stepik/sportprogramming/seq2.in").inputStream() private val OUTPUT = System.out private val reader = INPUT.bufferedReader() private var tokenizer: StringTokenizer = StringTokenizer("") private fun read(): String { if (tokenizer.hasMoreTokens().not()) { tokenizer = StringTokenizer(reader.readLine() ?: return "", " ") } return tokenizer.nextToken() } private fun readLn() = reader.readLine()!! private fun readInt() = read().toInt() private fun readIntArray(n: Int) = IntArray(n) { read().toInt() } private val writer = PrintWriter(OUTPUT, false) private inline fun output(block: PrintWriter.() -> Unit) { writer.apply(block).flush() }
0
Kotlin
0
0
c967e89058772ee2322cb05fb0d892bd39047f47
2,310
samokatas
MIT License
leetcode-75-kotlin/src/main/kotlin/ProductOfArrayExceptSelf.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * Given an integer array nums, * return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. * * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. * * You must write an algorithm that runs in O(n) time and without using the division operation. * * * * Example 1: * * Input: nums = [1,2,3,4] * Output: [24,12,8,6] * Example 2: * * Input: nums = [-1,1,0,-3,3] * Output: [0,0,9,0,0] * * * Constraints: * * 2 <= nums.length <= 105 * -30 <= nums[i] <= 30 * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. * * * Follow up: Can you solve the problem in O(1) extra space complexity? * (The output array does not count as extra space for space complexity analysis.) * @see <a href="https://leetcode.com/problems/product-of-array-except-self/">LeetCode</a> */ fun productExceptSelf(nums: IntArray): IntArray { val outputArray = IntArray(nums.size) var productBefore = 1 for (index in nums.indices) { outputArray[index] = productBefore productBefore *= nums[index] } var productAfter = 1 for (index in nums.indices.reversed()) { outputArray[index] *= productAfter productAfter *= nums[index] } return outputArray }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,327
leetcode-75
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-17.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.IntGrid import com.github.ferinagy.adventOfCode.get import com.github.ferinagy.adventOfCode.isIn import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import com.github.ferinagy.adventOfCode.rotateCcw import com.github.ferinagy.adventOfCode.rotateCw import com.github.ferinagy.adventOfCode.searchGraph import com.github.ferinagy.adventOfCode.toIntGrid fun main() { val input = readInputLines(2023, "17-input") val test1 = readInputLines(2023, "17-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val grid = input.map { line -> line.map { it.digitToInt() } }.toIntGrid() return navigateCrucible(grid, 0, 3) } private fun part2(input: List<String>): Int { val grid = input.map { line -> line.map { it.digitToInt() } }.toIntGrid() return navigateCrucible(grid, 4, 10) } private fun navigateCrucible(grid: IntGrid, minStraight: Int, maxStraight: Int) = searchGraph( startingSet = setOf(Triple(Coord2D(0, 0), Coord2D(0, 1), 0), Triple(Coord2D(0, 0), Coord2D(1, 0), 0)), isDone = { it.first.x == grid.xRange.last && it.first.y == grid.yRange.last && minStraight <= it.third }, nextSteps = { (pos, dir, s) -> buildSet { val left = dir.rotateCw() val c1 = pos + left if (minStraight <= s && c1.isIn(grid.xRange, grid.yRange)) this += Triple(c1, left, 1) to grid[c1] val right = dir.rotateCcw() val c2 = pos + right if (minStraight <= s && c2.isIn(grid.xRange, grid.yRange)) this += Triple(c2, right, 1) to grid[c2] val c3 = pos + dir if (c3.isIn(grid.xRange, grid.yRange) && s < maxStraight) this += Triple(c3, dir, s + 1) to grid[c3] } }, heuristic = { Coord2D(grid.xRange.last, grid.yRange.last).distanceTo(it.first) } )
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,141
advent-of-code
MIT License
kotlin/graphs/shortestpaths/BellmanFord.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.shortestpaths import java.util.stream.Stream object BellmanFord { val INF: Int = Integer.MAX_VALUE / 2 fun bellmanFord(graph: Array<List<Edge>>, s: Int, dist: IntArray, pred: IntArray): Boolean { Arrays.fill(pred, -1) Arrays.fill(dist, INF) dist[s] = 0 val n = graph.size for (step in 0 until n) { var updated = false for (u in 0 until n) { if (dist[u] == INF) continue for (e in graph[u]) { if (dist[e.v] > dist[u] + e.cost) { dist[e.v] = dist[u] + e.cost dist[e.v] = Math.max(dist[e.v], -INF) pred[e.v] = u updated = true } } } if (!updated) return true } // a negative cycle exists return false } fun findNegativeCycle(graph: Array<List<Edge>>): IntArray? { val n = graph.size val pred = IntArray(n) Arrays.fill(pred, -1) val dist = IntArray(n) var last = -1 for (step in 0 until n) { last = -1 for (u in 0 until n) { if (dist[u] == INF) continue for (e in graph[u]) { if (dist[e.v] > dist[u] + e.cost) { dist[e.v] = dist[u] + e.cost dist[e.v] = Math.max(dist[e.v], -INF) pred[e.v] = u last = e.v } } } if (last == -1) return null } for (i in 0 until n) { last = pred[last] } val p = IntArray(n) var cnt = 0 var u = last while (u != last || cnt == 0) { p[cnt++] = u u = pred[u] } val cycle = IntArray(cnt) for (i in cycle.indices) { cycle[i] = p[--cnt] } return cycle } // Usage example fun main(args: Array<String?>?) { val graph: Array<List<Edge>> = Stream.generate { ArrayList() }.limit(4).toArray { _Dummy_.__Array__() } graph[0].add(Edge(1, 1)) graph[1].add(Edge(0, 1)) graph[1].add(Edge(2, 1)) graph[2].add(Edge(3, -10)) graph[3].add(Edge(1, 1)) val cycle = findNegativeCycle(graph) System.out.println(Arrays.toString(cycle)) } class Edge(val v: Int, val cost: Int) }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
2,517
codelibrary
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxProfitWithFee.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 kotlin.math.max /** * 714. Best Time to Buy and Sell Stock with Transaction Fee * @see <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee">Source</a> */ fun interface MaxProfitWithFee { fun maxProfit(prices: IntArray, fee: Int): Int } /** * Approach 1: Dynamic Programming */ class MaxProfitWithFeeDP : MaxProfitWithFee { override fun maxProfit(prices: IntArray, fee: Int): Int { val n: Int = prices.size val free = IntArray(n) val hold = IntArray(n) // In order to hold a stock on day 0, we have no other choice but to buy it for prices[0]. hold[0] = -prices[0] for (i in 1 until n) { hold[i] = max(hold[i - 1], free[i - 1] - prices[i]) free[i] = max(free[i - 1], hold[i - 1] + prices[i] - fee) } return free[n - 1] } } /** * Approach 2: Space-Optimized Dynamic Programming */ class MaxProfitWithFeeSpaceOptimizedDP : MaxProfitWithFee { override fun maxProfit(prices: IntArray, fee: Int): Int { val n: Int = prices.size var free = 0 var hold = -prices[0] for (i in 1 until n) { val tmp = hold hold = max(hold, free - prices[i]) free = max(free, tmp + prices[i] - fee) } return free } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,984
kotlab
Apache License 2.0
src/main/kotlin/asaad/DaySeven.kt
Asaad27
573,138,684
false
{"Kotlin": 23483}
package asaad import java.io.File private const val MAX_STORAGE = 70000000 private const val REQUIRED_STORAGE = 30000000 private const val PART1 = 100000 class DaySeven(filePath: String) { private val file = File(filePath) private val input = readInput(file) private var lineNumber = 0 private fun readInput(file: File) = file.bufferedReader().readLines() fun result() { val head = Node(name = "head") val root = Node(name = "/") head.children.add(root) createFileTree(head) val dirSizes = mutableListOf<Int>() getDirsSizes(root, sizes = dirSizes) dirSizes.sort() println("\tpart 1: ${solve1(dirSizes)}") println("\tpart 2: ${solve2(root, dirSizes)}") } /** * Time complexity: O(Log(N)) where N is the number of directories */ private fun solve2(root: Node, sizes: MutableList<Int>): Int { val used = root.dirSize val available = MAX_STORAGE - used if (available >= REQUIRED_STORAGE) return 0 var answer = 0 var (left, right) = listOf(0, sizes.size - 1) while (left <= right) { val mid = left + (right - left) / 2 val current = sizes[mid] if (available >= REQUIRED_STORAGE - current) { answer = current right = mid - 1 } else { left = mid + 1 } } return answer } /** * @param sizes: the list where the directory sizes will be appended * gets the list of directory sizes * Space Complexity : O(N) where N is the number of directories */ private fun getDirsSizes(node: Node, sizes: MutableList<Int>) { sizes.add(node.dirSize) for (child in node.children) getDirsSizes(child, sizes) } /** * Time Complexity: O(N) where N is the number of directories */ private fun solve1(dirSizes: List<Int>) = dirSizes.takeWhile { it <= PART1 }.sum() /** * Creates a dir tree, and computes the size of each directory * Time Complexity: O(M) where M is the number of lines */ private fun createFileTree(current: Node): Int { var nextLine = input.readNext() val nodes = HashMap<String, Node>() while (nextLine != null) { when { nextLine.startsWith("$") -> { val command = parseCommand(nextLine) when (command.first) { Command.LS -> {} Command.GOTO -> { val dirNode = command.second!! if (dirNode == "/") nodes[dirNode] = current.children.first() current.dirSize += createFileTree(nodes[dirNode]!!) } Command.BACK -> return current.dirSize } } nextLine.startsWith("dir") -> { val dirName = nextLine.split(" ")[1] val dirNode = Node(name = dirName) nodes[dirName] = dirNode current.children.add(dirNode) } nextLine[0].isDigit() -> { val fileSize = nextLine.split(" ")[0].toInt() current.dirSize += fileSize } else -> { throw Exception("unable to parse line $nextLine") } } nextLine = input.readNext() } return current.dirSize } private fun parseCommand(line: String): Pair<Command, String?> { val split = line.split(" ") return when { split.size > 1 && split[1] == "ls" -> Command.LS to null split.size > 2 && split[1] == "cd" && split[2] == ".." -> Command.BACK to null split.size > 2 && split[1] == "cd" -> Command.GOTO to split[2] else -> throw Exception("unknown command $line") } } enum class Command { GOTO, BACK, LS } data class Node( var name: String, var dirSize: Int = 0, var children: MutableList<Node> = mutableListOf(), ) private fun <E> List<E>.readNext(): String? { if (lineNumber > size - 1) return null return input[lineNumber].also { lineNumber++ } } }
0
Kotlin
0
0
16f018731f39d1233ee22d3325c9933270d9976c
4,478
adventOfCode2022
MIT License
src/day07/Day07.kt
sophiepoole
573,708,897
false
null
package day07 import readInput fun main() { // val input = readInput("day07/input_test") val input = readInput("day07/input") val day = Day07() val fileSystem = day.parse(input) println("Part 1: ${day.part1(fileSystem)}") println("Part 2: ${day.part2(fileSystem)}") } sealed class Component data class File(val name: String, val size: Int) : Component() class Directory( var name: String, var parent: Directory? = null, var children: MutableMap<String, Component> = mutableMapOf(), var size: Int = 0 ) : Component() { fun updateSize(a : Int){ size += a parent?.updateSize(a) } } class Day07 { val totalSize = 70000000 val updateSize = 30000000 fun parse(input: List<String>): MutableList<Directory> { val root = Directory("/") var current = root val allDirectories = mutableListOf(root) for (line in input) { val split = line.split(" ") if (split[0] == "$") { if (split[1] == "cd") { current = when (split[2]) { ".." -> current.parent!! "/" -> root else -> { current.children[split[2]] as Directory } } } } else if (split[0] == "dir") { val directory = Directory(split[1], parent = current) current.children[split[1]] = directory allDirectories.add(directory) } else { current.children[split[0]] = File(split[1], split[0].toInt()) current.updateSize(split[0].toInt()) } } return allDirectories } fun part1(allDirectories: List<Directory>): Int { return allDirectories.filter { it.size <= 100000 }.sumOf { it.size } } fun part2(allDirectories: List<Directory>): Int { val freeSpace = 70000000 - allDirectories.first { it.name == "/" }.size val toFind = 30000000 - freeSpace return allDirectories.filter { it.size >= toFind }.minOf { it.size } } }
0
Kotlin
0
0
00ad7d82cfcac2cb8a902b310f01a6eedba985eb
2,173
advent-of-code-2022
Apache License 2.0
src/Day10.kt
jinie
572,223,871
false
{"Kotlin": 76283}
class Day10 { private var cycle = 0 private fun regX() = 1 + pendingInstructions.filter { it.first < cycle }.sumOf { it.second } private var pendingInstructions = mutableListOf<Pair<Int, Int>>() private fun runInstruction(instruction: String): Int { var cycles = 0 when (instruction.substring(0, 4)) { "addx" -> { cycles = 2 pendingInstructions.add(Pair(cycle + 2, instruction.substring(5).toInt())) } "noop" -> cycles = 1 } return cycles } fun part1(input: List<String>): Int { var ret = 0 input.forEach { for (i in 0 until runInstruction(it)) { cycle++ if (cycle in intArrayOf(20, 60, 100, 140, 180, 220)) { ret += (cycle * regX()) } } } return ret } fun part2(input: List<String>) { val displayLines = mutableListOf<String>() var currentLine = "" fun displayPos() = (cycle-1) % 40 input.forEach { for (i in 0 until runInstruction(it)) { cycle++ currentLine += if(regX() in intArrayOf(displayPos()-1, displayPos(), displayPos()+1)) "#" else " " if(cycle % 40 == 0){ check(currentLine.length == 40) displayLines.add(currentLine) currentLine = "" } } } displayLines.forEach { println(it) } } } fun main() { val testInput = readInput("Day10_test") check(Day10().part1(testInput) == 13140) measureTimeMillisPrint { val input = readInput("Day10") println(Day10().part1(input)) Day10().part2(input) } }
0
Kotlin
0
0
4b994515004705505ac63152835249b4bc7b601a
1,858
aoc-22-kotlin
Apache License 2.0
src/day16/Day16.kt
easchner
572,762,654
false
{"Kotlin": 104604}
package day16 import readInputString import java.util.PriorityQueue import kotlin.math.max import kotlin.math.pow import kotlin.system.measureNanoTime data class Connection (val label: String, var distance: Int) data class Valve( val label: String, val flowRate: Int, val connections: MutableList<Connection>, var open: Boolean ) fun main() { fun findShortestPath(graph: List<Valve>, start: String, target: String): Int { val q = PriorityQueue<Pair<Valve, Int>> { t1, t2 -> t1.second - t2.second} q.add(Pair(graph.find { it.label == start }!!, 0)) while (q.isNotEmpty()) { val next = q.remove() // There's no connection - whooaaaOhhhhhOooohhhhaaaaa if (next.second > 30) { return -1 } if (next.first.label == target) { return next.second } for (c in next.first.connections) { q.add(Pair(graph.find { it.label == c.label }!!, c.distance + next.second)) } } return -1 } fun getValveGraph(input: List<String>): List<Valve> { val valves = mutableListOf<Valve>() val regex = Regex("-*\\d+") val head = "AA" //input[0].substring(6, 8) // Valve AA has flow rate=0; tunnels lead to valves DD, II, BB for (line in input) { valves.add(Valve( label = line.substring(6, 8), flowRate = regex.find(line)!!.value.toInt(), connections = line.substringAfter("valve").substringAfter(" ").split(", ").map { Connection(it, 1) }.toMutableList(), open = false )) } var reduce = true while (reduce) { reduce = false for (v in valves) { // If it links to a valve with flow of 0, remove link and replace with bigger link val newConnections = mutableListOf<Connection>() for (c in v.connections) { val connected = valves.find { it.label == c.label }!! if (connected.flowRate == 0) { for (n in connected.connections) { newConnections.add(Connection(n.label, n.distance + c.distance)) } reduce = true } else { newConnections.add(c) } } v.connections.clear() v.connections.addAll(newConnections) // Clear out paths just back to self v.connections.removeIf { it.label == v.label } } // Clear out valves that are now skippable val newValves = mutableListOf<Valve>() for (v in valves) { val refs = valves.filter { r -> r.connections.map { c -> c.label }.contains(v.label) }.count() if (v.label == head || refs > 0) { newValves.add(v) } } valves.clear() valves.addAll(newValves) // Pull out duplicates to same node for (v in valves) { val newConnections = mutableListOf<Connection>() for (c in v.connections) { if (newConnections.count { it.label == c.label} == 0) { val min = v.connections.filter { it.label == c.label }.minBy { it.distance }.distance newConnections.add(Connection(c.label, min)) } } v.connections.clear() v.connections.addAll(newConnections) // Simplifies later logic if we just assume all bad valves are already open if (v.flowRate == 0) { v.open = true } } } // For each pair of valves, store just the shortest path for (v in valves) { val newConnections = mutableListOf<Connection>() for (c in valves) { if (c.label != v.label && c.label != head) { val shortest = findShortestPath(valves, v.label, c.label) if (shortest > 0) { newConnections.add(Connection(c.label, shortest)) } } } v.connections.clear() v.connections.addAll(newConnections) } return valves } val transpositionTable = hashMapOf<String, Int>() var bestSeen = 0 fun traverse(graph: List<Valve>, head: String, time: Int, priorPoints: Int, direct: Boolean = false): Int { var maxOutput = 0 val closed = graph.filter { !it.open } // End conditions, out of time, nothing left to open, can't possibly increase score if (time <= 0 || closed.isEmpty() || closed.sumOf { it.flowRate * (time - 1) } + priorPoints < bestSeen) { return 0 } // Have we been in this same situation before? // We only care about our location, closed valves, and time left val key = closed.joinToString("") { it.label } + " " + head + " " + time.toString() val pts = transpositionTable[key] if (pts != null) { return pts } val current = graph.find { it.label == head }!! // If we're closed, try opening if (current.flowRate > 0 && !current.open) { current.open = true val thisPoints = (time - 1) * current.flowRate maxOutput = max(maxOutput, (thisPoints + traverse(graph, head, time - 1, thisPoints + priorPoints))) current.open = false } // If we took an express route directly here, don't traverse without opening if (!direct) { // Find all open targets (each closed valve with flow) val closedValves = graph.filter { !it.open && it.label != current.label } for (v in closedValves) { val shortest = current.connections.find { it.label == v.label }!!.distance // Do we even have time to bother? if (shortest + 1 < time) { // If we were better off opening this one we can prune if (current.open || (v.flowRate * (time - 1 - shortest)) > (current.flowRate * time - 1)) { // If all remaining valves were opened immediately, could we possibly improve our max output? val bestRemaining = closedValves.sumOf { it.flowRate * (time - shortest - 1) } if (bestRemaining > maxOutput) { maxOutput = max(maxOutput, traverse(graph, v.label, time - shortest, priorPoints, true)) } } } } } transpositionTable[key] = maxOutput bestSeen = max(bestSeen, maxOutput) return maxOutput } fun part1(input: List<String>): Int { val graph = getValveGraph(input) val output = traverse(graph, "AA", 30, 0) return output } fun part2(input: List<String>): Int { val graph = getValveGraph(input).toMutableList() var maxOut = 0 val head = graph.find { it.label == "AA" } graph.remove(head) graph.add(head!!) // Divide nodes into two groupings, run both independently and add for (combo in 0 until (2.0.pow((graph.size - 1).toDouble())).toInt() / 2) { for (i in 0 until graph.size) { graph[i].open = combo shr i and 1 == 1 } graph.find { it.label == "AA" }!!.open = true var output = traverse(graph, "AA", 26, 0) bestSeen = 0 for (n in graph) { n.open = !n.open } graph.find { it.label == "AA" }!!.open = true output += traverse(graph, "AA", 26, 0) bestSeen = 0 maxOut = max(maxOut, output) } return maxOut } val testInput = readInputString("day16/test") val input = readInputString("day16/input") check(part1(testInput) == 1_651) transpositionTable.clear() val time1 = measureNanoTime { println(part1(input)) } println("Time for part 1 was ${"%,d".format(time1)} ns") transpositionTable.clear() check(part2(testInput) == 1_707) transpositionTable.clear() val time2 = measureNanoTime { println(part2(input)) } println("Time for part 2 was ${"%,d".format(time2)} ns") }
0
Kotlin
0
0
5966e1a1f385c77958de383f61209ff67ffaf6bf
8,664
Advent-Of-Code-2022
Apache License 2.0
src/Day18.kt
greg-burgoon
573,074,283
false
{"Kotlin": 120556}
import java.util.TreeSet fun main() { fun calculateSurfaceArea(coordList: List<List<Int>>): Int { var coordMap = mutableMapOf<String, Int>() return coordList.map { listOfCoord -> var neighbourDiscount = 0; listOfCoord.forEachIndexed { index, i -> var coordStringPlus = listOfCoord.toMutableList() coordStringPlus[index] = i + 1 var coordStringMinus = listOfCoord.toMutableList() coordStringMinus[index] = i - 1 neighbourDiscount += coordMap.getOrDefault(coordStringPlus.joinToString(","), 0) neighbourDiscount += coordMap.getOrDefault(coordStringMinus.joinToString(","), 0) } coordMap.put(listOfCoord.joinToString(","), 2) neighbourDiscount }.fold(0) { acc: Int, neighbourDiscount: Int -> acc + 6 - neighbourDiscount } } fun buildAirPocket(rootNode: String, rockMap: Map<String, Boolean>, exteriorSurfaceArea: Int): Int? { var visitedNodes = mutableMapOf<String, Boolean>() var nodeStack = TreeSet<String>() nodeStack.add(rootNode) var pocketSurfaceArea = 0 while (nodeStack.isNotEmpty() && pocketSurfaceArea <= exteriorSurfaceArea+1) { var nextString = nodeStack.pollFirst() var coord = nextString.split(",").map { it.toInt() } coord.let { it.forEachIndexed { index, i -> var coordStringPlus = coord.toMutableList() coordStringPlus[index] = i + 1 var coordStringMinus = coord.toMutableList() coordStringMinus[index] = i - 1 if (!rockMap.getOrDefault(coordStringPlus.joinToString(","), false) && !visitedNodes.getOrDefault(coordStringPlus.joinToString(","), false)) { nodeStack.add(coordStringPlus.joinToString(",")) } if (!rockMap.getOrDefault(coordStringMinus.joinToString(","), false) && !visitedNodes.getOrDefault(coordStringMinus.joinToString(","), false)) { nodeStack.add(coordStringMinus.joinToString(",")) } } } visitedNodes[nextString] = true pocketSurfaceArea = calculateSurfaceArea(visitedNodes.keys.map { it.split(",").map { it.toInt() } }) } if (pocketSurfaceArea <= exteriorSurfaceArea) { return pocketSurfaceArea } else { return null } } fun findAirPockets(coordList: MutableList<List<Int>>, exteriorSurfaceArea: Int): List<Int> { var neighbourMap = mutableMapOf<String, Int>() var rockMap = mutableMapOf<String, Boolean>() coordList.forEach { listOfCoord -> listOfCoord.forEachIndexed { index, i -> var coordStringPlus = listOfCoord.toMutableList() coordStringPlus[index] = i + 1 var coordStringMinus = listOfCoord.toMutableList() coordStringMinus[index] = i - 1 neighbourMap.compute(coordStringPlus.joinToString(",")) { k: String, v: Int? -> if (v == null) 1 else v + 1 } neighbourMap.compute(coordStringMinus.joinToString(",")) { k: String, v: Int? -> if (v == null) 1 else v + 1 } } rockMap.put(listOfCoord.joinToString(","), true) } rockMap.forEach{ neighbourMap.remove(it.key) } var airPockets = mutableListOf<Int>() neighbourMap.filter { it.value >= 3 }.keys.forEach { var potentialAirPocket = buildAirPocket(it, rockMap, exteriorSurfaceArea) if (potentialAirPocket != null) { airPockets.add(potentialAirPocket) } } return airPockets.toList() } fun part1(input: String): Int { var coordList = input.split("\n").map { coordString -> coordString.split(",").map { it.toInt() } } return calculateSurfaceArea(coordList) } fun part2(input: String): Int { var coordList = input.split("\n").map { coordString -> coordString.split(",").map { it.toInt() } }.toMutableList() var exteriorSurfaceArea = calculateSurfaceArea(coordList) var airPockets = findAirPockets(coordList, exteriorSurfaceArea/2) return calculateSurfaceArea(coordList) - airPockets.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") val result = part1(testInput) check(result == 64) val resultTwo = part2(testInput) check(resultTwo == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
4,880
aoc-kotlin
Apache License 2.0
base-portable/src/commonMain/kotlin/jetbrains/datalore/base/algorithms/Geometry.kt
randomnetcat
476,483,866
true
{"Kotlin": 5698914, "Python": 781400, "C": 2832, "CSS": 1923, "Shell": 1759, "JavaScript": 1121}
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.datalore.base.algorithms import jetbrains.datalore.base.gcommon.collect.IntSpan import jetbrains.datalore.base.geometry.DoubleVector import kotlin.math.abs fun <T> splitRings(points: List<T>): List<List<T>> { val rings = findRingIntervals(points).map { points.sublist(it) }.toMutableList() if (rings.isNotEmpty()) { if (!rings.last().isClosed()) { rings.set(rings.lastIndex, makeClosed(rings.last())) } } return rings } private fun <T> makeClosed(path: List<T>) = path.toMutableList() + path.first() fun <T> List<T>.isClosed() = first() == last() private fun <T> findRingIntervals(path: List<T>): List<IntSpan> { val intervals = ArrayList<IntSpan>() var startIndex = 0 var i = 0 val n = path.size while (i < n) { if (startIndex != i && path[startIndex] == path[i]) { intervals.add(IntSpan(startIndex, i + 1)) startIndex = i + 1 } i++ } if (startIndex != path.size) { intervals.add(IntSpan(startIndex, path.size)) } return intervals } private fun <T> List<T>.sublist(range: IntSpan): List<T> { return this.subList(range.lowerEnd, range.upperEnd) } fun calculateArea(ring: List<DoubleVector>): Double { return calculateArea(ring, DoubleVector::x, DoubleVector::y) } fun <T> isClockwise(ring: List<T>, x: (T) -> Double, y: (T) -> Double): Boolean { check(ring.isNotEmpty()) { "Ring shouldn't be empty to calculate clockwise" } var sum = 0.0 var prev = ring[ring.size - 1] for (point in ring) { sum += x(prev) * y(point) - x(point) * y(prev) prev = point } return sum < 0.0 } fun <T> calculateArea(ring: List<T>, x: T.() -> Double, y: T.() -> Double): Double { var area = 0.0 var j = ring.size - 1 for (i in ring.indices) { val p1 = ring[i] val p2 = ring[j] area += (p2.x() + p1.x()) * (p2.y() - p1.y()) j = i } return abs(area / 2) }
1
Kotlin
1
0
fe960f43d39844d04a89bd12490cd2dd4dbeaa51
2,149
lets-plot
MIT License
src/main/kotlin/days/Day4Solution.kt
yigitozgumus
434,108,608
false
{"Kotlin": 17835}
package days import BaseSolution class BingoBoard(rows: List<String>) { private val rowCounter = MutableList(rows.size) { 0 } private val colCounter = MutableList(rows.size) { 0 } var winner = false private val board = rows.toMutableList().mapTo(mutableListOf()) { row -> row.split(" ").filter { it != "" }.mapTo(mutableListOf()) { it.toInt() } } fun isBingoAfterCheck(nextNumber: Int): Boolean { val rowIndex = board.indexOfFirst { it.contains(nextNumber) } return if (rowIndex != -1) { val colIndex = board[rowIndex].indexOf(nextNumber) colCounter[colIndex]++ rowCounter[rowIndex]++ board[rowIndex][colIndex] = -1 rowCounter[rowIndex] == 5 || colCounter[colIndex] == 5 } else false } fun computeScore(nextNumber: Int) = board.sumOf { it.filter { num -> num > 0 }.sum() } * nextNumber } class Day4Solution(inputList: List<String>) : BaseSolution(inputList) { private val numberList = inputList.first().split(",").map { it.toInt() } private val boardList = inputList.subList(1, inputList.size).filterNot { it == "" } .windowed(size = 5, step = 5).map { BingoBoard(it) } override fun part1() { numberList.forEach { number -> boardList.forEach { board -> if (board.isBingoAfterCheck(number)) { println(board.computeScore(number)) return } } } } override fun part2() { numberList.forEach { number -> boardList.forEach { board -> if (board.isBingoAfterCheck(number) && board.winner.not()) { board.winner = true if (boardList.all { it.winner }) { println(board.computeScore(number)) return } } } } } }
0
Kotlin
0
0
c0f6fc83fd4dac8f24dbd0d581563daf88fe166a
1,954
AdventOfCode2021
MIT License
src/year2023/day09/Day09.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day09 import check import readInput fun main() { val testInput = readInput("2023", "Day09_test") check(part1(testInput), 114) check(part2(testInput), 2) val input = readInput("2023", "Day09") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>) = input.mapToHistories().sumOf { it.predictNextValue() } private fun part2(input: List<String>) = input.mapToHistories().sumOf { it.predictPrevValue() } private fun List<Int>.predictNextValue(): Int { if (all { it == 0 }) return 0 return last() + getChildSequence().predictNextValue() } private fun List<Int>.predictPrevValue(): Int { if (all { it == 0 }) return 0 return first() - getChildSequence().predictPrevValue() } private fun List<Int>.getChildSequence() = windowed(2).map { (a, b) -> b - a } private fun List<String>.mapToHistories() = map { line -> line.split(' ').map { it.toInt() } }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
938
AdventOfCode
Apache License 2.0
src/main/kotlin/days/aoc2021/Day3.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2021 import days.Day class Day3 : Day(2021, 3) { override fun partOne(): Any { calculateGammaAndEpsilon(inputList).let { return it.first * it.second } } fun calculateGammaAndEpsilon(input: List<String>): Pair<Int,Int> { val counts = Array(input.first().length) { 0 } input.forEach { line -> line.forEachIndexed { index, c -> when (c) { '0' -> counts[index]++ } } } val gamma = counts.reversedArray().foldIndexed(0) { index, acc, i -> if (i < input.size / 2) (acc + (1 shl index)) else acc } val epsilon = counts.reversedArray().foldIndexed(0) { index, acc, i -> if (i > input.size / 2) (acc + (1 shl index)) else acc } return Pair(gamma, epsilon) } override fun partTwo(): Any { return calculateGenAndScrubberRating(inputList).let { return it.first * it.second } } fun calculateGenAndScrubberRating(input: List<String>): Pair<Int,Int> { var currentScrubber = input.toList() var currentGen = input.toList() input.first().indices.forEach { index -> currentGen = pareDownListByIndexAndValue(currentGen, index, true) currentScrubber = pareDownListByIndexAndValue(currentScrubber, index, false) } val gen = currentGen.first().reversed().foldIndexed(0) {index, acc, c -> if (c == '1') acc + (1 shl index) else acc} val scrubber = currentScrubber.first().reversed().foldIndexed(0) {index, acc, c -> if (c == '1') acc + (1 shl index) else acc} return Pair(gen,scrubber) } private fun pareDownListByIndexAndValue(input: List<String>, index: Int, mostCommon: Boolean): List<String> { if (input.size == 1) return input var count = 0 input.forEach { line -> if (line[index] == '1') count++ } val ones = count val zeros = input.size - count var filterValue = if (mostCommon) { if (ones >= zeros) '1' else '0' } else { if (zeros <= ones) '0' else '1' } return input.filter { it[index] == filterValue } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
2,323
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/leonra/adventofcode/advent2023/day06/Day6.kt
LeonRa
726,688,446
false
{"Kotlin": 30456}
package com.leonra.adventofcode.advent2023.day06 import com.leonra.adventofcode.shared.readResource /** https://adventofcode.com/2023/day/6 */ private object Day6 { fun partOne(): Int { val times = mutableListOf<Int>() val records = mutableListOf<Int>() fun parseInputs(data: String): List<Int> = data.split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.toInt() } .toList() readResource("/2023/day06/part1.txt") { line -> val timeMatch = TIME.find(line) val distanceMatch = RECORD.find(line) if (timeMatch != null) { times.addAll(parseInputs(requireNotNull(timeMatch.groups[1]).value)) } else if (distanceMatch != null) { records.addAll(parseInputs(requireNotNull(distanceMatch.groups[1]).value)) } } var margin = 1 for (index in times.indices) { val time = times[index] val record = records[index] var ways = 0 for (hold in 1 until time) { val distance = hold * (time - hold) if (distance > record) { ways++ } } margin *= ways } return margin } fun partTwo(): Long { var time = 0L var record = 0L fun parseInput(data: String): Long = data.split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .fold("") { previous, next -> previous + next } .toLong() readResource("/2023/day06/part1.txt") { line -> val timeMatch = TIME.find(line) val distanceMatch = RECORD.find(line) if (timeMatch != null) { time = parseInput(requireNotNull(timeMatch.groups[1]).value) } else if (distanceMatch != null) { record = parseInput(requireNotNull(distanceMatch.groups[1]).value) } } var ways = 0L for (hold in 1 until time) { val distance = hold * (time - hold) if (distance > record) { ways++ } } return ways } private val TIME = Regex("Time: (.+)") private val RECORD = Regex("Distance: (.+)") } private fun main() { println("Part 1 margin of error: ${Day6.partOne()}") println("Part 2 ways: ${Day6.partTwo()}") }
0
Kotlin
0
0
46bdb5d54abf834b244ba9657d0d4c81a2d92487
2,538
AdventOfCode
Apache License 2.0
kt.kt
darian-catalin-cucer
598,111,644
false
null
fun quickSort(arr: IntArray, low: Int, high: Int) { if (low < high) { val pivotIndex = partition(arr, low, high) quickSort(arr, low, pivotIndex - 1) quickSort(arr, pivotIndex + 1, high) } } fun partition(arr: IntArray, low: Int, high: Int): Int { val pivot = arr[high] var i = low - 1 for (j in low until high) { if (arr[j] <= pivot) { i++ val temp = arr[i] arr[i] = arr[j] arr[j] = temp } } val temp = arr[i + 1] arr[i + 1] = arr[high] arr[high] = temp return i + 1 } //The code above implements the QuickSort algorithm, a classic divide-and-conquer algorithm for sorting an array. The quickSort function takes in an array arr, a low index low, and a high index high, and sorts the subarray arr[low..high] in place. The partition function is used to divide the subarray into two parts: elements smaller than the pivot and elements greater than the pivot. The pivot is chosen as the last element of the subarray. The partition function rearranges the elements so that all elements smaller than the pivot are before it, and all elements greater than the pivot are after it. The pivot index is then returned, which becomes the boundary between the two subarrays in the subsequent recursive calls to quickSort. The QuickSort algorithm sorts the array by repeatedly dividing it into smaller subarrays and sorting those subarrays until they are small enough to be sorted directly.
0
Kotlin
0
0
1cea70defa6d6e7429bace2402b23ac769a2fbba
1,508
divide-and-conquer-algorithms
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortArrayByParity.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.isEven import dev.shtanko.algorithms.extensions.swap import java.util.Arrays /** * 905. Sort Array By Parity * @see <a href="https://leetcode.com/problems/sort-array-by-parity">Source</a> */ fun interface SortArrayByParity { operator fun invoke(nums: IntArray): IntArray } /** * Approach 1: Stream */ class SortArrayByParityStream : SortArrayByParity { override operator fun invoke(nums: IntArray): IntArray { return Arrays.stream(nums) .boxed() .sorted { a, b -> (a % 2).compareTo(b % 2) } .mapToInt { i -> i } .toArray() } } /** * Approach 1: Kotlin */ class SortArrayByParityKotlin : SortArrayByParity { override operator fun invoke(nums: IntArray): IntArray = nums .sortedWith { a, b -> (a % 2).compareTo(b % 2) } .toIntArray() } class SortArrayByParityTwoPass : SortArrayByParity { override operator fun invoke(nums: IntArray): IntArray { val ans = IntArray(nums.size) var t = 0 for (i in nums.indices) { if (nums[i] % 2 == 0) ans[t++] = nums[i] } for (i in nums.indices) { if (nums[i] % 2 == 1) ans[t++] = nums[i] } return ans } } class SortArrayByParityInPlace : SortArrayByParity { override operator fun invoke(nums: IntArray): IntArray = nums.sortArrayByParity() private fun IntArray.sortArrayByParity(): IntArray { var i = 0 var j = size - 1 while (i < j) { if (this[i].isEven) { i++ } else { if (!this[j].isEven) { j-- } if (this[j].isEven) { swap(i, j) i++ j-- } } } return this } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,518
kotlab
Apache License 2.0
src/main/kotlin/day4/day4.kt
aaronbush
370,490,470
false
null
package day4 import loadFile fun main() { val data = "/day4/input.txt".loadFile() .fold(mutableListOf<MutableSet<Pair<String, String>>>(mutableSetOf())) { accum, line -> if (line.isBlank()) { accum.apply { add(mutableSetOf()) } // on blank line create new set of field/data } else { accum.apply { last().apply { addAll( line.split(" ").map { s -> s.split(":", limit = 2).let { Pair(it.first(), it.last()) } }) } } } } part1(data) part2(data) } fun part1(data: MutableList<MutableSet<Pair<String, String>>>) { val result = validRecords(data).count() println("part 1 is $result") } private fun validRecords(data: MutableList<MutableSet<Pair<String, String>>>): Sequence<MutableSet<Pair<String, String>>> { val requiredFields = setOf("byr", "ecl", "eyr", "hcl", "hgt", "iyr", "pid") val ignoreField = "cid" return data.filter { set -> set.map { it.first }.toSet() - ignoreField == requiredFields }.asSequence() } fun part2(data: MutableList<MutableSet<Pair<String, String>>>) { val hgtLayout = "(\\d+)(cm|in)".toRegex() val requiredFieldPredicates = mapOf( "byr" to { s: String -> s.length == 4 && s.toInt() in 1920..2002 }, "ecl" to { s: String -> s in setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") }, "eyr" to { s: String -> s.length == 4 && s.toInt() in 2020..2030 }, "hcl" to { s: String -> s.matches("#[0-9a-f]{6}".toRegex()) }, "hgt" to { s: String -> hgtLayout.find(s)?.destructured?.let { val (num, unit) = it when (unit) { "cm" -> num.toInt() in 150..193 "in" -> num.toInt() in 59..76 else -> false } } ?: false }, "iyr" to { s: String -> s.length == 4 && s.toInt() in 2010..2020 }, "pid" to { s: String -> s.length == 9 && s.toIntOrNull() != null }, "cid" to { s: String -> true }, ) val result = validRecords(data).count { rec -> rec.all { requiredFieldPredicates[it.first]?.invoke(it.second) ?: false } } println("part 2 is $result") }
0
Kotlin
0
0
41d69ebef7cfeae4079e8311b1060b272c5f9a29
2,380
aoc-2020-kotlin
MIT License
src/Day10.kt
ka1eka
574,248,838
false
{"Kotlin": 36739}
fun main() { fun part1(input: List<String>): Int = sequence { val breakPoints = setOf(20, 60, 100, 140, 180, 220) var x = 1 var cycle = 0 input.forEach { command -> val previousCycle = cycle when (command) { "noop" -> cycle++ else -> cycle += 2 } breakPoints.find { it in (previousCycle + 1)..cycle } ?.run { yield(this * x) } if (command != "noop") { x += command.substring(5).toInt() } } }.sum() fun part2(input: List<String>) = with(MutableList(40 * 6) { '.' }) { var position = 1 var cycle = 0 fun render() { val col = (cycle % (40 * 6)) % 40 val row = (cycle % (40 * 6)) / 40 if (col in position - 1..position + 1) { this[row * 40 + col] = '#' } else { this[row * 40 + col] = '.' } cycle++ } input.forEach { command -> when (command) { "noop" -> render() else -> { repeat(2) { render() } position += command.substring(5).toInt() } } } this.chunked(40) .joinToString("\n") { it.joinToString("") } } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check(part2(testInput) == buildString { append("##..##..##..##..##..##..##..##..##..##..\n") append("###...###...###...###...###...###...###.\n") append("####....####....####....####....####....\n") append("#####.....#####.....#####.....#####.....\n") append("######......######......######......####\n") append("#######.......#######.......#######.....") }) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4f7893448db92a313c48693b64b3b2998c744f3b
2,033
advent-of-code-2022
Apache License 2.0
test/leetcode/ValidTicTacToeState.kt
andrej-dyck
340,964,799
false
null
package leetcode import lib.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.* import org.junit.jupiter.params.converter.* import org.junit.jupiter.params.provider.* /** * https://leetcode.com/problems/valid-tic-tac-toe-state/ * * 794. Valid Tic-Tac-Toe State * [Medium] * * A Tic-Tac-Toe board is given as a string array board. * Return True if and only if it is possible to reach this board position * during the course of a valid tic-tac-toe game. * * The board is a 3 x 3 array, and consists of characters " ", "X", and "O". * The " " character represents an empty square. * * Here are the rules of Tic-Tac-Toe: * - Players take turns placing characters into empty squares (" "). * - The first player always places "X" characters, while the second player always places "O" characters. * - "X" and "O" characters are always placed into empty squares, never filled ones. * - The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal. * - The game also ends if all squares are non-empty. * - No more moves can be played if the game is over. * * Note: * - board is a length-3 array of strings, where each string board[i] has length 3. * - Each board[i][j] is a character in the set {" ", "X", "O"}. */ fun validTicTacToe(board: Array<String>) = TicTacToeBoard(board).isInValidState class TicTacToeBoard(private val board: Array<String>) { val isInValidState by lazy { when { xWon -> !oWon && xs == os + 1 oWon -> !xWon && xs == os else -> xs == os || xs == os + 1 } } val xWon by lazy { isWinner('X') } val oWon by lazy { isWinner('O') } private val xs by lazy { board.joinToString().count { it == 'X' } } private val os by lazy { board.joinToString().count { it == 'O' } } private fun isWinner(c: Char): Boolean = anyRowContainsOnly(c) || anyColumnContainsOnly(c) || anyDiagonalContainsOnly(c) private fun anyRowContainsOnly(c: Char) = board.any { it == "$c".repeat(3) } private fun anyColumnContainsOnly(c: Char) = (0..2).any { colIndex -> board.all { it[colIndex] == c } } private fun anyDiagonalContainsOnly(c: Char) = (0..2).all { board[it][it] == c } || (0..2).all { board[it][2 - it] == c } init { require( board.size == 3 && board.all { s -> s.length == 3 && s.all { c -> c in " XO" } } ) { "invalid board representation: ${board.formattedString()}" } } } /** * Unit tests */ class ValidTicTacToeStateTest { @ParameterizedTest @ValueSource( strings = [ "[\" \", \" \", \" \"]", "[\" \", \" XO\", \" \"]", "[\" XO\", \" XO\", \" \"]", "[\" X \", \" XO\", \" O \"]", "[\"XOX\", \"O O\", \"XOX\"]", ] ) fun `valid board when same count of Xs and Os (and no winner)`(board: String) = assertIsValid(board) @ParameterizedTest @ValueSource( strings = [ "[\" \", \" X \", \" \"]", "[\" X \", \" XO\", \" \"]", "[\" XO\", \" XO\", \" X \"]", "[\"OXO\", \"OXX\", \"XOX\"]", ] ) fun `valid board when count of Xs is 1 more than Os (and no winner)`(board: String) = assertIsValid(board) @ParameterizedTest @ValueSource( strings = [ "[\"XXX\", \" \", \"O O\"]", "[\" X \", \" XO\", \" XO\"]", "[\"XO \", \" XO\", \" X\"]", ] ) fun `valid board when X won and count of Os is 1 less (and O did not win)`(board: String) = assertIsValid(board) @ParameterizedTest @ValueSource( strings = [ "[\"OOO\", \" X \", \"X X\"]", "[\" XO\", \" XO\", \"X O\"]", "[\"OX \", \" OX\", \"O X\"]", ] ) fun `valid board when O won and count of Xs is equal (and X did not win)`(board: String) = assertIsValid(board) @ParameterizedTest @ValueSource( strings = [ "[\"O \", \" \", \" \"]", "[\"OO \", \"XXX\", \" OO\"]", "[\"OOO\", \" X \", \" \"]", ] ) fun `invalid board when count of Os is more than Xs`(board: String) = assertIsInvalid(board) @ParameterizedTest @ValueSource( strings = [ "[\"OOO\", \"XXX\", \" \"]", "[\"XO \", \"XO \", \"XO \"]", ] ) fun `invalid board when two winners exist`(board: String) = assertIsInvalid(board) @ParameterizedTest @ValueSource( strings = [ "[\"XXX\", \" O \", \"O O\"]", ] ) fun `invalid board when X won and count of Os is equal`(board: String) = assertIsInvalid(board) @ParameterizedTest @ValueSource( strings = [ "[\"OOO\", \"XX \", \"X X\"]", ] ) fun `invalid board when O won and count of Xs is 1 more`(board: String) = assertIsInvalid(board) private fun assertIsValid(board: String) { assertThat( validTicTacToe(board.toArray { removeSurrounding("\"") }) ).`as`("$board is valid").isTrue } private fun assertIsInvalid(board: String) { assertThat( validTicTacToe(board.toArray { removeSurrounding("\"") }) ).`as`("$board is invalid").isFalse } }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
5,489
coding-challenges
MIT License
src/main/kotlin/com/github/shmvanhouten/adventofcode/day4/RoomKeyDecoder.kt
SHMvanHouten
109,886,692
false
{"Kotlin": 616528}
package com.github.shmvanhouten.adventofcode.day4 class RoomKeyDecoder { fun checkIfRoomsAreReal(keys: String): Int { return keys .split("\n") .sumBy { checkIfRoomIsReal(it.trim()) } } fun getListOfValidRooms(encodedRoomNames: String): List<Room> { return encodedRoomNames.split("\n").mapNotNull { getRealRoom(it.trim()) } } fun checkIfRoomIsReal(key: String): Int { val (name:List<String>, sectorId: Int, checkSum: String) = retrieveRoomIdentifiersFromKey(key) val expectedRoomKey = getFiveCharactersMostRepresentedInTheName(name) return if (checkSum == expectedRoomKey) sectorId else 0 } private fun getRealRoom(key: String): Room? { val (name:List<String>, sectorId: Int, checkSum: String) = retrieveRoomIdentifiersFromKey(key) val expectedRoomKey = getFiveCharactersMostRepresentedInTheName(name) return if (checkSum == expectedRoomKey) Room(name, sectorId) else null } private fun retrieveRoomIdentifiersFromKey(key: String): Triple<List<String>, Int, String> { val (name, sectorIdAndCheckSum) = key.split("-").partition { it[0].isLetter() } val sectorId = sectorIdAndCheckSum[0].substringBefore('[').toInt() val checkSum = sectorIdAndCheckSum[0].substringAfter('[').substringBefore(']') return Triple(name, sectorId, checkSum) } private fun getFiveCharactersMostRepresentedInTheName(name: List<String>): String { val sortedCharacters = sortCharactersByQuantityAndAlphabet(name.joinToString("")) val roomKey = StringBuilder() for (indexedChar in sortedCharacters.withIndex()) { roomKey.append(indexedChar.value) if(indexedChar.index >= 4) break } // run breaker@{sortedCharacters.forEachIndexed { index, char -> roomKey.append(char); if (index == 4) return@breaker}} return roomKey.toString() } private fun sortCharactersByQuantityAndAlphabet(roomName: String): MutableSet<Char> { val characterToAmountMap = roomName.associateBy({ it }, { countTimesCharacterIsInRoomName(it, roomName) }) return characterToAmountMap .toSortedMap(compareByDescending<Char> { characterToAmountMap.getValue(it) }.thenBy { it }) .keys } private fun countTimesCharacterIsInRoomName(char: Char, name: String): Int { return name.count { it == char } } }
0
Kotlin
0
0
a8abc74816edf7cd63aae81cb856feb776452786
2,520
adventOfCode2016
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountComponents.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * Number of Connected Components in an Undirected Graph * @see <a href="https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph">Source</a> */ fun interface CountComponents { operator fun invoke(n: Int, edges: Array<IntArray>): Int } class CountComponentsDFS : CountComponents { override operator fun invoke(n: Int, edges: Array<IntArray>): Int { val representative = IntArray(n) val size = IntArray(n) for (i in 0 until n) { representative[i] = i size[i] = 1 } var components = n for (i in edges.indices) { components -= combine(representative, size, edges[i][0], edges[i][1]) } return components } private fun find(representative: IntArray, vertex: Int): Int { return if (vertex == representative[vertex]) { vertex } else { find(representative, representative[vertex]).also { representative[vertex] = it } } } private fun combine(representative: IntArray, size: IntArray, vertex1: Int, vertex2: Int): Int { var v1 = vertex1 var v2 = vertex2 v1 = find(representative, v1) v2 = find(representative, v2) return if (v1 == v2) { 0 } else { if (size[v1] > size[v2]) { size[v1] += size[v2] representative[v2] = v1 } else { size[v2] += size[v1] representative[v1] = v2 } 1 } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,212
kotlab
Apache License 2.0
src/Day01.kt
BHFDev
572,832,641
false
null
fun main() { fun part1(input: List<String>): Int { var highestCalories = 0 var currentCalories = 0 input.forEach {calories -> if(calories.isEmpty()) { if(currentCalories > highestCalories) { highestCalories = currentCalories } currentCalories = 0 } else { currentCalories += calories.toInt() } } return highestCalories } fun part2(input: List<String>): Int { val elvesCalories = mutableListOf<Int>() var currentCalories = 0 input.forEach {calories -> if(calories.isEmpty()) { elvesCalories.add(currentCalories) currentCalories = 0 } else { currentCalories += calories.toInt() } } return elvesCalories .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b158069483fa02636804450d9ea2dceab6cf9dd7
1,221
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/org/sj/aoc2022/day01/CalorieCounter.kt
sadhasivam
573,168,428
false
{"Kotlin": 10910}
package org.sj.aoc2022.day01 val maxNCalories = 3 fun computeElvesCaloriesList(input: List<String>): List<Int> { val elvesCalories = mutableListOf<Int>() var calories = 0 input.forEach { if (it.trim() != "") { calories += it.toInt() } else { elvesCalories.add(calories) calories = 0 } } if (calories > 0) { elvesCalories.add(calories) } return elvesCalories } /** * Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? */ fun maxElvesCalories(input: List<String>): Int = computeElvesCaloriesList(input).max() /** * Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? */ fun topNElvesCalories(input: List<String>, nCalories: Int): Int = computeElvesCaloriesList(input) .sorted() .asReversed() .take(nCalories) .sum()
0
Kotlin
0
0
7a1ceaddbe7e72bad0e9dfce268387d333b62143
948
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/cc/stevenyin/algorithms/SortHelper.kt
StevenYinKop
269,945,740
false
{"Kotlin": 107894, "Java": 9565}
package cc.stevenyin.algorithms import cc.stevenyin.algorithms._02_sorts.SortAlgorithm import kotlin.random.Random import kotlin.system.measureTimeMillis class SortHelper { } enum class RandomType() { NEARLY_ORDERED { override fun generate(nums: Int): Array<Int> { val random = Random(System.currentTimeMillis()) val result = Array(nums) { it } for (i in 0..10) { swap(result, random.nextInt(result.size), random.nextInt(result.size)) } return result } }, CHAOS { override fun generate(nums: Int): Array<Int> { val random = Random(System.currentTimeMillis()) val result = Array(nums) { 0 } for (i in 0 until nums) { result[i] = random.nextInt(0, nums) } return result } }, CLOSE_RANGE { override fun generate(nums: Int): Array<Int> { val random = Random(System.currentTimeMillis()) val result = Array(nums) { 0 } for (i in 0 until nums) { result[i] = random.nextInt(0, 5) } return result } }, ORDERED { override fun generate(nums: Int): Array<Int> { return Array(nums) { it } } }; abstract fun generate(nums: Int): Array<Int> } fun <T> swap(array: Array<T>, index1: Int, index2: Int) { if (index1 == index2) return val temp = array[index1] array[index1] = array[index2] array[index2] = temp } fun testSortAlgorithm(nums: Int, type: RandomType, vararg algorithms: SortAlgorithm) { val array = generateIntegerTestCases(nums, type) val expectedArray = generateIntegerExpectedResult(array) algorithms.forEach { algorithm -> val arrayIteration = array.copyOf() val timeMillis = measureTimeMillis { algorithm.sort(arrayIteration) } if (nums <= 20) { println("The final array is ${arrayIteration.contentToString()}") } println("(The ${algorithm.name} operation took $timeMillis ms)") assert(expectedArray.contentEquals(array)) { "The results aren incorrect!" } println() } } fun testSortAlgorithm(nums: Int, type: RandomType, clz: SortAlgorithm) { testSortAlgorithm(nums, type, *arrayOf(clz)) } fun generateIntegerTestCases(nums: Int, type: RandomType) = type.generate(nums) fun generateIntegerExpectedResult(array: Array<Int>): Array<Int> { val result = array.copyOf() result.sort() return result }
0
Kotlin
0
1
748812d291e5c2df64c8620c96189403b19e12dd
2,612
kotlin-demo-code
MIT License
src/main/kotlin/ca/kiaira/advent2023/day2/Day2.kt
kiairatech
728,913,965
false
{"Kotlin": 78110}
package ca.kiaira.advent2023.day2 import ca.kiaira.advent2023.Puzzle import com.github.michaelbull.logging.InlineLogger /** * Class representing the Day 2 puzzle for Advent of Code 2023. * It includes methods to parse game data and solve the puzzle for each part. * * @author <NAME> <<EMAIL>> * @since December 8th, 2023 */ object Day2 : Puzzle<List<Game>>(2) { /** * Parses the input data into a list of Game objects. * * @param input The input data as a sequence of strings. * @return A list of Game objects. */ override fun parse(input: Sequence<String>): List<Game> { return input.map { line -> val parts = line.split(": ") val id = parts[0].removePrefix("Game ").toInt() val subsets = parts[1].split("; ").map { parseSubset(it) } Game(id, subsets) }.toList() } /** * Solves Part 1 of the Day 2 puzzle. * Determines the sum of IDs of games feasible with specific cube limits. * * @param input The parsed list of Game objects. * @return The sum of IDs of feasible games. */ override fun solvePart1(input: List<Game>): Any { return input.filter { it.isFeasible(12, 13, 14) }.sumOf { it.id } } /** * Solves Part 2 of the Day 2 puzzle. * Calculates the sum of the power of minimum sets of cubes required for each game. * * @param input The parsed list of Game objects. * @return The sum of the power of minimum sets. */ override fun solvePart2(input: List<Game>): Any { return input.sumOf { it.calculatePower() } } /** * Parses a subset of cubes from a string into a map. * * @param subset The string representation of a subset of cubes. * @return A map representing the count of each color of cubes. */ private fun parseSubset(subset: String): Map<String, Int> { return subset.split(", ").associate { colorCount -> val (count, color) = colorCount.split(" ") color to count.toInt() } } } /** * Data class representing a single game with its ID and subsets of cubes. * * @param id The unique identifier of the game. * @param subsets The list of subsets of cubes revealed in each game. * * @author <NAME> <<EMAIL>> * @since December 8th, 2023 */ data class Game(val id: Int, val subsets: List<Map<String, Int>>) { /** * Determines if a game is feasible with a given maximum number of red, green, and blue cubes. * * @param maxRed The maximum number of red cubes available. * @param maxGreen The maximum number of green cubes available. * @param maxBlue The maximum number of blue cubes available. * @return True if the game is feasible, False otherwise. */ fun isFeasible(maxRed: Int, maxGreen: Int, maxBlue: Int): Boolean { return subsets.all { subset -> subset.getOrDefault("red", 0) <= maxRed && subset.getOrDefault("green", 0) <= maxGreen && subset.getOrDefault("blue", 0) <= maxBlue } } /** * Calculates the power of the minimum set of cubes required for the game. * The power is defined as the product of the minimum number of each color of cubes required. * * @return The power of the minimum set of cubes. */ fun calculatePower(): Int { val minRed = subsets.maxOfOrNull { it.getOrDefault("red", 0) } ?: 0 val minGreen = subsets.maxOfOrNull { it.getOrDefault("green", 0) } ?: 0 val minBlue = subsets.maxOfOrNull { it.getOrDefault("blue", 0) } ?: 0 return minRed * minGreen * minBlue } } /** Logger for logging information. */ private val logger = InlineLogger()
0
Kotlin
0
1
27ec8fe5ddef65934ae5577bbc86353d3a52bf89
3,474
kAdvent-2023
Apache License 2.0
src/Day03.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.io.Reader val priorities get() = mutableMapOf<Char, Int>().also { map -> ('a'..'z').forEachIndexed { index, c -> map[c] = index + 1 } ('A'..'Z').forEachIndexed { index, c -> map[c] = index + 27 } }.toMap() fun main() { val testInput = """ vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw """.trimIndent() check(partOne(testInput.reader()) == 157) val input = file("Day03.txt") println(partOne(input.bufferedReader())) check(partTwo(testInput.reader()) == 70) println(partTwo(input.bufferedReader())) } private fun partOne(source: Reader): Int { val priorities = priorities var prioritySum = 0 source.forEachLine { line -> val mid = line.length / 2 val compartment1 = line.substring(0, mid) val compartment2 = line.substring(mid) check(compartment1.length == compartment2.length) prioritySum += compartment1.toSet().intersect(compartment2.toSet()).fold(0) { acc, c -> acc + (priorities[c] ?: 0) } } return prioritySum } private fun partTwo(source: Reader): Int { val priorities = priorities var prioritySum = 0 val twoLineBuffer = ArrayList<String>(2) source.forEachLine { line -> if (twoLineBuffer.size < 2) { twoLineBuffer.add(line) } else { val a = twoLineBuffer[0].toSet() val b = twoLineBuffer[1].toSet() val c = line.toSet() val intersect = a.intersect(b).intersect(c) check(intersect.size == 1) val badge = intersect.toList()[0] prioritySum += priorities[badge] ?: 0 twoLineBuffer.clear() } } return prioritySum }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
1,892
advent-of-code-2022-kotlin
Apache License 2.0
day10.kt
benjaminjkraft
113,406,355
false
null
fun doHash(lengths: List<Int>, n: Int, rounds: Int): Array<Int> { var pos = 0 var skip = 0 val list = Array(n, { it }) for (round in 0 until rounds) { for (i in lengths.indices) { val listAgain = list.copyOf() for (j in 0 until lengths[i]) { list[(pos + j) % n] = listAgain[(pos + lengths[i] - 1 - j) % n] } pos += lengths[i] + skip skip++; } } return list } fun firstProd(list: Array<Int>): Int { return list[0] * list[1] } fun denseHash(list: Array<Int>, n: Int): String { var output = "" val blockSize = list.size / n for (i in 0 until n) { val byte = list.slice(i * blockSize until (i + 1) * blockSize).reduce( { j, k -> j xor k }) output += byte.toString(16).padStart(2, '0') } return output } fun main(args: Array<String>) { val line = readLine()!! val extra = arrayOf(17, 31, 73, 47, 23) println(firstProd(doHash(line.split(",").map({ it.toInt() }), 256, 1))) println(denseHash(doHash(line.map({ it.toInt() }) + extra, 256, 64), 16)) }
0
Rust
0
5
e3ac3563bf2d535f68e503ce03c76f41ec77fc31
1,130
aoc2017
MIT License
src/main/kotlin/ru/timakden/aoc/year2016/Day03.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2016 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 3: Squares With Three Sides](https://adventofcode.com/2016/day/3). */ object Day03 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2016/Day03") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>) = input.count { line -> isTrianglePossible("\\d+".toRegex().findAll(line).map { it.value }.toList()) } fun part2(input: List<String>): Int { var triangles = 0 (0..input.lastIndex step 3).forEach { i -> val list = mutableListOf<List<String>>() (0..2).forEach { j -> list += "\\d+".toRegex().findAll(input[i + j]).map { it.value }.toList() } repeat((0..2).filter { isTrianglePossible(listOf(list[0][it], list[1][it], list[2][it])) }.size) { triangles++ } } return triangles } private fun isTrianglePossible(sides: List<String>): Boolean { val (side1, side2, side3) = sides.map { it.toInt() } return side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1 } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
1,296
advent-of-code
MIT License
src/Day14.kt
TinusHeystek
574,474,118
false
{"Kotlin": 53071}
import extensions.grid.* class Day14 : Day(14) { private val directionalLower3: List<Point> = listOf(0 to 1, -1 to 1, 1 to 1) enum class CavePointType { ROCK, AIR, SAND, SPAWN_POINT } class CaveNode(point: Point) : Node(point) { var type = CavePointType.AIR override fun toString(): String = when(type) { CavePointType.ROCK -> "#" CavePointType.SAND -> "o" CavePointType.SPAWN_POINT -> "+" else -> "." } } private fun parseInput(input: String): List<List<Point>> { return input.lines() .map {coordinates -> coordinates.split(" -> ") .map { val points = it.split(",") Pair(points[0].toInt(), points[1].toInt() ) } } } private fun buildGrid(points: List<List<Point>>, addFloor: Boolean = false): Pair<Grid<CaveNode>, Int> { var topLeft = 0 to 0 var bottomRight = 0 to 0 points.flatten() .also { point -> val extraSpace = if (addFloor) point.maxOf { it.y } else 1 topLeft = point.minOf { it.x } - extraSpace to point.minOf { it.y } bottomRight = point.maxOf { it.x } + extraSpace to point.maxOf { it.y } + 1 + (if (addFloor) 1 else 0) } val size = bottomRight - (topLeft.x to 0) val map = MutableList(size.y + 1) { row -> MutableList(size.x + 1) { col -> CaveNode(col to row) } } val grid: Grid<CaveNode> = Grid(map) points.forEach { p -> p.windowed(2, 1) .forEach { pair -> for (row in pair.minOf { it.y } until pair.maxOf { it.y } + 1) { for (col in pair.minOf { it.x } until pair.maxOf { it.x } + 1) { grid.getNode(col - topLeft.x to row).type = CavePointType.ROCK } } } } if (addFloor) { map.last().forEach{ it.type = CavePointType.ROCK} } return (grid to topLeft.x) } private fun checkNeighboursNodes(grid: Grid<CaveNode>, currentNode: CaveNode) : Boolean { val neighbours = grid.getNeighbours(currentNode.point, directionalLower3) if (neighbours.isEmpty()) return false for (node in neighbours) { if (node.type == CavePointType.AIR) { val seekNodes = grid.getNeighbours(node.point, directionalLower3) if (seekNodes.isEmpty()) return false if (seekNodes.all { it.type != CavePointType.AIR }) { node.type = CavePointType.SAND return true } return checkNeighboursNodes(grid, node) } } return false } private fun countSandFalling(input: String, addFloor: Boolean): Int { val points = parseInput(input) val (grid, minX) = buildGrid(points, addFloor) val spawnNode = grid.getNode(500 - minX to 0) spawnNode.type = CavePointType.SPAWN_POINT while (checkNeighboursNodes(grid, spawnNode)) { // grid.print() } grid.print() return grid.map.flatten().count {it.type == CavePointType.SAND} } // --- Part 1 --- override fun part1ToInt(input: String): Int { return countSandFalling(input, false) } // --- Part 2 --- override fun part2ToInt(input: String): Int { return countSandFalling(input, true) + 1 } } fun main() { Day14().printToIntResults(24, 93) }
0
Kotlin
0
0
80b9ea6b25869a8267432c3a6f794fcaed2cf28b
3,657
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/leetcode/P473.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://github.com/antop-dev/algorithm/issues/494 class P473 { fun makesquare(matchsticks: IntArray): Boolean { val sum = matchsticks.sum() // 모든 성냥의 길이가 4면으로 떨어지지 않으면 안됨 if (sum % 4 > 0) return false val length = sum / 4 // 길이가 긴 성냥순으로 정렬 matchsticks.sortDescending() // 가장 긴 성냥의 길이가 한면의 길이보다 크면 안됨 if (matchsticks[0] > length) return false // 4면 val square = IntArray(4) { length } // DFS 탐색 return dfs(matchsticks, 0, square) } private fun dfs(matchsticks: IntArray, i: Int, square: IntArray): Boolean { // 성냥을 모두 사용했을 때 4면을 전부 채웠는지 체크 if (i >= matchsticks.size) { return square.all { it == 0 } } // 현재 성냥을 어느 면에 넣을지 선택 for (j in square.indices) { if (square[j] >= matchsticks[i]) { square[j] -= matchsticks[i] if (dfs(matchsticks, i + 1, square)) { return true } square[j] += matchsticks[i] // backtracking } } // 현재 성냥을 어느 면에도 넣지 못했으면 안됨 return false } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,394
algorithm
MIT License
src/main/kotlin/com/mckernant1/leetcode/FlightTraversal.kt
mckernant1
494,952,749
false
{"Kotlin": 33093}
package com.mckernant1.leetcode /** * Interview Question from Hopper. * * ChatGPT generated solution */ fun main() { val flights = listOf( Flight("A1", "City1", "City2"), Flight("A2", "City2", "City3"), Flight("A3", "City3", "City4"), Flight("A4", "City4", "City5"), Flight("A5", "City2", "City5"), Flight("A6", "City1", "City3"), Flight("A7", "City3", "City5") ) val startLocation = "City1" val endLocation = "City5" val allPaths = getAllPaths(flights, startLocation, endLocation) for (path in allPaths) { println("Route:") for (flight in path) { println("${flight.depart} to ${flight.arrival} (Flight ${flight.code})") } println() } } private data class Flight( val code: String, val depart: String, val arrival: String ) private fun getAllPaths( paths: List<Flight>, start: String, end: String ): List<List<Flight>> { // Helper function to find all paths recursively fun findPaths(current: String, visited: Set<String>): List<List<Flight>> { // Base case: if the current location is the end, return a list with an empty path if (current == end) { return listOf(emptyList()) } // Recursive case: find all possible flights from the current location val possibleFlights: List<Flight> = paths.filter { flight -> flight.depart == current && flight.arrival !in visited } // Recursive step: iterate through each possible flight and find paths from the arrival location val allPaths: MutableList<List<Flight>> = mutableListOf<List<Flight>>() for (flight: Flight in possibleFlights) { val updatedVisited: Set<String> = visited + flight.arrival val subPaths: List<List<Flight>> = findPaths(flight.arrival, updatedVisited) val extendedPaths: List<List<Flight>> = subPaths.map { subPath -> listOf(flight) + subPath } allPaths.addAll(extendedPaths) } return allPaths } return findPaths(start, setOf(start)) }
0
Kotlin
0
0
5aaa96588925b1b8d77d7dd98dd54738deeab7f1
2,170
kotlin-random
Apache License 2.0
src/Day04.kt
flexable777
571,712,576
false
{"Kotlin": 38005}
fun main() { infix fun IntRange.contains(other: IntRange): Boolean = this.first <= other.first && this.last >= other.last fun getRangePairs(line: String): Pair<IntRange, IntRange> { //Probably are some better ways of splitting val split = line.split(",") val assignment1 = split[0].split("-") val assignment1Range = assignment1[0].toInt()..assignment1[1].toInt() val assignment2 = split[1].split("-") val assignment2Range = assignment2[0].toInt()..assignment2[1].toInt() return Pair(assignment1Range, assignment2Range) } fun part1(input: List<String>): Int = input.count { line -> val (assignment1Range, assignment2Range) = getRangePairs(line) assignment1Range contains assignment2Range || assignment2Range contains assignment1Range } infix fun IntRange.overlaps(other: IntRange): Boolean { //TODO Could be improved for (n in this) { if (n in other) { return true } } return false } fun part2(input: List<String>): Int = input.count { line -> val (assignment1Range, assignment2Range) = getRangePairs(line) assignment1Range overlaps assignment2Range } val testInput = readInputAsLines("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInputAsLines("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9a739eb203c535a3d83bc5da1b6a6a90a0c7bd6
1,506
advent-of-code-2022
Apache License 2.0
src/Day17.kt
cypressious
572,916,585
false
{"Kotlin": 40281}
fun main() { fun parseTarget(input: String) = input .split("=|,|(\\.\\.)".toRegex()) .mapNotNull { it.toIntOrNull() } @Suppress("NAME_SHADOWING") fun simulate( target: List<Int>, dx: Int, dy: Int, xOnly: Boolean = false, yOnly: Boolean = false, ): Int { val (xMin, xMax, yMin, yMax) = target var x = 0 var y = 0 var dx = dx var dy = dy var wasRight = 0 > xMax var wasBelow = 0 < yMin var wasAbove = 0 > yMax var highestY = 0 while ((yOnly || !(wasRight)) && (xOnly || !(wasAbove && wasBelow))) { if ((yOnly || x in xMin..xMax) && (xOnly || y in yMin..yMax)) { return highestY } x += dx y += dy highestY = maxOf(highestY, y) if (dx > 0) { dx-- } else if (xOnly) { return -1 } dy-- if (x > xMax) wasRight = true if (y < yMin) wasBelow = true if (y > yMax) wasAbove = true } return -1 } fun part1(input: String): Int { val target = parseTarget(input) return (1..1000).maxOf { simulate(target, 0, it, yOnly = true) } } fun part2(input: String): Int { val target = parseTarget(input) val minDx = (1..1000).first { simulate(target, it, 0, xOnly = true) >= 0 } val maxDx = (0..1000).last { simulate(target, it, 0, xOnly = true) >= 0 } val minDy = (0 downTo -1000).last { simulate(target, 0, it, yOnly = true) >= 0 } val maxDy = (0..1000).last { simulate(target, 0, it, yOnly = true) >= 0 } var count = 0 for (dx in minDx..maxDx) { for (dy in minDy..maxDy) { if (simulate(target, dx, dy) >= 0) count++ } } return count } // test if implementation meets criteria from the description, like: val testInput = "target area: x=20..30, y=-10..-5" check(part1(testInput) == 45) check(part2(testInput) == 112) val input = readInput("Day17").first() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
169fb9307a34b56c39578e3ee2cca038802bc046
2,261
AdventOfCode2021
Apache License 2.0
src/Day14.kt
hufman
573,586,479
false
{"Kotlin": 29792}
import java.lang.Integer.max import java.lang.Integer.min fun main() { fun parse(input: List<String>): Array<BooleanArray> { val grid = Array(300) { BooleanArray(800) {false} } input.forEach { line -> val endPoints = line.split(" -> ").map { segment -> val pieces = segment.split(',').map { it.toInt() } Pair(pieces[0], pieces[1]) } // println("$line -> $endPoints") endPoints.windowed(2, 1).forEach { lineEnds -> // println(lineEnds) val startX = min(lineEnds[0].first, lineEnds[1].first) val endX = max(lineEnds[0].first, lineEnds[1].first) val startY = min(lineEnds[0].second, lineEnds[1].second) val endY = max(lineEnds[0].second, lineEnds[1].second) if (startY == endY) { (startX..endX).forEach { x -> grid[startY][x] = true } } if (startX == endX) { (startY..endY).forEach { y -> grid[y][startX] = true } } } } return grid } fun printGrid(grid: Array<BooleanArray>) { val endY = grid.indexOfLast { row -> row.any{it} } + 1 val startX = grid.filter { row -> row.any{it}}.minOf { row -> row.indexOfFirst { it } } - 1 val endX = grid.filter { row -> row.any{it}}.maxOf { row -> row.indexOfLast { it } } + 1 grid.take(endY).forEach { row -> println( (startX .. endX).map { x -> if (row[x]) '#' else '.' }.joinToString("") ) } } fun sprinkle(grid: Array<BooleanArray>, startX: Int = 500, startY: Int = 0, lastY: Int? = null): Pair<Int, Int>? { var x = startX var y = startY while (true) { if (y+1 == grid.size) { return null } if (y == lastY) { return Pair(x, y) } // println("Checking ${x}x$y: ${grid[y][x]}") if (!grid[y+1][x]) { y += 1 } else if (!grid[y+1][x-1]) { y += 1 x -= 1 } else if (!grid[y+1][x+1]) { y += 1 x += 1 } else { return Pair(x, y) } } } fun part1(input: List<String>): Int { val grid = parse(input) var sand = 0 printGrid(grid) while (true) { val sandLocation = sprinkle(grid) if (sandLocation != null) { // println("Found new sand particle at ${sandLocation.first}x${sandLocation.second}") grid[sandLocation.second][sandLocation.first] = true sand += 1 } else { // println("Done adding $sand grains") // printGrid(grid) return sand } } } fun part2(input: List<String>): Int { val grid = parse(input) var sand = 0 val maxY = grid.indexOfLast { row -> row.any{it} } + 2 val startX = grid.filter { row -> row.any{it}}.minOf { row -> row.indexOfFirst { it } } - 0 val endX = grid.filter { row -> row.any{it}}.maxOf { row -> row.indexOfLast { it } } + 0 (startX .. endX).forEach { x -> grid[maxY][x] = true } printGrid(grid) while (true) { val sandLocation = sprinkle(grid, lastY=maxY-1) if (sandLocation == null) { printGrid(grid) throw AssertionError("Unexpected pouring") } grid[sandLocation.second][sandLocation.first] = true sand += 1 if (sandLocation.first == 500 && sandLocation.second == 0) { println("Done adding $sand grains") printGrid(grid) return sand } } } // 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
1bc08085295bdc410a4a1611ff486773fda7fcce
3,375
aoc2022-kt
Apache License 2.0
kotlin/0935-knight-dialer.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
// Alternative solution class Solution { fun knightDialer(n: Int): Int { if (n == 1) return 10 val mod = 1_000_000_007 var moves = longArrayOf(1L, 4L, 2L, 2L) for(i in 0 until n - 1) { val temp = LongArray (4) temp[0] = moves[3] temp[1] = (2 * moves[2] + 2 * moves[3]) % mod temp[2] = moves[1] temp[3] = (2 * moves[0] + moves[1]) % mod moves = temp } var sum = 0L for (num in moves) { sum += num sum %= mod } return sum.toInt() } } // DP class Solution { fun knightDialer(n: Int): Int { val mod = 1_000_000_007 val moves = mapOf( 1 to listOf(6, 8), 2 to listOf(7, 9), 3 to listOf(4, 8), 4 to listOf(3, 9, 0), 5 to listOf(), 6 to listOf(1, 7, 0), 7 to listOf(2, 6), 8 to listOf(1, 3), 9 to listOf(4, 2), 0 to listOf(4, 6) ) var dp = LongArray (10) { 1 } for (i in 0 until (n - 1)) { val nextDP = LongArray (10) for (n in 0 until 10) { moves[n]?.forEach { j -> nextDP[j] = (nextDP[j] + dp[n]) % mod } } dp = nextDP } var sum = 0L for (num in dp) { sum += num sum %= mod } return sum.toInt() } } // recursion + memoization class Solution { fun knightDialer(n: Int): Int { val mod = 1_000_000_007 val moves = mapOf( 1 to listOf(6, 8), 2 to listOf(7, 9), 3 to listOf(4, 8), 4 to listOf(3, 9, 0), 5 to listOf(), 6 to listOf(1, 7, 0), 7 to listOf(2, 6), 8 to listOf(1, 3), 9 to listOf(4, 2), 0 to listOf(4, 6) ) val dp = Array (n + 1) { LongArray (10) { -1L } } fun dfs(n: Int, num: Int): Long { if (n == 0) return 1 if (dp[n][num] != -1L) return dp[n][num] var res = 0L moves[num]?.forEach { next -> res += dfs(n - 1, next) res %= mod } dp[n][num] = res return res } var res = 0L for (num in 0..9) { res += dfs(n - 1, num) res %= mod } return res.toInt() } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
2,532
leetcode
MIT License
src/Day03.kt
GarrettShorr
571,769,671
false
{"Kotlin": 82669}
fun main() { fun part1(input: List<String>): Int { val LOWER_OFFSET = 97-1 val UPPER_OFFSET = 65-27 var total = 0 for(line in input) { val firstHalf = line.substring(0, line.length/2) val secondHalf = line.substring(line.length/2) val shared = findSharedItem(firstHalf, secondHalf) var char = 0 if(shared.length > 0) { char = shared.toCharArray()[0].code } println("shared: $shared char: $char") total += if(char > 90) { char - LOWER_OFFSET } else { char - UPPER_OFFSET } } return total } fun part2(input: List<String>): Int { val LOWER_OFFSET = 'a'.code -1 val UPPER_OFFSET = 'A'.code -27 var total = 0 for(i in 0 .. input.size - 3 step 3) { val (elf1, elf2, elf3) = input.subList(i, i + 3) val shared = findSharedItem(elf1, elf2, elf3) var char = 0 if(shared.length > 0) { char = shared.toCharArray()[0].code } println("shared: $shared char: $char") if(char > 90) { total += char - LOWER_OFFSET } else { total += char - UPPER_OFFSET } } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") // println(part1(testInput)) println(part2(testInput)) val input = readInput("Day03") // output(part1(input)) output(part2(input)) } fun findSharedItem(str1: String, str2: String) : String{ var same = "" for(i in str1.indices) { for(j in str2.indices) { if(str1.substring(i, i+1) == str2.substring(j, j+1)) { return str1.substring(i, i + 1) } } } return "" } fun findSharedItem(str1: String, str2: String, str3: String) : String{ for(i in str1.indices) { for (j in str2.indices) { for (k in str3.indices) { if (str1.substring(i, i + 1) == str2.substring(j, j + 1) && str1.substring(i, i + 1) == str3.substring(k, k + 1)) { return str1.substring(i, i + 1) } } } } return "" }
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
2,061
AdventOfCode2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/IPO.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.Collections import java.util.PriorityQueue /** * 502. IPO * @see <a href="https://leetcode.com/problems/ipo/">Source</a> */ fun interface IPO { fun findMaximizedCapital(k: Int, w: Int, profits: IntArray, capital: IntArray): Int } class IPOGreedy : IPO { override fun findMaximizedCapital(k: Int, w: Int, profits: IntArray, capital: IntArray): Int { val n = profits.size val projects = Array(n) { Pair() } for (i in 0 until n) { projects[i] = Pair(capital[i], profits[i]) } projects.sort() val priority: PriorityQueue<Int> = PriorityQueue<Int>(Collections.reverseOrder()) var j = 0 var ans = w for (i in 0 until k) { while (j < n && projects[j].capital <= ans) { priority.add(projects[j++].profit) } if (priority.isEmpty()) { break } ans += priority.poll() } return ans } private data class Pair(var capital: Int = 0, var profit: Int = 0) : Comparable<Pair> { override fun compareTo(other: Pair): Int { return capital - other.capital } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,845
kotlab
Apache License 2.0
src/main/kotlin/Day10.kt
lanrete
244,431,253
false
null
import mathUti.gcd import kotlin.math.PI import kotlin.math.abs import kotlin.math.acos import kotlin.math.sqrt data class Coordinate(val x: Int, val y: Int) { override fun toString() = "($x, $y)" fun between(other: Coordinate): List<Coordinate> { val xGap = other.x - x val yGap = other.y - y val gcd = gcd(abs(xGap), abs(yGap)) val xUnitGap = xGap / gcd val yUnitGap = yGap / gcd return if (gcd > 0) (1 until gcd).map { Coordinate(x + it * xUnitGap, y + it * yUnitGap) } else ((gcd + 1)..-1).map { Coordinate(x + it * xUnitGap, y + it * yUnitGap) } } } typealias Stars = MutableSet<Coordinate> object Day10 : Solver() { override val day: Int = 10 override val inputs: List<String> = getInput() private fun getStars(): Stars { val stars = mutableSetOf<Coordinate>() inputs.forEachIndexed { y, s -> s.forEachIndexed { x, c -> if (c == '#') stars.add(Coordinate(x, y)) } } return stars } private var stars = getStars() private lateinit var base: Coordinate override fun question1(): String { val visibleCounts = stars .associateWith { base -> stars .filterNot { it == base } .count { base.between(it).none { between -> between in stars } } } base = visibleCounts .maxBy { it.value }?.key!! println("Base is selected at $base") return visibleCounts[base].toString() } private fun updateVisible(): MutableSet<Coordinate> { return stars .filterNot { it == base } .filter { base.between(it).none { between -> between in stars } } .toMutableSet() } private fun angel(other: Coordinate): Double { val v1x = 0 val v1y = 1 val v2x = (other.x - base.x) val v2y = -(other.y - base.y) val n1 = sqrt((v1x * v1x + v1y * v1y).toDouble()) val n2 = sqrt((v2x * v2x + v2y * v2y).toDouble()) val angel = acos((v1x * v2x + v1y * v2y) / (n1 * n2)) * 180 / PI return if (other.x < base.x) 360 - angel else angel } override fun question2(): String { var visibleStars = updateVisible() var destroyCnt = 1 while (visibleStars.isNotEmpty()) { visibleStars .associateWith { angel(it) } .toList() .sortedBy { it.second } .forEach { val destroyedStar = it.first println("$destroyCnt star to destroy is: $destroyedStar") stars.remove(destroyedStar) destroyCnt += 1 } visibleStars = updateVisible() } return "" } } fun main() { Day10.solve() }
0
Kotlin
0
1
15125c807abe53230e8d0f0b2ca0e98ea72eb8fd
2,926
AoC2019-Kotlin
MIT License
src/questions/WordSearch.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import kotlin.collections.LinkedHashSet /** * Given an m x n grid of characters board and a string word, return true if word exists in the grid. * The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are * horizontally or vertically neighboring. The same letter cell may not be used more than once. * * [Source](https://leetcode.com/problems/word-search) */ @UseCommentAsDocumentation private class WordSearch { private class Tree(val location: Location) { private val _children = mutableSetOf<Tree>() val children: Set<Tree> get() = _children.toSet() val childrenLength: Int get() = _children.size fun add(tree: Tree) { _children.add(tree) } fun add(location: Location) { add(Tree(location)) } } private val visited: LinkedHashSet<Location> = LinkedHashSet() fun exist(board: Array<CharArray>, word: String): Boolean { if (word.length > board[0].size * board.size) return false val occurrencesOfFirstChar = findOccurrencesInBoard(word[0], board) ?: return false // when word length is 1, only check occurrences if (word.length == 1 && occurrencesOfFirstChar.isNotEmpty()) { return true } // else do DFS with every first character occurrence as root for (occurrence in occurrencesOfFirstChar) { visited.clear() // restart val node = Tree(occurrence) // root if (checkIfExists(board, word.substring(1), node)) { return true } } return false } private fun checkIfExists(board: Array<CharArray>, remaining: String, node: Tree): Boolean { visited.add(node.location) val preLength = node.childrenLength addMatchingCharactersInNeighbors(node, board, remaining[0], node.location) // add children to the Tree [node] val postLength = node.childrenLength val matchExists = preLength != postLength if (matchExists && remaining.length == 1) { // only one character remains and there is already a match return true } for (child in node.children) { // DFS on children if (checkIfExists(board, remaining.substring(1), child)) { return true } else { visited.remove(child.location) // make it available for revisit later } } return false } /** * Adds the matches of [nextChar] to [node] in the vertical and horizontal neighbors if they haven't been visited yet */ private fun addMatchingCharactersInNeighbors( node: Tree, board: Array<CharArray>, nextChar: Char?, location: Pair<Int, Int>, ) { if (nextChar == null) return val (row, col) = location board.getOrNull(row + 1)?.getOrNull(col)?.also { if (nextChar == it && !visited.contains(row + 1 to col)) node.add(row + 1 to col) } board.getOrNull(row - 1)?.getOrNull(col)?.also { if (nextChar == it && !visited.contains(row - 1 to col)) node.add(row - 1 to col) } board.getOrNull(row)?.getOrNull(col + 1)?.also { if (nextChar == it && !visited.contains(row to col + 1)) node.add(row to col + 1) } board.getOrNull(row)?.getOrNull(col - 1)?.also { if (nextChar == it && !visited.contains(row to col - 1)) node.add(row to col - 1) } } private fun findOccurrencesInBoard(char: Char, board: Array<CharArray>): MutableList<Location>? { val occurrences = mutableListOf<Location>() for (row in 0..board.lastIndex) { for (col in 0..board[0].lastIndex) { val character = board[row][col] if (char == character) { occurrences.add(row to col) } } } return if (occurrences.isNotEmpty()) occurrences else null } } private typealias Location = Pair<Int, Int> fun main() { WordSearch().exist( board = arrayOf( charArrayOf('A', 'B', 'C', 'E'), charArrayOf('S', 'F', 'E', 'S'), charArrayOf('A', 'D', 'E', 'E') ), word = "ABCESEEEFSAD" ) shouldBe true WordSearch().exist( board = arrayOf( charArrayOf('A', 'B', 'C', 'E'), charArrayOf('S', 'F', 'E', 'S'), charArrayOf('A', 'D', 'E', 'E') ), word = "ABCESEEEFS" ) shouldBe true WordSearch().exist( board = arrayOf( charArrayOf('A', 'B', 'C', 'E'), charArrayOf('S', 'F', 'E', 'S'), charArrayOf('A', 'D', 'E', 'E') ), word = "ABCEFSADEESE" ) shouldBe true WordSearch().exist( board = arrayOf( charArrayOf('b'), charArrayOf('a'), charArrayOf('b'), charArrayOf('b'), charArrayOf('a') ), word = "baa" ) shouldBe false WordSearch().exist( board = arrayOf( charArrayOf('a', 'a', 'a', 'a'), charArrayOf('a', 'a', 'a', 'a'), charArrayOf('a', 'a', 'a', 'a') ), word = "aaaaaaaaaaaaa" ) shouldBe false WordSearch().exist( board = arrayOf( charArrayOf('a', 'b'), charArrayOf('c', 'd') ), word = "abcd" ) shouldBe false WordSearch().exist( board = arrayOf( charArrayOf('a') ), word = "a" ) shouldBe true WordSearch().exist( board = arrayOf( charArrayOf('A', 'B', 'C', 'E'), charArrayOf('S', 'F', 'C', 'S'), charArrayOf('A', 'D', 'E', 'E') ), word = "SEE" ) shouldBe true WordSearch().exist( board = arrayOf( charArrayOf('A', 'B', 'C', 'E'), charArrayOf('S', 'F', 'C', 'S'), charArrayOf('A', 'D', 'E', 'E') ), word = "ABCCED" ) shouldBe true WordSearch().exist( board = arrayOf( charArrayOf('A', 'B', 'C', 'E'), charArrayOf('S', 'F', 'C', 'S'), charArrayOf('A', 'D', 'E', 'E') ), word = "ABCB" ) shouldBe false }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
6,396
algorithms
MIT License
src/main/kotlin/org/dreambroke/Day1.kt
DreamBroke
729,562,380
false
{"Kotlin": 5424}
package org.dreambroke object Day1 : BaseProblem() { @JvmStatic fun main(args: Array<String>) { solvePartA() solvePartB() } override fun partA(input: String): String { val lines = Utils.splitStringByLine(input) var sum = 0 for (line in lines) { val (first, last) = findFirstAndLastDigits(line, null) if (first != null && last != null) { sum += (first + last).toInt() } } return sum.toString() } override fun partB(input: String): String { val lines = Utils.splitStringByLine(input) val digitsInWords = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") var sum = 0 for (line in lines) { val (first, last) = findFirstAndLastDigits(line, digitsInWords) if (first != null && last != null) { sum += (first + last).toInt() } } return sum.toString() } private fun findFirstAndLastDigits(line: String, digitsInWords: List<String>?): Pair<String?, String?> { var i = 0 var j = line.length - 1 var first: String? = null var last: String? = null while (i <= j) { if (first == null) { first = if (line[i].isDigit()) line[i].toString() else if (digitsInWords != null && line.substring(i).startsWithAny(digitsInWords)) digitsInWords.find { line.substring(i).startsWith(it) }?.let { (digitsInWords.indexOf(it) + 1).toString() } else null } if (last == null) { last = if (line[j].isDigit()) line[j].toString() else if (digitsInWords != null && line.substring(0, j + 1).endsWithAny(digitsInWords)) digitsInWords.find { line.substring(0, j + 1).endsWith(it) }?.let { (digitsInWords.indexOf(it) + 1).toString() } else null } if (first != null && last != null) return Pair(first, last) if (first == null) i++ if (last == null) j-- } return Pair(null, null) } private fun String.startsWithAny(list: List<String>) = list.any { this.startsWith(it) } private fun String.endsWithAny(list: List<String>) = list.any { this.endsWith(it) } }
0
Kotlin
0
0
5269cf089d4d367e69cf240c0acda568db6e4b22
2,382
AdventOfCode2023
Apache License 2.0
src/Day17.kt
ambrosil
572,667,754
false
{"Kotlin": 70967}
import java.io.File import kotlin.math.absoluteValue fun main() { val day17 = Day17(File("src/inputs/Day17.txt").readText()) println(day17.part1()) println(day17.part2()) } class Day17(input: String) { private val jets = jets(input) private val shapes = shapes() private val cave = (0..6).map { Point(it, 0) }.toMutableSet() private val down = Point(0, 1) private val up = Point(0, -1) private var jetCounter = 0 private var blockCounter = 0 fun part1(): Int { repeat(2022) { simulate() } return cave.height() } fun part2(): Long = calculateHeight(1000000000000L - 1) private fun simulate() { var currentShape = shapes.nth(blockCounter++).moveToStart(cave.minY()) do { val jetShape = currentShape * jets.nth(jetCounter++) if (jetShape in (0..6) && jetShape.intersect(cave).isEmpty()) { currentShape = jetShape } currentShape = currentShape * down } while (currentShape.intersect(cave).isEmpty()) cave += (currentShape * up) } private fun calculateHeight(targetBlockCount: Long): Long { data class State(val ceiling: List<Int>, val blockIdx: Int, val jetIdx: Int) val seen: MutableMap<State, Pair<Int, Int>> = mutableMapOf() while (true) { simulate() val state = State(cave.heuristicPrevious(), blockCounter % shapes.size, jetCounter % jets.size) if (state in seen) { val (blockCountAtLoopStart, heightAtLoopStart) = seen.getValue(state) val blocksPerLoop = blockCounter - 1L - blockCountAtLoopStart val totalLoops = (targetBlockCount - blockCountAtLoopStart) / blocksPerLoop val remainingBlocks = (targetBlockCount - blockCountAtLoopStart) - (totalLoops * blocksPerLoop) val heightGainedSinceLoop = cave.height() - heightAtLoopStart repeat (remainingBlocks.toInt()) { simulate() } return cave.height() + heightGainedSinceLoop * (totalLoops - 1) } seen[state] = blockCounter - 1 to cave.height() } } private operator fun IntRange.contains(set: Set<Point>): Boolean = set.all { it.x in this } private operator fun Set<Point>.times(point: Point): Set<Point> = map { it + point }.toSet() private fun Set<Point>.minY(): Int = minOf { it.y } private fun Set<Point>.height(): Int = minY().absoluteValue private fun Set<Point>.heuristicPrevious(): List<Int> { return groupBy { it.x } .map { pointList -> pointList.value.minBy { it.y } } .let { val normalTo = minY() it.map { point -> normalTo - point.y } } } private fun Set<Point>.moveToStart(ceilingHeight: Int): Set<Point> = map { it + Point(2, ceilingHeight - 4) }.toSet() private fun shapes(): List<Set<Point>> = listOf( setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0)), setOf(Point(1, 0), Point(0, -1), Point(1, -1), Point(2, -1), Point(1, -2)), setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, -1), Point(2, -2)), setOf(Point(0, 0), Point(0, -1), Point(0, -2), Point(0, -3)), setOf(Point(0, 0), Point(1, 0), Point(0, -1), Point(1, -1)) ) private fun jets(input: String): List<Point> = input.map { when (it) { '>' -> Point(1, 0) '<' -> Point(-1, 0) else -> throw IllegalStateException("Wrong jet $it") } } }
0
Kotlin
0
0
ebaacfc65877bb5387ba6b43e748898c15b1b80a
3,738
aoc-2022
Apache License 2.0
src/Day02.kt
acunap
573,116,784
false
{"Kotlin": 23918}
import java.lang.IllegalArgumentException import java.util.* import kotlin.time.ExperimentalTime import kotlin.time.measureTime @OptIn(ExperimentalTime::class) fun main() { fun part1(input: List<String>): Int { return input .map { it.split(" ") } .map { listOf(ShapeStrategy.fromString(it[0]), ShapeStrategy.fromString(it[1])) } .sumOf { (opponent, player) -> player.pointsAsShape() + player.pointsAsOutcome(opponent) } } fun part2(input: List<String>): Int { return input .map { it.split(" ") } .sumOf { val opponent = ShapeStrategy.fromString(it[0]) val outcome = Outcomes.fromString(it[1]) val player = ShapeStrategy.fromOutcomeExpected(outcome, opponent) player.pointsAsShape() + player.pointsAsOutcome(opponent) } } val time = measureTime { val input = readLines("Day02") println(part1(input)) println(part2(input)) } println("Real data time $time.") val timeTest = measureTime { val testInput = readLines("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) } println("Test data time $timeTest.") } interface ShapeStrategy { fun pointsAsShape(): Int fun pointsAsOutcome(other: ShapeStrategy): Int fun winsTo(): ShapeStrategy fun drawsTo(): ShapeStrategy fun losesTo(): ShapeStrategy companion object { fun fromString(code: String) = when(code) { "A", "X" -> RockStrategy() "B", "Y" -> PaperStrategy() "C", "Z" -> ScissorStrategy() else -> throw IllegalArgumentException() } fun fromOutcomeExpected(outcome: Outcomes, opponent: ShapeStrategy) = when(outcome) { Outcomes.LOSE -> opponent.winsTo() Outcomes.DRAW -> opponent.drawsTo() Outcomes.WIN -> opponent.losesTo() } } } class RockStrategy: ShapeStrategy { override fun pointsAsShape() = 1 override fun pointsAsOutcome(other: ShapeStrategy) = when(other) { is RockStrategy -> 3 is PaperStrategy -> 0 is ScissorStrategy -> 6 else -> throw IllegalArgumentException() } override fun winsTo() = ScissorStrategy() override fun drawsTo() = RockStrategy() override fun losesTo() = PaperStrategy() } class PaperStrategy: ShapeStrategy { override fun pointsAsShape() = 2 override fun pointsAsOutcome(other: ShapeStrategy) = when(other) { is RockStrategy -> 6 is PaperStrategy -> 3 is ScissorStrategy -> 0 else -> throw IllegalArgumentException() } override fun winsTo() = RockStrategy() override fun drawsTo() = PaperStrategy() override fun losesTo() = ScissorStrategy() } class ScissorStrategy: ShapeStrategy { override fun pointsAsShape() = 3 override fun pointsAsOutcome(other: ShapeStrategy) = when(other) { is RockStrategy -> 0 is PaperStrategy -> 6 is ScissorStrategy -> 3 else -> throw IllegalArgumentException() } override fun winsTo() = PaperStrategy() override fun drawsTo() = ScissorStrategy() override fun losesTo() = RockStrategy() } enum class Outcomes(val code: String) { LOSE("X"), DRAW("Y"), WIN("Z"); companion object { fun fromString(code: String) = Outcomes.values().find { outcome -> outcome.code == code } ?: throw IllegalArgumentException() } }
0
Kotlin
0
0
f06f9b409885dd0df78f16dcc1e9a3e90151abe1
3,538
advent-of-code-2022
Apache License 2.0
src/main/kotlin/leetcode/kotlin/hashtable/438. Find All Anagrams in a String.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.hashtable fun main() { println(findAnagrams2("cbaebabacd", "abc")) println(findAnagrams2("abab", "ab")) } // brute force private fun findAnagrams(s: String, p: String): List<Int> { var frequencyMap = p.toCharArray().groupBy { it }.mapValues { it.value.size } fun isAnagram(start: Int): Boolean { var map = frequencyMap.toMutableMap() for (i in start until start + p.length) { if (map.containsKey(s[i])) { map[s[i]] = map[s[i]]!! - 1 if (map[s[i]] == 0) map.remove(s[i]) } else { return false } } return true } var anslist = mutableListOf<Int>() for (i in 0 until s.length - p.length + 1) { if (isAnagram(i)) anslist.add(i) } return anslist } // sliding window private fun findAnagrams2(s: String?, p: String?): List<Int> { if (p == null || s == null) return emptyList() val list = mutableListOf<Int>() var frequencyMap = p.toCharArray().groupBy { it }.mapValues { it.value.size }.toMutableMap() // two points, initialize count to p's length var left = 0 var right = 0 var matches = p.length while (right < s.length) { var value = frequencyMap.get(s[right]) value?.let { if (it >= 1) matches-- frequencyMap.put(s[right], it - 1) } right++ if (matches == 0) list.add(left) if (right - left == p.length) { var value = frequencyMap.get(s[left]) value?.let { if (it >= 0) matches++ frequencyMap.put(s[left], value + 1) } left++ } } return list } fun findAnagrams3(txt: String, pat: String): List<Int> { val ans = mutableListOf<Int>() if (txt.length < pat.length) return ans val P = IntArray(256) val T = IntArray(256) for (i in pat.indices) { P[pat[i].toInt()]++ T[txt[i].toInt()]++ } for (i in pat.length until txt.length) { if (isEqual(T, P)) ans.add(i - pat.length) T[txt[i].toInt()]++ T[txt[i - pat.length].toInt()]-- } if (isEqual(T, P)) ans.add(txt.length - pat.length) return ans } // O(1) function, as hash size does not increase with input size private fun isEqual(hash1: IntArray, hash2: IntArray): Boolean { for (i in hash1.indices) { if (hash1[i] != hash2[i]) return false } return true }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
2,490
kotlinmaster
Apache License 2.0
src/day5/Day5.kt
blundell
572,916,256
false
{"Kotlin": 38491}
package day5 import readInput data class Instruction(val moves: Int, val from: Int, val to: Int) { override fun toString(): String { return "move $moves from $from to $to" } } fun main() { fun parseStacks(input: List<String>): List<ArrayDeque<Char>> { val captureCrates = "( {3}|\\[[A-Z]]) ?+".toRegex() val rowsOfCrates = mutableListOf<List<Char>>() for (line in input) { if (line.startsWith(" 1")) { // no more crates to parse break } val matchResult = captureCrates.findAll(line) val row = matchResult.map { it.groupValues[1].trim().getOrElse(1) { ' ' } }.toList() rowsOfCrates.add(row) } // Convert parsed rows into stacks val stacks = mutableListOf<ArrayDeque<Char>>() var rowIndex = -1 for (row in 0..rowsOfCrates.first().size) { stacks.add(ArrayDeque(mutableListOf())) } for (row in rowsOfCrates) { for (crate in row) { rowIndex++ if (crate != ' ') { stacks[rowIndex].addLast(crate) } } rowIndex = -1 } return stacks } fun parseInstructions(input: List<String>): List<Instruction> { val captureMoves = "[0-9]+".toRegex() var atInstructions = false val instructions = mutableListOf<Instruction>() for (line in input) { if (line.isBlank()) { atInstructions = true continue } if (!atInstructions) { continue } val matchResult = captureMoves.findAll(line) val v = matchResult.map { it.groupValues.first().toInt() }.toList() instructions.add(Instruction(v[0], v[1], v[2])) } return instructions } fun part1(input: List<String>): String { val stacks: List<ArrayDeque<Char>> = parseStacks(input) val instructions: List<Instruction> = parseInstructions(input) for (instruction in instructions) { for (n in 1..instruction.moves) { val toStack = stacks[instruction.to - 1] val fromStack = stacks[instruction.from - 1] toStack.addFirst(fromStack.removeFirst()) // println(instruction) // println(stacks) // println("--") } } return stacks.map { it.firstOrNull() ?: "" }.joinToString(separator = "") } fun part2(input: List<String>): String { val stacks: List<ArrayDeque<Char>> = parseStacks(input) val instructions: List<Instruction> = parseInstructions(input) for (instruction in instructions) { val toStack = stacks[instruction.to - 1] val fromStack = stacks[instruction.from - 1] val moveAll = mutableListOf<Char>() for (n in 0 until instruction.moves) { val crate = fromStack[n] moveAll.add(crate) } for (n in instruction.moves - 1 downTo 0) { fromStack.removeAt(n) } toStack.addAll(0, moveAll) // println(instruction) // println(stacks) // println("--") } return stacks.map { it.firstOrNull() ?: "" }.joinToString(separator = "") } // test if implementation meets criteria from the description, like: val testInput = readInput("day5/Day5_test") val part1Result = part1(testInput) check(part1Result == "CMZ") { "Got [$part1Result instead of CMZ." } val part2Result = part2(testInput) check(part2Result == "MCD") { "Got [$part2Result] instead of CMZ." } val input = readInput("day5/Day5") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f41982912e3eb10b270061db1f7fe3dcc1931902
3,915
kotlin-advent-of-code-2022
Apache License 2.0
gcj/y2022/round2/b_small.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2022.round2 import kotlin.math.round import kotlin.math.sqrt private fun dumb(m: Int): Int { val a = List(m + 2) { BooleanArray(m + 2) } val b = List(m + 2) { BooleanArray(m + 2) } for (r in 0..m) { for (x in 0..r) { val y = round(sqrt(1.0 * r * r - x * x)).toInt() b[x][y] = true b[y][x] = true } } var res = 0 for (x in 0..m + 1) for (y in 0..m + 1) { a[x][y] = round(sqrt(1.0 * x * x + y * y)) <= m if (a[x][y] != b[x][y]) { require(a[x][y]) res += 1 } } return res } private fun solve() = dumb(readInt()) * 4L fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
715
competitions
The Unlicense
src/day21/Day21.kt
dakr0013
572,861,855
false
{"Kotlin": 105418}
package day21 import kotlin.test.assertEquals import readInput fun main() { fun part1(input: List<String>): Long { return Expressions(input).root().value() } fun part2(input: List<String>): Long { return Expressions(input).resolveHumn() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") assertEquals(152, part1(testInput)) assertEquals(301, part2(testInput)) val input = readInput("Day21") println(part1(input)) println(part2(input)) } val mathOperationLinePattern = Regex("(\\w{4}): (\\w{4}) ([+\\-*/]) (\\w{4})") val specificNumberLinePattern = Regex("(\\w{4}): (\\d+)") typealias VariableName = String class Expressions(input: List<String>) { private val references = mutableMapOf<VariableName, Reference>() init { input.forEach { parse(it) } } fun root(): MathOperation = references["root"]!!.actualVariable as MathOperation fun resolveHumn(): Long { root().operator = "compare" references.remove("humn") return resolve("humn").value() } private fun resolve(name: VariableName): Variable { if (references.containsKey(name) && references[name]!!.actualVariable is Value) return references[name]!! references.remove(name) val referenceToOperation = references.values.single { it.canResolve(name) } if (referenceToOperation.name == name) return referenceToOperation val operation = referenceToOperation.actualVariable as MathOperation return if (operation.variable1.name == name) when (operation.operator) { "+" -> MathOperation(name, resolve(operation.name), operation.variable2, "-") "-" -> MathOperation(name, resolve(operation.name), operation.variable2, "+") "*" -> MathOperation(name, resolve(operation.name), operation.variable2, "/") "/" -> MathOperation(name, resolve(operation.name), operation.variable2, "*") "compare" -> operation.variable2 else -> error("unknown operator, should not happen") } else when (operation.operator) { "+" -> MathOperation(name, resolve(operation.name), operation.variable1, "-") "-" -> MathOperation(name, operation.variable1, resolve(operation.name), "-") "*" -> MathOperation(name, resolve(operation.name), operation.variable1, "/") "/" -> MathOperation(name, operation.variable1, resolve(operation.name), "/") "compare" -> operation.variable1 else -> error("unknown operator, should not happen") } } private fun parse(input: String): Variable { return if (mathOperationLinePattern.matches(input)) { val (name, nameVariable1, operator, nameVariable2) = mathOperationLinePattern.matchEntire(input)!!.groupValues.drop(1) MathOperation( name, references.getOrPut(nameVariable1) { Reference(nameVariable1) }, references.getOrPut(nameVariable2) { Reference(nameVariable2) }, operator) .also { references.getOrPut(name) { Reference(name) }.actualVariable = it } } else { val (name, number) = specificNumberLinePattern.matchEntire(input)!!.groupValues.drop(1) Value(name, number.toLong()).also { references.getOrPut(name) { Reference(name) }.actualVariable = it } } } } sealed interface Variable { val name: VariableName fun value(): Long fun canResolve(name: VariableName): Boolean } class Value(override val name: VariableName, val number: Long) : Variable { override fun value(): Long = number override fun canResolve(name: VariableName) = this.name == name } class MathOperation( override val name: VariableName, val variable1: Variable, val variable2: Variable, var operator: String ) : Variable { override fun value(): Long { return when (operator) { "+" -> variable1.value() + variable2.value() "-" -> variable1.value() - variable2.value() "*" -> variable1.value() * variable2.value() "/" -> variable1.value() / variable2.value() "compare" -> variable1.value().compareTo(variable2.value()).toLong() else -> error("unknown operator, should not happen") } } override fun canResolve(name: VariableName) = variable1.name == name || variable2.name == name || this.name == name } class Reference(override val name: VariableName) : Variable { lateinit var actualVariable: Variable override fun value() = actualVariable.value() override fun canResolve(name: VariableName) = actualVariable.canResolve(name) }
0
Kotlin
0
0
6b3adb09f10f10baae36284ac19c29896d9993d9
4,594
aoc2022
Apache License 2.0
src/main/kotlin/net/dilius/daily/coding/problem/n00x/008.kt
diliuskh
298,020,928
false
null
package net.dilius.daily.coding.problem.n00x import net.dilius.daily.coding.problem.Problem data class UnivalTree(val left: UnivalTree?, val right: UnivalTree?, val value: Int) class UnivalTreeCounter : Problem<UnivalTree, Int> { override fun solve(input: UnivalTree): Int { return solve0(input) } fun solve0(input: UnivalTree?): Int { if (input == null) { return 0 } if (input.left == null && input.right == null) { return 1 } return ((if (isUnival(input)) 1 else 0) + solve0(input.left) + solve0(input.right)) } private fun isUnival(input: UnivalTree): Boolean { return isLeaf(input) || isUnival0(input, input.value) } private fun isUnival0(root: UnivalTree?, value: Int): Boolean { if (root == null) return true if (root.value == value) { return isUnival0(root.left, value) && isUnival0(root.right, value) } return false } private fun isLeaf(input: UnivalTree): Boolean { return input.left == null && input.right == null } } class LinearUnivalTreeCounter: Problem<UnivalTree, Int> { override fun solve(input: UnivalTree): Int { return solve0(input).second } fun solve0(root: UnivalTree?): Pair<Boolean, Int> { if (root == null) { return true to 0 } val (isLeftUnival, leftUnivalCount) = solve0(root.left) val (isRightUnival, rightUnivalCount) = solve0(root.right) val totalUnivalCount = leftUnivalCount + rightUnivalCount if (isLeftUnival && isRightUnival) { if (root.left != null && root.value != root.left.value) { return false to totalUnivalCount } if (root.right != null && root.value != root.right.value) { return false to totalUnivalCount } return true to 1 + totalUnivalCount } return false to totalUnivalCount } }
0
Kotlin
0
0
7e5739f87dbce2b56d24e7bab63b6cee6bbc54bc
2,014
dailyCodingProblem
Apache License 2.0
src/Day10.kt
bin-wang
572,801,360
false
{"Kotlin": 19395}
import kotlin.math.abs fun main() { data class State(val register: Int, val history: List<Int>) fun solve(input: List<String>): Int { val finalState = input.fold(State(1, listOf())) { acc, line -> when (line) { "noop" -> State(acc.register, acc.history + acc.register) else -> { val increment = line.split(" ")[1].toInt() State(acc.register + increment, acc.history + List(2) { acc.register }) } } } // visualization for part 2 finalState.history.chunked(40).forEach { val line = it.mapIndexed { index, i -> if (abs(index - i) <= 1) { '█' } else { ' ' } }.joinToString(separator = "") println(line) } // return answer to part 1 return finalState.history.mapIndexedNotNull { index, v -> when { (index + 1 - 20) % 40 == 0 -> (index + 1) * v else -> null } }.sum() } val testInput = readInput("Day10_test") solve(testInput) val input = readInput("Day10") solve(input) }
0
Kotlin
0
0
dca2c4915594a4b4ca2791843b53b71fd068fe28
1,260
aoc22-kt
Apache License 2.0
src/Day02.kt
MT-Jacobs
574,577,538
false
{"Kotlin": 19905}
import Shape.* import GameState.* fun main() { fun part1(input: List<String>): Int { return input.map { it[0].toShape() to it[2].toShape() }.sumOf { (theirShape, myShape) -> myShape.evaluateAgainst(theirShape).score + myShape.score } } fun part2(input: List<String>): Int { return input.map { it[0].toShape() to it[2].toStrategy() }.sumOf { (theirShape, myStrategy) -> val myShape: Shape = theirShape.chooseStrategy(myStrategy) myStrategy.score + myShape.score } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") val part1Result = part1(testInput) check(part1Result == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) } enum class Shape(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3) } enum class GameState(val score: Int) { LOSE(0), DRAW(3), WIN(6) } fun Char.toShape(): Shape = when(this) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> throw RuntimeException("Bad letter.") } fun Char.toStrategy(): GameState = when(this) { 'X' -> LOSE 'Y' -> DRAW 'Z' -> WIN else -> throw RuntimeException("Bad letter.") } fun Shape.evaluateAgainst(otherShape: Shape): GameState = when (this) { ROCK -> { when (otherShape) { ROCK -> DRAW PAPER -> LOSE SCISSORS -> WIN } } PAPER -> { when (otherShape) { ROCK -> WIN PAPER -> DRAW SCISSORS -> LOSE } } SCISSORS -> { when (otherShape) { ROCK -> LOSE PAPER -> WIN SCISSORS -> DRAW } } } fun Shape.chooseStrategy(strategy: GameState): Shape = when (this) { ROCK -> { when (strategy) { WIN -> PAPER DRAW -> ROCK LOSE -> SCISSORS } } PAPER -> { when (strategy) { WIN -> SCISSORS DRAW -> PAPER LOSE -> ROCK } } SCISSORS -> { when (strategy) { WIN -> ROCK DRAW -> SCISSORS LOSE -> PAPER } } }
0
Kotlin
0
0
2f41a665760efc56d531e56eaa08c9afb185277c
2,478
advent-of-code-2022
Apache License 2.0
src/day22/Parser.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day22 import readInput import java.io.File import java.lang.IllegalStateException import java.util.regex.Pattern enum class Direction { LEFT, RIGHT; companion object { fun parse (encoded: Char): Direction { return when (encoded) { 'L' -> Direction.LEFT 'R' -> Direction.RIGHT else -> throw IllegalArgumentException ("Found a: $encoded") } } } } enum class Facing (val value: Int, val render: Char) { LEFT(2, '<'), RIGHT(0, '>'), UP(3, '^'), DOWN(1, 'v'); val invert: Facing get () = when (this) { LEFT -> RIGHT RIGHT -> LEFT UP -> DOWN DOWN -> UP } val left: Facing get () = turn (Direction.LEFT) val right: Facing get () = turn (Direction.RIGHT) fun turn (direction: Direction): Facing { when (direction) { Direction.LEFT -> { return when (this) { LEFT -> DOWN UP -> LEFT RIGHT -> UP DOWN -> RIGHT } } Direction.RIGHT -> { return when (this) { LEFT -> UP UP -> RIGHT RIGHT -> DOWN DOWN -> LEFT } } } } fun same (other: Facing): Boolean = same (this, other) companion object { val SAME = mutableMapOf<Pair<Facing, Facing>, Boolean>().apply { Facing.values().forEach { this[Pair(it, it)] = true this[Pair(it, it.invert)] = false } val set = { f1: Facing, f2: Facing, same: Boolean -> this[Pair(f1, f2)] = same this[Pair(f2, f1)] = same } set (UP, LEFT, false) set (UP, RIGHT, true) set (DOWN, LEFT, true) set (DOWN, RIGHT, false) } fun same (f1: Facing, f2: Facing): Boolean = SAME[Pair(f1, f2)] as Boolean } } enum class Tile (val encoded: Char) { WALL ('#'), FLOOR ('.') } data class Point (val x: Int, val y: Int) { fun add (other: Point): Point = Point (x + other.x, y + other.y) fun move (facing: Facing): Point = add (delta (facing)) override fun toString(): String = "($x, $y)" companion object { fun delta (facing: Facing): Point { return when (facing) { Facing.UP -> Point (0, - 1) Facing.DOWN -> Point (0, 1) Facing.RIGHT -> Point (+ 1, 0) Facing.LEFT -> Point (- 1, 0) } } } } sealed class Step { data class Forward (val steps: Int) : Step () { override fun toString (): String = "$steps" } data class Turn (val direction: Direction) : Step () { override fun toString (): String = "$direction" } } fun loadSimple(): Board = Board.parse (File ("src/day22/day22-simple.txt").readText()) fun loadBoard (example: Boolean): Board { val input = readInput(22, example) val board = Board.parse (input) return board } fun main (args: Array<String>) { val example = true val board = loadBoard(example) board.dump () return }
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
3,334
advent_of_code_2022
Apache License 2.0
src/TwoToOne.kt
adamWeesner
149,649,774
false
null
import org.junit.Test import java.util.* import kotlin.test.assertEquals /** * Two To One Code Kata * https://www.codewars.com/kata/5656b6906de340bd1b0000ac * * @author <NAME> * @since 9/15/2018 */ fun longest(s1: String, s2: String): String = (s1 + s2).split("").sorted().distinct().joinToString("", "", "") class TwoToOneTest { //......................... @Test fun test() { println("longest Fixed Tests") assertEquals("aehrsty", longest("aretheyhere", "yestheyarehere")) assertEquals("abcdefghilnoprstu", longest("loopingisfunbutdangerous", "lessdangerousthancoding")) assertEquals("acefghilmnoprstuy", longest("inmanylanguages", "theresapairoffunctions")) assertEquals("adefghklmnorstu", longest("lordsofthefallen", "gamekult")) assertEquals("acdeorsw", longest("codewars", "codewars")) assertEquals("acdefghilmnorstuw", longest("agenerationmustconfrontthelooming", "codewarrs")) } @Test fun test1() { println("Random Tests") for (i in 0..149) { val s1 = doEx(randInt(1, 10)) val s2 = doEx(randInt(1, 8)) //println(s1); //println(s2); //println(longestSol(s1, s2)); //println("****"); assertEquals(longestSol18(s1, s2), longest(s1, s2)) } } companion object { fun randInt(min: Int, max: Int): Int { return min + (Math.random() * ((max - min) + 1)).toInt() } fun doEx(k: Int): String { var res = "" var n = -1 for (i in 0..14) { n = randInt(97 + k, 122) for (j in 0 until randInt(1, 5)) res += n.toChar() } return res } fun longestSol18(s1: String, s2: String): String { var alpha1 = IntArray(26) for (i in alpha1.indices) alpha1[i] = 0 var alpha2 = IntArray(26) for (i in alpha2.indices) alpha2[i] = 0 for (i in 0 until s1.length) { val c = s1.get(i).toInt() if (c >= 97 && c <= 122) alpha1[c - 97]++ } for (i in 0 until s2.length) { val c = s2.get(i).toInt() if (c >= 97 && c <= 122) alpha2[c - 97]++ } var res = "" for (i in 0..25) { if (alpha1[i] != 0) { res += (i + 97).toChar() alpha2[i] = 0 } } for (i in 0..25) { if (alpha2[i] != 0) res += (i + 97).toChar() } val lstr = res.split(("").toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray() Arrays.sort(lstr) res = lstr.joinToString("") return res } } }
0
Kotlin
0
0
aa988ccbaafceef898b16fb6da68e6bf1d04137c
2,923
Code-Katas
MIT License
src/main/kotlin/g2401_2500/s2478_number_of_beautiful_partitions/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2478_number_of_beautiful_partitions // #Hard #String #Dynamic_Programming #2023_07_05_Time_230_ms_(100.00%)_Space_38.1_MB_(100.00%) class Solution { fun beautifulPartitions(s: String, k: Int, l: Int): Int { val cs = s.toCharArray() val n = cs.size if (!prime(cs[0]) || prime(cs[n - 1])) { return 0 } val dp = Array(k) { IntArray(n) } run { var i = n - l while (0 <= i) { dp[0][i] = if (prime(cs[i])) 1 else 0 --i } } for (i in 1 until k) { var sum = 0 run { var j = n - i * l while (0 <= j) { val mod = 1e9.toInt() + 7 if (0 == dp[i - 1][j]) { dp[i - 1][j] = sum } else if (0 != j && 0 == dp[i - 1][j - 1]) { sum = (sum + dp[i - 1][j]) % mod } --j } } var p = l - 1 var j = 0 while (j + l * i < n) { if (!prime(cs[j])) { ++j continue } p = Math.max(p, j + l - 1) while (prime(cs[p])) { p++ } if (0 == dp[i - 1][p]) { break } dp[i][j] = dp[i - 1][p] ++j } } return dp[k - 1][0] } private fun prime(c: Char): Boolean { return '2' == c || '3' == c || '5' == c || '7' == c } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,684
LeetCode-in-Kotlin
MIT License
src/cn/leetcode/codes/simple121/Simple121.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple121 import cn.leetcode.codes.out import kotlin.math.max fun main() { val nums = intArrayOf(7,1,5,3,6,4) // val nums = intArrayOf(7,6,4,3,1) val max = maxProfit(nums) val max2 = maxProfit2(nums) out("max = $max") out("max2 = $max2") } /* 121. 买卖股票的最佳时机 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。 注意:你不能在买入股票前卖出股票。 示例 1: 输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。 示例 2: 输入: [7,6,4,3,1] 输出: 0 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 */ //暴力破解 fun maxProfit(prices: IntArray): Int { if (prices.isEmpty()) return 0 var ans = 0 var i = 0 while (i < prices.size){ var j = i+1 while (j < prices.size) { val sum = prices[j] - prices[i] ans = max(sum, ans) j++ } i++ } return ans } //使用哨兵简化逻辑 fun maxProfit2(prices: IntArray): Int { if (prices.isEmpty()) return 0 //最小买入时机 var minProfit = Int.MAX_VALUE //最大卖出时机 var maxProfit = 0 for (n in prices){ //找到最小买入时机 if (n < minProfit){ minProfit = n }else if (n - minProfit > maxProfit){ //如果此时卖出 大于之前最大值 maxProfit = n - minProfit } } return maxProfit }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
1,912
LeetCodeSimple
Apache License 2.0
src/Day02.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val him = it.split(" ")[0] val me = it.split(" ")[1] val gameResult = if (him == "A" && me == "X") { 3 + 1 } else if (him == "A" && me == "Y") { 6 + 2 } else if (him == "A" && me == "Z") { 0 + 3 } else if (him == "B" && me == "X") { 0 + 1 } else if (him == "B" && me == "Y") { 3 + 2 } else if (him == "B" && me == "Z") { 6 + 3 } else if (him == "C" && me == "X") { 6 + 1 } else if (him == "C" && me == "Y") { 0 + 2 } // (him == "C" && me == "Z") else { 3 + 3 } gameResult } } fun part2(input: List<String>): Int { return input.sumOf { val him = it.split(" ")[0] val me = it.split(" ")[1] val gameResult = if (him == "A" && me == "X") { 0 + 3 } else if (him == "A" && me == "Y") { 3 + 1 } else if (him == "A" && me == "Z") { 6 + 2 } else if (him == "B" && me == "X") { 0 + 1 } else if (him == "B" && me == "Y") { 3 + 2 } else if (him == "B" && me == "Z") { 6 + 3 } else if (him == "C" && me == "X") { 0 + 2 } else if (him == "C" && me == "Y") { 3 + 3 } // (him == "C" && me == "Z") else { 6 + 1 } gameResult } } val testInput = readLines("Day02_test") val input = readLines("Day02") check(part1(testInput) == 15) check(part2(testInput) == 12) println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
1,987
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day18.kt
clechasseur
435,726,930
false
{"Kotlin": 315943}
package io.github.clechasseur.adventofcode2021 import io.github.clechasseur.adventofcode2021.data.Day18Data import kotlin.math.ceil import kotlin.math.floor object Day18 { private val data = Day18Data.data fun part1(): Int = data.lines().map { it.iterator().nextNode() }.reduce { acc, n -> acc + n }.magnitude fun part2(): Int { val nodes = data.lines().map { it.iterator().nextNode() } return nodes.indices.flatMap { i -> nodes.indices.filter { it != i }.map { j -> nodes[i] + nodes[j] } }.maxOf { it.magnitude } } private class Explosion(var leftParticle: Int?, var rightParticle: Int?) private class Node(var value: Int?, var left: Node?, var right: Node?) { val isLeaf: Boolean get() = value != null val magnitude: Int get() = value ?: (3 * left!!.magnitude + 2 * right!!.magnitude) fun clone(): Node = if (isLeaf) makeLeaf(value!!) else makePair(left!!.clone(), right!!.clone()) fun reduce(): Node { val node = clone() while (true) { if (node.explode(0) == null) { if (!node.split()) { break } } } return node } private fun smash(particle: Int, goLeft: Boolean) { if (isLeaf) { value = value!! + particle } else if (goLeft) { left!!.smash(particle, true) } else { right!!.smash(particle, false) } } private fun explode(depth: Int): Explosion? = if (isLeaf) null else when (depth) { 4 -> { val explosion = Explosion(left!!.magnitude, right!!.magnitude) left = null right = null value = 0 explosion } else -> { var explosion = left!!.explode(depth + 1) if (explosion != null) { if (explosion.rightParticle != null) { right!!.smash(explosion.rightParticle!!, true) explosion.rightParticle = null } } else { explosion = right!!.explode(depth + 1) if (explosion?.leftParticle != null) { left!!.smash(explosion.leftParticle!!, false) explosion.leftParticle = null } } explosion } } private fun split(): Boolean = if (isLeaf) { if (value!! > 9) { left = makeLeaf(floor(value!!.toDouble() / 2).toInt()) right = makeLeaf(ceil(value!!.toDouble() / 2).toInt()) value = null true } else { false } } else left!!.split() || right!!.split() override fun toString(): String = if (isLeaf) value!!.toString() else "[${left!!},${right!!}]" } private fun makeLeaf(value: Int) = Node(value, null, null) private fun makePair(left: Node, right: Node) = Node(null, left, right) private operator fun Node.plus(right: Node): Node = makePair(this, right).reduce() private fun Iterator<Char>.nextNode(): Node = when (val c = next()) { '[' -> nextPair() else -> makeLeaf(c.toString().toInt()) } private fun Iterator<Char>.nextPair(): Node { val left = nextNode() val comma = next() require(comma == ',') { "Invalid pair sequence, expected comma" } val right = nextNode() val closing = next() require(closing == ']') { "Invalid pair sequence, expected closing bracket" } return makePair(left, right) } }
0
Kotlin
0
0
4b893c001efec7d11a326888a9a98ec03241d331
3,868
adventofcode2021
MIT License
src/kotlin/_2022/Task11.kt
MuhammadSaadSiddique
567,431,330
false
{"Kotlin": 20410}
package _2022 import Task import readInput import utils.Numbers.lowestCommonMultiple import utils.Parse.firstInt typealias ReliefWorryLevel = (Long) -> Long typealias Inspection = Pair<Int, Long> object Task11 : Task { private val lcmDividers = lowestCommonMultiple(parseInput().map { it.divisibleBy }) override fun partA() = chaseMonkeys(rounds = 20) { worryLevel -> worryLevel / 3 } override fun partB() = chaseMonkeys(rounds = 10_000) { worryLevel -> worryLevel % lcmDividers } private fun chaseMonkeys(rounds: Int, reliefWorryLevel: ReliefWorryLevel): Long = parseInput() .let { monkeys -> (0 until rounds).fold(Array(monkeys.size) { 0L }) { inspections, _ -> monkeys.forEachIndexed { index, monkey -> monkey.`throw`(reliefWorryLevel).forEach { (throwIndex, item) -> inspections[index]++ monkeys[throwIndex].catch(item) } } inspections } } .sortedDescending() .take(2) .reduce { acc, inspections -> acc * inspections } private fun parseInput() = readInput("_2022/11") .split("\n\n") .mapIndexed { index, it -> it.split("\n").let(::Monkey) } private data class Monkey( val items: ArrayDeque<Long>, val operation: String, val divisibleBy: Int, val throwIndexes: Map<Boolean, Int> ) { constructor(it: List<String>) : this( items = ArrayDeque(it[1].split(' ', ',').mapNotNull { it.toLongOrNull() }), operation = it[2].split('=')[1].trim(), divisibleBy = it[3].firstInt(), throwIndexes = mapOf( true to it[4].firstInt(), false to it[5].firstInt() ) ) fun `throw`(reliefWorryLevel: ReliefWorryLevel): List<Inspection> = (0 until items.size).fold(listOf()) { inspections, _ -> val item = items.removeFirst() val worryLevel = when { operation == "old * old" -> item * item operation.startsWith("old *") -> item * operation.firstInt() operation.startsWith("old +") -> item + operation.firstInt() else -> error("undefined operation $operation") } val inspection = reliefWorryLevel(worryLevel).let { manageableWorryLevel -> val isDivisible = manageableWorryLevel % divisibleBy == 0L val throwIndex = throwIndexes[isDivisible] ?: error("undefined index $isDivisible") throwIndex to manageableWorryLevel } inspections + inspection } fun catch(item: Long) { items.add(item) } } }
0
Kotlin
0
0
3893ae1ac096c56e224e798d08d7fee60e299a84
2,915
AdventCode-Kotlin
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day24.kt
clechasseur
567,968,171
false
{"Kotlin": 493887}
package io.github.clechasseur.adventofcode.y2022 import io.github.clechasseur.adventofcode.util.Direction import io.github.clechasseur.adventofcode.util.Pt import io.github.clechasseur.adventofcode.util.move import io.github.clechasseur.adventofcode.y2022.data.Day24Data object Day24 { private val input = Day24Data.input fun part1(): Int = minutesToGoal(input.toValley(), thereAndBackAgain = false) fun part2(): Int = minutesToGoal(input.toValley(), thereAndBackAgain = true) private val xConstraints = 1..(input.lines().first().length - 2) private val yConstraints = 1..(input.lines().size - 2) private val entrance = Pt(xConstraints.first, 0) private val exit = Pt(xConstraints.last, yConstraints.last + 1) private val blizzardDirections = mapOf( '<' to Direction.LEFT, '^' to Direction.UP, '>' to Direction.RIGHT, 'v' to Direction.DOWN, ) private data class Blizzard(val pos: Pt, val direction: Direction) { fun move(): Blizzard { val newPos = pos.move(direction) return Blizzard(when { newPos.x < xConstraints.first -> Pt(xConstraints.last, newPos.y) newPos.x > xConstraints.last -> Pt(xConstraints.first, newPos.y) newPos.y < yConstraints.first -> Pt(newPos.x, yConstraints.last) newPos.y > yConstraints.last -> Pt(newPos.x, yConstraints.first) else -> newPos }, direction) } } private data class Valley(val blizzards: List<Blizzard>, val expedition: Pt) { fun moves(): List<Valley> { val possibleDestinations = Direction.values().map { expedition.move(it) } + expedition val newBlizzards = blizzards.map { it.move() } return possibleDestinations.filter { possibleDestination -> possibleDestination.validDestination && newBlizzards.none { it.pos == possibleDestination } }.map { destination -> Valley(newBlizzards, destination) } } private val Pt.validDestination: Boolean get() = this == entrance || this == exit || (x in xConstraints && y in yConstraints) } private fun minutesToGoal(initialValley: Valley, thereAndBackAgain: Boolean): Int { var valleys = setOf(initialValley) var minutes = 0 while (valleys.none { it.expedition == exit }) { valleys = valleys.flatMap { it.moves() }.toSet() minutes++ } if (thereAndBackAgain) { valleys = setOf(valleys.first { it.expedition == exit }) while (valleys.none { it.expedition == entrance }) { valleys = valleys.flatMap { it.moves() }.toSet() minutes++ } valleys = setOf(valleys.first { it.expedition == entrance }) while (valleys.none { it.expedition == exit }) { valleys = valleys.flatMap { it.moves() }.toSet() minutes++ } } return minutes } private fun String.toValley(): Valley = Valley(lines().withIndex().flatMap { (y, row) -> row.withIndex().mapNotNull { (x, c) -> val direction = blizzardDirections[c] if (direction != null) Blizzard(Pt(x, y), direction) else null } }, entrance) }
0
Kotlin
0
0
7ead7db6491d6fba2479cd604f684f0f8c1e450f
3,375
adventofcode2022
MIT License
src/main/kotlin/aoc22/Day07.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc22 import aoc22.Day07Domain.Command import aoc22.Day07Domain.Down import aoc22.Day07Domain.Ls import aoc22.Day07Domain.Cd import aoc22.Day07Domain.Up import aoc22.Day07Parser.parseCommands import aoc22.Day07Solution.part1Day07 import aoc22.Day07Solution.part2Day07 import common.Year22 object Day07: Year22 { fun List<String>.part1(): Int = part1Day07() fun List<String>.part2(): Int = part2Day07() } object Day07Solution { fun List<String>.part1Day07(): Int = getDirSizes().sumOfSmall() private fun List<Int>.sumOfSmall(): Int = filter { it < 100_000 }.sum() fun List<String>.part2Day07(): Int = getDirSizes().findSmallestToDelete() private val totalSpace = 70_000_000 private val neededSpace = 30_000_000 private fun List<Int>.findSmallestToDelete(): Int = filter { (neededSpace + max() - it) < totalSpace }.min() private fun List<String>.getDirSizes(): List<Int> = parseCommands() .let { with(Day07FileSys()) { it.dirSizes() } } } class Day07FileSys { private var pwd = "/" private val parents = mutableListOf<String>() private val dirSizeMap = mutableMapOf("/" to 0) fun List<Command>.dirSizes(): List<Int> = updateDirSizeMap() .let { dirSizeMap.values.toList() } private fun List<Command>.updateDirSizeMap() { forEach { when (it) { is Cd -> it.updateLocation() is Ls -> it.updateDirSizeMap() } } } private fun Ls.updateDirSizeMap() { dirSizeMap[getDirKey(parents.size, pwd)] = this.fileSize + (dirSizeMap[getDirKey(parents.size, pwd)] ?: 0) parents.forEachIndexed { index, parent -> dirSizeMap[getDirKey(index, parent)] = this.fileSize + (dirSizeMap[getDirKey(index, parent)] ?: 0) } } private fun Cd.updateLocation() { when (this) { Up -> parents.removeLast() is Down -> this.path.also { parents.add(pwd) } }.let { pwd = it } } private fun getDirKey(indexTo: Int, pwd: String): String = parents.subList(0, indexTo).joinToString("/") + pwd } class Day07FileSysFold { data class State( var pwd: String, val parents: List<String>, val dirSizeMap: Map<String, Int>, ) fun List<Command>.dirSizes(): List<Int> { val initialState = State( pwd = "/", parents = emptyList(), dirSizeMap = mutableMapOf("/" to 0) ) return fold(initialState) { acc, command -> when (command) { is Cd -> acc.cd(command) is Ls -> acc.ls(command) } }.dirSizeMap.values.toList() } private fun State.cd(cd: Cd): State = when (cd) { is Down -> this.cdDown(cd) Up -> this.cdUp() } private fun State.cdDown(down: Down): State = copy( pwd = down.path, parents = parents + listOf(down.path) ) private fun State.cdUp(): State = copy( pwd = parents.last(), parents = parents.dropLast(1) ) private fun State.ls(ls: Ls): State { val dirKey = getDirKey(parents.size, pwd) val thisDirSizeMap = mutableMapOf<String, Int>() thisDirSizeMap[dirKey] = ls.fileSize + (dirSizeMap[dirKey] ?: 0) parents.forEachIndexed { index, parent -> val dirKey1 = getDirKey(index, parent) thisDirSizeMap[dirKey1] = ls.fileSize + (dirSizeMap[dirKey1] ?: 0) } return copy(dirSizeMap = dirSizeMap + thisDirSizeMap) } private fun State.getDirKey(indexTo: Int, pwd: String): String = parents.subList(0, indexTo).joinToString("/") + pwd } object Day07Domain { sealed class Command sealed class Cd : Command() object Up : Cd() data class Down(val path: String) : Cd() data class Ls(val fileSize: Int) : Command() } object Day07Parser { fun List<String>.parseCommands(): List<Command> = mapNotNull { when { it.startsWith("\$ cd ") -> it.replace("\$ cd ", "").let { cd -> when (cd) { ".." -> Up else -> Down(cd) } } it.first().isDigit() -> Ls((it.filter { it.isDigit() }.toIntOrNull() ?: 0)) else -> null } } }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
4,563
aoc
Apache License 2.0
y2016/src/main/kotlin/adventofcode/y2016/Day13.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2016 import adventofcode.io.AdventSolution object Day13 : AdventSolution(2016, 13, "Maze") { var magicNumber: Int = 0 override fun solvePartOne(input: String): Int { magicNumber = input.toInt() return generateSequence(Solver(setOf(Cubicle(1, 1))), Solver::next) .takeWhile { Cubicle(31, 39) !in it.edge } .count() } override fun solvePartTwo(input: String): Int { magicNumber = input.toInt() return generateSequence(Solver(setOf(Cubicle(1, 1))), Solver::next) .take(52) .last() .visited .size } data class Solver(val edge: Set<Cubicle>, val visited: Set<Cubicle> = emptySet()) { fun next() = Solver( edge = edge.asSequence().flatMap(Cubicle::getNeighbors).filterNot { it in visited }.toSet(), visited = visited + edge ) } data class Cubicle(val x: Int, val y: Int) { fun getNeighbors() = sequenceOf( copy(x = x + 1), copy(x = x - 1), copy(y = y + 1), copy(y = y - 1)) .filter(Cubicle::isOpen) private fun isOpen(): Boolean = x >= 0 && y >= 0 && Integer.bitCount(x * x + 3 * x + 2 * x * y + y + y * y + magicNumber) % 2 == 0 } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,146
advent-of-code
MIT License
src/main/kotlin/com/tonnoz/adventofcode23/day16/Day16Part2.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day16 import com.tonnoz.adventofcode23.utils.println import com.tonnoz.adventofcode23.utils.readCharMatrix import kotlinx.coroutines.runBlocking import java.lang.IllegalArgumentException import kotlin.system.measureTimeMillis object Day16Part2 { @JvmStatic fun main(args: Array<String>) = runBlocking { val input = "input16.txt".readCharMatrix().toMutableList() val time = measureTimeMillis { val contraption = input.mapIndexed{i, row -> row.mapIndexed{j, value -> Cell(i, j, value)}} val memory = mutableMapOf<Cell,List<Direction>>() val solutions = mutableListOf<Int>() val topEdgeCells = contraption.first().drop(1).dropLast(1) val bottomEdgeCells = contraption.last().drop(1).dropLast(1) val leftEdgeCells = contraption.map { it.first() } val rightEdgeCells = contraption.map { it.last() } contraption.countEnergizedCells(topEdgeCells, Direction.DOWN, memory, solutions) contraption.countEnergizedCells(bottomEdgeCells, Direction.UP, memory, solutions) contraption.countEnergizedCells(leftEdgeCells, Direction.RIGHT, memory, solutions) contraption.countEnergizedCells(rightEdgeCells, Direction.LEFT, memory, solutions) solutions.max().println() } println("P2 time: $time ms") } private fun List<List<Cell>>.countEnergizedCells(edgeCells: List<Cell>, direction: Direction, memory: MutableMap<Cell, List<Direction>>, solutions: MutableList<Int>) { edgeCells.forEach { cell -> go(cell, this, memory, direction) val max = this.sumOf { row -> row.count { it.energized } } solutions.add(max) this.forEach { row -> row.forEach { it.energized = false } } memory.clear() } } data class Cell(val row: Int, val column: Int, val value: Char, var energized: Boolean = false) { fun nextCell(direction: Direction, contraption: List<List<Cell>>): Cell? { val cHeight = contraption.size val cWidth = contraption[0].size return when (direction) { Direction.UP -> if(row > 0) contraption[row-1][column] else null Direction.DOWN -> if(row < cHeight -1) contraption[row+1][column] else null Direction.LEFT -> if(column > 0) contraption[row][column-1] else null Direction.RIGHT -> if(column < cWidth -1) contraption[row][column+1] else null } } fun processSplit(direction: Direction) = when (value) { '|' -> when (direction) { Direction.UP -> listOf(Direction.UP) Direction.DOWN -> listOf(Direction.DOWN) Direction.LEFT,Direction.RIGHT -> listOf(Direction.UP, Direction.DOWN) } '-' -> when (direction) { Direction.UP, Direction.DOWN -> listOf(Direction.LEFT, Direction.RIGHT) Direction.LEFT -> listOf(Direction.LEFT) Direction.RIGHT -> listOf(Direction.RIGHT) } else -> { throw IllegalArgumentException("Invalid split cell: $this")} } fun processAngle(direction: Direction) = listOf(when (value) { '/' -> when (direction) { Direction.UP -> Direction.RIGHT Direction.DOWN -> Direction.LEFT Direction.LEFT -> Direction.DOWN Direction.RIGHT -> Direction.UP } '\\' -> when (direction) { Direction.UP -> Direction.LEFT Direction.DOWN -> Direction.RIGHT Direction.LEFT -> Direction.UP Direction.RIGHT -> Direction.DOWN } else -> { throw IllegalArgumentException("Invalid angle cell: $this")} }) fun processStraight(direction: Direction)= listOf(direction) } enum class Direction { UP, DOWN, LEFT, RIGHT } private fun go(cell: Cell, contraption: List<List<Cell>>, memory: MutableMap<Cell, List<Direction>>, direction: Direction) { if(memory[cell]?.contains(direction) == true) return //skip if seen before cell.energized = true memory[cell] = memory[cell]?.plus(direction) ?: listOf(direction) //add it to seen val nextMoves = when (cell.value) { '.' -> cell.processStraight(direction) '|' , '-' -> cell.processSplit(direction) '/','\\' -> cell.processAngle(direction) else -> throw IllegalArgumentException("Invalid cell: $cell") } nextMoves.forEach { cell.nextCell(it, contraption)?.let { nextCell -> go(nextCell, contraption, memory, it) } } } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
4,409
adventofcode23
MIT License
src/Day04.kt
mvmlisb
572,859,923
false
{"Kotlin": 14994}
private fun String.parseIntRange(): IntRange { val split = split("-") return split.first().toInt()..split.last().toInt() } private fun processRanges(process: (IntRange, IntRange) -> Boolean) = readInput("Day04_test").map { val split = it.split(",") if (process(split.first().parseIntRange(), split.last().parseIntRange())) 1 else 0 }.sum() private fun IntRange.fullyContains(other: IntRange) = first >= other.first && last <= other.last fun main() { val part1 = processRanges { first, second -> first.fullyContains(second) || second.fullyContains(first) } val part2 = processRanges { first, second -> first.contains(second.first) || second.contains(first.first) } println(part1) println(part2) }
0
Kotlin
0
0
648d594ec0d3b2e41a435b4473b6e6eb26e81833
732
advent_of_code_2022
Apache License 2.0
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/K-wayMerge.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* The "K-way Merge" coding pattern is commonly used to merge K sorted lists or arrays efficiently. */ //1. Kth Smallest Number in M Sorted Lists import java.util.PriorityQueue class ListNode(var `val`: Int) { var next: ListNode? = null } fun mergeKLists(lists: Array<ListNode?>): ListNode? { val minHeap = PriorityQueue<ListNode?>(compareBy { it?.`val` }) // Add the heads of all lists to the min heap for (list in lists) { if (list != null) { minHeap.offer(list) } } var dummy = ListNode(0) var current: ListNode? = dummy // Merge lists by repeatedly extracting the smallest element from the min heap while (minHeap.isNotEmpty()) { val minNode = minHeap.poll() current?.next = minNode current = current?.next if (minNode?.next != null) { minHeap.offer(minNode.next) } } return dummy.next } fun kthSmallestInLists(lists: Array<ListNode?>, k: Int): Int { val mergedList = mergeKLists(lists) var result = -1 var count = 0 var current: ListNode? = mergedList // Traverse the merged list to find the kth smallest element while (current != null) { count++ if (count == k) { result = current.`val` break } current = current.next } return result } fun main() { // Example usage val list1 = ListNode(2) list1.next = ListNode(6) list1.next?.next = ListNode(8) val list2 = ListNode(3) list2.next = ListNode(6) list2.next?.next = ListNode(7) val list3 = ListNode(1) list3.next = ListNode(3) list3.next?.next = ListNode(4) val lists = arrayOf(list1, list2, list3) val k = 5 val result = kthSmallestInLists(lists, k) println("Kth Smallest Number in M Sorted Lists: $result") } //2. Kth Smallest Number in a Sorted Matrix import java.util.PriorityQueue fun kthSmallest(matrix: Array<IntArray>, k: Int): Int { val minHeap = PriorityQueue<Pair<Int, Pair<Int, Int>>>(compareBy { it.first }) // Add the first element of each row to the min heap for (i in matrix.indices) { minHeap.offer(Pair(matrix[i][0], Pair(i, 0))) } var result = -1 // Extract the smallest element 'k' times repeat(k) { val current = minHeap.poll() result = current.first val rowIndex = current.second.first val colIndex = current.second.second // If there are more elements in the current row, add the next element to the min heap if (colIndex + 1 < matrix[rowIndex].size) { minHeap.offer(Pair(matrix[rowIndex][colIndex + 1], Pair(rowIndex, colIndex + 1))) } } return result } fun main() { // Example usage val matrix = arrayOf( intArrayOf(1, 5, 9), intArrayOf(10, 11, 13), intArrayOf(12, 13, 15) ) val k = 8 val result = kthSmallest(matrix, k) println("Kth Smallest Number in a Sorted Matrix: $result") } /* Kth Smallest Number in M Sorted Lists: The mergeKLists function merges K sorted lists using a min heap and returns the head of the merged list. The kthSmallestInLists function then finds the kth smallest number in the merged list. Kth Smallest Number in a Sorted Matrix: The kthSmallest function finds the kth smallest number in a sorted matrix using a min heap. It repeatedly extracts the smallest element and adds the next element from the same row if available. */
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
3,488
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/day14/Main.kt
nikwotton
572,814,041
false
{"Kotlin": 77320}
package day14 import java.io.File import kotlin.random.Random import kotlin.random.Random.Default const val workingDir = "src/day14" fun main() { val sample = File("$workingDir/sample.txt") val input1 = File("$workingDir/input_1.txt") println("Step 1a: ${runStep1(sample)}") // 24 println("Step 1b: ${runStep1(input1)}") println("Step 2a: ${runStep2(sample)}") // 93 println("Step 2b: ${runStep2(input1)}") } data class Position(val x: Int, val y: Int) typealias Path = List<Position> fun runStep1(input: File): String { val paths: List<Path> = input.readLines().map { it.split(" -> ").map { it.split(",").let { Position(it[0].toInt(), it[1].toInt()) } } } val blockingPoints = paths.flatMap { it.windowed(2).flatMap { (a, b) -> if (a.x == b.x) { (minOf(a.y, b.y)..maxOf(a.y, b.y)).map { Position(a.x, it) } } else if (a.y == b.y) { (minOf(a.x, b.x)..maxOf(a.x, b.x)).map { Position(it, a.y) } } else TODO() } }.toMutableList() fun lowerSand(sandPosition: Position): Position { if (!blockingPoints.contains(Position(sandPosition.x, sandPosition.y+1))) return Position(sandPosition.x, sandPosition.y+1) if (!blockingPoints.contains(Position(sandPosition.x-1, sandPosition.y+1))) return Position(sandPosition.x-1, sandPosition.y+1) if (!blockingPoints.contains(Position(sandPosition.x+1, sandPosition.y+1))) return Position(sandPosition.x+1, sandPosition.y+1) return sandPosition } val doneAt = blockingPoints.maxOf { it.y } + 1 fun dropSand(): Boolean { var sandPosition = Position(500, 0) while(true) { val newSandPosition = lowerSand(sandPosition) if (newSandPosition == sandPosition) { blockingPoints.add(newSandPosition) return true } if (newSandPosition.y >= doneAt) return false sandPosition = newSandPosition } } var ret = 0 while (dropSand()) ret++ return ret.toString() } fun runStep2(input: File): String { val paths: List<Path> = input.readLines().map { it.split(" -> ").map { it.split(",").let { Position(it[0].toInt(), it[1].toInt()) } } } val blockingPoints = paths.flatMap { it.windowed(2).flatMap { (a, b) -> if (a.x == b.x) { (minOf(a.y, b.y)..maxOf(a.y, b.y)).map { Position(a.x, it) } } else if (a.y == b.y) { (minOf(a.x, b.x)..maxOf(a.x, b.x)).map { Position(it, a.y) } } else TODO() } }.toMutableList() fun lowerSand(sandPosition: Position): Position { if (!blockingPoints.contains(Position(sandPosition.x, sandPosition.y+1))) return Position(sandPosition.x, sandPosition.y+1) if (!blockingPoints.contains(Position(sandPosition.x-1, sandPosition.y+1))) return Position(sandPosition.x-1, sandPosition.y+1) if (!blockingPoints.contains(Position(sandPosition.x+1, sandPosition.y+1))) return Position(sandPosition.x+1, sandPosition.y+1) return sandPosition } val floor = blockingPoints.maxOf { it.y } + 2 fun dropSand(): Boolean { var sandPosition = Position(500, 0) while(true) { val newSandPosition = lowerSand(sandPosition) if (newSandPosition == sandPosition || newSandPosition.y >= floor-1) { if (blockingPoints.contains(newSandPosition)) return false blockingPoints.add(newSandPosition) if (Random.nextInt(100) == 42) blockingPoints.removeAll { blockingPoints.contains(Position(it.x, it.y - 1)) && blockingPoints.contains(Position(it.x - 1, it.y - 1)) && blockingPoints.contains(Position(it.x + 1, it.y - 1)) } return true } if (newSandPosition == Position(500, 0)) return false sandPosition = newSandPosition } } var ret = 0 while (dropSand()) { if (ret%100==0) println("At ret $ret with points ${blockingPoints.size} minx: ${blockingPoints.minOf { it.x }} maxX: ${blockingPoints.maxOf { it.x }} minY: ${blockingPoints.minOf{it.y}} maxY: ${blockingPoints.maxOf{it.y}}") ret++ } return ret.toString() }
0
Kotlin
0
0
dee6a1c34bfe3530ae6a8417db85ac590af16909
4,419
advent-of-code-2022
Apache License 2.0
codeforces/round576/e.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round576 fun main() { val (n, rectNum) = readInts() val rectangles = Array(rectNum) { readInts() } val xSet = mutableSetOf(0, n) val ySet = mutableSetOf(0, n) for ((x1, y1, x2, y2) in rectangles) { xSet.add(x1 - 1) xSet.add(x2) ySet.add(y1 - 1) ySet.add(y2) } val xs = xSet.sorted() val ys = ySet.sorted() val m = xs.size + ys.size + 2 val c = Array(m) { IntArray(m) } for (i in 0 until xs.size - 1) { c[m - 2][i] = xs[i + 1] - xs[i] } for (j in 0 until ys.size - 1) { c[xs.size + j][m - 1] = ys[j + 1] - ys[j] } for ((x1, y1, x2, y2) in rectangles) { for (i in xs.indices) { if ((xs[i] < x1 - 1) || (xs[i] >= x2)) continue for (j in ys.indices) { if ((ys[j] < y1 - 1) || (ys[j] >= y2)) continue c[i][xs.size + j] = minOf(xs[i + 1] - xs[i], ys[j + 1] - ys[j]) } } } println(edmonsKarp(c, m - 2, m - 1)) } fun edmonsKarp(c: Array<IntArray>, s: Int, t: Int): Int { val n = c.size val f = Array(n) { IntArray(n) } val queue = IntArray(n) val prev = IntArray(n) var res = 0 while (true) { queue[0] = s var low = 0 var high = 1 prev.fill(-1) prev[s] = s while (low < high && prev[t] == -1) { val v = queue[low] low++ for (u in 0 until n) { if (prev[u] != -1 || f[v][u] == c[v][u]) { continue } prev[u] = v queue[high] = u high++ } } if (prev[t] == -1) { break } var flow = Integer.MAX_VALUE / 2 var u = t while (u != s) { flow = minOf(flow, c[prev[u]][u] - f[prev[u]][u]) u = prev[u] } u = t while (u != s) { f[prev[u]][u] += flow f[u][prev[u]] -= flow u = prev[u] } res += flow } return res } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,800
competitions
The Unlicense
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day05Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith private fun solution1(input: String) = parseInput(input).let { (stacks, procedure) -> procedure.forEach { (number, from, to) -> repeat(number) { val crate = stacks[from].removeFirst() stacks[to].add(0, crate) } } stacks.joinToString("") { it.first().toString() } } private fun solution2(input: String) = parseInput(input).let { (stacks, procedure) -> procedure.forEach { (number, from, to) -> val crates = stacks[from].take(number) repeat(number) { stacks[from].removeFirst() } stacks[to].addAll(0, crates) } stacks.joinToString("") { it.first().toString() } } private fun parseInput(input: String) = input.split("(\\s+\\d+\\s*)+\\n\\n".toRegex()).let { (crates, procedure) -> val stackLines = crates.lines().map { it.chunked(4).map { c -> c.replace("\\[|]|\\s+".toRegex(), "") } } val stacks = stackLines.fold(stackLines.last().indices.map { mutableListOf<Char>() }) { acc, line -> line.mapIndexed { index, c -> index to c }.filter { (_, c) -> c.isNotBlank() } .forEach { (index, c) -> acc.getOrNull(index)?.add(c[0]) } acc } stacks to procedure.lines().map { "move (\\d+) from (\\d+) to (\\d+)".toRegex().matchEntire(it)?.let { match -> arrayOf(match.groupValues[1].toInt(), match.groupValues[2].toInt() - 1, match.groupValues[3].toInt() - 1) } ?: throw IllegalStateException() } } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 5 class Day05Test : StringSpec({ "parse input" { val (stacks, procedure) = parseInput(exampleInput) stacks shouldContainExactly listOf( listOf('N', 'Z'), listOf('D', 'C', 'M'), listOf('P'), ) procedure shouldContainExactly listOf( arrayOf(1, 1, 0), arrayOf(3, 0, 2), arrayOf(2, 1, 0), arrayOf(1, 0, 1), ) } "example part 1" { ::solution1 invokedWith exampleInput shouldBe "CMZ" } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe "FJSRQCFTN" } "example part 2" { ::solution2 invokedWith exampleInput shouldBe "MCD" } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe "CJVLJQPHS" } }) private val exampleInput = """ [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2 """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
2,922
adventofcode-kotlin
MIT License
2015/src/main/kotlin/com/koenv/adventofcode/Day24.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode import java.util.* object Day24 { fun getCombinations(choices: List<Int>, used: MutableSet<Int>, neededValue: Int, numberOfItems: Int, startIndex: Int = 0): MutableList<MutableList<Int>>? { if (numberOfItems == 1) { var maxSoFar = Int.MIN_VALUE if (used.any()) { maxSoFar = used.max()!! } if (neededValue > maxSoFar && choices.contains(neededValue)) { return arrayListOf(arrayListOf(neededValue)) } return null } val results: MutableList<MutableList<Int>> = arrayListOf() for (i in startIndex..(choices.size - 1)) { val choice = choices[i] if (used.contains(choice)) { continue } if (neededValue <= choice) { continue; } used.add(choice) var innerResults = getCombinations(choices, used, neededValue - choice, numberOfItems - 1, i + 1) if (innerResults != null) { innerResults.forEach { it.add(0, choice) results.add(it) } } used.remove(choice) } if (results.any()) { return results } return null } fun getValidCombinationsWithLowestAmountOfItems(choices: List<Int>, groups: Int): MutableList<MutableList<Int>>? { val maxDepth = choices.size / groups var depth = 0 var validResults: MutableList<MutableList<Int>> = arrayListOf() do { depth++ val combinations = getCombinations(choices, hashSetOf(), choices.sum() / groups, depth) if (combinations != null) { validResults = ArrayList(combinations.map { ArrayList(it) }) } } while (depth < maxDepth && !validResults.any()) if (validResults.any()) { return validResults } return null } fun quantumEntanglement(combinations: List<Int>): Long { var result = 1L combinations.forEach { result *= it } return result } public fun getQuantumEntanglementOfIdealConfiguration(input: String, groups: Int): Long { val choices = input.lines().map { it.toInt() } val combinations = getValidCombinationsWithLowestAmountOfItems(choices, groups)!! return quantumEntanglement(combinations.filter { it.isNotEmpty() }.minBy { quantumEntanglement(it) }!!) } }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
2,582
AdventOfCode-Solutions-Kotlin
MIT License
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_77884.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package main.kotlin.programmers.lv01 import kotlin.math.sqrt /** * * https://school.programmers.co.kr/learn/courses/30/lessons/77884 * * 약수의 개수와 덧셈 * 문제 설명 * 두 정수 left와 right가 매개변수로 주어집니다. * left부터 right까지의 모든 수들 중에서, 약수의 개수가 짝수인 수는 더하고, 약수의 개수가 홀수인 수는 뺀 수를 return 하도록 solution 함수를 완성해주세요. * * 제한사항 * 1 ≤ left ≤ right ≤ 1,000 * 입출력 예 * left right result * 13 17 43 * 24 27 52 * 입출력 예 설명 * 입출력 예 #1 * * 다음 표는 13부터 17까지의 수들의 약수를 모두 나타낸 것입니다. * 수 약수 약수의 개수 * 13 1, 13 2 * 14 1, 2, 7, 14 4 * 15 1, 3, 5, 15 4 * 16 1, 2, 4, 8, 16 5 * 17 1, 17 2 * 따라서, 13 + 14 + 15 - 16 + 17 = 43을 return 해야 합니다. * 입출력 예 #2 * * 다음 표는 24부터 27까지의 수들의 약수를 모두 나타낸 것입니다. * 수 약수 약수의 개수 * 24 1, 2, 3, 4, 6, 8, 12, 24 8 * 25 1, 5, 25 3 * 26 1, 2, 13, 26 4 * 27 1, 3, 9, 27 4 * 따라서, 24 - 25 + 26 + 27 = 52를 return 해야 합니다. * */ fun main() { solution(13, 17) } private fun solution(left: Int, right: Int): Int { var answer: Int = 0 for (i in left..right) { if (countDivisors(i) % 2 == 0) { answer += i } else { answer -= i } } println(answer) return answer } private fun countDivisors(n: Int): Int { var count = 0 val sqrtN = sqrt(n.toDouble()).toInt() for (i in 1..sqrtN) { if (n % i == 0) { count += 2 // i와 n/i는 모두 약수이므로 2를 추가 } } // 만약 n이 제곱수인 경우 중복으로 카운트된 약수를 제거 if (sqrtN * sqrtN == n) { count-- } return count }
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
2,016
HoOne
Apache License 2.0
src/main/kotlin/day9/AllInASingleNight.kt
SaujanShr
685,121,393
false
null
package day9 import getInput val INPUT = getInput("day9") fun run1(): String { return INPUT .getRoutes() .getLocations() .getOptimalDistance() .toString() } fun run2(): String { return INPUT .getRoutes() .getLocations() .getLeastOptimalDistance() .toString() } fun String.getRoutes() = this .split('\n') .map { val path = it.split(' ') listOf(path[0], path[2], path[4]) } fun List<List<String>>.getLocations(): Map<String,Location> { val locations = this .flatMap { listOf(it[0], it[1]) } .distinct() .associateWith { Location(it) } this .forEach { (f, t, d) -> val from = locations[f]!! val to = locations[t]!! val distance = d.toInt() from.addRoute(to, distance) to.addRoute(from, distance) } return locations } fun Map<String,Location>.getOptimalDistance(): Int = this.values .minOf { this.values .toSet() .minus(it) .getOptimalDistance(it) } fun Set<Location>.getOptimalDistance(prev: Location): Int { if (this.isEmpty()) { return 0 } return this .minOf { this .minus(it) .getOptimalDistance(it) .plus(prev.getDistanceToLocation(it)) } } fun Map<String,Location>.getLeastOptimalDistance(): Int = this.values .maxOf { this.values .toSet() .minus(it) .getLeastOptimalDistance(it) } fun Set<Location>.getLeastOptimalDistance(prev: Location): Int { if (this.isEmpty()) { return 0 } return this .maxOf { this .minus(it) .getLeastOptimalDistance(it) .plus(prev.getDistanceToLocation(it)) } }
0
Kotlin
0
0
c6715a9570e62c28ed022c5d9b330a10443206c4
1,913
adventOfCode2015
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/symmetric_tree/SymmetricTree.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.symmetric_tree import katas.kotlin.leetcode.TreeNode import datsok.shouldEqual import org.junit.Test import java.util.* /** * https://leetcode.com/problems/symmetric-tree/ */ class SymmetricTreeTests { @Test fun `check is tree is a mirror of itself`() { TreeNode(1).isSymmetric() shouldEqual true TreeNode(1, TreeNode(0), TreeNode(0)).isSymmetric() shouldEqual true TreeNode(1, TreeNode(0), TreeNode(2)).isSymmetric() shouldEqual false TreeNode(1, TreeNode(2, TreeNode(3)), TreeNode(2, null, TreeNode(3)) ).isSymmetric() shouldEqual true TreeNode(1, TreeNode(2, TreeNode(3)), TreeNode(2, TreeNode(3)) ).isSymmetric() shouldEqual false TreeNode(1, TreeNode(2, TreeNode(3))).isSymmetric() shouldEqual false } } private fun TreeNode.isSymmetric(): Boolean { val leftQueue = LinkedList<TreeNode?>() val rightQueue = LinkedList<TreeNode?>() leftQueue.add(left) rightQueue.add(right) while (leftQueue.isNotEmpty() && rightQueue.isNotEmpty()) { val l = leftQueue.removeFirst() val r = rightQueue.removeFirst() if (l?.value != r?.value) return false if (l != null) { leftQueue.add(l.left) leftQueue.add(l.right) } if (r != null) { rightQueue.add(r.right) rightQueue.add(r.left) } } return leftQueue.isEmpty() && rightQueue.isEmpty() } private fun TreeNode.isSymmetric_() = inverted() == this private fun TreeNode.inverted(): TreeNode = TreeNode(value, left = right?.inverted(), right = left?.inverted())
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,689
katas
The Unlicense
src/day21/Day21.kt
ayukatawago
572,742,437
false
{"Kotlin": 58880}
package day21 import readInput fun main() { val input = readInput("day21/test") val monkeyMap = hashMapOf<String, Monkey>() input.forEach { val regex = """([a-z]+): ([a-z]+) ([+\-*/]) ([a-z]+)""".toRegex() val result = regex.matchEntire(it)?.groupValues ?: return@forEach val monkey = Monkey.WaitingMonkey(result[1], result[3][0], result[2], result[4]) monkeyMap[monkey.name] = monkey } input.forEach { val regex = """([a-z]+): (\d+)""".toRegex() val result = regex.matchEntire(it)?.groupValues ?: return@forEach val monkey = Monkey.NoWaitMonkey(result[1], result[2].toLong()) monkeyMap[monkey.name] = monkey } println(part1(monkeyMap)) println(part2(monkeyMap)) } private fun part1(monkeyMap: Map<String, Monkey>): Long { return monkeyMap["root"]!!.yell(monkeyMap) } private fun part2(monkeyMap: Map<String, Monkey>): Long { return monkeyMap["root"]!!.getHumanValue(monkeyMap, 0) } sealed class Monkey { abstract val name: String abstract fun yell(monkeyMap: Map<String, Monkey>): Long abstract fun getHumanValue(monkeyMap: Map<String, Monkey>, parentValue: Long): Long abstract fun hasHumanChild(monkeyMap: Map<String, Monkey>): Boolean data class NoWaitMonkey(override val name: String, private val number: Long) : Monkey() { override fun yell(monkeyMap: Map<String, Monkey>): Long = number override fun getHumanValue(monkeyMap: Map<String, Monkey>, parentValue: Long): Long = if (name == HUMAN_NAME) parentValue else number override fun hasHumanChild(monkeyMap: Map<String, Monkey>): Boolean = name == HUMAN_NAME companion object { private const val HUMAN_NAME = "humn" } } data class WaitingMonkey( override val name: String, val op: Char, val leftMonkeyName: String, val rightMonkeyName: String ) : Monkey() { override fun yell(monkeyMap: Map<String, Monkey>): Long { val leftMonkey = monkeyMap[leftMonkeyName]!! val rightMonkey = monkeyMap[rightMonkeyName]!! return leftMonkey.yell(monkeyMap) op rightMonkey.yell(monkeyMap) } override fun getHumanValue(monkeyMap: Map<String, Monkey>, parentValue: Long): Long { val leftMonkey = monkeyMap[leftMonkeyName]!! val rightMonkey = monkeyMap[rightMonkeyName]!! return when { name == "root" -> if (leftMonkey.hasHumanChild(monkeyMap)) { leftMonkey.getHumanValue(monkeyMap, rightMonkey.yell(monkeyMap)) } else { rightMonkey.getHumanValue(monkeyMap, leftMonkey.yell(monkeyMap)) } leftMonkey.hasHumanChild(monkeyMap) -> leftMonkey.getHumanValue(monkeyMap, parentValue leftInverseOp rightMonkey.yell(monkeyMap)) else -> rightMonkey.getHumanValue(monkeyMap, parentValue rightInverseOp leftMonkey.yell(monkeyMap)) } } override fun hasHumanChild(monkeyMap: Map<String, Monkey>): Boolean { val leftMonkey = monkeyMap[leftMonkeyName]!! val rightMonkey = monkeyMap[rightMonkeyName]!! return leftMonkey.hasHumanChild(monkeyMap) || rightMonkey.hasHumanChild(monkeyMap) } private infix fun Long.op(right: Long): Long = when (op) { '+' -> this + right '-' -> this - right '*' -> this * right else -> this / right } private infix fun Long.leftInverseOp(right: Long): Long = when (op) { '+' -> this - right '-' -> this + right '*' -> this / right else -> this * right } private infix fun Long.rightInverseOp(right: Long): Long = when (op) { '+' -> this - right '-' -> right - this '*' -> this / right else -> right / this } } }
0
Kotlin
0
0
923f08f3de3cdd7baae3cb19b5e9cf3e46745b51
4,171
advent-of-code-2022
Apache License 2.0
src/test/kotlin/year2015/Day18.kt
abelkov
47,995,527
false
{"Kotlin": 48425}
package year2015 import kotlin.test.Test import kotlin.test.assertEquals private const val GRID_SIZE = 100 private const val STEPS = 100 class Day18 { private fun getOnNeighbors(field: Array<Array<Int>>, i: Int, j: Int): Int = listOf( field[i - 1][j - 1], field[i - 1][j], field[i - 1][j + 1], field[i][j + 1], field[i + 1][j + 1], field[i + 1][j], field[i + 1][j - 1], field[i][j - 1] ).sum() @Test fun part1() { // 1 == On, 0 == Off val field: Array<Array<Int>> = Array(GRID_SIZE + 2) { Array(GRID_SIZE + 2) { 0 } } readInput("year2015/Day18.txt").lines().forEachIndexed { i, row -> row.forEachIndexed { j, light -> field[i + 1][j + 1] = if (light == '#') 1 else 0 } } repeat(STEPS) { val newField = Array(GRID_SIZE + 2) { Array(GRID_SIZE + 2) { 0 } } for (i in 1..GRID_SIZE) { for (j in 1..GRID_SIZE) { val onNeighbors = getOnNeighbors(field, i, j) if (field[i][j] == 1) { newField[i][j] = if (onNeighbors in 2..3) 1 else 0 } else { newField[i][j] = if (onNeighbors == 3) 1 else 0 } } } for (i in 1..GRID_SIZE) { for (j in 1..GRID_SIZE) { field[i][j] = newField[i][j] } } } val count = field.sumOf { row -> row.sumOf { it } } assertEquals(1061, count) } @Test fun part2() { // 1 == On, 0 == Off val field: Array<Array<Int>> = Array(GRID_SIZE + 2) { Array(GRID_SIZE + 2) { 0 } } readInput("year2015/Day18.txt").lines().forEachIndexed { i, row -> row.forEachIndexed { j, light -> field[i + 1][j + 1] = if (light == '#') 1 else 0 } } val corners = listOf( 1 to 1, 1 to GRID_SIZE, GRID_SIZE to GRID_SIZE, GRID_SIZE to 1, ) for ((i, j) in corners) { field[i][j] = 1 } repeat(STEPS) { val newField = Array(GRID_SIZE + 2) { Array(GRID_SIZE + 2) { 0 } } for (i in 1..GRID_SIZE) { for (j in 1..GRID_SIZE) { val onNeighbors = getOnNeighbors(field, i, j) if (field[i][j] == 1) { newField[i][j] = if (onNeighbors in 2..3) 1 else 0 } else { newField[i][j] = if (onNeighbors == 3) 1 else 0 } } } for (i in 1..GRID_SIZE) { for (j in 1..GRID_SIZE) { field[i][j] = newField[i][j] } } for ((i, j) in corners) { field[i][j] = 1 } } val count = field.sumOf { row -> row.sumOf { it } } assertEquals(1006, count) } }
0
Kotlin
0
0
0e4b827a742322f42c2015ae49ebc976e2ef0aa8
3,090
advent-of-code
MIT License
src/main/kotlin/days/Day16.kt
felix-ebert
317,592,241
false
null
package days class Day16 : Day(16) { private val fields = mutableMapOf<String, List<IntRange>>() private val myTicket = mutableListOf<Int>() private val nearbyTickets = mutableListOf<List<Int>>() init { var isTicket = false var isNearbyTicket = false for (line in inputList) { when { line.startsWith("your ticket") -> isTicket = true line.startsWith("nearby tickets") -> isNearbyTicket = true line.isEmpty() -> isTicket = false isTicket -> line.split(',').forEach { myTicket.add(it.toInt()) } isNearbyTicket -> nearbyTickets.add(line.split(',').map { it.toInt() }) else -> { val field = line.substringBefore(':') val ranges: List<IntRange> = line.substringAfter(": ").split(" or ").map { IntRange(it.substringBefore('-').toInt(), it.substringAfter('-').toInt()) } fields[field] = ranges } } } } override fun partOne(): Any { val validValues = fields.flatMap { it.value.flatMap { range -> range.toList() } } return nearbyTickets.flatten().sumOf { if (validValues.contains(it)) 0 else it } } override fun partTwo(): Any { // filter out the valid tickets val validValues = fields.flatMap { it.value.flatMap { range -> range.toList() } } val validTickets = nearbyTickets.filter { it.all { t -> validValues.contains(t) } }.toMutableList() validTickets.add(myTicket) // find all numbers for every column val numbers = mutableMapOf<Int, MutableList<Int>>() for (i in myTicket.indices) numbers[i] = mutableListOf() for (ticket in validTickets) { for (i in ticket.indices) { numbers[i]?.add(ticket[i]) } } // find all fields matching for every column val possibleFields = mutableMapOf<Int, MutableList<String>>() for (i in myTicket.indices) possibleFields[i] = mutableListOf() for ((col, values) in numbers) { for ((field, ranges) in fields) { if (values.all { it in ranges[0] || it in ranges[1] }) { possibleFields[col]?.add(field) } } } // reduce that list that there are no fields with multiple solutions val foundFields = mutableMapOf<Int, String>() while (foundFields.size < myTicket.size) { for ((col, fields) in possibleFields) { if (fields.size == 1) { val field = fields.first() foundFields[col] = field possibleFields.values.forEach { it.remove(field) } } } } // return the product of the “departure” fields on my ticket return foundFields.filter { it.value.startsWith("departure") }.keys.fold(1L) { acc, i -> acc * myTicket[i] } } }
0
Kotlin
0
4
dba66bc2aba639bdc34463ec4e3ad5d301266cb1
3,066
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/day13/Day13.kt
easchner
572,762,654
false
{"Kotlin": 104604}
package day13 import readInputSpaceDelimited fun main() { fun listCompare(a: String, b: String): Boolean? { var at = a var bt = b if (a.toIntOrNull() != null && b.toIntOrNull() != null) { if (a.toInt() < b.toInt()) return true if (a.toInt() > b.toInt()) return false return null } if (a.toIntOrNull() == null && b.toIntOrNull() != null) { bt = "[$b]" } if (a.toIntOrNull() != null && b.toIntOrNull() == null) { at = "[$a]" } if (a == "" && b != "") return false if (a != "" && b == "") return true if (a == "" && b == "") return null val aElements = mutableListOf<String>() val bElements = mutableListOf<String>() at = at.substring(1, at.length - 1) bt = bt.substring(1, bt.length - 1) while (at != "") { if (at[0] != '[') { aElements.add(at.substringBefore(",")) at = if (!at.contains(',')) "" else at.substringAfter(",") } else { var i = 1 var brackets = 1 while (brackets > 0 && i < at.length) { brackets += when (at[i]) { '[' -> 1 ']' -> -1 else -> 0 } i++ } aElements.add(at.substring(0, i)) at = at.substring(i) } } while (bt != "") { if (bt[0] != '[') { bElements.add(bt.substringBefore(",")) bt = if (!bt.contains(',')) "" else bt.substringAfter(",") } else { var i = 1 var brackets = 1 while (brackets > 0 && i < bt.length) { brackets += when (bt[i]) { '[' -> 1 ']' -> -1 else -> 0 } i++ } bElements.add(bt.substring(0, i)) bt = bt.substring(i) } } aElements.remove("") bElements.remove("") while (aElements.isNotEmpty() && bElements.isNotEmpty()) { val comp = listCompare(aElements.removeFirst(), bElements.removeFirst()) if (comp != null) return comp } if (aElements.isEmpty() && bElements.isNotEmpty()) return true if (aElements.isNotEmpty() && bElements.isEmpty()) return false return null } fun part1(input: List<List<String>>): Int { return input.mapIndexed { index, list -> if(listCompare(list[0], list[1]) == true) index + 1 else 0 }.sum() } fun part2(input: List<List<String>>): Int { val cleanInput = mutableListOf<String>() for (i in input) { for (j in i) { cleanInput.add(j) } } cleanInput.add("[[2]]") cleanInput.add("[[6]]") cleanInput.sortWith(Comparator<String> { a, b -> when (listCompare(a, b)) { true -> -1 false -> 1 else -> 0 } }) return (cleanInput.indexOf("[[2]]") + 1) * (cleanInput.indexOf("[[6]]") + 1) } val testInput = readInputSpaceDelimited("day13/test") val input = readInputSpaceDelimited("day13/input") check(part1(testInput) == 13) println(part1(input)) check(part2(testInput) == 140) println(part2(input)) }
0
Kotlin
0
0
5966e1a1f385c77958de383f61209ff67ffaf6bf
3,808
Advent-Of-Code-2022
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day18.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year21 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.permPairs fun PuzzleSet.day18() = puzzle(day = 18) { // Parse all numbers (AST like) val numbers = inputLines.map { SnailfishNumber.parse(it) } // Part one partOne = numbers.map { it.clone() }.reduce { acc, cur -> (acc + cur).reduceNumber() }.magnitude().s() // Part two // Get permutations and calculate partTwo = numbers.permPairs().maxOf { (a, b) -> (a.clone() + b.clone()).reduceNumber().magnitude() }.s() } private sealed class SnailfishNumber(var parent: NumberPair?) { companion object { fun parse(str: String): SnailfishNumber = if (str.startsWith("[")) { // Parse as a pair // Find the top level comma index var opening = 0 var idx = -1 str.forEachIndexed { i, c -> when (c) { '[' -> opening++ ']' -> opening-- ',' -> if (opening == 1) { // If there is only one opening bracket (without closing yet), // this index is the index of a top-level pair idx = i return@forEachIndexed } } } NumberPair(parse(str.take(idx).drop(1)), parse(str.drop(idx + 1).dropLast(1))) } else NormalInt(str.toInt()) } fun getAllParents(): List<NumberPair> { val parents = mutableListOf<NumberPair>() var next: NumberPair? = parent while (next != null) { parents.add(next) next = next.parent } return parents } operator fun plus(other: SnailfishNumber) = NumberPair(this, other, parent) abstract fun magnitude(): Int // Deep clone fun clone(): SnailfishNumber = when (this) { is NormalInt -> NormalInt(value) is NumberPair -> NumberPair(left.clone(), right.clone()) } } // Debugging is included for convenience private class NumberPair( var left: SnailfishNumber, var right: SnailfishNumber, parent: NumberPair? = null ) : SnailfishNumber(parent), Iterable<SnailfishNumber> { init { // Set parents left.parent = this right.parent = this } fun reduceNumber(): NumberPair { val result = this while (true) { val explodingPair = getExplodingPair(this) if (explodingPair != null) { explode(explodingPair, explodingPair.left, explodingPair.right) continue } val splittingNumber = getSplittingNumber(this) if (splittingNumber != null) { splittingNumber.split() continue } break } return result } fun goLeft(num: SnailfishNumber): SnailfishNumber? = if (num == right) left else parent?.goLeft(this) fun goRight(num: SnailfishNumber): SnailfishNumber? = if (num == left) right else parent?.goRight(this) fun leftNormalNumber(): NormalInt? = when (left) { is NormalInt -> left as NormalInt is NumberPair -> (left as NumberPair).leftNormalNumber() } fun rightNormalNumber(): NormalInt? = when (right) { is NormalInt -> right as NormalInt is NumberPair -> (right as NumberPair).rightNormalNumber() } fun replace(from: SnailfishNumber, to: SnailfishNumber) { when (from) { left -> left = to right -> right = to else -> error("from element was not found") } to.parent = this } override fun magnitude(): Int = left.magnitude() * 3 + right.magnitude() * 2 override fun iterator() = iterator { yield(left) yield(right) } override fun toString() = "${if (parent == null) "root" else ""}[$left,$right]" } private class NormalInt(val value: Int, parent: NumberPair? = null) : SnailfishNumber(parent) { fun split(): NumberPair { val newPair = NumberPair(NormalInt(value / 2), NormalInt(value - (value / 2))) parent?.replace(this, newPair) return newPair } override fun magnitude() = value override fun toString() = value.toString() } private fun getExplodingPair(num: SnailfishNumber): NumberPair? = when(num) { is NormalInt -> null is NumberPair -> { if (num.getAllParents().size == 4) num else getExplodingPair(num.left) ?: getExplodingPair(num.right) } } private fun getSplittingNumber(num: SnailfishNumber): NormalInt? = when (num) { is NormalInt -> if (num.value >= 10) num else null is NumberPair -> getSplittingNumber(num.left) ?: getSplittingNumber(num.right) } private fun explode(pair: NumberPair, left: SnailfishNumber, right: SnailfishNumber) { val parent = pair.parent ?: error("This pair must have a parent, in order to explode") if (left is NormalInt) { when (val goLeft = parent.goLeft(pair)) { is NormalInt -> goLeft.parent?.replace(goLeft, NormalInt(goLeft.value + left.value)) is NumberPair -> goLeft.rightNormalNumber()?.let { it.parent?.replace(it, NormalInt(it.value + left.value)) } else -> Unit } } if (right is NormalInt) { when (val goRight = parent.goRight(pair)) { is NormalInt -> goRight.parent?.replace(goRight, NormalInt(goRight.value + right.value)) is NumberPair -> goRight.leftNormalNumber()?.let { it.parent?.replace(it, NormalInt(it.value + right.value)) } else -> Unit } } parent.replace(pair, NormalInt(0)) }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
5,792
advent-of-code
The Unlicense
2016/src/main/java/p4/Problem4.kt
ununhexium
113,359,669
false
null
package p4 import more.CircularList import more.Input val NAME = "name" val ID = "id" val CHECKSUM = "checksum" val pattern = Regex("(?<$NAME>[\\p{Lower}-]+)-(?<$ID>\\p{Digit}+)\\[(?<$CHECKSUM>\\p{Lower}+)]") val alphabet = CircularList(('a'..'z').toList()) fun shift(c: Char, amount: Int) = alphabet[c.toInt() - 'a'.toInt() + amount] data class Room(val name: String, val id: Int, val checksum: String) { companion object { fun from(input: String): Room { val matcher = pattern.matchEntire(input) ?: throw RuntimeException("Broken input: $input") fun get(key: String) = matcher.groups[key]?.value ?: throw RuntimeException("No value for $key in $input") return Room( get(NAME), get(ID).toInt(), get(CHECKSUM) ) } } fun isReal(): Boolean { return checksum == hashIt() } fun hashIt(): String { return name // dashes don't count .replace("-", "") // count each letter .groupBy { it } .mapValues { it.value.size } // sort by occurrence .toList() /* * Sort by letter first. * So if there is a tie, we get the lowest letter. */ .sortedBy { it.first.toInt() } /* * Descending order. * Don't use reversed() as it would mess up the alphabetical order */ .sortedBy { -it.second } // only the 5 biggest count .take(5) // recreate the hash .map { it.first } .joinToString(separator = "") } fun decipher() = name .map { if (it == '-') ' ' else shift(it, id) } .joinToString(separator = "") } fun main(args: Array<String>) { val rooms = Input .getFor("p4") .split("\n") .map { Room.from(it) } val realOnes = rooms .sumBy { if (it.isReal()) it.id else 0 } println(realOnes) val roomName = "north" val northPoleRoom = rooms.filter { it.isReal() }.filter { it.decipher().contains(roomName) } println(northPoleRoom.map { it.toString() + " " + it.decipher() }) }
6
Kotlin
0
0
d5c38e55b9574137ed6b351a64f80d764e7e61a9
2,130
adventofcode
The Unlicense
src/org/aoc2021/Day15.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path import java.util.PriorityQueue object Day15 { data class RiskPath(val currentCost: Int, val row: Int, val col: Int) private fun solve(lines: List<String>, shouldExpandGrid: Boolean = false): Int { val rawGrid = parseLines(lines) val grid = if (shouldExpandGrid) expandGrid(rawGrid) else rawGrid val pq = PriorityQueue<RiskPath> { a, b -> a.currentCost.compareTo(b.currentCost) } pq.add(RiskPath(0, 0, 0)) val directions = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) val minCosts = mutableMapOf<Pair<Int, Int>, Int>() minCosts[0 to 0] = 0 while (true) { val top = pq.remove()!! if (top.row == grid.size - 1 && top.col == grid[0].size - 1) { return top.currentCost } directions.forEach { (dx, dy) -> val x = top.row + dx val y = top.col + dy if (x >= 0 && x < grid.size && y >= 0 && y < grid[0].size) { val newCost = top.currentCost + grid[x][y] if (newCost < (minCosts[x to y] ?: Integer.MAX_VALUE)) { pq.add(RiskPath(newCost, x, y)) minCosts[x to y] = newCost } } } } } private fun parseLines(lines: List<String>): List<List<Int>> { return lines.map { line -> line.map(Char::digitToInt) } } private fun expandGrid(grid: List<List<Int>>): List<List<Int>> { val newGrid = Array(grid.size * 5) { Array(grid[0].size * 5) { 0 } } for (i in grid.indices) { for (j in grid[0].indices) { for (k in 0 until 5) { for (x in 0 until 5) { val ni = i + grid.size * k val nj = j + grid[0].size * x newGrid[ni][nj] = grid[i][j] + k + x while (newGrid[ni][nj] > 9) { newGrid[ni][nj] -= 9 } } } } } return newGrid.map(Array<Int>::toList) } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input15.txt"), Charsets.UTF_8) val solution1 = solve(lines, shouldExpandGrid = false) println(solution1) val solution2 = solve(lines, shouldExpandGrid = true) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
2,595
advent-of-code-2021
The Unlicense
src/main/kotlin/com/ikueb/advent18/Day23.kt
h-j-k
159,901,179
false
null
package com.ikueb.advent18 import com.ikueb.advent18.model.Point3d import kotlin.math.abs object Day23 { private const val DEFINITION = "pos=<([-\\d]+),([-\\d]+),([-\\d]+)>, r=(\\d+)" fun getMostInRange(input: List<String>) = with(nanobots(input)) { count { maxBy { bot -> bot.radius }!!.inRangeTo(it) } } fun getMostCommonAndClosest(input: List<String>): Int { val nanobots = nanobots(input) var range = maxOf(nanobots.deltaBy { point.x }, nanobots.deltaBy { point.y }, nanobots.deltaBy { point.z }) val origin = Point3d(0, 0, 0) var candidates = setOf(Nanobot(origin, range)) while (range > 0) { range = (range / 2) + if (range > 2) 1 else 0 candidates = candidates.flatMap { it.point.adjacent(range).map { point -> Nanobot(point, range) } }.groupBy { bot -> nanobots.count { bot.inTotalRangeTo(it) } } .maxBy { it.key }!!.value.toSet() } return candidates.map { it.point.manhattanDistance(origin) }.min()!! } private fun nanobots(input: List<String>) = input.parseWith(DEFINITION) { (x, y, z, r) -> Nanobot(Point3d(x, y, z), r.toInt()) } } private data class Nanobot(val point: Point3d, val radius: Int) { fun inRangeTo(other: Nanobot) = point.manhattanDistance(other.point) <= radius fun inTotalRangeTo(other: Nanobot) = point.manhattanDistance(other.point) <= radius + other.radius } private inline fun <T> List<T>.deltaBy(block: T.() -> Int) = with(map(block)) { abs((max() ?: 0) - (min() ?: 0)) }
0
Kotlin
0
0
f1d5c58777968e37e81e61a8ed972dc24b30ac76
1,657
advent18
Apache License 2.0
day12/part2.kts
bmatcuk
726,103,418
false
{"Kotlin": 214659}
// --- Part Two --- // As you look out at the field of springs, you feel like there are way more // springs than the condition records list. When you examine the records, you // discover that they were actually folded up this whole time! // // To unfold the records, on each row, replace the list of spring conditions // with five copies of itself (separated by ?) and replace the list of // contiguous groups of damaged springs with five copies of itself (separated // by ,). // // So, this row: // // .# 1 // // Would become: // // .#?.#?.#?.#?.# 1,1,1,1,1 // // The first line of the above example would become: // // ???.###????.###????.###????.###????.### 1,1,3,1,1,3,1,1,3,1,1,3,1,1,3 // // In the above example, after unfolding, the number of possible arrangements // for some rows is now much larger: // // ???.### 1,1,3 - 1 arrangement // .??..??...?##. 1,1,3 - 16384 arrangements // ?#?#?#?#?#?#?#? 1,3,1,6 - 1 arrangement // ????.#...#... 4,1,1 - 16 arrangements // ????.######..#####. 1,6,5 - 2500 arrangements // ?###???????? 3,2,1 - 506250 arrangements // // After unfolding, adding all of the possible arrangement counts together // produces 525152. // // Unfold your condition records; what is the new sum of possible arrangement // counts? import java.io.* val cache = mutableMapOf<Pair<String,List<Int>>,Long>() fun countArrangements(record: String, groups: List<Int>): Long { if (record.isEmpty()) { return if (groups.isEmpty()) 1 else 0 } if (groups.isEmpty()) { return if ('#' in record) 0 else 1 } val cacheKey = record to groups if (cacheKey in cache) { return cache[cacheKey]!! } var result = 0L // if next position in the record is a dot, or possibly a dot... if (record[0] in ".?") { result += countArrangements(record.drop(1), groups) } // if next position in the record is a spring, or possibly a spring... if (record[0] in "#?") { // if the next group can fit at the beginning of the record, and there are // no dots in that substring, and if the character after the group is not a // spring (since there'd need to be a dot between groups), then recurse... if ( record.length >= groups[0] && '.' !in record.take(groups[0]) && (record.length == groups[0] || record[groups[0]] != '#') ) { result += countArrangements(record.drop(groups[0] + 1), groups.drop(1)) } } cache[cacheKey] = result return result } // Fairly naive approach - just generate every possible combination given the // number of groups, and compare that to the input to see which ones match. val result = File("input.txt").readLines().sumOf { val (records, groups) = it.split(' ').let { (r, g) -> "?$r".repeat(5).drop(1) to ",$g".repeat(5).drop(1).split(',').map(String::toInt) } countArrangements(records, groups) } println(result)
0
Kotlin
0
0
a01c9000fb4da1a0cd2ea1a225be28ab11849ee7
2,844
adventofcode2023
MIT License
src/Day09.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
import kotlin.math.abs fun main() { data class Point(var x: Int, var y: Int) fun solve(input: List<String>, knots: Int): Int { // Starting position is the "centre", with plenty of padding to avoid going into negative coordinates. // Positive X goes right, positive Y goes up. val rope = mutableListOf<Point>() repeat(knots) { rope.add(Point(1000, 1000)) } val head = rope[0] val tail = rope[rope.size - 1] val visited = mutableSetOf<String>() visited.add(tail.toString()) for (move in input) { val parts = move.split(" ") val direction = parts[0] val spaces = parts[1].toInt() repeat (spaces) { when (direction) { "U" -> head.y++ "R" -> head.x++ "D" -> head.y-- "L" -> head.x-- } for (i in 1 until rope.size) { val lead = rope[i - 1] val knot = rope[i] if (lead.x != knot.x && lead.y != knot.y && (abs(lead.x - knot.x) + abs(lead.y - knot.y)) > 2) { if (lead.x > knot.x) { knot.x++ } else if (lead.x < knot.x) { knot.x-- } if (lead.y > knot.y) { knot.y++ } else if (lead.y < knot.y) { knot.y-- } if (i == rope.size - 1) visited.add(knot.toString()) } if (lead.x - knot.x > 1) { repeat((lead.x - knot.x) - 1) { knot.x++ if (i == rope.size - 1) visited.add(knot.toString()) } } else if (knot.x - lead.x > 1) { repeat((knot.x - lead.x) - 1) { knot.x-- if (i == rope.size - 1) visited.add(knot.toString()) } } else if (lead.y - knot.y > 1) { repeat((lead.y - knot.y) - 1) { knot.y++ if (i == rope.size - 1) visited.add(knot.toString()) } } else if (knot.y - lead.y > 1) { repeat((knot.y - lead.y) - 1) { knot.y-- if (i == rope.size - 1) visited.add(knot.toString()) } } } } } return visited.size } fun part1(input: List<String>): Int { return solve(input, 2) } fun part2(input: List<String>): Int { return solve(input, 10) } val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
3,168
aoc-2022
Apache License 2.0