path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/g0601_0700/s0699_falling_squares/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0699_falling_squares // #Hard #Array #Ordered_Set #Segment_Tree #2023_02_22_Time_293_ms_(100.00%)_Space_48.8_MB_(50.00%) import java.util.Collections import java.util.TreeSet class Solution { fun fallingSquares(positions: Array<IntArray>): List<Int> { // Coordinate compression using TreeSet val unique: MutableSet<Int> = TreeSet() for (square in positions) { unique.add(square[0]) unique.add(square[0] + square[1] - 1) } // converted the TreeSet to a List val sorted: List<Int> = ArrayList(unique) // Storing the max heights for compressed coordinates val heights = IntArray(sorted.size) // Our answer list val list: MutableList<Int> = ArrayList(positions.size) // Global Max var max = 0 for (square in positions) { // coordinate compression lookup val x1 = Collections.binarySearch(sorted, square[0]) val x2 = Collections.binarySearch(sorted, square[0] + square[1] - 1) // get the current max for the interval between x1 and x2 var current = 0 for (i in x1..x2) { current = current.coerceAtLeast(heights[i]) } // add the new square on the top current += square[1] // update the interval with the new value for (i in x1..x2) { heights[i] = current } // recalculate the global max max = max.coerceAtLeast(current) list.add(max) } return list } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,633
LeetCode-in-Kotlin
MIT License
src/main/kotlin/alg03sorting/S5QuickSort.kt
deemson
349,702,470
false
null
package alg03sorting import alg03indexable.Indexable import alg03indexable.swap import kotlin.random.Random object S5QuickSort : Sort { /** * This function is the core of quicksort. It ensures that an arbitrary item from the part of the array * from left to right is in place, i.e. smaller than all of the items to the left * and larger than all of the items to the right of this item. * Method partition returns an index of the item, that was put in place. */ private fun <T> partition(indexable: Indexable<T>, comparator: Comparator<T>, left: Int, right: Int): Int { var leftMarker = left var rightMarker = right + 1 while (true) { // find item on the left to swap while (comparator.compare(indexable[++leftMarker], indexable[left]) < 0) { if (leftMarker == right) { break } } // find item on the right to swap while (true) { if (comparator.compare(indexable[left], indexable[--rightMarker]) >= 0) { break } } // check if markers cross if (leftMarker >= rightMarker) { break } // swap indexable.swap(leftMarker, rightMarker) } indexable.swap(left, rightMarker) // return index of item now known to be in place return rightMarker } private fun <T> sort(indexable: Indexable<T>, comparator: Comparator<T>, lo: Int, hi: Int) { if (lo >= hi) { return } val itemInPlaceIndex = partition(indexable, comparator, lo, hi) sort(indexable, comparator, lo, itemInPlaceIndex - 1) sort(indexable, comparator, itemInPlaceIndex + 1, hi) } private var random: Random init { val seed = System.currentTimeMillis() this.random = Random(seed) } private fun uniform(n: Int): Int { if (n <= 0) throw IllegalArgumentException("Parameter n must be positive") return random.nextInt(n) } private fun <T> shuffle(indexable: Indexable<T>) { for (index in indexable.indices) { val swapIndex = index + uniform(indexable.size - index) // between index and array.size - index indexable.swap(index, swapIndex) } } override fun <T> sort(indexable: Indexable<T>, comparator: Comparator<T>) { // required for guaranteed performance this.shuffle(indexable) sort(indexable, comparator, lo = 0, hi = indexable.size - 1) } }
0
Kotlin
0
0
a4bba4dfa962302114065032facefdf98585cfd7
2,631
algorithms
MIT License
src/test/kotlin/amb/aoc2020/day4.kt
andreasmuellerbluemlein
318,221,589
false
null
package amb.aoc2020 import org.junit.jupiter.api.Test class Day4 : TestBase() { private fun getInput(): List<String> { val passportCandidates = emptyList<String>().toMutableList() var input = "" getTestData("input4").forEach { if (it.isEmpty()) { passportCandidates.add(input) input = "" } else input += " $it" } return passportCandidates } @Test fun task1() { var numberOfValidInputs = 0 val requiredFields = setOf("byr", "iyr:", "eyr:", "hgt:", "hcl:", "ecl:", "pid:") getInput().forEach { candidate -> if (requiredFields.all { candidate.contains(it) }) { numberOfValidInputs++ logger.info { "valid: $candidate" } logger.info { "\\n" } } } logger.info { "found $numberOfValidInputs valid passports" } } @Test fun task2() { val requiredValidations = mapOf( "byr" to ::isYearOfBirthValid, "iyr" to ::isYearOfIssueValid, "eyr" to ::isYearOfExpirationValid, "hgt" to ::isHeightValid, "hcl" to ::isHairColorValid, "ecl" to ::isEyeColorValid, "pid" to ::isPidValid ) var countOfValidPassports = 0 getInput().forEach {input-> logger.info{"Input: $input"} val validationResults = requiredValidations.map { val regex = """${it.key}:([#a-z0-9]*)""".toRegex() val match = regex.find(input) match != null && it.value(match.value.substring(4)) } val allValid = validationResults.reduce{acc,i -> acc&&i} if (allValid) countOfValidPassports++ } logger.info { "found $countOfValidPassports valid passports" } } private fun isYearOfBirthValid(input: String): Boolean { return input.toIntOrNull() ?: 0 in 1921..2001 } private fun isYearOfIssueValid(input: String): Boolean { return input.toIntOrNull() ?: 0 in 2010..2020 } private fun isYearOfExpirationValid(input: String): Boolean { return input.toIntOrNull() ?: 0 in 2020..2030 } private fun isHeightValid(input:String): Boolean{ val cm = if(input.contains("cm")) true else { if (input.contains("in")) false else return false } val number = input.replace(if(cm) "cm" else "in","").toIntOrNull() return if(cm) number?:0 in 150..193 else number?:0 in 59..76 } private fun isHairColorValid(input: String): Boolean{ val validChars = "0123456789abcdef" return input.first() == '#' && input.substring(1).all { validChars.contains(it) } } private fun isEyeColorValid(input: String): Boolean { val validValues = setOf("amb","blu","brn","gry","grn","hzl","oth") return validValues.contains(input) } private fun isPidValid(input: String) : Boolean{ val digits = "0123456789" return input.length == 9 && input.all { digits.contains(it) } } }
1
Kotlin
0
0
dad1fa57c2b11bf05a51e5fa183775206cf055cf
3,190
aoc2020
MIT License
src/main/kotlin/com/groundsfam/advent/y2023/d09/Day09.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2023.d09 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines fun extrapolate(history: List<Long>, backward: Boolean): Long { if (history.all { it == 0L }) { return 0 } val diffs = (1 until history.size).map { i -> history[i] - history[i - 1] } val nextDiff = extrapolate(diffs, backward) return if (backward) { history.first() - nextDiff } else { history.last() + nextDiff } } fun main() = timed { val readings = (DATAPATH / "2023/day09.txt").useLines { lines -> lines .map { line -> line.split(" ") .map(String::toLong) } .toList() } readings .sumOf { history -> extrapolate(history, backward = false) } .also { println("Part one: $it") } readings .sumOf { history -> extrapolate(history, backward = true) } .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,052
advent-of-code
MIT License
src/main/java/com/marcinmoskala/math/CombinationsExt.kt
MarcinMoskala
87,302,297
false
null
@file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math /** * In mathematics, a combination is a way of selecting items from a collection, such that (unlike permutations) the * order of selection does not matter. * * For set {1, 2, 3}, 2 elements combinations are {1, 2}, {2, 3}, {1, 3}. * All possible combinations is called 'powerset' and can be found as an * extension function for set under this name */ fun <T> Set<T>.combinations(combinationSize: Int): Set<Set<T>> = when { combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize") combinationSize == 0 -> setOf(setOf()) combinationSize >= size -> setOf(toSet()) else -> powerset() .filter { it.size == combinationSize } .toSet() } fun <T> Set<T>.combinationsNumber(combinationSize: Int): Long = when { combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize") combinationSize >= size || combinationSize == 0 -> 1 else -> size.factorial() / (combinationSize.factorial() * (size - combinationSize).factorial()) } fun <T> Set<T>.combinationsWithRepetitions(combinationSize: Int): Set<Map<T, Int>> = when { combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize") combinationSize == 0 -> setOf(mapOf()) else -> combinationsWithRepetitions(combinationSize - 1) .flatMap { subset -> this.map { subset + (it to (subset.getOrElse(it) { 0 } + 1)) } } .toSet() } fun <T> Set<T>.combinationsWithRepetitionsNumber(combinationSize: Int): Long = when { combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize") combinationSize == 0 -> 1 else -> (size + combinationSize - 1).factorial() / (combinationSize.factorial() * (size - 1).factorial()) }
4
Kotlin
17
178
17a7329af042c5de232051027ec1155011d57da8
1,944
KotlinDiscreteMathToolkit
Apache License 2.0
aoc-2016/src/main/kotlin/nl/jstege/adventofcode/aoc2016/days/Day01.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2016.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.Direction import nl.jstege.adventofcode.aoccommon.utils.Point import nl.jstege.adventofcode.aoccommon.utils.extensions.scan import kotlin.reflect.KProperty1 /** * * @author <NAME> */ class Day01 : Day(title = "No Time for a Taxicab") { override fun first(input: Sequence<String>): Any { var dir = Direction.NORTH return input .first() .parse() .fold(Point.ZERO_ZERO) { p, (turn, steps) -> dir = dir.let(turn.directionMod) p.moveDirection(dir, steps) } .manhattan(Point.ZERO_ZERO) } override fun second(input: Sequence<String>): Any { var dir = Direction.NORTH var coordinate = Point.ZERO_ZERO val visited = mutableSetOf(coordinate) input.first().parse().forEach { (turn, steps) -> dir = dir.let(turn.directionMod) val first = coordinate.moveDirection(dir) val last = coordinate.moveDirection(dir, steps) val xs = if (last.x < first.x) first.x downTo last.x else first.x..last.x val ys = if (last.y < first.y) first.y downTo last.y else first.y..last.y Point.of(xs, ys).forEach { coordinate = it if (coordinate in visited) return coordinate.manhattan(Point.ZERO_ZERO) visited += coordinate } } throw IllegalStateException("No answer found.") } private fun String.parse(): List<Instruction> = this.split(", ").map { Instruction(Turn.parse(it.substring(0, 1)), it.substring(1).toInt()) } private data class Instruction(val turn: Turn, val steps: Int) private enum class Turn(val directionMod: KProperty1<Direction, Direction>) { LEFT(Direction::left), RIGHT(Direction::right); companion object { fun parse(v: String) = when (v) { "L" -> LEFT else -> RIGHT } } } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,131
AdventOfCode
MIT License
src/main/kotlin/ru/timakden/aoc/year2016/Day12.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2016 import ru.timakden.aoc.util.isNumber import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import ru.timakden.aoc.year2016.Day12.Command.* import ru.timakden.aoc.year2016.Day12.Command.Companion.toCommand /** * [Day 12: Leonardo's Monorail](https://adventofcode.com/2016/day/12). */ object Day12 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2016/Day12") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Int { val registers = mutableMapOf("a" to 0, "b" to 0, "c" to 0, "d" to 0) var currentInstruction = 0 while (currentInstruction < input.size) { val instruction = input[currentInstruction].split(" ") when (instruction.first().toCommand()) { COPY -> { val value = with(instruction[1]) { if (this.isNumber()) this.toInt() else registers[this] ?: 0 } registers[instruction[2]] = value currentInstruction++ } JUMP -> { with(instruction[1]) { if ((this.isNumber() && this.toInt() != 0) || registers[this] != 0) currentInstruction += instruction[2].toInt() else currentInstruction++ } } INCREMENT -> { with(instruction[1]) { registers[this] = registers[this]?.plus(1) ?: 0 } currentInstruction++ } DECREMENT -> { with(instruction[1]) { registers[this] = registers[this]?.minus(1) ?: 0 } currentInstruction++ } } } return registers["a"] ?: 0 } fun part2(input: List<String>): Int { val registers = mutableMapOf("a" to 0, "b" to 0, "c" to 1, "d" to 0) var currentInstruction = 0 while (currentInstruction < input.size) { val instruction = input[currentInstruction].split(" ") when (instruction.first().toCommand()) { COPY -> { val value = with(instruction[1]) { if (this.isNumber()) this.toInt() else registers[this] ?: 0 } registers[instruction[2]] = value currentInstruction++ } JUMP -> { with(instruction[1]) { if ((this.isNumber() && this.toInt() != 0) || registers[this] != 0) currentInstruction += instruction[2].toInt() else currentInstruction++ } } INCREMENT -> { with(instruction[1]) { registers[this] = registers[this]?.plus(1) ?: 0 } currentInstruction++ } DECREMENT -> { with(instruction[1]) { registers[this] = registers[this]?.minus(1) ?: 0 } currentInstruction++ } } } return registers["a"] ?: 0 } private enum class Command { COPY, JUMP, INCREMENT, DECREMENT; companion object { fun String.toCommand(): Command { return when (this) { "cpy" -> COPY "jnz" -> JUMP "inc" -> INCREMENT "dec" -> DECREMENT else -> throw IllegalArgumentException("Unknown command \"$this\"") } } } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
4,141
advent-of-code
MIT License
app/src/main/java/es/upm/bienestaremocional/data/questionnaire/daily/DailyScoredQuestionnaire.kt
Emotional-Wellbeing
531,973,820
false
{"Kotlin": 848055}
package es.upm.bienestaremocional.data.questionnaire.daily import es.upm.bienestaremocional.data.Measure import es.upm.bienestaremocional.data.questionnaire.Level import es.upm.bienestaremocional.data.questionnaire.Questionnaire import es.upm.bienestaremocional.data.questionnaire.QuestionnaireScored import es.upm.bienestaremocional.data.questionnaire.ScoreLevel /** * Information of the available daily questionnaires of the app with score * @param measure Measure which is implemented by the questionnaire * @param numberOfQuestions Number of the questions in the questionnaire * @param answerRange Inclusive range of the valid responses on a answer * @param levels List of the score levels of the questionnaire * @param minScore Minimum possible score for the questionnaire * @param maxScore Maximum possible score for the questionnaire */ enum class DailyScoredQuestionnaire( val measure: Measure, override val numberOfQuestions: Int, override val answerRange: IntRange, override val levels: List<ScoreLevel>, override val minScore: Int, override val maxScore: Int, ) : Questionnaire, QuestionnaireScored { Stress( measure = Measure.Stress, numberOfQuestions = 4, answerRange = 0..10, levels = listOf( ScoreLevel(0, 13, Level.Low), ScoreLevel(14, 27, Level.Moderate), ScoreLevel(28, 40, Level.High) ), minScore = 0, maxScore = 40 ), Depression( measure = Measure.Depression, numberOfQuestions = 3, answerRange = 0..10, levels = listOf( ScoreLevel(0, 10, Level.Low), ScoreLevel(11, 20, Level.Moderate), ScoreLevel(21, 30, Level.High) ), minScore = 0, maxScore = 30 ), Loneliness( measure = Measure.Loneliness, numberOfQuestions = 4, answerRange = 0..10, levels = listOf( ScoreLevel(0, 13, Level.Low), ScoreLevel(14, 27, Level.Moderate), ScoreLevel(28, 40, Level.High) ), minScore = 0, maxScore = 40 ); companion object { /** * Obtain a [DailyScoredQuestionnaire] from a certain [Measure] * @param measure to decode * @return [DailyScoredQuestionnaire] related if is any */ fun fromMeasure(measure: Measure): DailyScoredQuestionnaire? { return when (measure) { Measure.Stress -> Stress Measure.Depression -> Depression Measure.Loneliness -> Loneliness Measure.Suicide -> null Measure.Symptoms -> null } } } }
0
Kotlin
0
2
55c24943d57d1c0cb91ddce569f27d7e5cd6ed8d
2,720
App
Apache License 2.0
src/main/kotlin/exercises/quicksort/QuicksortQB.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package exercises.quicksort //Example that uses a custom quicksort to sort NFL QBs and passing yards. data class Quarterback(val name: String, val passingYards: Int) fun main() { // Define a list of Quarterback objects with their names and passing yards val quarterbacks = listOf( Quarterback("<NAME>", 5814), Quarterback("<NAME>", 4740), Quarterback("<NAME>", 4544), Quarterback("<NAME>", 4335), Quarterback("<NAME>", 4208) ) // Convert the list to a mutable list val mutableQuarterbacks = quarterbacks.toMutableList() // Print the quarterbacks list before sorting println("Before sorting Quarterbacks:") mutableQuarterbacks.forEach { println("${it.name}: ${it.passingYards} yards") } // Sort the mutableQuarterbacks list using the quickSort function quickSort(mutableQuarterbacks, 0, mutableQuarterbacks.size - 1) { qb1, qb2 -> qb1.passingYards - qb2.passingYards } // Print the quarterbacks list after sorting println("\nAfter sorting Quarterbacks:") mutableQuarterbacks.forEach { println("${it.name}: ${it.passingYards} yards") } } // QuickSort implementation fun <T> quickSort(list: MutableList<T>, low: Int, high: Int, comparator: (T, T) -> Int) { // Base case: If there are at least two elements if (low < high) { // Partition the list and get the pivot index val pivotIndex = partition(list, low, high, comparator) // Recursively sort the left partition quickSort(list, low, pivotIndex - 1, comparator) // Recursively sort the right partition quickSort(list, pivotIndex + 1, high, comparator) } } // Partition function for QuickSort fun <T> partition(list: MutableList<T>, low: Int, high: Int, comparator: (T, T) -> Int): Int { // Select the last element as the pivot val pivot = list[high] var i = low - 1 // Iterate through the subarray for (j in low until high) { // If the current element is smaller than the pivot if (comparator(list[j], pivot) < 0) { i++ // Swap list[i] and list[j] list.swap(i, j) } } // Swap list[i+1] and list[high] (placing the pivot in its correct position) list.swap(i + 1, high) return i + 1 } // Extension function to swap elements in a MutableList fun <T> MutableList<T>.swap(index1: Int, index2: Int) { val temp = this[index1] this[index1] = this[index2] this[index2] = temp } //Space and time complexity is O(log n)
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
2,577
dsa-kotlin
MIT License
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day13.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2022 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part13A : PartSolution() { lateinit var pairs: List<Pair<List<Any>, List<Any>>> override fun parseInput(text: String) { val lines = text.trim().split("\n") val pairs: MutableList<Pair<List<Any>, List<Any>>> = mutableListOf() for (i in lines.indices step 3) { val (_, left) = parseList(lines[i]) val (_, right) = parseList(lines[i + 1]) pairs.add(Pair(left, right)) } this.pairs = pairs } private fun parseList(text: String): Pair<Int, List<Any>> { val list = mutableListOf<Any>() var i = 1 while (i < text.length) { val token = getNextToken(text, i) if (token[0] == '[') { val (offset, values) = parseList(text.substring(i)) i += offset list.add(values) if (text[i] == ',') { i += 1 } } else if (text[i] == ']') { return Pair(i + 1, list) } else { list.add(token.dropLast(1).toInt()) i += token.length if (token.endsWith("]")) { return Pair(i, list) } } } return Pair(i, list) } private fun getNextToken(text: String, offset: Int = 0): String { var end = offset while (end < text.length) { val c = text[end] if (c == '[' || c == ']' || c == ',') { return text.substring(offset, end + 1) } end += 1 } return "" } override fun compute(): Int { var indexSum = 0 for ((i, pair) in pairs.withIndex()) { val (result, _) = checkOrder(pair.first, pair.second, i + 1) if (result) { indexSum += i + 1 } } return indexSum } @Suppress("UNCHECKED_CAST") fun checkOrder(left: Any, right: Any, i: Int, depth: Int = 0): Pair<Boolean, Boolean> { if (left is Int) { if (right is Int) { return checkOrder(left, right, i, depth) } return checkOrder(left, right as List<Any>, i, depth) } if (right is Int) { return checkOrder(left as List<Any>, right, i, depth) } return checkOrder(left as List<Any>, right as List<Any>, i, depth) } private fun checkOrder(left: Int, right: Int, i: Int, depth: Int = 0): Pair<Boolean, Boolean> { return checkOrder(listOf(left), listOf(right), i, depth) } private fun checkOrder(left: Int, right: List<Any>, i: Int, depth: Int = 0): Pair<Boolean, Boolean> { return checkOrder(listOf(left), right, i, depth) } private fun checkOrder(left: List<Any>, right: Int, i: Int, depth: Int = 0): Pair<Boolean, Boolean> { return checkOrder(left, listOf(right), i, depth) } private fun checkOrder(left: List<Any>, right: List<Any>, i: Int, depth: Int = 0): Pair<Boolean, Boolean> { var l = 0 var r = 0 while (true) { if (l >= left.size) { if (r < right.size) { return Pair(true, true) } return Pair(true, false) } if (r >= right.size) { return Pair(false, true) } val currentLeft = left[l++] val currentRight = right[r++] if (currentLeft is List<*> || currentRight is List<*>) { val (ret, imm) = checkOrder(currentLeft, currentRight, i, depth + 1) if (!ret) { return Pair(false, true) } if (imm) { return Pair(true, true) } } else { if ((currentLeft as Int) < (currentRight as Int)) { return Pair(true, true) } if (currentLeft > currentRight) { return Pair(false, true) } } } } override fun getExampleAnswer(): Int { return 13 } } class Part13B : Part13A() { override fun compute(): Int { val packets = pairs.flatMap { it.toList() } val sPackets = mutableListOf<Any>(2, 6) for (packet in packets) { var i = 0 while (i < sPackets.size) { val (result, _) = checkOrder(packet, sPackets[i], 0) if (result) { break } i += 1 } sPackets.add(i, packet) } val index1 = sPackets.indexOf(2) + 1 val index2 = sPackets.indexOf(6) + 1 return index1 * index2 } override fun getExampleAnswer(): Int { return 140 } } fun main() { Day(2022, 13, Part13A(), Part13B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
5,043
advent-of-code-kotlin
MIT License
src/main/kotlin/dev/patbeagan/days/Day01.kt
patbeagan1
576,401,502
false
{"Kotlin": 57404}
package dev.patbeagan.days /** * [Day 1](https://adventofcode.com/2022/day/1) */ class Day01 : AdventDay<Int> { /** * Prints out the calorie value * of the elf that is holding the most calories. */ override fun part1(input: String): Int = parseForElves(input) .maxBy { it.totalCalories } .totalCalories /** * Prints out the calorie value * of the top 3 elves that are holding the most calories. */ override fun part2(input: String): Int = parseForElves(input) .sortedByDescending { it.totalCalories } .take(3) .sumOf { it.totalCalories } /** * Converts the incoming text into a list of elves */ fun parseForElves(input: String): List<Elf> = input .trim() .split("\n\n") .map { s -> Elf(s.split("\n").map { it.toInt() }) } data class Elf( val calorieItems: List<Int>, ) { val totalCalories get() = calorieItems.sum() } }
0
Kotlin
0
0
4e25b38226bcd0dbd9c2ea18553c876bf2ec1722
1,019
AOC-2022-in-Kotlin
Apache License 2.0
src/main/kotlin/leetcode/kotlin/tree/285. Inorder Successor in BST.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package leetcode.kotlin.tree // solution not verified, as env. not available private fun inorderSuccessor(root: TreeNode?, p: TreeNode): TreeNode? { var seen = false var ans: TreeNode? = null fun dfs(root: TreeNode?) { if (root != null && ans == null) { dfs(root.left) if (seen) ans = root if (!seen && root == p) seen = true dfs(root.right) } } dfs(root) return ans } /** * We can think it like a binary search on sorted array, * where we need to find just next bigger element for the given element. * Every time root is considered as mid, and input space is pruned keeping next bigger within input space. * * 1. If given element if bigger or equal to current root, then next bigger will definitely be in right side of it, * whether its present or not, we don't care , just return it, null means it do not exist in tree. * * 2. If given element if small than root, then next bigger can be in left or may be current root is the next bigger. * If backtracking gives non-null node then we found next bigger in left subtree otherwise, current root is next bigger, return it. * */ private fun inorderSuccessor2(root: TreeNode?, p: TreeNode): TreeNode? { root?.let { if (p.`val` >= root.`val`) { return inorderSuccessor2(root.right, p) } else { var node = inorderSuccessor2(root.left, p) return node ?: root } } return null } // iterative version of "inorderSuccessor2" private fun inorderSuccessor3(root: TreeNode?, p: TreeNode): TreeNode { var res: TreeNode? = null var root = root // make root mutable while (root != null) { if (root.`val` > p.`val`) { res = root root = root.left } else root = root.right } return res!! }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,859
leetcode-kotlin
Apache License 2.0
2022/src/main/kotlin/com/github/akowal/aoc/Day10.kt
akowal
573,170,341
false
{"Kotlin": 36572}
package com.github.akowal.aoc import com.github.akowal.aoc.Day10.Cmd.Add import com.github.akowal.aoc.Day10.Cmd.Noop import kotlin.math.abs class Day10 { private val cmds = inputFile("day10").readLines().map { line -> when (line) { "noop" -> Noop else -> Add(line.substringAfter(' ').toInt()) } } fun solvePart1(): Int { var x = 1 var cycle = 0 var signals = 0 for (cmd in cmds) { repeat(cmd.duration) { cycle++ if ((cycle - 20) % 40 == 0) { signals += cycle * x } } x += cmd.delta } return signals } fun solvePart2(): String { val out = StringBuilder() var x = 1 var cycle = 0 for (cmd in cmds) { repeat(cmd.duration) { val pos = cycle % 40 cycle++ if (abs(x - pos) <= 1) { out.append('#') } else { out.append('.') } if (cycle % 40 == 0) { out.append('\n') } } x += cmd.delta } return out.toString() } private sealed interface Cmd { val duration: Int val delta: Int object Noop : Cmd { override val duration = 1 override val delta = 0 } data class Add(override val delta: Int) : Cmd { override val duration = 2 } } } fun main() { val solution = Day10() println(solution.solvePart1()) println(solution.solvePart2()) }
0
Kotlin
0
0
02e52625c1c8bd00f8251eb9427828fb5c439fb5
1,708
advent-of-kode
Creative Commons Zero v1.0 Universal
year2023/day06/part2/src/main/kotlin/com/curtislb/adventofcode/year2023/day06/part2/Year2023Day06Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- As the race is about to start, you realize the piece of paper with race times and record distances you got earlier actually just has very bad kerning. There's really only one race - ignore the spaces between the numbers on each line. So, the example from before: ``` Time: 7 15 30 Distance: 9 40 200 ``` ...now instead means this: ``` Time: 71530 Distance: 940200 ``` Now, you have to figure out how many ways there are to win this single race. In this example, the race lasts for 71530 milliseconds and the record distance you need to beat is 940200 millimeters. You could hold the button anywhere from 14 to 71516 milliseconds and beat the record, a total of 71503 ways! How many ways can you beat the record in this one much longer race? */ package com.curtislb.adventofcode.year2023.day06.part2 import com.curtislb.adventofcode.common.parse.parseInts import com.curtislb.adventofcode.year2023.day06.boat.BoatRace import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2023, day 6, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long { val (timeLine, distanceLine) = inputPath.toFile().readLines() val time = timeLine.joinIntsToLong() val distance = distanceLine.joinIntsToLong() val race = BoatRace(time, distance) return race.countWaysToWin() } /** * Returns the [Long] integer value given by concatenating all decimal integers in the string. */ private fun String.joinIntsToLong(): Long = parseInts().joinToString(separator = "").toLong() fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
1,696
AdventOfCode
MIT License
year2022/src/cz/veleto/aoc/year2022/Day21.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay class Day21(config: Config) : AocDay(config) { companion object { private const val RootMonkey = "root" private const val HumnMonkey = "humn" } override fun part1(): String { val monkeyYells = parseMonkeys().toMutableMap() return yell(monkeyYells, RootMonkey, skipHumn = false)!!.toString() } override fun part2(): String { val monkeyYells = parseMonkeys().toMutableMap() yell(monkeyYells, RootMonkey, skipHumn = true) val (number, monkeyCoveringHumn) = splitMonkeyToNumberAndMath(monkeyYells, RootMonkey) return digHumnOutOfMonkeys(monkeyYells, monkeyCoveringHumn, number).toString() } private fun parseMonkeys(): Map<String, MonkeyYell> = input.map { line -> val name = line.substring(0..3) val number = line.substring(6..line.lastIndex).toLongOrNull() val yell = if (number == null) { MonkeyYell.Math( monkey1 = line.substring(6..9), monkey2 = line.substring(13..16), operation = line[11], ) } else { MonkeyYell.Number(number) } name to yell }.toMap() private fun yell(monkeyYells: MutableMap<String, MonkeyYell>, yellingMonkey: String, skipHumn: Boolean): Long? { if (skipHumn && yellingMonkey == HumnMonkey) return null return when (val yell = monkeyYells[yellingMonkey]) { is MonkeyYell.Math -> { val evaluatedMonkey1 = yell(monkeyYells, yell.monkey1, skipHumn) val evaluatedMonkey2 = yell(monkeyYells, yell.monkey2, skipHumn) if (evaluatedMonkey1 != null && evaluatedMonkey2 != null) { when (yell.operation) { '+' -> evaluatedMonkey1 + evaluatedMonkey2 '-' -> evaluatedMonkey1 - evaluatedMonkey2 '*' -> evaluatedMonkey1 * evaluatedMonkey2 '/' -> evaluatedMonkey1 / evaluatedMonkey2 else -> error("unknown yell ${yell.operation} for monkey $yellingMonkey") }.also { monkeyYells[yellingMonkey] = MonkeyYell.Number(it) } } else { null } } is MonkeyYell.Number -> yell.number null -> error("unknown yell for monkey $yellingMonkey") } } private fun splitMonkeyToNumberAndMath( monkeyYells: MutableMap<String, MonkeyYell>, yellingMonkey: String, ): Triple<Long, String, Boolean> { val monkey = monkeyYells[yellingMonkey] as MonkeyYell.Math val side1 = monkeyYells[monkey.monkey1]!! val side2 = monkeyYells[monkey.monkey2]!! return when { monkey.monkey1 == HumnMonkey || side1 is MonkeyYell.Math -> Triple((side2 as MonkeyYell.Number).number, monkey.monkey1, false) side1 is MonkeyYell.Number -> Triple(side1.number, monkey.monkey2, true) else -> error("Can't split monkey $yellingMonkey") } } private fun digHumnOutOfMonkeys( monkeyYells: MutableMap<String, MonkeyYell>, monkeyCoveringHumn: String, number: Long, ): Long { if (monkeyCoveringHumn == HumnMonkey) return number val monkey = monkeyYells[monkeyCoveringHumn] as MonkeyYell.Math val (yellNumber, newCoveringMonkey, isNumberOnLeft) = splitMonkeyToNumberAndMath(monkeyYells, monkeyCoveringHumn) val newNumber = when (monkey.operation) { '+' -> number - yellNumber '-' -> if (isNumberOnLeft) yellNumber - number else number + yellNumber '*' -> number / yellNumber '/' -> if (isNumberOnLeft) number / yellNumber else number * yellNumber else -> error("unknown yell") } return digHumnOutOfMonkeys(monkeyYells, newCoveringMonkey, newNumber) } sealed interface MonkeyYell { data class Number(val number: Long) : MonkeyYell data class Math(val monkey1: String, val monkey2: String, val operation: Char) : MonkeyYell } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
4,187
advent-of-pavel
Apache License 2.0
src/main/kotlin/g1501_1600/s1547_minimum_cost_to_cut_a_stick/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1501_1600.s1547_minimum_cost_to_cut_a_stick // #Hard #Array #Dynamic_Programming #2023_06_12_Time_187_ms_(92.00%)_Space_37.5_MB_(95.00%) class Solution { fun minCost(n: Int, cuts: IntArray): Int { cuts.sort() val m = cuts.size val dp = Array(m + 1) { IntArray(m + 1) } for (i in 1..m) { for (j in 0..m - i) { val k = j + i var min = Int.MAX_VALUE for (p in j until k) { min = Math.min(min, dp[j][p] + dp[p + 1][k]) } val len = (if (k == m) n else cuts[k]) - if (j == 0) 0 else cuts[j - 1] dp[j][k] = min + len } } return dp[0][m] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
741
LeetCode-in-Kotlin
MIT License
src/main/kotlin/days/Day13.kt
nuudles
316,314,995
false
null
package days import kotlin.math.ceil class Day13 : Day(13) { override fun partOne(): Any { val target = inputList.first().toFloat() return inputList .last() .split(",") .filter { it != "x" } .map { it.toInt() } .minByOrNull { multiplier -> ceil(target / multiplier.toFloat()) * target - target } ?.let { (it * (ceil(target / it.toFloat()) * it - target)).toInt() } ?: Unit } override fun partTwo(): Any = inputList .last() .split(",") .withIndex() .filter { it.value != "x" } .map { IndexedValue(it.index, it.value.toLong()) } .let { list -> var ts = 1L var stepCount = 0 var stepper = 1L while (true) { println(ts) list .map { it.value to ((ts + it.index) % it.value == 0L) } .filter { it.second } .let { matches -> if (matches.count() == list.count()) { return ts } else if (matches.count() > stepCount) { stepper = matches.fold(1L) { product, entry -> product * entry.first } stepCount = matches.count() } } ts += stepper } } /* // Brute Force .let { list -> var ts = 100000000000000L while (true) { if (list.sumBy { ((ts + it.index) % it.value).toInt() } == 0) { return@let ts } ts++ } } */ }
0
Kotlin
0
0
5ac4aac0b6c1e79392701b588b07f57079af4b03
2,024
advent-of-code-2020
Creative Commons Zero v1.0 Universal
2020/day20/day20.kt
flwyd
426,866,266
false
{"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398}
/* * Copyright 2021 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package day20 import kotlin.math.sqrt import kotlin.time.ExperimentalTime import kotlin.time.TimeSource import kotlin.time.measureTimedValue /* Input: paragraphs with Tile: 123 headings and square grids of . # points, with # meaning true. Tiles can be joined side-by-side after arbitrary rotation and flip operations. */ // first value is Y axis (rows), second value is X axis (columns) typealias Point = Pair<Int, Int> operator fun Point.plus(other: Point) = Point(first + other.first, second + other.second) infix fun Point.until(other: Point) = (first until other.first).flatMap { y -> (second until other.second).map { x -> y to x } } fun toEdge(bools: Iterable<Boolean>) = bools.map { if (it) '#' else '.' }.joinToString("") enum class Side(val index: Int) { NORTH(0) { override val opposite get() = SOUTH override fun fromPoint(start: Point): Point = start.first - 1 to start.second }, EAST(1) { override val opposite get() = WEST override fun fromPoint(start: Point): Point = start.first to start.second + 1 }, SOUTH(2) { override val opposite get() = NORTH override fun fromPoint(start: Point) = start.first + 1 to start.second }, WEST(3) { override val opposite get() = EAST override fun fromPoint(start: Point) = start.first to start.second - 1 }; abstract val opposite: Side abstract fun fromPoint(start: Point): Point } data class PixelPattern(val points: List<Point>) { val origin = checkNotNull(points.map(Point::first).minOrNull()) to checkNotNull( points.map(Point::second).minOrNull() ) val maxCorner = checkNotNull(points.map(Point::first).maxOrNull()) to checkNotNull( points.map(Point::second).maxOrNull() ) fun shifted(offset: Point) = PixelPattern(points.map { it + offset }) companion object { fun parse(asciiArt: String): PixelPattern = PixelPattern( asciiArt.split("\n").withIndex().flatMap { (row, line) -> line.withIndex().filter { it.value == '#' }.map { row to it.index } } ) } } data class Tile(val id: Int, val grid: List<List<Boolean>>) { init { check(grid.size == grid[0].size) } val size = grid.size val edges = listOf( toEdge(grid.first()), toEdge(grid.map { it.last() }), toEdge(grid.last()), toEdge(grid.map { it.first() }), ) fun directionEdges() = Side.values().map { it to edges[it.index] } fun directionTo(other: Tile) = Side.values() .firstOrNull { side -> edges[side.index] == other.edges[side.opposite.index] } private fun flipVertical() = Tile(id, grid.reversed()) private fun flipHorizontal() = Tile(id, grid.map(List<Boolean>::reversed)) private fun rotateClockwise(): Tile { val lines = arrayOfNulls<BooleanArray>(grid[0].size) for (i in grid.indices) { lines[i] = BooleanArray(grid[0].size) { grid[it][i] } } return Tile(id, lines.map { it!!.toList() }.toList()) } private fun rotations(): List<Tile> { val rotate1 = rotateClockwise() val rotate2 = rotate1.rotateClockwise() val rotate3 = rotate2.rotateClockwise() return listOf(rotate1, rotate2, rotate3) } fun variants(): Set<Tile> { val rotations = rotations() val vertical = flipVertical() val horizontal = flipHorizontal() val diagonal = vertical.flipHorizontal() return ( rotations + vertical + vertical.rotations() + horizontal + horizontal.rotations() + diagonal + diagonal.rotations() ).toSet() } private fun matches(pattern: PixelPattern): Boolean { if (pattern.origin.first < 0 || pattern.origin.second < 0 || pattern.maxCorner.first >= size || pattern.maxCorner.second >= size ) { return false } return pattern.points.all { grid[it.first][it.second] } } fun findMatches(pattern: PixelPattern) = grid.indices.flatMap { row -> grid.indices.map { col -> row to col } .filter { matches(pattern.shifted(it)) } } fun gridString() = grid.joinToString("\n") { line -> line.map { if (it) '#' else '.' }.joinToString("") } companion object { fun parse(paragraph: String): Tile { val lines = paragraph.split("\n") val id = lines[0].removePrefix("Tile ").removeSuffix(":").toInt() val grid = lines.drop(1).map { line -> line.toCharArray().map { when (it) { '.' -> false '#' -> true else -> error("Unexpected character $it") } } } return Tile(id, grid) } } } class TileGrid(val size: Int) { private val cells = (0 until size).map { arrayOfNulls<Tile>(size) }.toTypedArray() val allPoints = (0 to 0) until (size - 1 to size - 1) operator fun get(point: Point): Tile? = cells[point.first][point.second] operator fun set(point: Point, tile: Tile?) { cells[point.first][point.second] = tile } operator fun contains(point: Point) = point.first in 0 until size && point.second in 0 until size fun isSet(point: Point) = this[point] != null fun isUsed(tileId: Int) = allPoints.any { this[it]?.id == tileId } fun validPlacement(point: Point, tile: Tile, directions: Collection<Side>): Boolean { if (point !in this) { return false } for (dir in directions) { dir.fromPoint(point).let { neighborPoint -> if (neighborPoint !in this) { return false } this[neighborPoint]?.let { neighbor -> if (tile.directionTo(neighbor) != dir) { return false } } } } return true } fun copy(): TileGrid { val result = TileGrid(size) for (i in 0 until size) { for (j in 0 until size) { result[i to j] = this[i to j] } } return result } fun toStitchedTile(): Tile { check(allPoints.all { isSet(it) }) val smallTileSize = cells[0][0]!!.size return Tile( 0, (0 until size).flatMap { gridRow -> (1 until smallTileSize - 1).map { tileRow -> (0 until size).flatMap { gridCol -> cells[gridRow][gridCol]!!.grid[tileRow].subList(1, smallTileSize - 1) } } } ) } override fun toString() = cells.joinToString("\n") { row -> row.map { it?.id }.joinToString("\t") } } /* Output: product of the ID of the four corners of the joined grid. */ object Part1 { fun solve(input: Sequence<String>): String { val originalTiles = input.toParagraphs().map { Tile.parse(it) }.toList() val originalById = originalTiles.map { it.id to it }.toMap() val withVariantsById = originalById.mapValues { it.value.variants() + it.value } val edgeIndex = mutableMapOf<String, MutableList<Tile>>() for (tile in withVariantsById.values.flatten()) { for (edge in tile.edges) { edgeIndex.getOrPut(edge, { mutableListOf() }).add(tile) } } var product = 1L for ((id, variants) in withVariantsById) { val matches = variants.flatMap(Tile::edges).toSet().flatMap { edgeIndex.getValue(it) }.map(Tile::id) .filter { it != id }.toSet() if (matches.size == 2) { // it's a corner product *= id } } return product.toString() } } /* Match a sea monster pattern to # positions. Output: number of # not covered by sea monster. */ object Part2 { fun solve(input: Sequence<String>): String { val seaMonsterAsciiArt = """ # # ## ## ### # # # # # # """ val seaMonster = PixelPattern.parse(seaMonsterAsciiArt) val originalTiles = input.toParagraphs().map { Tile.parse(it) }.toList() val originalById = originalTiles.map { it.id to it }.toMap() val withVariantsById = originalById.mapValues { it.value.variants() + it.value } val edgeIndex = mutableMapOf<String, MutableSet<Tile>>() for (tile in withVariantsById.values.flatten()) { for (edge in tile.edges) { edgeIndex.getOrPut(edge, { mutableSetOf() }).add(tile) } } val allMatches = mutableMapOf<Int, Set<Tile>>() val expectedDirections = mutableMapOf<Tile, Set<Side>>() val corners = mutableSetOf<Int>() for ((id, variants) in withVariantsById) { for (v in variants) { expectedDirections[v] = v.directionEdges() .filter { edgeIndex[it.second]!!.any { t -> t.id != v.id } } .map { it.first }.toSet() } allMatches[id] = variants.flatMap(Tile::edges).toSet().flatMap { edgeIndex.getValue(it) } .filter { it.id != id }.toSet() if (allMatches.getValue(id).map(Tile::id).toSet().size == 2) { // it's a corner corners.add(id) } } val gridSize = sqrt(originalTiles.size.toDouble()).toInt() fun recurse( grid: TileGrid, queue: Set<Point>, edgeExpected: Map<Point, Set<String>> ): TileGrid? { if (queue.isEmpty()) { for (point in grid.allPoints) { if (!grid.isSet(point)) { return null } return grid } } val myQueue = queue.mapTo(ArrayDeque()) { it } val point = myQueue.removeFirst() for (edge in edgeExpected.getValue(point)) { for (tile in edgeIndex.getValue(edge)) { if (grid.isUsed(tile.id)) { continue } if (grid.validPlacement(point, tile, expectedDirections.getValue(tile))) { // can add to the grid val myGrid = grid.copy() myGrid[point] = tile val q = myQueue.toMutableSet() val expected = edgeExpected.toMutableMap() for ((dir, e) in tile.directionEdges()) { val neighbor = dir.fromPoint(point) if (neighbor in myGrid) { expected[neighbor] = expected.getOrPut(neighbor, ::setOf) + e if (!myGrid.isSet(neighbor)) { q.add(neighbor) } } } recurse(myGrid, q, expected)?.let { return it } } } } return null } val goodGrid = corners.asSequence().flatMap { cornerId -> withVariantsById.getValue(cornerId).asSequence() .filter { expectedDirections.getValue(it) == setOf(Side.EAST, Side.SOUTH) }.map { tile -> recurse( TileGrid(gridSize), setOf(0 to 0), mapOf(0 to 0 to setOf(tile.edges[Side.EAST.index], tile.edges[Side.SOUTH.index])) ) } }.filterNotNull().first() // println("Found solution:") // println(goodGrid) val stitchedTile = goodGrid.toStitchedTile() // println(stitchedTile.gridString()) // println("Sea monsters look like") // println(seaMonsterAsciiArt) for (orientation in listOf(stitchedTile) + stitchedTile.variants()) { val offsets = orientation.findMatches(seaMonster) if (offsets.isNotEmpty()) { val seaMonsterPoints = offsets.map { seaMonster.shifted(it) }.flatMap(PixelPattern::points).toSet() return ((0 to 0) until (stitchedTile.size to stitchedTile.size)) .filterNot(seaMonsterPoints::contains) .filter { orientation.grid[it.first][it.second] }.count().toString() } } error("No sea monsters found in $goodGrid rotated") } } @ExperimentalTime @Suppress("UNUSED_PARAMETER") fun main(args: Array<String>) { val lines = generateSequence(::readLine).toList() print("part1: ") TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } print("part2: ") TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } } fun Sequence<String>.toParagraphs(): Sequence<String> { var paragraph = mutableListOf<String>() return sequence { forEach { line -> if (line.isNotBlank()) { paragraph.add(line) } else { if (paragraph.isNotEmpty()) { yield(paragraph.joinToString("\n")) } paragraph = mutableListOf() } } if (paragraph.isNotEmpty()) { yield(paragraph.joinToString("\n")) } } }
0
Julia
1
5
f2d6dbb67d41f8f2898dbbc6a98477d05473888f
12,367
adventofcode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindPivotIndex.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 /** * 724. Find Pivot Index * @see <a href="https://leetcode.com/problems/find-pivot-index/?envType=study-plan&id=level-1">Source</a> */ fun interface FindPivotIndex { fun pivotIndex(nums: IntArray): Int } class FindPivotIndexPrefixSum : FindPivotIndex { override fun pivotIndex(nums: IntArray): Int { var sum = 0 var leftsum = 0 for (x in nums) sum += x for (i in nums.indices) { if (leftsum == sum - leftsum - nums[i]) return i leftsum += nums[i] } return -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,195
kotlab
Apache License 2.0
subprojects/common/graph/src/test/kotlin/com/avito/grapth/ShortestPathTest.kt
avito-tech
230,265,582
false
{"Kotlin": 3574228, "Java": 67252, "Shell": 27656, "Dockerfile": 12799, "Makefile": 7970}
package com.avito.grapth import com.avito.graph.Operation import com.avito.graph.ShortestPath import com.avito.graph.SimpleOperation import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.Test class ShortestPathTest { @Test fun `zero operations - empty path`() { val path = shortestPath(emptySet()) assertThat(path.operations).isEmpty() } @Test fun `one operation - path with it`() { val operation = SimpleOperation(id = "id", duration = 1.0) val path = shortestPath(setOf(operation)) assertThat(path.operations).containsExactly(operation) } @Test fun `consecutive operations - all of them`() { val a1 = SimpleOperation(id = "a1", duration = 1.0) val a2 = SimpleOperation(id = "a2", duration = 1.0, predecessors = setOf("a1")) val a3 = SimpleOperation(id = "a3", duration = 1.0, predecessors = setOf("a2")) val path = shortestPath(setOf(a3, a2, a1)) assertThat(path.operations).containsExactly(a1, a2, a3) } @Test fun `independent chains - the shortest chain`() { val a1 = SimpleOperation(id = "a1", duration = 2.0) val a2 = SimpleOperation(id = "a2", duration = 3.0, predecessors = setOf("a1")) val b1 = SimpleOperation(id = "b1", duration = 3.0) val b2 = SimpleOperation(id = "b2", duration = 3.0, predecessors = setOf("b1")) val path = shortestPath(setOf(a1, a2, b1, b2)) assertThat(path.operations).containsExactly(a1, a2) } @Test fun `alternative parallel routes - the shortest route`() { val start = SimpleOperation(id = "start", duration = 1.0) val intermediate1 = SimpleOperation(id = "intermediate1", duration = 1.0, predecessors = setOf("start")) val intermediate2 = SimpleOperation(id = "intermediate2", duration = 2.0, predecessors = setOf("start")) val intermediate3 = SimpleOperation(id = "intermediate3", duration = 3.0, predecessors = setOf("start")) val end = SimpleOperation( id = "end", duration = 1.0, predecessors = setOf("intermediate1", "intermediate2", "intermediate3") ) val path = shortestPath(setOf(start, intermediate1, intermediate2, intermediate3, end)) assertThat(path.operations).containsExactly(start, intermediate1, end) } private fun shortestPath(operations: Set<Operation>) = ShortestPath(operations).find() }
10
Kotlin
48
390
9d60abdd26fc779dd57aa4f1ad51658b6a245d1e
2,486
avito-android
MIT License
string-similarity/src/commonMain/kotlin/com/aallam/similarity/SorensenDice.kt
aallam
597,692,521
false
null
package com.aallam.similarity import com.aallam.similarity.internal.Shingle /** * Sorensen-Dice coefficient, aka Sørensen index, Dice's coefficient or Czekanowski's binary (non-quantitative) index. * * The strings are first converted to boolean sets of k-shingles (sequences of k characters), then the similarity is * computed as 2 * |A inter B| / (|A| + |B|). * * Attention: Sorensen-Dice distance (and similarity) does not satisfy triangle inequality. * * [Sørensen–Dice coefficient](https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient) * * @param k length of k-shingles */ public class SorensenDice(public val k: Int = 3) { /** * Similarity is computed as 2 * |A ∩ B| / (|A| + |B|). * * @param first The first string to compare. * @param second The second string to compare. */ public fun similarity(first: String, second: String): Double { if (first == second) return 1.0 val profile1 = Shingle.profile(first, k) val profile2 = Shingle.profile(second, k) val intersect = profile1.keys.intersect(profile2.keys) return (2.0 * intersect.size) / (profile1.size + profile2.size) } /** * Returns 1 - similarity. * * @param first The first string to compare. * @param second The second string to compare. */ public fun distance(first: String, second: String): Double { return 1.0 - similarity(first, second) } }
0
Kotlin
0
1
40cd4eb7543b776c283147e05d12bb840202b6f7
1,470
string-similarity-kotlin
MIT License
src/Day02.kt
gnuphobia
578,967,785
false
{"Kotlin": 17559}
import kotlin.Exception as KotlinException fun main() { fun part1(input: List<String>): Int { val rps = RockPaperScissors() rps.playGame(input) return rps.gameScore } fun part2(input: List<String>): Int { val rps = RockPaperScissors() rps.playGameV2(input) return rps.gameScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") part1(input).println() part2(input).println() } class RockPaperScissors() { private val lose : Int = 0 private val draw : Int = 3 private val win : Int = 6 var gameScore = 0 fun playGame(gameRounds : List<String>) { for(round in gameRounds) { gameScore += playRound(round) } } fun playGameV2(gameRounds : List<String>) { for (round in gameRounds) { gameScore += playRoundV2(round) } } fun playRound(round : String) : Int { val (opponent, player) = round.split(' ') var score = 0 val opponentMove = RpsScore.ROCK.playType(opponent) val playerMove = RpsScore.ROCK.playType(player) score = playResult(opponentMove, playerMove) + playerMove.score return score } fun playResult(opponentPlayed : RpsScore, playerPlayed : RpsScore) : Int { if (opponentPlayed == playerPlayed) return draw if (opponentPlayed == RpsScore.ROCK && playerPlayed == RpsScore.SCISSORS) return lose if (opponentPlayed == RpsScore.ROCK && playerPlayed == RpsScore.PAPER) return win if (opponentPlayed == RpsScore.PAPER && playerPlayed == RpsScore.ROCK) return lose if (opponentPlayed == RpsScore.PAPER && playerPlayed == RpsScore.SCISSORS) return win if (opponentPlayed == RpsScore.SCISSORS && playerPlayed == RpsScore.PAPER) return lose return win } fun playRoundV2(round: String) : Int { val (opponent, outcome) = round.split(' ') var score = 0 val opponentMove = RpsScore.ROCK.playType(opponent) val playerMove = chooseMove(opponentMove, outComeType(outcome)) score = playResult(opponentMove, playerMove) + playerMove.score return score } fun outComeType(outcome: String) : Int { if (outcome == "X") return lose if (outcome == "Y") return draw return win } fun chooseMove(opponentPlayed: RpsScore, playerNeeds: Int) : RpsScore { if (playerNeeds == draw) { return opponentPlayed } if (playerNeeds == win) { if (opponentPlayed == RpsScore.ROCK) return RpsScore.PAPER if (opponentPlayed == RpsScore.PAPER) return RpsScore.SCISSORS return RpsScore.ROCK } if (opponentPlayed == RpsScore.ROCK) return RpsScore.SCISSORS if (opponentPlayed == RpsScore.PAPER) return RpsScore.ROCK return RpsScore.PAPER } } enum class RpsScore(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); fun playType(play : String) : RpsScore { if (play == "X" || play == "A") return ROCK if (play == "Y" || play == "B") return PAPER if (play == "Z" || play == "C") return SCISSORS return ROCK } }
0
Kotlin
0
0
a1b348ec33f85642534c46af8c4a69e7b78234ab
3,394
aoc2022kt
Apache License 2.0
src/main/java/challenges/cracking_coding_interview/moderate/q3_intersection/Tester.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.moderate.q3_intersection object Tester { fun equalish(a: Double, b: Double): Boolean { return Math.abs(a - b) < .001 } fun checkIfPointOnLineSegments(start: Point, middle: Point, end: Point): Boolean { if (equalish(start.x, middle.x) && equalish(start.y, middle.y)) { return true } if (equalish(middle.x, end.x) && equalish(middle.y, end.y)) { return true } if (start.x == end.x) { // Vertical return if (equalish(start.x, middle.x)) { Question.isBetween(start, middle, end) } else false } val line = Line(start, end) val x = middle.x val y = line.slope * x + line.yintercept return equalish(y, middle.y) } fun getPoints(size: Int): ArrayList<Point> { val points = ArrayList<Point>() var x1 = size * -1 while (x1 < size) { var y1 = size * -1 + 1 while (y1 < size - 1) { points.add(Point(x1.toDouble(), y1.toDouble())) y1 += 3 } x1 += 3 } return points } fun runTest(start1: Point, end1: Point, start2: Point, end2: Point): Boolean { val intersection = Question.intersection(start1, end1, start2, end2) var validate1 = true var validate2 = true if (intersection == null) { println("No intersection.") } else { validate1 = checkIfPointOnLineSegments(start1, intersection, end1) validate2 = checkIfPointOnLineSegments(start2, intersection, end2) if (validate1 && validate2) { println("has intersection") } if (!validate1 || !validate2) { println("ERROR -- $validate1, $validate2") } } println(" Start1: " + start1.x + ", " + start1.y) println(" End1: " + end1.x + ", " + end1.y) println(" Start2: " + start2.x + ", " + start2.y) println(" End2: " + end2.x + ", " + end2.y) if (intersection != null) { println(" Intersection: " + intersection.x + ", " + intersection.y) } return !(!validate1 || !validate2) } @JvmStatic fun main(args: Array<String>) { val points = getPoints(10) for (start1 in points) { for (end1 in points) { for (start2 in points) { for (end2 in points) { val success = runTest(start1, end1, start2, end2) if (!success) { return } } } } } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,780
CodingChallenges
Apache License 2.0
src/chapter2/section2/ex16_NaturalMergesort.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter2.section2 import chapter2.ArrayInitialState import chapter2.getDoubleArray import chapter2.section1.checkAscOrder import chapter2.sortMethodsCompare /** * 自然的归并排序 * 编写一个自底向上的归并排序,当需要将两个子数组排序时,能够利用数组中已经有序的部分 * 首先找到一个有序的子数组(移动指针直到当前元素比上一个元素小为止),然后找出另一个并将它们归并 * 根据数组大小和数组中递增子数组的最大长度分析算法的运行时间 */ fun <T : Comparable<T>> ex16_NaturalMergesort(array: Array<T>) { if (array.size <= 1) return val extraArray = array.copyOf() var start = 0 var mid = 0 var end = 0 fun findSortedSubArray(array: Array<T>, start: Int): Int { for (i in start until array.size - 1) { if (array[i + 1] < array[i]) { return i } } return array.size - 1 } while (true) { mid = findSortedSubArray(array, start) if (mid == array.size - 1) { if (start == 0) { break } else { start = 0 continue } } end = findSortedSubArray(array, mid + 1) merge(array, extraArray, start, mid, end) start = if (end == array.size - 1) { 0 } else { end + 1 } } } fun main() { val array = getDoubleArray(1000) ex16_NaturalMergesort(array) val result = array.checkAscOrder() println("result = $result") val sortMethods: Array<Pair<String, (Array<Double>) -> Unit>> = arrayOf( "Top Down Merge Sort" to ::topDownMergeSort, "ex16" to ::ex16_NaturalMergesort ) sortMethodsCompare(sortMethods, 10, 100_0000, ArrayInitialState.RANDOM) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,870
Algorithms-4th-Edition-in-Kotlin
MIT License
src/test/kotlin/io/noobymatze/aoc/y2022/Day8.kt
noobymatze
572,677,383
false
{"Kotlin": 90710}
package io.noobymatze.aoc.y2022 import io.noobymatze.aoc.Aoc import kotlin.test.Test class Day8 { data class Pos(val row: Int, val col: Int) @Test fun test() { val data = Aoc.getInput(8).lines() .flatMapIndexed { row, line -> line.mapIndexed { col, c -> (Pos(row, col)) to c.digitToInt() }} .toMap() val maxRow = data.keys.maxBy { it.row }.row val maxCol = data.keys.maxBy { it.col }.col val visible = data.filter { (pos, value) -> val left = (0 until pos.col).all { data[pos.copy(col = it)]!! < value } val right = (pos.col + 1 .. maxCol).all { data[pos.copy(col = it)]!! < value } val bottom = (pos.row + 1.. maxRow).all { data[pos.copy(row = it)]!! < value } val top = (0 until pos.row).all { data[pos.copy(row = it)]!! < value } left || right || bottom || top } println(visible.size) } @Test fun test2() { val data = Aoc.getInput(8).lines() .flatMapIndexed { row, line -> line.mapIndexed { col, c -> (Pos(row, col)) to c.digitToInt() }} .toMap() val maxRow = data.keys.maxBy { it.row }.row val maxCol = data.keys.maxBy { it.col }.col val visible = data.filterNot { it.key.row == 0 || it.key.col == 0 || it.key.row == maxRow || it.key.col == maxRow }.map { (pos, value) -> val left = (pos.col - 1 downTo 0).find { data[pos.copy(col = it)]!! >= value }?.let { pos.col - it } ?: pos.col val right = (pos.col + 1 .. maxCol).find { data[pos.copy(col = it)]!! >= value }?.let { it - pos.col } ?: (maxCol - pos.col) val bottom = (pos.row + 1.. maxRow).find { data[pos.copy(row = it)]!! >= value }?.let { it - pos.row } ?: (maxRow - pos.row) val top = (pos.row - 1 downTo 0).find { data[pos.copy(row = it)]!! >= value }?.let { pos.row - it } ?: pos.row left * right * bottom * top }.maxBy { it } println(visible) } }
0
Kotlin
0
0
da4b9d894acf04eb653dafb81a5ed3802a305901
2,130
aoc
MIT License
app/src/main/java/aquodev/textopalindromo/PalindromoFuns.kt
W3SS
121,782,931
false
null
package aquodev.textopalindromo /** * Devuelve un resultado booleano indicando si la palabra introducida * por parámetro es un palíndromo (palabra que se escribe igual en ambas * direcciones). * * /!\ El principal método (el que se debe usar con un sólo parámetro) depende de este. * * @param palabra Palabra la cual se comprobará si es palíndroma o no * @param lenPalabra Cantidad de caracteres que contiene la palabra * @return true si la palabra es palíndroma, false si no lo es. */ private fun esPalindromo(palabra: String, lenPalabra: Int): Boolean { if (lenPalabra < 2) { return true } else if (palabra[0] == palabra[lenPalabra - 1]) { return esPalindromo(palabra.substring(1, lenPalabra - 1), lenPalabra - 2) // Sabiendo que la primera y última letra coinciden, comprobamos si // la subcadena entre ambas letras sigue siendo palíndroma. } return false } /** * Devuelve un resultado booleano indicando si la palabra introducida * por parámetro es un palíndromo (palabra que se escribe igual en ambas * direcciones). * * /!\ Palabras de longitud 1 o textos vacíos no se considerarán palíndromas. * * @param texto Palabra la cual se comprobará si es palíndroma o no * @return true si la palabra es palíndroma, false si no lo es. */ fun esPalindromo(texto: String): Boolean { val palabra = texto.toLowerCase().trim() val lenTexto = palabra.length return if (lenTexto < 2 || palabra[0] != palabra[lenTexto - 1]) { false // Si es menor de 2 caracteres o si el primer y último caracter no coinciden } else { esPalindromo(palabra.substring(1, lenTexto - 1), lenTexto - 2) // Si el primer y último caracter coinciden y es mayor o igual que dos caracteres } // Toda esta condición se puede simplificar por un solo 'return', pero por legibilidad se deja tal y como está }
0
Kotlin
0
0
290b9f6d09b5d13c0e2d07a2e07d6234869d16d2
1,918
Palindromo-Kotlin-Android
MIT License
src/main/kotlin/dev/shtanko/algorithms/learn/Array.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.learn import dev.shtanko.algorithms.extensions.second fun secondStraightForward(arr: IntArray): Int { if (arr.size < 2) return -1 var first = Int.MAX_VALUE var second = Int.MAX_VALUE for (item in arr) { if (item < first) { second = first first = item } else if (item < second && item != first) { second = item } } return second } fun secondMinSort(arr: IntArray): Int { if (arr.size < 2) return -1 arr.sort() return arr.second() } fun uniqueWholeNumbersSet(arr: IntArray): IntArray { if (arr.isEmpty()) return intArrayOf() if (arr.size < 2) return arr return arr.toSet().toIntArray() } fun mergeTwoSortedPlus(arr1: IntArray, arr2: IntArray): IntArray { if (arr1.isEmpty() && arr2.isEmpty()) return intArrayOf() return arr1.plus(arr2) } fun mergeTwoSortedSF(arr1: IntArray, arr2: IntArray): IntArray { if (arr1.isEmpty() && arr2.isEmpty()) return intArrayOf() val mergedArraySize = arr1.size + arr2.size val mergedArray = IntArray(mergedArraySize) var pos = 0 for (value in arr1) { mergedArray[pos] = value pos++ } for (value in arr2) { mergedArray[pos] = value pos++ } return mergedArray }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,912
kotlab
Apache License 2.0
kotlin/app/src/main/kotlin/coverick/aoc/day13/DistressSignal.kt
RyTheTurtle
574,328,652
false
{"Kotlin": 82616}
package coverick.aoc.day13 import readResourceFile import splitOn var INPUT_FILE = "distressSignal-input.txt" enum class DatumType { NUMBER, LIST} data class Datum(val type: DatumType, val value:List<Int>) data class Packet(val data: ArrayList<Datum>) class DatumComparator { companion object : Comparator<Datum> { override fun compare(a:Datum, b:Datum): Int { var result = 0 // since datums store numbers as a list of a single value, this // logic can apply for both list-list and number-list comparisons and number-number comparisons var idx = 0 while(idx < a.value.size && idx < b.value.size){ result = a.value.get(idx).compareTo(b.value.get(0)) idx++ } // if list were unequal size, smaller list should have been on left side if(idx < a.value.size){ result = -1 }else if(idx < b.value.size){ result = 1 } return result } } } fun parsePacket(packetStr: String): Packet{ var idx = 0 val result = Packet(ArrayList<Datum>()) // define a few helpers for parsing fun isEndOfPacket(): Boolean { return idx >= packetStr.length } fun eat(c:Char){ if(packetStr.get(idx) == c){ idx++ } else { throw RuntimeException("Expected ${c} but found ${packetStr.get(idx)}") } } fun peek():Char { return packetStr.get(idx) } fun advance(){ idx++ } fun parseIntDatum(): Datum{ val buf:StringBuilder = StringBuilder() buf.append(packetStr.get(idx)) idx++ while(!isEndOfPacket() && packetStr.get(idx).isDigit()){ buf.append(packetStr.get(idx)) advance() } return Datum(DatumType.NUMBER, arrayListOf(buf.toString().toInt())) } fun parseListDatum():Datum{ eat('[') val intList = ArrayList<Datum>() while(!isEndOfPacket() && packetStr.get(idx) != ']'){ intList.add(parseIntDatum()) if(peek() == ','){ eat(',') } else { break } } return Datum(DatumType.LIST, intList.map{it.value.get(0)}) } eat('[') while(!isEndOfPacket()){ when(packetStr.get(idx)){ '[' -> { result.data.add(parseListDatum()) eat(']') } ']' -> return result ',' -> eat(',') else -> { result.data.add(parseIntDatum()) eat(',') } } } return result } fun part1(): Int { /** * Approach * split input on empty lines * * need to build a packet tokenizer and parser * * check how many packets are ordered properly * * when comparing left and right numbers, left should be smaller * * when comparing two lists, compare their indices for the left being smaller * than the right. if no determination of improper ordering is found, if left runs out * of items first, it's in the right order, if right * * when comparing list and int, convert int to list of one value */ val packetGroups = readResourceFile(INPUT_FILE).splitOn { it.isEmpty()} return 0 } fun part2(): Int{ return 0 } fun solution() { println("Distress Signal Part 1 solution: ${part1()}") println("Distress Signal Part 2 solution: ${part2()}") }
0
Kotlin
0
0
35a8021fdfb700ce926fcf7958bea45ee530e359
3,601
adventofcode2022
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions32.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import com.qiaoyuang.algorithm.round0.BinaryTreeNode import com.qiaoyuang.algorithm.round0.Queue fun test32() { testCase1().run { println("Print top to bottom: ") printlnBinaryTreeFromTop2Bottom() println("Print line by line: ") printlnBinaryTreeFromTop2BottomByLine() } } /** * Questions32-1: Print a binary tree from top to bottom */ private fun <T> BinaryTreeNode<T>.printlnBinaryTreeFromTop2Bottom() { val line = Queue<BinaryTreeNode<T>>() line.enqueue(this) while (!line.isEmpty) { val node = line.dequeue() print("${node.value}, ") node.left?.let { line.enqueue(it) } node.right?.let { line.enqueue(it) } } println() } /** * Questions32-2: Print a binary tree from top to bottom by line */ private fun <T> BinaryTreeNode<T>.printlnBinaryTreeFromTop2BottomByLine() { val line = Queue<BinaryTreeNode<T>>() line.enqueue(this) var thisLineNodesCount = 1 var nextLineNodesCount = 0 while (!line.isEmpty) { if (thisLineNodesCount == 0) { thisLineNodesCount = nextLineNodesCount nextLineNodesCount = 0 } val node = line.dequeue() print("${node.value}, ") if (--thisLineNodesCount == 0) println() node.left?.let { line.enqueue(it) nextLineNodesCount++ } node.right?.let { line.enqueue(it) nextLineNodesCount++ } } } private fun testCase1(): BinaryTreeNode<Int> { val node0 = BinaryTreeNode(0) val node1 = BinaryTreeNode(1, BinaryTreeNode(3), BinaryTreeNode(4, BinaryTreeNode(7), BinaryTreeNode(8))) val node2 = BinaryTreeNode(2, BinaryTreeNode(5), BinaryTreeNode(6)) node0.left = node1 node0.right = node2 return node0 }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,872
Algorithm
Apache License 2.0
Chapter07/BubbleSort.kt
PacktPublishing
125,371,513
false
null
import java.util.* fun <E: Comparable<E>> Array<E>.sort() { val len = size for (i in 0 until (len - 1)) { for (j in 0 until (len - i - 1)) { if (this[j].compareTo(this[j + 1]) > 0) { val temp = this[j] this[j] = this[j + 1] this[j + 1] = temp } } } } fun <E: Comparable<E>> Array<E>.descending() { val len = size for (i in 0 until (len - 1)) { for (j in 0 until (len - i - 1)) { if (this[j].compareTo(this[j + 1]) < 0) { val temp = this[j] this[j] = this[j + 1] this[j + 1] = temp } } } } fun <E: Comparable<E>> MutableList<E>.sort() { val len = size for (i in 0 until (len - 1)) { for (j in 0 until (len - i - 1)) { if (this[j].compareTo(this[j + 1]) > 0) { val temp = this[j] this[j] = this[j + 1] this[j + 1] = temp } } } } fun <E: Comparable<E>> List<E>.sort(): List<E> { val len = size val resultList = toMutableList() for (i in 0 until (len - 1)) { for (j in 0 until (len - i - 1)) { if (resultList[j].compareTo(resultList[j + 1]) > 0) { val temp = resultList[j] resultList[j] = resultList[j + 1] resultList[j + 1] = temp } } } return resultList } fun main(args: Array<String>) { val nums = arrayOf(2, 12, 89, 23, 76, 43, 12) nums.sort() println(Arrays.toString(nums)) nums.descending() println(Arrays.toString(nums)) val languages = mutableListOf("Kotlin", "Java", "C#", "R", "Python", "Scala", "Groovy", "C", "C++") languages.sort() println(languages) val doubles = listOf(1.2, 2.6, 10.2, 3.5, 200.4, 34.54, 12.3) val sortedDoubles = doubles.sort() println("Doubles Before Sort - $doubles") println("Doubles After Sort - $sortedDoubles") }
0
Kotlin
62
162
f125372a286a3bf4f0248db109a7427f6bc643a7
2,011
Hands-On-Data-Structures-and-Algorithms-with-Kotlin
MIT License
src/Day03.kt
laricchia
434,141,174
false
{"Kotlin": 38143}
import org.jetbrains.kotlinx.multik.api.mk import org.jetbrains.kotlinx.multik.api.toNDArray import org.jetbrains.kotlinx.multik.api.zeros import org.jetbrains.kotlinx.multik.ndarray.data.get import org.jetbrains.kotlinx.multik.ndarray.data.set import org.jetbrains.kotlinx.multik.ndarray.operations.count import org.jetbrains.kotlinx.multik.ndarray.operations.joinToString fun firstPart03(lists : List<List<Int>>) { val data = lists.toNDArray().transpose() // I assume I have a 2d array val rowNumber = data.shape[0] val colNumber = data.shape[1] val gammaRateBits = mk.zeros<Int>(rowNumber) val epsilonRateBits = gammaRateBits.copy() for (i in 0 until rowNumber) { if (data[i].count { it == 1 } > (colNumber / 2)) { gammaRateBits[i] = 1 epsilonRateBits[i] = 0 } else { gammaRateBits[i] = 0 epsilonRateBits[i] = 1 } } val gammaRate = Integer.parseInt(gammaRateBits.joinToString(separator = ""), 2) val epsilonRate = Integer.parseInt(epsilonRateBits.joinToString(separator = ""), 2) println(gammaRate * epsilonRate) } fun secondPart03(lists : List<List<Int>>) { var oxGenRatingPossibleValues = lists var co2ScrubRatingPossibleValues = lists var i = 0 while (oxGenRatingPossibleValues.size != 1) { val toConsider = oxGenRatingPossibleValues.toNDArray().transpose() val colNumber = toConsider.shape[1] val oneCount = toConsider[i].count { it == 1 } val shouldKeepOne = toConsider[i].count { it == 1 } >= (colNumber - oneCount) oxGenRatingPossibleValues = (if (shouldKeepOne) oxGenRatingPossibleValues.filter { it[i] == 1 } else oxGenRatingPossibleValues.filter { it[i] == 0 }) i++ } i = 0 while (co2ScrubRatingPossibleValues.size != 1) { val toConsider = co2ScrubRatingPossibleValues.toNDArray().transpose() val colNumber = toConsider.shape[1] val zeroCount = toConsider[i].count { it == 0 } val shouldKeepZero = zeroCount <= (colNumber - zeroCount) co2ScrubRatingPossibleValues = (if (shouldKeepZero) co2ScrubRatingPossibleValues.filter { it[i] == 0 } else co2ScrubRatingPossibleValues.filter { it[i] == 1 }) i++ } val oxygenRating = Integer.parseInt(oxGenRatingPossibleValues.first().joinToString(separator = ""), 2) val co2Rating = Integer.parseInt(co2ScrubRatingPossibleValues.first().joinToString(separator = ""), 2) println(oxygenRating * co2Rating) } fun main() { val input : List<String> = readInput("Day03") val lists = input.filter { it.isNotEmpty() }.map { it.split("").filter { it.isNotEmpty() }.map { it.toInt() } } firstPart03(lists) secondPart03(lists) }
0
Kotlin
0
0
7041d15fafa7256628df5c52fea2a137bdc60727
2,761
Advent_of_Code_2021_Kotlin
Apache License 2.0
resolutions/leet-code/problem-2/src/main/kotlin/br/com/gmfonseca/resolutions/leetcode/problem2/solutions/FasterSolution.kt
gmfonseca
420,417,142
false
{"Kotlin": 12932}
package br.com.gmfonseca.resolutions.leetcode.problem2.solutions import br.com.gmfonseca.resolutions.leetcode.problem2.AddTwoNumbersSolution import br.com.gmfonseca.resolutions.leetcode.problem2.model.ListNode class FasterSolution : AddTwoNumbersSolution { override fun addTwoNumbers(firstNode: ListNode, secondNode: ListNode): ListNode { val result = mutableListOf<Int>() var extra = 0 var firstAux: ListNode? = firstNode var secondAux: ListNode? = secondNode do { var sum: Int when { firstAux == null -> { sum = secondAux!!.`val` + extra secondAux = secondAux.next } secondAux == null -> { sum = firstAux.`val` + extra firstAux = firstAux.next } else -> { sum = secondAux.`val` + firstAux.`val` + extra firstAux = firstAux.next secondAux = secondAux.next } } if (sum >= 10) { extra = 1 sum -= 10 } else { extra = 0 } result.add(sum) } while (firstAux != null || secondAux != null) if (extra != 0) { result.add(extra) } return node(result) } private fun node(items: List<Int>): ListNode { val node = ListNode(items[0]) var aux = node for (i in 1..items.lastIndex) { aux = aux.next(items[i]) } return node } private fun ListNode.next(value: Int) = ListNode(value).also { next = it } }
0
Kotlin
0
0
7580bfa7b30ac7d435ffaf465dfaf5be983cdc07
1,722
problems
MIT License
kotlin/697.Degree of an Array(数组的度).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>Given a non-empty array of non-negative integers <code>nums</code>, the <b>degree</b> of this array is defined as the maximum frequency of any one of its elements.</p> <p>Your task is to find the smallest possible length of a (contiguous) subarray of <code>nums</code>, that has the same degree as <code>nums</code>.</p> <p><b>Example 1:</b><br /> <pre> <b>Input:</b> [1, 2, 2, 3, 1] <b>Output:</b> 2 <b>Explanation:</b> The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2. </pre> </p> <p><b>Example 2:</b><br /> <pre> <b>Input:</b> [1,2,2,3,1,4,2] <b>Output:</b> 6 </pre> </p> <p><b>Note:</b> <li><code>nums.length</code> will be between 1 and 50,000.</li> <li><code>nums[i]</code> will be an integer between 0 and 49,999.</li> </p><p>给定一个非空且只包含非负数的整数数组&nbsp;<code>nums</code>, 数组的度的定义是指数组里任一元素出现频数的最大值。</p> <p>你的任务是找到与&nbsp;<code>nums</code>&nbsp;拥有相同大小的度的最短连续子数组,返回其长度。</p> <p><strong>示例 1:</strong></p> <pre> <strong>输入:</strong> [1, 2, 2, 3, 1] <strong>输出:</strong> 2 <strong>解释:</strong> 输入数组的度是2,因为元素1和2的出现频数最大,均为2. 连续子数组里面拥有相同度的有如下所示: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] 最短连续子数组[2, 2]的长度为2,所以返回2. </pre> <p><strong>示例 2:</strong></p> <pre> <strong>输入:</strong> [1,2,2,3,1,4,2] <strong>输出:</strong> 6 </pre> <p><strong>注意:</strong></p> <ul> <li><code>nums.length</code>&nbsp;在1到50,000区间范围内。</li> <li><code>nums[i]</code>&nbsp;是一个在0到49,999范围内的整数。</li> </ul> <p>给定一个非空且只包含非负数的整数数组&nbsp;<code>nums</code>, 数组的度的定义是指数组里任一元素出现频数的最大值。</p> <p>你的任务是找到与&nbsp;<code>nums</code>&nbsp;拥有相同大小的度的最短连续子数组,返回其长度。</p> <p><strong>示例 1:</strong></p> <pre> <strong>输入:</strong> [1, 2, 2, 3, 1] <strong>输出:</strong> 2 <strong>解释:</strong> 输入数组的度是2,因为元素1和2的出现频数最大,均为2. 连续子数组里面拥有相同度的有如下所示: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] 最短连续子数组[2, 2]的长度为2,所以返回2. </pre> <p><strong>示例 2:</strong></p> <pre> <strong>输入:</strong> [1,2,2,3,1,4,2] <strong>输出:</strong> 6 </pre> <p><strong>注意:</strong></p> <ul> <li><code>nums.length</code>&nbsp;在1到50,000区间范围内。</li> <li><code>nums[i]</code>&nbsp;是一个在0到49,999范围内的整数。</li> </ul> **/ class Solution { fun findShortestSubArray(nums: IntArray): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
3,044
leetcode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindPermutation.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack /** * @see <a href="https://leetcode.com/problems/find-permutation/">Source</a> */ fun interface FindPermutation { operator fun invoke(s: String): IntArray } /** * Approach #1 Using Stack * Time complexity : O(n). * Space complexity : O(n). */ class FindPermutationStack : FindPermutation { override operator fun invoke(s: String): IntArray { val res = IntArray(s.length + 1) val stack: Stack<Int> = Stack() var j = 0 for (i in 1..s.length) { if (s[i - 1] == 'I') { stack.push(i) while (stack.isNotEmpty()) { res[j++] = stack.pop() } } else { stack.push(i) } } stack.push(s.length + 1) while (stack.isNotEmpty()) { res[j++] = stack.pop() } return res } } /** * Approach #2 Reversing the subarray. * Time complexity : O(n). * Space complexity : O(1). */ class FindPermutationReversing : FindPermutation { override operator fun invoke(s: String): IntArray { val res = IntArray(s.length + 1) for (i in res.indices) res[i] = i + 1 var i = 1 while (i <= s.length) { val j = i while (i <= s.length && s[i - 1] == 'D') i++ res.reverse(j - 1, i) i++ } return res } } /** * Approach #3 Two pointers. * Time complexity : O(n). * Space complexity : O(1). */ class FindPermutationTwoPointers : FindPermutation { override operator fun invoke(s: String): IntArray { val res = IntArray(s.length + 1) res[0] = 1 var i = 1 while (i <= s.length) { res[i] = i + 1 val j = i if (s[i - 1] == 'D') { while (i <= s.length && s[i - 1] == 'D') i++ var k = j - 1 var c = i while (k <= i - 1) { res[k] = c k++ c-- } } else { i++ } } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,796
kotlab
Apache License 2.0
src/test/aoc2019/Day7Test.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package test.aoc2019 import aoc2019.Day7 import org.junit.Assert.assertEquals import org.junit.Test import resourceAsList class Day7Test { @Test fun testPermutationsOf() { val d7 = Day7(listOf()) assertEquals(listOf(listOf(0L, 1L), listOf(1L, 0L)), d7.allPermutationsOf(0..1)) d7.allPermutationsOf(0..5) .also { perm -> assertEquals(true, perm.all { it.size == 6 }) } .also { perm -> assertEquals(true, perm.all { it.toSet().size == 6 }) } } @Test fun testPart1Example1() { val input = "3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0".split(",") assertEquals(43210, Day7(input).solvePart1()) } @Test fun testPart1Example2() { val input = "3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0".split(",") assertEquals(54321, Day7(input).solvePart1()) } @Test fun testPart1Example3() { val input = "3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0".split(",") assertEquals(65210, Day7(input).solvePart1()) } @Test fun partOneRealInput() { assertEquals(95757, Day7(resourceAsList("2019/day7.txt", ",")).solvePart1()) } @Test fun testPart2Example1() { val input = "3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5".split(",") assertEquals(139629729, Day7(input).solvePart2()) } @Test fun testPart2Example2() { val input = "3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,-5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10".split(",") assertEquals(18216, Day7(input).solvePart2()) } @Test fun partTwoRealInput() { assertEquals(4275738, Day7(resourceAsList("2019/day7.txt", ",")).solvePart2()) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,936
aoc
MIT License
Week1/src/BlackJack.kt
em4n0101
268,436,903
false
null
/** * Assignment 1 * * Program that creates a deck of cards, * deals two cards from that deck into a hand * and evaluates that hand of cards by finding * the sum of the pips. Display the cards in the * hand and the total of the pips in the hand. * * @author <NAME> (<EMAIL>) */ fun main() { // Get the deck and the hand with 2 cards var deck = createDeck() var hand = dealHand(deck, 2).toMutableList() // Print the cards println("\n\nYour hand was:") println(getVisualRepresentationFor(hand.toList())) // Check if get 21 or more, if so game it's over, if not ask the user for another card var total = evaluateHand(hand) if (total >= 21) printResults(total) else { println("Add additional card? (Y/N)") val input = readLine() if (input?.toLowerCase() == "Y".toLowerCase()) { // Get additional card and evaluate it hand.addAll(dealHand(deck, 1)) total = evaluateHand(hand) val lastCard = hand.last() println(getVisualRepresentationFor(listOf(lastCard))) printResults(total) } else { printResults(total) } } } /** * Function that creates a collection of cards * * @return the collection of cards */ fun createDeck(): MutableSet<Card> { val suits = setOf('\u2663', '\u2660', '\u2666', '\u2665') val pips = 1..13 var deck = mutableSetOf<Card>() for (pip in pips) { for (suit in suits) { deck.add(Card(pip, suit)) } } return deck } /** * Function that can deal n cards from the deck * * @param deck the collection of cards * @param numberOfCards number of cards it should place in the hand * @return collection containing the number of cards specified */ fun dealHand(deck: MutableSet<Card>, numberOfCards: Int) : List<Card> { var cards = mutableListOf<Card>() for (i in 0 until numberOfCards) { val randomCard = deck.random() deck.remove(randomCard) cards.add(randomCard) } return cards } /** * Function that evaluate the hand received * * @param hand the hand to evaluate * @return the total score */ fun evaluateHand(hand: List<Card>): Int { var res = 0 for (card in hand) { res += card.getValueForPips() } return res } /** * Function that print the total of the hand * * @param total the total of the hand */ fun printResults(total: Int) { println("For a total of: $total") if (total == 21) println("You Win!") else if (total >= 22) println("You Lose!") } /** * Function that get the visual representation of a hand * * @param cards the cards in the hand * @return a message with the visual representation of a card */ fun getVisualRepresentationFor(cards: List<Card>) : String { when (cards.size) { 1 -> { val card = cards.first() return """ .------. |${card.getReadablePips()} | | | | ${card.suit} | | | | ${card.getReadablePips()}| `-------'""".trimIndent() } 2 -> { val firstCard = cards.first() val secondCard = cards.last() return """ .------. |${firstCard.getReadablePips()} | | .------. | ${firstCard.suit} |${secondCard.getReadablePips()} | | | | | | ${secondCard.suit} | `-----| | | ${secondCard.getReadablePips()}| `-------'""".trimIndent() } else -> { return "" } } } /** * Class to represent a card into the game */ class Card(private val pip: Int, val suit: Char) { /** * Function to get a simple description of a card (A♣) */ override fun toString(): String { return "${getReadablePips()} $suit" } /** * Function to get a simple description of the pips (A, 1, 2, J, etc) */ fun getReadablePips () : String { return when (pip) { 1 -> "A" 2, 3, 4, 5, 6, 7, 8, 9, 10 -> pip.toString() 11 -> "J" 12 -> "Q" 13 -> "K" else -> "" } } /** * Function to get the value for the pip */ fun getValueForPips() : Int { return when (pip) { 1 -> 11 2, 3, 4, 5, 6, 7, 8, 9, 10 -> pip 11, 12, 13 -> 10 else -> 0 } } }
0
Kotlin
0
1
4f1ebb9d68091ef741ac69f2f46e16f512401de2
4,863
AndroidBootcampSummer2020
Apache License 2.0
src/day15.kt
miiila
725,271,087
false
{"Kotlin": 77215}
import java.io.File import kotlin.math.max import kotlin.system.exitProcess private const val DAY = 15 fun main() { if (!File("./day${DAY}_input").exists()) { downloadInput(DAY) println("Input downloaded") exitProcess(0) } val transformer = { x: String -> x.split(",") } val input = loadInput(DAY, false, transformer).first() // println(input) println(solvePart1(input)) println(solvePart2(input)) } // Part 1 private fun solvePart1(input: List<String>): Int { return input.map { it.fold(0) { acc, c -> ((acc + c.code) * 17) % 256 } }.sum() } // Part 2 private fun solvePart2(input: List<String>): Int { return input.fold(mutableMapOf<Int, MutableMap<String, Int>>()) { boxes, lens -> val s = max(lens.indexOf('-'), lens.indexOf('=')) val hash = lens.slice(0..<s).fold(0) { acc, c -> ((acc + c.code) * 17) % 256 } boxes[hash] = boxes[hash] ?: mutableMapOf() if (lens[s] == '-') { boxes[hash]!!.remove(lens.slice(0..1)) } if (lens[s] == '=') { boxes[hash]!![lens.slice(0..1)] = lens.last().digitToInt() } boxes } .filterValues { it.isNotEmpty() } .map { (boxOrder, box) -> (boxOrder + 1) * box.values.mapIndexed { slot, focalLength -> (slot + 1) * focalLength }.sum() } .sum() }
0
Kotlin
0
1
1cd45c2ce0822e60982c2c71cb4d8c75e37364a1
1,381
aoc2023
MIT License
src/main/kotlin/g0501_0600/s0593_valid_square/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0593_valid_square // #Medium #Math #Geometry #2023_02_01_Time_161_ms_(83.33%)_Space_35_MB_(66.67%) class Solution { fun validSquare(p1: IntArray, p2: IntArray, p3: IntArray, p4: IntArray): Boolean { val distancesSquared = IntArray(6) distancesSquared[0] = getDistanceSquared(p1, p2) distancesSquared[1] = getDistanceSquared(p1, p3) distancesSquared[2] = getDistanceSquared(p1, p4) distancesSquared[3] = getDistanceSquared(p2, p3) distancesSquared[4] = getDistanceSquared(p2, p4) distancesSquared[5] = getDistanceSquared(p3, p4) distancesSquared.sort() if (distancesSquared[0] == 0) { return false } if (distancesSquared[0] != distancesSquared[3]) { return false } return if (distancesSquared[4] != distancesSquared[5]) { false } else distancesSquared[5] == 2 * distancesSquared[0] } private fun getDistanceSquared(p1: IntArray, p2: IntArray): Int { val deltaX = p2[0] - p1[0] val deltaY = p2[1] - p1[1] return deltaX * deltaX + deltaY * deltaY } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,159
LeetCode-in-Kotlin
MIT License
src/Day01.kt
pejema
576,456,995
false
{"Kotlin": 7994}
fun main() { fun getCaloriesByElf(input: List<String>) : MutableList<Int> { val mutableList = mutableListOf<Int>() var totalCalories = 0 for (cal in input) { if (cal == "") { mutableList.add(totalCalories) totalCalories = 0 } else { totalCalories += cal.toInt() } } if (totalCalories > 0) { mutableList.add(totalCalories) } mutableList.sort() return mutableList; } fun part1(input: List<String>): Int { return getCaloriesByElf(input).max() } fun part2(input: List<String>): Int { return getCaloriesByElf(input).reversed().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") part1(input).println() part2(input).println() }
0
Kotlin
0
0
b2a06318f0fcf5c6067058755a44e5567e345e0c
1,024
advent-of-code
Apache License 2.0
src/Day10.kt
pimtegelaar
572,939,409
false
{"Kotlin": 24985}
fun main() { fun part1(input: List<String>): Int { var x = 1 var result = 0 var cycle = 1 input.forEach { line -> if (cycle % 40 == 20) { result += cycle * x } if (line.startsWith("addx")) { cycle++ if (cycle % 40 == 20) { result += cycle * x } x += line.substring(5).toInt() } cycle++ } return result } fun part2(input: List<String>): String { var x = 1 val stack = ArrayDeque(elements = input) var current: Int? = null var processing = false val cl = mutableListOf<Char>() for (i in 0..250) { val sp = i % 40 if (sp == 0) { cl.add('\n') } if (stack.isEmpty()) { break } if (processing) { processing = false } else { if (current != null) { x += current } val line = stack.removeFirst() if (line.startsWith("addx")) { current = line.substring(5).toInt() processing = true } else { current = null } } if (x in sp - 1..sp + 1) { cl.add('#') } else { cl.add('.') } } return cl.joinToString("") } val inputName = "Day10" val testInput = readInput(inputName + "_test") val input = readInput(inputName) val part1 = part1(testInput) check(part1 == 13140) { part1 } println(part1(input)) val part2 = part2(testInput) println(part2) println(part2(input)) }
0
Kotlin
0
0
16ac3580cafa74140530667413900640b80dcf35
1,865
aoc-2022
Apache License 2.0
src/main/kotlin/structures/Graph.kt
DmitryTsyvtsyn
418,166,620
false
{"Kotlin": 223256}
package structures import java.util.LinkedList import kotlin.collections.LinkedHashSet /** * * data structure: undirected graph without weights * * description: made up of vertices connected by edges * */ class Graph<T> { private val data = mutableMapOf<Vertex<T>, MutableList<Vertex<T>>>() /** * adds a new vertex with a value [value] */ fun addVertex(value: T) = data.putIfAbsent(Vertex(value), mutableListOf()) /** * removes a vertex by value [value] from a graph */ fun removeVertex(value: T) { val removingVertex = Vertex(value) data.values.forEach { list -> list.remove(removingVertex) } data.remove(removingVertex) } /** * adds an edge between two vertices, that have values [value1], [value2] */ fun addEdge(value1: T, value2: T) { val vertex1 = Vertex(value1) val vertex2 = Vertex(value2) data[vertex1]?.add(vertex2) data[vertex2]?.add(vertex1) } /** * removes an edge between two vertices, that have values [value1], [value2] */ fun removeEdge(value1: T, value2: T) { val vertex1 = Vertex(value1) val vertex2 = Vertex(value2) data[vertex1]?.remove(vertex2) data[vertex2]?.remove(vertex1) } /** * returns the associated vertices with the given vertex value [value] */ fun connectedVertexes(value: T) = data[Vertex(value)] ?: listOf() /** * traversal of the graph in depth, returns all vertices of the graph */ fun depthFirstTraversal() : List<Vertex<T>> { val visited = LinkedHashSet<Vertex<T>>() val queue = LinkedList<Vertex<T>>() val firstVertex = data.keys.firstOrNull() ?: return emptyList() queue.push(firstVertex) while (queue.isNotEmpty()) { val vertex = queue.poll() if (!visited.contains(vertex)) { visited.add(vertex) queue.addAll(data[vertex] ?: listOf()) } } return visited.toList() } /** * traversal of the graph in breadth, returns all vertices of the graph */ fun breadthFirstTraversal() : List<Vertex<T>> { val visited = LinkedHashSet<Vertex<T>>() val queue = LinkedList<Vertex<T>>() val firstVertex = data.keys.firstOrNull() ?: return emptyList() queue.add(firstVertex) visited.add(firstVertex) while (queue.isNotEmpty()) { val vertex = queue.poll() data[vertex]?.forEach { v -> if (!visited.contains(v)) { visited.add(v) queue.add(v) } } } return visited.toList() } } /** * graph vertex model */ data class Vertex<T>(val value: T)
0
Kotlin
135
767
7ec0bf4f7b3767e10b9863499be3b622a8f47a5f
2,834
Kotlin-Algorithms-and-Design-Patterns
MIT License
src/Day02.kt
kuolemax
573,740,719
false
{"Kotlin": 21104}
// --- Day 2: Rock Paper Scissors --- // The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage, a giant Rock Paper Scissors tournament is already in progress. // // Rock Paper Scissors is a game between two players. Each game contains many rounds; in each round, the players each simultaneously choose one of Rock, Paper, or Scissors using a hand shape. Then, a winner for that round is selected: Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, the round instead ends in a draw. // // Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win. "The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column--" Suddenly, the Elf is called away to help with someone's tent. // // The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. Winning every time would be suspicious, so the responses must have been carefully chosen. // // The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores for each round. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won). // // Since you can't be sure if the Elf is trying to help you or trick you, you should calculate the score you would get if you were to follow the strategy guide. // // For example, suppose you were given the following strategy guide: // // A Y // B X // C Z // // This strategy guide predicts and recommends the following: // // In the first round, your opponent will choose Rock (A), and you should choose Paper (Y). This ends in a win for you with a score of 8 (2 because you chose Paper + 6 because you won). // In the second round, your opponent will choose Paper (B), and you should choose Rock (X). This ends in a loss for you with a score of 1 (1 + 0). // The third round is a draw with both players choosing Scissors, giving you a score of 3 + 3 = 6. // In this example, if you were to follow the strategy guide, you would get a total score of 15 (8 + 1 + 6). // // What would your total score be if everything goes exactly according to your strategy guide? fun main() { // part1 穷举结果 val resultMap = mapOf( "A X" to 1 + 3, "A Y" to 2 + 6, "A Z" to 3 + 0, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 1 + 6, "C Y" to 2 + 0, "C Z" to 3 + 3 ) fun part1(lines: List<String>): Int { var totalScore = 0 for (line in lines) { val theScore = resultMap[line]!! totalScore += theScore } return totalScore } // part2 // A:Rock B:Paper C:Scissors val cardScore = mapOf( "A" to 1, "B" to 2, "C" to 3, ) val gameScore = mapOf( "Z" to 6, "X" to 0, "Y" to 3, ) /** * 根据对手出牌和对局详情决定我方出牌 * @param [card] 对手牌 * @param [comparatorResult] 对局情况 */ fun cardComparator(card: String, comparatorResult: String): String { // 石头,布,剪刀 val cards = listOf("A", "B", "C") val cardIndex = cards.indexOf(card) return when (comparatorResult) { "Z" -> { // 胜利,result > card cards[(cardIndex + 1) % cards.size] } "X" -> { // 输 cards[if ((cardIndex - 1) < 0) (cardIndex - 1) + cards.size else (cardIndex - 1)] } // 平局 "Y" -> return card else -> "" } } /** * 根据出牌情况计算得分 */ val gameResultScore = cardScore.keys.flatMap { card -> gameScore.keys.map { game -> // cardComparator(card, game) 找出结果的应该出的牌 "$card $game" to (cardScore[cardComparator(card, game)]!! + gameScore[game]!!) } }.toMap() fun part2(lines: List<String>): Int { var totalScore = 0 for (line in lines) { val theScore = gameResultScore[line]!! totalScore += theScore } return totalScore } val testInput = readInput("Day02_test") check(part1(testInput) == 64) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3045f307e24b6ca557b84dac18197334b8a8a9bf
4,710
aoc2022--kotlin
Apache License 2.0
src/main/kotlin/com/resnik/math/Helper.kt
mtresnik
348,187,516
false
null
package com.resnik.math import com.resnik.math.graph.objects.Edge import com.resnik.math.graph.objects.Vertex import kotlin.math.pow fun <T> permuteRecursive(set: Set<T>): Set<List<T>> { if (set.isEmpty()) return emptySet() fun <T> _permuteRecursive(list: List<T>): Set<List<T>> { if (list.isEmpty()) return setOf(emptyList()) val res: MutableSet<List<T>> = mutableSetOf() for (i in list.indices) { _permuteRecursive(list - list[i]).forEach { res.add(it + list[i]) } } return res } return _permuteRecursive(set.toList()) } fun getEdge(from: Vertex, to: Vertex): Edge = from.edges.first { it.to == to } fun verticesToEdges(vertices: List<Vertex>): List<Edge> { val ret = mutableListOf<Edge>() for (i in vertices.indices) { if (i < vertices.size - 1) { ret += getEdge(vertices[i], vertices[i + 1]) } } return ret } fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double { val EARTH_RADIUS_METERS = 6371e3 val lat1Rads = Math.toRadians(lat1) val lat2Rads = Math.toRadians(lat2) val dLat = Math.toRadians(lat2 - lat1) val dLon = Math.toRadians(lon2 - lon1) val a: Double = Math.sin(dLat / 2).pow(2) + Math.cos(lat1Rads) * Math.cos(lat2Rads) * Math.sin(dLon / 2).pow(2) val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) return EARTH_RADIUS_METERS * c }
0
Kotlin
0
0
d2d589306d34ca4b2026448078617bf2f62a3f76
1,509
graph
Apache License 2.0
src/Day02.kt
ianredman26
572,914,381
false
{"Kotlin": 3237}
fun main() { fun part1(input: List<String>): Int { val strategyGuide: MutableMap<String, String> = mutableMapOf() val total = 0 input.map { strategyGuide.put(it.first().lowercase(), it.last().lowercase()) } strategyGuide.map { round -> when (round.key) { "a" -> { total.plus(rock(round.value)) } "b" -> { total.plus(paper(round.value)) } "c" -> { total.plus(scissors(round.value)) } else -> {} } } return total } val testInput = readInput("Day02_test") // check(part1(testInput) == 15) // val input = readInput("Day01") println(part1(testInput)) // println(part2(part1(testInput))) } // A -> Rock // X -> Rock 1 // B -> Paper // Y -> Paper 2 // C -> Scissors // Z -> Scissors 3 // WIN -> 3 // DRAW -> 1 // LOSS -> 0 fun rock(choice: String): Int { return when (choice) { "x" -> { 4 } "y" -> { 7 } "z" -> { 3 } else -> { 0 } } } fun paper(choice: String): Int { return when (choice) { "x" -> { 1 } "y" -> { 2 } "z" -> { 9 } else -> { 0 } } } fun scissors(choice: String): Int { return when (choice) { "x" -> { 4 } "y" -> { 2 } "z" -> { 4 } else -> { 0 } } }
0
Kotlin
0
0
dcd9fae4531622cc974d2eb3d5ded94bf268ad1e
1,725
advent-of-code-2022
Apache License 2.0
src/day07/FileSystem.kt
treegem
572,875,670
false
{"Kotlin": 38876}
package day07 import day07.CommandLineConstants.COMMAND_CD import day07.CommandLineConstants.COMMAND_LS import day07.CommandLineConstants.DIR import day07.CommandLineConstants.PARENT_DIR import day07.LineType.* class FileSystem(input: List<String>) { private var currentDirectoryName: String = "/" private var currentParents = mutableListOf<String>() val directories: MutableSet<Directory> = mutableSetOf(Directory(listOf(), currentDirectoryName)) init { input .takeLast(input.size - 1) .forEach { line -> when (line.type) { CHANGE_DIRECTORY -> changeDirectory(line) LIST_DIRECTORY -> {} PRINT_DIRECTORY -> addDirectoryIfNotExists(line) PRINT_FILE -> addFile(line) } } } private fun changeDirectory(line: String) { val directoryName = line.substringAfter(COMMAND_CD) currentDirectoryName = when (directoryName) { PARENT_DIR -> { currentParents.removeLast() } else -> { currentParents.add(currentDirectoryName) directoryName } } } private fun addDirectoryIfNotExists(line: String) { val directoryName = line.substringAfter(DIR) if (!existsByNameAndParents(directoryName)) { val newDirectory = Directory( parents = currentParents + currentDirectoryName, name = directoryName ) directories.add(newDirectory) getCurrentDirectory().directories.add(newDirectory) } } private fun addFile(line: String) { getCurrentDirectory() .apply { files.add(File.from(line)) } } private fun getCurrentDirectory() = directories.single { it.name == currentDirectoryName && it.path == currentParents.joinToString() } private fun existsByNameAndParents(directoryName: String) = directories.any { it.name == directoryName && it.parents.joinToString() == (currentParents + currentDirectoryName).joinToString() } } enum class LineType { CHANGE_DIRECTORY, LIST_DIRECTORY, PRINT_DIRECTORY, PRINT_FILE, } object CommandLineConstants { const val COMMAND_CD = "$ cd " const val COMMAND_LS = "$ ls" const val DIR = "dir " const val PARENT_DIR = ".." } private val String.type: LineType get() = when { startsWith(COMMAND_CD) -> CHANGE_DIRECTORY startsWith(COMMAND_LS) -> LIST_DIRECTORY startsWith(DIR) -> PRINT_DIRECTORY else -> PRINT_FILE }
0
Kotlin
0
0
97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8
2,689
advent_of_code_2022
Apache License 2.0
src/main/kotlin/io/queue/OpenTheLock.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.queue import java.util.* import kotlin.collections.HashSet //https://leetcode.com/explore/learn/card/queue-stack/231/practical-application-queue/1375/ class OpenTheLock { private val initial = listOf(0, 0, 0, 0) private val error = -1 fun execute(deadEnds: Array<String>, goal: String): Int { val start = initial val target = goal.lockArrayListOfInt() val avoid = deadEnds.map { it.lockArrayListOfInt() }.toSet() if (start in avoid) return error var distance = 0 var toVisit = listOf(start) val visited = HashSet<List<Int>>() while (toVisit.isNotEmpty()) { val nextToVisit = mutableListOf<List<Int>>() for (node in toVisit) { if (node == target) return distance for (n in retrieveNeighbours(node)) { if (n !in visited && n !in avoid) { visited.add(n) nextToVisit.add(n) } } } toVisit = nextToVisit distance += 1 } return error } private fun retrieveNeighbours(current: List<Int>) = arrayListOf<List<Int>>().apply { (0..3).map { i -> val next = ArrayList(current) next[i] = (current[i] + 1) % 10 add(ArrayList(next)) next[i] = (current[i] + 9) % 10 add(next) } } private fun String.lockArrayListOfInt() = (0..3).map { Character.getNumericValue(this[it]) } } fun main() { val openTheLock = OpenTheLock() listOf( Help(deadEnds = arrayOf("0201", "0101", "0102", "1212", "2002"), target = "0202", output = 6), Help(deadEnds = arrayOf("8888"), target = "0009", output = 1), Help(deadEnds = arrayOf("8887", "8889", "8878", "8898", "8788", "8988", "7888", "9888"), target = "8888", output = -1) ).mapIndexed { index, item -> val output = openTheLock.execute(deadEnds = item.deadEnds, goal = item.target) if (output != item.output) { println("error with $item wrong output $output") } else println("done with $index") } } private data class Help(val deadEnds: Array<String>, val target: String, val output: Int)
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
2,078
coding
MIT License
src/commonMain/kotlin/Graph.kt
GHvW
322,429,575
false
null
package ghvw.graph import kotlinx.collections.immutable.* // G = (V, E) data class Graph<A>( val vertices: PersistentSet<A>, val edges: PersistentSet<Edge<A>> ) data class UnweightedGraph<A>( val vertices: PersistentSet<A>, val edges: PersistentSet<UnweightedEdge<A>> ) data class WeightedGraph<A>( val vertices: PersistentSet<A>, val edges: PersistentSet<WeightedEdge<A>> ) fun <A> unweightedEdgeSetOf(vararg pairs: Pair<A, A>): PersistentSet<UnweightedEdge<A>> = pairs .map { pair -> UnweightedEdge(pair.first, pair.second) } .toPersistentSet() typealias AdjacencyMap<A> = PersistentMap<A, PersistentSet<Edge<A>>> typealias U<A> = UnweightedEdge<A> // this could probably use a Lens fun <A> UnweightedGraph<A>.toAdjacencyMap(): AdjacencyMap<A> { val map = this.vertices .fold(persistentMapOf<A, PersistentSet<Edge<A>>>()) { persistentMap, vertex -> persistentMap.put(vertex, persistentSetOf()) } return this .edges .fold(map) { persistentMap, edge -> val from = persistentMap[edge.from()] val to = persistentMap[edge.to()] if (from != null && to != null) { persistentMap .put(edge.from(), from.add(edge)) .put(edge.to(), to.add(UnweightedEdge(edge.to(), edge.from()))) } else { persistentMap } } } // this could probably use a Lens fun <A> UnweightedGraph<A>.toDirectedAdjacencyMap(): AdjacencyMap<A> { val map = this .vertices .fold(persistentMapOf<A, PersistentSet<Edge<A>>>()) { persistentMap, vertex -> persistentMap.put(vertex, persistentSetOf()) } return this .edges .fold(map) { persistentMap, edge -> persistentMap[edge.from()] ?.let { persistentMap.put(edge.from(), it.add(edge)) } ?: persistentMap } } data class TraversalState<A>( val visited: MutableSet<A>, val memory: Conjable<Edge<A>> ) // TODO - would it be better to treat everything as a directed edge? // and get away with a sequence of edges instead of a sequence of Pair<vertex, edge> ? // it would make double the edges in an undirected graph but get rid of the Pairs // right now, traverse has unnecessary detail for a directed graph traverse. no need to figure out // to and from because it only goes one way. fun <A> traverse(state: TraversalState<A>): (AdjacencyMap<A>) -> Sequence<Edge<A>> = { map -> generateSequence(state, { s -> s.memory.peek()?.let { map[it.to()]?.let { edges -> edges .fold(s.copy(memory = s.memory.pop())) { result, edge -> // val (vertexFrom, _) = it val vertex = edge.to() if (result.visited.contains(vertex)) { result } else { result.visited.add(vertex) TraversalState(result.visited, result.memory.conj(edge)) } } } } }).mapNotNull { s -> s.memory.peek() } } fun <A> AdjacencyMap<A>.depthFirstTraverseFrom(vertex: A): Sequence<Edge<A>> = traverse( TraversalState( mutableSetOf(vertex), Stack(mutableListOf(U(vertex, vertex))) // Unweighted Edge as the start? ))(this) fun <A> AdjacencyMap<A>.breadthFirstTraverseFrom(vertex: A): Sequence<Edge<A>> = traverse( TraversalState( mutableSetOf(vertex), Queue(ArrayDeque(listOf(U(vertex, vertex)))) ))(this) fun <A> AdjacencyMap<A>.shortestPathsTo(vertex: A): Map<A, A> = this .breadthFirstTraverseFrom(vertex) .fold(mutableMapOf()) { map, edge -> map[edge.to()] = edge.from() map } fun <A> shortestPath(paths: Map<A, A>, from: A): Sequence<A> = generateSequence(from) { vertex -> paths[vertex]?.let { if (it != vertex) { it } else { null } } } fun <A> AdjacencyMap<A>.dijkstraShortestPathsTo(vertex: A): Pair<Map<A, A>, Map<A, Int>> =
0
Kotlin
0
0
a9e900e43f08598ee839b494a4dea41a7fb02789
4,404
venice
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/AsteroidCollision.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.Stack import kotlin.math.abs /** * 735. Asteroid Collision * @see <a href="https://leetcode.com/problems/asteroid-collision/">Source</a> */ fun interface AsteroidCollision { operator fun invoke(asteroids: IntArray): IntArray } /** * Approach: Stack */ class AsteroidCollisionStack : AsteroidCollision { override operator fun invoke(asteroids: IntArray): IntArray { val st: Stack<Int> = Stack<Int>() for (asteroid in asteroids) { var flag = true while (st.isNotEmpty() && st.peek() > 0 && asteroid < 0) { // If the top asteroid in the stack is smaller, then it will explode. // Hence, pop it from the stack, also continue with the next asteroid in the stack. if (abs(st.peek()) < abs(asteroid)) { st.pop() continue } else if (abs(st.peek()) == abs(asteroid)) { st.pop() } // If we reach here, the current asteroid will be destroyed // Hence, we should not add it to the stack flag = false break } if (flag) { st.push(asteroid) } } // Add the asteroids from the stack to the vector in the reverse order. val remainingAsteroids = IntArray(st.size) for (i in remainingAsteroids.indices.reversed()) { remainingAsteroids[i] = st.peek() st.pop() } return remainingAsteroids } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,222
kotlab
Apache License 2.0
day11/Kotlin/day11.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* fun print_day_11() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 11" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Dumbo Octopus -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_11() Day11().part_1() Day11().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day11 { private val octogrid = File("../Input/day11.txt").readLines().map { it.toCharArray().map { c -> c.digitToInt() }.toMutableList() }.toMutableList() data class GridPoint(val x:Int, val y:Int) { fun neighbours(xBoundary: Int, yBoundary: Int): List<GridPoint> = (-1 .. 1).map { yOffset -> (-1 .. 1).map { xOffset -> GridPoint(x+xOffset, y+yOffset) } }.flatten() .filter { it.x in 0 until xBoundary && it.y in 0 until yBoundary && !(it.x == x && it.y == y) } } fun part_1() { var totalFlashes = 0 for(step in 1..100) { val flashed = mutableListOf<GridPoint>() for (y in octogrid.indices) { for (x in octogrid[y].indices) { octogrid[y][x]++ } } do { val newFlashes = mutableListOf<GridPoint>() for (y in octogrid.indices) { for (x in octogrid[y].indices) { val gp = GridPoint(x, y) if (octogrid[y][x] > 9 && gp !in flashed) { newFlashes.add(gp) gp.neighbours(octogrid[y].size, octogrid.size).forEach { octogrid[it.y][it.x]++ } } } } flashed.addAll(newFlashes) } while(newFlashes.isNotEmpty()) totalFlashes += flashed.size flashed.forEach { octogrid[it.y][it.x] = 0 } } println("Puzzle 1: " + totalFlashes) } fun part_2() { val totalOctos = octogrid.flatten().size var step = 0 do { step++ val flashed = mutableListOf<GridPoint>() for (y in octogrid.indices) { for (x in octogrid[y].indices) { octogrid[y][x]++ } } do { val newFlashes = mutableListOf<GridPoint>() for (y in octogrid.indices) { for (x in octogrid[y].indices) { val gp = GridPoint(x, y) if (octogrid[y][x] > 9 && gp !in flashed) { newFlashes.add(gp) gp.neighbours(octogrid[y].size, octogrid.size).forEach { octogrid[it.y][it.x]++ } } } } flashed.addAll(newFlashes) } while(newFlashes.isNotEmpty()) flashed.forEach { octogrid[it.y][it.x] = 0 } } while(flashed.size != totalOctos) println("Puzzle 2: " + step) } }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
3,489
AOC2021
Apache License 2.0
day5/src/main/kotlin/day5/Main.kt
ErikHellman
433,722,039
false
{"Kotlin": 9432}
package day5 import java.io.File import kotlin.math.absoluteValue data class Point(val x: Int, val y: Int) fun main(args: Array<String>) { val diagram = HashMap<Point, Int>() File("input.txt").readLines().forEach { line -> val (start, end) = line .split("->") .map { pair -> val (x, y) = pair.trim() .split(',') .map { num -> num.toInt() } Point(x, y) } println("Got $start $end") val yRange = if (start.y <= end.y) start.y .. end.y else start.y downTo end.y val xRange = if (start.x <= end.x) start.x..end.x else start.x downTo end.x if (start.x == end.x) { println("Check vertical") for (i in yRange) { val point = Point(start.x, i) val intersects = (diagram[point] ?: 0) + 1 diagram[point] = intersects println("$point $intersects") } } else if (start.y == end.y) { println("Check horizontal") for (i in xRange) { val point = Point(i, start.y) val intersects = (diagram[point] ?: 0) + 1 diagram[point] = intersects println("$point $intersects") } } else if ((start.x - end.x).absoluteValue == (start.y - end.y).absoluteValue) { println("Check diagonal $start $end") xRange.zip(yRange).forEach { val point = Point(it.first, it.second) val intersects = (diagram[point] ?: 0) + 1 diagram[point] = intersects println("$point $intersects") } } else { println("Skip $start $end") } } println(diagram.filter { it.value >= 2 }.size) }
0
Kotlin
0
1
37f54d52633fff5f6fdd9e66926c57421fc721d2
1,844
advent-of-code-2021
Apache License 2.0
src/test/kotlin/io/noobymatze/aoc/y2022/Day9.kt
noobymatze
572,677,383
false
{"Kotlin": 90710}
package io.noobymatze.aoc.y2022 import io.noobymatze.aoc.Aoc import kotlin.math.abs import kotlin.test.Test class Day9 { data class Pos(var row: Int, var col: Int) @Test fun test() { val data = Aoc.getInput(9) .lineSequence().map { it.split(" ").let { (d, n) -> d to n.toInt() } } val head = Pos(0, 0) val tail = Pos(0, 0) val visited = mutableSetOf(0 to 0) for ((move, n) in data) { for (x in 0 until n) { when (move) { "U" -> head.row-- "D" -> head.row++ "R" -> head.col++ "L" -> head.col-- } move(head, tail) visited.add(tail.row to tail.col) } } println(visited.size) } @Test fun test2() { val data = Aoc.getInput(9) .lineSequence().map { it.split(" ").let { (d, n) -> d to n.toInt() } } val snake = Array(10) { Pos(0, 0) } val visited = mutableSetOf(0 to 0) for ((move, n) in data) { for (x in 0 until n) { when (move) { "U" -> snake[0].row-- "D" -> snake[0].row++ "R" -> snake[0].col++ "L" -> snake[0].col-- } for (i in 1 until snake.size) { move(snake[i - 1], snake[i]) } visited.add(snake.last().row to snake.last().col) } } println(visited.size) } private fun move(head: Pos, tail: Pos): Unit = when { // Adjacency with math, because I was too stupid before abs(head.row - tail.row) <= 1 && abs(head.col - tail.col) <= 1 -> Unit else -> { tail.row = when { head.row < tail.row -> tail.row - 1 head.row > tail.row -> tail.row + 1 else -> tail.row } tail.col = when { head.col < tail.col -> tail.col - 1 head.col > tail.col -> tail.col + 1 else -> tail.col } } } }
0
Kotlin
0
0
da4b9d894acf04eb653dafb81a5ed3802a305901
2,209
aoc
MIT License
src/main/kotlin/icfp2019/analyzers/ConservativeDistanceAnalyzer.kt
randomsamples
189,507,360
true
{"JavaScript": 797310, "Kotlin": 89529, "CSS": 9434, "HTML": 5859}
package icfp2019.analyzers import icfp2019.core.Analyzer import icfp2019.core.DistanceEstimate import icfp2019.model.GameState import icfp2019.model.Node import icfp2019.model.Point import icfp2019.model.RobotId import org.jgrapht.alg.connectivity.ConnectivityInspector import org.jgrapht.alg.spanning.PrimMinimumSpanningTree import org.jgrapht.graph.AsSubgraph data class ConservativeDistance(val estimate: DistanceEstimate, val pathNodes: Set<Node>) object ConservativeDistanceAnalyzer : Analyzer<(position: Point) -> ConservativeDistance> { override fun analyze(initialState: GameState): (robotId: RobotId, state: GameState) -> (position: Point) -> ConservativeDistance { val graphAnalyzer = GraphAnalyzer.analyze(initialState) val shortestPathAnalyzer = ShortestPathUsingDijkstra.analyze(initialState) return { id, state -> val graph = graphAnalyzer(id, state) val shortestPathAlgorithm = shortestPathAnalyzer(id, state) val unwrappedNodes = AsSubgraph(graph, graph.vertexSet().filter { it.isWrapped.not() }.toSet()) val connectivityInspector = ConnectivityInspector(unwrappedNodes) val connectedGraphs = connectivityInspector.connectedSets(); { point -> val node = initialState.get(point) val randomNodesFromEach: Set<Node> = connectedGraphs.map { it.first() } .plus(node) .toSet() val nodes: Set<Node> = randomNodesFromEach.windowed(2, step = 1).map { (n1, n2) -> shortestPathAlgorithm.getPath(n1, n2) }.flatMap { it.vertexList }.plus(connectedGraphs.flatten()).toSet() val connectedUnwrappedNodes = AsSubgraph(graph, nodes) val spanningTree = PrimMinimumSpanningTree(connectedUnwrappedNodes).spanningTree ConservativeDistance( DistanceEstimate(spanningTree.count()), spanningTree.edges.flatMap { listOf( graph.getEdgeSource(it), graph.getEdgeTarget(it) ) }.toSet() ) } } } }
0
JavaScript
0
0
afcf5123ffb72ac10cfa6b0772574d9826f15e41
2,292
icfp-2019
The Unlicense
aoc-kotlin/src/main/kotlin/day03/Day03.kt
mahpgnaohhnim
573,579,334
false
{"Kotlin": 29246, "TypeScript": 1975, "Go": 1693, "Rust": 1520, "JavaScript": 123}
package day03 import java.io.File class Day03 { companion object { fun getPrioritySum(inputText: String): Int { return inputText.lines().map { splitStringInHalf(it) } .sumOf { getItemPriority(it[0], it[1]) } } fun splitStringInHalf(text: String): List<String> { return text.chunked(text.length / 2) } fun getItemPriority(firstHalf: String, lastHalf: String): Int { val item = firstHalf.find { lastHalf.contains(it) }.toString() return getValueByItem(item) } fun getValueByItem(item: String): Int { val lowerCaseABC = ('a'..'z').joinToString("") val upperCaseABC = ('A'..'Z').joinToString("") val possibleValues = "$lowerCaseABC$upperCaseABC" return possibleValues.indexOf(item) + 1 } fun getPrioritySumPart2(inputText: String): Int { return inputText.lines().chunked(3).sumOf { getItemPriorityPart2(it) } } fun getItemPriorityPart2(elves: List<String>): Int { val item = elves[0].find { elves[1].contains(it) && elves[2].contains(it) }.toString() return getValueByItem(item) } } } fun main() { val inputFile = File(Day03::class.java.getResource("input.txt")?.path.orEmpty()) val resultPart1 = Day03.getPrioritySum(inputFile.readText()) val resultPart2 = Day03.getPrioritySumPart2(inputFile.readText()) println( """ resultPart1: $resultPart1 resultPart2: $resultPart2 """.trimIndent() ) }
0
Kotlin
0
0
c514152e9e2f0047514383fe536f7610a66aff70
1,631
aoc-2022
MIT License
src/iii_conventions/MyDate.kt
gallko
125,965,117
false
null
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int = when { year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth - other.dayOfMonth } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) operator fun MyDate.plus(interval: TimeInterval): MyDate = addTimeIntervals(interval, 1) operator fun MyDate.plus(pair: Pair<TimeInterval, Int>): MyDate = addTimeIntervals(pair.first, pair.second) enum class TimeInterval { DAY, WEEK, YEAR } operator fun TimeInterval.times(int: Int): Pair<TimeInterval, Int> = Pair(this, int) class DateRange(val start: MyDate, val endInclusive: MyDate): Iterable<MyDate> { override fun iterator(): Iterator<MyDate> = DateIterator(this) } class DateIterator(val dataRange: DateRange) : Iterator<MyDate> { var curDate: MyDate = dataRange.start override fun hasNext(): Boolean = curDate <= dataRange.endInclusive override fun next(): MyDate { val oldData = curDate curDate = curDate.nextDay() return oldData } } operator fun DateRange.contains(d: MyDate) : Boolean = when { start <= d && d <= endInclusive -> true start > endInclusive -> false else -> false }
0
Kotlin
0
0
c1290d56daf6276bfb5f82c1b0e3799262cf553c
1,401
kotlin-koans
MIT License
week11familytravel/FamilyTravel.kt
laitingsheng
341,616,623
false
null
import java.util.PriorityQueue class FamilyTravel { data class Stop(@JvmField val dist: Int, @JvmField val prevDist: Int, @JvmField val src: Int) : Comparable<Stop> { override fun compareTo(other: Stop): Int = dist - other.dist } fun shortest(edges: Array<String>): Int { val m = edges.first().length val converted = Array(edges.size) { i -> val s = edges[i] IntArray(m) { j -> when (val c = s[j]) { in 'a' .. 'z' -> c - 'a' + 1 in 'A' .. 'Z' -> c - 'A' + 27 else -> 53 } } } val q = PriorityQueue<Stop>() q.add(Stop(0, 52, 0)) val md = Array(m) { val re = IntArray(54) re.fill(Int.MAX_VALUE) re } md[0][53] = 0 while (q.isNotEmpty()) { val (d, pd, src) = q.poll() if (src == 1) return d converted[src].forEachIndexed { index, i -> if (i <= pd) { val nd = d + i if (nd < md[index][i]) { md[index][i] = nd q.add(Stop(nd, i, index)) } } } } return -1 } }
0
Kotlin
0
0
2fc3e7a23d37d5e81cdf19a9ea19901b25941a49
1,340
2020S1-COMP-SCI-7007
ISC License
src/main/kotlin/day06/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day06 import java.io.File private const val REPRODUCTION_INTERVAL = 7 fun main() { val fishReproductionTimers = File("src/main/kotlin/day06/input.txt").readLines().first().split(",").map { it.toInt() } val fishCountByTimer = fishReproductionTimers.fold(Array(9) { 0L }) { acc, fishReproductionTimer -> acc[fishReproductionTimer]++ acc } for (day in 0..79) { calculateFishCount(day, fishCountByTimer) } println(fishCountByTimer.asSequence().sumOf { it }) for (day in 80..255) { calculateFishCount(day, fishCountByTimer) } println(fishCountByTimer.asSequence().sumOf { it }) } private fun calculateFishCount(day: Int, fishCountByTimer: Array<Long>) { val reproductionDayTimer = day % REPRODUCTION_INTERVAL val newFishCount = fishCountByTimer[reproductionDayTimer] fishCountByTimer[reproductionDayTimer] += fishCountByTimer[7] fishCountByTimer[7] = fishCountByTimer[8] fishCountByTimer[8] = newFishCount }
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
1,005
aoc-2021
MIT License
src/main/kotlin/days/Day23.kt
mstar95
317,305,289
false
null
package days import java.util.* data class LLNode(val value: Int, var next: LLNode?) class Day23 : Day(23) { override fun partOne(): Any { val cups = inputString.split("").mapNotNull { if (it == "") null else LLNode(it.toInt(), null) } for (i in cups.indices) { cups[i].next = cups[(i+1)%cups.size] } var curr: LLNode? = cups[0] for (i in 1..100) { val move = curr?.next curr?.next = curr?.next?.next?.next?.next var destination = if (curr?.value == 1) 9 else curr!!.value - 1 while (destination in listOf(move?.value, move?.next?.value, move?.next?.next?.value)) { destination -= 1 if (destination < 1) { destination = 9 } } var dest = curr.next while (dest?.value != destination) { dest = dest?.next } move?.next?.next?.next = dest.next dest.next = move curr = curr.next } var one = curr while (one?.value != 1) { one = one?.next } while (one?.next?.value != 1) { print(one?.next?.value) one = one?.next } println() return 0 } override fun partTwo(): Any { val cups = inputString.split("").mapNotNull { if (it == "") null else LLNode(it.toInt(), null) } for (i in cups.indices) { cups[i].next = cups[(i+1)%cups.size] } var curr: LLNode = cups[8] for (i in 10..1000000) { curr.next = LLNode(i, null) curr = curr.next!! } curr.next = cups[0] curr = curr.next!! var cup_map = mutableMapOf<Int, LLNode>(curr.value to curr) var cc = curr.next!! while (cc != curr) { cup_map[cc.value] = cc cc = cc.next!! } for (i in 1..10000000) { val move = curr.next curr.next = curr.next?.next?.next?.next var destination = if (curr.value == 1) 1000000 else curr.value - 1 while (destination in listOf(move?.value, move?.next?.value, move?.next?.next?.value)) { destination -= 1 if (destination < 1) { destination = 1000000 } } var dest = cup_map[destination] move?.next?.next?.next = dest!!.next dest.next = move curr = curr.next!! } var one = cup_map[1]!! println("${one.next!!.value.toLong() * one.next!!.next!!.value.toLong()}") return 0 } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
2,705
aoc-2020
Creative Commons Zero v1.0 Universal
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[22]括号生成.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。 // // // // 示例 1: // // //输入:n = 3 //输出:["((()))","(()())","(())()","()(())","()()()"] // // // 示例 2: // // //输入:n = 1 //输出:["()"] // // // // // 提示: // // // 1 <= n <= 8 // // Related Topics 字符串 回溯算法 // 👍 1815 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun generateParenthesis(n: Int): List<String> { //递归 val res = ArrayList<String>() if(n == 0) return res generateStr(res,0,0,n,"") return res } private fun generateStr(res: java.util.ArrayList<String>, left: Int, right: Int, n: Int, s: String) { //递归结束条件 if(s.length == n * 2){ res.add(s) return } //逻辑处理 进入下层循环 if(left < n){ generateStr(res,left+1,right,n, "$s(") } if(right < left){ generateStr(res,left,right+1,n, "$s)") } //数据reverse } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,239
MyLeetCode
Apache License 2.0
src/iii_conventions/MyDate.kt
zerezhka
67,052,442
true
{"Kotlin": 83308, "Java": 4952}
package iii_conventions import java.util.* data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { private val value: Int = year * 365 + month * 30 + dayOfMonth override fun compareTo(other: MyDate): Int { return this.value - other.value } infix operator fun times(i: Int): MyDate { return this.addTimeIntervals(TimeInterval.DAY,i) } infix operator fun plus(ti: TimeInterval): MyDate { return this.addTimeIntervals(ti,1) } infix operator fun plus(ti: RepeatedTimeInterval): MyDate { return this.addTimeIntervals(ti.ti,ti.n) } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) enum class TimeInterval { DAY, WEEK, YEAR; private val value: MyDate = if (this == DAY) MyDate(0,0,1) else if (this == WEEK) MyDate(0,0,7) else if (this == YEAR) MyDate(1,0,0) else MyDate(0,0,0) infix operator fun times(i: Int): RepeatedTimeInterval { return RepeatedTimeInterval(this,i) } operator fun plus(ti: TimeInterval): MyDate { return this.value.addTimeIntervals(ti,1) } } class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> { operator fun contains(d: MyDate): Boolean { if (d >= start && d <= endInclusive) return true else return false } override fun iterator(): Iterator<MyDate> = object : Iterator<MyDate> { var current = start override fun hasNext(): Boolean { return current <= endInclusive } override fun next(): MyDate { if (!hasNext()) { throw NoSuchElementException() } val res = current current = current.nextDay() return res } } } class RepeatedTimeInterval(val ti: TimeInterval, val n: Int){ }
0
Kotlin
0
0
4cb3dba98b96ba6b250f898b4b0a5ab2b07c9e3c
1,935
kotlin-koans
MIT License
datastructures/src/main/kotlin/com/kotlinground/datastructures/linkedlists/singly/utils.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.datastructures.linkedlists.singly import java.util.Stack /** * Returns the maximum twin sum of a node and its twin, where a node's twin is at the index (n-1-i) where n is the * number of nodes in the linked list. * For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only * nodes with twins for n = 4. * @return: maximum twin sum of a node and it's twin */ fun maximumPairSum(head: SinglyLinkedListNode<Int>?): Int { if (head == null) { return 0 } var current = head val values = arrayListOf<Int>() while (current != null) { values.add(current.data) current = current.next } var maximumSum = 0 var left = 0 var right = values.size - 1 while (left < right) { maximumSum = maxOf(maximumSum, values[left] + values[right]) left += 1 right -= 1 } return maximumSum } fun maximumPairSumStack(head: SinglyLinkedListNode<Int>?): Int { if (head == null) { return 0 } var pointer = head val stack = Stack<Int>() while (pointer != null) { stack.add(pointer.data) pointer = pointer.next } var current = head var maximumSum = 0 val size = stack.size var count = 1 while (count < size / 2) { maximumSum = maxOf(maximumSum, current?.data!! + stack.pop()) current = current.next count++ } return maximumSum } fun maximumPairSumReverseInPlace(head: SinglyLinkedListNode<Int>?): Int { if (head == null) { return 0 } var slow = head var fast = head while (fast?.next != null) { fast = fast.next?.next slow = slow?.next } var nextNode: SinglyLinkedListNode<Int>? var prev: SinglyLinkedListNode<Int>? = null while (slow != null) { nextNode = slow.next slow.next = prev prev = slow slow = nextNode } var maximumSum = 0 var start = head while (prev != null) { maximumSum = maxOf(maximumSum, start?.data!! + prev.data) prev = prev.next start = start.next } return maximumSum }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
2,196
KotlinGround
MIT License
day9/src/main/kotlin/App.kt
ascheja
317,918,055
false
null
package net.sinceat.aoc2020.day9 import java.util.LinkedList fun main() { val testInput = parseInput("testinput.txt") val testBuffer = RingBuffer.fromSequence(testInput, 5) println(lookForFirstInvalidNumber(testBuffer, testInput)) val input = parseInput("input.txt") val invalidNumber = run { lookForFirstInvalidNumber(RingBuffer.fromSequence(input, 25), input) } println(invalidNumber!!) for (windowSize in 2 .. Integer.MAX_VALUE) { println("sequence length: $windowSize") for (window in input.windowed(windowSize, 1)) { val sum = window.sum() when { sum == invalidNumber -> { println("found it: ${window.minOrNull()!! + window.maxOrNull()!!}") return } sum > invalidNumber -> { break } } } } } fun lookForFirstInvalidNumber(buffer: RingBuffer, input: Sequence<Long>): Long? { for (nr in input.drop(buffer.size)) { if (nr !in buffer.allSums()) { return nr } buffer.add(nr) } return null } fun RingBuffer.allSums() = sequence { for (i in 0 until size) { val first = get(i) for (k in i until size) { val second = get(k) yield(first + second) } } } fun parseInput(fileName: String) = sequence { ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines -> yieldAll(lines.filter(String::isNotBlank).map(String::toLong)) } } class RingBuffer(private val inner: LinkedList<Long>) : List<Long> by inner { fun add(element: Long) { inner.removeFirst() inner.add(element) } companion object { fun fromSequence(sequence: Sequence<Long>, preambleLength: Int): RingBuffer { val preamble = LinkedList(sequence.take(preambleLength).toList()) return RingBuffer(preamble) } } }
0
Kotlin
0
0
f115063875d4d79da32cbdd44ff688f9b418d25e
2,016
aoc2020
MIT License
src/main/kotlin/g0801_0900/s0875_koko_eating_bananas/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0875_koko_eating_bananas // #Medium #Array #Binary_Search #Binary_Search_II_Day_4 // #2023_04_08_Time_267_ms_(93.85%)_Space_37.7_MB_(96.62%) class Solution { fun minEatingSpeed(piles: IntArray, h: Int): Int { var maxP = piles[0] var sumP = 0L for (pile in piles) { maxP = maxP.coerceAtLeast(pile) sumP += pile.toLong() } // binary search var low = ((sumP - 1) / h + 1).toInt() var high = maxP while (low < high) { val mid = low + (high - low) / 2 if (isPossible(piles, mid, h)) { high = mid } else { low = mid + 1 } } return low } private fun isPossible(piles: IntArray, k: Int, h: Int): Boolean { var sum = 0 for (pile in piles) { sum += (pile - 1) / k + 1 } return sum <= h } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
947
LeetCode-in-Kotlin
MIT License
src/main/kotlin/hu/advent/of/code/year2022/day8/Puzzle8B.kt
sztojkatamas
568,512,275
false
{"Kotlin": 157914}
package hu.advent.of.code.year2022.day8 import hu.advent.of.code.AdventOfCodePuzzle import hu.advent.of.code.BaseChallenge @AdventOfCodePuzzle class Puzzle8B: BaseChallenge(2022) { override fun run() { printPuzzleName() loadDataFromFile("data8.txt") val rows = data.makeRows() val cols = data.makeCols() println("The highest scenic score: ${getMaxScenicScore(rows, cols)}") } fun getMaxScenicScore(rows: List<List<Int>>, cols: List<List<Int>>): Int { val width = rows[0].size val height = cols[0].size val scores = mutableSetOf<Int>() for ( x in 1 until width - 1) { for ( y in 1 until height - 1) { val self = rows[x][y] val left = rows[x].take(y) val right = rows[x].takeLast(width - y - 1) val top = cols[y].take(x) val bottom = cols[y].takeLast(height - x - 1) val maxes = listOf(top.max(), bottom.max(), left.max(), right.max()) if (self > maxes.min()) { // when visible scores.add( top.reversed().viewDistance(self) * bottom.viewDistance(self) * left.reversed().viewDistance(self) * right.viewDistance(self) ) } } } return scores.max() } } fun List<Int>.viewDistance(num: Int): Int { return when { (num > this.max()) -> this.size else -> this.indexOfFirst { it >= num } + 1 } }
0
Kotlin
0
0
6aa9e53d06f8cd01d9bb2fcfb2dc14b7418368c9
1,607
advent-of-code-universe
MIT License
app/src/main/java/eu/kanade/tachiyomi/data/animelib/AnimelibUpdateRanker.kt
terabyte25
432,093,270
true
{"Kotlin": 3156741}
package eu.kanade.tachiyomi.data.animelib import eu.kanade.tachiyomi.data.database.models.Anime import java.util.Collections import kotlin.math.abs /** * This class will provide various functions to rank manga to efficiently schedule manga to update. */ object AnimelibUpdateRanker { val rankingScheme = listOf( (this::lexicographicRanking)(), (this::latestFirstRanking)(), (this::nextFirstRanking)() ) /** * Provides a total ordering over all the Mangas. * * Orders the manga based on the distance between the next expected update and now. * The comparator is reversed, placing the smallest (and thus closest to updating now) first. */ fun nextFirstRanking(): Comparator<Anime> { val time = System.currentTimeMillis() return Collections.reverseOrder( Comparator { animeFirst: Anime, animeSecond: Anime -> compareValues(abs(animeSecond.next_update - time), abs(animeFirst.next_update - time)) } ) } /** * Provides a total ordering over all the [Manga]s. * * Assumption: An active [Manga] mActive is expected to have been last updated after an * inactive [Manga] mInactive. * * Using this insight, function returns a Comparator for which mActive appears before mInactive. * @return a Comparator that ranks manga based on relevance. */ private fun latestFirstRanking(): Comparator<Anime> = Comparator { first: Anime, second: Anime -> compareValues(second.last_update, first.last_update) } /** * Provides a total ordering over all the [Anime]s. * * Order the manga lexicographically. * @return a Comparator that ranks manga lexicographically based on the title. */ private fun lexicographicRanking(): Comparator<Anime> = Comparator { first: Anime, second: Anime -> compareValues(first.title, second.title) } }
0
Kotlin
0
1
e793c6cd156ba4185d3ce23be976b61e12924ed3
2,001
aniyomi
Apache License 2.0
src/main/kotlin/com/dragbone/pizzabot/PizzaVoteParser.kt
dragbone
68,312,794
false
null
package com.dragbone.pizzabot import java.text.ParseException class PizzaVoteParser { companion object { private val dayMap: Map<String, DayOfWeek> = mapOf( "mo" to DayOfWeek.MONDAY, "di" to DayOfWeek.TUESDAY, "tu" to DayOfWeek.TUESDAY, "mi" to DayOfWeek.WEDNESDAY, "we" to DayOfWeek.WEDNESDAY, "do" to DayOfWeek.THURSDAY, "th" to DayOfWeek.THURSDAY, "fr" to DayOfWeek.FRIDAY, "sa" to DayOfWeek.SATURDAY, "so" to DayOfWeek.SUNDAY, "su" to DayOfWeek.SUNDAY ) val noneList: Set<String> = setOf("none", "null", "{}", "()", "[]", "nada", "never", "nope", ":-(", ":'-(") } fun mapToDay(day: String): DayOfWeek = dayMap[day.toLowerCase().substring(0, 2)]!! fun parsePizzaVote(input: String): Set<Vote> { if (noneList.contains(input.trim())) return emptySet() //remove all superfluous whitespace val cleanInput = input.replace(Regex("\\s*-\\s*"), "-").replace(Regex("\\(\\s*"), "(").replace(Regex("\\s*\\)"), ")") // Split on whitespaces and comma and remove all empty sections val sections = cleanInput.split(Regex("[\\s,]")).filter { it.length > 0 } // Map sections to votes val votes = sections.flatMap { parsePizzaVoteSection(it) } if (votes.groupBy { it.day }.any { it.value.count() > 1 }) throw IllegalArgumentException("You can't fool me with your double votes!") return votes.toSet() } private fun parsePizzaVoteSection(input: String): Iterable<Vote> { val strength = if (input.matches(Regex("\\(.+\\)"))) 0.5f else 1f val trimmed = input.trim('(', ')') if (trimmed.contains('-')) { val startEnd = trimmed.split('-') val start = mapToDay(startEnd[0]) val end = mapToDay(startEnd[1]) if (start >= end) throw ParseException("End before start in '$input'", 0) return (start.ordinal..end.ordinal).map { Vote(DayOfWeek.of(it), strength) } } return listOf(Vote(mapToDay(trimmed), strength)) } }
0
Kotlin
3
2
9d5757a5f74e627cc8db74202c9d7f7a959c8d7a
2,237
slacking-pizzabot
Apache License 2.0
src/iii_conventions/MyDate.kt
JeffreyRuder
75,589,618
false
null
package iii_conventions import java.util.* data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { if (this.year == other.year && this.month == other.month && this.dayOfMonth == other.dayOfMonth) { return 0 } else if (this.year < other.year) { return -1 } else if (this.year > other.year) { return 1 } else { if (this.month < other.month) { return -1 } else if (this.month > other.month) { return 1 } else { if (this.dayOfMonth < other.dayOfMonth) { return -1 } else { return 1 } } } } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) operator fun MyDate.plus(timeInterval: TimeInterval): MyDate = this.addTimeIntervals(timeInterval, 1) operator fun MyDate.plus(repeatedTimeInterval: RepeatedTimeInterval): MyDate = this.addTimeIntervals(repeatedTimeInterval.ti, repeatedTimeInterval.n) enum class TimeInterval { DAY, WEEK, YEAR } class RepeatedTimeInterval(val ti: TimeInterval, val n: Int) operator fun TimeInterval.times(n: Int): RepeatedTimeInterval = RepeatedTimeInterval(this, n) class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> { override fun iterator(): Iterator<MyDate> { return DateIterator(this) } } class DateIterator(val dateRange: DateRange) : Iterator<MyDate> { var date: MyDate = dateRange.start override fun hasNext(): Boolean { return date <= dateRange.endInclusive } override fun next(): MyDate { val result = date date = date.nextDay() return result } }
0
Kotlin
0
0
be230f075332880560ccf689152681cbd1778fac
1,904
kotlin-koans
MIT License
src/main/kotlin/com/dambra/adventofcode2018/day4/GuardPost.kt
pauldambra
159,939,178
false
null
package com.dambra.adventofcode2018.day4 import java.time.LocalDateTime class GuardPost(guardEvents: List<GuardEvent>) { var bestGuardStrategyOne: Int = 0 private set var bestGuardStrategyTwo: Int = 0 private set private val guards = mutableMapOf<String, MutableList<Int>>() init { var fellAsleep: LocalDateTime? = null for (e in guardEvents) { when (e) { is ShiftStarted -> guards.putIfAbsent(e.id, mutableListOf()) is GuardFellAsleep -> fellAsleep = e.eventDateTime is GuardWokeUp -> trackMinutesAsleep(e, fellAsleep) else -> throw Exception("impossible event") } } guardThatSpentLongestAsleep(guards) guardThatSleptMostOnAnyParticularMinute(guards) } private fun trackMinutesAsleep(ge: GuardEvent, fellAsleep: LocalDateTime?) { var current = fellAsleep!! while (!current.isEqual(ge.eventDateTime)) { this.guards[ge.id]!!.add(current.minute) current = current.plusMinutes(1) } } private fun guardThatSleptMostOnAnyParticularMinute(guards: MutableMap<String, MutableList<Int>>) { val guardMinuteFrequency = guards .filter { it.value.isNotEmpty() } .map { val minuteFrequencyForGuard = it.value .groupingBy { m -> m } .eachCount() .toList() it.key to minuteFrequencyForGuard.maxBy { x -> x.second }!! } .maxBy { it.second.second }!! println("guard that is most frequently asleep on a given minute is ${guardMinuteFrequency.first}") println("that minute is ${guardMinuteFrequency.second}") val mostFrequentAsleepMinute = Pair(guardMinuteFrequency.first, guardMinuteFrequency.second.first) bestGuardStrategyTwo = mostFrequentAsleepMinute.first.toInt() * mostFrequentAsleepMinute.second } private fun guardThatSpentLongestAsleep(guards: MutableMap<String, MutableList<Int>>) { val guardMostAsleep = guards.maxBy { it.value.size }!! println("guard most asleep was ${guardMostAsleep.key}") val minuteAsleepFreq = guards[guardMostAsleep.key]!! .groupingBy { it }.eachCount() .toList() .sortedByDescending { (_, v) -> v } .first() .first println("the minute they slept most was ${minuteAsleepFreq}") val longestSleepingGuardBestMinute = Pair(guardMostAsleep.key, minuteAsleepFreq) bestGuardStrategyOne = longestSleepingGuardBestMinute.first.toInt() * longestSleepingGuardBestMinute.second } }
0
Kotlin
0
1
7d11bb8a07fb156dc92322e06e76e4ecf8402d1d
2,729
adventofcode2018
The Unlicense
src/main/kotlin/cn/noisyfox/kotlin/itertools/Combination.kt
Noisyfox
90,817,761
false
null
/* * Copyright 2017 Noisyfox. * * 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 cn.noisyfox.kotlin.itertools /** * Created by Noisyfox on 2017/5/12. */ /** * Cartesian product of input iterables. * * The nested loops cycle like an odometer with the rightmost element advancing on every iteration. * This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, * the product tuples are emitted in sorted order. */ fun <T1, T2> Iterable<T1>.product(other: Iterable<T2>): Iterable<Pair<T1, T2>> { val result = mutableListOf<Pair<T1, T2>>() for (left in this) { other.mapTo(result) { Pair(left, it) } } return result } /** * Cartesian product of input iterables. * * The nested loops cycle like an odometer with the rightmost element advancing on every iteration. * This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, * the product tuples are emitted in sorted order. */ fun <T> Iterable<T>.product(): Iterable<Pair<T, T>> = this.product(this) /** * Return successive 2 length permutations of elements in the iterable. */ fun <T> Iterable<T>.permutations(): Iterable<Pair<T, T>> { val result = mutableListOf<Pair<T, T>>() for ((i1, v1) in this.withIndex()) { this .filterIndexed { i2, _ -> i1 != i2 } .mapTo(result) { Pair(v1, it) } } return result } /** * Return 2 length subsequences of elements from the input iterable. * * Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, * the combination tuples will be produced in sorted order. * * Elements are treated as unique based on their position, not on their value. * So if the input elements are unique, there will be no repeat values in each combination. */ fun <T> Iterable<T>.combinations(): Iterable<Pair<T, T>> { val result = mutableListOf<Pair<T, T>>() for ((i1, v1) in this.withIndex()) { this.drop(i1 + 1).mapTo(result) { Pair(v1, it) } } return result } /** * Return 2 length subsequences of elements from the input iterable allowing individual elements to be repeated more than once. * * Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, * the combination tuples will be produced in sorted order. * * Elements are treated as unique based on their position, not on their value. * So if the input elements are unique, there will be no repeat values in each combination. */ fun <T> Iterable<T>.combinationsWithReplacement(): Iterable<Pair<T, T>> { val result = mutableListOf<Pair<T, T>>() for ((i1, v1) in this.withIndex()) { this.drop(i1).mapTo(result) { Pair(v1, it) } } return result }
0
Kotlin
1
0
6efbba6c4126f45ba4cd23ef8d22e7871fdaef65
3,335
itertools-kotlin
Apache License 2.0
aoc2022/app/src/main/kotlin/aoc2022/Day15.kt
resurtm
574,518,237
false
null
// MIT License // // Copyright (c) 2022 <EMAIL> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package aoc2022 import java.io.File import kotlin.math.abs fun solveDay15() { val day15Solution1 = Day15Solution(DataFileType.EXAMPLE) day15Solution1.readFile() day15Solution1.solvePart1(10) day15Solution1.solvePart2(20) val day15Solution2 = Day15Solution(DataFileType.GITHUB) day15Solution2.readFile() day15Solution2.solvePart1(2000000) day15Solution2.solvePart2(4000000) val day15Solution3 = Day15Solution(DataFileType.GOOGLE) day15Solution3.readFile() day15Solution3.solvePart1(2000000) day15Solution3.solvePart2(4000000) } private class Day15Solution(val dft: DataFileType) { fun solvePart2(maxNeededY: Int) { for (neededY in 0..maxNeededY) { intervals.clear() sensors.forEach { sensor -> calcInterval(sensor, neededY)?.let { intervals.add(it) } } val merged = mergedIntervals() if (merged.size > 1) { val xCoord = merged.first().second.toLong() + 1L val result = xCoord * 4000000 + neededY println("Day 15. Data file type: ${dft}/${dft.value}. Part 2: $result.") break } } } fun solvePart1(neededY: Int) { sensors.forEach { sensor -> calcInterval(sensor, neededY)?.let { intervals.add(it) } } val merged = mergedIntervals() val result = merged.first().second - merged.first().first println("Day 15. Data file type: ${dft}/${dft.value}. Part 1: $result.") } private fun mergedIntervals(): MutableList<Pair<Int, Int>> { val intvals = intervals.sortedWith(IntervalComparator) val merged = mutableListOf(intvals[0].copy()) for (interval in intvals) { val last = merged.last() if ( last.first <= interval.first && last.second >= interval.first && last.second <= interval.second ) { merged[merged.size - 1] = Pair(last.first, interval.second) } else if ( last.first <= interval.first && last.second >= interval.second ) { // do nothing } else if ( last.first >= interval.first && last.second <= interval.second ) { merged[merged.size - 1] = interval.copy() } else { merged.add(interval.copy()) } } return merged } private fun calcInterval(sen: Sensor, neededY: Int): Pair<Int, Int>? { val coverage = abs(sen.pos.x - sen.beacon.x) + abs(sen.pos.y - sen.beacon.y) val yDist = abs(sen.pos.y - neededY) if (yDist > coverage) return null return Pair(sen.pos.x - (coverage - yDist), sen.pos.x + (coverage - yDist)) } fun readFile() = File(getDataFilePath(15, dft)).forEachLine { parseLine(it) } private fun parseLine(inputLine: String) { val matchResult = lineRegex.matchEntire(inputLine) ?: return val sensorX = matchResult.groups[1]?.value?.toInt() ?: return val sensorY = matchResult.groups[2]?.value?.toInt() ?: return val closestBeaconX = matchResult.groups[3]?.value?.toInt() ?: return val closestBeaconY = matchResult.groups[4]?.value?.toInt() ?: return val sensor = Sensor(pos = Point(sensorX, sensorY), beacon = Point(closestBeaconX, closestBeaconY)) sensors = sensors.plus(sensor) } private var sensors = emptyList<Sensor>() private val intervals = mutableListOf<Pair<Int, Int>>() private val lineRegex = Regex( "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)" ) private data class Sensor(val pos: Point, val beacon: Point) private data class Point(val x: Int = 0, val y: Int = 0) private class IntervalComparator { companion object : Comparator<Pair<Int, Int>> { override fun compare(a: Pair<Int, Int>, b: Pair<Int, Int>): Int { val second = if (a.second == b.second) 0 else if (a.second < b.second) -1 else 1 return if (a.first == b.first) second else if (a.first < b.first) -1 else 1 } } } }
0
Kotlin
0
0
145ad55e3c5b475ab343ea95c68f7b9d683e4f87
5,479
AdventOfCode
MIT License
src/com/ncorti/aoc2022/Day04.kt
cortinico
571,724,497
false
{"Kotlin": 5773}
package com.ncorti.aoc2022 private fun String.processInput() = split("\n") .map { it.split(",") } .map { (p1, p2) -> val pair1 = p1.split("-") val pair2 = p2.split("-") listOf(pair1[0].toInt(), pair1[1].toInt(), pair2[0].toInt(), pair2[1].toInt()) } fun main() { fun part1() = getInputAsText("04", String::processInput) .count { (p1l, p1r, p2l, p2r) -> (p2l in p1l..p1r && p2r in p1l..p1r) || (p1l in p2l..p2r && p1r in p2l..p2r) } fun part2() = getInputAsText("04", String::processInput) .count { (p1l, p1r, p2l, p2r) -> !(p2l > p1r || p2r < p1l) } println(part1()) println(part2()) }
4
Kotlin
0
1
cd9ad108a1ed1ea08f9313c4cad5e52a200a5951
644
adventofcode-2022
MIT License
src/main/kotlin/aoc2021/Day07.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2021 import utils.InputUtils import kotlin.math.absoluteValue fun main() { val testInput = """16,1,2,0,4,2,7,1,2,14""".split("\n") fun part1(input: List<String>): Int { val items = input[0].split(",").map { it.toInt() } return (items.min()..items.max()).minOf { pivot -> items.sumOf { (it - pivot).absoluteValue } } } fun triangle(i: Int) = (i * (i + 1)) / 2 fun part2(input: List<String>): Int { val items = input[0].split(",").map { it.toInt() } return (items.min()..items.max()).minOf { pivot -> items.sumOf { triangle((it - pivot).absoluteValue) } } } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 37) val puzzleInput = InputUtils.downloadAndGetLines(2021, 7) val input = puzzleInput.toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
947
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/homework5/hashTable/HashTable.kt
samorojy
340,891,499
false
null
package homework5.hashTable class HashTable<K, V>(private var hashFunction: HashFunction<K>) { companion object { const val MAX_LOAD_FACTOR = 0.7 } data class HashElement<K, V>(val key: K, var value: V) private var elementCount = 0 private var bucketCount = 1 private val loadFactor: Double get() { return elementCount / bucketCount.toDouble() } private var buckets = Array(bucketCount) { mutableListOf<HashElement<K, V>>() } fun add(key: K, value: V) { val hash = hashFunction.getHash(key) % bucketCount val element = buckets[hash].find { key == it.key } if (element != null) { if (value != element.value) { element.value = value } } else { buckets[hash].add(HashElement(key, value)) ++elementCount } if (loadFactor >= MAX_LOAD_FACTOR) { this.expand() } } private fun expand() { bucketCount *= 2 rewriteHashTable(bucketCount) } private fun rewriteHashTable(newSize: Int = bucketCount) { val newBuckets = Array(newSize) { mutableListOf<HashElement<K, V>>() } buckets.forEach { list -> list.forEach { hashElement -> val hash = hashFunction.getHash(hashElement.key) % (newSize) newBuckets[hash].add(hashElement) } } buckets = newBuckets } operator fun get(key: K): V? { val hash = hashFunction.getHash(key) % bucketCount return buckets[hash].find { key == it.key }?.value } fun remove(key: K): Boolean { val hash = hashFunction.getHash(key) % (bucketCount) val element = buckets[hash].find { key == it.key } if (element != null) { buckets[hash].remove(element) --elementCount } return element != null } fun contains(key: K): Boolean { val hash = hashFunction.getHash(key) % bucketCount return buckets[hash].find { key == it.key } != null } fun changeHashFunction(newHashFunction: HashFunction<K>) { hashFunction = newHashFunction rewriteHashTable() } fun getStatistic(): Map<String, Any> { var numberOfConflicts = 0 var maximumBucketLength = 0 buckets.forEach { if (it.size > 1) { ++numberOfConflicts } if (it.size > maximumBucketLength) { maximumBucketLength = it.size } } return mapOf( "Element count" to this.elementCount, "Bucket count" to this.bucketCount, "Load factor" to this.loadFactor, "Current Hash function" to this.hashFunction.name, "Conflicts number" to numberOfConflicts, "Maximum bucket length" to maximumBucketLength ) } }
0
Kotlin
0
0
d77c0af26cb55c74ae463f59244de233133b2320
2,926
spbu_kotlin_course
Apache License 2.0
subprojects/gradle/performance/src/main/kotlin/com/avito/performance/PerformanceTestComparator.kt
sundetova
287,793,131
true
{"Kotlin": 2450349, "Shell": 16022, "Python": 14063, "Dockerfile": 7151, "Makefile": 2131}
package com.avito.performance import com.avito.performance.stats.Stats import com.avito.performance.stats.compare.TestForComparing import com.avito.performance.stats.comparison.ComparedTest import com.avito.report.model.PerformanceTest import java.util.Collections.singletonList internal class PerformanceTestComparator(private val stats: Stats) { fun compare( currentTests: List<PerformanceTest>, previousTests: List<PerformanceTest> ): List<ComparedTest.Comparison> { return getTestsForComparing(currentTests, previousTests) .asSequence() .map { stats.compare(singletonList(it)) .get() .map { comparedResult -> ComparedTest.Comparison( comparedResult.testName, currentTests.find { it.testName == comparedResult.testName }!!.id, comparedResult.series ) } } .toList() .flatten() } private fun getTestsForComparing( currentTests: List<PerformanceTest>, previousTests: List<PerformanceTest> ): List<TestForComparing> { return currentTests.mapNotNull { currentTest -> previousTests.find { it.testName == currentTest.testName }?.let { previousTest -> currentTest.series.mapNotNull { metricToSeries -> val currentSeries = metricToSeries.value val previousSeries = previousTest.series[metricToSeries.key] if (previousSeries == null) { null } else { metricToSeries.key to TestForComparing.Series( previousSeries, currentSeries, SIGNIFICANCE ) } }.toMap() .let { series -> TestForComparing(currentTest.testName, series) } } }.toList() } } private const val SIGNIFICANCE = 0.05
0
Kotlin
1
0
eec301953e12f7e7b93b3ce09965b58f26373bbd
2,199
avito-android
MIT License
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day04.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2022 import com.dvdmunckhof.aoc.splitOnce import com.dvdmunckhof.aoc.toRange class Day04(private val input: List<String>) { fun solvePart1(): Int { return solve().count { (rangeA, rangeB) -> rangeA.contains(rangeB) || rangeB.contains(rangeA) } } fun solvePart2(): Int { return solve().count { (rangeA, rangeB) -> rangeA.overlaps(rangeB) || rangeB.overlaps(rangeA) } } private fun solve(): List<Pair<IntRange, IntRange>> { return input.map { pair -> val (partA, partB) = pair.splitOnce(",") partA.toRange() to partB.toRange() } } private fun IntRange.contains(other: IntRange): Boolean = this.contains(other.first) && this.contains(other.last) private fun IntRange.overlaps(other: IntRange): Boolean = this.contains(other.first) || this.contains(other.last) }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
886
advent-of-code
Apache License 2.0
src/main/kotlin/Puzzle14.kt
namyxc
317,466,668
false
null
import java.math.BigInteger import kotlin.math.pow object Puzzle14 { @JvmStatic fun main(args: Array<String>) { val input = Puzzle14::class.java.getResource("puzzle14.txt").readText() val program1 = Program(input) program1.run() println(program1.sumOfUsedMemoryAddresses()) val program2 = Program(input) program2.runV2() println(program2.sumOfUsedMemoryAddresses()) } class Program(input: String) { private val subPrograms = mutableListOf<SubProgram>() private val memory = HashMap<BigInteger, BigInteger>() private val memorySetterRegex = "^mem\\[(\\d+)\\] = (\\d+)$".toRegex() init { input.split("\n").forEach { line -> if (line.startsWith("mask = ")){ val mask = line.split(" = ")[1] subPrograms.add(SubProgram(mask)) }else{ val matchResult = memorySetterRegex.find(line) val memAddress = matchResult?.groups?.get(1)?.value!!.toInt() val memValue = matchResult.groups[2]?.value!!.toInt() subPrograms.last().addStatement(memAddress, memValue) } } } class SubProgram(private val mask: String) { private val statements = mutableListOf<Pair<Int, Int>>() private val memory = HashMap<BigInteger, BigInteger>() fun addStatement(memAddress: Int, memValue: Int){ statements.add(Pair(memAddress, memValue)) } fun run(): HashMap<BigInteger, BigInteger>{ statements.forEach { s -> val address = s.first.toBigInteger() val originalValue = s.second.toString(2).padStart(mask.length, '0') val maskedValue = mutableListOf<Char>() for (i in mask.length-1 downTo 0){ val maskValue = mask[i] val value = originalValue[i] maskedValue.add(0, if (maskValue == 'X') value else maskValue) } memory[address] = maskedValue.joinToString("").toBigInteger(2) } return memory } fun runV2(): HashMap<BigInteger, BigInteger>{ statements.forEach { s -> val originalAddress = s.first.toString(2).padStart(mask.length, '0') val value = s.second.toBigInteger() val maskedAddress = mutableListOf<Char>() for (i in mask.length-1 downTo 0){ val maskValue = mask[i] val address = originalAddress[i] maskedAddress.add(0, when (maskValue) { '0' -> address '1' -> '1' else -> 'F' } ) } val floatingBitCount = maskedAddress.count { it == 'F' } for (i in 0..(2.toDouble().pow(floatingBitCount.toDouble()).toInt())){ val number = i.toString(2).padStart(floatingBitCount, '0') val floatedAddress = mutableListOf<Char>() var numberIndex = 0 for (char in maskedAddress){ if (char == 'F'){ floatedAddress.add(number[numberIndex]) numberIndex++ }else{ floatedAddress.add(char) } } memory[floatedAddress.joinToString("").toBigInteger(2)] = value } } return memory } } fun run(){ subPrograms.forEach { subProgram -> val subProgramMemory = subProgram.run() subProgramMemory.forEach { (address, value) -> memory[address] = value } } } fun runV2(){ subPrograms.forEach { subProgram -> val subProgramMemory = subProgram.runV2() subProgramMemory.forEach { (address, value) -> memory[address] = value } } } fun sumOfUsedMemoryAddresses() = memory.filter { it.value != BigInteger.ZERO }.values.sumOf { it } } }
0
Kotlin
0
0
60fa6991ac204de6a756456406e1f87c3784f0af
4,651
adventOfCode2020
MIT License
Round 2 - A. Fresh Chocolate/src/app.kt
amirkhanyana
110,548,909
false
{"Kotlin": 20514}
import java.util.* fun main(args: Array<String>) { val input = Scanner(System.`in`) val T = input.nextInt() var Ti = 1 while (Ti <= T) { val N = input.nextInt() val P = input.nextInt() val groups = IntArray(N, { input.nextInt() % P }) val modedGroups = IntArray(P) for (group in groups) { modedGroups[group]++ } println("Case #$Ti: " + Solver(modedGroups, P).run()) ++Ti } } class Solver(private val modedGroups: IntArray, private val P: Int) { private val groupStore = IntArray(P) private var maxGroups = 0 fun run(): Int { for (i in 2..P) { solve(P, i) } maxGroups += modedGroups[0] modedGroups[0] = 0 return maxGroups + if (modedGroups.any({ it != 0 })) 1 else 0 } private fun solve(sum: Int, numberOfGroupsToUse: Int) { if (numberOfGroupsToUse == 1) { groupStore[sum]++ val min = (1 until P) .filter { groupStore[it] != 0 } .map { modedGroups[it] / groupStore[it] }.min()?: P if (min > 0) { maxGroups += min for (i in 1 until P) { modedGroups[i] -= min * groupStore[i] } } groupStore[sum]-- return } for (i in 1 until P) { if (i == sum) continue groupStore[i]++ solve((sum + P - i) % P, numberOfGroupsToUse - 1) groupStore[i]-- } } }
0
Kotlin
0
0
25a8e6dbd5843e9d4a054d316acc9d726995fffe
1,576
Google-Code-Jam-2017-Problem-Kotlin-Solutions
The Unlicense
src/Day01.kt
0xBuro
572,308,139
false
{"Kotlin": 4929}
fun main() { fun elfNotes(input: String): List<List<Int>> { return input.split("\n\n") .map { singleElf -> singleElf.lines() .map { it.toInt() } } } fun part1(input: String): Int { val elvesCarry = elfNotes(input) return elvesCarry.maxOf { it.sum() } } fun part2(input: String): Int { val elvesCarry = elfNotes(input) return elvesCarry .map { it.sum() } .sortedDescending() .take(3) .sum() } //val testInput = readInput("input") //check(part1(testInput) == 24000) val input = readInput("input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c05c4db78e24fc36f6f112bc1e8cf24ad5fd7698
707
Advent-of-Kotlin
Apache License 2.0
2018/kotlin/day22p2/src/main.kt
sgravrock
47,810,570
false
{"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488}
import java.lang.Exception import kotlin.math.min import kotlin.system.measureTimeMillis fun main(args: Array<String>) { val millis = measureTimeMillis { println(Cave(9171, 7, 721).fewestMinutesToTarget()) } println("in ${millis}ms") } data class Coord(val x: Int, val y: Int) enum class Region { Rocky, Narrow, Wet } enum class Tool { Torch, ClimbingGear, None } interface ICave { val depth: Int fun regionType(pos: Coord): Region; } class Cave(override val depth: Int, val targetX: Int, val targetY: Int) : ICave { private val memo = mutableMapOf<Coord, Int>() fun fewestMinutesToTarget(): Int { var bestToTarget = Int.MAX_VALUE val best = mutableMapOf<SearchState, Int>() val pending = mutableMapOf<SearchState, Int>() pending[SearchState(Coord(0, 0), Tool.Torch)] = 0 while (pending.isNotEmpty()) { val (cur, curMinutes) = pending.asSequence().first() pending.remove(cur) if (best.getOrDefault(cur, Int.MAX_VALUE) <= curMinutes || bestToTarget <= curMinutes) { continue } best[cur] = curMinutes if (cur.pos.x == targetX && cur.pos.y == targetY) { val toolChangeMinutes = if (cur.tool == Tool.Torch) 0 else 7 bestToTarget = min(bestToTarget, curMinutes + toolChangeMinutes) continue } for (n in cur.neighbors(this)) { val toolChangeMinutes = if (n.tool == cur.tool) 0 else 7 val minutes = curMinutes + toolChangeMinutes + 1 if (minutes < pending.getOrDefault(n, Int.MAX_VALUE)) { pending[n] = minutes } } } assert(bestToTarget != Int.MAX_VALUE) return bestToTarget } override fun regionType(pos: Coord): Region { if (pos.x == targetX && pos.y == targetY) { return Region.Rocky } return when (erosionLevel(pos) % 3) { 0 -> Region.Rocky 1 -> Region.Wet 2 -> Region.Narrow else -> throw Exception("Can't happen") } } private fun erosionLevel(pos: Coord): Int { return memo.getOrPut(pos, { (geologicIndex(pos) + depth) % 20183 }) } private fun geologicIndex(pos: Coord): Int { return if (pos.x == 0) { pos.y * 48271 } else if (pos.y == 0) { pos.x * 16807 } else { erosionLevel(Coord(pos.x - 1, pos.y)) * erosionLevel(Coord(pos.x, pos.y - 1)) } } } data class SearchState(val pos: Coord, val tool: Tool) { fun neighbors(cave: ICave): List<SearchState> { val region = cave.regionType(pos) val result = mutableListOf<SearchState>() val tools = Tool.values() for (x in -1..1) { for (y in -1..1) { if ((x == 0) xor (y == 0)) { val n = Coord(pos.x + x, pos.y + y) if (n.x >= 0 && n.y >= 0 && n.y < cave.depth) { for (t in tools) { if (canUseTool(t, region) && canUseTool(t, cave.regionType(n))) { result.add(SearchState(n, t)) } } } } } } return result } } fun canUseTool(t: Tool, r: Region): Boolean { return t != when (r) { Region.Rocky -> Tool.None Region.Wet -> Tool.Torch Region.Narrow -> Tool.ClimbingGear } }
0
Rust
0
0
ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3
3,681
adventofcode
MIT License
src/main/kotlin/aoc2023/Day16.kt
Ceridan
725,711,266
false
{"Kotlin": 110767, "Shell": 1955}
package aoc2023 import kotlin.math.max class Day16 { fun part1(input: String): Int { val grid = parseInput(input) return calculateConfiguration(grid, DirectedPoint(0 to 0, 'E')) } fun part2(input: String): Int { val grid = parseInput(input) val maxY = grid.keys.maxOf { it.y } val maxX = grid.keys.maxOf { it.x } var bestConfigurationScore = 0 val cache = mutableMapOf<DirectedPoint, Triple<DirectedPoint?, DirectedPoint?, Set<Point>>>() for (y in 0..maxY) { bestConfigurationScore = max(bestConfigurationScore, calculateConfiguration(grid, DirectedPoint(y to 0, 'E'), cache)) bestConfigurationScore = max(bestConfigurationScore, calculateConfiguration(grid, DirectedPoint(y to maxX, 'W'), cache)) } for (x in 0..maxX) { bestConfigurationScore = max(bestConfigurationScore, calculateConfiguration(grid, DirectedPoint(0 to x, 'S'), cache)) bestConfigurationScore = max(bestConfigurationScore, calculateConfiguration(grid, DirectedPoint(maxY to x, 'N'), cache)) } return bestConfigurationScore } private fun calculateConfiguration( grid: Map<Point, Char>, entryBeam: DirectedPoint, cache: MutableMap<DirectedPoint, Triple<DirectedPoint?, DirectedPoint?, Set<Point>>> = mutableMapOf() ): Int { val energized = mutableSetOf<Point>() val known = mutableSetOf<DirectedPoint>() val queue = ArrayDeque(listOf(entryBeam)) while (queue.isNotEmpty()) { val beam = queue.removeFirst() if (known.contains(beam)) continue known.add(beam) val (beam1, beam2, beamEnergized) = cache.getOrPut(beam) { followBeamUntilSplit(grid, beam) } energized.addAll(beamEnergized) beam1?.let { queue.add(beam1) } beam2?.let { queue.add(beam2) } } return energized.size } private fun followBeamUntilSplit( grid: Map<Point, Char>, beam: DirectedPoint ): Triple<DirectedPoint?, DirectedPoint?, Set<Point>> { val energized = mutableSetOf<Point>() var current = beam while (grid.containsKey(current.point)) { energized.add(current.point) val cell = grid[current.point] if (cell == '.') { current = current.move(current.direction) continue } current = when (current.direction) { 'N' -> when (cell) { '\\' -> current.move('W') '/' -> current.move('E') '|' -> current.move('N') else -> return Triple(current.move('W'), current.move('E'), energized) } 'W' -> when (cell) { '\\' -> current.move('N') '/' -> current.move('S') '-' -> current.move('W') else -> return Triple(current.move('N'), current.move('S'), energized) } 'S' -> when (cell) { '\\' -> current.move('E') '/' -> current.move('W') '|' -> current.move('S') else -> return Triple(current.move('E'), current.move('W'), energized) } 'E' -> when (cell) { '\\' -> current.move('S') '/' -> current.move('N') '-' -> current.move('E') else -> return Triple(current.move('S'), current.move('N'), energized) } else -> throw IllegalArgumentException("Unkwnon direction ${current.direction}") } } return Triple(null, null, energized) } private fun parseInput(input: String): Map<Point, Char> { val grid = mutableMapOf<Point, Char>() val lines = input.split('\n').filter { it.isNotEmpty() } for (y in lines.indices) { for (x in lines[y].indices) { grid[y to x] = lines[y][x] } } return grid } data class DirectedPoint(val point: Point, val direction: Char) { fun move(newDirection: Char) = DirectedPoint(point + DIRECTION_TRANSFORMS[newDirection]!!, newDirection) private companion object { val DIRECTION_TRANSFORMS = mapOf( 'N' to Pair(-1, 0), 'W' to Pair(0, -1), 'S' to Pair(1, 0), 'E' to Pair(0, 1), ) } } } fun main() { val day16 = Day16() val input = readInputAsString("day16.txt") println("16, part 1: ${day16.part1(input)}") println("16, part 2: ${day16.part2(input)}") }
0
Kotlin
0
0
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
4,856
advent-of-code-2023
MIT License
solutions/src/SumOfAbsoluteDifferences.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/ */ class SumOfAbsoluteDifferences { fun getSumAbsoluteDifferences(nums: IntArray): IntArray { val returnArray = IntArray(nums.size) val numsSolutions = mutableMapOf<Int,Int>() val numsSorted = nums.sorted(); var sum = 0 val sumAt = mutableListOf<Int>() for (i in numsSorted.indices) { sum+=numsSorted[i] sumAt.add( sum) } for (i in numsSorted.indices) { val numToTest = numsSorted[i] var differenceSum = 0 if (i-1 >= 0) { val lowerDiff = (numToTest*i) - sumAt[i-1] differenceSum+=lowerDiff } if (i+1 < numsSorted.size) { val higerDiff = ((sumAt[sumAt.lastIndex]-sumAt[i]) - (numToTest*(numsSorted.lastIndex-i))) differenceSum+= higerDiff } numsSolutions[numToTest] = differenceSum } return nums.map { numsSolutions[it]!! }.toIntArray() } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,094
leetcode-solutions
MIT License
src/Day06.kt
hrach
572,585,537
false
{"Kotlin": 32838}
fun main() { fun part1(input: List<String>): Int { val m = input.first() m.windowedSequence(4, 1).forEachIndexed { index, s -> if (s.toSet().size == 4) return index + 4 } error("e") } fun part2(input: List<String>): Int { val m = input.first() m.windowedSequence(14, 1).forEachIndexed { index, s -> if (s.toSet().size == 14) return index + 14 } error("e") } val testInput = readInput("Day06_test") check(part1(listOf("mjqjpqmgbljsphdztnvjfqwrcgsmlb")), 7) check(part1(listOf("bvwbjplbgvbhsrlpgdmjqwftvncz")), 5) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
40b341a527060c23ff44ebfe9a7e5443f76eadf3
720
aoc-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumWindowSubstring.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 /** * 76. Minimum Window Substring * @see <a href="https://leetcode.com/problems/minimum-window-substring/">Source</a> */ fun interface MinimumWindowSubstring { operator fun invoke(str: String, target: String): String } /** * Approach 1: Sliding Window */ class MWSSlidingWindow : MinimumWindowSubstring { override fun invoke(str: String, target: String): String { if (str.isEmpty() || target.isEmpty()) { return "" } val charFrequencyMap = IntArray(LIMIT) for (c in target.toCharArray()) { charFrequencyMap[c.code]++ } var start = 0 var end = 0 var minStart = 0 var minLen = Int.MAX_VALUE var counter: Int = target.length while (end < str.length) { val currentChar: Char = str[end] if (charFrequencyMap[currentChar.code] > 0) counter-- charFrequencyMap[currentChar.code]-- end++ while (counter == 0) { if (minLen > end - start) { minLen = end - start minStart = start } val startChar: Char = str[start] charFrequencyMap[startChar.code]++ if (charFrequencyMap[startChar.code] > 0) counter++ start++ } } return if (minLen == Int.MAX_VALUE) { "" } else { str.substring(minStart, minStart + minLen) } } companion object { private const val LIMIT = 128 } } /** * Approach 2: Optimized Sliding Window */ class MWSSlidingLongestSubstring : MinimumWindowSubstring { override fun invoke(str: String, target: String): String { if (str.isEmpty() || target.isEmpty()) { return "" } val charFrequencyMap: HashMap<Char, Int> = HashMap() for (character in str.toCharArray()) charFrequencyMap[character] = 0 for (character in target.toCharArray()) { if (charFrequencyMap.containsKey(character)) { charFrequencyMap[character] = charFrequencyMap.getOrDefault(character, 0) + 1 } else { return "" } } var start = 0 var end = 0 var minStart = 0 var minLen = Int.MAX_VALUE var counter: Int = target.length while (end < str.length) { val currentChar: Char = str[end] if (charFrequencyMap.getOrDefault(currentChar, 0) > 0) { counter-- } charFrequencyMap[currentChar] = charFrequencyMap.getOrDefault(currentChar, 0) - 1 end++ while (counter == 0) { if (minLen > end - start) { minLen = end - start minStart = start } val startChar: Char = str[start] charFrequencyMap[startChar] = charFrequencyMap.getOrDefault(startChar, 0) + 1 if (charFrequencyMap.getOrDefault(startChar, 0) > 0) counter++ start++ } } return if (minLen == Int.MAX_VALUE) { "" } else { str.substring(minStart, minStart + minLen) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,915
kotlab
Apache License 2.0
advent-of-code-2018/src/test/java/aoc/Advent1.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import extensions.kotlin.cycle import extensions.kotlin.scan import io.vavr.collection.HashMap import org.assertj.core.api.Assertions.assertThat import org.junit.Test class Advent1 { @Test fun `Frequency should be 425`() { val sum = advent1Input1.lines() .map { it.toLong() } .asSequence() .sum() assertThat(sum).isEqualTo(425) } private fun Sequence<Long>.findDuplicateFrequency(scanner: Scanner): Long { return this .cycle() .scan(0L) { acc, next -> acc + next } .scan(scanner) { acc, next -> acc.scan(next) } .filter { scanner -> scanner.duplicate != null } .first() .let { it.duplicate ?: 0 } } interface Scanner { fun scan(frequency: Long): Scanner val duplicate: Long? } /** * 754ms */ @Test fun `Frequency reached twice is 57538L Vavr`() { advent1Input2.lines() .asSequence() .map { it.trim().toLong() } .findDuplicateFrequency(VavrScanner()) .also { assertThat(it).isEqualTo(57538L) } } class VavrScanner : Scanner { var frequencyToCount: HashMap<Long, Int> = HashMap.empty() var found: Long? = null override fun scan(next: Long): Scanner { val prev = frequencyToCount.getOrElse(next, 0) val withAppended = frequencyToCount.put(next, prev + 1) if (prev == 1) { frequencyToCount = withAppended found = next } else { frequencyToCount = withAppended } return this } override val duplicate: Long? get() = found } /** * 637ms */ @Test fun `Frequency reached twice is 57538L MutableMap`() { advent1Input2.lines() .asSequence() .map { it.trim().toLong() } .findDuplicateFrequency(MutableMapScanner()) .also { assertThat(it).isEqualTo(57538L) } } class MutableMapScanner : Scanner { var frequencyToCount = mutableMapOf<Long, Int>() var found: Long? = null override fun scan(next: Long): Scanner { val prev = frequencyToCount.put(next, 1) if (prev != null && prev == 1) { found = next } return this } override val duplicate: Long? get() = found } @Test fun examples() { fun String.findDuplicateFrequency() = this.split(',') .asSequence() .map { it.trim().toLong() } .findDuplicateFrequency(VavrScanner()) // +1, -1 first reaches 0 twice. "+1, -1".findDuplicateFrequency() .let { assertThat(it).isEqualTo(0) } // +3, +3, +4, -2, -4 first reaches 10 twice. "+3, +3, +4, -2, -4".findDuplicateFrequency() .let { assertThat(it).isEqualTo(10) } // -6, +3, +8, +5, -6 first reaches 5 twice. "-6, +3, +8, +5, -6".findDuplicateFrequency() .let { assertThat(it).isEqualTo(5) } // +7, +7, -2, -7, -4 first reaches 14 twice. "+7, +7, -2, -7, -4".findDuplicateFrequency() .let { assertThat(it).isEqualTo(14) } } private val advent1Input2 = """ -14 +15 +9 +19 +18 +14 +14 -18 +15 +4 -18 -20 -2 +17 +16 -7 -3 +5 +1 -5 -11 -1 -6 -20 +1 +1 +4 +18 +5 -20 -10 +18 +5 -4 -5 -18 +9 +6 +1 -19 +13 +10 -22 -11 -14 -17 -10 -1 -13 +6 -17 +9 -11 -6 +3 -14 +4 -14 +15 +7 +15 -1 -4 +9 +10 +6 -9 +8 +3 +10 -14 +8 +22 +19 -15 +10 -6 +9 -4 +2 +11 -15 +14 +11 -14 +2 +7 +9 -22 -6 -3 -21 +10 +5 -20 +19 -3 -13 +5 -16 +12 +10 -12 -4 +12 +2 -1 -4 -8 -6 -3 -8 -8 +7 -10 -20 -12 -6 -17 +2 +20 +7 -17 -14 -8 +3 +11 +15 -4 -10 -16 -3 -19 -6 -3 -9 -16 -7 -16 -12 +11 -13 -6 +13 +4 -7 -3 +5 +12 +4 -19 -19 +7 +1 -7 -12 -7 -5 -17 +18 +3 +10 +15 -12 -8 +17 +9 +19 +4 +16 -11 +10 -6 -7 +6 +6 +19 +3 +8 -2 +12 +19 -17 +7 -2 -10 -16 -11 -1 -2 -17 -7 +22 +3 +8 +11 -12 -4 +3 +19 -16 +18 -12 -17 -8 +5 -11 +7 -12 -23 -2 +14 +8 +9 +3 +29 +16 -15 -2 -12 +24 +14 +2 +4 -2 +18 -9 -18 +8 -9 +4 +7 +19 +7 +10 -9 -14 -6 +5 +17 -14 +7 +2 -1 +11 +18 -2 -6 +19 -15 -18 -5 +12 +21 +2 +2 -5 +10 +8 -10 +1 -17 +6 +21 +18 -17 +7 -5 +43 -4 +50 -4 +9 +16 -12 +9 +10 -21 +3 +25 -9 +18 +17 -19 +5 +16 -8 -17 +16 +21 -16 +6 +12 -9 +19 -7 +4 -8 +7 +18 +17 -7 +11 +21 -6 +4 -17 -19 +18 +13 -17 +2 +4 -8 +9 +22 +2 +5 +13 +6 +3 -28 -17 -17 -6 +19 -16 -19 +11 -7 +6 -17 +3 -4 -7 -6 +10 +17 -7 -4 +2 +8 -7 -25 +15 -10 -18 -10 -10 -11 -11 +14 +14 -3 +21 +10 -11 +6 +11 +21 -25 -9 -14 +2 +16 -27 +4 -7 +6 -11 +29 +21 +21 +6 -10 +14 +17 +6 -13 +32 -23 +17 -1 +12 -6 -11 +27 -5 +19 -2 -21 -42 -21 +19 -64 +20 -38 +42 -23 +1 -29 +26 -4 +57 +6 -1 +31 +107 -9 +5 +19 -12 +20 -1 +30 +1 +2 -47 -38 +5 +13 +121 +69 -60 +57143 -13 -3 +13 +15 +1 -19 -11 +2 -14 +4 +15 +8 -7 +16 +3 -5 -16 +17 -18 +5 -7 +17 +11 +12 -2 +16 -17 +6 +12 -9 -16 -5 +9 +18 +15 -19 +16 +16 -9 +5 -18 +19 -17 -18 +9 +11 +7 -3 -7 -6 +3 -17 -4 +6 +4 +2 +10 -13 -21 +10 -17 +15 +1 -10 -13 +20 -14 +21 +13 +16 +5 +4 +19 +9 +12 +4 -10 +14 -6 +17 -9 -14 +3 +16 +6 +13 +6 -15 +14 +11 -1 +8 -4 +11 +5 -7 -19 -2 +14 +18 -14 +2 +18 +16 -3 +16 +7 +1 -12 -5 -18 +8 +11 -7 -8 -19 +14 -10 -7 +4 +9 -18 -2 +19 +21 +9 +1 -9 +4 -3 +4 -11 -17 +10 -2 +6 -20 +3 +15 +4 +19 +19 -14 +3 +1 +4 +12 +11 -8 +12 +18 -14 +2 -4 +19 -1 +4 +15 +13 +16 +7 -12 +10 -13 -3 -17 +19 -16 +5 -20 -15 +3 +18 +4 +3 +3 +14 -12 +8 +11 +7 +10 +13 -7 +5 -19 +12 -3 +18 -9 +7 +1 +18 +17 -6 +1 -15 +10 -5 -10 -6 +18 +16 +6 +5 -10 -8 -5 +7 -1 -4 +17 +1 +4 -8 +1 +11 -13 -18 -14 +5 +3 +19 +12 +8 -3 +5 -24 +3 -10 -20 -1 +10 -19 +6 +8 -3 -10 +15 -8 +14 -17 -17 +4 +1 -12 +13 -11 +4 +12 -25 -1 -8 +14 -23 -21 +17 -20 +2 -5 -1 +12 -10 +3 +17 +4 -15 +20 -1 +9 +23 -20 -22 -12 -10 -15 +11 -35 -12 -14 +16 -10 -19 +26 +12 +16 -8 -15 +19 +3 -12 -16 +10 +2 -1 +13 -7 +2 +12 +9 -1 +2 -21 +3 -1 +13 +7 +2 +3 +18 -32 +4 +43 +19 -3 -5 +20 -2 -2 +17 +61 +2 -5 +23 -3 +8 -12 +55 +12 +12 +6 +20 -6 +7 +15 +3 +11 +8 -4 -9 -19 -13 -4 +6 -10 -9 -5 -4 +11 +5 +15 -14 +2 +6 -22 +2 +18 -11 -2 -4 -16 -5 +12 +4 +20 +8 +18 -6 +15 +17 -11 +16 -13 -12 +1 -9 +3 +16 +4 +19 +9 -8 -7 -12 +11 +21 -11 -16 +8 +1 +25 +15 -9 -42 +12 -18 -6 -10 -8 -5 -23 -20 +14 +12 +23 +120 +19 -43 +9 -1 -1 -33 +6 +43 -103 -187 +9 +3 -82 -20 -7 +125 +72 +613 +56596 -18 -19 +12 -11 -19 +1 +19 -18 -6 -3 +16 -2 -10 -9 -13 -15 +16 +5 -15 +7 -8 -17 +7 -16 +14 +14 -15 +4 -15 -10 -9 +12 -15 +5 -1 +13 -15 -3 -19 +1 -6 -19 -19 +23 -25 -28 -10 -3 -21 -13 -14 +11 +18 -13 +1 -16 +14 +15 +5 -7 +10 +2 -14 +10 +11 +11 -6 -7 -4 +14 -12 -6 -3 -15 -10 -13 -17 +3 +2 +8 +18 -4 -11 +2 -12 +13 -9 +14 +17 +12 +1 -12 -14 +6 +5 -13 +20 -13 -22 +3 +15 +14 +17 +7 -22 -22 -14 -2 -20 +15 -3 -8 +13 +40 +72 -21 +25 -16 +11 +22 +22 +25 +16 +15 +15 +9 +12 -10 +9 +11 -1 +10 -16 +17 +8 -7 -17 +4 -11 +20 +10 +7 +6 -7 +8 -19 +23 +7 -1 -2 +17 -9 -3 +2 -10 -10 -23 +17 +7 +10 +6 +14 +12 -1 +3 -7 -3 +16 -11 +17 -7 -1 -3 -12 -114806 """.trimIndent() private val advent1Input1 = """ -14 +15 +9 +19 +18 +14 +14 -18 +15 +4 -18 -20 -2 +17 +16 -7 -3 +5 +1 -5 -11 -1 -6 -20 +1 +1 +4 +18 +5 -20 -10 +18 +5 -4 -5 -18 +9 +6 +1 -19 +13 +10 -22 -11 -14 -17 -10 -1 -13 +6 -17 +9 -11 -6 +3 -14 +4 -14 +15 +7 +15 -1 -4 +9 +10 +6 -9 +8 +3 +10 -14 +8 +22 +19 -15 +10 -6 +9 -4 +2 +11 -15 +14 +11 -14 +2 +7 +9 -22 -6 -3 -21 +10 +5 -20 +19 -3 -13 +5 -16 +12 +10 -12 -4 +12 +2 -1 -4 -8 -6 -3 -8 -8 +7 -10 -20 -12 -6 -17 +2 +20 +7 -17 -14 -8 +3 +11 +15 -4 -10 -16 -3 -19 -6 -3 -9 -16 -7 -16 -12 +11 -13 -6 +13 +4 -7 -3 +5 +12 +4 -19 -19 +7 +1 -7 -12 -7 -5 -17 +18 +3 +10 +15 -12 -8 +17 +9 +19 +4 +16 -11 +10 -6 -7 +6 +6 +19 +3 +8 -2 +12 +19 -17 +7 -2 -10 -16 -11 -1 -2 -17 -7 +22 +3 +8 +11 -12 -4 +3 +19 -16 +18 -12 -17 -8 +5 -11 +7 -12 -23 -2 +14 +8 +9 +3 +29 +16 -15 -2 -12 +24 +14 +2 +4 -2 +18 -9 -18 +8 -9 +4 +7 +19 +7 +10 -9 -14 -6 +5 +17 -14 +7 +2 -1 +11 +18 -2 -6 +19 -15 -18 -5 +12 +21 +2 +2 -5 +10 +8 -10 +1 -17 +6 +21 +18 -17 +7 -5 +43 -4 +50 -4 +9 +16 -12 +9 +10 -21 +3 +25 -9 +18 +17 -19 +5 +16 -8 -17 +16 +21 -16 +6 +12 -9 +19 -7 +4 -8 +7 +18 +17 -7 +11 +21 -6 +4 -17 -19 +18 +13 -17 +2 +4 -8 +9 +22 +2 +5 +13 +6 +3 -28 -17 -17 -6 +19 -16 -19 +11 -7 +6 -17 +3 -4 -7 -6 +10 +17 -7 -4 +2 +8 -7 -25 +15 -10 -18 -10 -10 -11 -11 +14 +14 -3 +21 +10 -11 +6 +11 +21 -25 -9 -14 +2 +16 -27 +4 -7 +6 -11 +29 +21 +21 +6 -10 +14 +17 +6 -13 +32 -23 +17 -1 +12 -6 -11 +27 -5 +19 -2 -21 -42 -21 +19 -64 +20 -38 +42 -23 +1 -29 +26 -4 +57 +6 -1 +31 +107 -9 +5 +19 -12 +20 -1 +30 +1 +2 -47 -38 +5 +13 +121 +69 -60 +57143 -13 -3 +13 +15 +1 -19 -11 +2 -14 +4 +15 +8 -7 +16 +3 -5 -16 +17 -18 +5 -7 +17 +11 +12 -2 +16 -17 +6 +12 -9 -16 -5 +9 +18 +15 -19 +16 +16 -9 +5 -18 +19 -17 -18 +9 +11 +7 -3 -7 -6 +3 -17 -4 +6 +4 +2 +10 -13 -21 +10 -17 +15 +1 -10 -13 +20 -14 +21 +13 +16 +5 +4 +19 +9 +12 +4 -10 +14 -6 +17 -9 -14 +3 +16 +6 +13 +6 -15 +14 +11 -1 +8 -4 +11 +5 -7 -19 -2 +14 +18 -14 +2 +18 +16 -3 +16 +7 +1 -12 -5 -18 +8 +11 -7 -8 -19 +14 -10 -7 +4 +9 -18 -2 +19 +21 +9 +1 -9 +4 -3 +4 -11 -17 +10 -2 +6 -20 +3 +15 +4 +19 +19 -14 +3 +1 +4 +12 +11 -8 +12 +18 -14 +2 -4 +19 -1 +4 +15 +13 +16 +7 -12 +10 -13 -3 -17 +19 -16 +5 -20 -15 +3 +18 +4 +3 +3 +14 -12 +8 +11 +7 +10 +13 -7 +5 -19 +12 -3 +18 -9 +7 +1 +18 +17 -6 +1 -15 +10 -5 -10 -6 +18 +16 +6 +5 -10 -8 -5 +7 -1 -4 +17 +1 +4 -8 +1 +11 -13 -18 -14 +5 +3 +19 +12 +8 -3 +5 -24 +3 -10 -20 -1 +10 -19 +6 +8 -3 -10 +15 -8 +14 -17 -17 +4 +1 -12 +13 -11 +4 +12 -25 -1 -8 +14 -23 -21 +17 -20 +2 -5 -1 +12 -10 +3 +17 +4 -15 +20 -1 +9 +23 -20 -22 -12 -10 -15 +11 -35 -12 -14 +16 -10 -19 +26 +12 +16 -8 -15 +19 +3 -12 -16 +10 +2 -1 +13 -7 +2 +12 +9 -1 +2 -21 +3 -1 +13 +7 +2 +3 +18 -32 +4 +43 +19 -3 -5 +20 -2 -2 +17 +61 +2 -5 +23 -3 +8 -12 +55 +12 +12 +6 +20 -6 +7 +15 +3 +11 +8 -4 -9 -19 -13 -4 +6 -10 -9 -5 -4 +11 +5 +15 -14 +2 +6 -22 +2 +18 -11 -2 -4 -16 -5 +12 +4 +20 +8 +18 -6 +15 +17 -11 +16 -13 -12 +1 -9 +3 +16 +4 +19 +9 -8 -7 -12 +11 +21 -11 -16 +8 +1 +25 +15 -9 -42 +12 -18 -6 -10 -8 -5 -23 -20 +14 +12 +23 +120 +19 -43 +9 -1 -1 -33 +6 +43 -103 -187 +9 +3 -82 -20 -7 +125 +72 +613 +56596 -18 -19 +12 -11 -19 +1 +19 -18 -6 -3 +16 -2 -10 -9 -13 -15 +16 +5 -15 +7 -8 -17 +7 -16 +14 +14 -15 +4 -15 -10 -9 +12 -15 +5 -1 +13 -15 -3 -19 +1 -6 -19 -19 +23 -25 -28 -10 -3 -21 -13 -14 +11 +18 -13 +1 -16 +14 +15 +5 -7 +10 +2 -14 +10 +11 +11 -6 -7 -4 +14 -12 -6 -3 -15 -10 -13 -17 +3 +2 +8 +18 -4 -11 +2 -12 +13 -9 +14 +17 +12 +1 -12 -14 +6 +5 -13 +20 -13 -22 +3 +15 +14 +17 +7 -22 -22 -14 -2 -20 +15 -3 -8 +13 +40 +72 -21 +25 -16 +11 +22 +22 +25 +16 +15 +15 +9 +12 -10 +9 +11 -1 +10 -16 +17 +8 -7 -17 +4 -11 +20 +10 +7 +6 -7 +8 -19 +23 +7 -1 -2 +17 -9 -3 +2 -10 -10 -23 +17 +7 +10 +6 +14 +12 -1 +3 -7 -3 +16 -11 +17 -7 -1 -3 -12 -114806 """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
10,812
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/Tribonacci.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1137. N-th Tribonacci Number * @see <a href="https://leetcode.com/problems/n-th-tribonacci-number/submissions/887948261/">Source</a> */ fun interface Tribonacci { operator fun invoke(n: Int): Int } /** * Approach 1: Space Optimisation : Dynamic Programming * Time complexity : O(N) */ class TribSpaceOptimisationDP : Tribonacci { override operator fun invoke(n: Int): Int { if (n < 3) return if (n == 0) 0 else 1 var tmp: Int var x = 0 var y = 1 var z = 1 for (i in 3..n) { tmp = x + y + z x = y y = z z = tmp } return z } } /** * Approach 2: Performance Optimisation : Recursion with Memoization * Time complexity : O(1) */ class TribRecursionMemo : Tribonacci { private val cache = IntArray(MAX).apply { this[1] = 1 this[2] = 1 } init { helper(MAX - 1) } override operator fun invoke(n: Int): Int = cache[n] private fun helper(k: Int): Int { if (k == 0) return 0 if (cache[k] != 0) return cache[k] cache[k] = helper(k - 1) + helper(k - 2) + helper(k - 3) return cache[k] } companion object { private const val MAX = 38 } } /** * Approach 3: Performance Optimisation : Dynamic Programming * Time complexity : O(1) */ class TPerformanceOptimisationDP : Tribonacci { private val cache = IntArray(N).apply { this[1] = 1 this[2] = 1 } init { for (i in 3 until N) { cache[i] = cache[i - 1] + cache[i - 2] + cache[i - 3] } } override operator fun invoke(n: Int): Int = cache[n] companion object { private const val N = 38 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,395
kotlab
Apache License 2.0
src/main/kotlin/tree/bintree/CentralNode.kt
yx-z
106,589,674
false
null
package tree.bintree import util.Tuple2 import util.prettyPrintTree import util.tu import kotlin.collections.set // given a binary tree, a central node n is a node : after deleting the node, // the tree is split into three parts: left child of n (and its subtree), right // child of n (and its subtree), and parent of n (and its parent as well as other child) // and these three parts all having at most half of the total nodes in this tree // find one central node fun <T> BinTreeNode<T>.centralNode(): BinTreeNode<T> { // O(n) for these two maps : // childrenMap[node]: (# of nodes in the left subtree, # of nodes in the right subtree) // parentMap[node]: # of nodes in the parent (and its parent as well as its other child) val childrenMap = countChildren() val parentMap = countParent(childrenMap, null) // println(childrenMap) // println(parentMap) val n = childrenMap[this]!!.first + childrenMap[this]!!.second + 1 val limit = (n + 1) / 2 var curr = this while (childrenMap[curr]!!.first > limit || childrenMap[curr]!!.second > limit) { val (l, r) = childrenMap[curr]!! curr = if (l > limit) { left!! } else { right!! } } return curr } private fun <T> BinTreeNode<T>.countChildren(map: HashMap<BinTreeNode<T>, Tuple2<Int, Int>> = HashMap()) : Map<BinTreeNode<T>, Tuple2<Int, Int>> { left?.countChildren(map) right?.countChildren(map) map[this] = (map[left]?.run { first + second + 1 } ?: 0) tu (map[right]?.run { first + second + 1 } ?: 0) return map } private fun <T> BinTreeNode<T>.countParent(childrenMap: Map<BinTreeNode<T>, Tuple2<Int, Int>>, parent: BinTreeNode<T>?, parentMap: HashMap<BinTreeNode<T>, Int> = HashMap()) : Map<BinTreeNode<T>, Int> { if (parent == null) { parentMap[this] = 0 } else { if (this === parent.left) { // left child parentMap[this] = parentMap[parent]!! + childrenMap[parent]!!.second + 1 } else { // right child parentMap[this] = parentMap[parent]!! + childrenMap[parent]!!.first + 1 } } left?.countParent(childrenMap, this, parentMap) right?.countParent(childrenMap, this, parentMap) return parentMap } fun main(args: Array<String>) { val root = BinTreeNode(5) root.left = BinTreeNode(3) root.right = BinTreeNode(1) root.left!!.left = BinTreeNode(4) root.left!!.left!!.left = BinTreeNode(10) root.left!!.left!!.right = BinTreeNode(20) root.left!!.right = BinTreeNode(2) root.right!!.right = BinTreeNode(8) root.prettyPrintTree() println(root.centralNode()) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
2,563
AlgoKt
MIT License
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/SortingAlgorithms/OnSortingAlgorithms/SelectionSort.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
package com.betulnecanli.kotlindatastructuresalgorithms.SortingAlgorithms.OnSortingAlgorithms /*Selection sort follows the basic idea of bubble sort but improves upon this algorithm by reducing the number of swapAt operations. Selection sort only swaps at the end of each pass.*/ /*Like bubble sort, selection sort has a worst and average time complexity of O(n²), which is fairly dismal. Unlike the bubble sort, it also has the best time complexity of O(n²). Despite this, it performs better than bubble sort because it performs only O(n) swaps — and the best thing about it is that it’s a simple one to understand.*/ fun <T : Comparable<T>> ArrayList<T>.selectionSort(showPasses: Boolean = false){ if(this.size < 2 ) return //1 for(current in 0 until (this.size - 1)){ var lowest = current //2 for(other in (current+1) until this.size){ if(this[lowest] > this[other]){ lowest = other } //3 if(lowest != current){ this.swapAt(lowest,current) } //4 if(showPasses) println(this) } } } /*1. You perform a pass for every element in the collection, except for the last one. There’s no need to include the last element because if all other elements are in their correct order, the last one will be as well. 2. In every pass, you go through the remainder of the collection to find the element with the lowest value. 3. If that element is not the current element, swap them. 4. This optional step shows you how the list looks after each step when you call the function with showPasses set to true. You can remove this and the parameter once you understand the algorithm.*/
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
1,986
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2023/d21/Day21.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2023.d21 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.grids.Grid import com.groundsfam.advent.grids.maybeGet import com.groundsfam.advent.grids.pointOfFirst import com.groundsfam.advent.grids.readGrid import com.groundsfam.advent.points.Point import com.groundsfam.advent.points.adjacents import com.groundsfam.advent.timed import kotlin.io.path.div private class Solution(private val grid: Grid<Char>) { private val start: Point = grid.pointOfFirst { it == 'S' } private val reachablePlotCache = mutableMapOf<Point, List<Int>>() /** * Give a starting point, find the number of plots that can be reached in * 0, 1, 2, 3, ... steps. Reachable plots are limited to a single grid * within the infinite plane, and all reachable plots within the grid are * eagerly found. * * The returned list is effectively a map from number of steps allowed to * number of plots that are reachable in that number of steps. For example, * `stepsToPlotsInGrid(from)[5]` is equal to the number of plots in one * grid that are reachable in exactly 5 steps, starting at the point `from`. * * @param from the starting point */ private fun stepsToPlotsInGrid(from: Point): List<Int> { reachablePlotCache[from]?.also { return it } val visited = mutableSetOf(from) val reachable = mutableListOf(1) var prevPoints = setOf(from) while (prevPoints.isNotEmpty()) { val nextPoints = mutableSetOf<Point>() prevPoints.forEach { p -> p.adjacents(diagonal = false).forEach { q -> if (grid.maybeGet(q) in setOf('.', 'S') && q !in visited) { visited.add(q) nextPoints.add(q) } } } val prevVisitedReachable = if (reachable.size >= 2) reachable[reachable.size - 2] else 0 reachable.add(prevVisitedReachable + nextPoints.size) prevPoints = nextPoints } return reachable.also { reachablePlotCache[from] = it } } /** * The number of steps required to reach the furthest reachable plot in a single grid, * starting at the point [from]. * * @param from the starting point */ private fun maxSteps(from: Point): Int = stepsToPlotsInGrid(from).size - 1 /** * The number of plots reachable within a single grid for paths starting at [from] and * taking exactly [numSteps] steps. * * This function is a helpful layer on top of [stepsToPlotsInGrid]. It accounts for cases * in which [numSteps] exceeds the number of steps required to reach the furthest * reachable plot within a single grid. * * @param from the starting point * @param numSteps the number of steps to take in each path */ private fun reachablePlotsInGrid(from: Point, numSteps: Int): Int { val maxSteps = maxSteps(from) val steps = if (numSteps >= maxSteps) maxSteps - ((numSteps - maxSteps) % 2) else numSteps return stepsToPlotsInGrid(from)[steps] } private fun findReachablePlots(from: Point, numSteps: Int): Long { if (numSteps < 0) { return 0 } val sideLen = grid.numCols // detect if we're computing plots for this grid only, // or along just an axis, or for a quadrant (via diagonal paths) if (from == start) { return reachablePlotsInGrid(from, numSteps).toLong() } val diagonalPaths = from.x != start.x && from.y != start.y // number of grids we can reach with enough steps remaining to reach all plots therein // call these "fully-explorable" grids // this is measured only along a straight line, not the full quadrant of grids we can reach // by diagonal paths val numGrids = if (numSteps >= maxSteps(from)) (numSteps - maxSteps(from)) / sideLen else 0 // number of fully-explorable grids that will have same parity of stepsLeft as starting grid val numGrids1 = ((numGrids + 1) / 2) .toLong() .let { // use the sum of odd numbers formula // 1 + 3 + 5 + ... + 2(n+1) = n^2 if (diagonalPaths) it * it else it } // number of full-explorable grids that will have opposite parity of stepsLeft as starting grid val numGrids2 = (numGrids / 2) .toLong() .let { // use the sum of even numbers formula // 2 + 4 + 6 + ... + 2n = n(n+1) if (diagonalPaths) it * (it + 1) else it } var sum = reachablePlotsInGrid(from, numSteps) * numGrids1 + reachablePlotsInGrid(from, numSteps - 1) * numGrids2 // find reachable plots in the non-fully-explorable grids var gridNum = numGrids + 1 var remainingSteps = numSteps - numGrids * sideLen while (remainingSteps >= 0) { // if using diagonal paths, multiply by gridNum because there is a whole diagonal line // of grids in which we'll have this many steps remaining sum += reachablePlotsInGrid(from, remainingSteps) * (if (diagonalPaths) gridNum else 1) gridNum++ remainingSteps -= sideLen } return sum } fun findReachablePlots(numSteps: Int): Long { val sideLen = grid.numCols // use assumption that start is in the exact middle of the odd-length square grid val stepsToEdge = (sideLen + 1) / 2 return listOf( // start grid Pair(start, 0), // axes Pair(start.copy(x = 0), 1), Pair(start.copy(y = 0), 1), Pair(start.copy(x = sideLen - 1), 1), Pair(start.copy(y = sideLen - 1), 1), // quadrants Pair(Point(0, 0), 2), Pair(Point(0, sideLen - 1), 2), Pair(Point(sideLen - 1, 0), 2), Pair(Point(sideLen - 1, sideLen - 1), 2), ).sumOf { (from, i) -> findReachablePlots(from, numSteps - i * stepsToEdge) } } } fun main() = timed { val solution = (DATAPATH / "2023/day21.txt") .readGrid() .let(::Solution) println("Part one: ${solution.findReachablePlots(64)}") println("Part two: ${solution.findReachablePlots(26_501_365)}") }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
6,636
advent-of-code
MIT License
src/main/kotlin/stlutils/optimization/stlReducer/SupportVerticesComputer.kt
ivan-osipov
199,982,728
false
null
package stlutils.optimization.stlReducer import stlutils.common.* import kotlin.math.max import kotlin.math.min internal class SupportVerticesComputer(private val data: GraphData) { fun compute( accuracyCoefX: Int = 1, accuracyCoefY: Int = 1, accuracyCoefZ: Int = 1 ): Set<VertexIdx> { if (data.source.triangles.isEmpty()) return emptySet() val boundingBox = computeBoundingBox() val partialBoundingBoxes = splitBoundingBox(boundingBox, accuracyCoefX, accuracyCoefY, accuracyCoefZ) val vectorsByBoxes = data.source.vertices.groupByBoxes(partialBoundingBoxes) return vectorsByBoxes.findSupportVertices(partialBoundingBoxes) .mapTo(HashSet()) { data.mappings.verticesIndices.getValue(it) } } private fun computeBoundingBox(): BoundingBox { val triangles = data.source.triangles var minVector: Vector3d = triangles.first().a var maxVector: Vector3d = triangles.first().a for (triangle in triangles) { for (point in triangle.vertices) { minVector = SimpleVector3d(min(point.x, minVector.x), min(point.y, minVector.y), min(point.z, minVector.z)) maxVector = SimpleVector3d(max(point.x, maxVector.x), max(point.y, maxVector.y), max(point.z, maxVector.z)) } } return BoundingBox(minVector, maxVector) } private fun splitBoundingBox( boundingBox: BoundingBox, accuracyCoefX: Int, accuracyCoefY: Int, accuracyCoefZ: Int ): MutableList<BoundingBox> { val (minVector, maxVector) = boundingBox val diagonal = minVector.abs() + maxVector.abs() val stepVector = SimpleVector3d( diagonal.x / accuracyCoefX, diagonal.y / accuracyCoefY, diagonal.z / accuracyCoefZ ) val boundingBoxes = mutableListOf<BoundingBox>() for (i in (0 until accuracyCoefX)) { for (j in (0 until accuracyCoefY)) { for (k in (0 until accuracyCoefZ)) { boundingBoxes.add( BoundingBox( SimpleVector3d( minVector.x + stepVector.x * i, minVector.y + stepVector.y * j, minVector.z + stepVector.z * k ), SimpleVector3d( minVector.x + stepVector.x * (i + 1), minVector.y + stepVector.y * (j + 1), minVector.z + stepVector.z * (k + 1) ) ) ) } } } return boundingBoxes } private fun Collection<Vector3d>.groupByBoxes(boundingBoxes: MutableList<BoundingBox>): Map<Int, List<Vector3d>> { return groupBy { (x, y, z) -> for ((i, bb) in boundingBoxes.withIndex()) { val (minVector, maxVector) = bb val (minX, minY, minZ) = minVector val (maxX, maxY, maxZ) = maxVector if (x in minX..maxX && y in minY..maxY && z in minZ..maxZ) { return@groupBy i } } throw IllegalStateException("($x,$y,$z) located in unknown bounding box") } } private fun Map<Int, List<Vector3d>>.findSupportVertices(boundingBoxes: MutableList<BoundingBox>): Set<Vector3d> { return entries.asSequence().flatMap { (boxIdx, vertices) -> if (vertices.isEmpty()) return@flatMap emptySequence<SimpleVector3d>() val (minVector, maxVector) = vertices.extremePointsBy { (boundingBoxes[boxIdx].center - it).length() }!! //TODO length is redundant, it can be just squares sequenceOf(minVector, maxVector) }.toSet() } }
1
Kotlin
0
0
c7c36c71e9990e28529b874c7522a38411a3913e
3,978
stl-utls
Apache License 2.0
src/main/kotlin/com/askrepps/advent2021/day02/Day02.kt
askrepps
726,566,200
false
{"Kotlin": 191862}
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.askrepps.advent2021.day02 import com.askrepps.advent2021.util.getInputLines import java.io.File enum class Direction { Forward, Up, Down } data class Position(val x: Int, val depth: Int, val aim: Int = 0) data class MovementCommand(val direction: Direction, val amount: Int) { val deltaX: Int get() = if (direction == Direction.Forward) { amount } else { 0 } val deltaDepth: Int get() = when(direction) { Direction.Up -> -amount Direction.Down -> amount else -> 0 } } fun String.toMovementCommand(): MovementCommand { val (directionString, amountString) = split(" ") val direction = when (directionString) { "forward" -> Direction.Forward "up" -> Direction.Up "down" -> Direction.Down else -> throw IllegalArgumentException("Unrecognized direction: $directionString") } return MovementCommand(direction, amountString.toInt()) } fun plotCourse(commands: List<MovementCommand>, makeMove: (Position, MovementCommand) -> Position) = commands.fold(initial = Position(x = 0, depth = 0), makeMove) fun getResult(commands: List<MovementCommand>, makeMove: (Position, MovementCommand) -> Position) = plotCourse(commands, makeMove).let { finalPosition -> finalPosition.x * finalPosition.depth } fun getPart1Answer(commands: List<MovementCommand>) = getResult(commands) { position, command -> Position(position.x + command.deltaX, position.depth + command.deltaDepth) } fun getPart2Answer(commands: List<MovementCommand>) = getResult(commands) { position, command -> val newX = position.x + command.deltaX if (command.direction == Direction.Forward) { val newDepth = position.depth + position.aim * command.deltaX Position(newX, newDepth, position.aim) } else { val newAim = position.aim + command.deltaDepth Position(newX, position.depth, newAim) } } fun main() { val commands = File("src/main/resources/day02.txt") .getInputLines().map { it.toMovementCommand() } println("The answer to part 1 is ${getPart1Answer(commands)}") println("The answer to part 2 is ${getPart2Answer(commands)}") }
0
Kotlin
0
0
89de848ddc43c5106dc6b3be290fef5bbaed2e5a
3,431
advent-of-code-kotlin
MIT License
src/main/kotlin/nl/kelpin/fleur/advent2018/Day04.kt
fdlk
159,925,533
false
null
package nl.kelpin.fleur.advent2018 typealias GuardID = Int typealias Minute = Int class Day04(input: List<String>) { data class Nap(val guard: GuardID, val minutes: IntRange) data class State(val guard: GuardID? = null, val napStarted: Int? = null, val naps: List<Nap> = listOf()) { fun beginShift(newGuard: GuardID) = copy(guard = newGuard, napStarted = null) fun fallAsleep(minutes: Int) = copy(napStarted = minutes) fun wakeUp(minutes: Int) = copy(napStarted = null, naps = naps + Nap(guard!!, napStarted!! until minutes)) } companion object { private val beginShiftRE = Regex(""".*Guard #(\d+) begins shift""") private val fallAsleepRE = Regex(""".*00:(\d{2})] falls asleep""") private val wakesUpRE = Regex(""".*00:(\d{2})] wakes up""") private fun MatchResult.intMatch(): Int = destructured.let{ (firstResult) -> firstResult.toInt() } fun processLine(status: State, line: String): State = when { line.matches(beginShiftRE) -> beginShiftRE.find(line)!!.intMatch().run(status::beginShift) line.matches(fallAsleepRE) -> fallAsleepRE.find(line)!!.intMatch().run(status::fallAsleep) line.matches(wakesUpRE) -> wakesUpRE.find(line)!!.intMatch().run(status::wakeUp) else -> throw IllegalArgumentException("Failed to parse: $line") } } private val guardNaps: Map<GuardID, List<Minute>> = input .sorted() .fold(State(), ::processLine).naps .groupBy { it.guard } .mapValues { it.value.flatMap { it.minutes } } fun part1(): Int = guardNaps .maxBy { it.value.size }!! .let { (guardID: GuardID, minutes: List<Minute>) -> guardID * minutes.mostFrequent().element } fun part2(): Int = guardNaps .mapValues { it.value.mostFrequent() } .maxBy { it.value.occurrence }!! .let { (guardID: GuardID, mostFrequent: Frequency<Minute>) -> guardID * mostFrequent.element } }
0
Kotlin
0
3
a089dbae93ee520bf7a8861c9f90731eabd6eba3
2,022
advent-2018
MIT License
aoc-2015/src/main/kotlin/aoc/AocDay20.kt
triathematician
576,590,518
false
{"Kotlin": 615974}
package aoc class AocDay20: AocDay(20) { companion object { @JvmStatic fun main(args: Array<String>) { AocDay20().run() } } override val testinput = """ 200 """.trimIndent().lines() /** All divisors, including 1 and self. */ private fun Int.divisors(): List<Int> { val res = mutableListOf(1) for (i in 2..minOf(this-1, (this/2+1))) { if (this % i == 0) res += i } res += this return res } override fun calc1(input: List<String>): Int { // we know we want a large number of divisors, so can speed things up by looking for multiples of 120 val target = input[0].toInt() generateSequence(120) { it + 120 }.map { if (it % 100000 < 120) println(it) it to it.divisors().sum() * 10 }.first { it.second >= target }.let { println("House ${it.first} gets ${it.second} presents") println(" delivered from ${it.first.divisors()}") return it.first } } override fun calc2(input: List<String>): Int { // we know we want a large number of divisors, so can speed things up by looking for multiples of 120 val target = input[0].toInt() val nums = IntArray(target/10) (1..target/10).forEach { elf -> if (elf % 1000000 == 0) println("Elf $elf is delivering their presents.") (1..50).forEach { if (elf*it-1 < nums.size) { nums[elf * it - 1] += elf * 11 } } } val i = nums.indexOfFirst { it >= target } + 1 println("House $i gets at least ${nums[i - 1]} presents") println(" delivered from ${i.divisors().filter { it >= i / 50 }}") return i } }
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
1,842
advent-of-code
Apache License 2.0
src/main/kotlin/year2023/day11/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2023.day11 import IProblem import kotlin.math.abs import kotlin.math.max import kotlin.math.min class Problem : IProblem { private val size: Int private val space: Array<IntArray> private val emptyRows: BooleanArray private val emptyCols: BooleanArray private val galaxies = mutableListOf<Pair<Int, Int>>() init { val lines = javaClass .getResourceAsStream("/2023/11.txt")!! .bufferedReader() .lines() .map(String::toCharArray) .toList() size = lines.size space = Array(size) { IntArray(size) { -1 } } emptyRows = BooleanArray(size) { true } emptyCols = BooleanArray(size) { true } for (i in 0 until size) { for (j in 0 until size) { if (lines[i][j] == '#') { space[i][j] = galaxies.size emptyRows[i] = false emptyCols[j] = false galaxies.add(Pair(j, i)) } } } } private fun distSum(n: Int): Long { var sum = 0L for (i in galaxies.indices) { for (j in i + 1 until galaxies.size) { val (x0, y0) = galaxies[i] val (x1, y1) = galaxies[j] var r = 0 var c = 0 for (k in min(x0, x1) until max(x0, x1)) { if (emptyCols[k]) { c++ } } for (k in min(y0, y1) until max(y0, y1)) { if (emptyRows[k]) { r++ } } sum += c * (n - 1) + abs(x0 - x1) + r * (n - 1) + abs(y0 - y1) } } return sum } override fun part1(): Long { return distSum(2) } override fun part2(): Long { return distSum(1_000_000) } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
1,958
advent-of-code
The Unlicense
src/day06/Day06.kt
apeinte
574,487,528
false
{"Kotlin": 47438}
package day06 import readDayInput //Don't forget to fill this constant. const val RESULT_EXAMPLE_PART_ONE_1 = 7 const val RESULT_EXAMPLE_PART_ONE_2 = 5 const val RESULT_EXAMPLE_PART_ONE_3 = 6 const val RESULT_EXAMPLE_PART_ONE_4 = 10 const val RESULT_EXAMPLE_PART_ONE_5 = 11 const val RESULT_EXAMPLE_PART_TWO_1 = 19 const val RESULT_EXAMPLE_PART_TWO_2 = 23 const val RESULT_EXAMPLE_PART_TWO_3 = 23 const val RESULT_EXAMPLE_PART_TWO_4 = 29 const val RESULT_EXAMPLE_PART_TWO_5 = 26 const val VALUE_OF_THE_DAY = 6 fun main() { fun getMarker(input: List<String>, targetLine: Int = 0, markerBeacon: Int):Int { var tmpInput: MutableList<String> = input[targetLine].split("").toMutableList() var inputLineToArray = tmpInput.apply { // Split are generated empty character at first and last index in the list removeFirst() removeLast() } var result = 0 var from = 0 var to = markerBeacon var charCounter = 0 fun checkList() { var dataPacket = inputLineToArray.subList(from, to) for (char in dataPacket) { charCounter++ if (dataPacket.filter { it ==char }.size > 1) { from++ to++ charCounter = 0 checkList() break } else { if (charCounter == markerBeacon) { result = to break } } } } checkList() println("The start mark for $tmpInput is $result.") return result } fun part1(input: List<String>, targetLine: Int = 0): Int { return getMarker(input, targetLine, 4) } fun part2(input: List<String>, targetLine: Int = 0): Int { return getMarker(input, targetLine, 14) } val inputRead = readDayInput(VALUE_OF_THE_DAY) val inputReadTest = readDayInput(VALUE_OF_THE_DAY, true) fun checkIfTestArePassedForPartOne(): Boolean { return part1(inputReadTest, 0) == RESULT_EXAMPLE_PART_ONE_1 && part1(inputReadTest,1) == RESULT_EXAMPLE_PART_ONE_2 && part1(inputReadTest,2) == RESULT_EXAMPLE_PART_ONE_3 && part1(inputReadTest,3) == RESULT_EXAMPLE_PART_ONE_4 && part1(inputReadTest,4) == RESULT_EXAMPLE_PART_ONE_5 } fun checkIfTestArePassedForPartTwo(): Boolean { return part2(inputReadTest, 0) == RESULT_EXAMPLE_PART_TWO_1 && part2(inputReadTest,1) == RESULT_EXAMPLE_PART_TWO_2 && part2(inputReadTest,2) == RESULT_EXAMPLE_PART_TWO_3 && part2(inputReadTest,3) == RESULT_EXAMPLE_PART_TWO_4 && part2(inputReadTest,4) == RESULT_EXAMPLE_PART_TWO_5 } if (checkIfTestArePassedForPartOne()) { println("How many characters need to be processed before the first start-of-packet marker is detected?\n${part1(inputRead)}") } if (checkIfTestArePassedForPartTwo()) { println("How many characters need to be processed before the first start-of-message marker is detected?\n${part2(inputRead)}") } }
0
Kotlin
0
0
4bb3df5eb017eda769b29c03c6f090ca5cdef5bb
3,235
my-advent-of-code
Apache License 2.0
atcoder/agc044/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package atcoder.agc044 fun main() { val n = readInt() val p = readInts().map { it - 1 } val dist = List(n) { x -> IntArray(n) { y -> sequenceOf(x, y, n - 1 - x, n - 1 - y).minOrNull()!! + 1 } } val on = List(n) { x -> BooleanArray(n) { true } } var ans = 0 val stack = IntArray(n * n) for (r in p) { val rx = r / n val ry = r % n ans += dist[rx][ry] - 1 on[rx][ry] = false dist[rx][ry]-- stack[0] = r var stackSize = 1 while (stackSize > 0) { val xy = stack[--stackSize] val x = xy / n val y = xy % n val distHere = dist[x][y] for (d in DX.indices) { val xx = x + DX[d] val yy = y + DY[d] val onNei = on.getOrNull(xx)?.getOrNull(yy) ?: continue val distNei = dist[xx][yy] val distNew = distHere + if (onNei) 1 else 0 if (distNew < distNei) { dist[xx][yy]-- stack[stackSize++] = xx * n + yy } } } } println(ans) } val DX = intArrayOf(1, 0, -1, 0) val DY = intArrayOf(0, 1, 0, -1) private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,148
competitions
The Unlicense
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day3/Day3.kt
jntakpe
433,584,164
false
{"Kotlin": 64657, "Rust": 51491}
package com.github.jntakpe.aoc2021.days.day3 import com.github.jntakpe.aoc2021.shared.Day import com.github.jntakpe.aoc2021.shared.readInputLines object Day3 : Day { private const val ZERO = '0' private const val ONE = '1' override val input = readInputLines(3) override fun part1(): Int { return (0 until input.first().length).map { input.commonBit(it) }.joinToString("") .let { it.toDecimal() * it.reverseBits().toDecimal() } } override fun part2() = input.rating(0) * input.rating(0, true) private fun List<String>.commonBit(index: Int) = if (map { it[index] }.count { it == ZERO } > size / 2) ZERO else ONE private fun List<String>.rating(index: Int, reverse: Boolean = false): Int { val char = commonBit(index).run { if (reverse) reverse() else this } return filter { it[index] == char }.run { singleOrNull()?.toDecimal() ?: rating(index + 1, reverse) } } private fun String.reverseBits() = map { it.reverse() }.joinToString("") private fun Char.reverse() = if (this == ZERO) ONE else ZERO private fun String.toDecimal() = Integer.parseInt(this, 2) }
0
Kotlin
1
5
230b957cd18e44719fd581c7e380b5bcd46ea615
1,150
aoc2021
MIT License
kotlin/src/katas/kotlin/permutation/AllPermutationTypes.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.permutation import nonstdlib.* import datsok.* import org.junit.* import java.util.* class AllPermutationTypes { @Test fun `permutations by removal`() { listOf(1, 2, 3).permutations_remove() shouldEqual listOf( listOf(3, 2, 1), listOf(2, 3, 1), listOf(3, 1, 2), listOf(1, 3, 2), listOf(2, 1, 3), listOf(1, 2, 3) ) listOf(1, 2, 3, 4).permutations_remove().printed() checkPermutationsFunction { it.permutations_remove().toList() } checkPermutationsFunction { it.permutations_remove_sequence().toList() } } @Test fun `permutations by addition`() { mutableListOf(1, 2, 3).permutations_add() shouldEqual listOf( listOf(1, 2, 3), listOf(2, 1, 3), listOf(2, 3, 1), listOf(1, 3, 2), listOf(3, 1, 2), listOf(3, 2, 1) ) mutableListOf(1, 2, 3, 4).permutations_add().toList().printed() checkPermutationsFunction { it.toMutableList().permutations_add().toList() } } @Test fun `permutations by addition minimum swaps`() { mutableListOf(1, 2, 3).permutations_add_min_change() shouldEqual listOf( listOf(1, 2, 3), listOf(2, 1, 3), listOf(2, 3, 1), listOf(3, 2, 1), listOf(3, 1, 2), listOf(1, 3, 2) ) mutableListOf(1, 2, 3, 4).permutations_add_min_change().printed() mutableListOf(0, 1, 2, 3).permutations_add_min_change().printed() .map { it.toLehmerCode().toLong().printed() } checkPermutationsFunction { it.toMutableList().permutations_add_min_change().toList() } } @Test fun `lexicographic permutations`() { listOf(1, 2, 3).permutations_lexicographic() shouldEqual listOf( listOf(1, 2, 3), listOf(1, 3, 2), listOf(2, 1, 3), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1) ) listOf(1, 2, 3, 4).permutations_lexicographic().join("\n").printed() listOf(0, 1, 2, 3).permutations_lexicographic() .map { it.toLehmerCode().toLong() } shouldEqual LongRange(0, 23).toList() checkPermutationsFunction { it.toMutableList().permutations_lexicographic().toList() } } @Test fun `lexicographic permutations using Lehmer code`() { listOf(1, 2, 3).permutations_lehmer() shouldEqual listOf( listOf(1, 2, 3), listOf(1, 3, 2), listOf(2, 1, 3), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1) ) listOf(1, 2, 3, 4).permutations_lehmer().join("\n").printed() checkPermutationsFunction { it.permutations_lehmer().toList() } } @Test fun `Heap's permutations`() { mutableListOf(1, 2, 3).permutations_heaps() shouldEqual listOf( listOf(1, 2, 3), listOf(2, 1, 3), listOf(3, 1, 2), listOf(1, 3, 2), listOf(2, 3, 1), listOf(3, 2, 1) ) mutableListOf(1, 2, 3, 4).permutations_heaps().join("\n").printed() checkPermutationsFunction { it.toMutableList().permutations_heaps().toList() } } companion object { private fun List<Int>.permutations_remove(): List<List<Int>> = if (size <= 1) listOf(this) else flatMap { item -> (this - item) .permutations_remove() .map { permutation -> permutation + item } } private fun List<Int>.permutations_remove_sequence(): Sequence<List<Int>> { if (size <= 1) return sequenceOf(this) val list = this return sequence { list.forEach { item -> val permutations = (list - item) .permutations_remove_sequence() .map { permutation -> permutation + item } yieldAll(permutations) } } } private fun MutableList<Int>.permutations_add(): List<List<Int>> { if (size <= 1) return listOf(this) val firstItem = first() val subPermutations = drop(1).toMutableList().permutations_add() return subPermutations.flatMap { subPermutation -> (0..subPermutation.size) .map { i -> ArrayList(subPermutation).apply { add(i, firstItem) } } } } private fun MutableList<Int>.permutations_add_min_change(): List<List<Int>> { if (size <= 1) return listOf(this) val item = first() val subPermutations = drop(1).toMutableList().permutations_add_min_change() return subPermutations.mapIndexed { index, subPermutation -> val permutation = (0..subPermutation.size) .map { i -> ArrayList(subPermutation).apply { add(i, item) } } if (index % 2 != 0) permutation.reversed() else permutation }.flatten() } /** * https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order * https://www.nayuki.io/page/next-lexicographical-permutation-algorithm */ private fun List<Int>.permutations_lexicographic(): List<List<Int>> { val values = this val list = indices.toMutableList() val result = ArrayList<List<Int>>() result.add(list.map { values[it] }) while (true) { val i = list.indices.windowed(2).findLast { (i1, i2) -> list[i1] < list[i2] }?.first() ?: return result val j = IntRange(i + 1, list.size - 1).findLast { list[i] < list[it] }!! list.swap(i, j) list.subList(i + 1, list.size).reverse() result.add(list.map { values[it] }) } } private fun List<Int>.permutations_lehmer(): List<List<Int>> { if (isEmpty()) return listOf(emptyList()) return LongRange(0, size.longFactorial() - 1) .map { it.toLehmerCode(size = size).toPermutation(this) } } private fun MutableList<Int>.permutations_heaps(n: Int = size): List<List<Int>> { if (n <= 1) return listOf(ArrayList(this)) return sequence { (1..n).forEach { i -> yieldAll(permutations_heaps(n - 1)) if (n % 2 == 0) swap(i - 1, n - 1) else swap(0, n - 1) } }.toList() } } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
6,684
katas
The Unlicense
src/Day02.kt
maxonof
572,454,805
false
{"Kotlin": 5967}
fun main() { val input = readInput("input2") val res = input.sumOf { val s = it.split(" ") val ss = getActualScore(s.last(), s.first()) println(ss) ss } println(res) } fun getScore(mine: String, theirs: String): Int { return when (mine) { "Y" -> { when (theirs) { "A" -> 8 "B" -> 5 else -> 2 } } "Z" -> { when (theirs) { "A" -> 3 "B" -> 9 else -> 6 } } else -> { when (theirs) { "A" -> 4 "B" -> 1 else -> 7 } } } } fun getActualScore(mine: String, theirs: String): Int { return when (mine) { "Y" -> { when (theirs) { "A" -> 4 "B" -> 5 else -> 6 } } "Z" -> { when (theirs) { "A" -> 8 "B" -> 9 else -> 7 } } else -> { when (theirs) { "A" -> 3 "B" -> 1 else -> 2 } } } }
0
Kotlin
0
0
ef03fc65dcd429d919eb12d054ce7c052780d7d7
1,263
aoc-2022-in-kotlin
Apache License 2.0
src/day02/Day02.kt
TimberBro
567,240,136
false
{"Kotlin": 11186}
package day02 import utils.readInput fun main() { fun part1(input: List<String>): Int { var result = 0 for (line in input) { val splitLine = line.split(":", "-", " ") val minValue = splitLine[0].toInt() val maxValue = splitLine[1].toInt() val character = splitLine[2][0] val password = splitLine[4].trim() if (password.count { it == character } in minValue..maxValue) { result++ } } return result } fun part2(input: List<String>): Int { var result = 0 for (line in input) { val splitLine = line.split(":", "-", " ") val minValue = splitLine[0].toInt() val maxValue = splitLine[1].toInt() val character = splitLine[2][0] val password = splitLine[4].trim() if ((password[minValue - 1] == character).xor(password[maxValue - 1] == character)) { result++ } } return result } val testInput = readInput("day02/Day02_test") check(part1(testInput) == 2) check(part2(testInput) == 1) val input = readInput("day02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1959383d2f422cc565560eefb1ed4f05bb87a386
1,309
aoc2020
Apache License 2.0
intellidiff/src/main/java/com/target/diff/writer/Hints.kt
target
393,172,530
false
null
package com.target.diff.writer import com.target.diff.differ.Change internal data class Hint(val expected: String, val actual: String) internal class Hints(val writer: HintWriter = HintWriter()) { fun generate(change: Change): Hint { return when (change) { is Change.DifferentContainerSize -> writer.write( expected = "size: ${change.oldSize}", actual = "size: ${change.currentSize}" ) is Change.DifferentType -> { writer.write( expected = "type: ${change.old::class.qualifiedName}", actual = "type: ${change.current::class.qualifiedName}" ) } is Change.Value -> { writer.write( expected = classifyContent(change.old), actual = classifyContent(change.current) ) } is Change.Removed -> { writer.write( expected = classifyContent(change.removed), actual = classifyContent(null) ) } is Change.Added -> { writer.write( expected = classifyContent(null), actual = classifyContent(change.added) ) } } } fun classifyContent(content: Any?): String { val classification = when (content) { null -> "null" is String -> classifyString(content) else -> "" } return if (classification.isNotEmpty()) { "content: $classification" } else { classification } } private fun classifyString(content: String): String { return when { content.isEmpty() -> "empty" content.isBlank() -> "blank" content.trim().length != content.length -> "trim-alert" else -> "" } } } private const val DEFAULT_OPEN_SYMBOL = "-->(" private const val DEFAULT_CLOSE_SYMBOL = ")" private const val DEFAULT_ALIGNMENT_SYMBOL = " " internal class HintWriter( val openSymbol: String = DEFAULT_OPEN_SYMBOL, val closeSymbol: String = DEFAULT_CLOSE_SYMBOL, val alignmentSymbol: String = DEFAULT_ALIGNMENT_SYMBOL ) { init { check(alignmentSymbol.length == 1) { """ alignmentSymbol is used t make up the difference in lengths between expected and actual values. This is only exposed as a String as to not make declaration feel weird moving between multiple quote types """.trimIndent() } } fun empty(): Hint { return Hint(expected = "", actual = "") } fun write(expected: String, actual: String): Hint { val expectedHint = format(content = expected) val actualHint = format(content = actual) val longestHint = Math.max(expectedHint.length, actualHint.length) return Hint( expected = align( content = expectedHint, size = longestHint ), actual = align( content = actualHint, size = longestHint ) ) } fun format(content: String): String { return if (content.isNotEmpty()) { return "$openSymbol$content$closeSymbol" } else { content } } fun align(content: String, size: Int): String { return if (content.length >= size) { content } else { content.plus(alignmentSymbol.repeat(size - content.length)) } } }
1
Kotlin
1
8
4f6c91231bf3c1792c9774f710812e6e2a91d330
3,193
intellidiff
Apache License 2.0
src/main/kotlin/year2022/day-14.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2022 import lib.aoc.Day import lib.aoc.Part import lib.math.Vector import lib.math.minus import lib.math.plus import kotlin.math.max import kotlin.math.min fun main() { Day(14, 2022, PartA14(), PartB14()).run() } open class PartA14 : Part() { internal lateinit var cave: MutableSet<Vector> internal lateinit var sand: MutableSet<Vector> internal var maxY = 0 override fun parse(text: String) { cave = mutableSetOf() maxY = 0 text.split("\n") .forEach { line -> val coordinates = line.split(" -> ") (0 until coordinates.size - 1).forEach { val (x1, y1) = coordinates[it].split(",") val (x2, y2) = coordinates[it + 1].split(",") val xStart = min(x1.toInt(), x2.toInt()) val xEnd = max(x1.toInt(), x2.toInt()) val yStart = min(y1.toInt(), y2.toInt()) val yEnd = max(y1.toInt(), y2.toInt()) maxY = max(maxY, yEnd) (yStart..yEnd).forEach { y -> (xStart..xEnd).forEach { x -> cave.add(Vector.at(x, y)) } } } } } override fun compute(): String { sand = mutableSetOf() while (true) { val sandResting = addSand() if (!sandResting) { return sand.size.toString() } } } private var vecLeft = Vector.at(-1, 0) private var vecRight = Vector.at(1, 0) private var vecDown = Vector.at(0, 1) internal fun addSand(): Boolean { var pos = Vector.at(500, 0) while (true) { if (pos.y > maxY) { return false } pos += vecDown if (collides(pos)) { if (!collides(pos + vecLeft)) { pos += vecLeft } else if (!collides(pos + vecRight)) { pos += vecRight } else { sand.add(pos - vecDown) return true } } } } private fun collides(pos: Vector) = pos in cave || pos in sand override val exampleAnswer: String get() = "24" } class PartB14 : PartA14() { override fun compute(): String { sand = mutableSetOf() (0 until 1000).forEach { cave.add(Vector.at(it, maxY + 2)) } maxY += 3 while (true) { addSand() if (Vector.at(500, 0) in sand) { return sand.size.toString() } } } override val exampleAnswer: String get() = "93" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
2,812
Advent-Of-Code-Kotlin
MIT License