path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumsSplicedArray.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 /** * 2321. Maximum Score Of Spliced Array * @see <a href="https://leetcode.com/problems/maximum-score-of-spliced-array/">Source</a> */ fun interface MaximumsSplicedArray { operator fun invoke(nums1: IntArray, nums2: IntArray): Int } class MaximumsSplicedArrayKadane : MaximumsSplicedArray { override operator fun invoke(nums1: IntArray, nums2: IntArray): Int { val n: Int = nums1.size var sum1 = 0 var sum2 = 0 var maxEndHere1 = Int.MIN_VALUE var maxSoFar1 = 0 var maxEndHere2 = Int.MIN_VALUE var maxSoFar2 = 0 for (i in 0 until n) { sum1 += nums1[i] sum2 += nums2[i] // kadane algorithm val diff = nums2[i] - nums1[i] maxSoFar1 = max(diff, maxSoFar1 + diff) maxEndHere1 = max(maxEndHere1, maxSoFar1) maxSoFar2 = max(-diff, maxSoFar2 - diff) maxEndHere2 = max(maxEndHere2, maxSoFar2) } return max(maxEndHere1 + sum1, maxEndHere2 + sum2) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,703
kotlab
Apache License 2.0
codechef/snackdown2021/preelim/guessrow.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codechef.snackdown2021.preelim import java.util.* @Suppress("UNUSED_PARAMETER") // Kotlin 1.2 fun main(args: Array<String>) { val (tests, n) = readInts() val desired = n / 2 val all = 1..n val cnk = List(n + 1) { LongArray(it + 1) { 1 } } for (i in 2..n) for (j in 1 until i) cnk[i][j] = cnk[i - 1][j - 1] + cnk[i - 1][j] fun cnk(i: Int, j: Int) = cnk[i].getOrElse(j) { 0 } fun prob(asked: Int, ones: Int, density: Int) = 1.0 * cnk(asked, ones) * cnk(n - asked, density - ones) / cnk(n, density) val prob = List(n + 1) { asked -> DoubleArray(asked + 1) { ones -> prob(asked, ones, desired) / all.sumOf { prob(asked, ones, it) } } } val random = Random(566) fun shuffle() = (0 until n).shuffled(random) fun solve() { val verShuffle = shuffle() val horShuffle = List(n) { shuffle() } fun ask(x: Int, y: Int): Int { println("? ${verShuffle[x] + 1} ${horShuffle[x][y] + 1}") return readInt() } fun answer(x: Int) { println("! ${verShuffle[x] + 1}") } val asked = IntArray(n) val ones = IntArray(n) val treeSet = TreeSet<Int>(compareBy({ prob[asked[it]][ones[it]] }, { it })) treeSet.addAll(asked.indices) while (true) { val x = treeSet.pollLast()!! ones[x] += ask(x, asked[x]++) if (asked[x] == n && ones[x] == desired) return answer(x) treeSet.add(x) } } repeat(tests) { solve() } } private fun readLn() = readLine()!!.trim() private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,546
competitions
The Unlicense
src/Day01.kt
akleemans
574,937,934
false
{"Kotlin": 5797}
fun main() { fun part1(input: List<String>): Int { var highest = 0 var currentCounter = 0 for (line in input) { if (line.isNotEmpty()) { currentCounter += line.toInt() } else { if (highest < currentCounter) { highest = currentCounter } currentCounter = 0 } } return highest } fun part2(input: List<String>): Int { val numberList = ArrayList<Int>() var currentCounter = 0 for (line in input) { if (line.isNotEmpty()) { currentCounter += line.toInt() } else { numberList.add(currentCounter) currentCounter = 0 } } numberList.add(currentCounter) return numberList.sortedDescending().take(3).sum() } val testInput = readInput("Day01_test_input") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01_input") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
fa4281772d89a6d1cda071db4b6fb92fff5b42f5
1,153
aoc-2022-kotlin
Apache License 2.0
src/Day06.kt
emanguy
573,113,840
false
{"Kotlin": 17921}
fun main() { fun firstUniqueWindowIndex(input: String, windowSize: Int): Int { for (window in input.asSequence().withIndex().windowed(windowSize)) { val uniqueCharacterSet = window.map { it.value }.toSet() if (uniqueCharacterSet.size == windowSize) { return window.last().index + 1 } } return -1 } fun part1(input: String): Int { return firstUniqueWindowIndex(input, 4) } fun part2(input: String): Int { return firstUniqueWindowIndex(input, 14) } // Verify the sample input works val inputs = readInput("Day06_test") val expectedPart1Values = listOf(7, 5, 6, 10, 11) val expectedPart2Values = listOf(19, 23, 23, 29, 26) inputs.zip(expectedPart1Values).forEach { (input, expectedValue) -> check(part1(input) == expectedValue) { "Failed on input $input " } } inputs.zip(expectedPart2Values).forEach { (input, expectedValue) -> check(part2(input) == expectedValue) { "Failed on input $input" } } val finalInputs = readInput("Day06") println(part1(finalInputs.first())) println(part2(finalInputs.first())) }
0
Kotlin
0
1
211e213ec306acc0978f5490524e8abafbd739f3
1,185
advent-of-code-2022
Apache License 2.0
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p00/Leet48.kt
artemkaxboy
513,636,701
false
{"Kotlin": 547181, "Java": 13948}
package com.artemkaxboy.leetcode.p00 import com.artemkaxboy.leetcode.LeetUtils private class Leet48 { fun rotate(matrix: Array<IntArray>) { val size = matrix.size for (layerNumber in 0 until size / 2) { rotateLayer(matrix, layerNumber) } } fun rotateLayer(matrix: Array<IntArray>, layerNumber: Int) { val limit = matrix.size - 1 - layerNumber for (element in layerNumber until limit) { var holder: Int? = null var coord = Coord(element, layerNumber) for (i in 0..4) { val (newCoord, newHolder) = rotateElement(matrix, coord, holder) holder = newHolder coord = newCoord } } } fun rotateElement(matrix: Array<IntArray>, element: Coord, holder: Int?): Pair<Coord, Int?> { val newHolder = matrix[element.y][element.x] holder?.let { matrix[element.y][element.x] = it } return element.rotate(matrix.size) to newHolder } data class Coord(val x: Int, val y: Int) { fun rotate(size: Int): Coord { return Coord(size - 1 - y, x) } } } fun main() { val testCase1 = "[[1,2,3],[4,5,6],[7,8,9]]" doWork(testCase1) val myCase = "[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]" doWork(myCase) val myCase2 = "[[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9]," + "[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9]]" doWork(myCase2) } private fun doWork(data: String) { val solution = Leet48() val prepared = data.split("],[").map { LeetUtils.stringToIntArray(it) }.toTypedArray() println("Data: \n${prepared.joinToString("\n") { it.joinToString() }}") solution.rotate(prepared) println("Data: \n${prepared.joinToString("\n") { it.joinToString() }}") }
0
Kotlin
0
0
516a8a05112e57eb922b9a272f8fd5209b7d0727
1,920
playground
MIT License
src/test/kotlin/com/eugenenosenko/coding/problems/arrays/compose_from_old/ComposeArrayFromOldSolution.kt
eugenenosenko
303,183,289
false
null
package com.eugenenosenko.coding.problems.arrays.compose_from_old // brute force approach fun createArray(arr: IntArray): IntArray { val result = mutableListOf<Int>() for (i in arr.indices) { result.add( arr.foldIndexed(1) { index: Int, acc: Int, item: Int -> // ignore current index if (i == index) acc else acc * item } ) } return result.toIntArray() } // more efficient fun createArrayMoreEfficientWithDivision(arr: IntArray): IntArray { val product = arr.reduce { acc, v -> acc * v } val result = IntArray(arr.size) for ((i, v) in arr.withIndex()) { result[i] = product / v } return result } fun createArrayMoreEfficientWithoutDivision(arr: IntArray): IntArray { val prefixes = arrayListOf<Int>() for (number in arr) { if (prefixes.isNotEmpty()) { prefixes.add(prefixes.last() * number) } else { prefixes.add(number) } } // peak prefixes println("Prefixes are $prefixes") val suffixes = arrayListOf<Int>() for (number in arr.reversed()) { if (suffixes.isNotEmpty()) { suffixes.add(suffixes.last() * number) } else { suffixes.add(number) } } // peak suffixes suffixes.reverse() println("Suffixes are $suffixes") val result = arrayListOf<Int>() for (i in arr.indices) { when (i) { 0 -> result.add(suffixes[i + 1]) arr.lastIndex -> result.add(prefixes[i - 1]) else -> result.add(suffixes[i + 1] * prefixes[i - 1]) } } return result.toIntArray() }
0
Kotlin
0
0
673cc3ef6aa3c4f55b9156d14d64d47588610600
1,698
coding-problems
MIT License
codeforces/globalround20/f1.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.globalround20 private fun solve() { val n = readInt() val a = readInts() val count = IntArray(n + 1) val pos = List(n + 1) { mutableListOf<Int>() } for (i in a.indices) { count[a[i]]++ pos[a[i]].add(i) } val often = count.indices.sortedBy { count[it] } val mostOften = often.last() val ans = IntArray(n) { -1 } for (i in 0..often.size - 2) { val v = often[i] val u = often[i + 1] for (j in 0 until count[v]) { ans[pos[u][j]] = v } } for (i in ans.indices) { if (ans[i] == -1) ans[i] = mostOften } println(ans.joinToString(" ")) } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
809
competitions
The Unlicense
src/main/kotlin/dev/bogwalk/batch2/Problem21.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch2 import dev.bogwalk.util.maths.sumProperDivisors /** * Problem 21: Amicable Numbers * * https://projecteuler.net/problem=21 * * Goal: Return the sum of all amicable numbers less than N. * * Constraints: 1 <= N <= 1e5 * * Proper Divisor: A number x that evenly divides N, where x != N. * * Amicable Number: A number X that has a pair Y, where X != Y but * d(X) = Y && d(Y) = X, with d(N) = sum{proper divisors of N}. * First amicable pairs = {(220, 284), (1184, 1210), (2620, 2924)} * * e.g.: N = 300 * amicable pairs = [{220, 284}]; since * d(220) = sum{1,2,4,5,10,11,20,22,44,55,110} = 284 * d(284) = sum{1,2,4,71,142} = 220 * sum = 220 + 284 = 504 */ class AmicableNumbers { /** * Sums amicable numbers < [n] even if larger pair-member is >= [n]. */ fun sumAmicablePairs(n: Int): Int { val amicableNums = mutableListOf<Int>() for (x in 2 until n) { val y = sumProperDivisors(x) // the partner of a newly explored amicable number must be larger if (y > x && sumProperDivisors(y) == x) { amicableNums.add(x) // account for possibility that only 1 of the amicable pair may be under N if (y < n) { amicableNums.add(y) } else { // future pairs will be > N break } } } return amicableNums.sum() } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
1,509
project-euler-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinCostConnectPoints.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD import kotlin.math.abs /** * 1584. Min Cost to Connect All Points * @see <a href="https://leetcode.com/problems/min-cost-to-connect-all-points">Source page</a> */ fun interface MinCostConnectPoints { operator fun invoke(points: Array<IntArray>): Int } class MinCostConnectPointsPrims : MinCostConnectPoints { override fun invoke(points: Array<IntArray>): Int { val n = points.size var res = 0 var i = 0 var connected = 0 val minD = IntArray(n) { MOD } while (++connected < n) { minD[i] = Int.MAX_VALUE var minJ = i for (j in 0 until n) { if (minD[j] != Int.MAX_VALUE) { minD[j] = minOf(minD[j], abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])) minJ = if (minD[j] < minD[minJ]) j else minJ } } res += minD[minJ] i = minJ } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,662
kotlab
Apache License 2.0
src/Day10.kt
RogozhinRoman
572,915,906
false
{"Kotlin": 28985}
fun main() { fun part1(input: List<String>): Int { var cycles = 1 var x = 1 var signalsSum = 0 val frames = listOf(20, 60, 100, 140, 180, 220) for (command in input) { var dx = 0 if (!command.startsWith("noop")) { cycles++ if (frames.contains(cycles - 1)) { signalsSum += x * (cycles - 1) } dx = command.split(' ').last().toInt() } cycles++ if (frames.contains(cycles - 1)) { signalsSum += x * (cycles - 1) } x += dx } return signalsSum } fun printGrid(grid: Array<MutableList<String>>) { for (i in grid.indices) { for (j in grid[i].indices) { print(grid[i][j]) } println() } } fun getSpritePositions(spritePosition: Int) = listOf(spritePosition - 1, spritePosition, spritePosition + 1) fun part2(input: List<String>) { val rowSize = 40 val grid = Array(6) { MutableList(rowSize) { "." } } var cycles = 0 var spriteCenter = 1 for (command in input) { var dx = 0 if (!command.startsWith("noop")) { if (getSpritePositions(spriteCenter).contains(cycles % rowSize)) { grid[cycles / rowSize][cycles % rowSize] = "#" } cycles++ dx = command.split(' ').last().toInt() } if (getSpritePositions(spriteCenter).contains(cycles % rowSize)) { grid[cycles / rowSize][cycles % rowSize] = "#" } cycles++ spriteCenter += dx } printGrid(grid) } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) // check(part2(testInput) == 70) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
6375cf6275f6d78661e9d4baed84d1db8c1025de
2,049
AoC2022
Apache License 2.0
src/main/kotlin/g1801_1900/s1847_closest_room/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1847_closest_room // #Hard #Array #Sorting #Binary_Search #2023_06_22_Time_1179_ms_(100.00%)_Space_92.1_MB_(100.00%) import java.util.Arrays import java.util.TreeSet class Solution { fun closestRoom(rooms: Array<IntArray>, queries: Array<IntArray>): IntArray { val numRoom = rooms.size val numQuery = queries.size for (i in 0 until numQuery) { queries[i] = intArrayOf(queries[i][0], queries[i][1], i) } Arrays.sort(rooms) { a: IntArray, b: IntArray -> if (a[1] != b[1]) a[1] - b[1] else a[0] - b[0] } Arrays.sort(queries) { a: IntArray, b: IntArray -> if (a[1] != b[1]) a[1] - b[1] else a[0] - b[0] } val roomIds = TreeSet<Int>() val result = IntArray(numQuery) var j = numRoom - 1 for (i in numQuery - 1 downTo 0) { val currRoomId = queries[i][0] val currRoomSize = queries[i][1] val currQueryIndex = queries[i][2] while (j >= 0 && rooms[j][1] >= currRoomSize) { roomIds.add(rooms[j--][0]) } if (roomIds.contains(currRoomId)) { result[currQueryIndex] = currRoomId continue } val nextRoomId = roomIds.higher(currRoomId) val prevRoomId = roomIds.lower(currRoomId) if (nextRoomId == null && prevRoomId == null) { result[currQueryIndex] = -1 } else if (nextRoomId == null) { result[currQueryIndex] = prevRoomId!! } else if (prevRoomId == null) { result[currQueryIndex] = nextRoomId } else { if (currRoomId - prevRoomId <= nextRoomId - currRoomId) { result[currQueryIndex] = prevRoomId } else { result[currQueryIndex] = nextRoomId } } } return result } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,942
LeetCode-in-Kotlin
MIT License
hackerrank/max-array-sum/Solution.kts
shengmin
5,972,157
false
null
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* data class Node(val includedMax: Int, val excludedMax: Int) // Complete the maxSubsetSum function below. fun maxSubsetSum(arr: Array<Int>): Int { if (arr.size == 1) { return maxOf(0, arr[0]) } val sums = Array<Node?>(arr.size) { null } sums[0] = Node(arr[0], 0) sums[1] = Node(arr[1], maxOf(arr[0], 0)) for (i in 2 until arr.size) { val n = arr[i] val previousNode = sums[i - 1]!! // If we exclude the current element // Then, the new excludedMax is just the max(previous includedMax, previous excludedMax) val excludedMax = maxOf(previousNode.includedMax, previousNode.excludedMax) // If we include the current element, the max will be max(previous excludedMax + current, i - 2 includedMax + current) val includedMax = maxOf(previousNode.excludedMax + n, sums[i - 2]!!.includedMax + n) sums[i] = Node(includedMax, excludedMax) } return maxOf(sums.last()!!.includedMax, sums.last()!!.excludedMax) } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val n = scan.nextLine().trim().toInt() val arr = scan.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray() val res = maxSubsetSum(arr) println(res) } main(arrayOf())
0
Java
18
20
08e65546527436f4bd2a2014350b2f97ac1367e7
1,639
coding-problem
MIT License
src/main/kotlin/com/colinodell/advent2021/Day18.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 class Day18 (private val input: List<String>) { fun solvePart1() = sumAndFindMagnitude(input) fun solvePart2() = getHighestMagnitudeOfTwo(input) data class SnailfishPairElement(var value: Int, var depth: Int) private fun parse(input: String): MutableList<SnailfishPairElement> { var depth = 0 val result = mutableListOf<SnailfishPairElement>() for (char in input) { when (char) { '[' -> depth++ ']' -> depth-- ',' -> continue else -> result.add(SnailfishPairElement(Character.getNumericValue(char), depth)) } } return result } private fun parseAndReduce(lines: Iterable<String>): List<SnailfishPairElement> { val lines = lines.map { parse(it) }.toMutableList() while (explodeIfNeeded(lines.first()) || splitIfNeeded(lines.first()) || addNextLineIfNeeded(lines)) { // keep reducing } return lines.first() } private fun explodeIfNeeded(current: MutableList<SnailfishPairElement>): Boolean { val toExplode = current.withIndex().firstOrNull { it.value.depth > 4 } ?: return false // Add the pair's left value to the first regular number on the left, if it exists if (toExplode.index > 0) { current[toExplode.index-1].value += toExplode.value.value } // Add the pair's right value to the first regular number on the right, if it exists if (toExplode.index + 2 < current.size) { current[toExplode.index+2].value += current[toExplode.index+1].value } // Replace the exploded pair with 0 current[toExplode.index].apply { value = 0; depth-- } current.removeAt(toExplode.index + 1) return true } private fun splitIfNeeded(current: MutableList<SnailfishPairElement>): Boolean { val toSplit = current.withIndex().firstOrNull { it.value.value >= 10 } ?: return false toSplit.value.depth++ val newPair = SnailfishPairElement(toSplit.value.value / 2 + toSplit.value.value % 2, toSplit.value.depth) toSplit.value.value /= 2 current.add(toSplit.index + 1, newPair) return true } private fun addNextLineIfNeeded(lines: MutableList<MutableList<SnailfishPairElement>>): Boolean { if (lines.size == 1) { return false } with(lines.first()) { addAll(lines.removeAt(1)) forEach { it.depth++ } } return true } private fun sumAndFindMagnitude(input: List<String>): Int { val numbers = parseAndReduce(input).toMutableList() for (depth in 4 downTo 0) { while (numbers.size > 1 && reduceMagnitudeIfNeeded(numbers, depth)) { // keep reducing } } return numbers[0].value } private fun reduceMagnitudeIfNeeded(numbers: MutableList<SnailfishPairElement>, depth: Int): Boolean { val element = numbers.withIndex().firstOrNull { it.value.depth == depth } ?: return false element.value.depth-- element.value.value = 3 * element.value.value + 2 * numbers[element.index + 1].value numbers.removeAt(element.index + 1) return true } private fun getHighestMagnitudeOfTwo(input: List<String>) = input .permutationPairs() .includingReversePairs() .maxOf { sumAndFindMagnitude(listOf(it.first, it.second)) } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
3,566
advent-2021
Apache License 2.0
src/Day03.kt
aemson
577,677,183
false
{"Kotlin": 7385}
fun main() { val inputData = readInput("Day03_input") val commonItems = inputData.map { item -> val numberOfItems = item.toCharArray().size val firstSet = item.substring(0, numberOfItems / 2).toCharArray().toList() val secondSet = item.substring(numberOfItems / 2, numberOfItems).toCharArray().toList() firstSet.intersect(secondSet.toSet()).first() } println("Rucksack Reorganization (Part 1) -> ${commonItems.map { it.priority() }.sumOf { it }}") val organizeGroups = inputData.chunked(3) val commonBadge = organizeGroups.map { groups -> val firstSack = groups[0].toCharArray().toSet() val secondSack = groups[1].toCharArray().toSet() val thirdSack = groups[2].toCharArray().toSet() firstSack.intersect(secondSack).intersect(thirdSack).first() } println("Rucksack Reorganization (Part 2) -> ${commonBadge.map { it.priority() }.sumOf { it }}") } private fun Char.priority(): Int = when (this) { in 'a'..'z' -> (this - 'a') + 1 in 'A'..'Z' -> (this - 'A') + 27 else -> throw IllegalArgumentException("Letter not in range: $this") }
0
Kotlin
0
0
ffec4b848ed5c2ba9b2f2bfc5b991a2019c8b3d4
1,161
advent-of-code-22
Apache License 2.0
day04/main.kt
LOZORD
441,007,912
false
{"Kotlin": 29367, "Python": 963}
import java.util.Scanner fun main() { val isPart1 = false // true => Part 1; false => Part 2 data class Position(val row: Int, val col: Int, var stamped: Boolean) class BingoBoard { val positionMap = HashMap<Int, Position>(25) val rowStamps = IntArray(5, { _ -> 5}) val colStamps = IntArray(5, { _ -> 5}) constructor(board: Array<IntArray>) { for ((i, row) in board.withIndex()) { for ((j, n) in row.withIndex()) { positionMap.set(n, Position(row=i, col=j, stamped=false)) } } } /** Attempts to stamp the spot with number n (if it's on the board). * If stamping results in a win, the score of the board of is returned. * Otherwise -1 is returned. * * The score is n * the sum of unstamped numbers. */ fun stamp(n: Int) : Int { val p = positionMap.get(n) if (p == null) { return -1 // Not on the board. } p.stamped = true rowStamps[p.row]-- colStamps[p.col]-- if (rowStamps[p.row] == 0 || colStamps[p.col] == 0) { // Bingo! return n * positionMap.filterValues { !it.stamped }.keys.sum() } return -1 // No Bingo. } override fun toString(): String { val grid = Array<IntArray>(5, { _ -> IntArray(5, { _ -> -1 })}) val s = StringBuilder() for ((n, p) in positionMap) { grid[p.row][p.col] = n } for (row in grid) { for (n in row) { s.append("$n ".padStart(2)) } s.append("\n") } return s.toString() } } val input = Scanner(System.`in`) val chosenNumbers = ArrayList<Int>() val whitespace = Regex("\\s+") var optimalSteps = if (isPart1) Int.MAX_VALUE else Int.MIN_VALUE var optimalScore = -1 while(input.hasNextLine()) { if (chosenNumbers.isEmpty()) { chosenNumbers.addAll(input.nextLine().split(',').map { s -> Integer.parseInt(s) }) continue } // Build up a Bingo grid. var grid = Array<IntArray>(5, { _ -> IntArray(5) }) var gridIndex = 0 while(input.hasNextLine()) { val scanned = input.nextLine() if (scanned.isBlank()) { break; } val split = scanned.trim().split(whitespace) grid[gridIndex++] = split.map { s -> Integer.parseInt(s) }.toIntArray() } // Play Bingo! var board = BingoBoard(grid) for ((i, n) in chosenNumbers.withIndex()) { val score = board.stamp(n) if (score < 0) { // No Bingo :( continue } // Bingo! val shouldUpdate = (isPart1 && optimalSteps > i) || (!isPart1 && optimalSteps < i) if (shouldUpdate) { optimalSteps = i optimalScore = score } // On to the next board. break } } println("SCORE: $optimalScore") }
0
Kotlin
0
0
17dd266787acd492d92b5ed0d178ac2840fe4d57
3,307
aoc2021
MIT License
src/Day04.kt
RaspiKonk
572,875,045
false
{"Kotlin": 17390}
/** * Day 4: den Strand aufräumen * * Part 1: Wie viele Assignments liegen vollständig in einem anderen Assignment? * Part 2: Wie viele Assignments überlappen? */ fun main() { val start = System.currentTimeMillis() val DAY: String = "04" println("Advent of Code 2022 - Day $DAY") // Solve part 1. fun part1(input: List<String>): Int { var encapsulationCounter: Int = 0 for(line in input) // 2-4,6-8 { val elf1: String = line.split(",")[0] val elf2: String = line.split(",")[1] //println(elf1 + " " + elf2) // check if one task is inside the other or vice versa val elf1Start: Int = elf1.split("-")[0].toInt() val elf1End: Int = elf1.split("-")[1].toInt() val elf2Start: Int = elf2.split("-")[0].toInt() val elf2End: Int = elf2.split("-")[1].toInt() if(((elf1Start >= elf2Start) && (elf1Start <= elf2End) && (elf1End <= elf2End) && (elf1End >= elf2Start)) || ((elf2Start >= elf1Start) && (elf2Start <= elf1End) && (elf2End <= elf1End) && (elf2End >= elf1Start)) ) { encapsulationCounter++ } } return encapsulationCounter } // Solve part 2. fun part2(input: List<String>): Int { var overlapCounter: Int = 0 for(line in input) // 2-4,6-8 { val elf1: String = line.split(",")[0] val elf2: String = line.split(",")[1] //println(elf1 + " " + elf2) // check if one task is inside the other or vice versa val elf1Start: Int = elf1.split("-")[0].toInt() val elf1End: Int = elf1.split("-")[1].toInt() val elf2Start: Int = elf2.split("-")[0].toInt() val elf2End: Int = elf2.split("-")[1].toInt() if(((elf1Start >= elf2Start) && (elf1Start <= elf2End) || (elf1End <= elf2End) && (elf1End >= elf2Start)) || ((elf2Start >= elf1Start) && (elf2Start <= elf1End) || (elf2End <= elf1End) && (elf2End >= elf1Start)) ) { overlapCounter++ } } return overlapCounter } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${DAY}_test") val input = readInput("Day${DAY}") // Part 1 check(part1(testInput) == 2) println("Part 1: ${part1(input)}") // 524 // Part 2 check(part2(testInput) == 4) println("Part 2: ${part2(input)}") // val elapsedTime = System.currentTimeMillis() - start println("Elapsed time: $elapsedTime ms") }
0
Kotlin
0
1
7d47bea3a5e8be91abfe5a1f750838f2205a5e18
2,343
AoC_Kotlin_2022
Apache License 2.0
ahp-base/src/main/kotlin/pl/poznan/put/ahp/ahp-utils.kt
sbigaret
164,424,298
true
{"Kotlin": 93061, "R": 67629, "Shell": 24899, "Groovy": 24559}
package pl.poznan.put.ahp data class RelationValue( val firstID: String, val secondID: String, val value: Double ) { fun reversed() = RelationValue(secondID, firstID, 1 / value) } fun AhpAlternative.relation() = name.relation() fun String.relation() = RelationValue(this, this, 1.0) data class Relations( private val map: MutableMap<CrytId, List<CrytId>> = mutableMapOf() ) : MutableMap<CrytId, List<CrytId>> by map { val leafs get() = filter { it.value.isEmpty() }.keys.sorted() fun of(criterion: CrytId) = get(criterion)!!.map { it.relation() } } data class CriteriaPreferences( private val map: MutableMap<CrytId, List<List<Double>>> = mutableMapOf() ) : MutableMap<CrytId, List<List<Double>>> by map data class Leafs( private val map: MutableMap<CrytId, Category> ) : MutableMap<CrytId, Category> by map { private val single get(): Category { require(size == 1) { "expected only one head of hierarchy, got $size: ${map { it.key }}" } return map { it.value }.first() } fun topCategory( relations: Relations, criteriaPreferences: CriteriaPreferences ) = buildCat(relations, criteriaPreferences, this).single private tailrec fun buildCat( relations: Relations, criteriaPreferences: CriteriaPreferences, leafs: Leafs ): Leafs { leafs.forEach { relations.remove(it.key) } if (relations.isEmpty()) return leafs val newLeafs = matchingRelationsToCategories(relations, leafs, criteriaPreferences) return buildCat(relations, criteriaPreferences, newLeafs) } private fun matchingRelationsToCategories(relations: Relations, leafs: Leafs, criteriaPreferences: CriteriaPreferences) = relations .mapValues { (k, v) -> matchRelationsWithCategories(k, v, leafs) } .filter { it.value.isNotEmpty() } .mapValues { (k, v) -> Category(k, v, criteriaPreferences.remove(k)!!) } .asLeafs() private fun matchRelationsWithCategories(k: CrytId, v: List<CrytId>, leafs: Leafs) = v.mapNotNull { leafs.remove(it) }.also { require(it.isEmpty() || it.size == v.size) { "not all categories matched for '$k'" } } } fun Map<CrytId, Category>.asLeafs() = Leafs(toMutableMap())
0
Kotlin
0
0
96c182d7e37b41207dc2da6eac9f9b82bd62d6d7
2,411
DecisionDeck
MIT License
src/main/kotlin/io/trie/MapSumPairs.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.trie import java.util.* // https://leetcode.com/explore/learn/card/trie/148/practical-application-i/1058/ class MapSumPairs { private val root = TrieNodeSum(null, "") fun insert(key: String, value: Int) { var current = root key.forEach { char -> current = current.getOrAdd(char) } current.value = value current.finishWord = true } fun sum(prefix: String): Int { var current: TrieNodeSum? = root prefix.forEach { char -> current = current?.getOrNull(char) } return current?.values() ?: 0 } private data class TrieNodeSum( val charValue: Char?, val path: String, var finishWord: Boolean = false, var value: Int = 0, val children: MutableList<TrieNodeSum> = mutableListOf()) { fun values(): Int{ var result = 0 val stack = LinkedList(listOf(this)) while (stack.isNotEmpty()) { val current = stack.pop() if (current.finishWord) { result += current.value } stack.addAll(current.children) } return result } fun add(child: TrieNodeSum) = children.add(child) fun getOrAdd(char: Char, finishWord: Boolean = false) = children.firstOrNull { it.charValue == char }?.also { it.finishWord = it.finishWord || finishWord } ?: TrieNodeSum(char, this.path + char, finishWord).also { children.add(it) } fun getOrNull(char: Char) = children.firstOrNull { it.charValue == char } } // val values = mutableListOf<Pair<String, Int>>() // // fun insert(key: String, value: Int) { // values.firstOrNull { it.first == key }?.let { values.remove(it) } // values.add(key to value) // } // // fun sum(prefix: String): Int = values.filter { it.first.startsWith(prefix) }.fold(0) { acc, item -> acc + item.second } } fun main() { val mapSumPairs = MapSumPairs() mapSumPairs.insert("apple", 3) println(mapSumPairs.sum("ap")) mapSumPairs.insert("app", 2) println(mapSumPairs.sum("ap")) }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,997
coding
MIT License
src/test/kotlin/be/brammeerten/y2022/Day9Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2022 import be.brammeerten.Co import be.brammeerten.extractRegexGroups import be.brammeerten.readFile import be.brammeerten.toCharList import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import kotlin.math.abs import kotlin.math.sign class Day9Test { @Test fun `part 1`() { val result = solve("2022/day9/exampleInput.txt", 2, print = true) Assertions.assertEquals(13, result) } @Test fun `part 1b`() { val result = solve("2022/day9/input.txt", 2) Assertions.assertEquals(5883, result) } @Test fun `part 2`() { val result = solve("2022/day9/exampleInput2.txt", 10) Assertions.assertEquals(36, result) } @Test fun `part 2b`() { val result = solve("2022/day9/input.txt", 10) Assertions.assertEquals(2367, result) } fun solve(file: String, snakeLength: Int, print: Boolean = false): Int { val map = RopeMap(snakeLength) readFile(file) .map { extractRegexGroups("(.) (\\d+)", it) } .flatMap { (dir, num) -> dir.repeat(num.toInt()).toCharList() } .map { char -> when (char) { 'U' -> Co(-1, 0) 'D' -> Co(1, 0) 'R' -> Co(0, 1) else -> Co(0, -1) } }.forEach { move -> map.move(move) if (print) map.print() } return map.visited.size } class RopeMap(length: Int) { private var snake: MutableList<Co> val visited: HashSet<Co> = HashSet() private var topLeft: Co = Co(-2, -2) private var bottomRight: Co = Co(2, 2) init { snake = generateSequence { Co(0,0) }.take(length).toMutableList() visited.add(snake[snake.size-1]) } fun move(co: Co) { snake[0] = snake[0] + co for (i in 1 until snake.size) snake[i] = follow(snake[i-1], snake[i]) visited.add(snake[snake.size-1]) topLeft = topLeft.min(snake[0]) bottomRight = bottomRight.max(snake[0]) } private fun follow(head: Co, tail: Co): Co { val colDiff = head.col - tail.col val rowDiff = head.row - tail.row return if (abs(colDiff) <= 1 && abs(rowDiff) <= 1) tail else Co(tail.row + rowDiff.sign, tail.col + colDiff.sign) } fun print() { for (row in topLeft.row..bottomRight.row) { for (col in topLeft.col..bottomRight.col) { if (snake[0] == Co(row, col)) print("H ") else if (snake[snake.size-1] == Co(row, col)) print("T ") else { val i = snake.indexOf(Co(row, col)) if (i != -1) print("" + (i + 1) + " ") else if (visited.contains(Co(row, col))) print("# ") else print(". ") } } println() } println("\n") } } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
3,307
Advent-of-Code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumKnightMoves.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.leetcode.MinimumKnightMoves.Companion.offsets import java.util.Deque import java.util.LinkedList import kotlin.math.abs import kotlin.math.min /** * Minimum Knight Moves * @see <a href="https://leetcode.com/problems/minimum-knight-moves">Source</a> */ fun interface MinimumKnightMoves { operator fun invoke(x: Int, y: Int): Int companion object { val offsets = arrayOf( intArrayOf(1, 2), intArrayOf(2, 1), intArrayOf(2, -1), intArrayOf(1, -2), intArrayOf(-1, -2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf(-1, 2), ) } } /** * Approach 1: BFS (Breadth-First Search) */ class MinimumKnightMovesBFS : MinimumKnightMoves { override operator fun invoke(x: Int, y: Int): Int { // - Rather than using the inefficient HashSet, we use the bitmap // otherwise we would run out of time for the test cases. // - We create a bitmap that is sufficient to cover all the possible // inputs, according to the description of the problem. val visited = Array(BITMAP_SIZE) { BooleanArray(BITMAP_SIZE) } val queue: Deque<IntArray> = LinkedList() queue.addLast(intArrayOf(0, 0)) var steps = 0 while (queue.isNotEmpty()) { val currLevelSize = queue.size // iterate through the current level for (i in 0 until currLevelSize) { val curr = queue.removeFirst() if (curr[0] == x && curr[1] == y) { return steps } for (offset in offsets) { val next = intArrayOf(curr[0] + offset[0], curr[1] + offset[1]) // align the coordinate to the bitmap if (!visited[next[0] + BITMAP_MID][next[1] + BITMAP_MID]) { visited[next[0] + BITMAP_MID][next[1] + BITMAP_MID] = true queue.addLast(next) } } } steps++ } // move on to the next level return steps } companion object { private const val BITMAP_SIZE = 605 private const val BITMAP_MID = 302 } } /** * Approach 2: Bidirectional BFS */ class MinimumKnightMovesBidirectional : MinimumKnightMoves { override operator fun invoke(x: Int, y: Int): Int { // data structures needed to move from the origin point val originQueue: Deque<IntArray> = LinkedList() originQueue.addLast(intArrayOf(0, 0, 0)) val originDistance: MutableMap<String, Int> = HashMap() originDistance["0,0"] = 0 // data structures needed to move from the target point val targetQueue: Deque<IntArray> = LinkedList() targetQueue.addLast(intArrayOf(x, y, 0)) val targetDistance: MutableMap<String, Int> = HashMap() targetDistance["$x,$y"] = 0 while (true) { // check if we reach the circle of target val origin = originQueue.removeFirst() val originXY = origin[0].toString() + "," + origin[1] if (targetDistance.containsKey(originXY)) { return origin[2] + targetDistance[originXY]!! } // check if we reach the circle of origin val target = targetQueue.removeFirst() val targetXY = target[0].toString() + "," + target[1] if (originDistance.containsKey(targetXY)) { return target[2] + originDistance[targetXY]!! } for (offset in offsets) { // expand the circle of origin val nextOrigin = intArrayOf(origin[0] + offset[0], origin[1] + offset[1]) val nextOriginXY = nextOrigin[0].toString() + "," + nextOrigin[1] if (!originDistance.containsKey(nextOriginXY)) { originQueue.addLast(intArrayOf(nextOrigin[0], nextOrigin[1], origin[2] + 1)) originDistance[nextOriginXY] = origin[2] + 1 } // expand the circle of target val nextTarget = intArrayOf(target[0] + offset[0], target[1] + offset[1]) val nextTargetXY = nextTarget[0].toString() + "," + nextTarget[1] if (!targetDistance.containsKey(nextTargetXY)) { targetQueue.addLast(intArrayOf(nextTarget[0], nextTarget[1], target[2] + 1)) targetDistance[nextTargetXY] = target[2] + 1 } } } } } /** * Approach 3: DFS (Depth-First Search) with Memoization */ class MinimumKnightMovesMemoization : MinimumKnightMoves { private val memo: MutableMap<String, Int> = HashMap() private fun dfs(x: Int, y: Int): Int { val key = "$x,$y" if (memo.containsKey(key)) { return memo[key]!! } return when { x + y == 0 -> { 0 } x + y == 2 -> { 2 } else -> { val ret = min( dfs(abs(x - 1), abs(y - 2)), dfs(abs(x - 2), abs(y - 1)), ) + 1 memo[key] = ret ret } } } override operator fun invoke(x: Int, y: Int): Int { return dfs(abs(x), abs(y)) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
6,102
kotlab
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions48.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round0 /** * 一个只包含小写字母的字符串的最大非重复子字符串的长度 */ fun test48() { val str = "arabcacfr" println("字符串:$str,最大子字符串的长度是:${longestSubstringWithoutDuplication(str)}") } fun longestSubstringWithoutDuplication(str: String): Int { // 检查字符是否合法 fun Char.isLegal(): Boolean = code in 97..122 // 获取字符在数组中的位置 fun Char.getPosition(): Int = code - 97 // 计算逻辑 val array = IntArray(26) var curLength = 0 var maxLength = 0 for (i in str.indices) { val c = str[i] require(c.isLegal()) { "输入的字符串包含不合法字符" } val position = c.getPosition() if (array[position] == 0) { curLength++ } else { curLength = 1 for (j in array.indices) array[j] = 0 } array[position]++ if (curLength > maxLength) maxLength = curLength } return maxLength }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
937
Algorithm
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch7/Problem80.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch7 import java.math.BigDecimal import java.math.MathContext import java.math.RoundingMode import kotlin.math.sqrt /** * Problem 80: Square Root Digital Expansion * * https://projecteuler.net/problem=80 * * Goal: For the first N natural numbers, find the total of the digit sums of the first P digits * for all irrational square roots x, such that x <= N. Note that this includes digits before & * after the decimal point. * * Constraints: 1 <= N <= 1e3 && 1 <= P <= 1e3 OR * 1 <= N <= 100 && 1 <= P <= 1e4 * * e.g.: N = 2, P = 20 * sqrt(1) = 1 (not irrational) * sqrt(2) = 1.4142135623730950488... * total = 76 */ class SquareRootDigitalExpansion { /** * Solution takes advantage of BigDecimal's intrinsic precision capabilities to return a * BigDecimal value of sqrt([n]) that has only [p] digits. * * N.B. This solution uses a manual square root implementation (using the Babylonian method), * instead of the in-built function BigDecimal.sqrt() added in Java 9, to handle HackerRank * submissions. This solution has a parameter toggle purely for the purposes of enabling the * latter & performing speed tests, for curiosity's sake. * * SPEED (BETTER for Manual sqrt) 1.94s for N = 100, P = 1e4 * SPEED (WORSE for Built-in sqrt) 3.98s for N = 100, P = 1e4 */ fun irrationalSquareDigitSum(n: Int, p: Int, manualRoot: Boolean = false): Int { // set precision (amount of digits before & after decimal point) val rules = MathContext(p, RoundingMode.FLOOR) var total = 0 for (num in 2..n) { if (sqrt(1.0 * num) % 1 == 0.0) continue // skip perfect squares val rootBD = if (manualRoot) { num.toBigDecimal().sqrtManual(rules) } else { num.toBigDecimal().sqrt(rules) } total += rootBD.toPlainString().sumOf { // equivalent to (it - '0').coerceAtLeast(0) if (it == '.') 0 else it.digitToInt() } } return total } /** * Solution follows the same idea as the original above, except for the following: * * - All square roots are cached in an array to allow quick access for future calculations. * * - The square root of a number is only calculated using the manual Babylonian method if * the number is prime. Otherwise, it is calculated using the product of the cached square * roots of its prime factors. Any potential rounding errors from this multiplication will * be offset by the precision of each cached BigDecimal root being set to exceed [p]. * * SPEED (BEST for Manual sqrt) 735.63ms for N = 100, P = 1e4 */ fun irrationalSquareDigitSumImproved(n: Int, p: Int): Int { val allRoots = Array<BigDecimal>(n + 1) { BigDecimal.ZERO } val rules = MathContext(p + 10, RoundingMode.FLOOR) var total = 0 for (num in 2..n) { var approx = 1 while (approx * approx < num) { approx++ } if (approx * approx == num) { // store then skip perfect squares allRoots[num] = approx.toBigDecimal() continue } var factor = approx - 1 while (num % factor != 0) { factor-- } val rootBD = if (factor > 1) { // if num is composite, multiply the first factors found allRoots[factor].multiply(allRoots[(num/factor)], rules) } else { // if num is prime, get the root manually num.toBigDecimal().sqrtManual(rules) } allRoots[num] = rootBD // truncate string to requested size plus 1 for the point character total += rootBD.toPlainString().take(p+1).sumOf { // equivalent to (it - '0').coerceAtLeast(0) if (it == '.') 0 else it.digitToInt() } } return total } /** * Manual implementation of the Babylonian method that calculates a successive approximation * of the square root of a BigDecimal. * * The Babylonian method oscillates between approximations of the square root until either * successive guesses are equal or the iteration has exceeded the requested precision. * * After the first arbitrary guess G is made, it is assumed that, if G is an overestimate, * then [this]/G will be an underestimate, so the average of the 2 estimates is found to get * a better approximation, such that: * * averageG = (G + [this]/G) / 2 * * N.B. If the BigDecimal can fit into a Long/Double value, the 1st guess is brought as close * as possible to the true sqrt by casting & getting the sqrt of the latter, as it will * require fewer iterations due to simply being of lower precision. * * @throws ArithmeticException if [this] is < 0. */ private fun BigDecimal.sqrtManual(mc: MathContext): BigDecimal { if (this < BigDecimal.ZERO) throw ArithmeticException("BigDecimal must be 0 or positive") if (this == BigDecimal.ZERO) return BigDecimal.ZERO var guess = if (this.precision() > 18) { this.divide(2.toBigDecimal(), mc) } else { sqrt(this.toDouble()).toBigDecimal(mc) } var i = 0 while (i < mc.precision + 1) { val averageGuess = (guess + this.divide(guess, mc)).divide(2.toBigDecimal(), mc) if (guess == averageGuess) break guess = averageGuess i++ } return guess } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
5,761
project-euler-kotlin
MIT License
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day03.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day class Day03 : Day("3959450", "7440311") { private val numbers = input.lines() override fun solvePartOne(): Any { val gammaRate = getRate { zeros, ones -> zeros > ones } val epsilonRate = getRate { zeros, ones -> zeros < ones } return gammaRate * epsilonRate } override fun solvePartTwo(): Any { val generatorRating = getRating { zeros, ones -> ones < zeros } val scrubberRating = getRating { zeros, ones -> zeros <= ones } return generatorRating * scrubberRating } private fun getRate(addZero: (zeros: Int, ones: Int) -> Boolean): Int { return (0 until numbers[0].length) .map { i -> val zeros = numbers.count { it[i] == '0' } val ones = numbers.count { it[i] == '1' } if (addZero(zeros, ones)) '0' else '1' } .joinToString("") .toInt(2) } private fun getRating(useZeros: (zeros: Int, ones: Int) -> Boolean): Int { return (0 until numbers[0].length) .fold(numbers) { acc, i -> if (acc.size == 1) { acc } else { val zeros = acc.filter { it[i] == '0' } val ones = acc.filter { it[i] == '1' } if (useZeros(zeros.size, ones.size)) zeros else ones } } .first() .toInt(2) } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
1,486
advent-of-code-2021
MIT License
src/day4/Day04.kt
dinoolivo
573,723,263
false
null
package day4 import day3.Interval import readInput fun main() { fun convertToIntervals(input: String):Pair<Interval, Interval>{ val rowParts = input.split(",") return Pair(Interval.fromString(rowParts[0]), Interval.fromString(rowParts[1])) } fun part1(input: List<Pair<Interval, Interval>>): Int = input.sumOf { intervals -> if (intervals.first.contains(intervals.second) || intervals.second.contains(intervals.first)) 1 as Int else 0 } fun part2(input: List<Pair<Interval, Interval>>): Int = input.sumOf { intervals -> if (intervals.first.overlaps(intervals.second)) 1 as Int else 0 } // verify that the solution works with test data val testInput = readInput("inputs/Day04_test").map(::convertToIntervals) println("Test Part 1: " + part1(testInput)) println("Test Part 2: " + part2(testInput)) //execute the two parts on the real input val input = readInput("inputs/Day04").map(::convertToIntervals) println("Part1: " + part1(input)) println("Part2: " + part2(input)) }
0
Kotlin
0
0
6e75b42c9849cdda682ac18c5a76afe4950e0c9c
1,080
aoc2022-kotlin
Apache License 2.0
src/leetcode_study_badge/algorithm/Day6.kt
faniabdullah
382,893,751
false
null
package leetcode_study_badge.algorithm class Day6 { fun checkInclusion(s1: String, s2: String): Boolean { if (s1.length > s2.length) return false val s1map = IntArray(26) val s2map = IntArray(26) for (i in s1.indices) { s1map[s1[i] - 'a']++ s2map[s2[i] - 'a']++ } for (i in 0 until s2.length - s1.length) { if (matches(s1map, s2map)) return true s2map[s2[i + s1.length] - 'a']++ s2map[s2[i] - 'a']-- } return matches(s1map, s2map) } private fun matches(s1map: IntArray, s2map: IntArray): Boolean { for (i in 0..25) { if (s1map[i] != s2map[i]) return false } return true } fun lengthOfLongestSubstring(s: String): Int { var longest = 0 var currentRunStartIndex = 0 val lastSeenIndices = IntArray(128) s.toCharArray().forEachIndexed { index, char -> with(char.code) { currentRunStartIndex = maxOf(lastSeenIndices[this], currentRunStartIndex) longest = maxOf(longest, index - currentRunStartIndex + 1) lastSeenIndices[this] = index + 1 println(" index $index - $currentRunStartIndex and $longest , lastSeen ${lastSeenIndices[this]}") } } return longest } } fun main() { println(Day6().checkInclusion("fabi", "ibafsalsaila")) println(Day6().lengthOfLongestSubstring("abcabcbb")) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,513
dsa-kotlin
MIT License
src/Day01.kt
rounakdatta
570,368,613
false
{"Kotlin": 1801}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { return input.fold(Pair(0, 0)) { (currentSum, maxSum), it -> if (it != "") { Pair(currentSum + it.toInt(), max(maxSum, currentSum + it.toInt())) } else { Pair(0, maxSum) } } .second } fun part2(input: List<String>): Int { return input.toMutableList().apply { this.add("") } .fold(Pair(0, mutableListOf(0))) { (currentSum, listOfSums), it -> if (it != "") { Pair(currentSum + it.toInt(), listOfSums) } else { Pair(0, listOfSums.apply { this.add(currentSum) }) } } .second.sorted() .takeLast(3) .sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
2a253d33c103d885f423a1046138d1dbc4216cec
935
aoc-2022
Apache License 2.0
src/main/kotlin/lain/Range.kt
liminalitythree
269,473,503
false
null
package lain import kotlin.math.abs data class Range(val min:Int, val max: Int) { init { if (min > max) { throw Exception("Range created with min greater than max, min: $min max: $max") } } companion object { fun and(a:Range, b:Range):Range { val min = if (a.min <= b.min) b.min else a.min val max = if (a.max >= b.max) b.max else a.max return Range(min, max) } fun or(a:Range, b:Range):Range { // lowest min, highest max val min = if (a.min <= b.min) a.min else b.min val max = if (a.max <= b.max) b.max else a.max return Range(min, max) } // subtract b from a, will return values that are in a but not in b fun subtract (a: Range, b: Range): List<Range> { if (!overlaps(a, b)) return listOf(a) // if b is completely inside a, eg it will split a into two ranges if (b.min > a.min && b.max < a.max) { return listOf( Range(a.min, b.min - 1), Range(b.max + 1, a.max) ) } // if b is overlapping the top of a if (b.max >= a.max) return listOf(Range(a.min, b.min - 1)) // else, b is overlapping the bottom of a return listOf(Range(b.max + 1, a.max)) } // returns true if the two input ranges overlap, false if they don't fun overlaps(a: Range, b:Range):Boolean { if (a.min > b.max) return false if (b.min > a.max) return false return true } } fun isEmpty():Boolean { if (this.min >= this.max) return true return false } // returns the difference between min and max fun width(): Int { return (abs(this.min - this.max)) } }
2
Kotlin
0
0
6d5fbcc29da148fd72ecb58b164fc5c845267e5c
1,947
bakadesu
Creative Commons Zero v1.0 Universal
y2019/src/main/kotlin/adventofcode/y2019/Day04.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution fun main() = Day04.solve() object Day04 : AdventSolution(2019, 4, "Secure Container") { override fun solvePartOne(input: String) = parseFast(input).count { c -> c.toString().zipWithNext().any { (a, b) -> a == b } } override fun solvePartTwo(input: String) = parseFast(input).count { c -> c.toString().groupBy { it }.any { it.value.size == 2 } } private fun parseFast(input: String): Sequence<Int> { val (l, h) = input.split('-').map(String::toInt) return iterate(h).dropWhile { it < l } } private fun iterate(bound: Int) = sequence { outer@ for (a in 0..9) for (b in a..9) for (c in b..9) for (d in c..9) for (e in d..9) for (f in e..9) { val res = a * 100_000 + b * 10_000 + c * 1_000 + d * 100 + e * 10 + f if (res > bound) break@outer yield(res) } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,124
advent-of-code
MIT License
src/Day08.kt
icoffiel
572,651,851
false
{"Kotlin": 29350}
private const val DAY = "Day08" fun main() { fun <T> Iterable<T>.takeWhileInclusive( predicate: (T) -> Boolean ): List<T> { var shouldContinue = true return takeWhile { val result = shouldContinue shouldContinue = predicate(it) result } } fun part1(input: List<String>): Int { val grid: List<List<Int>> = input .map { row -> row.map { it.digitToInt() } } val visibilityMatrix: List<List<Boolean>> = grid.mapIndexed { rowIndex, row -> row.mapIndexed { columnIndex, column -> val sizeToBeat = column when { rowIndex == 0 -> true // at the top of the grid rowIndex == grid.size - 1 -> true // at the bottom of the grid columnIndex == 0 -> true columnIndex == grid[0].size - 1 -> true else -> { val rowLeftBeat: Boolean = (0 until columnIndex) .map { when { grid[rowIndex][it] < sizeToBeat -> true else -> false } } .all { it } val rowRightBeat = (columnIndex + 1 until row.size) .map { when { grid[rowIndex][it] < sizeToBeat -> true else -> false } } .all { it } val columnUpBeat = (0 until rowIndex) .map { when { grid[it][columnIndex] < sizeToBeat -> true else -> false } } .all { it } val columnDownBeat = (rowIndex + 1 until grid.size) .map { when { grid[it][columnIndex] < sizeToBeat -> true else -> false } } .all { it } when { rowLeftBeat || rowRightBeat -> true // check if visible along the row columnUpBeat || columnDownBeat -> true // check if visible along the column else -> false // otherwise return false } } } } } return visibilityMatrix .flatten() .count { it } } fun part2(input: List<String>): Int { val grid: List<List<Int>> = input .map { row -> row.map { it.digitToInt() } } val visibilityMatrix: List<List<Int>> = grid.mapIndexed { rowIndex, row -> row.mapIndexed { columnIndex, column -> val currentValue = column val rowLeftScan = when (columnIndex) { 0 -> 0 else -> { (columnIndex - 1 downTo 0) .map { grid[rowIndex][it] } .takeWhileInclusive { it < currentValue } .count() } } val rowRightBeat = when (columnIndex) { row.size -> 0 else -> { (columnIndex + 1 until row.size) .map { grid[rowIndex][it] } .takeWhileInclusive { it < currentValue } .count() } } val columnUpBeat = when (rowIndex) { 0 -> 0 else -> { (rowIndex - 1 downTo 0) .map { grid[it][columnIndex] } .takeWhileInclusive { it < currentValue } .count() } } val columnDownBeat = when (rowIndex) { grid.size -> 0 else -> { (rowIndex + 1 until grid.size) .map { grid[it][columnIndex] } .takeWhileInclusive { it < currentValue } .count() } } rowLeftScan * rowRightBeat * columnUpBeat * columnDownBeat } } return visibilityMatrix .flatten() .max() } val testInput = readInput("${DAY}_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput(DAY) println("Part One: ${part1(input)}") check(part1(input) == 1676) println("Part Two: ${part2(input)}") check(part2(input) == 313200) }
0
Kotlin
0
0
515f5681c385f22efab5c711dc983e24157fc84f
5,288
advent-of-code-2022
Apache License 2.0
src/day10/Day10ToddGinsbergSolution.kt
commanderpepper
574,647,779
false
{"Kotlin": 44999}
package day10 import readInput import kotlin.math.absoluteValue fun main() { val day10Input = readInput("day10") val signals = parseInput(day10Input).runningReduce(Int::plus) val dayOneSolution = solvePart1(signals) println(dayOneSolution) solvePart2(signals) } fun parseInput(input: List<String>): List<Int> = buildList { add(1) input.forEach { line -> add(0) if (line.startsWith("addx")) { add(line.substringAfter(" ").toInt()) } } } fun List<Int>.sampleSignals(): List<Int> = (60 .. size step 40).map { cycle -> cycle * this[cycle - 1] } + this[19] fun solvePart1(signals: List<Int>): Int = signals.sampleSignals().sum() fun solvePart2(signals: List<Int>): Unit = signals.screen().print() fun List<Int>.screen(): List<Boolean> = this.mapIndexed { pixel, signal -> (signal-(pixel%40)).absoluteValue <= 1 } fun List<Boolean>.print() { this.windowed(40, 40, false).forEach { row -> row.forEach { pixel -> print(if(pixel) '#' else ' ') } println() } }
0
Kotlin
0
0
fef291c511408c1a6f34a24ed7070ceabc0894a1
1,112
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2023/day16/day16.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day16 import biz.koziolek.adventofcode.* fun main() { val inputFile = findInput(object {}) val mirrors = parseMirrorContraption(inputFile.bufferedReader().readLines()) val beamPath = simulateBeam(mirrors) println("Energized tiles: ${countEnergizedTiles(beamPath)}") } const val EMPTY_SPACE = '.' const val MIRROR_RIGHT = '/' const val MIRROR_LEFT = '\\' const val SPLITTER_VERTICAL = '|' const val SPLITTER_HORIZONTAL = '-' const val ENERGIZED_TILE = '#' fun parseMirrorContraption(lines: Iterable<String>): Map<Coord, Char> = lines.parse2DMap().filter { it.second != EMPTY_SPACE }.toMap() fun simulateBeam(mirrors: Map<Coord, Char>, start: Pair<Coord, Direction> = Coord(0, 0) to Direction.EAST): Sequence<Pair<Coord, Direction>> = sequence { var beams = listOf(start) val horizontalRange = mirrors.getHorizontalRange() val verticalRange = mirrors.getVerticalRange() val seen = mutableSetOf<Pair<Coord, Direction>>() while (beams.isNotEmpty()) { beams = beams.also { seen.addAll(it) }.flatMap { (beamCoord, beamDirection) -> val mirror = mirrors[beamCoord] val newDirections: List<Direction> = when (mirror) { MIRROR_RIGHT -> when (beamDirection) { Direction.NORTH -> listOf(Direction.EAST) Direction.SOUTH -> listOf(Direction.WEST) Direction.WEST -> listOf(Direction.SOUTH) Direction.EAST -> listOf(Direction.NORTH) } MIRROR_LEFT -> when (beamDirection) { Direction.NORTH -> listOf(Direction.WEST) Direction.SOUTH -> listOf(Direction.EAST) Direction.WEST -> listOf(Direction.NORTH) Direction.EAST -> listOf(Direction.SOUTH) } SPLITTER_VERTICAL -> when (beamDirection) { Direction.NORTH -> listOf(Direction.NORTH) Direction.SOUTH -> listOf(Direction.SOUTH) Direction.WEST -> listOf(Direction.NORTH, Direction.SOUTH) Direction.EAST -> listOf(Direction.NORTH, Direction.SOUTH) } SPLITTER_HORIZONTAL -> when (beamDirection) { Direction.NORTH -> listOf(Direction.WEST, Direction.EAST) Direction.SOUTH -> listOf(Direction.WEST, Direction.EAST) Direction.WEST -> listOf(Direction.WEST) Direction.EAST -> listOf(Direction.EAST) } else -> listOf(beamDirection) } newDirections.forEach { yield(beamCoord to it) } newDirections .map { beamCoord.move(it) to it } .filter { (coord, _) -> coord.x in horizontalRange && coord.y in verticalRange } .filter { it !in seen } } } } fun getEnergizedTiles(beamPath: Sequence<Pair<Coord, Direction>>): Map<Coord, List<Direction>> = beamPath.fold(mutableMapOf()) { acc, (coord, direction) -> acc.compute(coord) { _, existingDirections -> if (existingDirections == null) { listOf(direction) } else { existingDirections + direction } } acc } fun showPath(mirrors: Map<Coord, Char>, beamPath: Sequence<Pair<Coord, Direction>>): String { val energizedTiles = getEnergizedTiles(beamPath) return mirrors .to2DString { coord, mirror -> mirror ?: energizedTiles[coord]?.let { when (it.size) { 1 -> it[0].char else -> it.size.digitToChar(radix = 36) } } ?: EMPTY_SPACE } } fun showEnergizedTiles(beamPath: Sequence<Pair<Coord, Direction>>): String = beamPath .map { it.first to ENERGIZED_TILE } .toMap() .to2DString(EMPTY_SPACE) fun countEnergizedTiles(beamPath: Sequence<Pair<Coord, Direction>>): Int = getEnergizedTiles(beamPath).keys.size fun findBestBeamStart(mirrors: Map<Coord, Char>): Pair<Coord, Direction> { val width = mirrors.getWidth() val height = mirrors.getHeight() val startsNorth = (0..<width).map { x -> Coord(x, 0) to Direction.SOUTH } val startsSouth = (0..<width).map { x -> Coord(x, height - 1) to Direction.NORTH } val startsWest = (0..<height).map { y -> Coord(0, y) to Direction.EAST } val startsEast = (0..<height).map { y -> Coord(width - 1, y) to Direction.WEST } return (startsNorth + startsSouth + startsWest + startsEast) .maxBy { countEnergizedTiles(simulateBeam(mirrors, it)) } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
4,954
advent-of-code
MIT License
src/day7/Day7.kt
ZsemberiDaniel
159,921,870
false
null
package day7 import RunnablePuzzleSolver import java.lang.StringBuilder import java.util.* import kotlin.collections.HashMap class Day7 : RunnablePuzzleSolver { private val instructions: HashMap<Char, Instruction> = hashMapOf() private val workerCount = 5 override fun readInput1(lines: Array<String>) { lines.forEach { // which is needed for the instructionId val neededId = it[5] val instructionId = it[36] // we create objects if they are not present in the list if (!instructions.containsKey(neededId)) instructions[neededId] = Instruction(neededId) if (!instructions.containsKey(instructionId)) instructions[instructionId] = Instruction(instructionId) // add the prerequisite for the current line's instruction instructions[instructionId]!!.prerequisites.add(instructions[neededId]!!) instructions[neededId]!!.prerequisitesOf.add(instructions[instructionId]!!) } } override fun readInput2(lines: Array<String>) { } override fun solvePart1(): String { val orderOfInstructions = StringBuilder() // this contains whether an instruction has been finished val isInstructionDone: HashMap<Char, Boolean> = hashMapOf() for (instruction in instructions.values) { isInstructionDone[instruction.id] = false } // the instructions with which we need to begin has no prerequisites // we also need to map it to a sorted tree that is sorted in alphabetical order val availableInstructions = TreeSet(instructions.values.filter { it.prerequisites.isEmpty() } .toSortedSet(Comparator<Instruction> { i1, i2 -> i1.id.compareTo(i2.id) })) // while we have available instructions while (!availableInstructions.isEmpty()) { // we finish the current instruction val currInstruction = availableInstructions.pollFirst() isInstructionDone[currInstruction.id] = true orderOfInstructions.append(currInstruction.id) for (instruction in currInstruction.prerequisitesOf) { // there is no prerequisite that is not done if (instruction.prerequisites.find { !isInstructionDone[it.id]!! } == null && !availableInstructions.contains(instruction)) { availableInstructions.add(instruction) } } } return orderOfInstructions.toString() } override fun solvePart2(): String { // this contains whether an instruction has been finished and if it has it stores // when the instruction was finished val instructionDoneTime: HashMap<Char, Int?> = hashMapOf() for (instruction in instructions.values) { instructionDoneTime[instruction.id] = null } // the instructions with which we need to begin has no prerequisites // we also need to map it to a sorted tree that is sorted in alphabetical order val availableInstructions = TreeSet(instructions.values.filter { it.prerequisites.isEmpty() } .toSortedSet(Comparator<Instruction> { i1, i2 -> i1.id.compareTo(i2.id) })) val workersFinish = Array(workerCount) { 0 } // while we have available instructions while (!availableInstructions.isEmpty()) { val currInstruction = availableInstructions.pollFirst() // we get the prerequisite instruction that was finished the last and get when was it finished val currInstructionStartTime = instructionDoneTime[currInstruction.prerequisites.maxBy { instructionDoneTime[it.id] ?: 0 }?.id ?: -1] ?: 0 instructionDoneTime[currInstruction.id] = currInstructionStartTime + currInstruction.takesTime // we look for a worker who can do the current instruction by checking when (s)he finishes var workerWorkingId: Int? = null for (i in 0 until workerCount) { // we have a worker who can do this instruction if (workersFinish[i] <= instructionDoneTime[currInstruction.id]!! - currInstruction.takesTime) { workerWorkingId = i break } } // we found a worker that can work on this instruction if (workerWorkingId != null) { workersFinish[workerWorkingId] = instructionDoneTime[currInstruction.id]!! } else { // no worker can work on the current instruction right now // find the worker who finishes the earliest workerWorkingId = (0 until workerCount).minBy { workersFinish[it] }!! // delegate work to that worker workersFinish[workerWorkingId] += currInstruction.takesTime instructionDoneTime[currInstruction.id] = workersFinish[workerWorkingId] } // we need to update all the instructions that's prerequisites contain the current instruction for (instruction in currInstruction.prerequisitesOf) { // all prerequisites have been finished and not already added to available if (instruction.prerequisites.all { instructionDoneTime[it.id] != null } && !availableInstructions.contains(instruction)) { availableInstructions.add(instruction) } } } val maxFinishTime = workersFinish.max()!! for (i in 0 until workerCount) workersFinish[i] = maxFinishTime return workersFinish.max().toString() } data class Instruction(val id: Char) { val prerequisites: MutableList<Instruction> = mutableListOf() val prerequisitesOf: MutableList<Instruction> = mutableListOf() val takesTime = id - 'A' + 61 } }
0
Kotlin
0
0
bf34b93aff7f2561f25fa6bd60b7c2c2356b16ed
5,980
adventOfCode2018
MIT License
src/day3.kt
miiila
725,271,087
false
{"Kotlin": 77215}
import java.io.File import kotlin.system.exitProcess private const val DAY = 3 fun main() { if (!File("./day${DAY}_input").exists()) { downloadInput(DAY) println("Input downloaded") exitProcess(0) } val transformer = { x: String -> x } val input = loadInput(DAY, false, transformer) println(solvePart1(input)) println(solvePart2(input)) } // Part 1 private fun solvePart1(input: List<String>): Int { var res = 0 for ((row, line) in input.withIndex()) { var col = 0 while (col < line.length) { val c = line[col] if (c.isDigit()) { val num = line.slice(col..<line.length).takeWhile { it.isDigit() } if (isSymbolAround(row, col, num.length, input)) { res += num.toInt() } col += num.length } else { col++ } } } return res } fun isSymbolAround(row: Int, col: Int, colOffset: Int, grid: List<String>, symbol: Char? = null): Boolean { for (dr in -1..1) { if (row + dr < 0 || row + dr >= grid.count()) { continue } for (dc in -1..colOffset) { if (col + dc < 0 || col + dc >= grid[row + dr].length) { continue } val s = grid[row + dr][col + dc] if ((symbol != null && s == symbol) || s != '.' && !s.isDigit()) { return true } } } return false } // Part 2 private fun solvePart2(input: List<String>): Int { val gears = mutableMapOf<Pair<Int, Int>, List<Int>>() for ((row, line) in input.withIndex()) { var col = 0 while (col < line.length) { val c = line[col] if (c.isDigit()) { val num = line.slice(col..<line.length).takeWhile { it.isDigit() } val gear = getGearAround(row, col, num.length, input) if (gear != null) { gears[gear] = gears[gear]?.plus(num.toInt()) ?: listOf(num.toInt()) } col += num.length } else { col++ } } } return gears.filter { it.toPair().second.count() > 1 }.map { it.value.reduce(Int::times) }.sum() } fun getGearAround(row: Int, col: Int, colOffset: Int, grid: List<String>): Pair<Int, Int>? { for (dr in -1..1) { if (row + dr < 0 || row + dr >= grid.count()) { continue } for (dc in -1..colOffset) { if (col + dc < 0 || col + dc >= grid[row + dr].length) { continue } val s = grid[row + dr][col + dc] if (s == '*') { return Pair(row + dr, col + dc) } } } return null }
0
Kotlin
0
1
1cd45c2ce0822e60982c2c71cb4d8c75e37364a1
2,836
aoc2023
MIT License
src/day13/Day13.kt
pocmo
433,766,909
false
{"Kotlin": 134886}
package day13 import java.io.File data class Point( val x: Int, val y: Int ) data class Paper( val points: Map<Point, Boolean> ) { fun fold(instruction: Instruction): Paper { return when (instruction) { is Instruction.FoldUp -> foldUp(instruction.y) is Instruction.FoldLeft -> foldLeft(instruction.x) } } fun fold(instructions: List<Instruction>): Paper { var paper = this for (instruction in instructions) { paper = paper.fold(instruction) } return paper } fun foldLeft(x: Int): Paper { val newPoints = mutableMapOf<Point, Boolean>() points.keys.forEach { point -> if (point.x < x) { newPoints[point] = true } else if (point.x > x) { val steps = point.x - x val mirroredPoint = Point( x - steps, point.y ) newPoints[mirroredPoint] = true } else { throw IllegalStateException("Point on fold line") } } return Paper(newPoints) } fun foldUp(y: Int): Paper { val newPoints = mutableMapOf<Point, Boolean>() points.keys.forEach { point -> if (point.y < y) { newPoints[point] = true } else if (point.y > y) { val steps = point.y - y val mirroredPoint = Point( point.x, y - steps ) newPoints[mirroredPoint] = true } else { throw IllegalStateException("Point on fold line") } } return Paper(newPoints) } fun countPoints(): Int { return points.size } fun isMarked(x: Int, y: Int): Boolean { return isMarked(Point(x, y)) } fun isMarked(point: Point): Boolean { return points[point] == true } fun dump(): String { val size = size() return buildString { for (y in 0..size.y) { for (x in 0..size.x) { if (isMarked(x, y)) { append('#') } else { append('.') } } appendLine() } }.trim() } fun size(): Point { var x = 0 var y = 0 points.keys.forEach { point -> x = if (point.x > x) point.x else x y = if (point.y > y) point.y else y } return Point(x, y) } } sealed interface Instruction { data class FoldUp( val y: Int ) : Instruction data class FoldLeft( val x: Int ) : Instruction } fun readFromFile(fileName: String): Pair<Paper, List<Instruction>> { return readFromString(File(fileName) .readText()) } fun parsePoint(line: String): Point { val (x, y) = line.split(",") return Point(x.toInt(), y.toInt()) } fun parseInstruction(line: String): Instruction { return when { line.startsWith("fold along x=") -> Instruction.FoldLeft(line.split("=")[1].toInt()) line.startsWith("fold along y=") -> Instruction.FoldUp(line.split("=")[1].toInt()) else -> throw IllegalStateException("Unknown instruction: $line") } } fun readFromString(input: String): Pair<Paper, List<Instruction>> { var parsingPoints = true val points = mutableMapOf<Point, Boolean>() val instructions = mutableListOf<Instruction>() input.lines().forEach { line -> when { line.isEmpty() -> parsingPoints = false parsingPoints -> points[parsePoint(line)] = true else -> instructions.add(parseInstruction(line)) } } return Pair(Paper(points), instructions) } fun part1() { val (paper, instructions) = readFromFile("day13.txt") val instruction = instructions[0] val foldedPaper = paper.fold(instruction) val points = foldedPaper.countPoints() println("Points before fold: ${paper.countPoints()}") println("Points after fold: $points") } fun part2() { val (paper, instructions) = readFromFile("day13.txt") val foldedPaper = paper.fold(instructions) println(foldedPaper.dump()) } fun main() { part2() }
0
Kotlin
1
2
73bbb6a41229e5863e52388a19108041339a864e
4,372
AdventOfCode2021
Apache License 2.0
src/day10/Day10.kt
gautemo
317,316,447
false
null
package day10 import shared.getLinesAsInt fun adaptersDifferenceCalculation(adapters: List<Int>): Int{ val joltDiff = sortedWithChargerAndDevice(adapters).zipWithNext().map { it.second - it.first } return joltDiff.count { it == 1 } * joltDiff.count { it == 3 } } fun adaptersCombination(adapters: List<Int>): Long{ return comb(sortedWithChargerAndDevice(adapters)) } val cache = mutableMapOf<String, Long>() fun comb(adapters: List<Int>): Long{ return cache.getOrElse(adapters.joinToString()){ var combinations = 0L if(adapters.size > 2) { combinations += comb(adapters.subList(1, adapters.size)) }else{ combinations++ } if(adapters.size > 2 && adapters[2] - adapters[0] <= 3){ combinations += comb(adapters.subList(2, adapters.size)) } if(adapters.size > 3 && adapters[3] - adapters[0] <= 3){ combinations += comb(adapters.subList(3, adapters.size)) } cache[adapters.joinToString()] = combinations combinations } } fun sortedWithChargerAndDevice(adapters: List<Int>): List<Int>{ return listOf(0) + adapters.sorted() + listOf(adapters.max()!! + 3) } fun main(){ val adapters = getLinesAsInt("day10.txt") val result = adaptersDifferenceCalculation(adapters) println(result) val combinations = adaptersCombination(adapters) println(combinations) }
0
Kotlin
0
0
ce25b091366574a130fa3d6abd3e538a414cdc3b
1,424
AdventOfCode2020
MIT License
src/main/kotlin/days/day1/Day1.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day1 import days.Day class Day1 : Day(false) { override fun partOne() = readInput().map { it.filter (Char::isDigit) }.sumOf { (it.first() + "" + it.last()).toInt() } override fun partTwo(): Any { val inputDigits = readInput().map { convertStringWithSpelledOutDigitsToDigits(it) } val reversedInputDigits = readInput().map { convertStringWithSpelledOutDigitsToDigitsBackwards(it) } val numbers = inputDigits.map { it.filter (Char::isDigit) } val reversedNumbers = reversedInputDigits.map { it.filter (Char::isDigit) } val firstDigitString = numbers.map { it.first().toString() } val firstDigitFromBackString = reversedNumbers.map { it.last().toString() } return firstDigitString.zip(firstDigitFromBackString).sumOf { (it.first + it.second).toInt() } } private fun convertStringWithSpelledOutDigitsToDigits(input: String): String { var sequence = "" for (char in input) { val sequenceBuilder = StringBuilder(sequence) sequenceBuilder.append(char) sequence = sequenceBuilder.toString() val oldSequence = sequence sequence = convertStringWithSpelledOutDigitsNoOrder(sequence) if (oldSequence != sequence) { return sequence } } return sequence } private fun convertStringWithSpelledOutDigitsToDigitsBackwards(input: String): String { var sequence = "" for (i in input.length - 1 downTo 0) { val char = input[i] val sequenceBuilder = StringBuilder() sequenceBuilder.append(char) sequenceBuilder.append(sequence) sequence = sequenceBuilder.toString() val oldSequence = sequence sequence = convertStringWithSpelledOutDigitsNoOrder(sequence) if (oldSequence != sequence) { return sequence } } return sequence } private fun convertStringWithSpelledOutDigitsNoOrder(input: String): String { return input.replace("one", "1") .replace("two", "2") .replace("three", "3") .replace("four", "4") .replace("five", "5") .replace("six", "6") .replace("seven", "7") .replace("eight", "8") .replace("nine", "9") .replace("zero", "0") } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
2,446
advent-of-code_2023
The Unlicense
src/test/kotlin/leetcode/mock/MockInterview5.kt
Magdi
390,731,717
false
null
package leetcode.mock import org.junit.Assert import org.junit.Test class MockInterview5 { @Test fun `test case 1`() { // Assert.assertEquals(1, Solution().expressiveWords("heeellooo", arrayOf("hello", "hi", "helo"))) Assert.assertEquals(0, Solution().expressiveWords("lee", arrayOf("le"))) } } class Solution { fun judgeCircle(moves: String): Boolean { var x = 0 var y = 0 moves.forEach { m -> when (m) { 'U' -> y - 1 'D' -> y + 1 'L' -> x - 1 'R' -> y + 1 } } return x == 0 && y == 0 } fun expressiveWords(s: String, words: Array<String>): Int { var ans = 0 val main = decode(s) words.forEach { val query = decode(it) if (main.size == query.size) { var found = true for (i in main.indices) { if (main[i].first != query[i].first) { found = false } if (main[i].second < 3 && main[i].second != query[i].second) { found = false } if (query[i].second > main[i].second) { found = false } } if (found) ans++ } } return ans } private fun decode(s: String): List<Pair<Char, Int>> { val result = ArrayList<Pair<Char, Int>>() var cnt = 1 for (i in 0..s.lastIndex - 1) { if (s[i] != s[i + 1]) { result.add(Pair(s[i], cnt)) cnt = 1 } else { cnt++ } } result.add(Pair(s.last(), cnt)) return result } fun removeStones(stones: Array<IntArray>): Int { val stones = stones.map { (x, y) -> Point(x, y) } val f = WeightedUF(stones.size) for (i in 0..stones.lastIndex) { for (j in i + 1..stones.lastIndex) { if (stones[i].x == stones[j].x || stones[i].y == stones[j].y) { f.union(i, j) } } } return stones.size - f.components } class WeightedUF(val n: Int) { val parent: Array<Int> val weight: Array<Int> var components: Int init { parent = Array(n) { i -> i } weight = Array(n) { i -> 1 } components = n } fun find(p: Int): Int { var pMutable = p while (parent[pMutable] != pMutable) { pMutable = parent[pMutable] } return pMutable } fun union(p: Int, q: Int) { val pRoot = find(p) val qRoot = find(q) if (pRoot != qRoot) { if (weight[pRoot] < weight[qRoot]) { parent[qRoot] = pRoot weight[pRoot] += weight[qRoot] } else { parent[pRoot] = qRoot weight[qRoot] += weight[pRoot] } components-- } } } data class Point(val x: Int, val y: Int) }
0
Kotlin
0
0
63bc711dc8756735f210a71454144dd033e8927d
3,282
ProblemSolving
Apache License 2.0
src/main/kotlin/com/nibado/projects/advent/y2018/Day10.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2018 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Point import com.nibado.projects.advent.Rectangle import com.nibado.projects.advent.resourceLines import kotlin.math.max import kotlin.math.min object Day10 : Day { private val input = resourceLines(2018, 10).map(::parse) private val solution: Pair<String, Int> by lazy { solve() } private fun parse(line: String) = line.split("[^0-9-]+".toRegex()) .filterNot { it.trim().isEmpty() }.map { it.toInt() } .let { (x, y, dx, dy) -> Star(Point(x, y), Point(dx, dy)) } private fun toString(stars: List<Star>): String { val points = stars.map { it.loc }.toSet() val rect = Rectangle.containing(points) val builder = StringBuilder() for (y in rect.left.y..rect.right.y) { for (x in rect.left.x..rect.right.x) { builder.append(if (points.contains(Point(x, y))) { '#' } else { '.' }) } builder.append('\n') } return builder.toString() } private fun area(stars: List<Star>) = stars .fold(listOf(Int.MAX_VALUE, Int.MAX_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)) { (minX, minY, maxX, maxY), s -> listOf(min(minX, s.loc.x), min(minY, s.loc.y), max(maxX, s.loc.x), max(maxY, s.loc.y)) } .let { (minX, minY, maxX, maxY) -> (maxX - minX).toLong() * (maxY - minY).toLong() } private fun solve(): Pair<String, Int> { var stars = input var second = 0 var area = Long.MAX_VALUE while (true) { val next = stars.map { it.copy(loc = it.loc + it.velocity) } val nextArea = area(next) if (area < nextArea) { break } second++ stars = next area = nextArea } return toString(stars) to second } override fun part1() = Day10Ocr.ocr(solution.first) override fun part2() = solution.second data class Star(val loc: Point, val velocity: Point) }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
2,170
adventofcode
MIT License
src/day7/Day07.kt
behnawwm
572,034,416
false
{"Kotlin": 11987}
package day7 import readInput fun main() { val fileLines = readInput("day07-test", "day7") // val fileLines = readInput("day07", "day7") fun updateDirsCurrentDir(newDirName: String, storage: Dir) { // if (dirName in currentDir.dirs.map { it.relativePath }) // return val current = storage.currentDir current?.dirs?.removeIf { it.relativePath == current.relativePath && it.parentDir == current.parentDir } current?.dirs?.add(newDir) } fun updateFilesCurrentDir(newFile: File, storage: Dir) { // if (dirName in currentDir.dirs.map { it.relativePath }) // return val current = storage.currentDir current?.files?.removeIf { it.name == current.relativePath } current?.files?.add(newFile) } fun part1(fileLines: List<String>): Int { val storage = Dir("/", null) fileLines.forEach { println("*****") when { it.startsWith('$') -> { val commandLine = it.takeLast(it.length - 2).split(" ") println(commandLine) when (commandLine[0]) { "cd" -> { when (commandLine[1]) { ".." -> { storage.currentDir = storage.parentDir } "/" -> { storage.currentDir = storage.parentDir } else -> { storage.currentDir = storage.currentDir?.dirs?.find { it.relativePath == commandLine[1] } // currentDir.dirs.find { // it.relativePath == commandLine[1] // }.let { // currentDir = it!! // } } } } "ls" -> { } } } else -> { val data = it.split(" ") println(data) when (data[0]) { "dir" -> { updateDirsCurrentDir(data[1],storage) // currentDir.dirs.add( // Dir(data[1], currentDir) // ) } else -> { currentDir.files.add( File(data[1], data[0].toLong()) ) } } } } println(storage) } print(storage) var count = 0 return count } println( part1(fileLines) ) } data class State( val storage: Dir, val pointer: Dir ) data class Dir( val relativePath: String, val parentDir: Dir?, var currentDir: Dir? = null, val dirs: MutableList<Dir> = mutableListOf(), val files: MutableList<File> = mutableListOf() ) data class File( val name: String, val size: Long )
0
Kotlin
0
2
9d1fee54837cfae38c965cc1a5b267d7d15f4b3a
3,445
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/_2022/Day5.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2022 import PATTERN_LINE_SEPARATOR import REGEX_LINE_SEPARATOR import aoc import java.util.regex.Pattern private val EMPTY_LINE_REGEX = Pattern.compile("^${PATTERN_LINE_SEPARATOR}", Pattern.MULTILINE) private val STACK_REGEX = Pattern.compile("\\[(\\w)]") private val INSTRUCTION_REGEX = Pattern.compile("move (?<amount>\\d+) from (?<from>\\d+) to (?<to>\\d+)") fun main() { aoc(2022, 5) { aocRun { input -> process(input, Instruction::moveEach) } aocRun { input -> process(input, Instruction::moveAll) } } } private fun process(input: String, moveFunction: Instruction.(List<ArrayDeque<Char>>) -> Unit): String { val (stacksString, instructionsString) = input.split(EMPTY_LINE_REGEX).map { it.trimEnd() } val stacks = parseStacks(stacksString) val instructions = parseInstructions(instructionsString) instructions.forEach { moveFunction(it, stacks) } return stacks.joinToString(separator = "") { it.lastOrNull()?.toString() ?: "" } } private fun parseStacks(stacksString: String): List<ArrayDeque<Char>> { val stacks = buildList<ArrayDeque<Char>> { repeat(stacksString.takeLast(1).toInt()) { add(ArrayDeque()) } } stacksString.split(REGEX_LINE_SEPARATOR).reversed().drop(1).forEach { line -> STACK_REGEX.matcher(line).results().filter { it.group(1) != null }.forEach { match -> val char = match.group(1)[0] val stackIndex = (match.start(1) - 1) / 4 stacks[stackIndex].add(char) } } return stacks } private fun parseInstructions(instructionsString: String): List<Instruction> = buildList { INSTRUCTION_REGEX.matcher(instructionsString).run { while (find()) { add(Instruction(group("amount").toInt(), group("from").toInt() - 1, group("to").toInt() - 1)) } } } private data class Instruction(private val amount: Int, private val stackFrom: Int, private val stackTo: Int) { fun moveEach(stacks: List<ArrayDeque<Char>>) { val fromStack = stacks[stackFrom] val toStack = stacks[stackTo] repeat(amount) { toStack.add(fromStack.removeLast()) } } fun moveAll(stacks: List<ArrayDeque<Char>>) { val fromStack = stacks[stackFrom] val toStack = stacks[stackTo] val toMove = ArrayDeque<Char>() repeat(amount) { toMove.add(fromStack.removeLast()) } repeat(amount) { toStack.add(toMove.removeLast()) } } }
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
2,490
AdventOfCode
Creative Commons Zero v1.0 Universal
src/AoC16.kt
Pi143
317,631,443
false
null
import java.io.File fun main() { println("Starting Day 16 A Test 1") calculateDay16PartA( "Input/2020_Day16_Rules_Test1", "Input/2020_Day16_myTicket_Test1", "Input/2020_Day16_nearbyTickets_Test1" ) println("Starting Day 16 A Real") calculateDay16PartA("Input/2020_Day16_Rules", "Input/2020_Day16_myTicket", "Input/2020_Day16_nearbyTickets") println("Starting Day 16 B Test 1") calculateDay16PartB( "Input/2020_Day16_Rules_Test1", "Input/2020_Day16_myTicket_Test1", "Input/2020_Day16_nearbyTickets_Test1" ) println("Starting Day 16 B Real") calculateDay16PartB("Input/2020_Day16_Rules", "Input/2020_Day16_myTicket", "Input/2020_Day16_nearbyTickets") } fun calculateDay16PartA(ruleFile: String, myTicketFile: String, nearbyTicketFiles: String): Int { val rules = readDay16Rules(ruleFile) val myTicket = readDay16Ticket(myTicketFile) val nearbyTickets = readDay16Ticket(nearbyTicketFiles) var errorRate = 0 for (ticket in nearbyTickets) { for (number in ticket) { var numberValid = false for (rule in rules) { for (range in rule.rangeList) { if (number in range) { numberValid = true } } } if (!numberValid) { errorRate += number } } } println("The errorRate ist $errorRate") return errorRate } fun calculateDay16PartB(ruleFile: String, myTicketFile: String, nearbyTicketFiles: String): Int { val rules = readDay16Rules(ruleFile) val myTicket = readDay16Ticket(myTicketFile) val nearbyTickets = readDay16Ticket(nearbyTicketFiles) val validTickets = nearbyTickets.toMutableList() var ruleValidity: MutableMap<String, ArrayList<Int>> = mutableMapOf() for (ticket in nearbyTickets) { for (number in ticket) { var numberValid = false for (rule in rules) { for (range in rule.rangeList) { if (number in range) { numberValid = true } } } if (!numberValid) { validTickets.remove(ticket) } } } val amountTicketFields = myTicket[0].size for (rule in rules) { for (i in 0 until amountTicketFields) { var validForField = true for (ticket in validTickets) { var inAnyRange = false for (range in rule.rangeList) { if (ticket[i] in range) { inAnyRange = true } } if (!inAnyRange) { validForField = false } } if (validForField) { if (ruleValidity.containsKey(rule.name)) { ruleValidity[rule.name] = (arrayListOf(i) + ruleValidity[rule.name]!!) as ArrayList<Int> } else { ruleValidity[rule.name] = arrayListOf(i) } } } } while (ruleValidity.isNotEmpty()) { var foundRoule = -1 var foundKey: String = "" for (validity in ruleValidity) { if (validity.value.size == 1) { println("") print("${validity.key} is valid for: ") for (field in validity.value) { print("$field ") foundRoule = field foundKey = validity.key } } } ruleValidity.remove(foundKey) for (val2 in ruleValidity.keys) { if (foundRoule != -1) { ruleValidity[val2] = (ruleValidity[val2]!! - arrayListOf(foundRoule)) as ArrayList<Int> } } } return -1 } fun readDay16Rules(input: String): ArrayList<Rule> { val ruleList = arrayListOf<Rule>() File(localdir + input).forEachLine { val split = it.split(": ") val name = split[0] val params = split[1] val paramSplit = params.split(" or ") val rangeList: ArrayList<IntRange> = arrayListOf() for (param in paramSplit) { val rangeSplit = param.split("-") val intRange = IntRange(rangeSplit[0].toInt(), rangeSplit[1].toInt()) rangeList.add(intRange) } val rule = Rule(name, rangeList) ruleList.add(rule) } return ruleList } fun readDay16Ticket(input: String): ArrayList<ArrayList<Int>> { val ticketList = arrayListOf<ArrayList<Int>>() File(localdir + input).forEachLine { val ticket = arrayListOf<Int>() for (number in it.split(",")) { ticket.add(number.toInt()) } ticketList.add(ticket) } return ticketList } class Rule(name: String, rangeList: ArrayList<IntRange>) { val name = name val rangeList = rangeList }
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
5,044
AdventOfCode2020
MIT License
src/test/kotlin/days/y2022/Day05Test.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2052 import days.Day import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.Is.`is` import org.junit.jupiter.api.Test class Day05 : Day(2022, 5) { override fun partOne(input: String): Any { val crates = Crates.from(input) instructions(input).forEach { instruction -> crates.moveSingly(instruction) } return crates.message() } override fun partTwo(input: String): Any { val crates = Crates.from(input) instructions(input).forEach { instruction -> crates.moveMany(instruction) } return crates.message() } fun instructions(input: String) = input.split("\n\n").last().lines().map { Instruction.from(it) } class Crates(val positions: MutableList<MutableList<String>>) { fun moveSingly(input: Instruction) { var toMove = input.quantity while (toMove > 0) { val toMoveIndex = positions[input.fromCol()].lastNonBlankIndex() val toLandIndex = positions[input.toCol()].lastNonBlankIndex() + 1 val crate = positions[input.fromCol()][toMoveIndex] positions[input.fromCol()][toMoveIndex] = "" positions[input.toCol()][toLandIndex] = crate toMove-- } } fun moveMany(input: Instruction) { val fromCol = input.fromCol() var toMoveIndex = positions[fromCol].lastNonBlankIndex() val toCol = input.toCol() var toLandIndex = positions[toCol].lastNonBlankIndex() + input.quantity var toMove = input.quantity while (toMove > 0) { val crate = positions[fromCol][toMoveIndex] positions[fromCol][toMoveIndex] = "" positions[toCol][toLandIndex] = crate toMove-- toMoveIndex-- toLandIndex-- } } fun message() = positions.joinToString("") { it[it.lastNonBlankIndex()] } companion object { fun from(input: String): Crates { val (headerInput) = input.split("\n\n") val cratesInput = headerInput.lines().map { it.chunked(4) } val reversed = cratesInput.reversed().drop(1) val nRows = reversed.first().size val positions: MutableList<MutableList<String>> = MutableList(nRows) { MutableList(999) { "" } } reversed.forEachIndexed { lineIndex, line -> line.forEachIndexed { rowIndex, s -> if (s.trim().isNotEmpty()) { positions[rowIndex][lineIndex] = s.trim() .replace("[", "").replace("]", "") } } } return Crates(positions) } } } data class Instruction(val quantity: Int, val from: Int, val to: Int) { fun fromCol(): Int = from - 1 fun toCol(): Int = to - 1 companion object { fun from(input: String): Instruction { val (quantity, from, to) = input.split(" ").mapNotNull { it.toIntOrNull() } return Instruction(quantity, from, to) } } } } private fun List<String>.lastNonBlankIndex(): Int { var index = -1 for (i in this.indices) { if (this[i].trim().isEmpty()) { return index } else { index = i } } error("no blank") } class Day05Test { 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() @Test fun parsesInput() { val crates = Day05.Crates.from(exampleInput) assertThat(crates.positions[0][0], `is`("Z")) assertThat(crates.positions[0][1], `is`("N")) assertThat(crates.positions[0][2], `is`("")) assertThat(crates.positions[1][0], `is`("M")) assertThat(crates.positions[1][1], `is`("C")) assertThat(crates.positions[1][2], `is`("D")) assertThat(crates.positions[1][3], `is`("")) assertThat(crates.positions[2][1], `is`("")) } @Test fun moveCrates() { val crates = Day05.Crates.from(exampleInput) assertThat(crates.positions[1][2], `is`("D")) assertThat(crates.positions[0][2], `is`("")) crates.moveSingly(Day05.Instruction(1, 2, 1)) assertThat(crates.positions[1][2], `is`("")) assertThat(crates.positions[0][2], `is`("D")) crates.moveSingly(Day05.Instruction(3, 1, 3)) assertThat(crates.positions[2][0], `is`("P")) assertThat(crates.positions[2][1], `is`("D")) assertThat(crates.positions[2][2], `is`("N")) assertThat(crates.positions[2][3], `is`("Z")) assertThat(crates.positions[2][4], `is`("")) crates.moveSingly(Day05.Instruction(2, 2, 1)) assertThat(crates.positions[0][0], `is`("C")) assertThat(crates.positions[0][1], `is`("M")) assertThat(crates.positions[1][0], `is`("")) } @Test fun testExampleOne() { assertThat( Day05().partOne( exampleInput ), `is`("CMZ") ) } @Test fun testPartOne() { assertThat(Day05().partOne(), `is`("QPJPLMNNR")) } @Test fun moveCrates2() { val crates = Day05.Crates.from(exampleInput) assertThat(crates.positions[1][2], `is`("D")) assertThat(crates.positions[0][2], `is`("")) crates.moveMany(Day05.Instruction(1, 2, 1)) assertThat(crates.positions[1][2], `is`("")) assertThat(crates.positions[0][2], `is`("D")) crates.moveMany(Day05.Instruction(3, 1, 3)) assertThat(crates.positions[2][4], `is`("")) assertThat(crates.positions[2][3], `is`("D")) assertThat(crates.positions[2][0], `is`("P")) assertThat(crates.positions[2][2], `is`("N")) assertThat(crates.positions[2][1], `is`("Z")) } @Test fun testExampleTwo() { assertThat( Day05().partTwo( """ [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() ), `is`("MCD") ) } @Test fun testPartTwo() { assertThat(Day05().partTwo(), `is`("BQDNWJPVJ")) } }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
6,844
AdventOfCode
Creative Commons Zero v1.0 Universal
ceria/16/src/main/kotlin/Solution.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File; var versions = mutableListOf<Int>() var packets = mutableListOf<Pair<Int, List<Long>>>() fun main(args : Array<String>) { val input = File(args.first()).readLines().first().trim() println("Solution 1: ${solution1(convertHexToBinary(input))}") // println("Solution 2: ${solution2(convertHexToBinary(input))}") } private fun solution1(binary: String) :Int { parse(binary, mutableListOf<Long>()) return versions.sum() } private fun solution2(binary: String) :Long { parse(binary, mutableListOf<Long>()) var nextResult = 0L for (x in packets.indices) { println("$x -- ${packets.get(x)}") var packet = packets.get(x) } return nextResult } var evaluateImmidiately = setOf<Int>(0, 1) private fun applyOperators(p :Pair<Int, List<Long>>) :Long { when (p.first) { 0 -> return p.second.sum() 1 -> return p.second.reduce{ acc, i -> i * acc } 2 -> return p.second.minOf{ it } 3 -> return p.second.maxOf{ it } 5 -> if (p.second.first() > p.second.last()) { return 1L } else { return 0L } 6 -> if (p.second.first() < p.second.last()) { return 1L } else { return 0L } 7 -> if (p.second.first() == p.second.last()) { return 1L } else { return 0L } } return 0L } var position = 0 private fun parse(binary: String, vals: MutableList<Long>) :Pair<Int, Long> { var ptr = 0 var decimal = -1L while (ptr != binary.length - 1 ) { var version = binary.slice(ptr..ptr + 2).toInt(2) versions.add(version) ptr += 3 var type = binary.slice(ptr..ptr + 2).toInt(2) ptr += 3 if (type == 4) { // literal var literal = StringBuilder() var keepGoing = binary.get(ptr).digitToInt() while (keepGoing == 1) { literal.append(binary.slice(ptr + 1..ptr + 4)) ptr += 5 keepGoing = binary.get(ptr).digitToInt() } // get the last bit since keepGoing is now a 0 literal.append(binary.slice(ptr + 1..ptr + 4) ) ptr += 5 decimal = literal.toString().toLong(2) vals.add(decimal) } else { // operator var lengthTypeId = binary.get(ptr) if (lengthTypeId.equals('0')) { var values = mutableListOf<Long>() // the next 15 bits are a number that represents the total length in bits of the sub-packets contained by this packet var packetLength = binary.slice(ptr + 1..ptr + 15).toInt(2) ptr += 16 var newBinary = binary.slice(ptr..ptr + (packetLength - 1)) ptr += packetLength parse(newBinary, values) // println("ADDING $position" + Pair<Int, List<Long>>(type, values) ) position++ // if (type in evaluateImmidiately) { // var evaluated = applyOperators(Pair<Int, List<Long>>(type, values)) // values = mutableListOf<Long>(evaluated) // } packets.add( Pair<Int, List<Long>>(type, values) ) } else { // the next 11 bits are a number that represents the number of sub-packets immediately contained by this packet. var values = mutableListOf<Long>() var packetCount = binary.slice(ptr + 1..ptr + 11).toInt(2) ptr += 12 for (x in 1..packetCount - 1) { var newBinary = binary.slice(ptr..(binary.length - 1)) var result = parse(newBinary, values) ptr += result.first } // println("ADDING $position" + Pair<Int, List<Long>>(type, values) ) position++ // if (type in evaluateImmidiately) { // var evaluated = applyOperators(Pair<Int, List<Long>>(type, values)) // values = mutableListOf<Long>(evaluated) // } packets.add( Pair<Int, List<Long>>(type, values) ) } } // are we left with just 0's? if (binary.slice(ptr..(binary.length -1)).filter{ it == '1' }.length == 0 ) { // no 1's in the remaining binary string, so move the pointer to the end ptr = binary.length - 1 } } return Pair<Int, Long>(ptr, decimal) } private fun convertHexToBinary(hex: String) :String { var i = 0 val binary = StringBuilder() while (i < hex.length) { when(hex[i]) { '0' -> binary.append("0000") '1' -> binary.append("0001") '2' -> binary.append("0010") '3' -> binary.append("0011") '4' -> binary.append("0100") '5' -> binary.append("0101") '6' -> binary.append("0110") '7' -> binary.append("0111") '8' -> binary.append("1000") '9' -> binary.append("1001") 'A', 'a' -> binary.append("1010") 'B', 'b' -> binary.append("1011") 'C', 'c' -> binary.append("1100") 'D', 'd' -> binary.append("1101") 'E', 'e' -> binary.append("1110") 'F', 'f' -> binary.append("1111") } i++ } return binary.toString() }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
5,411
advent-of-code-2021
MIT License
2022/src/main/kotlin/day20.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.badInput import utils.mapItems fun main() { Day20.run(skipTest = true) } class Node(val value: Int, var head: Boolean = false) { lateinit var prev: Node lateinit var next: Node } object Day20 : Solution<List<Int>>() { override val name = "day20" override val parser = Parser.lines.mapItems { it.toInt() } private fun move(node: Node, amount: Int) { if (amount == 0) { return // nothing to do } var n = node if (amount > 0) { repeat(amount) { n = n.next } } else { badInput() // repeat(amount.absoluteValue + 1) { // n = n.prev // } } if (n == node) { return // nothing to do } if (node.head) { node.next.head = true node.head = false } else if (n.head) { n.head = false node.head = true } // remove node from orig place node.prev.next = node.next node.next.prev = node.prev // insert node after n val oldNext = n.next n.next = node oldNext.prev = node node.next = oldNext node.prev = n } private fun toArray(node: Node, sz: Int): IntArray { // find head var n = node while (!n.head) { n = n.next } val arr = IntArray(sz) { 0 } repeat(sz) { i -> arr[i] = n.value n = n.next } return arr } override fun part1(input: List<Int>): Any? { val nodes = Array<Node?>(input.size) { null } val head = Node(input.first(), true) nodes[0] = head var prev = head for (i in 1 until input.size) { prev.next = Node(input[i]) nodes[i] = prev.next prev.next.prev = prev prev = prev.next } // prev is now tail prev.next = head head.prev = prev nodes.filterNotNull().also { if (it.size != input.size) badInput() }.forEachIndexed { i, node -> // move node ahead or prev by X steps var move = node.value while (move <= 0) { move += input.size } if (node.value < 0) { move -= 1 } println("$i: move ${node.value} / $move") println("before: ${toArray(node, input.size).mapIndexed { index, i -> "[${index.toString().padStart(4)}]${i.toString().padStart(6)}" }.joinToString(" ")}") move(node, move) println("after : ${toArray(node, input.size).mapIndexed { index, i -> "[${index.toString().padStart(4)}]${i.toString().padStart(6)}" }.joinToString(" ")}") println() } val arr = toArray(head, input.size) // println("yarr") // find head var n = head var sum = 0 while (n.value != 0) { n = n.next } repeat (3) { repeat(1000) { n = n.next } sum += n.value } return sum } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,765
aoc_kotlin
MIT License
sort/merge_sort/kotlin/merge_sort.kt
ZoranPandovski
93,438,176
false
{"Jupyter Notebook": 21909905, "C++": 1692994, "Python": 1158220, "Java": 806066, "C": 560110, "JavaScript": 305918, "Go": 145277, "C#": 117882, "PHP": 85458, "Kotlin": 72238, "Rust": 53852, "Ruby": 43243, "MATLAB": 34672, "Swift": 31023, "Processing": 22089, "HTML": 18961, "Haskell": 14298, "Dart": 11842, "CSS": 10509, "Scala": 10277, "Haxe": 9750, "PureScript": 9122, "M": 9006, "Perl": 8685, "Prolog": 8165, "Shell": 7901, "Erlang": 7483, "Assembly": 7284, "R": 6832, "Lua": 6392, "LOLCODE": 6379, "VBScript": 6283, "Clojure": 5598, "Elixir": 5495, "OCaml": 3989, "Crystal": 3902, "Common Lisp": 3839, "Julia": 3567, "F#": 3376, "TypeScript": 3268, "Nim": 3201, "Brainfuck": 2466, "Visual Basic .NET": 2033, "ABAP": 1735, "Pascal": 1554, "Groovy": 976, "COBOL": 887, "Mathematica": 799, "Racket": 755, "PowerShell": 708, "Ada": 490, "CMake": 393, "Classic ASP": 339, "QMake": 199, "Makefile": 111}
fun mergeSortIA(array: IntArray) : IntArray { val arrayCopy = array.copyOf() val arrayCopy2 = array.copyOf() sortSectionIA(arrayCopy, arrayCopy2, 0, arrayCopy.size) return arrayCopy2 } /** * Sorts the specified section of the array. * * @param workA Should contain identical values as workB in the specified range. * The final values in the specified range are destroyed (actually they are made * of two adjacent sorted ranged). * @param workB Should contain identical values as workA in the specified range. * The final values in the specified range are the sorted values in that range. */ internal inline fun mergeHalvesIA(workA: IntArray, workB: IntArray, start: Int, mid: Int, exclusiveEnd: Int) { var p1 = start var p2 = mid for (i in start until exclusiveEnd) { if (p1 < mid && (p2 == exclusiveEnd || workA[p1] <= workA[p2])) { workB[i] = workA[p1] p1++ } else { workB[i] = workA[p2] p2++ } } } internal fun sortSectionIA(input: IntArray, output: IntArray, start: Int, exclusiveEnd: Int) : Unit { if (exclusiveEnd - start <= 1) return val mid = (start + exclusiveEnd) / 2 sortSectionIA(output, input, start, mid) sortSectionIA(output, input, mid, exclusiveEnd) mergeHalvesIA(input, output, start, mid, exclusiveEnd) }
62
Jupyter Notebook
1,994
1,298
62a1a543b8f3e2ca1280bf50fc8a95896ef69d63
1,626
al-go-rithms
Creative Commons Zero v1.0 Universal
src/main/kotlin/adventofcode/year2022/Day21MonkeyMath.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2022 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.String.containsOnlyDigits import adventofcode.year2022.Day21MonkeyMath.Companion.Operation.DIV import adventofcode.year2022.Day21MonkeyMath.Companion.Operation.MINUS import adventofcode.year2022.Day21MonkeyMath.Companion.Operation.PLUS import adventofcode.year2022.Day21MonkeyMath.Companion.Operation.TIMES class Day21MonkeyMath(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val monkeys by lazy { input .lines() .map { it.split(": ") } .associate { (name, expression) -> name to Monkey(expression) } .also { monkeys -> monkeys .values .filterIsInstance<MathMonkey>() .forEach { monkey -> monkey.leftMonkey = monkeys[monkey.leftMonkeyName]!! monkey.rightMonkey = monkeys[monkey.rightMonkeyName]!! } } } override fun partOne() = monkeys["root"]!!.yell() companion object { private enum class Operation(val operation: String) { PLUS("+"), MINUS("-"), TIMES("*"), DIV("/"); companion object { operator fun invoke(operation: String) = entries.associateBy(Operation::operation)[operation]!! } } private sealed class Monkey { abstract fun yell(): Long companion object { operator fun invoke(expression: String): Monkey = when (expression.containsOnlyDigits()) { true -> NumberMonkey(expression.toLong()) false -> { val (leftMonkeyName, operation, rightMonkeyName) = expression.split(" ") MathMonkey(leftMonkeyName, Operation(operation), rightMonkeyName) } } } } private class NumberMonkey(val number: Long) : Monkey() { override fun yell() = number } private class MathMonkey(val leftMonkeyName: String, val operation: Operation, val rightMonkeyName: String) : Monkey() { lateinit var leftMonkey: Monkey lateinit var rightMonkey: Monkey override fun yell() = when (operation) { PLUS -> leftMonkey.yell() + rightMonkey.yell() MINUS -> leftMonkey.yell() - rightMonkey.yell() TIMES -> leftMonkey.yell() * rightMonkey.yell() DIV -> leftMonkey.yell() / rightMonkey.yell() } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,779
AdventOfCode
MIT License
2017/day-10/solution.kt
bertptrs
47,429,580
false
{"Rust": 605086, "Python": 92178, "Java": 3238, "C#": 2880, "Lua": 2480, "Clojure": 2454, "Shell": 1957, "CoffeeScript": 1765, "C": 1729, "Kotlin": 1589, "Groovy": 1457, "JavaScript": 1210, "Julia": 1144, "Makefile": 983, "Go": 856, "Scala": 776, "Ruby": 738, "MATLAB": 646, "PHP": 622, "Haskell": 603, "Perl": 589, "R": 560, "Awk": 531, "C++": 449, "Swift": 337, "Lex": 310}
fun valArray(): IntArray { val arr = IntArray(256) for (i in arr.indices) { arr[i] = i } return arr } fun hash(input: IntArray, values: IntArray, index: Int, skip: Int): Pair<Int, Int> { var curIndex = index var curSkip = skip for (range in input) { val halfRange = range / 2 for (i in 0..(halfRange - 1)) { val i1 = (curIndex + i) % values.size val i2 = (curIndex + range - i - 1) % values.size values[i1] = values[i2].also { values[i2] = values[i1] } } curIndex = (curIndex + range + curSkip) % values.size curSkip++ } return Pair(curIndex, curSkip) } fun solve(input: String) { // Part 1 val part1input = input.split(",").map { it.toInt() }.toIntArray() val values = valArray() hash(part1input, values, 0, 0) println(values[0] * values[1]) // Part 2 val part2input = ArrayList(List(input.length) { input[it].toInt()}) part2input.addAll(arrayOf(17, 31, 73, 47, 23)) val values2 = valArray() var skip = 0 var index = 0 // Repeat hash 64 times for (i in 1..64) { val (newIndex, newSkip) = hash(part2input.toIntArray(), values2, index, skip) index = newIndex skip = newSkip } for (i in 0..15) { val startIndex = 16 * i val endIndex = startIndex + 15 val currentNum = values2.slice(startIndex..endIndex).reduce{a, b -> a.xor(b)} print("%02x".format(currentNum)) } println() } fun main(args: Array<String>) { solve(readLine()!!) }
0
Rust
1
12
1f41f4b35ae94f8be7eed3832c2ccb273059399d
1,589
adventofcode
MIT License
src/main/kotlin/Day04.kt
attilaTorok
573,174,988
false
{"Kotlin": 26454}
import kotlin.streams.toList fun main() { fun getFullyContainedPairsCount(fileName: String): Int { var sumOfFullyContainedPairs = 0 readInputWithStream(fileName).useLines { val iterator = it.iterator() while (iterator.hasNext()) { val assignmentPairs = iterator.next().split(",") val assignmentA = assignmentPairs[0].split("-").stream().mapToInt(String::toInt).toList() val assignmentB = assignmentPairs[1].split("-").stream().mapToInt(String::toInt).toList() if (assignmentA[0] <= assignmentB[0] && assignmentA[1] >= assignmentB[1] || assignmentB[0] <= assignmentA[0] && assignmentB[1] >= assignmentA[1]) { sumOfFullyContainedPairs++ } } } return sumOfFullyContainedPairs } fun getOverlappingPairCount(fileName: String): Int { var sumOfFullyContainedPairs = 0 readInputWithStream(fileName).useLines { val iterator = it.iterator() while (iterator.hasNext()) { val assignmentPairs = iterator.next().split(",") val assignmentA = assignmentPairs[0].split("-").stream().mapToInt(String::toInt).toList() val assignmentB = assignmentPairs[1].split("-").stream().mapToInt(String::toInt).toList() if (assignmentA[0] <= assignmentB[0] && assignmentA[1] >= assignmentB[0] || assignmentB[0] <= assignmentA[0] && assignmentB[1] >= assignmentA[0]) { sumOfFullyContainedPairs++ } } } return sumOfFullyContainedPairs } println("Test") println("Number of pairs where one range fully contain the other should be 2! Counted: ${getFullyContainedPairsCount("Day04_test")}") println("Number of pairs where's an overlap is 4! Counted: ${getOverlappingPairCount("Day04_test")}") println() println("Exercise") println("Number of pairs where one range fully contain the other should be 547! Counted: ${getFullyContainedPairsCount("Day04")}") println("Number of pairs where's an overlap is 843! Counted: ${getOverlappingPairCount("Day04")}") }
0
Kotlin
0
0
1799cf8c470d7f47f2fdd4b61a874adcc0de1e73
2,246
AOC2022
Apache License 2.0
src/day07/Day07.kt
Frank112
572,910,492
false
null
package day07 import assertThat import readInput fun main() { val cdCommandRegex = Regex("^\\$ cd (.+)$") val lsCommandRegex = Regex("^\\$ ls$") val directoryListingRegex = Regex("^dir (.+)$") val fileListingRegex = Regex("^(\\d+) (.+)$") fun parseInput(input: List<String>): Directory { val rootDir = Directory(cdCommandRegex.matchEntire(input[0])!!.groupValues[1], listOf()) var currentDir = rootDir for (line in input.drop(1)) { if (line.matches(lsCommandRegex)) { continue } else if (line.matches(cdCommandRegex)) { val dirName = cdCommandRegex.matchEntire(line)!!.groupValues[1] currentDir = if (dirName == "..") currentDir.parentDir!! else currentDir.findDirectoryByName(dirName)!! } else if (line.matches(directoryListingRegex)) { val dirName = directoryListingRegex.matchEntire(line)!!.groupValues[1] currentDir.add(Directory(dirName, listOf(), currentDir)) } else if (line.matches(fileListingRegex)) { val fileListingValues = fileListingRegex.matchEntire(line)!!.groupValues currentDir.add(File(fileListingValues[2], fileListingValues[1].toLong())) } else { throw IllegalStateException("Could not process line: '$line'") } } return rootDir } fun part1(input: Directory): Long { return Directory.findAllDirectoriesWithMaximumSize(input, 100000).sumOf { it.size() } } fun part2(input: Directory): Long { val requiredSpace = 30000000 - (70000000 - input.size()) return input.findAllDirectoriesWithMinimumSize(requiredSpace).sortedBy { it.size() }[0].size() } // test if implementation meets criteria from the description, like: val testInput = parseInput(readInput("day07/Day07_test")) println("Parsed test input: ${testInput}") assertThat(part1(testInput), 95437) assertThat(part2(testInput), 24933642) val input = parseInput(readInput("day07/Day07")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1e927c95191a154efc0fe91a7b89d8ff526125eb
2,148
advent-of-code-2022
Apache License 2.0
src/Day01.kt
novotnyradekcz
579,767,169
false
{"Kotlin": 11517}
fun main() { fun part1(input: List<String>): Int { var calories = 0 val maxima = mutableListOf<Int>() for (line in input) { if (line == "") { maxima.add(calories) calories = 0 } else { calories += line.toInt() } } maxima.add(calories) return maxima.max() } fun part2(input: List<String>): Int { var calories = 0 val maxima = mutableListOf<Int>() for (line in input) { if (line == "") { maxima.add(calories) calories = 0 } else { calories += line.toInt() } } maxima.add(calories) var topThree = 0 topThree += maxima.max() // highest maxima.remove(maxima.max()) topThree += maxima.max() // second highest maxima.remove(maxima.max()) topThree += maxima.max() // third highest return topThree } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
2f1907dc63344cf536f5031bc7e1c61db03fc570
1,310
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/pl/pjagielski/punkt/melody/Scale.kt
Syknapse
255,642,812
true
{"Kotlin": 38347, "SuperCollider": 4251, "Java": 237}
package pl.pjagielski.punkt.melody import pl.pjagielski.punkt.pattern.Step import pl.pjagielski.punkt.pattern.StepSequence import kotlin.math.absoluteValue val C = 60 val D = 62 val E = 64 val F = 65 val G = 67 val A = 69 val B = 71 fun Int.sharp() = inc() fun Int.flat() = dec() sealed class Intervals(val intervals: List<Int>) { fun reversed(): Intervals = Simple(this.intervals.reversed()) fun cycle() = pl.pjagielski.punkt.pattern.cycle(*this.intervals.toTypedArray()).filterNotNull() private class Simple(intervals: List<Int>) : Intervals(intervals) object major : Intervals(listOf(2,2,1,2,2,2,1)) object minor : Intervals(listOf(2,1,2,2,1,2,2)) object pentatonic : Intervals(listOf(3,2,2,3,2)) } class Degrees(val degrees: List<Int>) { constructor(vararg degrees: Int) : this(degrees.toList()) } fun degrees(degs: List<Int?>) = degs.map { deg -> deg?.let { Degrees(it) } }.asSequence() fun degrees(degs: Sequence<Int?>) = degs.map { deg -> deg?.let { Degrees(it) } } fun chords(chords: Iterable<List<Int>>) = chords.map { Degrees(it) }.asSequence() fun chords(chords: Iterable<Chord?>) = chords.map { it?.degrees?.let(::Degrees) } fun Iterable<Chord?>.toDegrees(): Sequence<Degrees?> = this.map { it?.degrees?.let(::Degrees) }.asSequence() fun Sequence<Chord?>.toDegrees(): Sequence<Degrees?> = this.map { it?.degrees?.let(::Degrees) } class Scale(val from: Int, val intervals: Intervals) { fun low() = Scale(from - 12, intervals) fun high() = Scale(from + 12, intervals) fun note(degree: Int): Int { return when { degree > 0 -> findNote(degree, intervals.cycle(), Int::plus) degree < 0 -> findNote(degree, intervals.reversed().cycle(), Int::minus) else -> from } } fun phrase(degrees: Sequence<Degrees?>, durations: Sequence<Double?>, at: Double = 0.0) = phrase(degrees, durations.iterator(), at) fun phrase(degrees: Sequence<Degrees?>, durations: List<Double?>, at: Double = 0.0) = phrase(degrees, durations.iterator(), at) private fun phrase(degrees: Sequence<Degrees?>, diter: Iterator<Double?>, at: Double = 0.0): StepSequence { var current = at return degrees.flatMap { deg -> if (!diter.hasNext()) return@flatMap sequenceOf<Step>() diter.next()?.let { dur -> val ret = deg?.degrees?.map { d -> Step(current, dur, note(d)) }?.asSequence() current += dur ret } ?: sequenceOf() } } private fun findNote(degree: Int, intervals: Sequence<Int>, next: (Int, Int) -> Int) : Int { var prev = from return intervals .map { prev = next(prev, it); prev } .take(degree.absoluteValue) .last() } }
0
null
0
0
2db710a726b31106ae09c5317a1521b9d84ea20c
2,817
punkt
Apache License 2.0
src/main/kotlin/days/Solution16.kt
Verulean
725,878,707
false
{"Kotlin": 62395}
package days import adventOfCode.InputHandler import adventOfCode.Solution import adventOfCode.util.PairOf import adventOfCode.util.Point2D import adventOfCode.util.plus object Solution16 : Solution<CharGrid>(AOC_YEAR, 16) { override fun getInput(handler: InputHandler) = handler.getInput("\n").map(String::toCharArray).toTypedArray() private fun CharGrid.countEnergizedTiles(position: Point2D, direction: Point2D): Int { val seen = mutableSetOf<PairOf<Point2D>>() val queue = ArrayDeque<PairOf<Point2D>>() queue.add(position to direction) do { var (p, d) = queue.removeFirst() p += d if (p to d in seen) continue val (i, j) = p val (di, dj) = d if (i !in this.indices || j !in this.indices) continue seen.add(p to d) when (this[i][j]) { '.' -> queue.add(p to d) '/' -> queue.add(p to (-dj to -di)) '\\' -> queue.add(p to (dj to di)) '|' -> { if (dj != 0) { queue.add(p to (1 to 0)) queue.add(p to (-1 to 0)) } else queue.add(p to d) } '-' -> { if (di != 0) { queue.add(p to (0 to 1)) queue.add(p to (0 to -1)) } else queue.add(p to d) } } } while (queue.isNotEmpty()) return seen.map { it.first }.toSet().size } override fun solve(input: CharGrid): PairOf<Int> { val n = input.size val ans1 = input.countEnergizedTiles(0 to -1, 0 to 1) val ans2 = input.indices.asSequence() .flatMap { i -> sequenceOf( (i to -1) to (0 to 1), (i to n) to (0 to -1), (-1 to i) to (1 to 0), (n to i) to (-1 to 0) ) } .maxOf { input.countEnergizedTiles(it.first, it.second) } return ans1 to ans2 } }
0
Kotlin
0
1
99d95ec6810f5a8574afd4df64eee8d6bfe7c78b
2,130
Advent-of-Code-2023
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions49.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import kotlin.math.min fun test49() { printlnResult(1) printlnResult(2) printlnResult(3) printlnResult(4) printlnResult(5) printlnResult(6) printlnResult(7) printlnResult(8) printlnResult(9) printlnResult(10) printlnResult(1500) } /** * Questions 49: Find the nth ugly number(only own factors: 2, 3, 5) */ private fun uglyNumber(n: Int): Int { require(n > 0) { "The n must greater than 0" } return if (n == 1) 1 else { val cache = IntArray(n) cache[0] = 1 var nextIndex = 1 var multiply2 = 0 var multiply3 = 0 var multiply5 = 0 while (nextIndex < n) { val min = min(cache[multiply2] * 2, cache[multiply3] * 3, cache[multiply5] * 5) cache[nextIndex] = min while (cache[multiply2] * 2 <= cache[nextIndex]) multiply2++ while (cache[multiply3] * 3 <= cache[nextIndex]) multiply3++ while (cache[multiply5] * 5 <= cache[nextIndex]) multiply5++ nextIndex++ } cache.last() } } private fun min(a: Int, b: Int, c: Int): Int = min(min(a, b), c) private fun printlnResult(n: Int) = println("The number $n ugly number is: ${uglyNumber(n)}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,334
Algorithm
Apache License 2.0
day13/src/main/kotlin/App.kt
ascheja
317,918,055
false
null
package net.sinceat.aoc2020.day13 fun main() { run { val (currentTime, busIds) = readInputPart1("testinput.txt") val (busId, nextDeparture) = busIds.nextDepartures(currentTime).minByOrNull { (_, nextDeparture) -> nextDeparture }!! println("$busId x ($nextDeparture - $currentTime) = ${busId * (nextDeparture - currentTime)}") } run { val (currentTime, busIds) = readInputPart1("input.txt") val (busId, nextDeparture) = busIds.nextDepartures(currentTime).minByOrNull { (_, nextDeparture) -> nextDeparture }!! println("$busId x ($nextDeparture - $currentTime) = ${busId * (nextDeparture - currentTime)}") println() } run { println(readInputPart2("testinput.txt").findFirstConsecutiveDepartures()) } run { println(readInputPart2("input.txt").findFirstConsecutiveDepartures()) } } fun List<Pair<Int, Int>>.findFirstConsecutiveDepartures(): Long { var time = 0L var stepSize = 1L for ((busId, offset) in this) { while ((time + offset) % busId != 0L) { time += stepSize } stepSize *= busId } return time } fun List<Int>.nextDepartures(currentTime: Int): Map<Int, Int> { return associate { busId -> Pair( busId, (currentTime / busId) * busId + busId ) } } fun readInputPart1(fileName: String): Pair<Int, List<Int>> { val lines = ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().readLines() val currentTime = lines[0].toInt() val busIds = lines[1].split(",").mapNotNull(String::toIntOrNull) return Pair(currentTime, busIds) } fun readInputPart2(fileName: String): List<Pair<Int, Int>> { val lines = ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().readLines() return lines[1].split(",").map(String::toIntOrNull).mapIndexed { index, busId -> if (busId == null) { return@mapIndexed null } Pair(busId, index) }.filterNotNull() }
0
Kotlin
0
0
f115063875d4d79da32cbdd44ff688f9b418d25e
2,073
aoc2020
MIT License
src/Day01.kt
kthun
572,871,866
false
{"Kotlin": 17958}
fun main() { fun createElves(input: List<String>): MutableList<List<Int>> { val elvesStrings = mutableListOf<List<Int>>() var thisElfStrings = mutableListOf<Int>() for (s in input) { if (s == "") { elvesStrings.add(thisElfStrings) thisElfStrings = mutableListOf() } else { thisElfStrings.add(s.toInt()) } } elvesStrings.add(thisElfStrings) return elvesStrings } fun part1(input: List<String>): Int { val elvesStrings = createElves(input) return elvesStrings.maxOf { it.sum() } } fun part2(input: List<String>): Int { val elvesStrings = createElves(input) return elvesStrings.sortedByDescending { it.sum() } .take(3) .sumOf { it.sum() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5452702e4e20ef2db3adc8112427c0229ebd1c29
1,137
aoc-2022
Apache License 2.0
src/Day02.kt
samo1
573,449,853
false
{"Kotlin": 4045}
fun main() { // A for Rock, B for Paper, and C for Scissors // X for Rock, Y for Paper, and Z for Scissors fun part1(input: List<String>) = input.sumOf { val shapeScore = when (it[2]) { 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> throw IllegalArgumentException("Invalid input '$it'") } val outcomeScore = when (it) { "A X" -> 3 "A Y" -> 6 "A Z" -> 0 "B X" -> 0 "B Y" -> 3 "B Z" -> 6 "C X" -> 6 "C Y" -> 0 "C Z" -> 3 else -> throw IllegalArgumentException("Invalid input '$it'") } shapeScore + outcomeScore } // A for Rock, B for Paper, and C for Scissors // X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win fun part2(input: List<String>) = input.sumOf { val myHand = when (it) { "A X" -> 'C' "A Y" -> 'A' "A Z" -> 'B' "B X" -> 'A' "B Y" -> 'B' "B Z" -> 'C' "C X" -> 'B' "C Y" -> 'C' "C Z" -> 'A' else -> throw IllegalArgumentException("Invalid input '$it'") } val shapeScore = when (myHand) { 'A' -> 1 'B' -> 2 'C' -> 3 else -> throw IllegalArgumentException("Invalid input '$it'") } val outcomeScore = when ("${it[0]} $myHand") { "A A" -> 3 "A B" -> 6 "A C" -> 0 "B A" -> 0 "B B" -> 3 "B C" -> 6 "C A" -> 6 "C B" -> 0 "C C" -> 3 else -> throw IllegalArgumentException("Invalid input '$it'") } shapeScore + outcomeScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
77e32453ba45bd4f9088f34be91939b94161cf13
2,124
adventofcode2022
Apache License 2.0
src/main/kotlin/kr/co/programmers/P68936.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://github.com/antop-dev/algorithm/issues/240 class P68936 { fun solution(arr: Array<IntArray>): IntArray { return recursive(arr, 0, 0, arr.size) } private fun recursive(arr: Array<IntArray>, y: Int, x: Int, size: Int): IntArray { val count = intArrayOf(0, 0); val n = y + size val m = x + size // 시작위치 ~ 크기만큼 0과 1의 개수를 카운트 var zero = 0 var one = 0 for (i in y until n) { for (j in x until m) { if (arr[i][j] == 0) zero++ else one++ } } when { // 모두 0인 경우 zero == size * size -> count[0]++ // 모두 1인 경우 one == size * size -> count[1]++ // 최소 크기인 경우 size == 2 -> { count[0] += zero count[1] += one } // 범위를 반으로 줄여서 다시 카운팅 else -> { val half = size / 2 for (i in y until n step half) { for (j in x until m step half) { val (z, o) = recursive(arr, i, j, half) count[0] += z count[1] += o } } } } // 카운팅을 위로 올린다. return count } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,446
algorithm
MIT License
src/main/kotlin/no/quist/aoc18/days/Day3.kt
haakonmt
159,945,133
false
null
package no.quist.aoc18.days import no.quist.aoc18.Day object Day3 : Day<List<Rectangle>, Any>() { override fun createInput(): List<Rectangle> = inputLines.map { line -> val (id, x, y, width, height) = line groupBy Regex("""#(\d*) @ (\d*),(\d*): (\d*)x(\d*)""") Rectangle(id, x.toInt(), y.toInt(), width.toInt(), height.toInt()) } override fun part1(input: List<Rectangle>): Int = input .foldToMap(0) { _, i -> i + 1 } .values .count { it >= 2 } override fun part2(input: List<Rectangle>): String { val covered = input.foldToMap(mutableListOf<String>()) { (id), list -> (list + id).toMutableList() } val overlapping = covered.values.filter { it.size >= 2 }.flatten() return input.find { (id) -> !overlapping.contains(id) }!!.id } private fun <T> List<Rectangle>.foldToMap(defaultValue: T, addValue: (Rectangle, T) -> T) : MutableMap<String, T> = fold(mutableMapOf()) { acc, r -> (r.x..(r.x + r.width - 1)).forEach { x -> (r.y..(r.y + r.height - 1)).forEach { y -> acc["$x,$y"] = addValue(r, (acc["$x,$y"] ?: defaultValue)) } } acc } } data class Rectangle( val id: String, val x: Int, val y: Int, val width: Int, val height: Int )
0
Kotlin
0
1
4591ae7aa9cbb70e26ae2c3a65ec9e55559c2690
1,369
aoc18
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year15/Day13.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year15 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.permutations fun PuzzleSet.day13() = puzzle { val exclusiveSeatings = inputLines.map { l -> val split = l.split(" ") val type = when (split[2]) { "gain" -> 1 "lose" -> -1 else -> error("What?") } val units = split[3].toInt() * type val nextTo = split.last().removeSuffix(".") SeatingOption(split[0], nextTo, units) } fun solve(seatings: List<SeatingOption>, people: List<String>): String { val findFor = { person: String, nextTo: String -> seatings.find { it.person == person && it.nextTo == nextTo }?.points ?: 0 } return people.permutations().maxOf { configuration -> configuration.withIndex().sumOf { (idx, p) -> val left = configuration.getRolledOver(idx - 1) val right = configuration.getRolledOver(idx + 1) findFor(p, left) + findFor(p, right) } }.s() } val people = exclusiveSeatings.map { it.person }.distinct() partOne = solve(exclusiveSeatings, people) partTwo = solve(exclusiveSeatings, people + "Me") } fun <T> List<T>.getRolledOver(index: Int): T = when { index >= size -> this[index % size] index < 0 -> getRolledOver(size + index) else -> this[index] } data class SeatingOption(val person: String, val nextTo: String, val points: Int)
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,499
advent-of-code
The Unlicense
day14/src/main/kotlin/ver_b.kt
jabbalaci
115,397,721
false
null
package b import java.io.File class Matrix(val matrix: List<List<Int>>) { private var groupCounter = 0 private val visited = mutableSetOf<Pair<Int, Int>>() override fun toString(): String { val sb = StringBuilder() for (row in matrix) { sb.append(row.joinToString("")) sb.append("\n") } return sb.toString() } private fun explore(i: Int, j: Int) { // recursive if ((i >= 0) && (i <= matrix.lastIndex) && (j >= 0) && (j <= matrix[0].lastIndex)) { if (Pair(i, j) !in visited) { if (matrix[i][j] == 1) { visited.add(Pair(i, j)) explore(i - 1, j) explore(i + 1, j) explore(i, j - 1) explore(i, j + 1) } } } } fun findGroups() { for (i in matrix.indices) { for (j in matrix[0].indices) { val curr = Pair(i, j) if ((curr !in visited) && (matrix[i][j] == 1)) { ++groupCounter explore(i, j) } } } } fun groupNumber() = groupCounter } fun main(args: Array<String>) { // production // it was generated from the hashes of the word "uugsqrei", // which was my puzzle input val fname = "matrix.txt" val matrix = readFile(fname) // example 1 // val fname = "pelda1.txt" // ebben 4 régió van // var matrix = readExample(fname) // example 2 // val fname = "pelda2.txt" // ebben 8 régió van // var matrix = readExample(fname) val m = Matrix(matrix) // println(m) m.findGroups() println(m.groupNumber()) } fun readFile(fname: String): List<List<Int>> { val matrix = mutableListOf<List<Int>>() File(fname).forEachLine { line -> matrix.add(line.map { c -> c.toString().toInt() }) } return matrix } fun readExample(fname: String): List<List<Int>> { val matrix = mutableListOf<List<Int>>() File(fname).forEachLine { l -> var line = l.replace('X', '1') line = line.replace('O', '1') line = line.replace('.', '0') matrix.add(line.map { c -> c.toString().toInt() }) } return matrix }
0
Kotlin
0
0
bce7c57fbedb78d61390366539cd3ba32b7726da
2,362
aoc2017
MIT License
src/Day06.kt
george-theocharis
573,013,076
false
{"Kotlin": 10656}
fun main() { fun List<String>.splitListPerSegments(size: Int) = flatMap { it.windowed(size, 1) } fun List<String>.findDistinctSegment() = first { packet -> packet.all { character -> packet.count { it == character } == 1 } } fun List<String>.indexOfDistinctSegment( firstDistinctPacket: String, distinctSegmentSize: Int ): Int = first().indexOf(firstDistinctPacket) + distinctSegmentSize fun part1(input: List<String>): Int { val distinctSegmentSize = 4 return input.splitListPerSegments(distinctSegmentSize).findDistinctSegment().run { input.indexOfDistinctSegment(this, distinctSegmentSize) } } fun part2(input: List<String>): Int { val distinctSegmentSize = 14 return input.splitListPerSegments(distinctSegmentSize).findDistinctSegment().run { input.indexOfDistinctSegment(this, distinctSegmentSize) } } val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7971bea39439b363f230a44e252c7b9f05a9b764
1,028
aoc-2022
Apache License 2.0
common/src/main/kotlin/combo/sat/optimizers/ObjectiveFunction.kt
rasros
148,620,275
false
null
package combo.sat.optimizers import combo.math.EMPTY_VECTOR import combo.math.VectorView import combo.model.EffectCodedVector import combo.model.Model import combo.sat.Instance import combo.sat.literal import combo.sat.not import combo.sat.toIx interface ObjectiveFunction { /** * Value to minimize evaluated on a [VectorView], which take on values between zeros and ones. */ fun value(vector: VectorView): Float /** * Optionally implemented. Optimal bound on function, if reached during search the algorithm will terminate immediately. */ fun lowerBound(): Float = Float.NEGATIVE_INFINITY fun upperBound(): Float = Float.POSITIVE_INFINITY /** * Override for efficiency reasons. New value should be previous value - improvement. */ fun improvement(instance: Instance, ix: Int): Float { val v1 = value(instance) instance.flip(ix) val v2 = value(instance) instance.flip(ix) return v1 - v2 } } /** * Linear sum objective, as in linear programming. */ open class LinearObjective(val maximize: Boolean, val weights: VectorView) : ObjectiveFunction { override fun value(vector: VectorView) = (vector dot weights).let { if (maximize) -it else it } } open class DeltaLinearObjective(maximize: Boolean, weights: VectorView) : LinearObjective(maximize, weights) { override fun improvement(instance: Instance, ix: Int): Float { val literal = !instance.literal(ix) return if (instance.literal(literal.toIx()) == literal) 0.0f else { val w = weights[literal.toIx()].let { if (instance.isSet(literal.toIx())) it else -it } if (maximize) -w else w } } } object SatObjective : LinearObjective(false, EMPTY_VECTOR) { override fun value(vector: VectorView) = 0.0f override fun lowerBound() = 0.0f override fun upperBound() = 0.0f override fun improvement(instance: Instance, ix: Int) = 0.0f } class EffectCodedObjective(val base: ObjectiveFunction, val model: Model) : ObjectiveFunction { override fun value(vector: VectorView) = base.value(EffectCodedVector(model, vector as Instance)) } /** * Exterior penalty added to objective used by genetic algorithms. * For information about possibilities, see: * Penalty Function Methods for Constrained Optimization with Genetic Algorithms * https://doi.org/10.3390/mca10010045 */ interface PenaltyFunction { fun penalty(value: Float, violations: Int, lowerBound: Float, upperBound: Float): Float } class LinearPenalty : PenaltyFunction { override fun penalty(value: Float, violations: Int, lowerBound: Float, upperBound: Float): Float = violations.toFloat() } class SquaredPenalty : PenaltyFunction { override fun penalty(value: Float, violations: Int, lowerBound: Float, upperBound: Float) = violations.let { (it * it).toFloat() } } /** * This penalty ensures that any infeasible candidate solution has a penalized * score that is strictly greater than a feasible solution. In order for that to work the * [combo.sat.optimizers.ObjectiveFunction.lowerBound] and [combo.sat.optimizers.ObjectiveFunction.upperBound] must be * implemented and be finite. Otherwise, choose another penalty function that does not rely on bounds. * */ class DisjunctPenalty(private val extended: PenaltyFunction = LinearPenalty()) : PenaltyFunction { override fun penalty(value: Float, violations: Int, lowerBound: Float, upperBound: Float): Float { return if (violations > 0) upperBound - lowerBound + extended.penalty(value, violations, lowerBound, upperBound) else 0.0f } } class StatisticObjectiveFunction(val base: ObjectiveFunction) : ObjectiveFunction by base { var functionEvaluations = 0 private set var improvementEvaluations = 0 private set override fun value(vector: VectorView): Float { functionEvaluations++ return base.value(vector) } override fun improvement(instance: Instance, ix: Int): Float { improvementEvaluations++ return base.improvement(instance, ix) } }
0
Kotlin
1
2
2f4aab86e1b274c37d0798081bc5500d77f8cd6f
4,122
combo
Apache License 2.0
src/main/kotlin/Day06.kt
Vampire
572,990,104
false
{"Kotlin": 57326}
fun main() { fun part1(input: List<String>, amountOfDistinct: Int = 4) = input[0] .toCharArray() .asSequence() .withIndex() .windowed(amountOfDistinct) .find { markerCandidate -> markerCandidate.distinctBy { it.value }.size == amountOfDistinct }!! .let { it.last().index + 1 } fun part2(input: List<String>) = part1(input, amountOfDistinct = 14) val testInput1 = readStrings("Day06_test1") check(part1(testInput1) == 7) val testInput2 = readStrings("Day06_test2") check(part1(testInput2) == 5) val testInput3 = readStrings("Day06_test3") check(part1(testInput3) == 6) val testInput4 = readStrings("Day06_test4") check(part1(testInput4) == 10) val testInput5 = readStrings("Day06_test5") check(part1(testInput5) == 11) val input = readStrings("Day06") println(part1(input)) check(part2(testInput1) == 19) check(part2(testInput2) == 23) check(part2(testInput3) == 23) check(part2(testInput4) == 29) check(part2(testInput5) == 26) println(part2(input)) }
0
Kotlin
0
0
16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f
1,088
aoc-2022
Apache License 2.0
kotlin/src/2023/Day01_2023.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
private val sdigits = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9, ) private fun digitAtStart(s: String, i: Int): Int? { val seq = s.subSequence(i until s.length) for ((sdig, dig) in sdigits.entries) { if (seq.startsWith(sdig)) return dig } if (seq[0].isDigit()) return seq[0].digitToInt() return null } fun main() { val input = readInput(1, 2023) val lines = input.trim().split("\n") val res1 = lines.asSequence() .map { line -> line.first {it.isDigit()}.toString() + line.last {it.isDigit()} } .map {it.toInt()} .sum() println("Part 1: $res1") var res2 = 0 for (line in lines) { var (first_dig, last_dig) = -1 to -1 for (i in line.indices) { val dig = digitAtStart(line, i) if (dig != null) { last_dig = dig if (first_dig < 0) first_dig = dig } } res2 += first_dig * 10 + last_dig } println("Part 2: $res2") }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
1,134
adventofcode
Apache License 2.0
src/leetcode_study_badge/data_structure/Day3.kt
faniabdullah
382,893,751
false
null
package leetcode_study_badge.data_structure class Day3 { fun getRowBrute(rowIndex: Int): List<Int> { val dp = Array(rowIndex + 1) { IntArray(rowIndex + 1) } dp[0][0] = 1 dp[rowIndex][rowIndex] = 1 var indexRow = 1 while (indexRow <= rowIndex) { repeat(rowIndex) { indexColumn -> if (indexColumn == 0) { dp[indexRow][0] = 1 return@repeat } if (indexColumn > indexRow) { return@repeat } if (indexColumn == indexRow) { dp[indexRow][indexColumn] = 1 } else { dp[indexRow][indexColumn] = dp[indexRow - 1][indexColumn] + dp[indexRow - 1][indexColumn - 1] } } indexRow++ } return dp[rowIndex].toList() } fun getRow(rowIndex: Int): List<Int> { //base case: first row if (rowIndex == 0) { val list: ArrayList<Int> = ArrayList() list.add(1) return list } //Recursion to calculate each row val aboveRow: List<Int> = getRow(rowIndex - 1) //When get the list of above row, start to calculate current row val row: MutableList<Int> = ArrayList() //Calculate each number in current row for (i in 0 until rowIndex + 1) { var left = 0 var right = 0 if (i > 0) left = aboveRow[i - 1] if (i < rowIndex) right = aboveRow[i] //Be careful of the index: should be i-1 & i row.add(left + right) } return row } fun rotate(matrix: Array<IntArray>): Unit { val n: Int = matrix.size for (i in 0 until (n + 1) / 2) { for (j in 0 until n / 2) { val temp = matrix[n - 1 - j][i] matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1] matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i] matrix[j][n - 1 - i] = matrix[i][j] matrix[i][j] = temp } } } // https://leetcode.com/problems/spiral-matrix-ii/ fun generateMatrix(n: Int): Array<IntArray> { val array = Array(n) { IntArray(n) { -1 } } var state = 0 var col = 0 var row = -1 val filled = n * n for (i in 1..filled) { when (state) { 0 -> { // right row++ array[col][row] = i if (row == n - 1 || array[col][row + 1] != -1) { state = 1 } } 1 -> { // down col++ array[col][row] = i if (col == n - 1 || array[col + 1][row] != -1) { state = 2 } } 2 -> { // left row-- array[col][row] = i if (row == 0 || array[col][row - 1] != -1) { state = 3 } } 3 -> { // top col-- array[col][row] = i if (col == 0 || array[col - 1][row] != -1) { state = 0 } } } } return array } } fun main() { val result = Day3().generateMatrix(6) var matrix = arrayOf( intArrayOf(1, 2, 3, 4, 50), intArrayOf(5, 6, 7, 8, 51), intArrayOf(9, 10, 11, 12, 52), intArrayOf(13, 14, 15, 16, 53), intArrayOf(17, 18, 19, 20, 54) ) Day3().rotate(matrix) println("After rotate") result.forEach { println(it.contentToString()) } }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
3,902
dsa-kotlin
MIT License
src/aoc2022/Day07.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
package aoc2022 import utils.* internal class Day07(lines: List<String>) { data class Directory(var size: Long = 0, val name: String, val parent: Directory?) // Container to be able to change the value in dirs and path val dirs = mutableListOf<Directory>() // A list containing the sizes of all directories val path = mutableListOf<Directory>() // A stack containing the current path of directories init { lines.forEach { val parts = it.split(" ") when (parts[0]) { "$" -> // Commands when (parts[1]) { "cd" -> when (parts[2]) { ".." -> path.removeLast() else -> { val d = Directory(name = parts[2], parent = path.lastOrNull()) dirs.add(d) path.add(d) } } else -> Unit // Do nothing for ls } "dir" -> Unit // Do nothing for dir // File else -> path.forEach { it.size += parts[0].toLong() } } } } fun part1(): Any { return dirs.map { it.size }.filter { it <= 100000 }.sum() } fun part2(): Any { val usedSpace = dirs.first().size val totalSpace = 70000000 val freeSpace = totalSpace - usedSpace val toDelete = 30000000 - freeSpace return dirs.map { it.size }.filter { it >= toDelete }.min() } companion object { fun runDay() { val day = "07".toInt() val todayTest = Day07(readInput(day, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 95437L) val today = Day07(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1", 1845346L) // 1523801 // 1540861 execute(todayTest::part2, "Day[Test] $day: pt 2", 24933642L) execute({ Day07(readInput(day, 2022)).part2() }, "Day $day: pt 2", 3636703L) } } } fun main() { Day07.runDay() }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
1,883
aoc2022
Apache License 2.0
src/Day13/December13.kt
Nandi
47,216,709
false
null
package Day13 import org.jgrapht.experimental.permutation.CollectionPermutationIter import org.jgrapht.graph.DefaultWeightedEdge import org.jgrapht.graph.SimpleWeightedGraph import java.nio.file.Files import java.nio.file.Paths import java.util.stream.Stream /** * In years past, the holiday feast with your family hasn't gone so well. Not everyone gets along! This year, you * resolve, will be different. You're going to find the optimal seating arrangement and avoid all those awkward * conversations. * * You start by writing up a list of everyone invited and the amount their happiness would increase or decrease if they * were to find themselves sitting next to each other person. You have a circular table that will be just big enough to * fit everyone comfortably, and so each person will have exactly two neighbors. * * Part 1 * * What is the total change in happiness for the optimal seating arrangement of the actual guest list? * * Part 2 * * In all the commotion, you realize that you forgot to seat yourself. At this point, you're pretty apathetic toward * the whole thing, and your happiness wouldn't really go up or down regardless of who you sit next to. You assume * everyone else would be just as ambivalent about sitting next to you, too. * * So, add yourself to the list, and give all happiness relationships that involve you a score of 0. * * What is the total change in happiness for the optimal seating arrangement that actually includes yourself? * * Created by Simon on 13/12/2015. */ class December13 { val seatingGraph: SimpleWeightedGraph<String, DefaultWeightedEdge> = SimpleWeightedGraph(DefaultWeightedEdge::class.java) fun createGraph(seatSelf: Boolean) { val lines = loadFile("src/Day13/13.dec_input.txt") for (line in lines) { var importantInfo = line.replace("would ", "").replace("happiness units by sitting next to ", "").replace(".", "") val (from, type, weight, to) = importantInfo.split(" ") if (from !is String || to !is String || type !is String || weight !is String) return var sign: Double if ("lose".equals(type)) { sign = -1.0 } else { sign = 1.0 } seatingGraph.addVertex(from) seatingGraph.addVertex(to) val edge = seatingGraph.getEdge(from, to) if (edge == null) { seatingGraph.setEdgeWeight(seatingGraph.addEdge(from, to), weight.toDouble().times(sign)) } else { seatingGraph.setEdgeWeight(edge, seatingGraph.getEdgeWeight(edge) + (weight.toDouble().times(sign))) } } if (seatSelf) { seatingGraph.addVertex("Simon") for (person in seatingGraph.vertexSet()) { if ("Simon".equals(person)) continue seatingGraph.setEdgeWeight(seatingGraph.addEdge("Simon", person), 0.0) } } var max = 0.0 var maxPath = listOf<String>() val iterator = CollectionPermutationIter<String>(seatingGraph.vertexSet()) while (iterator.hasNext()) { val permutation = iterator.nextArray var len = 0.0 for (i in 0..(permutation.size - 1)) { val from = permutation[i] val to = if ((i + 1) == permutation.size) permutation[0] else permutation[i + 1] val edge = seatingGraph.getEdge(from, to) ?: break len += seatingGraph.getEdgeWeight(edge) } if (len > max) { max = len maxPath = permutation } } println("The longest distance was ${max.toInt()} through $maxPath") } fun loadFile(path: String): Stream<String> { val input = Paths.get(path) val reader = Files.newBufferedReader(input) return reader.lines() } } fun main(args: Array<String>) { December13().createGraph(false) December13().createGraph(true) }
0
Kotlin
0
0
34a4b4c0926b5ba7e9b32ca6eeedd530f6e95bdc
4,059
adventofcode
MIT License
domain/src/main/kotlin/com/seanshubin/condorcet/domain/Ballot.kt
SeanShubin
126,547,543
false
null
package com.seanshubin.condorcet.domain data class Ballot(val id: String, val confirmation: String, val rankings: List<Ranking>) { init { if (candidates().distinct().size != rankings.size) throw RuntimeException("Ballots for $id has duplicate candidates: ${candidates().joinToString(",")}") } fun toRow(): List<Any> = listOf(id, confirmation, *(rankings.flatMap { it.toRow() }.toTypedArray())) fun pairwisePreferences(allCandidates: List<String>): List<Pair<String, String>> { val candidateRankMap = buildCandidateRankMap() fun betterRankThan(left: String, right: String): Boolean { val leftRank = candidateRankMap[left] val rightRank = candidateRankMap[right] if (leftRank == null) return false if (rightRank == null) return true return leftRank < rightRank } val result = mutableListOf<Pair<String, String>>() for (i in allCandidates) { for (j in allCandidates) { if (betterRankThan(i, j)) { result.add(Pair(i, j)) } } } return result } fun validate(candidates:List<String>){ rankings.forEach { it.validate(candidates) } } private fun buildCandidateRankMap(): Map<String, Int> = rankings.map { buildCandidateRankEntry(it) }.toMap() private fun buildCandidateRankEntry(ranking: Ranking): Pair<String, Int> = Pair(ranking.candidate, ranking.rank) fun candidates(): List<String> = rankings.map { it.candidate } companion object { private val spacePattern = Regex("\\s+") fun fromString(s: String): Ballot { val words = s.split(spacePattern) val id = words[0] val confirmation = words[1] val rankings = (2 until words.size step 2).map { i -> Ranking(words[i].toInt(), words[i + 1]) } return Ballot(id, confirmation, rankings) } } }
0
Kotlin
0
0
a5f887e9ab2281a9c15240a314a6de489ce42f76
2,062
condorcet
The Unlicense
src/Day23.kt
frungl
573,598,286
false
{"Kotlin": 86423}
fun main() { fun parseToSet(input: List<String>): Set<Pair<Int, Int>> { val set = mutableSetOf<Pair<Int, Int>>() input.forEachIndexed { i, s -> s.forEachIndexed { j, c -> if (c == '#') set.add(Pair(i, j)) } } return set } val go = listOf( listOf(-1 to 0, -1 to -1, -1 to 1), listOf(1 to 0, 1 to -1, 1 to 1), listOf(0 to -1, -1 to -1, 1 to -1), listOf(0 to 1, -1 to 1, 1 to 1), listOf(-1 to 0, -1 to -1, -1 to 1), listOf(1 to 0, 1 to -1, 1 to 1), listOf(0 to -1, -1 to -1, 1 to -1), listOf(0 to 1, -1 to 1, 1 to 1), ) val aroundPos = listOf( -1 to 0, 1 to 0, 0 to -1, 0 to 1, -1 to -1, -1 to 1, 1 to -1, 1 to 1 ) fun testPrint(set: Set<Pair<Int, Int>>) { val minX = set.minOf { it.first } val maxX = set.maxOf { it.first } val minY = set.minOf { it.second } val maxY = set.maxOf { it.second } val w = maxX - minX + 1 val h = maxY - minY + 1 val map = MutableList(w) { CharArray(h) { '.' } } set.forEach { pos -> map[pos.first - minX][pos.second - minY] = '#' } map.forEach { println(String(it)) } println() } fun part1(input: List<String>): Int { var set = parseToSet(input) var goPos = 0 repeat(10) { val nextPos = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() val cnt = mutableMapOf<Pair<Int, Int>, Int>() set.forEach { pos -> var allAroundEmpty = true aroundPos.forEach { around -> val newPos = pos.first + around.first to pos.second + around.second if (set.contains(newPos)) allAroundEmpty = false } if (!allAroundEmpty) { for (i in 0..3) { var allEmpty = true go[goPos + i].forEach { move -> val newPos = Pair(pos.first + move.first, pos.second + move.second) if (set.contains(newPos)) allEmpty = false } if (allEmpty) { val next = Pair(pos.first + go[goPos + i][0].first, pos.second + go[goPos + i][0].second) nextPos[pos] = next cnt[next] = cnt.getOrDefault(next, 0) + 1 break } } } } val newSet = mutableSetOf<Pair<Int, Int>>() for(pos in set) { if (nextPos.containsKey(pos)) { val next = nextPos[pos] ?: error("no next") if (cnt[next] == 1) { newSet.add(next) continue } } newSet.add(pos) } set = newSet goPos = (goPos + 1) % 4 } val minX = set.minOf { it.first } val maxX = set.maxOf { it.first } val minY = set.minOf { it.second } val maxY = set.maxOf { it.second } val w = maxX - minX + 1 val h = maxY - minY + 1 return w * h - set.size } fun part2(input: List<String>): Int { var set = parseToSet(input) var goPos = 0 for(i in 1..5000) { val nextPos = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() val cnt = mutableMapOf<Pair<Int, Int>, Int>() set.forEach { pos -> var allAroundEmpty = true aroundPos.forEach { around -> val newPos = pos.first + around.first to pos.second + around.second if (set.contains(newPos)) allAroundEmpty = false } if (!allAroundEmpty) { for (i in 0..3) { var allEmpty = true go[goPos + i].forEach { move -> val newPos = Pair(pos.first + move.first, pos.second + move.second) if (set.contains(newPos)) allEmpty = false } if (allEmpty) { val next = Pair(pos.first + go[goPos + i][0].first, pos.second + go[goPos + i][0].second) nextPos[pos] = next cnt[next] = cnt.getOrDefault(next, 0) + 1 break } } } } val newSet = mutableSetOf<Pair<Int, Int>>() for(pos in set) { if (nextPos.containsKey(pos)) { val next = nextPos[pos] ?: error("no next") if (cnt[next] == 1) { newSet.add(next) continue } } newSet.add(pos) } if (set == newSet) { return i } set = newSet goPos = (goPos + 1) % 4 } return -1 } val testInput = readInput("Day23_test") check(part1(testInput) == 110) check(part2(testInput) == 20) val input = readInput("Day23") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
5,567
aoc2022
Apache License 2.0
src/main/kotlin/year2021/day-11.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2021 import lib.MutableGrid2d import lib.Position import lib.aoc.Day import lib.aoc.Part import lib.math.Itertools fun main() { Day(11, 2021, PartA11(), PartB11()).run() } open class PartA11 : Part() { protected lateinit var energyLevels: MutableGrid2d<Int> override fun parse(text: String) { val content = text.split("\n").map { it.map { c -> c.digitToInt() }.toMutableList() }.toMutableList() energyLevels = MutableGrid2d(content) } override fun compute(): String { return (0..<100).sumOf { step() }.toString() } protected fun step(): Int { val moves = Position.moves(diagonals = true) val limits = energyLevels.limits val flashed = mutableSetOf<Position>() energyLevels.inc() var flashing = energyLevels.findAll { it > 9 } while (flashing.isNotEmpty()) { flashing = energyLevels.findAll { it > 9 }.filter { it !in flashed } flashed.addAll(flashing) val increasing = flashing.map { it.neighbours(moves, limits) }.flatten() increasing.forEach { energyLevels[it] += 1 } } flashed.forEach { energyLevels[it] = 0 } return flashed.size } private fun MutableGrid2d<Int>.inc() { content.forEach { for (i in it.indices) { it[i] += 1 } } } override val exampleAnswer: String get() = "1656" } class PartB11 : PartA11() { override fun compute(): String { for (steps in Itertools.count(1)) { step() if (energyLevels.all { it == 0 }) { return steps.toString() } } error("cannot be reached") } private fun MutableGrid2d<Int>.all(predicate: (Int) -> Boolean): Boolean { return content.flatten().all(predicate) } override val exampleAnswer: String get() = "195" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
2,029
Advent-Of-Code-Kotlin
MIT License
src/year2023/day06/Day.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2023.day06 import java.util.stream.LongStream import kotlin.streams.toList import year2023.solveIt fun main() { val day = "06" val expectedTest1 = 288L val expectedTest2 = 71503L fun isNotRecord(v: Long, duration: Long, record: Long) = v * (duration - v) <= record fun getIt(strings: List<String>): Long { val (durations, record) = strings.map { Regex("\\d+").findAll(it).map { foundValues -> foundValues.value.toLong() }.toList() } val validVelocities = durations.mapIndexed { raceNumber, duration -> LongStream.range(1, duration).dropWhile { v -> isNotRecord(v, duration, record[raceNumber]) }.toList() .asReversed().dropWhile { v -> isNotRecord(v, duration, record[raceNumber]) } } return validVelocities.map { it.size }.fold(1) { acc, i -> acc * i } } fun part1(input: List<String>): Long { return getIt(input) } fun part2(input: List<String>): Long { return getIt(input.map { it.replace(" ","") }) } solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2) }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
1,135
adventOfCode
Apache License 2.0
src/day08/Day08.kt
molundb
573,623,136
false
{"Kotlin": 26868}
package day08 import readInput import java.lang.Integer.max fun main() { val input = readInput(parent = "src/day08", name = "Day08_input") println(solvePartOne(input)) println(solvePartTwo(input)) } private fun solvePartTwo(input: List<String>): Int { val treeRows = mutableListOf<MutableList<Int>>() var highestScenicScore = 0 for (l in input) { val row = mutableListOf<Int>() for (c in l) { row.add(c.digitToInt()) } treeRows.add(row) } for (rowI in 1 until treeRows.lastIndex) { val row = treeRows[rowI] for (colI in 1 until row.lastIndex) { val tree = row[colI] var scenicScore = 1 // Check up for (z in rowI - 1 downTo 0) { val t = treeRows[z][colI] if (tree <= t || z == 0) { scenicScore *= rowI - z break } } // Check right for (z in colI + 1..row.lastIndex) { val t = treeRows[rowI][z] if (tree <= t || z == row.lastIndex) { scenicScore *= z - colI break } } // Check down for (z in rowI + 1..treeRows.lastIndex) { val t = treeRows[z][colI] if (tree <= t || z == treeRows.lastIndex) { scenicScore *= z - rowI break } } // Check left for (z in colI - 1 downTo 0) { val t = treeRows[rowI][z] if (tree <= t || z == 0) { scenicScore *= colI - z break } } highestScenicScore = max(highestScenicScore, scenicScore) } } return highestScenicScore } private fun solvePartOne(input: List<String>): Int { val treeRows = mutableListOf<MutableList<Int>>() var visibleTrees = 0 for (l in input) { val row = mutableListOf<Int>() for (c in l) { row.add(c.digitToInt()) } treeRows.add(row) } for ((rowI, row) in treeRows.withIndex()) { if (rowI == 0 || rowI == treeRows.lastIndex) { visibleTrees += row.size continue } for ((colI, tree) in row.withIndex()) { if (colI == 0 || colI == row.lastIndex) { visibleTrees++ continue } var blocked = 0 // Check up for (z in 0 until rowI) { val t = treeRows[z][colI] if (tree <= t) { blocked++ break } } // Check right for (z in colI + 1..row.lastIndex) { val t = treeRows[rowI][z] if (tree <= t) { blocked++ break } } // Check down for (z in rowI + 1..treeRows.lastIndex) { val t = treeRows[z][colI] if (tree <= t) { blocked++ break } } // Check left for (z in 0 until colI) { val t = treeRows[rowI][z] if (tree <= t) { blocked++ break } } if (blocked < 4) { visibleTrees++ } } } return visibleTrees }
0
Kotlin
0
0
a4b279bf4190f028fe6bea395caadfbd571288d5
3,633
advent-of-code-2022
Apache License 2.0
src/Day06.kt
hottendo
572,708,982
false
{"Kotlin": 41152}
fun main() { fun isMarker(marker: String, markerSize: Int): Boolean { /* takes a 4 character string as input and checks for duplicate chars. No duplicates -> marker found. */ if(marker.toSet().size == markerSize) { return true } return false } fun part1(input: List<String>): Int { var score = 0 val MARKER_SIZE = 4 for(item in input) { score = 0 while(score < item.length - MARKER_SIZE - 1) { val markerCandidate = item.slice(score..score + MARKER_SIZE - 1) if (isMarker(markerCandidate, MARKER_SIZE)) { break } score += 1 } } return score + MARKER_SIZE } fun part2(input: List<String>): Int { var score = 0 val MARKER_SIZE = 14 for(item in input) { score = 0 while(score < item.length - MARKER_SIZE - 1) { val markerCandidate = item.slice(score..score + MARKER_SIZE - 1) if (isMarker(markerCandidate, MARKER_SIZE)) { break } score += 1 } } return score + MARKER_SIZE } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") println("Part 1 (Test): ${part1(testInput)}") println("Part 2 (Test): ${part2(testInput)}") // check(part1(testInput) == 1) val input = readInput("Day06") println("Part 1 : ${part1(input)}") println("Part 2 : ${part2(input)}") }
0
Kotlin
0
0
a166014be8bf379dcb4012e1904e25610617c550
1,666
advent-of-code-2022
Apache License 2.0
src/main/kotlin/kLoops/examples/island.kt
Onuchin-Artem
231,309,462
false
{"Kotlin": 59394, "JavaScript": 4465}
package kLoops.examples typealias Point = Pair<Int, Int> data class World(val landPoints: Set<Point>, val height: Int, val width: Int) { fun print() { (0 until height).forEach { row -> (0 until width).forEach { column -> val value = if (landPoints.contains(Point(row, column))) 1 else 0 print("$value ") } println() } } fun neighbours(point: Point): List<Point> { val neighbours = mutableListOf<Point>() if (point.first > 0) neighbours.add(point.copy(first = point.first - 1)) if (point.first < height - 1) neighbours.add(point.copy(first = point.first + 1)) if (point.second > 0) neighbours.add(point.copy(second = point.second - 1)) if (point.second > width - 1) neighbours.add(point.copy(second = point.second + 1)) return neighbours.toList() } } fun isPerfectIsland(world: World): Boolean { val visitedPoint = mutableListOf(world.landPoints.first()) fun traverseIsland() { world.neighbours(visitedPoint.last()).forEach { neighbour -> if (world.landPoints.contains(neighbour) && !visitedPoint.contains(neighbour)) { visitedPoint.add(neighbour) traverseIsland() } } } traverseIsland() return visitedPoint.containsAll(world.landPoints) } val memmoization = mutableMapOf<World, Int>() fun findNumberOfSwitches(world: World, path: List<World>): Int { memmoization[world] = -1 if (memmoization[world]?: -1 > 0 ) { return memmoization[world]!! } val numberOfSwitches = if (isPerfectIsland(world)) { 0 } else { 1 + world.landPoints.flatMap { point -> world.neighbours(point).map { neighbour -> world.copy(landPoints = world.landPoints - point + neighbour) }.filter {newWorld -> !path.contains(newWorld) }.map { newWorld -> val sw = findNumberOfSwitches(newWorld, path + world) sw } }.min()!! } memmoization.put(world, numberOfSwitches) return numberOfSwitches } fun main() { val worldArray = listOf( listOf(0, 1, 0), listOf(0, 0, 1), listOf(1, 0, 0) ) val height = worldArray.size val width = worldArray[0].size val landPoints = (0 until height).flatMap { row -> (0 until width).flatMap { column -> if (worldArray[row][column] == 1) listOf(Point(row, column)) else listOf() } }.toSet() val world = World(landPoints, height, width) world.print() println("Fuck ${findNumberOfSwitches(world, listOf())}") println("Fuck ${findNumberOfSwitches(world, listOf())}") }
0
Kotlin
1
10
ee076b3ca539e8d5c7abc60f310b9624ba187dbf
2,785
k-Loops
MIT License
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day25/Day25.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day25 import eu.janvdb.aocutil.kotlin.readLines const val FILENAME = "input25.txt" fun main() { val board = Board.create() var currentBoard = board var nextBoard = board.move() var step = 1 while(currentBoard != nextBoard) { currentBoard = nextBoard nextBoard = currentBoard.move() step++ } println(step) } enum class Critter(val ch: Char) { EAST('>'), SOUTH('v'); companion object { fun map(ch: Char) = values().find { it.ch == ch } } } data class Board(val height: Int, val width: Int, val map: List<Critter?>) { fun move(): Board { val newMap = map.toMutableList() fun moveOneDirection(type: Critter, nextIndex: (Int, Int) -> Int) { val toMove = mutableMapOf<Int, Int>() for (y in 0 until height) { for (x in 0 until width) { val current = index(x, y) val next = nextIndex(x, y) if (newMap[current] == type && newMap[next] == null) toMove[current] = next } } toMove.forEach { newMap[it.key] = null newMap[it.value] = type } } moveOneDirection(Critter.EAST) { x, y -> index(x + 1, y) } moveOneDirection(Critter.SOUTH) { x, y -> index(x, y + 1) } return Board(height, width, newMap) } override fun toString(): String { val result = StringBuilder() for (y in 0 until height) { for (x in 0 until width) { result.append(map[index(x, y)]?.ch ?: '.') } result.append('\n') } return result.toString() } private fun index(x: Int, y: Int) = (y + height) % height * width + (x + width) % width companion object { fun create(): Board { val lines = readLines(2021, FILENAME) val map = lines.flatMap { it.map(Critter::map) } return Board(lines.size, lines[0].length, map) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,724
advent-of-code
Apache License 2.0
src/Day20.kt
palex65
572,937,600
false
{"Kotlin": 68582}
@file:Suppress("PackageDirectoryMismatch") package day20 import readInput import kotlin.math.* fun mix(numbers: List<Long>, times: Int = 1): List<Long> { val ns = numbers.withIndex().toMutableList() repeat(times) { for (idx in 0..numbers.lastIndex) { var i = ns.indexOfFirst { it.index == idx } val n = ns[i] val pos = (n.value % (ns.size - 1)).toInt() val dif = pos.sign repeat(abs(pos)) { i = ((i + dif).mod(ns.size)).also { ns[i] = ns[it] } } ns[i] = n } } return ns.map { it.value } } fun List<Long>.sum3(): Long { val idx0 = indexOf(0) return (idx0..idx0+3000 step 1000).sumOf { get(it % size) } } fun part1(lines: List<String>): Long = mix( lines.map { it.toLong() } ).sum3() fun part2(lines: List<String>): Long = mix( lines.map { (it.toLong() * 811589153) }, 10 ).sum3() fun main() { val testInput = readInput("Day20_test") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) // 5498 println(part2(input)) // 3390007892081 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
1,155
aoc2022
Apache License 2.0
src/main/java/ir/toolki/ganmaz/classification/DataSet.kt
shahrivari
134,160,197
false
{"Kotlin": 10064}
package ir.toolki.ganmaz.classification import com.google.common.collect.HashMultiset import com.google.common.collect.Multiset import com.google.common.collect.Multisets import java.util.* class DataSet(documents: List<Document>) { private val digestedDocs: MutableList<DigestedDoc> = arrayListOf() private var df: Multiset<String> = HashMultiset.create() init { documents.forEach { TextUtils.tokenizeAndNormalize(it.body()).toSet().forEach { df.add(it) } } df = Multisets.copyHighestCountFirst(df) documents.forEach { digestedDocs.add(DigestedDoc(it, df)) } } fun size() = digestedDocs.size fun score(doc: Document): List<Pair<DigestedDoc, Double>> { val map: MutableMap<DigestedDoc, Double> = hashMapOf() val digested = DigestedDoc(doc, df) val digestedLen = Math.sqrt(digested.termScore.values.map { it -> it * it }.sum()) digestedDocs.forEach { var sumScore = 0.0 digested.termScore.forEach { term, score -> if (it.termScore.containsKey(term)) sumScore += score * it.termScore.get(term)!!.toDouble() } val itLen = Math.sqrt(it.termScore.values.map { it -> it * it }.sum()) sumScore /= (digestedLen * itLen) map.put(it, sumScore) } return map.map { it -> Pair(it.key, it.value) }.sortedBy { it -> it.second }.reversed().toList() } fun classify(doc: Document, k: Int): String { val ranked = score(doc) var labels = ranked.map { it -> it.first.doc.label }.toList() labels = labels.subList(0, Math.min(k, labels.size)) val map = labels.groupBy { it } return Collections.max(map.entries, compareBy { it.value.size }).key } companion object { fun evaluate(train: List<Document>, test: List<Document>): Double { val dataset = DataSet(train) var corrects = 0 test.forEach { val klass = dataset.classify(it, 5) if (klass == it.label) corrects++ } return corrects.toDouble() / test.size } } }
0
Kotlin
1
0
e069145faf2cd2e042368ad71b26969f2d64e041
2,187
slstest
MIT License
kotlin/2019/qualification-round/cryptopangrams/src/main/kotlin/Solution.kt
ShreckYe
345,946,821
false
null
import java.math.BigInteger fun main() { val T = readLine()!!.toInt() repeat(T) { t -> val line = readLine()!!.split(' ') val N = line[0].toBigInteger() val L = line[1].toInt() val ciphertext = readLine()!!.splitToSequence(' ')/*.filter(String::isNotEmpty)*/.map(String::toBigInteger).toList() /*assert(L == ciphertext.size) { println("Case #${t + 1}: error: sizes don't match") return@repeat }*/ println("Case #${t + 1}: ${case(N, L, ciphertext)}") } } fun case(N: BigInteger, L: Int, ciphertext: List<BigInteger>): String { val (left, right) = ciphertext.withIndex().zipWithNext().first { it.first.value != it.second.value } val leftCipherValue = left.value val commonLetterPrime = leftCipherValue.gcd(right.value) val letterPrimeText = listOf( ciphertext.subListTo(left.index + 1).asReversed() .scan(commonLetterPrime) { letterPrime, cipherValue -> cipherValue / letterPrime }.subListFrom(1) .asReversed(), listOf(commonLetterPrime), ciphertext.subListFrom(right.index) .scan(commonLetterPrime) { letterPrime, cipherValue -> cipherValue / letterPrime }.subListFrom(1) ).flatten() val letterPrimes = letterPrimeText.distinct().sorted() //assert(26 == letterPrimes.size) { return "error: the number of letter primes is ${letterPrimes.size}" } //letterPrimes.forEach { assert(it <= N) { return "error: a number $it greater than N = $N" } } val primeToLetter = (letterPrimes zip UPPERCASE_LETTERS).toMap() return letterPrimeText.map(primeToLetter::get).joinToString("") } fun <E> List<E>.subListFrom(fromIndex: Int): List<E> = subList(fromIndex, size) fun <E> List<E>.subListTo(toIndex: Int): List<E> = subList(0, toIndex) val UPPERCASE_LETTERS = 'A'..'Z' // Copied from library inline fun <T, R> List<T>.scan(initial: R, operation: (acc: R, T) -> R): List<R> { val estimatedSize = size if (estimatedSize == 0) return listOf(initial) val result = ArrayList<R>(estimatedSize + 1).apply { add(initial) } var accumulator = initial for (element in this) { accumulator = operation(accumulator, element) result.add(accumulator) } return result } /* inline fun assert(value: Boolean, lazyMessage: () -> Any) { if (!value) { val message = lazyMessage() throw AssertionError(message) } }*/
0
Kotlin
1
1
743540a46ec157a6f2ddb4de806a69e5126f10ad
2,458
google-code-jam
MIT License
src/main/kotlin/Day01.kt
brigham
573,127,412
false
{"Kotlin": 59675}
fun main() { fun solve(input: List<String>, n: Int = 1): List<Int> { val calHeap = descendingHeap<Int>() input.asSequence() .chunkedBy { it.isNotBlank() } .map { block -> block.sumOf { it.toInt() } } .forEach { calHeap.add(it) } return (0 until n).map { calHeap.remove() }.toList() } fun part1(input: List<String>): Int { return solve(input)[0] } fun part2(input: List<String>): Int { return solve(input, 3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 25000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b87ffc772e5bd9fd721d552913cf79c575062f19
764
advent-of-code-2022
Apache License 2.0
src/main/day14/Part1.kt
ollehagner
572,141,655
false
{"Kotlin": 80353}
package day14 import common.Direction import common.Direction.* import common.Grid import common.Point import common.Vector import day14.CaveContent.* import readInput import java.util.function.Predicate val SAND_SOURCE_POINT = Point(500,0) fun main() { val cave = parseInput(readInput("day14/input.txt")) val yLimit = cave.max().y + 1 do { var noOverflow = pourSand(cave) { point -> point.y > yLimit } } while(noOverflow) val restingSandUnits = cave.values().filter { it == SAND }.count() println("Day 14 part 1. Units of sand resting: $restingSandUnits") } fun parseInput(input: List<String>): Grid<CaveContent> { val rocks = input .map { row -> row.split(" -> ") .map { it.split(",").let { values -> Point(values[0].toInt(), values[1].toInt()) } } .windowed(2, 1) .flatMap { (start, end) -> Vector(start, end).allPoints() } }.flatten() return Grid(rocks, ROCK) } fun pourSand(cave: Grid<CaveContent>, stopCondition: Predicate<Point>): Boolean { var sandUnitPosition = SAND_SOURCE_POINT var directionToMove: Direction do { if(stopCondition.test(sandUnitPosition)) return false directionToMove = listOf(UP, UP_LEFT, UP_RIGHT, NONE) .first { direction -> !cave.hasValue(sandUnitPosition.move(direction)) } sandUnitPosition = sandUnitPosition.move(directionToMove) } while(directionToMove != NONE) cave.set(sandUnitPosition, SAND) return true } enum class CaveContent(val symbol: Char) { ROCK('#'), AIR('.'), SAND('o'), SAND_SOURCE('+') }
0
Kotlin
0
0
6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1
1,632
aoc2022
Apache License 2.0
src/main/kotlin/adventofcode/PuzzleDay03.kt
MariusSchmidt
435,574,170
false
{"Kotlin": 28290}
package adventofcode import java.io.File class PuzzleDay03(significantBits: Int) { private val histogramSize = significantBits * 2 fun readGammaAndEpsilon(input: File): Pair<Int, Int> = input.useLines { bitsSequence -> val gammaBits = bitsSequence.deriveBitmask(true) val gamma = gammaBits.convertBitsToInt() val epsilon = gammaBits.flipBitmask().convertBitsToInt() gamma to epsilon } private fun Sequence<String>.deriveBitmask(mostCommonMode: Boolean) = calculateHistogramPerBitPosition() .collectBitmaskFromHistogram(mostCommonMode) private fun Sequence<String>.calculateHistogramPerBitPosition(): IntArray = fold(IntArray(histogramSize)) { histogram, bitString -> bitString.toCharArray().forEachIndexed { index, bit -> val histogramPos = if ('0' == bit) 2 * index else 2 * index + 1 histogram[histogramPos]++ } histogram } private fun IntArray.collectBitmaskFromHistogram(mostCommonMode: Boolean): CharArray = asIterable().windowed(2, 2).map { when (mostCommonMode) { true -> if (it[1] >= it[0]) '1' else '0' false -> if (it[1] < it[0]) '1' else '0' } }.toCharArray() private fun CharArray.flipBitmask(): CharArray = map { if (it == '0') '1' else '0' }.toCharArray() private fun CharArray.convertBitsToInt(): Int = fold(0) { int, bit -> val bitValue = if ('0' == bit) 0 else 1 int * 2 + bitValue } fun readOxygenScrubberRatings(input: File): Int = readRatingForMode(input, true) fun readCO2ScrubberRatings(input: File): Int = readRatingForMode(input, false) fun readLifeSupportRating(file: File) = readOxygenScrubberRatings(file) * readCO2ScrubberRatings(file) private fun readRatingForMode(input: File, mostCommonMode: Boolean) = input.useLines { bitsSequence -> var filteredNumbers = bitsSequence.toList() var bitmask = filteredNumbers.asSequence().deriveBitmask(mostCommonMode) for (bitPosition in bitmask.indices) { filteredNumbers = filteredNumbers.filter { it[bitPosition] == bitmask[bitPosition] } if (filteredNumbers.count() == 1) break bitmask = filteredNumbers.asSequence().deriveBitmask(mostCommonMode) } filteredNumbers }.first().toCharArray().convertBitsToInt() }
0
Kotlin
0
0
2b7099350fa612cb69c2a70d9e57a94747447790
2,526
adventofcode2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/d16/d16b.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d16 import readInput import java.util.PriorityQueue data class Node(val valve: Valve, val time: Int, val flow: Int, val opened: Set<Valve>, val pression: Int, val opening : Boolean) : Comparable<Node> { private fun score(): Float = (pression-(31-time)*flow)/time.toFloat() override fun compareTo(other: Node): Int = score().compareTo(other.score()) override fun toString(): String { return "Node(${valve.name}, time=$time, flow=$flow, pression=$pression, opening=$opening), opened=${opened.map { it.name }}" } } fun part1b(input: List<String>): Int { readFile(input) val queue = PriorityQueue<Node>() queue.add(Node(valves["AA"]!!, 1, 0, setOf(), 0, false)) while (queue.isNotEmpty()) { val start = queue.poll() if (start.time > 30) return start.pression if (start.opening) { queue.add(Node( start.valve, start.time + 1, start.flow, start.opened, start.pression - start.flow, false )) } else { if (start.time < 30 && start.valve.flow > 0 && start.valve !in start.opened) { queue.add( Node( start.valve, start.time + 1, start.flow + start.valve.flow, start.opened.plus(start.valve), start.pression - start.flow, true ) ) } for (next in start.valve.next) { queue.add( Node( valves[next]!!, start.time + 1, start.flow, start.opened, start.pression - start.flow, false ) ) } } } return 0 } fun main() { val input = readInput("d16/test") //val input = readInput("d16/input1") println(part1b(input)) //println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
2,138
aoc2022
Creative Commons Zero v1.0 Universal
kotlin/src/katas/kotlin/leetcode/twosum/TwoSum.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}
@file:Suppress("DuplicatedCode") package katas.kotlin.leetcode.twosum import nonstdlib.printed import datsok.shouldEqual import org.junit.Test import kotlin.random.Random /** * https://leetcode.com/problems/two-sum */ class TwoSum { @Test fun `find indices of numbers that add up to the target number (with loops)`() { arrayOf(2, 7, 11, 15).twoSum_it(target = 9) shouldEqual Pair(0, 1) arrayOf(2, 9, 0, 7).twoSum_it(target = 9) shouldEqual Pair(0, 3) arrayOf(5, 5).twoSum_it(target = 10) shouldEqual Pair(0, 1) arrayOf(10, -15).twoSum_it(target = -5) shouldEqual Pair(0, 1) arrayOf(-1, -2).twoSum_it(target = -3) shouldEqual Pair(0, 1) randomArray(seed = 123, size = 100).printed().twoSum_it(target = 10) shouldEqual Pair(0, 8) // 0.until(100).forEach { // randomArray(seed = 123, size = 10_000_000, min = -1000, max = 1000).twoSum_it(target = 10) // } } @Test fun `find indices of numbers that add up to the target number (with binary search)`() { arrayOf(2, 7, 11, 15).twoSum_bs(target = 9) shouldEqual Pair(0, 1) arrayOf(2, 9, 0, 7).twoSum_bs(target = 9) shouldEqual Pair(2, 1) arrayOf(5, 5).twoSum_bs(target = 10) shouldEqual Pair(0, 1) arrayOf(10, -15).twoSum_bs(target = -5) shouldEqual Pair(1, 0) arrayOf(-1, -2).twoSum_bs(target = -3) shouldEqual Pair(1, 0) randomArray(seed = 123, size = 100).printed().twoSum_bs(target = 10) shouldEqual Pair(43, 82) // 0.until(100).forEach { // randomArray(seed = 123, size = 10_000_000, min = -1000, max = 1000).twoSum_bs(target = 10) // } } private fun randomArray(seed: Int, size: Int, min: Int = 0, max: Int = 10): Array<Int> { val random = Random(seed) return Array(size) { random.nextInt(min, max) } } private fun Array<Int>.twoSum_it(target: Int): Pair<Int, Int> { indices.forEach { i1 -> (i1 + 1).until(size).forEach { i2 -> if (this[i1] + this[i2] == target) return Pair(i1, i2) } } error("no solution") } private fun Array<Int>.twoSum_bs(target: Int): Pair<Int, Int> { val sortedArray = sortedArray() sortedArray.indices.forEach { i1 -> val item1 = sortedArray[i1] val item2 = target - item1 val i2 = sortedArray.binarySearch(element = item2, fromIndex = i1 + 1) if (i2 > i1) return Pair(indexOf(item1), lastIndexOf(item2)) } error("no solution") } private fun Array<Int>.twoSum_set(target: Int): Pair<Int, Int> { val set = indices.toSet() indices.forEach { i1 -> (i1 + 1).until(size).forEach { i2 -> if (this[i1] + this[i2] == target) return Pair(i1, i2) } } error("no solution") } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,877
katas
The Unlicense
src/array/LeetCode240.kt
Alex-Linrk
180,918,573
false
null
package array /** * 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性: 每行的元素从左到右升序排列。 每列的元素从上到下升序排列。 示例: 现有矩阵 matrix 如下: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] 给定 target = 5,返回 true。 给定 target = 20,返回 false。 */ class Solution240 { fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean { if (matrix.isEmpty() || matrix[0].isEmpty()) return false if (target < matrix[0][0] || target > matrix[matrix.lastIndex][matrix[matrix.lastIndex].lastIndex]) return false var x = matrix[0].lastIndex var y = matrix.lastIndex while (matrix[y][x] > target) { if (x - 1 >= 0) x-- if (y - 1 >= 0) y-- } if (matrix[y][x] == target) return true for (start_y in y + 1..matrix.lastIndex) { for (start_x in 0..x) { if (matrix[start_y][start_x] == target) return true } } for (start_y in 0..y) { for (start_x in x..matrix[0].lastIndex) { if (matrix[start_y][start_x] == target) return true } } return false } } fun main() { // val l1 = intArrayOf(1, 4, 7, 11, 15) // val l2 = intArrayOf(2, 5, 8, 12, 19) // val l3 = intArrayOf(3, 6, 9, 16, 22) // val l4 = intArrayOf(10, 13, 14, 17, 24) // val l5 = intArrayOf(18, 21, 23, 26, 30) // val matrix = arrayOf(l1, l2, l3, l4, l5) // println(Solution240().searchMatrix(matrix, 26)) println(Solution240().searchMatrix(Array(1) { intArrayOf(-1, 3) }, 3)) println(Solution240().searchMatrix(Array(2) { intArrayOf(it + 1) }, 2)) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
1,852
LeetCode
Apache License 2.0
src/main/kotlin/days/Day22.kt
nuudles
316,314,995
false
null
package days class Day22 : Day(22) { override fun partOne(): Any { val (player1, player2) = inputString.split("\n\n").let { decks -> decks.first().split("\n").drop(1).map { it.toLong() }.toMutableList() to decks.last().split("\n").drop(1).map { it.toLong() }.toMutableList() } while (player1.count() > 0 && player2.count() > 0) { if (player1.first() > player2.first()) { player1.addAll(listOf(player1.removeFirst(), player2.removeFirst())) } else { player2.addAll(listOf(player2.removeFirst(), player1.removeFirst())) } } val winner = if (player1.count() > 0) player1 else player2 return winner .withIndex() .fold(0L) { sum, entry -> sum + entry.value * (winner.count() - entry.index) } } private fun playGame( decks: Pair<MutableList<Int>, MutableList<Int>> ): Pair<List<Int>, List<Int>> { val configurations = mutableSetOf<Pair<List<Int>, List<Int>>>() while (decks.first.count() > 0 && decks.second.count() > 0) { if (configurations.contains(decks)) { // Player 1 wins decks.first.addAll(decks.second) decks.second.clear() break } configurations.add(decks) val cards = decks.first.removeFirst() to decks.second.removeFirst() if (decks.first.count() >= cards.first && decks.second.count() >= cards.second) { playGame( decks.first.subList(0, cards.first).toMutableList() to decks.second.subList(0, cards.second).toMutableList() ).apply { if (first.count() > second.count()) { decks.first.addAll(listOf(cards.first, cards.second)) } else { decks.second.addAll(listOf(cards.second, cards.first)) } } } else { if (cards.first > cards.second) { decks.first.addAll(listOf(cards.first, cards.second)) } else { decks.second.addAll(listOf(cards.second, cards.first)) } } } return decks } override fun partTwo(): Any { val decks = inputString .split("\n\n").let { decks -> decks.first().split("\n").drop(1).map { it.toInt() }.toMutableList() to decks.last().split("\n").drop(1).map { it.toInt() }.toMutableList() } val winner = playGame(decks).run { if (first.count() > 0) first else second } return winner .withIndex() .fold(0) { sum, entry -> sum + entry.value * (winner.count() - entry.index) } } }
0
Kotlin
0
0
5ac4aac0b6c1e79392701b588b07f57079af4b03
2,889
advent-of-code-2020
Creative Commons Zero v1.0 Universal
2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day12.kt
codelicia
627,407,402
false
{"Kotlin": 49578, "PHP": 554, "Makefile": 293}
package com.codelicia.advent2021 import java.util.Stack class Day12(mapOfTheRemainingCaves: List<String>) { data class Vertex(val label: String) private val map = mapOfTheRemainingCaves .map { cave -> cave.split("-") } .map { cave -> cave.first() to cave.last() } private val graph = buildMap<Vertex, MutableList<Vertex>> { for (i in map) { this.putIfAbsent(Vertex(i.first), mutableListOf()) this.putIfAbsent(Vertex(i.second), mutableListOf()) this[Vertex(i.first)]!!.add(Vertex(i.second)) this[Vertex(i.second)]!!.add(Vertex(i.first)) } } fun part1(): Int = solve(fun(_) = true) fun part2(): Int { return solve(fun(visited: HashMap<String, Int>): Boolean { return visited.toMap().filter { it.value > 1 }.filter { it.key.lowercase() == it.key }.values.isNotEmpty() }) } private fun solve(predicate: (HashMap<String, Int>) -> Boolean): Int { val queue = Stack<Vertex>() queue.add(Vertex("start")) val results = mutableListOf<String>() while (queue.isNotEmpty()) bfs(graph, predicate, queue, results, "start") return results.size } private fun bfs( graph: Map<Vertex, MutableList<Vertex>>, predicate: (HashMap<String, Int>) -> Boolean, queue: Stack<Vertex>, results: MutableList<String>, path: String, visited: HashMap<String, Int> = hashMapOf() ) { val vertex = queue.pop() if (vertex.label == "end") { results.add(path) return } val count = visited.getOrElse(vertex.label) { 0 } visited[vertex.label] = count + 1 val neighbours = graph[vertex]!! for (neighbour in neighbours) { if (neighbour.label != "start") { val satisfiesPredicate = predicate(visited) if (neighbour.label.lowercase() == neighbour.label && visited.contains(neighbour.label) && satisfiesPredicate == true) continue queue.add(neighbour) bfs(graph, predicate, queue, results, "$path,${neighbour.label}", HashMap(visited)) } } } }
2
Kotlin
0
0
df0cfd5c559d9726663412c0dec52dbfd5fa54b0
2,232
adventofcode
MIT License
src/shreckye/coursera/algorithms/StronglyConnectedComponents.kt
ShreckYe
205,871,625
false
{"Kotlin": 72136}
package shreckye.coursera.algorithms import java.util.* import kotlin.collections.ArrayList data class Scc(val sccLeader: Int, val sccVertices: SimpleIntArrayList) private inline fun searchSccs( numVertices: Int, graph: IndexGraph, inverseGraph: IndexGraph, beforeSearchingScc: (Int) -> Unit, crossinline searchingScc: (Int, Int) -> Unit, afterSearchingScc: (Int) -> Unit ) { // First DFS val orderedVertices = Stack<Int>() inverseGraph.dfsAll { orderedVertices.push(it) } // Second DFS val searchedVertices = BitSet(numVertices) while (orderedVertices.isNotEmpty()) { val leader = orderedVertices.pop() if (!searchedVertices[leader]) { beforeSearchingScc(leader) graph.dfs(leader, searchedVertices) { searchingScc(leader, it) } afterSearchingScc(leader) } } } fun sccLeaderAndSizesSortedBySize(numVertices: Int, graph: IndexGraph, inverseGraph: IndexGraph): List<IntPair> { val sccs = ArrayList<IntPair>() var size = Int.MIN_VALUE searchSccs(numVertices, graph, inverseGraph, { size = 0 }, { _, _ -> size++ }, { sccs.add(it to size) }) sccs.sortByDescending(IntPair::second) return sccs } fun sccsSortedBySize(numVertices: Int, graph: IndexGraph, inverseGraph: IndexGraph): List<Scc> { val sccs = ArrayList<Scc>() var sccVertices: SimpleIntArrayList? = null searchSccs(numVertices, graph, inverseGraph, { sccVertices = SimpleIntArrayList() }, { leader, vertex -> sccVertices!!.add(vertex) }, { sccs.add(Scc(it, sccVertices!!)) }) sccs.sortByDescending { it.sccVertices.size } return sccs }
0
Kotlin
1
2
1746af789d016a26f3442f9bf47dc5ab10f49611
1,685
coursera-stanford-algorithms-solutions-kotlin
MIT License
src/Day10.kt
xNakero
572,621,673
false
{"Kotlin": 23869}
object Day10 { fun part1(): Int = with(readInput()) { generateSequence(20) { it + 40 }.take(6).toList() .map { (1 + this.take(it - 1).sum()) * it } }.sum() fun part2() { val registryByTime = readInput().let { commands -> commands.indices.map { command -> commands.take(command).sumOf { it } + 1 } } List(registryByTime.size) { index -> if (registryByTime[index].let { it - 1..it + 1 }.any { it == (index % 40) }) { "#" } else { "." } }.chunked(40).forEach { println(it.joinToString("")) } } private fun readInput(): List<Int> = readInput("day10") .flatMap { line -> line.split(" ") .let { if (it[0] == "addx") listOf(0, it[1].toInt()) else listOf(0) } } } fun main() { println(Day10.part1()) Day10.part2() }
0
Kotlin
0
0
c3eff4f4c52ded907f2af6352dd7b3532a2da8c5
963
advent-of-code-2022
Apache License 2.0
implementation/src/main/kotlin/io/github/tomplum/aoc/game/cards/CamelCards.kt
TomPlum
724,225,748
false
{"Kotlin": 141244}
package io.github.tomplum.aoc.game.cards class CamelCards(cardsData: List<String>) { private val hands = cardsData.associate { line -> val (hands, bid) = line.trim().split(" ") hands to bid } private val suits = listOf('A', 'K', 'Q', 'J', 'T') + (9 downTo 2).map { number -> number.toString()[0] } private val suitsWithJoker = listOf('A', 'K', 'Q', 'T') + (9 downTo 2).map { number -> number.toString()[0] } + 'J' fun calculateTotalWinnings(): Int { val ordered = hands.entries.fold(mutableMapOf<HandType, List<String>>()) { acc, (hand, bid) -> val handType = parseHandType(hand) val list = acc.computeIfAbsent(handType) { _ -> mutableListOf() }.toMutableList() list.add(hand) acc[handType] = list acc } return ordered.map { if (it.value.size > 1) { val sorted = it.value.sortedWith { o1, o2 -> val (stronger) = Pair(o1, o2).compareHands() if (o1 == stronger) { -1 } else if (o2 == stronger) { 1 } else { 0 } } Pair(it.key, sorted) } else { it.toPair() } }.toMap().entries .sortedByDescending { it.key.strength } .flatMap { it.value } .reversed() .mapIndexed { i, hand -> (i + 1) to hand } .sumOf { (rank, hand) -> rank * hands[hand]!!.toInt() } } fun calculateTotalWinningsWithJoker(): Int = hands.entries .fold(mutableMapOf<HandType, List<String>>()) { acc, (hand) -> val handType = if (hand.any { it == 'J' }) hand.determineBestJokerHand() else parseHandType(hand) val list = acc.computeIfAbsent(handType) { _ -> mutableListOf() }.toMutableList() list.add(hand) acc[handType] = list acc }.map { if (it.value.size > 1) { val sorted = it.value.sortedWith { o1, o2 -> val (stronger) = Pair(o1, o2).compareHandsWithJoker() if (o1 == stronger) { -1 } else if (o2 == stronger) { 1 } else { 0 } } Pair(it.key, sorted) } else { it.toPair() } } .toMap() .entries .sortedByDescending { it.key.strength } .flatMap { it.value } .reversed() .mapIndexed { i, hand -> (i + 1) to hand } .sumOf { (rank, hand) -> rank * hands[hand]!!.toInt() } fun parseHandType(hand: String): HandType { if (hand.all { card -> card == hand[0] }) { return HandType.FIVE_OF_A_KIND } else if (hand.isNofKind(4)) { return HandType.FOUR_OF_A_KIND } else if (hand.groupBy { it }.filter { it.value.size > 1 }.size == 1 && hand.groupBy { it }.values.size == 3) { return HandType.THREE_OF_A_KIND } else if (hand.isNofKind(3) && hand.isNofKind(2)) { return HandType.FULL_HOUSE } else if (hand.groupBy { it }.count { it.value.size == 2 } == 2) { return HandType.TWO_PAIR } else if (hand.groupBy { it }.count { it.value.size == 2 } == 1) { return HandType.ONE_PAIR } else if (hand.toList().distinct().size == hand.length) { return HandType.HIGH_CARD } else { return HandType.NO_HAND } } private fun String.isNofKind(n: Int) = this.groupBy { it }.any { it.value.size == n } // TODO: Refactor into strategies private fun Pair<String, String>.compareHands(): List<String> { (0..<this.first.length).forEach { i -> if (this.first[i] != this.second[i]) { val firstStrength = suits.reversed().indexOf(this.first[i]) val secondStrength = suits.reversed().indexOf(this.second[i]) return if (firstStrength > secondStrength) { listOf(this.first, this.second) } else { listOf(this.second, this.first) } } } return listOf(this.first, this.second) } private fun Pair<String, String>.compareHandsWithJoker(): List<String> { (0..<this.first.length).forEach { i -> if (this.first[i] != this.second[i]) { val firstStrength = suitsWithJoker.reversed().indexOf(this.first[i]) val secondStrength = suitsWithJoker.reversed().indexOf(this.second[i]) return if (firstStrength > secondStrength) { listOf(this.first, this.second) } else { listOf(this.second, this.first) } } } return listOf(this.first, this.second) } private fun jokerHands(hands: List<String>): List<String> { return hands.flatMap { hand -> if (hand.any { card -> card == 'J' }) { val permutations = suitsWithJoker.dropLast(1).map { suit -> hand.replaceFirst('J', suit) } jokerHands(permutations) } else { hands } } } private fun String.determineBestJokerHand() = jokerHands(listOf(this)) .map { hand -> parseHandType(hand) } .maxBy { handType -> handType.strength } }
0
Kotlin
0
1
d1f941a3c5bacd126177ace6b9f576c9af07fed6
5,665
advent-of-code-2023
Apache License 2.0
src/main/kotlin/Day20.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package aoc import java.lang.Math.floorMod fun solve20A(input: List<String>): Long { val numbers = input.mapIndexed { index, s -> Number(s.toLong(), index) }.toMutableList() numbers.mix() return numbers.extractGroveCoordinates() } fun solve20B(input: List<String>): Long { val decryptionKey = 811589153L val numbers = input.mapIndexed { index, s -> Number(s.toLong() * decryptionKey, index) }.toMutableList() repeat(10) { numbers.mix() } return numbers.extractGroveCoordinates() } data class Number( val value: Long, val originalPosition: Int, ) fun MutableList<Number>.mix() { for (i in this.indices) { val current = this.find { it.originalPosition == i }!! val currentIndex = this.indexOf(current) if (current.value == 0L) continue val targetIndex = wrapIndex(current.value + currentIndex, this.size - 1) this.remove(current) this.add(targetIndex, current) } } fun wrapIndex(moveBy: Long, length: Int) = floorMod(moveBy, length) fun List<Number>.extractGroveCoordinates(): Long { val zeroIndex = this.indexOfFirst { it.value == 0L } return listOf(1000L, 2000L, 3000L).sumOf { this[wrapIndex( it + zeroIndex, this.size )].value } }
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
1,294
advent-of-code-2022
Apache License 2.0
2015/src/main/kotlin/com/koenv/adventofcode/Day19.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode class Day19(input: CharSequence) { private val replacements: Map<String, List<String>> private val lexer: Lexer init { this.replacements = input.lines().map { val parts = it.split(" => ") parts[0] to parts[1] }.groupBy { it.first }.mapValues { it.value.map { it.second } } this.lexer = Lexer(replacements.keys.distinct().toList()) } public fun parse(input: String): List<Lexer.Token> { return lexer.parse(input) } public fun getPossibilities(input: String): List<String> { val tokens = parse(input) val possibilities = arrayListOf<String>() tokens.filter { it.type == Lexer.TokenType.REPLACEMENT }.forEach { token -> replacements[token.text]!!.forEach { replacement -> val text = StringBuilder() tokens.forEach { if (it == token) { text.append(replacement) } else { text.append(it.text) } } possibilities.add(text.toString()) } } return possibilities.distinct() } public fun fromElectronTo(input: String): Int { var target = input var steps = 0 while (target != "e") { replacements.forEach { entry -> entry.value.forEach { if (target.contains(it)) { target = target.substring(0, target.lastIndexOf(it)) + entry.key + target.substring(target.lastIndexOf(it) + it.length) steps++ } } } } return steps } class Lexer(private val replacementPossibilities: List<String>) { private var replacementMaxLength: Int init { this.replacementMaxLength = replacementPossibilities.map { it.length }.max()!! } public fun parse(input: String): List<Token> { val tokens = arrayListOf<Token>() var position = 0 while (position < input.length) { var nowPosition = position val it = StringBuilder() it.append(input[position]) nowPosition++ while (!replacementPossibilities.contains(it.toString()) && it.length < replacementMaxLength && nowPosition < input.length) { it.append(input[nowPosition]) nowPosition++ } if (replacementPossibilities.contains(it.toString())) { tokens.add(Token(position, TokenType.REPLACEMENT, it.toString())) position = nowPosition } else { tokens.add(Token(position, TokenType.TEXT, input[position].toString())) position++ } } return tokens } data class Token(val position: Int, val type: TokenType, val text: String) enum class TokenType { TEXT, REPLACEMENT } } }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
3,213
AdventOfCode-Solutions-Kotlin
MIT License
src/main/kotlin/g2001_2100/s2048_next_greater_numerically_balanced_number/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2001_2100.s2048_next_greater_numerically_balanced_number // #Medium #Math #Backtracking #Enumeration // #2023_06_23_Time_138_ms_(100.00%)_Space_33.4_MB_(100.00%) class Solution { fun nextBeautifulNumber(n: Int): Int { val arr = intArrayOf(0, 1, 2, 3, 4, 5, 6) val select = BooleanArray(7) val d = if (n == 0) 1 else Math.log10(n.toDouble()).toInt() + 1 return solve(1, n, d, 0, select, arr) } private fun solve(i: Int, n: Int, d: Int, sz: Int, select: BooleanArray, arr: IntArray): Int { if (sz > d + 1) { return Int.MAX_VALUE } if (i == select.size) { return if (sz >= d) make(0, n, sz, select, arr) else Int.MAX_VALUE } var ans = solve(i + 1, n, d, sz, select, arr) select[i] = true ans = Math.min(ans, solve(i + 1, n, d, sz + i, select, arr)) select[i] = false return ans } private fun make(cur: Int, n: Int, end: Int, select: BooleanArray, arr: IntArray): Int { if (end == 0) { return if (cur > n) cur else Int.MAX_VALUE } var ans = Int.MAX_VALUE for (j in 1 until arr.size) { if (!select[j] || arr[j] == 0) { continue } --arr[j] ans = Math.min(make(10 * cur + j, n, end - 1, select, arr), ans) ++arr[j] } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,426
LeetCode-in-Kotlin
MIT License
src/Day22.kt
wgolyakov
572,463,468
false
null
import javafx.geometry.Point3D import javafx.scene.transform.Rotate import javafx.scene.transform.Transform import kotlin.math.min import kotlin.math.roundToInt fun main() { val right = 0 val down = 1 val left = 2 val up = 3 val positionToMove = mapOf( right to (1 to 0), down to (0 to 1), left to (-1 to 0), up to (0 to -1), ) fun parseMap(input: List<String>): List<String> { val maxSize = input.take(input.size - 2).maxOf { it.length } val map = mutableListOf<String>() for (line in input.take(input.size - 2)) map.add(line.padEnd(maxSize, ' ')) return map } fun move1(map: List<String>, x: Int, y: Int, dx: Int, dy: Int): Pair<Int, Int> { var x2 = x + dx var y2 = y + dy if (x2 < 0) x2 = map[y].length - 1 if (x2 >= map[y].length) x2 = 0 if (y2 < 0) y2 = map.size - 1 if (y2 >= map.size) y2 = 0 return x2 to y2 } fun part1(input: List<String>): Int { val map = parseMap(input) val path = input.last() var facing = right var x = map[0].indexOf('.') var y = 0 var p = 0 while (p < path.length) { when (path[p]) { 'L' -> { if (facing == right) facing = up else facing-- p++ } 'R' -> { if (facing == up) facing = right else facing++ p++ } else -> { val l = path.indexOf('L', p).let { if (it == -1) path.length else it } val r = path.indexOf('R', p).let { if (it == -1) path.length else it } val next = min(l, r) val distance = path.substring(p ,next).toInt() for (m in 0 until distance) { val (dx, dy) = positionToMove[facing]!! var t = move1(map, x, y, dx, dy) while (map[t.second][t.first] == ' ') t = move1(map, t.first, t.second, dx, dy) if (map[t.second][t.first] == '.') { x = t.first y = t.second } else { break } } p = next } } } return (y + 1) * 1000 + (x + 1) * 4 + facing } class Face(val cx: Int, val cy: Int) { val neighbours = Array(4) { this } var vector = Point3D(0.0, 0.0, 0.0) var transform: Transform = Rotate() var facing = IntArray(4) { it } } val reverse = mapOf( right to left, down to up, left to right, up to down, ) val rotation = mapOf( right to Rotate(-90.0, Rotate.Y_AXIS), left to Rotate(90.0, Rotate.Y_AXIS), up to Rotate(-90.0, Rotate.X_AXIS), down to Rotate(90.0, Rotate.X_AXIS), ) fun rotateTransform(transform: Transform, facing: Int) = transform.createConcatenation(rotation[facing]!!) val epsilon = 1.0e-5 fun round(p: Point3D): Point3D { val x = if (-epsilon < p.x && p.x < epsilon) 0.0 else p.x val y = if (-epsilon < p.y && p.y < epsilon) 0.0 else p.y val z = if (-epsilon < p.z && p.z < epsilon) 0.0 else p.z return Point3D(x, y, z) } fun findStraightNeighboursBfs(faces: Map<Pair<Int, Int>, Face>, face0: Face) { val queue = ArrayDeque<Face>() queue.addLast(face0) face0.vector = Point3D(0.0, 0.0, -1.0) while (queue.isNotEmpty()) { val curr = queue.removeFirst() for ((facing, delta) in positionToMove) { val (dx, dy) = delta if (curr.neighbours[facing] !== curr) continue val neighbour = faces[curr.cx + dx to curr.cy + dy] ?: continue val revFacing = reverse[facing]!! curr.neighbours[facing] = neighbour curr.facing[facing] = facing neighbour.neighbours[revFacing] = curr neighbour.transform = rotateTransform(curr.transform, facing) neighbour.vector = round(neighbour.transform.transform(face0.vector)) neighbour.facing[revFacing] = revFacing queue.addLast(neighbour) } } } fun findOtherNeighbours(faces: Map<Pair<Int, Int>, Face>, face0: Face) { for (face in faces.values) { for ((facing, _) in positionToMove) { if (face.neighbours[facing] !== face) continue val neighbourTransform = rotateTransform(face.transform, facing) val neighbourVector = round(neighbourTransform.transform(face0.vector)) val neighbour = faces.values.find { it.vector == neighbourVector }!! face.neighbours[facing] = neighbour } } } fun findNeighboursFacing(faces: Map<Pair<Int, Int>, Face>) { for (face in faces.values) { for ((facing, _) in positionToMove) { val neighbour = face.neighbours[facing] val neighbourFacing = neighbour.neighbours.withIndex().find { n -> n.value === face }!!.index face.facing[facing] = reverse[neighbourFacing]!! neighbour.facing[neighbourFacing] = reverse[facing]!! } } } fun getPointOnBorder(p: Point3D, facing: Int): Pair<Double, Double> { return when (facing) { right -> -1.0 to p.y left -> 1.0 to p.y up -> p.x to 1.0 down -> p.x to -1.0 else -> error("Unknown facing: $facing") } } fun initFaces(map: List<String>, width: Int, height: Int, a: Int): Map<Pair<Int, Int>, Face> { val cubeWidth = width / a val cubeHeight = height / a val faces = mutableMapOf<Pair<Int, Int>, Face>() for (cy in 0 until cubeHeight) for (cx in 0 until cubeWidth) if (map[cy * a][cx * a] != ' ') faces[cx to cy] = Face(cx, cy) return faces } fun part2(input: List<String>): Int { val map = parseMap(input) val width = map[0].length val height = map.size val a = min(width, height) / 3 val faces = initFaces(map, width, height, a) val x0 = map[0].indexOf('.') val face0 = faces[x0 / a to 0]!! findStraightNeighboursBfs(faces, face0) findOtherNeighbours(faces, face0) findNeighboursFacing(faces) val a2 = (a.toDouble() - 1) / 2 val path = input.last() var facing = right var x = map[0].indexOf('.') var y = 0 var p = 0 while (p < path.length) { when (path[p]) { 'L' -> { if (facing == right) facing = up else facing-- p++ } 'R' -> { if (facing == up) facing = right else facing++ p++ } else -> { val l = path.indexOf('L', p).let { if (it == -1) path.length else it } val r = path.indexOf('R', p).let { if (it == -1) path.length else it } val next = min(l, r) val distance = path.substring(p ,next).toInt() for (m in 0 until distance) { val (dx, dy) = positionToMove[facing]!! var x2 = x + dx var y2 = y + dy var facing2 = facing if (x2 !in 0 until width || y2 !in 0 until height || map[y2][x2] == ' ') { val cx = x / a val cy = y / a val face = faces[cx to cy]!! val face2 = face.neighbours[facing] facing2 = face.facing[facing] val x1 = (x % a).toDouble() / a2 - 1 val y1 = (y % a).toDouble() / a2 - 1 val p3d = face.transform.transform(Point3D(x1, y1, -1.0)) val pNearBorder = face2.transform.createInverse().transform(p3d) val (xBorder, yBorder) = getPointOnBorder(pNearBorder, facing2) x2 = face2.cx * a + ((xBorder + 1) * a2).roundToInt() y2 = face2.cy * a + ((yBorder + 1) * a2).roundToInt() } if (map[y2][x2] == '.') { x = x2 y = y2 facing = facing2 } else { break } } p = next } } } return (y + 1) * 1000 + (x + 1) * 4 + facing } val testInput = readInput("Day22_test") check(part1(testInput) == 6032) check(part2(testInput) == 5031) val input = readInput("Day22") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
789a2a027ea57954301d7267a14e26e39bfbc3c7
7,194
advent-of-code-2022
Apache License 2.0
src/main/kotlin/wtf/log/xmas2021/day/day13/Day13.kt
damianw
434,043,459
false
{"Kotlin": 62890}
package wtf.log.xmas2021.day.day13 import com.google.common.collect.HashBasedTable import com.google.common.collect.Table import wtf.log.xmas2021.Day import wtf.log.xmas2021.util.collect.set import wtf.log.xmas2021.util.math.Point import java.io.BufferedReader object Day13 : Day<Input, Int, String> { override fun parseInput(reader: BufferedReader): Input { val points = mutableSetOf<Point>() val iterator = reader.lineSequence().iterator() while (iterator.hasNext()) { val line = iterator.next() if (line.isEmpty()) break val split = line.split(',') check(split.size == 2) points += Point(split[0].toInt(), split[1].toInt()) } val folds = mutableListOf<Fold>() while (iterator.hasNext()) { val line = iterator.next() check(line.startsWith("fold along ")) val split = line.substring(11).split('=') check(split.size == 2) folds += Fold( axis = when (val axis = split[0]) { "x" -> Fold.Axis.X "y" -> Fold.Axis.Y else -> error("Unknown fold axis: $axis") }, value = split[1].toInt(), ) } return Input(points, folds) } override fun part1(input: Input): Int { return solve(input.dotPositions, input.folds.take(1)).size() } override fun part2(input: Input): String { return solve(input.dotPositions, input.folds).dump() } private fun solve(dotPositions: Set<Point>, folds: List<Fold>): Table<Int, Int, Unit> { @Suppress("UNCHECKED_CAST") val table = HashBasedTable.create<Int, Int, Unit>() as Table<Int, Int, Unit> for (point in dotPositions) { table[point.x, point.y] = Unit } for (fold in folds) { for (point in table.cellSet().toSet()) { when (fold.axis) { Fold.Axis.X -> if (point.rowKey >= fold.value) { table.remove(point.rowKey, point.columnKey) table[(2 * fold.value) - point.rowKey, point.columnKey] = Unit } Fold.Axis.Y -> if (point.columnKey >= fold.value) { table.remove(point.rowKey, point.columnKey) table[point.rowKey, (2 * fold.value) - point.columnKey] = Unit } } } } return table } private fun Table<Int, Int, Unit>.dump(): String = buildString { val maxX = rowKeySet().maxOf { it } val maxY = columnKeySet().maxOf { it } append('\n') repeat(maxY + 1) { y -> repeat(maxX + 1) { x -> // Kotlin and Guava's annotations really don't get along @Suppress("SENSELESS_COMPARISON") append(if (get(x, y) != null) '#' else '.') } append('\n') } } } data class Input( val dotPositions: Set<Point>, val folds: List<Fold>, ) data class Fold( val axis: Axis, val value: Int, ) { enum class Axis { X, Y, } }
0
Kotlin
0
0
1c4c12546ea3de0e7298c2771dc93e578f11a9c6
3,244
AdventOfKotlin2021
BSD Source Code Attribution
src/main/kotlin/g0601_0700/s0648_replace_words/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0648_replace_words // #Medium #Array #String #Hash_Table #Trie #2023_02_11_Time_392_ms_(100.00%)_Space_62.4_MB_(25.00%) import java.util.function.Consumer class Solution { fun replaceWords(dictionary: List<String>, sentence: String): String { val trie = Trie() dictionary.forEach(Consumer { word: String -> trie.insert(word) }) val allWords = sentence.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (i in allWords.indices) { allWords[i] = trie.getRootForWord(allWords[i]) } return java.lang.String.join(" ", *allWords) } internal class Node { var links = arrayOfNulls<Node>(26) var isWordCompleted = false fun containsKey(ch: Char): Boolean { return links[ch.code - 'a'.code] != null } fun put(ch: Char, node: Node?) { links[ch.code - 'a'.code] = node } operator fun get(ch: Char): Node? { return links[ch.code - 'a'.code] } } internal class Trie { var root: Node = Node() fun insert(word: String) { var node: Node? = root for (i in word.indices) { if (!node!!.containsKey(word[i])) { node.put(word[i], Node()) } node = node[word[i]] } node!!.isWordCompleted = true } fun getRootForWord(word: String): String { var node: Node? = root val rootWord = StringBuilder() for (i in word.indices) { if (node!!.containsKey(word[i])) { rootWord.append(word[i]) node = node[word[i]] if (node!!.isWordCompleted) { return rootWord.toString() } } else { return word } } return word } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,000
LeetCode-in-Kotlin
MIT License
src/Day12.kt
mcrispim
573,449,109
false
{"Kotlin": 46488}
import java.security.InvalidParameterException fun main() { data class Pos(val line: Int, val col: Int) data class Node(val elevation: Char, val possibleWays: List<Pos>) { var distance: Int = Int.MAX_VALUE var comeFrom: Pos? = null } fun elevationOk(input: List<String>, pos: Pos): Char { val elevation = when (input[pos.line][pos.col]) { 'S' -> 'a' 'E' -> 'z' else -> input[pos.line][pos.col] } return elevation } fun getWays(pos: Pos, input: List<String>): List<Pos> { val startLine = 0 val endLine = input.lastIndex val startCol = 0 val endCol = input[0].lastIndex val elevation = elevationOk(input, pos) fun Pos.isValid() = line in startLine..endLine && col in startCol..endCol val possibleWays = listOf( Pos(pos.line - 1, pos.col), Pos(pos.line, pos.col - 1), Pos(pos.line, pos.col + 1), Pos(pos.line + 1, pos.col) ) val ways = mutableListOf<Pos>() for (p in possibleWays) { if (p.isValid() && elevationOk(input, p) in 'a'..elevation + 1) { ways.add(p) } } return ways } fun getGrafo(input: List<String>): Map<Pos, Node> { val graph = mutableMapOf<Pos, Node>() for ((lineNumber, line) in input.withIndex()) { for (colNumber in line.indices) { val pos = Pos(lineNumber, colNumber) graph[pos] = Node(elevationOk(input, pos), getWays(pos, input)) } } return graph } fun getDistance(graph: Map<Pos, Node>, start: Pos, end: Pos): Int { val unvisetedNodes = mutableListOf<Pos>() graph[start]?.distance = 0 unvisetedNodes.add(start) while (unvisetedNodes.isNotEmpty()) { val current = unvisetedNodes.removeAt(0) for (pos in graph[current]!!.possibleWays) { if (graph[pos]!!.distance > graph[current]!!.distance + 1) { graph[pos]!!.distance = graph[current]!!.distance + 1 graph[pos]!!.comeFrom = current unvisetedNodes.add(pos) } } } return graph[end]!!.distance } fun getStartEnd(input: List<String>): Pair<Pos, Pos> { var start: Pos? = null var end: Pos? = null for ((l, line) in input.withIndex()) { for ((c, elevation) in line.withIndex()) { if (elevation == 'S') start = Pos(l, c) if (elevation == 'E') end = Pos(l, c) } } if (start != null && end != null) return Pair(start, end) else throw InvalidParameterException("Não encontrado o <S>tart ou o <E>nd.") } fun part1(input: List<String>): Int { val graph = getGrafo(input) val (start, end) = getStartEnd(input) return getDistance(graph, start, end) } fun getStarts(input: List<String>): List<Pos> { val starts = mutableListOf<Pos>() for ((l, line) in input.withIndex()) { for ((c, elevation) in line.withIndex()) { if (elevation == 'S' || elevation == 'a') starts.add(Pos(l, c)) } } return starts.toList() } fun part2(input: List<String>): Int { val graph = getGrafo(input) val (_, end) = getStartEnd(input) val starts = getStarts(input) var minDistance = Int.MAX_VALUE for (start in starts) { val distance = getDistance(graph, start, end) if (distance < minDistance) { minDistance = distance } } return minDistance } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5fcacc6316e1576a172a46ba5fc9f70bcb41f532
4,154
AoC2022
Apache License 2.0
src/heap/LeetCode378.kt
Alex-Linrk
180,918,573
false
null
package heap import kotlin.math.max /** * 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。 *请注意,它是排序后的第k小元素,而不是第k个元素。 * *示例: * *matrix = [ *[ 1, 5, 9], *[10, 11, 13], *[12, 13, 15] *], *k = 8, * *返回 13。 *说明: *你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n2 。 */ class LeetCode378 { fun kthSmallest(matrix: Array<IntArray>, k: Int): Int { val heapArray = IntArray(matrix[0].size * matrix.size) for (y in 0 until matrix.size) { for (x in 0 until matrix[y].size) { heapArray[matrix[0].size * y + x] = matrix[y][x] } } val begin = heapArray.lastIndex / 2 for (start in begin downTo 0) maxHeapify(heapArray, start, heapArray.lastIndex) var size = 0 while (size < heapArray.size) { swip(heapArray, 0, heapArray.lastIndex - size) size++ maxHeapify(heapArray, 0, heapArray.lastIndex - size) } return heapArray[k - 1] } fun maxHeapify(nums: IntArray, index: Int, len: Int) { val left = index * 2 val right = left + 1 var max = left if (left > len) return if (right <= len && nums[left] < nums[right]) { max = right } if (nums[max] > nums[index]) { swip(nums, max, index) maxHeapify(nums, max, len) } } fun swip(nums: IntArray, x: Int, y: Int) { val temp = nums[x] nums[x] = nums[y] nums[y] = temp } } /** * [[1,3,5],[6,7,12],[11,14,14]] 1 [[1,5,9],[10,11,13],[12,13,15]] */ fun main() { println( LeetCode378().kthSmallest( arrayOf( intArrayOf(1, 3, 5), intArrayOf(6, 7, 12), intArrayOf(11, 14, 14) ) , 1 ) ) println( LeetCode378().kthSmallest( arrayOf( intArrayOf(1,5,9), intArrayOf(10,11,13), intArrayOf(12,13,15) ) , 8 ) ) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
2,201
LeetCode
Apache License 2.0
src/jvmMain/kotlin/day09/initial/Day09.kt
liusbl
726,218,737
false
{"Kotlin": 109684}
package day09.initial import util.add import util.set import java.io.File fun main() { // solvePart1() // Solution: 2175229206, time: 09:56 solvePart2() // Solution: 942, time: 10:06 } fun solvePart2() { // val input = File("src/jvmMain/kotlin/day09/input/input_part1_test.txt") val input = File("src/jvmMain/kotlin/day09/input/input.txt") val lines = input.readLines() val numberLines = lines.map { it.split(" ").map { it.trim().toLong() } } val result = numberLines.sumOf { line -> println(line.joinToString(" ")) var newLineList = listOf(line) while (!newLineList.last().all { it == 0L }) { val newLine = newLineList.last().zipWithNext { first, second -> second - first } newLineList = newLineList.add(newLine) println(newLine) } println(newLineList) val reversed = newLineList.reversed() val updatedList = reversed.foldIndexed(reversed) { index, acc, list -> if (index == 0) { acc.set(index, list.add(index = 0, value = 0)) } else { acc.set(index, list.add(index = 0, value = list.first() - acc[index - 1].first())) } } println(updatedList.reversed()) println() updatedList.last().first() } println(result) } fun solvePart1() { // val input = File("src/jvmMain/kotlin/day09/input/input_part1_test.txt") val input = File("src/jvmMain/kotlin/day09/input/input.txt") val lines = input.readLines() val numberLines = lines.map { it.split(" ").map { it.trim().toLong() } } val result = numberLines.sumOf { line -> println(line.joinToString(" ")) var newLineList = listOf(line) while (!newLineList.last().all { it == 0L }) { val newLine = newLineList.last().zipWithNext { first, second -> second - first } newLineList = newLineList.add(newLine) println(newLine) } println(newLineList) val reversed = newLineList.reversed() val updatedList = reversed.foldIndexed(reversed) { index, acc, list -> if (index == 0) { acc.set(index, list.add(0)) } else { acc.set(index, list.add(list.last() + acc[index - 1].last())) } } println(updatedList) println() updatedList.last().last() } println(result) }
0
Kotlin
0
0
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
2,509
advent-of-code
MIT License
src/y2015/Day24.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2015 import util.generateTakes import util.product import util.readInput object Day24 { private fun parse(input: List<String>): List<Long> { return input.map { it.toLong() } } fun part1(input: List<String>, compartments: Int): Long { val weights = parse(input) val total = weights.sum() val perCompartment = total / compartments println("total: $total") println("per compartment: $perCompartment") var passengerSize = 1 var passengerCandidates: List<List<Long>> while (true) { passengerCandidates = generateTakes(weights, passengerSize).filter { it.sum() == perCompartment }.toList() if (passengerCandidates.isNotEmpty()) { break } else { passengerSize++ } } return passengerCandidates.minOf { it.product() } } } fun main() { val testInput = """ 1 2 3 4 5 7 8 9 10 11 """.trimIndent().split("\n") println("------Tests------") println(Day24.part1(testInput, 3)) println(Day24.part1(testInput, 4)) println("------Real------") val input = readInput("resources/2015/day24") println(Day24.part1(input, 3)) println(Day24.part1(input, 4)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,396
advent-of-code
Apache License 2.0
2023/src/main/kotlin/Day06.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import kotlin.math.ceil import kotlin.math.floor import kotlin.math.pow import kotlin.math.sqrt object Day06 { private data class Race(val time: Long, val distance: Long) fun part1(input: String): Long { val (times, distances) = input.splitNewlines().map { it.splitWhitespace().drop(1).toLongList() } val races = times.zip(distances) { time, distance -> Race(time, distance) } return races .map { it.calculateNumWaysToWin() } .reduce(Long::times) } fun part2(input: String): Long { val (time, distance) = input.splitNewlines().map { it.splitWhitespace().drop(1).joinToString("").toLong() } return Race(time, distance).calculateNumWaysToWin() } private fun Race.quadraticRoots(): Pair<Double, Double> { val a = -1.0 val b = time.toDouble() val c = -distance.toDouble() val start = (-b + sqrt(b.pow(2) - (4*a*c))) / (2 * a) val end = (-b - sqrt(b.pow(2) - (4*a*c))) / (2 * a) return start to end } private fun Race.calculateNumWaysToWin(): Long { val (start, end) = quadraticRoots() // Adjust numbers sliiiiightly to account for less than and greater than (in case of int roots) return floor(end - .0001).toLong() - ceil(start + .0001).toLong() + 1 } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
1,242
advent-of-code
MIT License