path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day10.kt
sabercon
648,989,596
false
null
fun main() { fun countArrangements(jolts: List<Int>): Long { val cache = mutableMapOf<Int, Long>() fun countArrangementsFrom(index: Int): Long { if (index == jolts.lastIndex) return 1 if (index in cache) return cache[index]!! return (index + 1..jolts.lastIndex) .takeWhile { jolts[it] - jolts[index] <= 3 } .sumOf { countArrangementsFrom(it) } .also { cache[index] = it } } return countArrangementsFrom(0) } val input = readLines("Day10").map { it.toInt() }.sorted() val jolts = listOf(0) + input + (input.last() + 3) val diffs = jolts.zipWithNext { a, b -> b - a } println(diffs.count { it == 1 } * diffs.count { it == 3 }) countArrangements(jolts).println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
810
advent-of-code-2020
MIT License
src/aoc2022/Day12.kt
Playacem
573,606,418
false
{"Kotlin": 44779}
package aoc2022 import utils.readInput import java.util.* import kotlin.math.abs private object Day12 { data class Pos(val x: Int, val y: Int) data class ElevationMap(val elevation: Map<Pos, Int>, val startPos: Pos, val goalPos: Pos, val maxX: Int, val maxY: Int) fun reconstructPath(cameFrom: Map<Pos, Pos>, current: Pos): List<Pos> { val totalPath = mutableListOf(current) var tmp = current while (tmp in cameFrom.keys) { tmp = cameFrom[tmp]!! totalPath.add(0, tmp) } return totalPath } /** * Based on [the Wikipedia pseudo code for A* search algorithm](https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode) */ fun aStar( start: Pos, goal: Pos, estimate: (Pos) -> Double, provideNeighbors: (Pos) -> List<Pos>, distance: (Pos, Pos) -> Double ): List<Pos> { val openSet: PriorityQueue<Pos> = PriorityQueue { left, right -> (estimate(left) - estimate(right)).toInt() } openSet.add(start) val cameFrom: MutableMap<Pos, Pos> = mutableMapOf() val gScore: MutableMap<Pos, Double> = mutableMapOf() gScore[start] = 0.0 val fScore: MutableMap<Pos, Double> = mutableMapOf() fScore[start] = estimate(start) while (openSet.isNotEmpty()) { val current = openSet.remove() if (current == goal) { return reconstructPath(cameFrom, current) } val neighbors = provideNeighbors(current) for (neighbor in neighbors) { val tentativeGScore = gScore.getOrDefault(current, Double.POSITIVE_INFINITY) + distance(current, neighbor) if (tentativeGScore < gScore.getOrDefault(neighbor, Double.POSITIVE_INFINITY)) { cameFrom[neighbor] = current gScore[neighbor] = tentativeGScore fScore[neighbor] = tentativeGScore + estimate(neighbor) if (neighbor !in openSet) { openSet.add(neighbor) } } } } return listOf() } fun elevationSymbolToInt(symbol: Char): Int = when(symbol) { 'E' -> 26 'S' -> 1 in 'a'..'z' -> symbol.code - 'a'.code + 1 else -> error("Unknown symbol: $symbol") } fun parseInput(input: List<String>): ElevationMap { val elevation = mutableMapOf<Pos, Int>() var startPos: Pos? = null var goalPos: Pos? = null input.forEachIndexed { y, s -> s.forEachIndexed { x, char -> val pos = Pos(x, y) elevation[pos] = elevationSymbolToInt(char) when (char) { 'S' -> { startPos = pos } 'E' -> { goalPos = pos } } } } if (startPos == null || goalPos == null) { error("no start or goal found") } val maxX = input.first().length - 1 val maxY = input.size - 1 return ElevationMap(elevation, startPos!!, goalPos!!, maxX, maxY) } fun createNeighborProvider(elevationMap: ElevationMap): (Pos) -> List<Pos> { return { pos: Pos -> sequenceOf( Pos(pos.x - 1, pos.y), Pos(pos.x + 1, pos.y), Pos(pos.x, pos.y - 1), Pos(pos.x, pos.y + 1) ) .filter { it.x >= 0 } .filter { it.x <= elevationMap.maxX } .filter { it.y >= 0 } .filter { it.y <= elevationMap.maxY } .toList() } } fun createDistanceFunction(elevationMap: ElevationMap, goalPos: Pos): (Pos, Pos) -> Double { return { from, to -> val fromValue = elevationMap.elevation[from] val toValue = elevationMap.elevation[to] when { fromValue == null -> Double.POSITIVE_INFINITY toValue == null -> Double.POSITIVE_INFINITY toValue - fromValue > 1 -> Double.POSITIVE_INFINITY else -> abs(to.x - goalPos.x).toDouble() + abs(to.y - goalPos.y).toDouble() } } } fun createEstimate(goalPos: Pos): (Pos) -> Double { return { abs(it.x - goalPos.x).toDouble() + abs(it.y - goalPos.y).toDouble() } } } fun main() { val (year, day) = 2022 to "Day12" fun part1(input: List<String>): Int { val elevationMap = Day12.parseInput(input) val neighborProvider = Day12.createNeighborProvider(elevationMap) val distanceFunction = Day12.createDistanceFunction(elevationMap, elevationMap.goalPos) val estimate = Day12.createEstimate(elevationMap.goalPos) val res = Day12.aStar(elevationMap.startPos, elevationMap.goalPos, estimate, neighborProvider, distanceFunction) return res.size - 1 } fun part2(input: List<String>): Int { val elevationMap = Day12.parseInput(input) val neighborProvider = Day12.createNeighborProvider(elevationMap) val distanceFunction = Day12.createDistanceFunction(elevationMap, elevationMap.goalPos) val estimate = Day12.createEstimate(elevationMap.goalPos) val aLocations = elevationMap.elevation.filter { e -> e.value == 1 }.keys.toList() val minList = aLocations .map { Day12.aStar(it, elevationMap.goalPos, estimate, neighborProvider, distanceFunction) } .filter { it.isNotEmpty() } .minBy { it.size } return minList.size - 1 } val testInput = readInput(year, "${day}_test") val input = readInput(year, day) // test if implementation meets criteria from the description, like: check(part1(testInput) == 31) println(part1(input)) check(part2(testInput) == 29) println(part2(input)) }
0
Kotlin
0
0
4ec3831b3d4f576e905076ff80aca035307ed522
6,067
advent-of-code-2022
Apache License 2.0
src/main/kotlin/io/array/MinimumSizeSubArraySum.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.array import io.utils.runTests // https://leetcode.com/explore/learn/card/array-and-string/205/array-two-pointer-technique/1299/ class MinimumSizeSubArraySum { fun execute(target: Int, input: IntArray): Int { var result = Int.MAX_VALUE var left = 0 var sum = 0 for (index in input.indices) { sum += input[index] while (sum >= target) { result = minOf(result, index + 1 - left) sum -= input[left++] } } return when (result) { Int.MAX_VALUE -> 0 else -> result } } fun executeBruteForce(target: Int, input: IntArray): Int { for (minSize in 1..input.size) { for (startIndex in input.indices) { (startIndex until (startIndex + minSize)).fold(0) { acc, index -> when { index >= input.size -> acc acc + input[index] >= target -> return minSize else -> acc + input[index] } } } } return 0 } } fun main() { runTests(listOf( Triple(intArrayOf(2, 3, 1, 2, 4, 3), 7, 2), Triple(intArrayOf(2, 3, 1, 2, 4, 3), 50, 0), Triple(intArrayOf(1, 2, 3, 4, 5), 11, 3), Triple(intArrayOf(1, 2, 3, 4, 5), 15, 5) )) { (input, target, value) -> value to MinimumSizeSubArraySum().execute(target, input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,302
coding
MIT License
src/main/kotlin/groupnet/util/Combinatorics.kt
AlmasB
174,802,362
false
{"Kotlin": 167480, "Java": 91450, "CSS": 110}
package groupnet.util import org.paukov.combinatorics3.Generator /** * * @author <NAME> (<EMAIL>) */ /** * There is a performance reason to represent a combination using a List, * rather than a Set. * However, all combinations are guranteed to be sets. */ typealias Combination<T> = List<T> /** * A k-combination of a set T is a subset of k distinct elements of T. */ fun <T> combinationsOf(elements: Collection<T>, range: IntRange): List<Combination<T>> { val result = ArrayList<Combination<T>>() for (k in range) { result.addAll(Generator.combination(elements).simple(k).toList()) } return result } fun <T> combinations2(elements: Collection<T>): List< Pair<T, T> > { return combinationsOf(elements, 2) .map { it.first() to it.last() } } fun <T> combinationsOf(elements: Collection<T>, combinationSize: Int): List<Combination<T>> { return combinationsOf(elements, combinationSize..combinationSize) } /** * A partition of a set T is a set of non-empty subsets of T * such that every element t in T is in exactly one of these subsets. */ fun <T> partition2(elements: Collection<T>): List< Pair<List<T>, List<T>> > { return combinationsOf(elements, 1..elements.size / 2) .map { it to (elements - it) } } fun <T> partition2Lazy(elements: Collection<T>): Iterable< Pair<List<T>, List<T>> > { return object : Iterable<Pair<List<T>, List<T>>> { override fun iterator(): Iterator<Pair<List<T>, List<T>>> { return object : Iterator<Pair<List<T>, List<T>>> { var index = 1 var gen: Iterator<List<T>> = Generator.combination(elements).simple(index).iterator() override fun hasNext(): Boolean { return index <= elements.size / 2 } override fun next(): Pair<List<T>, List<T>> { val leftSet = gen.next() if (!gen.hasNext()) { index++ gen = Generator.combination(elements).simple(index).iterator() } return leftSet to (elements - leftSet) } } } } }
3
Kotlin
0
0
4aaa9de60ecdba5b9402b809e1e6e62489a1d790
2,238
D2020
Apache License 2.0
extension/model/api/src/main/kotlin/data/DmnHitPolicy.kt
holunda-io
240,229,098
false
{"Kotlin": 182949}
package io.holunda.decision.model.api.data import io.holunda.decision.model.api.AggregatorName import io.holunda.decision.model.api.HitPolicyName import io.holunda.decision.model.api.data.ResultType.* /** * Tuple combining camundas HitPolicy and the Aggregator (optional, for collection operations). * * A hit policy specifies how many rules of a decision table can be satisfied and which of the satisfied rules are included * in the decision table result. The hit policies Unique, Any and First will always return a maximum of one satisfied rule. * * The hit policies Rule Order and Collect can return multiple satisfied rules. */ enum class DmnHitPolicy(val determineResultType: (Int) -> ResultType) { /** * Only a single rule can be satisfied. The decision table result contains the output entries of the satisfied rule. * If more than one rule is satisfied, the Unique hit policy is violated. */ UNIQUE({ if (it > 1) TUPLE else SINGLE }), /** * Multiple rules can be satisfied. The decision table result contains only the output of the first satisfied rule. */ FIRST({ if (it > 1) TUPLE else SINGLE }), /** * Multiple rules can be satisfied. However, all satisfied rules must generate the same output. The decision table result contains only the output of one of the satisfied rules. * * If multiple rules are satisfied which generate different outputs, the hit policy is violated. */ ANY({ if (it > 1) TUPLE else SINGLE }), /** * Multiple rules can be satisfied. The decision table result contains the output of all satisfied rules in * the order of the rules in the decision table. */ RULE_ORDER({ if (it > 1) LIST else TUPLE_LIST }), /** * Multiple rules can be satisfied. * The decision table result contains the output of all satisfied rules in an arbitrary order as a list. */ COLLECT({ if (it > 1) TUPLE_LIST else LIST }), /** * The SUM aggregator sums up all outputs from the satisfied rules. * * TODO: can this be done for multiple outputs? */ COLLECT_SUM({ SINGLE }), /** * The COUNT aggregator can be use to return the count of satisfied rules. */ COLLECT_COUNT({ SINGLE }), /** * The MAX aggregator can be used to return the largest output value of all satisfied rules. */ COLLECT_MAX({ SINGLE }), // TODO: correct? /** * The MIN aggregator can be used to return the smallest output value of all satisfied rules. */ COLLECT_MIN({ SINGLE }), // TODO: correct? ; companion object { fun valueOf(hitPolicy: HitPolicyName, aggregator: AggregatorName?): DmnHitPolicy = valueOf( hitPolicy + if (aggregator != null) "_${aggregator}" else "" ) } }
18
Kotlin
0
6
dbbc98b35d95f53d1a3a78160308c5d955245fbd
2,705
camunda-decision
Apache License 2.0
src/day12/result.kt
davidcurrie
437,645,413
false
{"Kotlin": 37294}
package day12 import java.io.File fun Map<String, List<String>>.partOne(path: List<String>) : List<List<String>> { if (path.last() == "end") { return listOf(path) } return this[path.last()]!! .filter { it.uppercase() == it || !path.contains(it) } .map{ partOne( path + it) } .flatten() } fun Map<String, List<String>>.partTwo(path: List<String>, revisited: String? = null) : List<List<String>> { if (path.last() == "end") { return listOf(path) } return this[path.last()]!! .filter { it.uppercase() == it || !path.contains(it) || (it != "start" && path.contains(it) && revisited == null) } .map{ partTwo( path + it, if (it.lowercase() == it && path.contains(it)) it else revisited ) } .flatten() } fun main() { val input = File("src/day12/input.txt") .readLines() .map { it.split("-") } val bidirectional = input.map { (a, b) -> listOf(b, a) } + input val links = bidirectional.groupBy( keySelector = { it[0] }, valueTransform = { it[1] } ) println(links.partOne(listOf("start")).size) println(links.partTwo(listOf("start")).size) }
0
Kotlin
0
0
dd37372420dc4b80066efd7250dd3711bc677f4c
1,160
advent-of-code-2021
MIT License
Kotlin/problems/0054_sum_of_even_numbers_after_queries.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
// Problem Statement // We have an array A of integers, and an array queries of queries. // // For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index]. // Then, the answer to the i-th query is the sum of the even values of A. // // (Here, the given index = queries[i][1] is a 0-based index, and each query permanently // modifies the array A.) // // Return the answer to all queries. Your answer array should have answer[i] // as the answer to the i-th query. class Solution constructor() { fun sumEvenAfterQueries(A: IntArray, queries: Array<IntArray>): IntArray { var result:MutableList<Int> = mutableListOf<Int>(); var evenSum: Int = 0; for(value in A){ if(value%2==0){ evenSum += value; } } for(query in queries){ if(A[query[1]]%2==0){ evenSum-=A[query[1]]; } A[query[1]]+=query[0]; if(A[query[1]]%2==0){ evenSum+=A[query[1]]; } result.add(evenSum); } return result.toIntArray(); } } fun main(args:Array<String>){ var sol:Solution = Solution(); var A: IntArray = intArrayOf(1,2,3,4); var queries:Array<IntArray> = arrayOf(intArrayOf(1,0),intArrayOf(-3,1),intArrayOf(-4,0),intArrayOf(2,3)); println(sol.sumEvenAfterQueries(A,queries).joinToString(prefix = "[", postfix = "]")); }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
1,438
algorithms
MIT License
app/src/main/java/dev/zezula/books/util/StringExtensions.kt
zezulaon
589,699,261
false
{"Kotlin": 556103}
package dev.zezula.books.util import android.util.Patterns /** * List of articles in different languages. Used for sorting - if a book title contains an article, it should be * ignored (removed) when sorting. */ private val articles = listOf( "The", "A", "An", // English "Le", "La", "Les", "Un", "Une", // French "Der", "Die", "Das", "Ein", "Eine", // German "De", "Het", "Een", // Dutch "Il", "Lo", "La", "I", "Gli", "Le", "Un", "Una", // Italian "El", "La", "Los", "Las", "Un", "Una", // Spanish "O", "A", "Os", "As", "Um", "Uma", // Portuguese "Den", "Det", "Ett", "En", // Swedish "Den", "Det", "Ei", "Et", // Norwegian ) /** * Returns title without article. (If there are more articles, removes the first one). * Example: "The Lord of the Rings" -> "Lord of the Rings". * * @return a book title without article. */ fun String.toSortingTitle(): String { val title = this.trim() articles.forEach { article -> val prefix = "$article " if (title.startsWith(prefix, ignoreCase = true)) { return title.removePrefix(prefix).removePrefix(prefix.lowercase()) } } return title } /** * Returns author's last name for sorting purposes. (If there are more authors, returns the last name of the first * author) * * @return book's author's last name. */ fun String.toSortingAuthor(): String { var author = this.trim() val names = author.splitToAuthors() if (names.size > 1) { author = names.first() } return author.trim().split(" ").last() } /** * Splits string to list of authors. (The input string can contain multiple authors separated by comma). */ fun String.splitToAuthors(): List<String> { return this.split(",", ", ") .map { it.trim() } .filter { it.isNotBlank() } } /** * Creates ID out of author's name. This is done by removing all spaces and converting the name to lowercase. * For example both "<NAME> " and "j.r.r. tolkien" should result in same authorNameId: "j.r.r.tolkien". */ fun String.toAuthorNameId(): String { return this.replace(" ", "").lowercase() } /** * Checks if the string is a valid email address. (Uses [Patterns.EMAIL_ADDRESS] to validate the email address). */ fun String.isValidEmail(): Boolean { return if (this.isEmpty()) { false } else { Patterns.EMAIL_ADDRESS.matcher(this).matches() } }
1
Kotlin
0
6
84750e18ee62d57081096275936ded053b64e6f1
2,422
my-library
Apache License 2.0
kotlin/2018/src/main/kotlin/2018/Lib04.kt
nathanjent
48,783,324
false
{"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966}
package aoc.kt.y2018; import java.time.LocalDateTime import java.util.Locale import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit /** * Day 4. */ data class Message(val dateTime: LocalDateTime, val text: String) /** Part 1 */ fun processRepose1(input: String): String { val guardMap = makeGuardMap(input) val guardWithMostSleepTime = guardMap.map { val guardId = it.key val sleepTime = it.value.sumBy { sleepWakeTime -> ChronoUnit.MINUTES.between(sleepWakeTime.first, sleepWakeTime.second) .toInt() } Pair(guardId, sleepTime) } .maxBy { it.second }?.first val minuteGuardSleptMost = guardMap.get(guardWithMostSleepTime)?.flatMap { val sleepStart = it.first val sleepEnd = it.second val minutesSlept = mutableMapOf<Int, Long>() var timeCursor = sleepStart while (timeCursor.until(sleepEnd, ChronoUnit.MINUTES) > 0) { val minute = timeCursor.getMinute() val minuteCount = minutesSlept.getOrDefault(minute, 0) minutesSlept.put(minute, minuteCount + 1) timeCursor = timeCursor.plusMinutes(1) } minutesSlept.toList() }?.groupBy { it.first }?.map { Pair(it.key, it.value.sumBy { x -> x.second.toInt() }) }?.maxBy { it.second }?.first val output = guardWithMostSleepTime?.let { a -> minuteGuardSleptMost?.let { b -> a * b } } return output.toString() } /** Part 2 */ fun processRepose2(input: String): String { val guardMap = makeGuardMap(input) val m = guardMap.map { val minutesSlept = mutableMapOf<Int, Long>() it.value.forEach { val sleepStart = it.first val sleepEnd = it.second var timeCursor = sleepStart while (timeCursor.until(sleepEnd, ChronoUnit.MINUTES) > 0) { val minute = timeCursor.getMinute() val minuteCount = minutesSlept.getOrDefault(minute, 0) minutesSlept.put(minute, minuteCount + 1) timeCursor = timeCursor.plusMinutes(1) } } Pair(it.key, minutesSlept) } .map { val minuteSleptMost = it.second.maxBy { (_, sleptCount) -> sleptCount } Pair(it.first, minuteSleptMost) }.map { (g, m) -> Triple(g, m?.key, m?.value) }.maxBy { it.third?:-1 } val output = m?.first?.let { a -> m.second?.let { b -> a * b } } return output.toString() } private fun makeGuardMap(input: String): MutableMap<Int, MutableList<Pair<LocalDateTime, LocalDateTime>>> { val messageMatch = """(\[.*\])|([Gfw].*$)""".toRegex() val numMatch = """[0-9]+""".toRegex() val dateTimePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.ENGLISH) var messages = input.lines() .filter { !it.isEmpty() } .map { val (dateTimeStr, message) = messageMatch.findAll(it) .map { it.value } .toList() val dateTime = LocalDateTime.parse( dateTimeStr.trim { it == '[' || it == ']' }, dateTimePattern) Message(dateTime, message) } .sortedBy { it.dateTime } .toList() // Map of guards to datetime ranges val guardMap = mutableMapOf<Int, MutableList<Pair<LocalDateTime, LocalDateTime>>>() var currentGuardId = -1 var asleepStart: LocalDateTime? = null for (message in messages) { currentGuardId = numMatch.find(message.text)?.value?.toInt()?:currentGuardId if (message.text.contains("asleep")) { asleepStart = message.dateTime } if (message.text.contains("wake") && asleepStart != null) { val sleepWakeList = guardMap.getOrDefault(currentGuardId, mutableListOf()) sleepWakeList.add(Pair(asleepStart, message.dateTime)) guardMap.put(currentGuardId, sleepWakeList) } } return guardMap }
0
Rust
0
0
7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf
3,980
adventofcode
MIT License
src/main/kotlin/com/marcdenning/adventofcode/day21/Day21a.kt
marcdenning
317,730,735
false
{"Kotlin": 87536}
package com.marcdenning.adventofcode.day21 import java.io.File fun main(args: Array<String>) { val foods = File(args[0]).readLines().map { Food(getIngredients(it), getIdentifiedAllergens(it)) } val allIngredientsList = foods.flatMap { it.ingredients } val safeIngredients = getSafeIngredients(foods) val countOfInstancesOfSafeIngredients = allIngredientsList.count { safeIngredients.contains(it) } println("Number of instances of ingredients with no known allergens: $countOfInstancesOfSafeIngredients") } fun getSafeIngredients(foods: List<Food>): Set<String> { val allIngredientsList = foods.flatMap { it.ingredients } val allIngredientsSet = allIngredientsList.toSet() val allAllergensSet = foods.flatMap { it.allergens }.toSet() val ingredientsContainingAllergens = mutableSetOf<String>() for (allergen in allAllergensSet) { ingredientsContainingAllergens.addAll(getCommonIngredientsForAllergen(foods, allergen)) } return allIngredientsSet.subtract(ingredientsContainingAllergens) } fun getCommonIngredientsForAllergen(foods: List<Food>, allergen: String): List<String> { return foods .filter { it.allergens.contains(allergen) } .map { it.ingredients } .reduce { acc, list -> acc.intersect(list).toList() } } fun getIngredients(description: String): List<String> = description.split('(')[0].split(' ').filter { it.isNotBlank() }.toList() fun getIdentifiedAllergens(description: String) = description.split('(')[1].removePrefix("contains").split(',').map { it.removeSuffix(")").trim() }.toList() data class Food( val ingredients: List<String>, val allergens: List<String> )
0
Kotlin
0
0
b227acb3876726e5eed3dcdbf6c73475cc86cbc1
1,685
advent-of-code-2020
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions11.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import kotlin.math.min fun test11() { fun IntArray.printlnResult() = println("Find the IntArray ${toList()}'s smallest number is ${findMinNumber()}") intArrayOf(1, 2, 3, 4, 5, 6).printlnResult() intArrayOf(4, 5, 6, 1, 2, 3).printlnResult() intArrayOf(3, 4, 5, 6, 1, 2).printlnResult() intArrayOf(5, 6, 1, 2, 3, 4).printlnResult() intArrayOf(8).printlnResult() intArrayOf(8, 6).printlnResult() intArrayOf(1, 0, 1, 1, 1).printlnResult() intArrayOf(1, 1, 1, 0, 1).printlnResult() intArrayOf(1, 1, 0, 1, 1).printlnResult() } /** * Questions 11: We have a whirling IntArray. For example, the [3, 4, 5, 1, 2] is sorted IntArray [1, 2, 3, 4, 5]'s whirling, * find the smallest number in whirling IntArray. */ private fun IntArray.findMinNumber(): Int { if (isEmpty()) throw IllegalArgumentException("The IntArray is empty") return findMinNumber(0, lastIndex) } private tailrec fun IntArray.findMinNumber(start: Int, end: Int): Int { if (start == end) return this[start] val mid = (start + end) shr 1 val first = this[start] val middle = this[mid] val middle1 = this[mid + 1] val last = this[end] return when { first == middle && middle1 == last -> this.min() first <= middle && middle1 <= last -> min(first, middle1) first > middle && middle1 <= last -> findMinNumber(start, mid) first <= middle && middle1 > last -> findMinNumber(mid + 1, end) else -> throw IllegalArgumentException("The IntArray receiver is not a whirling IntArray") } }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,607
Algorithm
Apache License 2.0
src/test/kotlin/be/brammeerten/y2022/Day18Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2022 import be.brammeerten.C3 import be.brammeerten.readFile import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class Day18Test { @Test fun `part 1a`() { val droplet = parseDroplet("2022/day18/exampleInput.txt") Assertions.assertEquals(64, droplet.countSurface()) } @Test fun `part 1b`() { val droplet = parseDroplet("2022/day18/input.txt") Assertions.assertEquals(4340, droplet.countSurface()) } @Test fun `part 2a`() { val droplet = parseDroplet("2022/day18/exampleInput.txt") Assertions.assertEquals(58, droplet.countExteriorSurface()) } @Test fun `part 2b`() { val droplet = parseDroplet("2022/day18/input.txt") Assertions.assertEquals(2468, droplet.countExteriorSurface()) } fun parseDroplet(file: String): Droplet { return Droplet( readFile(file) .map { it.split(",").map { c -> c.toInt() } } .map { (x, y, z) -> C3(x, y, z) }) } data class Droplet(val cubes: List<C3>) { fun countSurface(): Int { val scanned = arrayListOf<C3>() var sides = cubes.size * 6 for (cube in cubes) { for (other in scanned) if (other.hasSameSide(cube)) sides -= 2 scanned.add(cube) } return sides } fun countExteriorSurface(): Int { val surrounding = getSurroundingCube() val exteriorBlocks = surrounding.grow().getSides().toHashSet() val allExt = getExteriorBlocksOfCuboid(exteriorBlocks, surrounding) return cubes.sumOf { cube -> allExt.count{ it.hasSameSide(cube) }} } fun getExteriorBlocksOfCuboid(ext: Set<C3>, cube: Cuboid): Set<C3> { val sides = cube.getSides() var exteriorBlocks = ext while (true) { val newExteriorBlocks = exteriorBlocks + sides .filter { !cubes.contains(it) } .filter { exteriorBlocks.any { c -> c.hasSameSide(it) } } if (newExteriorBlocks.size == exteriorBlocks.size) break exteriorBlocks = newExteriorBlocks } if (cube.shrink() == cube) return exteriorBlocks else return getExteriorBlocksOfCuboid(exteriorBlocks, cube.shrink()) } private fun getSurroundingCube(): Cuboid { var c1 = C3.MAX var c2 = C3.MIN cubes.forEach{c -> c1 = c1.min(c) c2 = c2.max(c) } return Cuboid(c1, c2) } } data class Cuboid(val minCo: C3, val maxCo: C3) { fun getSides(): Set<C3> { val side: HashSet<C3> = hashSetOf() // x plane for (y in minCo.y..maxCo.y) { for (z in minCo.z..maxCo.z) { side.add(C3(minCo.x, y, z)) side.add(C3(maxCo.x, y, z)) } } // y plane for (x in minCo.x..maxCo.x) { for (z in minCo.z..maxCo.z) { side.add(C3(x, minCo.y, z)) side.add(C3(x, maxCo.y, z)) } } // y plane for (x in minCo.x..maxCo.x) { for (y in minCo.y..maxCo.y) { side.add(C3(x, y, minCo.z)) side.add(C3(x, y, maxCo.z)) } } return side } fun shrink(): Cuboid { val xOff = if (maxCo.x - minCo.x <= 1) 0 else 1 val yOff = if (maxCo.y - minCo.y <= 1) 0 else 1 val zOff = if (maxCo.z - minCo.z <= 1) 0 else 1 return Cuboid(minCo + C3(xOff, yOff, zOff), maxCo - C3(xOff, yOff, zOff)) } fun grow(): Cuboid { return Cuboid(minCo - C3(1, 1, 1), maxCo + C3(1, 1, 1)) } } } fun C3.hasSameSide(other: C3): Boolean { return arrayOf( this + C3(0, 0, 1), this + C3(0, 1, 0), this + C3(1, 0, 0), this + C3(0, 0, -1), this + C3(0, -1, 0), this + C3(-1, 0, 0), ).contains(other) }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
4,339
Advent-of-Code
MIT License
src/day05/Day05.kt
hamerlinski
572,951,914
false
{"Kotlin": 25910}
package day05 import readInput fun main() { fun part1(stacks: SupplyStacks) { stacks.executeInstructions() println("solution1:") stacks.printAllLastCrates() } fun part2(stacks: SupplyStacks) { stacks.executeInstructionsOnCrateMover9001() println("solution2:") stacks.printAllLastCrates() } val input = readInput("Day05", "day05") val parsedInput = ParsedInput(input) val supplyStacks = SupplyStacks(parsedInput.stacks(), parsedInput.instructions()) val supplyStacksCopy = SupplyStacks(parsedInput.stacks(), parsedInput.instructions()) part1(supplyStacks) part2(supplyStacksCopy) } class ParsedInput(private val input: List<String>) { private val splitLine: Int = emptyLineIndex() private val regex = Regex("^' '{4}") private fun emptyLineIndex(): Int { var index = -1 for (line in input) { index += 1 if (line == "") break } return index } fun stacks(): MutableList<Stack> { val iterator = input.listIterator(splitLine) val numberOfStacks = iterator.previous().split(" ").size val containers: MutableList<Stack> = mutableListOf() for (i in 1..numberOfStacks) { val tempCrateList: MutableList<Crate> = mutableListOf() val tempStack = Stack(tempCrateList) containers.add(tempStack) } while (iterator.hasPrevious()) { val cratesRow = iterator.previous() .replace(regex, "[0] ") .replace(" ", " [0]") .replace("[", "") .replace("]", "") .split(" ") val cratesRowIterator = cratesRow.listIterator() var rowIndex = 0 while (cratesRowIterator.hasNext()) { val tempCrateValue = cratesRowIterator.next() if (tempCrateValue != "0") { val tempCrate = Crate(tempCrateValue) containers[rowIndex].addCrate(tempCrate) } rowIndex += 1 } } return containers } fun instructions(): MutableList<Instruction> { val iterator = input.listIterator() for (i in 0..splitLine) { // set iterator to first lane with crates iterator.next() } val instructions: MutableList<Instruction> = mutableListOf() while (iterator.hasNext()) { val tempInstruction = Instruction(iterator.next()) instructions.add(tempInstruction) } return instructions } } class SupplyStacks( private val stacks: MutableList<Stack>, private val instructions: MutableList<Instruction> ) { fun printAllLastCrates() { stacks.iterator().forEach { it.printLastCrate() } println() } fun executeInstructions() { instructions.listIterator().forEach { for (i in 1..it.amountOfCratesToMove()) { stacks[it.fromStack() - 1].moveOneCrate(stacks[it.toStack() - 1]) } } } fun executeInstructionsOnCrateMover9001() { instructions.listIterator().forEach { stacks[it.fromStack() - 1].moveMultipleCrates( it.amountOfCratesToMove(), stacks[it.toStack() - 1] ) } } } class Stack(private val crates: MutableList<Crate>) { fun moveOneCrate(toStack: Stack) { val crateToMove = crates[crates.lastIndex] toStack.crates.add(crateToMove) crates.removeAt(crates.lastIndex) } fun moveMultipleCrates(amount: Int, toStack: Stack) { for (i in amount downTo 1 step 1) { val crateToMove = crates[crates.lastIndex - i + 1] toStack.crates.add(crateToMove) crates.removeAt(crates.lastIndex - i + 1) } } fun printLastCrate() { print(crates[crates.lastIndex].value()) } fun addCrate(crate: Crate) { crates.add(crate) } } class Crate(private val name: String) { fun value(): String { return name } } class Instruction(input: String) { private val inputList: List<String> = input.split(" ") fun amountOfCratesToMove(): Int { return inputList[1].toInt() } fun fromStack(): Int { return inputList[3].toInt() } fun toStack(): Int { return inputList[5].toInt() } }
0
Kotlin
0
0
bbe47c5ae0577f72f8c220b49d4958ae625241b0
4,489
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2020/d13/Day13.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2020.d13 import com.groundsfam.advent.DATAPATH import kotlin.io.path.div import kotlin.io.path.useLines // find lowest positive solution to the equations // x = i1 (mod n1) // x = i2 (mod n2) // ... // where input is a list of (n1, i1) pairs // assumes that (n1, n2, ...) are mutually coprime // and 0 <= i1 < n1 etc. fun chineseRemainder(input: List<Pair<Int, Int>>): Long { var t = 0L var p = 1L input.forEach { (n, i) -> while (t % n != i.toLong()) { t += p } p *= n } return t } fun main() { var depart = 0 var busIdsUnparsed = emptyList<String>() (DATAPATH / "2020/day13.txt").useLines { lines -> lines.forEachIndexed { i, line -> when (i) { 0 -> depart = line.toInt() 1 -> busIdsUnparsed = line.split(",") } } } var minWait = Integer.MAX_VALUE var bestBusId = -1 busIdsUnparsed.filterNot { it == "x" }.map { it.toInt() }.let { busIds -> busIds.forEach { busId -> val wait = busId - (depart % busId) if (wait < minWait) { minWait = wait bestBusId = busId } } } println("Part one: ${minWait * bestBusId}") // (busId, index) pairs val busIdsIndices = mutableListOf<Pair<Int, Int>>().apply { busIdsUnparsed.forEachIndexed { i, busId -> if (busId != "x") busId.toInt().let { bid -> add(bid to (-i).mod(bid)) } } } chineseRemainder(busIdsIndices).also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,645
advent-of-code
MIT License
src/main/kotlin/aoc/Utils.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc import java.io.File import java.math.BigInteger import java.security.MessageDigest fun readFile(year: Int, day: Int, test: Int? = null): File { fun Int.twoDigit() = String.format("%02d", this) val testSuffix = if (test != null) "_test${test.twoDigit()}" else "" val basePath = if (test != null) "input/test" else "input/actual" return File("$basePath/$year/Day${day.twoDigit()}$testSuffix.txt") } /** * Converts string to aoc.md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0') /** * Splits a list by the given predicate * * @param predicate function that takes a element of the list and return true when predicate is matched * * @return List of List with a aoc.split parts */ fun <A> List<A>.split(predicate: (A) -> Boolean): List<List<A>> { fun go(input: List<A>): List<List<A>> { val first = input.takeWhile { !predicate(it) } val other = input.dropWhile { !predicate(it) }.drop(1) when { other.isEmpty() -> return listOf(first) else -> return listOf(first) + go(other) } } return go(this) } fun <T : Any> T.println(): T { println(this) return this } fun <T> List<List<T>>.transpose(): List<List<T>> { // Helpers fun <T> List<T>.tail(): List<T> = this.takeLast(this.size - 1) fun <T> T.append(xs: List<T>): List<T> = listOf(this).plus(xs) this.filter { it.isNotEmpty() }.let { ys -> return when (ys.isNotEmpty()) { true -> ys.map { it.first() }.append(ys.map { it.tail() }.transpose()) else -> emptyList() } } } fun <R, T> foldTree(tree: R, subNodes: (R) -> List<R>, init: T, f: (T, R) -> T): T { fun go(node: R, acc: T, f: (T, R) -> T): T { val nacc = f(acc, node) val subs = subNodes(node) return subs.fold(nacc) { a, n -> go(n, a, f) } } return go(tree, init, f) } fun IntRange.union(other: IntRange) = union(listOf(this, other)) fun union(r: List<IntRange>): List<IntRange> { val sorted = r.sortedBy { it.start } val merged = sorted.fold(Pair(listOf<IntRange>(), sorted[0])) { (list: List<IntRange>, cur: IntRange), range: IntRange -> when (range.first) { in cur -> Pair(list, cur.first..maxOf(range.last, cur.last)) else -> Pair(list + listOf(cur), range) } } return merged.first + listOf(merged.second) } fun <T> getCombinationPairs(list: List<T>, n: Int): List<Pair<List<T>, List<T>>> { val m = list.size val result = mutableListOf<Pair<List<T>, List<T>>>() fun go(n: Int, indexes: IntArray, start: Int, index: Int) { for (i in start..(m - 1)) { indexes[index] = i // println("indexes: ${indexes.toList()}, start: ${start}, index: ${index}") val newIndex = index + 1 if (newIndex == n) { val pair1 = Pair(list.filterIndexed { it, _ -> it in indexes }, list.filterIndexed { it, _ -> it !in indexes }) // println("added: $pair1") result.add(pair1) } else { go(n, indexes, i + 1, newIndex) } } } for (j in 1..n) { go(j, IntArray(j), 0, 0) } return result } fun Iterable<Int>.product() = this.fold(1) { acc, v -> acc * v } fun <T> getCombinations(list: Collection<T>): List<List<T>> = getCombinations(list, list.size) fun <T> getCombinations(list: Collection<T>, n: Int): List<List<T>> { val m = list.size val result = mutableListOf<List<T>>() fun go(n: Int, indexes: IntArray, start: Int, index: Int) { for (i in start..(m - 1)) { indexes[index] = i // println("indexes: ${indexes.toList()}, start: ${start}, index: ${index}") val newIndex = index + 1 if (newIndex == n) { val pair1 = list.filterIndexed { it, _ -> it in indexes } // println("added: $pair1") result.add(pair1) } else { go(n, indexes, i + 1, newIndex) } } } for (j in 1..n) { go(j, IntArray(j), 0, 0) } return result } fun <T : Any> Sequence<T>.zipNextPrevious(startEnd: T? = null, start: T? = null, end: T? = null): Sequence<Triple<T, T, T>> { // TODO: check conditions if ((startEnd != null) && (start != null) && (end != null)) throw IllegalArgumentException("either set startEnd or start and/or end") val e = startEnd ?: end val s = startEnd ?: start val seq = if (s != null) { if (e != null) { sequenceOf(s) + this + sequenceOf(e) } else { sequenceOf(s) + this } } else { if (e != null) { this + sequenceOf(e) } else { this } } return seq.zipWithNext().zipWithNext { a, b -> Triple(a.first, a.second, b.second) } } fun Int.gcd(other: Int): Int = if (other == 0) this else other.gcd(this % other) fun Long.gcd(other: Long): Long = if (other == 0L) this else other.gcd(this % other) fun Int.gcd(vararg others: Int) = others.fold(this) { acc, n -> acc.gcd(n) } fun Long.gcd(vararg others: Long) = others.fold(this) { acc, n -> acc.gcd(n) } fun Int.lcm(other: Int) = this / this.gcd(other) * other fun Long.lcm(other: Long) = this / this.gcd(other) * other fun Int.lcm(vararg others: Int) = others.fold(this) { acc, n -> acc.lcm(n) } fun Long.lcm(vararg others: Long) = others.fold(this) { acc, n -> acc.lcm(n) } operator fun Int.times(c: Char) = c.toString().repeat(this) fun <A> Pair<A, A>.same() = this.first == this.second
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
5,795
aoc-kotlin
Apache License 2.0
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day18/Day18.kt
jntakpe
433,584,164
false
{"Kotlin": 64657, "Rust": 51491}
package com.github.jntakpe.aoc2021.days.day18 import com.github.jntakpe.aoc2021.shared.Day import com.github.jntakpe.aoc2021.shared.readInputLines object Day18 : Day { override val input = readInputLines(18) override fun part1() = input.map(::parseNode).reduce(Node::plus).magnitude() override fun part2(): Number { return input.indices.flatMap { i -> input.indices.map { j -> i to j } } .filter { (i, j) -> i != j } .maxOf { (i, j) -> (parseNode(input[i]) + parseNode(input[j])).magnitude() } } private fun parseNode(input: String): Node { var i = 0 fun parse(parent: NodePair): Node { return if (input[i++] == '[') { NodePair(null, null, parent).apply { left = parse(this).also { i++ } right = parse(this).also { i++ } } } else NodeNumber(input[i - 1].digitToInt(), parent) } return parse(NodePair(null, null)) } sealed class Node(var parent: NodePair? = null) { abstract fun magnitude(): Int operator fun plus(other: Node) = NodePair(this, other).apply { reduce() } fun reduce() { toExplode()?.apply { leftNode()?.also { it.value = it.value + (left as NodeNumber).value } rightNode()?.also { it.value = it.value + (right as NodeNumber).value } parent?.update(this, NodeNumber(0)) this@Node.reduce() } toSplit()?.apply { parent?.update(this, NodePair(NodeNumber(value / 2), NodeNumber((value + 1) / 2))) this@Node.reduce() } } fun leftNode(): NodeNumber? = when (this) { is NodeNumber -> this parent?.left -> parent?.leftNode() parent?.right -> parent?.left?.farRightNode() else -> null } fun rightNode(): NodeNumber? = when (this) { is NodeNumber -> this parent?.left -> parent?.right?.farLeftNode() parent?.right -> parent?.rightNode() else -> null } private fun farLeftNode(): NodeNumber? = when (this) { is NodeNumber -> this is NodePair -> left?.farLeftNode() } private fun farRightNode(): NodeNumber? = when (this) { is NodeNumber -> this is NodePair -> right?.farRightNode() } private fun toExplode(depth: Int = 0): NodePair? = when (this) { is NodePair -> takeIf { depth >= 4 && left is NodeNumber && right is NodeNumber } ?: left?.toExplode(depth + 1) ?: right?.toExplode(depth + 1) else -> null } private fun toSplit(): NodeNumber? = when (this) { is NodeNumber -> takeIf { value >= 10 } is NodePair -> left?.toSplit() ?: right?.toSplit() } } open class NodePair(var left: Node?, var right: Node?, parent: NodePair? = null) : Node(parent) { init { left?.parent = this right?.parent = this } override fun magnitude() = 3 * left!!.magnitude() + 2 * right!!.magnitude() fun update(child: Node, newValue: Node) { if (left == child) { left = newValue } else if (right == child) { right = newValue } newValue.parent = this } } class NodeNumber(var value: Int, parent: NodePair? = null) : Node(parent) { override fun magnitude() = value } }
0
Kotlin
1
5
230b957cd18e44719fd581c7e380b5bcd46ea615
3,603
aoc2021
MIT License
kotlin/04.kt
NeonMika
433,743,141
false
{"Kotlin": 68645}
class Day4 : Day<Day4.Input>("04") { // Classes data class BingoNumber(val num: Int, var drawn: Boolean = false) class Board(d: List<List<BingoNumber>>) : TwoDimensionalArray<BingoNumber>(d) { val isSolved get() = isSolvedViaRow || isSolvedViaColumn val isSolvedViaRow get() = data.any { row -> row.all(BingoNumber::drawn) } val isSolvedViaColumn get() = (0 until cols).any { col -> data.all { row -> row[col].drawn } } val undrawnSum get() = flat.filter { !it.drawn }.sumOf { it.num } } data class Input(val numbers: List<Int>, val boards: List<Board>) // Data private fun data(lines: List<String>): Input { val numbers = lines[0].split(",").map(String::toInt) val boards = lines .drop(1) .chunked(5) .map { boardLines -> boardLines.map { line -> line.ints().map(::BingoNumber) } } .map(::Board) return Input(numbers, boards) } override fun dataStar1(lines: List<String>): Input = data(lines) override fun dataStar2(lines: List<String>): Input = data(lines) // 1 Star override fun star1(data: Input): Number { var finalNumber = 0 for (n in data.numbers) { for (board in data.boards) { board.flat.find { it.num == n }?.drawn = true } if (data.boards.any { it.isSolved }) { finalNumber = n break } } val solved = data.boards.first { it.isSolved } return finalNumber * solved.undrawnSum } // 2 Stars override fun star2(data: Input): Number { var finalNumber = 0 var finalBoard: Board? = null for (n in data.numbers) { for (board in data.boards) { board.flat.find { it.num == n }?.drawn = true } if (data.boards.count { it.isSolved } == data.boards.count() - 1) { finalBoard = data.boards.single { !it.isSolved } } if (data.boards.all { it.isSolved }) { finalNumber = n break } } return finalNumber * (finalBoard?.undrawnSum ?: error("here be dragon squids")) } } // main fun main() { Day4()() }
0
Kotlin
0
0
c625d684147395fc2b347f5bc82476668da98b31
2,360
advent-of-code-2021
MIT License
src/main/kotlin/ctci/chapterone/IsUnique.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package ctci.chapterone //1.1 - page 90 //In Kotlin, implement an algorithm to determine if a string has all unique characters. fun main() { val testCases = listOf("abcdef", "abcdea", "aaa", "", "a") for (testCase in testCases) { println("hasUniqueCharacters($testCase) = ${hasUniqueCharacters(testCase)}") } } // This function iterates through each character in the string and checks if it is already in the set of seen characters. // If it is, the function returns false, indicating that the string does not have all unique characters. // If the character is not in the set, it is added to the set. If the function reaches the end of the string without // finding any duplicate characters, it returns true, indicating that the string has all unique characters. fun hasUniqueCharacters(str: String): Boolean { val seenCharacters = mutableSetOf<Char>() for (c in str) { if (c in seenCharacters) { return false } seenCharacters.add(c) } return true } //The Big O complexity of the hasUniqueCharacters function is O(n), where n is the length of the string. This is because // the function iterates through each character in the string once and performs a constant time operation // (checking if the character is in the set and adding it to the set if it is not) on each character. //In general, the time complexity of a loop that iterates through a collection of size n is O(n). Therefore, the time // complexity of the hasUniqueCharacters function is linear in the size of the input string. //Note that the space complexity of the hasUniqueCharacters function is also O(n), since the set used to store the seen // characters may contain up to n elements if the string has all unique characters. // The function below is similar to the one above, using hash tables. A Map is a Hash Table. fun hasUniqueCharactersHash(str: String): Boolean { val seenCharacters = mutableMapOf<Char, Unit>() for (c in str) { if (c in seenCharacters) { return false } seenCharacters[c] = Unit } return true }
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
2,123
dsa-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CircularPermutation.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 /** * 1238. Circular Permutation in Binary Representation * @see <a href="https://leetcode.com/problems/circular-permutation-in-binary-representation/">Source</a> */ fun interface CircularPermutation { operator fun invoke(n: Int, start: Int): List<Int> } class CircularPermutationGrayCode : CircularPermutation { override operator fun invoke(n: Int, start: Int): List<Int> { val res: MutableList<Int> = ArrayList() for (i in 0 until (1 shl n)) { res.add(start xor i xor (i shr 1)) } return res } } class OneBitDiffPermutation : CircularPermutation { override operator fun invoke(n: Int, start: Int): List<Int> { val res: MutableList<Int> = ArrayList() val tmp = genOneBitDiffPermutation(n) // generate one bit diff permutations // rotate the tmp list to make it starts from "start" // before: {0, 1, ..., start, ..., end} // after: {start, ..., end, 0, 1, ...} var i = 0 while (i < tmp.size) { if (tmp[i] == start) { break } i++ } for (k in i until tmp.size) { res.add(tmp[k]) } for (q in 0 until i) { res.add(tmp[q]) } return res } /** * generate one bit diff permutations * 0, 1 * 0, 1, 11, 10 * 000, 001, 011, 010, 110, 111, 101, 100 */ private fun genOneBitDiffPermutation(n: Int): List<Int> { val tmp: MutableList<Int> = ArrayList() tmp.add(0) if (n == 0) { return tmp } for (i in 0 until n) { for (j in tmp.indices.reversed()) { tmp.add(tmp[j] + (1 shl i)) } } return tmp } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,425
kotlab
Apache License 2.0
src/main/kotlin/g1101_1200/s1125_smallest_sufficient_team/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1101_1200.s1125_smallest_sufficient_team // #Hard #Array #Dynamic_Programming #Bit_Manipulation #Bitmask // #2023_05_31_Time_181_ms_(100.00%)_Space_35.8_MB_(100.00%) class Solution { private var ans: List<Int> = ArrayList() fun smallestSufficientTeam(skills: Array<String>, people: List<List<String>>): IntArray { val n = skills.size val m = people.size val map: MutableMap<String, Int> = HashMap() for (i in 0 until n) { map[skills[i]] = i } val arr = IntArray(m) for (i in 0 until m) { val list = people[i] var `val` = 0 for (skill in list) { `val` = `val` or (1 shl map[skill]!!) } arr[i] = `val` } val banned = BooleanArray(m) for (i in 0 until m) { for (j in i + 1 until m) { val `val` = arr[i] or arr[j] if (`val` == arr[i]) { banned[j] = true } else if (`val` == arr[j]) { banned[i] = true } } } helper(0, n, arr, mutableListOf(), banned) val res = IntArray(ans.size) for (i in res.indices) { res[i] = ans[i] } return res } private fun helper(cur: Int, n: Int, arr: IntArray, list: MutableList<Int>, banned: BooleanArray) { if (cur == (1 shl n) - 1) { if (ans.isEmpty() || ans.size > list.size) { ans = ArrayList(list) } return } if (ans.isNotEmpty() && list.size >= ans.size) { return } var zero = 0 while (cur shr zero and 1 == 1) { zero++ } for (i in arr.indices) { if (banned[i]) { continue } if (arr[i] shr zero and 1 == 1) { list.add(i) helper(cur or arr[i], n, arr, list, banned) list.removeAt(list.size - 1) } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,079
LeetCode-in-Kotlin
MIT License
src/main/kotlin/Day11.kt
dliszewski
573,836,961
false
{"Kotlin": 57757}
class Day11 { fun part1(input: String): Long { val monkeys = input.split("\n\n").map { it.toMonkey() }.toTypedArray() val rounds = 20 val stressReducerFormula: (Long) -> Long = { it / 3 } repeat(rounds) { round -> monkeys.forEach { it.handleItems(stressReducerFormula).forEach { (item, monkey) -> monkeys[monkey].passItem(item) } } } return monkeys.map { it.handledItemsCount }.sortedDescending().take(2).reduce { acc, i -> acc * i } } fun part2(input: String): Long { val monkeys = input.split("\n\n").map { it.toMonkey() }.toTypedArray() val rounds = 10000 val lcm = monkeys.map { it.divisor.toLong() }.reduce(Long::times) val stressReducerFormula: (Long) -> Long = { it % lcm } repeat(rounds) { monkeys.forEach { it.handleItems(stressReducerFormula).forEach { (itemToPass, monkeyNumber) -> monkeys[monkeyNumber].passItem(itemToPass) } } } val map = monkeys.map { it.handledItemsCount } return map.sortedDescending().take(2).reduce { acc, i -> acc * i } } data class Monkey( private val items: MutableList<Long>, private val newStressLevelFormula: (Long) -> Long, val divisor: Int, private val passToOnSuccess: Int, private val passToOnFailure: Int, var handledItemsCount: Long = 0L ) { fun handleItems(stressReducerFormula: (Long) -> Long): List<Pair<Long, Int>> { val handledItems = items.map { handledItemsCount++ handleItem(it, stressReducerFormula) } items.clear() return handledItems } private fun handleItem(item: Long, stressReducerFormula: (Long) -> Long): Pair<Long, Int> { val newStressLevel = newStressLevelFormula(item) val levelAfterBoredMonkey = stressReducerFormula(newStressLevel) return levelAfterBoredMonkey to if (levelAfterBoredMonkey % divisor == 0L) passToOnSuccess else passToOnFailure } fun passItem(item: Long) { items.add(item) } } private fun String.toMonkey(): Monkey { val lines = split("\n") val monkeyNumber = lines[0].toMonkeyNumber() val items = lines[1].toItems() val operation = lines[2].mapToOperation() val divisor = lines[3].toDivisor() val passToOnSuccess = lines[4].toSuccessMonkey() val passToOnFailure = lines[5].toFailureMonkey() return Monkey(items, operation, divisor, passToOnSuccess, passToOnFailure) } private fun String.toMonkeyNumber() = substringAfter("Monkey ").dropLast(1).toInt() private fun String.toItems() = trim() .substringAfter("Starting items: ") .split(", ") .map { it.toLong() } .toMutableList() private fun String.toDivisor() = trim().substringAfter("Test: divisible by ").toInt() private fun String.toSuccessMonkey() = trim().substringAfter("If true: throw to monkey ").toInt() private fun String.toFailureMonkey() = trim().substringAfter("If false: throw to monkey ").toInt() private fun String.mapToOperation(): (Long) -> Long { val (sign, value) = trim().substringAfter("Operation: new = old ").split(" ") return when (sign) { "*" -> { old -> old * if (value == "old") old else value.toLong() } "+" -> { old -> old + if (value == "old") old else value.toLong() } else -> error("wrong operation $this") } } }
0
Kotlin
0
0
76d5eea8ff0c96392f49f450660220c07a264671
3,707
advent-of-code-2022
Apache License 2.0
src/Day10.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
fun main() { fun part1(input: List<String>): Int { var x = 1 var result = 0 var tact = 1 val commands = input.map { if (it == "noop") Pair(1, 0) else Pair(2, it.split(" ")[1].toInt()) }.toMutableList() var cursor = 0 while (tact <= 220 && cursor != input.size) { if (tact % 40 == 20) { result += tact * x } commands[cursor] = Pair(commands[cursor].first - 1, commands[cursor].second) if (commands[cursor].first == 0) { x += commands[cursor].second cursor++ } tact++ } return result } fun part2(input: List<String>): String { var x = 1 var tact = 0 val commands = input.map { if (it == "noop") Pair(1, 0) else Pair(2, it.split(" ")[1].toInt()) }.toMutableList() var cursor = 0 val line = StringBuilder("") val lines = mutableListOf<String>() while (tact <= 240) { val index = (tact % 40) if (index == 0) { lines.add(line.toString()) line.clear() } line.append( if (index >= x - 1 && index <= x + 1) { "#" } else "." ) if (cursor != input.size) { commands[cursor] = Pair(commands[cursor].first - 1, commands[cursor].second) if (commands[cursor].first == 0) { x += commands[cursor].second cursor++ } } tact++ } lines.forEach { println(it) } return "" } val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
1,937
Advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/PutMarbles.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 /** * 2551. Put Marbles in Bags * @see <a href="https://leetcode.com/problems/put-marbles-in-bags/">Source</a> */ fun interface PutMarbles { fun putMarblesInBags(weights: IntArray, k: Int): Long } class PutMarblesSort : PutMarbles { override fun putMarblesInBags(weights: IntArray, k: Int): Long { // We collect and sort the value of all n - 1 pairs. val n: Int = weights.size val pairWeights = IntArray(n - 1) for (i in 0 until n - 1) { pairWeights[i] = weights[i] + weights[i + 1] } // We will sort only the first (n - 1) elements of the array. pairWeights.sort(0, n - 1) // Get the difference between the largest k - 1 values and the // smallest k - 1 values. var answer = 0L for (i in 0 until k - 1) { answer += (pairWeights[n - 2 - i] - pairWeights[i]).toLong() } return answer } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,575
kotlab
Apache License 2.0
Algorithms/23 - Merge k Sorted Lists/src/Solution.kt
mobeigi
202,966,767
false
null
class ListNode(var `val`: Int) { var next: ListNode? = null } class Solution { /** * Extension function to convert a List<Int> to ListNode */ fun List<Int>.toListNode(): ListNode? { if (isEmpty()) { return null } val rootNode = ListNode(first()) var currentNode = rootNode for (i in 1 until size) { currentNode.next = ListNode(this[i]) currentNode = currentNode.next!! } return rootNode } /** * Extension function to convert a ListNode to List<Int> */ fun ListNode.toList(): List<Int> { var currentNode: ListNode? = this val result = mutableListOf<Int>() while (currentNode != null) { result.add(currentNode.`val`) currentNode = currentNode.next } return result } /** * mergeKLists * * Simple approach which simply collects all values and does a sort */ fun mergeKLists(lists: Array<ListNode?>): ListNode? { return lists.mapNotNull { it?.toList() }.flatten().sorted().toListNode() } /** * mergeKLists_Weave * * In this solution, we continuously inspect the k lists and the value at lists[i][0]. * We then check all the k lists and take all values that match the root min value. * This way, we iterate through all the k lists at the same time taking the values that we need. */ fun mergeKLists_Weave(lists: Array<ListNode?>): ListNode? { val currentLists = lists.map { it }.toMutableList() var minRootValue = getMinRootValue(currentLists) val result = mutableListOf<Int>() // Keep looping while there is a value at element 0 of the lists while (minRootValue != null) { currentLists.forEachIndexed { index, valuePair -> // Check if the next value in this list matches the min root value val doesMatchMinValue = valuePair?.`val` == minRootValue!! if (doesMatchMinValue) { result.add(minRootValue!!) currentLists[index] = valuePair?.next // We've processed this value, so we can go to the next node } } minRootValue = getMinRootValue(currentLists) } return result.toListNode() } // Returns the smallest value out of all the items at element 0 in all lists private fun getMinRootValue(lists: List<ListNode?>): Int? = lists.mapNotNull { it?.`val` }.min() }
0
Kotlin
0
0
e5e29d992b52e4e20ce14a3574d8c981628f38dc
2,658
LeetCode-Solutions
Academic Free License v1.1
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions40.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round0 /** * 找出数组中最小的k个数 */ fun test40() { val array = intArrayOf(4, 5, 1, 6, 2, 7, 3, 8) print("最小的4个数为:") (array getLeastNumbers2 4).forEach { print("$it ") } println() print("最小的4个数为:") (array getLeastNumbers1 4).forEach { print("$it ") } } /** * 解法一,需要修改输入数组,时间复杂度为O(n) */ infix fun IntArray.getLeastNumbers1(k: Int): IntArray { var index = partition(0, this.size - 1) while (index != k - 1) { if (index > k - 1) { index = partition(0, index - 1) } else { index = partition(index + 1, this.size - 1) } } val output = IntArray(k) for (i in 0 until k) { output[i] = this[i] } return output } /** * 解法二,无需修改输入数组,使用标准类库中的红黑树来实现,时间复杂度为 O(nlogk) */ infix fun IntArray.getLeastNumbers2(k: Int): IntArray { val tree = HashSet<Int>() // Kotlin 标准库里没有红黑树的数据结构,这里为了编译通过暂时用 HashSet 代替 TreeSet forEach { tree.add(it) } val output = IntArray(k) val iterator = tree.iterator() for (i in 0 until k) output[i] = iterator.next() return output }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,217
Algorithm
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2021/Day03.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright (c) 2021 by <NAME> */ /** * Advent of Code 2021, Day 3 - Binary Diagnostic * Problem Description: http://adventofcode.com/2021/day/3 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day3/ */ package com.ginsberg.advent2021 class Day03(private val input: List<String>) { fun solvePart1(): Int { val gamma = input.first().indices.map { column -> if (input.count { it[column] == '1' } > input.size / 2) '1' else '0' }.joinToString("") val epsilon = gamma.map { if (it == '1') '0' else '1' }.joinToString("") return gamma.toInt(2) * epsilon.toInt(2) } fun solvePart2(): Int = input.bitwiseFilter(true).toInt(2) * input.bitwiseFilter(false).toInt(2) private fun List<String>.bitwiseFilter(keepMostCommon: Boolean): String = first().indices.fold(this) { inputs, column -> if (inputs.size == 1) inputs else { val split = inputs.partition { it[column] == '1' } if (keepMostCommon) split.longest() else split.shortest() } }.first() private fun <T> Pair<List<T>, List<T>>.longest(): List<T> = if (first.size >= second.size) first else second private fun <T> Pair<List<T>, List<T>>.shortest(): List<T> = if (first.size < second.size) first else second }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
1,368
advent-2021-kotlin
Apache License 2.0
src/main/kotlin/name/valery1707/problem/leet/code/FizzBuzzK.kt
valery1707
541,970,894
false
null
package name.valery1707.problem.leet.code /** * # 412. Fizz Buzz * * Given an integer `n`, return a string array answer (**1-indexed**) where: * * `answer[i] == "FizzBuzz"` if `i` is divisible by `3` and `5`. * * `answer[i] == "Fizz"` if `i` is divisible by `3`. * * `answer[i] == "Buzz"` if `i` is divisible by `5`. * * `answer[i] == i` (as a string) if none of the above conditions are true. * * ### Constraints * * `1 <= n <= 10^4` * * <a href="https://leetcode.com/problems/fizz-buzz/">412. Fizz Buzz</a> */ interface FizzBuzzK { fun fizzBuzz(n: Int): List<String> @Suppress("EnumEntryName", "unused") enum class Implementation : FizzBuzzK { pure { override fun fizzBuzz(n: Int): List<String> { return (1..n).map { val div3 = it % 3 == 0 val div5 = it % 5 == 0 if (div3 && div5) "FizzBuzz" else if (div3) "Fizz" else if (div5) "Buzz" else it.toString() } } }, mutable { override fun fizzBuzz(n: Int): List<String> { val res = ArrayList<String>(n) for (it in 1..n) { val div3 = it % 3 == 0 val div5 = it % 5 == 0 res.add( if (div3 && div5) "FizzBuzz" else if (div3) "Fizz" else if (div5) "Buzz" else it.toString() ) } return res } }, } }
3
Kotlin
0
0
76d175f36c7b968f3c674864f775257524f34414
1,644
problem-solving
MIT License
src/main/kotlin/g1701_1800/s1771_maximize_palindrome_length_from_subsequences/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1771_maximize_palindrome_length_from_subsequences // #Hard #String #Dynamic_Programming #2023_06_18_Time_248_ms_(100.00%)_Space_69.7_MB_(100.00%) class Solution { fun longestPalindrome(word1: String, word2: String): Int { val len1 = word1.length val len2 = word2.length val len = len1 + len2 val word = word1 + word2 val dp = Array(len) { IntArray(len) } var max = 0 val arr = word.toCharArray() for (d in 1..len) { var i = 0 while (i + d - 1 < len) { if (arr[i] == arr[i + d - 1]) { dp[i][i + d - 1] = if (d == 1) 1 else Math.max(dp[i + 1][i + d - 2] + 2, dp[i][i + d - 1]) if (i < len1 && i + d - 1 >= len1) { max = Math.max(max, dp[i][i + d - 1]) } } else { dp[i][i + d - 1] = Math.max(dp[i + 1][i + d - 1], dp[i][i + d - 2]) } i++ } } return max } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,068
LeetCode-in-Kotlin
MIT License
day05/main.kt
LOZORD
441,007,912
false
{"Kotlin": 29367, "Python": 963}
import java.util.Scanner import java.util.stream.IntStream import java.util.stream.Stream import java.util.TreeMap fun main() { val isPart1 = false // Toggle between the two parts. data class Point(val row: Int, val col: Int) class Line(val from: Point, val to: Point) { fun isDiagonal(): Boolean { return from.row != to.row && from.col != to.col } fun isVeritcal(): Boolean { return from.col == to.col } fun isHorizontal(): Boolean { return from.row == to.row } fun iterator(): Iterator<Point> { if (isVeritcal()) { return IntStream .rangeClosed(Math.min(from.row, to.row), Math.max(from.row, to.row)) .mapToObj({ Point(row=it, col=from.col) }) .iterator() } else if (isHorizontal()) { return IntStream .rangeClosed(Math.min(from.col, to.col), Math.max(from.col, to.col)) .mapToObj({ Point(row=from.row, col=it) }) .iterator() } else { check(isDiagonal()) { "expected to be diagonal" } // Since we are guaranteed lines with 45 degree angles, // we know that the set of points we have to interpolate is // +/- 1 in each direction since the non-hypotenuse sides are // equal in length. // I have a feeling this is the generalized case of the ones above, // but we'll keep things as-is for now. val dist = Math.abs(from.row - to.row) check(dist == Math.abs(from.col - to.col)) { "expected points to have equal component distances" } val rowSign = if (from.row < to.row) 1 else -1 val colSign = if (from.col < to.col) 1 else -1 return IntStream .rangeClosed(0, dist) .mapToObj({ Point( row=from.row + (rowSign * it), col=from.col + (colSign * it), ) }).iterator() } } } val linePattern = Regex("(?<r1>\\d+),(?<c1>\\d+) -> (?<r2>\\d+),(?<c2>\\d+)").toPattern() fun parseLine(s: String): Line { val matcher = linePattern.matcher(s) check(matcher.matches()) { "expected $s to match $linePattern" } return Line( from=Point( row=matcher.group("r1").toInt(), col=matcher.group("c1").toInt() ), to=Point( row=matcher.group("r2").toInt(), col=matcher.group("c2").toInt() ), ) } val input = Scanner(System.`in`) val visited = HashMap<Point, Int>() while(input.hasNextLine()) { val scanned = input.nextLine() val line = parseLine(scanned) if (isPart1 and line.isDiagonal()) { continue } for (point in line.iterator()) { visited.merge(point, 1) { oldValue, _ -> oldValue + 1} } } print("POINTS_WITH_OVERLAP: %d".format( visited.filterValues { it > 1 }.size )) }
0
Kotlin
0
0
17dd266787acd492d92b5ed0d178ac2840fe4d57
3,328
aoc2021
MIT License
project_euler_kotlin/src/main/kotlin/Solution0011.kt
NekoGoddessAlyx
522,068,054
false
{"Kotlin": 44135, "Rust": 24687}
class Solution0011 : Solution() { // 2d grid implemented as a list within a list like so: grid[y][x] // NOTE THE [Y][X] val grid = """ 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """.trimIndent() .split("\n") .map { it.split(" ").map { it.toLong() } } override fun solve(): String { val width = 20 val height = 20 val searchLength = 4 var largestProduct = 0L // dangling column for (y in 0..height - searchLength) { for (x in 0 until width) { val product = grid[y][x] * grid[y + 1][x] * grid[y + 2][x] * grid[y + 3][x] if (product > largestProduct) largestProduct = product } } // row sticking out to the right for (x in 0 .. width - searchLength) { for (y in 0 until height) { val product = grid[y][x] * grid[y][x + 1] * grid[y][x + 2] * grid[y][x + 3] if (product > largestProduct) largestProduct = product } } // down-slanted diagonal for (x in 0 until height - searchLength) { for (y in searchLength - 1 .. height - searchLength) { val product = grid[y][x] * grid[y + 1][x + 1] * grid[y + 2][x + 2] * grid[y + 3][x + 3] if (product > largestProduct) largestProduct = product } } // up-slanted diagonal for (x in 0 until height - searchLength) { for (y in searchLength - 1 until height) { val product = grid[y][x] * grid[y - 1][x + 1] * grid[y - 2][x + 2] * grid[y - 3][x + 3] if (product > largestProduct) largestProduct = product } } return largestProduct.toString() } }
0
Kotlin
0
0
f899b786d5ea5ffd79da51604dc18c16308d2a8a
3,100
Project-Euler
The Unlicense
project/src/problems/FibonacciNumbers.kt
informramiz
173,284,942
false
null
package problems import java.util.* /** * https://codility.com/media/train/11-Fibonacci.pdf */ object FibonacciNumbers { fun findNthFibonacciNumber(n: Int): Int { val fib = Array(n+1) {0} fib[0] = 0 fib[1] = 1 for (i in 2..n) { fib[i] = fib[i-1] + fib[i-2] } return fib[n] } fun findNthFibonacciNumberOptimized(n: Int): Long { var secondLastFibonacci = 0L var lastFibonacci = 1L for (i in 2..n) { val nextFibonacci = lastFibonacci + secondLastFibonacci //now this next nextFibonacci will become last fibonacci for next iteration //and similarly LastFibonacci will become second last secondLastFibonacci = lastFibonacci lastFibonacci = nextFibonacci } return lastFibonacci } /** * Link: https://app.codility.com/programmers/lessons/13-fibonacci_numbers/ladder/ * Ladder * Count the number of different ways of climbing to the top of a ladder. * * * You have to climb up a ladder. The ladder has exactly N rungs, numbered from 1 to N. With each step, you can ascend by one or two rungs. More precisely: * with your first step you can stand on rung 1 or 2, * if you are on rung K, you can move to rungs K + 1 or K + 2, * finally you have to stand on rung N. * Your task is to count the number of different ways of climbing to the top of the ladder. * For example, given N = 4, you have five different ways of climbing, ascending by: * 1, 1, 1 and 1 rung, * 1, 1 and 2 rungs, * 1, 2 and 1 rung, * 2, 1 and 1 rungs, and * 2 and 2 rungs. * Given N = 5, you have eight different ways of climbing, ascending by: * 1, 1, 1, 1 and 1 rung, * 1, 1, 1 and 2 rungs, * 1, 1, 2 and 1 rung, * 1, 2, 1 and 1 rung, * 1, 2 and 2 rungs, * 2, 1, 1 and 1 rungs, * 2, 1 and 2 rungs, and * 2, 2 and 1 rung. * The number of different ways can be very large, so it is sufficient to return the result modulo 2P, for a given integer P. * Write a function: * class Solution { public int[] solution(int[] A, int[] B); } * that, given two non-empty arrays A and B of L integers, returns an array consisting of L integers specifying the consecutive answers; position I should contain the number of different ways of climbing the ladder with A[I] rungs modulo 2B[I]. * For example, given L = 5 and: * A[0] = 4 B[0] = 3 * A[1] = 4 B[1] = 2 * A[2] = 5 B[2] = 4 * A[3] = 5 B[3] = 3 * A[4] = 1 B[4] = 1 * the function should return the sequence [5, 1, 8, 0, 1], as explained above. * Write an efficient algorithm for the following assumptions: * L is an integer within the range [1..50,000]; * each element of array A is an integer within the range [1..L]; * each element of array B is an integer within the range [1..30]. */ fun ladder(A: Array<Int>, B: Array<Int>): Array<Int> { //EXPLANATION: // number of compositions of 1s and 2s that sum up to a total n is F(n+1) Fibonacci number //so F(n+1)-th Fibonacci number will give us total possible ways of climbing a ladder of length N //using steps of either 1 or 2 //reference: https://en.wikipedia.org/wiki/Fibonacci_number //look at Mathematics section of above link val maxA = A.max()!! val maxB = B.max()!! //We need to find Fibonacci numbers up to (maxA+1) to cover all possible lengths //as number of compositions of 1s and 2s that sum up to a total n is F(n+1) //we also need to say inside module (2^maxB) as required in question to avoid data overflow val fibonacciNumbers = findNFibonacciNumbersWithModulo(maxA + 1, BitwiseOperations.powerOf2(maxB)) val count = Array(A.size) {0} for (i in 0 until A.size) { //as number of compositions of 1s and 2s that sum up to a total n is F(n+1) //as we only need to return totalWaysOfClimbing % 2^B[i] according to problem statement so count[i] = BitwiseOperations.mod(fibonacciNumbers[A[i]+1], BitwiseOperations.powerOf2(B[i])) } return count } /** * Returns first n Fibonacci numbers while making sure their value never exceeds module */ fun findNFibonacciNumbersWithModulo(n: Int, modulo: Int): Array<Int> { val fib = Array(n+1) {0} fib[0] = 0 fib[1] = 1 for (i in 2..n) { fib[i] = BitwiseOperations.mod(fib[i-1] + fib[i-2], modulo) } return fib } fun countMinJumps(A: Array<Int>): Int { //get all the Fibonacci numbers until the last Fibonacci number exceeds A.size val fib = getFibonacciNumbersBelowExcept0(A.size).reversed() //as we need to find minimum jumps possible and there can be multiple points which can //lead to the end so we have to go through all those points. We will keep all those points //in queue and use a breadth first search algorithm to pick (BFS). The point the reaches to //the end first will be the one with minimum jumps val queue = LinkedList<Point>() //as initially the frog is at position -1 and jumpsCount 0 so queue.add(Point(-1, 0)) while (!queue.isEmpty()) { //get the next candidate point val point = queue.remove() //for each fibonacci number with value with which a jump is possible, add them to queue for (f in fib) { val nextPosition = point.position + f if (nextPosition == A.size) { //we reached the other bank so just return total jump count return point.jumpCount + 1 } else if (nextPosition >= 0 && nextPosition < A.size && A[nextPosition] == 1) { //we can jump from position i to nextPosition using current fibonacci length f queue.add(Point(nextPosition, point.jumpCount + 1)) //because we have discovered point A[nextPosition] so we mark it as discovered by assigning 0 //Why? Any point that is going to discover/lead to A[nextPosition] after it is already //discovered is obviously taking longer path // i.e: because we are using breadth first search //and A[nextPosition] appeared first in breadth and any point that later discovers A[nextPosition] //is in bottom breadth so that path is definitely not shorter. A[nextPosition] = 0 } } } return -1 } /** * Returns Fibonacci numbers until their value exceeds n */ private fun getFibonacciNumbersBelowExcept0(n: Int): List<Int> { val fib = mutableListOf<Int>() fib.add(1) fib.add(2) while (fib.last() <= n) { fib.add(fib[fib.lastIndex] + fib[fib.lastIndex-1]) } return fib } private data class Point(val position: Int, val jumpCount: Int) }
0
Kotlin
0
0
a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4
7,204
codility-challenges-practice
Apache License 2.0
src/main/kotlin/com/adrielm/aoc2020/solutions/day07/Day07.kt
Adriel-M
318,860,784
false
null
package com.adrielm.aoc2020.solutions.day07 import com.adrielm.aoc2020.common.Algorithms import com.adrielm.aoc2020.common.Solution import org.koin.dsl.module class Day07 : Solution<List<BaggageRule>, Int>(7) { override fun solveProblem1(input: List<BaggageRule>): Int { // build a graph from child to parent val childToParentGraph = mutableMapOf<String, MutableSet<String>>() for (rule in input) { for (child in rule.children) { childToParentGraph.getOrPut(child.colour) { mutableSetOf() }.add(rule.parentColour) } } // start -1 because lambda performs action at every level var parentCountThatHoldsGold = -1 Algorithms.dfsActionEveryLevel(childToParentGraph, "shiny gold") { parentCountThatHoldsGold++ } return parentCountThatHoldsGold } override fun solveProblem2(input: List<BaggageRule>): Int { val parentToChildGraph = mutableMapOf<String, Set<BaggageRule.ChildAndQuantity>>() for (rule in input) { parentToChildGraph[rule.parentColour] = rule.children.toSet() } return Algorithms.dfsReturn<String, BaggageRule.ChildAndQuantity, Int>( graph = parentToChildGraph, start = "shiny gold", getChildKeyLambda = { it.colour }, endOfLevelLambda = { _, childrenAndReturns -> 1 + childrenAndReturns.sumBy { it.child.quantity * it.returnValue } } ) - 1 // exclude the starting baggage } companion object { val module = module { single { Day07() } } } }
0
Kotlin
0
0
8984378d0297f7bc75c5e41a80424d091ac08ad0
1,637
advent-of-code-2020
MIT License
day03/src/main/kotlin/Main.kt
ickybodclay
159,694,344
false
null
import java.io.File data class Claim( val claimNum: Int, val offsetX: Int, val offsetY: Int, val width: Int, val height: Int) fun main() { val input = File(ClassLoader.getSystemResource("input.txt").file) // Write solution here! val claimList = ArrayList<Claim>() val claimRegex = Regex("#(\\d+) @ (\\d+),*(\\d+): (\\d+)x(\\d+)") input.readLines().map { val claimMatch = claimRegex.matchEntire(it)!! val claim = Claim( claimMatch.groups[1]!!.value.toInt(), claimMatch.groups[2]!!.value.toInt(), claimMatch.groups[3]!!.value.toInt(), claimMatch.groups[4]!!.value.toInt(), claimMatch.groups[5]!!.value.toInt()) claimList.add(claim) } val maxWidth = 1000 val maxHeight = 1000 val fabricGrid = Array(maxWidth) { IntArray(maxHeight) } claimList.forEach { mapClaim(fabricGrid, it) } //printGrid(fabricGrid) printPart1Solution(fabricGrid) printPart2Solution(fabricGrid, claimList) } fun mapClaim(grid: Array<IntArray>, claim: Claim) { for (x in claim.offsetX until claim.width + claim.offsetX) { for (y in claim.offsetY until claim.height + claim.offsetY) { grid[x][y]++ } } } fun printPart1Solution(grid: Array<IntArray>) { var sqInches = 0 for (x in 0 until 1000) { for (y in 0 until 1000) { if (grid[x][y] > 1) { sqInches++ } } } println("[part1] square inches of fabric are within two or more claims = $sqInches") } fun printPart2Solution(grid: Array<IntArray>, claimList: List<Claim>) { claimList.forEach { if (!checkClaimForOverlap(grid, it)) { println("[part2] claim that doesn't overlap = $it") } } } fun checkClaimForOverlap(grid: Array<IntArray>, claim: Claim) : Boolean { var overlap = false for (x in claim.offsetX until claim.width + claim.offsetX) { for (y in claim.offsetY until claim.height + claim.offsetY) { if (grid[x][y] > 1) { overlap = true } } } return overlap } fun printGrid(grid: Array<IntArray>) { println("Current Grid State:") for (x in 0 until 1000) { for (y in 0 until 1000) { print(when(grid[x][y]) { 0 -> '.' 1 -> 'x' else -> '#' }) } println() } }
0
Kotlin
0
0
9a055c79d261235cec3093f19f6828997b7a5fba
2,517
aoc2018
Apache License 2.0
src/main/kotlin/y2022/day15/Day15.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2022.day15 import Coord import kotlin.math.abs fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } fun input(): List<Pair<Coord, Coord>> { return AoCGenerics.getInputLines("/y2022/day15/test-input.txt").map { line -> Pair( Coord( x = line.split(" ")[2].split("=")[1].split(",")[0].toInt(), y = line.split(" ")[3].split("=")[1].split(":")[0].toInt() ), Coord( x = line.split(" ")[8].split("=")[1].split(",")[0].toInt(), y = line.split(" ")[9].split("=")[1].toInt() ) ) } } fun floodFillNonBeaconCoords(from: Coord, start:Coord, beacon: Coord,nonBeaconFields: MutableSet<Coord>, depth: Int) { if (depth == 0) return if (from == beacon) return if (nonBeaconFields.contains(from)) return if (from != start) nonBeaconFields.add(from) floodFillNonBeaconCoords(from.copy(x = from.x+1),start, beacon, nonBeaconFields, depth-1) floodFillNonBeaconCoords(from.copy(x = from.x-1),start, beacon, nonBeaconFields, depth-1) floodFillNonBeaconCoords(from.copy(y = from.y+1),start, beacon, nonBeaconFields, depth-1) floodFillNonBeaconCoords(from.copy(y = from.y-1),start, beacon, nonBeaconFields, depth-1) } fun part1(): Int { val nonBeaconCoords: MutableSet<Coord> = mutableSetOf() val sensorBeaconPairs = input() sensorBeaconPairs.forEach { pair -> val sensor = pair.first val beacon = pair.second val taxiDistance = abs(sensor.x - beacon.x) + abs(sensor.y - beacon.y) val nonBeaconFields = mutableSetOf<Coord>() println("For Sensor $sensor filling up to $taxiDistance fields away") floodFillNonBeaconCoords(sensor, sensor, beacon, nonBeaconFields, taxiDistance) nonBeaconCoords.addAll(nonBeaconFields) println(nonBeaconFields) } return nonBeaconCoords.count { coor -> coor.y == 10 } } fun part2(): Int { return 2 }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
2,038
AdventOfCode
MIT License
src/day02/Day02.kt
commanderpepper
574,647,779
false
{"Kotlin": 44999}
package day02 import readInput fun main() { val rockPaperScissors = readInput("day02") val split = rockPaperScissors.map { val split = it.split(" ") split.last() to split.first() } println(split.sumOf { it.determinePoints() }) println(split.sumOf { it.determinePointsFromOutcome() }) } /** * A, X - Rock (1) * B, Y - Paper (2) * C, Z - Scissor (3) */ fun Pair<String, String>.determinePoints(): Int { return when (this.first) { "X" -> 1 + when (this.second) { "A" -> 3 "B" -> 0 "C" -> 6 else -> 0 } "Y" -> 2 + when (this.second) { "A" -> 6 "B" -> 3 "C" -> 0 else -> 0 } "Z" -> 3 + when (this.second) { "A" -> 0 "B" -> 6 "C" -> 3 else -> 0 } else -> 0 } } /** * Outcomes (first column) * X - lose (0) * Y - draw (3) * Z - Win (6) * * A - Rock (1) * B - Paper (2) * C - Scissor (3) */ fun Pair<String, String>.determinePointsFromOutcome(): Int { return when(this.first){ "X" -> 0 + when(this.second){ "A" -> 3 "B" -> 1 "C" -> 2 else -> 0 } "Y" -> 3 + when(this.second){ "A" -> 1 "B" -> 2 "C" -> 3 else -> 0 } "Z" -> 6 + when(this.second){ "A" -> 2 "B" -> 3 "C" -> 1 else -> 0 } else -> 0 } }
0
Kotlin
0
0
fef291c511408c1a6f34a24ed7070ceabc0894a1
1,561
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem547/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem547 /** * LeetCode page: [547. Number of Provinces](https://leetcode.com/problems/number-of-provinces/); */ class Solution { /* Complexity: * Time O(N^2) and Space O(N) where N is the size of isConnected; */ fun findCircleNum(isConnected: Array<IntArray>): Int { val unionFind = UnionFind(isConnected.size) for (aCity in 0 until isConnected.lastIndex) { for (bCity in aCity + 1 until isConnected.size) { if (isConnected[aCity][bCity] == 1) { unionFind.union(aCity, bCity) } } } return unionFind.numUnions() } private class UnionFind(size: Int) { private val parent = IntArray(size) { it } private val rank = IntArray(size) private var numUnions = size fun union(a: Int, b: Int) { val aRoot = find(a) val bRoot = find(b) if (aRoot == bRoot) { return } when { rank[aRoot] < rank[bRoot] -> parent[aRoot] = bRoot rank[aRoot] > rank[bRoot] -> parent[bRoot] = aRoot else -> { parent[bRoot] = aRoot rank[aRoot]++ } } numUnions-- } private tailrec fun find(a: Int): Int { return if (parent[a] == a) a else find(parent[a]) } fun numUnions(): Int { return numUnions } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,546
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/TwoSum.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 /** * 1. Two Sum * @see <a href="https://leetcode.com/problems/two-sum/">Source</a> */ fun interface TwoSumStrategy { operator fun invoke(nums: IntArray, target: Int): IntArray } /** * Approach 1: Brute Force * Time complexity : O(n^2). * Space complexity : O(1). */ class TwoSumBruteForce : TwoSumStrategy { override operator fun invoke(nums: IntArray, target: Int): IntArray { for (i in nums.indices) { for (j in i + 1 until nums.size) { if (nums[j] == target - nums[i]) { return intArrayOf(i, j) } } } return intArrayOf() // or throw IllegalArgumentException("No two sum solution") } } /** * Approach 2: Two-pass Hash Table * Time complexity : O(n). * Space complexity : O(n). */ class TwoSumTwoPassHashTable : TwoSumStrategy { override operator fun invoke(nums: IntArray, target: Int): IntArray { val map: MutableMap<Int, Int> = HashMap() for (i in nums.indices) { map[nums[i]] = i } for (i in nums.indices) { val complement = target - nums[i] if (map.containsKey(complement) && map[complement] != i) { return intArrayOf(i, map.getOrDefault(complement, 0)) } } return intArrayOf() // or throw IllegalArgumentException("No two sum solution") } } /** * Approach 3: One-pass Hash Table * Time complexity : O(n). * Space complexity : O(n). */ class TwoSumOnePassHashTable : TwoSumStrategy { override operator fun invoke(nums: IntArray, target: Int): IntArray { val map: MutableMap<Int, Int> = HashMap() for (i in nums.indices) { val complement = target - nums[i] if (map.containsKey(complement)) { map[complement]?.let { return intArrayOf(it, i) } } map[nums[i]] = i } return intArrayOf() } } /** * Approach 4: Kotlin style One-pass Hash Table * Time complexity : O(n). * Space complexity : O(n). */ class TwoSumOneHashMap : TwoSumStrategy { override operator fun invoke(nums: IntArray, target: Int): IntArray { val map: MutableMap<Int, Int> = HashMap() nums.forEachIndexed { index, i -> map[i]?.let { return intArrayOf(it, index) } map[target - i] = index } return intArrayOf() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,100
kotlab
Apache License 2.0
src/day10/second/Solution.kt
verwoerd
224,986,977
false
null
package day10.second import day10.first.bestStationLocation import day10.first.readAsteroidsMap import tools.Coordinate import tools.timeSolution import java.util.concurrent.LinkedBlockingDeque import kotlin.math.PI import kotlin.math.abs import kotlin.math.atan2 fun main() = timeSolution { val map = readAsteroidsMap() val stationLocation = bestStationLocation(map).second // Create a Linked Double Ended Queue, ordered by the relative angles and closes asteroids first as tie breaker val angleList = LinkedBlockingDeque(map.filter { stationLocation != it } .map { val xDiff = (it.x - stationLocation.x).toDouble() val yDiff = (it.y - stationLocation.y).toDouble() // Calculate the angle relative to up abs(atan2(xDiff, yDiff) - PI) to it }.sortedWith(Comparator { o1, o2 -> // sort by angle, then by closest x, then by closest y (relative to the stationLocation) when (val diff = o1.first.compareTo(o2.first)) { 0 -> when(val xDiff = (stationLocation.x - o1.second.x).compareTo(stationLocation.x - o2.second.x)) { 0 -> (stationLocation.y - o1.second.y).compareTo(stationLocation.y - o2.second.y) else -> xDiff } else -> diff } })) var count = 0 var lastAngle: Double = -0.1 var lastCoordinate = Coordinate(0, 0) while (angleList.isNotEmpty() && count < 200) { val angle = angleList.removeFirst() when (angle.first) { // we just shot and asteroid at this angle already, move the turret first, so back of the line lastAngle -> angleList.add(angle) // shoot down the asteroid else -> { lastAngle = angle.first lastCoordinate = angle.second count++ } } } println(lastCoordinate.x *100 + lastCoordinate.y) }
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
2,012
AoC2019
MIT License
src/main/kotlin/aoc2022/Day21.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2022 import AoCDay import aoc2022.Job.YellNumber import aoc2022.Job.YellOperation import util.illegalInput private typealias Monkey = String private sealed interface Job { class YellNumber(val number: Long) : Job sealed class YellOperation(val left: Monkey, val right: Monkey) : Job { operator fun component1() = left operator fun component2() = right class Add(left: Monkey, right: Monkey) : YellOperation(left, right) class Subtract(left: Monkey, right: Monkey) : YellOperation(left, right) class Multiply(left: Monkey, right: Monkey) : YellOperation(left, right) class Divide(left: Monkey, right: Monkey) : YellOperation(left, right) } } private typealias MonkeyJobs = Map<Monkey, Job> // https://adventofcode.com/2022/day/21 object Day21 : AoCDay<Long>( title = "Monkey Math", part1ExampleAnswer = 152, part1Answer = 82225382988628, part2ExampleAnswer = 301, part2Answer = 3429411069028, ) { private fun parseJob(job: String) = job.toLongOrNull()?.let(::YellNumber) ?: run { val (left, op, right) = job.split(' ', limit = 3) when (op) { "+" -> YellOperation.Add(left, right) "-" -> YellOperation.Subtract(left, right) "*" -> YellOperation.Multiply(left, right) "/" -> YellOperation.Divide(left, right) else -> illegalInput(job) } } private fun parseMonkeyJobs(input: String) = input .lineSequence() .map { line -> line.split(": ", limit = 2) } .associate { (monkey, job) -> monkey to parseJob(job) } private const val ROOT = "root" private const val HUMN = "humn" context(MonkeyJobs) private val Monkey.job get() = this@MonkeyJobs.getValue(this@Monkey) context(MonkeyJobs) private fun Monkey.yell(): Long = when (val job = job) { is YellNumber -> job.number is YellOperation.Add -> job.left.yell() + job.right.yell() is YellOperation.Subtract -> job.left.yell() - job.right.yell() is YellOperation.Multiply -> job.left.yell() * job.right.yell() is YellOperation.Divide -> job.left.yell() / job.right.yell() } context(MonkeyJobs) private operator fun Monkey.contains(other: Monkey): Boolean = this == other || when (val job = this.job) { is YellNumber -> false is YellOperation -> other in job.left || other in job.right } override fun part1(input: String) = with(parseMonkeyJobs(input)) { ROOT.yell() } override fun part2(input: String): Long { val jobs = parseMonkeyJobs(input) with(jobs - ROOT - HUMN) { var (monkey, target) = run { val (left, right) = jobs[ROOT] as YellOperation if (with(jobs) { HUMN in left }) left to right.yell() else right to left.yell() } while (monkey != HUMN) { val job = monkey.job as YellOperation val (left, right) = job val humnInLeft = HUMN in left val known = (if (humnInLeft) right else left).yell() target = when (job) { is YellOperation.Add -> target - known is YellOperation.Subtract -> if (humnInLeft) target + known else known - target is YellOperation.Multiply -> target / known is YellOperation.Divide -> if (humnInLeft) target * known else known / target } monkey = if (humnInLeft) left else right } return target } } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
3,635
advent-of-code-kotlin
MIT License
TwoSumLessThanTarget.kt
sysion
353,734,921
false
null
/** * https://leetcode.com/problems/two-sum-less-than-k/ * * 1. Two Sum Less Than K * * Given an array A of integers and integer K, return the maximum S such that * there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying * this equation, return -1. * * Example 1: * Input: A = [34,23,1,24,75,33,54,8], K = 60 * Output: 58 * Explanation: * We can use 34 and 24 to sum 58 which is less than 60. * * Example 2: * Input: A = [10,20,30], K = 15 * Output: -1 * Explanation: * In this case it's not possible to get a pair sum less that 15. * * Note: * 1 <= A.length <= 100 * 1 <= A[i] <= 1000 * 1 <= K <= 2000 */ fun main(){ //val inputArray: IntArray = intArrayOf(34,23,1,24,75,33,54,8) //var targetSum = 60; val inputArray: IntArray = intArrayOf(10,20,30) var targetSum = 15; SumTwoNumbersLessThanTarget(inputArray, targetSum) } fun SumTwoNumbersLessThanTarget(intArray: IntArray, target: Int): Int { var SumLessThanTarget = -1 return SumLessThanTarget }
0
Kotlin
0
0
6f9afda7f70264456c93a69184f37156abc49c5f
993
DataStructureAlgorithmKt
Apache License 2.0
src/main/kotlin/com/leetcode/P994.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode import java.util.* // https://github.com/antop-dev/algorithm/issues/487 class P994 { fun orangesRotting(grid: Array<IntArray>): Int { val queue = LinkedList<Pair<Int, Int>>() val fresh = intArrayOf(0) // 함수에 값을 넘기기위해 참조로 씀 for (y in grid.indices) { for (x in grid[y].indices) { when (grid[y][x]) { 1 -> fresh[0]++ // fresh 카운팅 2 -> queue += y to x // rotten 위치 큐에 저장 } } } if (fresh[0] == 0) return 0 var minutes = -1 while (queue.isNotEmpty()) { repeat(queue.size) { val (y, x) = queue.poll() go(queue, grid, fresh, y - 1, x) // 북 go(queue, grid, fresh, y, x + 1) // 동 go(queue, grid, fresh, y + 1, x) // 남 go(queue, grid, fresh, y, x - 1) // 서 } minutes++ } return if (fresh[0] == 0) minutes else -1 } private fun go(queue: LinkedList<Pair<Int, Int>>, grid: Array<IntArray>, fresh: IntArray, y: Int, x: Int) { if (y >= 0 && y < grid.size && x >= 0 && x < grid[y].size && grid[y][x] == 1) { queue += y to x grid[y][x] = 2 fresh[0]-- } } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,374
algorithm
MIT License
src/y2023/Day16.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.Cardinal import util.Pos import util.readInput import util.timingStatistics import y2023.Day14.coerce object Day16 { data class Tile( val pos: Pos, val type: Type, ) enum class Type(val c: Char) { SPLITTER_UP('|'), SPLITTER_FLAT('-'), MIRROR_BACK('\\'), MIRROR_FORWARD('/'); fun nextDirectionAfter(direction: Cardinal): List<Cardinal> { return when (this) { SPLITTER_UP -> { when (direction) { Cardinal.NORTH, Cardinal.SOUTH -> listOf(direction) Cardinal.EAST, Cardinal.WEST -> listOf(Cardinal.NORTH, Cardinal.SOUTH) } } SPLITTER_FLAT -> { when (direction) { Cardinal.NORTH, Cardinal.SOUTH -> listOf(Cardinal.EAST, Cardinal.WEST) Cardinal.EAST, Cardinal.WEST -> listOf(direction) } } MIRROR_BACK -> { when (direction) { Cardinal.NORTH -> listOf(Cardinal.WEST) Cardinal.SOUTH -> listOf(Cardinal.EAST) Cardinal.EAST -> listOf(Cardinal.SOUTH) Cardinal.WEST -> listOf(Cardinal.NORTH) } } MIRROR_FORWARD -> { when (direction) { Cardinal.NORTH -> listOf(Cardinal.EAST) Cardinal.SOUTH -> listOf(Cardinal.WEST) Cardinal.EAST -> listOf(Cardinal.NORTH) Cardinal.WEST -> listOf(Cardinal.SOUTH) } } } } } data class Energization( val pos: Pos, val direction: Cardinal ) private fun tileType(c: Char): Type { return when (c) { '-' -> Type.SPLITTER_FLAT '|' -> Type.SPLITTER_UP '\\' -> Type.MIRROR_BACK '/' -> Type.MIRROR_FORWARD else -> throw IllegalArgumentException("Unknown tile type: $c") } } private fun parse(input: List<String>): List<Tile> { return input.flatMapIndexed { row, line -> line.mapIndexedNotNull { col, c -> if (c == '.') null else Tile( pos = Pos(row, col), type = tileType(c) ) } } } fun part1(input: List<String>): Long { val parsed = parse(input) val dimensions = input.size - 1 to input.first().length - 1 val tilesByPos = parsed.associateBy { it.pos } return countEnergized(tilesByPos, dimensions, 0 to 0, Cardinal.EAST) } private fun countEnergized( tilesByPos: Map<Pos, Tile>, dimensions: Pair<Int, Int>, start: Pos, direction: Cardinal ): Long { val energized = mutableSetOf<Energization>() var frontier = setOf(Energization(start, direction)) while (frontier.isNotEmpty()) { energized.addAll(frontier) frontier = frontier.flatMap { next(it, tilesByPos, dimensions) }.toSet() frontier = frontier - energized } return energized.map { it.pos }.toSet().size.toLong() } private fun next( from: Energization, tilesByPos: Map<Pair<Int, Int>, Tile>, dimensions: Pair<Int, Int> ): List<Energization> { val tile = tilesByPos[from.pos] val nextDirections = tile?.type?.nextDirectionAfter(from.direction) ?: listOf(from.direction) return nextDirections.map { dir -> Energization( dir.of(from.pos), dir ) }.filter { it.pos == it.pos.coerce(dimensions) } } fun part2(input: List<String>): Long { val parsed = parse(input) val dimensions = input.size - 1 to input.first().length - 1 val tilesByPos = parsed.associateBy { it.pos } val starts = (0..dimensions.first).flatMap { row -> listOf((row to 0) to Cardinal.EAST, (row to dimensions.second) to Cardinal.WEST) } + (0..dimensions.second).flatMap { col -> listOf((0 to col) to Cardinal.SOUTH, (dimensions.first to col) to Cardinal.NORTH) } return starts.maxOf { start -> countEnergized(tilesByPos, dimensions, start.first, start.second) } } } fun main() { val testInput = """ .|...\.... |.-.\..... .....|-... ........|. .......... .........\ ..../.\\.. .-.-/..|.. .|....-|.\ ..//.|.... """.trimIndent().split("\n") println("------Tests------") println(Day16.part1(testInput)) println(Day16.part2(testInput)) println("------Real------") val input = readInput(2023, 16) println("Part 1 result: ${Day16.part1(input)}") println("Part 2 result: ${Day16.part2(input)}") timingStatistics { Day16.part1(input) } timingStatistics { Day16.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
5,171
advent-of-code
Apache License 2.0
src/day3/p2.kt
TimCastelijns
113,205,922
false
null
package day3 enum class Direction { RIGHT, UP, LEFT, DOWN } var n = 100 val grid = Array(n) { Array(n, { "" }) } fun surroundingsSum(x: Int, y: Int): Int { var sum = 0 if (y > 0 && x > 0) { if (grid[y - 1][x - 1] != "") { val add = grid[y - 1][x - 1].trim().toInt() sum += add } } if (y > 0 && x <= n - 1) { if (grid[y - 1][x] != "") { val add = grid[y - 1][x].trim().toInt() sum += add } } if (y > 0 && x < n - 1) { if (grid[y - 1][x + 1] != "") { val add = grid[y - 1][x + 1].trim().toInt() sum += add } } if (x > 0 && y <= n - 1) { if (grid[y][x - 1] != "") { val add = grid[y][x - 1].trim().toInt() sum += add } } if (x < n - 1 && y <= n - 1) { if (grid[y][x + 1] != "") { val add = grid[y][x + 1].trim().toInt() sum += add } } if (y < n - 1 && x > 0) { if (grid[y + 1][x - 1] != "") { val add = grid[y + 1][x - 1].trim().toInt() sum += add } } if (x <= n - 1 && y < n - 1) { if (grid[y + 1][x] != "") { val add = grid[y + 1][x].trim().toInt() sum += add } } if (y < n - 1 && x < n - 1) { if (grid[y + 1][x + 1] != "") { val add = grid[y + 1][x + 1].trim().toInt() sum += add } } return sum } fun main(args: Array<String>) { var dir = Direction.RIGHT var y = n / 2 var x = if (n % 2 == 0) y - 1 else y var iteration = 0; for (j in 1..n * n - 1 + 1) { iteration++; if (iteration == 1) { grid[y][x] = "1" } else { val s = surroundingsSum(x, y) if (s > 265149) { println(s) break } grid[y][x] = "%d".format(s) } when (dir) { Direction.RIGHT -> if (x <= n - 1 && grid[y - 1][x].none() && j > 1) dir = Direction.UP Direction.UP -> if (grid[y][x - 1].none()) dir = Direction.LEFT Direction.LEFT -> if (x == 0 || grid[y + 1][x].none()) dir = Direction.DOWN Direction.DOWN -> if (grid[y][x + 1].none()) dir = Direction.RIGHT } when (dir) { Direction.RIGHT -> x++ Direction.UP -> y-- Direction.LEFT -> x-- Direction.DOWN -> y++ } } for (row in grid) println(row.joinToString("") { s -> "[%6d]".format(s.toInt()) }) println() }
0
Kotlin
0
0
656f2a424b323175cd14d309bc25430ac7f7250f
2,610
aoc2017
MIT License
src/main/kotlin/aoc2020/day01_report_repair/ReportRepair.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package aoc2020.day01_report_repair fun main() { util.solve(73371, ::partOne) util.solve(127642310, ::partTwo) } private const val TARGET = 2020 private fun List<Int>.findAddends(total: Int): Pair<Int, Int>? { val set = hashSetOf<Int>() this.forEach { if (it >= total) return@forEach val rest = total - it if (set.contains(rest)) { return Pair(rest, it) } set.add(it) } return null } fun partOne(input: String): Int = input .lines() .map(Integer::parseInt) .findAddends(TARGET) ?.let { (a, b) -> a * b } ?: throw IllegalStateException("No pair found?!") fun partTwo(input: String): Int { val items = input .lines() .map(Integer::parseInt) items.forEachIndexed { i, it -> items.subList(0, i) .findAddends(TARGET - it) ?.let { (a, b) -> return a * b * it } } throw IllegalStateException("No pair found?!") }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
971
aoc-2021
MIT License
src/main/kotlin/com/ginsberg/advent2023/Day10.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 10 - Pipe Maze * Problem Description: http://adventofcode.com/2023/day/10 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day10/ */ package com.ginsberg.advent2023 import com.ginsberg.advent2023.Point2D.Companion.EAST import com.ginsberg.advent2023.Point2D.Companion.NORTH import com.ginsberg.advent2023.Point2D.Companion.SOUTH import com.ginsberg.advent2023.Point2D.Companion.WEST class Day10(input: List<String>) { private val grid: Array<CharArray> = input.map { it.toCharArray() }.toTypedArray() private val start: Point2D = grid.indexOfFirst { 'S' in it }.let { y -> Point2D(grid[y].indexOf('S'), y) } fun solvePart1(): Int = traversePipe().size / 2 fun solvePart2(): Int { val pipe = traversePipe() grid.forEachIndexed { y, row -> row.forEachIndexed { x, c -> val at = Point2D(x, y) if (at !in pipe) grid[at] = '.' } } val emptyCorner = listOf( Point2D(0, 0), Point2D(0, grid[0].lastIndex), Point2D(grid.lastIndex, 0), Point2D(grid.lastIndex, grid[0].lastIndex) ) .first { grid[it] == '.' } traversePipe { current, direction, nextDirection -> grid.floodFill(current + markingDirection.getValue(direction), 'O') if (grid[current] in setOf('7', 'L', 'J', 'F')) { grid.floodFill(current + markingDirection.getValue(nextDirection), 'O') } } val find = if (grid[emptyCorner] == 'O') '.' else 'O' return grid.sumOf { row -> row.count { it == find } } } private fun traversePipe(preMove: (Point2D, Point2D, Point2D) -> (Unit) = { _, _, _ -> }): Set<Point2D> { val pipe = mutableSetOf(start) var current = start .cardinalNeighbors() .filter { grid.isSafe(it) } .first { val d = it - start (grid[it] to d in movements) } var direction = current - start while (current != start) { pipe += current movements[grid[current] to direction]?.let { nextDirection -> preMove(current, direction, nextDirection) direction = nextDirection current += direction } ?: error("Invalid movement detected: $current, $direction") } return pipe } private fun Array<CharArray>.floodFill(at: Point2D, c: Char) { if (!isSafe(at)) return val queue = ArrayDeque<Point2D>().apply { add(at) } while (queue.isNotEmpty()) { val next = queue.removeFirst() if (this[next] == '.') { this[next] = c queue.addAll(next.cardinalNeighbors().filter { isSafe(it) }) } } } private val movements: Map<Pair<Char, Point2D>, Point2D> = mapOf( ('|' to SOUTH) to SOUTH, ('|' to NORTH) to NORTH, ('-' to EAST) to EAST, ('-' to WEST) to WEST, ('L' to WEST) to NORTH, ('L' to SOUTH) to EAST, ('J' to SOUTH) to WEST, ('J' to EAST) to NORTH, ('7' to EAST) to SOUTH, ('7' to NORTH) to WEST, ('F' to WEST) to SOUTH, ('F' to NORTH) to EAST ) private val markingDirection: Map<Point2D, Point2D> = mapOf( SOUTH to EAST, NORTH to WEST, WEST to SOUTH, EAST to NORTH ) }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
3,705
advent-2023-kotlin
Apache License 2.0
kotlin/2018/qualification-round/cubic-ufo/src/main/kotlin/AnalysisSolution.kt
ShreckYe
345,946,821
false
null
import kotlin.math.acos import kotlin.math.cos import kotlin.math.sin import kotlin.math.sqrt fun main() { val t = readLine()!!.toInt() repeat(t, ::testCase) } fun testCase(ti: Int) { val a = readLine()!!.toFloat() // `op` stands for "original point" and `hp` stands for "highest point". val op = doubleArrayOf(0.5, 0.5, 0.5) val hpy = a.toDouble() / 2 // by the cube shadow theorem val hpxz = sqrt((square(0.5) * 3 - square(hpy)) / 2) val hp = doubleArrayOf(hpy, hpxz, hpxz) val cosTheta = ((hp * op) / (hp.magnitude() * op.magnitude())).coerceAtMost(1.0) val theta = acos(cosTheta) val axis = doubleArrayOf(-sqrt(1.0 / 2), 0.0, sqrt(1.0 / 2)) val originalFaceCenters = listOf( doubleArrayOf(0.5, 0.0, 0.0), doubleArrayOf(0.0, 0.5, 0.0), doubleArrayOf(0.0, 0.0, 0.5) ) val rotationMatrix = rotationMatrix(axis, theta) val faceCenters = originalFaceCenters.map { rotationMatrix * it } println("Case #${ti + 1}:\n${faceCenters.joinToString("\n") { it.joinToString(" ") }}") } fun square(x: Double): Double = x * x // vector operations operator fun DoubleArray.times(that: DoubleArray): Double { require(size == that.size) return (this zip that).sumByDouble { it.first * it.second } } fun DoubleArray.magnitude() = sqrt(sumByDouble(::square)) // see: https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle fun rotationMatrix(u: DoubleArray, theta: Double): Array<DoubleArray> { val (ux, uy, uz) = u val cosTheta = cos(theta) val sinTheta = sin(theta) fun firstRow(ux: Double, uy: Double, uz: Double) = doubleArrayOf( cosTheta + square(ux) * (1 - cosTheta), ux * uy * (1 - cosTheta) - uz * sinTheta, ux * uz * (1 - cosTheta) + uy * sinTheta ) return arrayOf( firstRow(ux, uy, uz), firstRow(uy, uz, ux).let { doubleArrayOf(it[2], it[0], it[1]) }, firstRow(uz, ux, uy).let { doubleArrayOf(it[1], it[2], it[0]) } ) } operator fun Array<DoubleArray>.times(thatVector: DoubleArray) = map { it * thatVector }.toDoubleArray()
0
Kotlin
1
1
743540a46ec157a6f2ddb4de806a69e5126f10ad
2,159
google-code-jam
MIT License
src/array/LeetCode334.kt
Alex-Linrk
180,918,573
false
null
package array /** * 给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。 *数学表达式如下: * *如果存在这样的 i, j, k,  且满足 0 ≤ i < j < k ≤ n-1, *使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。 *说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。 * *示例 1: * *输入: [1,2,3,4,5] *输出: true *示例 2: * *输入: [5,4,3,2,1] *输出: false * *来源:力扣(LeetCode) *链接:https://leetcode-cn.com/problems/increasing-triplet-subsequence *著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ class LeetCode334 { fun increasingTriplet(nums: IntArray): Boolean { var one = Integer.MAX_VALUE var two = Integer.MAX_VALUE for (n in nums) { when { n <= one -> one = n n <= two -> two = n else -> return true } } return false } } fun main() { println(LeetCode334().increasingTriplet(intArrayOf(5,1,5,5,2,5,4))) println(LeetCode334().increasingTriplet(intArrayOf(2,1,3,4,5))) println(LeetCode334().increasingTriplet(intArrayOf(5,4,3,2,1))) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
1,283
LeetCode
Apache License 2.0
src/main/kotlin/days/Day2.kt
broersma
574,686,709
false
{"Kotlin": 20754}
package days class Day2 : Day(2) { override fun partOne(): Any { val scores = mapOf("A" to 0, "B" to 1, "C" to 2, "X" to 0, "Y" to 1, "Z" to 2) return inputList .filter { it.isNotEmpty() } .map { val (a, b) = it.split(" ") scores[a]!! to scores[b]!! } .map { (a, b) -> val s = if ((a + 1) % 3 == b) { 6 } else if ((b + 1) % 3 == a) { 0 } else { 3 } s + b + 1 } .sum() } override fun partTwo(): Any { val scores = mapOf("A" to 0, "B" to 1, "C" to 2, "X" to 2, "Y" to 0, "Z" to 1) return inputList .filter { it.isNotEmpty() } .map { val (a, b) = it.split(" ") scores[a]!! to scores[b]!! } .map { (a, b) -> a to (a + b) % 3 } .map { (a, b) -> val s = if ((a + 1) % 3 == b) { 6 } else if ((b + 1) % 3 == a) { 0 } else { 3 } s + b + 1 } .sum() } }
0
Kotlin
0
0
cd3f87e89f7518eac07dafaaeb0f6adf3ecb44f5
1,583
advent-of-code-2022-kotlin
Creative Commons Zero v1.0 Universal
src/main/kotlin/problems/Day19.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems import java.util.* import kotlin.math.* typealias Point = Triple<Int, Int, Int> typealias Distance = Triple<Int, Int, Int> typealias RotationFunction = (Triple<Int, Int, Int>) -> Triple<Int, Int, Int> class Day19(override val input: String) : Problem { override val number: Int = 19 private val beaconsSeenFromScanner: Map<Int, List<Point>> = input.split("\n\n").associate { scanner -> val scannerNumber = """\d+""".toRegex() .find(scanner.lines().first())!! .groupValues .single() .toInt() scannerNumber to scanner.lines().drop(1).map { beaconCoords -> val (x, y, z) = beaconCoords.split(",").map { it.toInt() } Triple(x, y, z) } } private val numberOfScanners = beaconsSeenFromScanner.keys.maxOf { it } private val possibleRotations = listOf(0.0, PI / 2, PI, 3 * PI / 2) private val rotationFunctions = possibleRotations.flatMap { xRotation -> possibleRotations.flatMap { yRotation -> possibleRotations.map { zRotation -> { a: Point -> a.rotateZ(zRotation).rotateY(yRotation).rotateX(xRotation) } } } } private val connections:MutableMap<Int, MutableMap<Int, Pair<Point, (Point) -> Point>>> by lazy {findScannerConnections()} override fun runPartOne(): String { val connectionGraph = connections.map { (key, values) -> key to values.keys.toList() }.toMap() val prev = dijkstra(connectionGraph, 0) val beacons = mutableSetOf<Point>() beacons.addAll(beaconsSeenFromScanner[0]!!) for (source in 1..numberOfScanners) { val pathToRoot = path(prev, source).reversed() val toBeacons = pathToRoot.zipWithNext().fold(beaconsSeenFromScanner[source]!!) { acc, (iterFrom, iterTo) -> val (iterOrigin, iterRotationFunction) = connections[iterTo]!![iterFrom]!! translateCoordinates(acc, iterOrigin, iterRotationFunction) } beacons.addAll(toBeacons) } return beacons.size.toString() } override fun runPartTwo(): String { val connectionGraph = connections.map { (key, values) -> key to values.keys.toList() }.toMap() val prev = dijkstra(connectionGraph, 0) val scannersOrigins = mutableMapOf<Int, Point>() scannersOrigins[0] = Point(0,0,0) for (source in 1..numberOfScanners) { val pathToRoot = path(prev, source).reversed() val toBeacons = pathToRoot.zipWithNext().fold(Point(0,0,0)) { acc, (iterFrom, iterTo) -> val (iterOrigin, iterRotationFunction) = connections[iterTo]!![iterFrom]!! translateCoordinates(listOf(acc), iterOrigin, iterRotationFunction).single() } scannersOrigins[source] = toBeacons } var maxDistance = -1 for (scannerOne in 0..numberOfScanners) { for (scannerTwo in scannerOne+1..numberOfScanners) { val distance = scannersOrigins[scannerOne]!!.manhattanDistance(scannersOrigins[scannerTwo]!!) if (distance > maxDistance) { maxDistance = distance } } } return maxDistance.toString() } private fun findScannerConnections(): MutableMap<Int, MutableMap<Int, Pair<Point, (Point) -> Point>>> { val connections = mutableMapOf<Int, MutableMap<Int, Pair<Point, (Point) -> Point>>>() (0..numberOfScanners).forEach{scanner -> connections[scanner] = mutableMapOf() } for (scannerOne in 0..numberOfScanners) { for (scannerTwo in scannerOne + 1..numberOfScanners) { val overlap = overlapScanners(scannerOne, scannerTwo) if (overlap != null) { connections.computeIfAbsent(scannerOne) { mutableMapOf() } connections.computeIfAbsent(scannerTwo) { mutableMapOf() } connections[scannerOne]!![scannerTwo] = overlap connections[scannerTwo]!![scannerOne] = overlapScanners(scannerTwo, scannerOne)!! } } } return connections } fun dijkstra(connections: Map<Int, List<Int>>, source: Int): MutableList<Int> { val distance = MutableList<Long>(numberOfScanners + 1) { Int.MAX_VALUE.toLong() } val prev = MutableList(numberOfScanners + 1) { -1 } distance[source] = 0 val queue = PriorityQueue<Int>(compareBy { distance[it] }) queue.addAll(connections.keys) while (queue.isNotEmpty()) { val u = queue.poll()!! connections[u]!!.forEach { neighbour -> val alt = distance[u] + 1 if (alt < distance[neighbour]) { distance[neighbour] = alt prev[neighbour] = u if (queue.remove(neighbour)) { queue.add(neighbour) } } } } return prev } fun path(prev: List<Int>, to: Int): List<Int> { val path = mutableListOf<Int>() var current = to if (prev[current] != -1) { while (current != -1) { path.add(0, current) current = prev[current] } } return path } fun translateCoordinates(points: List<Point>, oldOrigin: Point, rotationFunction: RotationFunction): List<Point> { return points.map(rotationFunction).map { it + oldOrigin } } fun overlapScanners( originScannerIdx: Int, otherScannerIdx: Int ): Pair<Point, RotationFunction>? { val originScannerDistances = calculateDistances(beaconsSeenFromScanner[originScannerIdx]!!) for (rotationFunction in rotationFunctions) { val otherScannerBeaconsPostRotation = beaconsSeenFromScanner[otherScannerIdx]!!.map(rotationFunction) val otherScannerDistances = calculateDistances(otherScannerBeaconsPostRotation) val distanceIntersection = intersectDistances(originScannerDistances, otherScannerDistances) val a = distanceIntersection.indices.map { beaconIdx -> beaconsSeenFromScanner[originScannerIdx]!![distanceIntersection[beaconIdx].first] - rotationFunction( beaconsSeenFromScanner[otherScannerIdx]!![distanceIntersection[beaconIdx].second] ) }.toSet() if (a.size == 1) { return Pair(a.single(), rotationFunction) } } return null } fun calculateDistances(beacons: List<Point>): List<List<Distance>> { return beacons.map { first -> beacons.map { second -> first - second } } } fun intersectDistances( scannerA: List<List<Distance>>, scannerB: List<List<Distance>> ): List<Pair<Int, Int>> { return (scannerA.indices).flatMap { a -> scannerB.indices.map { b -> Pair(a, b) } } .map { Pair(it, scannerA[it.first].toSet().intersect(scannerB[it.second].toSet())) } .filter { it.second.size >= 12 } .map { it.first } } operator fun Point.minus(other: Point): Point { return Point(first - other.first, second - other.second, third - other.third) } operator fun Point.plus(other: Point): Point { return Point(first + other.first, second + other.second, third + other.third) } // Rotation formulas // https://www.mathworks.com/matlabcentral/answers/123763-how-to-rotate-entire-3d-data-with-x-y-z-values-along-a-particular-axis-say-x-axis#comment_487621 fun Point.rotateX(angle: Double): Point { val (x, y, z) = this val newX = x val newY = (y * cos(angle) - z * sin(angle)).roundToInt() val newZ = (y * sin(angle) + z * cos(angle)).roundToInt() return Point(newX, newY, newZ) } fun Point.rotateY(angle: Double): Point { val (x, y, z) = this val newX = (x * cos(angle) + z * sin(angle)).roundToInt() val newY = y val newZ = (z * cos(angle) - x * sin(angle)).roundToInt() return Triple(newX, newY, newZ) } fun Point.rotateZ(angle: Double): Point { val (x, y, z) = this val newX = (x * cos(angle) - y * sin(angle)).roundToInt() val newY = (x * sin(angle) + y * cos(angle)).roundToInt() val newZ = z return Triple(newX, newY, newZ) } fun Point.manhattanDistance(other: Point) : Int { val difference = this-other return difference.first.absoluteValue + difference.second.absoluteValue + difference.third.absoluteValue } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
8,859
AdventOfCode2021
MIT License
src/main/kotlin/day9/Day9.kt
mortenberg80
574,042,993
false
{"Kotlin": 50107}
package day9 import java.lang.IllegalArgumentException class Day9(val input: List<String>) { private val board = Board(Point(0, 0), Point(0, 0), Point(0, 0), mapOf()) private val rope = (1..10).map { Point(0, 0) }.toMutableList() private val board2 = Board2(Point(0, 0), rope, mutableMapOf()) private fun toCommandList(input: String): List<Command> { val direction = input.split(" ")[0] val repetitions = input.split(" ")[1].toInt() return when (direction) { "U" -> (1..repetitions).map { Command.Up(1) } "D" -> (1..repetitions).map { Command.Down(1) } "L" -> (1..repetitions).map { Command.Left(1) } "R" -> (1..repetitions).map { Command.Right(1) } else -> { throw IllegalArgumentException() } } } fun part1(): Int { val resultingBoard = input.flatMap { toCommandList(it) } .fold(board) { board, command -> board.handleCommand(command) } return resultingBoard.tailVisitationMap.size } fun part2(): Int { val resultingBoard = input.flatMap { toCommandList(it) } .fold(board2) { board2, command -> board2.handleCommand(command) } return resultingBoard.tailVisitationMap.size } } data class Board(val start: Point, val head: Point, val tail: Point, val tailVisitationMap: Map<Point, Int>) { fun handleCommand(command: Command): Board { when (command) { is Command.Down -> { val newHead = Point(head.x, head.y - 1) val newTail = calculateTail(newHead, tail) val count = tailVisitationMap[newTail] ?: 0 return this.copy( head = newHead, tail = newTail, tailVisitationMap = tailVisitationMap + (newTail to count + 1) ) } is Command.Left -> { val newHead = Point(head.x - 1, head.y) val newTail = calculateTail(newHead, tail) val count = tailVisitationMap[newTail] ?: 0 return this.copy( head = newHead, tail = newTail, tailVisitationMap = tailVisitationMap + (newTail to count + 1) ) } is Command.Right -> { val newHead = Point(head.x + 1, head.y) val newTail = calculateTail(newHead, tail) val count = tailVisitationMap[newTail] ?: 0 return this.copy( head = newHead, tail = newTail, tailVisitationMap = tailVisitationMap + (newTail to count + 1) ) } is Command.Up -> { val newHead = Point(head.x, head.y + 1) val newTail = calculateTail(newHead, tail) val count = tailVisitationMap[newTail] ?: 0 return this.copy( head = newHead, tail = newTail, tailVisitationMap = tailVisitationMap + (newTail to count + 1) ) } } } } data class Board2(val start: Point, val points: MutableList<Point>, val tailVisitationMap: MutableMap<Point, Int>) { fun handleCommand(command: Command): Board2 { when (command) { is Command.Down -> { points[0] = Point(points[0].x, points[0].y - 1) calculate() return this } is Command.Left -> { points[0] = Point(points[0].x - 1, points[0].y) calculate() return this } is Command.Right -> { points[0] = Point(points[0].x + 1, points[0].y) calculate() return this } is Command.Up -> { points[0] = Point(points[0].x, points[0].y + 1) calculate() return this } } } private fun calculate() { for (i in 1 until points.size) { points[i] = calculateTail(points[i - 1], points[i]) } tailVisitationMap.compute(points.last()) { _, oldValue -> (oldValue ?: 0) + 1 } } } private fun calculateTail(newHead: Point, existingTail: Point): Point { if (newHead == existingTail) return existingTail if (newHead.x == existingTail.x + 1 && newHead.y == existingTail.y + 1) return existingTail if (newHead.x == existingTail.x + 1 && newHead.y == existingTail.y - 1) return existingTail if (newHead.x == existingTail.x - 1 && newHead.y == existingTail.y + 1) return existingTail if (newHead.x == existingTail.x - 1 && newHead.y == existingTail.y - 1) return existingTail if (newHead.x == existingTail.x && newHead.y == existingTail.y + 1) return existingTail if (newHead.x == existingTail.x && newHead.y == existingTail.y - 1) return existingTail if (newHead.x == existingTail.x + 1 && newHead.y == existingTail.y) return existingTail if (newHead.x == existingTail.x - 1 && newHead.y == existingTail.y) return existingTail // same column if (newHead.x == existingTail.x) { // Only one space apart if (newHead.y == existingTail.y + 1 || newHead.y == existingTail.y - 1) { return existingTail } return if (newHead.y > existingTail.y) { Point(existingTail.x, existingTail.y + 1) } else { Point(existingTail.x, existingTail.y - 1) } } if (newHead.y == existingTail.y) { // same row if (newHead.x == existingTail.x + 1 || newHead.x == existingTail.x - 1) { return existingTail } return if (newHead.x > existingTail.x) { Point(existingTail.x + 1, existingTail.y) } else { Point(existingTail.x - 1, existingTail.y) } } // neither on same row nor column /* ..... ..... ...H. ...H. ..... -> ...T. ..T.. ..... ..... ..... */ if (newHead.x > existingTail.x && newHead.y > existingTail.y) return Point(existingTail.x + 1, existingTail.y + 1) if (newHead.x < existingTail.x && newHead.y > existingTail.y) return Point(existingTail.x - 1, existingTail.y + 1) return if (newHead.x > existingTail.x) { Point(existingTail.x + 1, existingTail.y - 1) } else { Point(existingTail.x - 1, existingTail.y - 1) } } sealed class Command { abstract val repetitions: Int data class Up(override val repetitions: Int) : Command() data class Down(override val repetitions: Int) : Command() data class Left(override val repetitions: Int) : Command() data class Right(override val repetitions: Int) : Command() } data class Point(val x: Int, val y: Int) fun main() { val testInput = Day9::class.java.getResourceAsStream("/day9_test.txt").bufferedReader().readLines() val test2Input = Day9::class.java.getResourceAsStream("/day9_test2.txt").bufferedReader().readLines() val input = Day9::class.java.getResourceAsStream("/day9_input.txt").bufferedReader().readLines() val day9test = Day9(testInput) val day9test2 = Day9(test2Input) val day9input = Day9(input) println("Day9 part 1 test result: ${day9test.part1()}") println("Day9 part 1 result: ${day9input.part1()}") println("Day9 part 2 test result: ${day9test2.part2()}") println("Day9 part 2 result: ${day9input.part2()}") }
0
Kotlin
0
0
b21978e145dae120621e54403b14b81663f93cd8
7,579
adventofcode2022
Apache License 2.0
src/Day07.kt
GarrettShorr
571,769,671
false
{"Kotlin": 82669}
fun main() { fun part1(input: List<String>): Int { val dirs = mutableListOf<Directory>() val topLevelDir = Directory("/") dirs.add(topLevelDir) var currentDir = topLevelDir var currlevel = 0 for(line in input) { if(line == "$ cd /") { currentDir = topLevelDir currlevel++ } // just move on to reading the files else if (line.startsWith("$ ls")) { continue } else if(line.startsWith("dir")) { var newDir = Directory(line.split(" ")[1], level = currlevel) newDir.parent = currentDir currentDir.subDirs.add(newDir) dirs.add(newDir) } // change the current dir to something inside of the current dir else if(line.startsWith("$ cd")) { if(line.endsWith("..")) { currlevel-- currentDir = currentDir.parent!! } else { currlevel++ val dir = line.split(" ")[2] currentDir = currentDir.subDirs.first { it.name == dir } } } // otherwise it's a file, add it else { val newFile = line.split(" ") currentDir.files.add(File(newFile[1], newFile[0].toInt())) } } println(topLevelDir) var total = 0 for(dir in dirs) { val current = dir.calculateDirSize() if(current <= 100000) { total += current } } return total } fun part2(input: List<String>): Int { val dirs = mutableListOf<Directory>() val topLevelDir = Directory("/") dirs.add(topLevelDir) var currentDir = topLevelDir var currlevel = 0 for(line in input) { if(line == "$ cd /") { currentDir = topLevelDir currlevel++ } // just move on to reading the files else if (line.startsWith("$ ls")) { continue } else if(line.startsWith("dir")) { val newDir = Directory(line.split(" ")[1], level = currlevel) newDir.parent = currentDir currentDir.subDirs.add(newDir) dirs.add(newDir) } // change the current dir to something inside of the current dir else if(line.startsWith("$ cd")) { if(line.endsWith("..")) { currlevel-- currentDir = currentDir.parent!! } else { currlevel++ val dir = line.split(" ")[2] currentDir = currentDir.subDirs.first { it.name == dir } } } // otherwise it's a file, add it else { val newFile = line.split(" ") currentDir.files.add(File(newFile[1], newFile[0].toInt())) } } println(topLevelDir) val total = topLevelDir.calculateDirSize() val needed = 30000000 val free = 70000000 - total val target = needed - free println("total: $total free $free target: $target") var smallest = 70000000 for(dir in dirs) { var dirSize = dir.calculateDirSize() if(dirSize < target) { continue } else { if(dirSize < smallest) { smallest = dirSize } } } dirs.forEach{ println(it.getPath()) } return smallest } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") // println(part1(testInput)) println(part2(testInput)) val input = readInput("Day07") // output(part1(input)) output(part2(input)) } data class Directory( var name: String, var subDirs: MutableSet<Directory> = mutableSetOf(), var files : MutableSet<File> = mutableSetOf(), var level: Int = 0 ) { var parent : Directory? = null fun calculateFilesSize() : Int { return files.sumOf { it.size } } fun getPath() : String { var path = name var parentDir = parent while(parentDir != null) { if(parentDir.name != "/") { path = "${parentDir.name}/$path" } else { path = "/$path" } parentDir = parentDir.parent } return path } fun calculateDirSize() : Int { val dirsToCount = subDirs.toMutableList() var total = calculateFilesSize() while(dirsToCount.size > 0) { val currentDir = dirsToCount.removeAt(0) dirsToCount.addAll(currentDir.subDirs) total += currentDir.calculateFilesSize() } return total } override fun toString(): String { return "Directory(name='$name', parent='$parent', level=$level, subdirs=${subDirs.joinToString { it.name }})" } } class File(var name: String, var size: Int)
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
4,464
AdventOfCode2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/PseudoPalindromicPaths.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2024 <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 /** * 1457. Pseudo-Palindromic Paths in a Binary Tree * @see <a href="https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree">Source</a> */ fun interface PseudoPalindromicPaths { operator fun invoke(root: TreeNode?): Int } class PseudoPalindromicPathsDFS : PseudoPalindromicPaths { override fun invoke(root: TreeNode?): Int { var count = 0 var path: Int val stack = ArrayDeque<Pair<TreeNode?, Int>>() stack.add(Pair(root, 0)) while (stack.isNotEmpty()) { val p = stack.removeLast() val node = p.first path = p.second if (node != null) { // compute occurrence of each digit // in the corresponding register path = path xor (1 shl node.value) // if it's a leaf check if the path is pseudo-palindromic if (node.left == null && node.right == null) { // check if at most one digit has an odd frequency if ((path and (path - 1)) == 0) { count++ } } else { stack.add(Pair(node.right, path)) stack.add(Pair(node.left, path)) } } } return count } } class PseudoPalindromicPathsRecursive : PseudoPalindromicPaths { private var count = 0 override fun invoke(root: TreeNode?): Int { preorder(root, 0) return count } fun preorder(node: TreeNode?, path: Int) { if (node != null) { // compute occurrences of each digit // in the corresponding register val updatedPath = path xor (1 shl node.value) // if it's a leaf check if the path is pseudo-palindromic if ((node.left == null && node.right == null) && (updatedPath and (updatedPath - 1) == 0)) { ++count } preorder(node.left, updatedPath) preorder(node.right, updatedPath) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,713
kotlab
Apache License 2.0
src/Day03.kt
askeron
572,955,924
false
{"Kotlin": 24616}
class Day03 : Day<Int>(157, 70, 7428, 2650) { private val priorities: Map<Char, Int> = (('a'..'z')+('A'..'Z')).mapIndexed { i, c -> c to i+1 }.toMap() override fun part1(input: List<String>): Int { return input.map { it.toCharArray().toList().splitInHalf() } .map { (a, b) -> a.intersect(b) } .map { it.distinct().singleValue() } .sumOf { priorities[it]!! } } override fun part2(input: List<String>): Int { return input.map { it.toCharArray().toList() } .chunked(3) .map { (a,b,c) -> a.intersect(b).intersect(c) } .map { it.distinct().singleValue() } .sumOf { priorities[it]!! } } }
0
Kotlin
0
1
6c7cf9cf12404b8451745c1e5b2f1827264dc3b8
706
advent-of-code-kotlin-2022
Apache License 2.0
src/net/sheltem/aoc/y2023/Day03.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2023 import net.sheltem.common.numericRegex import net.sheltem.common.toListLong import kotlin.math.max import kotlin.math.min suspend fun main() { Day03().run() } class Day03 : Day<Long>(4361, 467835) { override suspend fun part1(input: List<String>): Long = input .toEngineNumbers() .sum() override suspend fun part2(input: List<String>): Long = input .toGearRatios() .sum() } private val gearRegex = Regex("\\*") private fun List<String>.toEngineNumbers(): List<Long> = this .mapIndexed { index, line -> numericRegex .findAll(line) .filter { match -> val startIndex = max(match.range.first - 1, 0) val endIndex = min(match.range.last + 2, line.length - 1) val previousRow = this[max(index - 1, 0)].substring(startIndex, endIndex) val thisRow = this[index].substring(startIndex, endIndex) val nextRow = this[min(index + 1, this.size - 1)].substring(startIndex, endIndex) (previousRow + thisRow + nextRow).any { it.isSymbol() } }.toListLong() }.flatten() private fun Char.isSymbol() = !isDigit() && this != '.' private fun List<String>.toGearRatios(): List<Long> = this .mapIndexed { index, line -> gearRegex .findAll(line) .map { it.range.first } .mapNotNull { gearIndex -> val adjacentNumbers = this.findAdjacentNumbers(index, gearIndex) if (adjacentNumbers.size == 2) { adjacentNumbers.component1() * adjacentNumbers.component2() } else { null } }.toList() }.flatten() private fun List<String>.findAdjacentNumbers(index: Int, gearIndex: Int): List<Long> = (numericRegex.findAll(this[index - 1]).toList() + numericRegex.findAll(this[index]).toList() + numericRegex.findAll(this[index + 1]).toList()) .filter { gearIndex in it.numberRange() } .toListLong() private fun MatchResult.numberRange() = (range.first - 1)..(range.last + 1)
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,178
aoc
Apache License 2.0
src/Day01.kt
shoresea
576,381,520
false
{"Kotlin": 29960}
fun main() { fun part1(inputs: List<String>): Int { var max = 0 var sum = 0 for (input in inputs) { if (input == "") { max = maxOf(max, sum) sum = 0 } else { sum += input.toInt() } } return max } fun part2(inputs: List<String>): Int { val sums = ArrayList<Int>() var sum = 0 for (input in inputs) { if (input == "") { sums.add(sum) sum = 0 } else { sum += input.toInt() } } return sums.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") // check(part1(testInput) == 1) val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
e5d21eac78fcd4f1c469faa2967a4fd9aa197b0e
941
AOC2022InKotlin
Apache License 2.0
src/test/kotlin/com/onegravity/sudoku/Util.kt
1gravity
407,597,760
false
{"Kotlin": 148326}
package com.onegravity.sudoku import com.onegravity.sudoku.SudokuMatrix.Companion.getIndexValue import com.onegravity.sudoku.SudokuMatrix.Companion.toSudokuMatrix import com.onegravity.sudoku.model.Grid import com.onegravity.sudoku.model.Puzzle import org.junit.jupiter.api.Assertions import java.io.File import java.text.DecimalFormat fun testAndValidateSudoku( puzzle: Puzzle, solution: IntArray, solve: Array<BooleanArray>.(collect: (List<Int>) -> Unit) -> Unit ) { testSudoku(puzzle, solution, solve) } private fun testSudoku( puzzle: Puzzle, solution: IntArray?, solve: Array<BooleanArray>.(collect: (List<Int>) -> Unit) -> Unit ) { var solutionFound = false puzzle.toSudokuMatrix() .solve { rows -> if (solution != null) validateSolution(solution, puzzle, rows.toGrid(puzzle)) solutionFound = true } assert(solutionFound) } fun validateSolution(expected: IntArray, original: Puzzle, actual: Puzzle) { expected.forEachIndexed { index, value -> Assertions.assertEquals(original.getCell(index).isGiven, actual.getCell(index).isGiven) Assertions.assertEquals(value, actual.getCell(index).value) } } /** * Converts an AlgorithmX solution (Collection of row indices) into a Sudoku Grid. * * @param original the original Sudoku puzzle the algorithm solved so that we can set isGiven properly */ fun List<Int>.toGrid(original: Puzzle) = Grid(original.extraRegionType, original.isJigsaw) .apply { sorted().forEach { row -> val (index, value) = getIndexValue(row) setValue(index, value, original.getCell(index).isGiven) } } /** * Convert values from the standard csv format to an IntArray. * Input: .......12........3..23..4....18....5.6..7.8.......9.....85.....9...4.5..47...6... * Output: [0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,0,0,3 etc.] */ fun String.toIntArray() = this.map { c -> c.digitToIntOrNull() ?: 0 }.toIntArray() /** * Reads puzzles from a file in the standard csv format with comma separated solution. * * @param fileName The name of the file to read * @param process the function called with each Sudoku passing in the puzzle and the solution as IntArrays */ fun getPuzzles(fileName: String, limit: Int = Int.MAX_VALUE, process: (puzzle: IntArray, solution: IntArray) -> Unit) { var count = 0 File(ClassLoader.getSystemResource(fileName).file) .forEachLine { line -> // find Sudoku puzzles sudokuPattern.findAll(line) .forEach { matchResult -> if (count++ < limit) { // get group with puzzle values val puzzle = matchResult.groupValues[1].toIntArray() val solution = matchResult.groupValues[2].toIntArray() Assertions.assertEquals(81, puzzle.size) Assertions.assertEquals(81, solution.size) process(puzzle, solution) } else return@forEachLine } } } private val sudokuPattern = """^([\d.]{81}),(\d{81}).*$""".toRegex() fun testPerformance(testSet: String, puzzle: IntArray, solve: (puzzle: IntArray) -> Unit) { val l = System.currentTimeMillis() solve(puzzle) val time = System.currentTimeMillis() - l val puzzlesPerSec = 1000F.div(time) println("$testSet took: $time ms, puzzles/sec: ${puzzlesPerSec.twoDecimals()}") } fun testPerformance(testSet: String, filename: String, limit: Int = Int.MAX_VALUE, solve: (puzzle: IntArray) -> Unit) { var count = 0 var totalTime = 0L getPuzzles(filename, limit) { puzzle, _ -> count++ val l = System.currentTimeMillis() solve(puzzle) totalTime += System.currentTimeMillis() - l } val average = totalTime.toFloat().div(count) val puzzlesPerSec = 1000F.div(average) println("$filename - $testSet took: $totalTime ms, average: ${average.twoDecimals()} ms, puzzles/sec: ${puzzlesPerSec.twoDecimals()}") } private val df = DecimalFormat("0.00") fun Float.twoDecimals(): String = df.format(this)
0
Kotlin
0
1
4e8bfb119a57a101db4d873bf86cd5722105ebb3
4,177
Dancing-Links-Kotlin
Apache License 2.0
day01/src/main/kotlin/com/shifteleven/adventofcode2023/day01/App.kt
pope
733,715,471
false
{"Kotlin": 3950, "Nix": 1630}
package com.shifteleven.adventofcode2023.day01 import kotlin.math.min fun main() { part1() part2() } fun part1() { val lines = object {}.javaClass.getResourceAsStream("/input.txt")!!.bufferedReader().readLines() val sum = lines .stream() .mapToInt({ line -> var tens: Int? = null var ones = 0 for (c in line) { when (c) { in CharRange('0', '9') -> { ones = c.code - 0x30 tens = tens ?: ones * 10 } } } tens!! + ones }) .sum() println("Part 1: " + sum) } fun part2() { val lines = object {}.javaClass.getResourceAsStream("/input.txt")!!.bufferedReader().readLines() val sum = lines .stream() .mapToInt({ line -> var tens: Int? = null var ones = 0 for ((i, c) in line.withIndex()) { var num: Int? = null when (c) { in CharRange('0', '9') -> { num = c.code - 0x30 } 'o' -> { if (matchesWord(line, i, "one")) { num = 1 } } 't' -> { if (matchesWord(line, i, "two")) { num = 2 } else if (matchesWord(line, i, "three")) { num = 3 } } 'f' -> { if (matchesWord(line, i, "four")) { num = 4 } else if (matchesWord(line, i, "five")) { num = 5 } } 's' -> { if (matchesWord(line, i, "six")) { num = 6 } else if (matchesWord(line, i, "seven")) { num = 7 } } 'e' -> { if (matchesWord(line, i, "eight")) { num = 8 } } 'n' -> { if (matchesWord(line, i, "nine")) { num = 9 } } } if (num != null) { ones = num tens = tens ?: num * 10 } } tens!! + ones }) .sum() println("Part 2: " + sum) } fun matchesWord( line: String, idx: Int, word: String, ): Boolean { return line.subSequence(idx, min(idx + word.length, line.length)) == word }
0
Kotlin
0
0
cb2862a657d307b5ecd74ebb9c167548b67ba6fc
1,940
advent-of-code-2023-kotlin
The Unlicense
src/main/kotlin/days/Day13.kt
poqueque
430,806,840
false
{"Kotlin": 101024}
package days import util.Coor class Day13 : Day(13) { override fun partOne(): Any { val map = mutableListOf<Coor>() inputList.forEach { data -> if (data.contains(",")) { val (x, y) = data.split(",").map { it.toInt() } map.add(Coor(x, y)) } else if (data.contains("fold")) { val d = data.split(" ")[2].split("=") if (d[0] == "x") { val v = d[1].toInt() val newMap = mutableListOf<Coor>() for (point in map.toList()) { if (point.x > v) point.x = 2 * v - point.x newMap.add(point) } return newMap.distinct().size } } } return 0 } override fun partTwo(): Any { var map = mutableListOf<Coor>() inputList.forEach { data -> if (data.contains(",")) { val (x, y) = data.split(",").map { it.toInt() } map.add(Coor(x, y)) } else if (data.contains("fold")) { val d = data.split(" ")[2].split("=") if (d[0] == "x") { val v = d[1].toInt() val newMap = mutableListOf<Coor>() for (point in map.toList()) { if (point.x > v) point.x = 2 * v - point.x newMap.add(point) } map = newMap.distinct().toMutableList() } if (d[0] == "y") { val v = d[1].toInt() val newMap = mutableListOf<Coor>() for (point in map.toList()) { if (point.y > v) point.y = 2 * v - point.y newMap.add(point) } map = newMap.distinct().toMutableList() } } } for (y in 0..map.maxOf { it.y }) { for (x in 0..map.maxOf { it.x }) if (map.contains(Coor(x, y))) print("#") else print(" ") println() } println() return "PGHRKLKL" } }
0
Kotlin
0
0
4fa363be46ca5cfcfb271a37564af15233f2a141
2,234
adventofcode2021
MIT License
project-euler/kotlin/src/main/kotlin/dev/mikeburgess/euler/extensions/Long.kt
mddburgess
469,258,868
false
{"Kotlin": 47737}
package dev.mikeburgess.euler.extensions import dev.mikeburgess.euler.sequences.primeSequence import kotlin.math.sqrt fun Long.countDivisors() = when (this) { 1L -> 1 2L, 3L -> 2 else -> primeSequence() .takeWhile { it <= sqrt(toDouble()) } .map { countFactors(it) + 1 } .reduce { a, b -> a * b } } fun Long.countFactors(n: Long): Int { var count = 0 var temp = this while (temp % n == 0L) { temp /= n count++ } return count } fun Long.isEven() = this % 2 == 0L fun Long.isPalindrome(base: Long = 10L): Boolean { var temp = this var reverse = 0L while (temp > 0) { reverse = reverse * base + (temp % base) temp /= base } return this == reverse } fun Long.reciprocalCycleLength(): Long { val remainders = mutableMapOf<Long, Long>() var i = 1L var position = 1L do { remainders[i] = position++ i = (i % this) * 10 } while (i != 0L && remainders[i] == null) return when (i) { 0L -> 0L else -> position - remainders[i]!! } } fun Long.squared() = this * this
0
Kotlin
0
0
9ad8f26583b204e875b07782c8d09d9d8b404b00
1,133
code-kata
MIT License
2021/06/main.kt
chylex
433,239,393
false
null
import java.io.File import java.math.BigInteger import kotlin.system.measureTimeMillis fun main() { val initialConfiguration = File("input.txt").readLines() .single() .split(',') .map(String::toInt) println("(Took ${measureTimeMillis { part1(initialConfiguration) }} ms)") println("(Took ${measureTimeMillis { part2(initialConfiguration) }} ms)") } class FishConfiguration(initialConfiguration: List<Int>) { private var fishCountByAge = Array(9) { age -> initialConfiguration.count { it == age }.toBigInteger() } private var day = 0 private val totalFish get() = fishCountByAge.fold(BigInteger.ZERO, BigInteger::add) fun advance(days: Int) { for (day in 1..days) { advanceToNextDay() } } private fun advanceToNextDay() { val newCountByAge = Array(9) { BigInteger.ZERO} for ((age, count) in fishCountByAge.withIndex()) { if (age == 0) { newCountByAge[6] += count newCountByAge[8] += count } else { newCountByAge[age - 1] += count } } fishCountByAge = newCountByAge ++day println("Day ${day.toString().padStart(3)}: $totalFish fish") } } fun part1(initialConfiguration: List<Int>) { FishConfiguration(initialConfiguration).advance(80) } fun part2(initialConfiguration: List<Int>) { FishConfiguration(initialConfiguration).advance(256) }
0
Rust
0
0
04e2c35138f59bee0a3edcb7acb31f66e8aa350f
1,319
Advent-of-Code
The Unlicense
src/main/kotlin/20/20.kt
Wrent
225,133,563
false
null
import java.lang.RuntimeException fun main() { val maze = mutableMapOf<Coord, Maze>() val input = mutableMapOf<Coord, String>() INPUT20.split("\n") .forEachIndexed { i, row -> row.split("").filter { it != "" }.forEachIndexed { j, cell -> val coord = Coord(j, i) input[coord] = cell } } input.forEach { coord, cell -> when (cell) { "#" -> maze[coord] = Maze(coord, MazeWall()) "." -> maze[coord] = Maze(coord, MazeHall()) else -> maze[coord] = Maze(coord, MazeNothing()) } } input.forEach { coord, cell -> if (isLetter(cell)) { val (label, portalCoord) = readLabel(input, cell, coord) maze[portalCoord] = Maze(portalCoord, MazePortal(label, if (isOuter(coord, input)) -1 else 1)) } } val mazePortals = maze.filter { it.value.mazeBlock is MazePortal } mazePortals .forEach { mazePortal -> maze.filter { it.value.mazeBlock is MazePortal } .filter { it != mazePortal } .filter { (it.value.mazeBlock as MazePortal).label == (mazePortal.value.mazeBlock as MazePortal).label } .forEach { (it.value.mazeBlock as MazePortal).portsTo = mazePortal.key } } maze.values.forEach { val validNeighbours = mutableListOf<Pair<Maze, Int>>() processMazeNeighbour(it.coord.north(), maze, validNeighbours) processMazeNeighbour(it.coord.south(), maze, validNeighbours) processMazeNeighbour(it.coord.east(), maze, validNeighbours) processMazeNeighbour(it.coord.west(), maze, validNeighbours) val current = maze[it.coord]!!.mazeBlock if (current is MazePortal) { if (current.portsTo != null) { validNeighbours.add(Pair(maze[current.portsTo!!]!!, current.levelChange)) } } it.validNeighbors = validNeighbours } val start = maze.values.first { it.mazeBlock is MazePortal && it.mazeBlock.label == "AA" }.also { (it.mazeBlock as MazePortal).levelChange = 0 } val end = maze.values.first { it.mazeBlock is MazePortal && it.mazeBlock.label == "ZZ" }.also { (it.mazeBlock as MazePortal).levelChange = 0 } processMazeBlock(start, 0, 0) println("second result") println(end.steps[0]) } fun isOuter(coord: Coord, input: MutableMap<Coord, String>): Boolean { val maxX = input.keys.maxBy { it.x }!!.x val maxY = input.keys.maxBy { it.y }!!.y val minX = input.keys.minBy { it.x }!!.x val minY = input.keys.minBy { it.y }!!.y return coord.x == maxX || coord.x == maxX - 1 || coord.x == minX || coord.x == minX + 1 || coord.y == maxY || coord.y == maxY - 1 || coord.y == minY || coord.y == minY + 1 } fun processMazeBlock(current: Maze, steps: Int, level: Int) { if (level < 0 || level > 30) { return } if (current.mazeBlock is MazePortal) { println("Walking through ${current.mazeBlock.label} on level $level with $steps steps") } current.steps[level] = steps current.validNeighbors .filter { it.first.steps[level + it.second] ?: Int.MAX_VALUE > steps } .forEach { processMazeBlock(it.first, steps + 1, level + it.second) } } fun getLevelChange(it: Maze): Int { return if (it.mazeBlock is MazePortal) { it.mazeBlock.levelChange } else { 0 } } fun processMazeNeighbour(coord: Coord, maze: MutableMap<Coord, Maze>, validNeighbors: MutableList<Pair<Maze, Int>>) { val block = maze[coord] ?: return when (block.mazeBlock) { is MazeWall -> return is MazeNothing -> return } validNeighbors.add(Pair(block, 0)) } private fun readLabel(input: Map<Coord, String>, cell: String, coord: Coord): Pair<String, Coord> { if (isLetter(input[coord.north()])) { if (input[coord.south()] == ".") { return Pair(input[coord.north()] + cell, coord.south()) } else { return Pair(input[coord.north()] + cell, coord.north().north()) } } else if (isLetter(input[coord.south()])) { if (input[coord.south().south()] == ".") { return Pair(cell + input[coord.south()], coord.south().south()) } else { return Pair(cell + input[coord.south()], coord.north()) } } else if (isLetter(input[coord.west()])) { if (input[coord.west().west()] == ".") { return Pair(input[coord.west()] + cell, coord.west().west()) } else { return Pair(input[coord.west()] + cell, coord.east()) } } else if (isLetter(input[coord.east()])) { if (input[coord.west()] == ".") { return Pair(cell + input[coord.east()], coord.west()) } else { return Pair(cell + input[coord.east()], coord.east().east()) } } else { throw RuntimeException() } } private fun isLetter(cell: String?): Boolean { if (cell == null) { return false; } return cell.toLowerCase() != cell } data class Maze(val coord: Coord, val mazeBlock: MazeBlock) { var validNeighbors = mutableListOf<Pair<Maze, Int>>() var steps = mutableMapOf<Int, Int>() } sealed class MazeBlock(val char: Char) class MazeNothing : MazeBlock(' ') class MazeWall : MazeBlock('#') class MazeHall : MazeBlock('.') class MazePortal(val label: String, var levelChange: Int) : MazeBlock('.') { var portsTo: Coord? = null override fun toString(): String { return "MazePortal(label='$label', levelChange=$levelChange, portsTo=$portsTo)" } } const val TEST201 = """ A A #######.######### #######.........# #######.#######.# #######.#######.# #######.#######.# ##### B ###.# BC...## C ###.# ##.## ###.# ##...DE F ###.# ##### G ###.# #########.#####.# DE..#######...###.# #.#########.###.# FG..#########.....# ###########.##### Z Z """ const val TEST202 = """ Z L X W C Z P Q B K ###########.#.#.#.#######.############### #...#.......#.#.......#.#.......#.#.#...# ###.#.#.#.#.#.#.#.###.#.#.#######.#.#.### #.#...#.#.#...#.#.#...#...#...#.#.......# #.###.#######.###.###.#.###.###.#.####### #...#.......#.#...#...#.............#...# #.#########.#######.#.#######.#######.### #...#.# F R I Z #.#.#.# #.###.# D E C H #.#.#.# #.#...# #...#.# #.###.# #.###.# #.#....OA WB..#.#..ZH #.###.# #.#.#.# CJ......# #.....# ####### ####### #.#....CK #......IC #.###.# #.###.# #.....# #...#.# ###.### #.#.#.# XF....#.# RF..#.#.# #####.# ####### #......CJ NM..#...# ###.#.# #.###.# RE....#.# #......RF ###.### X X L #.#.#.# #.....# F Q P #.#.#.# ###.###########.###.#######.#########.### #.....#...#.....#.......#...#.....#.#...# #####.#.###.#######.#######.###.###.#.#.# #.......#.......#.#.#.#.#...#...#...#.#.# #####.###.#####.#.#.#.#.###.###.#.###.### #.......#.....#.#...#...............#...# #############.#.#.###.################### A O F N A A D M """ const val INPUT20 = """ I N S T Q I K W P J E O K E #####################################.###########.#.#######.#######.#####.#########.####################################### #.#.#.....#...#.#...........#.#.#.....#.#.........#.......#...#.........#.#.....#...#.......#.........#.......#.......#...# #.#.#####.###.#.###.#.#.###.#.#.#####.#.#####.#####.#####.#.#.###.#####.#.#.###.#.###.#.###.#.###.#######.###.###.#######.# #...........#...#.#.#.#.#.........#...#.....#.....#...#...#.#.#.#...#...#.....#.#.....#...#.#.#.#...#.#...#.#.#.#.........# ###########.#.###.#######.###.###.###.#.#.###.###########.###.#.###.#########.#.#######.#####.#.#.#.#.#.###.###.#.###.###.# #...#.#.#.......#...#.#...#...#.#...#.#.#.#.....#.#.....#...#...#...#.#.....#.#.#.......#.......#.#.#...#.#...#.#...#.#...# ###.#.#.###.###.#.###.#########.###.#.#.#####.###.#####.#.###.#.#.###.###.#.###.#.#########.###.#####.###.#.#.#.#.#######.# #...#.#.....#...#.....#.#.....#...........#.#.........#.....#.#.#.#.....#.#.....#.............#.#.......#.#.#.#.#.......#.# ###.#.#########.###.###.#.#.#.#.###.#####.#.#.#.#######.#####.#.#.#.#.###.###.#########.#.#.#.#####.#####.###.#.#.#####.#.# #.......#...............#.#.#...#.#.#...#...#.#.....#.....#.#.#.#.#.#...#.#.#.#...#...#.#.#.#.#.....#.......#.........#.#.# #####.###########.#.#.###########.#####.###.###.###.#####.#.###.#.#.###.#.#.#.###.###.#.#######.#.#####.#####.############# #.....#...#...#.#.#.#.#.#.#.........#.......#.....#.#.......#.#.#...#...#...#.#.....#...#.......#.....#.#.#.........#.....# #####.###.###.#.###.###.#.#######.###.#######.#.#.#######.###.#.###.#.#####.#####.#.#.###.#####.#.###.#.#.#.#####.#####.### #.#...........#.............................#.#.#.......#.#.....#...#.....#.....#.#.#.....#...#.#...#.........#.#...#.....# #.#.#.#.#.###.#.#.#####.###.#.#.#####.#####.#.###.#######.#.###.#.#.###.#####.#.#.#.###.#.#.###.#######.#.#.###.#######.### #.#.#.#.#...#.#.#.#.....#.#.#.#.#.......#...#...#...#.....#...#.#.#.#.#...#...#.#.#.....#.....#.#...#...#.#.........#.....# #.#######.#######.###.###.###.#####.###.###.#.#####.#.#.#.#.#####.###.#.#######.#.#.#.#######.###.#####.###.#####.###.#.#.# #.#...#...#.#.#.#...#.#.......#.....#...#.#.#.#.#.#.#.#.#.#.....#.#.#.#.#.......#.#.#.......#.........#.#...#.......#.#.#.# #.#.#####.#.#.#.###############.###.#####.#.#.#.#.###.###.#.#####.#.#.#.###.#.#.#.#####.#.###.#.#####.#################.#.# #...#.#...#.....#.#.#.....#.#.....#.#.......#.....#...#...#.....#.#.....#.#.#.#.#...#...#...#.#...#.....#...#...#.#.#.#.#.# ###.#.###.###.###.#.#.###.#.###.#######.###.###.#.#######.#.###########.#.#####.#.#########.###.#########.#####.#.#.#.###.# #.#.....#.#...#.....#.#.#...........#.#.#.#...#.#.#...#...#.....#...#...#.....#.#...#.....#.#.#.#.......#.#.#...#...#.#...# #.###.###.#.###.#.#####.#######.#.###.###.#.###.#.###.###.#.#.#.#.#####.###.###.#.#######.###.#####.#.###.#.#.###.###.###.# #.............#.#.#.#.....#.....#.#.........#...#.#.......#.#.#.#.....#.#.....#.#...#...#.....#.#.#.#.....#.#.#...#...#...# ###.#.#####.#####.#.#.###################.###.#########.###.#####.#.#.#.#.###.#.###.#.###.#####.#.###.#####.#.###.###.###.# #...#...#.#.#.......#.#...#.#...#.....#.#...#...#.#.......#.....#.#.#...#.#...#...#.......#.#.#.....#...#...#...#...#...#.# #####.#.#.#.#####.#.#.###.#.#.#######.#.###.#.###.#.#####.#.###########.#.#.###.###.###.###.#.#.#####.#####.###.#.###.###.# #...#.#...#.#.....#.#...#.................#.#.....#.#...#.#.....#...#...#.#.....#...#...#.#.#.....#.#...#.....#.....#.#...# #.#####.#######.#.#.#.###.###########.###.#.###.#######.#.#.#####.#####.#.###.#.#.#.#.#.#.#.#.###.#.#.#####.###.#.###.###.# #...#.#.#.#...#.#.#.#...#.#.....#.#.....#.....#...#...#...#...#.#.....#.#.#.#.#.#.#.#.#.........#.#...#.......#.#.......#.# ###.#.#.#.###.###.###.###.#####.#.#####.###.#####.###.###.#.###.#.#.###.#.#.#.#.###.###.###.#.#######.###.#########.#####.# #.....#...#.#.#.#...#.#.#.#.....#.........#.#.....#.......#.#.....#.....#.#...#.#...#.....#.#.#.#...#...#...#.#.........#.# ###.#.#.#.#.#.#.###.#.#.#######.#####.#########.#######.###.#####.#######.###########.#####.###.#.###.###.###.###.###.###.# #...#.#.#.#.#...........#...#...# N P N C I D K #.#.#...#.......#.#...#.#.#.....# ###.###.###.#.#####.#####.#.###.# K E P J E B N ###.###.###.#####.#.#####.###.#.# NW....#.........#.#.#...#...#.#...# #...#.....#.....#.....#.#...#.#.# ###.#.#####.###.#.#######.#####.# #.#.###.#.#.#.#####.#.#.#.#####.# #.....#.....#.#.#.#.#.#.#.#.#....DF #.#.#.#.#...#...#...#.#.....#....ZM #####.#.#####.#.#.#.#.#.#.#.###.# ###.#.#.#####.#####.###.#######.# #.....#.#...#.....#.....#.#.#...# VI....#...#.#...#.#.......#.#.#.#.# #######.#.#.#.###.###.#.#.#.###.# #.#.#.###.#.###.###.###.#.#.#.#.# #.#.#.....#...#.......#.........# #.#...#.#.............#.........# #.#.#.###.#.#.#.#####.#####.##### #####.#.###.#.###.#.###.######### RY....#.#.#.#.#.#.#...#.#.#.#.#....TE #...#.#...#.#.#...#.#...#.......# #.#####.#########.#####.#.###.#.# #.#.###.###########.#######.###.# #...#.....#.....#.#.#.......#.#.# CN..#.........#.....#.#.#.....#...# #.#.#.###.###.###.#.#.###.#####.# #####.###########.###.#.#.###.### #.#...#.................#.......# #.#.#...#.#...#.#...#...#.#...#..AS #####################.#.#######.# #.#.#.###.#.###.#.#####.###.###.# CT....#.....#.......#...#...#.#.#.# #.........................#.....# ###.#.###.###.#.#.#######.#.#.### ###.#.#############.#.#.###.#.### #...#...#...#.#.#.#.#...#.#......DN #...#.#.......#.#...#.#.#...#.#.# #.#####.###.#.#.###.###.###.##### #########.###.#.#####.#########.# #.....#.#...#.#...........#.#...# #...#.#.....#...#...#...#...#.#..CJ ###.###.###.#.#.#.###.#.#.#.###.# ###.#.#####.#.#####.#.#####.#.#.# #.......#.....#.#...#.#.#...#...# NW....#.....#.#.#.....#.#.........# ###############.#####.#######.### #.#.#.###.#.#.#####.#####.#####.# #...........#.#...#.#...#.....#.# #.#...#.#...#...............#.#.# #.###.#.#####.#####.#####.###.#.# #######.#####################.### QW..#...#...#...#.#.........#...#..IK #.............#.....#...........# #.#.#######.#.#.#####.#####.###.# #.#####.#.###.#.#.###.#########.# #.#.#.....#.#.#...#.......#...#..RY #.#...#.#...#...#...#.......#...# #.#.#.#.###.###.#######.#####.#.# #.#######.###.#####.#####.###.### BM..#...#...................#.....# #.......#.#.....#.......#.#......GM #################.#.#.########### ###.#.#############.#.#.#.#.###.# #.#.............#.#.#...#.#.....# IW....#.#...#.#...#...#.#...#...#.# #.#.#########.#.#.#######.###.### #######.###.#.###########.####### VI..#.......#...#.#.#.#...#.......# #...#.#.....#...#...#...#.#.#.#..KN #.#######.#####.###.#.###.#.#.### #.###.#.#####.###.#.###.###.#.#.# #.......#.#.......#.....#.#.#...# ZM..#.....#.#.#...#.#.#............ZZ ###.#####.#######.#.###.###.#.### #.#.#.###.#.#.###.#.#.#.#####.#.# #.........#.#.#.......#.....#....GM #...#.............#...#.#.#.#.#.# ###########.#.###.#############.# #############.#.#########.#.##### #.....#.........#...#.#.......#.# QW........#.#...#.#.........#...#..GZ #.#.#####.#####.#####.###.###.### #####.###.#####.###.#####.#.#.#.# #.#...#.....#.#.#.....#...#.....# #...........#...#.....#...#.#...# #.###.#.#.#.#.#.#####.#.#.###.#.# ###.#####.###########.###.#.###.# #...#...#.#.#.....#.#...#.#.#.#..GZ #.....#.#.#.....#.#.#.#...#...#.# ###.###.#.#.#.#.#.#.#.###.#.#.#.# #.#.#.#.#####.###.#.#.###.#.###.# DN......#.#.#.#.#.#.....#.#.#...#.# #.#.#.................#.......#.# #.#.#.#.#######.#####.#.###.#.#.# Q P A K B S C ###.#.#.#.#####.#.#.###.#.#.#.### #.#.#.#.#...........#...#...#.#.# O M S E M J T #...#.#.#...#...#.#.#.#.#.#.#...# #.#.#.#.###.#.#.#.###.#.###.#############.###.#####.#####.#########.#######.#########.#####.#.#.###.#.#.#.###.#.#.#.#.#.#.# #.#.#.#...#.#.#.#...#.#.#.....#.#.#.#.....#...#.#.....#.........#.#.......#...#.....#.#.#...#.#...#.#.#.#.#.#...#.#.#.#.#.# #.###.#####.#####.#####.###.###.#.#.###.###.###.#####.###.#######.###.#####.#.#####.#.#.#######.#.#####.###.#.###.###.##### #...#.#...#...#.#.....#.#.....#.......#.#.#.....#.#...#.....#...........#.#.#.#...#.......#.....#.#...#...#.....#.#.....#.# #.#.#.###.#.#.#.###.###.###.#######.###.#.#####.#.#.#.#.###.###.###.#####.###.#.#.#.###########.#.###.#.###.#.###.#.###.#.# #.#.#.#.....#.#.#.#.#.#.#.....#.#.........#.......#.#.#.#.....#...#.#.#...#...#.#.....#.#.....#.#...#...#.#.#...#.#...#...# #.#.#######.###.#.#.#.#.#.#.#.#.###.#.###.#.#########.###.###.###.###.#.#.#.###.#######.###.#.#.#.###.#.#.###.###.#.###.#.# #.#...#.#.#.#.#.....#...#.#.#.#.....#.#.#.#...#...#...#...#.#.#.#.....#.#...#...#...........#.#.#.#...#.....#...#.#...#.#.# ###.#.#.#.#.#.###.#####.###.#####.###.#.#.###.###.###.#.#.#.###.#####.#.###.###.#.###.#.#######.#####.#.#.###.#######.#.#.# #...#.#.........#...#...#.....#.....#.#.#.#...#.....#.#.#.#.......#...#...#.#...#...#.#.......#...#...#.#.#.#.....#...#.#.# ###.#.#.###.###########.###.#.#.#######.#.#.###.#.#.#.#.###.#.#######.###.#####.###.#.#########.#####.###.#.#.#.#.#######.# #.#.#.#...#.........#.....#.#.#.#...#.....#.....#.#.#.#.....#.#...#...#...#.........#.#...#...#.#.#.....#.#...#.#.......#.# #.#.#####.#.#.#####.###############.#####.#######.###.#######.#.###.#.#.#######.#.#.#.###.#.###.#.#.#.#.###.#.#.#.###.##### #...#.#...#.#...#...#.....#.......#.........#.......#.....#.......#.#.#.......#.#.#.#.........#.#.#.#.#...#.#.#.#...#.....# ###.#.#.#####.#.#####.#.#####.#.#.#.#####.#####.#####.#.#####.#.#####.#.###########.#.###.#.###.#.#.###########.###.###.### #.....#.#.....#.#...#.#...#.#.#.#.#.#.#.....#.....#...#.#.....#.#.....#.#...#...#.#.#...#.#...#.#.#.#...#.......#...#.....# #.###.###.###.#####.###.###.###.#####.#.###.#####.###.#####.#.#####.###.#.###.###.###.#####.#####.###.#######.#.#######.### #.#.#.#...#...#.........#.#...#.#.......#...#.....#...#...#.#.#.#.....#.........#.......#.#.#...#.#.....#.#...#.....#.....# ###.###################.#.#.###.#.#####.#.#######.###.###.###.#.###.###.#.###.###.#######.###.###.###.#.#.###.#.###.#####.# #.........#.#.#.........#.#.#...#.#.....#.#.........#.......#.#.......#.#.#.#.#.....#.................#.....#.#.#.#.....#.# #####.#####.#.#########.#.#.#.#.#####.###########.###.#######.#.#####.#.###.#####.#.###.#.#.#.#####.###########.#.#.#.###.# #.#.#.....#.#.#.#...#.........#...#.#.......#.#...#...#.#...#.#.....#.#.........#.#...#.#.#.#.....#.......#.....#...#.#...# #.#.###.###.#.#.###.#####.#.#.###.#.#.###.###.###.#.###.###.#.#####.#####.#.#.#######.#.#######.###.#.#####.###.#.#.#.###.# #.......#.#.....#.#...#.#.#.#.#.#.#.....#.#.....#.#.....#.....#.......#...#.#.#.#.#.......#...#...#.#...#.#...#.#.#.#.#...# #.#.###.#.###.###.###.#.#######.#.#.#######.#####.#.#.###.#.###.#.#####.#######.#.###.###.###.#######.###.###.#.###.#####.# #.#.#.#...............#.....#.#.#.........#...#...#.#...#.#.#...#.....#.#...#...#.#.....#.......#...........#.#...#.#.....# #####.#.###.#.#.#####.###.###.#.#######.###.#.#.###.#####.#####.#####.#.#.#####.#.###.#######.#.###.#.#.#.###.#.###.#.###.# #.......#...#.#.#.....#...............#...#.#.#.#.....#.......#.#...#.#.....#.#.....#.....#.#.#.#.#.#.#.#.#.#.#.#...#...#.# #.###.#####.#.#.###.#.#####.#######.#.###.#.#.#.#.###.#######.#.###.#####.###.#.###.#.#####.#####.#########.#.#####.###.#.# #.#.......#.#.#.#...#.........#.#.#.#.#...#.#...#.#...#.#.....#.#.....#...#...#.#.#.........................#.#...#.#.#.#.# #######.###.###.#####.#########.#.#.#.#.###.#######.###.#.###.#.#.###.#.###.#.#.#.#.###.###.#.###.#.#.#.#.#####.#.#.#.##### #.......#...#.....#...#.............#...#.........#.....#.#...#...#...#.....#.#.#.#...#...#.#...#.#.#.#.#.......#.#.......# ###################################.###########.###.#.###.###########.#######.#.########################################### P N P A D C D I M K E A F N B E """
0
Kotlin
0
0
0a783ed8b137c31cd0ce2e56e451c6777465af5d
23,060
advent-of-code-2019
MIT License
src/Day11/Day11.kt
martin3398
436,014,815
false
{"Kotlin": 63436, "Python": 5921}
import java.util.* fun main() { fun preprocess(input: List<String>) = input.map { it.map { x -> x.toString().toInt() }.toTypedArray() }.toTypedArray() fun simulateStep(input: Array<Array<Int>>): Int { var lights = 0 val queue = LinkedList<Pair<Int, Int>>() for (x in input.indices) { for (y in input.indices) { queue.add(x to y) } } while (!queue.isEmpty()) { val coords = queue.removeFirst() if (coords.first >= 0 && coords.first < input.size && coords.second >= 0 && coords.second < input[0].size) { input[coords.first][coords.second]++ if (input[coords.first][coords.second] == 10) { lights++ queue.addAll( listOf( coords.first - 1 to coords.second, coords.first - 1 to coords.second - 1, coords.first - 1 to coords.second + 1, coords.first to coords.second - 1, coords.first to coords.second + 1, coords.first + 1 to coords.second, coords.first + 1 to coords.second - 1, coords.first + 1 to coords.second + 1 ) ) } } } for (x in input.indices) { for (y in input.indices) { if (input[x][y] > 9) { input[x][y] = 0 } } } return lights } fun part1(input: Array<Array<Int>>): Int { var res = 0 for (i in 0 until 100) { res += simulateStep(input) } return res } fun part2(input: Array<Array<Int>>): Int { var i = 101 while (simulateStep(input) < 100) { i++ } return i } val testInput = preprocess(readInput(11, true)) val input = preprocess(readInput(11)) check(part1(testInput) == 1656) println(part1(input)) check(part2(testInput) == 195) println(part2(input)) }
0
Kotlin
0
0
085b1f2995e13233ade9cbde9cd506cafe64e1b5
2,224
advent-of-code-2021
Apache License 2.0
src/Day25.kt
er453r
572,440,270
false
{"Kotlin": 69456}
fun main() { val charToDigit = mapOf('=' to -2, '-' to -1, '0' to 0, '1' to 1, '2' to 2) val digitToChar = charToDigit.map { (char, digit) -> digit.toLong() to char }.toMap() fun toDecimal(snafu: String) = snafu.toCharArray().reversed().mapIndexed { index, char -> charToDigit[char]!! * 5.pow(index) }.sum() fun toSnafu(decimal: Long): String { var value = decimal var result = "" while (value > 0) { var digit = value % 5 if (digit > 2) digit -= 5 value = (value - digit) / 5 result += digitToChar[digit]!! } return result.reversed() } fun part1(input: List<String>) = toSnafu(input.sumOf { toDecimal(it) }) fun part2(input: List<String>) = "HOHOHO" test( day = 25, testTarget1 = "2=-1=0", testTarget2 = "HOHOHO", part1 = ::part1, part2 = ::part2, ) }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
940
aoc2022
Apache License 2.0
src/main/kotlin/g1901_2000/s1994_the_number_of_good_subsets/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1994_the_number_of_good_subsets // #Hard #Array #Dynamic_Programming #Math #Bit_Manipulation #Bitmask // #2023_06_21_Time_737_ms_(100.00%)_Space_54.2_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { private fun add(a: Long, b: Long): Long { var a = a a += b return if (a < MOD) a else a - MOD } private fun mul(a: Long, b: Long): Long { var a = a a *= b return if (a < MOD) a else a % MOD } private fun pow(a: Long, b: Long): Long { // a %= MOD; // b%=(MOD-1);//if MOD is prime var a = a var b = b var res: Long = 1 while (b > 0) { if (b and 1L == 1L) { res = mul(res, a) } a = mul(a, a) b = b shr 1 } return add(res, 0) } fun numberOfGoodSubsets(nums: IntArray): Int { val primes = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29) val mask = IntArray(31) val freq = IntArray(31) for (x in nums) { freq[x]++ } for (i in 1..30) { for (j in primes.indices) { if (i % primes[j] == 0) { if (i / primes[j] % primes[j] == 0) { mask[i] = 0 break } mask[i] = mask[i] or pow(2, j.toLong()).toInt() } } } val dp = LongArray(1024) dp[0] = 1 for (i in 1..30) { if (mask[i] != 0) { for (j in 0..1023) { if (mask[i] and j == 0 && dp[j] > 0) { dp[mask[i] or j] = add(dp[mask[i] or j], mul(dp[j], freq[i].toLong())) } } } } var ans: Long = 0 for (i in 1..1023) { ans = add(ans, dp[i]) } ans = mul(ans, pow(2, freq[1].toLong())) ans = add(ans, 0) return ans.toInt() } companion object { private const val MOD = (1e9 + 7).toLong() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,118
LeetCode-in-Kotlin
MIT License
src/day08/Day08.kt
tschens95
573,743,557
false
{"Kotlin": 32775}
package day08 import readInput fun main() { fun isVisible(i: Int, array: Array<IntArray>, column: Int, row: Int): Boolean { var aboveTrees = listOf<Int>() var leftTrees = listOf<Int>() var belowTrees = listOf<Int>() var rightTrees = listOf<Int>() for (k in 0 until row) { aboveTrees = aboveTrees.plus(array[column][k]) } for (j in 0 until column) { leftTrees = leftTrees.plus(array[j][row]) } for (k in row + 1 until array.size) { belowTrees = belowTrees.plus(array[column][k]) } for (j in column + 1 until array[0].size) { rightTrees = rightTrees.plus(array[j][row]) } if (aboveTrees.isNotEmpty() && aboveTrees.all { it < i }) { return true } if (leftTrees.isNotEmpty() && leftTrees.all { it < i }) { return true } if (belowTrees.isNotEmpty() && belowTrees.all { it < i }) { return true } if (rightTrees.isNotEmpty() && rightTrees.all { it < i }) { return true } return false } fun computeScenicScore(i: Int, array: Array<IntArray>, column: Int, row: Int): Int { // var aboveTrees = listOf<Int>() // var leftTrees = listOf<Int>() // var belowTrees = listOf<Int>() // var rightTrees = listOf<Int>() var scenicScoreAbove = 0 var scenicScoreLeft = 0 var scenicScoreBelow = 0 var scenicScoreRight = 0 for (k in (0 until row).reversed()) { if (array[column][k] < i) { scenicScoreAbove++ } else { scenicScoreAbove++ break } } for (j in (0 until column).reversed()) { if (array[j][row] < i) { scenicScoreLeft++ } else { scenicScoreLeft++ break } } for (k in row + 1 until array.size) { if (array[column][k] < i) { scenicScoreBelow++ } else { scenicScoreBelow++ break } } for (j in column + 1 until array[0].size) { if (array[j][row] < i) { scenicScoreRight++ } else { scenicScoreRight++ break } } return scenicScoreAbove * scenicScoreBelow * scenicScoreLeft * scenicScoreRight } fun part1(input: List<String>): Int { val array = Array(input.size) { IntArray(input[0].length) } var column = 0 // fill the matrix for ((row, i) in input.withIndex()) { val iterator = i.iterator() while (iterator.hasNext()) { val c = iterator.nextChar() array[row][column] = c.digitToInt() column++ } column = 0 } var countTrees = 0 for (col in array.indices) { val row = array[col] for (r in row.indices) { if (col == 0 || col == array.size - 1) { countTrees++ } else if (r == 0 || r == row.size - 1) { countTrees++ } else { if (isVisible(array[col][r], array, col, r)) countTrees++ } } } return countTrees } fun part2(input: List<String>): Int { val array = Array(input.size) { IntArray(input[0].length) } var column = 0 // fill the matrix for ((row, i) in input.withIndex()) { val iterator = i.iterator() while (iterator.hasNext()) { val c = iterator.nextChar() array[row][column] = c.digitToInt() column++ } column = 0 } val scenicMatrix = Array(input.size) { IntArray(input[0].length) } for (col in array.indices) { val row = array[col] for (r in row.indices) { if (col == 0 || col == array.size - 1) { scenicMatrix[col][r] = 0 } else if (r == 0 || r == row.size - 1) { scenicMatrix[col][r] = 0 } else { scenicMatrix[col][r] = computeScenicScore(array[col][r], array, col, r) } } } var maxScenic = 0 for (i in scenicMatrix.indices) { for (j in 0 until scenicMatrix[0].size) { if (scenicMatrix[i][j] > maxScenic) { maxScenic = scenicMatrix[i][j] } } } return maxScenic } val testInput = "30373\n" + "25512\n" + "65332\n" + "33549\n" + "35390" println(part1(testInput.split("\n"))) print(part1(readInput("08"))) println(part2(testInput.split("\n"))) print(part2(readInput("08"))) }
0
Kotlin
0
2
9d78a9bcd69abc9f025a6a0bde923f53c2d8b301
5,088
AdventOfCode2022
Apache License 2.0
grind-75-kotlin/src/main/kotlin/LinkedListCycle.kt
Codextor
484,602,390
false
{"Kotlin": 27206}
import commonclasses.ListNode /** * Given head, the head of a linked list, determine if the linked list has a cycle in it. * * There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. * Internally, pos is used to denote the index of the node that tail's next pointer is connected to. * Note that pos is not passed as a parameter. * * Return true if there is a cycle in the linked list. Otherwise, return false. * * * * Example 1: * * * Input: head = [3,2,0,-4], pos = 1 * Output: true * Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). * Example 2: * * * Input: head = [1,2], pos = 0 * Output: true * Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. * Example 3: * * * Input: head = [1], pos = -1 * Output: false * Explanation: There is no cycle in the linked list. * * * Constraints: * * The number of the nodes in the list is in the range [0, 10^4]. * -10^5 <= Node.val <= 10^5 * pos is -1 or a valid index in the linked-list. * * * Follow up: Can you solve it using O(1) (i.e. constant) memory? * @see <a href="https://leetcode.com/problems/linked-list-cycle/">LeetCode</a> * * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ fun hasCycle(head: ListNode?): Boolean { var slowPointer = head var fastPointer = head while (fastPointer != null && fastPointer.next != null) { slowPointer = slowPointer?.next fastPointer = fastPointer.next?.next if (fastPointer == slowPointer) { return true } } return false }
0
Kotlin
0
0
87aa60c2bf5f6a672de5a9e6800452321172b289
1,813
grind-75
Apache License 2.0
solutions/src/SearchRotatedSortedArray.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
import kotlin.math.roundToInt //https://leetcode.com/problems/search-in-rotated-sorted-array/ class SearchRotatedSortedArray { fun search(nums: IntArray, target: Int) : Int { val pivot = findPivot(nums, 0, nums.lastIndex) if (pivot == -1) return Math.max(nums.binarySearch(target),-1) if (nums[pivot] === target) return pivot return if (nums[0] <= target) Math.max(nums.binarySearch(target,toIndex = pivot),-1) else Math.max(nums.binarySearch(target, fromIndex = pivot+1),-1) } private fun findPivot(arr: IntArray, low: Int, high: Int): Int { if (high < low) return -1 if (high == low) return low val mid = (low + high) / 2 if (mid < high && arr[mid] > arr[mid + 1]) return mid if (mid > low && arr[mid] < arr[mid - 1]) return mid - 1 return if (arr[low] >= arr[mid]) findPivot(arr, low, mid - 1) else findPivot(arr, mid + 1, high) } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,015
leetcode-solutions
MIT License
app/src/main/kotlin/solution/Solution2104.kt
likexx
559,794,763
false
{"Kotlin": 136661}
package solution import solution.annotation.Leetcode class Solution2104 { @Leetcode(2104) class Solution { fun subArrayRanges(nums: IntArray): Long { // monolithic stacks // sum = sum(all maxes) - sum(all mins) val N = nums.size var sum: Long = 0 // maxes should be decremental, each maxes.last() should be the peak point in subarrays val maxes = mutableListOf<Int>() for (i in 0..N) { while (maxes.size > 0 && (i==N || nums[maxes.last()]<=nums[i])) { val last = maxes.removeAt(maxes.size-1) val left = if (maxes.size>0) { maxes.last() } else -1 sum += (last-left)*(i-last)*(nums[last].toLong()) } maxes.add(i) } // mins should be increment. each mins.last() should be the bottom of all subarrays val mins = mutableListOf<Int>() for (i in 0..N) { while (mins.size > 0 && (i==N || nums[mins.last()]>=nums[i])) { val last = mins.removeAt(mins.size-1) val left = if (mins.size>0) {mins.last()} else -1 sum -= (last-left)*(i-last)*nums[last].toLong() } mins.add(i) } return sum } fun subArrayRangesLoops(nums: IntArray): Long { var sum: Long = 0 val n = nums.size for (i in 0..n-1) { var curMax = nums[i] var curMin = nums[i] for (j in i+1..n-1) { curMax = kotlin.math.max(curMax, nums[j]) curMin = kotlin.math.min(curMin, nums[j]) sum += curMax - curMin } } return sum } fun subArrayRangesNaive(nums: IntArray): Long { var sum: Long = 0 for (i in nums.indices) { for (j in 0..i) { var curMin = nums[i] var curMax = nums[i] for (k in j..i) { curMax = kotlin.math.max(curMax, nums[k]) curMin = kotlin.math.min(curMin, nums[k]) } sum += kotlin.math.abs(curMax-curMin) } } return sum } } }
0
Kotlin
0
0
376352562faf8131172e7630ab4e6501fabb3002
2,435
leetcode-kotlin
MIT License
src/Day05.kt
wbars
576,906,839
false
{"Kotlin": 32565}
private fun getStacks() = listOf( ArrayDeque(listOf('R', 'Q', 'G', 'P', 'C', 'F')), ArrayDeque(listOf('P', 'C', 'T', 'W')), ArrayDeque(listOf('C', 'M', 'P', 'H', 'B')), ArrayDeque(listOf('R', 'P', 'M', 'S', 'Q', 'T', 'L')), ArrayDeque(listOf('N', 'G', 'V', 'Z', 'J', 'H', 'P')), ArrayDeque(listOf('J', 'P', 'D')), ArrayDeque(listOf('R', 'T', 'J', 'F', 'Z', 'P', 'G', 'L')), ArrayDeque(listOf('J', 'T', 'P', 'F', 'C', 'H', 'L', 'N')), ArrayDeque(listOf('W', 'C', 'T', 'H', 'Q', 'Z', 'V', 'G')), ) fun main() { fun part1(input: List<String>): String { val stacks = getStacks() val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") for (line in input) { val res = regex.matchEntire(line)!! val count = res.groups[1]!!.value.toInt() val from = res.groups[2]!!.value.toInt() val to = res.groups[3]!!.value.toInt() for (i in 0 until count) { stacks[to - 1].addFirst(stacks[from-1].removeFirst()) } } return stacks.map { it.first() }.joinToString("") } fun part2(input: List<String>): String { val stacks = getStacks() val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") for (line in input) { val res = regex.matchEntire(line)!! val count = res.groups[1]!!.value.toInt() val from = res.groups[2]!!.value.toInt() val to = res.groups[3]!!.value.toInt() val tmp = ArrayDeque<Char>(count) for (i in 0 until count) { tmp.addFirst(stacks[from-1].removeFirst()) } for (c in tmp) { stacks[to-1].addFirst(c) } } return stacks.map { it.first() }.joinToString("") } part1(readInput("input")).println() part2(readInput("input")).println() }
0
Kotlin
0
0
344961d40f7fc1bb4e57f472c1f6c23dd29cb23f
1,940
advent-of-code-2022
Apache License 2.0
Kotlin/days/src/day12.kt
dukemarty
224,307,841
false
null
import java.io.BufferedReader import java.io.FileReader import java.lang.StringBuilder import kotlin.math.abs import kotlin.math.sign //<x=1, y=-4, z=3> //<x=-14, y=9, z=-4> //<x=-4, y=-6, z=7> //<x=6, y=-9, z=-11> data class Vector3d(var x: Int = 0, var y: Int = 0, var z: Int = 0) { operator fun plusAssign(other: Vector3d) { x += other.x y += other.y z += other.z } fun getAbsSum(): Int { return (abs(x.toDouble()) + abs(y.toDouble()) + abs(z.toDouble())).toInt() } } data class Moon(val line: String, var position: Vector3d = Vector3d(), val velocity: Vector3d = Vector3d()) { init { val coords = line .trim('<', '>') .split(",") .map { it.trim() } .map { it.split("=")[1].toInt() } position = Vector3d(coords[0], coords[1], coords[2]) } fun getEnergy(): Int { return position.getAbsSum() * velocity.getAbsSum() } fun applyVelocity() { position += velocity } } class StarSystem(lines: Collection<String>) { var moons: List<Moon> = lines.map { Moon(it) }.toList() fun getTotalEnergy(): Int { return moons.sumBy { it.getEnergy() } } fun updateVelocity() { for (i in IntRange(0, moons.size - 2)) { for (j in IntRange(i + 1, moons.size - 1)) { applyGravity(i, j) } } } fun applyVelocity() { for (m in moons) { m.applyVelocity() } } private fun applyGravity(i: Int, j: Int) { moons[i].velocity.x -= moons[i].position.x.compareTo(moons[j].position.x).sign moons[j].velocity.x += moons[i].position.x.compareTo(moons[j].position.x).sign moons[i].velocity.y -= moons[i].position.y.compareTo(moons[j].position.y).sign moons[j].velocity.y += moons[i].position.y.compareTo(moons[j].position.y).sign moons[i].velocity.z -= moons[i].position.z.compareTo(moons[j].position.z).sign moons[j].velocity.z += moons[i].position.z.compareTo(moons[j].position.z).sign } override fun toString(): String { val sb = StringBuilder() sb.appendln("StarSystem:") sb.appendln(moons.joinToString(separator = "\n") { it.toString() }) return sb.toString() } } fun main(args: Array<String>) { println("--- Day 12: The N-Body Problem ---"); val br = BufferedReader(FileReader("puzzle_input/day12-input1.txt")) val starSystem = StarSystem(br.readLines()) println("Loaded all celestial bodies:: $starSystem") for (step in IntRange(1, 1000)) { starSystem.updateVelocity() starSystem.applyVelocity() if (step > 998) { println("Step $step:\n$starSystem") println("Energy: ${starSystem.getTotalEnergy()}") } } // while (step < 2) { // // } // val stationAsteroid = day10partOne(map) // // if (stationAsteroid != null) { // day10partTwo(map, stationAsteroid) // } else { // println("Skipped part two because no station was found. :)") // } }
0
Kotlin
0
0
6af89b0440cc1d0cc3f07d5a62559aeb68e4511a
3,126
dukesaoc2019
MIT License
src/main/kotlin/dev/shtanko/algorithms/sorts/BinarySort.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.sorts class BinarySort : AbstractSortStrategy { override fun <T : Comparable<T>> perform(arr: Array<T>) { val lo = 0 val hi = arr.size val initRunLen = countRunAndMakeAscending(arr, lo, hi) helper(arr, lo, hi, lo + initRunLen) } private fun <T : Comparable<T>> helper(a: Array<T>, lo: Int, hi: Int, start: Int) { var start0 = start assert(start0 in lo..hi) if (start0 == lo) start0++ while (start0 < hi) { val pivot = a[start0] // Set left (and right) to the index where a[start] (pivot) belongs var left = lo var right = start0 assert(left <= right) /* * Invariants: * pivot >= all in [lo, left). * pivot < all in [right, start). */ while (left < right) { val mid = left + right ushr 1 if (pivot < a[mid]) right = mid else left = mid + 1 } assert(left == right) /* * The invariants still hold: pivot >= all in [lo, left) and * pivot < all in [left, start), so pivot belongs at left. Note * that if there are elements equal to pivot, left points to the * first slot after them -- that's why this sort is stable. * Slide elements over to make room for pivot. */ when (val n = start0 - left) { // The number of elements to move 2 -> { a[left + 2] = a[left + 1] a[left + 1] = a[left] } 1 -> a[left + 1] = a[left] else -> System.arraycopy(a, left, a, left + 1, n) } a[left] = pivot start0++ } } private fun <T : Comparable<T>> countRunAndMakeAscending(a: Array<T>, lo: Int, hi: Int): Int { if (a.isEmpty()) return 0 var runHi = lo + 1 if (runHi == hi) return 1 // Find end of run, and reverse range if descending if (a[runHi++] < a[lo]) { // Descending while (runHi < hi && a[runHi] < a[runHi - 1]) { runHi++ } reverseRange(a, lo, runHi) } else { // Ascending while (runHi < hi && a[runHi] >= a[runHi - 1]) { runHi++ } } return runHi - lo } private fun <T : Comparable<T>> reverseRange(a: Array<T>, lo: Int, hi: Int) { var lo0 = lo var hi0 = hi hi0-- while (lo0 < hi0) { val t = a[lo0] a[lo0++] = a[hi0] a[hi0--] = t } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,335
kotlab
Apache License 2.0
src/main/kotlin/co/csadev/advent2022/Day18.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 18 * Problem Description: http://adventofcode.com/2021/day/18 */ package co.csadev.advent2022 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Point3D import co.csadev.adventOfCode.Resources.resourceAsList class Day18(override val input: List<String> = resourceAsList("22day18.txt")) : BaseDay<List<String>, Int, Int> { private val lava = input.map { it.split(",").asPoint3D }.toSet() private val List<String>.asPoint3D: Point3D get() = Point3D(this[0].toInt(), this[1].toInt(), this[2].toInt()) override fun solvePart1(): Int { val totalSides = lava.size * 6 val touching = lava.sumOf { it.adjacent.count { n -> n in lava } } return totalSides - touching } override fun solvePart2(): Int { val map = mutableMapOf<Point3D, Boolean>() lava.forEach { l -> map[l] = false } map[Point3D(-2, -2, -2)] = true val searchRange = (-2..22) // Add and mark visited nodes var added = 1 while (added > 0) { added = 0 map.filter { it.value } .forEach { (p, _) -> p.adjacent.filter { it.x in searchRange } .filter { it.y in searchRange } .filter { it.z in searchRange } .filter { map.getOrDefault(it, 0) == 0 } .forEach { added++ map[it] = true } } } return map.filter { !it.value } .flatMap { it.key.adjacent } .count { map.getOrDefault(it, false) } } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
1,751
advent-of-kotlin
Apache License 2.0
src/Day03.kt
peterphmikkelsen
573,069,935
false
{"Kotlin": 7834}
fun main() { fun part1(input: List<String>): Int { var sum = 0 for (item in input) { val (first, second) = item.chunked(item.length/2) sum += first.first(second::contains).alphabetPosition() } return sum } fun part2(input: List<String>): Int { var sum = 0 for (item in input.chunked(3)) { val (elf1, elf2, elf3) = item sum += elf1.first { elf2.contains(it) && elf3.contains(it) }.alphabetPosition() } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } private fun Char.alphabetPosition(): Int { val alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" return alphabet.indexOf(this) + 1 }
0
Kotlin
0
0
374c421ff8d867a0bdb7e8da2980217c3455ecfd
977
aoc-2022
Apache License 2.0
src/com/company/AStar.kt
Chopinsky
102,678,276
false
{"Java": 16873, "Kotlin": 16695}
package com.company import java.util.* import kotlin.collections.ArrayList val D1 = 1.0 val D2 = Math.sqrt(2.0) val p = 1/1000 fun aStarSearch(start: Pair<Int, Int>, goal: Pair<Int, Int>, map: HashMap<Pair<Int, Int>, Int>): ArrayList<Pair<Int, Int>> { val failure = ArrayList<Pair<Int, Int>>() // set of node already evaluated val closedSet = HashSet<Pair<Int, Int>>() // set of currently discovered nodes var openSet = ArrayList<Pair<Int, Int>>() openSet.add(start) val cameFrom = HashMap<Pair<Int, Int>, Pair<Int, Int>>() val gScore = HashMap<Pair<Int, Int>, Double>() val fScore = HashMap<Pair<Int, Int>, Double>() for (pos: Pair<Int, Int> in map.keys) { if (pos.first == start.first && pos.second == start.second) continue gScore[pos] = Double.NEGATIVE_INFINITY fScore[pos] = Double.NEGATIVE_INFINITY } gScore[start] = 0.0 fScore[start] = -1 * heuristicCostEstimate(start, start, goal) var current: Pair<Int, Int> var result: Pair<Pair<Int, Int>, ArrayList<Pair<Int, Int>>> var neighbors: ArrayList<Pair<Int, Int>> var tempGScore: Double while (!openSet.isEmpty()) { result = getNextNode(openSet, fScore) current = result.first openSet = result.second if (current.first == goal.first && current.second == goal.second) { return reconstructPath(cameFrom, current) } openSet = removeNode(openSet, current, fScore) closedSet.add(current) neighbors = getNeighbors(current, map) for (neighbor: Pair<Int, Int> in neighbors) { // Ignore the neighbor which is already evaluated. if (closedSet.contains(neighbor)) continue // Discover a new node if (!openSet.contains(neighbor)) openSet = insertNode(openSet, neighbor, fScore) // The distance from start to a neighbor tempGScore = gScore[current]!! + Math.sqrt(0.0 + (current.first - neighbor.first) * (current.first - neighbor.first) + (current.second - neighbor.second) * (current.second - neighbor.second)) if (tempGScore >= gScore[neighbor]!!) continue // This path is the best until now. Record it! cameFrom[neighbor] = current gScore[neighbor] = tempGScore fScore[neighbor] = -1 * (gScore[neighbor]!! + heuristicCostEstimate(neighbor, start, goal)) } } return failure } fun heuristicCostEstimate(pos: Pair<Int, Int>, start: Pair<Int, Int>, goal: Pair<Int, Int>, option: Int = 0): Double { val dx = (goal.first - pos.first).toDouble() val dy = Math.abs(goal.second - pos.second).toDouble() val result = when(option) { 1 -> D1 * (dx + dy) 2 -> D1 * Math.max(dx, dy) + (D2 - 1) * Math.min(dx, dy) 3 -> D1 * Math.sqrt((dx * dx) + (dy * dy)) // euclidean distance else -> D1 * (dx + dy) + (D2 - 2 * D1) * Math.min(dx, dy) // octile distance } // Method 1 to break tie: return result * (1.0 + p) // Method 2 to break tie: //val cross = Math.abs(dx * (start.first - goal.first) - dy * (start.second - goal.second)) //return result + cross * p } fun findNextNode(openSet: HashSet<Pair<Int, Int>>, fScore: HashMap<Pair<Int, Int>, Double>): Pair<Int, Int> { if (openSet.isEmpty()) { return Pair(0, 0) } if (openSet.size == 1) { return openSet.elementAt(0) } var lowScore = Double.MAX_VALUE var nextNode = openSet.elementAt(0) for (node: Pair<Int, Int> in openSet) { if (fScore[node]!! < lowScore) { lowScore = fScore[node]!! nextNode = node } } return nextNode } fun insertNode(openSet: ArrayList<Pair<Int, Int>>, node: Pair<Int, Int>, fScore: HashMap<Pair<Int, Int>, Double>): ArrayList<Pair<Int, Int>> { openSet.add(node) var child = openSet.size - 1 var parent = (child - 1) / 2 var temp: Pair<Int, Int> while (child != 0 && fScore[openSet[child]]!! > fScore[openSet[parent]]!!) { temp = openSet[child] openSet[child] = openSet[parent] openSet[parent] = temp child = parent parent = (parent - 1) / 2 } return openSet } fun removeNode(openSet: ArrayList<Pair<Int, Int>>, node: Pair<Int, Int>, fScore: HashMap<Pair<Int, Int>, Double>): ArrayList<Pair<Int, Int>> { openSet.remove(node) return buildMaxHeap(openSet, fScore) } fun getNextNode(openSet: ArrayList<Pair<Int, Int>>, fScore: HashMap<Pair<Int, Int>, Double>): Pair<Pair<Int, Int>, ArrayList<Pair<Int, Int>>> { val nextNode = Pair(openSet[0].first, openSet[0].second) val newSet: ArrayList<Pair<Int, Int>> if (openSet.size == 1) { newSet = openSet } else { // replacing the first node with the last node. openSet[0] = openSet.removeAt(openSet.size-1) // heapify the remaining array-list newSet = buildMaxHeap(openSet, fScore) } return Pair(nextNode, newSet) } fun buildMaxHeap(openSet: ArrayList<Pair<Int, Int>>, fScore: HashMap<Pair<Int, Int>, Double>): ArrayList<Pair<Int, Int>> { var middle = openSet.size / 2 - 1 var heapSet = openSet while (middle >= 0) { heapSet = heapifyArray(heapSet, fScore, middle, openSet.size - 1) middle -= 1 } return heapSet } fun heapifyArray(openSet: ArrayList<Pair<Int, Int>>, fScore: HashMap<Pair<Int, Int>, Double>, root: Int, last: Int): ArrayList<Pair<Int, Int>> { val left = 2 * root + 1 val right = left + 1 var largest = root val temp: Pair<Int, Int> if (left <= last && fScore[openSet[left]]!! > fScore[openSet[largest]]!!) largest = left if (right <= last && fScore[openSet[right]]!! > fScore[openSet[largest]]!!) largest = right return when (largest != root) { true -> { temp = openSet[largest] openSet[largest] = openSet[root] openSet[root] = temp heapifyArray(openSet, fScore, largest, last) //return value } else -> { openSet //return value } } } fun reconstructPath(cameFrom: HashMap<Pair<Int, Int>, Pair<Int, Int>>, current: Pair<Int, Int>): ArrayList<Pair<Int, Int>> { val path = ArrayList<Pair<Int, Int>>() path.add(current) var pos = current while (cameFrom.containsKey(pos)) { pos = cameFrom[pos]!! path.add(pos) } return path } fun getNeighbors(current: Pair<Int, Int>, map: HashMap<Pair<Int, Int>, Int>): ArrayList<Pair<Int, Int>> { var neighbor: Pair<Int, Int> val neighbors: ArrayList<Pair<Int, Int>> = ArrayList() for (i in -1..1) { for (j in -1..1) { if (i == 0 && j == 0) continue neighbor = Pair(current.first + i, current.second + j) if (map.containsKey(neighbor) && map[neighbor] == 1) { neighbors.add(neighbor) } } } return neighbors }
0
Java
0
0
2274ef85ee6af7c4145adcb7e45c36bf723db9c8
7,094
-Exercises--Kotlin_with_Java
MIT License
src/day14/Day14.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day14 import readInput private const val DAY_ID = "14" private data class Point( val x: Int, val y: Int ) private data class Cave( val rocks: Set<Point>, val minX: Int, val maxY: Int ) fun main() { fun parseInput(input: List<String>): List<List<Point>> = input.map { line -> line.split(" -> ").map { point -> val (x, y) = point.split(",").map { it.toInt() } Point(x, y) } } fun scanCave(data: List<List<Point>>): Cave { val rocks = mutableSetOf<Point>() var minX = Int.MAX_VALUE var maxY = Int.MIN_VALUE for (path in data) { for (i in 0 until path.size - 1) { val dx = -1 * compareValues(path[i].x, path[i + 1].x) val dy = -1 * compareValues(path[i].y, path[i + 1].y) var curr = path[i] val stop = Point(path[i + 1].x + dx, path[i + 1].y + dy) while (curr != stop) { rocks += curr minX = minOf(minX, curr.x) maxY = maxOf(maxY, curr.y) curr = Point(curr.x + dx, curr.y + dy) } } } return Cave(rocks, minX, maxY) } fun part1(input: List<String>): Int { val source = Point(500, 0) val data = parseInput(input) val directions = listOf(0 to 1, -1 to 1, 1 to 1) // down, down-left, down-right val cave = scanCave(data) var done = false val sands = mutableSetOf<Point>() while (!done) { var curr = source var canMove = true while (canMove) { var moved = false for ((dx, dy) in directions) { val next = Point(curr.x + dx, curr.y + dy) if (next.x < cave.minX || next.y > cave.maxY) { done = true break } if (next !in sands && next !in cave.rocks) { curr = next moved = true break } } canMove = moved } if (!done) { sands += curr } } return sands.size } fun part2(input: List<String>): Int { val source = Point(500, 0) val data = parseInput(input) val directions = listOf(0 to 1, -1 to 1, 1 to 1) // down, down-left, down-right val cave = scanCave(data) var done = false val sands = mutableSetOf<Point>() while (!done) { var curr = source var canMove = true while (canMove) { var moved = false for ((dx, dy) in directions) { val next = Point(curr.x + dx, curr.y + dy) if (next !in sands && next !in cave.rocks && next.y < cave.maxY + 2) { curr = next moved = true break } } canMove = moved } sands += curr done = curr == source } return sands.size } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("day${DAY_ID}/Day$DAY_ID") println(part1(input)) // answer = 755 println(part2(input)) // answer = 29805 }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
3,663
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SmallestInfiniteSet.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import java.util.SortedSet import java.util.TreeSet /** * 2336. Smallest Number in Infinite Set * @see <a href="https://leetcode.com/problems/smallest-number-in-infinite-set">Source</a> */ interface SmallestInfiniteSet { fun popSmallest(): Int fun addBack(num: Int) } /** * Approach 1: Hashset + Heap */ class SmallestInfiniteSetHash : SmallestInfiniteSet { private var isPresent: HashSet<Int> = HashSet() private var addedIntegers: PriorityQueue<Int> = PriorityQueue() private var currentInteger: Int = 1 override fun popSmallest(): Int { val answer: Int // If there are numbers in the min-heap, // top element is lowest among all the available numbers. if (addedIntegers.isNotEmpty()) { answer = addedIntegers.poll() isPresent.remove(answer) } else { answer = currentInteger currentInteger += 1 } return answer } override fun addBack(num: Int) { if (currentInteger <= num || isPresent.contains(num)) { return } // We push 'num' in the min-heap if it isn't already present. addedIntegers.add(num) isPresent.add(num) } } class SmallestInfiniteSetSortedSet : SmallestInfiniteSet { private val addedIntegers: SortedSet<Int> = TreeSet() private var currentInteger: Int = 1 override fun popSmallest(): Int { val answer: Int // If there are numbers in the sorted-set, // top element is lowest among all the available numbers. if (addedIntegers.isNotEmpty()) { answer = addedIntegers.first() addedIntegers.remove(answer) } else { answer = currentInteger currentInteger += 1 } return answer } override fun addBack(num: Int) { if (currentInteger <= num || addedIntegers.contains(num)) { return } // We push 'num' in the sorted-set if it isn't already present. addedIntegers.add(num) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,731
kotlab
Apache License 2.0
src/Day01.kt
JanTie
573,131,468
false
{"Kotlin": 31854}
fun main() { fun foldInput(input: List<String>) = input .foldRight(mutableListOf<Int>() to 0) { new, (currentList, currentCount) -> if (new.isNotBlank()) { // new input is not a blank line increase current count currentList to currentCount + new.toInt() } else { // add to list, set current count to 0 // use mutableList and simply add to prevent new lists from being created currentList.add(currentCount) currentList to 0 } } .first fun part1(input: List<String>): Int { return foldInput(input).maxOf { it } } fun part2(input: List<String>): Int { val output = mutableListOf<Int>() foldInput(input).forEach { calories -> if (output.isEmpty()) { // initial output.add(calories) return@forEach } output.indexOfLast { currentEntry -> calories >= currentEntry } .let { index -> // if new value is larger than a current value, add it to that index if (index != -1) index // if maxsize is not reached yet, and no index is found, add to front of list else if (output.size < MAX_SIZE) 0 // otherwise ignore value else null } ?.let { index -> output.add(index + 1, calories) if (output.size > MAX_SIZE) { output.removeAt(0) } } } return output.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) } private const val MAX_SIZE = 3
0
Kotlin
0
0
3452e167f7afe291960d41b6fe86d79fd821a545
1,992
advent-of-code-2022
Apache License 2.0
kafka-reference-impl/judge/src/main/kotlin/Capturing.kt
Terkwood
191,042,808
false
null
/** Return all open spaces connected to the target piece's formation */ fun liberties(target: Coord, board: Board): Set<Coord> = connected(target, board).flatMap { neighborSpaces(it, board) }.toSet() fun neighbors(target: Coord, board: Board): Set<Pair<Coord, Player?>> = listOf( Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1) ).asSequence().map { (x, y) -> Coord( x + target.x, y + target.y ) }.filterNot { it.x < 0 || it.x >= board.size || it.y < 0 || it.y >= board.size }.map { Pair(it, board.pieces[it]) }.toSet() /** Return neighboring empty spaces */ fun neighborSpaces(target: Coord, board: Board): Set<Coord> = neighbors(target, board).mapNotNull { if (it.second != null) null else it.first }.toSet() /* Return neighborPieces on all sides of the target */ fun neighborPieces(target: Coord, board: Board): Set<Pair<Coord, Player>> = neighbors(target, board).mapNotNull { val p = it.second if (p == null) null else Pair(it.first, p) }.toSet() fun deadFrom(target: Coord, placement: Coord, board: Board): Boolean = liberties(target, board) == setOf(placement) /** Return all pieces of the same color, connected to the target. Includes * the target itself. */ fun connected(target: Coord, board: Board): Set<Coord> { val player = board.pieces[target] ?: return setOf() tailrec fun halp(targets: Set<Coord>, acc: Set<Coord>): Set<Coord> { val sameColorPieces = targets.mapNotNull { val found = board.pieces[it] if (found == null) null else { Pair(it, found) } }.filter { it.second == player }.map { it.first } val sameColorNeighbors: Set<Coord> = sameColorPieces .flatMap { neighborPieces( it, board ) }.filter { it.second == player }.map { it .first }.toSet() return if (acc.containsAll(sameColorNeighbors)) acc else { val nextAcc = acc.union(sameColorNeighbors) halp(sameColorNeighbors, nextAcc) } } return halp(setOf(target), setOf(target)) } /** Returns a set of all coordinates captured by `player` placing a piece at * `placement` */ fun capturesFor(player: Player, placement: Coord, board: Board): Set<Coord> { val enemyNeighbors = neighborPieces(placement, board).filter { it.second != player }.map { Pair(it.first, it.second) } val someDead = enemyNeighbors.map { (target, _) -> if (deadFrom(target, placement, board)) { connected(target, board) } else HashSet() } return someDead.flatten().toSet() }
83
Rust
7
65
ec01dc3dae54e1e248d540d442caa1731f2822e4
3,024
BUGOUT
MIT License
lc004/src/main/kotlin/misc/Solution.kt
warmthdawn
467,419,502
false
{"Kotlin": 28653, "Java": 8222}
package misc; import kotlin.math.max import kotlin.system.measureTimeMillis import kotlin.time.ExperimentalTime import kotlin.time.measureTime data class State( val rank: Int, val star: Int, val continuousWin: Int, val preserveStars: Int ) class Solution { fun calc(starPerRank: Int, winPerPreserve: Int, totalWin: Int, targetRank: Int, gameRecord: String): Boolean { //缓存,好像除了浪费内存没啥用( val winCache = HashMap<State, State>() val failCache = HashMap<State, State>() //如果胜利,下一场次的状态 fun State.win(): State = winCache.computeIfAbsent(this) { if (star == starPerRank) { State( rank + 1, 1, (continuousWin + 1) % winPerPreserve, (continuousWin + 1) / winPerPreserve ) } else { State( rank, star + 1, (continuousWin + 1) % winPerPreserve, (continuousWin + 1) / winPerPreserve ) } } //如果失败,下一场次的状态 fun State.fail(): State = failCache.computeIfAbsent(this) { if (preserveStars > 0) { State( rank, star, 0, preserveStars - 1 ) } else if (star == 0) { State( if (rank == 1) 1 else rank - 1, starPerRank - 1, 0, 0 ) } else { State( rank, star + 1, 0, 0 ) } } //计算胜利场次数量 val restWins = totalWin - gameRecord.count { it == '1' } var maxRank = 1 //模拟 fun simulate(i: Int, currentState: State, chooseWins: Int) { if (chooseWins > restWins) { return } if (i >= gameRecord.length) { if (chooseWins == restWins) { maxRank = max(maxRank, currentState.rank) } return } when (gameRecord[i]) { '0' -> simulate(i + 1, currentState.fail(), chooseWins) '1' -> simulate(i + 1, currentState.win(), chooseWins) '?' -> { simulate(i + 1, currentState.fail(), chooseWins) simulate(i + 1, currentState.win(), chooseWins + 1) } else -> throw IllegalArgumentException("Game record should only contains '0', '1' and '?'") } } simulate(0, State(1, 1, 0, 0), 0) return maxRank >= targetRank } fun run() { val (m, d, B, C) = readLine()!!.split(" ").map { it.trim().toInt() } val S = readLine()!!.split(" ").filter { it.isNotEmpty() }.joinToString("") { it } val time = measureTimeMillis { val calc = calc(m, d, B, C, S) println(calc) } println("方法执行耗时 $time ms") } } fun main() { Solution().run() }
0
Kotlin
0
0
40dc158a934f0fc4a3c6076bf1b5babf8413e190
3,349
LeetCode
MIT License
src/Day03.kt
icoffiel
572,651,851
false
{"Kotlin": 29350}
private const val UPPERCASE_ASCII_RESET = 38 private const val LOWERCASE_ASCII_RESET = 96 fun main() { fun Char.toPriority() = when { isUpperCase() -> code - UPPERCASE_ASCII_RESET isLowerCase() -> code - LOWERCASE_ASCII_RESET else -> error("Unexpected condition") } fun part1(input: List<String>): Int { return input .map { it.chunked(it.length / 2) } .flatMap { (first, second) -> first.toSet() intersect second.toSet() } .sumOf { it.toPriority() } } fun part2(input: List<String>): Int { return input .chunked(3) .flatMap { (first, second, third) -> first.toSet() intersect second.toSet() intersect third.toSet() } .sumOf { it.toPriority() } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) check(part1(input) == 8085) println(part2(input)) check(part2(input) == 2515) }
0
Kotlin
0
0
515f5681c385f22efab5c711dc983e24157fc84f
1,053
advent-of-code-2022
Apache License 2.0
2023/07/Solution.kt
AdrianMiozga
588,519,359
false
{"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732}
import java.io.File private const val FILENAME = "2023/07/input.txt" private val numericToRank = mapOf( "5" to 6, "41" to 5, "32" to 4, "311" to 3, "221" to 2, "2111" to 1, ) fun main() { partOne() partTwo() } private fun partOne() { val file = File(FILENAME).readLines() val hands: MutableList<HandOne> = mutableListOf() for (line in file) { val (type, bid) = line.split(" ") val numeric = type.groupingBy { it }.eachCount().values.toList() .sortedDescending().joinToString(separator = "") val rank = numericToRank[numeric] ?: 0 hands.add(HandOne(type, bid, rank)) } var result = 0 for ((index, hand) in hands.sorted().withIndex()) { result += (hand.bid.toInt() * (index + 1)) } println(result) } private fun partTwo() { val file = File(FILENAME).readLines() val hands: MutableList<HandTwo> = mutableListOf() for (line in file) { val (type, bid) = line.split(" ") val map = HashMap<Char, Int>() var jCount = 0 for (character in type) { if (character == 'J') { jCount++ continue } if (map[character] != null) { map[character] = map[character]!! + 1 } else { map[character] = 1 } } val numeric = map.values.toList().sortedDescending().joinToString(separator = "") val updated = if (numeric.isEmpty()) { "5" } else { (numeric[0].code - 48 + jCount).toString() + numeric.slice(1 until numeric.length) } val rank = numericToRank[updated] ?: 0 hands.add(HandTwo(type, bid, rank)) } var result = 0 for ((index, hand) in hands.sorted().withIndex()) { result += (hand.bid.toInt() * (index + 1)) } println(result) }
0
Kotlin
0
0
c9cba875089d8d4fb145932c45c2d487ccc7e8e5
1,934
Advent-of-Code
MIT License
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem029.kt
mddburgess
261,028,925
false
null
package dev.mikeburgess.euler.problems import java.math.BigInteger /** * Problem 29 * * Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: * * 2^2 = 4, 2^3 = 8, 2^4 = 16, 2^5 = 32 * 3^2 = 9, 3^3 = 27, 3^4 = 81, 3^5 = 243 * 4^2 = 16, 4^3 = 64, 4^4 = 256, 4^5 = 1024 * 5^2 = 25, 5^3 = 125, 5^4 = 625, 5^5 = 3125 * * If they are then placed in numerical order, with any repeats removed, we get the following * sequence of 15 distinct terms: * * 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 * * How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? */ class Problem029 : Problem { override fun solve(): Long = (2..100L).flatMap { a -> (2..100).map { b -> a to b } } .map { (a, b) -> BigInteger.valueOf(a).pow(b) } .distinct() .count().toLong() }
0
Kotlin
0
0
86518be1ac8bde25afcaf82ba5984b81589b7bc9
901
project-euler
MIT License
src/day03/Day03.kt
ayukatawago
572,742,437
false
{"Kotlin": 58880}
package day03 import readInput fun main() { fun Char.getScore(): Int = when { this.isLowerCase() -> this - 'a' + 1 this.isUpperCase() -> this - 'A' + 27 else -> 0 } fun part1(input: List<String>): Int { var scoreSum = 0 input.map { it.chunked(it.length / 2) }.forEach { if (it.size != 2) return@forEach val firstSet = it[0].toSet() val secondSet = it[1].toSet() val intersectSet = firstSet intersect secondSet if (intersectSet.size != 1) return@forEach scoreSum += intersectSet.first().getScore() } return scoreSum } fun part2(input: List<String>): Int { var scoreSum = 0 input.chunked(3).forEach { if (it.size != 3) return@forEach val firstSet = it[0].toSet() val secondSet = it[1].toSet() val thirdSet = it[2].toSet() val intersectSet = firstSet intersect secondSet intersect thirdSet if (intersectSet.size != 1) return@forEach scoreSum += intersectSet.first().getScore() } return scoreSum } val testInput = readInput("day03/Day03_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
923f08f3de3cdd7baae3cb19b5e9cf3e46745b51
1,305
advent-of-code-2022
Apache License 2.0
src/Day06.kt
ka1eka
574,248,838
false
{"Kotlin": 36739}
fun main() { fun detectMarker(input: List<String>, size: Int) = input .first() .toCharArray() .asSequence() .windowed(size) .indexOfFirst { it.distinct().size == size } + size fun part1(input: List<String>): Int = detectMarker(input, 4) fun part2(input: List<String>): Int = detectMarker(input, 14) val testInput = readInput("Day06_test").map { listOf(it) } check(part1(testInput[0]) == 7) check(part1(testInput[1]) == 5) check(part1(testInput[2]) == 6) check(part1(testInput[3]) == 10) check(part1(testInput[4]) == 11) check(part2(testInput[0]) == 19) check(part2(testInput[1]) == 23) check(part2(testInput[2]) == 23) check(part2(testInput[3]) == 29) check(part2(testInput[4]) == 26) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4f7893448db92a313c48693b64b3b2998c744f3b
894
advent-of-code-2022
Apache License 2.0
src/Day17.kt
rod41732
572,917,438
false
{"Kotlin": 85344}
private fun simulateFall(rockGroup: Chunk, jets: Iterator<Int>, chamber: Chamber) { while (true) { val jet = jets.next() if (!chamber.rocksWillCollide(rockGroup.rocks, dx = jet, dy = 0)) { rockGroup.move(dx = jet, dy = 0) } // fall if (!chamber.rocksWillCollide(rockGroup.rocks, dy = -1)) { rockGroup.move(dy = -1) } else { break } } } fun main() { // bf XD fun part1(input: String, rounds: Int): Int { return Chamber(7).let {chamber -> val jetStream = parseJet(input).asSequence().cycled().iterator() val rockGroups = rockPrototype.asSequence().cycled().iterator() repeat(rounds) { val rockGroup = rockGroups.next().movedTo(3, chamber.height + 4) simulateFall(rockGroup, jetStream,chamber) chamber.addRocks(rockGroup.rocks) } chamber.height } } fun part2(input: String, rounds: Long): Long { check((rounds % 5).toInt() == 0) val jetStream = parseJet(input).asSequence().cycled().iterator() val rockGroups = rockPrototype.asSequence().withIndex().cycled().iterator() val chamber = Chamber(7) val rockEnd = rockPrototype.size - 1 var lastHeight = 0 val increment = mutableListOf<Int>() repeat(rounds) { val (rockGroup, rockIndex) = rockGroups.next() .let{ it.value.movedTo(3, chamber.height + 4) to it.index } simulateFall(rockGroup, jetStream, chamber) chamber.addRocks(rockGroup.rocks) // cycle optimization if (rockIndex == rockEnd) { chamber.height.let { increment.add(it - lastHeight) lastHeight = it } val cycle = findCycle(increment) if (cycle != null) { val accum = increment.runningReduce { acc, v -> acc + v } val ansIndex = rounds / 5 - 1 // need to add at least one cycle before optimization // e.g. consider optimizing this 1, 2, 100, 200, 300, 100, 200, 300, 100, 200, 300 ... return accum[ansIndex.mod(cycle.size) + cycle.size] + (ansIndex / cycle.size - 1) * cycle.sum() } } } return chamber.height.toLong() } val testInput = readInput("Day17_test").first() check(part1(testInput, rounds = 1) == 1) check(part1(testInput, rounds = 2) == 4) check(part1(testInput, rounds = 3) == 6) check(part1(testInput, rounds = 4) == 7) check(part1(testInput, rounds = 5) == 9) check(part1(testInput, rounds = 6) == 10) check(part1(testInput, rounds = 7) == 13) check(part1(testInput, rounds = 8) == 15) println(part1(testInput, rounds = 2022)) check(part1(testInput, rounds = 2022) == 3068) println(part1(testInput, rounds = 2022)) check(part1(testInput, rounds = 2022) == 3068) val input = readInput("Day17").first() println(part1(input, rounds = 2022)) // println(part2Test(testInput, rounds = 2000)) listOf(5, 10, 20, 100, 500, 725, 1000, 1500, 2100, 5000, 10000, 12005).forEach { println("checking $it") println("${part1(testInput, it).toLong()} ${part2(testInput, it.toLong())}") check(part1(testInput, it).toLong() == part2(testInput, it.toLong())) println("$it OK") } println("LUL") // part2Test(input) // part2Test(input, rounds = 1000) println(part2(input, 1_000_000_000_000L)) // 1562536023044 too big // 1562536022966 } private fun parseJet(input: String): List<Int> { return input.trim().map { if (it == '<') -1 else 1 } } private fun findCycle(l: List<Int>): List<Int>? { (1..l.size / 2).forEach { repeatSize -> l.reversed().chunked(repeatSize).filter { it.size == repeatSize }.let { chunks -> val first = chunks[0] val remaining = chunks.subList(1, chunks.size) if (remaining.all { it == first }) { return first } } } return null } private data class Chamber(val width: Int) { // Chamber has rock at position x = 0 (left), x = width + 1 (right), y = 0 (bottom) private val settledRocks = mutableSetOf<Rock>() var height = 0 // height of the highest point in the chamber, or 0 (the floor) if there's no rock /** return whether the rocks will collide with rocks/floor/side of chamber if it were moved that way */ fun rocksWillCollide(rocks: Iterable<Rock>, dx: Int = 0, dy: Int = 0): Boolean { return rocks.asSequence().map { it.moved(dx = dx, dy = dy) }.any { it.x == 0 || it.x == width + 1 || it.y == 0 || it in this.settledRocks } } /** add rocks, update height as appropriate */ fun addRocks(rocks: Iterable<Rock>) { rocks.forEach { settledRocks.add(it) if (it.y > height) height = it.y } } } data class Rock(var x: Int, var y: Int) { fun move(dx: Int = 0, dy: Int = 0) { x += dx y += dy } fun moved(dx: Int = 0, dy: Int = 0) = Rock(x + dx, y + dy) } data class Chunk(val rocks: List<Rock>) { var lowerLeft = Coord2D( x = rocks.minOf { it.x }, y = rocks.minOf { it.y }, ) /** return new rock group with same shape but lowerLeft position moved to specified point */ fun movedTo(lowerLeftX: Int, lowerLeftY: Int): Chunk { val dx = lowerLeftX - lowerLeft.x val dy = lowerLeftY - lowerLeft.y return Chunk(rocks.map { it.moved(dx, dy) }) } /** move all rocks by specified deltas */ fun move(dx: Int = 0, dy: Int = 0) { rocks.forEach { it.move(dx, dy) } } } private fun <T> Sequence<T>.cycled() = sequence { while (true) { yieldAll(this@cycled) } } val rockPrototype = listOf( // _ Chunk((0 until 4).map { Rock(it, 0) }), // + shape Chunk( listOf( Rock(0, 0), Rock(1, 0), Rock(0, 1), Rock(-1, 0), Rock(0, -1), ), ), // _| shape Chunk( listOf( Rock(0, 0), Rock(-1, 0), Rock(-2, 0), Rock(0, 1), Rock(0, 2), ), ), // | Chunk((0 until 4).map { Rock(0, it) }), // square Chunk((0 until 4).map { Rock(it / 2, it % 2) }), )
0
Kotlin
0
0
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
6,536
advent-of-code-kotlin-2022
Apache License 2.0
src/day05/Day05.kt
molundb
573,623,136
false
{"Kotlin": 26868}
package day05 import readInput import java.util.LinkedList fun main() { val input = readInput(parent = "src/day05", name = "Day05_input") println(solvePartOne(input)) println(solvePartTwo(input)) } private fun solvePartOne(input: List<String>) = solve(input, false) private fun solvePartTwo(input: List<String>) = solve(input, true) private fun solve(input: List<String>, partTwo: Boolean): String { val stacks: MutableMap<Int, LinkedList<Char>> = mutableMapOf( 1 to LinkedList<Char>(), 2 to LinkedList<Char>(), 3 to LinkedList<Char>(), 4 to LinkedList<Char>(), 5 to LinkedList<Char>(), 6 to LinkedList<Char>(), 7 to LinkedList<Char>(), 8 to LinkedList<Char>(), 9 to LinkedList<Char>(), ) for (s in input) { if (s.startsWith('[')) { for (i in s.indices) { val c = s[i] if (c.isLetter()) { val i1 = (i - 1) / 4 + 1 stacks[i1]!!.push(c) } } } if (s.startsWith("move")) { val split = s.split(' ') val numberOfCratesToMove = split[1].toInt() val fromStackNumber = split[3].toInt() val toStackNumber = split[5].toInt() val fromStack = stacks[fromStackNumber]!! stacks[fromStackNumber] = LinkedList(fromStack.dropLast(numberOfCratesToMove)) val toStack = stacks[toStackNumber]!! val cratesToMove = fromStack.takeLast(numberOfCratesToMove) toStack.addAll( if (partTwo) { cratesToMove } else { cratesToMove.reversed() } ) } } var res = "" stacks.values.forEach { res += it.last } return res }
0
Kotlin
0
0
a4b279bf4190f028fe6bea395caadfbd571288d5
1,871
advent-of-code-2022
Apache License 2.0
project_euler_kotlin/src/main/kotlin/Utils.kt
NekoGoddessAlyx
522,068,054
false
{"Kotlin": 44135, "Rust": 24687}
import java.math.BigInteger import kotlin.math.ceil import kotlin.math.sqrt /** Fibonacci sequence generator starting with 1 and 1 */ fun fibGenerator() = sequence { yield(1) // seed values (will result in the first number being 1 and the second number being 2 var a = 0 var b = 1 while (true) { val next = a + b a = b b = next yield(next) } } /** Fibonacci sequence generator starting with 1 and 1 */ fun bigFibGenerator() = sequence { yield(BigInteger.ONE) // seed values (will result in the first number being 1 and the second number being 2 var a = BigInteger.ZERO var b = BigInteger.ONE while (true) { val next = a + b a = b b = next yield(next) } } fun sqrt(n: Long): Long = sqrt(n.toDouble()).toLong() /** Returns a list of all prime factors of a number */ fun getPrimeFactors(n: Long): Map<Long, Long> { var number = n val primeFactors = mutableMapOf<Long, Long>() // remove the 2s until the number is odd while (number % 2 == 0L) { primeFactors[2L] = primeFactors.getOrDefault(2L, 0L) + 1 number /= 2L } // number is now odd, increment by 2 val factorizationEnd = sqrt(n) var factor = 3L while (factor <= factorizationEnd) { while (number % factor == 0L) { primeFactors[factor] = primeFactors.getOrDefault(factor, 0L) + 1 number /= factor } factor += 2 } // handle the case of prime numbers greater than 2 if (number > 2) primeFactors[number] = primeFactors.getOrDefault(number, 0L) + 1 return primeFactors } fun getDivisors(n: Long): List<Long> { val factors = mutableListOf(1L) var factor = 2L val end = ceil(sqrt(n.toDouble())).toLong() while (factor <= end) { if (n % factor == 0L) { factors += factor factors += n / factor } factor++ } factors += n factors.sort() return factors.distinct() } fun getProperDivisors(n: Long): List<Long> = getDivisors(n).filter { it < n } fun getNumberOfDivisors(n: Long): Long { var numFactors = 0L var factor = 1L val end = ceil(sqrt(n.toDouble())).toLong() while (factor < end) { if (n % factor == 0L) numFactors += 2 factor++ } // take care of square numbers if (sqrt(n) * sqrt(n) == n) numFactors++ return numFactors } /** Prime number sequence generator through brute force */ fun primeGenerator(): Sequence<Long> = sequence { yield(2L) var number = 3L while (true) { if (isPrime(number)) yield(number) number += 2L } } /** Optimized test for prime numbers */ fun isPrime(n: Long): Boolean { if (n == 2L || n == 3L) return true if (n <= 1L || n % 2L == 0L || n % 3L == 0L) return false var i = 5 while (i * i <= n) { if (n % i == 0L || n % (i + 2L) == 0L) return false i += 6 } return true } fun triangleNumberGenerator() = sequence<Long> { var previousTotal = 0L var index = 1L while (true) { previousTotal += index index++ yield(previousTotal) } } /** Collatz sequence, start must be >= 2 */ fun collatzSequenceGenerator(start: Long) = sequence { yield(start) var n = start while (true) { if (n % 2L == 0L) n /= 2L else n = 3 * n + 1 yield(n) if (n == 1L) return@sequence } } /** Collatz sequence length, start must be >= 2 */ fun collatzSequenceLength(start: Long): Long { var length = 1L var n = start while (true) { if (n % 2L == 0L) n /= 2L else n = 3 * n + 1 length++ // have faith they all get to 1 eventually :) if (n == 1L) return length } } fun factorial(n: Long): BigInteger = when { n < 0 -> throw IllegalArgumentException("n must be a non-negative integer.") n == 0L -> BigInteger.ONE n == 1L -> BigInteger.ONE else -> (2..n).fold(BigInteger.ONE) { acc, l -> acc * BigInteger.valueOf(l) } } /** n choose k. The number of combinations of n things taken k at a time */ fun combination(n: Long, k: Long): Long { return (factorial(n) / (factorial(k) * factorial(n - k))).toLong() } /** Similar to combinations but the order matters (where it doesn't for combinations) */ fun permutations(n: Long, k: Long): Long { return (factorial(n) / factorial(n - k)).toLong() } fun <T : Comparable<T>> orderedPermutationGenerator(input: Iterable<T>, choose: Int = -1) = sequence { val elements = input.toMutableList() if (elements.isEmpty()) return@sequence elements.sort() val c = if (choose != -1) choose else elements.size var hasNext = true while (hasNext) { yield(elements.subList(0, c)) var k = 0 var l = 0 hasNext = false for (i in elements.size - 1 downTo 1) { if (elements[i] > elements[i - 1]) { k = i - 1 hasNext = true break } } for (i in elements.size - 1 downTo k + 1) { if (elements[i] > elements[k]) { l = i break } } val t = elements[k] elements[k] = elements[l] elements[l] = t elements.subList(k + 1, elements.size).reverse() } } /** * Represents a number 1/[divisor] * * Contains a nonrepeating fractional part and a repeating fractional part as strings * The full decimal representation can be calculated as * * `0.(nonRepeatingFraction)(repeatingFraction)(repeatingFraction)(repeatingFraction)(...)` */ data class UnitFraction(val divisor: Long, val nonRepeatingFraction: String, val repeatingFraction: String) { override fun toString(): String = buildString { append("0.") append(nonRepeatingFraction) if (repeatingFraction.isNotEmpty()) { append("(") append(repeatingFraction) append(")") } } } /** Generates unit fractions (a number that contains a 1 in the numerator) starting from 2 */ fun unitFractionGenerator() = sequence { // the divisor (1/d) var d = 2L while (true) { // digits will hold all digits // if/when repeating digits are found, they will be removed and added to repeating digits val digits = StringBuilder() val remainders = mutableListOf<Long>() val repeatingDigits = StringBuilder() // dividend is the number to be continually divided to calculate the digits var dividend = 10L // dividend will be expanded (by 10) when necessary // keep track of that in order to append a 0 digit when appropriate var hadDigit = false main@while (dividend != 0L) { // expand the dividend if we can't neatly divide out the divisor while (dividend < d) { dividend *= 10L if (!hadDigit) { digits.append(0) remainders += dividend } hadDigit = false } // calculate the remainder and divide out what we can val remainder = dividend % d val digit = (dividend - remainder) / d // carry the remainder dividend = remainder // check if the current digit is already contained in the digits // if so, we're done dividing as we've found a repeating cycle for (index in digits.indices) { val c = digits[index] if (c == digit.toString()[0] && remainders[index] == remainder) { if (index == digits.lastIndex || index == 0) { repeatingDigits.appendRange(digits, index, digits.length) digits.delete(index, digits.length) break@main } else if (digits[index - 1] == digits.last()) { repeatingDigits.appendRange(digits, index - 1, digits.length - 1) digits.delete(index - 1, digits.length) break@main } } } // otherwise, append the digit digits.append(digit) remainders += dividend hadDigit = true } yield(UnitFraction(d++, digits.toString(), repeatingDigits.toString())) } }
0
Kotlin
0
0
f899b786d5ea5ffd79da51604dc18c16308d2a8a
8,475
Project-Euler
The Unlicense
src/main/kotlin/GroupAnagrams.kt
Codextor
453,514,033
false
{"Kotlin": 26975}
/** * Given an array of strings strs, group the anagrams together. You can return the answer in any order. * * An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, * typically using all the original letters exactly once. * * * * Example 1: * * Input: strs = ["eat","tea","tan","ate","nat","bat"] * Output: [["bat"],["nat","tan"],["ate","eat","tea"]] * Example 2: * * Input: strs = [""] * Output: [[""]] * Example 3: * * Input: strs = ["a"] * Output: [["a"]] * * * Constraints: * * 1 <= strs.length <= 10^4 * 0 <= strs[i].length <= 100 * strs[i] consists of lowercase English letters. * @see <a href="https://leetcode.com/problems/group-anagrams/">LeetCode</a> */ fun groupAnagrams(strs: Array<String>): List<List<String>> { val resultMap = mutableMapOf<List<Int>, MutableList<String>>() strs.forEach { string -> val countArray = IntArray(26) string.forEach { char -> countArray[char - 'a'] += 1 } val key = countArray.toList() val currentList = resultMap.getOrDefault(key, mutableListOf()) currentList.add(string) resultMap[key] = currentList } val resultList = mutableListOf<List<String>>() resultMap.values.forEach { listOfString -> resultList.add(listOfString) } return resultList }
0
Kotlin
1
0
68b75a7ef8338c805824dfc24d666ac204c5931f
1,361
kotlin-codes
Apache License 2.0
src/Day25.kt
rosyish
573,297,490
false
{"Kotlin": 51693}
import kotlin.math.abs fun main() { fun Char.snafuCharToInt(): Int { return when (this) { '2' -> 2 '1' -> 1 '0' -> 0 '-' -> -1 '=' -> -2 else -> throw IllegalArgumentException("$this is not a snafu char") } } fun Int.snafuIntToChar(): Char { return when (this) { 2 -> '2' 1 -> '1' 0 -> '0' -2 -> '=' -1 -> '-' else -> throw IllegalArgumentException("$this is not a snafu int") } } fun snafuStrToDecimal(str: String): Long { var num = 0L var multiplier = 1L for (i in str.indices.reversed()) { num += multiplier * str[i].snafuCharToInt() multiplier *= 5L } return num } fun decimalToSnafuStr(num: Long): String { var p = 1L var sumOfPowers = 0L while (p < (abs(num)) / 2) { sumOfPowers += p p *= 5 } var n = num var snafuStr = StringBuilder() while (p > 0) { var next = 0 var absoluteN = abs(n) while (next < 2 && 2 * sumOfPowers < absoluteN) { next++ absoluteN -= p } if (n > 0) { n -= (next * p) } else { n += (next * p) next = -next } snafuStr.append(next.snafuIntToChar()) p /= 5 sumOfPowers -= p } return snafuStr.toString() } readInput("Day25_input") .sumOf { str -> snafuStrToDecimal(str) } .also { println("Decimal value $it") } .let { num -> decimalToSnafuStr(num) } .also { println("Answer: $it") } .also { println("Snafu string back to decimal ${snafuStrToDecimal(it)}") } }
0
Kotlin
0
2
43560f3e6a814bfd52ebadb939594290cd43549f
1,901
aoc-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem103/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem103 import com.hj.leetcode.kotlin.common.model.TreeNode /** * LeetCode page: [103. Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the number of nodes in root; */ fun zigzagLevelOrder(root: TreeNode?): List<List<Int>> { if (root == null) return emptyList() val sortedValues = mutableListOf<List<Int>>() var sortedCurrentLevel = listOf(root) while (sortedCurrentLevel.isNotEmpty()) { sortedValues.add(sortedCurrentLevel.map { it.`val` }) val isNextLevelZig = sortedValues.size and 1 == 0 sortedCurrentLevel = sortedNextLevel(sortedCurrentLevel, isNextLevelZig) } return sortedValues } private fun sortedNextLevel(sortedCurrentLevel: List<TreeNode>, isNextLevelZig: Boolean): List<TreeNode> { return if (isNextLevelZig) { buildNextLevelInZigOrder(sortedCurrentLevel) } else { buildNextLevelInZagOrder(sortedCurrentLevel) } } private fun buildNextLevelInZigOrder(sortedCurrentLevel: List<TreeNode>): List<TreeNode> { val sortedNextLevel = mutableListOf<TreeNode>() for (index in sortedCurrentLevel.indices.reversed()) { val parentNode = sortedCurrentLevel[index] parentNode.left?.let { sortedNextLevel.add(it) } parentNode.right?.let { sortedNextLevel.add(it) } } return sortedNextLevel } private fun buildNextLevelInZagOrder(sortedCurrentLevel: List<TreeNode>): List<TreeNode> { val sortedNextLevel = mutableListOf<TreeNode>() for (index in sortedCurrentLevel.indices.reversed()) { val parentNode = sortedCurrentLevel[index] parentNode.right?.let { sortedNextLevel.add(it) } parentNode.left?.let { sortedNextLevel.add(it) } } return sortedNextLevel } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,053
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/AverageSalary.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 /** * 1491. Average Salary Excluding the Minimum and Maximum Salary * @see <a href="https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary"> * Source</a> */ fun interface AverageSalary { fun average(salary: IntArray): Double } class AverageSalaryBruteForce : AverageSalary { override fun average(salary: IntArray): Double { var sum = 0.0 var min = Int.MAX_VALUE var max = 0 for (s in salary) { sum += s if (s < min) { min = s } if (s > max) { max = s } } return sum.minus(max).minus(min) / salary.size.minus(2) } } class AverageSalarySimple : AverageSalary { override fun average(salary: IntArray): Double { return salary.sorted().toTypedArray().copyOfRange(1, salary.size - 1).average() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,543
kotlab
Apache License 2.0
src/Day01.kt
binaryannie
573,120,071
false
{"Kotlin": 10437}
fun main() { fun part1(input: List<String>): Int { var maxCalories = 0 var currentCalories = 0 input.forEach { if (it.isBlank()) { if(currentCalories > maxCalories) maxCalories = currentCalories currentCalories = 0 } else { currentCalories += it.toInt() } } if(currentCalories > maxCalories) maxCalories = currentCalories return maxCalories } fun part2(input: List<String>): Int { var elfCalories = mutableListOf<Int>() var currentCalories = 0 input.forEach { if (it.isBlank()) { elfCalories.add(currentCalories) currentCalories = 0 } else { currentCalories += it.toInt() } } elfCalories.add(currentCalories) elfCalories.sortDescending() return elfCalories.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
511fc33f9dded71937b6bfb55a675beace84ca22
1,249
advent-of-code-2022
Apache License 2.0
2020/Day10/src/main/kotlin/main.kt
airstandley
225,475,112
false
{"Python": 104962, "Kotlin": 59337}
import java.io.File fun getInput(file: String): List<String> { return File(file).readLines() } fun parseInput(input: List<String>): List<Int> { val output: MutableList<Int> = mutableListOf() for (line in input) { output.add(line.toInt()) } return output } fun countAdapterGaps(adapters: List<Int>): Triple<Int, Int, Int> { var oneVolt = 0 var twoVolt = 0 var threeVolt = 0 for (i in 1 until adapters.size) { when (adapters[i] - adapters[i - 1]) { 1 -> { oneVolt++ } 2 -> { twoVolt++ } 3 -> { threeVolt++ } else -> { throw Exception("Invalid List. Can't go from ${adapters[i - 1]} to ${adapters[i]}") } } } return Triple(oneVolt, twoVolt, threeVolt) } val countViableArrangementCalls: MutableMap<List<Int>, Long> = mutableMapOf() fun countViableArrangements(adapters: List<Int>): Long { var arrangements: Long = 0 for (i in 1 until adapters.size - 1) { println("(${adapters.first()} - ${adapters.last()}) Index: $i, Item: ${adapters[i]}, Count: $arrangements") // See if we can drop this element if (adapters[i + 1] - adapters[i - 1] <= 3) { // Include all the valid paths with this element removed val newList: MutableList<Int> = adapters.slice(IntRange(i + 1, adapters.size - 1)) as MutableList<Int> newList.add(0, adapters[i - 1]) println("Dropping ${adapters[i]}, NewList: ${newList.first()} to ${newList.last()}") arrangements += countViableArrangementCalls.getOrPut(newList) { countViableArrangements(newList) } } } return arrangements + 1 } fun main(args: Array<String>) { val input = parseInput(getInput("Input")) as MutableList<Int> input.sort() input.add(0, 0) input.add(input.last() + 3) val counts = countAdapterGaps(input) println("On Volt: ${counts.first}, Two Volts: ${counts.second}, Three Volts: ${counts.third}") println("First Solution: ${counts.first*counts.second}") val permutations = countViableArrangements(input) println("Second Solution: ${permutations.toBigDecimal().toPlainString()}") }
0
Python
0
0
86b7e289d67ba3ea31a78f4a4005253098f47254
2,292
AdventofCode
MIT License
src/year2022/day13/Day13.kt
kingdongus
573,014,376
false
{"Kotlin": 100767}
package year2022.day13 import readInputFileByYearAndDay import readTestFileByYearAndDay fun String.startsWithList(): Boolean = this.startsWith("[") fun String.extractFirstInt(): Int = this.split(",").first().toInt() infix fun String.extractListIndicesStartingFrom(start: Int): Pair<Int, Int> { if (this[start] != '[') return -1 to -1 var openingBrackets = 0 for (i in start..indices.last) { if (this[i] == '[') { openingBrackets += 1 } else if (this[i] == ']') { openingBrackets -= 1 } if (openingBrackets == 0) return start to i } return -1 to -1 } infix fun String.compareAsPacket(other: String): Int { var idLeft = 0 var idRight = 0 while (idLeft < this.length && idRight < other.length) { val remainingLeft = this.substring(idLeft) val remainingRight = other.substring(idRight) val leftIsList = remainingLeft.startsWithList() val rightIsList = remainingRight.startsWithList() // if left and right are ints, compare ints if (!leftIsList and !rightIsList) { val leftInt = remainingLeft.extractFirstInt() val rightInt = remainingRight.extractFirstInt() when (leftInt compareTo rightInt) { 1 -> return 1 -1 -> return -1 else -> { idLeft += leftInt.toString().length + 1 idRight += rightInt.toString().length + 1 } } } // if left and right are lists, compare the content else if (leftIsList and rightIsList) { val listLeft = remainingLeft extractListIndicesStartingFrom 0 val listRight = remainingRight extractListIndicesStartingFrom 0 when ( remainingLeft.substring(listLeft.first + 1, listLeft.second) compareAsPacket remainingRight.substring(listRight.first + 1, listRight.second) ) { 1 -> return 1 -1 -> return -1 else -> { idLeft += listLeft.second + 2 idRight += listRight.second + 2 } } } // if one is a list and the other is not, wrap the non-list in brackets and compare the results else if (!leftIsList and rightIsList) { val leftInt = remainingLeft.extractFirstInt() val leftList = "[$leftInt]" val rightListIndices = remainingRight extractListIndicesStartingFrom 0 val rightList = remainingRight.substring(rightListIndices.first, rightListIndices.second + 1) when (leftList compareAsPacket rightList) { 1 -> return 1 -1 -> return -1 else -> { idLeft += leftInt.toString().length + 1 idRight += rightListIndices.second + 1 } } } else { val rightInt = remainingRight.extractFirstInt() val rightList = "[$rightInt]" val leftListIndices = remainingLeft extractListIndicesStartingFrom 0 val leftList = remainingLeft.substring(leftListIndices.first, leftListIndices.second + 1) when (leftList compareAsPacket rightList) { 1 -> return 1 -1 -> return -1 else -> { idRight += rightInt.toString().length + 1 idLeft += leftListIndices.second + 1 } } } } // if left is empty and right is not, return -1 if (idLeft >= this.length && idRight < other.length) return -1 // if right is empty and left is not, return 1 if (idLeft < this.length) return 1 // if both are blank, undecided return 0 } fun main() { fun part1(input: List<String>): Int = input.chunked(3) .mapIndexed { index, strings -> if (strings[0] compareAsPacket strings[1] < 1) index + 1 else 0 } .sum() // just count the number of packets that are smaller, no need for full sort fun part2(input: List<String>): Int { val dividerPackets = listOf("[[2]]", "[[6]]") val packets = (input.filterNot { it.isBlank() } + dividerPackets).toMutableList() return dividerPackets .map { packets.count { packet -> (packet compareAsPacket it) == -1 } } .map { it + 1 } .reduce(Int::times) } val testInput = readTestFileByYearAndDay(2022, 13) check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInputFileByYearAndDay(2022, 13) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
aa8da2591310beb4a0d2eef81ad2417ff0341384
4,709
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/days/Day3.kt
mir47
433,536,325
false
{"Kotlin": 31075}
package days class Day3 : Day(3) { override fun partOne(): Int { var gamma = "" var epsilon = "" for (bitIndex in 0.until(inputList[0].length)) { val counts = inputList.groupingBy { it[bitIndex] }.eachCount() gamma += if ((counts['0'] ?: 0) > (counts['1'] ?: 0)) '0' else '1' epsilon += if ((counts['0'] ?: 0) > (counts['1'] ?: 0)) '1' else '0' } return multiplyBinaryStrings(gamma, epsilon) } override fun partTwo(): Int { val o2: String = filter(inputList, bitIndex = 0, fewer = false) val co2: String = filter(inputList, bitIndex = 0, fewer = true) return multiplyBinaryStrings(o2, co2) } private fun filter(list: List<String>, bitIndex: Int, fewer: Boolean): String { return if (list.size == 1) { list.first() } else { val groups = list.groupBy( { it[bitIndex] }, { it } ) val filtered = if (fewer) { if ((groups['0']?.size ?: 0) <= (groups['1']?.size ?: 0)) groups['0'] else groups['1'] } else { if ((groups['0']?.size ?: 0) > (groups['1']?.size ?: 0)) groups['0'] else groups['1'] } filter(filtered ?: emptyList(), bitIndex+1, fewer) } } private fun multiplyBinaryStrings(a: String, b: String) = Integer.parseInt(a, 2) * Integer.parseInt(b, 2) }
0
Kotlin
0
0
686fa5388d712bfdf3c2cc9dd4bab063bac632ce
1,420
aoc-2021
Creative Commons Zero v1.0 Universal
kotlin/src/com/s13g/aoc/aoc2020/Day22.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver import java.util.* /** * --- Day 22: Crab Combat --- * https://adventofcode.com/2020/day/22 */ class Day22 : Solver { override fun solve(lines: List<String>): Result { val playersA = parse(lines) // Make copy for Part B where we have to start over. val playersB = playersA.map { LinkedList(it) } // The game is going while none of them ran out of cards. while (playersA[0].isNotEmpty() && playersA[1].isNotEmpty()) { val top = Pair(playersA[0].removeAt(0), playersA[1].removeAt(0)) if (top.first > top.second) { playersA[0].add(top.first) playersA[0].add(top.second) } else { playersA[1].add(top.second) playersA[1].add(top.first) } } val winnerA = if (playersA.isNotEmpty()) 0 else 1 val resultA = playersA[winnerA].reversed().withIndex().map { (it.index + 1) * it.value }.sum() // Part 2 val winnerB = recursiveCombat(playersB, 1) val resultB = playersB[winnerB].reversed().withIndex().map { (it.index + 1) * it.value }.sum() return Result("$resultA", "$resultB") } private fun recursiveCombat(players: List<LinkedList<Long>>, gameNo: Int): Int { val history = Array(2) { mutableSetOf<Int>() } var roundNo = 1 var roundWinner = -42 while (players[0].isNotEmpty() && players[1].isNotEmpty()) { // Player 0 wins when history repeats. if (players[0].hashCode() in history[0] || players[1].hashCode() in history[1]) return 0 history[0].add(players[0].hashCode()) history[1].add(players[1].hashCode()) // Top cards. val top = Pair(players[0].pop(), players[1].pop()) roundWinner = if (players[0].size >= top.first && players[1].size >= top.second) { // Play sub-game, recursive combat! Create copies so that our list is not changed. val subListA = LinkedList(players[0].subList(0, top.first.toInt())) val subListB = LinkedList(players[1].subList(0, top.second.toInt())) recursiveCombat(listOf(subListA, subListB), gameNo + 1) } else if (top.first > top.second) 0 else 1 // Add cards to the round winners deck in the right order (winner's first). players[roundWinner].add(if (roundWinner == 0) top.first else top.second) players[roundWinner].add(if (roundWinner == 0) top.second else top.first) roundNo++ } return roundWinner } private fun parse(lines: List<String>): List<LinkedList<Long>> { val players = mutableListOf<LinkedList<Long>>(LinkedList(), LinkedList()) var activePlayerParsing = 0 for (line in lines) { if (line.startsWith("Player 1:") || line.isBlank()) continue if (line.startsWith("Player 2:")) activePlayerParsing = 1 else players[activePlayerParsing].add(line.toLong()) } return players } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,882
euler
Apache License 2.0
src/main/kotlin/me/grison/aoc/y2016/Day07.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2016 import me.grison.aoc.* class Day07 : Day(7, 2016) { override fun title() = "Internet Protocol Version 7" private val addresses = inputList.map { it.trim().split("""\[|\]""".regex()) } private val supernet = addresses.map { it.filterIndexed { i, _ -> i % 2 == 0 }.joinToString(" ") } private val hypernet = addresses.map { it.filterIndexed { i, _ -> i % 2 == 1 }.joinToString(" ") } override fun partOne() = supernet.zip(hypernet).count { (sup, hyp) -> isAbba(sup) && !isAbba(hyp) } override fun partTwo() = supernet.zip(hypernet).count { (sup, hyp) -> isAbabab(sup, hyp) } private fun isAbba(s: String): Boolean { val (a, b) = p(s, s.substring(1)) val (c, d) = p(s.substring(2), s.substring(3)) return d.indices.map { a[it] + b[it] + c[it] + d[it] } .any { it[0] + it[1] == it[3] + it[2] && it[0] != it[1] } } private fun isAbabab(sup: String, hyp: String): Boolean { val (b, c) = p(sup.substring(1), sup.substring(2)) return c.indices.map { sup[it] + b[it] + c[it] }.any { it[0] == it[2] && it[0] != it[1] && ((it[1] + it[0] + it[1]) in hyp) } } }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
1,196
advent-of-code
Creative Commons Zero v1.0 Universal
Day6/src/Orbit.kt
gautemo
225,219,298
false
null
import java.io.File fun readLines() = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readLines() fun main(){ val spaceObjects = mapSpace(readLines()) val orbits = findNrOrbits(spaceObjects) println(orbits) val toSanta = findNrOrbitsToSanta(spaceObjects) println(toSanta) } fun findNrOrbits(spaceObjects: Map<String, SpaceObject>) = countOrbits(spaceObjects) fun findNrOrbitsToSanta(spaceObjects: Map<String, SpaceObject>): Int { val myLink = link("YOU", spaceObjects).split(",") val santaLink = link("SAN", spaceObjects).split(",") val firstCommon = myLink.first { santaLink.contains(it) } return myLink.indexOf(firstCommon) + santaLink.indexOf(firstCommon) } fun link(ob: String, objects: Map<String, SpaceObject>, soFar: String = ""): String{ return if(objects.containsKey(ob) && objects[ob]!!.orbits != null) link(objects[ob]!!.orbits!!, objects, "$soFar,${objects[ob]!!.orbits}") else soFar.trim().trim(',') } fun mapSpace(objects: List<String>): Map<String, SpaceObject>{ val spaceObjects = mutableMapOf<String, SpaceObject>() for(ob in objects){ val rel = getObjects(ob) if(!spaceObjects.containsKey(rel.first)){ spaceObjects[rel.first] = SpaceObject(null) } val smaller = SpaceObject(rel.first) spaceObjects[rel.second] = smaller } return spaceObjects } fun countOrbits(spaceObjects: Map<String, SpaceObject>): Int{ var counter = 0 for(ob in spaceObjects){ counter += countOrbitsForObject(ob.value, spaceObjects) } return counter } fun countOrbitsForObject(ob: SpaceObject?, allObjects: Map<String, SpaceObject>):Int = if(ob?.orbits == null) 0 else 1 + countOrbitsForObject(allObjects[ob.orbits], allObjects) fun getObjects(line: String): Pair<String, String>{ val names = line.split(")") return Pair(names.first(), names.last()) } data class SpaceObject(val orbits: String?)
0
Kotlin
0
0
f8ac96e7b8af13202f9233bb5a736d72261c3a3b
1,969
AdventOfCode2019
MIT License
src/day11/Day11.kt
quinlam
573,215,899
false
{"Kotlin": 31932}
package day11 import utils.Day /** * Actual answers after submitting; * part1: 111210 * part2: 15447387620 */ class Day11 : Day<Long, Map<Int, Monkey>>( testPart1Result = 10605, testPart2Result = 2713310158, ) { override fun part1Answer(input: Map<Int, Monkey>): Long { val relief = 3 val numberOfRounds = 20 return calculateMonkeyBusiness(relief, numberOfRounds, input) } override fun part2Answer(input: Map<Int, Monkey>): Long { val relief = 1 val numberOfRounds = 10000 return calculateMonkeyBusiness(relief, numberOfRounds, input) } private fun calculateMonkeyBusiness(worryLevel: Int, rounds: Int, monkeys: Map<Int, Monkey>): Long { val commonModulo = monkeys.values.fold(1) { acc, m -> acc * m.testNumber } for (i in 1..rounds) { monkeys.values.forEach { it.inspect(worryLevel, commonModulo) { index, item -> monkeys[index]?.giveItem(item) } } } return monkeys.values .map { it.inspectionCount.toLong() } .sorted() .takeLast(2) .reduce { acc, i -> acc * i } } override fun modifyInput(input: List<String>): Map<Int, Monkey> { return input .withIndex() .groupBy { it.index / 7 } .mapValues { it.value.map { indexedValue -> indexedValue.value } } .mapValues { Monkey.fromString(it.value) } } }
0
Kotlin
0
0
d304bff86dfecd0a99aed5536d4424e34973e7b1
1,580
advent-of-code-2022
Apache License 2.0
kotlin/src/main/kotlin/io/github/ocirne/aoc/year2022/Day2.kt
ocirne
327,578,931
false
{"Python": 323051, "Kotlin": 67246, "Sage": 5864, "JavaScript": 832, "Shell": 68}
package io.github.ocirne.aoc.year2022 import io.github.ocirne.aoc.AocChallenge typealias ScoringFunction = (Day2.Shape, Char) -> Pair<Day2.Shape, Day2.Score> class Day2(val lines: List<String>) : AocChallenge(2022, 2) { enum class Shape(val score: Int) { ROCK(1), PAPER(2), SCISSOR(3), } enum class Score(val score: Int) { WIN(6), DRAW(3), LOST(0) } // opponent, me, score private val result = listOf( Triple(Shape.ROCK, Shape.ROCK, Score.DRAW), Triple(Shape.ROCK, Shape.PAPER, Score.WIN), Triple(Shape.ROCK, Shape.SCISSOR, Score.LOST), Triple(Shape.PAPER, Shape.ROCK, Score.LOST), Triple(Shape.PAPER, Shape.PAPER, Score.DRAW), Triple(Shape.PAPER, Shape.SCISSOR, Score.WIN), Triple(Shape.SCISSOR, Shape.ROCK, Score.WIN), Triple(Shape.SCISSOR, Shape.PAPER, Score.LOST), Triple(Shape.SCISSOR, Shape.SCISSOR, Score.DRAW), ) private val mappingOpponent = mapOf( 'A' to Shape.ROCK, 'B' to Shape.PAPER, 'C' to Shape.SCISSOR, ) private val mapping1 = mapOf( 'X' to Shape.ROCK, 'Y' to Shape.PAPER, 'Z' to Shape.SCISSOR, ) private val mapping2 = mapOf( 'X' to Score.LOST, 'Y' to Score.DRAW, 'Z' to Score.WIN, ) private val scoringPart1: ScoringFunction = { opponentShape, me -> val myShape: Shape = mapping1[me]!! val score: Score = result.first { (o, m, _) -> o == opponentShape && m == myShape }.third Pair(myShape, score) } private val scoringPart2: ScoringFunction = { opponentShape, me -> val score: Score = mapping2[me]!! val myShape: Shape = result.first { (o, _, s) -> o == opponentShape && s == score }.second Pair(myShape, score) } private fun scoreLines(scoringFun: ScoringFunction): Int { return lines .asSequence() .filter { line -> line.isNotBlank() } .map { line -> line.trim().split(' ') } .map { p -> Pair(p[0].first(), p[1].first())} .map { (opponent, me) -> scoringFun.invoke(mappingOpponent[opponent]!!, me) } .map { (m, s) -> m.score + s.score } .sum() } override fun part1(): Int { return scoreLines(scoringPart1) } override fun part2(): Int { return scoreLines(scoringPart2) } }
0
Python
0
1
b8a06fa4911c5c3c7dff68206c85705e39373d6f
2,447
adventofcode
The Unlicense