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
archive/src/main/kotlin/com/grappenmaker/aoc/year20/Day08.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year20 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.year20.Opcode.* import com.grappenmaker.aoc.hasDuplicateBy import com.grappenmaker.aoc.untilNotDistinctBy fun PuzzleSet.day8() = puzzle(8) { val insns = inputLines.map { l -> val (a, b) = l.split(" ") enumValueOf<Opcode>(a.uppercase()) to b.toInt() } fun List<Pair<Opcode, Int>>.seq() = generateSequence(0 to 0) { (acc, ptr) -> getOrNull(ptr)?.let { (op, a) -> when (op) { NOP -> acc to ptr + 1 ACC -> acc + a to ptr + 1 JMP -> acc to ptr + a } } } partOne = insns.seq().untilNotDistinctBy { (_, ptr) -> ptr }.last().first.s() partTwo = insns.indices.filter { insns[it].first in listOf(NOP, JMP) }.map { idx -> val (op, a) = insns[idx] insns.toMutableList().apply { set(idx, (if (op == NOP) JMP else NOP) to a) }.seq() }.first { !it.hasDuplicateBy { (_, ptr) -> ptr } }.last().first.s() } enum class Opcode { NOP, ACC, JMP }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,083
advent-of-code
The Unlicense
src/com/github/crunchynomnom/aoc2022/puzzles/Day07.kt
CrunchyNomNom
573,394,553
false
{"Kotlin": 14290, "Shell": 518}
package com.github.crunchynomnom.aoc2022.puzzles import Puzzle import java.io.File class Day07 : Puzzle() { private var dirHeap: MutableList<Dir> = mutableListOf() override fun part1(input: File) { var result = 0 for (line in input.readLines()) { when { line.endsWith('.') -> { val tmp = dirHeap.removeLast() result += tmp.getAdjustedSize() dirHeap.last().dirs.add(tmp) } line.startsWith("$ cd") -> dirHeap.add(Dir()) line.contains(Regex("[0-9]+")) -> dirHeap.last().files.add(line.split(" ")) } } while (dirHeap.size > 1) { val tmp = dirHeap.removeLast() result += tmp.getAdjustedSize() dirHeap.last().dirs.add(tmp) } result += dirHeap.last().getAdjustedSize() println(result) } override fun part2(input: File) { part1(input) // loads the directory val req = dirHeap.last().getTotalSize() + 30000000 - 70000000 println(dirHeap.last().getBestSize(req)) } private data class Dir( val dirs: MutableList<Dir> = mutableListOf(), val files: MutableList<List<String>> = mutableListOf(), var size: Int? = null ) { fun getAdjustedSize(limit: Int = 100000): Int { val result = getTotalSize() return (if(result <= limit) result else 0) } fun getBestSize(req: Int): Int { if (dirs.isEmpty()) return getTotalSize() var best = Int.MAX_VALUE for (dir in dirs) { val subbest = dir.getBestSize(req) if (subbest > req && subbest - req < best - req) best = subbest } return (if (getTotalSize() > req && getTotalSize() - req < best - req) getTotalSize() else best) } fun getTotalSize(): Int { if (size == null) { size = dirs.sumOf { x -> x.getTotalSize() } + files.sumOf { x -> x.first().toInt() } } return (size as Int) } } }
0
Kotlin
0
0
88bae9c0ce7f66a78f672b419e247cdd7374cdc1
2,196
advent-of-code-2022
Apache License 2.0
Dynamic Programming/Primitive Calculator/src/Task.kt
jetbrains-academy
515,621,972
false
{"Kotlin": 123026, "TeX": 51581, "Java": 3566, "Python": 1156, "CSS": 671}
private fun calculateDP(n: Int): IntArray { val minOp = IntArray(n + 1) minOp[0] = 0 for (i in 1..n) { var current = minOp[i - 1] + 1 for (div in 2..3) { if (i % div == 0) { current = minOf(current, minOp[i / div] + 1) } } minOp[i] = current } return minOp } private fun restoreAnswer(n: Int, minOp: IntArray): List<Int> { val answer = mutableListOf<Int>() var i = n while (i > 1) { answer.add(i) i = when { minOp[i] == minOp[i - 1] + 1 -> i - 1 i % 2 == 0 && minOp[i] == minOp[i / 2] + 1 -> i / 2 else -> i / 3 } } answer.add(1) answer.reverse() return answer } fun findMinimumOperations(n: Int): List<Int> { val minOp = calculateDP(n) return restoreAnswer(n, minOp) }
2
Kotlin
0
10
a278b09534954656175df39601059fc03bc53741
861
algo-challenges-in-kotlin
MIT License
src/chapter2/section5/ex23_SamplingForSelection.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter2.section5 import chapter2.getCompareTimes import chapter2.getDoubleArray import chapter2.less import chapter2.swap import extensions.random import extensions.shuffle /** * 选择的取样 * 实验使用取样来改进select()函数的想法。提示:使用中位数可能并不总是有效 * * 解:可以使用三取样快速排序的思想优化,也可以用更复杂的练习2.3.24来实现 * 这里为简单起见使用了三取样快速排序的思想 * 和标准三取样快速排序不同的是,先比较k和array.size的大小, * 若k<size/3,则每次取三个数中最小的,若size/3<k<2*size/3则每次取中值,若k>2*size/3则每次取最大值 */ fun <T : Comparable<T>> ex23_SamplingForSelection(array: Array<T>, k: Int): T { array.shuffle() return samplingForSelection(array, k, 0, array.size - 1) } fun <T : Comparable<T>> samplingForSelection(array: Array<T>, k: Int, start: Int, end: Int): T { //k必须在有效范围内 require(k in start..end) if (start == end) return array[k] //范围较小时直接排序,不取样 val size = end - start + 1 if (size > 10) { val indexArray = intArrayOf(start, (start + end) / 2, end) sortByIndex(array, indexArray) val select = when { k < size / 3 -> indexArray[0] k > 2 * size / 3 -> indexArray[2] else -> indexArray[1] } array.swap(start, select) } val partition = chapter2.section3.partition(array, start, end) return when { partition == k -> array[partition] partition < k -> samplingForSelection(array, k, partition + 1, end) else -> samplingForSelection(array, k, start, partition - 1) } } private fun <T : Comparable<T>> sortByIndex(array: Array<T>, indexArray: IntArray) { for (i in 1 until indexArray.size) { for (j in i downTo 1) { if (array.less(indexArray[j], indexArray[j - 1])) { indexArray.swap(j, j - 1) } else { break } } } } fun main() { val size = 10_0000 val times = 100 val array = getDoubleArray(size) var compareTimes1 = 0L var compareTimes2 = 0L repeat(times) { //当k很小或很大时,能节省更多的比较次数 val k = random(size) var value1 = 0.0 var value2 = 1.0 compareTimes1 += getCompareTimes(array.copyOf()) { value1 = select(it, k) } compareTimes2 += getCompareTimes(array.copyOf()) { value2 = ex23_SamplingForSelection(it, k) } check(value1 == value2) } println("select average compare: ${compareTimes1 / times} times") println(" ex23 average compare: ${compareTimes2 / times} times") }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,809
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/io/steinh/aoc/day05/AlmanacInputProcessor.kt
daincredibleholg
726,426,347
false
{"Kotlin": 25396}
package io.steinh.aoc.day05 class AlmanacInputProcessor { companion object { const val LENGTH_POSITION = 3 } fun transform(input: String): Input { return Input( extractSeeds(input), extractBlockFor("seed-to-soil", input), extractBlockFor("soil-to-fertilizer", input), extractBlockFor("fertilizer-to-water", input), extractBlockFor("water-to-light", input), extractBlockFor("light-to-temperature", input), extractBlockFor("temperature-to-humidity", input), extractBlockFor("humidity-to-location", input) ) } private fun extractSeeds(input: String): List<Long> { val spaceSeperatedSeeds = "^seeds: ([\\d ]+)\n".toRegex().find(input) ?: return emptyList() return spaceSeperatedSeeds.groupValues[1].split(" ").map { it.toLong() } } private fun extractBlockFor(prefix: String, input: String): List<Mapping> { val rawMappings = "$prefix map:.*([\\d \\n]+)".toRegex().findAll(input) return rawMappings.flatMap { "(\\d+) (\\d+) (\\d+)\\n?".toRegex().findAll(it.groupValues[1]) .map { mappings -> extractMapping(mappings) } }.toList() } private fun extractMapping(matchResult: MatchResult): Mapping { var length = matchResult.groupValues[LENGTH_POSITION].toLong() if (length > 0) { length -= 1 } val destinationRangeStart = matchResult.groupValues[1].toLong() val sourceRangeStart = matchResult.groupValues[2].toLong() return Mapping(destinationRangeStart..(destinationRangeStart+length), sourceRangeStart..(sourceRangeStart+length)) } } data class Mapping( val destinationRangeStart: LongRange, val sourceRangeStart: LongRange, ) data class Input( val seeds: List<Long>, val seedToSoilMappings: List<Mapping>, val soilToFertilizerMappings: List<Mapping>, val fertilizerToWaterMappings: List<Mapping>, val waterToLightMappings: List<Mapping>, val lightToTemperatureMappings: List<Mapping>, val temperatureToHumidityMappings: List<Mapping>, val humidityToLocationMappings: List<Mapping>, )
0
Kotlin
0
0
4aa7c684d0e337c257ae55a95b80f1cf388972a9
2,232
AdventOfCode2023
MIT License
src/main/kotlin/com/gildedrose/Item.kt
jack-bolles
424,172,564
false
{"Kotlin": 10899}
package com.gildedrose data class Item(val name: String, val sellIn: Int, val quality: Int) { override fun toString(): String { return this.name + ", " + this.sellIn + ", " + this.quality } } fun Item.ageBy(days: Int): Item { return copy( sellIn = remainingSellInAfter(days), quality = qualityIn(days) ) } private fun Item.remainingSellInAfter(days: Int): Int { return when (name) { "Sulfuras, Hand of Ragnaros" -> sellIn else -> sellIn - days } } private fun Item.qualityIn(days: Int): Int { return when { name == "Backstage passes to a TAFKAL80ETC concert" -> boundedQuality(quality + this.incrementQualityFor(days)) name == "Sulfuras, Hand of Ragnaros" -> quality name == "Aged Brie" -> boundedQuality(quality + days) name.startsWith("Conjured") -> boundedQuality(quality + -2 * days) else -> boundedQuality(quality + -1 * days) } } private fun boundedQuality(rawQuality: Int): Int { return Integer.min(50, Integer.max(0, rawQuality)) } private fun Item.incrementQualityFor(days: Int): Int { val daysToSell = sellIn return (1 until days + 1) .fold(0) { total, e -> total + accelerateQualityWhenExpiring(daysToSell - e, quality) } } private fun accelerateQualityWhenExpiring(sellIn: Int, startingQuality: Int): Int { return when { sellIn < 0 -> -startingQuality sellIn <= 5 -> 3 sellIn <= 10 -> 2 else -> 1 } }
0
Kotlin
0
0
20362811724367e10e60fcf79b8709e60e9b0dde
1,540
GildedRose-Refactoring-Kata-Kotlin
MIT License
2016/src/main/kotlin/com/koenv/adventofcode/Day4.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode import java.util.* import java.util.regex.Pattern import kotlin.comparisons.compareValues object Day4 { val ROOM_NAME_PATTERN: Pattern = Pattern.compile("([a-z\\-]*)-(\\d+)\\[([a-z]{5})\\]") fun getRoomName(input: String): RoomName { val matcher = ROOM_NAME_PATTERN.matcher(input) if (!matcher.find()) { throw IllegalStateException("Invalid room name: $input") } return RoomName( matcher.group(1), matcher.group(2).toInt(), matcher.group(3).toCharArray().toList() ) } fun getMostCommonLetters(encryptedName: String) = encryptedName.toCharArray() .filter { it != '-' } .groupBy { it } .values .sortedWith(Comparator { lhs, rhs -> if (lhs.size == rhs.size) { return@Comparator compareValues(lhs[0], rhs[0]) } compareValues(rhs.size, lhs.size) }) .map { it[0] } .take(5) fun isChecksumValid(room: RoomName) = room.mostCommonLetters == getMostCommonLetters(room.encryptedName) fun getSectorIdSum(input: String) = input.lines() .filter(String::isNotBlank) .map { getRoomName(it) } .filter { isChecksumValid(it) } .sumBy { it.sectorId } fun decryptName(room: RoomName) = String(room.encryptedName .toCharArray() .map { shiftLetter(it, room.sectorId) } .toCharArray()) fun shiftLetter(letter: Char, n: Int): Char { if (letter == '-') { return ' ' } var new = letter for (i in 1..n) { new = shiftLetter(new) } return new } fun shiftLetter(letter: Char): Char { if (letter == 'z') { return 'a' } return letter + 1 } fun getNorthPoleObjectStorageSectorId(input: String) = input.lines() .filter(String::isNotBlank) .map { getRoomName(it) } .filter { isChecksumValid(it) } .map { decryptName(it) to it.sectorId } .find { it.first == "northpole object storage" }!! .second data class RoomName( val encryptedName: String, val sectorId: Int, val mostCommonLetters: List<Char> ) }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
2,420
AdventOfCode-Solutions-Kotlin
MIT License
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day11.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day11 : Day<Int> { companion object { private const val SEAT_EMPTY = 'L' private const val SEAT_OCCUPIED = '#' private const val PRINT_DEBUG = false } private val initialState: Array<CharArray> = readDayInput() .lines() .map { line -> line.toCharArray() } .toTypedArray() private val height = initialState.size private val width = initialState[0].size private data class Vector(val dx: Int, val dy: Int) private data class Point(val x: Int, val y: Int) private operator fun Point.plus(vector: Vector) = Point( x = x + vector.dx, y = y + vector.dy ) // We check seats in every direction: horizontally, vertically, // and diagonally, both ways. private val possibleDirections: List<Vector> = (-1..+1).map { dx -> (-1..+1).map { dy -> Vector(dx, dy) } }.flatten() - Vector(0, 0) private fun Array<CharArray>.nextState(minOccupiedSeatsToBecomeEmpty: Int, maxDistance: Int): Array<CharArray> { return mapIndexed { iy, line -> line.mapIndexed { ix, item -> // Count the number of occupied seats around the current seat val occupiedSeats = possibleDirections.sumOf { vector -> countOccupiedSeatsVisibleFromSeat( position = Point(ix, iy) + vector, vector = vector, maxDistance = maxDistance ) } when { item == SEAT_EMPTY && occupiedSeats == 0 -> SEAT_OCCUPIED item == SEAT_OCCUPIED && occupiedSeats >= minOccupiedSeatsToBecomeEmpty -> SEAT_EMPTY else -> item } }.toCharArray() }.toTypedArray() } private tailrec fun Array<CharArray>.countOccupiedSeatsVisibleFromSeat( position: Point, vector: Vector, maxDistance: Int, acc: Int = 0, distance: Int = 1, ): Int { val widthOufOfBounds = position.x !in 0 until width val heightOufOfBounds = position.y !in 0 until height // If we're out of bounds, return the number of seats we've found. if (widthOufOfBounds || heightOufOfBounds) { return acc } // Check the seat at the current position return when (this[position.y][position.x]) { // If it's an occupied seat, we can't see through it, and we just report it SEAT_OCCUPIED -> acc + 1 // If it's an empty seat, we can't see through it, // so we report there's no occupied seat on this vector SEAT_EMPTY -> acc // There's floor here, so we can see further. // Advance one spot on our vector and check there else -> when { distance >= maxDistance -> acc else -> countOccupiedSeatsVisibleFromSeat( position = position + vector, vector = vector, acc = acc, distance = distance + 1, maxDistance = maxDistance ) } } } private fun print(grid: Array<CharArray>) { grid.forEach { line -> line.forEach { char -> print("$char ") } println() } println("---------\n") } private fun Array<CharArray>.countOccupiedSeats(): Int { return sumOf { line -> line.count { char -> char == SEAT_OCCUPIED } } } private tailrec fun Array<CharArray>.findFinalState( minOccupiedSeatsToBecomeEmpty: Int, maxDistance: Int ): Array<CharArray> { if (PRINT_DEBUG) print(this) val nextState = nextState(minOccupiedSeatsToBecomeEmpty, maxDistance) return when { contentDeepEquals(nextState) -> nextState else -> nextState.findFinalState(minOccupiedSeatsToBecomeEmpty, maxDistance) } } override fun step1() = initialState .findFinalState(minOccupiedSeatsToBecomeEmpty = 4, maxDistance = 1) .countOccupiedSeats() override fun step2() = initialState .findFinalState(minOccupiedSeatsToBecomeEmpty = 5, maxDistance = Int.MAX_VALUE) .countOccupiedSeats() override val expectedStep1: Int = 2324 override val expectedStep2: Int = 2068 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
4,621
adventofcode
Apache License 2.0
src/main/kotlin/leetcode/problem0126/WordLadder2.kt
ayukatawago
456,312,186
false
{"Kotlin": 266300, "Python": 1842}
package leetcode.problem0126 class WordLadder2 { fun findLadders(beginWord: String, endWord: String, wordList: List<String>): List<List<String>> { if (endWord !in wordList) return emptyList() val wordSet = setOf(beginWord) + wordList.toSet() val adjacentWordMap: HashMap<String, List<String>> = hashMapOf() wordSet.forEach { word -> adjacentWordMap[word] = wordSet.filter { it.isAdjacent(word) } } val queue = ArrayDeque<String>() val levelMap: HashMap<String, Int> = hashMapOf() val graph: HashMap<String, MutableSet<String>> = hashMapOf() levelMap[beginWord] = 0 queue.add(beginWord) while (queue.isNotEmpty()) { val currentWord = queue.removeFirst() val currentLevel = levelMap[currentWord] ?: throw IllegalStateException() if (!graph.containsKey(currentWord)) { graph[currentWord] = mutableSetOf() } adjacentWordMap[currentWord]?.forEach { graph[currentWord]?.add(it) if (!levelMap.containsKey(it)) { levelMap[it] = currentLevel + 1 queue.add(it) } } } if (!levelMap.containsKey(endWord)) { return emptyList() } val answerSet = mutableListOf<List<String>>() val stringPath = mutableListOf<String>() fun buildAnswer(word: String, level: Int) { if (word == beginWord) { answerSet.add(stringPath + listOf(word)) return } stringPath.add(word) graph[word]?.forEach { nextWord -> if (levelMap[nextWord] != level - 1) return@forEach buildAnswer(nextWord, level - 1) } stringPath.removeLast() } buildAnswer(endWord, levelMap[endWord]!!) return answerSet.map { it.reversed() } } private fun String.isAdjacent(target: String): Boolean { if (this.length != target.length) return false var count = 0 forEachIndexed { index, c -> if (target[index] != c) { count++ } } return count == 1 } }
0
Kotlin
0
0
f9602f2560a6c9102728ccbc5c1ff8fa421341b8
2,284
leetcode-kotlin
MIT License
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day03.kt
akikanellis
600,872,090
false
{"Kotlin": 142932, "Just": 977}
package com.akikanellis.adventofcode.year2022 object Day03 { fun sumOfPrioritiesForMisplacedItemTypes(input: String) = lines(input) .map { Pair(it.take(it.length / 2).toSet(), it.takeLast(it.length / 2).toSet()) } .map { it.first.intersect(it.second).single() } .sumOf { priority(it) } fun sumOfPrioritiesForBadges(input: String) = lines(input) .chunked(3) .map { Triple(it[0].toSet(), it[1].toSet(), it[2].toSet()) } .map { it.first.intersect(it.second).intersect(it.third).single() } .sumOf { priority(it) } private fun lines(input: String) = input .lines() .filter { it.isNotBlank() } private fun priority(itemType: Char) = when { itemType.isLowerCase() -> itemType - 'a' + 1 else -> itemType - 'A' + 27 } }
8
Kotlin
0
0
036cbcb79d4dac96df2e478938de862a20549dce
843
advent-of-code
MIT License
src/main/kotlin/day10.kt
mercer
113,610,628
false
null
// // References: // https://dzone.com/articles/solving-the-josephus-problem-in-kotlin class CircularHash { fun calculate(circularListSize: Int, lengths: List<Int>): Pair<Int, Int> { var circle = generateList(circularListSize) println(circle); println() for (length in lengths) { circle = circle.pinchAndTwist(length); println(circle); println() } return Pair(-1, -1) } class CircleList( private val items: List<Int>, private val currentPosition: Int, private val skipSize: Int ) { private val firstBead = Bead(items[0]) init { var currentBead = firstBead var nextBead = firstBead for (item in items.subList(1, items.lastIndex + 1)) { nextBead = Bead(item) currentBead.next = nextBead currentBead = nextBead } nextBead.next = firstBead debugBeads() } private fun debugBeads() { var currentBead = firstBead var beadsToList = listOf<Int>() for (i in 1..items.size) { beadsToList = beadsToList.plus(currentBead.position) currentBead = currentBead.next } println("beadsToList=$beadsToList") } fun pinchAndTwist(length: Int): CircleList { println("length=$length") val nextItems = pickBeadsToTwist(length) .asReversed() .plus(pickRemainingBeads(length)) val nextCurrentPosition = length + skipSize return CircleList(nextItems, nextCurrentPosition, skipSize + 1) } private fun pickBeadsToTwist(length: Int): List<Int> { var currentBead = firstBead for (i in 1..currentPosition) { currentBead = currentBead.next } var returnItems = listOf<Int>() for (i in 1..length) { returnItems = returnItems.plus(currentBead.position) currentBead = currentBead.next } println("pickfirstitems=$returnItems") return returnItems } private fun pickRemainingBeads(length: Int): List<Int> { var currentBead = firstBead for (i in 1..currentPosition) { currentBead = currentBead.next } for (i in 1..length) { currentBead = currentBead.next } var returnItems = listOf<Int>() for (i in 1..items.size - length) { returnItems = returnItems.plus(currentBead.position) currentBead = currentBead.next } println("picklastitems=$returnItems") return returnItems } override fun toString(): String { return "CircleList(items=$items, currentPosition=$currentPosition, skipSize=$skipSize)" } } class Bead(val position: Int) { lateinit var next: Bead lateinit var previous: Bead } private fun generateList(circularListSize: Int): CircleList { var count = 0 val items = generateSequence { (count++).takeIf { it < circularListSize } }.toList() return CircleList(items, 0, 0) } }
0
Kotlin
0
0
2bd6a2dc537f7ee44aa6fa23c2bf2804d034b4fc
3,374
advent-of-code-2017
The Unlicense
src/main/kotlin/g0001_0100/s0017_letter_combinations_of_a_phone_number/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0001_0100.s0017_letter_combinations_of_a_phone_number // #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table #Backtracking // #Algorithm_II_Day_11_Recursion_Backtracking #Udemy_Backtracking/Recursion // #Big_O_Time_O(4^n)_Space_O(n) #2023_07_03_Time_155_ms_(95.24%)_Space_34.9_MB_(96.34%) class Solution { fun letterCombinations(digits: String): List<String> { if (digits.isEmpty()) return ArrayList() val letters = arrayOf("", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz") val ans: MutableList<String> = ArrayList() val sb = StringBuilder() findCombinations(0, digits, letters, sb, ans) return ans } private fun findCombinations( start: Int, nums: String, letters: Array<String>, curr: StringBuilder, ans: MutableList<String> ) { if (curr.length == nums.length) { ans.add(curr.toString()) return } for (i in start until nums.length) { val n = Character.getNumericValue(nums[i]) for (j in 0 until letters[n].length) { val ch = letters[n][j] curr.append(ch) findCombinations(i + 1, nums, letters, curr, ans) curr.deleteCharAt(curr.length - 1) } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,368
LeetCode-in-Kotlin
MIT License
kotlin/src/katas/kotlin/leetcode/zigzag/ZigZag.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.zigzag import nonstdlib.printed import datsok.shouldEqual import org.junit.Test import kotlin.system.measureTimeMillis class ZigZagThreeRowTests { @Test fun `zigzag first column`() { "ABC".zigzag() shouldEqual "ABC" } @Test fun `zigzag one cycle`() { // A // B D // C "ABCD".zigzag() shouldEqual "ABDC" } @Test fun `zigzag two cycles`() { // A E // B D F H // C G "ABCDEFGH".zigzag() shouldEqual "AEBDFHCG" } } class ZigZagFourRowTests { @Test fun `zigzag first column`() { "ABCD".zigzag(rows = 4) shouldEqual "ABCD" } @Test fun `zigzag one cycle`() { // A G // B F // C E // D "ABCDEFG".zigzag(rows = 4) shouldEqual "AGBFCED" } @Test fun `zigzag two cycles`() { // A G N // B F H M // C E J L // D K "ABCDEFGHJKLMN".zigzag(rows = 4) shouldEqual "AGNBFHMCEJLDK" } } class ZigZagLongStringTests { @Test fun `long string`() { generateString(7).zigzag() shouldEqual "aebdfhcg" measureTimeMillis { longString.zigzag() }.printed() } private val longString = generateString(10_000_000) private fun generateString(length: Int) = (0..length).map { (it + 'a'.toInt()).toChar() }.joinToString("") } private fun String.zigzag(rows: Int = 3): String { val cycle = rows * 2 - 2 return (0..(cycle/2)).joinToString("") { val first = it val second = cycle - it filterIndexed { i, _ -> i % cycle == first || i % cycle == second } } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,682
katas
The Unlicense
src/main/kotlin/com/github/bpark/companion/analyzers/TypeFeatureAnalyzer.kt
bpark
93,539,081
false
null
/* * Copyright 2017 bpark * * 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.github.bpark.companion.analyzers import com.github.bpark.companion.input.Sentence import mu.KotlinLogging /** * Short alias for analyzed token. */ typealias AnalyzedToken = Pair<String, String> /** * Set of constants, fixed tags and predefined tokens. */ private object TokenConstants { const val VTAG = "VERB" const val JTAG = "JT" const val WHTAG = "WHQ" const val ITAG = "." const val QTAG = "?" const val ETAG = "!" val ANY = AnalyzedToken("", "*") val VERB = AnalyzedToken("_", VTAG) val START = AnalyzedToken("", "^") val QM = AnalyzedToken("QM", ".") val EM = AnalyzedToken("EM", ".") val DT = AnalyzedToken("DT", ".") val ANALYZER_TAGS = listOf(WHTAG, VTAG, JTAG, ITAG) } /** * Interface for all transformer steps. Each transformer step processes a list of analyzed tokens. */ private interface SentenceTransformer { fun transform(analyzedTokens: List<AnalyzedToken>): List<AnalyzedToken> fun startsWith(item: String, list: List<String>): Boolean { return list.stream().anyMatch { item.startsWith(it) } } } /** * Transformer to remove all irrelevant tokens for further processing, only verbs and a set of specific tokens are * kept. */ private object RelevantTokenTransformer : SentenceTransformer { val jTypes = listOf("much", "often", "many", "far") /** * Removes all irrelevant tokens from the list. */ override fun transform(analyzedTokens: List<AnalyzedToken>): List<AnalyzedToken> { val filteredTokens = analyzedTokens.map { if (startsWith(it.second, TokenConstants.ANALYZER_TAGS)) it else TokenConstants.ANY }.toMutableList() filteredTokens.forEachIndexed { index, (first, second) -> run { if (second == TokenConstants.VTAG) filteredTokens[index] = TokenConstants.VERB if (second == TokenConstants.JTAG && !jTypes.contains(first)) filteredTokens[index] = TokenConstants.ANY } } return filteredTokens } } /** * Removes all duplicated tokens. */ private object DuplicateTokenTransformer : SentenceTransformer { override fun transform(analyzedTokens: List<AnalyzedToken>): List<AnalyzedToken> { val filtered = analyzedTokens.toMutableList() for (tag in TokenConstants.ANALYZER_TAGS) { val index = filtered.indexOfFirst { it.second == tag } if (index != -1) { val first = filtered[index] filtered.removeAll { it.second == tag } filtered.add(index, first) } } val reduced = mutableListOf<AnalyzedToken>() filtered.forEach { if (reduced.lastOrNull() != it) reduced.add(it) } return reduced } } /** * Defines the start token, relevant if a phrase starts with a WH-Token or a verb. */ private object StartTokenTransformer : SentenceTransformer { override fun transform(analyzedTokens: List<AnalyzedToken>): List<AnalyzedToken> { val (_, tag) = analyzedTokens.first() val tokens = analyzedTokens.toMutableList() if (tag == TokenConstants.WHTAG || tag == TokenConstants.VTAG) { tokens.add(0, TokenConstants.START) } else if (tag != "*") { tokens.add(0, TokenConstants.ANY) } return tokens } } /** * Fills the remaining set of tokens with ANY Tokens (*) until a defined size of the set. */ private object FillTokenTransformer : SentenceTransformer { override fun transform(analyzedTokens: List<AnalyzedToken>): List<AnalyzedToken> { val tokens = analyzedTokens.toMutableList() while (tokens.size < 8) { tokens.add(tokens.size - 1, TokenConstants.ANY) } return tokens } } /** * Defines the End-Token (.!?). */ private object EndTokenTransformer : SentenceTransformer { override fun transform(analyzedTokens: List<AnalyzedToken>): List<AnalyzedToken> { val tokens = analyzedTokens.toMutableList() val (token, _) = tokens.last() if (token == TokenConstants.QTAG) { tokens[tokens.lastIndex] = TokenConstants.QM } if (token == TokenConstants.ETAG) { tokens[tokens.lastIndex] = TokenConstants.EM } if (token == TokenConstants.ITAG) { tokens[tokens.lastIndex] = TokenConstants.DT } return tokens } } /** * Transforms a given sentence into a fixed-length sequence of defined tokens. This token sequence is used to * build an instance for classification. */ object SentenceTypeFeatureTransformer : FeatureAnalyzer { private val logger = KotlinLogging.logger {} override fun transform(sentence: Sentence): List<String> { logger.info { "analyzing sentence $sentence" } val tokens = sentence.nlp.tokens val tags = sentence.nlp.posTags val transformers = listOf(RelevantTokenTransformer, DuplicateTokenTransformer, StartTokenTransformer, FillTokenTransformer, EndTokenTransformer) var analyzedTokens = mapToAnalyzed(tokens, tags) for (transformer in transformers) { analyzedTokens = transformer.transform(analyzedTokens) } logger.info { "analyzed tokens $analyzedTokens" } return analyzedTokens.map { render(it) } } private fun mapToAnalyzed(tokens: List<String>, tags: List<String>): List<AnalyzedToken> { val tokenTags = mutableListOf<Pair<String, String>>() for ((index, token) in tokens.withIndex()) { var tag = tags[index] if (tag.startsWith("WRB") || tag.startsWith("WP")) { tag = TokenConstants.WHTAG } if (tag.startsWith("VB")) { tag = TokenConstants.VTAG } if (tag == "JJ" || tag == "RB") { tag = TokenConstants.JTAG } tokenTags.add(Pair(token.toLowerCase(), tag)) } if (tags.last() != ".") { tokenTags.add(AnalyzedToken(".", ".")) } return tokenTags } private fun render(analyzedToken: AnalyzedToken): String { val (token, tag) = analyzedToken return if (token.isNotEmpty()) { "($token/$tag)" } else { "($tag)" } } }
0
Kotlin
0
0
56a81b36cbebdb3dfb343fd2a37ee4d227a8c4c4
7,069
companion-classification-micro
Apache License 2.0
AdventOfCodeDay11/src/nativeMain/kotlin/Day11.kt
bdlepla
451,510,571
false
{"Kotlin": 165771}
class Day11(private val lines:List<String>) { fun solvePart1():Int { val cavern = Matrix.create(lines) return (0 until 100).sumOf { countFlashesWhenStepping(cavern) } } fun solvePart2():Int { val cavern = Matrix.create(lines) val allPointsNumber = cavern.allPoints().count() var steps = 1 while (true) { if (allPointsNumber == countFlashesWhenStepping(cavern)) { return steps } steps += 1 } } private fun countFlashesWhenStepping(cavern:Matrix):Int { //println("Start Step") //println("----------") //println(cavern.print()) //println("----------") //println("") // increment all per step cavern.allPoints().forEach { pt -> cavern[pt] += 1 } // perform flashing; points only flash once per step // 10 indicates just flashed and must be handled (increment neighbors including diagonals) // >10 has already flashed and does not need to be activated this step // just counted val queue = Queue(cavern.allPoints().filter { cavern[it] == 10 }) val visited = emptySet<Point>().toMutableSet() while (queue.isNotEmpty()) { //println("queue = ${queue.asSequence().joinToString()}") val point = queue.dequeue() if (point !in visited) { visited.add(point) cavern[point] += 1 // increment to 10 so that we don't flash it again val neighbors = point.validNeighbors(cavern) neighbors.forEach { pt -> cavern[pt] += 1 } queue.enqueueAll(neighbors.filter { pt -> cavern[pt] == 10 }) } } // find all that flashed this step val pointsToReset = cavern.allPoints().filter { pt -> cavern[pt] > 9 }.toList() // reset flashed to 0 pointsToReset.forEach { pt -> cavern[pt] = 0 } // return count of flashed this step //println("${pointsToReset.count()} flashed this step") return pointsToReset.count() } private fun Point.neighbors() = listOf ( Point(this.first-1, this.second-1), Point(this.first, this.second-1), Point(this.first+1, this.second-1), Point(this.first-1, this.second), Point(this.first+1, this.second), Point(this.first-1, this.second+1), Point(this.first, this.second+1), Point(this.first+1, this.second+1)) private fun Point.validNeighbors(cavern:Matrix) = this.neighbors().filter{it in cavern} }
0
Kotlin
0
0
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
2,608
AdventOfCode2021
The Unlicense
src/main/kotlin/day3.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
fun day3 (lines: List<String>) { val partNumbers = findPartNumbers(lines) markInvalidPartNumbers(lines, partNumbers) findAdjacentGears(lines, partNumbers) val partNumberSum = partNumbers.filter { it.isValidPartNumber }.sumOf { it.number } val gearRatioSum = calculateGearRatioSum(partNumbers) println("Day 3 part 1: $partNumberSum") println("Day 3 part 2: $gearRatioSum") println() } fun findAdjacentGears(lines: List<String>, partNumbers: List<PartNumber>) { partNumbers.forEach { val gearCoordinate = anyAdjacentGear(lines, it) if(gearCoordinate != null) { it.gearCoordinate = gearCoordinate } } } fun anyAdjacentGear(lines: List<String>, partNumber: PartNumber): Coordinate? { for (i in partNumber.startX..<partNumber.startX + partNumber.length) { val gearCoordinate = findAdjacentGear(lines, i , partNumber.y) if (gearCoordinate != null) { return gearCoordinate } } return null } fun findAdjacentGear(lines: List<String>, x: Int, y: Int): Coordinate? { for (xi in x-1..x+1) { for (yi in y-1..y+1) { try { if (lines[yi][xi] == '*') { return Coordinate(xi, yi) } } catch (e: IndexOutOfBoundsException) { continue } } } return null } fun calculateGearRatioSum(partNumbers: List<PartNumber>): Long { var gearRatioSum = 0L for (i in partNumbers.indices) { if (partNumbers[i].gearCoordinate == null) { continue } val numbersWithGear = mutableListOf(partNumbers[i].number) for (j in partNumbers.indices) { if (i == j) { continue } if (partNumbers[i].gearCoordinate == partNumbers[j].gearCoordinate) { numbersWithGear.add(partNumbers[j].number) } } if (numbersWithGear.size == 2) { gearRatioSum += (numbersWithGear[0] * numbersWithGear[1]) } } return gearRatioSum / 2 } fun markInvalidPartNumbers(lines: List<String>, partNumbers: List<PartNumber>) { partNumbers.forEach { if(anyAdjacent(lines, it)) { it.isValidPartNumber = true } } } fun anyAdjacent(lines: List<String>, partNumber: PartNumber): Boolean { for (i in partNumber.startX..<partNumber.startX + partNumber.length) { if (isAdjacent(lines, i, partNumber.y)) { return true } } return false } fun isAdjacent(lines: List<String>, x: Int, y: Int): Boolean { for (xi in x-1..x+1) { for (yi in y-1..y+1) { try { if (lines[yi][xi] != '.' && !lines[yi][xi].isDigit()) { return true } } catch (e: IndexOutOfBoundsException) { continue } } } return false } fun findPartNumbers(lines: List<String>): List<PartNumber> { val partNumbers = mutableListOf<PartNumber>() lines.forEachIndexed { yIndex, row -> var numberBuilder = "" row.forEachIndexed { xIndex, cell -> if (cell.isDigit()) { numberBuilder += cell } else { if (numberBuilder.isNotEmpty()) { partNumbers.add(PartNumber(Integer.parseInt(numberBuilder), xIndex - numberBuilder.length, numberBuilder.length, yIndex, false, null)) } numberBuilder = "" } if (xIndex == row.length - 1 && numberBuilder.isNotEmpty()) { partNumbers.add(PartNumber(Integer.parseInt(numberBuilder), xIndex - numberBuilder.length, numberBuilder.length, yIndex, false, null)) } } } return partNumbers } data class PartNumber (val number: Int, val startX: Int, val length: Int, val y: Int, var isValidPartNumber: Boolean, var gearCoordinate: Coordinate?) data class Coordinate (val x: Int, val y: Int)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
4,100
advent_of_code_2023
MIT License
kotlin/src/katas/kotlin/leetcode/wildcard_matching/v2/WildcardMatching2.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.wildcard_matching.v2 import datsok.* import org.junit.* class WildcardMatching2 { @Test fun `some examples`() { match("", "") shouldEqual true match("a", "") shouldEqual false match("", "a") shouldEqual false match("a", "a") shouldEqual true match("a", "b") shouldEqual false match("aa", "a") shouldEqual false match("a", "aa") shouldEqual false match("ab", "ab") shouldEqual true match("", "?") shouldEqual false match("a", "?") shouldEqual true match("?", "a") shouldEqual false match("?", "?") shouldEqual true match("ab", "a?") shouldEqual true match("ab", "??") shouldEqual true match("ab", "???") shouldEqual false match("abc", "??") shouldEqual false match("", "*") shouldEqual true match("abc", "*") shouldEqual true match("abc", "ab*") shouldEqual true match("abc", "a*c") shouldEqual true match("abc", "*bc") shouldEqual true match("abc", "a*") shouldEqual true match("abc", "*c") shouldEqual true match("abc", "*cc") shouldEqual false match("abc", "aa*") shouldEqual false match("abc", "**") shouldEqual true } } private typealias Matcher = (input: String) -> List<String> private fun char(c: Char): Matcher = { input: String -> if (input.isEmpty() || input.first() != c) emptyList() else listOf(input.drop(1)) } private fun question(): Matcher = { input: String -> if (input.isEmpty()) emptyList() else listOf(input.drop(1)) } private fun star(): Matcher = { input: String -> if (input.isEmpty()) listOf(input) else input.indices.map { i -> input.substring(i + 1, input.length) } } private fun match(s: String, pattern: String): Boolean { val matchers = pattern.map { when (it) { '?' -> question() '*' -> star() else -> char(it) } } return matchers .fold(listOf(s)) { inputs, matcher -> inputs.flatMap(matcher) } .any { it.isEmpty() } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,110
katas
The Unlicense
src/main/kotlin/days/Day01.kt
julia-kim
569,976,303
false
null
package days import readInput fun main() { fun mapElvesToCaloriesCounted(input: List<String>): HashMap<Int, Int> { var i = 1 val hm: HashMap<Int, Int> = hashMapOf() input.forEach { calories -> if (calories.isBlank()) { i++ return@forEach } hm[i] = (hm[i] ?: 0) + calories.toInt() } return hm } fun part1(input: List<String>): Int { return mapElvesToCaloriesCounted(input).values.max() } fun part2(input: List<String>): Int { return mapElvesToCaloriesCounted(input).values.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
65188040b3b37c7cb73ef5f2c7422587528d61a4
941
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day10/Day10.kt
stoerti
726,442,865
false
{"Kotlin": 19680}
package io.github.stoerti.aoc.day10 import io.github.stoerti.aoc.Grid2D import io.github.stoerti.aoc.Grid2D.Coordinate import io.github.stoerti.aoc.IOUtils fun main(args: Array<String>) { val grid = IOUtils.readInput("day_10_input").let { Grid2D.charGrid(it) } println(grid) val result1 = part1(grid) println("Result1: $result1") } fun part1(map: Grid2D<Char>): Int { val start = map.findStart() println("Start at $start") val firstMove = listOf(start.up(), start.down(), start.left(), start.right()) .first { map.findPathNeighbors(it).contains(start) } val path = mutableListOf(start, firstMove) while (path.last() != start) { path.add(map.findPathNeighbors(path.last()).first { path[path.size-2] != it }) } return path.size / 2 } fun Grid2D<Char>.findStart(): Coordinate { map.forEachIndexed { y, col -> col.forEachIndexed { x, point -> if (point == 'S') return@findStart Coordinate( x, y ) } } throw Exception() } fun Grid2D<Char>.findPathNeighbors(coordinate: Coordinate): List<Coordinate> { return when (get(coordinate)) { '|' -> listOf(coordinate.up(), coordinate.down()) '-' -> listOf(coordinate.left(), coordinate.right()) 'L' -> listOf(coordinate.up(), coordinate.right()) 'J' -> listOf(coordinate.up(), coordinate.left()) '7' -> listOf(coordinate.left(), coordinate.down()) 'F' -> listOf(coordinate.right(), coordinate.down()) '.' -> emptyList() null -> emptyList() else -> throw Exception("Unknown char ${get(coordinate)} at $coordinate") } }
0
Kotlin
0
0
05668206293c4c51138bfa61ac64073de174e1b0
1,578
advent-of-code
Apache License 2.0
src/aoc_2022/Day02.kt
jakob-lj
573,335,157
false
{"Kotlin": 38689}
package aoc_2022 enum class PlayerSymbols(val value: Char) { ROCK("X".toCharArray()[0]), PAPER("Y".toCharArray()[0]), SCISSOR("Z".toCharArray()[0]) } enum class ElfSymbols(val value: Char) { ROCK("A".toCharArray()[0]), PAPER("B".toCharArray()[0]), SCISSOR("C".toCharArray()[0]) } enum class PlayerStrategy(val value: Char) { WIN("Z".toCharArray()[0]), DRAW("Y".toCharArray()[0]), LOOSE("X".toCharArray()[0]), } fun main(args: Array<String>) { val testInput = """ A Y B X C Z """.trimIndent() val input = testInput.filter { it.isLetter() }.toList() val rounds = mutableListOf<Pair<Char, Char>>() for (i in 0 until (input.size / 2)) { val k = i * 2 rounds.add(Pair(input[k], input[k + 1])) } val roundsPlayed = rounds.map { it.chooseCorrectWeaponForTotalWin() } val scores = roundsPlayed.map { it.calculateScore() } println(scores) println(scores.sum()) } fun Char.getWinningMove(): Char = when (this) { ElfSymbols.ROCK.value -> PlayerSymbols.PAPER.value ElfSymbols.PAPER.value -> PlayerSymbols.SCISSOR.value ElfSymbols.SCISSOR.value -> PlayerSymbols.ROCK.value else -> throw IllegalStateException("Symbol not found") } fun Char.getDrawMove(): Char = when (this) { ElfSymbols.ROCK.value -> PlayerSymbols.ROCK.value ElfSymbols.PAPER.value -> PlayerSymbols.PAPER.value ElfSymbols.SCISSOR.value -> PlayerSymbols.SCISSOR.value else -> throw IllegalStateException("Symbol not found") } fun Char.getLoosingMove(): Char = when (this) { ElfSymbols.ROCK.value -> PlayerSymbols.SCISSOR.value ElfSymbols.PAPER.value -> PlayerSymbols.ROCK.value ElfSymbols.SCISSOR.value -> PlayerSymbols.PAPER.value else -> throw IllegalStateException("Symbol not found") } fun Pair<Char, Char>.chooseCorrectWeaponForTotalWin(): Pair<Char, Char> { val move = when (this.second) { PlayerStrategy.WIN.value -> this.first.getWinningMove() PlayerStrategy.DRAW.value -> this.first.getDrawMove() PlayerStrategy.LOOSE.value -> this.first.getLoosingMove() else -> throw IllegalStateException("Player strat not found") } return Pair(this.first, move) } fun Char.calculateCharScore(): Int = when (val char = this) { PlayerSymbols.ROCK.value -> 1 PlayerSymbols.PAPER.value -> 2 PlayerSymbols.SCISSOR.value -> 3 else -> 0 } fun Pair<Char, Char>.calculateScoreIfWin(): Int { val drawScore = 3 val winnerScore = 6 return when (this.first) { ElfSymbols.ROCK.value -> when (this.second) { PlayerSymbols.PAPER.value -> winnerScore PlayerSymbols.ROCK.value -> drawScore else -> 0 } ElfSymbols.PAPER.value -> when (this.second) { PlayerSymbols.SCISSOR.value -> winnerScore PlayerSymbols.PAPER.value -> drawScore else -> 0 } ElfSymbols.SCISSOR.value -> when (this.second) { PlayerSymbols.ROCK.value -> winnerScore PlayerSymbols.SCISSOR.value -> drawScore else -> 0 } else -> 0 } } fun Pair<Char, Char>.calculateScore() = this.second.calculateCharScore() + this.calculateScoreIfWin()
0
Kotlin
0
0
3a7212dff9ef0644d9dce178e7cc9c3b4992c1ab
3,256
advent_of_code
Apache License 2.0
src/main/kotlin/g2801_2900/s2872_maximum_number_of_k_divisible_components/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2801_2900.s2872_maximum_number_of_k_divisible_components // #Hard #Dynamic_Programming #Depth_First_Search #Tree // #2023_12_21_Time_780_ms_(100.00%)_Space_79_MB_(100.00%) class Solution { private var ans = 0 fun maxKDivisibleComponents(n: Int, edges: Array<IntArray>, values: IntArray, k: Int): Int { val adj: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until n) { adj.add(ArrayList()) } for (edge in edges) { val start = edge[0] val end = edge[1] adj[start].add(end) adj[end].add(start) } val isVis = BooleanArray(n) isVis[0] = true get(0, -1, adj, isVis, values, k.toLong()) return ans } private fun get( curNode: Int, parent: Int, adj: List<MutableList<Int>>, isVis: BooleanArray, values: IntArray, k: Long ): Long { var sum = values[curNode].toLong() for (ele in adj[curNode]) { if (ele != parent && !isVis[ele]) { isVis[ele] = true sum += get(ele, curNode, adj, isVis, values, k) } } return if (sum % k == 0L) { ans++ 0 } else { sum } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,314
LeetCode-in-Kotlin
MIT License
src/Day17.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
private class Solution17(input: List<String>) { val jets = input.first().trim().split("").filter { it.isNotBlank() } val rocks = (0..6).map { MutableCoordinate(it, 0) }.toMutableSet() var jetCount = 0 fun part1(): Int { repeat(2022) { count -> val rock = nextRock(count, MutableCoordinate(2, rocks.maxOf { it.y } + 4)) while (true) { when (jets[jetCount % jets.size]) { ">" -> rock.moveRight(rocks) "<" -> rock.moveLeft(rocks) } jetCount++ if (!rock.tryMoveDown(rocks)) break } rocks.addAll(rock.coordinates()) } //rocks.groupBy { it.y }.toSortedMap(compareByDescending { it }).forEach{ y -> println((0..6).map { x -> if (MutableCoordinate(x, y.key) in rocks) "#" else " "}.joinToString("")) } return rocks.maxOf { it.y } } fun part2() = 0 abstract class Rock(val bottomLeft: MutableCoordinate) { abstract fun coordinates(): Set<MutableCoordinate> abstract val height: Int abstract val width: Int fun moveRight(rocks: MutableSet<MutableCoordinate>) { if (bottomLeft.x + width < 7) bottomLeft.x += 1 if ((rocks intersect coordinates()).isNotEmpty()) bottomLeft.x -= 1 } fun moveLeft(rocks: MutableSet<MutableCoordinate>) { if (bottomLeft.x > 0) bottomLeft.x -= 1 if ((rocks intersect coordinates()).isNotEmpty()) bottomLeft.x += 1 } fun moveDown() { bottomLeft.y -= 1 } fun moveUp() { bottomLeft.y += 1 } fun tryMoveDown(rocks: MutableSet<MutableCoordinate>): Boolean { if (bottomLeft.y == 0) return false moveDown() if ((rocks intersect coordinates()).isEmpty()) return true moveUp() return false } } fun nextRock(count: Int, bottomLeft: MutableCoordinate): Rock { return when (count % 5) { 0 -> Shape0(bottomLeft) 1 -> Shape1(bottomLeft) 2 -> Shape2(bottomLeft) 3 -> Shape3(bottomLeft) 4 -> Shape4(bottomLeft) else -> throw IllegalStateException() } } class Shape0(bottomLeft: MutableCoordinate) : Rock(bottomLeft) { override val height = 1 override val width = 4 override fun coordinates() = setOf( MutableCoordinate(bottomLeft.x, bottomLeft.y), MutableCoordinate(bottomLeft.x + 1, bottomLeft.y), MutableCoordinate(bottomLeft.x + 2, bottomLeft.y), MutableCoordinate(bottomLeft.x + 3, bottomLeft.y) ) } class Shape1(bottomLeft: MutableCoordinate) : Rock(bottomLeft) { override val height = 3 override val width = 3 override fun coordinates() = setOf( MutableCoordinate(bottomLeft.x + 1, bottomLeft.y), MutableCoordinate(bottomLeft.x, bottomLeft.y + 1), MutableCoordinate(bottomLeft.x + 1, bottomLeft.y + 1), MutableCoordinate(bottomLeft.x + 2, bottomLeft.y + 1), MutableCoordinate(bottomLeft.x + 1, bottomLeft.y + 2) ) } class Shape2(bottomLeft: MutableCoordinate) : Rock(bottomLeft) { override val height = 3 override val width = 3 override fun coordinates() = setOf( MutableCoordinate(bottomLeft.x, bottomLeft.y), MutableCoordinate(bottomLeft.x + 1, bottomLeft.y), MutableCoordinate(bottomLeft.x + 2, bottomLeft.y), MutableCoordinate(bottomLeft.x + 2, bottomLeft.y + 1), MutableCoordinate(bottomLeft.x + 2, bottomLeft.y + 2) ) } class Shape3(bottomLeft: MutableCoordinate) : Rock(bottomLeft) { override val height = 4 override val width = 1 override fun coordinates() = setOf( MutableCoordinate(bottomLeft.x, bottomLeft.y), MutableCoordinate(bottomLeft.x, bottomLeft.y + 1), MutableCoordinate(bottomLeft.x, bottomLeft.y + 2), MutableCoordinate(bottomLeft.x, bottomLeft.y + 3) ) } class Shape4(bottomLeft: MutableCoordinate) : Rock(bottomLeft) { override val height = 2 override val width = 2 override fun coordinates() = setOf( MutableCoordinate(bottomLeft.x, bottomLeft.y), MutableCoordinate(bottomLeft.x, bottomLeft.y + 1), MutableCoordinate(bottomLeft.x + 1, bottomLeft.y), MutableCoordinate(bottomLeft.x + 1, bottomLeft.y + 1) ) } } fun main() { val testSolution = Solution17(readInput("Day17_test")) check(testSolution.part1() == 3068) //check(testSolution.part2() == 0) val solution = Solution17(readInput("Day17")) println(solution.part1()) //println(solution.part2()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
4,960
aoc-2022
Apache License 2.0
src/Day03.kt
Svikleren
572,637,234
false
{"Kotlin": 11180}
fun main() { fun charToValue(char: Char): Int { if (char > 64.toChar() && char < 91.toChar()) return char.code - 38 if (char > 96.toChar() && char < 123.toChar()) return char.code - 96 return 0 } fun part1(input: List<String>): Int { return input .map { bag -> bag.chunked(bag.length / 2) } .map { (compartment1, compartment2) -> compartment1.first { it in compartment2 } } .sumOf { charToValue(it) } } fun part2(input: List<String>): Int { return input .chunked(3) .map { (bag1, bag2, bag3) -> bag1.first { it in bag2 && it in bag3 } } .sumOf { charToValue(it) } } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e63be3f83b96a73543bf9bc00c22dc71b6aa0f57
793
advent-of-code-2022
Apache License 2.0
lib/src/main/kotlin/com/bloidonia/advent/day05/Day05.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day05 import com.bloidonia.advent.readList import java.awt.Color import java.awt.image.BufferedImage import java.io.File import java.lang.Math.abs import javax.imageio.ImageIO data class Point(val x: Int, val y: Int) { override fun toString(): String = "($x,$y)" } data class Vent(val start: Point, val end: Point) { fun notDiagonal() = start.x == end.x || start.y == end.y // bresenham line algorithm fun coveredPoints(): List<Point> { var d = 0 val result = mutableListOf<Point>() val dx = abs(start.x - end.x) val dy = abs(start.y - end.y) val dirX = if (start.x < end.x) 1 else -1 val dirY = if (start.y < end.y) 1 else -1 var x = start.x var y = start.y if (dx > dy) { while (true) { result.add(Point(x, y)) if (x == end.x) break x += dirX d += 2 * dy; if (d > dx) { y += dirY; d -= 2 * dy; } } } else { while (true) { result.add(Point(x, y)) if (y == end.y) break y += dirY d += 2 * dx; if (d > dy) { x += dirX; d -= 2 * dx; } } } return result } override fun toString(): String = "$start -> $end" } fun String.toPoint() = split(",", limit = 2).let { (x, y) -> Point(x.toInt(), y.toInt()) } fun String.toVent() = split(" -> ".toPattern(), limit = 2).let { (start, end) -> Vent(start.toPoint(), end.toPoint()) } fun coveragePart1(vents: List<Vent>): Int = coveragePart2(vents.filter { it.notDiagonal() }) fun coveragePart2(vents: List<Vent>): Int = vents.flatMap { it.coveredPoints() } .groupingBy { it } .eachCount() .filter { it.value > 1 } .count() fun drawForFun(vents: List<Vent>) { val points = vents.flatMap { listOf(it.start, it.end) } val maxX = points.maxOf { it.x } val maxY = points.maxOf { it.y } val buffer = BufferedImage(maxX + 1, maxY + 1, BufferedImage.TYPE_INT_ARGB) buffer.graphics.apply { color = Color.WHITE fillRect(0, 0, maxX + 1, maxY + 1) color = Color.BLACK vents.forEach { drawLine(it.start.x, it.start.y, it.end.x, it.end.y) } ImageIO.write(buffer, "png", File("/tmp/vents.png")) } } fun main() { println(coveragePart1(readList("/day05input.txt") { it.toVent() })) println(coveragePart2(readList("/day05input.txt") { it.toVent() })) drawForFun(readList("/day05input.txt") { it.toVent() }) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
2,736
advent-of-kotlin-2021
MIT License
2023/8/solve-2.kts
gugod
48,180,404
false
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
import java.io.File import kotlin.text.Regex fun lcmOf(a: Long, b: Long): Long { val larger = maxOf(a,b) val maxLcm = a * b var lcm = larger while (lcm <= maxLcm) { if (lcm % a == 0L && lcm % b == 0L) { return lcm } lcm += larger } return maxLcm } val lines = File(args.getOrNull(0) ?: "input").readLines() val navigation = lines[0].toCharArray() val network = lines.subList(2, lines.size) .fold(mutableMapOf<String,Pair<String,String>>()) { nw, line -> val nodes = Regex("[A-Z][A-Z][A-Z]").findAll(line).map { it.value.toString() }.toList() nw.apply { set(nodes[0], Pair(nodes[1], nodes[2])) } } var currentNodes = network.keys.filter { it.endsWith("A") } val rounds = currentNodes.map { var current = it var rounds = 0L var i = 0 while (!current.endsWith("Z")) { val c = navigation[i] val leftRight = network.getValue(current) current = when (c) { 'L' -> leftRight.first 'R' -> leftRight.second else -> throw IllegalStateException("Which way ?") } i = (i + 1) % navigation.size rounds++ } rounds } println(rounds.reduce { a,b -> lcmOf(a,b) })
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
1,242
advent-of-code
Creative Commons Zero v1.0 Universal
src/chapter2/problem4/solution1.kts
neelkamath
395,940,983
false
null
/* Question: Partition: Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions. EXAMPLE Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition=5] Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 Answer: Creating two linked lists. */ class LinkedListNode(var data: Int, var next: LinkedListNode? = null) { fun partition(value: Int): LinkedListNode { var lesserHead: LinkedListNode? = null var lesserTail: LinkedListNode? = null var notLesserHead: LinkedListNode? = null var notLesserTail: LinkedListNode? = null var node: LinkedListNode? = this while (node != null) { if (node.data < value) { if (lesserHead == null) { lesserHead = LinkedListNode(node.data) lesserTail = lesserHead } else { lesserTail!!.next = LinkedListNode(node.data) lesserTail = lesserTail.next } } else { if (notLesserHead == null) { notLesserHead = LinkedListNode(node.data) notLesserTail = notLesserHead } else { notLesserTail!!.next = LinkedListNode(node.data) notLesserTail = notLesserTail.next } } node = node.next } if (lesserTail != null) lesserTail.next = notLesserHead return lesserHead!! } override fun toString(): String { val builder = StringBuilder() var node: LinkedListNode? = this while (node != null) { if (!builder.isEmpty()) builder.append(" -> ") builder.append(node!!.data) node = node!!.next } builder.insert(0, "[") builder.append("]") return builder.toString() } } /** Throws an [IndexOutOfBoundsException] if the [Collection] has no elements. */ fun Collection<Int>.toLinkedList(): LinkedListNode { if (size == 0) throw IndexOutOfBoundsException() val head = LinkedListNode(first()) var node = head (1 until size).forEach { node.next = LinkedListNode(elementAt(it)) node = node.next!! } return head } with(listOf(3, 5, 8, 5, 10, 2, 1).toLinkedList()) { println("Input: $this\nOutput: ${partition(5)}") }
0
Kotlin
0
0
4421a061e5bf032368b3f7a4cee924e65b43f690
2,646
ctci-practice
MIT License
src/Day01.kt
strindberg
572,685,170
false
{"Kotlin": 15804}
import java.lang.Integer.max fun main() { fun part1(input: List<String>): Int = input.fold(Pair(0, 0)) { (max, total), line -> if (line.isEmpty()) Pair(max(total, max), 0) else Pair(max, total + line.toInt()) }.first fun part2(input: List<String>): Int = input.fold(Pair(listOf(0, 0, 0), 0)) { (maxThree, total), line -> if (line.isEmpty()) Pair((maxThree + total).sortedDescending().take(3), 0) else Pair(maxThree, total + line.toInt()) }.first.sum() val input = readInput("Day01") val part1 = part1(input) println(part1) check(part1 == 69693) val part2 = part2(input) println(part2) check(part2 == 200945) }
0
Kotlin
0
0
c5d26b5bdc320ca2aeb39eba8c776fcfc50ea6c8
843
aoc-2022
Apache License 2.0
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day2PasswordPhilosophy.kt
Scavi
68,294,098
false
{"Java": 1449516, "Kotlin": 59149}
package com.scavi.brainsqueeze.adventofcode class Day2PasswordPhilosophy { private val split = """(\d+)-(\d+) (.): (.*)""".toRegex() fun solveA(input: List<String>, policy: (rule: Rule) -> Boolean): Int { var validPasswords = 0 for (pwSetup in input) { val rule = parse(pwSetup) validPasswords = if (policy(rule)) validPasswords + 1 else validPasswords } return validPasswords } private fun parse(pwSetup: String): Rule { val (f, t, ch, pass) = split.find(pwSetup)!!.destructured return Rule(f.toInt(), t.toInt(), ch[0], pass) } fun oldPolicyRule(rule: Rule): Boolean { return rule.pass.filter { it == rule.ch }.count().let { it in rule.f..rule.t } } fun newPolicyRule(rule: Rule): Boolean { return (rule.pass.length >= rule.f && rule.pass[rule.f - 1] == rule.ch) xor (rule.pass.length >= rule.t && rule.pass[rule.t - 1] == rule.ch) } data class Rule(val f: Int, val t: Int, val ch: Char, val pass: String) }
0
Java
0
1
79550cb8ce504295f762e9439e806b1acfa057c9
1,059
BrainSqueeze
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/PalindromePartitioning4.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 /** * 1745. Palindrome Partitioning IV * @see <a href="https://leetcode.com/problems/palindrome-partitioning-iv/">Source</a> */ fun interface PalindromePartitioning4 { fun checkPartitioning(s: String): Boolean } class PalindromePartitioning4DP : PalindromePartitioning4 { override fun checkPartitioning(s: String): Boolean { val n = s.length val arr = s.toCharArray() val dp = Array(n) { BooleanArray( n, ) } for (i in n - 1 downTo 0) { for (j in i until n) { if (arr[i] == arr[j]) { dp[i][j] = if (i + 1 <= j - 1) { dp[i + 1][j - 1] } else { true } } else { dp[i][j] = false } } } // iterate every mid and then check: left, mid and right for (i in 1 until n - 1) { for (j in i until n - 1) { if (dp[0][i - 1] && dp[i][j] && dp[j + 1][n - 1]) { return true } } } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,836
kotlab
Apache License 2.0
src/main/kotlin/g2001_2100/s2054_two_best_non_overlapping_events/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2001_2100.s2054_two_best_non_overlapping_events // #Medium #Array #Dynamic_Programming #Sorting #Binary_Search #Heap_Priority_Queue // #2023_06_25_Time_851_ms_(100.00%)_Space_108.7_MB_(50.00%) import java.util.Arrays class Solution { fun maxTwoEvents(events: Array<IntArray>): Int { Arrays.sort(events) { a: IntArray, b: IntArray -> a[0] - b[0] } val max = IntArray(events.size) for (i in events.indices.reversed()) { if (i == events.size - 1) { max[i] = events[i][2] } else { max[i] = events[i][2].coerceAtLeast(max[i + 1]) } } var ans = 0 for (i in events.indices) { val end = events[i][1] var left = i + 1 var right = events.size while (left < right) { val mid = left + (right - left) / 2 if (events[mid][0] <= end) { left = mid + 1 } else { right = mid } } var value = events[i][2] if (right < events.size) { value += max[right] } ans = ans.coerceAtLeast(value) } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,263
LeetCode-in-Kotlin
MIT License
src/Day06_part2.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { fun part2(input: String): Int { val inArr = input.toCharArray() val map = mutableMapOf<Char, Int>() for (i in inArr.indices) { map[inArr[i]] = map.getOrDefault(inArr[i], 0) + 1 if (i - 14 >= 0) { map[inArr[i - 14]] = map.getOrDefault(inArr[i - 14], 0) - 1 } if (i >= 13 && !map.any { it.value > 1 }) { return i + 1 } } return 0 } val testInput = readInput("Day06_test") check(part2(testInput.first()) == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06") println(part2(input.first())) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
871
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/tasso/adventofcode/_2022/day02/Day02.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2022.day02 import dev.tasso.adventofcode.Solution class Day02 : Solution<Int> { private val outcomeValueMap = mapOf("loss" to 0, "draw" to 3, "win" to 6) private val shapeValueMap = mapOf("rock" to 1, "paper" to 2, "scissors" to 3) override fun part1(input: List<String>): Int { return input.sumOf { val opponentMove = decodeMove(it[0]) val yourMove = decodeMove(it[2]) val outcome = getOutcome(opponentMove, yourMove) val outcomeValue = outcomeValueMap[outcome]!! val shapeValue = shapeValueMap[yourMove]!! shapeValue + outcomeValue } } override fun part2(input: List<String>): Int { return input.sumOf { val opponentMove = decodeMove(it[0]) val expectedOutcome = decodeOutcome(it[2]) val yourMove = getExpectedMove(opponentMove, expectedOutcome) val outcomeValue = outcomeValueMap[expectedOutcome]!! val shapeValue = shapeValueMap[yourMove]!! shapeValue + outcomeValue } } private fun decodeMove(input: Char): String { return when (input) { 'A', 'X' -> "rock" 'B', 'Y' -> "paper" 'C', 'Z' -> "scissors" else -> throw IllegalArgumentException("Unexpected move encoding ($input)") } } private fun decodeOutcome(input: Char): String { return when (input) { 'X' -> "loss" 'Y' -> "draw" 'Z' -> "win" else -> throw IllegalArgumentException("Unexpected outcome encoding ($input)") } } private fun getOutcome(opponentMove: String, yourMove: String) : String { return when (opponentMove to yourMove) { "rock" to "paper", "paper" to "scissors", "scissors" to "rock" -> "win" "rock" to "rock", "paper" to "paper", "scissors" to "scissors" -> "draw" "rock" to "scissors", "paper" to "rock", "scissors" to "paper" -> "loss" else -> throw IllegalArgumentException("Unexpected input ($opponentMove, $yourMove)") } } private fun getExpectedMove(opponentMove: String, expectedOutcome: String) : String { return when (opponentMove to expectedOutcome) { "rock" to "loss", "paper" to "win", "scissors" to "draw" -> "scissors" "rock" to "draw", "paper" to "loss", "scissors" to "win" -> "rock" "rock" to "win", "paper" to "draw", "scissors" to "loss" -> "paper" else -> throw IllegalArgumentException("Unexpected input ($opponentMove, $expectedOutcome)") } } }
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
2,712
advent-of-code
MIT License
google/2019/round1_b/1/easy.kt
seirion
17,619,607
false
{"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294}
fun main(args: Array<String>) { val t = readLine()!!.toInt() repeat(t) { solve(it) } } fun solve(num: Int) { val (P, Q) = readLine()!!.split(" ").map { it.toInt() } val xValues = IntArray(Q + 2) { 0 } val yValues = IntArray(Q + 2) { 0 } repeat(P) { val (xx, yy, d) = readLine()!!.split(" ") val x = xx.toInt() val y = yy.toInt() when (d) { "W" -> put(xValues, 0, x) "E" -> put(xValues, x + 1, Q + 1) "S" -> put(yValues, 0, y) else -> put(yValues, y + 1, Q + 1) } } var best = 0 var bestX = 0 var bestY = 0 for (x in 0..Q) { for (y in 0..Q) { if (best < xValues[x] + yValues[y]) { best = xValues[x] + yValues[y] bestX = x bestY = y } } } println("Case #${num + 1}: $bestX $bestY") } fun put(array: IntArray, from:Int, to: Int) { (from until to).forEach { array[it]++ } }
0
C++
4
4
a59df98712c7eeceabc98f6535f7814d3a1c2c9f
1,022
code
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/welcometoprison/model/arrivals/search/SearchByNameAndPrisonNumber.kt
ministryofjustice
397,318,042
false
{"Kotlin": 442896, "Dockerfile": 1195}
package uk.gov.justice.digital.hmpps.welcometoprison.model.arrivals.search import uk.gov.justice.digital.hmpps.welcometoprison.model.arrivals.RecentArrival import uk.gov.justice.digital.hmpps.welcometoprison.model.arrivals.search.Searcher.Result import uk.gov.justice.digital.hmpps.welcometoprison.model.arrivals.search.Searcher.SearchStrategy import uk.gov.justice.digital.hmpps.welcometoprison.model.arrivals.search.Weights.Companion.CONSTANT import uk.gov.justice.digital.hmpps.welcometoprison.model.arrivals.search.Weights.Companion.EXACT_MATCH import uk.gov.justice.digital.hmpps.welcometoprison.model.arrivals.search.Weights.Companion.PARTIAL_MATCH class SearchByNameAndPrisonNumber : SearchStrategy<String, RecentArrival> { private val fuzzyScorer = FuzzyScorer() override fun evaluate(query: String, item: RecentArrival) = Result(item, calculateRelevance(query, item)) private fun calculateRelevance(query: String, item: RecentArrival): Int? { val fields = item.splitToFields() val terms = query.splitToTerms() return when { terms.isEmpty() -> CONSTANT else -> calculateRelevanceForTerms(terms, fields) } } private fun calculateRelevanceForTerms(terms: List<String>, fields: List<String>) = cartesianProduct(terms, fields) .map { (term, field) -> this.calculateRelevanceForField(term, field) } .filterNotNull() .reduceOrNull { total, relevance -> relevance + total } private fun calculateRelevanceForField(term: String, field: String): Int? = when { field == term -> EXACT_MATCH field.contains(term) -> PARTIAL_MATCH else -> fuzzyScorer.score(term, field) } } private fun String.splitToTerms() = this.trim().replace("[,.-]".toRegex(), " ").lowercase().split("\\s+".toRegex()).filter { it.isNotBlank() } private fun RecentArrival.splitToFields() = listOf(prisonNumber, firstName, lastName).map { it.trim().lowercase() } /** * Produces a list that contains every combination of elements in ts and us */ private fun <T, U> cartesianProduct(ts: List<T>, us: List<U>): List<Pair<T, U>> = ts.flatMap { t -> us.map { u -> t to u } }
0
Kotlin
0
0
d98ea95ba869e7d922dfe5c1323d8e3b95692ec3
2,115
hmpps-welcome-people-into-prison-api
MIT License
src/day5/second/Solution.kt
verwoerd
224,986,977
false
null
package day5.second import tools.boolToInt import tools.timeSolution fun main() = timeSolution { executeProgram(readLine()!!.split(",").map { it.toInt() }.toIntArray()) } fun executeProgram(code: IntArray): Int { var pointer = 0 loop@ while (true) { val current = code[pointer] val startPointer = pointer var mode3 = current / 10_000 % 10 val mode2 = current / 1_000 % 10 val mode1 = current / 100 % 10 val opcode = current % 100 when (opcode) { 1 -> setValue( code, getValue(code, code[pointer + 1], mode1) + getValue(code, code[pointer + 2], mode2), code[pointer + 3], 1 ) 2 -> setValue( code, getValue(code, code[pointer + 1], mode1) * getValue(code, code[pointer + 2], mode2), code[pointer + 3], 1 ) 3 -> setValue(code, readLine()!!.toInt(), code[pointer + 1], 1) 4 -> println(getValue(code, code[pointer + 1], mode1)) 5 -> if (getValue(code, code[pointer + 1], mode1) != 0) pointer = getValue(code, code[pointer + 2], mode2) 6 -> if (getValue(code, code[pointer + 1], mode1) == 0) pointer = getValue(code, code[pointer + 2], mode2) 7 -> setValue( code, boolToInt(getValue(code, code[pointer + 1], mode1) < getValue(code, code[pointer + 2], mode2)), code[pointer + 3], 1 ) 8 -> setValue( code, boolToInt(getValue(code, code[pointer + 1], mode1) == getValue(code, code[pointer + 2], mode2)), code[pointer + 3], 1 ) 99 -> break@loop else -> throw IllegalArgumentException("Invalid opcode ${code[pointer]}") } if (pointer == startPointer) { pointer += when (opcode) { in 1..2, in 7..8 -> 4 in 3..4 -> 2 in 5..6 -> 3 else -> throw IllegalArgumentException("Invalid step $opcode") } } } return code[0] } fun getValue(code: IntArray, value: Int, mode: Int): Int { return when (mode) { 0 -> code[value] 1 -> value else -> throw java.lang.IllegalArgumentException("Illegal parameter mode $mode") } } fun setValue(code: IntArray, value: Int, address: Int, mode: Int) { when (mode) { 0 -> code[code[address]] = value 1 -> code[address] = value } }
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
2,334
AoC2019
MIT License
src/Day11.kt
tbilou
572,829,933
false
{"Kotlin": 40925}
fun main() { val day = "Day11" // Hardcode input fun input(): List<Monkey> { var monkey0 = Monkey( ArrayDeque(listOf(89, 84, 88, 78, 70)), { a: Long -> a * 5 }, mapOf(true to 6, false to 7), 7 ) var monkey1 = Monkey( ArrayDeque(listOf(76, 62, 61, 54, 69, 60, 85)), { a: Long -> a + 1 }, mapOf(true to 0, false to 6), 17 ) var monkey2 = Monkey( ArrayDeque(listOf(83, 89, 53)), { a: Long -> a + 8 }, mapOf(true to 5, false to 3), 11 ) var monkey3 = Monkey( ArrayDeque(listOf(95, 94, 85, 57)), { a: Long -> a + 4 }, mapOf(true to 0, false to 1), 13 ) var monkey4 = Monkey( ArrayDeque(listOf(82, 98)), { a: Long -> a + 7 }, mapOf(true to 5, false to 2), 19 ) var monkey5 = Monkey( ArrayDeque(listOf(69)), { a: Long -> a + 2 }, mapOf(true to 1, false to 3), 2 ) var monkey6 = Monkey( ArrayDeque(listOf(82, 70, 58, 87, 59, 99, 92, 65)), { a: Long -> a * 11 }, mapOf(true to 7, false to 4), 5 ) var monkey7 = Monkey( ArrayDeque(listOf(91, 53, 96, 98, 68, 82)), { a: Long -> a * a }, mapOf(true to 4, false to 2), 3 ) return listOf(monkey0, monkey1, monkey2, monkey3, monkey4, monkey5, monkey6, monkey7) } fun testInput(): List<Monkey> { var monkey1 = Monkey( ArrayDeque(listOf(79, 98)), { a: Long -> a * 19 }, mapOf(true to 2, false to 3), 23 ) var monkey2 = Monkey( ArrayDeque(listOf(54, 65, 75, 74)), { a: Long -> a + 6 }, mapOf(true to 2, false to 0), 19 ) var monkey3 = Monkey( ArrayDeque(listOf(79, 60, 97)), { a: Long -> a * a }, mapOf(true to 1, false to 3), 13 ) var monkey4 = Monkey( ArrayDeque(listOf(74)), { a: Long -> a + 3 }, mapOf(true to 0, false to 1), 17 ) return listOf(monkey1, monkey2, monkey3, monkey4) } fun part1(input: List<Monkey>): Int { var rounds = 20 repeat(rounds) { input.forEach { monkey -> for (item in monkey.items) { monkey.inspected++ val worryLevel = monkey.operation.invoke(item) / 3 val nextMonkeyIndex = monkey.test.get(worryLevel % monkey.divisibleBy == 0L) input[nextMonkeyIndex!!].items.addLast(worryLevel) } monkey.items.clear() } } return input.map { monkey -> monkey.inspected } .sortedDescending() .take(2) .reduce(Int::times) } fun part2(input: List<Monkey>): Long { // MrSimbax in the subreddit: // Part 2 is basically part 1 but operations are done modulo N, where N is the product of all numbers from the input divisibility rules. // This works because if N = n * m then a % n == x implies (a % N) % n == x. // For completeness, this also holds for N = lcm(n, m), which may be smaller than n * m if the divisors are composite. // In the puzzle all divisors are primes though so lcm(n, m) == n * m. val magicNumber = input.map { it.divisibleBy }.reduce(Int::times) var rounds = 10_000 repeat(rounds) { input.forEach { monkey -> for (item in monkey.items) { monkey.inspected++ val worryLevel = monkey.operation.invoke(item) % magicNumber val nextMonkeyIndex = monkey.test.get(worryLevel % monkey.divisibleBy == 0L) input[nextMonkeyIndex!!].items.addLast(worryLevel) } monkey.items.clear() } } return input.map { monkey -> monkey.inspected.toLong() } .sortedDescending() .take(2) .reduce(Long::times) } // test if implementation meets criteria from the description, like: check(part1(testInput()) == 10605) check(part2(testInput()) == 2713310158) println(part1(input())) println(part2(input())) } data class Monkey( val items: ArrayDeque<Long>, val operation: (Long) -> Long, val test: Map<Boolean, Int>, var divisibleBy: Int, var inspected: Int = 0 )
0
Kotlin
0
0
de480bb94785492a27f020a9e56f9ccf89f648b7
4,759
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/arrays/FrequencyOfMaximumValue.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.arrays /** * Given an array ‘nums’ of length N containing positive integers * and an array ‘query’ of length ‘Q’ containing indexes, * print/store for each query the count of maximum value in the sub-array starting at index ‘i’ * and ending at index ‘N-1’. */ fun main() { frequencyOfMaxValue(arrayOf(5, 4, 5, 3, 2), arrayOf(1, 2, 3, 4, 5)) .forEach { print("$it ") } // 2, 1, 1, 1, 1 } // O(n + q) time | O(n) space private fun frequencyOfMaxValue(numbers: Array<Int>, q: Array<Int>): Array<Int> { val cnt = IntArray(numbers.size) { -1 } var max = -1 var counter = 1 for (i in numbers.size - 1 downTo 0) { if (numbers[i] == max) counter++ if (numbers[i] > max) { max = numbers[i] counter = 1 } cnt[i] = counter } return q.map { cnt[it - 1] }.toTypedArray() }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
929
algs4-leprosorium
MIT License
src/main/kotlin/com/nibado/projects/advent/y2020/Day19.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2020 import com.nibado.projects.advent.* object Day19 : Day { private val values = resourceStrings(2020, 19) private val rules1 = values.first().split("\n") .map { it.split(":").let { (id, rule) -> id.toInt() to rule.trim() } } .toMap() private val rules2 = rules1 + listOf(8 to "42 | 42 8", 11 to "42 31 | 42 11 31").toMap() private val lines = values[1].split("\n") override fun part1() = lines.count { isMatch(rules1, it, listOf(0)) } override fun part2() = lines.count { isMatch(rules2, it, listOf(0)) } private fun isMatch(ruleMap: Map<Int, String>, line: CharSequence, rules: List<Int>): Boolean { if (line.isEmpty()) { return rules.isEmpty() } else if (rules.isEmpty()) { return false } return ruleMap.getValue(rules[0]).let { rule -> if (rule[1] in 'a'..'z') { if (line.startsWith(rule[1])) { isMatch(ruleMap, line.drop(1), rules.drop(1)) } else false } else rule.split(" | ").any { isMatch(ruleMap, line, it.split(" ").map(String::toInt) + rules.drop(1)) } } } }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,236
adventofcode
MIT License
src/day24/Day24.kt
spyroid
433,555,350
false
null
package day24 import kotlinx.coroutines.runBlocking import readInput import kotlin.math.floor import kotlin.system.measureTimeMillis // Some thoughts about that // https://docs.google.com/spreadsheets/d/1eSizAHZFgb7XiQsDK7oG2U-f8c0M01F-c8K9nf68akg/edit?usp=sharing fun calc(ww: Int, zz: Int = 0, p1: Int = 0, p2: Int = 0, p3: Int = 0): Int { // var z = zz // var y = 0 // var x = 0 // mul x 0 // var x = zz // var x = (zz % 26) + p2 // param var z = zz / p1 // param // x += 10 // param // x = if (x == ww) 1 else 0 // x = if (x == 0) 1 else 0 val x = if ((zz % 26) + p2 == ww) 0 else 1 // var y = 0 val y = 26 + x // y += x // y += 1 z = z * y // y = (ww + p3) * x // y += w // y += 2 // param // y *= x z = z + ((ww + p3) * x) // println("w=$ww x=$x y=$y z=$z") return z } fun calc1(ww: Int, zz: Int = 0, p1: Int = 0, p2: Int = 0, p3: Int = 0) { var z = 0 // param val x = 1//if ((zz % 26) + 10 == ww) 0 else 1 // val y = 26 + 1 // z = z * y z = ww + 2 } fun calc5(ww: Int, zz: Int = 0, p1: Int = 0, p2: Int = 0, p3: Int = 0) { var z = zz / 26 // param val x = if ((zz % 26) - 8 == ww) 0 else 1 val y = 26 + x z = z * y z = z + ((ww + 1) * x) } val p1 = intArrayOf( 1, 1, 1, 1, 26, 1, 26, 26, 1, 26, 1, 26, 26, 26) val p2 = intArrayOf(10, 15, 14, 15, -8, 10, -16, -4, 11, -3, 12, -7, -15, -7) val p3 = intArrayOf( 2, 16, 9, 0, 1, 12, 6, 6, 3, 5, 9, 3, 2, 3) fun backwards(i: Int, zz: Int, skip: Set<Int>): Pair<Int, Int> { for (w in 9 downTo 1) for (z in 26 downTo 1) { var rz = calc(ww = w, zz = z, p1 = p1[i], p2 = p2[i], p3 = p3[i]) // println(rz) if (rz == zz && z !in skip) { return Pair(w, z) // println("$w $z") } } return Pair(0, 0) } fun backwardsAll(i: Int, zz: Int): List<Pair<Int, Int>> { val all = mutableListOf<Pair<Int, Int>>() for (w in 9 downTo 1) for (z in 26 downTo 1) { val rz = calc(ww = w, zz = z, p1 = p1[i], p2 = p2[i], p3 = p3[i]) if (rz == zz) all.add(Pair(w, z)) } return all } fun main(): Unit = runBlocking { fun part1(input: List<String>): Int { var zz = 0 var i = 13 val nums = ArrayDeque<Int>() fun deeper(i: Int, zz: Int): Boolean { if (i == 0) return true val all1 = backwardsAll(i, zz) for (a in all1) { println("Trying $i $a ") val all2 = backwardsAll(i - 1, a.second) if (all2.isNotEmpty()) { nums.addFirst(a.first) val res = deeper(i - 1, a.second) if (res) break } } nums.removeFirst() return false } deeper(13, 0) return 0 } fun part2(input: List<String>) = 0 // check(part1(readInput("day24/input")) == 1) measureTimeMillis { print("⭐️ Part1: ${part1(readInput("day24/test"))}") }.also { time -> println(" in $time ms") } // check(part2(4, 8) == 1) // measureTimeMillis { print("⭐️ Part2: ${part2(7, 1)}") }.also { time -> println(" in $time ms") } }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
3,214
Advent-of-Code-2021
Apache License 2.0
src/nativeMain/kotlin/Day9.kt
rubengees
576,436,006
false
{"Kotlin": 67428}
import kotlin.math.abs class Day9 : Day { private data class Point(val x: Int, val y: Int) { fun distanceTo(other: Point) = Distance(this.x - other.x, this.y - other.y) fun move(distance: Distance) = copy(x = x + distance.x, y = y + distance.y) fun moveBehind(other: Point): Point { val distance = other.distanceTo(this) return if (abs(distance.x) == 2 || abs(distance.y) == 2) { this.move(Distance(x = distance.x.coerceIn(-1..1), y = distance.y.coerceIn(-1..1))) } else { this } } } private data class Distance(val x: Int, val y: Int) private fun parseDirection(char: Char): Distance { return when (char) { 'L' -> Distance(x = -1, y = 0) 'R' -> Distance(x = 1, y = 0) 'U' -> Distance(x = 0, y = -1) 'D' -> Distance(x = 0, y = 1) else -> error("Unknown direction $char") } } override suspend fun part1(input: String): String { val visited = mutableSetOf(Point(0, 0)) var head = Point(x = 0, y = 0) var tail = Point(x = 0, y = 0) for (line in input.lines()) { val directionDistance = parseDirection(line[0]) val amount = line.substring(2).toInt() repeat(amount) { head = head.move(directionDistance) tail = tail.moveBehind(head) visited.add(tail) } } return visited.size.toString() } override suspend fun part2(input: String): String { val visited = mutableSetOf(Point(x = 0, y = 0)) var head = Point(x = 0, y = 0) val tails = (0 until 9).map { Point(x = 0, y = 0) }.toMutableList() for (line in input.lines()) { val directionDistance = parseDirection(line[0]) val amount = line.substring(2).toInt() repeat(amount) { head = head.move(directionDistance) for (i in 0 until tails.size) { tails[i] = tails[i].moveBehind(tails.getOrElse(i - 1) { head }) } visited.add(tails.last()) } } return visited.size.toString() } }
0
Kotlin
0
0
21f03a1c70d4273739d001dd5434f68e2cc2e6e6
2,282
advent-of-code-2022
MIT License
LeetCode/Nearest Exit from Entrance in Maze/main.kt
thedevelopersanjeev
112,687,950
false
null
import java.util.* class Solution { private fun isSafe(i: Int, j: Int, m: Int, n: Int): Boolean { return i >= 0 && j >= 0 && i < m && j < n } private fun isBoundary(i: Int, j: Int, m: Int, n: Int): Boolean { return i == 0 || j == 0 || i == m - 1 || j == n - 1 } fun nearestExit(maze: Array<CharArray>, entrance: IntArray): Int { val dx = listOf(0, 0, 1, -1) val dy = listOf(1, -1, 0, 0) val (m, n) = listOf(maze.size, maze[0].size) val visited = Array(m) { BooleanArray(n) { false } } val q: Queue<IntArray> = LinkedList() q.add(intArrayOf(entrance[0], entrance[1], 0)) visited[entrance[0]][entrance[1]] = true while (q.isNotEmpty()) { val curr = q.poll() for (k in 0 until 4) { val (nx, ny) = listOf(curr[0] + dx[k], curr[1] + dy[k]) if (!isSafe(nx, ny, m, n) || visited[nx][ny] || maze[nx][ny] == '+') { continue } if (isBoundary(nx, ny, m, n) && maze[nx][ny] == '.' && !visited[nx][ny]) { return curr[2] + 1 } if (maze[nx][ny] == '.' && !visited[nx][ny]) { visited[nx][ny] = true q.add(intArrayOf(nx, ny, curr[2] + 1)) } } } return -1 } }
0
C++
58
146
610520cc396fb13a03c606b5fb6739cfd68cc444
1,392
Competitive-Programming
MIT License
kotlin/704. Binary Search.kt
joaoreis
457,046,710
false
{"Kotlin": 19374}
import kotlin.math.floor class Solution { fun search(nums: IntArray, target: Int): Int { var initialIndex = 0 var endIndex = nums.size - 1 while (initialIndex <= endIndex) { val midIndex = (initialIndex + floor((endIndex - initialIndex) / 2f)).toInt() if (target == nums[midIndex]) return midIndex when { target > nums[midIndex] -> initialIndex = midIndex + 1 target < nums[midIndex] -> endIndex = midIndex - 1 } } return -1 } } class RecursiveSolution { fun search(nums: IntArray, target: Int): Int { return if (nums.isEmpty()) { -1 } else { bsearch(nums, target, 0, nums.size - 1) } } private fun bsearch(nums: IntArray, target: Int, left: Int, right: Int): Int { if (left <= right) { val midIndex = left + floor((right - left) / 2f).toInt() return when { target == nums[midIndex] -> midIndex target > nums[midIndex] -> bsearch(nums, target, midIndex + 1, right) else -> bsearch(nums, target, left, midIndex - 1) } } return -1 } }
0
Kotlin
0
0
d9fc04b95c8a6dc99fbf4bfcf9d36b05b16fa093
1,239
leetcode
MIT License
src/main/aoc2020/Day10.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2020 class Day10(input: List<String>) { private val differences = input.map { it.toInt() } .toMutableList() .apply { add(0); add(maxOrNull()!! + 3) } .sorted() .zipWithNext { a, b -> b - a } fun solvePart1(): Int { return differences.groupingBy { it } .eachCount() .values .reduce(Int::times) // There are only 1 and 3 differences in the input, multiply them } fun solvePart2(): Long { // Different variations only happen with at least two ones in a row, count the length of all sequences of one. var onesInARow = 0 val sequencesOfOnes = differences .map { if (it == 1) 0.also { onesInARow++ } else onesInARow.also { onesInARow = 0 } } .filter { it > 1 } // We're in luck, the input never has more than 4 ones in a row. We don't need any generic // formula for calculating the length, we can just count by hand how many possibilities // each sequence generate. Then we just multiply everything to get the total number of combinations. return sequencesOfOnes.map { when (it) { 2 -> 2L 3 -> 4L 4 -> 7L else -> error("unsupported amount: $it") } }.reduce(Long::times) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,391
aoc
MIT License
kotlin/src/2022/Day17_2022.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
import kotlin.math.* private typealias Shape = List<Pair<Int, Int>> private val Width = 7 fun main() { val d = readInput(17).trim().map {if (it == '<') -1 else 1} val b = mutableListOf<Array<Int>>() var ptr = -1 fun next(s: Shape): Shape { ptr += 1 // left-right movement var s1 = s.map {it.first to it.second + d[ptr % d.size]} if (s1.any {it.second < 0 || it.second >= Width || b[it.first][it.second] != 0}) s1 = s // downwards movement val s2 = s1.map {it.first - 1 to it.second} if (s2.any {it.first < 0 || b[it.first][it.second] != 0}) return s1 return s2 } fun simulate(s: Shape): Shape { var (prev, nxt) = s to next(s) // while the shape goes down, we simulate it while (prev[0].first != nxt[0].first) { prev = nxt.also {nxt = next(nxt)} } return nxt } fun height() = b.indexOfLast {it.any {x -> x != 0}} + 1 fun itemAt(idx: Long, y: Int): Shape = when (idx % 5) { 0L -> (2..5).map {y to it} 1L -> listOf(y to 3, y+1 to 2, y+1 to 3, y+1 to 4, y+2 to 3) 2L -> listOf(y to 2, y to 3, y to 4, y+1 to 4, y+2 to 4) 3L -> listOf(y to 2, y+1 to 2, y+2 to 2, y+3 to 2) 4L -> listOf(y to 2, y to 3, y+1 to 2, y+1 to 3) else -> throw IllegalArgumentException("This is impossible, but the compiler does not know :(") } // part1 for (i in 0 until 2022) { val h = height() val item = itemAt(i.toLong(), h + 3) // add new empty rows at the top, if needed repeat(max(0, item.maxOf {it.first} + 1 - h)) { b.add(Array(Width) {0}) } val xitem = simulate(item) for (pt in xitem) { b[pt.first][pt.second] = 1 } } println(height()) // part2 ptr = -1 b.clear() data class State(val iMod: Int, val ptr: Int, val history: List<Int>) // val states = mutableMapOf<State, Pair<Long, Int>>() var (i, add) = 0L to 0L var history = listOf<Int>() val M = 1000000000000L while (i < M) { val h = height() val item = itemAt(i, h + 3) // add new empty rows at the top, if needed repeat(max(0, item.maxOf {it.first} + 1 - h)) { b.add(Array(Width) {0}) } val xitem = simulate(item) val (dy, dx) = xitem[0].first - item[0].first to xitem[0].second - xitem[0].second if (history.size < 10) { history = history + listOf(dy, dx) } else if (add == 0L) { history = history.drop(2) + listOf(dy, dx) val state = State((i % 5).toInt(), ptr % d.size, history) // assume that if this state happened before, the events between will repeat periodically if (state in states) { val (iPrev, hPrev) = states[state]!! val period = i - iPrev add = (M - i) / period * (h - hPrev) i += period * ((M - i) / period) } else states[state] = i to h } for (pt in xitem) { b[pt.first][pt.second] = 1 } i += 1 } println(height() + add) }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
3,209
adventofcode
Apache License 2.0
src/Day10.kt
psabata
573,777,105
false
{"Kotlin": 19953}
fun main() { val testInput = Day10.Computer(InputHelper("Day10_test.txt").readLines()) check(testInput.part1() == 13140) check(testInput.part2() == 0) val input = Day10.Computer(InputHelper("Day10.txt").readLines()) println("Part 1: ${input.part1()}") println("Part 2: ${input.part2()}") } object Day10 { class Computer(input: List<String>) { private val operations: List<Operation> private val sampleTime = listOf(20, 60, 100, 140, 180, 220) private var x = 1 private var timer: Int = 0 private val signalStrengths: MutableList<Int> = mutableListOf() private val screen: Screen = Screen() init { operations = input.map { when { it.startsWith("noop") -> { Operation.Noop() } it.startsWith("addx") -> { Operation.Addx(it.split(' ')[1].toInt()) } else -> throw IllegalArgumentException(it) } } } fun part1(): Int { reset() return execute() } fun part2(): Int { reset() execute() screen.print() return 0 } private fun reset() { x = 1 timer = 0 signalStrengths.clear() screen.reset() } private fun execute(): Int { for (operation in operations) { for (tick in 1..operation.cycleTime) { timer++ if (sampleTime.contains(timer)) { signalStrengths.add(timer * x) } screen.draw(timer, x) } x += operation.execute() } return signalStrengths.sum() } } sealed class Operation(val cycleTime: Int) { open fun execute(): Int = 0 class Noop: Operation(1) class Addx(private val argument: Int) : Operation(2) { override fun execute(): Int { return argument } } } class Screen { private val screenWidth: Int = 40 private val screenHeight: Int = 6 private val pixels = Array(screenHeight) { CharArray(screenWidth) } fun reset() { pixels.forEach { it.fill('.') } } fun draw(timer: Int, sprite: Int) { val row = timer / screenWidth % screenHeight val column = (timer-1) % screenWidth val pixel = if (column in sprite - 1 .. sprite + 1) '#' else '.' // println("timer: $timer, row: $row, column: $column, sprite: $sprite, pixel: $pixel") if (pixel == '#') { pixels[row][column] = pixel } } fun print() { pixels.forEach { println(it) } } } }
0
Kotlin
0
0
c0d2c21c5feb4ba2aeda4f421cb7b34ba3d97936
2,991
advent-of-code-2022
Apache License 2.0
src/Day05.kt
casslabath
573,177,204
false
{"Kotlin": 27085}
fun main() { fun part1(input: List<String>): String { val stacks = mutableListOf( mutableListOf('R','S','L','F','Q'), mutableListOf('N','Z','Q','G','P','T'), mutableListOf('S','M','Q','B'), mutableListOf('T','G','Z','J','H','C','B','Q'), mutableListOf('P','H','M','B','N','F','S'), mutableListOf('P','C','Q','N','S','L','V','M'), mutableListOf('W','C','F'), mutableListOf('Q','H','G','Z','W','V','P','M'), mutableListOf('G','Z','D','L','C','N','R') ) input.map {line -> val (number, fromLoc, toLoc) = line .replace("move ", "") .replace("from ", "") .replace("to ", "") .split(" ") .map { it.toInt() } for(i in 1..number) { stacks[toLoc-1].add(stacks[fromLoc-1].removeLast()) } } var top = "" stacks.map { top += it.last() } return top } fun part2(input: List<String>): String { val stacks = mutableListOf( mutableListOf('R','S','L','F','Q'), mutableListOf('N','Z','Q','G','P','T'), mutableListOf('S','M','Q','B'), mutableListOf('T','G','Z','J','H','C','B','Q'), mutableListOf('P','H','M','B','N','F','S'), mutableListOf('P','C','Q','N','S','L','V','M'), mutableListOf('W','C','F'), mutableListOf('Q','H','G','Z','W','V','P','M'), mutableListOf('G','Z','D','L','C','N','R') ) input.map {line -> val (number, fromLoc, toLoc) = line .replace("move ", "") .replace("from ", "") .replace("to ", "") .split(" ") .map { it.toInt() } stacks[fromLoc-1].takeLast(number).map { stacks[toLoc-1].add(it) } for(i in 1..number) { stacks[fromLoc-1].removeLast() } } var top = "" stacks.map { top += it.last() } return top } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f7305e45f41a6893b6e12c8d92db7607723425e
2,227
KotlinAdvent2022
Apache License 2.0
src/main/aoc2015/Day17.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2015 class Day17(input: List<String>) { val parsedInput = input.map { it.toInt() } private fun fill(capacity: Int, emptyContainers: List<Int>, usedContainers: List<Int>, combinations: MutableList<List<Int>>) { if (capacity == 0) { combinations.add(usedContainers) return } val candidates = emptyContainers.filter { it <= capacity } if (candidates.isEmpty()) { return } val first = candidates.first() val rest = candidates.drop(1) // Either a container is used... fill(capacity - first, rest, usedContainers.toMutableList().apply { add(first) }, combinations) // ... or it's not used fill(capacity, rest, usedContainers, combinations) } private fun findAllCombinations(capacity: Int): MutableList<List<Int>> { val allCombinations = mutableListOf<List<Int>>() fill(capacity, parsedInput, listOf(), allCombinations) return allCombinations } fun solvePart1(totalCapacity: Int = 150): Int { return findAllCombinations(totalCapacity).size } fun solvePart2(totalCapacity: Int = 150): Int { val combinations = findAllCombinations(totalCapacity) val min = combinations.minByOrNull { it.size }!!.size return combinations.filter { it.size == min }.size } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,429
aoc
MIT License
src/leetcodeProblem/leetcode/editor/en/ReshapeTheMatrix.kt
faniabdullah
382,893,751
false
null
//In MATLAB, there is a handy function called reshape which can reshape an m x //n matrix into a new one with a different size r x c keeping its original data. // // You are given an m x n matrix mat and two integers r and c representing the //number of rows and the number of columns of the wanted reshaped matrix. // // The reshaped matrix should be filled with all the elements of the original //matrix in the same row-traversing order as they were. // // If the reshape operation with given parameters is possible and legal, output //the new reshaped matrix; Otherwise, output the original matrix. // // // Example 1: // // //Input: mat = [[1,2],[3,4]], r = 1, c = 4 //Output: [[1,2,3,4]] // // // Example 2: // // //Input: mat = [[1,2],[3,4]], r = 2, c = 4 //Output: [[1,2],[3,4]] // // // // Constraints: // // // m == mat.length // n == mat[i].length // 1 <= m, n <= 100 // -1000 <= mat[i][j] <= 1000 // 1 <= r, c <= 300 // // Related Topics Array Matrix Simulation 👍 1527 👎 168 package leetcodeProblem.leetcode.editor.en class ReshapeTheMatrix { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun matrixReshape(nums: Array<IntArray>, r: Int, c: Int): Array<IntArray> { val mutableList = mutableListOf<Int>() nums.forEach { intArray -> intArray.forEach { int -> mutableList.add(int) } } if (mutableList.count() != r * c) return nums val answer = Array(r) { IntArray(c) } var index = 0 for (row in 0 until r) { for (column in 0 until c) { answer[row][column] = mutableList[index] index++ } } return answer } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,054
dsa-kotlin
MIT License
src/main/kotlin/adventofcode/year2020/Day04PassportProcessing.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2020 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day04PassportProcessing(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val passports by lazy { input.split("\n\n").map { it.replace("\n", " ").split(" ") }.map(::Passport) } override fun partOne() = passports .count { !setOf(it.byr, it.iyr, it.eyr, it.hgt, it.hcl, it.ecl, it.pid).contains(null) } override fun partTwo() = passports .asSequence() .filter { !setOf(it.byr, it.iyr, it.eyr, it.hgt, it.hcl, it.ecl, it.pid).contains(null) } .filter { it.byr!!.toInt() in 1920..2002 } .filter { it.iyr!!.toInt() in 2010..2020 } .filter { it.eyr!!.toInt() in 2020..2030 } .filter { (it.hgt!!.endsWith("cm") && it.hgt.replace("cm", "").toInt() in 150..193) || (it.hgt.endsWith("in") && it.hgt.replace("in", "").toInt() in 59..76) } .filter { """#([0-9a-f]{6})""".toRegex().matches(it.hcl!!) } .filter { listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth").any { color -> it.ecl!! == color } } .filter { it.pid!!.toIntOrNull() != null && it.pid.length == 9 } .count() companion object { data class Passport( val byr: String?, val iyr: String?, val eyr: String?, val hgt: String?, val hcl: String?, val ecl: String?, val pid: String?, val cid: String? ) { constructor(fields: List<String>) : this( fields.find { it.startsWith("byr") }?.split(":")?.get(1), fields.find { it.startsWith("iyr") }?.split(":")?.get(1), fields.find { it.startsWith("eyr") }?.split(":")?.get(1), fields.find { it.startsWith("hgt") }?.split(":")?.get(1), fields.find { it.startsWith("hcl") }?.split(":")?.get(1), fields.find { it.startsWith("ecl") }?.split(":")?.get(1), fields.find { it.startsWith("pid") }?.split(":")?.get(1), fields.find { it.startsWith("cid") }?.split(":")?.get(1) ) } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,198
AdventOfCode
MIT License
src/main/kotlin/Puzzle22.kt
namyxc
317,466,668
false
null
object Puzzle22 { @JvmStatic fun main(args: Array<String>) { val input = Puzzle22::class.java.getResource("puzzle22.txt").readText() val decksNormalPlay = Decks(input) println(decksNormalPlay.calculateWinnerScoreNormalPlay()) val decksRecursivePlay = Decks(input) println(decksRecursivePlay.calculateWinnerScoreRecursivePlay()) } class Decks(input: String) { private val deck1: MutableList<Int> private val deck2: MutableList<Int> init { val decks = input.split("\n\n") deck1 = decks.first().split("\n").drop(1).map { it.toInt() }.toMutableList() deck2 = decks.last().split("\n").drop(1).map { it.toInt() }.toMutableList() } fun calculateWinnerScoreNormalPlay(): Int { playDecksNormal() val winnerDeck = if (deck1.isEmpty()) deck2 else deck1 return winnerDeck.reversed().mapIndexed { index, i -> i * (index+1) }.sum() } private fun playDecksNormal() { while (noEmptyDeck()){ val card1 = deck1.first() deck1.removeAt(0) val card2 = deck2.first() deck2.removeAt(0) if (card1 > card2){ deck1.add(card1) deck1.add(card2) }else{ deck2.add(card2) deck2.add(card1) } } } fun calculateWinnerScoreRecursivePlay(): Int { val previousConfigs = mutableSetOf<String>() while (noEmptyDeck()){ val key = deck1.joinToString(", ") + " | " + deck2.joinToString(", ") if (previousConfigs.contains(key)){ deck2.clear() } else { previousConfigs.add(key) playOneRound(deck1, deck2) } } val winnerDeck = if (deck1.isEmpty()) deck2 else deck1 return winnerDeck.reversed().mapIndexed { index, i -> i * (index+1) }.sum() } private fun getWinnerRecursive(subDeck1: MutableList<Int>, subDeck2: MutableList<Int>): Int { val previousConfigs = mutableSetOf<String>() while (subDeck1.isNotEmpty() && subDeck2.isNotEmpty()) { val key = subDeck1.joinToString(", ") + " | " + subDeck2.joinToString(", ") if (previousConfigs.contains(key)) { return 1 } else { previousConfigs.add(key) playOneRound(subDeck1, subDeck2) } } return if (subDeck1.isEmpty()) 2 else 1 } private fun playOneRound(subDeck1: MutableList<Int>, subDeck2: MutableList<Int> ) { val card1 = subDeck1.first() subDeck1.removeAt(0) val card2 = subDeck2.first() subDeck2.removeAt(0) val winner: Int = if (subDeck1.size >= card1 && subDeck2.size >= card2) { getWinnerRecursive(subDeck1.take(card1).toMutableList(), subDeck2.take(card2).toMutableList()) } else { if (card1 > card2) 1 else 2 } if (winner == 1) { subDeck1.add(card1) subDeck1.add(card2) } else { subDeck2.add(card2) subDeck2.add(card1) } } private fun noEmptyDeck() = deck1.isNotEmpty() && deck2.isNotEmpty() } }
0
Kotlin
0
0
60fa6991ac204de6a756456406e1f87c3784f0af
3,597
adventOfCode2020
MIT License
src/main/kotlin/pl/mrugacz95/aoc/day22/day22.kt
mrugacz95
317,354,321
false
null
package pl.mrugacz95.aoc.day22 fun <T : Comparable<T>> Iterable<T>.argmax(): Int? { return withIndex().maxByOrNull { it.value }?.index } const val withCaching = false // cache slow down execution val cache = mutableMapOf<Pair<Boolean, Int>, Pair<Int, List<Int>>>() const val debug = false fun log(message: String) { if (debug) { println(message) } } var games = 1 fun play( decks: List<List<Int>>, recursiveVersion: Boolean = false, parentGame: Int? = null ): Pair<Int, List<Int>> { val game = games++ if (withCaching) cache[Pair(recursiveVersion, decks.hashCode())]?.let { log("Cache hit, gameplay skipped") log("The winner of game $game is player ${it.first + 1}!\n") log("...anyway, back to game ${parentGame}.") return it } val gameStates = mutableSetOf<Int>() val cards = decks.map { it.toMutableList() } var roundNumber = 1 log("=== Game $game ===") while (!cards.any { it.isEmpty() }) { log("\n-- Round $roundNumber (Game $game) --") if (cards.hashCode() in gameStates) return Pair(0, cards[0]) gameStates.add(cards.hashCode()) log("Player 1's deck: ${cards[0].joinToString(", ")}") log("Player 2's deck: ${cards[1].joinToString(", ")}") val desk = cards.map { it.removeAt(0) } log("Player 1 plays: ${desk[0]}") log("Player 2 plays: ${desk[1]}") val wins = if (!recursiveVersion) { desk.argmax() ?: throw RuntimeException("No winner found") } else { when { desk.zip(cards).all { it.first <= it.second.size } -> { log("Playing a sub-game to determine the winner...\n") val newDecks = cards.zip(desk).map { it.first.take(it.second) }.toMutableList() val (winner, _) = play(newDecks, true, game) winner } else -> { desk.argmax() ?: throw RuntimeException("No winner found") } } } log("Player ${wins + 1} wins round $roundNumber of game $game!") roundNumber += 1 cards[wins].addAll( if (wins == 0) { desk } else { desk.reversed() } ) } val winner = cards.withIndex().first { it.value.isNotEmpty() }.index log("The winner of game $game is player ${winner + 1}!\n") if (parentGame != null) log("...anyway, back to game $parentGame.") val result = Pair(winner, cards[winner]) if (withCaching) { cache[Pair(recursiveVersion, decks.hashCode())] = result } return result } fun calculatePlayerScore(cards: List<Int>): Int { return cards.reversed().withIndex().map { it.value * (it.index + 1) }.sum() } fun main() { val decks = {}::class.java.getResource("/day22.in") .readText() .split("\n\n") .map { deck -> deck.split("\n").drop(1).map { it.toInt() } } println("Answer part 1: ${calculatePlayerScore(play(decks).second)}") println("Answer part 2: ${calculatePlayerScore(play(decks, true).second)}") }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
3,271
advent-of-code-2020
Do What The F*ck You Want To Public License
src/objects/Functions.kt
davidassigbi
334,302,078
false
null
package objects import classes.Func import kotlin.math.atan import kotlin.math.cos import kotlin.math.pow import kotlin.math.tan object Functions { /* x.pow(3) + 3* x.pow(2) + 3*x+1 2 * tan(x) - 1 */ val f = Func({ x, _ -> atan((x + 1) / 2) - x }, "x * x - 2 * x + 1") val g = Func({ x, _ -> f(x) - x }, "$f - x") val fx = Func({ x, _ -> x - f(x) }, "x - $f") /* * 2 * x - 2 * */ val df = Func({ x, _ -> - 1 + (0.5) / ( 1 + ((x + 1)/2).pow(2) ) }, "2 * x - 2") val fi = Func({ x, _ -> x - f(x) / df(x) }, "x - f(x) / df(x)") val dfApproximative = Func({ xn, xnMoins1 -> (f(xn) - f(xnMoins1)) / (xn - xnMoins1) }, "(f(x1) - f(x0)) / (x1 - x0)") val fiApproximativeBiss = Func({ xn, xnMoins1 -> xn - f(xn) / dfApproximative(xn, xnMoins1) }, "x1 - f(x1) / df(x1 , x0)") val fiApproximativeDenominator = Func({ xn, xnMoins1 -> f(xn) - f(xnMoins1) }, "f(xn) - f(xn-1)") val fiApproximative = Func({ xn, xnMoins1 -> (f(xn) * xnMoins1 - f(xnMoins1) * xn) / (fiApproximativeDenominator(xn, xnMoins1)) }, "( f(xn)*xn-1 - f(xn-1)*xn ) / ( df(xn,xn-1))") val yPrime = Func({t: Double, y: Double -> t * cos(y) },"t * cos(y)") val integrationFunction = Func({ x, _ -> x * x * x},"x^3") fun computeFrom(x: Double, coefList: List<Double>, reversed: Boolean = false): Double { var result = .0 val coefs = if(reversed) coefList.reversed() else coefList for(i in 0 until coefs.size) result += coefs[i].pow(i) return result } fun computeFractionalFunction(x: Double, numeratorCoefList: List<Double>,denominatorCoefList: List<Double>): Double { var result = .0 var numeratorValue = 1.0 var denominatorValue = 1.0 for(coef in numeratorCoefList) numeratorValue *= (x + coef) for(coef in denominatorCoefList) denominatorValue *= (x + coef) if(denominatorValue != .0) result = numeratorValue / denominatorValue return result } }
0
Kotlin
0
1
3ed410b4bc72465f8fcb5e753a6a69eb44bb0d36
2,050
numerical-solver
Apache License 2.0
src/main/kotlin/extensions/sequences/Middle.kt
swantescholz
102,711,230
false
null
package extensions.sequences import util.astTrue import java.util.* fun <T> Sequence<T>.concat(you: Sequence<T>): Sequence<T> { return AppendSequence<T>(this, you) } fun <T> Sequence<T>.append(vararg elements: T): Sequence<T> = this.concat(elements.asSequence()) fun <T> Sequence<T>.prepend(vararg elements: T): Sequence<T> = elements.asSequence().concat(this) fun <T> Sequence<T?>.takeUntilNull(): Sequence<T> { return takeWhile { it != null }.map { it!! } } inline fun <A, B> Sequence<A>.foldMap(initial: B, crossinline operation: (B, A) -> B): Sequence<B> { var current = initial return this.map { current = operation(current, it) return@map current } } inline fun <T> Sequence<T>.peek(crossinline f: (T) -> Unit) = this.map { f(it); it } fun <T> Sequence<T>.withIndex1(): Sequence<IndexedValue<T>> { return this.withIndex().map { IndexedValue(it.index + 1, it.value) } } inline fun <A, B : Comparable<B>> Sequence<A>.takeNSmallestBy(n: Int, transform: (A) -> B): Sequence<A> { val maxpq = PriorityQueue<Pair<A, B>>(n, { a: Pair<A, B>?, b: Pair<A, B>? -> var res = 0 if (a != null && b != null) { res = -a.second.compareTo(b.second) } res }) val iter = this.iterator() (1..n).forEach { if (!iter.hasNext()) throw IllegalArgumentException("not $n elements in sequence") val x = iter.next() val elem = Pair(x, transform(x)) maxpq.offer(elem) } while (iter.hasNext()) { val x = iter.next() val y = transform(x) if (maxpq.peek().second.compareTo(y) > 0) { maxpq.remove() maxpq.offer(Pair(x, y)) } } val ll = LinkedList<A>() while (!maxpq.isEmpty()) { ll.addFirst(maxpq.remove().first) } return ll.asSequence() } //drops all elements that are not uniquely only once in the sequence fun <T> Sequence<T>.filterUnique(): Sequence<T> { return this.groupBy { it }.asSequence().filter { it.value.size == 1 }.map { it.key } } fun <T> Sequence<T>.intertwine(you: Sequence<T>): Sequence<T> { return this.zip(you, { a, b -> sequenceOf(a, b) }).flatten() } fun <T, K, V> Sequence<T>.groupByWith(entryMapping: (T) -> Pair<K, V>): Map<K, List<V>> { return this.groupByToWith(entryMapping, LinkedHashMap<K, MutableList<V>>()) } fun <T, K, V> Sequence<T>.groupByToWith(entryMapping: (T) -> Pair<K, V>, destinationMap: MutableMap<K, MutableList<V>>): Map<K, MutableList<V>> { this.forEach { element -> val entry = entryMapping(element) if (entry.first !in destinationMap) destinationMap.put(entry.first, ArrayList<V>()) destinationMap[entry.first]?.add(entry.second) } return destinationMap } fun <T> Sequence<T>.cutIntoSegments(segmentLength: Int): Sequence<ArrayList<T>> { astTrue(segmentLength > 0) var list = ArrayList<T>() return this.map { list.add(it) if (list.size == segmentLength) { val res = list list = ArrayList<T>() return@map res } return@map null }.filterNotNull() }
0
Kotlin
0
0
20736acc7e6a004c29c328a923d058f85d29de91
2,919
ai
Do What The F*ck You Want To Public License
src/com/kingsleyadio/adventofcode/y2022/day10/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2022.day10 import com.kingsleyadio.adventofcode.util.readInput fun main() { part1() part2() } fun part1() { var cycle = 0 var value = 1 var signalSums = 0 fun checksum() { val interestingCycles = setOf(20, 60, 100, 140, 180, 220) if (cycle in interestingCycles) signalSums += cycle * value } readInput(2022, 10).forEachLine { line -> val split = line.split(" ") cycle++ checksum() if (split[0] == "addx") { cycle++ value += split[1].toInt() checksum() } } println(signalSums) } fun part2() { var cycle = 0 var value = 1 val crt = Array(6) { CharArray(40) } fun display() { val index = cycle - 1 val y = index / 40 val x = index % 40 crt[y][x] = if (x in value - 1..value + 1) '#' else ' ' } readInput(2022, 10).forEachLine { line -> val split = line.split(" ") cycle++ display() if (split[0] == "addx") { cycle++ display() value += split[1].toInt() } } crt.forEach { println(String(it)) } }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,206
adventofcode
Apache License 2.0
src/day5/fr/Day05_1.kt
BrunoKrantzy
433,844,189
false
{"Kotlin": 63580}
package day5.fr import java.io.File fun readInputInt(name: String) = File("src", "$name.txt").readLines() fun main() { val testInput = day2.fr.readInputInt("input5") val regex = "^(\\d+),(\\d+)\\s->\\s(\\d+),(\\d+)".toRegex() var x1 = 0 var x2 = 0 var y1 = 0 var y2 = 0 var maxX = 0 var maxY = 0 var lstH = mutableListOf<Triple<Int, Int, Int>>() var lstV = mutableListOf<Triple<Int, Int, Int>>() testInput.forEach { val match = regex.find(it) x1 = match!!.groups[1]!!.value.toInt() y1 = match.groups[2]!!.value.toInt() x2 = match.groups[3]!!.value.toInt() y2 = match.groups[4]!!.value.toInt() maxX = maxOf(maxX, x1) maxX = maxOf(maxX, x2) maxY = maxOf(maxY, y1) maxY = maxOf(maxY, y2) if (x1 == x2) { val yy1 = minOf(y1, y2) val yy2 = maxOf(y1, y2) val v = Triple(x1, yy1, yy2) lstV.add(v) } else if (y1 == y2) { val xx1 = minOf(x1, x2) val xx2 = maxOf(x1, x2) val h = Triple(y1, xx1, xx2) lstH.add(h) } } var tabVents = Array (maxY+1) { Array(maxX+1) { 0 } } lstH.forEach { for (i in it.second ..it.third) { tabVents[it.first][i]++ } } lstV.forEach { for (i in it.second ..it.third) { tabVents[i][it.first]++ } } var rep = 0 tabVents.forEach { it.forEach { it2 -> if (it2 > 1) rep++ } } println(rep) }
0
Kotlin
0
0
0d460afc81fddb9875e6634ee08165e63c76cf3a
1,607
Advent-of-Code-2021
Apache License 2.0
scripts/Day11.kts
matthewm101
573,325,687
false
{"Kotlin": 63435}
import java.io.File data class Monkey(val items: MutableList<Long>, val op: (Long) -> Long, val divisor: Long, val trueTarget: Int, val falseTarget: Int, var inspects: Long) val lines = File("../inputs/11.txt").readLines() run { val monkeys = (lines.indices step 7).map { i -> val items = lines[i + 1].drop(18).split(", ").map { it.toLong() }.toMutableList() val op = if (lines[i + 2][23] == '*') { if (lines[i + 2].drop(25) == "old") { x: Long -> x * x } else { x: Long -> x * lines[i + 2].drop(25).toLong() } } else if (lines[i + 2][23] == '+') { if (lines[i + 2].drop(25) == "old") { x: Long -> x + x } else { x: Long -> x + lines[i + 2].drop(25).toLong() } } else { throw Exception("Unhandled operation: ${lines[i + 2].drop(13)}") } val divisor = lines[i + 3].drop(21).toLong() val trueTarget = lines[i + 4].drop(29).toInt() val falseTarget = lines[i + 5].drop(30).toInt() Monkey(items, op, divisor, trueTarget, falseTarget, 0) } for (round in 1..20) { monkeys.forEach { monkey -> monkey.items.forEach { item -> val newItem = monkey.op(item) / 3 if (newItem % monkey.divisor == 0L) monkeys[monkey.trueTarget].items += newItem else monkeys[monkey.falseTarget].items += newItem monkey.inspects++ } monkey.items.clear() } } val monkeyBusiness = monkeys.sortedBy { it.inspects }.drop(monkeys.size - 2).fold(1L) { acc, monkey -> acc * monkey.inspects } println("The monkey business after 20 rounds (with worry) is $monkeyBusiness.") } run { val monkeys = (lines.indices step 7).map { i -> val items = lines[i + 1].drop(18).split(", ").map { it.toLong() }.toMutableList() val op = if (lines[i + 2][23] == '*') { if (lines[i + 2].drop(25) == "old") { x: Long -> x * x } else { x: Long -> x * lines[i + 2].drop(25).toLong() } } else if (lines[i + 2][23] == '+') { if (lines[i + 2].drop(25) == "old") { x: Long -> x + x } else { x: Long -> x + lines[i + 2].drop(25).toLong() } } else { throw Exception("Unhandled operation: ${lines[i + 2].drop(13)}") } val divisor = lines[i + 3].drop(21).toLong() val trueTarget = lines[i + 4].drop(29).toInt() val falseTarget = lines[i + 5].drop(30).toInt() Monkey(items, op, divisor, trueTarget, falseTarget, 0) } val lcm = monkeys.map { it.divisor }.reduce { acc, i -> acc * i } for (round in 1..10000) { monkeys.forEach { monkey -> monkey.items.forEach { item -> val newItem = monkey.op(item % lcm) if (newItem % monkey.divisor == 0L) monkeys[monkey.trueTarget].items += newItem else monkeys[monkey.falseTarget].items += newItem monkey.inspects++ } monkey.items.clear() } } val monkeyBusiness = monkeys.sortedBy { it.inspects }.drop(monkeys.size - 2).fold(1L) { acc, monkey -> acc * monkey.inspects } println("The monkey business after 10000 rounds (without worry) is $monkeyBusiness.") }
0
Kotlin
0
0
bbd3cf6868936a9ee03c6783d8b2d02a08fbce85
3,370
adventofcode2022
MIT License
Number Base Converter/task/src/converter/Main.kt
jwgibanez
399,542,486
false
{"Java": 42892, "HTML": 14987, "Kotlin": 3698}
package converter import java.math.BigDecimal import java.math.BigInteger import java.util.* import kotlin.math.pow fun main() { val scanner = Scanner(System.`in`) while (true) { print("Enter two numbers in format: {source base} {target base} (To quit type /exit) ") when (val input1 = scanner.nextLine()) { "/exit" -> return else -> { val split = input1.split(" ") val sourceBase = split[0].toBigInteger() val targetBase = split[1].toBigInteger() loop@ while (true) { print("Enter number in base $sourceBase to convert to base $targetBase (To go back type /back) ") when(val input2 = scanner.nextLine()) { "/back" -> break@loop else -> { val decimal: BigDecimal = if (sourceBase != BigInteger.TEN) converter(input2, sourceBase).toBigDecimal() else input2.toBigDecimal() val target = if (targetBase == BigInteger.TEN) decimal else converter(decimal, targetBase, input2.contains(".")) println("Conversion result: $target\n") } } } } } } } fun converter(source: String, sourceBase: BigInteger): String { var sum = BigDecimal.ZERO val integer: String val fraction: String if (source.contains(".")) { val split = source.split(".") integer = split[0] fraction = split[1] } else { integer = source fraction = "" } // Integer part val reversed = integer.reversed() for (i in reversed.indices) { sum += if (reversed[i].isDigit()) reversed[i].toString().toBigDecimal() * sourceBase.toBigDecimal().pow(i) else (10 + reversed[i].code - 'a'.code).toBigDecimal() * sourceBase.toBigDecimal().pow(i) } // Fractional part val sourceBaseDecimal = sourceBase.toDouble() var fractionSum = 0.0 for (i in fraction.indices) { fractionSum += if (fraction[i].isDigit()) fraction[i].toString().toDouble() / sourceBaseDecimal.pow(i + 1) else (10 + fraction[i].code - 'a'.code).toDouble() / sourceBaseDecimal.pow(i + 1) } return (sum + fractionSum.toBigDecimal()).toString() } fun converter(base10: BigDecimal, target: BigInteger, contains: Boolean) : String { var resultInteger = "" var resultFraction = "" val split = base10.toString().split(".") val integer = split[0].toBigInteger() // Integer part var remaining = integer while (remaining >= target) { resultInteger += convert((remaining % target).toInt()) remaining /= target } resultInteger += convert(remaining.toInt()) // Fraction part var ctr = 0 var fraction = base10 - integer.toBigDecimal() if (contains) println(fraction) while (fraction > BigDecimal.ZERO) { if (ctr == 10) break val remainingDecimal = fraction * target.toBigDecimal() fraction = remainingDecimal - remainingDecimal.toInt().toBigDecimal() resultFraction += convert(remainingDecimal.toInt()) ctr++ } while (contains && resultFraction.length < 5) { // padding resultFraction += 0 } return if (!contains) resultInteger.reversed() else resultInteger.reversed() + if (resultFraction.isNotEmpty()) ".${resultFraction.substring(0, 5)}" else ".00000" } fun convert(value: Int): String { return if (value < 10) value.toString() else ('a'.code + (value-10)).toChar().toString() }
0
Java
0
0
ea76a3c8b709c388873515f50c3051e2c81ad070
3,698
kotlin-number-base-converter
Apache License 2.0
src/main/kotlin/days/Day07.kt
TheMrMilchmann
571,779,671
false
{"Kotlin": 56525}
/* * Copyright (c) 2022 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package days import utils.* fun main() { val data = readInput() val root = Directory("/", parent = null) var workingDir = root for (line in data) { if (line.startsWith("$")) { val segments = line.removePrefix("$ ").split(' ') val command = segments.first() when (command) { "cd" -> workingDir = workingDir.resolve(segments[1]) "ls" -> {} // Ignore else -> error("Unknown command: $command") } } else { if (line.startsWith("dir")) { val name = line.removePrefix("dir ").trim() workingDir.createDirectory(name) } else { val (size, name) = line.split(' ') workingDir.createFile(name, size.toLong()) } } } // println(root.printToString()) fun part1(): Long = root.directorySequence().sumOf { if (it.size <= 100000) it.size else 0 } fun part2(): Long { val TOTAL_SPACE = 70_000_000L val MIN_UNUSED_SPACE = 30_000_000L // Just assumes that we have to delete stuff val minSizeToDelete = MIN_UNUSED_SPACE - (TOTAL_SPACE - root.size) return root.directorySequence().filter { it.size >= minSizeToDelete }.minOf { it.size } } println("Part 1: ${part1()}") println("Part 2: ${part2()}") } private fun Directory.printToString(): String = buildString { appendLine("- $name (dir)") val children = children.values.joinToString(separator = "\n") { when (it) { is Directory -> it.printToString() is File -> "- ${it.name} (file, size=${it.size})" } } append(children.prependIndent(" ")) } private sealed class Node { abstract val name: String abstract val size: Long abstract fun nodeSequence(): Sequence<Node> } private data class Directory( override val name: String, private val parent: Directory? ) : Node() { val children = mutableMapOf<String, Node>() private val root: Directory get() { var res = this while (res.parent != null) res = res.parent!! return res } override val size by lazy(LazyThreadSafetyMode.NONE) { children.values.sumOf(Node::size) } fun createDirectory(name: String): Directory { check(name !in children) { name } return Directory(name, parent = this).also { children[name] = it } } fun createFile(name: String, size: Long): File { check(name !in children) return File(name, size).also { children[name] = it } } override fun nodeSequence(): Sequence<Node> = sequence { yield(this@Directory) children.forEach { (_, node) -> yieldAll(node.nodeSequence()) } } fun directorySequence(): Sequence<Directory> = nodeSequence().filterIsInstance<Directory>() fun resolve(path: String): Directory = when (path) { ".." -> parent ?: error("Cannot resolve parent of root") "/" -> root else -> children.values.filterIsInstance<Directory>().find { it.name == path } ?: createDirectory(name) } } private data class File( override val name: String, override val size: Long ) : Node() { override fun nodeSequence(): Sequence<Node> = sequenceOf(this) }
0
Kotlin
0
1
2e01ab62e44d965a626198127699720563ed934b
4,444
AdventOfCode2022
MIT License
src/graphs/weighted/Main.kt
ArtemBotnev
136,745,749
false
{"Kotlin": 79256, "Shell": 292}
package graphs.weighted import utils.Timer private const val GRAPH_MAX_SIZE = 10 private const val INFINITY = 10_000L fun main() { undirectedWeightedMST() directedWeightedShortest() } private fun undirectedWeightedMST() { val graph = UndirectedWeightedGraph<Char>(GRAPH_MAX_SIZE, INFINITY).apply { addVertex('A') addVertex('B') addVertex('C') addVertex('D') addVertex('E') addVertex('F') addVertex('J') addEdge('A', 'B', 2) addEdge('A', 'C', 8) addEdge('B', 'D', 5) addEdge('C', 'E', 9) addEdge('C', 'E', 9) addEdge('B', 'J', 10_001) addEdge('D', 'J', 4) addEdge('C', 'J', 1) addEdge('E', 'J', 7) addEdge('D', 'E', 1) addEdge('D', 'F', 5) addEdge('C', 'F', 6) } println() println("Graph with vertices: $graph") println("Minimum Spanning Tree of weighted graph") val timer = Timer().apply { start() } graph.mstw {from, to, weight -> println("$from-($weight)-$to") } println(timer.stopAndShowTime()) println() } private fun directedWeightedShortest() { val vertices = arrayOf('A', 'B', 'C', 'D', 'E', 'F', 'J') val graph = DirectedWeightedGraph<Char>(GRAPH_MAX_SIZE, INFINITY).apply { vertices.forEach { addVertex(it) } addEdge('A', 'B', 8) addEdge('A', 'J', 1) addEdge('B', 'E', 5) addEdge('C', 'A', 3) addEdge('C', 'J', 10) addEdge('D', 'B', 4) addEdge('E', 'C', 3) addEdge('E', 'F', 6) addEdge('F', 'A', 7) addEdge('F', 'D', 3) addEdge('J', 'D', 2) } println("Directed weighted graph with vertices: $graph") println("Shortest paths:") println() val timer = Timer() vertices.forEach { findShortestPathsFrom(graph, it, timer) } } private fun <T> findShortestPathsFrom(graph: DirectedWeightedGraph<T>, vertex: T, timer: Timer) { println("shortest paths from vertex $vertex:") timer.start() val paths = graph.shortestPath(vertex) paths?.run { forEach { pair -> println("path: ${pair.first.joinToString("->")} sum: ${pair.second}") } } ?: println("There are some unreachable vertices in the graph") println(timer.stopAndShowTime()) println() }
0
Kotlin
0
0
530c02e5d769ab0a49e7c3a66647dd286e18eb9d
2,345
Algorithms-and-Data-Structures
MIT License
kotlin/src/interview/最长回文子串.kt
yunshuipiao
179,794,004
false
null
package interview //abcdcbe, 比如bcdcb就是结果 //中心法 fun longestPalindrome(s: String): String { //求位置l为中心的最长回文子串的开始位置和长度 fun expandAroundCenter(s: String, l: Int, r: Int, result: IntArray) { val len = s.length - 1 var left = l var right = r while (left >= 0 && right <= len && s[left] == s[right]) { left += 1 right -= 1 } result[0] = left + 1 result[1] = right - left - 1 } if (s.isBlank()) { return s } var longestBegin = 0 var longestLen = 0 val result = intArrayOf(0, 0) s.forEachIndexed { index, c -> //以位置i为中心的最长回文子串 expandAroundCenter(s, index, index, result) if (result[1] > longestLen) { longestBegin = result[0] longestLen = result[1] } // 以位置i,i+1 为中心的最长回文子串 expandAroundCenter(s, index, index + 1, result) if (result[1] > longestLen) { longestBegin = result[0] longestLen = result[1] } } return s.substring(result[0], result[1]) }
29
Kotlin
0
2
6b188a8eb36e9930884c5fa310517be0db7f8922
1,203
rice-noodles
Apache License 2.0
src/main/kotlin/days/Day21.kt
TheMrMilchmann
433,608,462
false
{"Kotlin": 94737}
/* * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package days import utils.* fun main() { val pattern = """Player (\d+) starting position: (\d+)""".toRegex() val players = readInput().map { line -> val (_, pos) = pattern.matchEntire(line)?.destructured ?: error("Could not parse $line") pos.toInt() } fun part1(): Int { val positions = players.mapTo(mutableListOf()) { it } val scores = players.mapTo(mutableListOf()) { 0 } var roll = 0 outer@while (true) { for (player in players.indices) { var advance = 0 for (i in 0..2) advance += ((++roll - 1) % 100) + 1 positions[player] = ((positions[player] + advance - 1) % 10) + 1 scores[player] = scores[player] + positions[player] if (scores[player] >= 1000) break@outer } } return scores.minOf { it } * roll } fun part2(): Long { data class State( val curPos: Int, val curScore: Int, val nxtPos: Int, val nxtScore: Int, val roll: Int ) data class Result(val p1Wins: Long, val p2Wins: Long) val rolls = listOf(1, 2, 3).let { sides -> sides.flatMap { first -> sides.flatMap { second -> sides.map { third -> first + second + third } } } } val cache = mutableMapOf<State, Result>() fun State.process(): Result = when { curScore >= 21 || nxtScore >= 21 -> { if (roll % 2 == 0 && curScore <= nxtScore) Result(p1Wins = 1, p2Wins = 0) else Result(p1Wins = 0, p2Wins = 1) } else -> cache.getOrPut(this) { rolls.map { advance -> val newPos = ((curPos + advance - 1) % 10) + 1 State( curPos = nxtPos, curScore = nxtScore, nxtPos = newPos, nxtScore = curScore + newPos, roll = roll + 1 ) }.map(State::process) .reduce { acc, e -> Result(acc.p1Wins + e.p1Wins, acc.p2Wins + e.p2Wins) } } } return State( curPos = players[0], curScore = 0, nxtPos = players[1], nxtScore = 0, roll = 0 ).process().let { maxOf(it.p1Wins, it.p2Wins) } } println("Part 1: ${part1()}") println("Part 2: ${part2()}") }
0
Kotlin
0
1
dfc91afab12d6dad01de552a77fc22a83237c21d
3,702
AdventOfCode2021
MIT License
src/main/kotlin/cloud/dqn/leetcode/ValidPalindromeKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/valid-palindrome/description/ Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. */ class ValidPalindromeKt { class Solution { /** Use indexing at beginning and end walk beginning up and end down to valid char while (beginnning > end) { if (s[beginning] != s[end]) { return false } walk beginning up and end down to valid char } return true */ object ValidChar { var set: HashSet<Char> init { val size = ((26*2+10) * 0.75 + 8).toInt() set = HashSet(size) set.addAll('0'..'9') set.addAll('A'..'Z') set.addAll('a'..'z') } } companion object { val VALID_CHAR = Regex("[a-zA-Z0-9]") } private fun caseInsensitiveNotEqual(s: String, i: Int, j: Int): Boolean { return s[i].toLowerCase() != s[j].toLowerCase() } private fun findNextIncreasingValidIndex(s: String, currentIndex: Int = -1): Int { var j = if (currentIndex <= -1) { 0 } else { currentIndex + 1 } while (j < s.length) { if (ValidChar.set.contains(s[j])) { // if (VALID_CHAR.matches(s[j].toString())) { return j } j++ } return s.length } private fun findNextDecreasingValidIndex(s: String, currentIndex: Int? = null): Int { var j = if (currentIndex == null || currentIndex > s.length) { s.length } else { currentIndex - 1 } while (j > 0) { if (ValidChar.set.contains(s[j])) { // if (VALID_CHAR.matches(s[j].toString())) { return j } j-- } return -1 } fun isPalindrome(s: String): Boolean { var beginningIndex = findNextIncreasingValidIndex(s, -1) var endingIndex = findNextDecreasingValidIndex(s, s.length) while (beginningIndex < endingIndex) { if (caseInsensitiveNotEqual(s, beginningIndex, endingIndex)) { return false } beginningIndex = findNextIncreasingValidIndex(s, beginningIndex) endingIndex = findNextDecreasingValidIndex(s, endingIndex) } return true } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
3,103
cloud-dqn-leetcode
No Limit Public License
kotlin/numeric/WalshHadamarTransform.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package numeric import java.util.Arrays object WalshHadamarTransform { // calculates c[k] = sum(a[i]*b[j] | i op j == k), where op = XOR | OR | AND // complexity: O(n*log(n)) fun convolution(a: IntArray, b: IntArray, op: Operation): IntArray { transform(a, op, false) transform(b, op, false) for (i in a.indices) { a[i] *= b[i] } transform(a, op, true) return a } fun transform(a: IntArray, op: Operation, inverse: Boolean) { val n = a.size var step = 1 while (step < n) { var i = 0 while (i < n) { for (j in i until i + step) { val u = a[j] val v = a[j + step] when (op) { Operation.XOR -> { a[j] = u + v a[j + step] = u - v } Operation.OR -> { a[j] = if (inverse) v else u + v a[j + step] = if (inverse) u - v else u } Operation.AND -> { a[j] = if (inverse) v - u else v a[j + step] = if (inverse) u else v + u } } } i += 2 * step } step *= 2 } if (op == Operation.XOR && inverse) { for (i in 0 until n) { a[i] /= n } } } // Usage example fun main(args: Array<String?>?) { val a = intArrayOf(3, 2, 1, 5) val b = intArrayOf(6, 3, 4, 8) System.out.println(Arrays.toString(convolution(a, b, Operation.AND))) } enum class Operation { XOR, OR, AND } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,866
codelibrary
The Unlicense
3/src/symbol/Symbol.kt
ldk123456
155,069,463
false
null
package symbol fun main(args: Array<String>) { val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) //总数操作符 println("=====总数操作符=====") println("list.any{it > 10}: ${list.any { it > 10 }}") println("list.all{it in 1..10}: ${list.all { it in 1..10 }}") println("list.none { it > 10 }: ${list.none { it > 10 }}") println("list.count { it in 1..10 }: ${list.count { it in 1..10 }}") println("list.sumBy { it * it }: ${list.sumBy { it * it }}") println("list.min(): ${list.min()}") println("list.minBy { it * it }: ${list.minBy { it * it }}") //过滤操作符 println("=====过滤操作符=====") println("list.filter { it != 5 }:${list.filter { it != 5 }}") println("list.filterNot { it == 5 }: ${list.filterNot { it == 5 }}") println("list.filterNotNull(): ${list.filterNotNull()}") println("list.take(4): ${list.take(4)}") println("list.takeLast(4): ${list.takeLast(4)}") println("list.takeLastWhile { it !!< 5 }: ${list.takeLastWhile { it !!< 5 }}") println("list.drop(4):${list.drop(4)}") println("list.dropLastWhile { it == 4 }: ${list.dropLastWhile { it == 4 }}") println("list.dropWhile { it !!< 4 }: ${list.dropWhile { it !!< 4 }}") println("list.slice(listOf(1, 2, 3)): ${list.slice(listOf(1, 2, 3))}") //映射操作符 println("=====映射操作符=====") val list1 = listOf(1, 2, 3, 4, 5) val list2 = listOf(6, 7, 8, 9, 10) println(list1.map { it + 1 }) println(list1.mapIndexed { index, i -> index * i }) println(list1.mapNotNull { it + 5 }) println(listOf(list1, list2).flatMap { it -> it }) println(listOf(list1.groupBy { if (it > 3) "big" else "small" })) //顺序操作符 println("=====顺序操作符=====") val list3 = listOf(1, 5, 9, 7, 26, 74, 32, 47, 41, 42, 6) println("list.reversed(): ${list3.reversed()}") println("list.sorted(): ${list3.sorted()}") println("list.sortedBy { it % 2 }: ${list3.sortedBy { it % 2 }}") println("list.sortedDescending(): ${list3.sortedDescending()}") println("list.sortedByDescending { it % 2 }: ${list3.sortedByDescending { it % 2 }}") //生产操作符 println("=====生产操作符=====") println("list1.zip(list2): ${list1.zip(list2)}") println("list1.zip(list2){it1, it2 -> it1 + it2}: ${list1.zip(list2){it1, it2 -> it1 + it2}}") println("list1.partition { it > 3 }: ${list1.partition { it > 3 }}") println("list1.plus(list2): ${list1.plus(list2)}") println("listOf(Pair(1, 2), Pair(3, 4)).unzip(): ${listOf(Pair(1, 2), Pair(3, 4)).unzip()}") //元素操作符 println("=====元素操作符=====") println("list.contains(14): ${list.contains(14)}") println("list.elementAt(4): ${list.elementAt(4)}") println("list.elementAtOrElse(14, {it + 3}): ${list.elementAtOrElse(14, {it + 3})}") println("list.elementAtOrNull(14): ${list.elementAtOrNull(14)}") println("list.first(): ${list.first()}") println("list.first { it % 3 == 0 }: ${list.first { it % 3 == 0 }}") println("list.firstOrNull{ it > 14 }: ${list.firstOrNull{ it > 14 }}") println("list.indexOf(5): ${list.indexOf(5)}") println("list.indexOfFirst { it == 14 }: ${list.indexOfFirst { it == 14 }}") println("list.lastOrNull { it == 8 }: ${list.lastOrNull { it == 8 }}") println("list.single { it == 8 }: ${list.single { it == 8 }}") println("list.singleOrNull { it == 8 }: ${list.singleOrNull { it == 8 }}") }
0
Kotlin
0
0
8dc6bff0ef47b824bb5861cd6f4a27bdcefa39f3
3,487
Introduction
Apache License 2.0
src/commonMain/kotlin/com/github/knok16/regrunch/dfa/LanguageSize.kt
knok16
593,302,527
false
null
package com.github.knok16.regrunch.dfa import com.github.knok16.regrunch.utils.BigInteger import com.github.knok16.regrunch.utils.ONE import com.github.knok16.regrunch.utils.ZERO import com.github.knok16.regrunch.utils.plus fun <A, S> isLanguageEmpty(dfa: DFA<A, S>): Boolean { val visited = HashSet<S>() fun dfs(state: S): Boolean { if (state in dfa.finalStates) return true if (!visited.add(state)) return false return dfa.alphabet.any { symbol -> dfs(dfa.transition(state, symbol)) } } return !dfs(dfa.startState) } fun <A, S> languageSize(dfa: DFA<A, S>): BigInteger? { val deadStates = dfa.deadStates() val currentlyIn = HashSet<S>() val resultCache = HashMap<S, BigInteger?>() fun dfs(state: S): BigInteger? { if (state in deadStates) return ZERO if (state in resultCache) return resultCache[state] if (state in currentlyIn) return null currentlyIn.add(state) val result = dfa.alphabet.fold<A, BigInteger?>( if (state in dfa.finalStates) ONE else ZERO ) { acc, symbol -> acc?.let { dfs(dfa.transition(state, symbol))?.let { it + acc } } } resultCache[state] = result currentlyIn.remove(state) return result } return dfs(dfa.startState) } fun <A, S> isLanguageInfinite(dfa: DFA<A, S>): Boolean { val deadStates = dfa.deadStates() val currentlyIn = HashSet<S>() val visited = HashSet<S>() fun dfs(state: S): Boolean { if (state in deadStates) return false if (state in visited) return false if (state in currentlyIn) return true currentlyIn.add(state) val result = dfa.alphabet.any { symbol -> dfs(dfa.transition(state, symbol)) } currentlyIn.remove(state) visited.add(state) return result } return dfs(dfa.startState) }
0
Kotlin
1
11
87c6a7ab9f6db4e48e9d3caf88b278c59297ed7b
1,903
regrunch
MIT License
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day06.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.Point import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues import nl.jstege.adventofcode.aoccommon.utils.extensions.sortTo import nl.jstege.adventofcode.aoccommon.utils.extensions.transformTo /** * * @author <NAME> */ class Day06 : Day(title = "Probably a Fire Hazard") { private companion object Configuration { private const val GRID_COLS = 1000 private const val GRID_ROWS = 1000 private const val INPUT_PATTERN_STRING = """(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)""" private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex() private const val OP_INDEX = 1 private const val X1_INDEX = 2 private const val Y1_INDEX = 3 private const val X2_INDEX = 4 private const val Y2_INDEX = 5 private val OP_INDICES = intArrayOf(OP_INDEX, X1_INDEX, Y1_INDEX, X2_INDEX, Y2_INDEX) } override fun first(input: Sequence<String>): Any = input .parse() .transformTo(BooleanArray(GRID_COLS * GRID_ROWS)) { grid, (op, from, to) -> (from.y..to.y).forEach { y -> (from.x..to.x).forEach { x -> grid[x, y] = op == "turn on" || op == "toggle" && !grid[x, y] } } } .count { it } override fun second(input: Sequence<String>): Any = input .parse() .transformTo(IntArray(GRID_ROWS * GRID_COLS)) { grid, (op, from, to) -> (from.y..to.y).forEach { y -> (from.x..to.x).forEach { x -> grid[x, y] = Math.max( 0, grid[x, y] + when (op) { "turn on" -> 1 "turn off" -> -1 else -> 2 } ) } } } .sum() private fun Sequence<String>.parse(): Sequence<Operation> = this .map { it.extractValues(INPUT_REGEX, *OP_INDICES) } .map { (op, sx1, sy1, sx2, sy2) -> val (x1, x2) = sx1.toInt() sortTo sx2.toInt() val (y1, y2) = sy1.toInt() sortTo sy2.toInt() Operation(op, Point.of(x1, y1), Point.of(x2, y2)) } private operator fun BooleanArray.get(x: Int, y: Int): Boolean = this[y * GRID_COLS + x] private operator fun IntArray.get(x: Int, y: Int): Int = this[y * GRID_COLS + x] private operator fun BooleanArray.set(x: Int, y: Int, v: Boolean) { this[y * GRID_COLS + x] = v } private operator fun IntArray.set(x: Int, y: Int, v: Int) { this[y * GRID_COLS + x] = v } data class Operation(val operation: String, val from: Point, val to: Point) }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,883
AdventOfCode
MIT License
y2017/src/main/kotlin/adventofcode/y2017/Day15.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution object Day15 : AdventSolution(2017, 15, "Dueling Generators") { override fun solvePartOne(input: String): String { val (seedA, seedB) = parseInput(input) val genA = generateSequence(seedA) { it * 16807L % 2147483647L } val genB = generateSequence(seedB) { it * 48271L % 2147483647L } return judge(genA, genB, 40_000_000).toString() } override fun solvePartTwo(input: String): String { val (seedA, seedB) = parseInput(input) val genA = generateSequence(seedA) { it * 16807L % 2147483647L } .filter { it % 4L == 0L } val genB = generateSequence(seedB) { it * 48271L % 2147483647L } .filter { it % 8L == 0L } return judge(genA, genB, 5_000_000).toString() } private fun parseInput(input: String): List<Long> = input.lines() .map { it.substringAfter("starts with ").toLong() } // This one's a bit subtle. A JVM Short has 16 bits, but is interpreted as signed two's complement. // There's definitely going to be overflow, so you really shouldn't be doing arithmetic with these. // Equality works fine though, and that's all we need. private fun judge(s0: Sequence<Long>, s1: Sequence<Long>, count: Int): Int = s0.zip(s1) .take(count) .count { (a, b) -> a.toShort() == b.toShort() } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,296
advent-of-code
MIT License
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day20.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day class Day20 : Day("4928", "16605") { private data class Pixel(val x: Int, val y: Int) private val enhancementAlgorithm = input .split("\n\n")[0] .toCharArray() .map { it == '#' } private val inputLitPixels = input .split("\n\n")[1] .lines() .flatMapIndexed { y, line -> line.toCharArray().mapIndexed { x, ch -> if (ch == '#') { Pixel(x, y) } else { null } } } .filterNotNull() .toSet() override fun solvePartOne(): Any { return getLitPixelsAfterEnhancements(2) } override fun solvePartTwo(): Any { return getLitPixelsAfterEnhancements(50) } private fun getLitPixelsAfterEnhancements(enhancements: Int): Int { var width = inputLitPixels.maxOf { it.x } + enhancements * 4 + 1 var height = inputLitPixels.maxOf { it.y } + enhancements * 4 + 1 var litPixels = Array(height) { y -> BooleanArray(width) { x -> inputLitPixels.contains(Pixel(x - enhancements * 2, y - enhancements * 2)) } } for (i in 0 until enhancements) { width -= 2 height -= 2 litPixels = Array(height) { y -> BooleanArray(width) { x -> val bits = StringBuilder() bits.append(if (litPixels[y][x]) 1 else 0) bits.append(if (litPixels[y][x + 1]) 1 else 0) bits.append(if (litPixels[y][x + 2]) 1 else 0) bits.append(if (litPixels[y + 1][x]) 1 else 0) bits.append(if (litPixels[y + 1][x + 1]) 1 else 0) bits.append(if (litPixels[y + 1][x + 2]) 1 else 0) bits.append(if (litPixels[y + 2][x]) 1 else 0) bits.append(if (litPixels[y + 2][x + 1]) 1 else 0) bits.append(if (litPixels[y + 2][x + 2]) 1 else 0) enhancementAlgorithm[bits.toString().toInt(2)] } } } return litPixels.sumOf { row -> row.count { it } } } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
2,253
advent-of-code-2021
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NextGreatestLetter.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 /** * 744. Find Smallest Letter Greater Than Target * @see <a href="https://leetcode.com/problems/find-smallest-letter-greater-than-target/">Source</a> */ fun interface NextGreatestLetter { operator fun invoke(letters: CharArray, target: Char): Char } /** * Approach 1: Brute Force */ class NextGreatestLetterBruteForce : NextGreatestLetter { override operator fun invoke(letters: CharArray, target: Char): Char { for (letter in letters) { if (letter > target) { return letter } } return letters[0] } } /** * Approach 2: Binary Search */ class NextGreatestLetterBinarySearch : NextGreatestLetter { override operator fun invoke(letters: CharArray, target: Char): Char { var left = 0 var right: Int = letters.size - 1 var mid: Int while (left <= right) { mid = (left + right) / 2 if (letters[mid] <= target) { left = mid + 1 } else { right = mid - 1 } } return if (left == letters.size) letters[0] else letters[left] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,782
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinMovesToMakePalindrome.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 /** * 2193. Minimum Number of Moves to Make Palindrome * @see <a href="https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/">Source</a> */ fun interface MinMovesToMakePalindrome { operator fun invoke(s: String): Int } class MinMovesToMakePalindromeGreedy : MinMovesToMakePalindrome { override operator fun invoke(s: String): Int { var res = 0 var s0 = s while (s0.isNotEmpty()) { val i: Int = s0.indexOf(s0[s0.length - 1]) if (i == s0.length - 1) { res += i / 2 } else { res += i s0 = s0.substring(0, i) + s0.substring(i + 1) } s0 = s0.substring(0, s0.length - 1) } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,408
kotlab
Apache License 2.0
src/Utils.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
import java.math.BigInteger import java.security.MessageDigest import java.util.EnumMap import kotlin.io.path.Path import kotlin.io.path.readLines /** * Reads lines from the given input txt file. */ fun readInput(name: String) = Path("src", "$name.txt").readLines() /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0') fun <T> List<T>.toPair(): Pair<T, T> { check(size == 2) return Pair(this[0], this[1]) } fun <T> Iterable<T>.countUntil(predicate: (T) -> Boolean): Int { var count = 0 for (e in this) { ++count if (predicate(e)) break } return count } fun <T> lexicographicalCompare(left: List<T>, right: List<T>, comparator: (T, T) -> Int): Int = left.zip(right).firstNotNullOfOrNull { (l, r) -> comparator(l, r).takeIf { it != 0 } } ?: (left.size compareTo right.size) fun List<Int>.product() = reduce(Int::times) private val numberRegex = Regex("""\d+""") fun String.isNumber() = numberRegex.matches(this) operator fun <T> List<T>.component6() = this[5] operator fun <T> List<T>.component7() = this[6] /** * Optimized version for EnumMap */ inline fun <reified K: Enum<K>, V, R> Map<K, V>.mapValues(transform: (Map.Entry<K, V>) -> R): Map<K, R> = EnumMap<K, R>(K::class.java).also { for (entry in this) { it[entry.key] = transform(entry) } } enum class Direction { UP, DOWN, LEFT, RIGHT }
0
Kotlin
0
0
afbcec6a05b8df34ebd8543ac04394baa10216f0
1,497
advent-of-code-22
Apache License 2.0
src/main/kotlin/sortingandsearching/CountOfSmallerNumbersAfterSelf.kt
e-freiman
471,473,372
false
{"Kotlin": 78010}
package sortingandsearching private const val OFFSET = 10000 private const val SIZE = 2 * 10000 + 1 private val segmentTree = IntArray(4 * SIZE) { 0 } private fun update(vertex: Int, left: Int, right: Int, pos: Int, value: Int) { if (left == right) { segmentTree[vertex] += value return } val middle = (left + right) / 2 if (pos <= middle) { update(2 * vertex, left, middle, pos, value) } else { update(2 * vertex + 1,middle + 1, right, pos, value) } segmentTree[vertex] = segmentTree[2 * vertex] + segmentTree[2 * vertex + 1] } private fun query(vertex: Int, left: Int, right: Int, queryLeft: Int, queryRight: Int): Int { if (left == queryLeft && right == queryRight) { return segmentTree[vertex] } val middle = (left + right) / 2 return when { queryRight <= middle -> query(2 * vertex, left, middle, queryLeft, queryRight) queryLeft > middle -> query(2 * vertex + 1, middle + 1, right, queryLeft, queryRight) else -> query(2 * vertex, left, middle, queryLeft, middle) + query(2 * vertex + 1, middle + 1, right, middle + 1, queryRight) } } // O(N*logN) private fun countSmaller(nums: IntArray): List<Int> { val ret = mutableListOf<Int>() // O(N * logN) for (num in nums.reversed()) { // O(logN) update(1, 0, SIZE, num + OFFSET, 1) // O(logN) ret.add(query(1, 0, SIZE, 0, num + OFFSET - 1)) } return ret.reversed() } fun main() { println(countSmaller(intArrayOf(5,2,6,1))) }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
1,565
LeetcodeGoogleInterview
Apache License 2.0
src/day03/Day03Answer2.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day03 import readInput /** * Answers from [Advent of Code 2022 Day 3 | Kotlin](https://youtu.be/IPLfo4zXNjk) */ fun main() { fun part1(input: List<String>): Int { val sharedItems = input.map { val first = it.substring(0 until it.length / 2) val second = it.substring(it.length / 2) (first intersect second).single() } return sharedItems.sumOf { it.priority } } fun part2(input: List<String>): Int { val keycards = input.chunked(3) { val (a, b, c) = it val keycard = a intersect b intersect c keycard.single() } return keycards.sumOf { it.priority } } val testInput = readInput("day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("day03") println(part1(input)) // 8123 println(part2(input)) // 2620 } val Char.priority get(): Int { return when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("Check your input! $this") } } // or, for fewer manual call to `.toSet`: infix fun String.intersect(other: String) = toSet() intersect other.toSet() infix fun Set<Char>.intersect(other: String) = this intersect other.toSet()
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
1,338
advent-of-code-2022
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/stores_and_houses/StoresAndHouses.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.stores_and_houses import datsok.shouldEqual import org.junit.Test import kotlin.math.abs /** * https://leetcode.com/discuss/interview-question/350248/Google-or-Summer-Intern-OA-2019-or-Stores-and-Houses * * You are given 2 arrays representing integer locations of stores and houses (each location in this problem is one-dimentional). For each house, find the store closest to it. * Return an integer array result where result[i] should denote the location of the store closest to the i-th house. * If many stores are equidistant from a particular house, choose the store with the smallest numerical location. * Note that there may be multiple stores and houses at the same location. */ class StoresAndHousesTests { @Test fun examples() { findClosesStores(houses = arrayOf(5, 10, 17), stores = arrayOf(1, 5, 20, 11, 16)) shouldEqual listOf(5, 11, 16) findClosesStores(houses = arrayOf(0, 5, 10, 17), stores = arrayOf(1, 5, 20, 11, 16)) shouldEqual listOf(1, 5, 11, 16) findClosesStores(houses = arrayOf(2, 4, 2), stores = arrayOf(5, 1, 2, 3)) shouldEqual listOf(2, 3, 2) findClosesStores(houses = arrayOf(4, 8, 1, 1), stores = arrayOf(5, 3, 1, 2, 6)) shouldEqual listOf(3, 6, 1, 1) } private fun findClosesStores(houses: Array<Int>, stores: Array<Int>): List<Int> { stores.sort() return houses.map { position -> val i = stores.binarySearch(position) if (i >= 0) stores[i] else { val i1 = -i - 2 val i2 = -i - 1 when { i1 < 0 -> stores[i2] i2 >= stores.size -> stores[i1] abs(position - stores[i1]) <= abs(position - stores[i2]) -> stores[i1] else -> stores[i2] } } } } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,014
katas
The Unlicense
src/day09/Day09.kt
commanderpepper
574,647,779
false
{"Kotlin": 44999}
package day09 import readInput import kotlin.math.abs fun main(){ val dayNineInput = readInput("day09") // println("Tail visited ${partOne(dayNineInput)}") println("Tail visited ${partTwo(dayNineInput)}") } // Failed part two solution private fun partTwo(dayNineInput: List<String>): Int { val tailVisitedPositions = mutableSetOf<Position>() // The head knot is represented by the first item, the tail know is represented by the last item // Int represents the index of the knot in the original list val rope = MutableList<Pair<Int, Knot>>(10){it to Knot(Position(xPosition = XPosition(0), yPosition = YPosition(0)))} // println(rope) // val ropePairs = rope.windowed(2) // ropePairs.forEach { // println(it) // } rope.forEach { println(it.second) } println() tailVisitedPositions.add(rope.last().second.position) dayNineInput.forEach { val instruction = it.split(" ") val direction = instruction.first() val movement = instruction.last() repeat(movement.toInt()) { rope.forEach { println(it.second) } println() val ropePairs = rope.windowed(2) when (direction) { "R" -> { ropePairs.forEach { pairOfKnots -> val firstKnowIndex = pairOfKnots.first().first var firstKnot = pairOfKnots.first().second val secondKnotIndex = pairOfKnots.last().first var secondKnot = pairOfKnots.last().second rope[firstKnowIndex] = firstKnowIndex to firstKnot.copy( position = firstKnot.position.copy( xPosition = XPosition(firstKnot.position.xPosition.position + 1) ) ) if (areKnotsNextToEachOther(rope[firstKnowIndex].second, secondKnot).not()) { rope[secondKnotIndex] = secondKnotIndex to secondKnot.copy( position = secondKnot.position.copy( xPosition = XPosition(secondKnot.position.xPosition.position + 1) ) ) } } tailVisitedPositions.add(rope.last().second.position) } "L" -> { ropePairs.forEach { pairOfKnots -> val (firstKnowIndex, firstKnot) = pairOfKnots.first() val (secondKnotIndex, secondKnot) = pairOfKnots.last() rope[firstKnowIndex] = firstKnowIndex to firstKnot.copy( position = firstKnot.position.copy( xPosition = XPosition(firstKnot.position.xPosition.position - 1) ) ) if (areKnotsNextToEachOther(rope[firstKnowIndex].second, secondKnot).not()) { rope[secondKnotIndex] = secondKnotIndex to secondKnot.copy( position = secondKnot.position.copy( xPosition = XPosition(secondKnot.position.xPosition.position - 1) ) ) } } tailVisitedPositions.add(rope.last().second.position) } "U" -> { ropePairs.forEach { pairOfKnots -> val (firstKnowIndex, firstKnot) = pairOfKnots.first() val (secondKnotIndex, secondKnot) = pairOfKnots.last() rope[firstKnowIndex] = firstKnowIndex to firstKnot.copy( position = firstKnot.position.copy( yPosition = YPosition(firstKnot.position.yPosition.position + 1) ) ) if (areKnotsNextToEachOther(rope[firstKnowIndex].second, secondKnot).not()) { rope[secondKnotIndex] = secondKnotIndex to secondKnot.copy( position = secondKnot.position.copy( yPosition = YPosition(firstKnot.position.yPosition.position + 1) ) ) } } tailVisitedPositions.add(rope.last().second.position) } else -> { ropePairs.forEach { pairOfKnots -> val (firstKnowIndex, firstKnot) = pairOfKnots.first() val (secondKnotIndex, secondKnot) = pairOfKnots.last() rope[firstKnowIndex] = firstKnowIndex to firstKnot.copy( position = firstKnot.position.copy( yPosition = YPosition(firstKnot.position.yPosition.position - 1) ) ) if (areKnotsNextToEachOther(rope[firstKnowIndex].second, secondKnot).not()) { rope[secondKnotIndex] = secondKnotIndex to secondKnot.copy( position = secondKnot.position.copy( yPosition = YPosition(firstKnot.position.yPosition.position - 1) ) ) } } tailVisitedPositions.add(rope.last().second.position) } } } } return tailVisitedPositions.size } private fun partOne(dayNineInput: List<String>): Int { val tailVisitedPositions = mutableSetOf<Position>() var tail = Knot(Position(xPosition = XPosition(0), yPosition = YPosition(0))) var head = Knot(Position(xPosition = XPosition(0), yPosition = YPosition(0))) tailVisitedPositions.add(tail.position) dayNineInput.forEach { val instruction = it.split(" ") val direction = instruction.first() val movement = instruction.last() repeat(movement.toInt()) { val currentHeadPosition = head.position when (direction) { // Going Right "R" -> { head = head.copy(position = currentHeadPosition.copy(xPosition = XPosition(currentHeadPosition.xPosition.position + 1))) if (areKnotsNextToEachOther(head, tail).not()) { tail = tail.copy(position = currentHeadPosition) } } // Going Left "L" -> { head = head.copy(position = currentHeadPosition.copy(xPosition = XPosition(currentHeadPosition.xPosition.position - 1))) if (areKnotsNextToEachOther(head, tail).not()) { tail = tail.copy(position = currentHeadPosition) } } // Going Up "U" -> { head = head.copy(position = currentHeadPosition.copy(yPosition = YPosition(currentHeadPosition.yPosition.position + 1))) if (areKnotsNextToEachOther(head, tail).not()) { tail = tail.copy(position = currentHeadPosition) } } // Going Down else -> { head = head.copy(position = currentHeadPosition.copy(yPosition = YPosition(currentHeadPosition.yPosition.position - 1))) if (areKnotsNextToEachOther(head, tail).not()) { tail = tail.copy(position = currentHeadPosition) } } } tailVisitedPositions.add(tail.position) } } return tailVisitedPositions.size } fun areKnotsNextToEachOther(head: Knot, tail: Knot): Boolean { // check if on top of one another if(head.position == tail.position){ return true } val xDistance = abs(head.position.xPosition.position - tail.position.xPosition.position) val yDistance = abs(head.position.yPosition.position - tail.position.yPosition.position) val nextToEachOthersXCoordinate = xDistance == 1 || xDistance == 0 val nextToEachOthersYCoordinate = yDistance == 1 || yDistance == 0 // If the xDistance and yDistance are both 1 then they are next to each other. if(nextToEachOthersXCoordinate && nextToEachOthersYCoordinate){ return true } return false } data class Knot(val position: Position) data class Position(val xPosition: XPosition, val yPosition: YPosition) @JvmInline value class XPosition(val position: Int) @JvmInline value class YPosition(val position: Int)
0
Kotlin
0
0
fef291c511408c1a6f34a24ed7070ceabc0894a1
8,988
advent-of-code-kotlin-2022
Apache License 2.0
2022/Day07/problems.kt
moozzyk
317,429,068
false
{"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794}
import java.io.File import kotlin.collections.mutableListOf class Node constructor(val name: String, var size: Int, val parent: Node?) { val childNodes = mutableListOf<Node>() fun isDir(): Boolean = childNodes.size > 0 } fun main(args: Array<String>) { val lines = File(args[0]).readLines() val fs = buildFS(lines) println(problem1(fs)) println(problem2(fs)) } fun buildFS(commands: List<String>): Node { val root = Node("/", 0, null) var currentNode = root for (cmd in commands) { val components = cmd.split(" ") if (components[1].equals("cd")) { when (components[2]) { "/" -> currentNode = root ".." -> currentNode = currentNode.parent!! else -> { val dirNode = Node(components[2], 0, currentNode) currentNode.childNodes.add(dirNode) currentNode = dirNode } } } else if (components[1].equals("ls")) {} else { if (components[0].equals("dir")) { // not needed } else { var fileNode = Node(components[1], components[0].toInt(), currentNode) currentNode.childNodes.add(fileNode) } } } setSize(root) return root } fun setSize(node: Node): Int { var size: Int = 0 for (child in node.childNodes) { setSize(child) size += child.size } node.size = size + node.size return node.size } fun printTree(node: Node, indent: Int) { println("${" ".repeat(indent)}- ${node.name} (${node.size})") for (child in node.childNodes) { printTree(child, indent + 1) } } fun problem1(node: Node): Int { var size: Int = if (node.size > 100000) 0 else node.size for (child in node.childNodes.filter { it.isDir() }) { size += problem1(child) } return size } fun dirToDelete(node: Node, spaceToFree: Int, bestCandidate: Node): Node { var candidate = if (node.size > spaceToFree && node.size < bestCandidate.size) node else bestCandidate for (child in node.childNodes.filter { it.isDir() }) { candidate = dirToDelete(child, spaceToFree, candidate) } return candidate } fun problem2(node: Node): Int { val freeSpace = 70000000 - node.size val spaceToFree = 30000000 - freeSpace val dir = dirToDelete(node, spaceToFree, node) return dir.size }
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
2,465
AdventOfCode
MIT License
src/main/kotlin/Day02.kt
luluvia
576,815,205
false
{"Kotlin": 7130}
class Day02 { private val scores1 = mapOf( 'X' to mapOf('A' to 4, 'B' to 1, 'C' to 7), 'Y' to mapOf('A' to 8, 'B' to 5, 'C' to 2), 'Z' to mapOf('A' to 3, 'B' to 9, 'C' to 6) ) private val scores2 = mapOf( 'X' to mapOf('A' to 3, 'B' to 1, 'C' to 2), 'Y' to mapOf('A' to 4, 'B' to 5, 'C' to 6), 'Z' to mapOf('A' to 8, 'B' to 9, 'C' to 7) ) fun part1(input: List<String>): Int { var score = 0 for (line in input) { val opChoice = line[0] val myChoice = line[2] score += scores1[myChoice]!![opChoice]!! } return score } fun part2(input: List<String>): Int { var score = 0 for (line in input) { val opChoice = line[0] val myOutcome = line[2] score += scores2[myOutcome]!![opChoice]!! } return score } }
0
Kotlin
0
0
29ddde3b0d7acbe0ef1295ec743e7d0417cfef53
922
advent-of-code-22
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/TextJustification.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 68. Text Justification * @see <a href="https://leetcode.com/problems/text-justification/">Source</a> */ fun interface TextJustification { operator fun invoke(words: Array<String>, maxWidth: Int): List<String> } class TextJustificationImpl : TextJustification { override operator fun invoke(words: Array<String>, maxWidth: Int): List<String> { var curr = 0 val out: MutableList<String> = ArrayList() while (curr < words.size) { var currLineLen = 0 val start = curr var end = curr // Determine start and end positions while (end < words.size && currLineLen + words[end].length + (end - start) <= maxWidth) { currLineLen += words[end].length end++ } currLineLen += end - start - 1 val spaces = IntArray(end - start) { 1 } spaces[spaces.size - 1] = 0 // Last word does not appended with space unless it is at last line if (currLineLen < maxWidth) { if (end == words.size) { // Add spaces to end at last line spaces[spaces.size - 1] += maxWidth - currLineLen } else { // Iterate through spaces until all spaces consumed val arrSize = max(spaces.size - 1, 1) val spaceNeeded = maxWidth - currLineLen var i = 0 var j = 0 while (i < spaceNeeded) { spaces[j]++ i++ j = (j + 1) % arrSize } } } val sb = StringBuilder() for (i in start until end) { sb.append(words[i]) // Add spaces from spaces array for (j in 0 until spaces[i - start]) sb.append(" ") } out.add(sb.toString()) curr = end } return out } } class TextJustificationImpl2 : TextJustification { override operator fun invoke(words: Array<String>, maxWidth: Int): List<String> { var left = 0 val result: MutableList<String> = ArrayList() while (left < words.size) { val right = findRight(left, words, maxWidth) result.add(justify(left, right, words, maxWidth)) left = right + 1 } return result } private fun justify(left: Int, right: Int, words: Array<String>, maxWidth: Int): String { if (left == right) { return padRight(words[left], maxWidth) } var sum = words[left].length for (i in left + 1..right) { sum += words[i].length } val isLastLine = right == words.size - 1 val numWords = right - left val numWhitespace = maxWidth - sum val numSpacesBetween = if (isLastLine) 1 else numWhitespace / numWords var remainder = if (isLastLine) 0 else numWhitespace % numWords val result = java.lang.StringBuilder() for (i in left until right) { result.append(words[i]) result.append(whitespace(numSpacesBetween)) result.append(if (remainder-- > 0) " " else "") } result.append(words[right]) return if (isLastLine) { padRight(result.toString(), maxWidth) } else { result.toString() } } private fun whitespace(numSpacesBetween: Int): String { val sb = java.lang.StringBuilder() for (i in 0 until numSpacesBetween) { sb.append(" ") } return sb.toString() } private fun padRight(s: String, maxWidth: Int): String { val sb = java.lang.StringBuilder(s) sb.append(whitespace(maxWidth - s.length)) return sb.toString() } private fun findRight(left: Int, words: Array<String>, maxWidth: Int): Int { var right = left var sum = words[right++].length while (right < words.size && sum + 1 + words[right].length <= maxWidth) { sum += 1 + words[right++].length } return right - 1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,876
kotlab
Apache License 2.0
hexagon/HexagonStandoffSolver.kt
Brinsky
398,903,731
false
null
package hexagon // Solver for Hexagon Standoff from "<NAME>" // Glossary: // // Piece: the individual, moveable game pieces with symbols on them // Slot: the board locations where pieces may be placed // Offset: the number of increments by which a piece has been rotated (counterclockwise) from its // "default" orientation // Index: a particular symbol location within a piece, but fixed to a particular "side" regardless // of offset (e.g. the bottom edge will always be 0 even after rotation) val NUM_PIECES = 7 val PIECE_SIZE = 6 val PIECES = arrayOf( arrayOf("γ", "χ", "α", "ε", "π", "λ"), // 0 arrayOf("γ", "ε", "χ", "π", "λ", "α"), // 1 arrayOf("λ", "ε", "α", "π", "γ", "χ"), // 2 arrayOf("α", "χ", "π", "γ", "ε", "λ"), // 3 arrayOf("π", "χ", "α", "λ", "ε", "γ"), // 4 arrayOf("α", "π", "γ", "λ", "χ", "ε"), // 5 arrayOf("α", "χ", "λ", "π", "γ", "ε"), // 6 ) data class SlotIndex(val slot: Int, val index: Int) val EQUALITY_POINTS = mapOf( SlotIndex(0, 4) to SlotIndex(1, 1), SlotIndex(0, 5) to SlotIndex(4, 2), SlotIndex(0, 0) to SlotIndex(3, 3), SlotIndex(1, 0) to SlotIndex(4, 3), SlotIndex(1, 5) to SlotIndex(2, 2), SlotIndex(4, 4) to SlotIndex(2, 1), SlotIndex(4, 1) to SlotIndex(3, 4), SlotIndex(4, 0) to SlotIndex(6, 3), SlotIndex(4, 5) to SlotIndex(5, 2), SlotIndex(2, 0) to SlotIndex(5, 3), SlotIndex(3, 5) to SlotIndex(6, 2), SlotIndex(6, 4) to SlotIndex(5, 1), ) fun main() { var numSolutions = 0 // Iterate over factoriadic numbers, then convert them to permutations - we are doing this to // find every permutation of piece placements // // Note that generating permutations recursively is much easier and possibly more performant, // but the ability to iterate over the problem space without recursion was prioritized for (slotsFactoriadic in factoriadicIterator(NUM_PIECES)) { val slots = factoriadicToPermutation(slotsFactoriadic) // Iterate over the possible rotations taking place for each slot (for the piece within // that slot) for (offsets in fixedBaseIterator(PIECE_SIZE, NUM_PIECES)) { if (isSolution(slots, offsets, EQUALITY_POINTS)) { println( "Solution found with slottings " + slots.contentToString() + " and offsets " + offsets.contentToString() ) numSolutions++ } } } } fun isSolution( slots: IntArray, offsets: IntArray, equalityPoints: Map<SlotIndex, SlotIndex> ): Boolean { // Check each edge that occurs between two pieces for equality of symbol for ((k, v) in equalityPoints) { if (getRotation(slots[k.slot], offsets[k.slot], k.index) != getRotation(slots[v.slot], offsets[v.slot], v.index) ) { return false } } return true } // https://en.wikipedia.org/wiki/Factorial_number_system#Permutations fun factoriadicToPermutation(factoriadic: IntArray): IntArray { val permutation = IntArray(factoriadic.size) { -1 } for (i in factoriadic.indices) { // "i" should go at relative position "factoriadic[i]" val targetRelativePos = factoriadic[i] var currentRelativePos = 0 var j = 0 while (permutation[j] != -1 || currentRelativePos < targetRelativePos) { if (permutation[j] == -1) { currentRelativePos++ } j++ } permutation[j] = i } return permutation } fun getRotation(piece: Int, offset: Int, index: Int): String { return PIECES[piece][(index + offset) % PIECE_SIZE] }
0
Kotlin
0
0
61b528f6fe583b06f57a77c0f2dc90546f35c0b8
4,123
hexagon-standoff
MIT License
kotlin/410.Split Array Largest Sum(分割数组的最大值).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>Given an array which consists of non-negative integers and an integer <i>m</i>, you can split the array into <i>m</i> non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these <i>m</i> subarrays. </p> <p><b>Note:</b><br /> If <i>n</i> is the length of array, assume the following constraints are satisfied: <ul> <li>1 &le; <i>n</i> &le; 1000</li> <li>1 &le; <i>m</i> &le; min(50, <i>n</i>)</li> </ul> </p> <p><b>Examples: </b> <pre> Input: <b>nums</b> = [7,2,5,10,8] <b>m</b> = 2 Output: 18 Explanation: There are four ways to split <b>nums</b> into two subarrays. The best way is to split it into <b>[7,2,5]</b> and <b>[10,8]</b>, where the largest sum among the two subarrays is only 18. </pre> </p><p>给定一个非负整数数组和一个整数&nbsp;<em>m</em>,你需要将这个数组分成&nbsp;<em>m&nbsp;</em>个非空的连续子数组。设计一个算法使得这&nbsp;<em>m&nbsp;</em>个子数组各自和的最大值最小。</p> <p><strong>注意:</strong><br /> 数组长度&nbsp;<em>n&nbsp;</em>满足以下条件:</p> <ul> <li>1 &le; <em>n</em> &le; 1000</li> <li>1 &le; <em>m</em> &le; min(50, <em>n</em>)</li> </ul> <p><strong>示例: </strong></p> <pre> 输入: <strong>nums</strong> = [7,2,5,10,8] <strong>m</strong> = 2 输出: 18 解释: 一共有四种方法将<strong>nums</strong>分割为2个子数组。 其中最好的方式是将其分为<strong>[7,2,5]</strong> 和 <strong>[10,8]</strong>, 因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。 </pre> <p>给定一个非负整数数组和一个整数&nbsp;<em>m</em>,你需要将这个数组分成&nbsp;<em>m&nbsp;</em>个非空的连续子数组。设计一个算法使得这&nbsp;<em>m&nbsp;</em>个子数组各自和的最大值最小。</p> <p><strong>注意:</strong><br /> 数组长度&nbsp;<em>n&nbsp;</em>满足以下条件:</p> <ul> <li>1 &le; <em>n</em> &le; 1000</li> <li>1 &le; <em>m</em> &le; min(50, <em>n</em>)</li> </ul> <p><strong>示例: </strong></p> <pre> 输入: <strong>nums</strong> = [7,2,5,10,8] <strong>m</strong> = 2 输出: 18 解释: 一共有四种方法将<strong>nums</strong>分割为2个子数组。 其中最好的方式是将其分为<strong>[7,2,5]</strong> 和 <strong>[10,8]</strong>, 因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。 </pre> **/ class Solution { fun splitArray(nums: IntArray, m: Int): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
2,496
leetcode
MIT License
src/day24/Parser.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day24 import readInput import java.lang.IllegalArgumentException import java.lang.IllegalStateException enum class Direction (val dx: Int, val dy: Int, val encoded: Char) { UP (0, -1, '^'), LEFT (-1, 0, '<'), DOWN (0, 1, 'v'), RIGHT (1, 0, '>'); val invert: Direction get () = values()[(ordinal + 2) % values().size] } data class Point (val x: Int, val y: Int) { fun add (other: Point): Point = Point (x + other.x, y + other.y) fun add (dx: Int, dy: Int): Point= Point (x + dx, y + dy) fun move (dir: Direction): Point = Point (x + dir.dx, y + dir.dy) fun move (dir: Direction, xwrap: Int, ywrap: Int): Point { var x = x + dir.dx if (x < 0) { if (x != -1) { throw Exception () } x = xwrap - 1 } else if (x == xwrap) { x = 0 } var y = y + dir.dy if (y < 0) { if (y != -1) { throw Exception () } y = ywrap - 1 } else if (y == ywrap) { y = 0 } return Point (x, y) } } class Valley (val width: Int, val height: Int, val start: Int, val end: Int, var init: MutableList<Pair<Point, Direction>>) { var blizzards = Array<MutableList<Direction>> (width * height) { mutableListOf<Direction> () } private set fun toIndex (x: Int, y: Int): Int = x + y * width fun toIndex (point: Point): Int = toIndex (point.x, point.y) fun toPoint (index: Int): Point = Point (index % width, index / width) fun getBlizzards (x: Int, y: Int): MutableList<Direction> = blizzards[toIndex (x, y)] as MutableList<Direction> fun getBlizzards (point: Point): MutableList<Direction> = blizzards[toIndex (point)] as MutableList<Direction> var time = 0 val startPoint = Point (start, -1) val endPoint = Point (end, height) var positions = mutableListOf<Point> () fun isValid (p: Point): Boolean = p.x >= 0 && p.y >= 0 && p.x < width && p.y < height init { for (blizzard in init) { val (point, direction) = blizzard getBlizzards (point).add (direction) } positions.add (Point (start, -1)) } /** * Returns all the possible moves from the specified point including * remaining stationary at that point. */ fun possibleMoves (pos: Point): List<Point> { val list = mutableListOf<Point> (pos) list.add (pos.move (Direction.UP)) list.add (pos.move (Direction.DOWN)) list.add (pos.move (Direction.LEFT)) list.add (pos.move (Direction.RIGHT)) return list.filter { isValid (it) || (it == startPoint) || (it == endPoint) } } /** * Filters all the possible moves for those that are legal by * way of not being under threat from an adjacent blizzard. */ fun legalMoves (possible: List<Point>): List<Point> { val legal = mutableListOf<Point> () outer@for (point in possible) { if (point == startPoint || point == endPoint) { legal.add(point) } else { for (dir in Direction.values()) { val threat = point.move (dir, width, height) if (blizzards[toIndex (threat)].contains(dir.invert)) { continue@outer } } legal.add (point) } } return legal } fun round () { val newPositions = mutableListOf<Point> () for (pos in positions) { val legal = legalMoves (possibleMoves (pos)) for (move in legal) { if (! newPositions.contains (move)) { newPositions.add (move) } } } tick () positions = newPositions return } fun tick () { val temp = Array<MutableList<Direction>> (width * height) { mutableListOf<Direction> () } for (y in 0 until height) { for (x in 0 until width) { val point = Point (x, y) val dirs = getBlizzards (x, y) for (dir in dirs) { val updated = point.move (dir, width, height) temp[toIndex(updated)].add(dir) } } } blizzards = temp time++ return } fun render (f: StringBuffer.(Point) -> Unit): String { val wall = '#' val ingress: StringBuffer.(Int, Boolean) -> Unit = { which, isStart -> append(wall) for (i in 0 until width) { if (i == which) { val point = if (isStart) Point (start, -1) else Point (end, height) f (point) } else { append(wall) } } append(wall) append("\n") } return StringBuffer ().apply { append ("Valley dim=($width x $height), pos=${positions.size}, time=$time\n") ingress (start, true) for (y in 0 until height) { append ('#') for (x in 0 until width) { val p = Point (x, y) f (p) } append ("#\n") } ingress (end, false) }.toString () } fun dump () = println (toString ()) override fun toString(): String { return render { p -> if (positions.contains (p)) { append('E') } else if (p == startPoint || p == endPoint) { append ('.') } else { val blizzards = getBlizzards (p) append (when (blizzards.size) { 0 -> '.' 1 -> blizzards[0].encoded in 2 .. 9 -> "${blizzards.size}"[0] else -> 'B' }) } } } companion object { fun parse (input: String): Valley { val strs = input.trim ().split ("\n") val width = strs.first ().length - 2 val height = strs.size - 2 val start = strs.first().indexOf ('.') - 1 val end = strs.last().indexOf ('.') - 1 val blizzards = mutableListOf<Pair<Point, Direction>> () for (i in 1 until strs.size - 1) { val y = i - 1 val str = strs[i].substring (1, strs[i].length - 1) for (x in str.indices) { val c = str[x] if (c != '.') { val dir = Direction.values().first { it.encoded == c } blizzards.add (Pair (Point (x, y), dir)) } } } return Valley (width, height, start, end, blizzards) } } } fun loadValley (example: Boolean): Valley { val input = readInput (24, example) return Valley.parse (input) } fun main (args:Array<String>) { val example = true val valley = loadValley (example) valley.dump () return }
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
7,208
advent_of_code_2022
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day02.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part2A : PartSolution() { lateinit var commands: List<Command> override fun parseInput(text: String) { val lines = text.trimEnd().split("\n") commands = lines.map { Command(it) } } override fun compute(): Int { var depth = 0 var pos = 0 for (command in commands) { when (command.direction) { Direction.FORWARD -> pos += command.count Direction.DOWN -> depth += command.count Direction.UP -> depth -= command.count } } return pos * depth } override fun getExampleAnswer(): Int { return 150 } enum class Direction { FORWARD, DOWN, UP } data class Command(val direction: Direction, val count: Int) private fun Command(line: String): Command { val parts = line.split(" ") val dir = Direction.valueOf(parts[0].uppercase()) return Command(dir, parts[1].toInt()) } } class Part2B : Part2A() { override fun compute(): Int { var aim = 0 var depth = 0 var pos = 0 for (command in commands) { when (command.direction) { Direction.FORWARD -> { pos += command.count depth += aim * command.count } Direction.DOWN -> aim += command.count Direction.UP -> aim -= command.count } } return pos * depth } override fun getExampleAnswer(): Int { return 900 } } fun main() { Day(2021, 2, Part2A(), Part2B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
1,733
advent-of-code-kotlin
MIT License
src/main/kotlin/icfp2019/analyzers/WeightedBoardGraphAnalyzer.kt
godaddy-icfp
186,746,222
false
{"JavaScript": 797310, "Kotlin": 116879, "CSS": 9434, "HTML": 5859, "Shell": 70}
package icfp2019.analyzers import icfp2019.Cache import icfp2019.core.Analyzer import icfp2019.model.* import org.jgrapht.Graph import org.jgrapht.graph.DefaultEdge typealias WeightFunction<V> = (node1: V) -> (node2: V) -> Double fun <V> byState(boardStates: BoardNodeStates, locationFor: (V) -> Point): WeightFunction<V> = { n1 -> val n1State = locationFor(n1).lookupIn(boardStates) when { n1State.isWrapped -> { _ -> 1.5 } n1State.hasBooster -> { _ -> 0.01 } else -> { n2 -> val n2State = locationFor(n2).lookupIn(boardStates) when { n2State.isWrapped -> 1.5 n2State.hasBooster -> 0.01 else -> 1.0 } } } } infix fun <V, E> Graph<V, E>.withWeights(weight: WeightFunction<V>): Graph<V, E> { val simpleGraph = this.copy(weighted = true) simpleGraph.edgeSet().forEach { edge -> val nodes = simpleGraph(edge) simpleGraph.setEdgeWeight( edge, weight(nodes.source)(nodes.target) ) } return simpleGraph } data class EdgeVertices<V>(val source: V, val target: V) fun <V, E> Graph<V, E>.getEdgeVertices(edge: E): EdgeVertices<V> { return EdgeVertices(getEdgeSource(edge), getEdgeTarget(edge)) } object WeightedBoardGraphAnalyzer : Analyzer<Graph<BoardCell, DefaultEdge>> { private val cache = Cache.forGameState { state -> val copy = BoardCellsGraphAnalyzer.cache(state.board()).copy(weighted = true) copy withWeights byState(state.boardState()) { it.point } } override fun analyze(initialState: GameState): (robotId: RobotId, state: GameState) -> Graph<BoardCell, DefaultEdge> { return { _, state -> cache(state) } } }
13
JavaScript
12
0
a1060c109dfaa244f3451f11812ba8228d192e7d
1,746
icfp-2019
The Unlicense
src/Day03_part2.kt
rosyish
573,297,490
false
{"Kotlin": 51693}
fun main() { fun getElementPriority(ch: Char): Int { return when (ch) { in 'a'..'z' -> 1 + (ch - 'a') in 'A'..'Z' -> 27 + (ch - 'A') else -> throw IllegalArgumentException("Character not a letter") } } fun findCommonElement(input: List<String>): Char { val commonItems = input .map { str -> str.toSet() } .reduce() { a, b -> a.intersect(b) } return if (commonItems.size == 1) commonItems.first() else throw IllegalArgumentException("Sets of 3 have more than a single common item") } val result = readInput("Day03_input") .asSequence() .windowed(size = 3, step = 3) { getElementPriority(findCommonElement(it)) }.sum() println(result) }
0
Kotlin
0
2
43560f3e6a814bfd52ebadb939594290cd43549f
844
aoc-2022
Apache License 2.0
test/leetcode/WordSearch.kt
andrej-dyck
340,964,799
false
null
package leetcode import lib.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.* import org.junit.jupiter.params.* import org.junit.jupiter.params.converter.* import org.junit.jupiter.params.provider.* /** * https://leetcode.com/problems/word-search/ * * 79. Word Search * [Medium] * * Given an m x n board and a word, find if the word exists in the grid. * * The word can be constructed from letters of sequentially adjacent cells, * where "adjacent" cells are horizontally or vertically neighboring. * The same letter cell may not be used more than once. * * Constraints: * - m == board.length * - n = board[i].length * - 1 <= m, n <= 200 * - 1 <= word.length <= 10^3 * - board and word consists only of lowercase and uppercase English letters. */ typealias Board = Array<String> typealias Coordinates = Sequence<XY> typealias Path = Coordinates fun findWordsOnBoard(board: Board, words: List<String>) = words.filter { boardContainsWord(board, it) } fun boardContainsWord(board: Board, word: String) = board.findPath(word).any() // for leetcode fun Board.findPath(word: String, xys: Coordinates = xys(), path: Path = emptySequence()): Path = if (word.isEmpty()) path else xys .filter { word.first() == maybeValue(it) && it !in path } .map { findPath(word.drop(1), it.neighbors(), path + it) } .find { it.any() } .orEmpty() private fun Board.xys() = asSequence().flatMapIndexed { y, r -> r.mapIndexed { x, _ -> XY(x, y) } } private fun Board.maybeValue(xy: XY) = getOrNull(xy.y)?.getOrNull(xy.x) data class XY(val x: Int, val y: Int) { fun neighbors() = sequenceOf(right(), down(), up(), left()) fun up() = copy(y = y - 1) fun right() = copy(x = x + 1) fun down() = copy(y = y + 1) fun left() = copy(x = x - 1) } /** * Unit tests */ class WordsInsideARectangleTest { @ParameterizedTest @CsvSource( "[KOTE, NULE, AFIN]; [Kotlin, fun, file, line, null]; [KOTLIN, FUN, FILE, LINE]", "[ABCE, SFCS, ADEE]; [ABCCED, SEE, ABCB]; [ABCCED, SEE]", // ABCB can only be found by visiting a cell twice delimiter = ';' ) fun `finds words on board by finding a path of adjacent cells starting anywhere`( @ConvertWith(StringArrayArg::class) board: Array<String>, @ConvertWith(StringArrayArg::class) words: Array<String>, @ConvertWith(StringArrayArg::class) expectedWords: Array<String> ) { assertThat( findWordsOnBoard(board, words.map { it.uppercase() }) ).containsExactlyElementsOf( expectedWords.toList() ) } }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
2,648
coding-challenges
MIT License
dcp_kotlin/src/main/kotlin/dcp/day312/day312.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day312 // day312.kt // By <NAME>, 2020. import kotlin.math.max /** * This is sequence A052980 in the Online Encyclopedia of Integer Sequences: * * https://oeis.org/A052980 * * and is a deceptively difficult problem of dynamic programming (i.e. using memoization to make recurrence relations * feasible to solve). My initial attempt was to tabulate all unique tilings of the board up to symmetry and sub-boards * but this proceeds until 6: * A A B B C C * A D D E E C * which is indivisible into smaller tilings, and that solution was too complicated what with symmetries. * * Consider the case of placing the last tile. We have four distinct cases: * * 1. A vertical domino: * A * A * * 2. A horizontal domino: * A A * * 3. A tromino extending on the top: * A A * A * * 4. A tromino extending on the bottom: * A * A A * * We now want to derive recurrence relations to describe these cases. * Let F(N) be the number of distinct tilings that can tile a 2xN board. * We also need the cases: * X X and X * X X X * Let G(N) be the number of distinct tilings that tile a 2xN board with a square jutting out. * We can reduce this to the number of distinct tilings with a square jutting out the top, and multiply by 2 to get * the symmetry. * * Then we get that: * F(N) = F(N-1) + F(N-2) + 2G(N-2). * because we can either have one vertical domino as our previous move (option 1), one horizontal domino as our * previous move (option 2 as it reduces the size of the board by 2), or one of the tromino situations (which * reduces the board by 2). * * The base cases for F are: * A or A A * A B B * so F(1) = 1 and F(2) = 2. * * We now need a recurrence relation and the base cases for G. * We have two situations in which this may happen (four through symmetry, hence the multiple of 2 in the * recurrence relation for F): * X A A or X A A * X X X A * * In the first case, a domino was last placed, leaving us a 2XN rectangle with a jut with G(N-1) possible tilings. * In the second case, a tromino was last placed, leaving us a 2xN rectangle with F(N-1) possible tilings. * * Thus, we have that: * G(N) = F(N-1) + G(N-1) * * The base cases for G are: * A A or A B B or A B B * A A A A B * so G(1) = 1 and G(2) = 2. * * In both cases, there is 1 way to cover a 2x0 board (i.e. nothing), so that is also a base case. * * This gives us all we need to calculate the recurrences. */ fun coverings(n: Int): Int { // We need mutable lists to store the intermediate values. val f = MutableList(max(3, n+1)){0} f[0] = 1 f[1] = 1 f[2] = 2 val g = MutableList(max(3,n+1)){0} g[0] = 1 g[1] = 1 g[2] = 2 for (i in 3 until n+1) { g[i] = g[i-1] + f[i-1] f[i] = f[i-1] + f[i-2] + 2 * g[i-2] } return f[n] } fun main() { for (i in 0 until 15) println("$i -> ${coverings(i)}") }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
3,175
daily-coding-problem
MIT License
src/Day01.kt
alex-rieger
573,375,246
false
null
fun getCaloriesPerElfList(input: List<String>): List<Int> { var buffer = 0 return input.fold(mutableListOf<Int>()) { acc, calories -> if (calories.isEmpty()) { acc.add(buffer) buffer = 0 } else { buffer = buffer.plus(calories.toInt()) } acc } } fun main() { fun part1(input: List<String>): Int { return getCaloriesPerElfList(input).max() } fun part2(input: List<String>): Int { return getCaloriesPerElfList(input).sorted().takeLast(3).sum() } // // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") // check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
77de0265ff76160e7ea49c9b9d31caa1cd966a46
804
aoc-2022-kt
Apache License 2.0
src/main/kotlin/com/leetcode/top100LikedQuestions/easy/maxim_depth_of_binary_tree/Main.kt
frikit
254,842,734
false
null
package com.leetcode.top100LikedQuestions.easy.maxim_depth_of_binary_tree fun main() { println("Test case 1:") val t1 = TreeNode(1) run { val leftFirstLeaf = TreeNode(3) val rightFirstLeaf = TreeNode(2) val leftSecondLeaf = TreeNode(5) val rightSecondLeaf = null //set nodes t1.left = leftFirstLeaf t1.right = rightFirstLeaf leftFirstLeaf.left = leftSecondLeaf leftFirstLeaf.right = rightSecondLeaf } println(Solution().maxDepth(t1)) println() println("Test case 2:") println(Solution().maxDepth(null)) println() } /** * 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 maxDepth(root: TreeNode?, currentDepth: Int = 1): Int { if (root == null) return 0 if (root.left == null && root.right == null) return currentDepth val leftSide = if (root.left != null) maxDepth(root.left, currentDepth + 1) else 0 val rightSide = if (root.right != null) maxDepth(root.right, currentDepth + 1) else 0 return Math.max(leftSide, rightSide) } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null }
0
Kotlin
0
0
dda68313ba468163386239ab07f4d993f80783c7
1,372
leet-code-problems
Apache License 2.0
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day04/Day04.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day04 import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input04-test.txt" const val FILENAME = "input04.txt" fun main() { val pairs = readLines(2022, FILENAME) .map(String::toElfPair) val part1 = pairs.count { it.fullyOverlaps() } println(part1) val part2 = pairs.count { it.overlaps() } println(part2) } data class SectionRange(val from: Int, val to: Int) { fun fullyOverlapsWith(other: SectionRange): Boolean { if (this.from>=other.from && this.to<=other.to) return true if (other.from>=this.from && other.to<=this.to) return true return false } fun overLapsWith(other: SectionRange): Boolean { if (this.to < other.from) return false if (other.to < this.from) return false return true } } data class ElfPair(val first: SectionRange, val second: SectionRange) { fun fullyOverlaps(): Boolean = first.fullyOverlapsWith(second) fun overlaps(): Boolean = first.overLapsWith(second) } fun String.toSectionRange(): SectionRange { val parts = this.split("-") return SectionRange(parts[0].toInt(), parts[1].toInt()) } fun String.toElfPair(): ElfPair { val parts = this.split(",") return ElfPair(parts[0].toSectionRange(), parts[1].toSectionRange()) }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,223
advent-of-code
Apache License 2.0
facebook/2019/round1/1/main.kt
seirion
17,619,607
false
{"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294}
import java.util.* fun main(args: Array<String>) { val t = readLine()!!.toInt() repeat(t) { print("Case #${it + 1}: ") solve() } } data class T(val a: Int, val b: Int, val c: Int) fun solve() { val (n, m) = readLine()!!.split(" ").map { it.toInt() } val input = ArrayList<T>() val dist = ArrayList<IntArray>() repeat(n + 1) { dist.add(IntArray(n + 1) { 1000000000 } ) } repeat(m) { val (a, b, c) = readLine()!!.split(" ").map { it.toInt() } input.add(T(a, b, c)) dist[a][b] = c dist[b][a] = c } (1..n).forEach { i -> (1..n).forEach { j -> (1..n).forEach { k -> dist[j][k] = Math.min(dist[j][k], dist[j][i] + dist[i][k]) } } } input.forEach { if (dist[it.a][it.b] != it.c) { println("Impossible") return } } println(m) input.forEach { println("${it.a} ${it.b} ${it.c}") } }
0
C++
4
4
a59df98712c7eeceabc98f6535f7814d3a1c2c9f
1,008
code
Apache License 2.0
src/main/kotlin/year2022/Day15.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2022 import utils.Direction.* import utils.Point2D class Day15(input: String) { data class Sensor(val position: Point2D, val beacon: Point2D) { val coverage = position.manhattan(beacon) } private val regex = """Sensor at x=(.*), y=(.*): closest beacon is at x=(.*), y=(.*)""".toRegex() private val sensors = input.lines() .map { regex.find(it)!!.groupValues.drop(1).map(String::toInt) } .map { (xs, ys, xb, yb) -> Sensor(Point2D(xs, ys), Point2D(xb, yb)) } private val xl = sensors.minOf { minOf(it.position.x, it.beacon.x, it.position.x - it.coverage) } private val xr = sensors.maxOf { maxOf(it.position.x, it.beacon.x, it.position.x + it.coverage) } fun part1(row: Int) = (xl..xr).count { col -> Point2D(col, row).let { point -> sensors.any { it.beacon != point && it.position.manhattan(point) <= it.coverage } } } fun part2(limit: Int): Long { fun check(point: Point2D) = point.x in (0..limit) && point.y in (0..limit) && sensors.none { it.position.manhattan(point) <= it.coverage } sensors.forEach { sensor -> with(sensor.position) { listOf( move(dx = -sensor.coverage - 1), move(dy = -sensor.coverage - 1), move(dx = sensor.coverage + 1), move(dy = sensor.coverage + 1), move(dx = -sensor.coverage - 1) ).windowed(2) .zip(listOf(RIGHT_UP, RIGHT_DOWN, LEFT_DOWN, LEFT_UP)) .forEach { (points, dir) -> var (current, target) = points while (current != target) { if (check(current)) { return current.x.toLong() * 4000000 + current.y.toLong() } current = current.move(dir) } } } } error("Should have found a single one!") } }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
2,137
aoc-2022
Apache License 2.0
src/main/kotlin/days/aoc2022/Day13.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2022 import days.Day class Day13 : Day(2022,13) { override fun partOne(): Any { return calculateSumOfCountOfPairsInCorrectOrder(inputList) } override fun partTwo(): Any { return calculateDecoderKey(inputList) } fun calculateSumOfCountOfPairsInCorrectOrder(input: List<String>): Int { return input .filter { it.isNotEmpty() } .windowed(2, 2) .mapIndexed { index, packets -> val left = parsePacket(packets.first()) val right = parsePacket(packets.last()) if (left <= right) index + 1 else 0 }.sum() } fun calculateDecoderKey(input: List<String>): Int { val packets = input.filter { it.isNotEmpty() }.map { parsePacket(it) } return packets .plus(parsePacket("[[2]]")) .plus(parsePacket("[[6]]")) .sorted() .mapIndexed { index, packet -> if (packet.name == "[[2]]" || packet.name == "[[6]]") { index + 1 } else { 1 } }.reduce { acc, i -> acc * i } } private fun parsePacket(line: String): Packet { val packet = PacketList(name = line) var current: PacketList? = packet var number = "" line.drop(1).forEach { c -> when (c) { '[' -> { val newList = PacketList(name = null, parent = current) current?.children?.add(newList) current = newList } ']' -> { if (number.isNotEmpty()) { current?.children?.add(PacketInteger(number.toInt())) number = "" } current = current?.parent } ',' -> { if (number.isNotEmpty()) { current?.children?.add(PacketInteger(number.toInt())) number = "" } } in '0'..'9' -> { number += c } } } return packet } open class Packet(val name: String? = null) : Comparable<Packet> { override fun compareTo(other: Packet): Int { if (this is PacketList && other is PacketList) { for (i in children.indices) { if (i in other.children.indices) { val result = children[i].compareTo(other.children[i]) if (result != 0) { return result } } } return children.lastIndex.compareTo(other.children.lastIndex) } else if (this is PacketInteger && other is PacketInteger) { return value.compareTo(other.value) } else { val temp = PacketList(null) return if (this is PacketList) { temp.children.add(other) compareTo(temp) } else { temp.children.add(this) temp.compareTo(other) } } } } class PacketList(name: String?, val parent: PacketList? = null) : Packet(name) { val children = mutableListOf<Packet>() } class PacketInteger(val value: Int) : Packet() }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
3,519
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/InterleavingString.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 /** * 97. Interleaving String * @see <a href="https://leetcode.com/problems/interleaving-string/">Source</a> */ fun interface InterleavingStringStrategy { operator fun invoke(s1: String, s2: String, s3: String): Boolean } class InterleavingStringBruteForce : InterleavingStringStrategy { override operator fun invoke(s1: String, s2: String, s3: String): Boolean { return Triple(s1, s2, s3).isInterleave(0, 0, "") } private fun Triple<String, String, String>.isInterleave(i: Int, j: Int, res: String): Boolean { if (res == third && i == first.length && j == second.length) return true var ans = false if (i < first.length) ans = ans or isInterleave(i + 1, j, res + first[i]) if (j < second.length) ans = ans or isInterleave(i, j + 1, res + second[j]) return ans } } // Recursion with memoization class InterleavingStringRecursionWithMemo : InterleavingStringStrategy { override operator fun invoke(s1: String, s2: String, s3: String): Boolean { val memo = Array(s1.length) { IntArray(s2.length) } for (i in s1.indices) { for (j in s2.indices) { memo[i][j] = -1 } } return Triple(s1, s2, s3).isInterleave(0, 0, 0, memo) } private fun Triple<String, String, String>.isInterleave( i: Int, j: Int, k: Int, memo: Array<IntArray>, ): Boolean { if (i == first.length) { return second.substring(j) == third.substring(k) } if (j == second.length) { return first.substring(i) == third.substring(k) } if (memo[i][j] >= 0) { return memo[i][j] == 1 } var ans = false val isThirdEqualFirst = third[k] == first[i] val isThirdEqualSecond = third[k] == second[j] val thirdToFirstPredicate = isThirdEqualFirst && isInterleave(i + 1, j, k + 1, memo) val thirdToSecondPredicate = isThirdEqualSecond && isInterleave(i, j + 1, k + 1, memo) if (thirdToFirstPredicate || thirdToSecondPredicate) { ans = true } memo[i][j] = if (ans) 1 else 0 return ans } } // Using 2D Dynamic Programming class InterleavingString2D : InterleavingStringStrategy { override operator fun invoke(s1: String, s2: String, s3: String): Boolean { return isInterleave(s1, s2, s3) } private fun isInterleave(s1: String, s2: String, s3: String): Boolean { if (s3.length != s1.length + s2.length) { return false } val dp = Array(s1.length + 1) { BooleanArray( s2.length + 1, ) } for (i in 0..s1.length) { for (j in 0..s2.length) { when { i == 0 && j == 0 -> { dp[i][j] = true } i == 0 -> { dp[i][j] = dp[i][j - 1] && s2[j - 1] == s3[i + j - 1] } j == 0 -> { dp[i][j] = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1] } else -> { dp[i][j] = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1] || dp[i][j - 1] && s2[j - 1] == s3[i + j - 1] } } } } return dp[s1.length][s2.length] } } // Using 1D Dynamic Programming class InterleavingString1D : InterleavingStringStrategy { override operator fun invoke(s1: String, s2: String, s3: String): Boolean { return isInterleave(s1, s2, s3) } private fun isInterleave(s1: String, s2: String, s3: String): Boolean { if (s3.length != s1.length + s2.length) { return false } val dp = BooleanArray(s2.length + 1) for (i in 0..s1.length) { for (j in 0..s2.length) { when { i == 0 && j == 0 -> { dp[j] = true } i == 0 -> { dp[j] = dp[j - 1] && s2[j - 1] == s3[i + j - 1] } j == 0 -> { dp[j] = dp[j] && s1[i - 1] == s3[i + j - 1] } else -> { dp[j] = dp[j] && s1[i - 1] == s3[i + j - 1] || dp[j - 1] && s2[j - 1] == s3[i + j - 1] } } } } return dp[s2.length] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,213
kotlab
Apache License 2.0
src/main/kotlin/g2401_2500/s2492_minimum_score_of_a_path_between_two_cities/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2492_minimum_score_of_a_path_between_two_cities // #Medium #Depth_First_Search #Breadth_First_Search #Graph #Union_Find // #2023_07_05_Time_929_ms_(91.67%)_Space_109.9_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun minScore(n: Int, roads: Array<IntArray>): Int { val parent = IntArray(n + 1) val rank = IntArray(n + 1) for (i in 1..n) { parent[i] = i rank[i] = Int.MAX_VALUE } var ans = Int.MAX_VALUE for (road in roads) { union(parent, rank, road[0], road[1], road[2]) } val u: Int = find(parent, 1) val v: Int = find(parent, n) if (u == v) { ans = rank[u] } return ans } private fun find(parent: IntArray, x: Int): Int { return if (x == parent[x]) x else find(parent, parent[x]).also { parent[x] = it } } private fun union(parent: IntArray, rank: IntArray, u: Int, v: Int, w: Int) { var u = u var v = v u = find(parent, u) v = find(parent, v) if (rank[u] <= rank[v]) { parent[v] = u rank[u] = Math.min(rank[u], w) } else { parent[u] = v rank[v] = Math.min(rank[v], w) } return } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,310
LeetCode-in-Kotlin
MIT License
src/main/kotlin/SudokuSolver.kt
Constanze3
749,840,989
false
{"Kotlin": 12466}
package org.example /** * A SudokuSolver can be used to find solutions of a certain sudoku puzzle state. * * @constructor creates a new solver for the given sudoku */ class SudokuSolver(sudoku: Sudoku) { private val sudoku = Sudoku(sudoku) private val workingSudoku = Sudoku(sudoku) private val solutions = mutableListOf<Sudoku>() /** * Finds and returns all solutions of the sudoku puzzle state provided to the solver. * * @return a list of solutions in the order they were found (an empty list if there are no solutions) */ fun getAllSolutions(): MutableList<Sudoku> { while (solutionGenerator.hasNext()) { solutions.add(solutionGenerator.next()) } return solutions } /** * Returns a solution iterator for the solutions of the sudoku puzzle state provided to the solver. * * Use this if finding all solutions is not necessary. * * @return a solution iterator for the solutions of the sudoku puzzle state */ fun getSolutionIterator(): Iterator<Sudoku> { return iterator { var i = 0 while (true) { if (i < solutions.size) { yield(solutions[i]) i++ } else { if (solutionGenerator.hasNext()) { val solution = solutionGenerator.next() solutions.add(solution) i++ yield(solution) } else { break } } } } } private val solutionGenerator = solve(this.sudoku.data.flatten().filter { cell -> cell.value == null }) private fun solve(emptyCells: List<SudokuCell>): Iterator<Sudoku> = iterator { if (emptyCells.isEmpty()) { if (workingSudoku.isSolved()) { yield(Sudoku(workingSudoku)) } } else { val currentCell = emptyCells[0] val x = currentCell.position.x val y = currentCell.position.y for (v in 1..9) { workingSudoku.data[x][y].value = v if (workingSudoku.isValidCell(Position2D(x, y))) { yieldAll(solve(emptyCells.drop(1))) } } workingSudoku.data[x][y].value = null } } }
0
Kotlin
0
0
d0543fbf318fcee39691339ec89b3336d5a06b49
2,433
simple-sudoku-solver
MIT License
src/Day21.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
sealed interface Node21 { fun calc(): Long fun shouldEqual(other: Long): Long? data class Cont(val int: Long) : Node21 { override fun calc(): Long = int override fun shouldEqual(other: Long) = null } data class Expression(val el1: Node21, val op: String, val el2: Node21) : Node21 { override fun calc(): Long { val calc1 = el1.calc() val calc2 = el2.calc() return when (op) { "+" -> calc1 + calc2 "-" -> calc1 - calc2 "*" -> calc1 * calc2 "/" -> calc1 / calc2 "=" -> { val try1 = el1.shouldEqual(calc2) if (try1 != null) return try1 val try2 = el2.shouldEqual(calc1) if (try2 != null) return try2 if (calc1 == calc2) 1L else 0L } else -> error("Operation $op is not supported") } } override fun shouldEqual(other: Long): Long? { val calc1 = el1.calc() val calc2 = el2.calc() when (op) { "+" -> { val try1 = el1.shouldEqual(other - calc2) if (try1 != null) return try1 val try2 = el2.shouldEqual(other - calc1) if (try2 != null) return try2 return null } "-" -> { val try1 = el1.shouldEqual(other + calc2) if (try1 != null) return try1 val try2 = el2.shouldEqual(calc1 - other) if (try2 != null) return try2 return null } "*" -> { val try1 = el1.shouldEqual(other / calc2) if (try1 != null) return try1 val try2 = el2.shouldEqual(other / calc1) if (try2 != null) return try2 return null } "/" -> { val try1 = el1.shouldEqual(other * calc2) if (try1 != null) return try1 val try2 = el2.shouldEqual(calc1 / other) if (try2 != null) return try2 return null } } return null } } data class Ref(val name: String, val provider: (String) -> Node21) : Node21 { override fun calc(): Long = provider(name).calc() override fun shouldEqual(other: Long): Long? { return if (name != "humn") provider(name).shouldEqual(other) else other } } } fun main() { fun String.toNode(provider: (String) -> Node21): Pair<String, Node21> { fun String.internalToNode(): Node21 { val sec = toLongOrNull() return if (sec == null) { Node21.Ref(this, provider) } else Node21.Cont(sec) } val tokens = split(' ', ':').filterNot(String::isBlank) val name = tokens[0] return if (tokens.size == 2) { name to tokens[1].internalToNode() } else name to Node21.Expression(tokens[1].internalToNode(), tokens[2], tokens[3].internalToNode()) } fun part1(input: List<String>): Long { val map = hashMapOf<String, Node21>() input .filterNot { it.isBlank() } .map { el -> el.toNode { map[it]!! } } .toMap(map) return map["root"]!!.calc() } fun part2(input: List<String>): Long { val map = hashMapOf<String, Node21>() input .filterNot { it.isBlank() } .map { if (it.startsWith("root:")) it.replace('+', '=') else it } .map { el -> el.toNode { map[it]!! } } .toMap(map) return map["root"]!!.calc() } val testInput = readInput("Day21_test") check(part1(testInput) == 152L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
4,095
aoc-2022
Apache License 2.0
src/main/kotlin/de/skyrising/aoc/aoc.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc import java.util.* import kotlin.math.sqrt const val RUNS = 10 const val WARMUP = 5 const val MEASURE_ITERS = 10 const val BENCHMARK = false fun buildFilter(args: Array<String>): PuzzleFilter { if (args.isEmpty()) return PuzzleFilter.all().copy(latestOnly = true) if (args[0] == "all") return PuzzleFilter.all() val year = args[0].toInt() val filter = PuzzleFilter.year(year) if (args.size <= 1) return filter.copy(latestOnly = true) if (args[1] == "all") return filter return PuzzleFilter(sortedSetOf(PuzzleDay(year, args[1].toInt()))) } fun main(args: Array<String>) { val filter = buildFilter(args) registerFiltered(filter) val puzzlesToRun = allPuzzles.filter(filter) for (puzzle in puzzlesToRun) { val input = puzzle.getRealInput() try { if (BENCHMARK) { input.benchmark = true var result: Any? = null val allTimes = DoubleArray(WARMUP + MEASURE_ITERS) { a -> measure(RUNS) { b -> if (a == WARMUP + MEASURE_ITERS - 1 && b == RUNS - 1) input.benchmark = false input.use { puzzle.runPuzzle(input).also { result = it } } } } val times = allTimes.copyOfRange(WARMUP, allTimes.size) val avg = times.average() val stddev = sqrt(times.map { (it - avg) * (it - avg) }.average()) println( String.format( Locale.ROOT, "%d/%02d/%d.%d %-32s: %16s, %s ± %4.1f%%", puzzle.day.year, puzzle.day.day, puzzle.part, puzzle.index, puzzle.name, result, formatTime(avg), stddev * 100 / avg ) ) } else { val start = System.nanoTime() val result = input.use { puzzle.runPuzzle(input) } val time = (System.nanoTime() - start) / 1000.0 println( String.format( Locale.ROOT, "%d/%02d/%d.%d %-32s: %16s, %s ± ?", puzzle.day.year, puzzle.day.day, puzzle.part, puzzle.index, puzzle.name, result, formatTime(time) ) ) } } catch (e: Exception) { println( String.format( Locale.ROOT, "%d/%02d/%d.%d %-32s: %16s, %s", puzzle.day.year, puzzle.day.day, puzzle.part, puzzle.index, puzzle.name, e.javaClass.simpleName, e.message ) ) e.printStackTrace() } } println("Done") } private fun formatTime(us: Double): String { if (us < 1000) return "%7.3fµs".format(us) val ms = us / 1000 if (ms < 1000) return "%7.3fms".format(ms) return "%7.3fs ".format(ms / 1000) }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
3,377
aoc
MIT License
src/2023/Day15.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2023` import java.io.File import java.util.* fun main() { Day15().solve() } class Day15 { val input1 = """ rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7 """.trimIndent() val input2 = """ """.trimIndent() fun hash(s: String): Int { var r = 0 s.forEach { r = ((r + it.code)*17 )%256 } return r } fun solve() { val f = File("src/2023/inputs/day15.in") val s = Scanner(f) // val s = Scanner(input1) // val s = Scanner(input2) var sum = 0 var sum1 = 0L var lineix = 0 val lines = mutableListOf<String>() while (s.hasNextLine()) { lineix++ val line = s.nextLine().trim() if (line.isEmpty()) { continue } lines.add(line) } val cmds = lines[0].split(',') sum = cmds.map { val r = hash(it) r }.sum() val m = mutableMapOf<Int, MutableMap<String, Pair<Int, Int>>>() (0..255).forEach{m[it] = mutableMapOf() } var i = 0 cmds.forEach { val t = it.split(Regex("[-=]")) val label = t[0] val h = hash(label) if (it[label.length] == '=') { val f = t[1].toInt() if (m[h]!!.contains(label)) { val i0 = m[h]!![label]!!.second m[h]!![label] = f to i0 } else { m[h]!![label] = f to i++ } } else { m[h]!!.remove(label) } } m.forEach { boxIx, m1 -> val r0 = if (m1.isEmpty()) { 0 } else { val r = m1.values.sortedBy { it.second }.mapIndexed { ix, it1 -> val r1 = (ix + 1).toLong() * (boxIx + 1) * (it1.first) r1 }.sum() r } sum1 += r0 } print("$sum $sum1\n") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
2,146
advent-of-code
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year18/Day07.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year18 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.asPair fun PuzzleSet.day7() = puzzle(day = 7) { val pairs = inputLines.map { it.split(" ") .filter { p -> p.length == 1 } .map { p -> p.singleOrNull() ?: error("?") }.asPair() } val rules = pairs.groupBy { it.second }.mapValues { (_, v) -> v.map { it.first } } val possibleTasks = pairs.flatMap { it.toList() }.distinct().sorted() fun partOne() { val tasks = possibleTasks.toMutableList() val done = mutableListOf<Char>() while (tasks.isNotEmpty()) { val task = tasks.first { done.containsAll(rules[it] ?: emptyList()) } done += task tasks -= task } partOne = done.joinToString("") } fun partTwo() { val tasks = possibleTasks.toMutableList() val done = mutableListOf<Char>() data class WorkerInfo(val task: Char? = null, val doneAt: Int = 0) var seconds = 0 val workers = MutableList(5) { WorkerInfo() } while (tasks.isNotEmpty()) { workers.forEachIndexed { idx, (t, tDone) -> if (seconds < tDone) return@forEachIndexed tasks -= t ?: return@forEachIndexed done += t ?: return@forEachIndexed workers[idx] = WorkerInfo() } if (tasks.isEmpty()) break val currentTasks = workers.mapNotNull { it.task }.toHashSet() workers.forEachIndexed { idx, w -> if (w.task != null) return@forEachIndexed val task = tasks.firstOrNull { it !in currentTasks && done.containsAll(rules[it] ?: emptyList()) } ?: return@forEachIndexed currentTasks += task workers[idx] = WorkerInfo(task, seconds + (task - 'A') + 61) } seconds++ } partTwo = seconds.s() } partOne() partTwo() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,014
advent-of-code
The Unlicense
src/main/kotlin/Day12.kt
goblindegook
319,372,062
false
null
package com.goblindegook.adventofcode2020 import com.goblindegook.adventofcode2020.extension.plus import com.goblindegook.adventofcode2020.extension.times import com.goblindegook.adventofcode2020.extension.toIntOr import com.goblindegook.adventofcode2020.input.load import kotlin.math.PI import kotlin.math.absoluteValue import kotlin.math.cos import kotlin.math.sin fun main() { val instructions = load("/day12-input.txt") println(navigateShip(instructions)) println(navigateShipByWaypoint(instructions)) } fun navigateShip(instructions: String): Int = instructions .lines() .map { it.substring(0, 1) to (it.substring(1).toIntOr(0)) } .fold(0 to 0) { (distance, degrees), (command, value) -> when (command) { "S", "E" -> distance + value to degrees "N", "W" -> distance - value to degrees "F" -> distance + value * factor(degrees) to degrees "L" -> distance to degrees + value "R" -> distance to degrees - value else -> distance to degrees } }.first.absoluteValue fun navigateShipByWaypoint(instructions: String): Int = instructions .lines() .map { it.substring(0, 1) to (it.substring(1).toIntOr(0)) } .fold((0 to 0) to (10 to -1)) { (ship, waypoint), (command, value) -> when (command) { "S" -> ship to waypoint + (0 to value) "E" -> ship to waypoint + (value to 0) "N" -> ship to waypoint + (0 to -value) "W" -> ship to waypoint + (-value to 0) "F" -> ship + (waypoint * value) to waypoint "L" -> ship to waypoint.rotate(-value) "R" -> ship to waypoint.rotate(value) else -> ship to waypoint } }.first.let { (x, y) -> x.absoluteValue + y.absoluteValue } private inline val Int.radianValue: Double get() = this * PI / 180.0 private fun factor(deg: Int) = cos(deg.radianValue).toInt() - sin(deg.radianValue).toInt() private fun Pair<Int, Int>.rotate(deg: Int) = (this * cos(deg.radianValue).toInt()) + ((-second to first) * sin(deg.radianValue).toInt())
0
Kotlin
0
0
85a2ff73899dbb0e563029754e336cbac33cb69b
2,109
adventofcode2020
MIT License