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/aoc2023/Day16.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2023 import utils.Vertex import utils.checkEquals import utils.readInputAs2DCharArray fun main(): Unit = with(Day16) { part1(testInput) .checkEquals(46) part1(input) .checkEquals(6816) // .sendAnswer(part = 1, day = "16", year = 2023) part2(testInput).checkEquals(51) part2(input) .checkEquals(8163) // .sendAnswer(part = 2, day = "16", year = 2023) } object Day16 { enum class Dir { up, down, left, right } infix fun Vertex.to(d: Dir) = VertexToDir(this, d) data class VertexToDir(val vertex: Vertex, val dir: Dir) operator fun Array<CharArray>.get(v: Vertex) = this.getOrNull(v.y)?.getOrNull(v.x) ?: '#' fun part1(input: Array<CharArray>): Int = input.countEnergized(Vertex(0, 0) to Dir.right) fun part2(input: Array<CharArray>): Int { val cols = input[0].size val rows = input.size val possibleStart = buildList<VertexToDir> { for (i in 0..<rows) { for (j in 0..<cols) { if (i in 1..rows - 2 && j in 1..cols - 2) continue if (i == 0) add(Vertex(j, i) to Dir.down) else if (i == rows - 1) add(Vertex(j, i) to Dir.up) if (j == 0) add(Vertex(j, i) to Dir.right) else if (j == cols - 1) add(Vertex(j, i) to Dir.left) } } } return possibleStart.maxOf { input.countEnergized(it) } } fun Array<CharArray>.countEnergized(start: VertexToDir): Int { val energized = hashSetOf<VertexToDir>() val heads = ArrayDeque(listOf(start)) while (heads.any()) { val curr = heads.removeFirst() val c = this[curr.vertex] if (c == '#' || curr in energized) { continue } energized.add(curr) val (nextPoint, nextSplitPointOrNull) = when (c) { '.' -> curr.getNextVertexToDir() to null '/' -> { val newDir = when (curr.dir) { Dir.right -> Dir.up Dir.down -> Dir.left Dir.left -> Dir.down Dir.up -> Dir.right } val new = (curr.vertex to newDir).getNextVertexToDir() new to null } '\\' -> { val newDir = when (curr.dir) { Dir.up -> Dir.left Dir.right -> Dir.down Dir.left -> Dir.up Dir.down -> Dir.right } val new = (curr.vertex to newDir).getNextVertexToDir() new to null } '-' -> { var splitPoint: VertexToDir? = null val newDir = when (curr.dir) { Dir.left, Dir.right -> curr.dir Dir.down, Dir.up -> { splitPoint = (curr.vertex to Dir.right).getNextVertexToDir() Dir.left } } val new = (curr.vertex to newDir).getNextVertexToDir() new to splitPoint } '|' -> { var splitPoint: VertexToDir? = null val newDir = when (curr.dir) { Dir.down, Dir.up -> curr.dir Dir.left, Dir.right -> { splitPoint = (curr.vertex to Dir.down).getNextVertexToDir() Dir.up } } val new = (curr.vertex to newDir).getNextVertexToDir() new to splitPoint } else -> error("not supported") } heads.addFirst(nextPoint) if (nextSplitPointOrNull != null) heads.addLast(nextSplitPointOrNull) } return energized.distinctBy { it.vertex }.count() } private fun VertexToDir.getNextVertexToDir(): VertexToDir { val v = vertex val dir = dir return when (dir) { Dir.up -> v.up() Dir.down -> v.down() Dir.left -> v.left() Dir.right -> v.right() } to dir } val input get() = readInputAs2DCharArray("Day16", "aoc2023") val testInput get() = readInputAs2DCharArray("Day16_test", "aoc2023") }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
4,755
Kotlin-AOC-2023
Apache License 2.0
src/main/kotlin/adventOfCode2023/Day05.kt
TetraTsunami
726,140,343
false
{"Kotlin": 80024}
package adventOfCode2023 import util.* @Suppress("unused") class Day05(input: String, context: RunContext = RunContext.PROD) : Day(input, context) { data class RangeMap(val destStart: Long, val srcStart: Long, val rangeLen: Long) { val srcEnd = srcStart + rangeLen val destEnd = destStart + rangeLen fun isInRange(index: Long): Boolean { return index >= srcStart && index < srcStart + rangeLen } fun hasOverlap(seedRange: SeedRange): Boolean { return seedRange.start < srcEnd && seedRange.end > srcStart } fun getDestIndex(srcIndex: Long): Long { return destStart + (srcIndex - srcStart) } fun getSrcIndex(destIndex: Long): Long { return srcStart + (destIndex - destStart) } fun getDestRange(seedrng: SeedRange): SeedRange { // effectively finding overlap of two ranges // find starting index of overlap val start = if (seedrng.start < srcStart) srcStart else seedrng.start // find ending index of overlap val end = if (seedrng.end > srcEnd) srcEnd else seedrng.end // return new range with overlap return SeedRange(getDestIndex(start), end - start) } fun getDestIndexRemainder(seedrng: SeedRange): List<SeedRange> { // finding non-overlap of two ranges // could be 0, 1, or 2 ranges val overlap = this.getDestRange(seedrng) var overlapStart = this.getSrcIndex(overlap.start) var overlapEnd = this.getSrcIndex(overlap.end) val remainder = mutableListOf<SeedRange>() if (seedrng.start < overlapStart) { remainder.add(SeedRange(seedrng.start, overlapStart - seedrng.start)) } if (seedrng.end > overlapEnd) { remainder.add(SeedRange(overlapEnd, seedrng.end - overlapEnd)) } return remainder } } data class SeedRange(val start: Long, val length: Long) { val end = start + length fun isInRange(index: Long): Boolean { return index >= start && index < start + length } fun getDestIndex(srcIndex: Long): Long { return start + (srcIndex - start) } fun toPair(): Pair<Long, Long> { return Pair(start, length) } } override fun solve() { run { val seeds = lines[0].split(" ").subList(1, lines[0].split(" ").size).map { it.toLong() } var i = 3 var lastSeeds = seeds.toMutableList() var thisSeeds = mutableListOf<Long>() while (i < lines.size) { val line = lines[i] if (line == "") { i += 2 thisSeeds.addAll(lastSeeds) lastSeeds = thisSeeds.toMutableList() thisSeeds.clear() continue } val words = line.split(" ") val map = RangeMap( words[0].toLong(), words[1].toLong(), words[2].toLong() ) val temp = lastSeeds.toList() for (seed in temp) { if (map.isInRange(seed)) { thisSeeds.add(map.getDestIndex(seed)) lastSeeds.remove(seed) } } i++ } thisSeeds.addAll(lastSeeds) a(thisSeeds.min()) } // pairs of (start, length) val seeds: List<SeedRange> = lines[0].split(" ").subList(1, lines[0].split(" ").size).map { it.toLong() } .chunked(2).map { SeedRange(it[0], it[1]) } var i = 3 var lastSeeds = seeds.toMutableList() var thisSeeds = mutableListOf<SeedRange>() while (i < lines.size) { val line = lines[i] if (line == "") { i += 2 thisSeeds.addAll(lastSeeds) lastSeeds = thisSeeds.toMutableList() thisSeeds.clear() continue } val words = line.split(" ") val map = RangeMap( words[0].toLong(), words[1].toLong(), words[2].toLong() ) val temp = lastSeeds.toList() for (seedRange in temp) { lastSeeds.remove(seedRange) if (map.hasOverlap(seedRange)) { thisSeeds.add(map.getDestRange(seedRange)) lastSeeds.addAll(map.getDestIndexRemainder(seedRange)) } else { lastSeeds.add(seedRange) } } i++ } thisSeeds.addAll(lastSeeds) a(thisSeeds.minBy { it.start }.start) } }
0
Kotlin
0
0
78d1b5d1c17122fed4f4e0a25fdacf1e62c17bfd
4,982
AdventOfCode2023
Apache License 2.0
src/main/kotlin/org/dreambroke/Day2.kt
DreamBroke
729,562,380
false
{"Kotlin": 5424}
package org.dreambroke object Day2 : BaseProblem() { data class CubeCounts(val red: Int, val green: Int, val blue: Int) private fun handleLine(line: String, action: (CubeCounts) -> Unit) { val cubesGroupStr = line.substringAfter(":").trim() val cubesGroup = cubesGroupStr.split(";") var maxRedCubesCount = 0 var maxGreenCubesCount = 0 var maxBlueCubesCount = 0 for (cubes in cubesGroup) { val singleCubeList = cubes.split(",") for (cube in singleCubeList) { val singleCube = cube.trim().split(" ") val count = singleCube[0].toInt() val color = singleCube[1] when (color) { "red" -> if (count > maxRedCubesCount) maxRedCubesCount = count "green" -> if (count > maxGreenCubesCount) maxGreenCubesCount = count "blue" -> if (count > maxBlueCubesCount) maxBlueCubesCount = count } } } action(CubeCounts(maxRedCubesCount, maxGreenCubesCount, maxBlueCubesCount)) } @JvmStatic fun main(args: Array<String>) { solvePartA() solvePartB() } override fun partA(input: String): String { val totalBlueCubes = 14 val totalGreenCubes = 13 val totalRedCubes = 12 val lines = Utils.splitStringByLine(input) var result = 0 for (line in lines) { handleLine(line) { cubeCounts -> if (cubeCounts.blue <= totalBlueCubes && cubeCounts.green <= totalGreenCubes && cubeCounts.red <= totalRedCubes) { val gameId = line.substringBefore(":").trim().split(" ")[1].toInt() result += gameId } } } return result.toString() } override fun partB(input: String): String { val lines = Utils.splitStringByLine(input) var result = 0 for (line in lines) { handleLine(line) { cubeCounts -> result += cubeCounts.blue * cubeCounts.green * cubeCounts.red } } return result.toString() } }
0
Kotlin
0
0
5269cf089d4d367e69cf240c0acda568db6e4b22
2,184
AdventOfCode2023
Apache License 2.0
src/test/kotlin/com/igorwojda/integer/pyramidgenerator/Solution.kt
igorwojda
159,511,104
false
{"Kotlin": 254856}
package com.igorwojda.integer.pyramidgenerator // iterative solution private object Solution1 { private fun generatePyramid(n: Int): List<String> { val list = mutableListOf<String>() val numColumns = (n * 2) - 1 (0 until n).forEach { row -> val numHashes = (row * 2) + 1 val numSpaces = numColumns - numHashes var sideString = "" repeat(numSpaces / 2) { sideString += " " } var hashString = "" repeat(numHashes) { hashString += "#" } list.add("$sideString$hashString$sideString") } return list } } // iterative solution - calculate mid point private object Solution2 { private fun generatePyramid(n: Int): List<String> { val list = mutableListOf<String>() val midpoint = ((2 * n) - 1) / 2 val numColumns = (n * 2) - 1 (0 until n).forEach { row -> var rowStr = "" (0 until numColumns).forEach { column -> rowStr += if (midpoint - row <= column && midpoint + row >= column) { "#" } else { " " } } list.add(rowStr) } return list } } // simplified iterative solution private object Solution3 { private fun generatePyramid(n: Int): MutableList<String> { val list = mutableListOf<String>() val maxRowLen = n * 2 - 1 for (i in 1..n) { val rowLen = i * 2 - 1 val sideString = " ".repeat((maxRowLen - rowLen) / 2) val hashString = "#".repeat(rowLen) list.add("$sideString$hashString$sideString") } return list } }
9
Kotlin
225
895
b09b738846e9f30ad2e9716e4e1401e2724aeaec
1,735
kotlin-coding-challenges
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1319/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1319 /** * LeetCode page: [1319. Number of Operations to Make Network Connected](https://leetcode.com/problems/number-of-operations-to-make-network-connected/); */ class Solution { /* Complexity: * Time O(E) and Space O(E) where E is the size of connections; */ fun makeConnected(n: Int, connections: Array<IntArray>): Int { val numCables = connections.size if (numCables < n - 1) return -1 val adjacent = adjacent(n, connections) val numConnectedComponents = numConnectedComponents(n, adjacent) return numConnectedComponents - 1 } private fun adjacent(numComputers: Int, connections: Array<IntArray>): List<List<Int>> { val adjacent = List<MutableList<Int>>(numComputers) { mutableListOf() } for ((u, v) in connections) { adjacent[u].add(v) adjacent[v].add(u) } return adjacent } private fun numConnectedComponents(numComputers: Int, adjacent: List<List<Int>>): Int { var numComponents = 0 val visited = hashSetOf<Int>() val computers = 0 until numComputers for (computer in computers) { if (computer in visited) { continue } numComponents++ visitAllReachableComputers(computer, adjacent, visited) } return numComponents } private fun visitAllReachableComputers( sourceComputer: Int, adjacent: List<List<Int>>, visited: MutableSet<Int> ) { if (sourceComputer in visited) { return } visited.add(sourceComputer) for (label in adjacent[sourceComputer]) { visitAllReachableComputers(label, adjacent, visited) } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,802
hj-leetcode-kotlin
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions49.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round0 /** * 求第n个丑数 */ fun test49() { val number = 1500 println("第${number}个丑数是:${getUglyNumber1(number)}") println("第${number}个丑数是:${getUglyNumber2(number)}") } // 逐个判断法 fun getUglyNumber1(n: Int): Int { require(n > 0) { "输入的数字必须是正整数" } var i = 1 var number = 1 while (i <= n) { if (number.isUgly()) i++ number++ } return --number } //判断是否是丑数 fun Int.isUgly(): Boolean { var x = this while (x % 2 == 0) x = x shr 1 while (x % 3 == 0) x /= 3 while (x % 5 == 0) x /= 5 return x == 1 } // 累计法 fun getUglyNumber2(n: Int): Int { require(n > 0) { "输入的数字必须是正整数" } // 判断三个数中的最小值 fun min(x: Int, y: Int, z: Int): Int { val temp = if (x < y) x else y return if (temp < z) temp else z } val uglyNumbers = IntArray(n) uglyNumbers[0] = 1 var uglyIndex = 0 var multiply2 = 0 var multiply3 = 0 var multiply5 = 0 while (uglyIndex + 1 < n) { val value2 = uglyNumbers[multiply2] shl 1 val value3 = uglyNumbers[multiply3] * 3 val value5 = uglyNumbers[multiply5] * 5 uglyNumbers[++uglyIndex] = min(value2, value3, value5) if (uglyNumbers[uglyIndex] == value2) multiply2++ if (uglyNumbers[uglyIndex] == value3) multiply3++ if (uglyNumbers[uglyIndex] == value5) multiply5++ } return uglyNumbers[n-1] }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,406
Algorithm
Apache License 2.0
src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0918_maximum_sum_circular_subarray // #Medium #Array #Dynamic_Programming #Divide_and_Conquer #Queue #Monotonic_Queue // #Dynamic_Programming_I_Day_5 #2023_04_16_Time_339_ms_(86.96%)_Space_46.4_MB_(56.52%) class Solution { private fun kadane(nums: IntArray, sign: Int): Int { var currSum = Int.MIN_VALUE var maxSum = Int.MIN_VALUE for (i in nums) { currSum = sign * i + currSum.coerceAtLeast(0) maxSum = maxSum.coerceAtLeast(currSum) } return maxSum } fun maxSubarraySumCircular(nums: IntArray): Int { if (nums.size == 1) { return nums[0] } var sumOfArray = 0 for (i in nums) { sumOfArray += i } val maxSumSubarray = kadane(nums, 1) val minSumSubarray = kadane(nums, -1) * -1 return if (sumOfArray == minSumSubarray) { maxSumSubarray } else { maxSumSubarray.coerceAtLeast(sumOfArray - minSumSubarray) } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,038
LeetCode-in-Kotlin
MIT License
src/test/kotlin/com/eugenenosenko/coding/problems/arrays/pair_with_sum_x/FindPairWithSumXSolution.kt
eugenenosenko
303,183,289
false
null
package com.eugenenosenko.coding.problems.arrays.pair_with_sum_x fun findPairSolution(arr: IntArray, sum: Int): IntArray { // sort array first from smallest to largest // you'll end up with an array [0,1,2,3,5,6] arr.sort() // create two pointers var left = 0 var right = arr.size - 1 while (left < right) { val rightV = arr[right] val leftV = arr[left] when { // for example, sum is 7, result should be 1, 6 // upon first iteration you'll compare numbers 0, 6 // this will land you on the second case and increment left counter by one // next iteration will be between 1 and 6 which is what we're looking for // right value is too large leftV + rightV > sum -> right-- // left value is too small leftV + rightV < sum -> left++ // just right! leftV + rightV == sum -> return intArrayOf(leftV, rightV) } } return intArrayOf() } fun findPairOnceSolution(arr: IntArray, sum: Int): IntArray { val visited = HashSet<Int>() for (v in arr) { // calculate different, i.e. 17 - 7 = 10 val tmp = sum - v if (visited.contains(tmp)) { return intArrayOf(tmp, v) } visited.add(v) } return intArrayOf() }
0
Kotlin
0
0
673cc3ef6aa3c4f55b9156d14d64d47588610600
1,355
coding-problems
MIT License
leetcode/src/array/Offer03.kt
zhangweizhe
387,808,774
false
null
package array fun main() { // 剑指 Offer 03. 数组中重复的数字 // https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/ println(findRepeatNumber2(intArrayOf(2, 3, 1, 0, 2, 5, 3))) } fun findRepeatNumber(nums: IntArray): Int { val list = HashSet<Int>(nums.size) for (i in nums) { if (list.contains(i)) { return i }else { list.add(i) } } return -1 } fun findRepeatNumber1(nums: IntArray): Int { var i = 0 while (i < nums.size) { while (nums[i] == i) { i++ } if (nums[i] == nums[nums[i]]) { return nums[i] } /** *注意不能写为:因为 nums[nums[i]] 是依赖 nums[i] 的,所以 nums[i] 要晚于 nums[nums[i]] 被修改 * val tmp = nums[i] * nums[i] = nums[nums[i]] * nums[nums[i]] = tmp */ val tmp = nums[nums[i]] nums[nums[i]] = nums[i] nums[i] = tmp i++ } return -1 } fun findRepeatNumber2(nums: IntArray): Int { var i = 0 while (i < nums.size) { while (nums[i] == i) { i++ } if (nums[i] == nums[nums[i]]) { return nums[i] } val tmp = nums[nums[i]] nums[nums[i]] = nums[i] nums[i] = tmp } return -1 }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,377
kotlin-study
MIT License
src/main/kotlin/com/github/shmvanhouten/adventofcode/day10/InstructionCentral.kt
SHMvanHouten
109,886,692
false
{"Kotlin": 616528}
package com.github.shmvanhouten.adventofcode.day10 import com.github.shmvanhouten.adventofcode.day10.DestinationType.OUTPUT class InstructionCentral(private val botDispatch: BotDispatch = BotDispatch()) { private val VALUE = "value" fun findBotThatComparesValues(instructions: String, firstValue: Int, secondValue: Int): Int? { carryOutInstructions(instructions) return botDispatch.bots.find { it.pickupLog?.lowChip == firstValue && it.pickupLog?.highChip == secondValue }?.pickupLog?.botNumber } fun findTheChipsInOutputsMultiplied(instructions: String, outputsToMultiply: List<Int>): Int? { carryOutInstructions(instructions) return botDispatch.outputs.filter { getValuesForOutputsNeeded(it, outputsToMultiply) }.map { it.chip }.reduce{ acc: Int, chip: Int -> acc * chip } } private fun getValuesForOutputsNeeded(output: Output, outputsToMultiply: List<Int>): Boolean = outputsToMultiply.any { it == output.outputNumber } private fun carryOutInstructions(instructions: String) { val (pickupInstructions, sortingInstructions) = instructions.split("\n") .map { it.split(" ") }.partition { it[0] == VALUE } botDispatch.bots = buildBots(sortingInstructions) botDispatch.outputs = buildOutputs(sortingInstructions) botDispatch.givePickupOrdersToBots(pickupInstructions.map { buildPickupOrderFromInstruction(it) }) } private fun buildOutputs(sortingInstructions: List<List<String>>): List<Output> = sortingInstructions.mapNotNull { buildOutputFromInstruction(it) }.flatMap { it } private fun buildOutputFromInstruction(rawInstruction: List<String>): List<Output>? { val listOfOutputs = mutableListOf<Output>() if (getDestinationType(rawInstruction[5]) == OUTPUT) { listOfOutputs.add(Output(rawInstruction[6].toInt())) } if (getDestinationType(rawInstruction[10]) == OUTPUT) { listOfOutputs.add(Output(rawInstruction[11].toInt())) } return listOfOutputs } private fun buildPickupOrderFromInstruction(rawInstruction: List<String>): PickupOrder { val chip = rawInstruction[1].toInt() val destination = Destination(getDestinationType(rawInstruction[4]), rawInstruction[5].toInt()) return PickupOrder(destination, chip) } private fun buildBots(sortingInstructions: List<List<String>>): List<SortingBot> = sortingInstructions.map { buildBotFromInstruction(it) } private fun buildBotFromInstruction(rawInstruction: List<String>): SortingBot { val botNumber = rawInstruction[1].toInt() val lowChipDestination = Destination(getDestinationType(rawInstruction[5]), rawInstruction[6].toInt()) val highChipDestination = Destination(getDestinationType(rawInstruction[10]), rawInstruction[11].toInt()) val instruction = Instruction(lowChipDestination, highChipDestination) return SortingBot(instruction, botDispatch, botNumber) } }
0
Kotlin
0
0
a8abc74816edf7cd63aae81cb856feb776452786
3,048
adventOfCode2016
MIT License
src/main/kotlin/_0018_4Sum.kt
ryandyoon
664,493,186
false
null
// https://leetcode.com/problems/4sum fun fourSum(nums: IntArray, target: Int): List<List<Int>> { val targetLong = target.toLong() val quardruplets = mutableSetOf<Quardruplet>() nums.sort() for (first in 0..nums.lastIndex - 3) { for (second in first + 1..nums.lastIndex - 2) { var third = second + 1 var fourth = nums.lastIndex while (third < fourth) { val sum = nums[first].toLong() + nums[second] + nums[third] + nums[fourth] if (sum == targetLong) { quardruplets.add(Quardruplet(nums[first], nums[second], nums[third], nums[fourth])) third++ fourth-- } else if (sum > target) { fourth-- } else { third++ } } } } return quardruplets.toList().map { listOf(it.first, it.second, it.third, it.fourth) } } data class Quardruplet(val first: Int, val second: Int, val third: Int, val fourth: Int)
0
Kotlin
0
0
7f75078ddeb22983b2521d8ac80f5973f58fd123
1,061
leetcode-kotlin
MIT License
src/main/kotlin/days/Day22.kt
mstar95
317,305,289
false
null
package days class Day22 : Day(22) { override fun partOne(): Any { val (deck1, deck2) = prepareInput(inputString) val winner = play(deck1.toMutableList(), deck2.toMutableList()) return winner.foldIndexed(0) { idx, acc, elem -> acc + elem * (winner.size - idx) } } override fun partTwo(): Any { val (deck1, deck2) = prepareInput(inputString) val winner = recursivePlay(deck1.toMutableList(), deck2.toMutableList()) return winner.second.foldIndexed(0) { idx, acc, elem -> acc + elem * (winner.second.size - idx) } } private fun play(deck1: MutableList<Int>, deck2: MutableList<Int>): List<Int> { var c1: Int var c2: Int while (deck1.isNotEmpty() && deck2.isNotEmpty()) { c1 = deck1.removeFirst() c2 = deck2.removeFirst() if (c1 > c2) { deck1.add(c1) deck1.add(c2) } if (c1 < c2) { deck2.add(c2) deck2.add(c1) } if (c1 == c2) { error("same cards") } } return if (deck1.isNotEmpty()) deck1 else deck2 } private fun recursivePlay(deck1: MutableList<Int>, deck2: MutableList<Int>): Pair<Int, List<Int>> { var c1: Int var c2: Int val history = mutableSetOf<Pair<MutableList<Int>, MutableList<Int>>>() while (deck1.isNotEmpty() && deck2.isNotEmpty()) { if (history.contains(deck1 to deck2)) { return 1 to deck1 } history.add(deck1 to deck2) c1 = deck1.removeFirst() c2 = deck2.removeFirst() if (c1 <= deck1.size && c2 <= deck2.size) { val res = recursivePlay(deck1.toMutableList().subList(0, c1), deck2.toMutableList().subList(0, c2)) if (res.first == 1) { deck1.add(c1) deck1.add(c2) } else { deck2.add(c2) deck2.add(c1) } continue } if (c1 > c2) { deck1.add(c1) deck1.add(c2) } if (c1 < c2) { deck2.add(c2) deck2.add(c1) } if (c1 == c2) { error("same cards") } } return if (deck1.isNotEmpty()) 1 to deck1 else 2 to deck2 } fun prepareInput(input: String) = input.split("\n\n") .map { d -> d.split("\n").drop(1).map { it.toInt() } } .let { it[0] to it[1] } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
2,674
aoc-2020
Creative Commons Zero v1.0 Universal
src/Day01.kt
Cryosleeper
572,977,188
false
{"Kotlin": 43613}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 for (value in input) { if (value.isEmpty()) { max = max(max, current) current = 0 } else { current += value.toInt() } } max = max(max, current) return max } fun part2(input: List<String>): Int { val sums = mutableListOf<Int>() var current = 0 for (value in input) { if (value.isEmpty()) { sums.add(current) current = 0 } else { current += value.toInt() } } sums.add(current) return sums.sortedDescending().subList(0, 3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 10) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a638356cda864b9e1799d72fa07d3482a5f2128e
1,054
aoc-2022
Apache License 2.0
src/main/kotlin/advent/of/code/day04/Solution.kt
brunorene
160,263,437
false
null
package advent.of.code.day04 import advent.of.code.day04.State.* import java.io.File enum class State(val match: Regex) { SHIFT(Regex(".+Guard #([0-9]+) begins shift")), SLEEP(Regex(".+:([0-9]{2})\\] falls asleep")), AWAKE(Regex(".+:([0-9]{2})\\] wakes up")) } fun commonPart(selector: (Map.Entry<Int, Array<Int>>) -> Int): Int { val guardSleep = mutableMapOf<Int, Array<Int>>() var currentGuard = 0 var asleep = 0 val lines = File("day04.txt").readLines().sorted() for (line in lines) { when { SHIFT.match matches line -> { currentGuard = SHIFT.match.find(line)?.groups!![1]!!.value.toInt() if (guardSleep[currentGuard] == null) guardSleep[currentGuard] = Array(60) { 0 } } SLEEP.match matches line -> { asleep = SLEEP.match.find(line)!!.groups[1]!!.value.toInt() } AWAKE.match matches line -> { val awake = AWAKE.match.find(line)!!.groups[1]!!.value.toInt() for (b in (asleep until awake)) guardSleep[currentGuard]!![b]++ } } } val guardMostSleep = guardSleep.maxBy(selector)!!.key return guardMostSleep * guardSleep[guardMostSleep]!! .mapIndexed { index, i -> Pair(index, i) } .maxBy { it.second }!!.first } fun part1() = commonPart { it.value.sum() } fun part2() = commonPart { it.value.max() ?: 0 }
0
Kotlin
0
0
0cb6814b91038a1ab99c276a33bf248157a88939
1,477
advent_of_code_2018
The Unlicense
year2018/src/main/kotlin/net/olegg/aoc/year2018/day17/Day17.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day17 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.D import net.olegg.aoc.utils.Directions.L import net.olegg.aoc.utils.Directions.R import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.get import net.olegg.aoc.utils.set import net.olegg.aoc.year2018.DayOf2018 /** * See [Year 2018, Day 17](https://adventofcode.com/2018/day/17) */ object Day17 : DayOf2018(17) { private val PATTERN = "(\\w)=(\\d+), \\w=(\\d+)..(\\d+)".toRegex() private val WATER = setOf('~', '|') private val STOP = setOf('~', '#', null) override fun first(): Any? { val (xs, ys, map) = fill() return ys.sumOf { y -> xs.count { x -> map[y][x] in WATER } } } override fun second(): Any? { val (xs, ys, map) = fill() return ys.sumOf { y -> xs.count { x -> map[y][x] == '~' } } } private fun fill(): Triple<IntRange, IntRange, List<MutableList<Char>>> { val start = Vector2D(500, 0) val clay = lines .mapNotNull { line -> PATTERN.matchEntire(line)?.let { match -> val (direction, valueRaw, rangeFromRaw, rangeToRaw) = match.destructured return@mapNotNull if (direction == "x") { valueRaw.toInt()..valueRaw.toInt() to rangeFromRaw.toInt()..rangeToRaw.toInt() } else { rangeFromRaw.toInt()..rangeToRaw.toInt() to valueRaw.toInt()..valueRaw.toInt() } } } val minX = minOf(start.x - 1, clay.minOf { it.first.first - 1 }) val maxX = maxOf(start.x + 1, clay.maxOf { it.first.last + 1 }) val minY = minOf(start.y, clay.minOf { it.second.first }) val maxY = maxOf(start.y, clay.maxOf { it.second.last }) val bbox = Pair( Vector2D(minX, minY), Vector2D(maxX, maxY), ) val map = List(maxY - minY + 1) { MutableList(maxX - minX + 1) { '.' } } clay.forEach { line -> line.second.forEach { yRaw -> line.first.forEach { xRaw -> map[Vector2D(xRaw, yRaw) - bbox.first] = '#' } } } fill(map, start - bbox.first) return Triple( IntRange(0, maxX - minX), IntRange( clay.minOf { it.second.first } - minY, clay.maxOf { it.second.last } - minY, ), map, ) } private fun fill( map: List<MutableList<Char>>, coord: Vector2D ): Boolean { val reachBottom = when { map[coord] in STOP -> false coord.y == map.lastIndex -> true map[coord] == '|' -> true else -> { map[coord] = '~' fill(map, coord + D.step) || (fill(map, coord + L.step) or fill(map, coord + R.step)) } } if (reachBottom) { map[coord] = '|' generateSequence(coord) { it + L.step } .drop(1) .takeWhile { map[it] == '~' } .forEach { map[it] = '|' } generateSequence(coord) { it + R.step } .drop(1) .takeWhile { map[it] == '~' } .forEach { map[it] = '|' } } return reachBottom } } fun main() = SomeDay.mainify(Day17)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
3,082
adventofcode
MIT License
src/questions/RotateImage.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.assertIterableSame /** * You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). * * [Source](https://leetcode.com/problems/rotate-image-/) */ @UseCommentAsDocumentation fun rotate(matrix: Array<IntArray>) { // 1. Find the transpose of the matrix // 2. Reverse the rows of the transpose // Transpose = swap rows & col transpose(matrix) // Reverse rows reverseRows(matrix) } private fun reverseRows(matrix: Array<IntArray>) { val colMaxIndex = matrix[0].lastIndex for (row in 0..matrix.lastIndex) { for (col in 0..matrix[0].lastIndex / 2) { // swap only till col midpoint val temp = matrix[row][colMaxIndex - col] matrix[row][colMaxIndex - col] = matrix[row][col] matrix[row][col] = temp } } } private fun transpose(matrix: Array<IntArray>) { // GOTCHA: Swap 00:00, 01:10, 02:20, 11:11, 12:21, 22:22 for (row in 0..matrix.lastIndex) { for (col in row..matrix[0].lastIndex) { swapRowsCols(matrix, row, col) } } } private fun swapRowsCols(matrix: Array<IntArray>, i: Int, j: Int) { if (i == j) return val temp = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = temp } fun main() { run { val input = arrayOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9) ) rotate(input) assertIterableSame( input.toList(), arrayOf( intArrayOf(7, 4, 1), intArrayOf(8, 5, 2), intArrayOf(9, 6, 3) ).toList() ) } run { val input = arrayOf( intArrayOf(5, 1, 9, 11), intArrayOf(2, 4, 8, 10), intArrayOf(13, 3, 6, 7), intArrayOf(15, 14, 12, 16) ) rotate(input) assertIterableSame( input.toList(), arrayOf( intArrayOf(15, 13, 2, 5), intArrayOf(14, 3, 4, 1), intArrayOf(12, 6, 8, 9), intArrayOf(16, 7, 10, 11) ).toList() ) } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,259
algorithms
MIT License
src/questions/IteratorForCombination.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import java.lang.StringBuilder /** * Design the CombinationIterator class: * * * CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. * * next() Returns the next combination of length combinationLength in lexicographical order. * * hasNext() Returns true if and only if there exists a next combination. * * [Source](https://leetcode.com/problems/iterator-for-combination/) */ @UseCommentAsDocumentation class CombinationIterator(characters: String, combinationLength: Int) { private val cLength = combinationLength private val chars = characters // Hold indices of next return sequence // for eg: for combinationLength=3 and characters=abcde i.e. // trackIndex ranges from: // 012, 013, 014, 023, 024, 034, 123, 124, 134, 234 // abc, abd, abe, acd, ace, ade, bcd, bce, bde, cde // This pattern shows to generate next track index, you just have to make sure none of the digit crosses // its right digit i.e trackIndex[i] + 1 < trackIndex[i + 1] private var trackIndex: Array<Int>? = null init { findNextGenerator() } fun next(): String { val sb = StringBuilder(cLength) for (i in trackIndex!!) { sb.append(chars[i]) } return sb.toString().also { findNextGenerator() // prepare next sequence } } private fun findNextGenerator() { if (trackIndex == null) { // for first time trackIndex = Array(cLength) { it } // for combinationLength=3, it will be [0,1,2] } else { setNextValidTrackIndex(cLength - 1) } } private fun setNextValidTrackIndex(index: Int) { require(trackIndex != null) trackIndex!!.let { track -> if (index < 0) { trackIndex = null // no more sequence possible return } val rightDigitValue = track.getOrNull(index + 1) ?: chars.length if (track[index] + 1 < rightDigitValue) { // to prevent collision like [0,3,3] make sure 1 can be safely added track[index] = track[index] + 1 val current = track[index] // next sequence after [0,3,4] is [1,2,3] so var dist = 1 for (i in index + 1..track.lastIndex) { track[i] = dist + current dist++ } } else { setNextValidTrackIndex(index - 1) } } } fun hasNext(): Boolean { return trackIndex != null // next sequence is already prepared so just check if not null } } fun main() { run { val itr = CombinationIterator("abc", 2) itr.next() shouldBe "ab" itr.hasNext() shouldBe true itr.next() shouldBe "ac" itr.hasNext() shouldBe true itr.next() shouldBe "bc" itr.hasNext() shouldBe false } run { val itr = CombinationIterator("abcd", 3) itr.next() shouldBe "abc" itr.hasNext() shouldBe true itr.next() shouldBe "abd" itr.hasNext() shouldBe true itr.next() shouldBe "acd" itr.hasNext() shouldBe true itr.next() shouldBe "bcd" itr.hasNext() shouldBe false } run { CombinationIterator("chp", 1).apply { hasNext() shouldBe true next() shouldBe "c" hasNext() shouldBe true hasNext() shouldBe true next() shouldBe "h" next() shouldBe "p" hasNext() shouldBe false hasNext() shouldBe false hasNext() shouldBe false hasNext() shouldBe false hasNext() shouldBe false } } run { CombinationIterator("ahijp", 2).apply { hasNext() shouldBe true next() shouldBe "ah" next() shouldBe "ai" hasNext() shouldBe true next() shouldBe "aj" hasNext() shouldBe true next() shouldBe "ap" hasNext() shouldBe true next() shouldBe "hi" next() shouldBe "hj" } } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
4,373
algorithms
MIT License
src/Day01.kt
arnoutvw
572,860,930
false
{"Kotlin": 33036}
fun main() { fun part1(input: List<String>): Int { var maxCals = 0; var cals = 0; input.forEach { if(it.isBlank()) { if(cals > maxCals) { maxCals = cals; } cals = 0; } else { cals += Integer.valueOf(it); } } return maxCals; } fun part2(input: List<String>): Int { val cals = ArrayList<Int>(); var cal = 0; input.forEach { if(it.isBlank()) { cals.add(cal) cal = 0; } else { cal += Integer.valueOf(it); } } return cals.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4
1,035
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/Problem33.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
@file:Suppress("MagicNumber") /** * Digit cancelling fractions * * The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may * incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. * * We shall consider fractions like, 30/50 = 3/5, to be trivial examples. * * There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two * digits in the numerator and denominator. * * If the product of these four fractions is given in its lowest common terms, find the value of the denominator. * * https://projecteuler.net/problem=33 */ fun main() { println(isDigitCancellingFractions(numerator = 49, denominator = 98)) println(findDigitCancellingFractionsProductDenominator()) } private fun findDigitCancellingFractionsProductDenominator(): Int = buildList { // From 10 to 99, since we only support two digits. for (i in 11 until 100) { for (j in 10 until i) { if (isDigitCancellingFractions(numerator = j, denominator = i)) { add(j to i) } } } }.reduce { (n1, d1), (n2, d2) -> (n1 * n2) to (d1 * d2) }.let { (numerator, denominator) -> val denBI = denominator.toBigInteger() val gcd = numerator.toBigInteger().gcd(denominator.toBigInteger()) (denBI / gcd).toInt() } private fun isDigitCancellingFractions(numerator: Int, denominator: Int): Boolean { check(numerator in 10..99) check(denominator in 10..99) check(numerator < denominator) val numDigits = numerator.digits().toSet() val denDigits = denominator.digits().toSet() val repeatedDigits = numDigits intersect denDigits if (numDigits.size == 1 || denDigits.size == 1 || repeatedDigits.size != 1) { return false } val digit = repeatedDigits.first() val newNumerator = numDigits.first { it != digit }.toDouble() val newDenominator = denDigits.first { it != digit }.toDouble() // ignore trivial fractions were common digit is zero return digit != 0 && newDenominator != 0.0 && (numerator.toDouble() / denominator.toDouble()) == (newNumerator / newDenominator) }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
2,102
project-euler
MIT License
src/main/kotlin/sschr15/aocsolutions/Day6.kt
sschr15
317,887,086
false
{"Kotlin": 184127, "TeX": 2614, "Python": 446}
package sschr15.aocsolutions import sschr15.aocsolutions.util.* import kotlin.math.sqrt /** * AOC 2023 [Day 6](https://adventofcode.com/2023/day/6) * Challenge: How many ways can you get a boat down a river if you press a button for random amounts of time? */ object Day6 : Challenge { @ReflectivelyUsed override fun solve() = challenge(2023, 6) { // test() // fun fact: INVALID_CHARACTERS is a compiler error, but kotlin lets you suppress compiler errors :) @Suppress("LocalVariableName", "INVALID_CHARACTERS") fun rangeOfPossibilities(time: Long, distanceNeeded: Long): Long { val sqrtPart = sqrt((time * time - 4 * distanceNeeded).toDouble()) val positiveNumerator = -time + sqrtPart val negativeNumerator = -time - sqrtPart val denominator = -2 val positiveAnswer = positiveNumerator / denominator val negativeAnswer = negativeNumerator / denominator val `x equals negative b plus or minus the square root of b squared minus 4ac all over two a` = positiveAnswer..negativeAnswer // for LaTeX people: val `x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}` = `x equals negative b plus or minus the square root of b squared minus 4ac all over two a` val shortestPress = `x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}`.start.ceilingToLong() val longestPress = `x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}`.endInclusive.floorToLong() return longestPress - shortestPress + 1 } part1 { val times = inputLines.first().findLongs() val distances = inputLines.last().findLongs() times.zip(distances).map { (time, distance) -> rangeOfPossibilities(time, distance) }.reduce(Long::times) } part2 { val time = inputLines.first().filter { it.isDigit() }.toLong() val distance = inputLines.last().filter { it.isDigit() }.toLong() rangeOfPossibilities(time, distance) } } @JvmStatic fun main(args: Array<String>) = println("Time: ${solve()}") }
0
Kotlin
0
0
e483b02037ae5f025fc34367cb477fabe54a6578
2,172
advent-of-code
MIT License
advent-of-code-2023/src/main/kotlin/Day24.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
// Day 24: Never Tell Me The Odds // https://adventofcode.com/2023/day/24 import java.io.File data class Hailstone( val initialPosition: Triple<Long, Long, Long>, val velocity: Triple<Long, Long, Long>, ) { private fun getSlope(): Double { return velocity.second / velocity.first.toDouble() } private fun getIntercept(): Double { return initialPosition.second - (getSlope() * initialPosition.first) } fun extrapolateY(x: Double): Double { return getSlope() * x + getIntercept() } } fun main() { val lines = File("src/main/resources/Day24.txt").readLines() val regex = """(-? ?\d*), (-? ?\d*), (-? ?\d*) @ (-? ?\d+), (-? ?\d+), (-? ?\d+)""".toRegex() val hailstones = lines.mapNotNull { regex.matchEntire(it)?.destructured?.let { result -> val (px, py, pz, vx, vy, vz) = result Hailstone( initialPosition = Triple(px.trim().toLong(), py.trim().toLong(), pz.trim().toLong()), velocity = Triple(vx.trim().toLong(), vy.trim().toLong(), vz.trim().toLong()) ) } } val delta1 = 200_000_000_000_000.0 val delta2 = 400_000_000_000_000.0 checkIfHailstonesCross(hailstones, delta1, delta2) //TODO Part 2 } private fun checkIfHailstonesCross(hailstones: List<Hailstone>, delta1: Double, delta2: Double) { val pathsToCheck = hailstones.mapIndexed { x, hailstone -> (x + 1..<hailstones.size).map { y -> hailstone to hailstones[y] } }.flatten() val intersections = pathsToCheck.count { (hailstone1, hailstone2) -> val x1 = delta1 val x2 = delta2 val y1 = hailstone1.extrapolateY(x1) val y2 = hailstone1.extrapolateY(x2) val x3 = delta1 val x4 = delta2 val y3 = hailstone2.extrapolateY(x3) val y4 = hailstone2.extrapolateY(x4) val x12 = x1 - x2 val x34 = x3 - x4 val y12 = y1 - y2 val y34 = y3 - y4 val c = x12 * y34 - y12 * x34 val a = x1 * y2 - y1 * x2 val b = x3 * y4 - y3 * x4 val x = (a * x34 - b * x12) / c val y = (a * y34 - b * y12) / c val inAreaIntersect = x in delta1..delta2 && y in delta1..delta2 val isIntersectFutureOfH1 = hailstone1.velocity.first < 0 && x < hailstone1.initialPosition.first || hailstone1.velocity.first > 0 && x > hailstone1.initialPosition.first val isIntersectFutureOfH2 = hailstone2.velocity.first < 0 && x < hailstone2.initialPosition.first || hailstone2.velocity.first > 0 && x > hailstone2.initialPosition.first inAreaIntersect && isIntersectFutureOfH1 && isIntersectFutureOfH2 } println(intersections) }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
2,767
advent-of-code
Apache License 2.0
src/main/kotlin/day18.kt
p88h
317,362,882
false
null
internal data class Token(val op: Char, var v: Long) internal fun Parse(input: String): List<Token> { return input.split(' ').chunked(2).map { Token(it[0].first(), it[1].toLong()) } } internal fun Evaluate(input: String, pri: Char? = null): Long { var tokens = Parse(input) if (pri != null) { var tokens2 = arrayListOf(Token('+', 0L)) for (t in tokens) { if (t.op == pri) { if (t.op == '+') tokens2.last().v += t.v else tokens2.last().v *= t.v } else { tokens2.add(t) } } tokens = tokens2 } return tokens.fold(0L) { r, t -> if (t.op == '+') r + t.v else r * t.v } } internal fun Process(line: String, pri: Char? = null): Long { var stack = arrayListOf(StringBuilder("+ ")) for (i in line.indices) when (line[i]) { '(' -> stack.add(StringBuilder("+ ")) ')' -> { val v = Evaluate(stack.removeLast().toString(), pri) stack.last().append(v) } else -> stack.last().append(line[i]) } return Evaluate(stack.last().toString(), pri) } fun main(args: Array<String>) { val lines = allLines(args, "day18.in").toList() println(lines.map { Process(it) }.sum()) println(lines.map { Process(it, '+') }.sum()) }
0
Kotlin
0
5
846ad4a978823563b2910c743056d44552a4b172
1,302
aoc2020
The Unlicense
src/main/kotlin/com/github/dangerground/aoc2020/Day6.kt
dangerground
317,439,198
false
null
package com.github.dangerground.aoc2020 import com.github.dangerground.aoc2020.util.DayInput class Day6(batches: List<List<String>>) { val groups = mutableListOf<Group>() init { batches.forEach { groups.add(Group(it)) } } fun part1(): Int { return groups.sumOf { it.countAnswers() } } fun part2(): Int { return groups.sumOf { it.countAmbiguouslyAnswers() } } } class Group(private val answers: List<String>) { private val totalQuestionsAnswered = mutableSetOf<Char>() private val questionsAnsweredAmbiguously: Set<Char> init { val questionsAnswered = answers[0].toCharArray().toMutableSet() answers.forEachIndexed { index, member -> member.forEach { answer -> this.totalQuestionsAnswered.add(answer) } if (index > 0) { questionsAnswered.removeIf { !member.contains(it) } } } questionsAnsweredAmbiguously = questionsAnswered } fun countAnswers() = totalQuestionsAnswered.count() fun countAmbiguouslyAnswers() = questionsAnsweredAmbiguously.count() override fun toString(): String { return "Group(answers=$answers questionsAnsweredAmbiguously=${questionsAnsweredAmbiguously.size} ($questionsAnsweredAmbiguously))" } } fun main() { val input = DayInput.batchesOfStringList(6) val day6 = Day6(input) // part 1 //val part1 = day6.part1() //println("result part 1: $part1") // part2 val part2 = day6.part2() println("result part 2: $part2") }
0
Kotlin
0
0
c3667a2a8126d903d09176848b0e1d511d90fa79
1,625
adventofcode-2020
MIT License
app/src/main/java/com/themobilecoder/adventofcode/day4/DayFour.kt
themobilecoder
726,690,255
false
{"Kotlin": 323477}
package com.themobilecoder.adventofcode.day4 import com.themobilecoder.adventofcode.splitByNewLine class DayFour { fun solveDayFourPartOne(input: String) : Int { val cards = input.splitByNewLine() var sumOfPoints = 0 cards.forEach { card -> val winningNumbers = card.getWinningNumbersFromInput() val yourNumbers = card.getYourTicketNumbersFromInput() val points = yourNumbers.fold(0) { totalCount, number -> if (winningNumbers.contains(number)) { if (totalCount == 0) { 1 } else { totalCount * 2 } } else { totalCount } } sumOfPoints += points } return sumOfPoints } fun solveDayFourPartTwo(input: String) : Int { val cards = input.splitByNewLine() val gameCardsCopiesMap = mutableMapOf<Int, Int>() for (i in 1..cards.size) { gameCardsCopiesMap[i] = 1 } cards.forEach { card -> val winningNumbers = card.getWinningNumbersFromInput() val yourNumbers = card.getYourTicketNumbersFromInput() val gameId = card.getGameId() val countOfCardsBelowToCopy = yourNumbers.fold(0) { totalCount, number -> if (winningNumbers.contains(number)) { (totalCount + 1) } else { totalCount } } for (i in gameId + 1 .. gameId + countOfCardsBelowToCopy) { if (gameCardsCopiesMap.contains(i)) { val originalValue = gameCardsCopiesMap[i] ?: 1 gameCardsCopiesMap[i] = (originalValue + (gameCardsCopiesMap[gameId] ?: 1)) } } } return gameCardsCopiesMap.values.sum() } }
0
Kotlin
0
0
b7770e1f912f52d7a6b0d13871f934096cf8e1aa
1,949
Advent-of-Code-2023
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions40.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test40() { printlnResult(arrayOf( booleanArrayOf(true, false, true, false, false), booleanArrayOf(false, false, true, true, true), booleanArrayOf(true, true, true, true, true), booleanArrayOf(true, false, false, true, false) )) } /** * Questions 40: Find the biggest rectangle only contains 1 in a rectangle contains 0 and 1 */ private fun Array<BooleanArray>.biggestArea(): Int { require(isNotEmpty() && first().isNotEmpty()) { "The inputted rectangle can't be empty" } val heights = IntArray(first().size) var maxArea = 0 forEach { for (i in it.indices) if (it[i]) heights[i]++ else heights[i] = 0 val area = heights.maxVolume() if (area > maxArea) maxArea = area } return maxArea } private fun printlnResult(rectangle: Array<BooleanArray>) = println("The maximum area is ${rectangle.biggestArea()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,013
Algorithm
Apache License 2.0
src/test/kotlin/be/brammeerten/y2023/Day12Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2023 import be.brammeerten.readFileAndSplitLines import be.brammeerten.toCharList import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class Day12Test { @Test fun `part 1`() { val num1 = readFileAndSplitLines("2023/day12/exampleInput.txt", " ") .sumOf { tryIt(it[0], it[1].split(",").map { it.toInt() }) } val num2 = readFileAndSplitLines("2023/day12/input.txt", " ") .sumOf { tryIt(it[0], it[1].split(",").map { it.toInt() }) } assertThat(num1).isEqualTo(21); assertThat(num2).isEqualTo(7090); } @Test fun `part 2`() { val num1 = readFileAndSplitLines("2023/day12/exampleInput.txt", " ") .sumOf { val damaged = it[1].split(",").map { it.toInt() } val damagedAll = mutableListOf<Int>() for (i in 0 until 5) damagedAll.addAll(damaged) tryIt((it[0] + "?").repeat(5).dropLast(1), damagedAll) } val num2 = readFileAndSplitLines("2023/day12/input.txt", " ") .sumOf { val damaged = it[1].split(",").map { it.toInt() } val damagedAll = mutableListOf<Int>() for (i in 0 until 5) damagedAll.addAll(damaged) tryIt((it[0] + "?").repeat(5).dropLast(1), damagedAll) } assertThat(num1).isEqualTo(525152) assertThat(num2).isEqualTo(6792010726878) // Too low = 1667431902 } var cache: MutableMap<String, Long> = mutableMapOf() // .#.###.#.###### fun tryIt(conditions: String, damagedGroups: List<Int>): Long { val index = conditions + "$" + damagedGroups.joinToString(",") val cacheVal = cache[index] if (cacheVal != null) return cacheVal if (conditions.isEmpty() && damagedGroups.isEmpty()) { cache[index] = 1 return 1 } if ((conditions.isEmpty() && damagedGroups.isNotEmpty()) || (damagedGroups.isEmpty() && conditions.contains('#'))) { cache[index] = 0 return 0 } if (conditions.length < damagedGroups.sum() + damagedGroups.size - 1) { cache[index] = 0 return 0; } if (conditions[0] == '.') { val cacheVal = tryIt(conditions.drop(1), damagedGroups) cache[index] = cacheVal return cacheVal } else if (conditions[0] == '#') { val nextDamagedSize = damagedGroups.first() if (conditions.substring(0, nextDamagedSize).contains(".")) { cache[index] = 0 return 0 } if (conditions.length > nextDamagedSize) { if (conditions[nextDamagedSize] == '#') { cache[index] = 0 return 0 } val cacheVal = tryIt(conditions.substring(nextDamagedSize + 1), damagedGroups.drop(1)) cache[index] = cacheVal return cacheVal } return tryIt(conditions.substring(nextDamagedSize), damagedGroups.drop(1)) } else { // == '?' val cacheVal = tryIt("." + conditions.substring(1), damagedGroups) + tryIt("#" + conditions.substring(1), damagedGroups) cache[index] = cacheVal return cacheVal } } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
3,407
Advent-of-Code
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day12.kt
clechasseur
567,968,171
false
{"Kotlin": 493887}
package io.github.clechasseur.adventofcode.y2022 import io.github.clechasseur.adventofcode.dij.Dijkstra import io.github.clechasseur.adventofcode.dij.Graph import io.github.clechasseur.adventofcode.util.Direction import io.github.clechasseur.adventofcode.util.Pt import io.github.clechasseur.adventofcode.y2022.data.Day12Data object Day12 { private val input = Day12Data.input fun part1(): Int { val heightmap = Heightmap(input) val (dist, _) = Dijkstra.build(heightmap, heightmap.startPos) return dist[heightmap.endPos]!!.toInt() } fun part2(): Int { val heightmap = Heightmap(input) val (dist, _) = Dijkstra.build(heightmap, heightmap.startPos) return heightmap.allLowestPos.minOf { dist[it]!! }.toInt() } private class Heightmap(asString: String) : Graph<Pt> { val pts: Map<Pt, Char> = asString.lineSequence().flatMapIndexed { y, line -> line.mapIndexed { x, elevation -> Pt(x, y) to elevation } }.toMap() val startPos: Pt get() = pts.entries.single { it.value == 'E' }.key val endPos: Pt get() = pts.entries.single { it.value == 'S' }.key val allLowestPos: Collection<Pt> get() = pts.filterValues { it == 'a' || it == 'S' }.keys fun elevation(pt: Pt): Char = when (val e = pts[pt]) { 'S' -> 'a' 'E' -> 'z' else -> e ?: error("$pt is outside the heightmap") } override fun allPassable(): List<Pt> = pts.keys.toList() override fun neighbours(node: Pt): List<Pt> = Direction.displacements.map { node + it }.filter { it in pts.keys && elevation(it) - elevation(node) >= -1 } override fun dist(a: Pt, b: Pt): Long = 1L } }
0
Kotlin
0
0
7ead7db6491d6fba2479cd604f684f0f8c1e450f
1,810
adventofcode2022
MIT License
bitmanipulation/src/main/kotlin/com/kotlinground/bitmanipulation/countbits/countBits.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.bitmanipulation.countbits /** * To understand the solution, we remember the following two points from math: * * All whole numbers can be represented by 2N (even) and 2N+1 (odd). * For a given binary number, multiplying by 2 is the same as adding a zero at the end (just as we just add a zero when * multiplying by ten in base 10). * Since multiplying by 2 just adds a zero, then any number and its double will have the same number of 1's. Likewise, * doubling a number and adding one will increase the count by exactly 1. Or: * * countBits(N) = countBits(2N) * countBits(N)+1 = countBits(2N+1) * * Thus, we can see that any number will have the same bit count as half that number, with an extra one if it's an odd * number. We iterate through the range of numbers and calculate each bit count successively in this manner: * * for (i in 0 until num) { * counter[i] = counter[i // 2] + i % 2 * } * * With a few modifications: * * - Define the base case of counter[0] = 0, and start at 1. * - We need to include num, so use num+1 as the bound on the range. * - Bit-shifting 1 has the same effect as dividing by 2, and is faster, so replace i // 2 with i >> 1. * - We can choose to either initiate our list with counter = [0] * (num+1) or just counter = [0] and then append to it * (which has O(1)). It's a little faster to initiate it with zeroes and then access it rather than appending each time, * but I've chosen the latter for better readability. * - Some solutions use i & 1 to determine the parity of i. While this accomplishes the same purpose as i % 2 and keeps * with the bitwise-operator theme, it is faster to calculate the modulus. * * Time and Space Complexity * Time: O(n) - We iterate through the range of numbers once. * Space: O(n) - We use a num-sized array. */ fun countBits(n: Int): IntArray { val counter = IntArray(n + 1) { 0 } for (i in 1 until n + 1) { counter[i] = counter[i.shr(1)] + i % 2 } return counter }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
2,025
KotlinGround
MIT License
android/scripts/src/main/kotlin/com/github/pgreze/versions/CandidateResolver.kt
pgreze
535,231,537
false
{"Kotlin": 23102}
package com.github.pgreze.versions import java.io.File import kotlin.math.roundToInt fun main(args: Array<String>) { val versions = File(args.first()).parseVersions() val artifactToAvailableVersion: CandidateResolution = versions.groupByCandidateAvailable() println( ">> Up-to-date artifacts:\n" + artifactToAvailableVersion.upToDate.joinToString("") { "- ${it.key} = ${it.version}\n" } ) println( ">> With an update:\n" + artifactToAvailableVersion.newUpdateAvailable.entries.joinToString("") { "- ${it.key.key} :: ${it.key.version} -> ${it.value}\n" } ) println(artifactToAvailableVersion.toSummary()) } data class CandidateResolution( val upToDate: List<Artifact>, val newUpdateAvailable: Map<Artifact, String>, val upToDateRatio: Int = (upToDate.size + newUpdateAvailable.size).let { total -> if (total == 0) 100 else (100.0 * upToDate.size / total).roundToInt() }, ) fun CandidateResolution.toSummary(): String = "${upToDate.size} up-to-date artifacts ($upToDateRatio%) + ${newUpdateAvailable.size} with an update available" private val String.isUnstable: Boolean get() = contains("(alpha|beta|rc)".toRegex(RegexOption.IGNORE_CASE)) fun ArtifactToAvailableVersions.groupByCandidateAvailable(): CandidateResolution { val keyToCandidate: List<Pair<Artifact, String?>> = map { (artifact, versions) -> val unstable = artifact.version.isUnstable val candidate = versions.lastOrNull { unstable || it.isUnstable.not() } artifact to candidate } val groups: Map<Boolean, List<Pair<Artifact, String?>>> = keyToCandidate.groupBy { it.second != null } val upToDate = groups.getOrElse(false, ::listOf).map { a -> a.first } return CandidateResolution( upToDate = upToDate, newUpdateAvailable = groups.getOrElse(true, ::listOf).map { it.first to it.second!! }.toMap(), ) }
0
Kotlin
2
4
32a03204fc65c3a2dc5cc5781383225314afa253
1,953
kotlin-ci
Apache License 2.0
app/src/main/kotlin/advent_of_code/year_2022/day2/RockPaperScissors.kt
mavomo
574,441,138
false
{"Kotlin": 56468}
package advent_of_code.year_2022.day2 import advent_of_code.year_2022.day2.RPS.* import advent_of_code.year_2022.day2.RPS.Companion.myScoreByRoundResult import advent_of_code.year_2022.day2.RPS.Companion.myShapesCombination import advent_of_code.year_2022.day2.RPS.Companion.scoresByShape import advent_of_code.year_2022.day2.RPS.Companion.shapesByOpponent import advent_of_code.year_2022.day2.RPS.ODD.* import com.google.common.collect.ImmutableList class RockPaperScissors { fun computeMyScoreForRoundGuessingTheResult( rules: Map<Pair<Shape, Shape>, Shape>, currentGame: Pair<Shape, Shape> ): Pair<Shape?, Int> { val opponentShape = currentGame.first val myShape = currentGame.second val pair = computeMyScoreForSingleGame(opponentShape, myShape, rules, currentGame) return Pair(pair.second, pair.first) } private fun computeMyScoreForSingleGame( opponentShape: Shape, myShape: Shape, rules: Map<Pair<Shape, Shape>, Shape>, currentGame: Pair<Shape, Shape> ): Pair<Int, Shape> { val winningShape: Shape var myScore = 0 if (opponentShape != myShape) { winningShape = rules[currentGame]!! if (winningShape == myShape) { val isSameShape = myShape === opponentShape myScore = (if (isSameShape) computeRoundScore(myShape, DRAW) else computeRoundScore(myShape, VICTORY)) } else { myScore += computeRoundScore(myShape, DEFEAT) } } else { winningShape = myShape myScore = computeRoundScore(myShape, DRAW) } return Pair(myScore, winningShape) } private fun computeRoundScore(myShape: Shape, expectedODD: ODD): Int { var myScore = myScoreByRoundResult[expectedODD]!! myScore += scoresByShape[myShape]!! return myScore } fun computeMyScoreForAllRounds( allRounds: List<Pair<Char, Char>>, rules: Map<Pair<Shape, Shape>, Shape> ): ImmutableList<Int> { val scores = mutableListOf<Int>() allRounds.forEach { val currentGame = Pair(shapesByOpponent[it.first]!!, myShapesCombination[it.second]!!) val myScoreThisRound = computeMyScoreForRoundGuessingTheResult(rules, currentGame) scores.add(myScoreThisRound.second) } return ImmutableList.copyOf(scores) } fun computeMyScoreKnowingTheResult( currentInput: Pair<Shape, ODD>, rulesBook: Map<Pair<Shape, Shape>, Shape> ): Int { val myShape: Shape = findMyMatchingShape(currentInput, rulesBook) val myScore = myScoreByRoundResult[currentInput.second]!!.plus(scoresByShape[myShape]!!) return myScore } private fun findMyMatchingShape( currentInput: Pair<Shape, ODD>, rulesBook: Map<Pair<Shape, Shape>, Shape>, ) = when (currentInput.second) { DRAW -> rulesBook.values.find { it == currentInput.first }!! DEFEAT -> { val suggestedGame = rulesBook.entries.find { it.key.first == currentInput.first && it.value == currentInput.first } suggestedGame!!.key.second } VICTORY -> { val suggestedGame = rulesBook.entries.find { it.key.first == currentInput.first && it.value != currentInput.first } suggestedGame!!.key.second } } fun computeMyGameScoreKnowingTheResult( allRounds: List<Pair<Char, Char>>, rules: Map<Pair<Shape, Shape>, Shape> ): Int { val scores = mutableListOf<Int>() allRounds.forEach { val opponentShape = shapesByOpponent[it.first]!! val expectedResult = Companion.expectedResult[it.second]!! val currentGame: Pair<Shape, ODD> = Pair(opponentShape, expectedResult) val myScoreThisRound = computeMyScoreKnowingTheResult(currentGame, rules) scores.add(myScoreThisRound) } return scores.sum() } }
0
Kotlin
0
0
b7fec100ea3ac63f48046852617f7f65e9136112
4,028
advent-of-code
MIT License
src/Day21second.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
enum class Operation(val symbol: String) { CONSTANT("C"), ADD("+"), SUBSTRACT("-"), MULTIPLY("*"), DIVIDE("/"), COMPARE("="), HUMAN("H"); companion object { private val mapping = values().associateBy(Operation::symbol) fun fromSymbol(symbol: String): Operation { return mapping[symbol]!! } } } fun main() { fun nullableAdd(a: Long?, b: Long?): Long? { return b?.let { a?.plus(it) } } fun nullableSubstract(a: Long?, b: Long?): Long? { return b?.let { a?.minus(it) } } fun nullableDivide(a: Long?, b: Long?): Long? { if (a != null && b != null && a % b != 0L) { throw Exception("Not divisible") } return b?.let { a?.div(it) } } fun nullableMultiply(a: Long?, b: Long?): Long? { return b?.let { a?.times(it) } } class Monkey(val operation: Operation, val children: List<String>, var value: Long?) { fun calculateFromChildren(tree: Map<String, Monkey>) { children.forEach { ch -> tree[ch]!!.calculateFromChildren(tree) } when (operation) { Operation.CONSTANT -> return Operation.HUMAN -> return Operation.COMPARE -> return else -> { val left = tree[children[0]]!!.value val right = tree[children[1]]!!.value value = when(operation) { Operation.ADD -> nullableAdd(left, right) Operation.SUBSTRACT -> nullableSubstract(left, right) Operation.MULTIPLY -> nullableMultiply(left, right) Operation.DIVIDE -> nullableDivide(left, right) else -> { throw Exception("Somehow operation list not exastive") } } } } } fun calculateFromParent(expectedValue: Long?, tree: Map<String, Monkey>) { value = expectedValue if (children.isEmpty()) { return } val left = tree[children[0]]!! val right = tree[children[1]]!! if (left.value == null) { when(operation) { Operation.COMPARE -> left.calculateFromParent(right.value!!, tree) Operation.ADD -> left.calculateFromParent(value!! - right.value!!, tree) Operation.MULTIPLY -> { if (value!! % right.value!! != 0L) { throw Exception("Can't reverse multiplication") } left.calculateFromParent(value!! / right.value!!, tree) } Operation.DIVIDE -> left.calculateFromParent(value!! * right.value!!, tree) Operation.SUBSTRACT -> left.calculateFromParent(value!! + right.value!!, tree) else -> { throw Exception("Constant/human have children??? oO") } } return } when(operation) { Operation.COMPARE -> right.calculateFromParent(left.value!!, tree) Operation.ADD -> right.calculateFromParent(value!! - left.value!!, tree) Operation.MULTIPLY -> { if (value!! % left.value!! != 0L) { throw Exception("Can't reverse multiplication") } right.calculateFromParent(value!! / left.value!!, tree) } Operation.DIVIDE -> { if (left.value!! % value!! != 0L) { throw Exception("Can't reverse division") } right.calculateFromParent(left.value!! / value!!, tree) } Operation.SUBSTRACT -> right.calculateFromParent(left.value!! - value!!, tree) else -> { throw Exception("Constant/human have children??? oO") } } } } fun parseMonkey(input: String): Pair<String, Monkey> { val (name, formula) = input.split(":") if (name == "humn") { return (name to Monkey(Operation.HUMAN, listOf(), null)) } if (formula.trim().split(" ").size == 1) { return (name to Monkey(Operation.CONSTANT, listOf(), formula.trim().toLong())) } val (left, operation, right) = formula.trim().split(" ") if (name == "root") { return name to Monkey(Operation.COMPARE, listOf(left, right), null) } return name to Monkey(Operation.fromSymbol(operation), listOf(left, right),null) } fun part2(input: List<String>): Long { val monkeys = input.associate(::parseMonkey) monkeys["root"]!!.calculateFromChildren(monkeys) monkeys["root"]!!.calculateFromParent(null, monkeys) return monkeys["humn"]!!.value!! } println("Day21 part2") val testInput = readInput("Day21-test") val realInput = readInput("Day21") println("test: ${part2(testInput)}") println("real: ${part2(realInput)}") }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
5,283
aoc-2022
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[107]二叉树的层序遍历 II.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import kotlin.collections.ArrayList //给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) // // 例如: //给定二叉树 [3,9,20,null,null,15,7], // // // 3 // / \ // 9 20 // / \ // 15 7 // // // 返回其自底向上的层序遍历为: // // //[ // [15,7], // [9,20], // [3] //] // // Related Topics 树 广度优先搜索 // 👍 404 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun levelOrderBottom(root: TreeNode?): List<List<Int>> { //二叉树层序遍历 遍历完成之后反转结果 时间复杂度 O(n) val res = ArrayList<ArrayList<Int>>() if (root == null) return res //使用队列保存node 先进先出 val linkedList = LinkedList<TreeNode>() linkedList.addLast(root) while (!linkedList.isEmpty()){ var count = linkedList.size var templist = ArrayList<Int>() for (i in 0 until count){ var node = linkedList.removeFirst() if (node.left != null){ linkedList.addLast(node.left) } if (node.right != null){ linkedList.addLast(node.right) } templist.add(node.`val`) } res.add(templist) } res.reverse() return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,805
MyLeetCode
Apache License 2.0
src/main/kotlin/day14.kt
gautemo
433,582,833
false
{"Kotlin": 91784}
import shared.getText fun polymerTemplate(input: String, times: Int = 10): Long{ val (template, insertionsString) = input.split("\n\n") val insertions = insertionsString.lines().map { val (first, second) = it.split("->") Pair(first.trim(), second.trim()) } var countMap = mutableMapOf<String, Long>() template.windowed(2).forEach { countMap[it] = countMap.getOrDefault (it, 0) + 1 } repeat(times){ val newCountMap = mutableMapOf<String, Long>() countMap.forEach { pair -> val match = insertions.find { it.first == pair.key } if(match != null) { val pair1 = "${pair.key.first()}${match.second}" val pair2 = "${match.second}${pair.key.last()}" newCountMap[pair1] = newCountMap.getOrDefault(pair1, 0) + pair.value newCountMap[pair2] = newCountMap.getOrDefault(pair2, 0) + pair.value } } countMap = newCountMap } val countLetters = mutableMapOf<Char, Long>() countMap.forEach { countLetters[it.key.first()] = countLetters.getOrDefault(it.key.first(), 0) + it.value countLetters[it.key.last()] = countLetters.getOrDefault(it.key.last(), 0) + it.value } countLetters.forEach{ countLetters[it.key] = it.value / 2 } countLetters[template.first()] = countLetters[template.first()]!! + 1 countLetters[template.last()] = countLetters[template.last()]!! + 1 val numbers = countLetters.map { it.value }.sorted() return numbers.last() - numbers.first() } fun main(){ val input = getText("day14.txt") val task1 = polymerTemplate(input) println(task1) val task2 = polymerTemplate(input, 40) println(task2) }
0
Kotlin
0
0
c50d872601ba52474fcf9451a78e3e1bcfa476f7
1,762
AdventOfCode2021
MIT License
src/main/kotlin/days/Day13.kt
andilau
433,504,283
false
{"Kotlin": 137815}
package days @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2021/day/13", date = Date(day = 13, year = 2021) ) class Day13(val input: List<String>) : Puzzle { private val points = input.parsePoints() private val instructions = input.parseInstructions() override fun partOne() = instructions .take(1) .fold(points) { points, instruction -> points.foldAxis(instruction) } .count() override fun partTwo() = instructions .fold(points) { points, instruction -> points.foldAxis(instruction) } .print() private fun Set<Point>.foldAxis(instruction: FoldInstruction): Set<Point> = when (instruction.axis) { 'x' -> this.map { if (it.x < instruction.foldAt) it else it.copy(x = 2 * instruction.foldAt - it.x) }.toSet() 'y' -> this.map { if (it.y < instruction.foldAt) it else it.copy(y = 2 * instruction.foldAt - it.y) }.toSet() else -> throw IllegalArgumentException("Unable to fold axis: ${instruction.axis}") } private fun Set<Point>.print() = this.groupBy { it.y } .toSortedMap() .forEach { (y, points) -> val xMax = points.maxByOrNull { it.x }?.x ?: 0 (0..xMax).forEach { print(if (Point(it, y) in points) "#" else " ") } println() } private fun List<String>.parsePoints(): Set<Point> = this.takeWhile { it.isNotEmpty() } .map { from(it) } .toSet() private fun List<String>.parseInstructions(): List<FoldInstruction> = this.dropWhile { it.isNotEmpty() } .filter { it.isNotEmpty() } .map { FoldInstruction.from(it) } data class FoldInstruction(val axis: Char, val foldAt: Int) { companion object { fun from(line: String) = FoldInstruction( line.substringAfter("fold along ").first(), line.substringAfter('=').toInt() ) } } private fun from(line: String): Point { return Point( line.substringBefore(',').toInt(), line.substringAfter(',').toInt() ) } }
0
Kotlin
0
0
b3f06a73e7d9d207ee3051879b83e92b049a0304
2,397
advent-of-code-2021
Creative Commons Zero v1.0 Universal
classroom/src/main/kotlin/com/radix2/algorithms/week3/NutsAndBolts.kt
rupeshsasne
190,130,318
false
{"Java": 66279, "Kotlin": 50290}
package com.radix2.algorithms.week3 import java.util.* class NutsAndBolts { fun solve(nuts: IntArray, bolts: IntArray) { shuffle(nuts) shuffle(bolts) solve(nuts, bolts, 0, nuts.size - 1) } private fun solve(nuts: IntArray, bolts: IntArray, lo: Int, hi: Int) { if (lo >= hi) return val pivot = partition(nuts, bolts[lo], lo, hi) partition(bolts, nuts[pivot], lo, hi) solve(nuts, bolts, lo, pivot - 1) solve(nuts, bolts, pivot + 1, hi) } private fun partition(array: IntArray, pivot: Int, lo: Int, hi: Int): Int { var i = lo var j = hi + 1 while (true) { while (array[++i] <= pivot) { if (i == hi) break if (array[i] == pivot) { exch(array, lo, i) i-- } } while (pivot <= array[--j]) { if (j == lo) break if (array[j] == pivot) { exch(array, lo, j) j++ } } if (i >= j) break exch(array, i, j) } exch(array, lo, j) return j } private fun exch(array: IntArray, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } private fun shuffle(array: IntArray) { val rnd = Random() for (i in 1 until array.size) { val randomIndex = rnd.nextInt(i) exch(array, i, randomIndex) } } } fun main(args: Array<String>) { val nuts = intArrayOf(5, 3, 7, 9, 2, 8, 4, 1, 6, 0, 10, 11, 12, 13, 14, 15, 16, 17) val bolts = intArrayOf(4, 7, 1, 6, 3, 0, 8, 9, 2, 5, 10, 11, 12, 13, 14, 15, 16, 17) NutsAndBolts().solve(nuts, bolts) println(""" Nuts : ${nuts.joinToString(separator = ", ")} Bolts : ${bolts.joinToString(separator = ", ")} """.trimIndent()) }
0
Java
0
1
341634c0da22e578d36f6b5c5f87443ba6e6b7bc
1,986
coursera-algorithms-part1
Apache License 2.0
src/problems/187-findRepeatedDnaSequences.kt
w1374720640
352,006,409
false
null
package problems /** * 187. 重复的DNA序列 https://leetcode-cn.com/problems/repeated-dna-sequences/ * * 解:创建两个HashSet, * 从起点开始遍历原始字符,每次截取10个字符,如果第一个Set中不存在,则存放到第一个Set中,否则存放到第二个Set中 * 最后将第二个Set转换为List即可, * 时间复杂度O(N),空间复杂度O(N) */ fun findRepeatedDnaSequences(s: String): List<String> { val firstSet = HashSet<String>() val secondSet = HashSet<String>() for (i in 0..s.length - 10) { val key = s.substring(i, i + 10) if (firstSet.contains(key)) { secondSet.add(key) } else { firstSet.add(key) } } return secondSet.toList() } /** * 根据Rabin-Karp算法对Hash函数进行优化,让Hash函数可以在常数时间内完成(无论是截取10字符还是100字符) * 设需要计算的字符为R进制,定义hash函数为 var h=0;for(i in s.indices) h=h*R+i;return h; * 对于长度为M的子字符串,当需要计算下一个字符串的hash值时, * 需要将原hash值减去第一个字符乘以R的M-1次方,再将结果乘R,再加上下一个字符的值就是下一个字符串的hash值(数学上可以证明公式的正确性) * 可以参考《算法(第四版》这本书和我的另一个仓库中的完整代码实现: * https://github.com/w1374720640/Algorithms-4th-Edition-in-Kotlin/blob/master/src/chapter5/section3/RabinKarp.kt * 这里ACGT只有四种,所以R=4,M=10,和完整实现相比,没有对大素数取余, * 仍然使用两个HashSet,不过第一个HashSet存放Int值, * 时间复杂度和空间复杂度仍然是O(N),但是系数变小 */ fun findRepeatedDnaSequences2(s: String): List<String> { if (s.length <= 10) return emptyList() val map = hashMapOf<Char, Int>('A' to 0, 'C' to 1, 'G' to 2, 'T' to 3) val R = 4 // R的M-1次方 var RM = 1 repeat(9) { RM *= R } val firstSet = HashSet<Int>() val secondSet = HashSet<String>() var hash = 0 // 计算第一组子字符串的Hash值 repeat(10) { hash = hash * R + map[s[it]]!! } firstSet.add(hash) for (i in 1..s.length - 10) { // 计算去除第一个元素的hash值 hash -= map[s[i - 1]]!! * RM // 计算添加后一个元素后的hash值 hash = hash * R + map[s[i + 9]]!! if (firstSet.contains(hash)) { secondSet.add(s.substring(i, i + 10)) } else { firstSet.add(hash) } } return secondSet.toList() } /** * 通过位运算来确定hash值 * ACGT共有四个数,用两位二进制表示分别为00 01 10 11 * 计算hash值时,将原值左移两位,分别和四个二进制数或操作,得到新的hash值 * 子字符串长度固定为10,每个字母对应的二进制占两位,取前12为为0,后20为为1的整数作为掩码,与新的hash值与操作,得到最终的hash值 * 不同排列的子字符串hash值必定不同 */ fun findRepeatedDnaSequences3(s: String): List<String> { if (s.length <= 10) return emptyList() val map = hashMapOf<Char, Int>('A' to 0, 'C' to 1, 'G' to 2, 'T' to 3) val bitmask = -1 ushr 12 // -1的二进制位全部为1,无符号右移12位,则前12位为0,后12位为1 val firstSet = HashSet<Int>() val secondSet = HashSet<String>() var hash = 0 // 计算第一组子字符串的Hash值 repeat(10) { hash = (hash shl 2) or map[s[it]]!! } firstSet.add(hash and bitmask) for (i in 1..s.length - 10) { hash = ((hash shl 2) or map[s[i + 9]]!!) and bitmask if (firstSet.contains(hash)) { secondSet.add(s.substring(i, i + 10)) } else { firstSet.add(hash) } } return secondSet.toList() } private fun test(s: String, array: Array<String>) { val set1 = findRepeatedDnaSequences(s).toSet() val set2 = array.toHashSet() check(set1.size == set2.size) set1.forEach { check(set2.contains(it)) } } fun main() { test("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", arrayOf("AAAAACCCCC", "CCCCCAAAAA")) test("AAAAAAAAAAA", arrayOf("AAAAAAAAAA")) test("AAAAAAAAAA", arrayOf()) test("ACAGT", arrayOf()) test("AAAACCCCCGGGGGTTTTT", arrayOf()) println("check succeed.") }
0
Kotlin
0
0
21c96a75d13030009943474e2495f1fc5a7716ad
4,409
LeetCode
MIT License
src/main/kotlin/com/psmay/exp/advent/y2021/Day09.kt
psmay
434,705,473
false
{"Kotlin": 242220}
package com.psmay.exp.advent.y2021 import com.psmay.exp.advent.y2021.util.Grid import com.psmay.exp.advent.y2021.util.laterallyAdjacentCells object Day09 { // This top part was for part 1. It's written to process a stream of lines and produce a stream of results; it is // meant to be suitable for maps with an arbitrarily large number of rows with a reasonable number of columns. private class HeightMapRow { val knownHeights: List<Int> constructor() { knownHeights = emptyList() } constructor(knownHeights: List<Int>) { this.knownHeights = knownHeights } operator fun get(index: Int): Int? { return if (knownHeights.indices.contains(index)) knownHeights[index] else null } } data class CellWindow(val columnIndex: Int, val rowIndex: Int, val height: Int, val adjacentHeights: List<Int?>) { fun isLowPoint() = adjacentHeights.filterNotNull().all { height < it } } private fun getCellWindowsForRow(rowIndex: Int, rowAbove: HeightMapRow, row: HeightMapRow, rowBelow: HeightMapRow) = row.knownHeights.mapIndexed { columnIndex, height -> val top = rowAbove[columnIndex] val right = row[columnIndex + 1] val bottom = rowBelow[columnIndex] val left = row[columnIndex - 1] CellWindow(columnIndex, rowIndex, height, listOf(top, right, bottom, left)) } private fun getCellWindowsForRows(rows: Sequence<HeightMapRow>): Sequence<CellWindow> { val emptyRowSequence = sequenceOf(HeightMapRow()) // Padding added to allow scanning above the top or below the bottom. val padded = emptyRowSequence + rows + emptyRowSequence val windowed = padded.windowed(3) return windowed.flatMapIndexed { rowIndex, windowRows -> val (rowAbove, row, rowBelow) = windowRows getCellWindowsForRow(rowIndex, rowAbove, row, rowBelow) } } fun getCellWindows(rows: Sequence<List<Int>>) = getCellWindowsForRows(rows.map { HeightMapRow(it) }) // This next part expects to hold the entire height map in memory. fun Grid<Int>.mapSurroundingBasin(startPosition: Pair<Int, Int>): Set<Pair<Int, Int>> { val seen = mutableMapOf<Pair<Int, Int>, Boolean>() var nextToProcess = listOf(startPosition) while (nextToProcess.any()) { val toProcess = nextToProcess.filter { !seen.contains(it) } nextToProcess = toProcess.flatMap { pos -> val value = isInBasin(pos) seen[pos] = value if (value) pos.laterallyAdjacentCells() else emptyList() } .distinct() .filter { !seen.contains(it) } } return seen .filter { (_, value) -> value } .map { (pos, _) -> pos } .toSet() } private fun Grid<Int>.isInBasin(position: Pair<Int, Int>) = (getOrNull(position) ?: Int.MAX_VALUE) < 9 }
0
Kotlin
0
0
c7ca54612ec117d42ba6cf733c4c8fe60689d3a8
3,136
advent-2021-kotlin
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day13.kt
hughjdavey
317,575,435
false
null
package days class Day13 : Day(13) { // 3606 override fun partOne(): Any { val timestamp = inputList.first().toInt() val buses = inputList.last().split(",").mapNotNull { it.toIntOrNull() }.map { Bus(it) } val bus = generateSequence(buses) { bs -> bs.map { it.loop() } } .find { bs -> bs.any { it.time >= timestamp } } ?.sortedBy { it.time } ?.find { it.time >= timestamp } return bus?.let { (it.time - timestamp) * it.id } ?: 0 } // 379786358533423 override fun partTwo(): Any { return offsetDepartures(inputList.last().split(",")) } // todo make more functional! fun offsetDepartures(rawBuses: List<String>): Long { val (buses, offsets) = rawBuses.foldIndexed(listOf<Int>() to listOf<Int>()) { index, lists, raw -> if (raw == "x") lists else lists.first.plus(raw.toInt()) to lists.second.plus(index) } var inc = buses.first().toLong() var timestamp = 0L var matched = 1 while (matched < buses.size) { timestamp += inc val times = List(offsets.size) { it to timestamp + offsets[it] } if (times.take(matched + 1).all { (index, time) -> time % buses[index] == 0L }) { inc *= buses[matched++] } } return timestamp } data class Bus(val id: Int, val time: Int = 0) { fun loop() = Bus(id, time + id) } }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
1,476
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/g2101_2200/s2163_minimum_difference_in_sums_after_removal_of_elements/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2163_minimum_difference_in_sums_after_removal_of_elements // #Hard #Array #Dynamic_Programming #Heap_Priority_Queue // #2023_06_26_Time_854_ms_(100.00%)_Space_79.2_MB_(100.00%) import java.util.PriorityQueue class Solution { fun minimumDifference(nums: IntArray): Long { val n = nums.size / 3 val minHeap = PriorityQueue<Int>() val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } val leftMemo = LongArray(nums.size) val rightMemo = LongArray(nums.size) var current = 0L for (i in 0..2 * n - 1) { current += nums[i].toLong() maxHeap.add(nums[i]) if (maxHeap.size > n) { val removed = maxHeap.poll() current -= removed.toLong() leftMemo[i] = current } if (maxHeap.size == n) { leftMemo[i] = current } } current = 0 for (i in nums.size - 1 downTo n) { current += nums[i].toLong() minHeap.add(nums[i]) if (minHeap.size > n) { val removed = minHeap.poll() current -= removed.toLong() } if (minHeap.size == n) { rightMemo[i] = current } } var min = Long.MAX_VALUE for (i in n - 1..2 * n - 1) { min = Math.min(min, leftMemo[i] - rightMemo[i + 1]) } return min } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,480
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/github/michaelbull/advent2023/math/Distance.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.math import kotlin.math.abs import kotlin.math.max import kotlin.math.pow import kotlin.math.sqrt /** * Calculates the two-dimensional [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance#Two_dimensions) * between [positions][Vector2] [p] and [q] in the [x][Vector2.x] and [y][Vector2.y] dimensions. */ fun euclideanDistance(p: Vector2, q: Vector2): Int { val delta = q - p return delta.euclideanDistance() } fun Vector2.euclideanDistance(): Int { return sqrt(x.toDouble().pow(2) + y.toDouble().pow(2)).toInt() } infix fun Vector2.euclideanDistanceTo(other: Vector2): Int { return euclideanDistance(this, other) } /** * Calculates the two-dimensional [Chebyshev distance](https://en.wikipedia.org/wiki/Chebyshev_distance) * between [positions][Vector2] [p] and [q] in the [x][Vector2.x] and [y][Vector2.y] dimensions. */ fun chebyshevDistance(p: Vector2, q: Vector2): Int { val delta = q - p return delta.chebyshevDistance() } fun Vector2.chebyshevDistance(): Int { return max(abs(x), abs(y)) } infix fun Vector2.chebyshevDistanceTo(other: Vector2): Int { return chebyshevDistance(this, other) } /** * Calculates the two-dimensional [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry) * between [positions][Vector2] [p] and [q] in the [x][Vector2.x] and [y][Vector2.y] dimensions. */ fun manhattanDistance(p: Vector2, q: Vector2): Int { val delta = q - p return delta.manhattanDistance() } fun Vector2.manhattanDistance(): Int { return abs(x) + abs(y) } infix fun Vector2.manhattanDistanceTo(other: Vector2): Int { return manhattanDistance(this, other) }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
1,698
advent-2023
ISC License
src/shreckye/coursera/algorithms/Course 3 Programming Assignment #2 Question 2.kts
ShreckYe
205,871,625
false
{"Kotlin": 72136}
package shreckye.coursera.algorithms // number of bits shouldn't exceed 32 val filename = args[0] val (numNodes, numBits, nodes) = java.io.File(filename).bufferedReader().use { val (numNodes, numBits) = it.readLine().splitToInts() val nodes = it.lineSequence().map { it.splitWithWhiteSpaceAndFilterEmpty().joinToString("") .toInt(2) }.toIntArray(numNodes) Triple(numNodes, numBits, nodes) } fun largestKWithSpacingAtLeast(numNodes: Int, numBits: Int, nodes: IntArray, spacingAtLeast: Int): Int { val indexClusterUnionFind = UnionFind(numNodes) val indicesAtNodes = Array<SimpleIntArrayList?>(1 shl numBits) { null } for ((index, node) in nodes.withIndex()) { val indicesAtNode = indicesAtNodes[node] if (indicesAtNode === null) indicesAtNodes[node] = simpleIntArrayListOf(index) else indicesAtNode.add(index) } val nodeIndexPairsAtDistances = (0 until spacingAtLeast).map { distance -> nodes.withIndex().asSequence().flatMap { (index1, node1) -> node1.flipSequence(numBits, distance) .mapNotNull { indicesAtNodes[it] } .flatMap { it.asSequence() } .filter { index2 -> index1 < index2 } .map { index2 -> Edge(index1, index2) } } } return numNodes - nodeIndexPairsAtDistances.sumBy { it.count { indexClusterUnionFind.findAndUnionIfNecessary(it.vertex1, it.vertex2) } } } println(largestKWithSpacingAtLeast(numNodes, numBits, nodes, 3))
0
Kotlin
1
2
1746af789d016a26f3442f9bf47dc5ab10f49611
1,577
coursera-stanford-algorithms-solutions-kotlin
MIT License
src/main/kotlin/com/frankandrobot/rapier/nlp/generalize.patterns.cases.kt
frankandrobot
62,833,944
false
null
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.frankandrobot.rapier.nlp import com.frankandrobot.rapier.meta.RapierParams import com.frankandrobot.rapier.pattern.Pattern import com.frankandrobot.rapier.pattern.PatternElement import com.frankandrobot.rapier.pattern.PatternList import com.frankandrobot.rapier.util.combinations import com.frankandrobot.rapier.util.fillCopy import com.frankandrobot.rapier.util.sort import org.funktionale.option.Option import org.funktionale.option.Option.None import org.funktionale.option.toOption import java.util.* internal fun areEqualLengths(a : Pattern, b : Pattern) = a.length == b.length && a.length > 0 internal fun exactlyOneIsEmpty(a : Pattern, b : Pattern) = a.length != b.length && (a.length == 0 || b.length == 0) internal fun exactlyOneHasOneElement(a : Pattern, b : Pattern) = (a.length > b.length && b.length == 1) || (b.length > a.length && a.length == 1) internal fun areVeryLong(a : Pattern, b : Pattern, params : RapierParams) : Boolean { val patterns = sort(a, b) val shorter = patterns.first val longer = patterns.second val diff = longer.length - shorter.length return (longer.length >= 3 && diff > params.maxDifferenceInPatternLength) || (longer.length > params.maxUnequalPatternLength && diff >= 2) || longer.length > params.maxPatternLength } /** * The case when the two patterns have the same length. * * Pairs up the pattern elements from first to last and compute the generalizations of * each pair. Then combine the generalizations of the pairs of elements in order. */ internal fun caseEqualLengthPatterns(a : Pattern, b : Pattern) : Option<List<Pattern>> { if (areEqualLengths(a, b)) { val bIter = b().iterator() val generalizations = a().map { generalize(it, bIter.next()) } return combinations(generalizations).map(::Pattern).toOption() } return None } /** * The case when the shorter pattern has 0 elements. * * The pattern elements in the longer pattern are generalized into a set of pattern * lists, one pattern list for each alternative generalization of the constraints of * the pattern elements. The length of the pattern lists is the sum of the lengths of * the elements of the longer pattern, with pattern items having a length of one. */ internal fun caseAnEmptyPattern(a: Pattern, b : Pattern) : Option<List<Pattern>> { if (exactlyOneIsEmpty(a, b)) { val nonEmpty = if (a.length == 0) b else a val length = nonEmpty().fold(0) { total, patternElement -> total + patternElement.length } val generalizations = nonEmpty().fold(listOf(nonEmpty()[0])) { total, patternElement -> total .flatMap { prevPatternElement -> generalize(prevPatternElement, patternElement) } .distinct() } return generalizations .map { Pattern( PatternList( wordConstraints = it.wordConstraints, posTagConstraints = it.posTagConstraints, semanticConstraints = it.semanticConstraints, length = length ) ) } .toOption() } return None } /** * The case when the shorter pattern has exactly 1 element. */ internal fun casePatternHasSingleElement(a: Pattern, b: Pattern) : Option<List<Pattern>> { if (exactlyOneHasOneElement(a, b)) { val c = if (b.length == 1) a else b val d = if (b.length == 1) b else a val length = Math.max( d()[0].length, c().fold(0) { total, patternElement -> total + patternElement.length } ) val generalizations = c().fold(listOf(d()[0])) { total, patternElement -> total .flatMap { prevPatternElement -> generalize(prevPatternElement, patternElement) } .distinct() } return generalizations .map { Pattern( PatternList( wordConstraints = it.wordConstraints, posTagConstraints = it.posTagConstraints, semanticConstraints = it.semanticConstraints, length = length ) ) } .toOption() } return None } /** * Handle the case when * * - pattern lengths difference is more than `maxDifferenceInPatternLength` * for any pattern length, OR * - longer pattern is more than `maxUnequalPatternLength` and patterns length difference * is at least 2, OR * - longer pattern is more than `maxPatternLength` * * With these settings * * maxPatternLength = 15 * maxUnequalPatternLength = 10 * maxDifferenceInPatternLength = 5 * * this will NOT handle the following scenarios: * * - the longest pattern is less than 10 and the difference in lengths is less than 5 * - the two patterns have the same length and are less than 15 */ internal fun caseVeryLongPatterns(a : Pattern, b : Pattern, params : RapierParams) : Option<List<Pattern>> { if (areVeryLong(a, b, params)) { val longer = sort(a, b).second return listOf(Pattern(PatternList(length = longer.length))).toOption() } return None } internal fun caseGeneral(a : Pattern, b : Pattern) : Option<List<Pattern>> { val patterns = sort(a, b) val shorter = patterns.first val longer = patterns.second val newPatterns = extend(shorter().listIterator(), shorter.length, longer.length) return newPatterns.flatMap{ caseEqualLengthPatterns(it, longer).get() }.toOption() } /** * Extends the shorter list to longerLength by duplicating elements. However, it must * satisfy the following constraints: * * 1. every original element must appear in the extended lists * 2. elements must appear in the same order as the original list * * Example: suppose the original list is [a,b,c] and longerLength = 4. * Then [a,a,a,a] and [a,c,c,b] will NOT be generated. There are only three possible * lists: * * - [a,a,b,c] * - [a,b,b,c] * - [a,b,c,c] */ internal tailrec fun extend(shorter: ListIterator<PatternElement>, shorterLength: Int, longerLength: Int, _extended: ArrayList<Pattern> = arrayListOf(Pattern())) : List<Pattern> { if (!shorter.hasNext()) { return _extended } val curElemIndex = shorter.nextIndex() val curElem = shorter.next() var nexExtended = _extended.fold(ArrayList<Pattern>()) { total, pattern -> // Here's how we satisfy the constraint that every element in the shorter list // must match with at least one element in the longer list: // we can add at most maxIndex-minIndex+1 copies of the current element. // And that's exactly what we do---we create new Patterns with the current elem // added 1 to maxIndex-minIndex+1 times. val prevIndex = pattern.length val minIndex = Math.max(prevIndex, curElemIndex) val maxIndex = longerLength - shorterLength + curElemIndex val newPatterns = ArrayList<Pattern>() if (shorter.hasNext()) { var i = minIndex while (i <= maxIndex) { newPatterns.add(pattern + Pattern(fillCopy(i - minIndex + 1, curElem))) ++i } } else { // we reached the end so just fill the rest of the list with the last elem newPatterns.add(pattern + Pattern(fillCopy(maxIndex - minIndex + 1, curElem))) } total.addAll(newPatterns) total } return extend(shorter, shorterLength, longerLength, nexExtended) }
1
Kotlin
1
1
ddbc0dab60ca595e63a701e2f8cd6694ff009adc
8,005
rapier
Apache License 2.0
src/main/kotlin/unam/ciencias/heuristicas/algorithm/Metrologist.kt
angelgladin
203,038,278
false
{"TSQL": 7853771, "Kotlin": 28077, "TeX": 21759}
package unam.ciencias.heuristicas.algorithm import unam.ciencias.heuristicas.Constants.Companion.EARTH_RADIUS_IN_METERS import unam.ciencias.heuristicas.heuristic.Solution import unam.ciencias.heuristicas.model.City import kotlin.math.* /** * TODO * * @property graph Pondered graph representing a the cities as vertices and its connections * represented as weighted edges. * @property cities The instance of TSP which is going to be solved. */ class Metrologist( private val graph: Graph<Int, City>, private val cities: ArrayList<Int> ) { /** The induced graph built with the [graph] using the [cities] as vertices. */ val inducedGraph = graph.inducedGraph(cities) /** TODO */ val normalizer = normalizer() private fun augmentedCostFunction(u: Int, v: Int): Double = if (graph.hasEdge(u, v)) graph.edgeWeight(u, v)!! else naturalDistance(u, v) * maxDistance() private fun naturalDistance(u: Int, v: Int): Double { val latitudeU = rad(inducedGraph.getNodeInfo(u)!!.latitude) val longitudeU = rad(inducedGraph.getNodeInfo(u)!!.longitude) val latitudeV = rad(inducedGraph.getNodeInfo(v)!!.latitude) val longitudeV = rad(inducedGraph.getNodeInfo(v)!!.longitude) val a = sin((latitudeV - latitudeU) / 2).pow(2) + cos(latitudeU) * cos(latitudeV) * sin((longitudeV - longitudeU) / 2).pow(2) val r = EARTH_RADIUS_IN_METERS val c = 2 * atan2(sqrt(a), sqrt(1 - a)) return r * c } fun costFunction(solution: Solution, swappedIndices: Boolean = false): Double { val path = solution.path var pathWeightSum = 0.0 for (i in 0 until path.size - 1) { pathWeightSum += augmentedCostFunction(path[i], path[i + 1]) } if (swappedIndices) { val n = path.size - 1 val i = solution.swappedIndices!!.first val j = solution.swappedIndices!!.second var edgeWeightToRemove = 0.0 var modifiedEdgeWeights = 0.0 // If they are adjacents. if (j - i == 1) { if (i == 0) { edgeWeightToRemove = augmentedCostFunction(path[i], path[j]) + augmentedCostFunction(path[j], path[j + 1]) modifiedEdgeWeights = augmentedCostFunction(path[j], path[i]) + augmentedCostFunction(path[i], path[j + 1]) } else if (i > 0 && j < n) { edgeWeightToRemove = augmentedCostFunction(path[i - 1], path[i]) + augmentedCostFunction(path[i], path[j]) + augmentedCostFunction(path[j], path[j + 1]) modifiedEdgeWeights = augmentedCostFunction(path[i - 1], path[j]) + augmentedCostFunction(path[j], path[i]) + augmentedCostFunction(path[i], path[j + 1]) } else if (i == n - 1) { edgeWeightToRemove = augmentedCostFunction(path[i - 1], path[i]) + augmentedCostFunction(path[i], path[j]) modifiedEdgeWeights = augmentedCostFunction(path[i - 1], path[n]) + augmentedCostFunction(path[n], path[i]) } } else { if (i == 0 && j == n) { edgeWeightToRemove = augmentedCostFunction(path[0], path[1]) + augmentedCostFunction(path[n - 1], path[n]) modifiedEdgeWeights = augmentedCostFunction(path[n], path[1]) + augmentedCostFunction(path[n - 1], path[0]) } else if (i == 0 && j > 1 && j < n) { edgeWeightToRemove = augmentedCostFunction(path[0], path[1]) + augmentedCostFunction(path[j - 1], path[j]) + augmentedCostFunction(path[j], path[j + 1]) modifiedEdgeWeights = augmentedCostFunction(path[j], path[1]) + augmentedCostFunction(path[j - 1], path[0]) + augmentedCostFunction(path[0], path[j + 1]) } else if (i > 0 && i < n - 1 && j == n) { edgeWeightToRemove = augmentedCostFunction(path[i - 1], path[i]) + augmentedCostFunction(path[i], path[i + 1]) + augmentedCostFunction(path[n - 1], path[n]) modifiedEdgeWeights = augmentedCostFunction(path[i - 1], path[n]) + augmentedCostFunction(path[n], path[i + 1]) + augmentedCostFunction(path[n - 1], path[i]) } else { edgeWeightToRemove = augmentedCostFunction(path[i - 1], path[i]) + augmentedCostFunction(path[i], path[i + 1]) + augmentedCostFunction(path[j - 1], path[j]) + augmentedCostFunction(path[j], path[j + 1]) modifiedEdgeWeights = augmentedCostFunction(path[i - 1], path[j]) + augmentedCostFunction(path[j], path[i + 1]) + augmentedCostFunction(path[j - 1], path[i]) + augmentedCostFunction(path[i], path[j + 1]) } } pathWeightSum -= edgeWeightToRemove pathWeightSum += modifiedEdgeWeights } return pathWeightSum / normalizer } /** * TODO * * @return */ private fun normalizer(): Double { var result = 0.0 val orderedWeights = ArrayList(inducedGraph.edges) orderedWeights.sortWith(Comparator { o1, o2 -> o2.weight.compareTo(o1.weight) }) for ((i, edge) in orderedWeights.withIndex()) { if (i > inducedGraph.size() - 2) break result += edge.weight } return result } fun maxDistance(): Double = inducedGraph.edges.peek().weight private fun rad(g: Double): Double = (g * Math.PI) / 180 }
0
TSQL
0
0
b8f3288ebc17f1a1468da4631cbf8af58f4fd28b
6,194
TSP-Threshold-Accepting
MIT License
src/Day06.kt
akleemans
574,937,934
false
{"Kotlin": 5797}
fun main() { fun duplicateCount(text: String): Int { val invalid = ArrayList<Char>() for (i in text.indices) { val c = text[i].lowercaseChar() if (invalid.contains(c)) continue for (j in i + 1 until text.length) { if (c == text[j].lowercaseChar()) { invalid.add(c) break } } } return invalid.size; } fun part1(input: List<String>): Int { val s = input.get(0) for (i in 4..s.length) { if (duplicateCount(s.substring(i - 4, i)) == 0) { return i; } } return 0 } fun part2(input: List<String>): Int { val s = input.get(0) for (i in 14..s.length) { if (duplicateCount(s.substring(i - 14, i)) == 0) { return i; } } return 0 } val testInput = readInput("Day06_test_input") check(part1(testInput) == 11) check(part2(testInput) == 26) val input = readInput("Day06_input") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
fa4281772d89a6d1cda071db4b6fb92fff5b42f5
1,203
aoc-2022-kotlin
Apache License 2.0
leetcode/src/sort/Q268.kt
zhangweizhe
387,808,774
false
null
package sort fun main() { // 268. 丢失的数字 // https://leetcode-cn.com/problems/missing-number/ println(missingNumber1(intArrayOf(9,6,4,2,3,5,7,0,1))) } private fun missingNumber(nums: IntArray): Int { val n = nums.size nums.sort() var i = 0 while (i < n-1) { if (nums[i+1] - nums[i] > 1) { return nums[i+1] - 1 } i++ } return if (nums[0] == 0) { // 缺少最后一个数,即n n }else { // 缺少第一个数,即0 0 } } private fun missingNumber1(nums: IntArray): Int { var sum = 0 val n = nums.size for (i in 1..n) { sum += i sum -= nums[i-1] } return sum }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
724
kotlin-study
MIT License
src/Day01.kt
marciprete
574,547,125
false
{"Kotlin": 13734}
fun main() { fun getCalories(input: List<String>): List<Int> { return input.foldIndexed(ArrayList<ArrayList<Int>>(1)) { index, acc, item -> if(index==0 || item.isEmpty()) { acc.add(ArrayList()) } else { acc.last().add(item.toInt()) } acc }.map { it.sum() } } fun part1(input: List<String>): Int { return getCalories(input).max() } fun part2(input: List<String>): Int { return getCalories(input).sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6345abc8f2c90d9bd1f5f82072af678e3f80e486
813
Kotlin-AoC-2022
Apache License 2.0
src/day13.kt
miiila
725,271,087
false
{"Kotlin": 77215}
import java.io.File import kotlin.system.exitProcess private const val DAY = 13 val results = mutableMapOf<List<String>, MutableList<Int>>() fun main() { if (!File("./day${DAY}_input").exists()) { downloadInput(DAY) println("Input downloaded") exitProcess(0) } val transformer = { x: String -> x } val input = parseMirrors(loadInput(DAY, false, transformer)) // println(input) println(solvePart1(input)) println(solvePart2(input)) } // Part 1 private fun solvePart1(input: List<List<String>>): Int { val res = input.sumOf { results[it] = mutableListOf(-1, -1) val v = hasVerticalLine(it) results[it]!![0] = v val h = hasHorizontalLine(it) results[it]!![1] = h if (v >= 0) v + 1 else (h + 1) * 100 } return res } // Part 2 private fun solvePart2(input: List<List<String>>): Int { val res = input.sumOf { val v = hasVerticalLine(it, true) val h = hasHorizontalLine(it, true) if (v >= 0) v + 1 else (h + 1) * 100 } return res } fun hasVerticalLine(grid: List<String>, withFix: Boolean = false): Int { val cols = grid[0].count() val mid = if (cols % 2 == 1) cols / 2 else cols / 2 - 1 for (x in (mid downTo 0).zip(mid..<cols).map { it.toList() }.flatten()) { val r = verifyVerticalLine(x, grid, withFix) if (r >= 0) { if (results[grid]!![0] == r) { continue } return r } } return -1 } fun hasHorizontalLine(grid: List<String>, withFix: Boolean = false): Int { val rows = grid.count() val mid = if (rows % 2 == 1) rows / 2 else rows / 2 - 1 for (x in (mid downTo 0).zip(mid..<rows).map { it.toList() }.flatten()) { val r = verifyHorizontalLine(x, grid, withFix) if (r >= 0) { if (results[grid]!![1] == r) { continue } return r } } return -1 } fun verifyHorizontalLine(line: Int, grid: List<String>, withFix: Boolean = false): Int { var fixed = false var x = line var y = line + 1 if (y >= grid.count()) { return -1 } while (x >= 0 && y < grid.count()) { if (grid[x] != grid[y]) { if (withFix && !fixed) { if (grid[x].zip(grid[y]).count { it.first != it.second } == 1) { fixed = true x-- y++ continue } } return -1 } x-- y++ } return line } fun verifyVerticalLine(line: Int, grid: List<String>, withFix: Boolean = false): Int { var fixed = false var x = line var y = line + 1 if (y >= grid[0].count()) { return -1 } while (x >= 0 && y < grid[0].count()) { if (getColumn(x, grid) != getColumn(y, grid)) { if (withFix && !fixed) { if (getColumn(x, grid).zip(getColumn(y, grid)).count { it.first != it.second } == 1) { fixed = true x-- y++ continue } } return -1 } x-- y++ } return line } fun getColumn(i: Int, grid: List<String>): String { return grid.joinToString("") { it[i].toString() } } fun parseMirrors(input: List<String>): List<List<String>> { val res = mutableListOf<List<String>>() var i = mutableListOf<String>() for (l in input) { if (l == "") { res.add(i) i = mutableListOf<String>() continue } i.add(l) } res.add(i) return res }
0
Kotlin
0
1
1cd45c2ce0822e60982c2c71cb4d8c75e37364a1
3,719
aoc2023
MIT License
src/Day01.kt
jdappel
575,879,747
false
{"Kotlin": 10062}
fun main() { fun logic(input: List<String>): Map<Int,Int> { var elves = mutableMapOf<Int,Int>() var tmp = 0 var cnt = 0 input.forEach { line -> if (line.isNotEmpty()) { tmp += line.toInt() } else { elves[++cnt] = tmp tmp = 0 } } return elves } fun part1(input: List<String>): Int { return logic(input).maxBy { entry -> entry.value }.value } fun part2(input: List<String>): Int { return logic(input).entries.sortedByDescending { entry -> entry.value }.take(3).sumOf { it.value } } // test if implementation meets criteria from the description, like: //val testInput = readInput("Day01_test") //check(part1(testInput) == 1) val input = readInput("Day01_test") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ddcf4f0be47ccbe4409605b37f43534125ee859d
917
AdventOfCodeKotlin
Apache License 2.0
src/main/kotlin/com/github/brpeterman/advent2022/CampSections.kt
brpeterman
573,059,778
false
{"Kotlin": 53108}
package com.github.brpeterman.advent2022 class CampSections { fun countOverlaps(assignments: List<Pair<IntRange, IntRange>>): Int { return assignments.fold(0, { total, assignment -> if ((assignment.second.contains(assignment.first.first)) || (assignment.second.contains(assignment.first.endInclusive))) { total + 1 } else { total } }) } fun countRedundancies(assignments: List<Pair<IntRange, IntRange>>): Int { return assignments.fold(0, { total, assignment -> if ((assignment.second.contains(assignment.first.start)) && (assignment.second.contains(assignment.first.endInclusive))) { total + 1 } else { total } }) } companion object { fun parseInput(input: String): List<Pair<IntRange, IntRange>> { return input.split("\n") .filter { it.isNotBlank() } .map { line -> val ranges = line.split(",") .map { section -> val (start, end) = section.split("-") start.toInt()..end.toInt() } .sortedBy { it.endInclusive - it.start } Pair(ranges[0], ranges[1]) } } } }
0
Kotlin
0
0
1407ca85490366645ae3ec86cfeeab25cbb4c585
1,428
advent2022
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day25.kt
clechasseur
567,968,171
false
{"Kotlin": 493887}
package io.github.clechasseur.adventofcode.y2022 import io.github.clechasseur.adventofcode.y2022.data.Day25Data import kotlin.math.pow object Day25 { private val input = Day25Data.input fun part1(): String = input.lines().map { SnafuNumber(it) }.sum().asSnafu private val snafuValues = mapOf('2' to 2L, '1' to 1L, '0' to 0L, '-' to -1L, '=' to -2L) private data class SnafuNumber(val asSnafu: String) { constructor(valueAsDecimal: Long) : this(valueAsDecimal.snafuify()) val asDecimal: Long get() = asSnafu.reversed().withIndex().sumOf { (p, c) -> snafuValues[c]!! * 5.0.pow(p).toLong() } } private fun Long.snafuify(): String { var buf = toString(5).reversed() var carry = 0 var res = "" while (buf.isNotEmpty()) { val c = buf.first().toString().toInt() + carry buf = buf.drop(1) carry = 0 res += when (c) { in 0..2 -> c.toString() 3 -> { carry = 1 "=" } 4 -> { carry = 1 "-" } else -> { carry = c - 4 (c - 5).toString() } } } if (carry != 0) { res += carry.toString() } return res.reversed() } private fun Collection<SnafuNumber>.sum(): SnafuNumber = SnafuNumber(sumOf { it.asDecimal }) }
0
Kotlin
0
0
7ead7db6491d6fba2479cd604f684f0f8c1e450f
1,556
adventofcode2022
MIT License
leetcode2/src/leetcode/CountAndSay.kt
hewking
68,515,222
false
null
package leetcode /** * 38. 报数 * https://leetcode-cn.com/problems/count-and-say/ * Created by test * Date 2019/5/23 1:18 * Description * 报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 被读作 "one 1" ("一个一") , 即 11。 11 被读作 "two 1s" ("两个一"), 即 21。 21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。 给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。 注意:整数顺序将表示为一个字符串。 示例 1: 输入: 1 输出: "1" 示例 2: 输入: 4 输出: "1211" */ object CountAndSay { class Solution { /** * 思路: * 1.首先题目要看懂,说的报数的是n的下一项 *2.首先知道传入的n是趟数,所以必定是有n次,第一次已知 可以直接返回结果 * 3.用count计数,c作为每次对比的字符的临时变量 * 4.每一轮重置 count ,c * 5.从高位开始计数,到每一轮循环的末尾 手动循环外添加 报数结果 * */ fun countAndSay(n: Int): String { var s = "1" if (n == 1) return "1" val rs = StringBuffer() var count = 0 var c = s[0] for (i in 2 ..n) { count = 0 c = s[0] for (j in 0 until s.length){ if (c == s[j]) { count ++ } else { rs.append(count) rs.append(c) c = s[j] count = 1 } if (j == s.length -1) { rs.append(count) rs.append(c) } } s = rs.toString() rs.delete(0,rs.length) } return s } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,069
leetcode
MIT License
2018/kotlin/day16p1/src/main.kt
sgravrock
47,810,570
false
{"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488}
import java.util.* fun main(args: Array<String>) { val start = Date() val classLoader = Opcode::class.java.classLoader val input = classLoader.getResource("input.txt").readText() val instructions = Instruction.parse(input) val matches = instructions.filter { it.behavesLike().size >= 3 } println(matches.size) println("in ${Date().time - start.time}ms") } enum class Opcode { addr, addi, mulr, muli, banr, bani, borr, bori, setr, seti, gtir, gtri, gtrr, eqir, eqri, eqrr } fun evaluate(opcode: Opcode, registers: List<Int>, i1: Int, i2: Int, o: Int): List<Int> { val result = registers.toMutableList() result[o] = when (opcode) { Opcode.addr -> registers[i1] + registers[i2] Opcode.addi -> registers[i1] + i2 Opcode.mulr -> registers[i1] * registers[i2] Opcode.muli -> registers[i1] * i2 Opcode.banr -> (registers[i1].toUInt() and registers[i2].toUInt()).toInt() Opcode.bani -> (registers[i1].toUInt() and i2.toUInt()).toInt() Opcode.borr -> (registers[i1].toUInt() or registers[i2].toUInt()).toInt() Opcode.bori -> (registers[i1].toUInt() or i2.toUInt()).toInt() Opcode.setr -> registers[i1] Opcode.seti -> i1 Opcode.gtir -> if (i1 > registers[i2]) 1 else 0 Opcode.gtri -> if (registers[i1] > i2) 1 else 0 Opcode.gtrr -> if (registers[i1] > registers[i2]) 1 else 0 Opcode.eqir -> if (i1 == registers[i2]) 1 else 0 Opcode.eqri -> if (registers[i1] == i2) 1 else 0 Opcode.eqrr -> if (registers[i1] == registers[i2]) 1 else 0 } return result } data class Instruction(val input: List<Int>, val codes: List<Int>, val output: List<Int>) { fun behavesLike(): List<Opcode> { return Opcode.values().filter { opcode -> evaluate(opcode, input, codes[1], codes[2], codes[3]) == output } } companion object { fun parse(input: String): List<Instruction> { return input.lines() .filter { it != "" } .chunked(3) .map { chunk -> Instruction( input = extractList(chunk[0]), codes = extractList(chunk[1]), output = extractList(chunk[2]) ) } } } } fun extractList(s: String): List<Int> { return s .replace(Regex("[^\\d ]"), "") .replace(Regex("^ *"), "") .split(" ") .map { it.toInt() } }
0
Rust
0
0
ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3
2,596
adventofcode
MIT License
advent2022/src/main/kotlin/year2022/Day20.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay import kotlin.math.absoluteValue /** * this swaps beforeFirst -> first -> second -> afterSecond, * to beforeFirst -> second -> first -> afterSecond */ private fun swap(first: Day20.Node, second: Day20.Node) { val beforeFirst = first.previous val afterSecond = second.next // correct afterSecond to be after first afterSecond.previous = first first.next = afterSecond // correct second to be before first first.previous = second second.next = first // correct beforeFirst to be before second second.previous = beforeFirst beforeFirst.next = second } class Day20 : AdventDay(2022, 20) { class CyclicLinkedList { lateinit var start: Node lateinit var content: List<Node> companion object { fun from(input: List<Long>, key: Long = 1): CyclicLinkedList { val list = CyclicLinkedList() list.content = input.mapIndexed { index, data -> Node( index, // adjust data to cycle length, so we do not need to move unnecessarily data * key % (input.size - 1), data // start is for groveCoordinates, says it starts at value 0 ).also { if (data == 0L) list.start = it } } // setup prev and next for every element in the middle list.content.windowed(2).forEach { (a, b) -> a.next = b b.previous = a } val first = list.content.first() val last = list.content.last() first.previous = last last.next = first return list } } fun groveCoordinates(): List<Int> = buildList { var current = start repeat(3) { current = current[1000] add(current.id) } } fun mixing() { content.forEach { node -> repeat(node.data.absoluteValue.toInt()) { if (node.data < 0) { swap(node.previous, node) } else { swap(node, node.next) } } } } operator fun get(index: Int): Node = content[index] } data class Node(val id: Int, val data: Long, val originalData: Long) { lateinit var previous: Node lateinit var next: Node operator fun get(index: Int): Node { var current = this repeat(index) { current = current.next } return current } } override fun part1(input: List<String>): Long { val list = CyclicLinkedList.from(input.map { it.toLong() }) list.mixing() return list.groveCoordinates().sumOf { list[it].data } } override fun part2(input: List<String>): Long { val key = 811589153L val list = CyclicLinkedList.from(input.map { it.toLong() }, key) // mix 10 times repeat(10) { list.mixing() } // use originValue to compute sum, since data is % cycle length return list.groveCoordinates().sumOf { list[it].originalData * key } } } fun main() = Day20().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
3,407
advent-of-code
Apache License 2.0
src/main/kotlin/solutions/day03/Day3.kt
Dr-Horv
112,381,975
false
null
package solutions.day03 import solutions.Solver import utils.Coordinate import utils.Direction import utils.step data class Cursor(var x: Int, var y:Int) fun Cursor.manhattanDistance() : Int = Math.abs(x) + Math.abs(y) data class CircleInfo(val circle: Int, val numbers: Int) class Day3: Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val target = input.first().toInt() if(target == 1) { return 0.toString() } if(partTwo) { return doPartTwo(target) } val circleInfo = determineCircle(target) val number = circleInfo.numbers + (circleInfo.circle-2) val cursor = Cursor(circleInfo.circle - 1, 0) val valueAtTopRightCorner = number + (circleInfo.circle - 1) if(target <= valueAtTopRightCorner) { val steps = (target-number) - 1 cursor.y = cursor.y + steps return cursor.manhattanDistance().toString() } cursor.y = circleInfo.circle - 1 val stepsToTraverseSide = (circleInfo.circle - 1) * 2 val valueAtTopLeftCorner = valueAtTopRightCorner + stepsToTraverseSide if(target <= valueAtTopLeftCorner) { val steps = target - valueAtTopRightCorner - 1 cursor.x = cursor.x - steps return cursor.manhattanDistance().toString() } cursor.x = cursor.x - stepsToTraverseSide val valueAtBottomLeftCorner = valueAtTopLeftCorner + stepsToTraverseSide if(target <= valueAtBottomLeftCorner) { val steps = target - valueAtTopLeftCorner - 1 cursor.y = cursor.y - steps return cursor.manhattanDistance().toString() } cursor.y = cursor.y - stepsToTraverseSide val valueAtBottomRightCorner = valueAtBottomLeftCorner + stepsToTraverseSide if(target <= valueAtBottomRightCorner) { val steps = target - valueAtBottomLeftCorner - 1 cursor.x = cursor.x + steps return cursor.manhattanDistance().toString() } cursor.x = cursor.x + stepsToTraverseSide val valueBeforeBackAtStart = valueAtBottomRightCorner + (stepsToTraverseSide / 2 - 1) if(target <= valueBeforeBackAtStart) { val steps = target - valueAtBottomRightCorner - 1 cursor.y = cursor.y + steps return cursor.manhattanDistance().toString() } throw RuntimeException("Not found") } private fun doPartTwo(target: Int): String { val memory: MutableMap<Coordinate, Int> = mutableMapOf<Coordinate, Int>().withDefault { 0 } val start = Coordinate(0, 0) memory.put(start, 1) return traverse(target, start, memory, Direction.RIGHT, 1) } private fun traverse(target: Int, curr: Coordinate, memory: MutableMap<Coordinate, Int>, direction: Direction, steps: Int): String { if(steps == 0) { val circleInfo = determineCircle(memory.size) val stepsNext = (circleInfo.circle - 1) * 2 return when(direction) { Direction.UP -> traverse(target, curr, memory, Direction.LEFT, stepsNext) Direction.LEFT -> traverse(target, curr, memory, Direction.DOWN, stepsNext) Direction.DOWN -> traverse(target, curr, memory, Direction.RIGHT, stepsNext+1) Direction.RIGHT -> traverse(target, curr, memory, Direction.UP, stepsNext-1) } } val next = curr.step(direction) val sum = getSum(next, memory) if(sum > target) { return sum.toString() } memory.put(next, sum) return traverse(target, next, memory, direction, steps-1) } private fun getSum(coordinate: Coordinate, memory: MutableMap<Coordinate, Int>): Int { return memory.getValue(coordinate.step(Direction.UP)) + memory.getValue(coordinate.step(Direction.LEFT)) + memory.getValue(coordinate.step(Direction.RIGHT)) + memory.getValue(coordinate.step(Direction.DOWN)) + memory.getValue(Coordinate(coordinate.x+1, coordinate.y+1)) + memory.getValue(Coordinate(coordinate.x-1, coordinate.y+1)) + memory.getValue(Coordinate(coordinate.x+1, coordinate.y-1)) + memory.getValue(Coordinate(coordinate.x-1, coordinate.y-1)) } private fun determineCircle(target: Int): CircleInfo { var steps = 0 if(target > 1) { steps += 1 } var circle = 2 while(true) { val nextSteps = steps + (circle-1) * 8 if(nextSteps > target) { return CircleInfo(circle, steps) } circle++ steps = nextSteps } } }
0
Kotlin
0
2
975695cc49f19a42c0407f41355abbfe0cb3cc59
4,840
Advent-of-Code-2017
MIT License
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/graphs/prim/Prim.kt
FunkyMuse
168,687,007
false
{"Kotlin": 1728251}
package dev.funkymuse.datastructuresandalgorithms.graphs.prim import dev.funkymuse.datastructuresandalgorithms.graphs.Edge import dev.funkymuse.datastructuresandalgorithms.graphs.EdgeType import dev.funkymuse.datastructuresandalgorithms.graphs.Graph import dev.funkymuse.datastructuresandalgorithms.graphs.Vertex import dev.funkymuse.datastructuresandalgorithms.graphs.adjacency.AdjacencyList import dev.funkymuse.datastructuresandalgorithms.queue.priority.AbstractPriorityQueue import dev.funkymuse.datastructuresandalgorithms.queue.priority.comparator.ComparatorPriorityQueue import kotlin.math.roundToInt object Prim { private fun <T> addAvailableEdges(vertex: Vertex<T>, graph: Graph<T>, visited: Set<Vertex<T>>, priorityQueue: AbstractPriorityQueue<Edge<T>>) { graph.edges(vertex).forEach { edge -> if (edge.destination !in visited) { priorityQueue.enqueue(edge) } } } fun <T> produceMinimumSpanningTree(graph: AdjacencyList<T>): Pair<Double, AdjacencyList<T>> { var cost = 0.0 val adjacencyList = AdjacencyList<T>() val visited = mutableSetOf<Vertex<T>>() val comparator = Comparator<Edge<T>> { first, second -> val firstWeight = first.weight ?: 0.0 val secondWeight = second.weight ?: 0.0 (secondWeight - firstWeight).roundToInt() } val priorityQueue = ComparatorPriorityQueue(comparator) adjacencyList.copyVertices(graph) val start = graph.allVertices.firstOrNull() ?: return Pair(cost, adjacencyList) visited.add(start) addAvailableEdges(start, graph, visited, priorityQueue) while (true) { val smallestEdge = priorityQueue.dequeue() ?: break val vertex = smallestEdge.destination if (vertex in visited) continue visited.add(vertex) cost += smallestEdge.weight ?: 0.0 adjacencyList.add(EdgeType.UNDIRECTED, smallestEdge.source, smallestEdge.destination, smallestEdge.weight) addAvailableEdges(vertex, graph, visited, priorityQueue) } return Pair(cost, adjacencyList) } }
0
Kotlin
92
771
e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1
2,185
KAHelpers
MIT License
src/main/kotlin/com/colinodell/advent2021/Day03.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 class Day03 (private val input: List<String>) { private val bitSize = input.first().length fun solvePart1(): Int { // For each column / bit-index, figure out the most common bit value, and then concatenate those together var gammaRateAsString = (0 until bitSize).concatenationOf { column -> input.mostCommonBit(column) } // Convert binary string to decimal val gammaRateDecimal = Integer.parseInt(gammaRateAsString, 2) // Clever way to find the epsilon rate, since the sum of both rates will always equal // one less than the maximum value that can be stored in `bitSize` bits val epsilonRateDecimal = (1 shl bitSize) - gammaRateDecimal - 1 return gammaRateDecimal * epsilonRateDecimal } fun solvePart2(): Int { // Set to 1, since we'll be multiplying the answer as we go var answer = 1 // First we operate with the most common bit, then we operate with the opposite of that (the least common bit) for (mostCommon in listOf(true, false)) { // Clone the list of numbers var numbers = input.toMutableList() // At each bit position... for (bitPosition in 0 until bitSize) { // Remove all numbers that don't have the desired bit // The `== mostCommon` part is just a clever shortcut to invert the result so we find the least common bit numbers = numbers.filter { (it.get(bitPosition) == numbers.mostCommonBit(bitPosition)) == mostCommon }.toMutableList() // Only one number left? It must be our answer if (numbers.size == 1) { answer *= numbers[0].toInt(2) break } } } return answer } // Using input data, return the most common bit at the given column private fun List<String>.mostCommonBit(column: Int): Char { val onesCount = this.count { it[column] == '1' } val zeroesCount = this.size - onesCount return if (onesCount >= zeroesCount) '1' else '0' } // Using the current iterable, execute the given function on each element and concatenate the returned chars into a string private inline fun <T> Iterable<T>.concatenationOf(selector: (T) -> Char): String { var result = "" for (element in this) { result += selector(element) } return result } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
2,510
advent-2021
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ReconstructItinerary.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.PriorityQueue import java.util.Stack /** * 332. Reconstruct Itinerary * @see <a href="https://leetcode.com/problems/reconstruct-itinerary">Source</a> */ fun interface ReconstructItinerary { operator fun invoke(tickets: List<List<String>>): List<String> } class ReconstructItineraryRecursive : ReconstructItinerary { private val targets: MutableMap<String, PriorityQueue<String>> = HashMap() private val route: MutableList<String> = LinkedList() override fun invoke(tickets: List<List<String>>): List<String> { for (ticket in tickets) targets.computeIfAbsent(ticket[0]) { PriorityQueue() }.add(ticket[1]) visit("JFK") return route } private fun visit(airport: String) { while (targets.containsKey(airport) && targets[airport]?.isEmpty()?.not() == true) { targets[airport]?.let { visit(it.poll()) } } route.add(0, airport) } } class ReconstructItineraryIterative : ReconstructItinerary { override fun invoke(tickets: List<List<String>>): List<String> { val targets: MutableMap<String, PriorityQueue<String?>> = HashMap() for (ticket in tickets) targets.computeIfAbsent(ticket[0]) { PriorityQueue() }.add(ticket[1]) val route: MutableList<String> = LinkedList() val stack: Stack<String> = Stack() stack.push("JFK") while (!stack.empty()) { while (targets.containsKey(stack.peek()) && targets[stack.peek()]?.isEmpty()?.not() == true) { stack.push(targets[stack.peek()]?.poll()) } route.add(0, stack.pop()) } return route } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,329
kotlab
Apache License 2.0
src/main/kotlin/adventofcode2018/Day11ChronalCharge.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2018 class Day11ChronalCharge data class FuelCell(val x: Int, val y: Int, val powerLevel: Int) { companion object { fun forSerialNumber(x: Int, y: Int, serialNumber: Int): FuelCell = FuelCell(x, y, computePowerLevel(x, y, serialNumber)) private fun computePowerLevel(x: Int, y: Int, serialNumber: Int): Int { var powerLevel = ((x + 10) * y + serialNumber) * (x + 10) if (powerLevel > 99) { powerLevel = (powerLevel / 100) % 10 } else { powerLevel = 0 } powerLevel -= 5 return powerLevel } } } class PowerGrid(val serialNumber: Int) { val fuelCells: List<FuelCell> val squareScores = mutableMapOf<FuelCell, Int>() init { fuelCells = (1..300).flatMap { x -> (1..300).map { y -> FuelCell.forSerialNumber(x, y, serialNumber) } } } fun calculateScores(maxGridSize: Int) { (1..89397).forEach { index -> squareScores[fuelCells[index]] = computeScoreAt(index, maxGridSize) } } fun findLargestGrid(): String { var largestGrid = "" var maxScore = 0 (1 .. 300).forEach { gridSize -> (0 until (300 - gridSize)).forEach { x -> (0 until (300 - gridSize)).forEach { y -> val currentScore = computeScoreAt(y + (300 * x), gridSize) if (currentScore > maxScore) { maxScore = currentScore largestGrid = "${x + 1},${y + 1},$gridSize" } } } } return largestGrid } private fun computeScoreAt(index: Int, gridSize: Int): Int { var result = 0 (0 until gridSize).forEach { y -> (300 * y until (300 * y + gridSize)).forEach { result += fuelCells[index + it].powerLevel } } return result } fun getHighestPowerLevelCoordinates(): String { val highScoreCell = squareScores.maxBy { it.value } return "${highScoreCell.key.x},${highScoreCell.key.y}" } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
2,197
kotlin-coding-challenges
MIT License
src/test/kotlin/year2015/Day13.kt
abelkov
47,995,527
false
{"Kotlin": 48425}
package year2015 import kotlin.math.max import kotlin.test.* class Day13 { @Test fun part1() { val map = mutableMapOf<String, MutableMap<String, Int>>() // Alice would gain 54 happiness units by sitting next to Bob. val regex = """(\w+) would (\w+) (\d+) happiness units by sitting next to (\w+).""".toRegex() for (line in readInput("year2015/Day13.txt").lines()) { val matchResult = regex.matchEntire(line) val (person1, sign, units, person2) = matchResult!!.groupValues.drop(1) map.putIfAbsent(person1, mutableMapOf()) val signedUnits = if (sign == "gain") units.toInt() else -units.toInt() map.getValue(person1)[person2] = signedUnits } var optimal = Int.MIN_VALUE for (guests: List<String> in map.keys.permutations()) { var sum = 0 for ((index, guest) in guests.withIndex()) { val prevIndex = (index - 1).mod(guests.size) val nextIndex = (index + 1).mod(guests.size) val prevGuest = guests[prevIndex] val nextGuest = guests[nextIndex] sum += map.getValue(guest).getValue(prevGuest) sum += map.getValue(guest).getValue(nextGuest) } optimal = max(optimal, sum) } assertEquals(709, optimal) } @Test fun part2() { val map = mutableMapOf<String, MutableMap<String, Int>>() // Alice would gain 54 happiness units by sitting next to Bob. val regex = """(\w+) would (\w+) (\d+) happiness units by sitting next to (\w+).""".toRegex() for (line in readInput("year2015/Day13.txt").lines()) { val matchResult = regex.matchEntire(line) val (person1, sign, units, person2) = matchResult!!.groupValues.drop(1) map.putIfAbsent(person1, mutableMapOf()) val signedUnits = if (sign == "gain") units.toInt() else -units.toInt() map.getValue(person1)[person2] = signedUnits } map["me"] = mutableMapOf() for (person in map.keys) { map.getValue(person)["me"] = 0 map.getValue("me")[person] = 0 } var optimal = Int.MIN_VALUE for (guests: List<String> in map.keys.permutations()) { var sum = 0 for ((index, guest) in guests.withIndex()) { val prevIndex = (index - 1).mod(guests.size) val nextIndex = (index + 1).mod(guests.size) val prevGuest = guests[prevIndex] val nextGuest = guests[nextIndex] sum += map.getValue(guest).getValue(prevGuest) sum += map.getValue(guest).getValue(nextGuest) } optimal = max(optimal, sum) } assertEquals(668, optimal) } }
0
Kotlin
0
0
0e4b827a742322f42c2015ae49ebc976e2ef0aa8
2,864
advent-of-code
MIT License
src/main/kotlin/io/github/sdkei/kotlin_jvm_utils/PermutationAndCombination.kt
sdkei
150,868,041
false
{"Kotlin": 28918}
package io.github.sdkei.kotlin_jvm_utils /** * Returns permutation of elements of the receiver. * * ``` * listOf("A", "B", "C").permutation(2) // -> [[A, B], [A, C], [B, A], [B, C], [C, A], [C, B]] * ``` * * @param count number of elements of permutation. */ fun <T> Iterable<T>.permutation(count: Int): List<List<T>> { require(count >= 0) val inputList = if (this is List<T>) this else toList() require(count <= inputList.size) return inputList.subPermutation(count) } private fun <T> List<T>.subPermutation(count: Int): List<List<T>> { if (count == 1) return map { listOf(it) } return (0 until size).flatMap { index -> val first = listOf(this[index]) (subList(0, index) + subList(index + 1, size)) .subPermutation(count - 1) .map { first + it } } } /** * Returns combination of elements of the receiver. * * ``` * listOf("A", "B", "C", "D").combination(3) // -> [[A, B, C], [A, B, D], [A, C, D], [B, C, D]] * ``` * * @param count number of elements of combination. */ fun <T> Iterable<T>.combination(count: Int): List<List<T>> { require(count >= 0) val inputList = if (this is List<T>) this else toList() require(count <= inputList.size) return inputList.subCombination(count) } private fun <T> List<T>.subCombination(count: Int): List<List<T>> { if (count == 1) return map { listOf(it) } return (0 until size - (count - 1)).flatMap { index -> val first = listOf(this[index]) subList(index + 1, size) .subCombination(count - 1) .map { first + it } } }
0
Kotlin
0
0
db6280c9442bdb317db5717860f105d3371edf77
1,632
KotlinJvmUtils
Apache License 2.0
src/main/kotlin/g2401_2500/s2416_sum_of_prefix_scores_of_strings/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2416_sum_of_prefix_scores_of_strings // #Hard #Array #String #Counting #Trie #2023_07_04_Time_2062_ms_(50.00%)_Space_191.8_MB_(100.00%) class Solution { private val child: Array<Solution?> = arrayOfNulls(26) private var ct: Int = 0 fun sumPrefixScores(words: Array<String>): IntArray { for (s in words) { insert(s) } val res = IntArray(words.size) for (i in words.indices) { val word = words[i] res[i] = countPre(word) } return res } private fun insert(word: String) { var cur: Solution? = this for (element in word) { val id = element.code - 'a'.code if (cur!!.child[id] == null) { cur.child[id] = Solution() } cur.child[id]!!.ct++ cur = cur.child[id] } } private fun countPre(word: String): Int { var cur: Solution? = this var localCt = 0 for (element in word) { val id = element.code - 'a'.code if (cur!!.child[id] == null) { return localCt } localCt += cur.ct cur = cur.child[id] } localCt += cur!!.ct return localCt } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,290
LeetCode-in-Kotlin
MIT License
src/Day25.kt
wgolyakov
572,463,468
false
null
import kotlin.math.max fun main() { val toDecimalDigit = mapOf( '2' to 2, '1' to 1, '0' to 0, '-' to -1, '=' to -2, ) val toSnafuDigit = mapOf( 0 to "0", 1 to "1", 2 to "2", 3 to "1=", 4 to "1-", 5 to "10", 6 to "11", 7 to "12", 8 to "2=", 9 to "2-", ) fun toDecimal(snafu: String): Long { var decimal = 0L var p = 1L for (c in snafu.reversed()) { decimal += p * toDecimalDigit[c]!! p *= 5 } return decimal } fun toSnafu(decimal: Long): String { var n = decimal val snafu = StringBuilder() var r = 0 do { val d = (n % 5).toInt() + r n /= 5 val s = toSnafuDigit[d]!! snafu.insert(0, s.last()) r = if (s.length > 1) s[0].digitToInt() else 0 } while (n > 0) if (r != 0) snafu.insert(0, toSnafuDigit[r]!!) return snafu.toString() } fun part1(input: List<String>) = toSnafu(input.sumOf { toDecimal(it) }) val snafuDigitsSum = mapOf( ('2' to '2') to "1-", ('2' to '1') to "1=", ('2' to '0') to "2", ('2' to '-') to "1", ('2' to '=') to "0", ('1' to '2') to "1=", ('1' to '1') to "2", ('1' to '0') to "1", ('1' to '-') to "0", ('1' to '=') to "-", ('0' to '2') to "2", ('0' to '1') to "1", ('0' to '0') to "0", ('0' to '-') to "-", ('0' to '=') to "=", ('-' to '2') to "1", ('-' to '1') to "0", ('-' to '0') to "-", ('-' to '-') to "=", ('-' to '=') to "-2", ('=' to '2') to "0", ('=' to '1') to "-", ('=' to '0') to "=", ('=' to '-') to "-2", ('=' to '=') to "-1", ) fun plus(snafu1: String, snafu2: String): String { val sum = StringBuilder() var r = '0' for (i in 0 until max(snafu1.length, snafu2.length)) { val d1 = if (i < snafu1.length) snafu1[snafu1.length - 1 - i] else '0' val d2 = if (i < snafu2.length) snafu2[snafu2.length - 1 - i] else '0' val s1 = snafuDigitsSum[d1 to d2]!! val s2 = snafuDigitsSum[s1.last() to r]!! sum.insert(0, s2.last()) val r1 = if (s1.length > 1) s1[0] else '0' val r2 = if (s2.length > 1) s2[0] else '0' r = snafuDigitsSum[r1 to r2]!![0] } if (r != '0') sum.insert(0, r) return sum.toString() } fun part2(input: List<String>) = input.reduce { a, b -> plus(a, b) } val testInput = readInput("Day25_test") check(part1(testInput) == "2=-1=0") check(part2(testInput) == "2=-1=0") val input = readInput("Day25") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
789a2a027ea57954301d7267a14e26e39bfbc3c7
2,375
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day2.kt
dlew
75,886,947
false
null
class Day2 { enum class Move { UP, DOWN, LEFT, RIGHT } data class Location(val x: Int, val y: Int) companion object { val INV = 'Z' // Invalid character val NUMBER_GRID = arrayOf( arrayOf('1', '2', '3'), arrayOf('4', '5', '6'), arrayOf('7', '8', '9') ) val HARD_GRID = arrayOf( arrayOf(INV, INV, '1', INV, INV), arrayOf(INV, '2', '3', '4', INV), arrayOf('5', '6', '7', '8', '9'), arrayOf(INV, 'A', 'B', 'C', INV), arrayOf(INV, INV, 'D', INV, INV) ) private fun parseInput(input: String): List<List<Move>> = input.split('\n') .map { it.map { c -> when (c) { 'U' -> Move.UP 'D' -> Move.DOWN 'L' -> Move.LEFT 'R' -> Move.RIGHT else -> throw IllegalArgumentException("Invalid input character: '$c'") } } } fun decode(grid: Array<Array<Char>>, start: Location, input: String) = parseInput(input) .fold(listOf(start), { state, moves -> state.plusElement(executeMoves(grid, state.last(), moves)) }) .drop(1) .fold("", { text, loc -> text + grid[loc.y][loc.x] }) private fun executeMoves(grid: Array<Array<Char>>, start: Location, moves: List<Move>) = moves.fold(start, { location, move -> executeMove(grid, location, move) }) private fun executeMove(grid: Array<Array<Char>>, loc: Location, move: Move): Location = when (move) { Move.UP -> { val newY = loc.y - 1 if (newY < 0 || grid[loc.x][newY] == INV) loc else Location(loc.x, newY) } Move.DOWN -> { val newY = loc.y + 1 if (newY >= grid[loc.x].size || grid[loc.x][newY] == INV) loc else Location(loc.x, newY) } Move.LEFT -> { val newX = loc.x - 1 if (newX < 0 || grid[newX][loc.y] == INV) loc else Location(newX, loc.y) } Move.RIGHT -> { val newX = loc.x + 1 if (newX >= grid.size || grid[newX][loc.y] == INV) loc else Location(newX, loc.y) } } } }
0
Kotlin
2
12
527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd
2,256
aoc-2016
MIT License
src/main/kotlin/days/Day3.kt
andilau
573,139,461
false
{"Kotlin": 65955}
package days @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2022/day/3", date = Date(day = 3, year = 2022) ) class Day3(input: List<String>) : Puzzle { private val rucksacks = input.asSequence().map { line -> Rucksack.from(line) } override fun partOne(): Int = rucksacks.sumOf { it.priority() } override fun partTwo(): Int = rucksacks.chunked(3) .map { it.map(Rucksack::content).reduce { a, b -> a intersect b }.single().priority() } .sum() companion object { private val PRIORITY = ('a'..'z') + ('A'..'Z') fun Char.priority() = PRIORITY.indexOf(this).plus(1) } data class Rucksack(val line: String) { fun content(): Set<Char> = line.toSet() fun priority(): Int = line .chunked(line.length / 2) .map { it.toSet() } .reduce { a, b -> a intersect b } .sumOf { it.priority() } companion object { fun from(line: String): Rucksack = Rucksack(line) } } }
0
Kotlin
0
0
da824f8c562d72387940844aff306b22f605db40
1,062
advent-of-code-2022
Creative Commons Zero v1.0 Universal
src/day03/Day03.kt
ubuntudroid
571,771,936
false
{"Kotlin": 7845}
package day03 import readInput fun main() { val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int = input .map { it.subSequence(0, it.length / 2) to it.subSequence(it.length / 2, it.length) } .map { (firstCompartment, secondCompartment) -> firstCompartment.find { secondCompartment.contains(it) }!! } .sumOf { it.toPriority() } fun part2(input: List<String>): Int = input .chunked(3) { elfGroupRucksacks -> elfGroupRucksacks[0].find { elfGroupRucksacks[1].contains(it) && elfGroupRucksacks[2].contains(it) }!! } .sumOf { it.toPriority() } fun Char.toPriority(): Int = when (this) { 'a' -> 1 'b' -> 2 'c' -> 3 'd' -> 4 'e' -> 5 'f' -> 6 'g' -> 7 'h' -> 8 'i' -> 9 'j' -> 10 'k' -> 11 'l' -> 12 'm' -> 13 'n' -> 14 'o' -> 15 'p' -> 16 'q' -> 17 'r' -> 18 's' -> 19 't' -> 20 'u' -> 21 'v' -> 22 'w' -> 23 'x' -> 24 'y' -> 25 'z' -> 26 'A' -> 27 'B' -> 28 'C' -> 29 'D' -> 30 'E' -> 31 'F' -> 32 'G' -> 33 'H' -> 34 'I' -> 35 'J' -> 36 'K' -> 37 'L' -> 38 'M' -> 39 'N' -> 40 'O' -> 41 'P' -> 42 'Q' -> 43 'R' -> 44 'S' -> 45 'T' -> 46 'U' -> 47 'V' -> 48 'W' -> 49 'X' -> 50 'Y' -> 51 'Z' -> 52 else -> throw IllegalArgumentException("Unknown priority: $this") }
0
Kotlin
0
0
fde55dcf7583aac6571c0f6fc2d323d235337c27
1,480
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxFrequency.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 1838. Frequency of the Most Frequent Element * @see <a href="https://leetcode.com/problems/frequency-of-the-most-frequent-element/">Source</a> */ fun interface MaxFrequency { fun maxFrequency(nums: IntArray, k: Int): Int } class MaxFrequencySlidingWindow : MaxFrequency { override fun maxFrequency(nums: IntArray, k: Int): Int { val n = nums.size nums.sort() var ans = 0 var left = 0 var sum: Long = 0 for (right in 0 until n) { sum += nums[right] while (nums[right] * 1L * (right - left + 1) - sum > k) { sum -= nums[left] left++ } ans = max(ans, right - left + 1) } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,418
kotlab
Apache License 2.0
kotlin/2021/round-1b/broken-clock/src/main/kotlin/Solution.kt
ShreckYe
345,946,821
false
null
import java.math.BigInteger fun main() { val t = readLine()!!.toInt() repeat(t, ::testCase) } fun testCase(ti: Int) { val (a, b, c) = readLine()!!.splitToSequence(' ').map { it.toLong() }.toList() val ans = ans(a, b, c) with(ans) { println("Case #${ti + 1}: $h $m $s $n") } } data class Time(val h: Long, val m: Long, val s: Long, val n: Long) fun ans(a: Long, b: Long, c: Long) = listOf( listOf(a, b, c), listOf(a, c, b), listOf(b, a, c), listOf(b, c, a), listOf(c, a, b), listOf(c, b, a) ).asSequence() .mapNotNull { (hnt, mnt, snt) -> ansHMSNT(hnt, mnt, snt) }.first() // nt = num ticks fun ansHMSNT(hnt: Long, mnt: Long, snt: Long): Time? { val nsAfterHMOverlap = (mnt - hnt).toPosNumTicks().toFraction() / (mSpeedInNs - hSpeedInNs).toFraction() val nsAfterMSOverlap = (snt - mnt).toPosNumTicks().toFraction() / (sSpeedInNs - mSpeedInNs).toFraction() val allInNs = hmOverlapTimesInNs.asSequence() .map { (it + nsAfterHMOverlap).toIntegerOrNull()?.toLong() } .find { allInNs -> allInNs !== null && msOverlapTimesInNs.any { val nsAfterH = (it + nsAfterMSOverlap).toIntegerOrNull()?.toLong() nsAfterH !== null && (allInNs % hInNs) == nsAfterH } } return if (allInNs != null) allInNsToTime(allInNs) else null } fun allInNsToTime(allInNs: Long): Time { var r: Long val n = allInNs % sInNs r = allInNs / sInNs val s = r % mInS r /= mInS val m = r % hInM r /= hInM val h = r return Time(h, m, s, n) } const val hSpeedInNs = 1L const val mSpeedInNs = 12L const val sSpeedInNs = 720L infix fun Long.intDiv(that: Long): Long? = if (this % that != 0L) null else this / that const val numCircleTicks = 360 * 12 * 10_000_000_000L fun Long.toPosNumTicks(): Long = if (this >= 0) this else this + numCircleTicks val sInNs = 1_000_000_000L val mInS = 60L val hInM = 60L val hInNs = hInM * mInS * sInNs val hmOverlapGapNumTicks = numCircleTicks divBy 11 val hmOverlapTimesInNs = List(11) { hmOverlapGapNumTicks * it.toFraction() / hSpeedInNs.toFraction() } val msOverlapGapNumTicks = numCircleTicks divBy 59 val msOverlapTimesInNs = List(59) { msOverlapGapNumTicks * it.toFraction() / mSpeedInNs.toFraction() } data class Fraction internal constructor(val numerator: BigInteger, val denominator: BigInteger) { init { require(denominator > BigInteger.ZERO) } operator fun plus(that: Fraction) = reducedFraction( numerator * that.denominator + that.numerator * denominator, denominator * that.denominator ) operator fun unaryMinus() = Fraction(-numerator, denominator) operator fun minus(that: Fraction) = this + -that operator fun times(that: Fraction) = reducedFraction(numerator * that.numerator, denominator * that.denominator) fun inv() = if (numerator > BigInteger.ZERO) Fraction(denominator, numerator) else Fraction(-denominator, -numerator) operator fun div(that: Fraction) = this * that.inv() operator fun compareTo(that: Fraction) = (numerator * that.denominator).compareTo(that.numerator * denominator) override fun toString(): String = "$numerator/$denominator" fun toSimplestString(): String = if (denominator == BigInteger.ONE) numerator.toString() else toString() fun toIntegerOrNull(): BigInteger? = if (denominator == BigInteger.ONE) numerator else null companion object { val zero = Fraction(BigInteger.ZERO, BigInteger.ONE) val one = Fraction(BigInteger.ONE, BigInteger.ONE) } } fun reducedFraction(numerator: BigInteger, denominator: BigInteger): Fraction { val gcd = numerator.gcd(denominator) val nDivGcd = numerator / gcd val dDivGcd = denominator / gcd return if (denominator > BigInteger.ZERO) Fraction(nDivGcd, dDivGcd) else Fraction(-nDivGcd, -dDivGcd) } infix fun BigInteger.divBy(that: BigInteger) = reducedFraction(this, that) infix fun Int.divBy(that: Int) = toBigInteger() divBy that.toBigInteger() infix fun Long.divBy(that: Long) = toBigInteger() divBy that.toBigInteger() fun BigInteger.toFraction() = Fraction(this, BigInteger.ONE) fun Int.toFraction() = toBigInteger().toFraction() fun Long.toFraction() = toBigInteger().toFraction()
0
Kotlin
1
1
743540a46ec157a6f2ddb4de806a69e5126f10ad
4,470
google-code-jam
MIT License
src/main/kotlin/g0401_0500/s0488_zuma_game/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0401_0500.s0488_zuma_game // #Hard #String #Dynamic_Programming #Breadth_First_Search #Memoization // #2023_01_03_Time_1727_ms_(100.00%)_Space_131.5_MB_(100.00%) class Solution { fun findMinStep(board: String, hand: String): Int { return dfs(board, hand) } private fun dfs(board: String, hand: String): Int { return findMinStepDp(board, hand, HashMap()) } private fun findMinStepDp(board: String, hand: String, dp: MutableMap<String, MutableMap<String, Int?>?>): Int { if (board.isEmpty()) { return 0 } if (hand.isEmpty()) { return -1 } if (dp[board] != null && dp[board]!![hand] != null) { return dp[board]!![hand]!! } var min = -1 for (i in 0..board.length) { for (j in 0 until hand.length) { if ((j == 0 || hand[j] != hand[j - 1]) && (i == 0 || board[i - 1] != hand[j]) && ( i < board.length && board[i] == hand[j] || i > 0 && i < board.length && board[i - 1] == board[i] && board[i] != hand[j] ) ) { val newS = StringBuilder(board) newS.insert(i, hand[j]) val sR = findMinStepDp( removeRepeated(newS.toString()), hand.substring(0, j) + hand.substring(j + 1, hand.length), dp ) if (sR != -1) { min = if (min == -1) sR + 1 else Integer.min(min, sR + 1) } } } } dp.putIfAbsent(board, HashMap()) dp[board]!![hand] = min return min } private fun removeRepeated(original: String): String { var count = 1 var i = 1 while (i < original.length) { if (original[i] == original[i - 1]) { count++ i++ } else { if (count >= 3) { return removeRepeated( original.substring(0, i - count) + original.substring(i, original.length) ) } else { count = 1 i++ } } } return if (count >= 3) { removeRepeated(original.substring(0, original.length - count)) } else { original } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,585
LeetCode-in-Kotlin
MIT License
kotlin/src/main/kotlin/com/tolchev/algo/array/435NonOverlappingIntervals.kt
VTolchev
692,559,009
false
{"Kotlin": 53858, "C#": 47939, "Java": 1802}
package com.tolchev.algo.array class NonOverlappingIntervals { fun eraseOverlapIntervals(intervals: Array<IntArray>): Int { intervals.sortWith { a, b -> a[1].compareTo(b[1]) } var maxFinishTime = intervals[0][1] var removeCount = 0 for (i in 1 ..< intervals.size) if (intervals[i][0] < maxFinishTime){ removeCount++ } else{ maxFinishTime = intervals[i][1] } return removeCount } } class NonOverlappingIntervalsSlow { fun eraseOverlapIntervals(intervals: Array<IntArray>): Int { var allIntersection = Array<MutableSet<Int>>(intervals.size){mutableSetOf()} intervals.sortWith { a, b -> a[0].compareTo(b[0]) } for (i1 in 0 ..< intervals.size-1){ var i2 = i1 +1 while (i2 < intervals.size && (intervals[i2][0] < intervals[i1][1])){ allIntersection[i1].add(i2) allIntersection[i2].add(i1) i2++ } } var removeCount = 0 var i1 = 0 while (i1 < intervals.size){ var i2 = i1 + 1 while ((allIntersection[i1]?.size ?: 0) != 0 && (allIntersection[i2]?.size ?: 0) != 0 && intervals[i2][0] < intervals[i1][1]) { if (allIntersection[i1]!!.size > allIntersection[i2]!!.size){ removeInterval(i1, allIntersection) } else{ removeInterval(i2, allIntersection) i2++ } removeCount++ } i1++ } return removeCount } private fun removeInterval(index: Int, allIntersection : Array<MutableSet<Int>>) { var intersections = allIntersection[index]!! for (intersection in intersections) { allIntersection[intersection]!!.remove(index) } intersections.clear() } }
0
Kotlin
0
0
c3129f23e4e7ba42b44f9fb4af39a95f4a762550
2,012
algo
MIT License
year2021/day09/basin/src/main/kotlin/com/curtislb/adventofcode/year2021/day09/basin/HeightMap.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2021.day09.basin import com.curtislb.adventofcode.common.grid.Grid import com.curtislb.adventofcode.common.geometry.Point import com.curtislb.adventofcode.common.grid.forEachPointValue import com.curtislb.adventofcode.common.grid.mutableGridOf /** * A map of heights at various positions on an undersea cave floor. * * @param mapString A string representing the height of all floor positions. The string must consist * of equal-length lines, each of the form `"${A}${B}${C}..."`, where `A`, `B`, `C`, etc. are * decimal digits representing the heights of the given character positions. * * @throws IllegalArgumentException If `mapString` does not match the required format. */ class HeightMap(mapString: String) { /** * A grid containing the heights of all floor positions. */ private val heightGrid: Grid<Int> = mutableGridOf<Int>().apply { for (line in mapString.trim().lines()) { val heights = line.trim().map { it.digitToInt() } addShallowRow(heights) } } /** * Returns the sizes of all basins in this heightmap. * * A basin is a contiguous collection of cardinally adjacent positions with heights less than * [MAX_HEIGHT]. The size of a basin is the number of distinct positions that are part of it. */ fun findBasinSizes(): List<Int> { // Keep track of all previously visited basin points val visited = mutableSetOf<Point>() // Counts contiguous unvisited basin points reachable from (and including) `point` fun unvisitedSizeFrom(point: Point): Int = if (point !in visited && isBasin(point)) { // Once it's been counted, mark this basin point as visited visited.add(point) 1 + point.cardinalNeighbors().sumOf { unvisitedSizeFrom(it) } } else { 0 } // Scan through the heightmap, greedily searching for basins val basinSizes = mutableListOf<Int>() heightGrid.forEachPointValue { point, height -> if (point !in visited && height < MAX_HEIGHT) { basinSizes.add(unvisitedSizeFrom(point)) } } return basinSizes } /** * Returns the positions of all low points in this height map. * * A low point is any floor position with a height that is lower than all cardinally adjacent * positions in the heightmap. */ fun findLowPoints(): List<Point> { val points = mutableListOf<Point>() heightGrid.forEachPointValue { point, height -> // Check if all cardinal neighbor positions are lower than this one val isLowPoint = point.cardinalNeighbors().all { neighbor -> val neighborHeight = heightGrid.getOrNull(neighbor) neighborHeight == null || neighborHeight > height } if (isLowPoint) { points.add(point) } } return points } /** * Checks if the given [point] position is a part of a basin in this heightmap. * * See [findBasinSizes] for the definition of a basin. */ fun isBasin(point: Point): Boolean = heightGrid.getOrNull(point)?.let { it < MAX_HEIGHT } == true /** * Returns the risk level for a given [point] position in this heightmap. * * @throws IndexOutOfBoundsException If [point] is outside the range of the heightmap. */ fun riskLevel(point: Point): Int = heightGrid[point] + 1 companion object { /** * The maximum height of any floor position in a heightmap. */ private const val MAX_HEIGHT = 9 } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
3,757
AdventOfCode
MIT License
16.kts
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
import kotlin.math.max val grid = System.`in`.bufferedReader().lines().toList() val up = Pair(0, -1); val right = Pair(1, 0); val down = Pair(0, 1); val left = Pair(-1, 0) data class Beam(val pos: Pair<Int, Int>, val dir: Pair<Int, Int>) { private fun inside() = pos.first >= 0 && pos.second >= 0 && pos.first < grid[0].length && pos.second < grid.size private fun move(): List<Beam> { when (grid[pos.second][pos.first]) { '-' -> if (dir == left || dir == right) return listOf(Beam(Pair(pos.first + dir.first, pos.second + dir.second), dir)) else return listOf(Beam(Pair(pos.first - 1, pos.second), left), Beam(Pair(pos.first + 1, pos.second), right)) '|' -> if (dir.first == 0) return listOf(Beam(Pair(pos.first + dir.first, pos.second + dir.second), dir)) else return listOf(Beam(Pair(pos.first, pos.second - 1), Pair(0, -1)), Beam(Pair(pos.first, pos.second + 1), Pair(0, 1))) '/' -> when (dir) { up -> return listOf(Beam(Pair(pos.first + 1, pos.second), right)) right -> return listOf(Beam(Pair(pos.first, pos.second - 1), up)) down -> return listOf(Beam(Pair(pos.first - 1, pos.second), left)) left -> return listOf(Beam(Pair(pos.first, pos.second + 1), down)) } '\\' -> when (dir) { up -> return listOf(Beam(Pair(pos.first - 1, pos.second), left)) right -> return listOf(Beam(Pair(pos.first, pos.second + 1), down)) down -> return listOf(Beam(Pair(pos.first + 1, pos.second), right)) left -> return listOf(Beam(Pair(pos.first, pos.second - 1), up)) } '.' -> return listOf(Beam(Pair(pos.first + dir.first, pos.second + dir.second), dir)) } throw IllegalStateException() } fun energized(): Int { val queue = ArrayList<Beam>() val processed = HashSet<Beam>() queue.add(this) while (!queue.isEmpty()) { val beam = queue.removeFirst() if (!beam.inside() || !processed.add(beam)) continue queue.addAll(beam.move()) } return processed.map { it.pos }.toSet().size } } var result2 = 0 for (r in 0..<grid.size) { result2 = max(result2, max(Beam(Pair(0, r), right).energized(), Beam(Pair(grid[0].length - 1, r), left).energized())) } for (c in 0..<grid[0].length) { result2 = max(result2, max(Beam(Pair(c, 0), down).energized(), Beam(Pair(c, grid.size - 1), up).energized())) } println(listOf(Beam(Pair(1, 0), right).energized(), result2))
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
2,803
aoc2023
MIT License
src/Day01.kt
ivancordonm
572,816,777
false
{"Kotlin": 36235}
fun main() { fun part1(input: List<String>) = input.sumarize().first() fun part2(input: List<String>) = input.sumarize().take(3).sum() val testInput = readInput("Day01_test") val input = readInput("Day01") check(part1(testInput) == 24000) println(part1(input)) check(part2(testInput) == 45000) println(part2(input)) } private fun List<String>.sumarize() = listOf( -1, *mapIndexedNotNull { index, item -> index.takeIf { item.isBlank() } }.toTypedArray(), lastIndex + 1 ).zipWithNext().let { indexes -> indexes.map { pair -> this.subList(pair.first + 1, pair.second).sumOf { it.toInt() } } }.sortedDescending()
0
Kotlin
0
2
dc9522fd509cb582d46d2d1021e9f0f291b2e6ce
712
AoC-2022
Apache License 2.0
Retos/Reto #4 - PRIMO, FIBONACCI Y PAR [Media]/kotlin/PavDev3.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
fun main() { println("Introduce un número:") val input = readLine() try { val n = input!!.toInt() val result = isPrimeAndFibonacciAndParity(n) println(result) } catch (e: NumberFormatException) { println("La entrada no es un número válido.") } } fun isPrimeAndFibonacciAndParity(n: Int): String { val par = if (n % 2 == 0) "par" else "impar" val primo = if (isPrime(n)) "es primo" else "no es primo" val fibonacci = if (fibonnacci(n)) "es parte de la serie de Fibonacci" else "no es parte de la serie de Fibonacci" return "El número $n es $par, $primo y $fibonacci" } fun isPrime(n: Int): Boolean { if (n <= 1) return false if (n <= 3) return true if (n % 2 == 0 || n % 3 == 0) return false var i = 5 while (i * i <= n) { if (n % i == 0 || n % (i + 2) == 0) return false i += 6 } return true } fun fibonnacci(n: Int): Boolean { var a = 0 var b = 1 while (b < n) { val c = a + b a = b b = c if (b == n) return true } return false }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
1,144
retos-programacion-2023
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestWordDistance.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.abs import kotlin.math.min fun interface ShortestWordDistanceStrategy { operator fun invoke(words: Array<String>, word1: String, word2: String): Int } class ShortestWordDistanceBruteForce : ShortestWordDistanceStrategy { override operator fun invoke(words: Array<String>, word1: String, word2: String): Int { var minDistance: Int = words.size for (i in words.indices) { if (words[i] == word1) { for (j in words.indices) { if (words[j] == word2) { minDistance = min(minDistance, abs(i - j)) } } } } return minDistance } } class ShortestWordDistanceOnePass : ShortestWordDistanceStrategy { override operator fun invoke(words: Array<String>, word1: String, word2: String): Int { var i1 = -1 var i2 = -1 var minDistance: Int = words.size for (i in words.indices) { if (words[i] == word1) { i1 = i } else if (words[i] == word2) { i2 = i } if (i1 != -1 && i2 != -1) { minDistance = min(minDistance, abs(i1 - i2)) } } return minDistance } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,926
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/StampingSequence.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue import java.util.Stack import kotlin.math.max import kotlin.math.min /** * 936. Stamping The Sequence * @see <a href="https://leetcode.com/problems/stamping-the-sequence/">Source</a> */ class StampingSequence { fun movesToStamp(stamp: String, target: String): IntArray { val m: Int = stamp.length val n: Int = target.length val queue: Queue<Int> = LinkedList() val done = BooleanArray(n) val ans: Stack<Int> = Stack() val a: MutableList<Node> = ArrayList() for (i in 0..n - m) { // For each window [i, i+M), A[i] will contain // info on what needs to change before we can // reverse stamp at this window. val made: MutableSet<Int> = HashSet() val todo: MutableSet<Int> = HashSet() for (j in 0 until m) { if (target[i + j] == stamp[j]) { made.add(i + j) } else { todo.add(i + j) } } a.add(Node(made, todo)) // If we can reverse stamp at i immediately, // enqueue letters from this window. if (todo.isEmpty()) { ans.push(i) for (j in i until i + m) if (!done[j]) { queue.add(j) done[j] = true } } } calculateEachEnqueuedLetter(queue, a, m, n, ans, done) for (b in done) { if (!b) { return IntArray(0) } } val ret = IntArray(ans.size) var t = 0 while (ans.isNotEmpty()) { ret[t++] = ans.pop() } return ret } private fun calculateEachEnqueuedLetter( queue: Queue<Int>, a: List<Node>, m: Int, n: Int, ans: Stack<Int>, done: BooleanArray, ) { // For each enqueued letter (position), while (queue.isNotEmpty()) { val i: Int = queue.poll() // For each window that is potentially affected, // j: start of window for (j in max(0, i - m + 1)..min(n - m, i)) { // This window is affected if (a[j].todo.contains(i)) { a[j].todo.remove(i) if (a[j].todo.isEmpty()) { ans.push(j) for (o in a[j].made) { if (!done[o]) { queue.add(o) done[o] = true } } } } } } } private data class Node(var made: Set<Int>, var todo: MutableSet<Int>) }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,479
kotlab
Apache License 2.0
src/main/kotlin/be/tabs_spaces/advent2021/days/Day13.kt
janvryck
433,393,768
false
{"Kotlin": 58803}
package be.tabs_spaces.advent2021.days import be.tabs_spaces.advent2021.days.Day13.Axis.X import be.tabs_spaces.advent2021.days.Day13.Axis.Y class Day13 : Day(13) { private val transparentPaper = TransparentPaper.parse(inputList) override fun partOne() = transparentPaper.fold(1).size override fun partTwo() = transparentPaper.fold().visualize() class TransparentPaper private constructor( private val dots: List<Point>, private val foldingInstructions: List<FoldingInstruction> ) { companion object { fun parse(input: List<String>): TransparentPaper { val foldingInstructions = parseFoldingInstructions(input) return TransparentPaper(parsePoints(input), foldingInstructions) } private fun parsePoints(input: List<String>) = input .takeWhile { it.isNotBlank() } .map { it.split(",") } .map { (x, y) -> Point(x.toInt(), y.toInt()) } private fun parseFoldingInstructions(input: List<String>) = input.takeLastWhile { it.isNotBlank() } .map { it.replace("fold along ", "").split("=") } .map { (axis, line) -> FoldingInstruction(Axis.from(axis), line.toInt()) } } fun fold(times: Int = 1) = fold(foldingInstructions.take(times)) fun fold() = fold(foldingInstructions) private fun fold(instructions: List<FoldingInstruction>) = instructions.fold(dots) { dots, instruction -> dots.mapNotNull { it.fold(instruction) }.distinct() }.distinct() } data class Point(val x: Int, val y: Int) { fun fold(instruction: FoldingInstruction): Point? = when (instruction.axis) { X -> foldX(instruction.foldLine) Y -> foldY(instruction.foldLine) } private fun foldX(foldLine: Int): Point? = when (x) { in 0 until foldLine -> this.copy() foldLine -> null else -> this.copy(x = offset(x, foldLine)) } private fun foldY(foldLine: Int): Point? = when (y) { in 0 until foldLine -> this.copy() foldLine -> null else -> this.copy(y = offset(y, foldLine)) } private fun offset(original: Int, foldLine: Int): Int = original - 2 * (original - foldLine) } data class FoldingInstruction(val axis: Axis, val foldLine: Int) enum class Axis { X, Y; companion object { fun from(raw: String) = when (raw.uppercase()) { "X" -> X "Y" -> Y else -> throw IllegalArgumentException("Unknown axis") } } } private fun List<Point>.visualize() = (0..this.maxOf { it.y }).joinToString(separator = "", prefix = "\n") { y -> (0..this.maxOf { it.x }).joinToString(separator = "", postfix = "\n") { x -> firstOrNull { it.x == x && it.y == y }?.let { "#" } ?: "." } } }
0
Kotlin
0
0
f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9
3,005
advent-2021
Creative Commons Zero v1.0 Universal
src/Day25.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
fun main() { fun snafu2dec(input: String): Long { var ret = 0L input.forEach { ret = 5 * ret + when (it) { '2' -> 2L '1' -> 1L '0' -> 0L '-' -> -1L '=' -> -2L else -> throw IllegalArgumentException() } } return ret } fun dec2snafu(v: Long): String { if (v == 0L) return "" val lastDigit = when (v % 5) { 0L -> '0' 1L -> '1' 2L -> '2' 3L -> '=' 4L -> '-' else -> throw IllegalStateException() } val remind = when (v % 5) { 0L, 1L, 2L -> 0L 3L, 4L -> 1L else -> throw IllegalStateException() } return dec2snafu(v / 5L + remind) + lastDigit } fun part1(input: List<String>): String { val dec = input.sumOf { snafu2dec(it) } val snafu = dec2snafu(dec) println(dec) println(snafu2dec(snafu)) return snafu } val input = readInput("Day25") println(part1(input)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
1,142
aoc2022-kotlin
Apache License 2.0
src/main/kotlin/day08/DayEight.kt
Neonader
572,678,494
false
{"Kotlin": 19255}
package day08 import java.io.File val fileList = File("puzzle_input/day08.txt").useLines { it.toList() } val forest = fileList.map { row -> row.toList().map { col -> col.code } } val width = forest[0].size val height = forest.size fun visible(row: Int, col: Int): Boolean { val tree = forest[row][col] if ( row == 0 || row == height || col == 0 || col == width ) return true var visible = true // visible from above for (otherTree in forest.slice(0 until row)) visible = visible && otherTree[col] < tree if (visible) return true // visible from left visible = true for (otherTree in forest[row].slice(0 until col)) visible = visible && otherTree < tree if (visible) return true // visible from right visible = true for (otherTree in forest[row].slice(col + 1 until width)) visible = visible && otherTree < tree if (visible) return true // visible from below visible = true for (otherTree in forest.slice(row + 1 until height)) visible = visible && otherTree[col] < tree return visible } fun scenicScore(row: Int, col: Int): Int { val tree = forest[row][col] var score = 1 if ( row == 0 || row == height || col == 0 || col == width ) return 0 // up distance var distance = 0 for (otherTree in forest.slice(row - 1 downTo 0)) { distance++ if (otherTree[col] >= tree) break } score *= distance // left distance distance = 0 for (otherTree in forest[row].slice(col - 1 downTo 0)) { distance++ if (otherTree >= tree) break } score *= distance // right distance distance = 0 for (otherTree in forest[row].slice(col + 1 until width)) { distance++ if (otherTree >= tree) break } score *= distance // down distance distance = 0 for (otherTree in forest.slice(row + 1 until height)) { distance++ if (otherTree[col] >= tree) break } score *= distance return score } fun a(): Int { var sum = 0 for (row in 0 until height) for (col in 0 until width) if (visible(row, col)) sum++ return sum } fun b(): Int { var max = 0 for (row in 0 until height) for (col in 0 until width) if (scenicScore(row, col) > max) max = scenicScore(row, col) return max }
0
Kotlin
0
3
4d0cb6fd285c8f5f439cb86cb881b4cd80e248bc
2,226
Advent-of-Code-2022
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem673/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem673 /** * LeetCode page: [673. Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/); */ class Solution { /* Complexity: * Time O(N^2) and Space O(N) where N is the size of nums; */ fun findNumberOfLIS(nums: IntArray): Int { /* dp[i]::= the (length, count) pair of the longest increasing * subsequences which start at index i; */ val dp = Array(nums.size) { Pair(1, 1) } for (start in nums.indices.reversed()) { var maxLength = 1 var countMaxLength = 1 for (next in start + 1..<nums.size) { if (nums[next] <= nums[start]) { continue } val length = 1 + dp[next].first when { length == maxLength -> countMaxLength += dp[next].second length > maxLength -> { maxLength = length countMaxLength = dp[next].second } } } dp[start] = Pair(maxLength, countMaxLength) } val maxLength = dp.maxOf { (length, _) -> length } return dp.sumOf { (length, count) -> if (length == maxLength) count else 0 } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,351
hj-leetcode-kotlin
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2022/Day24.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2022 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.XY import com.s13g.aoc.resultFrom import java.lang.RuntimeException /** * --- Day 24: <NAME> --- * https://adventofcode.com/2022/day/24 */ class Day24 : Solver { enum class Type { UP, DOWN, LEFT, RIGHT, WALL } private data class Blizzard(val pos: XY, val type: Type) override fun solve(lines: List<String>): Result { val map = mutableListOf<Blizzard>() for ((y, line) in lines.withIndex()) { for (x in line.indices) { if (line[x] == '.') continue val dir = when (line[x]) { '>' -> Type.RIGHT '<' -> Type.LEFT '^' -> Type.UP 'v' -> Type.DOWN '#' -> Type.WALL else -> throw RuntimeException("Uh oh") } map.add(Blizzard(XY(x, y), dir)) } } val world = World(map, lines[0].length, lines.size) val end = XY(lines[0].length - 2, lines.size - 1) val partA = sim(setOf(XY(1, 0)), world, end) val partB1 = sim(setOf(end), partA.first, XY(1, 0)) val partB2 = sim(setOf(XY(1, 0)), partB1.first, end) return resultFrom( partA.second, partA.second + partB1.second + partB2.second ) } private fun sim( initPos: Set<XY>, initWorld: World, end: XY ): Pair<World, Int> { var world = initWorld val positions = initPos.toMutableSet() var minute = 0 while (end !in positions) { val nextWorld = world.next() val posCopy = positions.toSet() positions.clear() for (pos in posCopy) { positions.addAll(setOf( pos, // Wait XY(pos.x - 1, pos.y), XY(pos.x + 1, pos.y), XY(pos.x, pos.y - 1), XY(pos.x, pos.y + 1) ).filter { nextWorld.isFree(it) }) } world = nextWorld minute++ } return Pair(world, minute) } private data class World( val map: List<Blizzard>, val width: Int, val height: Int ) { fun isFree(pos: XY) = map.count { it.pos == pos } == 0 && pos.x in 0 until width && pos.y in 0 until height fun next(): World { val result = mutableListOf<Blizzard>() for (item in map) { if (item.type == Type.UP) { val newY = if (item.pos.y > 1) item.pos.y - 1 else height - 2 result.add(Blizzard(XY(item.pos.x, newY), Type.UP)) } else if (item.type == Type.DOWN) { val newY = if (item.pos.y < (height - 2)) item.pos.y + 1 else 1 result.add(Blizzard(XY(item.pos.x, newY), Type.DOWN)) } else if (item.type == Type.LEFT) { val newX = if (item.pos.x > 1) item.pos.x - 1 else width - 2 result.add(Blizzard(XY(newX, item.pos.y), Type.LEFT)) } else if (item.type == Type.RIGHT) { val newX = if (item.pos.x < (width - 2)) item.pos.x + 1 else 1 result.add(Blizzard(XY(newX, item.pos.y), Type.RIGHT)) } else if (item.type == Type.WALL) { result.add(item) } } return World(result, width, height) } fun toMap() = map.associate { it.pos to it.type }.toMap() fun print(dude: XY) { val locMap = toMap() for (y in 0 until height) { for (x in 0 until width) { val pos = XY(x, y) if (dude == pos) print('E') else if (pos !in locMap) print('.') else if (locMap[pos] == Type.UP) print('^') else if (locMap[pos] == Type.DOWN) print('v') else if (locMap[pos] == Type.LEFT) print('<') else if (locMap[pos] == Type.RIGHT) print('>') else if (locMap[pos] == Type.WALL) print('#') } print("\n") } print("\n") } } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
3,738
euler
Apache License 2.0
src/main/kotlin/days/Day7.kt
shymmq
318,337,339
false
null
package days class Day7 : Day(7) { override fun partOne(): Any { val parents = input // parse into a list of edges .flatMap { ruleStr -> val parent = "^\\w+ \\w+".toRegex().find(ruleStr)!!.value val children = "(?<=\\d )\\w+ \\w+".toRegex().findAll(ruleStr).toList().map(MatchResult::value) children.map { parent to it } } // associate each node with list of incoming edges .groupBy { it.second } // associate each node with list of parents .mapValues { entry -> entry.value.map { it.first }.toSet() } fun ancestors(node: String): Set<String> = parents[node].orEmpty() + parents[node]?.flatMap(::ancestors)?.toSet().orEmpty() return ancestors("shiny gold").size } override fun partTwo(): Int { val children = input // associate each node with a list of (child, number) pairs .associate { ruleStr -> val parent = "^\\w+ \\w+".toRegex().find(ruleStr)!!.value val children = "(\\d) (\\w+ \\w+)".toRegex() .findAll(ruleStr).toList() .map(MatchResult::groupValues) .map { it[2] to it[1].toInt() } parent to children } fun totalChildren(node: String): Int = 1 + children[node].orEmpty().sumBy { (child, number) -> totalChildren(child) * number } return totalChildren("shiny gold") } }
0
Kotlin
0
0
8292e8f30eaf7a58c5dc0074f85b7339b6999e18
1,551
aoc20-kotlin
Creative Commons Zero v1.0 Universal
src/_2015/Day03.kt
albertogarrido
572,874,945
false
{"Kotlin": 36434}
package _2015 import _2015.CardinalDirection.* import readInput import java.lang.IllegalArgumentException fun main() { part1Tests(readInput("2015", "day03_test")) part2Tests(readInput("2015", "day03_test_2")) runScenario(readInput("2015", "day03")) } private fun runScenario(input: List<String>) { println(part1(input[0])) println(part2(input[0])) } private fun part1(input: String): Int { var currentLocation = Point.initial() val houseGifts = HashMap<Point, Int>() houseGifts[currentLocation] = 1 var dirCount = 0 do { val nextDirection = input[dirCount] currentLocation = when (CardinalDirection.fromValue(nextDirection)) { N -> Point(currentLocation.x, currentLocation.y + 1) E -> Point(currentLocation.x + 1, currentLocation.y) S -> Point(currentLocation.x, currentLocation.y - 1) W -> Point(currentLocation.x - 1, currentLocation.y) } try { var gifts = houseGifts[currentLocation] houseGifts[currentLocation] = if (gifts != null) { ++gifts } else { 1 } } catch (_: NoSuchElementException) { houseGifts[currentLocation] = 1 } dirCount++ } while (dirCount < input.length) return houseGifts.size } private fun part2(input: String): Int { var santaLocation = Point.initial() var roboSantaLocation = Point.initial() val houseGifts = HashMap<Point, Int>() houseGifts[santaLocation] = 1 houseGifts[santaLocation] = 2 input.chunked(2).forEach { coupleDirections -> val santaDirection = CardinalDirection.fromValue(coupleDirections[0]) val roboSantaDirection = CardinalDirection.fromValue(coupleDirections[1]) santaLocation = when (santaDirection) { N -> Point(santaLocation.x, santaLocation.y + 1) E -> Point(santaLocation.x + 1, santaLocation.y) S -> Point(santaLocation.x, santaLocation.y - 1) W -> Point(santaLocation.x - 1, santaLocation.y) } roboSantaLocation = when (roboSantaDirection) { N -> Point(roboSantaLocation.x, roboSantaLocation.y + 1) E -> Point(roboSantaLocation.x + 1, roboSantaLocation.y) S -> Point(roboSantaLocation.x, roboSantaLocation.y - 1) W -> Point(roboSantaLocation.x - 1, roboSantaLocation.y) } try { var gifts = houseGifts[santaLocation] houseGifts[santaLocation] = if (gifts != null) { ++gifts } else { 1 } } catch (_: NoSuchElementException) { houseGifts[santaLocation] = 1 } try { var gifts = houseGifts[roboSantaLocation] houseGifts[roboSantaLocation] = if (gifts != null) { ++gifts } else { 1 } } catch (_: NoSuchElementException) { houseGifts[roboSantaLocation] = 1 } } return houseGifts.size } private data class Point(val x: Int, val y: Int) { companion object { fun initial() = Point(0, 0) } } private enum class CardinalDirection { N, E, S, W; companion object { fun fromValue(value: Char): CardinalDirection = when (value) { '^' -> N '>' -> E 'v' -> S '<' -> W else -> throw IllegalArgumentException("$value is not a valid cardinal point") } } } private fun runTests(testInput: List<String>) { part1Tests(testInput) part2Tests(testInput) } fun part1Tests(testInput: List<String>) { val result1 = part1(testInput[0]) check(result1 == 2) { "Part 1: expected 2, obtained $result1" } val result2 = part1(testInput[1]) check(result2 == 4) { "Part 1: expected 4, obtained $result2" } val result3 = part1(testInput[2]) check(result3 == 2) { "Part 1: expected 2, obtained $result3" } } fun part2Tests(testInput: List<String>) { val result1 = part2(testInput[0]) check(result1 == 3) { "a Part 2: expected 3, obtained $result1" } val result2 = part2(testInput[1]) check(result2 == 3) { "b Part 2: expected 3, obtained $result2" } val result3 = part2(testInput[2]) check(result3 == 11) { "c Part 2: expected 11, obtained $result3" } }
0
Kotlin
0
0
ef310c5375f67d66f4709b5ac410d3a6a4889ca6
4,397
AdventOfCode.kt
Apache License 2.0
Final Project/src/main/java/Bees.kt
edjacob25
166,317,485
false
{"TeX": 77616, "Java": 42668, "Kotlin": 13806, "Rust": 7029, "C++": 3268, "C#": 3139, "MATLAB": 1783}
import BinPacking.Solver.BinPackingSolver import BinPacking.Solver.Feature import BinPacking.Solver.Heuristic import BinPacking.Solver.HyperHeuristic import BinPacking.Utils.BinPackingProblemSet import java.util.* import kotlin.random.Random class Bees( features: Array<out Feature>?, heuristics: Array<out Heuristic>?, seed: Int, private val params: BeesParameters, trainingSet: String ) : HyperHeuristic(features, heuristics) { private val random = Random(seed) private val problems = BinPackingProblemSet(trainingSet) private var best: Pair<Array<DoubleArray>, Double> = Pair(createRandomBee(), Double.MAX_VALUE) init { var population = (0 until params.numOfBees) .map { Pair(createRandomBee(), 0.0) } .toMutableList() for (gen in 1..params.generations) { // Evaluate population on the problem population = population.map { Pair(it.first, evaluate(it.first)) }.toMutableList() // Sort population population.sortBy { it.second } // Select the best of exists if (population[0].second < best.second) { best = population[0] println("Best now is ${best.first} with cost ${best.second}") } val nextGen = mutableListOf<Pair<Array<DoubleArray>, Double>>() for ((i, item) in population.take(params.bestBees).withIndex()) { val neighSize = if (i < params.eliteBees) params.descendantsOfEliteBees else params.descendantsOfBestBees nextGen.addAll(generateNeighbors(item.first, neighSize)) } nextGen.addAll(createScoutBees(params.numOfBees - params.bestBees)) population = nextGen if (params.patchSize > 0.1 && params.patchDecrementPossibility > random.nextDouble()) { params.patchSize = params.patchSize - 0.05 } } } override fun getHeuristic(solver: BinPackingSolver?): Heuristic { val state = features.map { solver!!.getFeature(it) }.toDoubleArray() val chosen = best.first .mapIndexed { index, array -> Pair(index, calculateDistance(array, state)) } .minBy { it.second }!!.first return heuristics[chosen] } private fun calculateDistance(feature: DoubleArray, actual: DoubleArray): Double { var sum = 0.0 for (i in features.indices) { sum += Math.pow(feature[i] - actual[i], 2.0) } return Math.sqrt(sum) } private fun generateNeighbor(original: Array<DoubleArray>): Array<DoubleArray> { val neighbor = original.copyOf() for (i in 0 until heuristics.size) { for (j in 0 until features.size) { neighbor[i][j] = neighbor[i][j] + random.nextDouble(-params.patchSize, params.patchSize) } } return neighbor } private fun generateNeighbors(original: Array<DoubleArray>, neighSize: Int): Collection<Pair<Array<DoubleArray>, Double>> { return (0 until neighSize).map { Pair(generateNeighbor(original), 0.0) } } private fun createScoutBees(number: Int): Collection<Pair<Array<DoubleArray>, Double>> { return (0 until number).map { Pair(createRandomBee(), 0.0) } } private fun evaluate(bee: Array<DoubleArray>): Double { val results = mutableListOf<Double>() for (problem in problems.instances) { val solver = BinPackingSolver(problem) val state = features.map { solver.getFeature(it) }.toDoubleArray() val chosen = bee .mapIndexed { index, array -> Pair(index, calculateDistance(array, state)) } .minBy { it.second }!!.first solver.solve(heuristics[chosen]) results.add(solver.getFeature(Feature.AVGW)) } return results.sum() } private fun createRandomBee(): Array<DoubleArray> { val result = Array(heuristics.size) { DoubleArray(features.size) } for (i in 0 until heuristics.size) { for (j in 0 until features.size) { result[i][j] = random.nextDouble() } } return result } override fun toString(): String { val string: StringBuilder = StringBuilder() for ((i, array) in best.first.withIndex()) { string.append(Arrays.toString(array)).append(" => ").append(heuristics[i]).append("\n") } return string.toString().trim { it <= ' ' } } } data class BeesParameters(var numOfBees: Int, val generations: Int, val bestBees: Int, val eliteBees: Int, var patchSize: Double, val patchDecrementPossibility: Double, val descendantsOfBestBees: Int, val descendantsOfEliteBees: Int) { override fun toString(): String = "nb${numOfBees}_g${generations}_bb${bestBees}_eb${eliteBees}_dbb${bestBees}_deb$descendantsOfEliteBees" }
0
TeX
0
0
6945f257eb7ed22a97350a0f3af9153ff9caf0ec
5,048
ComputationalFundaments
MIT License
src/main/kotlin/aoc2022/Day03.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2022 import AoCDay import util.illegalInput // https://adventofcode.com/2022/day/3 object Day03 : AoCDay<Int>( title = "Rucksack Reorganization", part1ExampleAnswer = 157, part1Answer = 8139, part2ExampleAnswer = 70, part2Answer = 2668, ) { private class Rucksack(val items: String) { val compartment1 get() = items.substring(0, items.length / 2) val compartment2 get() = items.substring(items.length / 2, items.length) } private fun rucksacks(input: String) = input.lineSequence().map(::Rucksack) private fun Sequence<Char>.sumOfItemPriorities(): Int = sumOf { item -> when (item) { in 'a'..'z' -> (item - 'a') + 1 in 'A'..'Z' -> (item - 'A') + 27 else -> illegalInput(item) } } override fun part1(input: String) = rucksacks(input) .map { rucksack -> rucksack.compartment1.first { item -> item in rucksack.compartment2 } } .sumOfItemPriorities() override fun part2(input: String) = rucksacks(input) .chunked(3) .map { (r1, r2, r3) -> r1.items.first { item -> item in r2.items && item in r3.items } } .sumOfItemPriorities() }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
1,239
advent-of-code-kotlin
MIT License
src/Day05.kt
hijst
572,885,261
false
{"Kotlin": 26466}
data class CraneMove( val amount: Int, val from: Int, val to: Int ) class Cargo( private val stacks: MutableList<String>, private val moves: List<CraneMove> ) { fun stackTops(): String = stacks.map { it.last() }.joinToString("") fun executeAllMoves9000() = moves.forEach { move -> stacks[move.to] += stacks[move.from].takeLast(move.amount).reversed() stacks[move.from] = stacks[move.from].dropLast(move.amount) } fun executeAllMoves9001() = moves.forEach { move -> stacks[move.to] += stacks[move.from].takeLast(move.amount) stacks[move.from] = stacks[move.from].dropLast(move.amount) } } fun main() { fun part1(cargo: Cargo): String { cargo.executeAllMoves9000() return cargo.stackTops() } fun part2(cargo: Cargo): String { cargo.executeAllMoves9001() return cargo.stackTops() } val testInput1 = readCargo("Day05_test") val testInput2 = readCargo("Day05_test") check(part1(testInput1) == "CMZ") check(part2(testInput2) == "MCD") val input1 = readCargo("Day05_input") val input2 = readCargo("Day05_input") println(part1(input1)) println(part2(input2)) }
0
Kotlin
0
0
2258fd315b8933642964c3ca4848c0658174a0a5
1,210
AoC-2022
Apache License 2.0
src/day04/Day04.kt
Sardorbekcyber
573,890,266
false
{"Kotlin": 6613}
package day04 import java.io.File fun main() { fun part1(input: String) : Long { val data = input.split("\n").sumOf { line -> val parts = line.split(",") val firstPart = parts[0].split("-") val secondPart = parts[1].split("-") val firstStart = firstPart.first().toInt() val firstEnd = firstPart.last().toInt() val secondStart = secondPart.first().toInt() val secondEnd = secondPart.last().toInt() when { firstStart <= secondStart && firstEnd >= secondEnd -> 1L firstStart >= secondStart && firstEnd <= secondEnd -> 1L else -> 0L } } return data } fun part2(input: String) : Long { val data = input.split("\n").sumOf { line -> val parts = line.split(",") val firstPart = parts[0].split("-") val secondPart = parts[1].split("-") val firstStart = firstPart.first().toInt() val firstEnd = firstPart.last().toInt() val secondStart = secondPart.first().toInt() val secondEnd = secondPart.last().toInt() when { secondEnd < firstStart -> 0L firstEnd < secondStart -> 0L else -> 1L } } return data } val testInput = File("src/day04/Day04_test.txt").readText() println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 2L) check(part2(testInput) == 4L) val input = File("src/day04/Day04.txt").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
56f29c8322663720bc83e7b1c6b0a362de292b12
1,674
aoc-2022-in-kotlin
Apache License 2.0
src/Day09.kt
fonglh
573,269,990
false
{"Kotlin": 48950, "Ruby": 1701}
fun main() { fun isAdjacent(head: Pair<Int, Int>, tail: Pair<Int, Int>): Boolean { for (row in head.first-1..head.first+1) { for (col in head.second-1..head.second+1) { if (tail.first == row && tail.second == col) return true } } return false } // must call after every step of head so head is at most 2 steps away from tail fun moveTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> { // Already adjacent, do nothing if (isAdjacent(head, tail)) return tail // same row if (head.first == tail.first) { return if (head.second > tail.second) { Pair(tail.first, tail.second + 1) } else { Pair(tail.first, tail.second - 1) } } else if (head.second == tail.second) { // same column return if (head.first > tail.first) { Pair(tail.first+1, tail.second) } else { Pair(tail.first-1, tail.second) } } else { return if (head.first > tail.first && head.second > tail.second) { //up right Pair(tail.first+1, tail.second+1) } else if (head.first < tail.first && head.second < tail.second) { //down left Pair(tail.first-1, tail.second-1) } else if (head.first > tail.first && head.second < tail.second) { //up left Pair(tail.first+1, tail.second-1) } else { //down right Pair(tail.first-1, tail.second+1) } } return tail } fun part1(input: List<String>): Int { var head = Pair(0, 0) var tail = Pair(0, 0) var tailCovered: MutableSet<Pair<Int, Int>> = mutableSetOf(tail) input.forEach { val steps = it.substringAfter(" ").toInt() when(it.substringBefore(" ")) { "U" -> { for(i in 1..steps) { head = Pair(head.first+1, head.second) tail = moveTail(head, tail) tailCovered.add(tail) } } "D" -> { for(i in 1..steps) { head = Pair(head.first-1, head.second) tail = moveTail(head, tail) tailCovered.add(tail) } } "L" -> { for(i in 1..steps) { head = Pair(head.first, head.second-1) tail = moveTail(head, tail) tailCovered.add(tail) } } "R" -> { for(i in 1..steps) { head = Pair(head.first, head.second+1) tail = moveTail(head, tail) tailCovered.add(tail) } } else -> throw Exception() } } return tailCovered.size } fun ropeToString(rope: Array<Pair<Int, Int>>): String { var output = StringBuilder() for (knot in rope) { output.append(knot) } return output.toString() } fun cascade(rope: Array<Pair<Int, Int>>): Array<Pair<Int, Int>> { for(i in 0 until rope.size-1) { rope[i+1] = moveTail(rope[i], rope[i+1]) } return rope } fun part2(input: List<String>): Int { var rope = Array<Pair<Int, Int>>(10) { Pair(0, 0) } var tailCovered: MutableSet<Pair<Int, Int>> = mutableSetOf(rope.last()) input.forEach { val steps = it.substringAfter(" ").toInt() when(it.substringBefore(" ")) { "U" -> { for(i in 1..steps) { var head = rope[0] rope[0] = Pair(head.first+1, head.second) rope = cascade(rope) tailCovered.add(rope.last()) } } "D" -> { for(i in 1..steps) { var head = rope[0] rope[0] = Pair(head.first-1, head.second) rope = cascade(rope) tailCovered.add(rope.last()) } } "L" -> { for(i in 1..steps) { var head = rope[0] rope[0] = Pair(head.first, head.second-1) rope = cascade(rope) tailCovered.add(rope.last()) } } "R" -> { for(i in 1..steps) { var head = rope[0] rope[0] = Pair(head.first, head.second+1) rope = cascade(rope) tailCovered.add(rope.last()) } } else -> throw Exception() } } return tailCovered.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ef41300d53c604fcd0f4d4c1783cc16916ef879b
5,496
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/leetcode/top100LikedQuestions/medium/add_two_numbers/Main.kt
frikit
254,842,734
false
null
package com.leetcode.top100LikedQuestions.medium.add_two_numbers fun main() { println("Test case 1:") val ll1 = ListNode(2, ListNode(4, ListNode(3, null))) val ll2 = ListNode(5, ListNode(6, ListNode(4, null))) println(Solution().addTwoNumbers(ll1, ll2)) //[7,0,8] println() println("Test case 2:") val ll12 = ListNode(9, ListNode(9, ListNode(9, null))) val ll22 = ListNode(9, ListNode(9, null)) println(Solution().addTwoNumbers(ll12, ll22)) //[8, 9, 0, 1] println() println("Test case 3:") val ll13 = ListNode(5, null) val ll23 = ListNode(5, null) println(Solution().addTwoNumbers(ll13, ll23)) //[0, 1] println() } class Solution { fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { if (l1 == null || l2 == null) return null var newLinkedList: ListNode? = null var currL1 = l1 var currL2 = l2 var rest = 0 while (currL1 != null || currL2 != null) { val f1 = if (currL1?.`val` == null) 0 else currL1.`val` val f2 = if (currL2?.`val` == null) 0 else currL2.`val` var sum = f1 + f2 if (sum > 9) { sum = sum - 10 + rest rest = 1 } else { if (sum == 10) { sum = 0 rest = 1 } else { sum = sum + rest if (sum > 9) { sum = sum - 10 rest = 1 } else { rest = 0 } } } if (newLinkedList == null) { newLinkedList = ListNode(sum, null) if (currL1?.next == null && currL2?.next == null && rest != 0) { newLinkedList.next = ListNode(rest, null) } } else { var lastElement = newLinkedList while (lastElement?.next != null) { lastElement = lastElement.next } lastElement?.next = ListNode(sum, null) if (currL1?.next == null && currL2?.next == null && rest != 0) { lastElement?.next?.next = ListNode(rest, null) } } currL1 = currL1?.next currL2 = currL2?.next } return newLinkedList } } data class ListNode(var `val`: Int, var next: ListNode? = null)
0
Kotlin
0
0
dda68313ba468163386239ab07f4d993f80783c7
2,496
leet-code-problems
Apache License 2.0
app/src/main/java/com/mouredev/weeklychallenge2022/Challenge39.kt
mouredev
440,606,306
false
{"Kotlin": 111136}
package com.mouredev.weeklychallenge2022 /* * Reto #39 * TOP ALGORITMOS: QUICK SORT * Fecha publicación enunciado: 27/09/22 * Fecha publicación resolución: 03/10/22 * Dificultad: MEDIA * * Enunciado: Implementa uno de los algoritmos de ordenación más famosos: el "Quick Sort", * creado por <NAME>. * - Entender el funcionamiento de los algoritmos más utilizados de la historia nos ayuda a * mejorar nuestro conocimiento sobre ingeniería de software. Dedícale tiempo a entenderlo, * no únicamente a copiar su implementación. * - Esta es una nueva serie de retos llamada "TOP ALGORITMOS", donde trabajaremos y entenderemos * los más famosos de la historia. * * Información adicional: * - Usa el canal de nuestro Discord (https://mouredev.com/discord) "🔁reto-semanal" * para preguntas, dudas o prestar ayuda a la comunidad. * - Tienes toda la información sobre los retos semanales en * https://retosdeprogramacion.com/semanales2022. * */ // Basado en https://www.genbeta.com/desarrollo/implementando-el-algoritmo-quicksort fun main() { val sortedArray = quicksort(arrayOf(3, 5, 1, 8, 9, 0)) sortedArray.forEach { println(it) } } private fun quicksort(array: Array<Int>): Array<Int> { return if (array.isEmpty()) array else quicksort(array, 0, array.size - 1) } private fun quicksort(array: Array<Int>, first: Int, last: Int): Array<Int> { var i = first var j = last var array = array val pivot = (array[i] + array[j]) / 2 while (i < j) { while (array[i] < pivot) { i += 1 } while (array[j] > pivot) { j -= 1 } if (i <= j) { val x = array[j] array[j] = array[i] array[i] = x i += 1 j -= 1 } } if (first < j) { array = quicksort(array, first, j) } if (last > i) { array = quicksort(array, i, last) } return array }
796
Kotlin
1,060
1,912
211814959bd8e98566b2440e3e4237dd210a74f2
1,996
Weekly-Challenge-2022-Kotlin
Apache License 2.0
src/main/java/challenges/educative_grokking_coding_interview/sliding_window/_4/LongestSubstringKDistinct.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.sliding_window._4 /** * Given a string, find the length of the longest substring in it with no more than K distinct characters. * * https://www.educative.io/courses/grokking-the-coding-interview/YQQwQMWLx80 */ object LongestSubstringKDistinct { private fun findLength(str: String?, k: Int): Int { require(!str.isNullOrEmpty()) var windowStart = 0 var maxLength = 0 val charFrequencyMap: MutableMap<Char, Int> = HashMap() // in the following loop we'll try to extend the range [windowStart, windowEnd] for (windowEnd in str.indices) { val rightChar = str[windowEnd] charFrequencyMap[rightChar] = charFrequencyMap.getOrDefault(rightChar, 0) + 1 // shrink the sliding window, until we are left with 'k' distinct characters in the frequency map while (charFrequencyMap.size > k) { val leftChar = str[windowStart] charFrequencyMap[leftChar] = charFrequencyMap[leftChar]!! - 1 if (charFrequencyMap[leftChar] == 0) { charFrequencyMap.remove(leftChar) } windowStart++ // shrink the window } maxLength = maxLength.coerceAtLeast(windowEnd - windowStart + 1) // remember the maximum length so far // Equals // maxLength = Math.max(maxLength, windowEnd - windowStart + 1) // remember the maximum length so far } return maxLength } @JvmStatic fun main(args: Array<String>) { println("Length of the longest substring: " + findLength("araaci", 2)) println("Length of the longest substring: " + findLength("araaci", 1)) println("Length of the longest substring: " + findLength("cbbebi", 3)) } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
1,842
CodingChallenges
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[714]买卖股票的最佳时机含手续费.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。 // // 你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。 // // 返回获得利润的最大值。 // // 注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。 // // 示例 1: // // 输入: prices = [1, 3, 2, 8, 4, 9], fee = 2 //输出: 8 //解释: 能够达到的最大利润: //在此处买入 prices[0] = 1 //在此处卖出 prices[3] = 8 //在此处买入 prices[4] = 4 //在此处卖出 prices[5] = 9 //总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8. // // 注意: // // // 0 < prices.length <= 50000. // 0 < prices[i] < 50000. // 0 <= fee < 50000. // // Related Topics 贪心算法 数组 动态规划 // 👍 367 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun maxProfit(prices: IntArray, fee: Int): Int { //动态规划 时间复杂度 O(n) val dp = IntArray(2) dp[0] = 0; dp[1] = -prices[0] for(i in 2..prices.size){ //没有持股 和前一天相比计算收益 dp[0] = dp[0].coerceAtLeast(dp[1] + prices[i - 1] - fee) //持股和前一天相比计算收益 dp[1] = dp[1].coerceAtLeast(dp[0] - prices[i - 1]) } return dp[0] } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,632
MyLeetCode
Apache License 2.0
src/com/leecode/array/Code1.kt
zys0909
305,335,860
false
null
package com.leecode.array /** * 一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。 如何在一个1到100的整数数组中找到丢失的数字? google, Amazon,tencent 示例 1: 输入: [0,1,3] 输出: 2 示例 2: 输入: [0,1,2] 输出: 3 示例 3: 输入: [0,1,2,3,4,5,6,7,9] 输出: 8 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/que-shi-de-shu-zi-lcof */ /** * * 直接遍历 */ fun missingNumber1(nums: IntArray): Int { var result: Int = 0 for (i in nums) { if (i != result) { break } result++ } return result } /** * 二手分查找法 */ fun missingNumber2(nums: IntArray): Int { var start = 0 var end = nums.size - 1 if (nums[end] == end) { return end + 1 } while (start < end) { val mid = (start + end) / 2 if (nums[mid] != mid) { end = mid } else { start = mid + 1 } } return start }
0
Kotlin
0
0
869c7c2f6686a773b2ec7d2aaa5bea2de46f1e0b
1,176
CodeLabs
Apache License 2.0
leetcode/990-SatisfiabilityOfEqualityEquations/Solution.kt
everyevery
17,393,217
false
null
class Solution { class Some () { val parent = IntArray(26) {it} val rank = IntArray(26) {it} fun union(a: Int, b: Int): Unit { val pa = find(a) val pb = find(b) if (rank[a] > rank[b]) { parent[pb] = pa rank[pa] += rank[pb] } else { parent[pa] = pb rank[pb] += rank[pa] } } fun find (n: Int): Int { var p = parent[n] while (p != parent[p]) { parent[p] = parent[parent[p]] p = parent[p] } return p } } fun equationsPossible(equations: Array<String>): Boolean { val s = Some() for (eq in equations) { if (eq[1] == '=') { s.union(eq[0] - 'a', eq[3] - 'a') } } for (eq in equations) { if (eq[1] == '!') { val a = s.find(eq[0] - 'a') val b = s.find(eq[3] - 'a') if (a == b) { return false } } } return true } } //class Solution { // fun CharArray.replace(from: Char, to: Char) { // for (i in this.indices) { // if (this[i] == from) { // this[i] = to // } // } // } // // // fun equationsPossible(equations: Array<String>): Boolean { // val vars = "abcdefghijklmnopqrstuvwxyz".toCharArray() // val vals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray() // for (rel in equations) { // val v1 = rel[0].toInt() - 'a'.toInt(); // val v2 = rel[3].toInt() - 'a'.toInt(); // if (rel[1] == '=') { // if (vals[v1] != vals[v2]) { // vals.replace(vals[v1], vals[v2]) // } // } // } // for (rel in equations) { // val v1 = rel[0].toInt() - 'a'.toInt(); // val v2 = rel[3].toInt() - 'a'.toInt(); // if (rel[1] == '!') { // if (vals[v1] == vals[v2]) { // return false // } // } // } // return true // } //}
0
Roff
3
1
e9a93f228692a3f82d1d60932e7871833f9e0931
2,247
algorithm_code
MIT License
src/test/kotlin/Day2Test.kt
corentinnormand
725,992,109
false
{"Kotlin": 40576}
import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class Day2Test { @Test fun test() { val input = """ Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green """.trimIndent().lines() val result = input.map { it.split(":") } .map { s -> val second = s[1].split(';') .map { str -> str.split(",") } .map { str -> str.map { it.trim() } } .map { str -> str.map { it.split(" "); } } .map { str -> str.map { s -> Pair(s[1], s[0].toInt()) } } .map { it.toMap() } .flatMap { it.entries } .groupBy { it.key } .mapValues { it.value.sumOf { v -> v.value } } val pair = Pair(s[0].split(" ")[1].toInt(), second) println(pair) pair } .filter { it.second.all { e -> (e.key == "blue" && e.value < 14) || (e.key == "green" && e.value < 13) || (e.key == "red" && e.value < 12) } } .sumOf { it.first } println(result) } }
0
Kotlin
0
0
2b177a98ab112850b0f985c5926d15493a9a1373
1,474
aoc_2023
Apache License 2.0
src/Day10.kt
gojoel
573,543,233
false
{"Kotlin": 28426}
fun main() { val input = readInput("10") // val input = readInput("10_test") fun valuesAtCycle(input: List<String>, cycle: Int) : HashMap<Int, Int> { val values: HashMap<Int, Int> = hashMapOf() var currentCycle = 1 var value = 1 values[1] = value for (i in 1 .. cycle) { val cmd = input[i - 1] if (cmd.startsWith("addx")) { currentCycle += 2 if (currentCycle > cycle) { break } values[currentCycle - 1] = value value += cmd.split(" ")[1].toInt() values[currentCycle] = value } else { currentCycle += 1 if (currentCycle > cycle) { break } values[currentCycle] = value } } if (values[cycle] == null) { values[cycle] = value } return values } fun signalStrength(input: List<String>, cycle: Int) : Int { val value = valuesAtCycle(input, cycle)[cycle] ?: 0 return value * cycle } fun part1(input: List<String>): Int { val cycles = arrayListOf(20, 60, 100, 140, 180, 220) return cycles.sumOf { signalStrength(input, it) } } fun part2(input: List<String>) { val cycle = 240 val valueRegister = valuesAtCycle(input, cycle) var spriteX: Int var x = 1 for (i in 1..cycle) { spriteX = valueRegister[i] ?: 0 if (spriteX - x == 0 || x - spriteX == 1 || x - spriteX == 2) { print("#") } else { print(".") } x++ if (i % 40 == 0) { x = 1 println() } } } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0690030de456dad6dcfdcd9d6d2bd9300cc23d4a
1,927
aoc-kotlin-22
Apache License 2.0
app/src/main/kotlin/advent_of_code/year_2022/day1/CounterOfCalories.kt
mavomo
574,441,138
false
{"Kotlin": 56468}
package advent_of_code.year_2022.day1 class CounterOfCalories { fun computeCaloriesCarriedByEachElf(caloriesMeasurements: List<String>): Map<Int, Int> { val allMeasurements = mutableMapOf<Int, Int>() var currentElfIndex = caloriesMeasurements.indexOfFirst { it.isEmpty() }.plus(1) var accumulator = 0 caloriesMeasurements.forEach { rawMeasurement -> if (rawMeasurement.isNotEmpty() && !rawMeasurement.isLastElement(caloriesMeasurements) ) { accumulator += rawMeasurement.toInt() }else{ val sumOfCalories = if(rawMeasurement.isLastElement(caloriesMeasurements)) rawMeasurement.toInt() else accumulator allMeasurements[currentElfIndex] = sumOfCalories accumulator = 0 currentElfIndex++ } } return allMeasurements } private fun String.isLastElement(caloriesMeasurements: List<String>): Boolean { val indexOfCurrentMeasure = caloriesMeasurements.indexOf(this) val lastElement = caloriesMeasurements.indexOfLast { it.isNotEmpty() } return indexOfCurrentMeasure==lastElement } fun getMaxCarriedCaloriesByASingleElf(allMeasurements: Map<Int, Int>): Int { return allMeasurements.entries.maxOf { it.value } } fun getTotalCaloriesForTheHeaviestTop3(allMeasurements: Map<Int, Int>): Any { val totalCaloriesForTheTopThree = allMeasurements.entries.sortedByDescending { it.value } return totalCaloriesForTheTopThree.take(3).sumOf { it.value } } }
0
Kotlin
0
0
b7fec100ea3ac63f48046852617f7f65e9136112
1,581
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NonOverlappingIntervals.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 /** * 435. Non-overlapping Intervals * @see <a href="https://leetcode.com/problems/non-overlapping-intervals/">Source</a> */ fun interface NonOverlappingIntervals { fun eraseOverlapIntervals(intervals: Array<IntArray>): Int } class NonOverlappingIntervalsGreedy : NonOverlappingIntervals { override fun eraseOverlapIntervals(intervals: Array<IntArray>): Int { intervals.sortWith { a, b -> if (a[1] != b[1]) a[1] - b[1] else b[0] - a[0] } var v = intervals[0] var ans = -1 intervals.forEach { if (it[0] < v[1]) ans++ else v = it } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,243
kotlab
Apache License 2.0
src/aoc2022/Day16_.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import utils.checkEquals import utils.sendAnswer fun main() { data class Valve(val name :String,val rate:Int, val que : Set<String>, var isOpen :Boolean = false) fun part1(input: List<String>): Int { var score = 0 var minutes = 31 val valves = mutableSetOf<Valve>() for (line in input){ val name = line.substringAfter("Valve ").takeWhile { it.isUpperCase() } val rate = line.substringAfter("rate=").takeWhile { it.isDigit() }.toInt() val leadTunnels = line.substringAfter(';').dropWhile { !it.isUpperCase() }.split(", ").sorted() valves += Valve(name, rate, leadTunnels.toSet()) } val map = valves.associateBy { it.name } val graph = valves.associate { it.name to it.que.toSet() } val visted = mutableSetOf<String>() val stack = ArrayDeque<String>(listOf("AA")) val rateToMin = mutableListOf<Pair<Int, Int>>() val pro = mutableListOf<Int>() var currValve = map["AA"]!! val knownValues = mutableListOf<Valve>() while (minutes >0 && stack.any()){ } return pro.sum() } fun part2(input: List<String>): Int { return input.size } // parts execution val testInput = readInput("Day16_test") val input = readInput("Day16") part1(testInput).checkEquals(1651) part1(input) .sendAnswer(part = 1, day = "16", year = 2022) part2(testInput).checkEquals(TODO()) part2(input) .sendAnswer(part = 2, day = "16", year = 2022) }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
1,587
Kotlin-AOC-2023
Apache License 2.0
AdventOfCodeDay16/src/nativeMain/kotlin/Packet.kt
bdlepla
451,510,571
false
{"Kotlin": 165771}
sealed class BITSPacket(val version: Int) { abstract val value: Long companion object { fun of(input: Iterator<Char>): BITSPacket { val version = input.nextInt(3) return when (val packetType = input.nextInt(3)) { 4 -> BITSLiteral.of(version, input) else -> BITSOperator.of(version, packetType, input) } } } abstract fun allVersions(): List<Int> } private class BITSLiteral(version: Int, override val value: Long) : BITSPacket(version) { override fun allVersions(): List<Int> = listOf(version) companion object { fun of(version: Int, input: Iterator<Char>): BITSLiteral = BITSLiteral(version, parseLiteralValue(input)) private fun parseLiteralValue(input: Iterator<Char>): Long = input.nextUntilFirst(5) { it.startsWith('0') }.joinToString("") { it.drop(1) }.toLong(2) } } private class BITSOperator(version: Int, type: Int, val subPackets: List<BITSPacket>) : BITSPacket(version) { override fun allVersions(): List<Int> = listOf(version) + subPackets.flatMap { it.allVersions() } override val value: Long = when (type) { 0 -> subPackets.sumOf{it.value} 1 -> subPackets.productOf{it.value} 2 -> subPackets.minOf{it.value} 3 -> subPackets.maxOf{it.value} 5 -> if (subPackets[0].value > subPackets[1].value) 1 else 0 6 -> if (subPackets[0].value < subPackets[1].value) 1 else 0 7 -> if (subPackets[0].value == subPackets[1].value) 1 else 0 else -> -1L } companion object { fun of(version: Int, type: Int, input: Iterator<Char>): BITSOperator { return when (input.nextInt(1)) { // Length Type 0 -> { val subPacketLength = input.nextInt(15) val subPacketIterator = input.next(subPacketLength).iterator() val subPackets = subPacketIterator.executeUntilEmpty { of(it) } BITSOperator(version, type, subPackets) } 1 -> { val numberOfPackets = input.nextInt(11) val subPackets = (1..numberOfPackets).map { of(input) } BITSOperator(version, type, subPackets) } else -> error("Invalid Operator length type") } } } }
0
Kotlin
0
0
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
2,487
AdventOfCode2021
The Unlicense
solutions/src/main/kotlin/fr/triozer/aoc/y2022/Day03.kt
triozer
573,964,813
false
{"Kotlin": 16632, "Shell": 3355, "JavaScript": 1716}
package fr.triozer.aoc.y2022 import fr.triozer.aoc.utils.readInput // #region part1 private fun part1(input: List<String>): Int = input.sumOf { val (first, second) = it.chunked(it.length / 2) val item = first.filter { c -> second.contains(c) }[0] if (item.isUpperCase()) { item.code - 'A'.code + 27 } else { item.code - 'a'.code + 1 } } // #endregion part1 // #region part2 private fun part2(input: List<String>) = input.windowed(3, 3).sumOf { val (first, second, third) = it val badge = first.filter { c -> second.contains(c) && third.contains(c) }[0] if (badge.isUpperCase()) { badge.code - 'A'.code + 27 } else { badge.code - 'a'.code + 1 } } // #endregion part2 private fun main() { val testInput = readInput(2022, 3, "test") check(part1(testInput) == 157) check(part2(testInput) == 70) println("Checks passed ✅") val input = readInput(2022, 3, "input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a9f47fa0f749a40e9667295ea8a4023045793ac1
1,014
advent-of-code
Apache License 2.0